#!/usr/bin/env python3 """Extract features from PostTrainBench traces and dump them for analysis. python analysis/run_analysis.py --figures # both agents python analysis/run_analysis.py --agent codex # one of them python analysis/run_analysis.py --results-root PATH --agent mine Per agent, writes under `analysis/out//`: runs.csv / runs.json one row per trace, included and excluded summary.json cohort-level aggregates used by the report narratives/*.md a readable account of each analysed run and figures under `docs/results/figures//`. """ from __future__ import annotations import argparse import csv import json import os import sys from collections import Counter, defaultdict sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from trace_analysis.features import extract, to_row # noqa: E402 from trace_analysis.parse import load_all # noqa: E402 from trace_analysis.stats import ( # noqa: E402 dev_to_harness_drop, feature_correlations, final_verification, oom_recovery, per_task_table, rerun_variance, technique_effects, ) LUSTRE = "/lustre-storage/fsx_2/user/jiaruiliu/ptb-data" AGENT_ROOTS = { "claude": f"{LUSTRE}/results/claude_non_api_claude-opus-5_10h_run1", "codex": f"{LUSTRE}/results_codex_sdk_gpt-5.6-sol_20261006/codex_sdk_gpt-5.6-sol_10h_run1", } ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) OUT_DIR = os.path.join(ROOT, "analysis", "out") def out_dir(agent: str) -> str: return os.path.join(OUT_DIR, agent) def build(results_root: str): runs = load_all(results_root) feats = [extract(r) for r in runs] return runs, feats def summarize(feats) -> dict: """Cohort aggregates. The analysed cohort is every trace where the agent got to run its own research loop end to end and the harness graded the result. Traces killed by our cluster, our preempted judge pool, or our expired certificate are reported separately: they are our bugs, and reading them as agent behaviour would be measuring our infrastructure instead of the agent. """ inc = [f for f in feats if f.cohort in ("primary", "recovered")] exc = [f for f in feats if f.cohort == "excluded"] def mean(xs): xs = [x for x in xs if x is not None] return sum(xs) / len(xs) if xs else None tool_tot: Counter[str] = Counter() act_tot: Counter[str] = Counter() act_time: defaultdict[str, float] = defaultdict(float) bg_time: defaultdict[str, float] = defaultdict(float) tech_runs: Counter[str] = Counter() risk_runs: Counter[str] = Counter() err_runs: Counter[str] = Counter() ds_runs: Counter[str] = Counter() for f in inc: tool_tot.update(f.tool_counts) act_tot.update(f.action_counts) for k, v in f.action_time_s.items(): act_time[k] += v for k, v in f.bg_time_s.items(): bg_time[k] += v tech_runs.update(f.techniques.keys()) risk_runs.update(f.risks.keys()) err_runs.update(f.error_signals.keys()) ds_runs.update(f.datasets) n = max(len(inc), 1) return { "n_traces": len(feats), "n_included": len(inc), "cohort_counts": dict(Counter(f.cohort for f in feats)), "n_excluded": len(exc), "exclusions": dict(Counter(f.exclusion_reason for f in exc)), "cells_covered": len({(f.task, f.base_model) for f in inc}), "means": { "accuracy": mean([f.accuracy for f in inc]), "wall_h": mean([f.wall_h for f in inc]), "api_s": mean([f.api_s for f in inc]), "turns": mean([f.turns for f in inc]), "tool_calls": mean([f.tool_calls for f in inc]), "output_tokens": mean([f.output_tokens for f in inc]), "cost_usd": mean([f.cost_usd for f in inc]), "n_eval_calls": mean([f.n_eval_calls for f in inc]), "n_observed_scores": mean([f.n_observed_scores for f in inc]), "n_distinct_model_versions": mean([f.n_distinct_model_versions for f in inc]), "first_eval_h": mean([f.first_eval_h for f in inc]), "tail_idle_h": mean([f.tail_idle_h for f in inc]), "machine_busy_frac": mean([f.machine_busy_frac for f in inc]), "dead_air_h": mean([f.dead_air_h for f in inc]), "time_awareness_calls": mean([f.time_awareness_calls for f in inc]), "tool_errors": mean([f.tool_errors for f in inc]), "bg_tasks": mean([f.bg_tasks for f in inc]), "max_parallel_bg": mean([f.max_parallel_bg for f in inc]), "compactions": mean([f.compactions for f in inc]), "thinking_blocks": mean([f.thinking_blocks for f in inc]), "thinking_chars": mean([f.thinking_chars for f in inc]), "narration_chars": mean([f.narration_chars for f in inc]), "honesty_gap": mean([f.honesty_gap for f in inc]), "subagents": mean([f.subagents for f in inc]), "final_message_chars": mean([f.final_message_chars for f in inc]), }, "tool_totals": dict(tool_tot.most_common()), "action_totals": dict(act_tot.most_common()), "action_hours": {k: round(v / 3600, 2) for k, v in sorted(act_time.items(), key=lambda kv: -kv[1])}, "bg_hours_per_run": {k: round(v / 3600 / n, 2) for k, v in sorted(bg_time.items(), key=lambda kv: -kv[1])}, "technique_run_counts": dict(tech_runs.most_common()), "risk_run_counts": dict(risk_runs.most_common()), "error_run_counts": dict(err_runs.most_common()), "dataset_run_counts": dict(ds_runs.most_common(40)), "per_task": per_task_table(inc), "feature_correlations": feature_correlations(inc), "technique_effects": technique_effects(inc), "rerun_variance": rerun_variance(inc), "final_verification": final_verification(inc), "dev_to_harness_drop": dev_to_harness_drop(inc), "oom_recovery": oom_recovery(inc), } def run_one(agent: str, results_root: str, figures: bool) -> dict: od = out_dir(agent) os.makedirs(od, exist_ok=True) runs, feats = build(results_root) print(f"[{agent}] parsed {len(runs)} traces from {results_root}") rows = [to_row(f) for f in feats] cols = sorted({k for r in rows for k in r}) with open(os.path.join(od, "runs.csv"), "w", newline="") as fh: w = csv.DictWriter(fh, fieldnames=cols) w.writeheader() w.writerows(rows) with open(os.path.join(od, "runs.json"), "w") as fh: json.dump(rows, fh, indent=1) summary = summarize(feats) summary["agent"] = agent summary["results_root"] = results_root keep = {f.run_id for f in feats if f.cohort in ("primary", "recovered")} cohort_runs = [r for r in runs if r.run_id in keep] from trace_analysis.probes import probe_cohort summary["prose_probes"] = probe_cohort(cohort_runs) with open(os.path.join(od, "summary.json"), "w") as fh: json.dump(summary, fh, indent=1) print(f"[{agent}] cohort {summary['cohort_counts']}, cells {summary['cells_covered']}") if figures: from trace_analysis.figures import make_all make_all(runs, feats, agent) from trace_analysis.narrative import write_all write_all(cohort_runs, os.path.join(od, "narratives")) return summary def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--agent", default="all", help="claude | codex | all | a custom label") ap.add_argument("--results-root", default=None, help="override; required for a custom label") ap.add_argument("--figures", action="store_true") args = ap.parse_args() if args.agent == "all": targets = list(AGENT_ROOTS.items()) elif args.results_root: targets = [(args.agent, args.results_root)] elif args.agent in AGENT_ROOTS: targets = [(args.agent, AGENT_ROOTS[args.agent])] else: ap.error(f"unknown agent {args.agent!r}; pass --results-root") for agent, root in targets: run_one(agent, root, args.figures) if __name__ == "__main__": main()