519 lines
26 KiB
Python
519 lines
26 KiB
Python
"""Aggregates run records into the protocol's headline numbers (§13, §15,
|
||
§16, §17): Verified Success Rate, repair cycles to an accepted solution,
|
||
context consumed and expected cost per correct solution."""
|
||
|
||
import glob
|
||
import json
|
||
import os
|
||
import statistics
|
||
|
||
from . import util
|
||
|
||
|
||
def load(paths):
|
||
runs = []
|
||
for p in paths:
|
||
for f in [p] if p.endswith("run.json") else glob.glob(os.path.join(p, "**", "run.json"), recursive=True):
|
||
if "/superseded/" in f:
|
||
continue
|
||
runs.append(util.read_json(f))
|
||
return runs
|
||
|
||
|
||
def mean(xs):
|
||
xs = [x for x in xs if x is not None]
|
||
return round(statistics.mean(xs), 2) if xs else None
|
||
|
||
|
||
def aggregate(runs):
|
||
cells = {}
|
||
for r in runs:
|
||
if r.get("track") == "B":
|
||
a = r["agent"]
|
||
key = (r["task"]["id"], r["language"]["name"], "B:" + (a.get("label") or a["name"]), a["name"] + ":" + a["model"])
|
||
else:
|
||
key = (r["task"]["id"], r["language"]["name"], r["model"].get("class") or "-", r["model"]["id"])
|
||
cells.setdefault(key, []).append(r)
|
||
rows = []
|
||
for (task, lang, cls, model), rs in sorted(cells.items()):
|
||
acc = [r for r in rs if r.get("accepted")]
|
||
costs = [r.get("cost_usd") for r in rs]
|
||
total_cost = None if any(c is None for c in costs) else round(sum(costs), 4)
|
||
rows.append({
|
||
"task": task, "language": lang, "class": cls, "model": model,
|
||
"runs": len(rs), "accepted": len(acc),
|
||
"verified_success_rate": round(len(acc) / len(rs), 3),
|
||
"repair_cycles_accepted": mean([r["metrics"]["failed_verifier_cycles"] + r["metrics"]["failed_test_cycles"] for r in acc if r["metrics"].get("failed_verifier_cycles") is not None]),
|
||
"context_tokens_mean": mean([r["metrics"].get("input_tokens") for r in rs]),
|
||
"uncached_input_tokens_mean": mean([((r["metrics"].get("context") or {}).get("provider_input_tokens") or {}).get("uncached") for r in rs]),
|
||
"cumulative_context_tokens_mean": mean([(r["metrics"].get("context") or {}).get("cumulative_context_tokens") for r in rs]),
|
||
"unique_reference_tokens_mean": mean([(r["metrics"].get("context") or {}).get("unique_reference_tokens") for r in rs]),
|
||
"reference_coverage_mean": mean([(r["metrics"].get("context") or {}).get("reference_coverage") for r in rs]),
|
||
"elapsed_seconds_mean": mean([r["metrics"].get("elapsed_seconds") for r in rs]),
|
||
"output_tokens_mean": mean([r["metrics"].get("output_tokens") for r in rs]),
|
||
"tool_calls_mean": mean([r["metrics"]["tool_calls"] for r in rs]),
|
||
"first_check_accepted": sum(1 for r in rs if r["metrics"].get("first_check_accepted") or r["metrics"].get("first_build_accepted")),
|
||
"cost_total_usd": total_cost,
|
||
"cost_per_correct_usd": None if total_cost is None or not acc else round(total_cost / len(acc), 4),
|
||
"unclassified_failures": sum(1 for r in rs if r.get("accepted") is False and not r.get("classification")),
|
||
"terminations": sorted({r["metrics"]["termination"] for r in rs}),
|
||
})
|
||
return rows
|
||
|
||
|
||
def markdown(rows):
|
||
head = ["task", "language", "class", "model", "runs", "accepted", "VSR", "repair cycles (accepted)", "tool calls",
|
||
"provider input (uncached)", "cumulative context", "unique reference", "ref. coverage", "seconds", "cost/correct USD", "unclassified failures"]
|
||
out = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
|
||
for r in rows:
|
||
# Track B runs on subscriptions: no honest cost per solution (protocol §39b).
|
||
cost = "n/a (Track B)" if r["class"].startswith("B:") else r["cost_per_correct_usd"]
|
||
out.append("| " + " | ".join(str(x) for x in [
|
||
r["task"], r["language"], r["class"], r["model"], r["runs"], r["accepted"], r["verified_success_rate"], r["repair_cycles_accepted"],
|
||
r["tool_calls_mean"], f"{r['context_tokens_mean']} ({r['uncached_input_tokens_mean']})", r["cumulative_context_tokens_mean"],
|
||
r["unique_reference_tokens_mean"], r["reference_coverage_mean"], r["elapsed_seconds_mean"], cost, r["unclassified_failures"]]) + " |")
|
||
return "\n".join(out)
|
||
|
||
|
||
def print_report(paths, as_json=False):
|
||
rows = aggregate(load(paths))
|
||
print(json.dumps(rows, indent=2) if as_json else markdown(rows))
|
||
|
||
|
||
def _agent_key(r):
|
||
if r.get("track") == "B":
|
||
return (r["agent"].get("label") or "") + " " + r["agent"]["name"]
|
||
return (r["model"].get("class") or "") + " " + r["model"]["id"]
|
||
|
||
|
||
def summary(paths):
|
||
"""The shareable summary of an experiment (no task details beyond task
|
||
IDs): the PASS/FAIL matrix per task, per-cell metrics, and aggregates
|
||
by language and by agent/model."""
|
||
runs = load(paths)
|
||
langs = sorted({r["language"]["name"] for r in runs})
|
||
agents = sorted({_agent_key(r) for r in runs})
|
||
tasks = sorted({r["task"]["id"] for r in runs})
|
||
out = []
|
||
for t in tasks:
|
||
out.append(f"### {t}\n")
|
||
out.append("| agent | " + " | ".join(langs) + " |")
|
||
out.append("|---|" + "---|" * len(langs))
|
||
for a in agents:
|
||
cells = []
|
||
for lang in langs:
|
||
rs = [r for r in runs if r["task"]["id"] == t and r["language"]["name"] == lang and _agent_key(r) == a]
|
||
cells.append(" ".join("PASS" if r.get("accepted") else ("FAIL" if r.get("accepted") is False else "?") for r in rs) or "-")
|
||
out.append(f"| {a} | " + " | ".join(cells) + " |")
|
||
out.append("")
|
||
head = ["task", "language", "agent", "verified", "first attempt", "repair cycles", "tool calls", "seconds",
|
||
"unique bundle", "context via tools", "provider input cached/uncached", "classification", "caught by"]
|
||
out.append("### Cells\n")
|
||
out.append("| " + " | ".join(head) + " |")
|
||
out.append("|" + "---|" * len(head))
|
||
for r in sorted(runs, key=lambda r: (r["task"]["id"], r["language"]["name"], _agent_key(r))):
|
||
m = r["metrics"]
|
||
ctx = m.get("context") or {}
|
||
pin = ctx.get("provider_input_tokens") or {}
|
||
cyc = None if m.get("failed_verifier_cycles") is None else m["failed_verifier_cycles"] + (m.get("failed_test_cycles") or 0)
|
||
cl = r.get("classification") or {}
|
||
out.append("| " + " | ".join(str(x) for x in [
|
||
r["task"]["id"], r["language"]["name"], _agent_key(r), "PASS" if r.get("accepted") else "FAIL",
|
||
m.get("first_public_test_passed"), cyc, m.get("tool_calls"), m.get("elapsed_seconds"),
|
||
ctx.get("unique_reference_tokens"), ctx.get("cumulative_context_tokens"), f"{pin.get('cached')}/{pin.get('uncached')}",
|
||
cl.get("category", "-" if r.get("accepted") else "unclassified"), cl.get("caught_by") or "-"]) + " |")
|
||
out.append("")
|
||
for title, keyf in (("language", lambda r: r["language"]["name"]), ("agent", _agent_key)):
|
||
out.append(f"### By {title}\n")
|
||
out.append(f"| {title} | runs | accepted | VSR | mean repair cycles | mean tool calls | mean seconds | mean uncached input |")
|
||
out.append("|---|---|---|---|---|---|---|---|")
|
||
for k in sorted({keyf(r) for r in runs}):
|
||
rs = [r for r in runs if keyf(r) == k]
|
||
acc = sum(1 for r in rs if r.get("accepted"))
|
||
cyc = [r["metrics"]["failed_verifier_cycles"] + (r["metrics"].get("failed_test_cycles") or 0) for r in rs if r["metrics"].get("failed_verifier_cycles") is not None]
|
||
unc = [((r["metrics"].get("context") or {}).get("provider_input_tokens") or {}).get("uncached") for r in rs]
|
||
out.append(f"| {k} | {len(rs)} | {acc} | {round(acc / len(rs), 3)} | {mean(cyc)} | {mean([r['metrics'].get('tool_calls') for r in rs])} | {mean([r['metrics'].get('elapsed_seconds') for r in rs])} | {mean(unc)} |")
|
||
out.append("")
|
||
return "\n".join(out)
|
||
|
||
|
||
def _source_size(run_dir, exts):
|
||
files = lines = nbytes = 0
|
||
ws = os.path.join(run_dir, "workspace")
|
||
for root, dirs, names in os.walk(ws):
|
||
dirs[:] = [d for d in dirs if d not in ("target", ".zig-cache", "zig-cache", "zig-out", ".git")]
|
||
for n in names:
|
||
if os.path.splitext(n)[1] in exts:
|
||
p = os.path.join(root, n)
|
||
with open(p, "rb") as f:
|
||
data = f.read()
|
||
files, lines, nbytes = files + 1, lines + data.count(b"\n"), nbytes + len(data)
|
||
return files, lines, nbytes
|
||
|
||
|
||
def _diagnostic_codes(r, run_dir):
|
||
"""Counts of verifier/compiler diagnostic codes seen in the run's command
|
||
outputs (codes only: no message text, no task content)."""
|
||
import collections
|
||
import re
|
||
|
||
from . import native
|
||
|
||
counts = collections.Counter()
|
||
if r.get("track") == "B":
|
||
cmds = native.command_events(r["agent"]["name"], os.path.join(run_dir, "transcript.jsonl"))
|
||
outputs = [o for _, _, o in cmds]
|
||
else:
|
||
outputs = [json.loads(l).get("output") or "" for l in open(os.path.join(run_dir, "events.jsonl")) if '"event": "command"' in l]
|
||
lang = r["language"]["name"]
|
||
for o in outputs:
|
||
if lang in ("aji_air", "aji_source"):
|
||
counts.update(re.findall(r'"code":"([ET]\d{4})"', o))
|
||
elif lang == "rust":
|
||
counts.update(re.findall(r"error\[(E\d{4})\]", o))
|
||
counts["error(no code)"] += len(re.findall(r"(?m)^error: ", o))
|
||
else:
|
||
counts["error"] += len(re.findall(r": error: ", o))
|
||
return dict(counts.most_common())
|
||
|
||
|
||
# Diagnostics about the textual form of AIR (syntax, names, module header,
|
||
# SSA, CFG): the classes the source frontend is meant to remove. Type
|
||
# mismatches (E1001 from AIR, E7005 from source) are semantic and counted
|
||
# separately, so relabeling cannot make the IR-form count look better.
|
||
IR_FORM = {"E0001", "E0002", "E0003", "E0004", "E0005", "E0006", "E5001", "E5002"}
|
||
TYPE_MISMATCH = {"E1001", "E7005"}
|
||
|
||
|
||
def _lowered_size(run_dir):
|
||
"""`aji lower --stats` summed over the workspace's .aji files: raw and
|
||
normalized lowered AIR bytes (spec 15 §11); None when nothing lowers."""
|
||
import subprocess
|
||
|
||
aji = os.path.join(util.REPO, "zig-out", "bin", "aji")
|
||
raw = norm = 0
|
||
found = False
|
||
for root, dirs, names in os.walk(os.path.join(run_dir, "workspace")):
|
||
dirs[:] = [d for d in dirs if d not in ("zig-out", ".zig-cache", ".git")]
|
||
for n in names:
|
||
if not n.endswith(".aji"):
|
||
continue
|
||
r = subprocess.run([aji, "lower", "--stats", os.path.join(root, n)], capture_output=True, text=True)
|
||
if r.returncode != 0:
|
||
continue
|
||
st = json.loads(r.stdout)
|
||
raw, norm, found = raw + st["air_bytes"], norm + st["air_bytes_normalized"], True
|
||
return (raw, norm) if found else None
|
||
|
||
|
||
def profile(paths):
|
||
"""Per-run cost profile for failure and cost analysis (protocol §27,
|
||
§38): termination, output tokens, solution size and diagnostic codes.
|
||
Shareable: numbers and diagnostic codes only."""
|
||
from . import languages
|
||
|
||
out = ["| task | language | agent | termination | output tokens | tool calls | source files / lines / bytes | lowered AIR bytes raw / normalized | docs files read | IR-form diagnostics | type mismatches | diagnostic codes (count) |",
|
||
"|---|---|---|---|---|---|---|---|---|---|---|---|"]
|
||
for p in paths:
|
||
for f in sorted(glob.glob(os.path.join(p, "**", "run.json"), recursive=True)):
|
||
if "/superseded/" in f:
|
||
continue
|
||
r = util.read_json(f)
|
||
d = os.path.dirname(f)
|
||
exts = set(languages.load(r["language"]["name"]).get("source_extensions", []))
|
||
files, lines, nbytes = _source_size(d, exts)
|
||
codes = _diagnostic_codes(r, d)
|
||
m = r["metrics"]
|
||
lowered = _lowered_size(d) if r["language"]["name"] == "aji_source" else None
|
||
docs = (m.get("context") or {}).get("docs") or {}
|
||
ir = sum(v for k, v in codes.items() if k in IR_FORM)
|
||
ty = sum(v for k, v in codes.items() if k in TYPE_MISMATCH)
|
||
out.append(f"| {r['task']['id']} | {r['language']['name']} | {_agent_key(r)} | {m.get('termination')} | {m.get('output_tokens')} | {m.get('tool_calls')} | "
|
||
f"{files} / {lines} / {nbytes} | {f'{lowered[0]} / {lowered[1]}' if lowered else '-'} | "
|
||
f"{docs.get('unique_docs_read', '-')} | {ir} | {ty} | {', '.join(f'{k} {v}' for k, v in codes.items()) or '-'} |")
|
||
return "\n".join(out)
|
||
|
||
|
||
# ---------------------------------------------------------------- M checkpoint / P6A-9 rows
|
||
|
||
def _code_kinds():
|
||
"""code -> kind from docs/reference/error-codes.md (`ownership.use_after_move`, …)."""
|
||
import re
|
||
|
||
kinds = {}
|
||
with open(os.path.join(util.REPO, "docs", "reference", "error-codes.md"), encoding="utf-8") as f:
|
||
for line in f:
|
||
m = re.match(r"\| ([ET]\d{4}) \| ([a-z_]+)\.", line)
|
||
if m:
|
||
kinds[m.group(1)] = m.group(2)
|
||
return kinds
|
||
|
||
|
||
def _diagnostic_buckets(codes):
|
||
"""The checkpoint's diagnostic fields. Every code lands in exactly one
|
||
bucket; codes in none of the named ones are counted in `other`, never
|
||
dropped."""
|
||
kinds = _code_kinds()
|
||
b = {k: 0 for k in ("E0001-E0006", "E5001", "E5002", "E1001", "E7005", "other_E7xxx", "ownership", "borrow",
|
||
"resource", "concurrency", "runtime_traps", "other")}
|
||
for code, n in codes.items():
|
||
kind = kinds.get(code, "")
|
||
if code in ("E0001", "E0002", "E0003", "E0004", "E0005", "E0006"):
|
||
b["E0001-E0006"] += n
|
||
elif code in ("E5001", "E5002", "E1001", "E7005"):
|
||
b[code] += n
|
||
elif code.startswith("E7"):
|
||
b["other_E7xxx"] += n
|
||
elif code.startswith("T"):
|
||
b["runtime_traps"] += n
|
||
elif kind == "ownership":
|
||
b["ownership"] += n
|
||
elif kind in ("borrow", "memory", "island"):
|
||
b["borrow"] += n
|
||
elif kind == "resource":
|
||
b["resource"] += n
|
||
elif kind in ("concurrency", "atomic", "task", "sync", "io"):
|
||
b["concurrency"] += n
|
||
else:
|
||
b["other"] += n
|
||
b["ir_form_total"] = b["E0001-E0006"] + b["E5001"] + b["E5002"]
|
||
return b
|
||
|
||
|
||
# B1 (docs/evaluation/b1-heldout-plan.md §5): pre-test statically caught
|
||
# safety errors, i.e. safety diagnostics a compiler or verifier reported
|
||
# before any test ran. Fixed before the freeze. Not symmetric across
|
||
# languages (Zig has none by definition): a mechanism measure for Aji and
|
||
# Rust, never a cross-language safety claim.
|
||
AJI_SAFETY_KINDS = {"ownership", "borrow", "init", "memory", "island", "resource", "concurrency", "atomic", "task", "sync", "unsafe"}
|
||
RUST_SAFETY_CODES = {"E0382", "E0499", "E0502", "E0505", "E0506", "E0507", "E0596", "E0597", "E0716", "E0373"}
|
||
RUST_SEND_SYNC = ("cannot be sent between threads safely", "cannot be shared between threads safely")
|
||
|
||
|
||
def statically_prevented(r, run_dir, codes=None):
|
||
"""Safety diagnostics reported during the run (codes only). Zig has no
|
||
static safety diagnostics: 0 by definition."""
|
||
lang = r["language"]["name"]
|
||
codes = codes if codes is not None else _diagnostic_codes(r, run_dir)
|
||
if lang in ("aji_air", "aji_source"):
|
||
kinds = _code_kinds()
|
||
return sum(n for c, n in codes.items() if c.startswith("E") and kinds.get(c) in AJI_SAFETY_KINDS)
|
||
if lang == "rust":
|
||
n = sum(v for c, v in codes.items() if c in RUST_SAFETY_CODES)
|
||
return n + _rust_send_sync(r, run_dir)
|
||
return 0
|
||
|
||
|
||
def _rust_send_sync(r, run_dir):
|
||
from . import native
|
||
|
||
if r.get("track") == "B":
|
||
outputs = [o for _, _, o in native.command_events(r["agent"]["name"], os.path.join(run_dir, "transcript.jsonl"))]
|
||
else:
|
||
outputs = [json.loads(l).get("output") or "" for l in open(os.path.join(run_dir, "events.jsonl")) if '"event": "command"' in l]
|
||
return sum(o.count(m) for o in outputs for m in RUST_SEND_SYNC)
|
||
|
||
|
||
# Unchecked operations in the final program (B1 §5): a static count.
|
||
ZIG_UNCHECKED = ("@ptrCast", "@ptrFromInt", "@intFromPtr", "@alignCast", "@constCast", "@volatileCast", "@setRuntimeSafety(false)")
|
||
|
||
|
||
def unsafe_usage(r, run_dir):
|
||
import re
|
||
|
||
lang = r["language"]["name"]
|
||
ws = os.path.join(run_dir, "workspace")
|
||
exts = {"rust": (".rs",), "zig": (".zig",), "aji_source": (".aji",), "aji_air": (".air",)}.get(lang, ())
|
||
n = 0
|
||
for root, _, files in os.walk(ws):
|
||
if any(p in root for p in ("/target", "/.zig-cache", "/zig-out")):
|
||
continue
|
||
for fn in files:
|
||
if not fn.endswith(exts):
|
||
continue
|
||
text = open(os.path.join(root, fn), encoding="utf-8", errors="replace").read()
|
||
text = re.sub(r"//[^\n]*", "", text) if lang != "aji_air" else re.sub(r";[^\n]*", "", text)
|
||
if lang == "rust":
|
||
n += len(re.findall(r"\bunsafe\b", text))
|
||
elif lang == "zig":
|
||
n += sum(text.count(b) for b in ZIG_UNCHECKED)
|
||
elif lang == "aji_source":
|
||
n += len(re.findall(r"effects \[[^\]]*\bunsafe\b", text)) + len(re.findall(r"\bref unchecked\b|\bassume\(", text))
|
||
else:
|
||
n += len(re.findall(r"effects \[[^\]]*\bunsafe\b", text)) + len(re.findall(r"borrow\.index\.unchecked|\bassume ", text))
|
||
return n
|
||
|
||
|
||
def wilson(k, n, z=1.96):
|
||
"""95 % Wilson score interval for k successes in n runs."""
|
||
if n == 0:
|
||
return (0.0, 0.0)
|
||
p = k / n
|
||
d = 1 + z * z / n
|
||
c = p + z * z / (2 * n)
|
||
h = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5)
|
||
return ((c - h) / d, (c + h) / d)
|
||
|
||
|
||
def vsr_table(paths, tasks=None, as_json=False):
|
||
"""B1 §6.1: verified success rate per agent stack × language with 95 %
|
||
Wilson intervals; `tasks` restricts to a set of task ids (for example
|
||
the medium ones). Numbers only."""
|
||
runs = [r for r in load(paths) if tasks is None or r["task"]["id"] in tasks]
|
||
cells = {}
|
||
for r in runs:
|
||
key = (_agent_key(r), r["language"]["name"])
|
||
k, n = cells.get(key, (0, 0))
|
||
cells[key] = (k + (1 if r.get("accepted") else 0), n + 1)
|
||
agents = sorted({a for a, _ in cells})
|
||
langs = sorted({l for _, l in cells})
|
||
if as_json:
|
||
return json.dumps([{"agent": a, "language": l, "accepted": cells[(a, l)][0], "runs": cells[(a, l)][1],
|
||
"vsr": cells[(a, l)][0] / cells[(a, l)][1], "ci95": wilson(*cells[(a, l)])}
|
||
for a in agents for l in langs if (a, l) in cells], indent=1)
|
||
out = ["| agent | " + " | ".join(langs) + " |", "|---|" + "---:|" * len(langs)]
|
||
for a in agents:
|
||
row = []
|
||
for l in langs:
|
||
if (a, l) not in cells:
|
||
row.append("—")
|
||
continue
|
||
k, n = cells[(a, l)]
|
||
lo, hi = wilson(k, n)
|
||
row.append(f"{100 * k / n:.0f} % ({k}/{n}; {100 * lo:.0f}–{100 * hi:.0f})")
|
||
out.append(f"| {a} | " + " | ".join(row) + " |")
|
||
return "\n".join(out)
|
||
|
||
|
||
def _median(xs):
|
||
xs = sorted(x for x in xs if x is not None)
|
||
if not xs:
|
||
return None
|
||
m = len(xs) // 2
|
||
return xs[m] if len(xs) % 2 else (xs[m - 1] + xs[m]) / 2
|
||
|
||
|
||
def cost_proxies(paths, tasks=None, as_json=False):
|
||
"""B1 §5 (D5): per agent stack × language, totals over ALL runs divided
|
||
by accepted runs (the price of failures included), and per-run medians.
|
||
No dollar cost: subscriptions have no honest price per solution."""
|
||
runs = [r for r in load(paths) if tasks is None or r["task"]["id"] in tasks]
|
||
cells = {}
|
||
for r in runs:
|
||
cells.setdefault((_agent_key(r), r["language"]["name"]), []).append(r)
|
||
rows = []
|
||
for (agent, lang), rs in sorted(cells.items()):
|
||
acc = sum(1 for r in rs if r.get("accepted"))
|
||
unc = [((r["metrics"].get("context") or {}).get("provider_input_tokens") or {}).get("uncached") for r in rs]
|
||
out = [r["metrics"].get("output_tokens") for r in rs]
|
||
wall = [r["metrics"].get("elapsed_seconds") for r in rs]
|
||
tools = [r["metrics"].get("tool_calls") for r in rs]
|
||
|
||
def per_acc(xs):
|
||
if acc == 0 or any(x is None for x in xs):
|
||
return None
|
||
return round(sum(xs) / acc, 1)
|
||
|
||
rows.append({"agent": agent, "language": lang, "runs": len(rs), "accepted": acc,
|
||
"uncached_input_per_accepted": per_acc(unc), "output_tokens_per_accepted": per_acc(out),
|
||
"wall_seconds_per_accepted": per_acc(wall),
|
||
"median_uncached_input_per_run": _median(unc), "median_output_tokens_per_run": _median(out),
|
||
"median_wall_seconds_per_run": _median(wall), "median_tool_calls_per_run": _median(tools)})
|
||
if as_json:
|
||
return json.dumps(rows, indent=1)
|
||
head = ["agent", "language", "runs", "accepted", "uncached_input_per_accepted", "output_tokens_per_accepted",
|
||
"wall_seconds_per_accepted", "median_uncached_input_per_run", "median_output_tokens_per_run",
|
||
"median_wall_seconds_per_run", "median_tool_calls_per_run"]
|
||
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
|
||
for row in rows:
|
||
lines.append("| " + " | ".join("n/a" if row[h] is None else str(row[h]) for h in head) + " |")
|
||
return "\n".join(lines)
|
||
|
||
|
||
def checkpoint_rows(paths):
|
||
"""One row per run with the fields of the M checkpoint and P6A-9 (plan,
|
||
P6A-9). Only what the record holds: a field the run did not collect is
|
||
"n/a", never reconstructed. Shareable: numbers, codes and documentation
|
||
file names only."""
|
||
from . import languages
|
||
|
||
na = "n/a"
|
||
rows = []
|
||
for p in paths:
|
||
for f in sorted(glob.glob(os.path.join(p, "**", "run.json"), recursive=True)):
|
||
if "/superseded/" in f:
|
||
continue
|
||
r = util.read_json(f)
|
||
d = os.path.dirname(f)
|
||
lang = r["language"]["name"]
|
||
m = r["metrics"]
|
||
ctx = m.get("context") or {}
|
||
pin = ctx.get("provider_input_tokens") or {}
|
||
docs = ctx.get("docs")
|
||
cyc = None if m.get("failed_verifier_cycles") is None else m["failed_verifier_cycles"] + (m.get("failed_test_cycles") or 0)
|
||
if docs is not None:
|
||
rb = docs.get("read_tokens_by_group") or {}
|
||
doc_fields = {"quick_reference_unique": rb.get("quick_reference", na), "source_docs_unique": rb.get("source_docs", na),
|
||
"air_docs_unique": rb.get("air_docs", na), "files_opened": docs.get("files_opened", na),
|
||
"coverage_by_section": docs.get("coverage_by_section", na)}
|
||
elif lang == "aji_air":
|
||
# Single-file AIR bundle: everything read was AIR documentation,
|
||
# as recorded at the time (unique_reference_tokens, reference_coverage).
|
||
doc_fields = {"quick_reference_unique": na, "source_docs_unique": na,
|
||
"air_docs_unique": ctx.get("unique_reference_tokens", na), "files_opened": na,
|
||
"coverage_by_section": {"reference-bundle.md": ctx["reference_coverage"]} if ctx.get("reference_coverage") is not None else na}
|
||
else:
|
||
doc_fields = {k: na for k in ("quick_reference_unique", "source_docs_unique", "air_docs_unique", "files_opened", "coverage_by_section")}
|
||
exts = set(languages.load(lang).get("source_extensions", []))
|
||
_, _, nbytes = _source_size(d, exts)
|
||
program = {"source_bytes": nbytes, "lowered_air_bytes": na, "mechanical_air_eliminated_raw": na, "mechanical_air_eliminated_normalized": na}
|
||
if lang == "aji_source":
|
||
low = _lowered_size(d)
|
||
if low:
|
||
program.update({"lowered_air_bytes": low[0], "lowered_air_bytes_normalized": low[1],
|
||
"mechanical_air_eliminated_raw": round(1 - nbytes / low[0], 4) if low[0] else na,
|
||
"mechanical_air_eliminated_normalized": round(1 - nbytes / low[1], 4) if low[1] else na})
|
||
|
||
def v(x):
|
||
return na if x is None else x
|
||
|
||
codes = _diagnostic_codes(r, d)
|
||
rows.append({
|
||
"task": r["task"]["id"], "agent": _agent_key(r),
|
||
"condition": {"aji_air": "air", "aji_source": "source"}.get(lang, lang),
|
||
"result": "PASS" if r.get("accepted") else ("FAIL" if r.get("accepted") is False else na),
|
||
"agent_status": v(m.get("agent_status")), "evaluation_status": v(m.get("evaluation_status")),
|
||
"first_public_check": v(m.get("first_public_test_passed")), "repair_cycles": v(cyc),
|
||
"tool_calls": v(m.get("tool_calls")), "wall_seconds": v(m.get("elapsed_seconds")),
|
||
"provider_input_total": v(pin.get("total")), "provider_input_uncached": v(pin.get("uncached")),
|
||
"output_tokens": v(m.get("output_tokens")),
|
||
"docs": doc_fields,
|
||
"diagnostics": _diagnostic_buckets(codes),
|
||
"program": program,
|
||
# B1 §5 (n/a in records without the data).
|
||
"pretest_static_safety_caught": statically_prevented(r, d, codes),
|
||
"unsafe_usage": unsafe_usage(r, d) if os.path.isdir(os.path.join(d, "workspace")) else na,
|
||
"failure_class": v((r.get("classification") or {}).get("category")),
|
||
"caught_by": v((r.get("classification") or {}).get("caught_by")),
|
||
"atomic_error": v((r.get("classification") or {}).get("atomic_error")),
|
||
})
|
||
return rows
|
||
|
||
|
||
def checkpoint(paths, as_json=False):
|
||
rows = checkpoint_rows(paths)
|
||
if as_json:
|
||
return json.dumps(rows, indent=2)
|
||
out = []
|
||
for r in sorted(rows, key=lambda r: (r["task"], r["agent"], r["condition"])):
|
||
out.append(f"## {r['task']} · {r['agent']} · {r['condition']}\n")
|
||
for k in ("result", "agent_status", "evaluation_status", "first_public_check", "repair_cycles", "tool_calls", "wall_seconds",
|
||
"provider_input_total", "provider_input_uncached", "output_tokens"):
|
||
out.append(f"- {k}: {r[k]}")
|
||
for group in ("docs", "diagnostics", "program"):
|
||
out.append(f"- {group}:")
|
||
for k, x in r[group].items():
|
||
out.append(f" - {k}: {json.dumps(x) if isinstance(x, (dict, list)) else x}")
|
||
out.append("")
|
||
return "\n".join(out)
|