public snapshot · areas/examples/raft-nib/ · system@main · commit da2bf624f03d · shared 2026-11-23T17:23:12Z· frozen: this page does not change when the repository does
all files
  1"""Read a raft-nib journal into the facts the site draws: when each node held
  2which role, crashes and restarts, applies, and the saves the Durability check
  3reads. Only the journal is read; nothing here knows the program's source."""
  4import json
  5
  6HOSTS = ["10.0.0.1", "10.0.0.2", "10.0.0.3"]
  7
  8
  9def entries(path):
 10    with open(path) as f:
 11        for line in f:
 12            line = line.strip()
 13            if line:
 14                yield json.loads(line)
 15
 16
 17def value(e):
 18    o = e.get("outcome") or {}
 19    return o.get("value")
 20
 21
 22def host(node):
 23    return node.split(":")[0] if node else ""
 24
 25
 26def sent(e):
 27    """The message a Net.Sim.send carried, decoded, or None."""
 28    try:
 29        b = bytes.fromhex(e["argv"][1]["bytes"]).decode()
 30        return json.loads(b)
 31    except (KeyError, IndexError, ValueError, TypeError):
 32        return None
 33
 34
 35def received(e):
 36    """The message a Net.Sim.recv answered with, decoded, or None."""
 37    try:
 38        return json.loads(bytes.fromhex(value(e)["bytes"]).decode())
 39    except (KeyError, TypeError, ValueError, AttributeError):
 40        return None
 41
 42
 43def read(path):
 44    """Facts of one run, with every event stamped with the virtual time the
 45    run had reached (the last `Time.Sim.now` answer before it)."""
 46    now = 0
 47    roles = {h: [] for h in HOSTS}      # (t, role, term)
 48    crashes = []                        # (host, at, restart or None)
 49    applies = []                        # (t, host, index, cmd)
 50    saves = []                          # (seq, t, host, term, voted)
 51    leaders = {}                        # term -> (host, t)
 52    count = 0
 53    ops = {}
 54    state = {h: ("follower", 0) for h in HOSTS}   # what each node last became
 55
 56    def become(h, t, role, term):
 57        if state[h] != (role, term):
 58            state[h] = (role, term)
 59            roles[h].append((t, role, term))
 60
 61    for e in entries(path):
 62        count += 1
 63        op = e.get("op", "")
 64        ops[op] = ops.get(op, 0) + 1
 65        if op == "Time.Sim.now" and isinstance(value(e), int):
 66            now = max(now, value(e))
 67        elif op == "World.crash":
 68            h, at = e["argv"]
 69            crashes.append([h, at, None])
 70            now = max(now, at)
 71            become(h, at, "down", state[h][1])
 72        elif op == "World.restart":
 73            h, at = e["argv"]
 74            for c in crashes:
 75                if c[0] == h and c[2] is None:
 76                    c[2] = at
 77                    break
 78            now = max(now, at)
 79            become(h, at, "follower", state[h][1])
 80        elif op == "Raft.Store.save":
 81            h, term, voted = e["argv"]
 82            saves.append((e["seq"], now, h, term, voted))
 83            if voted == h:
 84                become(h, now, "candidate", term)
 85            elif term > state[h][1]:
 86                become(h, now, "follower", term)
 87        elif op == "Net.Sim.send":
 88            m = sent(e)
 89            if m and m.get("kind") == "append":
 90                h = m["from"]
 91                if m["term"] not in leaders:
 92                    leaders[m["term"]] = (h, now)
 93                become(h, now, "leader", m["term"])
 94        elif op == "Net.Sim.recv":
 95            # A candidate that hears an append for its term (or a later one)
 96            # steps down without writing anything, so the journal shows it
 97            # only as the message it received.
 98            m = received(e)
 99            h = host(e.get("node", ""))
100            if m and h in state and m.get("kind") == "append":
101                role, term = state[h]
102                if role != "down" and m["term"] >= term and role != "follower" \
103                        and not (role == "leader" and m["term"] == term):
104                    become(h, now, "follower", m["term"])
105        elif op == "Raft.Machine.apply":
106            h, i, cmd = e["argv"]
107            applies.append((now, h, i, cmd))
108    return {"roles": roles, "crashes": crashes, "applies": applies,
109            "saves": saves, "leaders": leaders, "entries": count,
110            "end": now, "ops": ops}
111
112
113def segments(facts, end):
114    """Each host's run as [start, stop, role, term] spans, merged."""
115    out = {}
116    for h, evs in facts["roles"].items():
117        spans = []
118        cur = (0, "follower", 0)
119        for t, role, term in evs:
120            if (role, term) != (cur[1], cur[2]):
121                if t > cur[0]:
122                    spans.append([cur[0], t, cur[1], cur[2]])
123                cur = (t, role, term)
124        spans.append([cur[0], end, cur[1], cur[2]])
125        out[h] = [s for s in spans if s[1] > s[0]]
126    return out
127
128
129def durability_break(facts):
130    """The first save that breaks Durability, with the save it contradicts."""
131    last = {}
132    for seq, t, h, term, voted in facts["saves"]:
133        if h in last:
134            pseq, pt, pterm, pvoted = last[h]
135            ok = term > pterm or (term == pterm and (pvoted == "" or pvoted == voted))
136            if not ok:
137                return {"before": (pseq, pt, h, pterm, pvoted), "after": (seq, t, h, term, voted)}
138        last[h] = (seq, t, term, voted)
139    return None