Algorithm Search⌘K

Algorithmadvanced

Inverse rules algorithm

Also called inverse rules.

Turn each local-as-view definition into Datalog rules with Skolem terms that derive global facts from source facts, then evaluate the query and drop answers with Skolem terms.

Time
O(N^(r(b+1))) worst
Space
O(N^r) extra
Where
N = the number of tuples in the view instance; b = the largest number of body atoms in a rule; r = the largest arity of a predicate
Properties
deterministicexactnot in placeofflineiterative
Origin
Oliver M. Duschka, Michael R. Genesereth, 1997

The inverse rules algorithm answers a query over a global schema when the sources are described as views over that schema, the local-as-view setting of GAV and LAV integration. It differs from the bucket algorithm and MiniCon in what it builds. Those two write a union of conjunctive queries over the views. Inverse rules write a Datalog program that runs the views backwards, so the query may itself be recursive. On a given view instance the program returns the certain answers under the open world assumption.

In plain words

A view says "the source holds the pairs (a, c) such that a cites some b and b cites c". Read backwards, each stored pair tells you two facts of the global database: a cites something, and that something cites c. You do not know the something, so you give it a name built from the stored pair, such as "the paper between a and c".

The algorithm writes one backward rule for each atom of each view. It then runs the query on the facts that these rules produce, with the made up names in place of the unknown values. An answer that holds a made up name is not a real answer, so it is dropped. The rest are exactly the answers that hold in every database the sources allow.

The problem

The input is a set of views V(Yˉ) :- p1(uˉ1),…,pr(uˉr)V(\bar Y) \text{ :- } p_1(\bar u_1), \ldots, p_r(\bar u_r) over global predicates, a view instance II that gives a set of tuples for each view, and a query QQ. QQ is a Datalog program over the global predicates with a goal predicate, for example a conjunctive query Q(xˉ) :- R1(uˉ1),…,Rm(uˉm)Q(\bar x) \text{ :- } R_1(\bar u_1), \ldots, R_m(\bar u_m) in AHV notation. The views and the query have no constants and no comparisons. Set semantics holds. Under the open world assumption, a global database DD is possible if each view of DD contains the stored tuples. The output is the set of tuples of constants that QQ returns on every possible DD.

The algorithm

  1. INVERSE-RULES(Q, Views, I)
  2. 1R <- empty
  3. 2for each view V(Y) :- p_1(u_1), ..., p_r(u_r) do
  4. 3sigma <- the identity on Y, and u -> f_{V,u}(Y) for each existential variable u of V
  5. 4for j <- 1 to r do
  6. 5add the rule p_j(sigma(u_j)) :- V(Y) to R
  7. 6P <- the rules of Q together with R
  8. 7M <- the least fixpoint of P on the facts of I
  9. 8return the goal tuples of M that hold no function term

Line L3 is a Skolemization of the view definition. The view says that for each stored tuple there exist values of its existential variables. The term fV,u(Yˉ)f_{V,u}(\bar Y) names the value of uu for one stored tuple, and different tuples give different names. Lines L4 and L5 split the body, so each rule derives one global atom from one view atom. These rules are not recursive, and their heads hold function terms of depth one only.

Line L7 is ordinary Datalog evaluation, by naive or semi-naive iteration. The rules of QQ never build new function terms, so the fixpoint is finite. Line L8 removes answers that depend on a value that no source stores.

Example

The views are the running example of Pottinger and Halevy:

  • 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 six rules:

rule head body
R1 cites(a,fV4,b(a))(a, f_{V_4,b}(a)) V4(a)V_4(a)
R2 cites(fV4,b(a),a)(f_{V_4,b}(a), a) V4(a)V_4(a)
R3 sameTopic(c,d)(c, d) V5(c,d)V_5(c, d)
R4 cites(f,fV6,g(f,h))(f, f_{V_6,g}(f, h)) V6(f,h)V_6(f, h)
R5 cites(fV6,g(f,h),h)(f_{V_6,g}(f, h), h) V6(f,h)V_6(f, h)
R6 sameTopic(f,fV6,g(f,h))(f, f_{V_6,g}(f, h)) V6(f,h)V_6(f, h)

The query is 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), and the instance is V4={(p1)}V_4 = \{(p_1)\}, V5={(p1,p2)}V_5 = \{(p_1, p_2)\}, V6={(p3,p3),(p4,p5)}V_6 = \{(p_3, p_3), (p_4, p_5)\}. Write s1=fV4,b(p1)s_1 = f_{V_4,b}(p_1), s3=fV6,g(p3,p3)s_3 = f_{V_6,g}(p_3, p_3) and s4=fV6,g(p4,p5)s_4 = f_{V_6,g}(p_4, p_5).

step facts
R1, R2 on V4(p1)V_4(p_1) cites(p1,s1)(p_1, s_1), cites(s1,p1)(s_1, p_1)
R3 on V5(p1,p2)V_5(p_1, p_2) sameTopic(p1,p2)(p_1, p_2)
R4 to R6 on V6(p3,p3)V_6(p_3, p_3) cites(p3,s3)(p_3, s_3), cites(s3,p3)(s_3, p_3), sameTopic(p3,s3)(p_3, s_3)
R4 to R6 on V6(p4,p5)V_6(p_4, p_5) cites(p4,s4)(p_4, s_4), cites(s4,p5)(s_4, p_5), sameTopic(p4,s4)(p_4, s_4)
rule of QQ Q(p3)Q(p_3) with y=s3y = s_3

Q(p1)Q(p_1) is not derived. It would need sameTopic(p1,s1)(p_1, s_1), but the sources only say that p1p_1 has the same topic as p2p_2, and nothing says that p2p_2 is the paper that p1p_1 cites. Q(p4)Q(p_4) would need cites(s4,p4)(s_4, p_4). So line L8 returns {(p3)}\{(p_3)\}. The rewriting Q′(x) :- V6(x,x)Q'(x) \text{ :- } V_6(x, x) that MiniCon finds gives the same answer.

A recursive query. Let QQ be the transitive closure path(x,y) :- e(x,y)(x, y) \text{ :- } e(x, y) and path(x,y) :- e(x,z),path(z,y)(x, y) \text{ :- } e(x, z), \text{path}(z, y), with views Hop(a,c) :- e(a,b),e(b,c)(a, c) \text{ :- } e(a, b), e(b, c) and Direct(a,b) :- e(a,b)(a, b) \text{ :- } e(a, b). With Hop ={(1,3)}= \{(1, 3)\} and Direct ={(3,4),(5,1)}= \{(3, 4), (5, 1)\}, the rules give e(1,s)e(1, s), e(s,3)e(s, 3), e(3,4)e(3, 4) and e(5,1)e(5, 1) for a Skolem term ss. The fixpoint has path facts through ss, and line L8 keeps (1,3)(1, 3), (1,4)(1, 4), (3,4)(3, 4), (5,1)(5, 1), (5,3)(5, 3) and (5,4)(5, 4). No finite union of conjunctive queries over the views gives these answers on all instances, since the paths can be of any length.

Correctness

Theorem (Duschka and Genesereth). For a Datalog query and conjunctive views, INVERSE-RULES stops and returns exactly the certain answers of QQ on II under the open world assumption.

The proof file proves it in full. The facts derived by lines L1 to L5 form a database D0D_0 in which the function terms play the role of labeled nulls, the same database the chase would build. D0D_0 is possible, since each stored tuple has its witness. D0D_0 maps into each possible database by a map that fixes the constants, since the witnesses of that database give the values of the function terms. Datalog answers are preserved by such maps. So a tuple of constants is an answer on D0D_0 if and only if it is an answer on every possible database.

Duschka and Genesereth also show that the program PP is the maximally contained rewriting of QQ among Datalog programs over the views, once the function terms are removed. For a conjunctive query, it is equivalent to the union that MiniCon returns.

Proof: The inverse rules program computes the certain answers of a Datalog query over conjunctive viewsfull

Setting. The global schema has predicates p1,p2,…p_1, p_2, \ldots. Each view is V(Yˉ) :- p1(uˉ1),…,pr(uˉr)V(\bar Y) \text{ :- } p_1(\bar u_1), \ldots, p_r(\bar u_r), a conjunctive query over the global schema whose head has distinct variables and no constants. The query QQ is a Datalog program with safe rules, no constants and a goal predicate. Its derived predicates are not global predicates or view names. A view instance II gives a finite set I(V)I(V) of tuples of constants for each view. Set semantics holds. Under the open world assumption, a global database DD is possible for II if I(V)⊆V(D)I(V) \subseteq V(D) for each view VV. The certain answers are the tuples of constants tˉ\bar t with tˉ∈Q(D)\bar t \in Q(D) for every possible DD.

For a view VV and an existential variable uu of VV, line L3 uses the function symbol fV,uf_{V,u}. The term fV,u(tˉ)f_{V,u}(\bar t) for a tuple tˉ∈I(V)\bar t \in I(V) is treated as a new value. Two such terms are equal only if they have the same symbol and the same arguments, and no term equals a constant.

Let D0D_0 be the set of global facts pj(σtˉ(uˉj))p_j(\sigma_{\bar t}(\bar u_j)), over all views VV, all tˉ∈I(V)\bar t \in I(V) and all atoms pj(uˉj)p_j(\bar u_j) of VV, where σtˉ\sigma_{\bar t} sends YpY_p to tpt_p and each existential uu to fV,u(tˉ)f_{V,u}(\bar t).

Lemma 1 (the inverse rules derive D0D_0). The least model of the program of line L6 on II is I∪D0∪MI \cup D_0 \cup M, where MM is the set of facts of the derived predicates of QQ in the least model of QQ on D0D_0.

Proof. The rules of lines L1 to L5 have one view atom in the body and a global atom in the head. A body match is a tuple tˉ∈I(V)\bar t \in I(V), and the head is then pj(σtˉ(uˉj))p_j(\sigma_{\bar t}(\bar u_j)). No rule has a view name in its head, so the view facts stay II, and the inverse rules derive exactly D0D_0. The rules of QQ have no global predicate in their heads, so the global facts are exactly D0D_0, and the facts of the derived predicates are those of the least model of QQ on D0D_0. □\square

Lemma 2 (D0D_0 is possible). If each function term is read as a value of its own, D0D_0 is a possible database for II.

Proof. For tˉ∈I(V)\bar t \in I(V), the map σtˉ\sigma_{\bar t} sends each atom of the body of VV to a fact of D0D_0 and sends the head Yˉ\bar Y to tˉ\bar t. So tˉ∈V(D0)\bar t \in V(D_0). □\square

Lemma 3 (D0D_0 maps into each possible database). For each possible DD there is a map hh from the values of D0D_0 to the values of DD that is the identity on constants and sends each fact of D0D_0 to a fact of DD.

Proof. For each view VV and tˉ∈I(V)\bar t \in I(V), we have tˉ∈V(D)\bar t \in V(D), so there is a valuation μtˉ\mu_{\bar t} of the variables of VV that sends the body into DD and Yˉ\bar Y to tˉ\bar t. Set h(fV,u(tˉ))=μtˉ(u)h(f_{V,u}(\bar t)) = \mu_{\bar t}(u) and let hh fix constants. This is well defined, because different pairs (V,u,tˉ)(V, u, \bar t) give different terms. Then h(σtˉ(w))=μtˉ(w)h(\sigma_{\bar t}(w)) = \mu_{\bar t}(w) for each variable ww of VV, so hh sends the fact pj(σtˉ(uˉj))p_j(\sigma_{\bar t}(\bar u_j)) to pj(μtˉ(uˉj))p_j(\mu_{\bar t}(\bar u_j)), a fact of DD. □\square

Lemma 4 (Datalog is preserved under homomorphisms). If hh fixes constants and sends each fact of AA to a fact of BB, then h(sˉ)∈Q(B)h(\bar s) \in Q(B) for each sˉ∈Q(A)\bar s \in Q(A).

Proof. By induction on the stage of the least fixpoint at which a fact of QQ on AA appears. A fact derived by a rule with a body match ν\nu on the model of AA gives the match h∘νh \circ \nu on the model of BB, by the induction hypothesis for the body facts, since the rules have no constants and no negation. The head of h∘νh \circ \nu is hh of the head of ν\nu. □\square

Theorem (Duschka and Genesereth). INVERSE-RULES stops, and its output is the set of certain answers of QQ on II under the open world assumption.

Proof. Termination. Each function term has constants of II as arguments, so D0D_0 is finite, and the rules of QQ create no new values. So the fixpoint of line L7 has a finite set of possible facts, and each round of the naive iteration that does not stop adds one.

Output is certain. Let tˉ\bar t be a tuple of line L8: a goal fact of the least model, with no function term. By Lemma 1, tˉ∈Q(D0)\bar t \in Q(D_0). Let DD be possible and hh as in Lemma 3. By Lemma 4, h(tˉ)∈Q(D)h(\bar t) \in Q(D), and h(tˉ)=tˉh(\bar t) = \bar t, since tˉ\bar t holds only constants.

Every certain answer is output. Let tˉ\bar t be certain. By Lemma 2, D0D_0 is possible, so tˉ∈Q(D0)\bar t \in Q(D_0), a goal fact of the least model by Lemma 1, and tˉ\bar t holds only constants, so line L8 keeps it. ■\blacksquare

Running time. Fix QQ and the views (data complexity). Let NN be the number of tuples of II, rr the largest arity of a predicate and bb the largest number of atoms in the body of a rule. Each tuple of II adds a bounded number of function terms, so the model has O(N)O(N) values and O(Nr)O(N^r) possible facts. The naive iteration makes at most O(Nr)O(N^r) rounds. In one round, the backtracking match of a rule tries at most one fact per body atom at each level, so it visits O(Nrb)O(N^{r b}) partial matches, each in O(1)O(1) steps for a fixed program. The total is O(Nr(b+1))O(N^{r (b + 1)}) time and O(Nr)O(N^r) space, polynomial in data complexity.

Complexity

The bounds are theorems, proved in the proof file. They are in data complexity: the query and the views are fixed and the view instance grows.

  • Time. The model has O(N)O(N) values and O(Nr)O(N^r) possible facts. Naive evaluation makes at most O(Nr)O(N^r) rounds of O(Nrb)O(N^{r b}) work, so O(Nr(b+1))O(N^{r(b+1)}) in total. Semi-naive evaluation does better in practice.
  • Space. O(Nr)O(N^r) for the model.

Building the rules takes time linear in the size of the view definitions. In combined complexity, evaluating the Datalog program is EXPTIME-complete in general, as for any Datalog program.

Properties

  • Exact. It returns the certain answers, not an approximation.
  • Deterministic. The rules and the fixpoint do not depend on any choice.
  • Recursive queries. It works unchanged when QQ is recursive, where the bucket algorithm and MiniCon do not apply.
  • No rewriting search. The rules come from the views alone, so they can be built once and reused for every query.
  • Repeated work. The derived global database can be much larger than needed, because every view atom is unfolded for every stored tuple, even if the query never uses it.

Variants and improvements

  • Removing function symbols. Duschka, Genesereth and Levy turn the program into a Datalog program without function terms, by tracking which arguments hold which function symbol. The result is a rewriting over the views that a plain Datalog engine can run.
  • Functional dependencies and access patterns. The same journal paper handles functional dependencies on the global schema and sources with binding patterns, where the maximally contained rewriting can need recursion even for a conjunctive query.
  • The chase. In data exchange, the same idea appears as the chase of source-to-target dependencies, with labeled nulls in place of function terms.

When to use it

Use inverse rules when the query is recursive, or when you have a Datalog engine and want the answers on a given view instance. For conjunctive queries where the rewriting itself is needed, for example to optimize the plan or to send subqueries to the sources, MiniCon is faster. In the experiments of Pottinger and Levy (a measurement), MiniCon was faster than the inverse rules when both had to produce a rewriting.

Pitfalls

  • One null per variable, not per tuple. If line L3 uses a constant name such as bV4b_{V_4} for the existential bb, all tuples of V4V_4 share one unknown paper. Then V4(p1)V_4(p_1) and V4(p6)V_4(p_6) give cites(p1,b)(p_1, b) and cites(b,p6)(b, p_6), and a path query wrongly finds a path from p1p_1 to p6p_6.
  • Keeping function terms in answers. Without the filter of line L8, the output holds tuples such as path(1,s)(1, s) that name no real value.
  • Closed world. The algorithm gives certain answers under the open world assumption. Under the closed world assumption, where each view holds exactly its stored tuples, certain answers to conjunctive queries are coNP-hard in data complexity, as Abiteboul and Duschka showed.
  • Comparisons. With comparison predicates in the views, a Skolem term has no known order, and the rules of line L5 are no longer enough.

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.

inverse_rules_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/inverse-rules-algorithm/. The authors are listed in prov/TPC6ZK.jsonl.

"""The inverse rules algorithm of Duschka and Genesereth.

An atom is a pair (predicate, tuple of terms). In a rule, every term is a
variable (a string) or, in the head of an inverse rule only, a Skolem term
("f", view, variable, tuple of head variables). A rule is a pair (head atom,
list of body atoms). A Datalog query is a pair (rules, goal predicate); its
rules use the global predicates and their own predicates. A view is a pair
(head, body) of a conjunctive query whose head has distinct variables, and
views is a dict from view name to view. A view instance is a dict from view
name to a set of tuples of constants. A value in a derived fact is a constant
(a string) or a ground Skolem term ("f", view, variable, tuple of values).
Set semantics holds throughout.
"""


def is_function_term(v):
    return isinstance(v, tuple)


def inverse_rules(views):
    """For each view and each atom of its body, one rule that derives the atom."""
    rules = []  # @line L1
    for name in sorted(views):  # @line L2
        vhead, vbody = views[name]
        sigma = {y: y for y in vhead}  # @line L3
        for _, args in vbody:
            for u in args:
                if u not in sigma:
                    sigma[u] = ("f", name, u, tuple(vhead))
        for pred, args in vbody:  # @line L4
            rules.append(((pred, tuple(sigma[u] for u in args)), [(name, tuple(vhead))]))  # @line L5
    return rules


def _matches(atoms, facts, binding):
    """Yield each extension of binding that maps every atom to a fact."""
    if not atoms:
        yield binding
        return
    pred, args = atoms[0]
    for tup in facts.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:], facts, new)


def _ground(term, binding):
    if is_function_term(term):
        f, view, var, args = term
        return (f, view, var, tuple(binding[a] for a in args))
    return binding[term]


def fixpoint(rules, facts):
    """The least model of the rules over the facts, by naive iteration."""
    model = {p: set(ts) for p, ts in facts.items()}
    changed = True
    while changed:
        changed = False
        for (hpred, hargs), body in rules:
            new = set()
            for m in _matches(list(body), model, {}):
                new.add(tuple(_ground(t, m) for t in hargs))
            target = model.setdefault(hpred, set())
            if not new <= target:
                target |= new
                changed = True
    return model


def inverse_rules_answers(query, views, view_instance):
    """The certain answers of a Datalog query over the views, under the open world assumption."""
    rules, goal = query
    program = list(rules) + inverse_rules(views)  # @line L6
    model = fixpoint(program, view_instance)  # @line L7
    return {t for t in model.get(goal, set()) if not any(is_function_term(v) for v in t)}  # @line L8


def cq_as_program(query):
    """A conjunctive query (head, body) as a one-rule Datalog query with goal 'q'."""
    head, body = query
    return ([(("q", tuple(head)), list(body))], "q")
test_inverse_rules_algorithm.py 230 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/inverse-rules-algorithm/. The authors are listed in prov/TPC6ZK.jsonl.

import itertools
import random

from inverse_rules_algorithm import cq_as_program, fixpoint, inverse_rules, inverse_rules_answers

# 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"))]),
}

# Transitive closure over e, a recursive query.
TC = (
    [
        (("path", ("x", "y")), [("e", ("x", "y"))]),
        (("path", ("x", "y")), [("e", ("x", "z")), ("path", ("z", "y"))]),
    ],
    "path",
)


def variables(atoms):
    seen = {}
    for _, args in atoms:
        for a in args:
            seen.setdefault(a, None)
    return list(seen)


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, ()):
        if len(tup) != len(args):
            continue
        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 naive_datalog(rules, db):
    """Oracle evaluation: apply every rule until nothing changes (no function terms)."""
    model = {p: set(ts) for p, ts in db.items()}
    while True:
        before = sum(len(v) for v in model.values())
        for (hp, ha), body in rules:
            for m in list(all_maps(body, model)):
                model.setdefault(hp, set()).add(tuple(m[a] for a in ha))
        if sum(len(v) for v in model.values()) == before:
            return model


def canonical_db(views, view_instance):
    """Oracle: chase the view facts with labeled nulls, one fresh null per existential and view fact."""
    db = {}
    k = 0
    for name in sorted(view_instance):
        vhead, vbody = views[name]
        for t in sorted(view_instance[name]):
            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 db


def certain_by_chase(query, views, view_instance):
    rules, goal = query
    model = naive_datalog(rules, canonical_db(views, view_instance))
    return {t for t in model.get(goal, set()) if not any(isinstance(v, tuple) for v in t)}


def expand(body, views):
    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 out


def brute_rewriting_answers(query, views, view_instance):
    """Oracle for a conjunctive query: evaluate every contained rewriting with at
    most n view atoms (n the number of subgoals) on the view instance."""
    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))
    out = set()
    for size in range(1, len(qbody) + 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]
            index = {}
            for pred, args in expand(body, views):
                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 heads:
                for m in all_maps(body, view_instance):
                    out.add(tuple(m[v] for v in t))
    return out


def view_image(views, db):
    out = {}
    for name, (vhead, vbody) in views.items():
        out[name] = {tuple(m[y] for y in vhead) for m in all_maps(vbody, db)}
    return out


def random_views(rng):
    views = {}
    for k in range(rng.randint(1, 3)):
        vv = ["a", "b", "c"]
        vbody = []
        for _ in range(rng.randint(1, 2)):
            if rng.random() < 0.8:
                atom = ("e", (rng.choice(vv), rng.choice(vv)))
            else:
                atom = ("p", (rng.choice(vv),))
            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 views


def random_cq(rng):
    qv = ["x", "y", "z"]
    body = []
    for _ in range(rng.randint(1, 2)):
        if rng.random() < 0.75:
            atom = ("e", (rng.choice(qv), rng.choice(qv)))
        else:
            atom = ("p", (rng.choice(qv),))
        if atom not in body:
            body.append(atom)
    used = variables(body)
    return (tuple(rng.sample(used, rng.randint(0, min(2, len(used))))), body)


def random_db(rng):
    dom = ["1", "2", "3", "4"]
    db = {"e": set(), "p": set()}
    for _ in range(rng.randint(0, 6)):
        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_rules():
    rules = inverse_rules(PAPER_VIEWS)
    f1 = ("f", "V4", "b", ("a",))
    f2 = ("f", "V6", "g", ("f", "h"))
    assert rules == [
        (("cites", ("a", f1)), [("V4", ("a",))]),
        (("cites", (f1, "a")), [("V4", ("a",))]),
        (("sameTopic", ("c", "d")), [("V5", ("c", "d"))]),
        (("cites", ("f", f2)), [("V6", ("f", "h"))]),
        (("cites", (f2, "h")), [("V6", ("f", "h"))]),
        (("sameTopic", ("f", f2)), [("V6", ("f", "h"))]),
    ]


def test_paper_answers():
    inst = {"V4": {("p1",)}, "V5": {("p1", "p2")}, "V6": {("p3", "p3"), ("p4", "p5")}}
    # Only V6(p3, p3) gives a paper that cites and is cited by a paper on its topic.
    assert inverse_rules_answers(cq_as_program(Q1), PAPER_VIEWS, inst) == {("p3",)}
    model = fixpoint(list(cq_as_program(Q1)[0]) + inverse_rules(PAPER_VIEWS), inst)
    sk = ("f", "V4", "b", ("p1",))
    assert ("p1", sk) in model["cites"] and (sk, "p1") in model["cites"]


def test_recursive_query():
    # Hop(a, c) hides the middle stop of a two-leg trip. Direct(a, b) shows one leg.
    views = {
        "Hop": (("a", "c"), [("e", ("a", "b")), ("e", ("b", "c"))]),
        "Direct": (("a", "b"), [("e", ("a", "b"))]),
    }
    inst = {"Hop": {("1", "3")}, "Direct": {("3", "4"), ("5", "1")}}
    got = inverse_rules_answers(TC, views, inst)
    assert got == {("1", "3"), ("1", "4"), ("3", "4"), ("5", "1"), ("5", "3"), ("5", "4")}
    assert got == certain_by_chase(TC, views, inst)


def test_conjunctive_queries_against_rewritings():
    rng = random.Random(5)
    for _ in range(80):
        views, query = random_views(rng), random_cq(rng)
        for _ in range(3):
            inst = view_image(views, random_db(rng))
            got = inverse_rules_answers(cq_as_program(query), views, inst)
            assert got == brute_rewriting_answers(query, views, inst)


def test_recursive_queries_against_chase_and_sound():
    rng = random.Random(9)
    for _ in range(80):
        views = random_views(rng)
        db = random_db(rng)
        inst = view_image(views, db)
        got = inverse_rules_answers(TC, views, inst)
        assert got == certain_by_chase(TC, views, inst)
        # Sound: each answer holds in the database the views came from.
        assert got <= naive_datalog(TC[0], db).get("path", set())


def test_empty_and_boolean():
    views = {"V": (("a",), [("e", ("a", "b"))])}
    assert inverse_rules_answers(cq_as_program(((), [("e", ("x", "y"))])), views, {"V": set()}) == set()
    assert inverse_rules_answers(cq_as_program(((), [("e", ("x", "y"))])), views, {"V": {("1",)}}) == {()}
    # The hidden value never shows up in an answer.
    assert inverse_rules_answers(cq_as_program((("y",), [("e", ("x", "y"))])), views, {"V": {("1",)}}) == set()

History

Duschka and Genesereth introduced the inverse rules at PODS 1997, in a paper on recursive queries over views. The journal version, with Levy, appeared in the Journal of Logic Programming in 2000 and added the removal of function symbols, functional dependencies and binding patterns. Abiteboul and Duschka placed the method among the results on the complexity of certain answers in 1998. Pottinger and Levy compared it with the bucket algorithm and MiniCon in 2000.

References

  1. Oliver M. Duschka and Michael R. Genesereth, Answering recursive queries using views, PODS 1997, pages 109-116, the inverse rules and the proof that they give the maximally contained Datalog rewriting
  2. Oliver M. Duschka, Michael R. Genesereth and Alon Y. Levy, Recursive query plans for data integration, Journal of Logic Programming 43(1), 2000, pages 49-73, inverse rules, the removal of function symbols, and functional dependencies
  3. Alon Y. Halevy, Answering queries using views: a survey, The VLDB Journal 10(4), 2001, pages 270-294, the inverse rules algorithm among the algorithms for data integration
  4. Serge Abiteboul and Oliver M. Duschka, Complexity of answering queries using materialized views, PODS 1998, pages 254-263, certain answers under the open world assumption

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