Files

465 lines
24 KiB
Python

#!/usr/bin/env python3
"""Index, transcripts and deltas of the Codex lossy-delta runs (test tooling, stdlib only, Python 3.9+).
index.py RUNS_ROOT [--out DIR] [--no-transcripts]
Reads every cell under RUNS_ROOT (`[set/]V?/<task>-r<k>/cell.json`) and writes into --out (default RUNS_ROOT/_index):
index.csv one row per cell (variant, task, repeat, rounds, accepted, token distributions, wall, tok/s, skip counters, final message tail, paths)
rounds.csv one row per model request (input / cached / output / reasoning tokens, times, status, the actions the model took)
index.md the same as a table, the per-task lossy-minus-lossless round deltas (V1-V2 vanilla, V3-V4 ours, cross deltas), the spread across repeats,
the first point where lossy and lossless sessions diverge, and the greedy-determinism check (same variant, repeat 1 against repeat 2)
and, unless --no-transcripts, CELL/transcript.md: the session in reading order (every round: new tool outputs, the model's reasoning, calls, messages).
It makes NO quality judgement; it only computes numbers and points to where to read.
"""
import csv
import glob
import gzip
import json
import math
import os
import re
import statistics
import sys
LABEL = {"V1": "vanilla lossy", "V2": "vanilla lossless", "V3": "ours lossy", "V4": "ours lossless"}
PAIRS = [("V1", "V2", "vanilla"), ("V3", "V4", "ours")]
CROSS = [("V3", "V1", "lossy: ours minus vanilla"), ("V4", "V2", "lossless: ours minus vanilla")]
# ---------------------------------------------------------------------------------------------------------------- reading
def jl(path):
out = []
try:
with open(path, encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if line:
try:
out.append(json.loads(line))
except ValueError:
pass
except OSError:
pass
return out
def gz_json(path):
try:
return json.loads(gzip.open(path, "rb").read().decode("utf-8", errors="replace"))
except (OSError, ValueError):
return None
def gz_text(path):
try:
return gzip.open(path, "rb").read().decode("utf-8", errors="replace")
except OSError:
return ""
def find_cells(root):
cells = []
for cj in sorted(glob.glob(os.path.join(root, "**", "cell.json"), recursive=True)):
d = os.path.dirname(cj)
if "/_index" in d.replace(os.sep, "/"):
continue
rel = os.path.relpath(d, root).replace(os.sep, "/")
parts = rel.split("/")
sset = "/".join(parts[:-2])
cells.append((sset, d, json.load(open(cj))))
return cells
def sse_items(text):
"""Output items (from response.output_item.done) and the terminal response object of an SSE body."""
items, final = [], None
for line in text.splitlines():
if line.startswith("data:"):
try:
d = json.loads(line[5:].strip())
except ValueError:
continue
t = d.get("type")
if t == "response.output_item.done":
items.append(d.get("item") or {})
elif t in ("response.completed", "response.incomplete", "response.failed"):
final = d.get("response") or d
if not items and final:
items = final.get("output") or []
if not items and text.lstrip().startswith("{"):
try:
items = json.loads(text).get("output") or []
except ValueError:
pass
return items, final
def action_of(item):
t = item.get("type")
if t == "function_call":
return "call %s %s" % (item.get("name"), (item.get("arguments") or "").strip())
if t == "message":
txt = "".join(c.get("text") or "" for c in item.get("content") or [] if isinstance(c, dict))
return "message %s" % txt.strip()
if t == "reasoning":
return None # reasoning text is not an action
return "%s %s" % (t, json.dumps(item, sort_keys=True)[:200])
def item_text(item):
t = item.get("type")
if t == "function_call":
return "CALL %s(%s)" % (item.get("name"), item.get("arguments"))
if t == "message":
return "MESSAGE: " + "".join(c.get("text") or "" for c in item.get("content") or [] if isinstance(c, dict))
if t == "reasoning":
summ = " ".join((s.get("text") or "") for s in item.get("summary") or [] if isinstance(s, dict))
cont = " ".join((s.get("text") or "") for s in item.get("content") or [] if isinstance(s, dict))
enc = len(item.get("encrypted_content") or "")
return "REASONING: %s%s%s" % (summ, cont, (" [encrypted %d bytes]" % enc) if enc else "")
if t == "function_call_output":
out = item.get("output")
return "TOOL OUTPUT (%s): %s" % (item.get("call_id"), out if isinstance(out, str) else json.dumps(out))
if t == "message" or item.get("role"):
c = item.get("content")
if isinstance(c, list):
c = "".join(x.get("text") or "" for x in c if isinstance(x, dict))
return "%s: %s" % (item.get("role"), c)
return json.dumps(item)[:1000]
# ---------------------------------------------------------------------------------------------------------------- one cell
def cell_rounds(d):
return [r for r in jl(os.path.join(d, "proxy", "rounds.jsonl")) if r.get("round")]
def counters(d, info):
"""Route tail skip counters of the cell from the engine log slice (ours: per request lines; vanilla: cumulative lines)."""
out = {"skip_entries": None, "skip_experts": None, "skip_source": ""}
p = os.path.join(d, "engine-slice.log")
try:
text = open(p, errors="replace").read()
except OSError:
return out
if re.search(r"route tail skip: (\d+) missed experts skipped \((\d+) entries\)", text):
# cumulative since the engine start: the value at the start of the cell is the last one logged before it (read from the stack log)
base_e = base_x = 0
stack_log = (info.get("stack") or {}).get("engine_log")
off = info.get("engine_log_start_offset") or 0
if stack_log and os.path.exists(stack_log) and off:
with open(stack_log, "rb") as f:
head = f.read(off).decode("utf-8", errors="replace")
prev = re.findall(r"route tail skip: (\d+) missed experts skipped \((\d+) entries\)", head)
if prev:
base_x, base_e = int(prev[-1][0]), int(prev[-1][1])
last_x, last_e = [(int(a), int(b)) for a, b in re.findall(r"route tail skip: (\d+) missed experts skipped \((\d+) entries\)", text)][-1]
out.update({"skip_entries": last_e - base_e, "skip_experts": last_x - base_x, "skip_source": "vanilla cumulative delta"})
return out
pat = r"expert tier:.*?route tail skip (\d+) entries / (\d+) experts"
ours = re.findall(pat, text)
tiers = re.findall(r"leleka-serve expert tier:", text)
if ours:
# the counters are cumulative since the engine start: last value of the cell minus the last value logged before it
base_e = base_x = 0
stack_log = (info.get("stack") or {}).get("engine_log")
off = info.get("engine_log_start_offset") or 0
if stack_log and os.path.exists(stack_log) and off:
with open(stack_log, "rb") as f:
head = f.read(off).decode("utf-8", errors="replace")
prev = re.findall(pat, head)
if prev:
base_e, base_x = int(prev[-1][0]), int(prev[-1][1])
le, lx = int(ours[-1][0]), int(ours[-1][1])
out.update({"skip_entries": le - base_e, "skip_experts": lx - base_x, "skip_source": "ours cumulative delta (entries, distinct-expert count as logged)"})
elif tiers:
out.update({"skip_entries": 0, "skip_experts": 0, "skip_source": "ours: %d tier lines, none with a tail skip" % len(tiers)})
return out
def pct(xs, p):
if not xs:
return None
xs = sorted(xs)
return xs[min(len(xs) - 1, int(p * len(xs)))]
def summarize(sset, d, info):
rs = cell_rounds(d)
ok = [r for r in rs if (r.get("resp") or {}).get("terminal") == "response.completed"]
inp = [(r.get("resp") or {}).get("input_tokens") for r in rs]
outt = [(r.get("resp") or {}).get("output_tokens") for r in rs]
inp = [x for x in inp if isinstance(x, int)]
outt = [x for x in outt if isinstance(x, int)]
dec_ms = sum((r.get("t_end_ms") or 0) - (r.get("t_first_byte_ms") or r.get("t_end_ms") or 0) for r in ok)
tot_out = sum(outt)
model_ms = sum((r.get("t_end_ms") or 0) - (r.get("t_start_ms") or 0) for r in rs)
events = jl(os.path.join(d, "codex-events.jsonl"))
tool_calls = sum(1 for e in events if e.get("type") == "item.completed" and (e.get("item") or {}).get("type") == "command_execution")
c = counters(d, info)
row = {
"set": sset, "variant": info["variant"], "label": LABEL.get(info["variant"], ""), "task": info["task"], "rep": info["rep"],
"rounds": len(rs), "rounds_completed": len(ok), "rounds_failed": len(rs) - len(ok),
"accepted": "yes" if info.get("accepted") else "no", "termination": info.get("termination"), "codex_rc": info.get("codex_rc"),
"wall_s": info.get("wall_s"), "model_s": round(model_ms / 1000, 1),
"in_tokens_total": sum(inp), "out_tokens_total": tot_out, "ctx_peak": max(inp) if inp else None,
"in_per_round_p50": pct(inp, .5), "in_per_round_p90": pct(inp, .9), "out_per_round_p50": pct(outt, .5), "out_per_round_p90": pct(outt, .9), "out_per_round_max": max(outt) if outt else None,
"cached_tokens_total": sum((r.get("resp") or {}).get("cached_tokens") or 0 for r in rs),
"decode_tok_s": round(tot_out / (dec_ms / 1000), 1) if dec_ms > 0 else None,
"tool_calls": tool_calls, "skip_entries": c["skip_entries"], "skip_experts": c["skip_experts"], "skip_source": c["skip_source"],
"final_message_tail": re.sub(r"\s+", " ", info.get("final_message_tail") or "")[-240:],
"cell_dir": d, "session_log": os.path.join(d, "proxy", "rounds.jsonl"), "transcript": os.path.join(d, "transcript.md"),
"codex_rollout": (glob.glob(os.path.join(d, "codex-home", "sessions", "**", "rollout-*.jsonl"), recursive=True) or [""])[0],
"start_utc": info.get("start_utc"), "uptime_s_at_block": (info.get("stack") or {}).get("uptime_s_at_block"),
}
return row, rs
# ---------------------------------------------------------------------------------------------------------------- transcript
def build_actions(d, rs):
"""Per round: (new input items, output items, terminal). Reads the gzip request / response bodies."""
acts, prev_in, prev_out = [], None, []
for r in rs:
s = "%04d" % r["seq"]
req = gz_json(os.path.join(d, "proxy", "rounds", s + ".req.json.gz")) or {}
inp = req.get("input") if isinstance(req.get("input"), list) else []
items, final = sse_items(gz_text(os.path.join(d, "proxy", "rounds", s + ".resp.sse.gz")))
if prev_in is None:
new = inp
note = "first request"
else:
base = len(prev_in) + len(prev_out)
if len(inp) >= base and inp[:len(prev_in)] == prev_in:
new = inp[base:]
note = ""
else:
new = inp
note = "history was rewritten (retry or compaction): all %d input items shown" % len(inp)
acts.append({"seq": r["seq"], "round": r["round"], "req": req, "new": new, "note": note, "out": items, "final": final, "rec": r})
prev_in, prev_out = inp, items
return acts
def write_transcript(d, acts, info):
lines = []
lines.append("# %s %s r%s (%s)" % (info["variant"], info["task"], info["rep"], LABEL.get(info["variant"], "")))
lines.append("accepted=%s termination=%s wall=%ss rounds=%d" % (info.get("accepted"), info.get("termination"), info.get("wall_s"), len(acts)))
lines.append("")
for a in acts:
rec, u = a["rec"], (a["rec"].get("resp") or {})
lines.append("## round %d (proxy seq %d) status=%s in=%s cached=%s out=%s reasoning=%s t=%s..%s ms" % (
a["round"], a["seq"], rec.get("status"), u.get("input_tokens"), u.get("cached_tokens"), u.get("output_tokens"), u.get("reasoning_tokens"),
rec.get("t_start_ms"), rec.get("t_end_ms")))
if a["note"]:
lines.append("(%s)" % a["note"])
for it in a["new"]:
txt = item_text(it) if isinstance(it, dict) else str(it)
if a["round"] == 1 and isinstance(it, dict) and it.get("role") in ("developer", "system") and len(txt) > 3000:
txt = txt[:600] + " ... [%d chars, cut: see the request file]" % len(txt)
elif len(txt) > 2500:
txt = txt[:2000] + "\n... [%d chars cut: full text in proxy/rounds/%04d.req.json.gz]" % (len(txt), a["seq"])
lines.append("IN " + txt.replace("\n", "\n "))
for it in a["out"]:
lines.append("OUT " + item_text(it).replace("\n", "\n "))
if rec.get("outcome") not in (None, "ok") or u.get("error"):
lines.append("!! outcome=%s error=%s" % (rec.get("outcome"), json.dumps(u.get("error"))[:300]))
lines.append("")
text = "\n".join(lines) + "\n"
p = os.path.join(d, "transcript.md")
with open(p + ".part", "w", encoding="utf-8") as f:
f.write(text)
os.replace(p + ".part", p)
# line numbers of every round's OUT lines, for the divergence report
idx = {}
for n, line in enumerate(text.splitlines(), 1):
m = re.match(r"## round (\d+) ", line)
if m:
idx[int(m.group(1))] = n
return idx
def action_seq(a):
return [x for x in (action_of(i) for i in a["out"]) if x]
def first_divergence(acts_a, acts_b):
"""-> (round, action_a, action_b) of the first round whose actions differ, or None when the common prefix is identical."""
for k in range(min(len(acts_a), len(acts_b))):
sa, sb = action_seq(acts_a[k]), action_seq(acts_b[k])
if sa != sb:
return k + 1, sa, sb
if len(acts_a) != len(acts_b):
k = min(len(acts_a), len(acts_b))
return k + 1, ["(session A ends)"] if len(acts_a) == k else action_seq(acts_a[k]), ["(session B ends)"] if len(acts_b) == k else action_seq(acts_b[k])
return None
# ---------------------------------------------------------------------------------------------------------------- statistics
def mean(xs):
return sum(xs) / len(xs) if xs else float("nan")
def sd(xs):
return statistics.stdev(xs) if len(xs) > 1 else float("nan")
def fmt(x, nd=1):
return "-" if x is None or (isinstance(x, float) and math.isnan(x)) else ("%.*f" % (nd, x))
def rounds_by(rows):
g = {}
for r in rows:
if r["set"] != "":
continue
g.setdefault((r["task"], r["variant"]), []).append(r)
return g
def delta_table(rows, tasks, pairs, title):
g = rounds_by(rows)
out = ["### " + title, "", "| task | A | B | n(A) | n(B) | rounds A (mean, sd, min-max) | rounds B (mean, sd, min-max) | A-B rounds | A/B-1 | completed A | completed B | paired A-B by repeat |", "|---|---|---|---|---|---|---|---|---|---|---|---|"]
allrel = {}
for (a, b, name) in pairs:
for t in tasks:
ra, rb = g.get((t, a), []), g.get((t, b), [])
if not ra or not rb:
continue
xa, xb = [r["rounds"] for r in ra], [r["rounds"] for r in rb]
ca = sum(1 for r in ra if r["accepted"] == "yes")
cb = sum(1 for r in rb if r["accepted"] == "yes")
by_b = {r["rep"]: r["rounds"] for r in rb}
paired = ["r%s:%+d" % (r["rep"], r["rounds"] - by_b[r["rep"]]) for r in ra if r["rep"] in by_b]
rel = mean(xa) / mean(xb) - 1 if mean(xb) else float("nan")
allrel.setdefault(name, []).append(rel)
out.append("| %s | %s | %s | %d | %d | %s, %s, %d-%d | %s, %s, %d-%d | %s | %s | %d/%d | %d/%d | %s |" % (
t, a, b, len(xa), len(xb), fmt(mean(xa)), fmt(sd(xa)), min(xa), max(xa), fmt(mean(xb)), fmt(sd(xb)), min(xb), max(xb),
"%+.1f" % (mean(xa) - mean(xb)), "%+.1f%%" % (100 * rel), ca, len(ra), cb, len(rb), " ".join(paired)))
out.append("")
for name, rels in allrel.items():
rels = [x for x in rels if not math.isnan(x)]
if rels:
out.append("%s: mean of the per-task relative deltas %+.1f%% (sd across tasks %s, %d tasks); the per-task rows above are the evidence, this line is only a summary." % (
name, 100 * mean(rels), fmt(100 * sd(rels)) + "%", len(rels)))
out.append("")
return out
def noise_section(rows, tasks):
g = rounds_by(rows)
cvs = []
out = ["### Run-to-run noise of the round count (same variant, same task, different repeat)", "", "| task | variant | n | rounds | mean | sd | CV |", "|---|---|---|---|---|---|---|"]
for t in tasks:
for v in ("V1", "V2", "V3", "V4"):
rs = g.get((t, v), [])
if len(rs) >= 2:
x = [r["rounds"] for r in rs]
cv = sd(x) / mean(x) if mean(x) else float("nan")
cvs.append(cv)
out.append("| %s | %s | %d | %s | %s | %s | %s |" % (t, v, len(x), " ".join(map(str, x)), fmt(mean(x)), fmt(sd(x)), fmt(100 * cv) + "%"))
out.append("")
cvs = [c for c in cvs if not math.isnan(c)]
if cvs:
cv = math.sqrt(mean([c * c for c in cvs]))
out.append("Pooled CV of rounds across the cells with >= 2 repeats: %.0f%% (%d cells)." % (100 * cv, len(cvs)))
out.append("Resolvable relative difference of two cell means with n repeats each (two-sided alpha 0.05, power 0.8, pooled CV; normal approximation 2.8 * CV * sqrt(2/n)):")
for n in (2, 3, 4, 6, 9, 12):
out.append("- n=%d: about %.0f%%" % (n, 280 * cv * math.sqrt(2.0 / n)))
out.append("")
return out
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
root = os.path.abspath(args[0])
outdir = os.path.abspath(sys.argv[sys.argv.index("--out") + 1]) if "--out" in sys.argv else os.path.join(root, "_index")
do_tr = "--no-transcripts" not in sys.argv
os.makedirs(outdir, exist_ok=True)
rows, per_cell, round_rows = [], {}, []
for sset, d, info in find_cells(root):
row, rs = summarize(sset, d, info)
rows.append(row)
acts = build_actions(d, rs)
if do_tr:
idx = write_transcript(d, acts, info)
else:
idx = {}
per_cell[(sset, info["variant"], info["task"], info["rep"])] = (d, acts, idx, row)
for a in acts:
rec, u = a["rec"], a["rec"].get("resp") or {}
ttft = (rec.get("t_first_byte_ms") or 0) - (rec.get("t_start_ms") or 0)
dec = (rec.get("t_end_ms") or 0) - (rec.get("t_first_byte_ms") or rec.get("t_end_ms") or 0)
round_rows.append({"set": sset, "variant": info["variant"], "task": info["task"], "rep": info["rep"], "round": a["round"], "seq": a["seq"],
"status": rec.get("status"), "terminal": u.get("terminal"), "input_tokens": u.get("input_tokens"), "cached_tokens": u.get("cached_tokens"),
"output_tokens": u.get("output_tokens"), "reasoning_tokens": u.get("reasoning_tokens"), "ttft_ms": ttft, "decode_ms": dec,
"tok_s": round(u["output_tokens"] / (dec / 1000), 1) if u.get("output_tokens") and dec > 0 else None,
"actions": " | ".join(x[:120].replace("\n", " ") for x in action_seq(a))})
rows.sort(key=lambda r: (r["set"], r["task"], r["variant"], r["rep"]))
if rows:
with open(os.path.join(outdir, "index.csv"), "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
w.writeheader()
w.writerows(rows)
if round_rows:
with open(os.path.join(outdir, "rounds.csv"), "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=list(round_rows[0].keys()))
w.writeheader()
w.writerows(round_rows)
tasks = sorted(set(r["task"] for r in rows if r["set"] == ""))
md = ["# Codex lossy-delta: index of %d cells" % len(rows), "", "Variants: " + "; ".join("%s = %s" % (k, v) for k, v in LABEL.items()), ""]
md += ["## Cells", "", "| set | variant | task | rep | rounds (ok/failed) | accepted | termination | wall s | ctx peak | in/round p50 | out/round p50 (max) | decode tok/s | skip entries | final message tail | transcript |", "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
for r in rows:
md.append("| %s | %s | %s | %s | %d (%d/%d) | %s | %s | %s | %s | %s | %s (%s) | %s | %s | %s | %s |" % (
r["set"] or "-", r["variant"], r["task"], r["rep"], r["rounds"], r["rounds_completed"], r["rounds_failed"], r["accepted"], r["termination"], fmt(r["wall_s"], 0),
r["ctx_peak"], r["in_per_round_p50"], r["out_per_round_p50"], r["out_per_round_max"], fmt(r["decode_tok_s"]), r["skip_entries"],
r["final_message_tail"][-100:].replace("|", "/"), r["transcript"]))
md.append("")
md += ["## Round deltas (lossy minus lossless; A-B rows are computed from the cells above, the matrix set only)", ""]
md += delta_table(rows, tasks, PAIRS, "Lossy minus lossless per engine: V1-V2 (vanilla), V3-V4 (ours)")
md += delta_table(rows, tasks, CROSS, "Cross deltas: ours minus vanilla (V3-V1 lossy, V4-V2 lossless)")
md += noise_section(rows, tasks)
md += ["## First divergence of lossy and lossless sessions (same task and repeat; first round whose actions differ)", "",
"Actions = the model's tool calls (name + arguments) and messages of that round; reasoning text is not compared. Lines refer to each cell's transcript.md.", "",
"| task | engine | rep | lossy cell | lossless cell | first differing round | transcript line (lossy / lossless) | lossy action | lossless action |", "|---|---|---|---|---|---|---|---|---|"]
for t in tasks:
for (lossy, lossless, name) in PAIRS:
for key, (d, acts, idx, row) in sorted(per_cell.items()):
sset, v, tt, rep = key
if v != lossy or tt != t or sset != "":
continue
other = per_cell.get((sset, lossless, t, rep))
if not other:
continue
dv = first_divergence(acts, other[1])
if dv is None:
md.append("| %s | %s | %d | %s | %s | none: identical actions in all %d common rounds | - | - | - |" % (t, name, rep, d, other[0], min(len(acts), len(other[1]))))
else:
k, sa, sb = dv
md.append("| %s | %s | %d | %s | %s | %d | %s / %s | %s | %s |" % (t, name, rep, d, other[0], k, idx.get(k, "-"), other[2].get(k, "-"),
(" ; ".join(sa))[:160].replace("|", "/"), (" ; ".join(sb))[:160].replace("|", "/")))
md += ["", "## Determinism check (same variant, same task, repeat i against repeat j; greedy decoding is requested but the adaptive expert tier and the prefix cache state are not bit-exact run to run)", "",
"| variant | task | reps | first differing round | rounds A / B | accepted A / B |", "|---|---|---|---|---|---|"]
by_vt = {}
for key in per_cell:
sset, v, t, rep = key
if sset == "":
by_vt.setdefault((v, t), []).append(rep)
for (v, t), reps in sorted(by_vt.items()):
reps = sorted(reps)
for i in range(len(reps)):
for j in range(i + 1, len(reps)):
a = per_cell[("", v, t, reps[i])] if ("", v, t, reps[i]) in per_cell else None
b = per_cell[("", v, t, reps[j])] if ("", v, t, reps[j]) in per_cell else None
if not a or not b:
continue
dv = first_divergence(a[1], b[1])
md.append("| %s | %s | r%d vs r%d | %s | %d / %d | %s / %s |" % (v, t, reps[i], reps[j], "identical" if dv is None else dv[0], len(a[1]), len(b[1]), a[3]["accepted"], b[3]["accepted"]))
with open(os.path.join(outdir, "index.md"), "w", encoding="utf-8") as f:
f.write("\n".join(md) + "\n")
print("wrote %d cells, %d rounds into %s" % (len(rows), len(round_rows), outdir))
if __name__ == "__main__":
main()