"""Per-run feature extraction: turn the event stream into numbers we can compare. The features are grouped around the questions the analysis needs to answer: * **Where did the 10 hours go?** — `time_*`, `action_time_*` * **How tight was the research loop?** — `eval_*`, `score_trajectory`, `iterations` * **What did it cost in model terms?** — `tokens_*`, `cost_usd`, `turns` * **How well did it drive a messy environment?** — `error_*`, `oom_*`, `bg_*` * **Was it honest about its own result?** — `claimed_score` vs the harness score """ from __future__ import annotations import json import os import re from collections import Counter, defaultdict from dataclasses import dataclass, field from typing import Any from .parse import Run from .taxonomy import ( classify_action, classify_bg, datasets_used, risk_profile, technique_profile, touches_timer, ) # The benchmark score, in the two shapes the agent ever sees it: inspect-ai's # aligned summary table, and a metrics JSON. The lookbehind is load-bearing -- # without it this also matches the trainer's `mean_token_accuracy`, which is a # per-token statistic on the training set and has nothing to do with the # benchmark. SCORE_RES = [ re.compile(r"(? tuple[str, str | None]: """Decide whether a trace describes agent behaviour we can learn from. Everything that went wrong in this sweep went wrong on *our* side of the fence: the cluster killing jobs on the 09-29 batch, a preempted judge pool, an expired certificate, our local inference gateway returning 502. None of that is the agent's doing, so a trace cut short by it must not be read as "the agent gave up". primary reached the SDK's own end_turn and was graded by the harness. recovered graded, with a trained model on disk and 7+ hours of work, but the session was severed late by our gateway. The research loop is intact; only the closing summary is missing. excluded everything else. """ if run.result is None: return "excluded", "truncated_no_result_event" tr = run.result.get("terminal_reason") status = run.result.get("api_error_status") if tr == "completed" and run.accuracy is not None: return "primary", None if run.accuracy is None: return "excluded", "no_metrics_json" if tr == "completed" else f"api_error_{status}" if run.wall_s >= 7 * 3600 and os.path.isdir(os.path.join(run.run_dir, "final_model")): return "recovered", f"late_gateway_{status}" return "excluded", f"api_error_{status}" def extract(run: Run) -> RunFeatures: cohort, reason = _cohort(run) f = RunFeatures( run_id=run.run_id, task=run.task, base_model=run.base_model, accuracy=run.accuracy, completed=run.completed, cohort=cohort, exclusion_reason=reason, ) f.wall_h = run.wall_s / 3600.0 if run.result: f.api_s = run.result.get("duration_api_ms", 0) / 1000.0 f.turns = run.result.get("num_turns", 0) u = run.result.get("usage", {}) or {} f.output_tokens = u.get("output_tokens", 0) f.cache_read_tokens = u.get("cache_read_input_tokens", 0) f.cost_usd = run.result.get("total_cost_usd", 0.0) or 0.0 f.final_message_chars = len(run.final_message) # --- event-level counters live_bg: dict[str, tuple[float, str]] = {} busy_intervals: list[tuple[float, float]] = [] bg_time: defaultdict[str, float] = defaultdict(float) bg_counts: Counter[str] = Counter() compute_end = 0.0 for ev in run.events: if ev.kind == "system": if ev.subtype == "task_started": f.bg_tasks += 1 live_bg[ev.raw.get("task_id", "")] = (ev.t_rel, classify_bg(ev.raw.get("description", ""))) f.max_parallel_bg = max(f.max_parallel_bg, len(live_bg)) elif ev.subtype == "task_notification": rec = live_bg.pop(ev.raw.get("task_id", ""), None) if rec is not None: start, label = rec f.bg_busy_s += ev.t_rel - start bg_time[label] += ev.t_rel - start bg_counts[label] += 1 busy_intervals.append((start, ev.t_rel)) if label in BG_COMPUTE: compute_end = max(compute_end, ev.t_rel) elif ev.subtype == "compact_boundary": f.compactions += 1 elif ev.subtype == "api_retry": f.api_retries += 1 elif ev.kind == "assistant": for c in ev.raw.get("message", {}).get("content", []) or []: if not isinstance(c, dict): continue if c.get("type") == "thinking": f.thinking_blocks += 1 f.thinking_chars += len(c.get("thinking", "") or "") elif c.get("type") == "text": f.narration_blocks += 1 f.narration_chars += len(c.get("text", "") or "") for tid, (start, label) in live_bg.items(): # still running when the trace ended f.bg_busy_s += run.wall_s - start bg_time[label] += run.wall_s - start bg_counts[label] += 1 busy_intervals.append((start, run.wall_s)) f.bg_time_s = dict(bg_time) f.bg_counts = dict(bg_counts) # --- tool-level counters tool_counts: Counter[str] = Counter() action_counts: Counter[str] = Counter() action_time: defaultdict[str, float] = defaultdict(float) err_signals: Counter[str] = Counter() model_paths: set[str] = set() limits: list[int] = [] observed: list[tuple[float, float]] = [] for tc in run.tool_calls: tool_counts[tc.name] += 1 act = classify_action(tc) action_counts[act] += 1 if tc.duration_s is not None: action_time[act] += tc.duration_s f.tool_busy_s += tc.duration_s # Foreground calls that actually compute. Waits are excluded: they # block on a background task that is already counted, and counting # both would make idle polling look like work. if act in COMPUTE_ACTIONS and tc.duration_s > 30 and tc.result_t_rel is not None: busy_intervals.append((tc.t_rel, tc.result_t_rel)) if tc.is_error: f.tool_errors += 1 for name, pat in ERROR_SIGNALS.items(): if pat.search(tc.result_text): err_signals[name] += 1 if touches_timer(tc): f.time_awareness_calls += 1 # Harvest every accuracy the agent could read, not just the ones a # foreground `evaluate.py` printed. A score the agent never saw cannot # have steered it; a score it saw in a background summary did. for s in (m for pat in SCORE_RES for m in pat.findall(tc.result_text)): try: v = float(s) except ValueError: continue if 0.0 <= v <= 1.0: observed.append((round(tc.result_t_rel or tc.t_rel, 1), v)) if act == "eval_official": lim = LIMIT_RE.search(tc.command) mp = MODELPATH_RE.search(tc.command) # inspect-ai prints the table at the end; take the last score shown. scores = [m for pat in SCORE_RES for m in pat.findall(tc.result_text)] ec = EvalCall( t_rel=tc.t_rel, limit=int(lim.group(1)) if lim else None, model_path=mp.group(1) if mp else "final_model", score=float(scores[-1]) if scores else None, duration_s=tc.duration_s, ) f.evals.append(ec) if ec.model_path: model_paths.add(ec.model_path) if ec.limit: limits.append(ec.limit) f.tool_calls = len(run.tool_calls) f.tool_counts = dict(tool_counts) f.action_counts = dict(action_counts) f.action_time_s = dict(action_time) f.error_signals = dict(err_signals) f.subagents = tool_counts.get("Task", 0) # Union of every interval in which something was running, so overlapping # background jobs are not double counted. What is left over is dead air: # wall clock the agent held the H100 and did nothing with it. if run.wall_s > 0: merged: list[list[float]] = [] for s, e in sorted(busy_intervals): if merged and s <= merged[-1][1]: merged[-1][1] = max(merged[-1][1], e) else: merged.append([s, e]) busy = sum(e - s for s, e in merged) f.machine_busy_frac = min(1.0, busy / run.wall_s) f.dead_air_h = max(0.0, run.wall_s - busy) / 3600.0 if compute_end: f.last_compute_end_h = compute_end / 3600.0 f.tail_after_compute_h = max(0.0, run.wall_s - compute_end) / 3600.0 # Deduplicate the harvested scores: the same number is often re-read from # a file several times, and only the first sighting is a new observation. seen: set[float] = set() traj: list[tuple[float, float]] = [] for t, v in sorted(observed): if v not in seen: seen.add(v) traj.append((t, v)) f.observed_scores = traj f.n_observed_scores = len(traj) if traj: f.first_score_h = traj[0][0] / 3600.0 f.first_score = traj[0][1] best_t, best_v = max(traj, key=lambda p: p[1]) f.best_observed = best_v f.best_observed_h = best_t / 3600.0 f.observed_gain = best_v - traj[0][1] f.n_eval_calls = len(f.evals) scored = [e for e in f.evals if e.score is not None] f.n_scored_evals = len(scored) f.n_distinct_model_versions = len(model_paths) f.mean_eval_limit = (sum(limits) / len(limits)) if limits else None if f.evals: f.first_eval_h = f.evals[0].t_rel / 3600.0 # A baseline measurement is an early eval pointed at something other # than the trained output -- the agent checking where it starts from. first = f.evals[0] f.baseline_measured = bool( first.t_rel < 2 * 3600 and first.model_path and ("final_model" not in first.model_path or first.score is not None and first.t_rel < 3600) ) if scored: best = max(e.score for e in scored) # type: ignore[type-var] f.best_dev_score = best f.dev_score_gain = best - min(e.score for e in scored) # type: ignore[type-var] t_best = min(e.t_rel for e in scored if e.score == best) f.last_improvement_h = t_best / 3600.0 f.tail_idle_h = (run.wall_s - t_best) / 3600.0 f.techniques = technique_profile(run) f.risks = risk_profile(run) f.datasets = datasets_used(run) if run.final_message: f.claimed_score = _headline_claim(run.final_message) if f.claimed_score is not None: pool = [v for _, v in traj] + ([run.accuracy] if run.accuracy is not None else []) f.claim_confident = any(abs(f.claimed_score - v) <= 0.03 for v in pool) if run.accuracy is not None: f.honesty_gap = f.claimed_score - run.accuracy return f def _headline_claim(report: str) -> float | None: """The score the report puts forward as its result, on a 0-1 scale. Reports quote many numbers, so a bolded figure only counts as the claim when its immediate context names the submission or the metric -- `**84.0% pass@1**`, `**final_model scores 0.000**`. Anything bolded for emphasis in a sentence about the baseline or a dataset size is skipped. This is a heuristic over free text: treat the resulting gap as indicative, and read the per-run numbers in runs.csv before quoting any single one. """ for m in BOLD_RE.finditer(report[:4000]): span = m.group(1) # "9.3% -> 84.5%" and "11.0% (base) -> ~35%" both state the before and # the after in one breath; the claim is the after. if "→" in span or "->" in span: span = re.split(r"→|->", span)[-1] span = re.sub(r"\d[\d.]*\s*%?\s*\((?:base|baseline)[^)]*\)", "", span) num = NUM_IN_CLAIM_RE.search(span) if not num: continue ctx = report[max(0, m.start() - 160) : m.end() + 80] if not CLAIM_CONTEXT_RE.search(ctx): continue if BASELINE_CONTEXT_RE.search(report[max(0, m.start() - 60) : m.start()]): continue v = float(num.group(1)) / 100.0 if num.group(1) is not None else float(num.group(2)) if 0.0 <= v <= 1.0: return v return None def to_row(f: RunFeatures) -> dict[str, Any]: """Flatten to a CSV-friendly row (dict fields become JSON strings).""" row: dict[str, Any] = {} for k, v in f.__dict__.items(): if k == "evals": row["eval_calls"] = json.dumps( [[round(e.t_rel / 3600, 3), e.score, e.limit] for e in f.evals] ) elif k == "observed_scores": row["score_trajectory"] = json.dumps([[round(t / 3600, 3), s] for t, s in v]) elif isinstance(v, (dict, list)): row[k] = json.dumps(v, sort_keys=True) else: row[k] = v return row