Algorithm Search⌘K

Algorithmadvanced

MiniCon algorithm

Also called MiniCon.

Rewrite a conjunctive query using views: form minimal descriptions of the subgoals each view can cover, then combine sets of them that cover the query exactly once.

Time
O(a n k (m+1)^n (n k m+1)^n) worst
Space
O(a n k (m+1)^n) extra
Where
a = the largest arity of a predicate; k = the number of views; m = the largest number of subgoals of a view; n = the number of subgoals of the query
Properties
deterministicexactnot in placeofflinerecursive
Origin
Rachel Pottinger, Alon Y. Halevy, 2000

MiniCon rewrites a conjunctive query into a union of conjunctive queries over a set of views, for answering queries using views in local-as-view integration. It returns the maximally contained rewriting, as the bucket algorithm does, but it does the containment work before it combines views. The bucket algorithm puts each view in a bucket for one subgoal and then tests every combination for containment. MiniCon first finds, for each view, the smallest set of subgoals that the view must cover together, and then it only combines these sets when they do not overlap. No containment test is left at the end.

In plain words

A view stores the answers of a small query, and some of its variables are not stored. If a query subgoal uses a variable that the view hides, the view can only help if it also covers every other subgoal that uses that variable, because the hidden value cannot be joined with anything outside the view.

MiniCon starts with one subgoal and one view. Each time the view would hide a variable that some other subgoal needs, it pulls that subgoal into the same group. The result is a small group of subgoals that the view covers alone. Then it picks groups from different views so that each subgoal is in exactly one group, and each such choice gives one rewriting.

The problem

The input is a query Q(xˉ) :- R1(uˉ1),…,Rn(uˉn)Q(\bar x) \text{ :- } R_1(\bar u_1), \ldots, R_n(\bar u_n) in AHV notation and a set of views, each of the form V(Yˉ) :- S1(wˉ1),…,Sr(wˉr)V(\bar Y) \text{ :- } S_1(\bar w_1), \ldots, S_r(\bar w_r). All terms are variables, there are no comparisons, and set semantics holds. A variable of a view is distinguished if it is in the head and existential otherwise. A rewriting is a conjunctive query over the view names. It is contained in QQ when its expansion, the query you get by replacing each view atom by the body of the view with new existential variables, is contained in QQ. The output is a union of contained rewritings that contains every other contained union of conjunctive queries.

A MiniCon description (MCD) for a view VV is a tuple (h,φ,G)(h, \varphi, G). GG is a set of subgoals of QQ, hh is a head homomorphism that may equate head variables of VV, and φ\varphi maps the variables of GG to variables of VV so that each subgoal of GG maps onto hh of some subgoal of VV. It must satisfy Property 1:

  • C1. Each head variable of QQ in GG maps to a distinguished variable of VV.
  • C2. If φ(x)\varphi(x) is existential, then every subgoal of QQ that holds xx is in GG.

The algorithm

  1. MINICON(Q, Views)
  2. 1C <- empty
  3. 2for each subgoal g of Q, view V and subgoal v of V with the predicate of g do
  4. 3(h, phi) <- the least restrictive pair with phi(g) = h(v); skip if none exists
  5. 4for each (h', phi', G) in CLOSE(Q, V, h, phi, {g}) do
  6. 5add the MCD (V, h', phi', G) to C
  7. 6R <- empty
  8. 7for each set {M_1, ..., M_c} of MCDs in C whose sets G_i partition the subgoals of Q do
  9. 8EC <- the classes of the query variables, with x ~ y if phi_i(x) = phi_i(y) for some i
  10. 9Psi_i(y) <- a variable x with phi_i(x) = y, or a fresh variable if there is none
  11. 10add Q'(EC(X)) :- V_1(EC(Psi_1(h_1(Y_1)))), ..., V_c(EC(Psi_c(h_c(Y_c)))) to R
  12. 11return R
  13. CLOSE(Q, V, h, phi, G)
  14. 12if phi maps a head variable of Q to an existential variable of V then return nothing
  15. 13if no subgoal g' outside G holds a variable x with phi(x) existential then return {(h, phi, G)}
  16. 14for each subgoal v' of V with the predicate of g' do
  17. 15extend (h, phi) least restrictively so that phi(g') = h(v'); skip v' if impossible
  18. 16return also everything that CLOSE(Q, V, h, phi, G + {g'}) returns

Lines L3 and L15 unify a query subgoal with a view subgoal position by position. When two query variables meet one view variable, or one query variable meets two view variables, the two view variables must become one. That is allowed only for two distinguished variables, and then the head homomorphism hh equates them. An existential variable cannot be equated with anything else, because the view stores no value for it.

Line L12 is C1. Line L13 checks C2: it looks for a subgoal outside GG that shares a variable mapped to an existential. If there is one, lines L14 to L16 try each way to map it into the same view. A branch that fails is dropped, and if all branches fail, the seed of line L2 gives no MCD.

The combination step needs no containment test. Line L7 takes MCDs whose subgoal sets are disjoint and cover the query. Line L8 joins the query variables that one view puts in the same place. Line L9 picks the argument of each head position: the query variable mapped there, or a new variable for a position that no query variable uses.

Example

The query and views come from Pottinger and Halevy. Q(x) :- cites(x,y),cites(y,x),sameTopic(x,y)Q(x) \text{ :- } \text{cites}(x, y), \text{cites}(y, x), \text{sameTopic}(x, y) asks for papers that cite a paper on the same topic that cites them back. The views are

  • V4(a) :- cites(a,b),cites(b,a)V_4(a) \text{ :- } \text{cites}(a, b), \text{cites}(b, a),
  • V5(c,d) :- sameTopic(c,d)V_5(c, d) \text{ :- } \text{sameTopic}(c, d),
  • V6(f,h) :- cites(f,g),cites(g,h),sameTopic(f,g)V_6(f, h) \text{ :- } \text{cites}(f, g), \text{cites}(g, h), \text{sameTopic}(f, g).

Call the subgoals g1,g2,g3g_1, g_2, g_3. The table shows the seeds of line L2 and what CLOSE does with them.

seed after line L3 CLOSE MCD
g1g_1 with cites(a,b)(a, b) of V4V_4 x↦ax \mapsto a, y↦by \mapsto b yy is existential, so add g2g_2 with cites(b,a)(b, a); then g3g_3 needs sameTopic, which V4V_4 lacks none
g1g_1 with cites(b,a)(b, a) of V4V_4 x↦bx \mapsto b line L12: head variable xx on an existential none
g3g_3 with sameTopic(c,d)(c, d) of V5V_5 x↦cx \mapsto c, y↦dy \mapsto d nothing to add (V5,{g3})(V_5, \{g_3\})
g1g_1 with cites(f,g)(f, g) of V6V_6 x↦fx \mapsto f, y↦gy \mapsto g add g2g_2 with cites(g,h)(g, h), which forces h↦fh \mapsto f; add g3g_3 with sameTopic(f,g)(f, g) (V6,{g1,g2,g3})(V_6, \{g_1, g_2, g_3\}), h={f,h↦f}h = \{f, h \mapsto f\}
g2g_2 with cites(g,h)(g, h) of V6V_6 y↦gy \mapsto g, x↦hx \mapsto h the same closure the same MCD

The other seeds fail at line L12 or repeat an MCD. V5V_5 covers g3g_3 alone, but no MCD covers g1g_1 and g2g_2 without g3g_3. So line L7 finds one partition, {g1,g2,g3}\{g_1, g_2, g_3\}, and the answer is Q′(x) :- V6(x,x)Q'(x) \text{ :- } V_6(x, x). The bucket algorithm would build 2 times 2 times 2 candidates here and test each one for containment.

A chain. For Q(x,w) :- e(x,y),e(y,z),e(z,w)Q(x, w) \text{ :- } e(x, y), e(y, z), e(z, w) with V1(a,c) :- e(a,b),e(b,c)V_1(a, c) \text{ :- } e(a, b), e(b, c) and V2(a,b) :- e(a,b)V_2(a, b) \text{ :- } e(a, b), there are five MCDs: V2V_2 on each subgoal alone, V1V_1 on {g1,g2}\{g_1, g_2\} and V1V_1 on {g2,g3}\{g_2, g_3\}. A single subgoal cannot use V1V_1, since its middle variable bb is existential and is shared with the next or previous subgoal. Three partitions exist, and MiniCon returns Q′(x,w) :- V1(x,z),V2(z,w)Q'(x, w) \text{ :- } V_1(x, z), V_2(z, w), Q′(x,w) :- V2(x,y),V1(y,w)Q'(x, w) \text{ :- } V_2(x, y), V_1(y, w) and Q′(x,w) :- V2(x,y),V2(y,z),V2(z,w)Q'(x, w) \text{ :- } V_2(x, y), V_2(y, z), V_2(z, w).

Correctness

Theorem (Pottinger and Halevy). For conjunctive queries and views without comparisons, the union of the rewritings that MINICON returns is a maximally contained rewriting of QQ among unions of conjunctive queries over the views.

The proof file proves it in full. Soundness uses C2: a variable that two MCDs share is distinguished in both, so the containment mapping of each MCD agrees with the others on it. Completeness starts from a containment mapping of QQ into the expansion of any contained rewriting. The subgoals that map into one view atom split into pieces that share existential variables, each piece is an MCD that the search finds, and these MCDs give a rewriting that contains the given one.

By the results of Abiteboul and Duschka, the maximally contained rewriting gives the certain answers under the open world assumption when the views and the query are conjunctive.

Proof: MiniCon returns a maximally contained rewriting of a conjunctive query using conjunctive viewsfull

Setting. The query is Q(xˉ) :- g1,…,gnQ(\bar x) \text{ :- } g_1, \ldots, g_n and each view is V(Yˉ) :- v1,…,vrV(\bar Y) \text{ :- } v_1, \ldots, v_r with r≤mr \le m. All terms are variables, there are no comparisons, and set semantics holds. A variable of a view is a head variable if it is in Yˉ\bar Y and existential otherwise. A rewriting PP is a conjunctive query over the view names. Its expansion PexpP^{exp} replaces each view atom V(aˉ)V(\bar a), the kk-th atom of PP, by the body of VV under the renaming renkren_k that sends the head variable at position pp to apa_p and each existential uu to a new variable uku_k used nowhere else. PP is contained in QQ if Pexp⊆QP^{exp} \subseteq Q. By the Chandra-Merlin theorem, A⊆BA \subseteq B for conjunctive queries if and only if there is a containment mapping from BB to AA: a map on variables that sends the head of BB to the head of AA and each body atom of BB to a body atom of AA.

An MCD is a tuple (V,h,φ,G)(V, h, \varphi, G). Here GG is a set of subgoals of QQ, hh maps the head variables of VV to head variables of VV with h(h(y))=h(y)h(h(y)) = h(y) (the head homomorphism), and φ\varphi maps the variables of GG to variables of VV with values in the range of hh or existential, such that each g∈Gg \in G has a subgoal vv of VV with φ(g)=h(v)\varphi(g) = h(v). Here hh is the identity on existentials. Property 1 is the pair of conditions of lines L12 and L13:

  • (C1) φ(x)\varphi(x) is a head variable for each head variable xx of QQ in GG;
  • (C2) if φ(x)\varphi(x) is existential, then every subgoal of QQ that holds xx is in GG.

Lemma 1 (unification). Let φ,h\varphi, h be as above and let a subgoal gg of QQ and a subgoal vv of VV have the same predicate. Line L15 (and line L3, with φ\varphi empty and hh the identity) returns the least restrictive extension (φ′,h′)(\varphi', h') with φ′(g)=h′(v)\varphi'(g) = h'(v) that equates no existential with another variable, or fails if none exists. It returns a result if there is a map ρ\rho from the variables of VV with ρ∘h=ρ\rho \circ h = \rho on head variables, ρ\rho one to one on existentials with values that no head variable takes, and ρ(φ(x))=ρ(vp)\rho(\varphi(x)) = \rho(v_p) for each position pp at which gg holds xx.

Proof. The procedure walks the positions of gg. At position pp with variable xx and view variable a=h(vp)a = h(v_p), it sets φ(x)=a\varphi(x) = a if φ(x)\varphi(x) is not set. If φ(x)=b≠a\varphi(x) = b \ne a, then bb and aa must become one variable. This is possible only if both are head variables, and then the procedure merges their classes in hh and φ\varphi, keeping the head variable with the lowest position as the class name. Each merge is forced by the equation φ(g)=h(v)\varphi(g) = h(v), so the result is the least restrictive one, and the choice of names makes it unique. Under the map ρ\rho of the second claim, ρ(a)=ρ(vp)=ρ(b)\rho(a) = \rho(v_p) = \rho(b). If aa or bb were existential, the conditions on ρ\rho would give a=ba = b. So the procedure never fails, and the merges keep ρ∘h′=ρ\rho \circ h' = \rho and ρ∘φ′=ρ∘φ\rho \circ \varphi' = \rho \circ \varphi on old variables. □\square

Lemma 2 (each output tuple is an MCD with Property 1). Each tuple added at line L5 is an MCD that satisfies C1 and C2.

Proof. Lemma 1 keeps φ(g)=h(v)\varphi(g) = h(v) for each subgoal added so far, since later merges apply to both sides. Line L12 rejects every state that breaks C1, and the state is only returned by line L13 when no subgoal outside GG holds a variable with an existential image, which is C2. □\square

Lemma 3 (soundness). Each rewriting Q′Q' added at line L10 is contained in QQ.

Proof. Line L7 picks MCDs M1,…,McM_1, \ldots, M_c, with Mi=(Vi,hi,φi,Gi)M_i = (V_i, h_i, \varphi_i, G_i), whose sets GiG_i partition the subgoals of QQ. Line L8 gives the classes ECEC, and line L9 gives the atom Vi(aˉi)V_i(\bar a^i) with api=EC(Ψi(hi(Yp)))a^i_p = EC(\Psi_i(h_i(Y_p))), where Ψi(y)\Psi_i(y) is a variable xx with φi(x)=y\varphi_i(x) = y or a fresh variable. Let reniren_i be the renaming of the expansion of the ii-th atom. For a head variable yy, reni(y)=apiren_i(y) = a^i_p for its position pp, and reni(hi(y))=reni(y)ren_i(h_i(y)) = ren_i(y), since hih_i is idempotent and both give EC(Ψi(hi(y)))EC(\Psi_i(h_i(y))).

Define τ(x)=reni(φi(x))\tau(x) = ren_i(\varphi_i(x)) for xx a variable of a subgoal of GiG_i. This does not depend on ii. If xx occurs in GiG_i and in GjG_j with i≠ji \ne j, then φi(x)\varphi_i(x) is a head variable by C2, so τ(x)=EC(Ψi(φi(x)))=EC(x)\tau(x) = EC(\Psi_i(\varphi_i(x))) = EC(x), because Ψi(φi(x))\Psi_i(\varphi_i(x)) is a variable with the same φi\varphi_i image as xx and so in the class of xx. The same holds for jj.

For g∈Gig \in G_i, there is vv with φi(g)=hi(v)\varphi_i(g) = h_i(v), so τ(g)=reni(hi(v))=reni(v)\tau(g) = ren_i(h_i(v)) = ren_i(v), an atom of Q′expQ'^{exp}. For a head variable xx of QQ, C1 gives τ(x)=EC(x)\tau(x) = EC(x), the head of Q′Q' at that position. So τ\tau is a containment mapping from QQ to Q′expQ'^{exp}, and Q′⊆QQ' \subseteq Q. □\square

Lemma 4 (completeness). Let PP be a conjunctive rewriting with P⊆QP \subseteq Q. Then some rewriting Q′Q' added at line L10 has P⊆Q′P \subseteq Q'.

Proof. Take a containment mapping τ\tau from QQ to PexpP^{exp}. Each τ(g)\tau(g) is an atom of the expansion of some atom k(g)k(g) of PP, so τ(g)=renk(g)(vg)\tau(g) = ren_{k(g)}(v_g) for a subgoal vgv_g of that view. Fix such choices. Let GkG_k be the subgoals with k(g)=kk(g) = k, and write ρ=renk\rho = ren_k.

A variable of PexpP^{exp} of the form uku_k is existential in the kk-th expansion and occurs only there. So if τ(x)=uk\tau(x) = u_k, every subgoal that holds xx is in GkG_k. Call two subgoals of GkG_k linked if they share a variable xx with τ(x)\tau(x) of the form uku_k.

Start the procedure at line L2 with a subgoal g∈Gkg \in G_k, the view of the kk-th atom and the subgoal vgv_g. At line L14, take the branch vg′v_{g'} for the subgoal g′g' that line L13 picks. By Lemma 1, applied with ρ\rho, each unification succeeds and keeps ρ(φ(x))=τ(x)\rho(\varphi(x)) = \tau(x). So φ(x)\varphi(x) is existential exactly when τ(x)\tau(x) is of the form uku_k, because ρ\rho sends head variables to variables of PP and existentials to variables uku_k. Line L12 never fails, since a head variable xx of QQ has τ(x)\tau(x) in the head of PP. Line L13 picks only subgoals linked to the current set. So this branch returns an MCD whose set is the linked component of gg in GkG_k. These components partition each GkG_k, and the sets GkG_k partition the subgoals of QQ. Line L7 enumerates this partition, since it tries every disjoint cover. Let Q′Q' be its rewriting.

Map each variable of Q′Q' to a variable of PP. A class EC(x)EC(x) goes to τ(x)\tau(x). This is well defined, because φi(x)=φi(y)\varphi_i(x) = \varphi_i(y) gives τ(x)=ρi(φi(x))=τ(y)\tau(x) = \rho_i(\varphi_i(x)) = \tau(y). A fresh variable made at line L9 for the class of a head variable yy of ViV_i goes to ρi(y)\rho_i(y). Then the pp-th argument of the ii-th atom of Q′Q' goes to ρi(hi(Yp))=ρi(Yp)\rho_i(h_i(Y_p)) = \rho_i(Y_p), the pp-th argument of atom kk of PP. The head EC(xˉ)EC(\bar x) goes to τ(xˉ)\tau(\bar x), the head of PP. This is a containment mapping from Q′Q' to PP, so P⊆Q′P \subseteq Q'. □\square

Theorem. MINICON stops, and the union RR of its output is a maximally contained rewriting of QQ using the views among unions of conjunctive queries: R⊆QR \subseteq Q, and P⊆RP \subseteq R for each union of conjunctive queries PP over the views with P⊆QP \subseteq Q.

Proof. Termination: each recursion of CLOSE adds a subgoal to GG, so its depth is at most nn, and each loop is over a finite set. Lemma 3 gives R⊆QR \subseteq Q. A union P⊆QP \subseteq Q has each disjunct contained in QQ, and Lemma 4 puts each disjunct inside one member of RR. ■\blacksquare

Running time. Let kk be the number of views and aa the largest arity. An MCD is fixed by its view and by the view subgoal chosen for each subgoal in GG, because Lemma 1 makes the unifier unique. So there are at most d≤k(m+1)nd \le k (m + 1)^n MCDs, and the search of lines L2 to L5 has at most nkm⋅mnn k m \cdot m^n leaves, each reached in O(n2a)O(n^2 a) steps. A set of MCDs that partitions the subgoals is fixed by the partition, at most nnn^n choices, and by the view and view subgoal of each subgoal, at most (km)n(k m)^n choices, so line L7 yields at most (nkm)n(n k m)^n sets. This is the bound of Pottinger and Halevy. The enumeration visits at most (nkm+1)n(n k m + 1)^n partial covers and scans the dd MCDs at each one. The total time is O(a n k (m+1)n(nkm+1)n)O(a\, n\, k\, (m + 1)^n (n k m + 1)^n) in combined complexity.

Complexity

All bounds are in combined complexity, since the query and the views are the input.

  • Time. An MCD is fixed by its view and by the view subgoal of each query subgoal, so there are at most k(m+1)nk (m + 1)^n MCDs. A set of MCDs that partitions the subgoals is fixed by the partition and by these choices, so line L7 yields at most (nkm)n(n k m)^n sets, as Pottinger and Halevy state. With the scans of the enumeration, the total is O(a n k (m+1)n(nkm+1)n)O(a\, n\, k\, (m + 1)^n (n k m + 1)^n) time (a theorem, proved in the proof file).
  • Space. O(a n k (m+1)n)O(a\, n\, k\, (m + 1)^n) for the MCDs, plus the output.

The exponent in nn cannot go away in general, since deciding whether an equivalent rewriting exists is NP-complete. In practice the number of MCDs is small, because C2 kills most seeds early.

Properties

  • Exact. The output is the maximally contained rewriting, not an approximation of it.
  • Deterministic. The order of the views and the subgoals fixes the order of the output.
  • No final containment test. Every combination of line L7 is a contained rewriting, by the soundness lemma.
  • Duplicates. Two partitions can give the same rewriting up to variable names, and a rewriting can be contained in another one. The code removes only exact copies.

Variants and improvements

  • Comparison predicates. Pottinger and Halevy extend MiniCon to queries and views with arithmetic comparisons. The extension needs extra checks on the comparisons that an MCD covers. This page and its code treat only the case without comparisons.
  • Equivalent rewritings. To find an equivalent rewriting, run the same combination step, then test each candidate for containment of QQ in its expansion.
  • Inverse rules. The inverse rules algorithm gets the same answers from the view instance by a Datalog program with Skolem terms, without writing out the rewriting.

When to use it

Use MiniCon when you need the rewriting itself, for example to send it to the sources or to optimize it, and the views are many. Pottinger and Levy measured (a measurement, in Java on a dual Pentium II) that MiniCon scales to more than a thousand views for chain queries, while the bucket and inverse rules algorithms are much slower. If you only need the answers on one view instance, the inverse rules program is simpler.

Pitfalls

  • Skipping C2. If line L13 always returns, an MCD can cover one subgoal with a view that hides the join variable. In the chain, V1V_1 would cover e(x,y)e(x, y) alone with y↦by \mapsto b, and the combination Q′(x,w) :- V1(x,u),V2(y,z),V2(z,w)Q'(x, w) \text{ :- } V_1(x, u), V_2(y, z), V_2(z, w) loses the join on yy. Its expansion is not contained in QQ.
  • Equating an existential. Lines L3 and L15 may only merge two distinguished view variables. If the unifier also merges an existential with another variable, it produces MCDs whose rewritings claim joins that the view does not expose.
  • Head variables on existentials. Without line L12, g1g_1 with cites(b,a)(b, a) of V4V_4 in the example sends the answer variable xx to bb, which the view does not return.
  • Overlapping MCDs. Line L7 needs disjoint sets. If it allows overlaps, the rewritings are still contained, but there are many more of them, and each one is contained in a rewriting from a disjoint set, so the extra work buys nothing.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

minicon_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minicon-algorithm/. The authors are listed in prov/Y3KK7E.jsonl.

"""The MiniCon algorithm for conjunctive queries and conjunctive views.

An atom is a pair (predicate, tuple of variables). A conjunctive query is a
pair (head, body): head is a tuple of variables and body is a list of atoms.
All terms are variables: there are no constants and no comparisons. A view is
a conjunctive query whose head has distinct variables, and views is a dict
from view name to view. A rewriting is a conjunctive query whose predicates
are view names. Set semantics holds throughout.
"""


def variables(atoms):
    """The variables of a list of atoms, in order of first occurrence."""
    seen = {}
    for _, args in atoms:
        for a in args:
            seen.setdefault(a, None)
    return list(seen)


def _matches(atoms, index, binding):
    """Yield each extension of binding that maps every atom to a tuple of index."""
    if not atoms:
        yield binding
        return
    pred, args = atoms[0]
    for tup in index.get(pred, ()):
        if len(tup) != len(args):
            continue
        new = dict(binding)
        ok = True
        for a, v in zip(args, tup):
            if new.setdefault(a, v) != v:
                ok = False
                break
        if ok:
            yield from _matches(atoms[1:], index, new)


def evaluate(query, instance):
    """The answers of a conjunctive query on an instance {predicate: set of tuples}."""
    head, body = query
    return {tuple(m[x] for x in head) for m in _matches(list(body), instance, {})}


def contained(q1, q2):
    """True if q1 is contained in q2: a containment mapping sends q2 onto the frozen q1."""
    (head1, body1), (head2, body2) = q1, q2
    if len(head1) != len(head2):
        return False
    start = {}
    for a, b in zip(head2, head1):
        if start.setdefault(a, b) != b:
            return False
    index = {}
    for pred, args in body1:
        index.setdefault(pred, set()).add(tuple(args))
    return next(_matches(list(body2), index, start), None) is not None


def expand(rewriting, views):
    """Replace each view atom by the body of its view, with fresh existential variables."""
    head, body = rewriting
    out = []
    for k, (name, args) in enumerate(body):
        vhead, vbody = views[name]
        ren = dict(zip(vhead, args))
        for pred, us in vbody:
            out.append((pred, tuple(ren.setdefault(u, "%s#%d" % (u, k)) for u in us)))
    return (tuple(head), out)


def _unify(phi, hmap, g_args, v_args, vhead):
    """Extend (phi, hmap) so that phi(g) = hmap(v), in the least restrictive way, or None.

    phi maps query variables to view variables. hmap maps each head variable of
    the view to its representative: it is the head homomorphism. vhead maps each
    head variable to its position, and the representative of a class is the
    head variable with the lowest position. An existential view variable may
    not be equated with any other view variable.
    """
    phi, hmap = dict(phi), dict(hmap)
    for x, a in zip(g_args, v_args):
        a = hmap.get(a, a)
        b = phi.get(x)
        if b is None:
            phi[x] = a
        elif b != a:
            if b not in vhead or a not in vhead:
                return None
            if vhead[a] < vhead[b]:
                a, b = b, a
            for y in hmap:
                if hmap[y] == a:
                    hmap[y] = b
            for y in phi:
                if phi[y] == a:
                    phi[y] = b
    return phi, hmap


def _close(query, view, phi, hmap, cover):
    """Yield each (phi, hmap, cover) that extends the input and satisfies Property 1."""
    qhead, qbody = query
    vhead, vbody = view
    vheadset = {y: k for k, y in enumerate(vhead)}
    if any(x in phi and phi[x] not in vheadset for x in qhead):  # @line L12
        return
    for j, (pred, args) in enumerate(qbody):  # @line L13
        if j not in cover and any(x in phi and phi[x] not in vheadset for x in args):
            break
    else:
        yield phi, hmap, cover
        return
    for vpred, vargs in vbody:  # @line L14
        if vpred == pred and len(vargs) == len(args):
            ext = _unify(phi, hmap, args, vargs, vheadset)  # @line L15
            if ext is not None:
                yield from _close(query, view, ext[0], ext[1], cover | {j})  # @line L16


def form_mcds(query, views):
    """The MiniCon descriptions: tuples (view name, hmap, phi, frozenset of subgoal indexes)."""
    qhead, qbody = query
    mcds = {}  # @line L1
    for i, (pred, args) in enumerate(qbody):  # @line L2
        for name in sorted(views):
            vhead, vbody = views[name]
            for vpred, vargs in vbody:
                if vpred != pred or len(vargs) != len(args):
                    continue
                start = _unify({}, {y: y for y in vhead}, args, vargs, {y: k for k, y in enumerate(vhead)})  # @line L3
                if start is None:
                    continue
                for phi, hmap, cover in _close(query, views[name], start[0], start[1], frozenset([i])):  # @line L4
                    key = (name, tuple(sorted(hmap.items())), tuple(sorted(phi.items())), cover)
                    mcds[key] = (name, hmap, phi, cover)  # @line L5
    return [mcds[k] for k in sorted(mcds, key=repr)]


def _partitions(n, mcds):
    """Each list of MCDs whose subgoal sets are disjoint and cover 0..n-1 (Property 2)."""

    def rec(covered, chosen):
        if len(covered) == n:
            yield list(chosen)
            return
        first = min(set(range(n)) - covered)
        for m in mcds:
            if first in m[3] and not (m[3] & covered):
                chosen.append(m)
                yield from rec(covered | m[3], chosen)
                chosen.pop()

    yield from rec(frozenset(), [])


def combine_mcds(query, views, mcds):
    """The conjunctive rewritings, one for each set of MCDs that partitions the subgoals."""
    qhead, qbody = query
    order = {x: k for k, x in enumerate(list(qhead) + variables(qbody))}
    result = []  # @line L6
    for combo in _partitions(len(qbody), mcds):  # @line L7
        parent = {x: x for x in order}

        def find(x):
            while parent[x] != x:
                x = parent[x]
            return x

        for _, _, phi, _ in combo:  # @line L8
            first = {}
            for x in sorted(phi, key=order.get):
                y = phi[x]
                if y in first:
                    rx, ry = find(x), find(first[y])
                    if rx != ry:
                        lo, hi = sorted((rx, ry), key=order.get)
                        parent[hi] = lo
                else:
                    first[y] = x
        fresh = 0
        body = []
        for name, hmap, phi, _ in combo:
            inv = {}
            for x in sorted(phi, key=order.get):
                inv.setdefault(phi[x], x)
            args = []
            for y in views[name][0]:
                y = hmap[y]
                if y not in inv:  # @line L9
                    fresh += 1
                    inv[y] = "_%d" % fresh
                    args.append(inv[y])
                else:
                    args.append(find(inv[y]) if inv[y] in parent else inv[y])
            body.append((name, tuple(args)))
        rewriting = (tuple(find(x) for x in qhead), body)
        if rewriting not in result:
            result.append(rewriting)  # @line L10
    return result


def minicon(query, views):
    """A union of conjunctive rewritings that is the maximally contained rewriting of query."""
    mcds = form_mcds(query, views)
    return combine_mcds(query, views, mcds)  # @line L11


def answer(rewritings, view_instance):
    """The answers of a union of rewritings on an instance of the views."""
    out = set()
    for r in rewritings:
        out |= evaluate(r, view_instance)
    return out
test_minicon_algorithm.py 181 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minicon-algorithm/. The authors are listed in prov/Y3KK7E.jsonl.

import itertools
import random

from minicon_algorithm import answer, contained, evaluate, expand, form_mcds, minicon, variables

# The example of Pottinger and Levy (VLDB 2000), Section 3.
Q1 = (("x",), [("cites", ("x", "y")), ("cites", ("y", "x")), ("sameTopic", ("x", "y"))])
PAPER_VIEWS = {
    "V4": (("a",), [("cites", ("a", "b")), ("cites", ("b", "a"))]),
    "V5": (("c", "d"), [("sameTopic", ("c", "d"))]),
    "V6": (("f", "h"), [("cites", ("f", "g")), ("cites", ("g", "h")), ("sameTopic", ("f", "g"))]),
}


def certain_answers(query, views, view_instance):
    """Oracle: chase the view facts into a canonical database with labeled nulls,
    evaluate the query and keep the answers without nulls."""
    db = {}
    k = 0
    for name, tuples in view_instance.items():
        vhead, vbody = views[name]
        for t in sorted(tuples):
            k += 1
            m = dict(zip(vhead, t))
            for pred, args in vbody:
                db.setdefault(pred, set()).add(tuple(m.setdefault(u, ("null", k, u)) for u in args))
    return {t for t in evaluate(query, db) if not any(isinstance(v, tuple) for v in t)}


def view_image(views, db):
    return {name: evaluate(v, db) for name, v in views.items()}


def brute_contained_rewritings(query, views, max_atoms):
    """Oracle: every contained rewriting with at most max_atoms view atoms whose
    variables are query variables or fresh ones, with each possible head."""
    qhead, qbody = query
    qvars = variables(qbody)
    atoms = []
    for name in sorted(views):
        arity = len(views[name][0])
        for args in itertools.product(qvars + [None], repeat=arity):
            atoms.append((name, args))
    for size in range(1, max_atoms + 1):
        for combo in itertools.combinations_with_replacement(atoms, size):
            fresh = itertools.count()
            body = [(n, tuple(a if a is not None else "_f%d" % next(fresh) for a in args)) for n, args in combo]
            ehead, ebody = expand(((), body), views)
            index = {}
            for pred, args in ebody:
                index.setdefault(pred, set()).add(args)
            rvars = set(variables(body))
            heads = set()
            for h in _all_maps(qbody, index):
                t = tuple(h[x] for x in qhead)
                if all(v in rvars for v in t):
                    heads.add(t)
            for t in sorted(heads):
                yield (t, body)


def _all_maps(atoms, index, binding=None):
    binding = {} if binding is None else binding
    if not atoms:
        yield binding
        return
    pred, args = atoms[0]
    for tup in index.get(pred, ()):
        new = dict(binding)
        if all(new.setdefault(a, v) == v for a, v in zip(args, tup)):
            yield from _all_maps(atoms[1:], index, new)


def random_case(rng):
    preds = [("e", 2), ("p", 1)]
    qv = ["x", "y", "z"]
    body = []
    for _ in range(rng.randint(1, 3)):
        p, ar = rng.choice(preds)
        atom = (p, tuple(rng.choice(qv) for _ in range(ar)))
        if atom not in body:
            body.append(atom)
    used = variables(body)
    head = tuple(rng.sample(used, rng.randint(0, min(2, len(used)))))
    views = {}
    for k in range(rng.randint(1, 3)):
        vv = ["a", "b", "c"]
        vbody = []
        for _ in range(rng.randint(1, 2)):
            p, ar = rng.choice(preds)
            atom = (p, tuple(rng.choice(vv) for _ in range(ar)))
            if atom not in vbody:
                vbody.append(atom)
        vused = variables(vbody)
        vhead = tuple(rng.sample(vused, rng.randint(1, len(vused))))
        views["V%d" % k] = (vhead, vbody)
    return (head, body), views


def random_db(rng):
    dom = ["1", "2", "3"]
    db = {"e": set(), "p": set()}
    for _ in range(rng.randint(0, 5)):
        db["e"].add((rng.choice(dom), rng.choice(dom)))
    for _ in range(rng.randint(0, 2)):
        db["p"].add((rng.choice(dom),))
    return db


def test_paper_example():
    mcds = form_mcds(Q1, PAPER_VIEWS)
    # V5 covers sameTopic(x, y) alone. V6 must cover all three subgoals, with f = h.
    assert [(m[0], sorted(m[3])) for m in mcds] == [("V5", [2]), ("V6", [0, 1, 2])]
    v6 = mcds[1]
    assert v6[1] == {"f": "f", "h": "f"}
    assert v6[2] == {"x": "f", "y": "g"}
    assert minicon(Q1, PAPER_VIEWS) == [(("x",), [("V6", ("x", "x"))])]


def test_equivalent_rewriting_found():
    # Q(x, z) :- e(x, y), e(y, z) with the view V(a, b) :- e(a, b).
    q = (("x", "z"), [("e", ("x", "y")), ("e", ("y", "z"))])
    views = {"V": (("a", "b"), [("e", ("a", "b"))])}
    rs = minicon(q, views)
    assert rs == [(("x", "z"), [("V", ("x", "y")), ("V", ("y", "z"))])]
    assert contained(q, expand(rs[0], views)) and contained(expand(rs[0], views), q)


def test_no_rewriting_when_join_variable_is_hidden():
    # The join variable y is existential in each view, so nothing can join the two halves.
    q = (("x", "z"), [("e", ("x", "y")), ("e", ("y", "z"))])
    views = {"L": (("a",), [("e", ("a", "b"))]), "R": (("b",), [("e", ("a", "b"))])}
    assert minicon(q, views) == []


def test_sound_and_maximal_on_random_cases():
    rng = random.Random(7)
    checked = 0
    while checked < 150:
        query, views = random_case(rng)
        if not query[1]:
            continue
        checked += 1
        rs = minicon(query, views)
        for r in rs:
            assert set(r[0]) <= set(variables(r[1]))
            assert contained(expand(r, views), query)
        if len(query[1]) <= 2:
            for b in brute_contained_rewritings(query, views, len(query[1])):
                assert any(contained(b, r) for r in rs), (query, views, b, rs)
        for _ in range(4):
            db = random_db(rng)
            inst = view_image(views, db)
            got = answer(rs, inst)
            assert got <= evaluate(query, db)
            assert got == certain_answers(query, views, inst)


def test_paper_example_maximal():
    rs = minicon(Q1, PAPER_VIEWS)
    for b in brute_contained_rewritings(Q1, PAPER_VIEWS, 2):
        assert any(contained(b, r) for r in rs)


def test_head_variables_can_be_equated():
    # V(a) :- e(a, a) answers Q(x, y) :- e(x, y) only on the diagonal.
    q = (("x", "y"), [("e", ("x", "y"))])
    views = {"V": (("a",), [("e", ("a", "a"))])}
    assert minicon(q, views) == [(("x", "x"), [("V", ("x",))])]
    assert answer(minicon(q, views), {"V": {("1",)}}) == {("1", "1")}


def test_boolean_query():
    q = ((), [("e", ("x", "y"))])
    views = {"V": (("a",), [("e", ("a", "b"))])}
    rs = minicon(q, views)
    assert answer(rs, {"V": {("1",)}}) == {()}
    assert answer(rs, {"V": set()}) == set()

History

Levy, Rajaraman and Ordille introduced the bucket algorithm for the Information Manifold in 1996, and Duschka and Genesereth gave the inverse rules algorithm in 1997. Pottinger and Levy (Alon Levy, now Halevy) presented MiniCon at VLDB 2000. The journal version, with comparison predicates and experiments, appeared in the VLDB Journal in 2001. Halevy's survey of the same year places MiniCon among the algorithms for data integration.

References

  1. Rachel Pottinger and Alon Halevy, MiniCon: a scalable algorithm for answering queries using views, The VLDB Journal 10(2), 2001, pages 182-198, MiniCon descriptions, Property 1, the combination step and the experiments
  2. Alon Y. Halevy, Answering queries using views: a survey, The VLDB Journal 10(4), 2001, pages 270-294, the section on algorithms for data integration
  3. AnHai Doan, Alon Halevy and Zachary Ives, Principles of Data Integration, Morgan Kaufmann, 2012, Chapter 2, answering queries using views, the MiniCon algorithm

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example