Algorithm Search⌘K

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.

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
Properties
deterministicexactnot externalnot in placeonlineiterative
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 ee brings a change to the input collections: here a set of roots and a bag of directed edges (a,b)(a, b). The program is an iterative dataflow: here graph reachability,

Re,0=distinct(rootse),Re,i+1=distinct(rootse+dst(Re,i⋈edgese)),R_{e,0} = \mathrm{distinct}(\mathit{roots}_e), \qquad R_{e,i+1} = \mathrm{distinct}\big(\mathit{roots}_e + \mathrm{dst}(R_{e,i} \bowtie \mathit{edges}_e)\big),

where dst\mathrm{dst} keeps the target of each joined edge. After each epoch the output is Re,iR_{e,i} for every ii, 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 t=(e,i)t = (e, i) with the product order: (e1,i1)≤(e2,i2)(e_1, i_1) \le (e_2, i_2) when e1≤e2e_1 \le e_2 and i1≤i2i_1 \le i_2. This is a partial order: (0,3)(0, 3) and (1,2)(1, 2) are not comparable. Every two times have a least upper bound s∨us \vee u, the pair of the maxima. A trace XX maps times to signed bags, and the collection at tt is the sum of X[s]X[s] over all s≤ts \le t. By Möbius inversion on this order the difference at tt is unique: X[e,i]X[e, i] is the collection at (e,i)(e, i) minus the collections at (e−1,i)(e - 1, i) and (e,i−1)(e, i - 1), plus the collection at (e−1,i−1)(e - 1, i - 1).

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.

  1. ADVANCE(e, Δroots, Δedges)
  2. 1roots[(e, 0)] ← Δroots; edges[(e, 0)] ← Δedges ▷ input changes enter at iteration 0
  3. 2for i ← 0, 1, 2, ... while i ≤ i_max or R[(e, i - 1)] ≠ 0 do ▷ i_max: the largest iteration stored
  4. t ← (e, i)
  5. 3if i > 0 then fed[t] ← R[(e, i - 1)] ▷ the feedback edge adds 1 to the iteration
  6. 4J[t] ← the sum over all s, u with s ∨ u = t of dst(fed[s] ⋈ edges[u])
  7. 5U[t] ← roots[t] + J[t]
  8. 6if U[t] ≠ 0 then C ← C ∪ {t} ∪ {t ∨ c : c ∈ C} ▷ the closure of the times at which U changes
  9. 7if t ∈ C then
  10. 8R[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 tt is the sum of the joins of all pairs of differences at times s,u≤ts, u \le t, and a pair contributes from time s∨us \vee u 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 ∨\vee. 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 1→21 \to 2 and 2→32 \to 3. Epoch 1 removes 1→21 \to 2 and adds 1→31 \to 3 and 3→43 \to 4. The differences of R are:

time difference of R R at this time
(0,0)(0, 0) 11 +1 {1}\{1\}
(0,1)(0, 1) 22 +1 {1,2}\{1, 2\}
(0,2)(0, 2) 33 +1 {1,2,3}\{1, 2, 3\}
(1,0)(1, 0) none {1}\{1\}
(1,1)(1, 1) 33 +1, 22 -1 {1,3}\{1, 3\}
(1,2)(1, 2) 33 -1, 44 +1 {1,3,4}\{1, 3, 4\}

R at (1,1)(1, 1) is the sum of the differences at (0,0)(0, 0), (0,1)(0, 1), (1,0)(1, 0) and (1,1)(1, 1), which gives {1,3}\{1, 3\}. The difference at (1,2)(1, 2) 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 0→1→⋯→200 \to 1 \to \cdots \to 20 is computed in epoch 0, and epoch 1 adds the edge 20→2120 \to 21. The only difference of epoch 1 is 2121 +1 at time (1,21)(1, 21), 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 (e,i)(e, i) to R at (e,i−1)(e, i - 1). The join trace accumulates to the join of the accumulated inputs, because the join is bilinear and s,u≤ts, u \le t holds exactly when s∨u≤ts \vee u \le t. 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 UU is 0 outside the closure of the times of UU. 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 t=(e,i)t = (e, i) of an epoch and an iteration, with the product order (e1,i1)≤(e2,i2)(e_1, i_1) \le (e_2, i_2) if and only if e1≤e2e_1 \le e_2 and i1≤i2i_1 \le i_2. Any two times have a least upper bound s∨u=(max⁡(es,eu),max⁡(is,iu))s \vee u = (\max(e_s, e_u), \max(i_s, i_u)). A trace δ\delta maps times to signed bags, nonzero at finitely many times, and its accumulation is X(t)=∑s≤tδ[s]X(t) = \sum_{s \le t} \delta[s].

The program. The inputs after epoch ee are rootse\mathit{roots}_e and edgese\mathit{edges}_e, bags with nonnegative weights. The iterates are Re,0=distinct(rootse)R_{e,0} = \mathrm{distinct}(\mathit{roots}_e) and Re,i+1=distinct(rootse+dst(Re,i⋈edgese))R_{e,i+1} = \mathrm{distinct}(\mathit{roots}_e + \mathrm{dst}(R_{e,i} \bowtie \mathit{edges}_e)), where dst(F⋈E)\mathrm{dst}(F \bowtie E) has, for each node bb, the weight ∑(a,b)F[a]⋅E[(a,b)]\sum_{(a, b)} F[a] \cdot E[(a, b)]. We must show that after epoch EE has been processed, the trace of R has accumulation Re,iR_{e,i} at every time (e,i)(e, i) with e≤Ee \le E.

Lemma 1 (uniqueness of differences). For every function XX from times to signed bags with X(e,i)=0X(e, i) = 0 when e<0e < 0 or i<0i < 0, there is exactly one trace with accumulation XX, namely

δ[e,i]=X(e,i)−X(e−1,i)−X(e,i−1)+X(e−1,i−1).\delta[e, i] = X(e, i) - X(e - 1, i) - X(e, i - 1) + X(e - 1, i - 1).

If the values δ[s]\delta[s] for s≤ts \le t, s≠ts \ne t, are known, then δ[t]=X(t)−∑s≤t, s≠tδ[s]\delta[t] = X(t) - \sum_{s \le t,\ s \ne t} \delta[s].

Proof. The second statement is the definition of the accumulation at tt solved for δ[t]\delta[t]. It fixes each δ[t]\delta[t] by induction along any order that lists the times below tt first, which gives uniqueness. The formula has accumulation XX, because the sum over the rectangle below (e,i)(e, i) telescopes. □\square

Lemma 2 (inputs). Line L1 adds the change of epoch ee at time (e,0)(e, 0). So the accumulations of the input traces at (e,i)(e, i) are rootse\mathit{roots}_e and edgese\mathit{edges}_e, for every ii.

Proof. The times (e′,0)(e', 0) below (e,i)(e, i) are those with e′≤ee' \le e, and the changes of epochs 00 to ee add up to the inputs after epoch ee. □\square

Lemma 3 (join). Let FF and EE be traces with accumulations F(t)F(t) and E(t)E(t). The trace J[r]=∑s∨u=rdst(F[s]⋈E[u])J[r] = \sum_{s \vee u = r} \mathrm{dst}(F[s] \bowtie E[u]) of line L4 has accumulation dst(F(t)⋈E(t))\mathrm{dst}(F(t) \bowtie E(t)).

Proof. dst(⋅⋈⋅)\mathrm{dst}(\cdot \bowtie \cdot) is bilinear, so dst(F(t)⋈E(t))=∑s≤t∑u≤tdst(F[s]⋈E[u])\mathrm{dst}(F(t) \bowtie E(t)) = \sum_{s \le t} \sum_{u \le t} \mathrm{dst}(F[s] \bowtie E[u]). And s≤ts \le t and u≤tu \le t hold together exactly when s∨u≤ts \vee u \le t. Grouping the pairs by r=s∨ur = s \vee u gives ∑r≤tJ[r]\sum_{r \le t} J[r]. □\square

Lemma 4 (feedback). Line L3 sets fed[(e,i)]=R[(e,i−1)]\mathit{fed}[(e, i)] = R[(e, i - 1)] for i≥1i \ge 1 and leaves fed[(e,0)]=0\mathit{fed}[(e, 0)] = 0. If RR has accumulation R(e,i)R(e, i), then fed\mathit{fed} has accumulation R(e,i−1)R(e, i - 1) at (e,i)(e, i), and 0 at (e,0)(e, 0).

Proof. The times (e′,i′)(e', i') below (e,i)(e, i) with i′≥1i' \ge 1 correspond one to one to the times (e′,i′−1)(e', i' - 1) below (e,i−1)(e, i - 1). □\square

Lemma 5 (closure). Let UU be a trace, CC the closure of its support under ∨\vee, and ff any function on signed bags with f(0)=0f(0) = 0. The unique trace ρ\rho with accumulation f(U(t))f(U(t)) is 0 outside CC.

Proof. Let t=(e,i)∉Ct = (e, i) \notin C, and let PP be the support times below tt. If PP is empty, UU is 0 at tt and at the three times below it in Lemma 1, so ρ[t]=0\rho[t] = 0. Otherwise let t∗=⋁P∈Ct^* = \bigvee P \in C. Then t∗≤tt^* \le t and t∗≠tt^* \neq t. If t∗t^* has iteration below ii, every support time below tt is also below (e,i−1)(e, i - 1), and every support time below (e−1,i)(e - 1, i) is below (e−1,i−1)(e - 1, i - 1). So U(e,i)=U(e,i−1)U(e, i) = U(e, i - 1) and U(e−1,i)=U(e−1,i−1)U(e - 1, i) = U(e - 1, i - 1), and the four terms of Lemma 1 for f∘Uf \circ U cancel. If t∗t^* has iteration ii, its epoch is below ee, and the same argument with the roles of the coordinates exchanged applies. □\square

Lemma 6 (distinct). Lines L6 to L8 store, at every processed time tt, the value ρ[t]\rho[t] of the unique trace with accumulation distinct(U(t))\mathrm{distinct}(U(t)), provided that the traces are already correct at all times s≤ts \le t with s≠ts \ne t.

Proof. Line L6 keeps the closure CC of the support of UU: adding a time tt to a set closed under ∨\vee and adding t∨ct \vee c for every cc in it gives a closed set again, because (t∨c1)∨(t∨c2)=t∨(c1∨c2)(t \vee c_1) \vee (t \vee c_2) = t \vee (c_1 \vee c_2). Every time added is ≥t\ge t, so it is processed later or now. If t∈Ct \in C, line L8 computes distinct(U(t))−∑s≤t, s≠tR[s]\mathrm{distinct}(U(t)) - \sum_{s \le t,\ s \ne t} R[s], which is ρ[t]\rho[t] by Lemma 1. If t∉Ct \notin C, nothing is stored, and ρ[t]=0\rho[t] = 0 by Lemma 5. □\square

Lemma 7 (stopping). Let imax⁡i_{\max} be the largest iteration of a time with a nonzero difference before epoch ee. If, in epoch ee, i>imax⁡i > i_{\max} and R[(e,i−1)]=0R[(e, i - 1)] = 0, then every trace is 0 at every time (e,j)(e, j) with j≥ij \ge i, so line L2 may stop.

Proof. By induction on jj. At (e,j)(e, j), line L3 adds R[(e,j−1)]R[(e, j - 1)], which is 0. A join pair with s∨u=(e,j)s \vee u = (e, j) needs ss with iteration jj, because the edge differences have iteration 0; a time of an earlier epoch has iteration at most imax⁡<ji_{\max} < j, and fed[(e,j)]=0\mathit{fed}[(e, j)] = 0. So the join and the union are 0 at (e,j)(e, j). A time of CC with iteration jj would be a least upper bound of support times of UU, one of which has iteration jj; there is none. So R[(e,j)]=0R[(e, j)] = 0 by Lemma 6. □\square

Theorem 1 (correctness). After epoch EE is processed, each trace holds its unique differences at every time (e,i)(e, i) with e≤Ee \le E, and the accumulation of the trace of R at (e,i)(e, i) is Re,iR_{e,i}.

Proof. The times are processed in lexicographic order, epoch first, which lists every s≤ts \le t with s≠ts \ne t before tt. 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 (e,i)(e, i) accumulates to rootse+dst(R(e,i−1)⋈edgese)\mathit{roots}_e + \mathrm{dst}(R(e, i - 1) \bowtie \mathit{edges}_e), or to rootse\mathit{roots}_e for i=0i = 0, and R accumulates to its distinct, which is the definition of Re,iR_{e,i}. ■\blacksquare

Termination. For a fixed epoch, Re,0⊆Re,1R_{e,0} \subseteq R_{e,1}, and the step from Re,iR_{e,i} to Re,i+1R_{e,i+1} is monotone, so Re,i⊆Re,i+1R_{e,i} \subseteq R_{e,i+1}. With nn nodes, the iterates of every epoch are constant from i=ni = n on. Then the four terms of Lemma 1 cancel for every time (e,i)(e, i) with i>ni > n, and the condition of Lemma 7 holds for some i≤max⁡(imax⁡,n)+2i \le \max(i_{\max}, n) + 2. Each time costs a finite scan of the traces.

Complexity

The costs are per epoch, in the word RAM model, with dd the number of differences that the epoch adds to all traces and nn 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 O(log⁡n)O(\log n) per lookup in a sorted index, or expected O(1)O(1) in a hash index, plus the number of matches. So an epoch costs about O(dlog⁡n)O(d \log n) when each key has few differences. In the worst case one key holds all nn differences and the cost is O(dn)O(d n). 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, O(n)O(n). 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 (1,2)(1, 2) would be taken against (1,1)(1, 1) only, and every iteration of epoch 1 would redo work. The product order is what lets (1,2)(1, 2) reuse (0,2)(0, 2).
  • Missing closure times. Evaluating distinct only at the times at which its input changes is wrong. For example, a difference at (0,3)(0, 3) and one at (1,0)(1, 0) can change the output at (1,3)(1, 3), 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.

differential_dataflow.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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.

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
  • a full proof of space.extra
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