Algorithm Search⌘K

Definitionadvanced

Denial constraint

Also called denial constraints.

A constraint that forbids any choice of tuples that makes a conjunction of comparisons true. It generalizes functional dependencies and is used to detect errors.

A denial constraint says that some combination of tuples must not occur: no choice of tuples may make all of a list of comparisons true at once. A functional dependency is the special case with two tuples, equalities on the left side and one inequality on the right side. A conditional functional dependency is a different extension of the same idea. It adds constants to a functional dependency but keeps only equality, while a denial constraint allows the order comparisons <<, ≤\le, >>, ≥\ge between any attributes. Data cleaning systems such as HoloClean use denial constraints as their main language for errors.

Definition

Let RR be a relation schema. A predicate has the form tx.A  θ  ty.Bt_x.A \;\theta\; t_y.B or tx.A  θ  ct_x.A \;\theta\; c, where tx,tyt_x, t_y are tuple variables, A,BA, B are attributes, cc is a constant and θ\theta is one of =,≠,<,≤,>,≥=, \ne, <, \le, >, \ge. A denial constraint is a sentence

φ  =  ∀t1,…,tk∈R:¬(P1∧⋯∧Pm)\varphi \;=\; \forall t_1, \ldots, t_k \in R : \neg (P_1 \wedge \cdots \wedge P_m)

with predicates P1,…,PmP_1, \ldots, P_m over the tuple variables t1,…,tkt_1, \ldots, t_k. Set semantics holds: RR is a set of tuples. An instance II of RR satisfies φ\varphi if no assignment of tuples of II to the variables makes every PiP_i true. An assignment that does is a violation. As in the work of Chu, Ilyas and Papotti, the tuple variables of one constraint take different tuples, so a constraint with two variables talks about pairs of different tuples. Most uses need only k≤2k \le 2, and this page and its code treat k=1k = 1 and k=2k = 2.

In first-order terms, a denial constraint is a universal sentence whose body is a negated conjunction of atoms and comparisons. Satisfaction is preserved by deleting tuples: a subset of an instance that satisfies φ\varphi also satisfies it. This is why deletions alone can always repair a violation of a set of denial constraints.

Examples and non-examples

The table Tax has the attributes Name, State, Salary and Rate:

row Name State Salary Rate
0 Ann NY 50 10
1 Bob NY 70 8
2 Cat NY 90 12
3 Dan CA 40 9
4 Eve CA -5 7
  • An order constraint. "In one state, a higher salary may not have a lower tax rate" is ∀t1,t2:¬(t1.State=t2.State∧t1.Salary<t2.Salary∧t1.Rate>t2.Rate)\forall t_1, t_2 : \neg (t_1.\text{State} = t_2.\text{State} \wedge t_1.\text{Salary} < t_2.\text{Salary} \wedge t_1.\text{Rate} > t_2.\text{Rate}). The only violation is (t1,t2)=(row 0,row 1)(t_1, t_2) = (\text{row } 0, \text{row } 1): Ann earns less than Bob in NY but pays a higher rate. No functional dependency can say this.
  • A single-tuple constraint. ∀t:¬(t.Salary<0)\forall t : \neg (t.\text{Salary} < 0) has one violation, row 4.
  • A functional dependency. State→Rate\text{State} \to \text{Rate} is ∀t1,t2:¬(t1.State=t2.State∧t1.Rate≠t2.Rate)\forall t_1, t_2 : \neg (t_1.\text{State} = t_2.\text{State} \wedge t_1.\text{Rate} \ne t_2.\text{Rate}). In general, X→YX \to Y gives one denial constraint for each attribute of YY.
  • A constant CFD. The pattern "if the country code is 01 and the area code is 908, the city is MH" is the single-tuple constraint ∀t:¬(t.CC=01∧t.AC=908∧t.CT≠MH)\forall t : \neg (t.\text{CC} = 01 \wedge t.\text{AC} = 908 \wedge t.\text{CT} \ne \text{MH}).
  • Non-example: an inclusion dependency. "Each order has a customer" asks for a tuple to exist. Deleting the customer creates a violation, so no denial constraint can express it. It is a tuple-generating dependency.
  • Non-example: a constraint over the same tuple twice. Under the convention of different tuples, ∀t1,t2:¬(t1.A=t2.A)\forall t_1, t_2 : \neg (t_1.A = t_2.A) says that AA is a key, not that the table is empty. With the same tuple allowed, every nonempty table would violate it.

To find the violations of a constraint with two tuple variables, hash the rows on the attributes joined by equality, and compare only the rows in one bucket:

  1. VIOLATIONS(I, phi)
  2. 1E <- the predicates t1.A = t2.B of phi; P <- the other predicates
  3. 2H <- an empty hash table
  4. 3for each row t of I do add t to H under the key (t.B for each predicate of E)
  5. 4for each row s of I do
  6. 5for each row t in H under the key (s.A for each predicate of E) do
  7. 6if t ≠ s and every predicate of P holds for (s, t) then report (s, t)

This finds the same set of pairs as checking all n2n^2 ordered pairs, which is what the code tests against. It takes O(np)O(n p) time to build the table, for nn rows and pp predicates, plus O(p)O(p) for each pair of rows that share a key. With no equality predicate, as in "no two rows with t1.A<t2.At_1.A < t_2.A and t1.B>t2.Bt_1.B > t_2.B", every pair shares the empty key and the cost is O(n2p)O(n^2 p).

  • Functional dependency. The denial constraints with two tuple variables, equalities and one inequality on the same attribute.
  • Conditional functional dependency. Functional dependencies on the tuples that match a pattern of constants. Each CFD is a set of denial constraints, one per pattern and attribute.
  • Equality-generating dependency. A formula ∀xˉ(φ(xˉ)→xi=xj)\forall \bar x (\varphi(\bar x) \to x_i = x_j) with a conjunction of atoms φ\varphi. Read as ¬(φ∧xi≠xj)\neg (\varphi \wedge x_i \ne x_j), it is a denial constraint without order comparisons.
  • Implication. Chu, Ilyas and Papotti give a sound set of inference rules for denial constraints, in the spirit of Armstrong's axioms, and show that deciding whether a set of denial constraints implies another one is coNP-complete.
  • Repairs and consistent answers. Under denial constraints, a subset repair is a maximal consistent subset. Consistent query answering asks which answers hold in all of them. Chomicki and Marcinkowski study both for denial constraints.

Code

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.

denial_constraint.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/denial-constraint/. The authors are listed in prov/HJ9YV3.jsonl.

"""Denial constraints and the detection of their violations.

A row is a tuple of values. A term is (1, a) for attribute a of the first
tuple variable, (2, a) for attribute a of the second, or ("c", v) for the
constant v. A predicate is (left, op, right) with op one of =, !=, <, <=, >,
>=, and left is a term of a tuple variable. A denial constraint is a list of
predicates and says that no assignment of rows to the tuple variables makes
all of them true. A constraint that mentions only (1, a) terms has one tuple
variable; otherwise it has two, and the two rows must be different rows.
Set semantics: the rows are distinct.
"""

OPS = {
    "=": lambda x, y: x == y,
    "!=": lambda x, y: x != y,
    "<": lambda x, y: x < y,
    "<=": lambda x, y: x <= y,
    ">": lambda x, y: x > y,
    ">=": lambda x, y: x >= y,
}


def _value(term, s, t):
    k, a = term
    if k == "c":
        return a
    return s[a] if k == 1 else t[a]


def holds(pred, s, t):
    left, op, right = pred
    return OPS[op](_value(left, s, t), _value(right, s, t))


def arity(dc):
    """The number of tuple variables of a constraint: 1 or 2."""
    terms = [p[0] for p in dc] + [p[2] for p in dc]
    return 2 if any(k == 2 for k, _ in terms) else 1


def violations_brute(rows, dc):
    """The violations by the definition: each row i (one variable) or each
    ordered pair (i, j) of different rows (two variables) that makes all predicates true."""
    if arity(dc) == 1:
        return {(i,) for i, s in enumerate(rows) if all(holds(p, s, s) for p in dc)}
    return {
        (i, j)
        for i, s in enumerate(rows)
        for j, t in enumerate(rows)
        if i != j and all(holds(p, s, t) for p in dc)
    }


def violations(rows, dc):
    """The same set as violations_brute, found by hashing on the equality
    predicates between the two tuple variables."""
    if arity(dc) == 1:
        return violations_brute(rows, dc)
    joins, rest = [], []  # @line L1
    for left, op, right in dc:
        if op == "=" and {left[0], right[0]} == {1, 2}:
            if left[0] == 2:
                left, right = right, left
            joins.append((left[1], right[1]))
        else:
            rest.append((left, op, right))
    table = {}  # @line L2
    for j, t in enumerate(rows):  # @line L3
        table.setdefault(tuple(t[b] for _, b in joins), []).append(j)
    out = set()
    for i, s in enumerate(rows):  # @line L4
        for j in table.get(tuple(s[a] for a, _ in joins), ()):  # @line L5
            if i != j and all(holds(p, s, rows[j]) for p in rest):  # @line L6
                out.add((i, j))
    return out


def from_fd(lhs, rhs):
    """The denial constraints of the functional dependency lhs -> rhs, one per attribute of rhs."""
    return [[((1, a), "=", (2, a)) for a in lhs] + [((1, b), "!=", (2, b))] for b in rhs]


def satisfies(rows, dcs):
    return all(not violations(rows, dc) for dc in dcs)
test_denial_constraint.py 71 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/denial-constraint/. The authors are listed in prov/HJ9YV3.jsonl.

import itertools
import random

from denial_constraint import arity, from_fd, satisfies, violations, violations_brute

# Attributes: 0 = Name, 1 = State, 2 = Salary, 3 = Rate.
TAX = [
    ("Ann", "NY", 50, 10),
    ("Bob", "NY", 70, 8),
    ("Cat", "NY", 90, 12),
    ("Dan", "CA", 40, 9),
    ("Eve", "CA", -5, 7),
]
# In one state, a higher salary may not have a lower tax rate.
RATE_DC = [((1, 1), "=", (2, 1)), ((1, 2), "<", (2, 2)), ((1, 3), ">", (2, 3))]
NO_NEGATIVE_SALARY = [((1, 2), "<", ("c", 0))]


def test_tax_example():
    assert violations(TAX, RATE_DC) == {(0, 1)}
    assert violations(TAX, NO_NEGATIVE_SALARY) == {(4,)}
    assert arity(RATE_DC) == 2 and arity(NO_NEGATIVE_SALARY) == 1


def fd_holds(rows, lhs, rhs):
    return all(
        not all(s[a] == t[a] for a in lhs) or all(s[b] == t[b] for b in rhs)
        for s, t in itertools.product(rows, repeat=2)
    )


def random_dc(rng, nattrs):
    dc = []
    for _ in range(rng.randint(1, 3)):
        op = rng.choice(["=", "=", "!=", "<", "<=", ">", ">="])
        left = (rng.choice([1, 1, 2]), rng.randrange(nattrs))
        r = rng.random()
        if r < 0.7:
            right = (rng.choice([1, 2, 2]), rng.randrange(nattrs))
        else:
            right = ("c", rng.randint(0, 3))
        dc.append((left, op, right))
    return dc


def test_against_brute_force_over_pairs():
    rng = random.Random(42)
    for _ in range(300):
        nattrs = rng.randint(1, 4)
        rows = list({tuple(rng.randint(0, 3) for _ in range(nattrs)) for _ in range(rng.randint(0, 12))})
        dc = random_dc(rng, nattrs)
        assert violations(rows, dc) == violations_brute(rows, dc)


def test_functional_dependency_as_denial_constraints():
    rng = random.Random(7)
    for _ in range(200):
        rows = list({tuple(rng.randint(0, 2) for _ in range(3)) for _ in range(rng.randint(0, 8))})
        lhs = rng.sample(range(3), rng.randint(0, 2))
        rhs = [b for b in range(3) if b not in lhs][:1]
        assert satisfies(rows, from_fd(lhs, rhs)) == fd_holds(rows, lhs, rhs)


def test_same_row_is_not_a_pair():
    # t1.A = t2.A alone would be violated by any row paired with itself.
    rows = [(1,), (2,)]
    assert violations(rows, [((1, 0), "=", (2, 0))]) == set()
    assert violations(rows, [((1, 0), "<", (2, 0))]) == {(0, 1)}

References

  1. Xu Chu, Ihab F. Ilyas and Paolo Papotti, Discovering denial constraints, PVLDB 6(13), 2013, pages 1498-1509, the definition of denial constraints, the inference rules and the implication problem
  2. Xu Chu, Ihab F. Ilyas and Paolo Papotti, Holistic data cleaning: putting violations into context, ICDE 2013, pages 458-469, violation detection and repair with denial constraints
  3. Jan Chomicki and Jerzy Marcinkowski, Minimal-change integrity maintenance using tuple deletions, Information and Computation 197(1-2), 2005, pages 90-121, repairs and consistent answers under denial constraints
  4. Leopoldo Bertossi, Database Repairing and Consistent Query Answering, Morgan and Claypool, 2011, the chapters on repairs and consistent answers, where denial constraints are a main class of integrity constraints

Where this leads

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW4 complete
  • a review of the text: no review record reviews/HJ9YV3/text.yaml