Algorithm Search⌘K

Algorithmresearch

Higher-order incremental view maintenance

Also called DBToaster, recursive IVM.

Materialize the deltas of a view, the deltas of those deltas and so on, so each update is applied by simple arithmetic on maps.

Time
O(2^k m) worst · averageO(2^k) best
Space
O(2^k m) extra
Where
k = the number of atoms of the query; m = the largest number of entries in one map
Properties
deterministicexactnot externalnot in placeonlineiterative
Origin
Christoph Koch, 2010

Higher-order incremental view maintenance keeps a query result up to date by storing not only the result but also its delta with respect to each base relation, the deltas of those deltas, and so on, as a hierarchy of maps. Classic incremental view maintenance applies delta rules once and evaluates the delta query, often a join, on every update. Here the delta query is itself maintained, so an update only looks up stored values, multiplies and adds. Koch (2010) gave the idea for queries over a ring of databases, and Ahmad, Kennedy, Koch and Nikolic (2012) call the transformation the viewlet transform, while DBSP and differential dataflow keep the first-order delta and maintain the state of each operator instead.

In plain words

Suppose you keep the total of a sum over a join of three tables. A new row arrives in one table. The change of the total is that row's value times a number that depends on the other two tables. Ordinary maintenance computes that number by a join every time. This algorithm keeps the number in a stored table, ready to read.

That stored table must also change when the other tables change. Its change again has the same form: a value times a number that depends on fewer tables. So you store those numbers too, and so on, until a number depends on no table at all.

After that, a new row only causes reads, products and sums in the stored tables. No join runs.

The problem

The input is a query and a sequence of updates. The query is a sum over a natural join of base relations R1,…,RkR_1, \ldots, R_k with distinct names (no self-join), of the product of some attribute values VALS\mathit{VALS}, grouped by attributes FF:

Q[F]=∑x∈R1⋈⋯⋈Rk∏v∈VALSxv.Q[F] = \sum_{x \in R_1 \bowtie \cdots \bowtie R_k} \prod_{v \in \mathit{VALS}} x_v.

With VALS\mathit{VALS} empty, QQ is COUNT(*). Each relation gives each tuple an integer weight. An update adds a weight ww to one tuple tt of one relation RjR_j: w=1w = 1 is an insertion and w=−1w = -1 a deletion. A set is a Z-set with weights 0 and 1, and distinct maps a Z-set to a set, so sets and bags are special cases. After each update, the current value of QQ must be available.

The algorithm

For a set SS of atoms, let rem\mathrm{rem} be the other atoms and Vars(X)\mathrm{Vars}(X) the attributes of the atoms in XX. The map MSM_S is the delta of QQ with respect to the atoms of SS, with the attributes that connect SS to the rest as its key:

KS=Vars(rem)∩(Vars(S)∪F),MS(y)=∑z∏i∈remRi(y,z)∏v∈VALS, v summedzv,K_S = \mathrm{Vars}(\mathrm{rem}) \cap (\mathrm{Vars}(S) \cup F), \qquad M_S(y) = \sum_{z} \prod_{i \in \mathrm{rem}} R_i(y, z) \prod_{v \in \mathit{VALS},\ v \text{ summed}} z_v,

where zz ranges over the other attributes of rem\mathrm{rem}. Then M∅M_\emptyset is QQ, and MS()=1M_S() = 1 when SS holds all atoms. An update to RjR_j changes MSM_S only for j∉Sj \notin S, and by the delta rule for a product its change is a lookup in MS∪{j}M_{S \cup \{j\}}, which the update does not change.

  1. INIT()
  2. 1for each set S of atoms: M_S ← an empty map; M_all() ← 1
  3. UPDATE(j, t, w) ▷ add weight w to tuple t of R_j
  4. 2for each set S of atoms with j ∉ S do ▷ any order: M_{S ∪ {j}} does not change
  5. 3S' ← S ∪ {j}
  6. 4for each entry (y', c) of M_{S'} that agrees with t on the attributes of R_j do
  7. 5y ← y' together with t, cut to the key K_S
  8. 6M_S[y] ← M_S[y] + w · c · (the product of the values of t in VALS that M_S sums)
  9. 7if M_S[y] = 0 then remove the entry y
  10. RESULT(f)
  11. 8return M_∅[f] times the product of the values of f in VALS

The compiler of Ahmad et al. writes the loop of line L2 for each relation, at compile time, as a trigger program: a short list of statements of the form "map +=\mathrel{+}= value times lookup". Line L4 with a hash index on the attributes of KS′K_{S'} that tt fixes reads only the matching entries.

Example

The query is Q=∑A⋅DQ = \sum A \cdot D over R(A,B)⋈S(B,C)⋈T(C,D)R(A, B) \bowtie S(B, C) \bowtie T(C, D). The six maps below QQ are:

map key definition
MRM_R BB ∑C,DS(b,C) T(C,D) D\sum_{C, D} S(b, C)\, T(C, D)\, D
MSM_S B,CB, C (∑AR(A,b) A)(∑DT(c,D) D)\big(\sum_A R(A, b)\, A\big)\big(\sum_D T(c, D)\, D\big)
MTM_T CC ∑A,BR(A,B) S(B,c) A\sum_{A, B} R(A, B)\, S(B, c)\, A
MRSM_{RS} CC ∑DT(c,D) D\sum_D T(c, D)\, D
MRTM_{RT} B,CB, C S(b,c)S(b, c)
MSTM_{ST} BB ∑AR(A,b) A\sum_A R(A, b)\, A

The trigger for an insertion of (a,b)(a, b) into RR is: Q+=a⋅MR(b)Q \mathrel{+}= a \cdot M_R(b); MS(b,c)+=a⋅MRS(c)M_S(b, c) \mathrel{+}= a \cdot M_{RS}(c) for each cc; MT(c)+=a⋅MRT(b,c)M_T(c) \mathrel{+}= a \cdot M_{RT}(b, c) for each cc; MST(b)+=aM_{ST}(b) \mathrel{+}= a. Five insertions give:

update change of QQ other changes QQ
R(1,10)R(1, 10) 1⋅MR(10)=01 \cdot M_R(10) = 0 MST(10)=1M_{ST}(10) = 1 0
S(10,20)S(10, 20) MS(10,20)=0M_S(10, 20) = 0 MT(20)=1M_T(20) = 1, MRT(10,20)=1M_{RT}(10, 20) = 1 0
T(20,5)T(20, 5) 5⋅MT(20)=55 \cdot M_T(20) = 5 MR(10)=5M_R(10) = 5, MS(10,20)=5M_S(10, 20) = 5, MRS(20)=5M_{RS}(20) = 5 5
R(2,10)R(2, 10) 2⋅MR(10)=102 \cdot M_R(10) = 10 MS(10,20)=15M_S(10, 20) = 15, MT(20)=3M_T(20) = 3, MST(10)=3M_{ST}(10) = 3 15
T(20,7)T(20, 7) 7⋅MT(20)=217 \cdot M_T(20) = 21 MR(10)=12M_R(10) = 12, MS(10,20)=36M_S(10, 20) = 36, MRS(20)=12M_{RS}(20) = 12 36

The last update would cost first-order IVM a join of RR and SS. Here it reads one entry, MT(20)=3M_T(20) = 3. The check: the join has (1+2)⋅(5+7)=36(1 + 2) \cdot (5 + 7) = 36 as its sum of A⋅DA \cdot D. A later deletion of R(1,10)R(1, 10) gives Q=36−1⋅MR(10)=24Q = 36 - 1 \cdot M_R(10) = 24.

Correctness

The claim is that after every update each map equals its definition over the current relations. Since no relation name occurs twice, every map is linear in each relation. So adding ww to the weight of tt in RjR_j changes MSM_S, for j∉Sj \notin S, by ww times the sum with RjR_j fixed to tt. With the attributes of tt fixed, that sum is MS∪{j}M_{S \cup \{j\}} at the matching key, times the values of tt that MSM_S sums over. MS∪{j}M_{S \cup \{j\}} does not contain RjR_j and does not change, so the order of the maps in line L2 does not matter. Induction on the number of updates finishes the proof. The proof never uses positive weights, so the maps are exact for any order of signed updates. The full proof is in the proof page.

Proof: The maps of the viewlet transform stay equal to their definitions after every updatefull

We use the line numbers of the pseudocode on the page. The query has atoms R1,…,RkR_1, \ldots, R_k with distinct relation names (no self-join), variable sets V1,…,VkV_1, \ldots, V_k, value variables VALS\mathit{VALS} and group variables FF. A database gives each relation a function from tuples to integers, the weights, with finitely many nonzero values; negative weights are allowed. For a set XX of atoms, Vars(X)=⋃i∈XVi\mathrm{Vars}(X) = \bigcup_{i \in X} V_i. An assignment to a set of variables WW is a function from WW to values, and Ri(x)R_i(x) means the weight of the tuple x∣Vix|_{V_i} in RiR_i.

Definitions. For each set SS of atoms let rem={1,…,k}∖S\mathrm{rem} = \{1, \ldots, k\} \setminus S and

KS=Vars(rem)∩(Vars(S)∪F),ZS=Vars(rem)∖KS,K_S = \mathrm{Vars}(\mathrm{rem}) \cap (\mathrm{Vars}(S) \cup F), \qquad Z_S = \mathrm{Vars}(\mathrm{rem}) \setminus K_S,
MS(y)=∑z  ∏i∈remRi(y∪z)∏v∈VALS∩ZSzv,M_S(y) = \sum_{z} \; \prod_{i \in \mathrm{rem}} R_i(y \cup z) \prod_{v \in \mathit{VALS} \cap Z_S} z_v,

where yy is an assignment to KSK_S and the sum is over the assignments zz to ZSZ_S. The sum is finite: a term is nonzero only if each (y∪z)∣Vi(y \cup z)|_{V_i} has nonzero weight, and ZS⊆Vars(rem)Z_S \subseteq \mathrm{Vars}(\mathrm{rem}). For SS the set of all atoms, KS=ZS=∅K_S = Z_S = \emptyset, the product is empty, and MS()=1M_S() = 1. For S=∅S = \emptyset, K∅=Vars(all)∩F=FK_\emptyset = \mathrm{Vars}(\text{all}) \cap F = F, so M∅(f)M_\emptyset(f) times ∏v∈VALS∩Ffv\prod_{v \in \mathit{VALS} \cap F} f_v is the query Q[f]Q[f], which is what line L8 returns. The stored map holds the nonzero values of MSM_S.

Lemma 1 (keys). For j∉Sj \notin S and S′=S∪{j}S' = S \cup \{j\}: (a) KS′⊆KS∪VjK_{S'} \subseteq K_S \cup V_j; (b) KS∖Vj⊆KS′K_S \setminus V_j \subseteq K_{S'}; (c) ZS∖Vj=ZS′Z_S \setminus V_j = Z_{S'}.

Proof. Let rem′=rem∖{j}\mathrm{rem}' = \mathrm{rem} \setminus \{j\}, so Vars(rem′)⊆Vars(rem)\mathrm{Vars}(\mathrm{rem}') \subseteq \mathrm{Vars}(\mathrm{rem}) and Vars(rem)∖Vj⊆Vars(rem′)\mathrm{Vars}(\mathrm{rem}) \setminus V_j \subseteq \mathrm{Vars}(\mathrm{rem}'). (a) A variable of KS′K_{S'} is in Vars(rem′)\mathrm{Vars}(\mathrm{rem}') and in Vars(S)∪F∪Vj\mathrm{Vars}(S) \cup F \cup V_j; if it is not in VjV_j it is in Vars(rem)∩(Vars(S)∪F)=KS\mathrm{Vars}(\mathrm{rem}) \cap (\mathrm{Vars}(S) \cup F) = K_S. (b) A variable of KSK_S not in VjV_j is in Vars(rem)∖Vj⊆Vars(rem′)\mathrm{Vars}(\mathrm{rem}) \setminus V_j \subseteq \mathrm{Vars}(\mathrm{rem}') and in Vars(S)∪F⊆Vars(S′)∪F\mathrm{Vars}(S) \cup F \subseteq \mathrm{Vars}(S') \cup F. (c) A variable uu of ZS∖VjZ_S \setminus V_j is in Vars(rem′)\mathrm{Vars}(\mathrm{rem}') and not in Vars(S)∪F\mathrm{Vars}(S) \cup F and not in VjV_j, so not in Vars(S′)∪F\mathrm{Vars}(S') \cup F: u∈ZS′u \in Z_{S'}. Conversely, u∈ZS′u \in Z_{S'} is in $\mathrm{Vars}(\mathrm{rem}) $ and not in Vars(S)∪F∪Vj\mathrm{Vars}(S) \cup F \cup V_j, so u∈ZS∖Vju \in Z_S \setminus V_j. □\square

Lemma 2 (delta of one map). Let the update add ww to the weight of tuple tt in RjR_j, and let τ\tau be the assignment of tt to VjV_j. For j∉Sj \notin S, the change of MSM_S is

ΔMS(y)={w⋅∏v∈VALS∩ZS∩Vjτv⋅MS′((y∪τ)∣KS′)if y agrees with τ on KS∩Vj,0otherwise,\Delta M_S(y) = \begin{cases} w \cdot \prod_{v \in \mathit{VALS} \cap Z_S \cap V_j} \tau_v \cdot M_{S'}\big((y \cup \tau)|_{K_{S'}}\big) & \text{if } y \text{ agrees with } \tau \text{ on } K_S \cap V_j, \\ 0 & \text{otherwise,} \end{cases}

with MS′M_{S'} read before or after the update, which are equal. For j∈Sj \in S, MSM_S does not change.

Proof. If j∈Sj \in S, RjR_j does not occur in the definition of MSM_S. Let j∉Sj \notin S. Because no other atom uses the name RjR_j, the product in the definition is linear in RjR_j: replacing RjR_j by Rj+w[⋅=t]R_j + w[\cdot = t] adds the terms

w∑z[ (y∪z)∣Vj=τ ]∏i∈rem′Ri(y∪z)∏v∈VALS∩ZSzv.w \sum_{z} [\,(y \cup z)|_{V_j} = \tau\,] \prod_{i \in \mathrm{rem}'} R_i(y \cup z) \prod_{v \in \mathit{VALS} \cap Z_S} z_v.

The bracket is zero unless yy agrees with τ\tau on KS∩VjK_S \cap V_j and zz agrees with τ\tau on ZS∩VjZ_S \cap V_j. Then zz is τ\tau on ZS∩VjZ_S \cap V_j and a free assignment z′z' on ZS∖Vj=ZS′Z_S \setminus V_j = Z_{S'} (Lemma 1c). The value factors split into the fixed part ∏v∈VALS∩ZS∩Vjτv\prod_{v \in \mathit{VALS} \cap Z_S \cap V_j} \tau_v and ∏v∈VALS∩ZS′zv′\prod_{v \in \mathit{VALS} \cap Z_{S'}} z'_v. The assignment y∪τy \cup \tau covers KS∪Vj⊇KS′K_S \cup V_j \supseteq K_{S'} (Lemma 1a), and each RiR_i with i∈rem′i \in \mathrm{rem}' reads only variables of Vars(rem′)=KS′∪ZS′\mathrm{Vars}(\mathrm{rem}') = K_{S'} \cup Z_{S'}. So the sum over z′z' is MS′((y∪τ)∣KS′)M_{S'}((y \cup \tau)|_{K_{S'}}) by definition. MS′M_{S'} does not change, because j∈S′j \in S'. □\square

Lemma 3 (the loop of lines L4 to L6 adds exactly ΔMS\Delta M_S). For j∉Sj \notin S, lines L4 to L6 add ΔMS(y)\Delta M_S(y) to entry yy for every yy with ΔMS(y)≠0\Delta M_S(y) \neq 0, and nothing else.

Proof. Line L4 visits each nonzero entry y′y' of MS′M_{S'} that agrees with τ\tau on KS′∩VjK_{S'} \cap V_j, and line L5 sets y=(y′∪τ)∣KSy = (y' \cup \tau)|_{K_S}, which is well defined because y′y' and τ\tau agree where both are defined. The map y′↦yy' \mapsto y is a bijection between these entries and the yy that agree with τ\tau on KS∩VjK_S \cap V_j and have MS′((y∪τ)∣KS′)≠0M_{S'}((y \cup \tau)|_{K_{S'}}) \neq 0: its inverse is y↦(y∪τ)∣KS′y \mapsto (y \cup \tau)|_{K_{S'}}, because KS′⊆KS∪VjK_{S'} \subseteq K_S \cup V_j (Lemma 1a) and KS∖Vj⊆KS′K_S \setminus V_j \subseteq K_{S'} (Lemma 1b), so y′y' determines yy and yy determines y′y'. Line L6 adds ww times the value factor times MS′(y′)M_{S'}(y'), which is ΔMS(y)\Delta M_S(y) by Lemma 2. Every yy with ΔMS(y)≠0\Delta M_S(y) \neq 0 has such a y′y'. □\square

Theorem 1 (correctness). After every sequence of updates, each stored map MSM_S holds exactly the nonzero values of its definition, and line L8 returns QQ over the current relations.

Proof. By induction on the number of updates. At the start every relation is empty, so every MSM_S with SS not the set of all atoms is 00 (each term has a factor Ri=0R_i = 0 with i∈rem≠∅i \in \mathrm{rem} \neq \emptyset), and line L1 creates empty maps and Mall()=1M_{\text{all}}() = 1. For an update, line L2 changes only the maps with j∉Sj \notin S. Each such map reads only MS′M_{S'} with j∈S′j \in S', which line L2 does not change, so the order of the loop does not matter, and by Lemma 3 each MSM_S gets exactly its change. Line L7 removes entries that become 0, so the stored entries are the nonzero values. The statement about line L8 is the case S=∅S = \emptyset. ■\blacksquare

The proof never uses that weights are positive. So the maps are exact for any sequence of signed updates, in any order: the final maps depend only on the final weights.

Termination. Line L2 visits 2k2^k maps, and line L4 visits the finitely many entries of one map.

Space. The stored maps hold ∑S∣MS∣\sum_S |M_S| nonzero entries. Each MSM_S has at most one entry for each assignment to KSK_S that extends tuples of the relations in rem\mathrm{rem}, so with mm the largest number of entries in a map, the space is O(2km)O(2^k m). The work of one update is the number of entries visited at line L4, at most 2km2^k m; with a hash index on the variables KS′∩VjK_{S'} \cap V_j of each map, only the matching entries are visited. □\square

Complexity

The costs are per update, in the word RAM model with hash maps, so lookups take expected O(1)O(1) time.

  • Time. An update to RjR_j touches the 2k−12^{k-1} maps MSM_S with j∉Sj \notin S, and for each it visits the matching entries of one child map. When the update fixes the whole key of each child, as for the update of TT in the example, each map costs one lookup and the total is O(2k)O(2^k) expected time. In the worst case a child has mm matching entries, which gives O(2km)O(2^k m). These are bounds for each single update, in expectation over the hash function, not amortized.
  • Memory. The maps hold at most 2km2^k m entries. A map can be much larger than the relations: MSM_S in the example has an entry for each pair of a BB value and a CC value.
  • Reading. RESULT costs O(1)O(1) expected time per group. The query is never evaluated.

In Koch's calculus each delta lowers the degree of the query in the relations by one, so the hierarchy ends after kk levels with constants. He shows that for this calculus each update can be done with the full hierarchy in NC0, constant parallel time.

Properties

  • Exact. The maps are equal to their definitions after every update, not approximate.
  • Online, with constant work for many updates. The work of an update does not depend on the size of the relations when each lookup has one match.
  • Order independent and safe for late data. The maps depend only on the current weights. A late update, or a deletion that arrives before its insertion and leaves a weight of -1 for a while, is applied when it arrives, and the maps are exact for the weights at that moment.
  • No base relations. The maps include the needed parts of the relations, so the view and its maps together are self-maintainable.

Variants and improvements

  • Factorized maps. MSM_S in the example is the product of MSTM_{ST} and MRSM_{RS}. A compiler can store such a map as the product of two smaller maps, which saves space and work.
  • Self-joins. With a relation that occurs twice, the delta of a product has the extra term ΔR⋅ΔR\Delta R \cdot \Delta R, and the child map changes during the update. The full viewlet transform handles this with the rules of the ring.
  • Choosing maps. Not every map needs to be stored. A map can be computed from the relations at update time when that is cheaper, which mixes first-order and higher-order maintenance.
  • Nested aggregates and inequality joins. The full compiler accepts a larger calculus, with nested aggregates and inequality joins, in which some deltas are not simpler than the query. For those parts a map is not always the cheapest choice.
  • Batches. An update can carry many tuples. The same triggers apply, with a loop over the batch or with a join of the batch and the child map.
  • Other rings. The construction needs only addition, multiplication and inverses for deletions, so it works for any ring of values, as in provenance semirings with negatives.

When to use it

Use it for SUM and COUNT queries over joins that must be fresh after every update, with many small updates and a fixed query, such as live dashboards and order books. Prefer first-order incremental view maintenance when the maps would be much larger than the relations, when updates come in large batches, or when the query uses MIN, MAX or distinct, which have no inverse.

Pitfalls

  • Map blowup. There are 2k2^k maps, and a map keyed by several attributes of different relations can hold a product of their domains. Check the key of each map before storing it.
  • Self-joins treated as distinct relations. Renaming one copy of RR and updating only it gives a wrong result. Both copies change at once, and the ΔR⋅ΔR\Delta R \cdot \Delta R term is needed.
  • MIN and MAX. They are not ring operations: a deletion of the current minimum cannot be undone by subtraction. These need the base data or a sorted structure per group.
  • Updates inside the loop. Line L2 is correct in any order only because the child MS∪{j}M_{S \cup \{j\}} does not change. Code that also updates the children in the same pass must read the old values.
  • Floating-point values. With floats, the sum of many additions and subtractions drifts, and an entry that should be 0 is not removed at line L7. Use exact numbers or remove entries below a tolerance.

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.

higher_order_ivm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/higher-order-ivm/. The authors are listed in prov/0ABZ30.jsonl.

"""Higher-order incremental view maintenance by the viewlet transform.

The query is a sum over a natural join of distinct relations (no self-join):

    Q[F] = SUM over the join of R_1, ..., R_k of the product of the values x_v, v in VALS,

grouped by the variables F. Relations have integer weights (a weight w > 0 is
w copies, w < 0 is a deletion). With VALS empty, Q is COUNT(*).

For each set S of atoms other than the set of all atoms, the program keeps a
map M_S, the delta of Q with respect to the atoms of S. With rem the atoms not
in S and Vars(X) the variables of the atoms in X:

    K_S = Vars(rem) & (Vars(S) | F)          the key of M_S
    Z_S = Vars(rem) - K_S                    the variables summed out
    M_S(y) = SUM over z of PROD_{i in rem} R_i(y, z) * PROD_{v in VALS & Z_S} z_v

M_{} is Q (without the value factors of F), and M_{all atoms}() = 1. An update
of tuple t with weight w to atom j changes only the maps with j not in S, and

    M_S(y) += w * PROD_{v in VALS & Z_S & V_j} t_v * M_{S + j}(y'),

where y' runs over the entries of M_{S + j} that agree with t, and y is y' with t,
cut to K_S. No join is evaluated: every update is lookups, products and sums.
"""

from collections import Counter
from collections.abc import Mapping, Sequence


class HigherOrderIVM:
    def __init__(self, atoms: Mapping[str, Sequence[str]], vals: Sequence[str] = (),
                 group: Sequence[str] = ()) -> None:
        self.names = list(atoms)
        self.vars = {n: tuple(atoms[n]) for n in self.names}
        for n, vs in self.vars.items():
            if len(set(vs)) != len(vs):
                raise ValueError("atom %r repeats a variable" % n)
        allv = set().union(*map(set, self.vars.values()))
        if not set(vals) <= allv or not set(group) <= allv:
            raise ValueError("unknown variable in vals or group")
        self.vals = frozenset(vals)
        self.group = tuple(group)
        self.full = frozenset(self.names)
        self.key: dict = {}
        self.zvars: dict = {}
        self.maps: dict = {}
        k = len(self.names)
        for mask in range(1 << k):  # @line L1
            s = frozenset(self.names[i] for i in range(k) if mask >> i & 1)
            rem = self.full - s
            vrem = set().union(*(set(self.vars[n]) for n in rem)) if rem else set()
            vs = set().union(*(set(self.vars[n]) for n in s)) if s else set()
            key = tuple(sorted(vrem & (vs | set(self.group))))
            self.key[s] = key
            self.zvars[s] = vrem - set(key)
            self.maps[s] = Counter({(): 1}) if s == self.full else Counter()
        self.work = 0

    def update(self, name: str, t: Sequence, w: int = 1) -> None:
        """Apply weight w of tuple t to relation name."""
        vj = self.vars[name]
        if len(t) != len(vj):
            raise ValueError("tuple %r does not fit %r" % (t, vj))
        bind = dict(zip(vj, t))
        # The child S + j does not contain j, so the order of the maps does not matter.
        for s in self.maps:  # @line L2
            if name in s:
                continue
            child = s | {name}  # @line L3
            ckey = self.key[child]
            factor = w
            for v in self.vals & self.zvars[s] & set(vj):
                factor *= bind[v]
            out = self.maps[s]
            for yc, c in list(self.maps[child].items()):  # @line L4
                self.work += 1
                env = dict(zip(ckey, yc))
                if any(env[v] != bind[v] for v in ckey if v in bind):
                    continue
                env.update(bind)
                y = tuple(env[v] for v in self.key[s])  # @line L5
                out[y] += factor * c  # @line L6
                if out[y] == 0:
                    del out[y]  # @line L7

    def result(self) -> dict:
        """Q as a dict from group values (in the order of group) to the sum; zero groups are absent."""
        top = self.maps[frozenset()]
        pos = [self.key[frozenset()].index(v) for v in self.group]
        res = {}
        for y, c in top.items():  # @line L8
            g = tuple(y[i] for i in pos)
            for v, x in zip(self.key[frozenset()], y):
                if v in self.vals:
                    c *= x
            if c:
                res[g] = c
        return res


def brute_force(atoms: Mapping[str, Sequence[str]], rels: Mapping[str, Mapping], vals=(), group=()) -> dict:
    """Q by enumeration of the join of the weighted relations, for tests."""
    names = list(atoms)
    envs = [({}, 1)]
    for n in names:
        nxt = []
        for env, wt in envs:
            for t, w in rels.get(n, {}).items():
                if any(env.get(v, x) != x for v, x in zip(atoms[n], t)):
                    continue
                e = dict(env)
                e.update(zip(atoms[n], t))
                nxt.append((e, wt * w))
        envs = nxt
    res: Counter = Counter()
    for env, wt in envs:
        for v in vals:
            wt *= env[v]
        res[tuple(env[v] for v in group)] += wt
    return {g: c for g, c in res.items() if c}


def map_definition(ivm: HigherOrderIVM, rels: Mapping[str, Mapping], s: frozenset) -> dict:
    """M_S by its definition, for tests: the sum over the atoms not in S, grouped by K_S."""
    rem = [n for n in ivm.names if n not in s]
    sub = {n: ivm.vars[n] for n in rem}
    vals = tuple(sorted(ivm.vals & ivm.zvars[s]))
    if not rem:
        return {(): 1}
    return brute_force(sub, rels, vals, ivm.key[s])
test_higher_order_ivm.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/higher-order-ivm/. The authors are listed in prov/0ABZ30.jsonl.

import random
from collections import Counter

import pytest

from higher_order_ivm import HigherOrderIVM, brute_force, map_definition

CHAIN = {"R": ("A", "B"), "S": ("B", "C"), "T": ("C", "D")}

QUERIES = [
    (CHAIN, ("A", "D"), ()),
    (CHAIN, (), ()),
    (CHAIN, ("C",), ("B",)),
    (CHAIN, ("A",), ("A", "D")),
    ({"R": ("A", "B"), "S": ("B", "C")}, ("A", "C"), ()),
    ({"R": ("A", "B"), "S": ("B", "C"), "T": ("C", "A")}, ("B",), ()),
    ({"R": ("A",), "S": ("B",)}, ("A", "B"), ()),
    ({"R": ("A", "B"), "S": ("A", "C"), "T": ("A", "D"), "U": ("D", "E")}, ("B", "E"), ("A",)),
    ({"R": ("A", "B")}, ("B",), ("A",)),
]


def check_all(ivm, rels, vals, group, atoms):
    assert ivm.result() == brute_force(atoms, rels, vals, group)
    for s in ivm.maps:
        if s != ivm.full:
            assert dict(ivm.maps[s]) == map_definition(ivm, rels, s)


def test_page_example() -> None:
    h = HigherOrderIVM(CHAIN, ("A", "D"))
    ups = [("R", (1, 10)), ("S", (10, 20)), ("T", (20, 5)), ("R", (2, 10)), ("T", (20, 7))]
    got = []
    for n, t in ups:
        h.update(n, t)
        got.append(h.result().get((), 0))
    assert got == [0, 0, 5, 15, 36]
    assert dict(h.maps[frozenset({"R"})]) == {(10,): 12}
    assert dict(h.maps[frozenset({"T"})]) == {(20,): 3}
    assert dict(h.maps[frozenset({"S", "T"})]) == {(10,): 3}
    h.update("R", (1, 10), -1)
    assert h.result() == {(): 24}


def test_against_recomputation() -> None:
    for seed in range(60):
        rng = random.Random(seed)
        for atoms, vals, group in QUERIES:
            h = HigherOrderIVM(atoms, vals, group)
            rels = {n: Counter() for n in atoms}
            for _ in range(25):
                n = rng.choice(list(atoms))
                live = [t for t, c in rels[n].items() if c > 0]
                if live and rng.random() < 0.35:
                    t, w = rng.choice(live), -1
                else:
                    t, w = tuple(rng.randrange(3) for _ in atoms[n]), rng.choice([1, 1, 2])
                h.update(n, t, w)
                rels[n][t] += w
                rels[n] = +rels[n]
                check_all(h, rels, vals, group, atoms)


def test_insert_then_delete_returns_to_empty() -> None:
    rng = random.Random(7)
    h = HigherOrderIVM(CHAIN, ("A", "D"), ("B",))
    ups = [(rng.choice("RST"), (rng.randrange(3), rng.randrange(3))) for _ in range(30)]
    for n, t in ups:
        h.update(n, t)
    for n, t in reversed(ups):
        h.update(n, t, -1)
    assert h.result() == {}
    assert all(not m for s, m in h.maps.items() if s != h.full)


def test_any_order_of_signed_updates() -> None:
    # A deletion may arrive before its insertion; the maps stay exact for negative weights.
    for seed in range(20):
        rng = random.Random(100 + seed)
        ups = [(rng.choice("RST"), (rng.randrange(3), rng.randrange(3)), rng.choice([-1, 1, 2])) for _ in range(20)]
        results = []
        for order in (ups, list(reversed(ups)), rng.sample(ups, len(ups))):
            h = HigherOrderIVM(CHAIN, ("A",), ("D",))
            rels = {n: Counter() for n in CHAIN}
            for n, t, w in order:
                h.update(n, t, w)
                rels[n][t] += w
            rels = {n: Counter({t: c for t, c in r.items() if c}) for n, r in rels.items()}
            check_all(h, rels, ("A",), ("D",), CHAIN)
            results.append(h.result())
        assert results[0] == results[1] == results[2]


def test_rejects_bad_input() -> None:
    with pytest.raises(ValueError):
        HigherOrderIVM({"R": ("A", "A")})
    with pytest.raises(ValueError):
        HigherOrderIVM({"R": ("A",)}, ("Z",))
    h = HigherOrderIVM({"R": ("A", "B")})
    with pytest.raises(ValueError):
        h.update("R", (1,))

History

Koch (2010) set incremental view maintenance in a ring of databases, where tuples have integer multiplicities and deletions are insertions with negative weight. In that ring the delta of a query is again a query, of lower degree, so it can be maintained in the same way, and so on. Ahmad, Kennedy, Koch and Nikolic (2012) built a compiler that turns a SQL query into trigger programs over the maps by the viewlet transform, and showed large speedups over first-order maintenance in their experiments. Koch, Ahmad, Kennedy, Nikolic, Nötzli, Lupei and Shaikhha (2014) gave the full description of the compiler. Budiu, Chajed, McSherry, Ryzhyk and Tannen later gave DBSP, which keeps the first-order delta rules and adds streams and recursion.

References

  1. Christoph Koch, Incremental query evaluation in a ring of databases, Proceedings of ACM PODS 2010, pages 87 to 98, the ring of databases with integer multiplicities, the aggregation calculus and its delta queries, the drop in degree with each delta, and the result that maintaining all higher-order deltas puts each update in NC0 for this calculus (the theorem number is not checked)
  2. Yanif Ahmad, Oliver Kennedy, Christoph Koch and Milos Nikolic, DBToaster, higher-order delta processing for dynamic, frequently fresh views, PVLDB 5(10), 2012, pages 968 to 979, the viewlet transform, which compiles a query into a hierarchy of maps and one trigger program per relation and kind of update
  3. Christoph Koch, Yanif Ahmad, Oliver Kennedy, Milos Nikolic, Andres Nötzli, Daniel Lupei and Amir Shaikhha, DBToaster, higher-order delta processing for dynamic, frequently fresh views, The VLDB Journal 23(2), 2014, pages 253 to 278, the full compiler, with the choice and factorization of the maps, nested aggregates, and the experiments (general locator)

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 time.average
  • a full proof of time.best
  • a full proof of time.worst
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