Algorithm Search⌘K

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.

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
Properties
deterministicexactnot in placeofflineiterative
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 II and a finite set Σ\Sigma of source-to-target tgds ∀x (φ(x)→∃y ψ(x,y))\forall x\, (\varphi(x) \to \exists y\, \psi(x, y)). Set semantics holds throughout. Values are constants or labeled nulls ⊥1,⊥2,…\bot_1, \bot_2, \ldots (written N1, N2 in the code).

  • A homomorphism h:K→Lh : K \to L maps values to values, is the identity on constants and maps each fact of KK to a fact of LL.
  • An instance CC is a core if no homomorphism maps CC to a proper subset of CC. A core of KK is a subset C⊆KC \subseteq K that is a core with a homomorphism K→CK \to C.
  • A block of KK is a connected part of the graph on the nulls of KK 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

  1. CORE-SOLUTION(I, Sigma)
  2. 1J <- CHASE(I, Sigma) ▷ the canonical universal solution
  3. 2for each block B of J, in a fixed order do
  4. 3F <- the facts of J that hold a null of B
  5. 4while some map h on the nulls of F has h(F) ⊆ J and h(F) ≠ F do
  6. 5J <- J minus (F minus h(F))
  7. 6F <- F ∩ J
  8. 7return J
  9. CHASE(I, Sigma)
  10. 8J <- the empty instance
  11. 9for each tgd and each assignment of its body variables that maps the body into I do
  12. 10add the head to J, with fresh nulls for the existential variables
  13. 11return 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, hh is the identity on constants and on all nulls outside FF. The search for hh is a backtracking match of the facts of FF into JJ, with the nulls of FF as the variables, the same as evaluating a conjunctive query with ∣F∣|F| atoms. Line L5 replaces FF by its image h(F)h(F), which is already in JJ. This is the image of JJ under the map that is hh on FF and the identity elsewhere.

Example

The mapping has two tgds, d1:∀x,y (Flight(x,y)→∃z (Leg(x,z)∧Leg(z,y)))d_1 : \forall x, y\, (\text{Flight}(x, y) \to \exists z\, (\text{Leg}(x, z) \wedge \text{Leg}(z, y))) and d2:∀x,y (Flight(x,y)→∃u Leg(x,u))d_2 : \forall x, y\, (\text{Flight}(x, y) \to \exists u\, \text{Leg}(x, u)). The source is I={Flight(a,b),Flight(b,c)}I = \{\text{Flight}(a, b), \text{Flight}(b, c)\}. The chase fires four triggers and gives

J={Leg(a,⊥1),Leg(⊥1,b),Leg(b,⊥2),Leg(⊥2,c),Leg(a,⊥3),Leg(b,⊥4)}.J = \{\text{Leg}(a, \bot_1), \text{Leg}(\bot_1, b), \text{Leg}(b, \bot_2), \text{Leg}(\bot_2, c), \text{Leg}(a, \bot_3), \text{Leg}(b, \bot_4)\}.

Each null is its own block.

block FF a map hh with h(F)⊆Jh(F) \subseteq J, h(F)≠Fh(F) \neq F facts removed
⊥1\bot_1 Leg(a,⊥1)(a, \bot_1), Leg(⊥1,b)(\bot_1, b) none: only ⊥1\bot_1 has both a Leg from aa and a Leg to bb none
⊥2\bot_2 Leg(b,⊥2)(b, \bot_2), Leg(⊥2,c)(\bot_2, c) none, for the same reason none
⊥3\bot_3 Leg(a,⊥3)(a, \bot_3) ⊥3↦⊥1\bot_3 \mapsto \bot_1 Leg(a,⊥3)(a, \bot_3)
⊥4\bot_4 Leg(b,⊥4)(b, \bot_4) ⊥4↦⊥2\bot_4 \mapsto \bot_2 Leg(b,⊥4)(b, \bot_4)

The core is {Leg(a,⊥1),Leg(⊥1,b),Leg(b,⊥2),Leg(⊥2,c)}\{\text{Leg}(a, \bot_1), \text{Leg}(\bot_1, b), \text{Leg}(b, \bot_2), \text{Leg}(\bot_2, c)\}. The trigger of d2d_2 adds nothing that d1d_1 does not already give. A query Q(x,y) :- Leg(x,z),Leg(z,y)Q(x, y) \text{ :- } \text{Leg}(x, z), \text{Leg}(z, y) gives the same null-free answers {(a,b),(b,c)}\{(a, b), (b, c)\} on JJ 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 CC of the canonical universal solution JJ such that CC is a core, JJ maps homomorphically to CC, and CC is a universal solution.

The proof has four parts.

  1. The chase result JJ 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.
  2. Each fact of JJ holds nulls of one trigger only, so a block has at most ww nulls.
  3. An instance is a core if and only if no group of nulls has a map hh as in line L4. If such an hh 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 hh.
  4. 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 Σ\Sigma of source-to-target tgds ∀x (φ(x)→∃y ψ(x,y))\forall x\, (\varphi(x) \to \exists y\, \psi(x, y)), with no target dependencies. An instance is a finite set of facts. A value is a constant or a labeled null. A homomorphism h:K→Lh : K \to L maps values to values, is the identity on constants, and maps each fact of KK to a fact of LL. An instance CC is a core if there is no homomorphism from CC to a proper subset of CC. A core of KK is a subset C⊆KC \subseteq K that is a core and has a homomorphism K→CK \to C. A target instance KK is a solution for a source instance II if (I,K)(I, K) satisfies Σ\Sigma, and it is universal if it has a homomorphism into each solution.

Let ww be the largest number of existential variables in one tgd and let aa be the largest number of atoms in one head.

Lemma 1 (the chase). Lines L8 to L11 return a universal solution JJ.

Proof. A trigger is a tgd with an assignment mm of its body variables that maps the body into II. For each trigger, line L10 adds the head with fresh nulls for the existential variables. So each trigger has a witness in JJ, and JJ is a solution. Let KK be any solution. For each trigger, KK has values bb for the existential variables such that ψ(m(x),b)\psi(m(x), b) holds in KK. Map the fresh nulls of that trigger to bb. The nulls of different triggers are different, so this defines one map hh, and hh is the identity on constants. Each fact of JJ comes from one trigger and hh maps it to a fact of KK. So h:J→Kh : J \to K. □\square

Lemma 2 (small blocks). Each fact of JJ holds nulls of one trigger only. So each block of JJ has at most ww nulls, and at most aa facts of JJ hold a null of a given block.

Proof. A fact added at line L10 holds constants of II 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. □\square

Lemma 3 (groups). Let KK be an instance, and split its nulls into groups G1,…,GkG_1, \ldots, G_k such that each fact holds nulls of at most one group. Let FiF_i be the set of facts that hold a null of GiG_i. Call a map hh from GiG_i to the values of KK a witness for ii if h(Fi)⊆Kh(F_i) \subseteq K and h(Fi)≠Fih(F_i) \neq F_i, where hh is the identity on all other values. Then KK is a core if and only if no group has a witness.

Proof. Assume hh is a witness for ii. Let gg be hh on GiG_i and the identity elsewhere. A fact outside FiF_i holds no null of GiG_i, so gg fixes it, and g(K)=(K∖Fi)∪h(Fi)⊆Kg(K) = (K \setminus F_i) \cup h(F_i) \subseteq K. Since ∣h(Fi)∣≤∣Fi∣|h(F_i)| \le |F_i| and h(Fi)≠Fih(F_i) \neq F_i, some fact f∈Fif \in F_i is not in h(Fi)h(F_i). It is also not in K∖FiK \setminus F_i, so f∉g(K)f \notin g(K). So gg maps KK to a proper subset of KK, and KK is not a core.

Now assume KK is not a core: some homomorphism rr maps KK into a proper subset of KK. Each fact of KK is ground or is in exactly one FiF_i, and rr fixes the ground facts. If r(Fi)=Fir(F_i) = F_i for each ii, then r(K)=Kr(K) = K, which is false. So r(Fi)≠Fir(F_i) \neq F_i for some ii. The facts of FiF_i hold only constants and nulls of GiG_i, so the restriction of rr to GiG_i maps FiF_i to r(Fi)⊆Kr(F_i) \subseteq K, and it is a witness for ii. □\square

Lemma 4 (one step). Let JtJ_t be the instance before an execution of line L5, with a witness hh for the current group with facts FF. Then Jt+1=Jt∖(F∖h(F))=g(Jt)J_{t+1} = J_t \setminus (F \setminus h(F)) = g(J_t) for the map gg of Lemma 3, and Jt+1J_{t+1} is a proper subset of JtJ_t.

Proof. By the first part of the proof of Lemma 3, g(Jt)=(Jt∖F)∪h(F)g(J_t) = (J_t \setminus F) \cup h(F). Since h(F)⊆Jth(F) \subseteq J_t, this is Jt∖(F∖h(F))J_t \setminus (F \setminus h(F)). The set F∖h(F)F \setminus h(F) is not empty, as shown there. □\square

Invariant. Let B1,…,BkB_1, \ldots, B_k be the blocks of JJ in the order of line L2. At each time, let the group GiG_i be the set of nulls of BiB_i that still occur, and let FiF_i be the facts that hold one of them. Every fact of the current instance is a fact of JJ, so it holds nulls of at most one group, and Lemma 3 applies to the groups. Line L3 sets the variable FF to FiF_i when block ii starts, and lines L5 and L6 keep F=FiF = F_i, because line L5 removes only facts of FiF_i. For the same reason, the work on block jj does not change FiF_i for i≠ji \neq j.

Theorem. The procedure stops and returns an instance CC such that C⊆JC \subseteq J, there is a homomorphism J→CJ \to C, CC is a core, and CC is a universal solution.

Proof. Termination. Each pass through line L5 removes at least one fact by Lemma 4, so there are at most ∣J∣|J| 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 G:J→CG : J \to C with G(J)=CG(J) = C.

Core. Fix ii. When the loop of block ii ends, there is no witness for ii in the instance J′J' of that time. After that, FiF_i does not change, by the invariant, and the instance only shrinks, so C⊆J′C \subseteq J'. A witness for ii in CC maps FiF_i into C⊆J′C \subseteq J', so it would be a witness in J′J'. So no group has a witness in CC, and CC is a core by Lemma 3.

Universal solution. Let a trigger with assignment mm hold in II. By Lemma 1, JJ has the facts ψ(m(x),y0)\psi(m(x), y_0) for the fresh nulls y0y_0. Then C=G(J)C = G(J) has the facts ψ(m(x),G(y0))\psi(m(x), G(y_0)), because GG fixes the constants m(x)m(x). So CC is a solution. For a solution KK, Lemma 1 gives J→KJ \to K, and C⊆JC \subseteq J, so the inclusion followed by that map is a homomorphism C→KC \to K. ■\blacksquare

Corollary (one core for all universal solutions). Let C1C_1 and C2C_2 be cores, with homomorphisms f:C1→C2f : C_1 \to C_2 and g:C2→C1g : C_2 \to C_1. Then C1C_1 and C2C_2 are isomorphic. So all universal solutions have isomorphic cores, the core CC above is the core of each of them, and no universal solution has fewer facts than CC.

Proof. The map g∘fg \circ f sends C1C_1 into C1C_1. Since C1C_1 is a core, its image is all of C1C_1. So g∘fg \circ f is onto the facts of C1C_1, hence onto its values, and as these are finite it is a bijection on them. So ff is one to one on values, and ∣C1∣=∣f(C1)∣≤∣C2∣|C_1| = |f(C_1)| \le |C_2|. In the same way ∣C2∣≤∣C1∣|C_2| \le |C_1|, so f(C1)=C2f(C_1) = C_2. The inverse of ff on values maps each fact f(c)f(c) back to cc, so it is a homomorphism, and ff is an isomorphism.

Two universal solutions U1U_1 and U2U_2 have homomorphisms each way, so their cores, which are subsets with homomorphisms from them, have homomorphisms each way and are isomorphic. If UU is a universal solution and C′C' is a core of UU, then C′⊆UC' \subseteq U and C′C' is isomorphic to CC, so ∣C∣=∣C′∣≤∣U∣|C| = |C'| \le |U|. □\square

Running time. Fix Σ\Sigma, so ww, aa and the arities are constants. Let m=∣J∣m = |J|, so the number of values of JJ is O(m)O(m). Line L4 runs at most mm times with success and at most once per block without, so at most 2m2m times. One search backtracks over the at most aa facts of FF. Each node of the search tree is a partial map of the nulls of FF, and different nodes at one depth give different partial maps, so there are at most (a+1)⋅O(m)w(a + 1) \cdot O(m)^w nodes. Each node scans the facts of one relation, O(m)O(m) work, and building the index takes O(mlog⁡m)O(m \log m). So one search takes O(mw+1)O(m^{w+1}) time, and the whole run takes O(mw+2)O(m^{w+2}) time. For a fixed Σ\Sigma, mm is polynomial in ∣I∣|I|, so this is polynomial time in data complexity.

Complexity

Fix Σ\Sigma. Let mm be the number of facts of JJ and ww the largest number of existential variables in one tgd. Line L4 succeeds at most mm times, since each success removes a fact, and fails at most once per block, so it runs at most 2m2m times. One search tries the partial maps of at most ww nulls to the O(m)O(m) values of JJ, and each step scans one relation.

  • Time. O(mw+1)O(m^{w+1}) for one search, and O(mw+2)O(m^{w+2}) in total. For a fixed Σ\Sigma, mm is polynomial in ∣I∣|I|, so the run takes polynomial time in data complexity.
  • Space. O(m)O(m) 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 Σ\Sigma is part of the input, the exponent ww grows with the mapping. Core problems are hard in general: Fagin, Kolaitis and Popa showed that deciding whether a graph HH is the core of a graph GG 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 ww.
  • Monotone shrinking. Each step removes facts and never adds one, so each prefix of the run is a universal solution between JJ and the core.
  • No new values. The core uses only values that occur in JJ.

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 hh of line L4 is the identity on constants and maps into values that already occur in JJ. A map that may invent values does not give a subset.
  • Blocks grow with target dependencies. The bound of ww 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 JJ can give different naive answers to a query with negation. In the example, "some xx has Leg(a,x)(a, x) and no Leg(x,b)(x, b)" is true on JJ, with x=⊥3x = \bot_3, 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.

data_exchange_core_computation.pyI0RawGitHub
# 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

  1. Ronald Fagin, Phokion G. Kolaitis and Lucian Popa, Data exchange: getting to the core, ACM TODS 30(1), 2005, pages 174-210
  2. 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
  3. Marcelo Arenas, Pablo Barceló, Leonid Libkin and Filip Murlak, Foundations of Data Exchange, Cambridge University Press, 2014, Chapter 6, Good solutions
  4. 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.

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