Algorithm Search⌘K

Algorithmadvanced

Bucket algorithm

Also called Levy bucket algorithm.

Rewrite a query using views: put in a bucket for each subgoal the views that can cover it, then test each combination of bucket entries for containment.

Time
O(a n (k m)^(2n) (n m)^(3n)) worst
Space
O(a n (k m)^n (n m)^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 placeofflineiterative
Origin
Alon Y. Levy, Anand Rajaraman, Joann J. Ordille, 1996

The bucket algorithm 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 was the first practical algorithm for this task. It differs from MiniCon in where it does the work: the bucket algorithm considers each subgoal alone when it chooses views, and then pays with a containment test for every combination. MiniCon looks at the joins first and needs no test at the end.

In plain words

Each part of the question, such as "x cites y", gets a bucket. Into the bucket go all the views that hold facts of that kind and that keep the values the answer needs. Then the algorithm tries every way to take one view from each bucket.

A choice can still be wrong, because two parts of the question may need to join on a value that a view does not keep. So the algorithm checks each choice: it writes out what the chosen views really say and tests whether that is enough to answer the question. Sometimes a choice works only after two of its variables are made the same, and the algorithm tries that too.

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, and it is contained in QQ when its expansion, with each view atom replaced by the view body and new existential variables, is contained in QQ. The output is a union of contained rewritings that contains every other contained union of conjunctive queries.

The algorithm

  1. BUCKET(Q, Views)
  2. 1for each subgoal g of Q do
  3. 2bucket[g] <- empty
  4. 3for each view V and each subgoal v of V with the predicate of g do
  5. 4if g unifies with v and each head variable of Q in g meets a head variable of V then
  6. 5add the head of V under the unifier to bucket[g], with fresh variables for unmatched positions
  7. 6result <- empty
  8. 7for each choice (a_1, ..., a_n) in bucket[g_1] × ... × bucket[g_n] do
  9. 8Q' <- Q(X) :- a_1, ..., a_n
  10. 9for each most general equating theta of variables of Q' with theta(Q') contained in Q do
  11. 10add theta(Q'), with redundant atoms removed, to result
  12. 11return result without the members that are contained in other members

Line L4 unifies the query subgoal with the view subgoal position by position, so that query variables and view variables that meet fall into one class. The test asks that every head variable of QQ in the subgoal lands in a class with a distinguished view variable. Otherwise the view cannot return the value that the answer needs. Line L5 writes the view atom with, at each head position, a query variable of its class, or a new variable if no query variable reached that position.

Line L9 is the containment test. It expands Q′Q' and looks for a containment mapping from QQ into the expansion, by the Chandra-Merlin theorem. The search may equate variables of Q′Q', but never an existential variable of the expansion with anything other than a query variable. Each search branch that succeeds gives the least equating for that branch. Line L10 removes atoms while the query stays equivalent, the same step as conjunctive query minimization. Line L11 drops rewritings that add no answers.

Example

The query and views are the running example of 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), with

  • 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).

Lines L1 to L5 give these buckets. The fresh variables are u1,u2,u3u_1, u_2, u_3.

subgoal bucket
cites(x,y)(x, y) V4(x)V_4(x), V6(x,u1)V_6(x, u_1)
cites(y,x)(y, x) V4(x)V_4(x), V6(u2,x)V_6(u_2, x)
sameTopic(x,y)(x, y) V5(x,y)V_5(x, y), V6(x,u3)V_6(x, u_3)

V4V_4 is in the first bucket by cites(a,b)(a, b), with x↦ax \mapsto a. Its other subgoal cites(b,a)(b, a) would put xx on the existential bb, so line L4 rejects it. Line L7 makes 2⋅2⋅2=82 \cdot 2 \cdot 2 = 8 candidates. None of them is contained in QQ as it stands.

candidate line L9 line L10
V4(x),V4(x),V5(x,y)V_4(x), V_4(x), V_5(x, y) yy must be the existential bb of V4V_4 and also the variable yy of V5V_5: no equating none
V6(x,u1),V6(u2,x),V6(x,u3)V_6(x, u_1), V_6(u_2, x), V_6(x, u_3) map all three subgoals into the expansion of one V6V_6 atom, which equates its free argument with xx V6(x,x)V_6(x, x)
V4(x),V4(x),V6(x,u3)V_4(x), V_4(x), V_6(x, u_3) map all three subgoals into the expansion of V6(x,u3)V_6(x, u_3): u3=xu_3 = x V4(x),V6(x,x)V_4(x), V_6(x, x)
V6(x,u1),V6(u2,x),V5(x,y)V_6(x, u_1), V_6(u_2, x), V_5(x, y) the same with the first atom: u1=xu_1 = x V6(x,x),V5(x,y)V_6(x, x), V_5(x, y)
the 4 other candidates each holds a V6V_6 atom and gets the same kind of equating V6(x,x)V_6(x, x) with V4(x)V_4(x), V5(x,y)V_5(x, y) or both

Line L10 cannot remove V4(x)V_4(x) or V5(x,y)V_5(x, y), since each one adds a condition. But each of these rewritings is contained in V6(x,x)V_6(x, x), so line L11 leaves one rewriting, Q′(x) :- V6(x,x)Q'(x) \text{ :- } V_6(x, x), the same as MiniCon gives. The work was 8 candidates with a containment search each, where MiniCon formed two descriptions and one combination.

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), the buckets are {V1(x,u1),V2(x,y)}\{V_1(x, u_1), V_2(x, y)\}, {V1(y,u2),V1(u3,z),V2(y,z)}\{V_1(y, u_2), V_1(u_3, z), V_2(y, z)\} and {V1(u4,w),V2(z,w)}\{V_1(u_4, w), V_2(z, w)\}, so there are 12 candidates. The ones made only of V1V_1 atoms admit no equating. The result, after line L11, is V1(x,u),V2(u,w)V_1(x, u), V_2(u, w), then V2(x,y),V1(y,w)V_2(x, y), V_1(y, w), then V2(x,y),V2(y,z),V2(z,w)V_2(x, y), V_2(y, z), V_2(z, w).

Correctness

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

The proof file proves it in full. Soundness holds because line L9 only keeps equatings that pass the containment test. For completeness, take a contained rewriting PP and a containment mapping of QQ into its expansion. Each subgoal lands in the expansion of one view atom of PP, so it passes line L4 for that view, and the entries of these views form a candidate. The containment mapping tells the search of line L9 which atoms to use, and the equating it finds is more general than the one that turns the candidate into a part of PP. So PP is contained in a rewriting that line L10 adds.

Under the open world assumption, the maximally contained rewriting gives the certain answers of a conjunctive query over conjunctive views, by the results of Abiteboul and Duschka.

Proof: The bucket algorithm 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 of the kk views 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 the jj-th atom V(aˉ)V(\bar a) of PP by the body of VV under the renaming renjren_j that sends the head variable at position pp to apa_p and each existential uu to a new variable uju_j. PP is contained in QQ if Pexp⊆QP^{exp} \subseteq Q. By the Chandra-Merlin theorem, A⊆BA \subseteq B if and only if there is a containment mapping from BB to AA. A containment mapping from AA to BB also shows that B⊆AB \subseteq A whenever BB is obtained from AA by a substitution, and that A⊆A′A \subseteq A' when A′A' has the same head and a subset of the body of AA.

Lemma 1 (bucket entries). Line L4 accepts a subgoal vv of a view VV for a subgoal gg if and only if, in the classes made by unifying gg with vv position by position, the class of each head variable of QQ in gg holds a head variable of VV. Line L5 then adds the atom V(eˉ)V(\bar e), where epe_p is a query variable in the class of YpY_p if there is one, and a fresh variable otherwise.

Proof. This is what lines L3 to L5 compute. □\square

Lemma 2 (equatings). For a candidate CC, line L9 yields maps θ\theta on the variables of CC such that θ(C)⊆Q\theta(C) \subseteq Q. If σ\sigma maps the variables of CC to variables and there is a containment mapping τ\tau from QQ to σ(C)exp\sigma(C)^{exp} that sends each subgoal gig_i to σ^(Ai)\hat\sigma(A_i) for an atom AiA_i of CexpC^{exp}, where σ^\hat\sigma is σ\sigma on the variables of CC and one to one on the existentials of CexpC^{exp} with values outside the variables of σ(C)\sigma(C), then line L9 yields a θ\theta and a map σ′\sigma' with σ=σ′∘θ\sigma = \sigma' \circ \theta.

Proof. The search picks an atom AiA_i of CexpC^{exp} for each gig_i and unifies them. It keeps a state only if no class holds two terms of CexpC^{exp} one of which is an existential. At the end, θ\theta sends each variable of CC to the first variable of CC in its class. Map each query variable xx to the term of CexpC^{exp} in its class, after θ\theta. A class with an existential holds only that one term of CexpC^{exp}, and the head variables of QQ start in the class of the head of CC. So this map sends xˉ\bar x to the head of θ(C)\theta(C) and each gig_i to θ(Ai)\theta(A_i), an atom of θ(C)exp\theta(C)^{exp}. If θ\theta makes two atoms of CC equal, line L10 keeps one copy, and the existentials of the other copy map onto those of the kept copy. So θ(C)⊆Q\theta(C) \subseteq Q.

For the second claim, follow the branch that picks the atoms AiA_i. Every term placed in the class of xx has the image τ(x)\tau(x) under σ^\hat\sigma, since each unification step joins terms whose images are equal. An existential uu has an image that no other term of CexpC^{exp} has, so its class holds no other term of CexpC^{exp} and the branch is kept. Variables of CC in one class have one image under σ\sigma, so σ\sigma is constant on the classes, and σ=σ′∘θ\sigma = \sigma' \circ \theta for the map σ′\sigma' that sends θ(y)\theta(y) to σ(y)\sigma(y). □\square

Lemma 3 (minimize). The procedure applied at line L10 returns a query equivalent to its input.

Proof. It drops an atom only when the shorter query, which contains the longer one, is also contained in it. □\square

Theorem. BUCKET stops, and the union RR of its output is a maximally contained rewriting of QQ among unions of conjunctive queries over the views: 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. The buckets, the candidates and the search branches are finite.

Soundness. Each rewriting added at line L10 is equivalent to some θ(C)⊆Q\theta(C) \subseteq Q by Lemmas 2 and 3. Line L11 only removes rewritings.

Completeness. It suffices to treat a conjunctive rewriting P⊆QP \subseteq Q, since a union is contained in QQ exactly when each disjunct is. Take a containment mapping τ\tau from QQ to PexpP^{exp}. Each τ(gi)\tau(g_i) is renj(v)ren_j(v) for an atom j=j(i)j = j(i) of PP and a subgoal v=viv = v_i of its view. Write ρi=renj(i)\rho_i = ren_{j(i)}.

Unify gig_i with viv_i. Every member of a class has the same image, τ\tau of the query variables and ρi\rho_i of the view variables. A head variable xx of QQ has τ(x)\tau(x) in the head of PP, a variable of PP. An existential has an image uju_j that is not a variable of PP. So the class of xx holds a head variable of the view, and by Lemma 1 the bucket of gig_i holds an entry Ei=V(eˉ)E_i = V(\bar e) built from viv_i. Let CC be the candidate with these entries, and define σ\sigma on its variables: a query variable xx in an entry goes to τ(x)\tau(x), and a fresh variable at position pp of EiE_i goes to ρi(Yp)\rho_i(Y_p). In both cases the variable at position pp of EiE_i goes to ρi(Yp)\rho_i(Y_p), the pp-th argument of atom j(i)j(i) of PP. So σ(Ei)\sigma(E_i) is atom j(i)j(i) of PP, and σ\sigma sends the head xˉ\bar x of CC to τ(xˉ)\tau(\bar x), the head of PP.

For each atom jj of PP that some gig_i uses, fix one such i0(j)i_0(j), and let AiA_i be the atom of the expansion of Ei0(j(i))E_{i_0(j(i))} that comes from viv_i. Let σ^\hat\sigma send the existential uu of the expansion of Ei0(j)E_{i_0(j)} to uju_j. Then σ^(Ai)=ρi(vi)=τ(gi)\hat\sigma(A_i) = \rho_i(v_i) = \tau(g_i), and σ^\hat\sigma is one to one on these existentials with values outside the variables of PP. Line L7 reaches CC, and by Lemma 2, line L9 yields a θ\theta with σ=σ′∘θ\sigma = \sigma' \circ \theta. The map σ′\sigma' sends the head of θ(C)\theta(C) to the head of PP and each atom θ(Ei)\theta(E_i) to an atom of PP, so P⊆θ(C)P \subseteq \theta(C), and the rewriting added at line L10 is equivalent to θ(C)\theta(C). Line L11 drops a rewriting only if it is contained in one that stays, so PP is contained in a member of RR. ■\blacksquare

Running time. Let aa be the largest arity. Each bucket has at most kmk m entries, so line L7 makes at most (km)n(k m)^n candidates. For one candidate, the expansion has at most nmn m atoms, so the search of line L9 has at most (nm)n(n m)^n leaves and depth nn, and each step costs O(nma)O(n m a). A containment test between two rewritings of at most nn atoms is a backtracking search with at most nnn^n leaves of depth nn, each step O(a)O(a), so it costs O(nn+1a)O(n^{n+1} a), and minimizing one rewriting takes nn such tests. So at most F=(km)n(nm)nF = (k m)^n (n m)^n rewritings are found, in O(F nn+3m a)O(F\, n^{n+3} m\, a) time. Line L11 makes at most F2F^2 containment tests. The total is O(a n (km)2n(nm)3n)O(a\, n\, (k m)^{2n} (n m)^{3n}) time in combined complexity, using nn≤(nm)nn^n \le (n m)^n.

Complexity

All bounds are in combined complexity, and all are theorems proved in the proof file.

  • Time. Each bucket has at most kmk m entries, so there are at most (km)n(k m)^n candidates. The search of line L9 has at most (nm)n(n m)^n branches per candidate. With the containment tests of lines L10 and L11, the total is O(a n (km)2n(nm)3n)O(a\, n\, (k m)^{2n} (n m)^{3n}).
  • Space. O(a n (km)n(nm)n)O(a\, n\, (k m)^n (n m)^n) for the rewritings found before line L11.

Deciding whether an equivalent rewriting exists is NP-complete, so an exponent in nn is expected. The product of line L7 is the part that hurts in practice: Pottinger and Halevy measured (a measurement) that the bucket algorithm slows down sharply as the number of views grows, while MiniCon does not.

Properties

  • Exact. The output is the maximally contained rewriting.
  • Deterministic. The order of views and subgoals fixes the order of the output.
  • Local first step. Line L4 looks at one subgoal at a time, so a bucket can hold a view that fails for every combination.
  • Containment per candidate. Each candidate costs a search that is exponential in the worst case.

Variants and improvements

  • Comparison predicates. Levy, Rajaraman and Ordille also check that the comparisons of the query are consistent with those of the view before an entry goes into a bucket.
  • MiniCon. MiniCon moves the join check of line L9 into the first step, so it never builds the candidates that fail.
  • Inverse rules. The inverse rules algorithm skips the rewriting and computes the same answers with a Datalog program.

When to use it

Use it for teaching, and when there are few views and short queries, where the candidates are few and the code is simple. For many views, MiniCon gives the same output much faster. When only the answers on one view instance are needed, inverse rules are simpler.

Pitfalls

  • No containment test. If line L9 accepts every candidate, the result is not contained in QQ. In the example, V4(x),V4(x),V5(x,y)V_4(x), V_4(x), V_5(x, y) would be returned, but it does not say that the paper yy of sameTopic is the one that xx cites.
  • No equating. If line L9 tests only the candidate as it is, with θ\theta the identity, the example returns nothing, since none of the 8 candidates is contained in QQ without u1=xu_1 = x. The answer V6(x,x)V_6(x, x) is lost.
  • Distinguished variables in the bucket. If line L4 does not check the head variables of QQ, V4V_4 enters the first bucket through cites(b,a)(b, a) as V4(y)V_4(y), with xx on the hidden bb. Line L9 still keeps only contained rewritings, so the output stays right, but the number of candidates grows.
  • Line L11. Without it, the output can hold rewritings contained in others. The answers are the same, but the union is larger than needed.

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.

bucket_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bucket-algorithm/. The authors are listed in prov/GBX8BH.jsonl.

"""The bucket 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.
"""

import itertools


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.

    The fresh variable for the existential u of the k-th atom is "u#k". Query
    and rewriting variables must not contain "#".
    """
    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)


class _Classes:
    """A small union-find over hashable items."""

    def __init__(self):
        self.parent = {}

    def find(self, x):
        self.parent.setdefault(x, x)
        while self.parent[x] != x:
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra != rb:
            self.parent[rb] = ra

    def groups(self):
        out = {}
        for x in list(self.parent):
            out.setdefault(self.find(x), []).append(x)
        return out


def build_buckets(query, views):
    """Step 1: for each subgoal of the query, the view atoms that can cover it."""
    qhead, qbody = query
    dist = set(qhead)
    order = {x: k for k, x in enumerate(list(qhead) + variables(qbody))}
    fresh = itertools.count(1)
    buckets = []
    for pred, args in qbody:  # @line L1
        bucket = []  # @line L2
        for name in sorted(views):  # @line L3
            vhead, vbody = views[name]
            for vpred, vargs in vbody:
                if vpred != pred or len(vargs) != len(args):
                    continue
                uf = _Classes()
                for x, a in zip(args, vargs):
                    uf.union(("q", x), ("v", a))
                cls = uf.groups()
                heads = {("v", y) for y in vhead}
                if any(not any(m in heads for m in cls[uf.find(("q", x))]) for x in args if x in dist):  # @line L4
                    continue
                entry = []
                for y in vhead:
                    qs = [m[1] for m in cls.get(uf.find(("v", y)), []) if m[0] == "q"]
                    if qs:
                        entry.append(min(qs, key=lambda x: (x not in dist, order[x])))
                    else:
                        entry.append("_%d" % next(fresh))
                bucket.append((name, tuple(entry)))  # @line L5
        buckets.append(bucket)
    return buckets


def equatings(query, rewriting, views):
    """Each most general way to equate variables of rewriting so that its expansion
    is contained in query. Yields a dict from rewriting variables to variables.

    The search picks, for each subgoal of the query, an atom of the expansion
    with the same predicate, and unifies the two. An existential variable of the
    expansion may be unified only with query variables.
    """
    qhead, qbody = query
    rhead, rbody = rewriting
    ehead, ebody = expand(rewriting, views)
    rvars = list(rhead) + [v for v in variables(rbody) if v not in rhead]
    rset = set(rvars)
    pos = {v: k for k, v in enumerate(rvars)}

    def valid(uf):
        for members in uf.groups().values():
            es = [m[1] for m in members if m[0] == "e"]
            if len(es) > 1 and any(t not in rset for t in es):
                return False
        return True

    def rec(i, uf):
        if i == len(qbody):
            theta = {}
            for members in uf.groups().values():
                es = sorted((m[1] for m in members if m[0] == "e" and m[1] in rset), key=pos.get)
                for t in es:
                    theta[t] = es[0]
            yield theta
            return
        pred, args = qbody[i]
        for epred, eargs in ebody:
            if epred != pred or len(eargs) != len(args):
                continue
            new = _Classes()
            new.parent = dict(uf.parent)
            for x, t in zip(args, eargs):
                new.union(("q", x), ("e", t))
            if valid(new):
                yield from rec(i + 1, new)

    start = _Classes()
    for x, y in zip(qhead, rhead):
        start.union(("q", x), ("e", y))
    if valid(start):
        yield from rec(0, start)


def _apply(theta, rewriting):
    head, body = rewriting
    new_body = []
    for name, args in body:
        atom = (name, tuple(theta.get(a, a) for a in args))
        if atom not in new_body:
            new_body.append(atom)
    return (tuple(theta.get(x, x) for x in head), new_body)


def minimize(query):
    """Drop atoms of a conjunctive query while the result stays equivalent to it."""
    head, body = query
    body = list(body)
    i = 0
    while i < len(body):
        rest = body[:i] + body[i + 1:]
        if set(head) <= set(variables(rest)) and contained((head, rest), (head, body)):
            body = rest
        else:
            i += 1
    return (head, body)


def bucket_algorithm(query, views):
    """A union of conjunctive rewritings that is the maximally contained rewriting of query."""
    qhead, qbody = query
    buckets = build_buckets(query, views)
    found = []  # @line L6
    for combo in itertools.product(*buckets):  # @line L7
        candidate = (tuple(qhead), list(combo))  # @line L8
        for theta in equatings(query, candidate, views):  # @line L9
            r = minimize(_apply(theta, candidate))
            if r not in found:
                found.append(r)  # @line L10
    kept = []
    for r in found:  # @line L11
        if any(contained(r, k) for k in kept):
            continue
        kept = [k for k in kept if not contained(k, r)] + [r]
    return kept


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_bucket_algorithm.py 190 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bucket-algorithm/. The authors are listed in prov/GBX8BH.jsonl.

import itertools
import random

from bucket_algorithm import (
    answer,
    bucket_algorithm,
    build_buckets,
    contained,
    equatings,
    evaluate,
    expand,
    minimize,
    variables,
)

# The example of Pottinger and Levy (VLDB 2000), Section 3.1.
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 _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 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):
        for args in itertools.product(qvars + [None], repeat=len(views[name][0])):
            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]
            _, 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 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)
        views["V%d" % k] = (tuple(rng.sample(vused, rng.randint(1, len(vused)))), 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_buckets():
    b = build_buckets(Q1, PAPER_VIEWS)
    assert b == [
        [("V4", ("x",)), ("V6", ("x", "_1"))],
        [("V4", ("x",)), ("V6", ("_2", "x"))],
        [("V5", ("x", "y")), ("V6", ("x", "_3"))],
    ]
    # No choice works as it stands: each needs an equality or fails.
    for combo in itertools.product(*b):
        assert not contained(expand((("x",), list(combo)), PAPER_VIEWS), Q1)


def test_paper_rewriting():
    assert bucket_algorithm(Q1, PAPER_VIEWS) == [(("x",), [("V6", ("x", "x"))])]


def test_equating_makes_a_candidate_contained():
    cand = (("x",), [("V6", ("x", "_1")), ("V6", ("_2", "x")), ("V6", ("x", "_3"))])
    thetas = list(equatings(Q1, cand, PAPER_VIEWS))
    assert thetas
    for theta in thetas:
        r = (tuple(theta.get(v, v) for v in cand[0]), [(n, tuple(theta.get(a, a) for a in args)) for n, args in cand[1]])
        assert contained(expand(r, PAPER_VIEWS), Q1)
    assert minimize((("x",), [("V6", ("x", "x")), ("V6", ("x", "x")), ("V6", ("x", "_3"))])) == (("x",), [("V6", ("x", "x"))])


def test_no_rewriting_when_join_variable_is_hidden():
    q = (("x", "z"), [("e", ("x", "y")), ("e", ("y", "z"))])
    views = {"L": (("a",), [("e", ("a", "b"))]), "R": (("b",), [("e", ("a", "b"))])}
    assert build_buckets(q, views) == [[("L", ("x",))], [("R", ("z",))]]
    assert bucket_algorithm(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 = bucket_algorithm(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_head_variables_can_be_equated():
    q = (("x", "y"), [("e", ("x", "y"))])
    views = {"V": (("a",), [("e", ("a", "a"))])}
    rs = bucket_algorithm(q, views)
    assert rs == [(("x", "x"), [("V", ("x",))])]
    assert answer(rs, {"V": {("1",)}}) == {("1", "1")}


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

History

Levy, Rajaraman and Ordille described the bucket algorithm at VLDB 1996 as the query planner of the Information Manifold, a system that answered queries over many web sources described as views. Duschka and Genesereth gave the inverse rules algorithm in 1997. Pottinger and Levy presented MiniCon at VLDB 2000 and compared it with both. Halevy's 2001 survey describes all three.

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, the description of the bucket algorithm, its running example and the experimental comparison
  2. Alon Y. Halevy, Answering queries using views: a survey, The VLDB Journal 10(4), 2001, pages 270-294, the bucket algorithm among the 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 bucket 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