File size: 8,232 Bytes
158258b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#!/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/<agent>/`:
    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/<agent>/`.
"""

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()