Algorithm Search⌘K

Algorithmresearch

Asynchronous barrier snapshotting

Also called ABS, barrier-aligned checkpointing.

Take consistent snapshots of a stream job by injecting barriers into the sources and aligning them at each operator, without stopping the job.

Time
O(s + c + b) worst · averageO(s + c) best
Space
O(s + b) extra
Where
b = the number of records held at blocked inputs or logged on back edges; c = the number of channels; s = the size of the states of all tasks
Properties
deterministicexactnot externalnot in placeonlineiterative
Origin
Paris Carbone, Gyula Fóra, Stephan Ewen, Seif Haridi, Kostas Tzoumas, 2015

Asynchronous barrier snapshotting is an algorithm that takes a consistent snapshot of a running stream job: the sources put a barrier into their output streams, and each task copies its state when the barrier has arrived on all its inputs, holding back the inputs on which it came first. It solves the global snapshot problem for dataflow graphs. The Chandy and Lamport snapshot also sends markers, but it records the records in flight on every channel, while this algorithm records no channel state on an acyclic graph and logs only the records on the back edges of cycles. Unlike a database checkpoint with a log, recovery restores the copies and replays the inputs from the stored offsets.

In plain words

Workers pass items along fixed lines, and each worker keeps counts. You want a photo of all counts that fits together, without stopping work.

At the start of the lines, you drop a flag into each line. A worker that sees a flag on one input line stops taking from that line and keeps working on the others. When the flag has come on all its input lines, the worker writes down its counts, sends the flag on, and takes from all lines again. So every count in the photo includes exactly the items that came before the flags.

After a crash, every worker starts from its written counts, and the lines start again from the place where the flags went in. Each item is counted once. If the lines form a loop, a worker also writes down the items that come back around the loop before the flag does.

The problem

A job is a directed graph of tasks joined by FIFO channels that lose no message. Sources read records from inputs that can be read again from any offset, such as a log. Every other task has a state and applies a deterministic operator to each record. A snapshot must hold a state for each task, an offset for each source, and the records in flight on each channel, all at one consistent cut: no record is counted in the state of its receiver unless its sender had sent it in its own part of the snapshot. Restarting the job from the snapshot must then give a run in which each input record changes each state once. The job must not stop while the snapshot is taken.

The algorithm

A depth-first search from the sources marks the back edges, the channels that close a cycle. All other channels are regular, and they form an acyclic graph. For snapshot nn:

  1. ON-BARRIER(t, c, n) ▷ task t takes barrier n from input channel c
  2. 1if c is regular then block c; seen ← seen ∪ {c} else mark the back edge c
  3. 2if t has no copy for n and seen holds every regular input of t then
  4. 3send barrier n on every output channel of t
  5. 4copy ← the state of t; log ← empty; start logging
  6. 5unblock every input of t; seen ← ∅
  7. 6if t is logging and barrier n has come on every back edge into t then
  8. 7stop logging; store (copy, log) as the part of t in snapshot n
  9. ON-RECORD(t, c, x)
  10. 8if t is logging and c is a back edge then append (c, x) to log
  11. 9apply the operator of t to x and send its output records
  12. ON-TRIGGER(s, n) ▷ the coordinator starts snapshot n at source s
  13. 10store the offset of s as its part of snapshot n; send barrier n on every output channel of s

A blocked channel keeps its records in its buffer until line L5. On an acyclic graph, line L6 holds at once and the log is empty, which is Algorithm 1 of Carbone et al. With cycles, the back edges are never blocked, since a task that waits for a barrier from its own cycle would wait forever; the records logged at line L8 are the state of those channels, which is Algorithm 2. The snapshot is complete when every task has stored its part.

To recover, every task gets its copy, every source goes back to its stored offset, the regular channels are empty, and each log is put at the front of its back edge.

Example

Sources s1s_1 and s2s_2 read the records 1, 4 and the record 5. Tasks m1m_1 and m2m_2 map xx to x mod 3x \bmod 3, and a task cnt with inputs from m1m_1 and m2m_2 counts the keys. The steps are:

  1. s1s_1 sends 1. Snapshot 0 starts: s1s_1 stores offset 1 and sends the barrier, then sends 4. s2s_2 sends 5, stores offset 1 and sends the barrier.
  2. m1m_1 passes the key 1, the barrier and the key 1 of record 4. m2m_2 passes the key 2 and the barrier.
  3. cnt takes the key 1, then the barrier from m1m_1, and blocks that input. The key of record 4 waits in its buffer.
  4. cnt takes the key 2 from m2m_2, then the barrier from m2m_2. It copies its state and unblocks.
with alignment copy at the first barrier, no blocking
copy of cnt {1: 1, 2: 1}\{1{:}\ 1,\ 2{:}\ 1\} {1: 1}\{1{:}\ 1\}
cnt after recovery from offsets 1 and 1 and a run to the end {1: 2, 2: 1}\{1{:}\ 2,\ 2{:}\ 1\} {1: 2}\{1{:}\ 2\}
cnt in the run without failure {1: 2, 2: 1}\{1{:}\ 2,\ 2{:}\ 1\} {1: 2, 2: 1}\{1{:}\ 2,\ 2{:}\ 1\}

Without blocking, cnt takes the key 2 after its copy, but s2s_2 had sent record 5 before its offset. The record is in neither the copy nor the replay, and it is lost.

Correctness

Barrier nn leaves a task at the moment of its copy, and a task copies only after it has taken the barrier from every regular input. So along a regular channel the receiver copies after the sender, and along a back edge the sender copies after the receiver, because the search reached the sender from the receiver along regular channels. Blocking makes sure that a task takes, before its copy, only records that were ahead of the barrier on their channel, so their senders sent them before their own copies: the copies form a consistent cut. On a regular channel every record ahead of the barrier is taken before the copy, so the channel is empty in the cut. On a back edge the records in flight are those that arrive after the copy and before the barrier, which is what line L8 logs. Ordering the events before the cut by their real order gives a run of the job that ends in the snapshot, and so recovery continues a run without failure. The full proof is in the proof page.

Proof: Barrier snapshots record a consistent global state, and recovery from them is a run of the jobfull

We use the line numbers of the pseudocode on the page. The job is a directed graph of tasks with FIFO channels that lose no message. Sources read records from replayable inputs at an offset. Every other task applies a deterministic operator to each record that it takes, which changes its state and sends records on its outputs. Barriers change no state. The back edges are the channels that close a cycle in a depth-first search from the sources; all other channels are regular. The regular channels form an acyclic graph, because every cycle of a graph contains a back edge of any depth-first search.

Fix one snapshot nn. The cut point of a source is its step L10. The cut point of any other task tt is its step L4. The pre-cut events of a task are the records that it took and sent before its cut point.

Lemma 1 (order of cut points). If (u,t)(u, t) is a regular channel, the cut point of tt is after the cut point of uu. If (u,t)(u, t) is a back edge, the cut point of uu is after the cut point of tt.

Proof. Barrier nn is sent on (u,t)(u, t) only at the cut point of uu (lines L3 and L10), and tt passes L2 only after it has taken barrier nn from every regular input. This gives the first claim. For a back edge (u,t)(u, t), the search reached uu from tt along a path of tree edges, which are regular. By the first claim, the cut points increase along that path. □\square

Lemma 2 (no orphan records). Every record that a task takes before its cut point was sent before the cut point of its sender.

Proof. Let tt take xx from channel c=(u,t)c = (u, t) before its cut point. If cc is regular, tt blocks cc when it takes barrier nn from it (line L1) and unblocks it only at line L5, after its cut point. So xx came before the barrier on cc, and, the channel being FIFO, uu sent xx before it sent the barrier, which is at its cut point. If cc is a back edge, uu sent xx before tt took it, which is before the cut point of tt, which is before the cut point of uu by Lemma 1. □\square

So the pre-cut events form a consistent cut: no record is received in the cut and sent outside it.

Lemma 3 (channel states). The records sent in the cut and not received in it are none on a regular channel, and, on a back edge cc into tt, exactly the records that tt logs from cc at line L8.

Proof. On a regular channel (u,t)(u, t), all records sent before the cut point of uu come before barrier nn, and tt takes the barrier before its cut point, so it takes all of them before its cut point. On a back edge c=(u,t)c = (u, t), the records sent before the cut point of uu are those before barrier nn on cc. The task tt logs the records that it takes from cc after its cut point (line L4 starts the log) and stops when it takes the barrier from cc (lines L6 and L7). Since cc is FIFO and never blocked, these are exactly the records before the barrier that tt takes after its cut point. □\square

Theorem 1 (consistency). The snapshot, made of the copied states, the source offsets and the logs, is a global state of the job that some run of the job, without barriers, reaches from the start.

Proof. Order all pre-cut events by the real order in which they happened. This order lists each send of a record before its receipt, and on each channel the receipts are in the order of the sends, because the real run did so. Removing the post-cut events keeps these properties, since by Lemma 2 no pre-cut receipt depends on a post-cut send, and removing the barrier steps changes no state. Each task is deterministic, so in this run every task ends in the state that it had at its cut point, which is the copy of line L4, and every source has read its stored offset. The channel contents are given by Lemma 3. ■\blacksquare

Theorem 2 (recovery). Restore the copied states, reset each source to its offset, leave the regular channels empty, and put each log at the front of its back edge. Every run from this state is the continuation of a run of the job from the start on the same inputs. So each input record changes the state of each task in the same way as in some run without failure, once.

Proof. By Theorem 1, the restored state is the state after a run prefix PP of the job. The records of PP are exactly the input records before the offsets, together with the records that they cause. The sources continue from their offsets, so each later input record is read once, after PP. A continuation from the restored state is therefore a continuation of PP. ■\blacksquare

For a job whose final states do not depend on the order in which the scheduler runs the tasks, such as the jobs in the tests, the state after recovery and a run to the end is the state of the run without failure.

Termination. Assume a fair scheduler, which takes from every unblocked nonempty channel eventually. We show that every task reachable from the sources stores its part of snapshot nn. Order the tasks topologically along the regular channels, which is possible because they form an acyclic graph. Sources pass L10 when they take the trigger. Suppose every regular predecessor of tt has passed its cut point. Then barrier nn is on every regular input of tt. An input of tt is blocked only after the barrier has been taken from it, so the barriers on the others are taken, and tt passes L2 to L5. By induction, every task passes its cut point, and so it sends barrier nn on every output, back edges included. No back edge is ever blocked, so every task takes barrier nn from each of its back edges, line L6 holds, and line L7 stores its part. A blocked channel is unblocked at L5, so no record waits forever.

Without alignment the proof of Lemma 2 fails: a task that copies its state at the first barrier and keeps taking records from an input whose barrier has not yet come takes records that are in neither the copy nor the replay, and a task that copies at the last barrier without blocking holds records in its copy that the replay sends again. The test of the page example shows the first case.

Complexity

Costs are in the word RAM model, per snapshot and per record, in the worst case and not amortized.

  • Per record. Line L8 and the test for a blocked input add O(1)O(1) time to each record, in the worst case.
  • Per snapshot. Each barrier crosses each channel once, O(c)O(c), and the copies cost O(s)O(s). Logging and buffering add O(b)O(b), so a snapshot costs O(s+c+b)O(s + c + b), and O(s+c)O(s + c) on an acyclic graph whose inputs are never blocked long. A real system writes the copies to durable storage in the background, with copy-on-write state, so that the tasks do not wait for the write.
  • Memory. The copies take O(s)O(s). The buffers of the blocked inputs hold the records that arrive between the first and the last barrier at a task, and the logs hold the records on back edges during a snapshot. Both are O(b)O(b), and the algorithm alone does not bound bb: it depends on how far the barriers of the inputs of a task are apart, which backpressure limits by slowing the sources.

Properties

  • Exactly once for the state. Each input record changes each task state once, after any number of failures, if the sources can replay and the operators are deterministic.
  • Asynchronous. No global pause: a task stops only the inputs on which the barrier has come, and only until its other inputs catch up.
  • Small snapshots. On acyclic graphs no record in flight is stored. The snapshot is the task states and the source offsets.
  • Late data. The barrier divides the records by the order in which they arrive, not by event time. A late record is an ordinary record, and the state of event-time operators, such as their open windows and the current event-time watermark, is part of the copy. After recovery the replay delivers the same records in the same order, so a late record is either handled or dropped exactly as in the run without failure.

Variants and improvements

  • Without alignment, at least once. Tasks do not block and copy at the last barrier. Records after an early barrier are in the copy and are replayed again, so recovery can count them twice. Systems offer this for lower latency when duplicates are acceptable.
  • Unaligned barriers. A task copies its state at the first barrier and also stores, as channel state, the records that are ahead of the barrier on the other inputs, as in the Chandy and Lamport snapshot. This removes the wait for slow inputs at the price of larger snapshots. Apache Flink added such a mode later.
  • Incremental copies. Only the part of the state that changed since the last snapshot is written.
  • Outputs to external systems. The snapshot covers only the internal state. Writes to an outside system are made exactly once by holding them in a transaction that commits when the snapshot completes, which is a form of two-phase commit.

When to use it

Use it for fault tolerance of long-running stateful stream jobs with replayable sources, where the job must keep running while it is backed up, and where the state is large but the records in flight should not be stored. With very skewed inputs, where barriers arrive far apart and alignment holds back too much, use unaligned barriers. Prefer Chandy and Lamport when there are no sources to replay from and all channel state must be stored.

Pitfalls

  • No alignment. Copying at the first barrier without blocking loses records, as in the example. Copying at the last barrier without blocking counts some twice.
  • Blocking back edges. A task in a cycle that waits for the barrier from its back edge waits for itself, and the snapshot never completes.
  • Sources that cannot replay. Offsets mean nothing if the input cannot be read again from them, so a socket or a queue without retention gives no exactly-once guarantee.
  • Nondeterministic operators. Operators that read the clock or a random source give a different run after recovery. The run is still consistent with the snapshot, but its outputs can differ from those already sent.
  • Slow alignment. A slow input holds back the barrier of all other inputs of its task, and the buffers grow, which raises latency and memory until backpressure acts.

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.

asynchronous_barrier_snapshotting.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/asynchronous-barrier-snapshotting/. The authors are listed in prov/8TJ3Y4.jsonl.

"""Asynchronous barrier snapshotting, simulated on one thread.

A job is a directed graph of tasks joined by FIFO channels. Sources read
records from input lists at an offset. Every other task has a state (a
Counter) and an operator op(state, sender, value) that updates the state and
returns a list of (receiver, value) pairs to send.

A snapshot n starts at the sources: each source stores its offset and sends
barrier n on its outputs. A task blocks each regular input on which barrier n
has arrived. When it has arrived on all regular inputs, the task sends the
barrier on, copies its state and unblocks. Back edges, found by depth-first
search from the sources, are never blocked: the task logs the records that
arrive on them after its copy, until the barrier comes back on each of them.

A scheduler picks a random enabled step at each turn, so channels are FIFO
but their speeds are arbitrary. With aligned=False the tasks copy their state
at the first barrier and do not block, which is not consistent.
"""

import copy
import random
from collections import Counter, deque

class Barrier:
    """Barrier n, sent on a channel between records."""

    __slots__ = ("n",)

    def __init__(self, n: int) -> None:
        self.n = n


def back_edges(tasks, channels, sources) -> set:
    """The channels that close a cycle in a depth-first search from the sources."""
    outs = {t: [c for c in channels if c[0] == t] for t in tasks}
    color = {t: 0 for t in tasks}  # 0 new, 1 on the stack, 2 done
    back = set()

    def visit(t):
        color[t] = 1
        for c in outs[t]:
            if color[c[1]] == 1:
                back.add(c)
            elif color[c[1]] == 0:
                visit(c[1])
        color[t] = 2

    for s in sources:
        if color[s] == 0:
            visit(s)
    for t in tasks:
        if color[t] == 0:
            visit(t)
    return back


class Job:
    def __init__(self, ops: dict, channels: list, inputs: dict, aligned: bool = True) -> None:
        self.ops = ops                    # task -> operator, or None for a source
        self.inputs = inputs              # source -> list of records
        self.tasks = list(ops)
        self.sources = [t for t in self.tasks if ops[t] is None]
        self.channels = list(channels)
        self.ins = {t: [c for c in channels if c[1] == t] for t in self.tasks}
        self.outs = {t: [c for c in channels if c[0] == t] for t in self.tasks}
        self.back = back_edges(self.tasks, self.channels, self.sources)
        self.aligned = aligned
        self.queue = {c: deque() for c in self.channels}
        self.state = {t: Counter() for t in self.tasks}
        self.offset = {s: 0 for s in self.sources}
        self.blocked = {t: set() for t in self.tasks}
        self.seen = {t: set() for t in self.tasks}        # regular inputs that gave the barrier
        self.back_seen = {t: set() for t in self.tasks}   # back edges that gave the barrier
        self.logging = {t: None for t in self.tasks}      # (state copy, log) while logging
        self.done_for = {t: -1 for t in self.tasks}       # the last snapshot copied
        self.parts: dict = {}                             # snapshot -> task -> part
        self.complete: list = []                          # finished snapshots, in order
        self.in_flight = None
        self.to_trigger: set = set()
        self.next_id = 0

    # ---- the algorithm -------------------------------------------------

    def trigger(self) -> None:
        self.in_flight = self.next_id
        self.next_id += 1
        self.parts[self.in_flight] = {}
        self.to_trigger = set(self.sources)

    def source_barrier(self, s) -> None:
        n = self.in_flight
        self.to_trigger.discard(s)
        self.parts[n][s] = {"offset": self.offset[s]}  # @line L10
        for c in self.outs[s]:
            self.queue[c].append(Barrier(n))
        self._check_complete()

    def _copy(self, t, n) -> None:
        for c in self.outs[t]:
            self.queue[c].append(Barrier(n))  # @line L3
        self.done_for[t] = n
        self.logging[t] = (copy.deepcopy(self.state[t]), [])  # @line L4
        self.blocked[t] = set()  # @line L5
        self.seen[t] = set()

    def _finish_if_ready(self, t, n) -> None:
        back_in = [c for c in self.ins[t] if c in self.back]
        if self.logging[t] is not None and all(c in self.back_seen[t] for c in back_in):  # @line L6
            st, log = self.logging[t]
            self.parts[n][t] = {"state": st, "log": log}  # @line L7
            self.logging[t] = None
            self.back_seen[t] = set()
            self._check_complete()

    def on_barrier(self, t, c, n) -> None:
        regular = [x for x in self.ins[t] if x not in self.back]
        if c in self.back:
            self.back_seen[t].add(c)
        elif self.aligned:
            self.blocked[t].add(c)  # @line L1
            self.seen[t].add(c)
        if self.done_for[t] < n and (not self.aligned or set(regular) <= self.seen[t]):  # @line L2
            self._copy(t, n)
        self._finish_if_ready(t, n)

    def on_record(self, t, c, x) -> None:
        if self.logging[t] is not None and c in self.back:
            self.logging[t][1].append((c, x))  # @line L8
        for dst, y in self.ops[t](self.state[t], c[0], x):  # @line L9
            self.queue[(t, dst)].append(y)

    def _check_complete(self) -> None:
        n = self.in_flight
        if n is not None and len(self.parts[n]) == len(self.tasks):
            self.complete.append(n)
            self.in_flight = None

    # ---- the scheduler -------------------------------------------------

    def actions(self, may_trigger: bool) -> list:
        acts = []
        if may_trigger and self.in_flight is None:
            acts.append(("trigger",))
        for s in self.sources:
            if s in self.to_trigger:
                acts.append(("barrier", s))
            if self.offset[s] < len(self.inputs[s]):
                acts.append(("emit", s))
        for t in self.tasks:
            for c in self.ins[t]:
                if self.queue[c] and c not in self.blocked[t]:
                    acts.append(("take", t, c))
        return acts

    def do(self, act) -> None:
        if act[0] == "trigger":
            self.trigger()
        elif act[0] == "barrier":
            self.source_barrier(act[1])
        elif act[0] == "emit":
            s = act[1]
            x = self.inputs[s][self.offset[s]]
            self.offset[s] += 1
            for c in self.outs[s]:
                self.queue[c].append(x)
        else:
            _, t, c = act
            m = self.queue[c].popleft()
            if isinstance(m, Barrier):
                self.on_barrier(t, c, m.n)
            else:
                self.on_record(t, c, m)

    def run(self, rng: random.Random, steps=None, snapshots: int = 0, p_trigger: float = 0.05) -> bool:
        """Run up to steps turns (or to the end), starting up to `snapshots` snapshots.

        Returns True when the job has nothing left to do.
        """
        k = 0
        while steps is None or k < steps:
            may = len(self.complete) + (self.in_flight is not None) < snapshots
            acts = self.actions(may)
            if not acts:
                return True
            if acts[0][0] == "trigger" and (len(acts) == 1 or rng.random() < p_trigger):
                self.do(acts[0])
            else:
                rest = [a for a in acts if a[0] != "trigger"]
                self.do(rng.choice(rest))
            k += 1
        return not self.actions(False)

    # ---- recovery ------------------------------------------------------

    def last_snapshot(self):
        """The parts of the last finished snapshot, or of the empty start state."""
        if self.complete:
            return self.parts[self.complete[-1]]
        empty = {s: {"offset": 0} for s in self.sources}
        empty.update({t: {"state": Counter(), "log": []} for t in self.tasks if t not in self.sources})
        return empty

    def restored(self, parts, inputs=None) -> "Job":
        """A new job that starts from a snapshot: states and offsets, regular channels empty,
        and the logged back-edge records in front of their channels."""
        job = Job(self.ops, self.channels, self.inputs if inputs is None else inputs, self.aligned)
        for t in self.tasks:
            if t in self.sources:
                job.offset[t] = parts[t]["offset"]
            else:
                job.state[t] = copy.deepcopy(parts[t]["state"])
                for c, x in parts[t]["log"]:
                    job.queue[c].append(x)
        return job

    def final_states(self) -> dict:
        return {t: +self.state[t] for t in self.tasks if t not in self.sources}


def drain(job: Job, rng: random.Random) -> dict:
    """Run to the end without snapshots and return the task states."""
    job.run(rng)
    return job.final_states()


# ---- two example jobs ----------------------------------------------------

def op_key(dst, m):
    def op(state, sender, x):
        return [(dst, x % m)]
    return op


def op_count(dst):
    def op(state, sender, x):
        state[x] += 1
        return [(dst, (x, state[x]))]
    return op


def op_sink(state, sender, x):
    state[x] += 1
    return []


def acyclic_job(a, b, aligned=True) -> Job:
    """Two sources, a map on each, a keyed count with two inputs, and a sink."""
    ops = {"s1": None, "s2": None, "m1": op_key("cnt", 3), "m2": op_key("cnt", 3),
           "cnt": op_count("sink"), "sink": op_sink}
    ch = [("s1", "m1"), ("s2", "m2"), ("m1", "cnt"), ("m2", "cnt"), ("cnt", "sink")]
    return Job(ops, ch, {"s1": list(a), "s2": list(b)}, aligned)


def op_dec(state, sender, x):
    state[x] += 1
    out = [("sink", x)]
    if x > 0:
        out.append(("fb", x - 1))
    return out


def op_fb(state, sender, x):
    state["passes"] += 1
    return [("dec", x)]


def cyclic_job(a, b) -> Job:
    """Two sources feed a loop: dec sends x - 1 around the cycle dec -> fb -> dec while x > 0."""
    ops = {"s1": None, "s2": None, "dec": op_dec, "fb": op_fb, "sink": op_sink}
    ch = [("s1", "dec"), ("s2", "dec"), ("dec", "fb"), ("fb", "dec"), ("dec", "sink")]
    return Job(ops, ch, {"s1": list(a), "s2": list(b)})
test_asynchronous_barrier_snapshotting.py 94 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/asynchronous-barrier-snapshotting/. The authors are listed in prov/8TJ3Y4.jsonl.

import random
from collections import Counter

from asynchronous_barrier_snapshotting import acyclic_job, cyclic_job, drain

PAGE_STEPS = [("emit", "s1"), ("trigger",), ("barrier", "s1"), ("emit", "s1"),
              ("emit", "s2"), ("barrier", "s2"),
              ("take", "m1", ("s1", "m1")), ("take", "m1", ("s1", "m1")), ("take", "m1", ("s1", "m1")),
              ("take", "m2", ("s2", "m2")), ("take", "m2", ("s2", "m2")),
              ("take", "cnt", ("m1", "cnt")), ("take", "cnt", ("m1", "cnt")),
              ("take", "cnt", ("m2", "cnt")), ("take", "cnt", ("m2", "cnt"))]


def page_run(aligned):
    job = acyclic_job([1, 4], [5], aligned)
    for act in PAGE_STEPS:
        job.do(act)
    job.run(random.Random(0))
    return job


def test_page_example() -> None:
    truth = drain(acyclic_job([1, 4], [5]), random.Random(1))
    assert truth["cnt"] == Counter({1: 2, 2: 1})

    job = page_run(True)
    snap = job.last_snapshot()
    assert snap["s1"]["offset"] == 1 and snap["s2"]["offset"] == 1
    assert snap["cnt"]["state"] == Counter({1: 1, 2: 1})
    assert drain(job.restored(snap), random.Random(2)) == truth

    bad = page_run(False)
    snap = bad.last_snapshot()
    assert snap["cnt"]["state"] == Counter({1: 1})
    assert drain(bad.restored(snap), random.Random(2))["cnt"] == Counter({1: 2})


def random_inputs(rng):
    return ([rng.randrange(6) for _ in range(rng.randrange(0, 8))],
            [rng.randrange(6) for _ in range(rng.randrange(0, 8))])


def check(make, seed, aligned=True):
    """Fail the job at a random step; return (recovery is exact, snapshot is a consistent cut, log size)."""
    rng = random.Random(seed)
    a, b = random_inputs(rng)
    truth = drain(make(a, b, aligned) if aligned is not None else make(a, b), random.Random(seed + 1))
    job = make(a, b, aligned) if aligned is not None else make(a, b)
    job.run(rng, steps=rng.randrange(0, 80), snapshots=rng.randrange(1, 4), p_trigger=0.2)
    snap = job.last_snapshot()
    recovered = drain(job.restored(snap), random.Random(seed + 2))
    # The cut: the job run on the prefixes of the inputs up to the stored offsets.
    pa, pb = a[:snap["s1"]["offset"]], b[:snap["s2"]["offset"]]
    prefix = make(pa, pb, aligned) if aligned is not None else make(pa, pb)
    cut = drain(prefix, random.Random(seed + 3))
    from_snap = drain(job.restored(snap, {"s1": pa, "s2": pb}), random.Random(seed + 4))
    logged = sum(len(p.get("log", [])) for p in snap.values())
    return recovered == truth, from_snap == cut, logged, snap, cut


def test_acyclic_recovery_and_cut() -> None:
    for seed in range(300):
        exact, consistent, logged, snap, cut = check(acyclic_job, seed)
        assert exact and consistent
        assert logged == 0
        # No channel state: the copied states are the states of the prefix run.
        for t in ("m1", "m2", "cnt", "sink"):
            assert +snap[t]["state"] == cut[t]


def test_cyclic_recovery_and_cut() -> None:
    with_log = 0
    for seed in range(300):
        exact, consistent, logged, _, _ = check(cyclic_job, seed, aligned=None)
        assert exact and consistent
        with_log += logged > 0
    assert with_log > 0  # back-edge logging was used


def test_back_edges() -> None:
    assert cyclic_job([], []).back == {("fb", "dec")}
    assert acyclic_job([], []).back == set()


def test_no_alignment_is_not_consistent() -> None:
    wrong = 0
    for seed in range(300):
        exact, consistent, _, _, _ = check(acyclic_job, seed, aligned=False)
        wrong += not (exact and consistent)
        assert check(acyclic_job, seed, aligned=True)[:2] == (True, True)
    assert wrong > 0

History

Chandy and Lamport (1985) gave the snapshot algorithm with markers on FIFO channels that records channel states. Carbone, Fóra, Ewen, Haridi and Tzoumas (2015) adapted it to dataflow jobs as asynchronous barrier snapshotting, with alignment to remove channel state on acyclic graphs and logging only on back edges, and used it in Apache Flink. Carbone, Ewen, Fóra, Haridi, Richter and Tzoumas (2017) described the state management of Flink built on it, including outputs to external systems.

References

  1. Paris Carbone, Gyula Fóra, Stephan Ewen, Seif Haridi and Kostas Tzoumas, Lightweight asynchronous snapshots for distributed dataflows, arXiv 2015, Section 4.1 (the snapshot problem on the graph of tasks and channels, with termination and feasibility), Section 4.2 and Algorithm 1 (acyclic graphs, no channel state), Section 4.3 and Algorithm 2 (cyclic graphs, back edges found by depth-first search and logged), Section 5 (recovery)
  2. State management in Apache Flink: consistent stateful distributed stream processing, the snapshot protocol as used in production, with partitioned state, alignment, rescaling and outputs to external systems (general locator)
  3. K. Mani Chandy and Leslie Lamport, Distributed snapshots, determining global states of distributed systems, ACM Transactions on Computer Systems 3(1), 1985, pages 63 to 75, the marker rules and the proof that the recorded state is reachable, which this algorithm adapts (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
  • 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