Algorithmresearch
Core computation for data exchange
Also called core of a universal solution.
Compute the core, the smallest universal solution: chase, then retract blocks of nulls. Polynomial in data complexity for s-t tgds, and for weakly acyclic target tgds with egds.
- Solves
- Data exchange problem
- Time
- O(m^(w+2)) worst
- Space
- O(m) extra
- Where
- m = the number of facts of the canonical universal solution; w = the largest number of existential variables in one tgd
- Model
- Word RAM
- Properties
- deterministicexactnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ronald Fagin, Phokion G. Kolaitis, Lucian Popa, 2005
This algorithm computes the core of the universal solutions of a data exchange problem: the smallest target instance that is still a universal solution. The page on universal solutions defines the notion and shows that many universal solutions exist. This page gives the method that picks the best one. For source-to-target tgds, it runs the chase and then folds away the redundant facts one small block of nulls at a time.
In plain words
The chase fills the target with facts that have unknown values, called labeled nulls. It is careful but wasteful. If one rule says "each flight leaves its origin to some place" and another rule says the same in more detail, the chase writes both facts, and the short one adds nothing.
A fact is redundant when you can rename some unknown values into values that are already there and still stay inside the instance. The core is what is left when no renaming removes anything. The method takes each group of unknowns that occur together, tries all renamings of that group, and removes the facts that a renaming makes redundant. Each group is small, because each rule makes only a few unknowns. So the work stays polynomial in the size of the data.
The problem
The input is a source instance and a finite set of source-to-target tgds . Set semantics holds throughout. Values are constants or labeled nulls (written N1, N2 in the code).
- A homomorphism maps values to values, is the identity on constants and maps each fact of to a fact of .
- An instance is a core if no homomorphism maps to a proper subset of . A core of is a subset that is a core with a homomorphism .
- A block of is a connected part of the graph on the nulls of in which two nulls are joined when they occur in one fact.
The output is a core of the universal solutions. It is unique up to a renaming of nulls (see Correctness), so "the core" is well defined.
The algorithm
CORE-SOLUTION(I, Sigma)- 1
J <- CHASE(I, Sigma) ▷ the canonical universal solution - 2
for each block B of J, in a fixed order do - 3
F <- the facts of J that hold a null of B - 4
while some map h on the nulls of F has h(F) ⊆ J and h(F) ≠ F do - 5
J <- J minus (F minus h(F)) - 6
F <- F ∩ J - 7
return J CHASE(I, Sigma)- 8
J <- the empty instance - 9
for each tgd and each assignment of its body variables that maps the body into I do - 10
add the head to J, with fresh nulls for the existential variables - 11
return J
CHASE is the oblivious chase for source-to-target tgds: each trigger fires one time, even when its head already holds. The result is the canonical universal solution. In line L4, is the identity on constants and on all nulls outside . The search for is a backtracking match of the facts of into , with the nulls of as the variables, the same as evaluating a conjunctive query with atoms. Line L5 replaces by its image , which is already in . This is the image of under the map that is on and the identity elsewhere.
Example
The mapping has two tgds, and . The source is . The chase fires four triggers and gives
Each null is its own block.
| block | a map with , | facts removed | |
|---|---|---|---|
| Leg, Leg | none: only has both a Leg from and a Leg to | none | |
| Leg, Leg | none, for the same reason | none | |
| Leg | Leg | ||
| Leg | Leg |
The core is . The trigger of adds nothing that does not already give. A query gives the same null-free answers on and on the core, because the two instances have homomorphisms each way.
Correctness
The proof file proves the theorem below in full.
Theorem. For source-to-target tgds, CORE-SOLUTION stops and returns a subset of the canonical universal solution such that is a core, maps homomorphically to , and is a universal solution.
The proof has four parts.
- The chase result is a universal solution. Each trigger has a witness, and the fresh nulls of each trigger can be mapped to the witness values of that trigger in any other solution.
- Each fact of holds nulls of one trigger only, so a block has at most nulls.
- An instance is a core if and only if no group of nulls has a map as in line L4. If such an exists, it removes a fact. If the instance is not a core, a homomorphism onto a proper subset must move the facts of some group, and its restriction to that group is such an .
- Work on one block removes only facts of that block, and the instance only shrinks. So a block that has no map left at the end of its loop has none at the end of the run.
All universal solutions have the same core, up to a renaming of nulls, and no universal solution is smaller. Fagin, Kolaitis and Popa proved this. The proof file gives the short argument: two cores with homomorphisms each way are isomorphic.
Proof: The block method returns the core of the universal solutions for source-to-target tgdsfull
Setting. The mapping is a finite set of source-to-target tgds , with no target dependencies. An instance is a finite set of facts. A value is a constant or a labeled null. A homomorphism maps values to values, is the identity on constants, and maps each fact of to a fact of . An instance is a core if there is no homomorphism from to a proper subset of . A core of is a subset that is a core and has a homomorphism . A target instance is a solution for a source instance if satisfies , and it is universal if it has a homomorphism into each solution.
Let be the largest number of existential variables in one tgd and let be the largest number of atoms in one head.
Lemma 1 (the chase). Lines L8 to L11 return a universal solution .
Proof. A trigger is a tgd with an assignment of its body variables that maps the body into . For each trigger, line L10 adds the head with fresh nulls for the existential variables. So each trigger has a witness in , and is a solution. Let be any solution. For each trigger, has values for the existential variables such that holds in . Map the fresh nulls of that trigger to . The nulls of different triggers are different, so this defines one map , and is the identity on constants. Each fact of comes from one trigger and maps it to a fact of . So .
Lemma 2 (small blocks). Each fact of holds nulls of one trigger only. So each block of has at most nulls, and at most facts of hold a null of a given block.
Proof. A fact added at line L10 holds constants of and nulls made for its own trigger. Two nulls are in one block only if a chain of facts joins them, and each fact of the chain stays within one trigger. The facts that hold a null of the block all come from the head of that trigger.
Lemma 3 (groups). Let be an instance, and split its nulls into groups such that each fact holds nulls of at most one group. Let be the set of facts that hold a null of . Call a map from to the values of a witness for if and , where is the identity on all other values. Then is a core if and only if no group has a witness.
Proof. Assume is a witness for . Let be on and the identity elsewhere. A fact outside holds no null of , so fixes it, and . Since and , some fact is not in . It is also not in , so . So maps to a proper subset of , and is not a core.
Now assume is not a core: some homomorphism maps into a proper subset of . Each fact of is ground or is in exactly one , and fixes the ground facts. If for each , then , which is false. So for some . The facts of hold only constants and nulls of , so the restriction of to maps to , and it is a witness for .
Lemma 4 (one step). Let be the instance before an execution of line L5, with a witness for the current group with facts . Then for the map of Lemma 3, and is a proper subset of .
Proof. By the first part of the proof of Lemma 3, . Since , this is . The set is not empty, as shown there.
Invariant. Let be the blocks of in the order of line L2. At each time, let the group be the set of nulls of that still occur, and let be the facts that hold one of them. Every fact of the current instance is a fact of , so it holds nulls of at most one group, and Lemma 3 applies to the groups. Line L3 sets the variable to when block starts, and lines L5 and L6 keep , because line L5 removes only facts of . For the same reason, the work on block does not change for .
Theorem. The procedure stops and returns an instance such that , there is a homomorphism , is a core, and is a universal solution.
Proof. Termination. Each pass through line L5 removes at least one fact by Lemma 4, so there are at most passes in total. Each witness search of line L4 is over a finite set of maps.
Subset and homomorphism. By Lemma 4, the instance only shrinks, and each step is the image of the instance before it under a homomorphism. The composition of these maps is a homomorphism with .
Core. Fix . When the loop of block ends, there is no witness for in the instance of that time. After that, does not change, by the invariant, and the instance only shrinks, so . A witness for in maps into , so it would be a witness in . So no group has a witness in , and is a core by Lemma 3.
Universal solution. Let a trigger with assignment hold in . By Lemma 1, has the facts for the fresh nulls . Then has the facts , because fixes the constants . So is a solution. For a solution , Lemma 1 gives , and , so the inclusion followed by that map is a homomorphism .
Corollary (one core for all universal solutions). Let and be cores, with homomorphisms and . Then and are isomorphic. So all universal solutions have isomorphic cores, the core above is the core of each of them, and no universal solution has fewer facts than .
Proof. The map sends into . Since is a core, its image is all of . So is onto the facts of , hence onto its values, and as these are finite it is a bijection on them. So is one to one on values, and . In the same way , so . The inverse of on values maps each fact back to , so it is a homomorphism, and is an isomorphism.
Two universal solutions and have homomorphisms each way, so their cores, which are subsets with homomorphisms from them, have homomorphisms each way and are isomorphic. If is a universal solution and is a core of , then and is isomorphic to , so .
Running time. Fix , so , and the arities are constants. Let , so the number of values of is . Line L4 runs at most times with success and at most once per block without, so at most times. One search backtracks over the at most facts of . Each node of the search tree is a partial map of the nulls of , and different nodes at one depth give different partial maps, so there are at most nodes. Each node scans the facts of one relation, work, and building the index takes . So one search takes time, and the whole run takes time. For a fixed , is polynomial in , so this is polynomial time in data complexity.
Complexity
Fix . Let be the number of facts of and the largest number of existential variables in one tgd. Line L4 succeeds at most times, since each success removes a fact, and fails at most once per block, so it runs at most times. One search tries the partial maps of at most nulls to the values of , and each step scans one relation.
- Time. for one search, and in total. For a fixed , is polynomial in , so the run takes polynomial time in data complexity.
- Space. for the instance and its index, plus the recursion of one search, which is bounded by the number of facts in a block.
In combined complexity, where is part of the input, the exponent grows with the mapping. Core problems are hard in general: Fagin, Kolaitis and Popa showed that deciding whether a graph is the core of a graph is DP-complete.
Properties
- Exact. It returns the core, not an approximation.
- Deterministic. The order of the blocks fixes which isomorphic copy of the core is returned.
- Polynomial in data complexity. The degree of the polynomial depends on the mapping through .
- Monotone shrinking. Each step removes facts and never adds one, so each prefix of the run is a universal solution between and the core.
- No new values. The core uses only values that occur in .
Variants and improvements
- Target egds. With egds on the target, the chase can merge nulls, so the blocks are no longer bounded by one trigger. Fagin, Kolaitis and Popa gave polynomial algorithms under broad conditions of this kind.
- Weakly acyclic target tgds. Gottlob and Nash gave a polynomial algorithm in data complexity when the source-to-target dependencies are arbitrary tgds and the target dependencies are a weakly acyclic set of tgds with egds. They also proved a fixed-parameter intractability result, and they showed that with a predicate that tells nulls from constants the problem becomes NP-complete.
- Query minimization. The same retraction idea applied to the canonical database of a conjunctive query gives conjunctive query minimization, by the Chandra-Merlin theorem.
When to use it
Use the core when you must store the target instance, since it is the smallest universal solution and has no redundant facts. It gives the same certain answers to unions of conjunctive queries as any other universal solution. When the target is only used to answer such queries and size does not matter, the canonical universal solution is enough and saves the extra pass.
Pitfalls
- Nulls must not map to fresh values. The map of line L4 is the identity on constants and maps into values that already occur in . A map that may invent values does not give a subset.
- Blocks grow with target dependencies. The bound of nulls per block holds for source-to-target tgds. With target tgds or egds, a block can hold nulls from many triggers, and the simple search can become exponential in the data.
- Termination of the chase. With target tgds, the chase may not stop. Weak acyclicity is a sufficient condition for it to stop, not a necessary one.
- Queries with negation. The core and can give different naive answers to a query with negation. In the example, "some has Leg and no Leg" is true on , with , but false on the core. Neither answer is the certain answer in general.
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/data-exchange-core-computation/. The authors are listed in prov/6E0XMM.jsonl.
"""The core of the canonical universal solution, for source-to-target tgds.
A fact is a pair (relation, tuple of values). A value is a constant (a string)
or a labeled null (a Null). A tgd is a pair (body, head) of lists of atoms
(relation, tuple of variable names). The variables of the head that are not in
the body are existential. Set semantics: an instance is a set of facts.
"""
class Null:
"""A labeled null. Two nulls are equal when their numbers are equal."""
__slots__ = ("id",)
def __init__(self, i):
self.id = i
def __eq__(self, other):
return isinstance(other, Null) and other.id == self.id
def __hash__(self):
return hash(("null", self.id))
def __repr__(self):
return "N%d" % self.id
def is_null(v):
return isinstance(v, Null)
def value_key(v):
"""A total order on values: constants first, then nulls by number."""
return (1, v.id, "") if is_null(v) else (0, 0, str(v))
def fact_key(f):
return (f[0], tuple(value_key(v) for v in f[1]))
def _index(inst):
by_rel = {}
for rel, tup in sorted(inst, key=fact_key):
by_rel.setdefault(rel, []).append(tup)
return by_rel
def _matches(atoms, by_rel, binding, is_var):
"""Yield each extension of binding that maps every atom to a fact of the index.
is_var(t) says which terms are variables. Any other term must map to itself.
"""
if not atoms:
yield binding
return
rel, terms = atoms[0]
for tup in by_rel.get(rel, ()):
if len(tup) != len(terms):
continue
new = dict(binding)
ok = True
for t, v in zip(terms, tup):
if is_var(t):
if new.setdefault(t, v) != v:
ok = False
break
elif t != v:
ok = False
break
if ok:
yield from _matches(atoms[1:], by_rel, new, is_var)
def chase(source, tgds, first_null=1):
"""The canonical universal solution: each trigger fires once, with fresh nulls."""
by_rel = _index(source)
out = set() # @line L8
nxt = first_null
for body, head in tgds: # @line L9
body_vars = {t for _, ts in body for t in ts}
exist = sorted({t for _, ts in head for t in ts} - body_vars)
seen = set()
for m in _matches(list(body), by_rel, {}, lambda t: True):
key = tuple(sorted(m.items()))
if key in seen:
continue
seen.add(key)
m = dict(m)
for y in exist:
m[y] = Null(nxt)
nxt += 1
for rel, ts in head: # @line L10
out.add((rel, tuple(m[t] for t in ts)))
return out # @line L11
def null_blocks(inst):
"""The blocks: the connected parts of the graph on the nulls in which two
nulls are joined when they occur in the same fact. Sorted lists of nulls."""
parent = {}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for _, tup in inst:
ns = [v for v in tup if is_null(v)]
for n in ns:
parent.setdefault(n, n)
for n in ns[1:]:
ra, rb = find(ns[0]), find(n)
if ra != rb:
parent[rb] = ra
groups = {}
for n in parent:
groups.setdefault(find(n), []).append(n)
blocks = [sorted(g, key=value_key) for g in groups.values()]
return sorted(blocks, key=lambda b: value_key(b[0]))
def apply(h, fact):
rel, tup = fact
return (rel, tuple(h.get(v, v) for v in tup))
def find_witness(part, inst):
"""A map h on the nulls of part with h(part) a subset of inst and h(part) != part, or None."""
atoms = sorted(part, key=fact_key)
for h in _matches(atoms, _index(inst), {}, is_null):
if {apply(h, f) for f in part} != part:
return h
return None
def core(inst):
"""The core of an instance whose blocks are small, by retracting one block at a time."""
inst = set(inst)
for block in null_blocks(inst): # @line L2
nulls = set(block)
part = {f for f in inst if any(v in nulls for v in f[1])} # @line L3
while True:
h = find_witness(part, inst) # @line L4
if h is None:
break
image = {apply(h, f) for f in part}
inst -= part - image # @line L5
part &= inst # @line L6
return inst # @line L7
def core_solution(source, tgds):
"""The core of the universal solutions for source and the s-t tgds."""
return core(chase(source, tgds)) # @line L1
test_data_exchange_core_computation.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/data-exchange-core-computation/. The authors are listed in prov/6E0XMM.jsonl.
import itertools
import random
from data_exchange_core_computation import (
Null,
chase,
core,
core_solution,
is_null,
null_blocks,
)
D1 = ([("Flight", ("x", "y"))], [("Leg", ("x", "z")), ("Leg", ("z", "y"))])
D2 = ([("Flight", ("x", "y"))], [("Leg", ("x", "u"))])
I = {("Flight", ("a", "b")), ("Flight", ("b", "c"))}
def nulls_of(inst):
return sorted({v for _, t in inst for v in t if is_null(v)}, key=lambda n: n.id)
def adom(inst):
return sorted({v for _, t in inst for v in t}, key=repr)
def image(h, inst):
return {(r, tuple(h.get(v, v) for v in t)) for r, t in inst}
def endomorphisms(inst):
"""All maps from the nulls to the values of inst that map inst into itself, by brute force."""
ns, vals = nulls_of(inst), adom(inst)
for combo in itertools.product(vals, repeat=len(ns)):
h = dict(zip(ns, combo))
if image(h, inst) <= inst:
yield h
def maps_into(src, dst):
ns, vals = nulls_of(src), adom(dst)
return any(image(dict(zip(ns, c)), src) <= dst for c in itertools.product(vals, repeat=len(ns)))
def isomorphic(c1, c2):
n1, n2 = nulls_of(c1), nulls_of(c2)
if len(c1) != len(c2) or len(n1) != len(n2):
return False
return any(image(dict(zip(n1, p)), c1) == c2 for p in itertools.permutations(n2))
def satisfies(source, tgds, target):
"""Brute force: each match of a body in the source has a witness for the head in the target."""
vals_s = sorted({v for _, t in source for v in t})
vals_t = adom(target)
for body, head in tgds:
bv = sorted({x for _, ts in body for x in ts})
ev = sorted({x for _, ts in head for x in ts} - set(bv))
for c in itertools.product(vals_s, repeat=len(bv)):
m = dict(zip(bv, c))
if all((r, tuple(m[x] for x in ts)) in source for r, ts in body):
if not any(all((r, tuple({**m, **dict(zip(ev, d))}[x] for x in ts)) in target for r, ts in head)
for d in itertools.product(vals_t, repeat=len(ev))):
return False
return True
def naive_eval(query, inst):
"""The null-free answers of a CQ (head variables, body atoms) by brute force."""
hv, body = query
vs = sorted({x for _, ts in body for x in ts})
vals = adom(inst)
out = set()
for c in itertools.product(vals, repeat=len(vs)):
m = dict(zip(vs, c))
if all((r, tuple(m[x] for x in ts)) in inst for r, ts in body):
ans = tuple(m[x] for x in hv)
if not any(is_null(v) for v in ans):
out.add(ans)
return out
def random_setting(rng):
"""Small random source instance and s-t tgds over S(2), P(1) into T(2), U(1)."""
consts = ["a", "b", "c"]
source = set()
for _ in range(rng.randint(1, 3)):
source.add(("S", (rng.choice(consts), rng.choice(consts))))
if rng.random() < 0.5:
source.add(("P", (rng.choice(consts),)))
tgds = []
for _ in range(rng.randint(1, 3)):
body = [("S", ("x0", "x1"))] if rng.random() < 0.8 else [("P", ("x0",))]
bvars = sorted({x for _, ts in body for x in ts})
terms = bvars + ["y0", "y1"][: rng.randint(0, 2)]
head = []
for _ in range(rng.randint(1, 3)):
if rng.random() < 0.7:
head.append(("T", (rng.choice(terms), rng.choice(terms))))
else:
head.append(("U", (rng.choice(terms),)))
tgds.append((body, head))
return source, tgds
def random_query(rng):
vs = ["v0", "v1", "v2"]
body = []
for _ in range(rng.randint(1, 3)):
if rng.random() < 0.75:
body.append(("T", (rng.choice(vs), rng.choice(vs))))
else:
body.append(("U", (rng.choice(vs),)))
used = sorted({x for _, ts in body for x in ts})
return (used[: rng.randint(0, len(used))], body)
def test_example():
j = chase(I, [D1, D2])
n = {k: Null(k) for k in range(1, 5)}
assert j == {("Leg", ("a", n[1])), ("Leg", (n[1], "b")), ("Leg", ("b", n[2])), ("Leg", (n[2], "c")),
("Leg", ("a", n[3])), ("Leg", ("b", n[4]))}
assert null_blocks(j) == [[n[1]], [n[2]], [n[3]], [n[4]]]
c = core(j)
assert c == {("Leg", ("a", n[1])), ("Leg", (n[1], "b")), ("Leg", ("b", n[2])), ("Leg", (n[2], "c"))}
assert core_solution(I, [D1, D2]) == c
q2 = (["x", "y"], [("Leg", ("x", "z")), ("Leg", ("z", "y"))])
assert naive_eval(q2, c) == {("a", "b"), ("b", "c")}
assert naive_eval((["x", "y"], [("Leg", ("x", "y"))]), c) == set()
def test_constant_absorbs_null():
# S(x, y) -> exists z T(x, z), and S(x, y) -> T(x, y): the null folds onto the constant.
tgds = [([("S", ("x", "y"))], [("T", ("x", "z"))]), ([("S", ("x", "y"))], [("T", ("x", "y"))])]
c = core_solution({("S", ("a", "b"))}, tgds)
assert c == {("T", ("a", "b"))}
def test_against_brute_force():
rng = random.Random(2024)
checked = 0
while checked < 60:
source, tgds = random_setting(rng)
j = chase(source, tgds)
if len(nulls_of(j)) > 4:
continue
checked += 1
c = core(j)
assert c <= j
assert satisfies(source, tgds, c)
assert maps_into(j, c)
# The smallest image of an endomorphism of j is the core, so its size is |c|.
assert min(len(image(h, j)) for h in endomorphisms(j)) == len(c)
# c has no proper endomorphism.
assert all(image(h, c) == c for h in endomorphisms(c))
# A different universal solution has an isomorphic core.
j2 = chase(source, list(reversed(tgds)) + tgds[:1], first_null=100)
assert isomorphic(core(j2), c)
# Certain answers of CQs by naive evaluation agree on j and on its core.
for _ in range(3):
q = random_query(rng)
assert naive_eval(q, j) == naive_eval(q, c)
def test_edges():
assert chase(set(), [D1]) == set()
assert core(set()) == set()
ground = {("T", ("a", "b"))}
assert core(ground) == ground
# A block of two nulls that folds onto a constant, and a block that is already a core.
n1, n2 = Null(1), Null(2)
inst = {("T", ("a", n1)), ("T", (n1, n2)), ("T", ("a", "b")), ("T", ("b", "b"))}
assert core(inst) == {("T", ("a", "b")), ("T", ("b", "b"))}
loop = {("T", ("a", n1)), ("T", (n1, n2)), ("T", (n2, n2))}
assert core(loop) == loop
History
Fagin, Kolaitis, Miller and Popa defined universal solutions and the canonical universal solution in their work on data exchange, which appeared at ICDT 2003 and in Theoretical Computer Science in 2005. Fagin, Kolaitis and Popa then showed in ACM TODS in 2005 that all universal solutions share one core, that it is the smallest universal solution, and that it can be computed in polynomial time under broad conditions. Gottlob and Nash answered an open problem from that work in the Journal of the ACM in 2008, with a polynomial algorithm for weakly acyclic target tgds and egds.
References
- Ronald Fagin, Phokion G. Kolaitis and Lucian Popa, Data exchange: getting to the core, ACM TODS 30(1), 2005, pages 174-210
- Georg Gottlob and Alan Nash, Efficient core computation in data exchange, Journal of the ACM 55(2), 2008, the polynomial algorithm for weakly acyclic target dependencies
- Marcelo Arenas, Pablo Barceló, Leonid Libkin and Filip Murlak, Foundations of Data Exchange, Cambridge University Press, 2014, Chapter 6, Good solutions
- Ronald Fagin, Phokion G. Kolaitis, Renée J. Miller and Lucian Popa, Data exchange: semantics and query answering, Theoretical Computer Science 336(1), 2005, universal solutions and the chase
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 6E0XMM Edit this page History Report an error Markdown