Algorithmresearch
Differential dataflow
Also called differential computation.
Incremental computation for iterative dataflow programs that keeps differences indexed by a partial order of versions and iterations.
- Solves
- View maintenance problem
- Time
- O(d n) worstO(d log n) averageO(d) best
- Space
- O(n) extra
- Where
- d = the number of differences that one epoch adds to all traces; n = the number of differences stored in all traces
- Model
- Word RAM
- Properties
- deterministicexactnot externalnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Frank McSherry, Derek G. Murray, Rebecca Isaacs, Michael Isard, 2013
Differential dataflow is an algorithm for incremental computation of dataflow programs with loops, in which each collection is stored as differences, signed changes indexed by times that form a partial order, such as pairs of an input epoch and a loop iteration. A change to the input at a later epoch then reuses the work of every earlier epoch at the same iteration, so a small input change causes a small amount of work even inside an iteration. Incremental view maintenance and delta rules handle one dimension of change, and semi-naive evaluation handles only the iterations of one fixed input, while differential dataflow handles both at once. DBSP restates the idea with nested streams in place of a partial order, and timely dataflow is the runtime model that it was built on.
In plain words
Think of a computation that repeats a step until nothing changes, such as finding every place you can reach from a start point. Now the map changes a little, and you want the new answer.
Starting again from zero repeats almost all of the old work. Keeping only the old final answer is not enough, because the new run would redo the old steps.
So you keep, for each step of the old run, only what changed at that step. For the new run you record, for each step, only how it differs from the same step of the old run. Most of those records are empty, so most of the work is skipped. Each stored change is labeled with two numbers, the version of the input and the step, and a result is the sum of all labeled changes that are not later in either number.
The problem
The input is a sequence of epochs. Each epoch brings a change to the input collections: here a set of roots and a bag of directed edges . The program is an iterative dataflow: here graph reachability,
where keeps the target of each joined edge. After each epoch the output is for every , and in particular its limit, the set of nodes reachable from the roots, which breadth-first search also computes. A collection is a Z-set, a bag with integer weights. A set is a Z-set with weights 0 and 1, and distinct maps a Z-set to a set.
The algorithm
Times are pairs with the product order: when and . This is a partial order: and are not comparable. Every two times have a least upper bound , the pair of the maxima. A trace maps times to signed bags, and the collection at is the sum of over all . By Möbius inversion on this order the difference at is unique: is the collection at minus the collections at and , plus the collection at .
The dataflow has the inputs roots and edges, a feedback edge fed that holds R one iteration later, a join, a union and a distinct. An epoch is processed one iteration at a time.
ADVANCE(e, Δroots, Δedges)- 1
roots[(e, 0)] ← Δroots; edges[(e, 0)] ← Δedges ▷ input changes enter at iteration 0 - 2
for i ← 0, 1, 2, ... while i ≤ i_max or R[(e, i - 1)] ≠ 0 do ▷ i_max: the largest iteration stored t ← (e, i)- 3
if i > 0 then fed[t] ← R[(e, i - 1)] ▷ the feedback edge adds 1 to the iteration - 4
J[t] ← the sum over all s, u with s ∨ u = t of dst(fed[s] ⋈ edges[u]) - 5
U[t] ← roots[t] + J[t] - 6
if U[t] ≠ 0 then C ← C ∪ {t} ∪ {t ∨ c : c ∈ C} ▷ the closure of the times at which U changes - 7
if t ∈ C then - 8
R[t] ← distinct(the collection U at t) - (the sum of R[s] over s ≤ t, s ≠ t)
Line L4 is the differential join. The join is bilinear, so the join of the collections at is the sum of the joins of all pairs of differences at times , and a pair contributes from time on. Line L8 is the differential version of a nonlinear operator: it compares the new output with the accumulated old output. Lines L6 and L7 evaluate it only at the times in the closure of its input times under . At any other time its output difference is 0, so most times cost nothing. A real system keeps each trace as an arrangement, indexed by key, so that line L4 finds the matching differences by a lookup, and runs the dataflow on timely dataflow, which tells each operator when a time is complete.
Example
Epoch 0 has the root 1 and the edges and . Epoch 1 removes and adds and . The differences of R are:
| time | difference of R | R at this time |
|---|---|---|
| +1 | ||
| +1 | ||
| +1 | ||
| none | ||
| +1, -1 | ||
| -1, +1 |
R at is the sum of the differences at , , and , which gives . The difference at removes the 3 that epoch 0 found at iteration 2, since epoch 1 found it at iteration 1. Distinct was evaluated 5 times in all, at the 5 times of the closure. In a second example, a path is computed in epoch 0, and epoch 1 adds the edge . The only difference of epoch 1 is +1 at time , and distinct runs once.
Correctness
The proof is by induction over the times in the order epoch first, then iteration, which lists every smaller time first. The input traces accumulate to the inputs of each epoch at every iteration, because their changes enter at iteration 0. The feedback trace accumulates at to R at . The join trace accumulates to the join of the accumulated inputs, because the join is bilinear and holds exactly when . For distinct, line L8 computes the unique difference, and a short argument on the four terms of the Möbius formula shows that the difference of any function of is 0 outside the closure of the times of . The loop of line L2 can stop once the iteration is past every stored iteration and R did not change at the last one. The full proof is in the proof page.
Proof: Differential reachability stores exactly the differences of every iterate at every timefull
We use the line numbers of the pseudocode on the page. Times are pairs of an epoch and an iteration, with the product order if and only if and . Any two times have a least upper bound . A trace maps times to signed bags, nonzero at finitely many times, and its accumulation is .
The program. The inputs after epoch are and , bags with nonnegative weights. The iterates are and , where has, for each node , the weight . We must show that after epoch has been processed, the trace of R has accumulation at every time with .
Lemma 1 (uniqueness of differences). For every function from times to signed bags with when or , there is exactly one trace with accumulation , namely
If the values for , , are known, then .
Proof. The second statement is the definition of the accumulation at solved for . It fixes each by induction along any order that lists the times below first, which gives uniqueness. The formula has accumulation , because the sum over the rectangle below telescopes.
Lemma 2 (inputs). Line L1 adds the change of epoch at time . So the accumulations of the input traces at are and , for every .
Proof. The times below are those with , and the changes of epochs to add up to the inputs after epoch .
Lemma 3 (join). Let and be traces with accumulations and . The trace of line L4 has accumulation .
Proof. is bilinear, so . And and hold together exactly when . Grouping the pairs by gives .
Lemma 4 (feedback). Line L3 sets for and leaves . If has accumulation , then has accumulation at , and 0 at .
Proof. The times below with correspond one to one to the times below .
Lemma 5 (closure). Let be a trace, the closure of its support under , and any function on signed bags with . The unique trace with accumulation is 0 outside .
Proof. Let , and let be the support times below . If is empty, is 0 at and at the three times below it in Lemma 1, so . Otherwise let . Then and . If has iteration below , every support time below is also below , and every support time below is below . So and , and the four terms of Lemma 1 for cancel. If has iteration , its epoch is below , and the same argument with the roles of the coordinates exchanged applies.
Lemma 6 (distinct). Lines L6 to L8 store, at every processed time , the value of the unique trace with accumulation , provided that the traces are already correct at all times with .
Proof. Line L6 keeps the closure of the support of : adding a time to a set closed under and adding for every in it gives a closed set again, because . Every time added is , so it is processed later or now. If , line L8 computes , which is by Lemma 1. If , nothing is stored, and by Lemma 5.
Lemma 7 (stopping). Let be the largest iteration of a time with a nonzero difference before epoch . If, in epoch , and , then every trace is 0 at every time with , so line L2 may stop.
Proof. By induction on . At , line L3 adds , which is 0. A join pair with needs with iteration , because the edge differences have iteration 0; a time of an earlier epoch has iteration at most , and . So the join and the union are 0 at . A time of with iteration would be a least upper bound of support times of , one of which has iteration ; there is none. So by Lemma 6.
Theorem 1 (correctness). After epoch is processed, each trace holds its unique differences at every time with , and the accumulation of the trace of R at is .
Proof. The times are processed in lexicographic order, epoch first, which lists every with before . The times that are skipped after the stop of an epoch hold 0 in every trace, by Lemma 7. So, by induction along this order, Lemmas 2, 3, 4 and 6 apply at every time with all earlier times correct. Then the union at accumulates to , or to for , and R accumulates to its distinct, which is the definition of .
Termination. For a fixed epoch, , and the step from to is monotone, so . With nodes, the iterates of every epoch are constant from on. Then the four terms of Lemma 1 cancel for every time with , and the condition of Lemma 7 holds for some . Each time costs a finite scan of the traces.
Complexity
The costs are per epoch, in the word RAM model, with the number of differences that the epoch adds to all traces and the number of differences stored.
- Time. With arrangements sorted or hashed by key, each new difference at an operator input is matched with the differences of the same key in the other trace, which costs per lookup in a sorted index, or expected in a hash index, plus the number of matches. So an epoch costs about when each key has few differences. In the worst case one key holds all differences and the cost is . These bounds are per epoch, not amortized, and they count the differences, not the size of the collections.
- Memory. Every difference of every trace is kept, . Systems compact the traces: once no future time can tell two times apart, their differences are added together. This is safe for times below the frontier of timely dataflow.
- Nonlinear operators. For each key, distinct and other nonlinear operators are evaluated at the times of the closure of that key's input times, which can be much larger than the number of input times.
Properties
- Exact. The accumulated collections at every time equal the iterates of the program.
- Incremental in both dimensions. A change at a later epoch reuses all work of earlier epochs at every iteration, and inside an epoch only the changed differences are processed.
- Late data. The epochs are logical. A record that arrives after its epoch has been processed is entered in the current epoch, and the outputs of that epoch and later ones include it. To place records by event time, the input keeps an epoch open until the frontier of timely dataflow, or a watermark, says that it is complete.
- Deterministic. The differences do not depend on the order in which the operators run, only on the times.
Variants and improvements
- Arrangements. Indexed traces shared by many operators and queries, so that a collection is indexed once and read by every join that needs it.
- Compaction. Times that are no longer distinguishable, because the frontier has passed them, are merged, which keeps memory bounded for long-running inputs.
- Other lattices. Any lattice of times works. Nested loops give longer tuples of iteration counters, and the times can be ordered by event time and processing time.
- Nested streams. DBSP keeps the two dimensions as a stream of streams, with a total order on each level, and proves the same rules with simpler algebra.
- Other operators. Grouping and aggregation, top-k, and connected components by label propagation follow the pattern of distinct: compute the output at the closure times, and subtract the accumulated old output.
When to use it
Use it for iterative computations, such as graph reachability, connected components, shortest paths and recursive Datalog queries, over inputs that change in small steps, when each new answer is needed quickly. Prefer recomputation when most of the input changes at each epoch, and semi-naive evaluation when the input never changes.
Pitfalls
- Total order of times. Indexing the differences by a total order, such as epoch first, loses the reuse: the difference at would be taken against only, and every iteration of epoch 1 would redo work. The product order is what lets reuse .
- Missing closure times. Evaluating distinct only at the times at which its input changes is wrong. For example, a difference at and one at can change the output at , where the input has no difference.
- Memory growth. Without compaction, the traces keep every difference of every epoch.
- Many closure times. A key with differences at many incomparable times can have a closure of size quadratic in their number, which makes nonlinear operators slow.
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/differential-dataflow/. The authors are listed in prov/Q08Q0Y.jsonl.
"""Differential computation of graph reachability, with times (epoch, iteration).
A collection that varies with time t is stored as differences: a map from
times to signed Counters, with the collection at t equal to the sum of the
differences at all times s <= t in the product order
(e1, i1) <= (e2, i2) iff e1 <= e2 and i1 <= i2.
The program is the iterative dataflow
R_{e,0} = distinct(roots_e)
R_{e,i+1} = distinct(roots_e + dst(R_{e,i} join edges_e))
where roots_e and edges_e are the inputs after epoch e. The inputs change only
at times (e, 0). The feedback edge moves each difference of R from (e, i) to
(e, i + 1). The join puts the product of differences at s and u at the least
upper bound of s and u, and distinct is evaluated only at the times in the
closure, under least upper bounds, of the times at which its input changes.
The code finds the matching differences by scanning, which is simple and slow;
a real system keeps them in indexed traces.
"""
from collections import Counter
from collections.abc import Iterable, Mapping
def leq(s: tuple, t: tuple) -> bool:
return s[0] <= t[0] and s[1] <= t[1]
def lub(s: tuple, t: tuple) -> tuple:
return (max(s[0], t[0]), max(s[1], t[1]))
def _clean(c: Mapping) -> Counter:
return Counter({k: w for k, w in c.items() if w != 0})
class Trace:
"""Differences of one collection, indexed by time."""
def __init__(self) -> None:
self.diffs: dict = {}
def add(self, t: tuple, d: Mapping) -> None:
d = _clean(d)
if d:
cur = self.diffs.get(t, Counter())
cur.update(d)
cur = _clean(cur)
if cur:
self.diffs[t] = cur
else:
self.diffs.pop(t, None)
def at(self, t: tuple, strict: bool = False) -> Counter:
"""The collection at t: the sum of the differences at times s <= t (s < t if strict)."""
out: Counter = Counter()
for s, d in self.diffs.items():
if leq(s, t) and not (strict and s == t):
out.update(d)
return _clean(out)
def get(self, t: tuple) -> Counter:
return self.diffs.get(t, Counter())
class Reachability:
"""Maintain the nodes reachable from roots as edges and roots change, epoch by epoch."""
def __init__(self) -> None:
self.roots = Trace()
self.edges = Trace()
self.fed = Trace() # R delayed by one iteration
self.join = Trace() # dst(fed join edges)
self.union = Trace() # roots + join, the input of distinct
self.out = Trace() # R
self.closure: set = set()
self.epoch = -1
self.imax = -1 # the largest iteration of any stored time
self.distinct_evals = 0
def _note(self, t: tuple) -> None:
self.imax = max(self.imax, t[1])
def advance(self, d_roots: Mapping = (), d_edges: Mapping = ()) -> None:
"""Apply the changes of the next epoch and run its iterations to the fixed point."""
e = self.epoch + 1
self.epoch = e
self.roots.add((e, 0), Counter(d_roots)) # @line L1
self.edges.add((e, 0), Counter(d_edges))
i = 0
while True:
t = (e, i)
if i > 0 and i > self.imax and not self.out.get((e, i - 1)):
break # @line L2
if i > 0:
self.fed.add(t, self.out.get((e, i - 1))) # @line L3
dj: Counter = Counter()
for s, df in self.fed.diffs.items(): # @line L4
for u, de in self.edges.diffs.items():
if lub(s, u) != t:
continue
for node, w in df.items():
for (a, b), x in de.items():
if a == node:
dj[b] += w * x
self.join.add(t, dj)
du = Counter(self.roots.get(t)) # @line L5
du.update(self.join.get(t))
du = _clean(du)
if du:
self.union.add(t, du)
if t not in self.closure: # @line L6
self.closure |= {lub(t, c) for c in self.closure} | {t}
if t in self.closure: # @line L7
self.distinct_evals += 1
u_t = self.union.at(t)
want = Counter({x: 1 for x, w in u_t.items() if w > 0})
have = self.out.at(t, strict=True)
diff = Counter(want)
diff.subtract(have)
self.out.add(t, diff) # @line L8
for tr in (self.fed, self.join, self.union, self.out):
if t in tr.diffs:
self._note(t)
i += 1
def reachable(self, e: int, i: int | None = None) -> set:
"""R at (e, i), or at the end of the iterations of epoch e if i is None."""
if i is None:
i = max([s[1] for s in self.out.diffs] + [0]) + 1
return {x for x, w in self.out.at((e, i)).items() if w > 0}
def recompute(roots: Iterable, edges: Iterable, i: int) -> set:
"""R_{e,i} from scratch, by the definition of the iteration."""
roots = set(roots)
edges = set(edges)
r = set(roots)
for _ in range(i):
r = roots | {b for a, b in edges if a in r}
return r
def bfs(roots: Iterable, edges: Iterable) -> set:
adj: dict = {}
for a, b in edges:
adj.setdefault(a, []).append(b)
seen = set(roots)
frontier = list(seen)
while frontier:
nxt = []
for a in frontier:
for b in adj.get(a, []):
if b not in seen:
seen.add(b)
nxt.append(b)
frontier = nxt
return seen
test_differential_dataflow.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/differential-dataflow/. The authors are listed in prov/Q08Q0Y.jsonl.
import random
from collections import Counter
from differential_dataflow import Reachability, bfs, leq, lub, recompute
def test_order() -> None:
assert leq((0, 3), (1, 3)) and not leq((0, 3), (1, 2)) and not leq((1, 2), (0, 3))
assert lub((0, 3), (1, 0)) == (1, 3)
def test_page_example() -> None:
rd = Reachability()
rd.advance({1: 1}, {(1, 2): 1, (2, 3): 1})
rd.advance({}, {(1, 2): -1, (1, 3): 1, (3, 4): 1})
diffs = {t: dict(d) for t, d in rd.out.diffs.items()}
assert diffs == {(0, 0): {1: 1}, (0, 1): {2: 1}, (0, 2): {3: 1},
(1, 1): {3: 1, 2: -1}, (1, 2): {3: -1, 4: 1}}
assert rd.reachable(0) == {1, 2, 3}
assert rd.reachable(1) == {1, 3, 4}
assert [rd.reachable(1, i) for i in range(3)] == [{1}, {1, 3}, {1, 3, 4}]
assert rd.distinct_evals == 5
def random_epochs(rng, n, epochs):
roots, edges = Counter(), Counter()
out = []
for e in range(epochs):
dr, de = Counter(), Counter()
for _ in range(rng.randrange(0, 4)):
x = (rng.randrange(n), rng.randrange(n))
de[x] += -1 if edges[x] + de[x] > 0 and rng.random() < 0.5 else 1
if e == 0 or rng.random() < 0.5:
x = rng.randrange(n)
dr[x] += -1 if roots[x] > 0 and rng.random() < 0.5 else 1
roots.update(dr)
edges.update(de)
roots, edges = +roots, +edges
out.append((dr, de, set(roots), set(edges)))
return out
def test_against_recomputation_and_bfs() -> None:
for seed in range(150):
rng = random.Random(seed)
n = rng.randrange(2, 7)
rd = Reachability()
hist = []
for dr, de, roots, edges in random_epochs(rng, n, 6):
rd.advance(dr, de)
hist.append((roots, edges))
for e, (r, g) in enumerate(hist):
for i in range(n + 2):
assert rd.reachable(e, i) == recompute(r, g, i)
assert rd.reachable(e) == bfs(r, g)
def test_differences_are_exact() -> None:
# The stored difference at (e, i) is R(e,i) - R(e-1,i) - R(e,i-1) + R(e-1,i-1),
# so distinct, evaluated only at closure times, misses no time.
def as_counter(s):
return Counter({x: 1 for x in s})
for seed in range(80):
rng = random.Random(1000 + seed)
n = rng.randrange(2, 6)
rd = Reachability()
hist = []
for dr, de, roots, edges in random_epochs(rng, n, 5):
rd.advance(dr, de)
hist.append((roots, edges))
val = {}
for e, (r, g) in enumerate(hist):
for i in range(n + 3):
val[(e, i)] = as_counter(recompute(r, g, i))
for (e, i) in val:
if i == n + 2:
continue
d = Counter(val[(e, i)])
for (de_, di), sign in (((e - 1, i), -1), ((e, i - 1), -1), ((e - 1, i - 1), 1)):
if (de_, di) in val:
for x, w in val[(de_, di)].items():
d[x] += sign * w
d = Counter({x: w for x, w in d.items() if w})
assert d == rd.out.get((e, i))
assert set(rd.out.diffs) <= rd.closure
def test_small_change_touches_few_times() -> None:
# A long path: adding one edge at the end changes R at one time only.
rd = Reachability()
rd.advance({0: 1}, {(k, k + 1): 1 for k in range(20)})
before = rd.distinct_evals
rd.advance({}, {(20, 21): 1})
assert rd.reachable(1) == set(range(22))
assert {t for t in rd.out.diffs if t[0] == 1} == {(1, 21)}
assert rd.distinct_evals - before == 1
History
McSherry, Murray, Isaacs and Isard (2013) introduced differential dataflow at CIDR, with times that combine input versions and loop iterations in a lattice and differences indexed by them, and showed experiments on iterative graph computations over changing inputs. It ran on Naiad, the timely dataflow system of Murray, McSherry, Isaacs, Isard, Barham and Abadi (2013). Later work by McSherry and others added shared arrangements, and Budiu, Chajed, McSherry, Ryzhyk and Tannen gave DBSP (2023), which restates the theory with nested streams.
References
- Differential dataflow, the versions and iterations as a lattice, the differences indexed by its elements, the incremental operators and the loop with its feedback, and the experiments on graph computations (general locator)
- Naiad: a timely dataflow system, the timely dataflow runtime on which differential dataflow ran, with timestamps of an epoch and loop counters (the page numbers are not checked here)
- 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, Section 6, nested streams, which give the same two dimensions of time with one total order per level
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 Q08Q0Y Edit this page History Report an error Markdown