#!/usr/bin/env python3 """Regenerate released statistics from trajectory-free attempt records.""" from __future__ import annotations import argparse import csv import json import math import random import tempfile from collections import Counter, defaultdict from pathlib import Path ROOT = Path(__file__).resolve().parents[1] COMPLETE = ROOT / "results/complete-suite" PANEL = ROOT / "results/five-arm-panel" def read_csv(path: Path) -> list[dict[str, str]]: with path.open(newline="", encoding="utf-8") as handle: return list(csv.DictReader(handle)) def write_csv(path: Path, rows: list[dict]) -> None: path.parent.mkdir(parents=True, exist_ok=True) if not rows: return fields: list[str] = [] for row in rows: fields.extend(key for key in row if key not in fields) with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=fields) writer.writeheader() writer.writerows(rows) def truth(value: str | bool) -> bool: return value is True or str(value).lower() in {"1", "true"} def number(value: str) -> float | None: return None if value in {"", "None"} else float(value) def quantile(values: list[float], probability: float) -> float: ordered = sorted(values) position = (len(ordered) - 1) * probability low = int(position) high = min(low + 1, len(ordered) - 1) return ordered[low] + (ordered[high] - ordered[low]) * (position - low) def vectors(rows: list[dict]) -> dict[str, tuple[int, ...]]: grouped: dict[str, list[dict]] = defaultdict(list) for row in rows: grouped[row["task"]].append(row) return { task: tuple(int(truth(row["passed"])) for row in sorted(items, key=lambda x: (int(x.get("trial_index", x.get("replicate", 0))), x["trial_name"]))) for task, items in grouped.items() } def bootstrap_rate(task_vectors: dict[str, tuple[int, ...]], repetitions: int, rng: random.Random) -> list[float]: rates = [sum(value) / len(value) for value in task_vectors.values()] samples = [sum(rates[rng.randrange(len(rates))] for _ in rates) / len(rates) for _ in range(repetitions)] return [quantile(samples, 0.025), quantile(samples, 0.975)] def compare_vectors(left: dict[str, tuple[int, ...]], right: dict[str, tuple[int, ...]], repetitions: int, permutations: int, rng: random.Random) -> dict: tasks = sorted(left) differences = [sum(right[task]) / 2 - sum(left[task]) / 2 for task in tasks] samples = [sum(differences[rng.randrange(len(differences))] for _ in differences) / len(differences) for _ in range(repetitions)] observed = abs(sum(differences) / len(differences)) hits = 0 for _ in range(permutations): statistic = abs(sum(value if rng.getrandbits(1) else -value for value in differences) / len(differences)) hits += statistic >= observed - 1e-12 return { "delta": sum(differences) / len(differences), "ci_low": quantile(samples, 0.025), "ci_high": quantile(samples, 0.975), "p": (hits + 1) / (permutations + 1), } def reproduce_complete(out: Path) -> None: rows = read_csv(COMPLETE / "attempts.csv") bootstrap = 10_000 permutations = 100_000 rng = random.Random(20260909) by_cell: dict[str, list[dict]] = defaultdict(list) for row in rows: by_cell[row["cell"]].append(row) primary = [] costs = [] terminations = [] for cell in ("luna_baseline", "luna_policy", "terra_baseline", "terra_policy", "sol_baseline", "sol_policy"): cell_rows = by_cell[cell] tv = vectors(cell_rows) distribution = Counter(sum(value) for value in tv.values()) attempts = len(cell_rows) passes = sum(sum(value) for value in tv.values()) ci = bootstrap_rate(tv, bootstrap, rng) primary.append({ "cell": cell, "model": cell_rows[0]["model"], "condition": cell.split("_", 1)[1], "tasks": len(tv), "attempts": attempts, "passes": passes, "pass_at_1": passes / attempts, "pass_at_2": sum(any(value) for value in tv.values()) / len(tv), "pass_squared": sum(all(value) for value in tv.values()) / len(tv), "pass_at_1_ci_low": ci[0], "pass_at_1_ci_high": ci[1], "zero_of_two": distribution[0], "one_of_two": distribution[1], "two_of_two": distribution[2], }) def mean(key: str): values = [number(row[key]) for row in cell_rows if number(row[key]) is not None] return sum(values) / len(values) costs.append({ "cell": cell, "total_cost_usd": sum(number(row["cost_usd"]) or 0 for row in cell_rows), "mean_cost_usd": mean("cost_usd"), "mean_agent_sec": mean("agent_seconds"), "mean_input_tokens": mean("input_tokens"), "mean_cache_tokens": mean("cache_tokens"), "mean_output_tokens": mean("output_tokens"), }) for reason, count in Counter(row["termination_reason"] for row in cell_rows).items(): terminations.append({"cell": cell, "termination_reason": reason, "attempts": count}) comparisons = [] transitions = [] for model in ("luna", "terra", "sol"): left = vectors(by_cell[f"{model}_baseline"]) right = vectors(by_cell[f"{model}_policy"]) result = compare_vectors(left, right, bootstrap, permutations, rng) changes = {task: sum(right[task]) - sum(left[task]) for task in left} comparisons.append({ "model": model, "delta_pass_at_1": result["delta"], "ci_low": result["ci_low"], "ci_high": result["ci_high"], "paired_permutation_p": result["p"], "improved": sum(value > 0 for value in changes.values()), "regressed": sum(value < 0 for value in changes.values()), "unchanged": sum(value == 0 for value in changes.values()), }) for task in sorted(left): a, b = sum(left[task]), sum(right[task]) transitions.append({"model": model, "task": task, "baseline_passes": a, "policy_passes": b, "transition": f"{a}->{b}"}) eligible = {row["task"] for row in read_csv(PANEL / "task-matrix.csv") if truth(row["eligible"])} cohort = [] for cell in ("terra_baseline", "sol_baseline", "terra_policy"): selected = [row for row in by_cell[cell] if row["task"] in eligible] tv = vectors(selected) passes = sum(sum(value) for value in tv.values()) cohort.append({"cell": cell, "tasks": len(tv), "attempts": len(selected), "passes": passes, "pass_at_1": passes / len(selected), "delta_pass_at_1": "", "ci_low": "", "ci_high": "", "paired_permutation_p": ""}) left = vectors([row for row in by_cell["sol_baseline"] if row["task"] in eligible]) right = vectors([row for row in by_cell["terra_policy"] if row["task"] in eligible]) result = compare_vectors(left, right, bootstrap, permutations, rng) cohort.append({"cell": "terra_policy_minus_sol_baseline", "tasks": len(eligible), "attempts": "", "passes": "", "pass_at_1": "", "delta_pass_at_1": result["delta"], "ci_low": result["ci_low"], "ci_high": result["ci_high"], "paired_permutation_p": result["p"]}) firing_rows = [row for row in rows if row["policy_fired"] != ""] firing_summary = [] for cell in sorted({row["cell"] for row in firing_rows}): selected = [row for row in firing_rows if row["cell"] == cell] firing_summary.append({"cell": cell, "attempts": len(selected), "fired_attempts": sum(truth(row["policy_fired"]) for row in selected), "silent_attempts": sum(not truth(row["policy_fired"]) for row in selected), "tasks_with_fire": len({row["task"] for row in selected if truth(row["policy_fired"])})}) write_csv(out / "primary.csv", primary) write_csv(out / "comparisons.csv", comparisons) write_csv(out / "task-transitions.csv", transitions) write_csv(out / "cost-latency.csv", costs) write_csv(out / "terminations.csv", terminations) write_csv(out / "policy-firing-summary.csv", firing_summary) write_csv(out / "terra-sol-eligible-cohort.csv", cohort) def panel_compare(left: list[dict], right: list[dict], tasks: list[str], repetitions: int, permutations: int, rng: random.Random) -> dict: a = {task: [truth(row["passed"]) for row in left if row["task"] == task and truth(row["scored"])] for task in tasks} b = {task: [truth(row["passed"]) for row in right if row["task"] == task and truth(row["scored"])] for task in tasks} complete = [task for task in tasks if len(a[task]) == 2 and len(b[task]) == 2] if len(complete) != len(tasks): return {"status": "pending", "tasks_complete": len(complete), "tasks_required": len(tasks)} result = compare_vectors({task: tuple(map(int, a[task])) for task in tasks}, {task: tuple(map(int, b[task])) for task in tasks}, repetitions, permutations, rng) return {"status": "complete", "tasks": len(tasks), **result} def reproduce_panel(out: Path) -> None: rows = read_csv(PANEL / "attempt-funnel.csv") lineage = read_csv(PANEL / "lineage-audit.csv") conditions = ["baseline", "real", "sham", "always_verify", "reconsider"] by_condition = {condition: [row for row in rows if row["condition"] == condition] for condition in conditions} task_rows = read_csv(PANEL / "task-matrix.csv") tasks = sorted(row["task"] for row in task_rows) eligible = sorted(row["task"] for row in task_rows if truth(row["eligible"])) silent = sorted(set(tasks) - set(eligible)) progress = [] cohort = [] for condition in conditions: selected = by_condition[condition] seconds = [number(row["agent_seconds"]) for row in selected if number(row["agent_seconds"]) is not None] outputs = [number(row["output_tokens"]) for row in selected if number(row["output_tokens"]) is not None] progress.append({ "condition": condition, "runs": len({row["run_id"] for row in lineage if row["condition"] == condition}), "attempts": len(selected), "scored_attempts": sum(truth(row["scored"]) for row in selected), "unscored_attempts": sum(not truth(row["scored"]) for row in selected), "tasks": len({row["task"] for row in selected}), "passes": sum(truth(row["passed"]) for row in selected if truth(row["scored"])), "eligible_attempts": sum(truth(row["eligible"]) and truth(row["scored"]) for row in selected), "fired_attempts": sum(truth(row["fired"]) and truth(row["scored"]) for row in selected), "behavior_yes": sum(row["behavior_marker"] == "yes" and truth(row["scored"]) for row in selected), "behavior_manual": sum(row["behavior_marker"] == "manual" and truth(row["scored"]) for row in selected), "cost_usd": sum(number(row["cost_usd"]) or 0 for row in selected), "mean_agent_seconds": sum(seconds) / len(seconds), "mean_output_tokens": sum(outputs) / len(outputs), }) for name, task_set in (("eligible", set(eligible)), ("silent", set(silent)), ("all", set(tasks))): subset = [row for row in selected if row["task"] in task_set and truth(row["scored"])] cohort.append({"condition": condition, "cohort": name, "tasks": len({row["task"] for row in subset}), "attempts": len(subset), "passes": sum(truth(row["passed"]) for row in subset), "pass_rate": sum(truth(row["passed"]) for row in subset) / len(subset), "fired_attempts": sum(truth(row["fired"]) for row in subset), "cost_usd": sum(number(row["cost_usd"]) or 0 for row in subset)}) lineage_summary = [] for condition in conditions: selected = by_condition[condition] for replicate in (1, 2): subset = [row for row in selected if int(row["replicate"]) == replicate] lineage_summary.append({"condition": condition, "replicate": replicate, "tasks": len(subset), "original_selected": sum(int(row["lineage_rank"]) == 0 for row in subset), "first_recovery_selected": sum(int(row["lineage_rank"]) == 1 for row in subset), "second_recovery_selected": sum(int(row["lineage_rank"]) == 2 for row in subset), "discarded_no_fair_attempts": sum(int(row["replaced_no_fair_attempts"]) for row in subset)}) families = sorted({family for row in rows for family in row["eligible_families"].split(";") if family}) family_rows = [] for condition in conditions: for family in families: subset = [row for row in by_condition[condition] if truth(row["scored"]) and family in row["eligible_families"].split(";")] family_rows.append({"condition": condition, "family": family, "eligible_attempts": len(subset), "condition_observed": sum(row["runtime_condition_observed"] == "True" for row in subset), "fired": sum(family in row["fired_families"].split(";") for row in subset), "behavior_yes": sum(row["behavior_marker"] == "yes" for row in subset), "scored_attempts": len(subset), "verifier_passes": sum(truth(row["passed"]) for row in subset)}) repetitions, permutations = 10_000, 100_000 rng = random.Random(20260910) comparisons = [] for left, right in [("real", "sham"), ("real", "baseline"), ("real", "always_verify"), ("real", "reconsider"), ("sham", "baseline")]: for name, task_set in (("eligible", eligible), ("silent", silent), ("all", tasks)): result = panel_compare(by_condition[left], by_condition[right], task_set, repetitions, permutations, rng) # panel_compare computes right-left; the registered panel reports left-right. if result.get("status") == "complete": result["delta"] *= -1 result["ci_low"], result["ci_high"] = -result["ci_high"], -result["ci_low"] comparisons.append({"left": left, "right": right, "cohort": name, **result}) def task_differences(condition_left: str, condition_right: str, task_set: list[str]) -> list[float]: left_rows, right_rows = by_condition[condition_left], by_condition[condition_right] return [ (sum(truth(row["passed"]) for row in left_rows if row["task"] == task) - sum(truth(row["passed"]) for row in right_rows if row["task"] == task)) / 2 for task in task_set ] eligible_diffs = task_differences("real", "sham", eligible) silent_diffs = task_differences("real", "sham", silent) observed = sum(eligible_diffs) / len(eligible_diffs) - sum(silent_diffs) / len(silent_diffs) samples = [] for _ in range(repetitions): eligible_sample = sum(eligible_diffs[rng.randrange(len(eligible_diffs))] for _ in eligible_diffs) / len(eligible_diffs) silent_sample = sum(silent_diffs[rng.randrange(len(silent_diffs))] for _ in silent_diffs) / len(silent_diffs) samples.append(eligible_sample - silent_sample) combined = [(value, "eligible") for value in eligible_diffs] + [(value, "silent") for value in silent_diffs] hits = 0 for _ in range(permutations): rng.shuffle(combined) first = [value for value, _ in combined[:len(eligible_diffs)]] second = [value for value, _ in combined[len(eligible_diffs):]] statistic = sum(first) / len(first) - sum(second) / len(second) hits += abs(statistic) >= abs(observed) - 1e-12 interaction = {"status": "complete", "interaction": observed, "ci_low": quantile(samples, 0.025), "ci_high": quantile(samples, 0.975), "p": (hits + 1) / (permutations + 1)} write_csv(out / "condition-progress.csv", progress) write_csv(out / "cohort-summary.csv", cohort) write_csv(out / "lineage-summary.csv", lineage_summary) write_csv(out / "family-funnel.csv", family_rows) write_csv(out / "comparisons.csv", comparisons) (out / "interaction.json").write_text(json.dumps(interaction, indent=2) + "\n", encoding="utf-8") def equivalent(left: Path, right: Path) -> bool: a, b = read_csv(left), read_csv(right) if len(a) != len(b) or [set(row) for row in a] != [set(row) for row in b]: return False for x, y in zip(a, b): for key in x: try: if not math.isclose(float(x[key]), float(y[key]), rel_tol=1e-12, abs_tol=1e-12): return False except ValueError: if x[key] != y[key]: return False return True def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--out", type=Path, help="write regenerated tables here") parser.add_argument("--check", action="store_true", help="compare regenerated tables with the release") args = parser.parse_args() if not args.out and not args.check: parser.error("choose --out DIR or --check") if args.check: with tempfile.TemporaryDirectory() as directory: root = Path(directory) reproduce_complete(root / "complete-suite") reproduce_panel(root / "five-arm-panel") failures = [] for section in ("complete-suite", "five-arm-panel"): for generated in (root / section).glob("*.csv"): if not equivalent(generated, ROOT / "results" / section / generated.name): failures.append(f"{section}/{generated.name}") generated_interaction = json.loads((root / "five-arm-panel/interaction.json").read_text()) released_interaction = json.loads((PANEL / "interaction.json").read_text()) if generated_interaction != released_interaction: failures.append("five-arm-panel/interaction.json") if failures: raise SystemExit("Regenerated tables differ: " + ", ".join(failures)) print("All derivable released tables regenerated successfully.") else: reproduce_complete(args.out / "complete-suite") reproduce_panel(args.out / "five-arm-panel") print(args.out) if __name__ == "__main__": main()