Algorithm Search⌘K

Techniquecore

Delta rules

Also called delta queries, derivative of a query.

Rules that give the change of a query result from the changes of its inputs, for each operator of relational algebra.

Delta rules are the technique that gives, for each operator of relational algebra, an expression for the change of its result in terms of the changes of its inputs and the old values of its inputs. Applied by structural recursion to a query EE, they give a query ΔE\Delta E with E(D+ΔD)=E(D)+ΔEE(D + \Delta D) = E(D) + \Delta E. Incremental view maintenance is the algorithm that evaluates ΔE\Delta E after each update and adds it to a materialized view. Higher-order IVM applies the rules again to ΔE\Delta E itself, and DBSP restates them as one theorem about linear and bilinear operators on streams of changes.

In plain words

A view is a stored query answer. When a few rows of the tables change, you do not want to run the query again. Delta rules tell you, one operator at a time, how a change at the input of the operator becomes a change at its output.

For a filter, you filter the changed rows. For a projection, you project the changed rows. For a union, you put the two changes together. A join is harder: new rows on the left meet the old right side, new rows on the right meet the old left side, and new rows on the two sides also meet each other. Difference, duplicate removal and grouping look at the old count of each changed row or group and give the new count.

You then add the change to the stored answer.

When it applies

  • The query is an expression of the bag relational algebra: selection, projection, renaming, union, difference, intersection, product, join, duplicate elimination and grouping with COUNT and SUM. The rules here are for this algebra. Recursive queries need a fixed point; see semi-naive evaluation and the DRed algorithm.
  • A change is a signed bag: each tuple has an integer weight, positive for insertions and negative for deletions. A bag is a change with weights at least 0. A set is a Z-set with weights 0 and 1, and distinct maps a Z-set to a set. So one set of rules covers bags, sets and changes.
  • The old values of the inputs of each operator are available, stored or computable. A view that needs no such values is self-maintainable.
  • The rule is evaluated in the state that it was written for. The rules below read the state before the update. If the base tables are already changed, use the variant for the state after the update, or the logs of deferred view maintenance.
  • Delta rules have no notion of time, so late data needs no special case. A change that arrives late is one more delta, computed against the state at the moment it is applied. Because the weights add up, the view after all changes equals EE on the final tables, in any order of application.

The template

Write E[t]E[t] for the weight of tuple tt in EE, supp(X)\mathrm{supp}(X) for the tuples with nonzero weight in XX, and ++ for the sum of weights, tuple by tuple. A join of two signed bags multiplies weights. E1E_1 and E2E_2 are the subexpressions at their old values, and ΔE1\Delta E_1 and ΔE2\Delta E_2 are their changes, found by the same procedure.

  1. DELTA(E) ▷ returns ΔE with E(D + ΔD) = E(D) + ΔE
  2. 1if E = R then return ΔR ▷ a base table: its change is given
  3. 2if E = σ_p(E1) then return σ_p(ΔE1)
  4. 3if E = π_A(E1) then return π_A(ΔE1) ▷ weights of equal tuples add up
  5. 4if E = E1 ⊎ E2 then return ΔE1 + ΔE2
  6. 5if E = E1 ⋈ E2 then return ΔE1 ⋈ E2 + E1 ⋈ ΔE2 + ΔE1 ⋈ ΔE2
  7. 6if E = f(E1, E2) for f in {monus, min} then return, for each t in supp(ΔE1) ∪ supp(ΔE2),
  8. f(E1[t] + ΔE1[t], E2[t] + ΔE2[t]) - f(E1[t], E2[t])
  9. 7if E = δ(E1) then return, for each t in supp(ΔE1), [E1[t] + ΔE1[t] > 0] - [E1[t] > 0]
  10. 8if E = γ_{G; aggs}(E1) then keep, per group g, the count n, the non-null count k and the sum s
  11. 9for each group g of a tuple in supp(ΔE1): add -1 to the old row of g and +1 to the new row of g

Renaming passes the change through with new attribute names, and a product is a join with no common attribute. At line L6, monus is the bag difference, max⁡(0,m−n)\max(0, m - n), and min is the bag intersection. At line L7, [x][x] is 1 if xx holds and 0 if not. At line L9, a group with no rows before the update has no old row to remove, and a group with no rows after it has no new row to add. With no grouping attributes the single result row always exists, as in SQL.

Why it works. The proof is by induction on EE. Lines L2 to L4 hold because selection, projection and union are linear: they act on each tuple's weight on its own, so f(X+ΔX)=f(X)+f(ΔX)f(X + \Delta X) = f(X) + f(\Delta X). Line L5 holds because the join is bilinear, so (E1+ΔE1)⋈(E2+ΔE2)(E_1 + \Delta E_1) \bowtie (E_2 + \Delta E_2) expands into E1⋈E2E_1 \bowtie E_2 and the three terms of the rule. This is the product rule of finite differences, Δ(fg)=Δf⋅g+f⋅Δg+Δf⋅Δg\Delta(fg) = \Delta f \cdot g + f \cdot \Delta g + \Delta f \cdot \Delta g. Lines L6 and L7 are not linear, so they use the definition: the new weight minus the old weight, and only tuples whose input weight changes can change. Line L9 removes the old row of each changed group and adds its new one, and the summary (n,k,s)(n, k, s) of a group after the update is its old summary plus the summary of the change, because counts and sums are linear.

Cost. Lines L1 to L4 cost O(1)O(1) per changed tuple in the worst case and keep no memory. Line L5 must store both old inputs, and with a hash index on the join attributes each changed tuple costs O(1)O(1) expected time plus its number of matches, which can be the size of the other input. Lines L6, L7 and L9 keep one counter per distinct tuple or one summary per group, in a hash map, and cost O(1)O(1) expected time per changed tuple. The reference code on this page computes the old values of the subexpressions from scratch, which is simpler to check and much slower. Real systems store them.

Example. Take R(A,B)={(1,10),(2,10),(3,20)}R(A, B) = \{(1, 10), (2, 10), (3, 20)\} and S(B,C)={(10,x),(20,y)}S(B, C) = \{(10, x), (20, y)\}, so R⋈S={(1,10,x),(2,10,x),(3,20,y)}R \bowtie S = \{(1, 10, x), (2, 10, x), (3, 20, y)\}. The update inserts (4,20)(4, 20) into RR, deletes (1,10)(1, 10) from RR, and inserts (20,z)(20, z) into SS. Line L5 gives three terms.

term tuples and weights
ΔR⋈S\Delta R \bowtie S (4,20,y)(4, 20, y) +1, (1,10,x)(1, 10, x) -1
R⋈ΔSR \bowtie \Delta S (3,20,z)(3, 20, z) +1
ΔR⋈ΔS\Delta R \bowtie \Delta S (4,20,z)(4, 20, z) +1

Their sum, added to the old view, gives {(2,10,x),(3,20,y),(3,20,z),(4,20,y),(4,20,z)}\{(2, 10, x), (3, 20, y), (3, 20, z), (4, 20, y), (4, 20, z)\}, which is R⋈SR \bowtie S on the new tables. Now group the join by BB with $n = $ COUNT(*) and $s = $ SUM(AA). The old view is {(10,2,3),(20,1,3)}\{(10, 2, 3), (20, 1, 3)\}. Lines L8 and L9 touch groups 10 and 20 and give the change −(10,2,3)+(10,1,2)−(20,1,3)+(20,4,14)-(10, 2, 3) + (10, 1, 2) - (20, 1, 3) + (20, 4, 14).

Classic examples

  • Incremental view maintenance evaluates DELTA after each transaction. Its counting algorithm is the set case: it keeps the weight of each tuple as a count of derivations and applies line L7 at the end.
  • Semi-naive evaluation of Datalog applies line L5 to each rule in each round: only joins with at least one new fact can make new facts.
  • The DRed algorithm applies the rules to recursive views, where deletions need a step that derives tuples again.
  • Higher-order IVM notes that ΔE\Delta E is itself a query, with a delta of its own, and stores the deltas of deltas so that each update costs only lookups and additions.
  • DBSP states lines L2 to L5 as two theorems: the delta of a linear operator is the operator itself, and the delta of a bilinear operator has the three terms of line L5.

Variations

  • Two terms for the join. Since ΔE1⋈E2+ΔE1⋈ΔE2=ΔE1⋈(E2+ΔE2)\Delta E_1 \bowtie E_2 + \Delta E_1 \bowtie \Delta E_2 = \Delta E_1 \bowtie (E_2 + \Delta E_2), line L5 can read the new value of E2E_2 and drop the third term. In the example, ΔR⋈Snew+R⋈ΔS\Delta R \bowtie S_{\mathrm{new}} + R \bowtie \Delta S gives the same four weights.
  • Separate insertions and deletions. The older rules for sets and bags give two expressions per operator, one for the inserted tuples and one for the deleted tuples, in place of one signed change.
  • Rules for the state after the update. If the base tables already hold the new values, each old value is written as the new value minus the change, which is the past query of deferred maintenance.
  • Other aggregates. AVG is SUM divided by COUNT, so it follows from line L8. MIN and MAX have a rule for insertions (compare with the old value) but not for deletions: deleting the current minimum needs the other rows of the group.
  • Outer joins. A left outer join is the join plus the left rows with no match, padded with NULL. Its change has the part of line L5 and a part for the left rows whose number of matches goes from 0 to more than 0 or back, found as at line L7.

Pitfalls

  • Dropping the term ΔR⋈ΔS\Delta R \bowtie \Delta S. It is easy to forget that new tuples on both sides meet each other. In the example, the sum of the first two terms misses (4,20,z)(4, 20, z).
  • Evaluating a rule in the wrong state. The three terms of line L5 read the old RR and SS. If the update is applied first and the same terms read the new tables, the example gives (4,20,z)(4, 20, z) weight 3 in place of 1. Colby and others show the same fault for a projection of a join and for a difference.
  • Treating difference as linear. Monus is not linear: with R={(5,1)}R = \{(5, 1)\} and T={(5,1),(5,1)}T = \{(5, 1), (5, 1)\}, the view R∖TR \setminus T is empty, and deleting one copy from TT leaves it empty, but ΔR−ΔT\Delta R - \Delta T gives (5,1)(5, 1) weight +1. Line L6 uses the old weights to get 0.
  • Duplicate elimination without counts. Line L7 needs the old weight of each tuple below δ\delta. A view that stores only the set result cannot tell whether a deleted tuple had another derivation.
  • Self-joins. In R⋈RR \bowtie R both inputs change together. Line L5 handles this if ΔE1\Delta E_1 and ΔE2\Delta E_2 are both ΔR\Delta R, but code that changes one copy of RR at a time must read the other copy at the matching state.
  • NULL keys. Under SQL a NULL join attribute matches nothing, in the change as in the table. The rules must use the same join test as the query, or the view drifts from the query.

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.

dbrel.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the databases pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Naive relations, operators by definition, SQL three-valued logic and a page-counting disk.

This is the reference that the tests of the databases pages compare against.
Every operator here follows its definition directly, with nested loops and no
index, hash table or sort of the input. Do not use it as a fast engine.

Relations
    Relation(schema, rows, mode) holds a tuple of distinct attribute names and
    a collections.Counter from tuples to positive counts. mode is "bag" (the
    default, SQL semantics) or "set" (relational theory); in set mode every
    count is 1. rows may be an iterable of tuples (duplicates add up) or a
    mapping from tuples to counts. Two relations are equal when they have the
    same attributes (in any column order) and the same count for each tuple.
    The mode is not compared.

Operators (each returns a new Relation in the mode of its input)
    select(rel, pred)            keeps a row only when pred(row) is True
    where(rel, pred)             the same as select (the SQL WHERE filter)
    project(rel, attrs)          bag: counts add up; set: duplicates removed
    rename(rel, mapping)         mapping is {old: new}
    union(r, s)                  bag: UNION ALL (counts add); set: union
    difference(r, s)             bag: monus max(0, m - n); set: r - s
    intersection(r, s)           bag: min(m, n); set: intersection
    product(r, s)                attributes must be disjoint; counts multiply
    natural_join(r, s)           nested loops on the common attributes
    theta_join(r, s, pred)       select(product(r, s), pred)
    semijoin(r, s), antijoin(r, s)
    distinct(rel)                every count becomes 1
    aggregate(rel, group_attrs, aggs)
                                 aggs is a list of (func, attr, out) with func in
                                 count_star, count, count_distinct, sum, avg, min, max

A predicate receives the row as a dict from attribute name to value. It may
return True, False or None (UNKNOWN). Only True keeps the row.

Nulls
    NULL is None. Joins follow SQL: a common attribute that is None in either
    row never matches. aggregate follows SQL: GROUP BY puts all nulls of a
    column in one group, every aggregate except count_star skips nulls, and
    sum, avg, min and max of no non-null value give None while count gives 0.
    With no grouping attributes, aggregate returns one row even for an empty
    input, as SQL does.

Expressions
    evaluate(expr, db, mode) evaluates a tree of nested tuples:
        ("scan", name)
        ("select", pred, e)          ("project", attrs, e)
        ("rename", mapping, e)       ("distinct", e)
        ("union", e1, e2)            ("difference", e1, e2)
        ("intersection", e1, e2)     ("product", e1, e2)
        ("join", e1, e2)             ("theta_join", pred, e1, e2)
        ("semijoin", e1, e2)         ("antijoin", e1, e2)
        ("aggregate", group_attrs, aggs, e)
    db maps a name to a Relation. Each scanned relation is first put in mode.

Three-valued logic
    tv_and, tv_or and tv_not are the strong Kleene connectives on True, False
    and None. cmp3(op, x, y) compares with op in =, <>, !=, <, <=, >, >= and
    returns None when x or y is None.

Disk
    Disk counts page reads and writes. load(rows, per_page) puts an existing
    input on the disk without counting it. paginate(rows, per_page) splits a
    list of rows into pages.

Random data
    random_relation(rng, schema, n, domain, mode, null_rate) draws n rows.
"""

from collections import Counter
from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
from fractions import Fraction
from numbers import Number
import random

BAG = "bag"
SET = "set"
MODES = (BAG, SET)


# ---------------------------------------------------------------- ordering

def value_key(v: object) -> tuple:
    """A total order on the values of one column: None first, then numbers, then strings."""
    if v is None:
        return (0, 0)
    if isinstance(v, Number):
        return (1, v)
    if isinstance(v, str):
        return (2, v)
    if isinstance(v, tuple):
        return (3, tuple(value_key(x) for x in v))
    return (4, repr(v))


def row_key(t: Sequence) -> tuple:
    """A total order on tuples that tolerates None. Use it to sort rows in tests."""
    return tuple(value_key(v) for v in t)


# ---------------------------------------------------------------- relations

class Relation:
    """A relation: a schema (tuple of names), a Counter of tuples and a mode."""

    __slots__ = ("schema", "rows", "mode")

    def __init__(self, schema: Sequence[str], rows: Iterable | Mapping = (), mode: str = BAG) -> None:
        if mode not in MODES:
            raise ValueError("mode must be 'bag' or 'set'")
        schema = tuple(schema)
        if len(set(schema)) != len(schema):
            raise ValueError("duplicate attribute in schema %r" % (schema,))
        counts: Counter = Counter()
        items = rows.items() if isinstance(rows, Mapping) else ((t, 1) for t in rows)
        for t, c in items:
            t = tuple(t)
            if len(t) != len(schema):
                raise ValueError("tuple %r does not fit schema %r" % (t, schema))
            if c < 0:
                raise ValueError("negative count for %r" % (t,))
            if c:
                counts[t] += c
        if mode == SET:
            counts = Counter({t: 1 for t in counts})
        self.schema = schema
        self.rows = counts
        self.mode = mode

    def index(self, attr: str) -> int:
        return self.schema.index(attr)

    def reorder(self, schema: Sequence[str]) -> "Relation":
        """The same relation with its columns in the order of schema."""
        schema = tuple(schema)
        if sorted(schema) != sorted(self.schema):
            raise ValueError("schemas %r and %r differ" % (self.schema, schema))
        pos = [self.schema.index(a) for a in schema]
        return Relation(schema, {tuple(t[i] for i in pos): c for t, c in self.rows.items()}, self.mode)

    def with_mode(self, mode: str) -> "Relation":
        return Relation(self.schema, self.rows, mode)

    def as_dict(self, t: Sequence) -> dict:
        return dict(zip(self.schema, t))

    def sorted_rows(self) -> list:
        """Every tuple, repeated by its count, in row_key order."""
        out = []
        for t in sorted(self.rows, key=row_key):
            out.extend([t] * self.rows[t])
        return out

    def __iter__(self):
        return iter(self.sorted_rows())

    def __len__(self) -> int:
        return sum(self.rows.values())

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Relation):
            return NotImplemented
        if sorted(self.schema) != sorted(other.schema):
            return False
        return self.rows == other.reorder(self.schema).rows

    def __repr__(self) -> str:
        body = ", ".join("%r: %d" % (t, self.rows[t]) for t in sorted(self.rows, key=row_key))
        return "Relation(%r, {%s}, %r)" % (self.schema, body, self.mode)


def _mode2(r: Relation, s: Relation) -> str:
    if r.mode != s.mode:
        raise ValueError("operands have modes %r and %r" % (r.mode, s.mode))
    return r.mode


def _same_schema(r: Relation, s: Relation) -> Relation:
    """s with its columns in the order of r; the attribute sets must be equal."""
    if sorted(r.schema) != sorted(s.schema):
        raise ValueError("union-incompatible schemas %r and %r" % (r.schema, s.schema))
    return s.reorder(r.schema)


# ---------------------------------------------------------------- three-valued logic

def tv_and(a: bool | None, b: bool | None) -> bool | None:
    if a is False or b is False:
        return False
    if a is None or b is None:
        return None
    return True


def tv_or(a: bool | None, b: bool | None) -> bool | None:
    if a is True or b is True:
        return True
    if a is None or b is None:
        return None
    return False


def tv_not(a: bool | None) -> bool | None:
    return None if a is None else not a


_CMP = {
    "=": 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,
    ">=": lambda x, y: x >= y,
}


def cmp3(op: str, x: object, y: object) -> bool | None:
    """SQL comparison: None (UNKNOWN) if either side is NULL."""
    if op not in _CMP:
        raise ValueError("unknown comparison %r" % (op,))
    if x is None or y is None:
        return None
    return bool(_CMP[op](x, y))


def is_true(v: bool | None) -> bool:
    """The WHERE test: only True passes; False and None (UNKNOWN) do not."""
    return v is True


# ---------------------------------------------------------------- operators

def select(rel: Relation, pred: Callable[[dict], bool | None]) -> Relation:
    out = {t: c for t, c in rel.rows.items() if pred(rel.as_dict(t)) is True}
    return Relation(rel.schema, out, rel.mode)


where = select


def project(rel: Relation, attrs: Sequence[str]) -> Relation:
    attrs = tuple(attrs)
    pos = [rel.index(a) for a in attrs]
    out: Counter = Counter()
    for t, c in rel.rows.items():
        out[tuple(t[i] for i in pos)] += c
    return Relation(attrs, out, rel.mode)


def rename(rel: Relation, mapping: Mapping[str, str]) -> Relation:
    for a in mapping:
        if a not in rel.schema:
            raise ValueError("no attribute %r to rename" % (a,))
    return Relation(tuple(mapping.get(a, a) for a in rel.schema), rel.rows, rel.mode)


def union(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = Counter(r.rows)
    out.update(s.rows)
    return Relation(r.schema, out, mode)


def difference(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = {t: max(0, c - s.rows.get(t, 0)) for t, c in r.rows.items()}
    return Relation(r.schema, out, mode)


def intersection(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = {t: min(c, s.rows.get(t, 0)) for t, c in r.rows.items()}
    return Relation(r.schema, out, mode)


def product(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    if common:
        raise ValueError("product needs disjoint schemas; common: %r" % (common,))
    out: Counter = Counter()
    for t, c in r.rows.items():
        for u, d in s.rows.items():
            out[t + u] += c * d
    return Relation(r.schema + s.schema, out, mode)


def _matches(r: Relation, s: Relation, t: tuple, u: tuple, common: Sequence[str]) -> bool:
    for a in common:
        x, y = t[r.index(a)], u[s.index(a)]
        if x is None or y is None or x != y:
            return False
    return True


def natural_join(r: Relation, s: Relation) -> Relation:
    """Nested loops over both inputs. With no common attribute it is the product."""
    mode = _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    rest = [a for a in s.schema if a not in common]
    rest_pos = [s.index(a) for a in rest]
    out: Counter = Counter()
    for t, c in r.rows.items():
        for u, d in s.rows.items():
            if _matches(r, s, t, u, common):
                out[t + tuple(u[i] for i in rest_pos)] += c * d
    return Relation(r.schema + tuple(rest), out, mode)


def theta_join(r: Relation, s: Relation, pred: Callable[[dict], bool | None]) -> Relation:
    return select(product(r, s), pred)


def semijoin(r: Relation, s: Relation) -> Relation:
    """Rows of r (with their counts) that join with at least one row of s."""
    _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    out = {t: c for t, c in r.rows.items() if any(_matches(r, s, t, u, common) for u in s.rows)}
    return Relation(r.schema, out, r.mode)


def antijoin(r: Relation, s: Relation) -> Relation:
    """Rows of r (with their counts) that join with no row of s."""
    _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    out = {t: c for t, c in r.rows.items() if not any(_matches(r, s, t, u, common) for u in s.rows)}
    return Relation(r.schema, out, r.mode)


def distinct(rel: Relation) -> Relation:
    return Relation(rel.schema, {t: 1 for t in rel.rows}, rel.mode)


AGG_FUNCS = ("count_star", "count", "count_distinct", "sum", "avg", "min", "max")


def _avg(vals: list) -> object:
    total = sum(vals)
    if all(isinstance(v, (int, Fraction)) for v in vals):
        return Fraction(total, 1) / len(vals)
    return total / len(vals)


def agg_value(func: str, vals: list) -> object:
    """One SQL aggregate over a list of column values (with repeats). count_star counts all."""
    if func == "count_star":
        return len(vals)
    nn = [v for v in vals if v is not None]
    if func == "count":
        return len(nn)
    if func == "count_distinct":
        seen: list = []
        for v in nn:
            if v not in seen:
                seen.append(v)
        return len(seen)
    if not nn:
        return None
    if func == "sum":
        return sum(nn)
    if func == "avg":
        return _avg(nn)
    if func == "min":
        return min(nn)
    if func == "max":
        return max(nn)
    raise ValueError("unknown aggregate %r" % (func,))


def aggregate(rel: Relation, group_attrs: Sequence[str], aggs: Sequence[tuple]) -> Relation:
    """gamma_{G; f(A) -> B}(rel) by definition.

    aggs is a list of (func, attr, out); attr is ignored for count_star and may
    be None. For each distinct group key, in row_key order, the whole input is
    scanned. Each result row has count 1 in either mode.
    """
    group_attrs = tuple(group_attrs)
    gpos = [rel.index(a) for a in group_attrs]
    for func, attr, _ in aggs:
        if func not in AGG_FUNCS:
            raise ValueError("unknown aggregate %r" % (func,))
        if func != "count_star":
            rel.index(attr)
    keys: list = []
    for t in rel.rows:
        k = tuple(t[i] for i in gpos)
        if k not in keys:
            keys.append(k)
    if not group_attrs and not keys:
        keys = [()]
    out: Counter = Counter()
    for k in sorted(keys, key=row_key):
        row = list(k)
        for func, attr, _ in aggs:
            vals: list = []
            for t, c in rel.rows.items():
                if tuple(t[i] for i in gpos) == k:
                    vals.extend([None if func == "count_star" else t[rel.index(attr)]] * c)
            row.append(agg_value(func, vals))
        out[tuple(row)] = 1
    schema = group_attrs + tuple(o for _, _, o in aggs)
    return Relation(schema, out, rel.mode)


# ---------------------------------------------------------------- evaluation

def evaluate(expr: tuple, db: Mapping[str, Relation], mode: str = BAG) -> Relation:
    """Evaluate an expression tree of nested tuples over db, in mode."""
    if mode not in MODES:
        raise ValueError("mode must be 'bag' or 'set'")
    op = expr[0]
    ev = lambda e: evaluate(e, db, mode)
    if op == "scan":
        return db[expr[1]].with_mode(mode)
    if op == "select":
        return select(ev(expr[2]), expr[1])
    if op == "project":
        return project(ev(expr[2]), expr[1])
    if op == "rename":
        return rename(ev(expr[2]), expr[1])
    if op == "distinct":
        return distinct(ev(expr[1]))
    if op == "aggregate":
        return aggregate(ev(expr[3]), expr[1], expr[2])
    if op == "theta_join":
        return theta_join(ev(expr[2]), ev(expr[3]), expr[1])
    binary = {
        "union": union, "difference": difference, "intersection": intersection,
        "product": product, "join": natural_join, "semijoin": semijoin, "antijoin": antijoin,
    }
    if op in binary:
        return binary[op](ev(expr[1]), ev(expr[2]))
    raise ValueError("unknown operator %r" % (op,))


# ---------------------------------------------------------------- disk

def paginate(rows: Sequence, per_page: int) -> list:
    """Split rows into pages of per_page rows; the last page may be shorter."""
    if per_page < 1:
        raise ValueError("per_page must be at least 1")
    rows = list(rows)
    return [rows[i:i + per_page] for i in range(0, len(rows), per_page)]


class Disk:
    """Pages on a simulated disk. Each read_page and write_page call costs one I/O."""

    def __init__(self) -> None:
        self.pages: dict = {}
        self.reads = 0
        self.writes = 0
        self._next = 0

    def alloc(self) -> int:
        pid = self._next
        self._next += 1
        self.pages[pid] = ()
        return pid

    def write_page(self, pid: int, rows: Iterable) -> None:
        if pid not in self.pages:
            raise KeyError("page %r was not allocated" % (pid,))
        self.pages[pid] = tuple(rows)
        self.writes += 1

    def read_page(self, pid: int) -> list:
        self.reads += 1
        return list(self.pages[pid])

    def free(self, pid: int) -> None:
        del self.pages[pid]

    def load(self, rows: Sequence, per_page: int) -> list:
        """Store an input file without counting I/O; return its page ids in order."""
        ids = []
        for page in paginate(rows, per_page):
            pid = self.alloc()
            self.pages[pid] = tuple(page)
            ids.append(pid)
        return ids

    def io(self) -> int:
        return self.reads + self.writes

    def reset_counters(self) -> None:
        self.reads = 0
        self.writes = 0


# ---------------------------------------------------------------- random data

def random_relation(rng: random.Random, schema: Sequence[str], n: int,
                    domain: int | Sequence | Mapping = 4, mode: str = BAG,
                    null_rate: float = 0.0) -> Relation:
    """n rows drawn with rng. domain is a size k (values 0 to k - 1), a list of
    values, or a dict from attribute to either. Each value is None with
    probability null_rate. In set mode duplicates collapse, so there may be
    fewer than n rows."""
    schema = tuple(schema)

    def values(a: str) -> list:
        d = domain[a] if isinstance(domain, Mapping) else domain
        return list(range(d)) if isinstance(d, int) else list(d)

    doms = [values(a) for a in schema]
    rows = []
    for _ in range(n):
        t = []
        for d in doms:
            if null_rate and rng.random() < null_rate:
                t.append(None)
            else:
                t.append(rng.choice(d))
        rows.append(tuple(t))
    return Relation(schema, rows, mode)
delta_rules.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delta-rules/. The authors are listed in prov/Q8ZX00.jsonl.

"""Delta rules for the bag relational algebra, applied by structural recursion.

A change is a signed Counter from tuples to nonzero integers: a positive
weight is an insertion of that many copies and a negative weight a deletion.
A bag is a change with only positive weights, and a set is a bag with weights
1. For a database D (dbrel Relations) and a change dD (a dict from relation
names to signed Counters, such that D + dD has no negative counts),
delta(expr, D, dD) returns (schema, dE) with

    E(D + dD) = E(D) + dE.

The rules use the old values E_i(D) of the subexpressions, which the code
computes with dbrel.evaluate. Expressions are the nested tuples of dbrel:
scan, select, project, rename, union (UNION ALL), difference (monus),
intersection (min), distinct, product, join, and aggregate with count_star,
count and sum.
"""

from collections import Counter
from collections.abc import Mapping

import dbrel


def _clean(c: Counter) -> Counter:
    return Counter({t: w for t, w in c.items() if w != 0})


def _reorder(schema_from, schema_to, c: Counter) -> Counter:
    pos = [schema_from.index(a) for a in schema_to]
    out: Counter = Counter()
    for t, w in c.items():
        out[tuple(t[i] for i in pos)] += w
    return out


def zjoin(sr, r: Mapping, ss, s: Mapping):
    """The natural join of two signed Counters: weights multiply. NULL never matches."""
    common = [a for a in sr if a in ss]
    rest = [a for a in ss if a not in common]
    pr = [sr.index(a) for a in common]
    ps = [ss.index(a) for a in common]
    prest = [ss.index(a) for a in rest]
    out: Counter = Counter()
    for t, w in r.items():
        k = tuple(t[i] for i in pr)
        if any(v is None for v in k):
            continue
        for u, x in s.items():
            if tuple(u[i] for i in ps) == k:
                out[t + tuple(u[i] for i in prest)] += w * x
    return tuple(sr) + tuple(rest), _clean(out)


def apply_change(rel: dbrel.Relation, d: Mapping) -> dbrel.Relation:
    """rel + d; raises an error if a count becomes negative."""
    c = Counter(rel.rows)
    for t, w in d.items():
        c[t] += w
    return dbrel.Relation(rel.schema, {t: w for t, w in c.items() if w != 0})


def new_db(db: Mapping, dd: Mapping) -> dict:
    return {name: apply_change(rel, dd.get(name, {})) for name, rel in db.items()}


AGGS = ("count_star", "count", "sum")


def delta(expr: tuple, db: Mapping, dd: Mapping):
    """Return (schema, dE) such that E(db + dd) = E(db) + dE."""
    op = expr[0]
    old = lambda e: dbrel.evaluate(e, db)
    if op == "scan":  # @line L1
        rel = db[expr[1]]
        return rel.schema, _clean(Counter(dd.get(expr[1], {})))
    if op == "select":  # @line L2
        sch, d = delta(expr[2], db, dd)
        return sch, Counter({t: w for t, w in d.items() if expr[1](dict(zip(sch, t))) is True})
    if op == "project":  # @line L3
        sch, d = delta(expr[2], db, dd)
        attrs = tuple(expr[1])
        return attrs, _clean(_reorder(sch, attrs, d))
    if op == "rename":
        sch, d = delta(expr[2], db, dd)
        return tuple(expr[1].get(a, a) for a in sch), d
    if op == "union":  # @line L4
        s1, d1 = delta(expr[1], db, dd)
        s2, d2 = delta(expr[2], db, dd)
        out = Counter(d1)
        out.update(_reorder(s2, s1, d2))
        return s1, _clean(out)
    if op in ("join", "product"):  # @line L5
        e1, e2 = old(expr[1]), old(expr[2])
        s1, d1 = delta(expr[1], db, dd)
        s2, d2 = delta(expr[2], db, dd)
        out: Counter = Counter()
        for a, b in ((d1, e2.reorder(s2).rows), (e1.reorder(s1).rows, d2), (d1, d2)):
            sch, part = zjoin(s1, a, s2, b)
            out.update(part)
        return sch, _clean(out)
    if op in ("difference", "intersection"):  # @line L6
        e1, e2 = old(expr[1]), old(expr[2])
        s1, d1 = delta(expr[1], db, dd)
        s2, d2 = delta(expr[2], db, dd)
        d2 = _reorder(s2, s1, d2)
        o1, o2 = e1.reorder(s1).rows, e2.reorder(s1).rows
        f = (lambda m, n: max(0, m - n)) if op == "difference" else min
        out = Counter()
        for t in set(d1) | set(d2):
            out[t] = f(o1[t] + d1[t], o2[t] + d2[t]) - f(o1[t], o2[t])
        return s1, _clean(out)
    if op == "distinct":  # @line L7
        e1 = old(expr[1])
        s1, d1 = delta(expr[1], db, dd)
        o1 = e1.reorder(s1).rows
        out = Counter({t: int(o1[t] + w > 0) - int(o1[t] > 0) for t, w in d1.items()})
        return s1, _clean(out)
    if op == "aggregate":  # @line L8
        group, aggs, sub = tuple(expr[1]), expr[2], expr[3]
        if any(f not in AGGS for f, _, _ in aggs):
            raise ValueError("only count_star, count and sum have delta rules here")
        e1 = old(sub)
        s1, d1 = delta(sub, db, dd)
        gpos = [s1.index(a) for a in group]
        o1 = e1.reorder(s1).rows
        touched = sorted({tuple(t[i] for i in gpos) for t in d1}, key=dbrel.row_key)
        schema = group + tuple(o for _, _, o in aggs)
        out: Counter = Counter()

        def summary(rows: Mapping, g: tuple):
            """For each aggregate: (count of rows, count of non-null values, sum)."""
            res = []
            for f, attr, _ in aggs:
                n = k = s = 0
                for t, w in rows.items():
                    if tuple(t[i] for i in gpos) != g:
                        continue
                    n += w
                    if f != "count_star" and t[s1.index(attr)] is not None:
                        k += w
                        s += w * t[s1.index(attr)]
                res.append((n, k, s))
            return res

        def row(g: tuple, stats) -> tuple:
            vals = []
            for (f, _, _), (n, k, s) in zip(aggs, stats):
                vals.append(n if f == "count_star" else k if f == "count" else (s if k > 0 else None))
            return g + tuple(vals)

        for g in touched:  # @line L9
            before = summary(o1, g)
            change = summary(d1, g)
            after = [tuple(x + y for x, y in zip(b, c)) for b, c in zip(before, change)]
            n_before, n_after = before[0][0], after[0][0]
            # With no grouping attributes the single result row always exists.
            if n_before > 0 or not group:
                out[row(g, before)] -= 1
            if n_after > 0 or not group:
                out[row(g, after)] += 1
        return schema, _clean(out)
    raise ValueError("no delta rule for %r" % (op,))


def maintain(view: dbrel.Relation, expr: tuple, db: Mapping, dd: Mapping) -> dbrel.Relation:
    """Apply the delta of expr to a materialized view of expr over db."""
    sch, d = delta(expr, db, dd)
    return apply_change(view, _reorder(sch, view.schema, d))
test_delta_rules.py 97 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delta-rules/. The authors are listed in prov/Q8ZX00.jsonl.

import random
from collections import Counter

import dbrel
from delta_rules import delta, maintain, new_db, zjoin

R = ("scan", "R")
S = ("scan", "S")
T = ("scan", "T")

EXPRS = [
    ("join", R, S),
    ("project", ("A",), ("join", R, S)),
    ("select", lambda r: dbrel.cmp3("<>", r["B"], 1), R),
    ("union", R, T),
    ("difference", R, T),
    ("intersection", R, T),
    ("distinct", ("project", ("A",), R)),
    ("aggregate", ("B",), [("count_star", None, "n"), ("sum", "A", "s"), ("count", "A", "k")], ("join", R, S)),
    ("aggregate", (), [("count_star", None, "n"), ("sum", "C", "s")], S),
    ("join", ("join", R, S), ("rename", {"A": "C", "B": "E"}, T)),
    ("difference", ("project", ("A",), R), ("project", ("A",), T)),
    ("distinct", ("difference", R, T)),
    ("product", ("project", ("A",), R), ("rename", {"B": "E", "C": "F"}, S)),
]


def random_db(rng, null_rate=0.1):
    return {
        "R": dbrel.random_relation(rng, ("A", "B"), rng.randrange(0, 9), 3, null_rate=null_rate),
        "S": dbrel.random_relation(rng, ("B", "C"), rng.randrange(0, 9), 3, null_rate=null_rate),
        "T": dbrel.random_relation(rng, ("A", "B"), rng.randrange(0, 9), 3, null_rate=null_rate),
    }


def random_change(rng, db, null_rate=0.1):
    dd = {}
    for name, rel in db.items():
        d = Counter()
        for t, c in rel.rows.items():
            if rng.random() < 0.4:
                d[t] -= rng.randrange(1, c + 1)
        ins = dbrel.random_relation(rng, rel.schema, rng.randrange(0, 4), 3, null_rate=null_rate)
        d.update(ins.rows)
        dd[name] = Counter({t: w for t, w in d.items() if w})
    return dd


def test_page_example() -> None:
    db = {"R": dbrel.Relation(("A", "B"), [(1, 10), (2, 10), (3, 20)]),
          "S": dbrel.Relation(("B", "C"), [(10, "x"), (20, "y")])}
    dd = {"R": Counter({(4, 20): 1, (1, 10): -1}), "S": Counter({(20, "z"): 1})}
    sch, d = delta(("join", R, S), db, dd)
    assert sch == ("A", "B", "C")
    assert d == Counter({(1, 10, "x"): -1, (3, 20, "z"): 1, (4, 20, "y"): 1, (4, 20, "z"): 1})
    # Without the term dR join dS the change misses (4, 20, z).
    _, a = zjoin(("A", "B"), dd["R"], ("B", "C"), db["S"].rows)
    _, b = zjoin(("A", "B"), db["R"].rows, ("B", "C"), dd["S"])
    assert (a + b)[(4, 20, "z")] == 0 and len(+(a + b)) == 2
    # Monus: R has (5, 1) twice, T once; deleting it from T raises R - T from 1 to 2.
    db2 = {"R": dbrel.Relation(("A", "B"), [(5, 1), (5, 1)]), "T": dbrel.Relation(("A", "B"), [(5, 1)])}
    assert delta(("difference", R, T), db2, {"T": Counter({(5, 1): -1})})[1] == Counter({(5, 1): 1})
    # Deleting one of the two copies from R instead lowers R - T to 0.
    assert delta(("difference", R, T), db2, {"R": Counter({(5, 1): -1})})[1] == Counter({(5, 1): -1})


def test_against_recomputation() -> None:
    for seed in range(120):
        rng = random.Random(seed)
        db = random_db(rng)
        for expr in EXPRS:
            view = dbrel.evaluate(expr, db)
            cur = db
            for _ in range(3):
                dd = random_change(rng, cur)
                view = maintain(view, expr, cur, dd)
                cur = new_db(cur, dd)
                assert view == dbrel.evaluate(expr, cur)


def test_only_changed_tuples_appear() -> None:
    # A change that touches no tuple gives an empty delta for every expression.
    rng = random.Random(1)
    db = random_db(rng, 0.0)
    for expr in EXPRS:
        assert not delta(expr, db, {})[1]


def test_set_case_by_distinct() -> None:
    # Set semantics: the view distinct(project_A(R)) changes only when a value appears or disappears.
    db = {"R": dbrel.Relation(("A", "B"), [(1, 1), (1, 2), (2, 1)])}
    expr = ("distinct", ("project", ("A",), R))
    assert delta(expr, db, {"R": Counter({(1, 1): -1})})[1] == Counter()
    assert delta(expr, db, {"R": Counter({(2, 1): -1, (3, 3): 1})})[1] == Counter({(2,): -1, (3,): 1})

Exercises

  1. Give the rule for the semijoin E1⋉E2E_1 \ltimes E_2 under set semantics. Which old values does it need?
  2. Prove the two-term form of the join rule, and give the form that reads the new value of E1E_1 in place of E2E_2.
  3. Find two tables and one deletion for which MIN of a group cannot be found from the old view and the change alone.
  4. A view is πA(R⋈S)\pi_A(R \bowtie S) under bag semantics. Show that the rules need no count of derivations, and say what extra state the set version needs.

References

  1. Efficiently updating materialized views, the differential expressions for select-project-join views, with the three terms of the join, and the multiplicity counters for projections
  2. Incremental recomputation of active relational expressions, the change rules for each operator of the set relational algebra (general locator, volume and pages not checked)
  3. Maintaining views incrementally, the counting algorithm, which applies delta rules to tuples with counts of derivations
  4. Incremental maintenance of views with duplicates, delta rules for the bag algebra, with monus and duplicate elimination, and their correctness
  5. Algorithms for deferred view maintenance, Examples 1.2 and 1.3, which show that a rule written for the state before the update gives wrong results when it is evaluated in the state after the update
  6. Maintenance of materialized views, problems, techniques, and applications, the survey of maintenance methods by view language and kind of change
  7. Mihai Budiu, Tej Chajed, Frank McSherry, Leonid Ryzhyk and Val Tannen, DBSP: automatic incremental view maintenance for rich query languages, PVLDB 16(7), 2023, pages 1601 to 1614, Theorem 3.3 (a linear operator is its own delta) and Theorem 3.4 (the delta of a bilinear operator such as the join)

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)
WritingW3 standard
  • five exercises