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
- Model
- Word RAM
- Properties
- deterministicexactnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 over global predicates, a view instance that gives a set of tuples for each view, and a query . is a Datalog program over the global predicates with a goal predicate, for example a conjunctive query 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 is possible if each view of contains the stored tuples. The output is the set of tuples of constants that returns on every possible .
The algorithm
INVERSE-RULES(Q, Views, I)- 1
R <- empty - 2
for each view V(Y) :- p_1(u_1), ..., p_r(u_r) do - 3
sigma <- the identity on Y, and u -> f_{V,u}(Y) for each existential variable u of V - 4
for j <- 1 to r do - 5
add the rule p_j(sigma(u_j)) :- V(Y) to R - 6
P <- the rules of Q together with R - 7
M <- the least fixpoint of P on the facts of I - 8
return 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 names the value of 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 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:
- ,
- ,
- .
Lines L1 to L5 give six rules:
| rule | head | body |
|---|---|---|
| R1 | cites | |
| R2 | cites | |
| R3 | sameTopic | |
| R4 | cites | |
| R5 | cites | |
| R6 | sameTopic |
The query is , and the instance is , , . Write , and .
| step | facts |
|---|---|
| R1, R2 on | cites, cites |
| R3 on | sameTopic |
| R4 to R6 on | cites, cites, sameTopic |
| R4 to R6 on | cites, cites, sameTopic |
| rule of | with |
is not derived. It would need sameTopic, but the sources only say that has the same topic as , and nothing says that is the paper that cites. would need cites. So line L8 returns . The rewriting that MiniCon finds gives the same answer.
A recursive query. Let be the transitive closure path and path, with views Hop and Direct. With Hop and Direct , the rules give , , and for a Skolem term . The fixpoint has path facts through , and line L8 keeps , , , , and . 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 on under the open world assumption.
The proof file proves it in full. The facts derived by lines L1 to L5 form a database in which the function terms play the role of labeled nulls, the same database the chase would build. is possible, since each stored tuple has its witness. 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 if and only if it is an answer on every possible database.
Duschka and Genesereth also show that the program is the maximally contained rewriting of 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 . Each view is , a conjunctive query over the global schema whose head has distinct variables and no constants. The query 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 gives a finite set of tuples of constants for each view. Set semantics holds. Under the open world assumption, a global database is possible for if for each view . The certain answers are the tuples of constants with for every possible .
For a view and an existential variable of , line L3 uses the function symbol . The term for a tuple 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 be the set of global facts , over all views , all and all atoms of , where sends to and each existential to .
Lemma 1 (the inverse rules derive ). The least model of the program of line L6 on is , where is the set of facts of the derived predicates of in the least model of on .
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 , and the head is then . No rule has a view name in its head, so the view facts stay , and the inverse rules derive exactly . The rules of have no global predicate in their heads, so the global facts are exactly , and the facts of the derived predicates are those of the least model of on .
Lemma 2 ( is possible). If each function term is read as a value of its own, is a possible database for .
Proof. For , the map sends each atom of the body of to a fact of and sends the head to . So .
Lemma 3 ( maps into each possible database). For each possible there is a map from the values of to the values of that is the identity on constants and sends each fact of to a fact of .
Proof. For each view and , we have , so there is a valuation of the variables of that sends the body into and to . Set and let fix constants. This is well defined, because different pairs give different terms. Then for each variable of , so sends the fact to , a fact of .
Lemma 4 (Datalog is preserved under homomorphisms). If fixes constants and sends each fact of to a fact of , then for each .
Proof. By induction on the stage of the least fixpoint at which a fact of on appears. A fact derived by a rule with a body match on the model of gives the match on the model of , by the induction hypothesis for the body facts, since the rules have no constants and no negation. The head of is of the head of .
Theorem (Duschka and Genesereth). INVERSE-RULES stops, and its output is the set of certain answers of on under the open world assumption.
Proof. Termination. Each function term has constants of as arguments, so is finite, and the rules of 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 be a tuple of line L8: a goal fact of the least model, with no function term. By Lemma 1, . Let be possible and as in Lemma 3. By Lemma 4, , and , since holds only constants.
Every certain answer is output. Let be certain. By Lemma 2, is possible, so , a goal fact of the least model by Lemma 1, and holds only constants, so line L8 keeps it.
Running time. Fix and the views (data complexity). Let be the number of tuples of , the largest arity of a predicate and the largest number of atoms in the body of a rule. Each tuple of adds a bounded number of function terms, so the model has values and possible facts. The naive iteration makes at most rounds. In one round, the backtracking match of a rule tries at most one fact per body atom at each level, so it visits partial matches, each in steps for a fixed program. The total is time and 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 values and possible facts. Naive evaluation makes at most rounds of work, so in total. Semi-naive evaluation does better in practice.
- Space. 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 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 for the existential , all tuples of share one unknown paper. Then and give cites and cites, and a path query wrongly finds a path from to .
- Keeping function terms in answers. Without the filter of line L8, the output holds tuples such as path 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag TPC6ZK Edit this page History Report an error Markdown