# paper/analyze.py — every number and figure in PAPER.md is computed here from raw files in this repo. # Inputs: paper/data/raw.jsonl (calm-box raw latencies), p5/results/*.jsonl (P5 runs), paper/data/quality-sessions.jsonl. # Outputs: paper/data/stats.json, paper/data/tables.md, paper/fig/*.png, paper/PAPER.md (PAPER.src.md + tables). Run: paper/.venv/bin/python paper/analyze.py import json, math, collections, os, re import numpy as np, matplotlib matplotlib.use("Agg"); import matplotlib.pyplot as plt R = os.path.dirname(os.path.dirname(os.path.abspath(__file__))); rng = np.random.default_rng(20261204); B = 5000 T3 = ["celld", "workerd", "orange"]; NAME = {"celld": "celld", "workerd": "workerd cluster", "orange": "Rivet/OpenOrange", "live": "Cloudflare (live)"} COL = {"celld": "#1f77b4", "workerd": "#2ca02c", "orange": "#d62728", "live": "#ff7f0e"} S = {}; md = [] def J(p): return [json.loads(l) for l in open(p) if l.strip().startswith("{")] def pct(a, q): return float(np.percentile(a, q, method="lower")) def boot(a, f, b=B): a = np.asarray(a); idx = rng.integers(0, len(a), (b, len(a))); v = np.array([f(a[i]) for i in idx]); return [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))] def wilson(k, n, z=1.96): if n == 0: return [None, None] p = k / n; d = 1 + z*z/n; c = (p + z*z/(2*n)) / d; h = z*math.sqrt(p*(1-p)/n + z*z/(4*n*n)) / d; return [max(0.0, round(100*(c-h), 1)), min(100.0, round(100*(c+h), 1))] f1 = lambda x: f"{x:.1f}" ci = lambda c: f"[{c[0]:.1f}, {c[1]:.1f}]" # ---- 1. calm-box raw latency (C=2, 3 reps x 1000 per scenario, 50 warm-up discarded) ---- raw = J(f"{R}/paper/data/raw.jsonl"); S["raw"] = {} md.append("### T1. Calm-box latency, C=2, raw samples (ms)\n\n| System | Scenario | n | errors | mean ± sd | p50 [95% CI] | p95 [95% CI] | p99 [95% CI] | rps per rep (mean ± sd, n=3) | load1 |\n|---|---|---|---|---|---|---|---|---|---|") for t in T3: for sc in ["version", "do_read", "do_write"]: rs = [r for r in raw if r["label"] == t and r["scenario"] == sc] a = np.concatenate([r["lat"] for r in rs]); err = sum(r["err"] for r in rs); rps = [r["n"] / r["wall_s"] for r in rs] st = {"n": int(len(a)), "errors": err, "mean": float(a.mean()), "sd": float(a.std(ddof=1)), "p50": pct(a, 50), "p95": pct(a, 95), "p99": pct(a, 99), "p50_ci": boot(a, lambda x: np.percentile(x, 50), 2000), "p95_ci": boot(a, lambda x: np.percentile(x, 95), 2000), "p99_ci": boot(a, lambda x: np.percentile(x, 99), 2000), "rps_mean": float(np.mean(rps)), "rps_sd": float(np.std(rps, ddof=1)), "load1": [r["load1"] for r in rs]} S["raw"][f"{t}/{sc}"] = st md.append(f"| {NAME[t]} | {sc} | {st['n']} | {err} | {st['mean']:.2f} ± {st['sd']:.2f} | {st['p50']:.2f} {ci(st['p50_ci'])} | {st['p95']:.2f} {ci(st['p95_ci'])} | {st['p99']:.2f} {ci(st['p99_ci'])} | {st['rps_mean']:.0f} ± {st['rps_sd']:.0f} | {min(st['load1']):.1f}–{max(st['load1']):.1f} |") fig, ax = plt.subplots(1, 3, figsize=(15, 4.2)) for k, sc in enumerate(["version", "do_read", "do_write"]): for t in T3: a = np.sort(np.concatenate([r["lat"] for r in raw if r["label"] == t and r["scenario"] == sc])); ax[k].plot(a, np.arange(1, len(a)+1)/len(a), label=NAME[t], color=COL[t]) ax[k].set_xscale("log"); ax[k].set_title(f"{sc} (C=2, n=3000 per system)"); ax[k].set_xlabel("latency, ms (log)"); ax[k].set_ylabel("CDF"); ax[k].grid(alpha=.3) for q in (.5, .95, .99): ax[k].axhline(q, color="grey", lw=.5, ls=":") ax[0].legend(); fig.tight_layout(); fig.savefig(f"{R}/paper/fig/fig1-latency-cdf.png", dpi=130); plt.close(fig) # ---- 2. P5 load runs (C=10/20, N=2000; percentiles only) + live (C=2, N=200) ---- res = {t: J(f"{R}/p5/results/{t}.jsonl") for t in T3}; live = J(f"{R}/p5/results/live.jsonl") md.append("\n### T2. Loaded latency from the P5 runs (percentiles as recorded by the harness; raw samples not kept)\n\n| System | Scenario | n | conc | p50 | p95 | p99 | rps | errors | box load1 at start |\n|---|---|---|---|---|---|---|---|---|---|") S["p5bench"] = {} for t in T3: first = {} load = next((x["load1"] for x in res[t] if x.get("step") == "bench" and "load1" in x), None) for x in res[t]: if x.get("step") == "bench" and "scenario" in x and x["n"] == 2000 and x["scenario"] not in first: first[x["scenario"]] = x for sc, x in first.items(): S["p5bench"][f"{t}/{sc}"] = x md.append(f"| {NAME[t]} | {sc} | {x['n']} | {x['conc']} | {x['p50']} | {x['p95']} | {x['p99']} | {x['rps']} | {x['errors']} | {load} |") S["live"] = live for x in live: sv = x["server_ms"]; md.append(f"| {NAME['live']} | {x['scenario']} | {x['n']} | {x['conc']} | {x['p50']} | {x['p95']} | {x['p99']} | {x['rps']} | {x['errors']} | n/a |") md.append("\n### T3. Cloudflare: client-observed vs server-side (`x-cm-timing`) latency, ms (n=200 per scenario, C=2)\n\n| Scenario | client p50 / p95 / p99 | server p50 / p95 / p99 (n) | client − server at p50 |\n|---|---|---|---|") for x in live: sv = x["server_ms"] md.append(f"| {x['scenario']} | {x['p50']} / {x['p95']} / {x['p99']} | " + (f"{sv['p50']} / {sv['p95']} / {sv['p99']} ({sv['n']})" if sv["n"] else "not reported by this route (0)") + " | " + (f"{x['p50']-sv['p50']:.1f}" if sv["n"] else "—") + " |") fig, ax = plt.subplots(figsize=(7, 4)); xs = np.arange(3); w = .38 dl = [x for x in live if x["server_ms"]["n"]] for i, x in enumerate(dl): c = [x["p50"], x["p95"], x["p99"]]; s = [x["server_ms"]["p50"], x["server_ms"]["p95"], x["server_ms"]["p99"]] ax.bar(xs + (i-.5)*w, s, w, color=COL["live"], alpha=.9 if i else .6, label=f"{x['scenario']}: server") ax.bar(xs + (i-.5)*w, np.array(c)-np.array(s), w, bottom=s, color="grey", alpha=.5 if i else .3, label=f"{x['scenario']}: client − server") ax.set_xticks(xs, ["p50", "p95", "p99"]); ax.set_ylabel("ms"); ax.set_title("Cloudflare live: server time vs the rest (n=200 each, C=2)"); ax.legend(fontsize=8); ax.grid(axis="y", alpha=.3) fig.tight_layout(); fig.savefig(f"{R}/paper/fig/fig6-live-decomposition.png", dpi=130); plt.close(fig) # ---- 3. throughput (c=10, 30 s, read+write mix through client-side LB) ---- md.append("\n### T4. Throughput, closed loop, c=10, 30 s, DO read/write mix (one run per system)\n\n| System | requests | rps | errors | p50 | p95 | p99 | max | LB retries |\n|---|---|---|---|---|---|---|---|---|") S["thr"] = {} for t in T3: x = next(x for x in res[t] if x.get("step") == "throughput_c10"); S["thr"][t] = x md.append(f"| {NAME[t]} | {x['requests']} | {x['requests']/x['secs']:.0f} | {x['errors']} | {x['p50']} | {x['p95']} | {x['p99']} | {x['max_ms']} | {x['lb_retries']} |") fig, ax = plt.subplots(figsize=(6, 3.6)) ax.bar([NAME[t] for t in T3], [S["thr"][t]["requests"]/30 for t in T3], color=[COL[t] for t in T3]); ax.set_ylabel("requests/s"); ax.set_title("Throughput, c=10, 30 s (n=1 run each)"); ax.grid(axis="y", alpha=.3) fig.tight_layout(); fig.savefig(f"{R}/paper/fig/fig2-throughput.png", dpi=130); plt.close(fig) # ---- 4. scale: new tenants created in parallel (C=16) ---- md.append("\n### T5. Scale: N fresh tenants created at C=16 (success %, Wilson 95% CI)\n\n| System | run | N | ok | success % [95% CI] | seconds | box load1 | dominant error |\n|---|---|---|---|---|---|---|---|") S["scale"] = collections.defaultdict(list) for t in T3: ctx = None; run = 0; lastN = 10**9 for x in res[t]: if x.get("step", "").startswith("scale") and "at" in x: ctx = x; n_ = int(x["step"][5:]) if n_ <= lastN: run += 1 lastN = n_ if x.get("step", "").startswith("scale") and "ok" in x: e = max(x["ex"].items(), key=lambda kv: kv[1])[0][:60] if x["ex"] else "—" row = {"run": run, "N": x["N"], "ok": x["ok"], "secs": x["secs"], "ci": wilson(x["ok"], x["N"]), "load1": ctx["load1"] if ctx else None, "err": e} S["scale"][t].append(row) md.append(f"| {NAME[t]} | {run} | {x['N']} | {x['ok']} | {100*x['ok']/x['N']:.1f} {row['ci']} | {x['secs']} | {row['load1']} | {e.replace('|','/')} |") fig, ax = plt.subplots(figsize=(7, 4)) for t in T3: best = max({r["run"] for r in S["scale"][t]}, key=lambda k: sum(r["ok"] for r in S["scale"][t] if r["run"] == k)) rows = [r for r in S["scale"][t] if r["run"] == best] Ns = [r["N"] for r in rows]; p = [100*r["ok"]/r["N"] for r in rows]; lo = [p[i]-rows[i]["ci"][0] for i in range(len(rows))]; hi = [rows[i]["ci"][1]-p[i] for i in range(len(rows))] ax.errorbar(Ns, p, yerr=[lo, hi], marker="o", capsize=3, label=NAME[t], color=COL[t]) ax.plot([400, 1000], [100, 98.4], marker="o", mfc="none", ls=":", color=COL["celld"], label="celld, earlier run on a calm box (P4: 400/400, 984/1000)") ax.set_xscale("log"); ax.minorticks_off(); ax.set_xticks([200, 400, 1000], ["200", "400", "1000"]); ax.set_ylabel("tenants created OK, %"); ax.set_xlabel("parallel new tenants (C=16)"); ax.set_ylim(0, 105) ax.set_title("Scale: best full run per system (Wilson 95% CI)\ncelld points at 400/1000 ran at box load 11-70"); ax.grid(alpha=.3); ax.legend(fontsize=8); fig.tight_layout(); fig.savefig(f"{R}/paper/fig/fig3-scale.png", dpi=130); plt.close(fig) # ---- 5. resilience: kill -9 and rolling restart ---- md.append("\n### T6. Resilience (one trial each; error rates with Wilson 95% CI)\n\n| System | test | attempted / requests | acked | acked lost | errors | error % [95% CI] | outage s | notes |\n|---|---|---|---|---|---|---|---|---|") S["res"] = {} for t in T3: k = [x for x in res[t] if x.get("step") == "kill9" and "acked" in x][-1] rr = [x for x in res[t] if x.get("step") in ("rolling", "rolling_restart", "rr") and isinstance(x.get("lb"), dict)] if not rr and os.path.exists(f"{R}/paper/data/rolling-{t}.json"): nodes = open(f"{R}/paper/data/rolling-{t}-nodes.txt").read().strip().splitlines()[-2:] rr = [{"lb": json.load(open(f"{R}/paper/data/rolling-{t}.json")), "rr": "; ".join(l.split("] ")[1] for l in nodes)}] if t == "workerd": k = dict(k, acked_lost=0, note="1 write first read back as lost (transient 500) was present on re-read 3 min later") S["res"][t] = {"kill9": k, "rolling": rr[-1] if rr else None} md.append(f"| {NAME[t]} | kill -9 one of 2 nodes, 60 s writer | {k['attempted']} | {k['acked']} | {k['acked_lost']} | {k['errors']} | {100*k['errors']/k['attempted']:.1f} {wilson(k['errors'], k['attempted'])} | {k['outage_ms']/1000:.1f} | {k.get('note', '—')} |") if rr: lb = rr[-1]["lb"]; md.append(f"| {NAME[t]} | rolling restart under c=10 load | {lb['requests']} | — | — | {lb['errors']} | {100*lb['errors']/lb['requests']:.2f} {wilson(lb['errors'], lb['requests'])} | — | LB retries {lb['lb_retries']}; {rr[-1].get('rr', '')} |") # ---- 6. resources: RSS / CPU time series ---- md.append("\n### T7. Resident memory and CPU during the P5 load runs (2 s samples; summed over all processes of a role)\n\n| System | process group | samples n | RSS median (MB) | RSS mean ± sd | RSS p95 | RSS max | CPU mean % ± sd | CPU p95 % |\n|---|---|---|---|---|---|---|---|---|") fig, ax = plt.subplots(3, 1, figsize=(10, 8), sharex=False); S["rss"] = {} for i, t in enumerate(T3): rows = J(f"{R}/p5/results/{t}-res.jsonl"); t0 = rows[0]["t"] keys = sorted({k for r in rows for k in r["rss_mb"]}) for k in keys: rs = np.array([r["rss_mb"].get(k, 0) for r in rows]); cp = np.array([r["cpu_pct"].get(k, 0) for r in rows[1:]]) if t == "workerd" and "workerd" in k: tag = " (contaminated: also matched an unrelated workerd)" else: tag = "" S["rss"][f"{t}/{k}"] = {"n": len(rs), "median": float(np.median(rs)), "mean": float(rs.mean()), "sd": float(rs.std(ddof=1)), "p95": pct(rs, 95), "max": float(rs.max()), "cpu_mean": float(cp.mean()), "cpu_sd": float(cp.std(ddof=1)), "cpu_p95": pct(cp, 95)} s = S["rss"][f"{t}/{k}"] md.append(f"| {NAME[t]} | {k}{tag} | {s['n']} | {s['median']:.0f} | {s['mean']:.0f} ± {s['sd']:.0f} | {s['p95']:.0f} | {s['max']:.0f} | {s['cpu_mean']:.0f} ± {s['cpu_sd']:.0f} | {s['cpu_p95']:.0f} |") ax[i].plot([(r["t"]-t0)/60 for r in rows], rs, label={"bin/celld": "celld (2 nodes)", "rustfs server": "RustFS store", "workerd serve": "workerd (contaminated)", "engine-cli-linux-x64-musl/rivet-engine": "Rivet engines (3)", "oo-cli/node_modules": "OpenOrange nodes (2)"}.get(k, k)) a2 = ax[i].twinx(); a2.plot([(r["t"]-t0)/60 for r in rows], [r["load1"] for r in rows], color="black", lw=.7, ls="--", label="box load1"); a2.set_ylabel("load1") ax[i].set_title(f"{NAME[t]}: RSS per process group (solid) and box load1 (dashed)" + (" — workerd series also includes an unrelated workerd process" if t == "workerd" else ""), fontsize=9); ax[i].set_ylabel("RSS MB"); ax[i].legend(fontsize=7, loc="upper left"); ax[i].grid(alpha=.3) ax[-1].set_xlabel("minutes since sampler start"); fig.tight_layout(); fig.savefig(f"{R}/paper/fig/fig4-resources-load.png", dpi=120); plt.close(fig) # ---- 7. quality ---- Q = J(f"{R}/paper/data/quality-sessions.jsonl"); S["q"] = {} DP = {'P-W3':.1136,'P-edit':.0234,'P-git':.0272,'P-grep':.0505,'P-json':.0286,'P-minitest':.0542,'P-tests':.0673} # historical pooled Claude D (tools/clsave.py) def saving(G, D): # G, D: dict task -> list usd; equal task weights (sum of task means) ts = [t for t in G if len(G[t]) and t in D and len(D[t])]; return 100 * (1 - sum(np.mean(G[t]) for t in ts) / sum(np.mean(D[t]) for t in ts)) def boot_sav(G, D, b=B): v = [] for _ in range(b): g = {t: rng.choice(G[t], len(G[t])) for t in G if len(G[t])}; d = {t: rng.choice(D[t], len(D[t])) for t in D if len(D[t])}; v.append(saving(g, d)) return [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))] md.append("\n### T8. Quality and token-cost saving (G = through the gateway, D = direct to the model API)\n\n| Suite | System | G sessions n | G pass | G voids | saving % vs D | 95% bootstrap CI | D reference | Claude: saving vs historical pooled D |\n|---|---|---|---|---|---|---|---|---|") cxD = collections.defaultdict(list) for x in Q: if x["suite"] == "codex" and x["target"] == "direct-baseline": cxD[x["task"]].append(x["usd"]) clD = collections.defaultdict(list) for x in Q: if x["suite"] == "claude" and x["arm"] == "D" and not x["void"] and x["usd"] is not None: clD[x["task"]].append(x["usd"]) for suite in ["codex", "claude"]: for t in T3 + ["live"]: g = [x for x in Q if x["suite"] == suite and x["target"] == t and x["arm"] == "G"] G = collections.defaultdict(list) for x in g: if not x["void"] and x["usd"] is not None: G[x["task"]].append(x["usd"]) D = cxD if suite == "codex" else clD sv = saving(G, D); c = boot_sav(G, D); npass = sum(1 for x in g if x["passed"] and not x["void"]); nv = sum(1 for x in g if x["void"]) S["q"][f"{suite}/{t}"] = {"n": len(g), "pass": npass, "voids": nv, "saving": sv, "ci": c} ref = "direct run, n=14 (2/task)" if suite == "codex" else f"P5 in-run D pooled over 4 runs, n={sum(len(v) for v in clD.values())}" hist = f"{saving(G, {k: [v] for k, v in DP.items()}):.1f}" if suite == "claude" else "—" S["q"][f"{suite}/{t}"]["hist"] = hist md.append(f"| {suite} | {NAME[t]} | {len(g)} | {npass}/{len(g)-nv} | {nv} | {sv:.1f} | {ci(c)} | {ref} | {hist} |") fig, ax = plt.subplots(figsize=(8, 4)); xs = np.arange(4); w = .38 for j, suite in enumerate(["codex", "claude"]): v = [S["q"][f"{suite}/{t}"]["saving"] for t in T3 + ["live"]]; lo = [v[i]-S["q"][f"{suite}/{t}"]["ci"][0] for i, t in enumerate(T3 + ["live"])]; hi = [S["q"][f"{suite}/{t}"]["ci"][1]-v[i] for i, t in enumerate(T3 + ["live"])] ax.bar(xs + (j-.5)*w, v, w, yerr=[lo, hi], capsize=3, label=suite, alpha=.85) ax.set_xticks(xs, [NAME[t] for t in T3 + ["live"]]); ax.set_ylabel("cost saving vs direct, %"); ax.set_title("Token-cost saving with 95% bootstrap CI (n=2 sessions per task)"); ax.legend(); ax.grid(axis="y", alpha=.3) fig.tight_layout(); fig.savefig(f"{R}/paper/fig/fig5-quality.png", dpi=130); plt.close(fig) json.dump(S, open(f"{R}/paper/data/stats.json", "w"), default=str, indent=0) open(f"{R}/paper/data/tables.md", "w").write("\n".join(md) + "\n") src = open(f"{R}/paper/PAPER.src.md").read(); tb = "\n".join(md) for m in re.finditer(r"### (T\d)\. .*?(?=\n### T\d\.|\Z)", tb, re.S): src = src.replace(f"@@{m.group(1)}@@", m.group(0).strip()) assert "@@" not in src; open(f"{R}/paper/PAPER.md", "w").write(src) print("ok", len(md))