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.
- Solves
- View maintenance problem
- 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
- Model
- Word RAM
- Properties
- deterministicexactnot externalnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with distinct names (no self-join), of the product of some attribute values , grouped by attributes :
With empty, is COUNT(*). Each relation gives each tuple an integer weight. An update adds a weight to one tuple of one relation : is an insertion and 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 must be available.
The algorithm
For a set of atoms, let be the other atoms and the attributes of the atoms in . The map is the delta of with respect to the atoms of , with the attributes that connect to the rest as its key:
where ranges over the other attributes of . Then is , and when holds all atoms. An update to changes only for , and by the delta rule for a product its change is a lookup in , which the update does not change.
INIT()- 1
for each set S of atoms: M_S ← an empty map; M_all() ← 1 UPDATE(j, t, w) ▷ add weight w to tuple t of R_j- 2
for each set S of atoms with j ∉ S do ▷ any order: M_{S ∪ {j}} does not change - 3
S' ← S ∪ {j} - 4
for each entry (y', c) of M_{S'} that agrees with t on the attributes of R_j do - 5
y ← y' together with t, cut to the key K_S - 6
M_S[y] ← M_S[y] + w · c · (the product of the values of t in VALS that M_S sums) - 7
if M_S[y] = 0 then remove the entry y RESULT(f)- 8
return 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 value times lookup". Line L4 with a hash index on the attributes of that fixes reads only the matching entries.
Example
The query is over . The six maps below are:
| map | key | definition |
|---|---|---|
The trigger for an insertion of into is: ; for each ; for each ; . Five insertions give:
| update | change of | other changes | |
|---|---|---|---|
| 0 | |||
| , | 0 | ||
| , , | 5 | ||
| , , | 15 | ||
| , , | 36 |
The last update would cost first-order IVM a join of and . Here it reads one entry, . The check: the join has as its sum of . A later deletion of gives .
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 to the weight of in changes , for , by times the sum with fixed to . With the attributes of fixed, that sum is at the matching key, times the values of that sums over. does not contain 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 with distinct relation names (no self-join), variable sets , value variables and group variables . 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 of atoms, . An assignment to a set of variables is a function from to values, and means the weight of the tuple in .
Definitions. For each set of atoms let and
where is an assignment to and the sum is over the assignments to . The sum is finite: a term is nonzero only if each has nonzero weight, and . For the set of all atoms, , the product is empty, and . For , , so times is the query , which is what line L8 returns. The stored map holds the nonzero values of .
Lemma 1 (keys). For and : (a) ; (b) ; (c) .
Proof. Let , so and . (a) A variable of is in and in ; if it is not in it is in . (b) A variable of not in is in and in . (c) A variable of is in and not in and not in , so not in : . Conversely, is in $\mathrm{Vars}(\mathrm{rem}) $ and not in , so .
Lemma 2 (delta of one map). Let the update add to the weight of tuple in , and let be the assignment of to . For , the change of is
with read before or after the update, which are equal. For , does not change.
Proof. If , does not occur in the definition of . Let . Because no other atom uses the name , the product in the definition is linear in : replacing by adds the terms
The bracket is zero unless agrees with on and agrees with on . Then is on and a free assignment on (Lemma 1c). The value factors split into the fixed part and . The assignment covers (Lemma 1a), and each with reads only variables of . So the sum over is by definition. does not change, because .
Lemma 3 (the loop of lines L4 to L6 adds exactly ). For , lines L4 to L6 add to entry for every with , and nothing else.
Proof. Line L4 visits each nonzero entry of that agrees with on , and line L5 sets , which is well defined because and agree where both are defined. The map is a bijection between these entries and the that agree with on and have : its inverse is , because (Lemma 1a) and (Lemma 1b), so determines and determines . Line L6 adds times the value factor times , which is by Lemma 2. Every with has such a .
Theorem 1 (correctness). After every sequence of updates, each stored map holds exactly the nonzero values of its definition, and line L8 returns over the current relations.
Proof. By induction on the number of updates. At the start every relation is empty, so every with not the set of all atoms is (each term has a factor with ), and line L1 creates empty maps and . For an update, line L2 changes only the maps with . Each such map reads only with , which line L2 does not change, so the order of the loop does not matter, and by Lemma 3 each 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 .
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 maps, and line L4 visits the finitely many entries of one map.
Space. The stored maps hold nonzero entries. Each has at most one entry for each assignment to that extends tuples of the relations in , so with the largest number of entries in a map, the space is . The work of one update is the number of entries visited at line L4, at most ; with a hash index on the variables of each map, only the matching entries are visited.
Complexity
The costs are per update, in the word RAM model with hash maps, so lookups take expected time.
- Time. An update to touches the maps with , 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 in the example, each map costs one lookup and the total is expected time. In the worst case a child has matching entries, which gives . These are bounds for each single update, in expectation over the hash function, not amortized.
- Memory. The maps hold at most entries. A map can be much larger than the relations: in the example has an entry for each pair of a value and a value.
- Reading. RESULT costs 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 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. in the example is the product of and . 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 , 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 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 and updating only it gives a wrong result. Both copies change at once, and the 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 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.
# 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 0ABZ30 Edit this page History Report an error Markdown