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#!/usr/bin/env python3
  2"""Write site/index.html from real runs of raft.nib.
  3
  4Authoring-time only: the deploy serves the committed site/ and runs none of
  5this. Every number, journal line and drawing on the page comes from a run made
  6here, and every code block is cut from the source it names, so the page cannot
  7describe a program that is not the one in this directory.
  8
  9    python3 gen/build.py [--verify-log FILE]
 10
 11Needs nibc and nib-tla built in this tree, the tree-sitter grammar's
 12node_modules (for highlighting), and a checker as nib-tla finds one
 13(APALACHE_JAR, NIB_TLA_JAVA). Without --verify-log it runs
 14`nib-tla verify areas/examples/raft-nib` itself, which takes about two minutes.
 15"""
 16import gzip
 17import html
 18import json
 19import os
 20import re
 21import shutil
 22import subprocess
 23import sys
 24import tempfile
 25from concurrent.futures import ThreadPoolExecutor
 26
 27import journal
 28
 29HERE = os.path.dirname(os.path.abspath(__file__))
 30APP = os.path.dirname(HERE)
 31REPO = os.path.abspath(os.path.join(APP, "..", "..", ".."))
 32NIBC = os.environ.get("NIBC", os.path.join(REPO, "system/tools/nib/_build/default/lib/nibc.exe"))
 33NIBTLA = os.environ.get("NIB_TLA", os.path.join(REPO, "system/tools/modelcheck/nib-tla/target/release/nib-tla"))
 34TS_DIR = os.path.join(REPO, "system", "tools", "tree-sitter-nib")
 35SITE = os.path.join(APP, "site")
 36
 37# The two runs the page draws. The hero is the correct program under the crash
 38# world; the refused one is the store that forgets, under the same world.
 39HERO = ("Main", 3)
 40REFUSED = ("Forgetful", 1)
 41COLORS = {"10.0.0.1": "n1", "10.0.0.2": "n2", "10.0.0.3": "n3"}
 42
 43
 44def die(msg):
 45    sys.exit("build.py: " + msg)
 46
 47
 48def run(cmd, **kw):
 49    return subprocess.run(cmd, capture_output=True, text=True, **kw)
 50
 51
 52# ─── Runs ───────────────────────────────────────────────────────────────────
 53
 54def record(tmp, wire, seed, world_file="worlds/crash.json"):
 55    # As `nib-tla verify` makes a sweep's world: the base file with its seed set.
 56    world = json.load(open(os.path.join(APP, world_file)))
 57    world = {**world, "seed": seed}
 58    tag = os.path.basename(world_file).split(".")[0]
 59    wpath = os.path.join(tmp, f"{wire}-{tag}-{seed}.json")
 60    json.dump(world, open(wpath, "w"))
 61    jpath = os.path.join(tmp, f"{wire}-{tag}-{seed}.jsonl")
 62    env = dict(os.environ, NIBC_STD=os.path.join(REPO, "system/tools/nib/std"))
 63    r = run([NIBC, "--run", os.path.join(APP, "raft.nib"), "--wire", wire,
 64             "--world", wpath, "--journal-out", jpath], env=env)
 65    if r.returncode != 0:
 66        die(f"{wire} seed {seed} did not run:\n{r.stderr}")
 67    v = run([NIBTLA, "check", "--spec", os.path.join(APP, "RaftTrace.tla"), "--journal", jpath])
 68    verdict = re.search(r"verdict=(\w+)", v.stdout + v.stderr)
 69    if not verdict:
 70        die(f"nib-tla gave no verdict for {wire} seed {seed}:\n{v.stderr}")
 71    return {"wire": wire, "seed": seed, "world": world, "journal": jpath,
 72            "stdout": r.stdout.strip().splitlines(), "verdict": verdict.group(1),
 73            "check": (v.stdout + v.stderr), "facts": journal.read(jpath)}
 74
 75
 76def verify_rows(log):
 77    rows = []
 78    for line in log.splitlines():
 79        m = re.match(r"nib-tla: sweep ([\w-]+): (\d+) of (\d+) seeds admitted, (\d+) refused", line)
 80        if m:
 81            at = {int(a): int(b) for a, b in re.findall(r"seed (\d+) at seq=(\d+)", line)}
 82            rows.append({"name": m.group(1), "admitted": int(m.group(2)),
 83                         "seeds": int(m.group(3)), "refused": int(m.group(4)), "at": at})
 84    scen = re.search(r"scenario (\w+): (\w+) \((\d+) entries", log)
 85    took = re.search(r"verify \S+: ([\d.]+)s", log)
 86    if not rows or not scen or not took:
 87        die("the verify log does not have the lines this page reads")
 88    manifest = json.load(open(os.path.join(APP, "tla.json")))
 89    by = {s["name"]: s for s in manifest["sweeps"]}
 90    for r in rows:
 91        s = by[r["name"]]
 92        r.update(wire=s["wire"], world=s["world"], expect=s["expect"])
 93    return rows, scen.groups(), float(took.group(1))
 94
 95
 96# ─── Source cuts ────────────────────────────────────────────────────────────
 97
 98def cut(path, start, stop=None, include_stop=False):
 99    """The lines of `path` from the first that starts with `start` up to (not
100    including) the next that starts with `stop`, or to the first blank line."""
101    lines = open(os.path.join(APP, path)).read().splitlines()
102    try:
103        i = next(n for n, l in enumerate(lines) if l.startswith(start))
104    except StopIteration:
105        die(f"{path} has no line starting {start!r}")
106    j = i + 1
107    while j < len(lines):
108        if stop is None and lines[j].strip() == "":
109            break
110        if stop is not None and lines[j].startswith(stop):
111            if include_stop:
112                j += 1
113            break
114        j += 1
115    out = lines[i:j]
116    while out and out[-1].strip() == "":
117        out.pop()
118    return "\n".join(out)
119
120
121def highlight_nib(src):
122    """tree-sitter's highlighting of a nib fragment, as the lines of a pre."""
123    staged = tempfile.mkdtemp(prefix=".hl-", dir=TS_DIR)
124    try:
125        f = os.path.join(staged, "cut.nib")
126        open(f, "w").write(src + "\n")
127        # A config of our own, so the grammar is found wherever the user's
128        # tree-sitter config looks: its parser directory is the grammar's parent.
129        cfg = os.path.join(staged, "config.json")
130        json.dump({"parser-directories": [os.path.dirname(TS_DIR)]}, open(cfg, "w"))
131        r = run(["npx", "tree-sitter", "highlight", "--html", "--css-classes",
132                 "--config-path", cfg, "--query-paths=queries/highlights.scm", f], cwd=TS_DIR)
133        if r.returncode != 0:
134            die("tree-sitter highlight failed:\n" + r.stderr)
135    finally:
136        shutil.rmtree(staged, ignore_errors=True)
137    lines = re.findall(r'<td class=line>(.*?)</td>', r.stdout, re.S)
138    if not lines:
139        die("no highlighted lines")
140    return "\n".join(l[:-1] if l.endswith("\n") else l for l in lines)
141
142
143def code(src, lang, caption):
144    body = highlight_nib(src) if lang == "nib" else html.escape(src)
145    return (f'<figure class="code"><pre class="{lang}"><code>{body}</code></pre>'
146            f'<figcaption>{caption}</figcaption></figure>')
147
148
149def entry_line(e, keep=("seq", "kind", "op", "argv", "node", "outcome")):
150    return json.dumps({k: e[k] for k in keep if k in e}, separators=(",", ":"))
151
152
153def find(path, seqs):
154    want = set(seqs)
155    return [e for e in journal.entries(path) if e.get("seq") in want]
156
157
158# ─── Drawing a run ──────────────────────────────────────────────────────────
159
160def timeline(rec, refusal=None, title=""):
161    """Three lanes, one per node, across the run's virtual time."""
162    f = rec["facts"]
163    end = 3000
164    spans = journal.segments(f, end)
165    W, left, right = 900, 92, 34
166    lane_h, gap, top = 34, 26, 30
167    x = lambda t: left + (W - left - right) * min(t, end) / end
168    H = top + 3 * (lane_h + gap) + 26
169    out = [f'<svg class="timeline" viewBox="0 0 {W} {H}" role="img" aria-labelledby="t-{rec["wire"]}">',
170           f'<title id="t-{rec["wire"]}">{html.escape(title)}</title>',
171           '<defs><pattern id="hatch" width="6" height="6" patternUnits="userSpaceOnUse" '
172           'patternTransform="rotate(45)"><line x1="0" y1="0" x2="0" y2="6" class="hatch"/></pattern></defs>']
173    for t in range(0, end + 1, 500):
174        out.append(f'<line class="grid" x1="{x(t):.1f}" x2="{x(t):.1f}" y1="{top - 8}" y2="{H - 22}"/>')
175        out.append(f'<text class="tick" x="{x(t):.1f}" y="{H - 6}" text-anchor="middle">{t} ms</text>')
176    first_apply = {}
177    for t, h, i, cmd in f["applies"]:
178        first_apply.setdefault((h, i), t)
179    for n, h in enumerate(journal.HOSTS):
180        y = top + n * (lane_h + gap)
181        mid = y + lane_h / 2
182        c = COLORS[h]
183        out.append(f'<text class="host" x="0" y="{mid + 4:.1f}">{h}</text>')
184        out.append(f'<line class="lane {c}" x1="{left}" x2="{W - right}" y1="{mid}" y2="{mid}"/>')
185        for s0, s1, role, term in spans[h]:
186            x0, x1 = x(s0), x(s1)
187            if role == "leader":
188                out.append(f'<rect class="leader {c}" x="{x0:.1f}" y="{y + 4}" width="{x1 - x0:.1f}" height="{lane_h - 8}" rx="2"/>')
189                if x1 - x0 > 70:
190                    out.append(f'<text class="role" x="{x0 + 8:.1f}" y="{mid + 4:.1f}">leads term {term}</text>')
191            elif role == "candidate":
192                out.append(f'<rect class="candidate {c}" x="{x0:.1f}" y="{y + 9}" width="{max(x1 - x0, 2):.1f}" height="{lane_h - 18}" rx="2"/>')
193            elif role == "down":
194                out.append(f'<rect class="down" x="{x0:.1f}" y="{y}" width="{x1 - x0:.1f}" height="{lane_h}" fill="url(#hatch)"/>')
195                out.append(f'<text class="downlabel" x="{(x0 + x1) / 2:.1f}" y="{y - 5}" text-anchor="middle">crashed</text>')
196        for (hh, i), t in first_apply.items():
197            if hh == h:
198                out.append(f'<line class="apply {c}" x1="{x(t):.1f}" x2="{x(t):.1f}" y1="{y + lane_h + 2}" y2="{y + lane_h + 9}"/>')
199    if refusal:
200        bt, at, h = refusal["before"][1], refusal["after"][1], refusal["after"][2]
201        n = journal.HOSTS.index(h)
202        y = top + n * (lane_h + gap)
203        # The monitor stops at the refusal: what follows is drawn, but faded,
204        # because nothing after that entry was checked.
205        out.append(f'<rect class="unread" x="{x(at):.1f}" y="{top - 10}" width="{x(end) - x(at):.1f}" height="{H - 22 - top + 10}"/>')
206        out.append(f'<text class="unreadlabel" x="{x(end) - 4:.1f}" y="{top - 16}" text-anchor="end">not checked past the refusal</text>')
207        out.append(f'<line class="refuse" x1="{x(at):.1f}" x2="{x(at):.1f}" y1="{top - 14}" y2="{H - 22}"/>')
208        out.append(f'<circle class="refuse-dot" cx="{x(bt):.1f}" cy="{y + lane_h / 2}" r="5"/>')
209        out.append(f'<circle class="refuse-dot" cx="{x(at):.1f}" cy="{y + lane_h / 2}" r="5"/>')
210        out.append(f'<text class="refuselabel" x="{x(at) + 8:.1f}" y="{top - 16}">refused at entry {refusal["after"][0]}</text>')
211    out.append("</svg>")
212    return "\n".join(out)
213
214
215# ─── The page ───────────────────────────────────────────────────────────────
216
217def main():
218    args = sys.argv[1:]
219    log = None
220    if args[:1] == ["--verify-log"] and len(args) == 2:
221        log = open(args[1]).read()
222    for p in (NIBC, NIBTLA):
223        if not os.path.exists(p):
224            die(f"{p} is not built")
225    tmp = tempfile.mkdtemp(prefix="raft-site-")
226    try:
227        hero = record(tmp, *HERO)
228        bad = record(tmp, *REFUSED)
229        if hero["verdict"] != "admitted" or bad["verdict"] != "refused":
230            die(f"expected admitted/refused, got {hero['verdict']}/{bad['verdict']}")
231        brk = journal.durability_break(bad["facts"])
232        if not brk or str(brk["after"][0]) not in bad["check"]:
233            die("the monitor's refusal is not the save this page explains")
234        if log is None:
235            v = run([NIBTLA, "verify", "areas/examples/raft-nib"], cwd=REPO)
236            log = v.stdout + v.stderr
237        rows, scen, took = verify_rows(log)
238        # Every refused seed again: the run must refuse where verify said it
239        # did, and what the program printed about itself is counted.
240        jobs = [(r, seed) for r in rows if r["expect"] == "refused" for seed in r["at"]]
241
242        def again(job):
243            r, seed = job
244            rec = record(tmp, r["wire"], seed, r["world"])
245            if rec["verdict"] != "refused" or f"seq={r['at'][seed]}" not in rec["check"] \
246                    and str(r["at"][seed]) not in rec["check"]:
247                die(f"{r['wire']} seed {seed} did not refuse at {r['at'][seed]} again")
248            return rec["stdout"][-1].startswith("safe")
249        with ThreadPoolExecutor(max_workers=4) as pool:
250            said_safe = list(pool.map(again, jobs))
251        refused_runs = (len(jobs), sum(said_safe))
252        pair = find(bad["journal"], [brk["before"][0], brk["after"][0]])
253        crash_e = [e for e in journal.entries(bad["journal"]) if e.get("op") == "World.crash"][0]
254        os.makedirs(os.path.join(SITE, "runs"), exist_ok=True)
255        for rec, name in ((hero, "main-crash-3"), (bad, "forgetful-crash-1")):
256            # Compressed with no timestamp, so the same run writes the same bytes.
257            data = gzip.compress(open(rec["journal"], "rb").read(), compresslevel=9, mtime=0)
258            open(os.path.join(SITE, "runs", name + ".jsonl.gz"), "wb").write(data)
259            json.dump(rec["world"], open(os.path.join(SITE, "runs", name + ".world.json"), "w"), indent=2)
260        for src in ("raft.nib", "RaftTrace.tla"):
261            shutil.copyfile(os.path.join(APP, src), os.path.join(SITE, src + ".txt"))
262        page = render(hero, bad, brk, pair, crash_e, rows, scen, took, refused_runs)
263    finally:
264        shutil.rmtree(tmp, ignore_errors=True)
265    open(os.path.join(SITE, "index.html"), "w").write(page)
266    print(f"wrote site/index.html ({len(page)} bytes)")
267
268
269def render(hero, bad, brk, pair, crash_e, rows, scen, took, refused_runs):
270    hf, bf = hero["facts"], bad["facts"]
271    leaders = sorted(hf["leaders"].items())
272    lead_txt = ", ".join(f"{h} leads term {t} from {ms} ms" for t, (h, ms) in leaders)
273    before, after = brk["before"], brk["after"]
274    entries_total = hf["entries"]
275    src_lines = sum(1 for _ in open(os.path.join(APP, "raft.nib")))
276    clock_ops = hf["ops"].get("Time.Sim.now", 0) + hf["ops"].get("Time.Sim.sleep", 0)
277
278    wires = cut("raft.nib", "wire Main", None) + "\n\n" + cut("raft.nib", "wire Forgetful", None)
279    store = cut("raft.nib", "interface Store where", None)
280    ram = cut("raft.nib", "effector Ram is Store", None)
281    handle_sig = cut("raft.nib", "  func handle ::", "    let next")
282    keep = cut("raft.nib", "  func keep ::", None)
283    durable = cut("RaftTrace.tla", "Durable(t0", None)
284    save_arm = cut("RaftTrace.tla", '  \\/ /\\ e.op = "Raft.Store.save"', '  \\/ /\\ e.op = "Raft.Machine.apply"')
285    world = open(os.path.join(APP, "worlds", "crash.json")).read().strip()
286
287    def row(r):
288        ok = (r["expect"] == "admitted" and r["refused"] == 0) or (r["expect"] == "refused" and r["refused"] > 0)
289        result = (f'{r["admitted"]} of {r["seeds"]} admitted' if r["expect"] == "admitted"
290                  else f'{r["refused"]} of {r["seeds"]} refused')
291        return (f'<tr><td><code>{r["wire"]}</code></td><td><code>{r["world"]}</code></td>'
292                f'<td>{r["expect"]}</td><td class="{"held" if ok else "broke"}">{result}</td></tr>')
293
294    table = "\n".join(row(r) for r in rows)
295    T = lambda s: s  # prose is written inline below
296
297    return f"""<!doctype html>
298<html lang="en">
299<head>
300<meta charset="utf-8">
301<meta name="viewport" content="width=device-width, initial-scale=1">
302<title>Raft, checked from its own journal</title>
303<meta name="description" content="Raft written in nib, run on a simulated network that loses, reorders and crashes, and checked entry by entry against a TLA+ safety monitor.">
304<link rel="stylesheet" href="style.css">
305</head>
306<body>
307<header class="top">
308  <p class="crumb"><a href="https://nib.app.jahfer.link">nib</a> / examples / raft</p>
309  <h1>Raft, checked from its own journal</h1>
310  <p class="lede">Three Raft nodes run in one nib process on a simulated network
311  that drops, delays and duplicates messages and crashes machines. Every effect
312  the program performs is written to a journal, and a TLA+ monitor reads that
313  journal entry by entry, refusing the run at the first step that breaks one of
314  Raft's safety rules.</p>
315</header>
316
317<figure class="run hero">
318<div class="scroll">{timeline(hero, title="A run of the correct program under three crashes")}</div>
319<figcaption>
320<p>The correct program, seed {hero['seed']} of <code>worlds/crash.json</code>:
321each node crashes once, for 300 to 500 ms. {lead_txt}. Short ticks under a
322lane are entries that node applied. The run is {entries_total:,} journal
323entries, and the monitor <strong class="ok">admits</strong> all of them.</p>
324<p class="key"><span class="sw leader"></span> leads a term
325<span class="sw candidate"></span> stands for election
326<span class="sw down"></span> crashed</p>
327<p>Download <a href="runs/main-crash-3.jsonl.gz">the journal</a> and
328<a href="runs/main-crash-3.world.json">the world file that makes it</a>.</p>
329</figcaption>
330</figure>
331
332<main>
333<section id="pipeline">
334<h2>How a run becomes a verdict</h2>
335<p>Nothing here inspects the program's memory or instruments its code. The
336program runs as written, and the journal of what it did is the only thing
337checked. Five steps, each a section below:</p>
338<ol class="pipeline">
339  <li><a href="#program"><b>The program</b></a> names every effect it can perform in its types.</li>
340  <li><a href="#world"><b>The world</b></a> answers those effects, and makes every network and timing decision.</li>
341  <li><a href="#journal"><b>The journal</b></a> records each answer and each decision, in order.</li>
342  <li><a href="#monitor"><b>The monitor</b></a> replays the journal against five safety properties.</li>
343  <li><a href="#verdict"><b>The verdict</b></a>: admitted, or refused at a named entry.</li>
344</ol>
345</section>
346
347<section id="program">
348<h2><span class="n">1</span> The program</h2>
349<p><a href="raft.nib.txt"><code>raft.nib</code></a> is leader election and
350log replication for three nodes, in {src_lines} lines. Each node listens on its own
351address, dials its peers, and feeds every message and a timer's ticks into one
352mailbox; its main loop takes one event at a time. A function's type says which
353effects it may perform, so the step that handles one event says it touches the
354store, the network, randomness, the state machine and the voting rules, and
355nothing else:</p>
356{code(handle_sig, "nib", "<code>raft.nib</code>: the event handler's signature. Everything after <code>!</code> is an effect.")}
357<p>The effects are interfaces. What survives a crash (the current term, the
358vote, the log) goes through <code>Store</code>, and every write is a recorded
359operation made before the message it justifies is sent:</p>
360{code(store, "nib", "<code>raft.nib</code>: the persistent state, as an interface.")}
361<p>A <em>wire</em> binds each interface to an implementation. Swapping one
362binding gives a program with a known bug and leaves the rest of the protocol
363alone, so the checks have something to refuse. <code>Forgetful</code> binds a
364store whose <code>recover</code> answers nothing, as a node that never synced
365its writes would:</p>
366{code(wires, "nib", "<code>raft.nib</code>: two of the four wires. <code>Mutant</code> votes twice in a term; <code>Careless</code> ignores the candidate's log.")}
367{code(ram, "nib", "<code>raft.nib</code>: the store that forgets.")}
368</section>
369
370<section id="world">
371<h2><span class="n">2</span> The world</h2>
372<p><code>Net.Sim</code>, <code>Time.Sim</code> and <code>Random.Sim</code> are
373simulated implementations of the network, clock and randomness interfaces.
374All three nodes are fibres in one process; virtual time moves only when every
375fibre is waiting, so three seconds of cluster time take a fraction of a second.
376A world file says what the world does:</p>
377{code(world, "json", "<code>worlds/crash.json</code>: a random schedule, 1 to 40 ms delivery, 5% loss, 2% duplication, and a crash of each node.")}
378<p>Every decision the world makes is a <em>choice</em>: when each message
379arrives (or whether it is lost), which ready fibre runs next, each random
380draw, each crash. A seed makes them; a world file can also state them
381outright. A crash kills every fibre of that host where it stands and closes
382its connections. Effector state survives, because it belongs to the wire,
383not to a fibre, so it is the program's disk. Restarting is the program's own
384work: a supervisor outside the node sees it killed and runs it again.</p>
385{code(keep, "nib", "<code>raft.nib</code>: the supervisor. Its next <code>listen</code> waits until the world brings the host back.")}
386</section>
387
388<section id="journal">
389<h2><span class="n">3</span> The journal</h2>
390<p>Every operation and every choice is a line of JSON, carrying the node that
391performed it and the answer it got. The hero run is {entries_total:,} lines,
392{clock_ops:,} of them clock reads and sleeps. Messages are sent as JSON, so
393the checker can read a message's kind and term out of the bytes. Here is the
394crash, and the two writes the monitor compares in the refused run below
395(fields trimmed):</p>
396<figure class="code"><pre class="journal"><code>{html.escape(entry_line(crash_e))}
397{html.escape(entry_line(pair[0]))}
398{html.escape(entry_line(pair[1]))}</code></pre>
399<figcaption>Entries {crash_e['seq']}, {pair[0]['seq']} and {pair[1]['seq']} of
400<a href="runs/forgetful-crash-1.jsonl.gz">the refused run</a>.</figcaption></figure>
401<p>The same journal is also a replay: run the program against it, and each
402recorded answer and choice is served back in order, so the run happens again
403exactly, crashes included, with no world file needed. <code>nib-tla
404world</code> turns a journal's choices back into a world file, so a failing
405run can be edited and cut down.</p>
406</section>
407
408<section id="monitor">
409<h2><span class="n">4</span> The monitor</h2>
410<p><a href="RaftTrace.tla.txt"><code>RaftTrace.tla</code></a> is not a model
411of Raft. It rebuilds what the journal shows (who led which term, each node's
412log, what was applied and saved) and refuses the journal at the first entry
413that breaks one of these:</p>
414<dl class="props">
415<dt>Election safety</dt><dd>At most one node leads a term. A node leads term
416<i>t</i> when it sends an append of term <i>t</i>.</dd>
417<dt>Log matching</dt><dd>Two logs holding an entry of the same term at the
418same index agree up to that index, checked on every <code>Store.append</code>.</dd>
419<dt>Leader completeness</dt><dd>An entry applied before a node stood for term
420<i>t</i> is in that node's log whenever it leads <i>t</i>.</dd>
421<dt>State machine safety</dt><dd>No two nodes apply different commands at one
422index.</dd>
423<dt>Durability</dt><dd>A node's saved term never goes back, and its vote in a
424term, once saved, never changes.</dd>
425</dl>
426{code(durable + chr(10) + chr(10) + save_arm, "tla", "<code>RaftTrace.tla</code>: Durability, and the step that checks it on each save.")}
427<p>Any operation the monitor does not name is refused too, so a new effect in
428the program cannot pass unexamined. <code>nib-tla</code> checks this with a
429probe: it appends an operation nobody mapped and requires the monitor to
430refuse it.</p>
431</section>
432
433<section id="verdict">
434<h2><span class="n">5</span> The verdict</h2>
435<p>The forgetful store, seed {bad['seed']} of the same world. Node
436{after[2]} voted for {before[4]} in term {before[3]} at {before[1]} ms. It
437crashed, came back with nothing, and at {after[1]} ms heard of term
438{after[3]} again and saved it with no vote: free to vote a second time in a
439term it has already voted in. The monitor refuses the run there, at entry
440{after[0]}, before a second leader exists to show for it.</p>
441<figure class="run">
442<div class="scroll">{timeline(bad, refusal=brk, title="The forgetful store, refused at the save that erased a vote")}</div>
443<figcaption><p>Dots mark the two saves: the vote, and the save that erased
444it. The program's own end-of-run check, which compares what every node
445applied, printed <code>{html.escape(bad['stdout'][-1])}</code>.</p></figcaption>
446</figure>
447<p>That last line is the point. Of the {refused_runs[0]} refused runs in the
448table below, {refused_runs[1]} printed <code>safe</code>: the nodes agreed at
449the end, and the bug was invisible to "it ran and agreed with itself". On
450every commit, CI runs <code>nib-tla verify
451areas/examples/raft-nib</code>: one calm run, then each sweep below over a range of
452seeds. The correct program must be admitted on every seed, and each broken
453wire must be refused on at least one.</p>
454<div class="scroll"><table>
455<thead><tr><th>wire</th><th>world</th><th>expected</th><th>result</th></tr></thead>
456<tbody>
457<tr><td><code>Main</code></td><td><code>worlds/calm.json</code></td><td>admitted</td><td class="held">{scen[1]}, {int(scen[2]):,} entries</td></tr>
458{table}
459</tbody></table></div>
460<p class="small">The whole check took {took:.0f} s on a laptop.</p>
461</section>
462
463<section id="platform">
464<h2>What nib provides</h2>
465<p>None of this is special to Raft. It follows from four decisions in the
466language and its runtime:</p>
467<dl class="props">
468<dt>Effects are in the types</dt><dd>A function lists what it may do. So
469every way the program touches the world is a named operation with a
470signature, which is exactly what a journal can record and a monitor can
471name.</dd>
472<dt>Wires choose implementations</dt><dd>The same program runs on real
473sockets or on <code>Net.Sim</code>, and a known-wrong variant is one binding
474away, with no mocks and no flags in the protocol code.</dd>
475<dt>The scheduler has one choice point</dt><dd>Fibres change hands only
476where one waits, and every such switch asks the world which ready fibre runs
477next. Under a seed that choice is random; in a journal it is recorded; in a
478replay it is served back.</dd>
479<dt>The journal is the run</dt><dd>Operations are recorded when they complete,
480each with its node, fibre and message id, and chained by digest. The same
481file drives replay, the checker, and the world file that reproduces it.</dd>
482</dl>
483</section>
484
485<section id="limits">
486<h2>What this does not show</h2>
487<ul>
488<li>It checks the runs it is given: tens of seeds, not every interleaving.
489A bug that needs a schedule no seed draws goes unseen.</li>
490<li>The monitor checks safety only. A run in which no leader is ever elected is
491admitted.</li>
492<li>Leader completeness is checked only as far as the journal can settle it:
493commits are inferred from applies.</li>
494<li>Everything runs on the simulated world. Real sockets can be recorded, but
495not yet replayed with concurrent servers.</li>
496</ul>
497</section>
498
499<section id="run">
500<h2>Run it yourself</h2>
501<p>From a checkout of the repository, with <code>nibc</code> and
502<code>nib-tla</code> built:</p>
503<pre class="shell"><code>nibc --run areas/examples/raft-nib/raft.nib --wire Main \\
504  --world areas/examples/raft-nib/worlds/crash.json --journal-out run.jsonl
505nib-tla check --spec areas/examples/raft-nib/RaftTrace.tla --journal run.jsonl
506nib-tla verify areas/examples/raft-nib</code></pre>
507<p><code>explore.sh</code> runs any wire under many seeds and keeps each
508refused run with the world file that reproduces it.</p>
509</section>
510</main>
511
512<footer>
513<p>Generated from runs of the program in
514<code>areas/examples/raft-nib</code> by <code>gen/build.py</code>; every
515number and journal line on this page comes from those runs. The source is
516also here as text: <a href="raft.nib.txt">raft.nib</a>,
517<a href="RaftTrace.tla.txt">RaftTrace.tla</a>.
518About nib: <a href="https://nib.app.jahfer.link">nib.app.jahfer.link</a>.</p>
519</footer>
520</body>
521</html>
522"""
523
524
525if __name__ == "__main__":
526    main()