|
| 1 | +r"""backfill_tasks — re-run only the missing/failed tasks of an existing model row. |
| 2 | +
|
| 3 | +Reads the model's existing ``result.json`` + ``raw_outputs.jsonl`` from |
| 4 | +``<out>/<safe_model_slug>/``, re-runs ONLY the requested task IDs against the |
| 5 | +live pack, merges old and new per-task results, re-aggregates, and rewrites |
| 6 | +both files in place (originals are backed up with a ``.bak`` suffix). |
| 7 | +
|
| 8 | +Usage:: |
| 9 | +
|
| 10 | + python -m scripts.backfill_tasks \ |
| 11 | + --model anthropic/claude-sonnet-4.6 \ |
| 12 | + --tasks T1-OPS-003,T1-OPS-004,T1-OPS-005,T1-OPS-006 \ |
| 13 | + --pack operations --runs 5 --judge --out results/operations |
| 14 | +
|
| 15 | +If the model has no existing row (e.g. gpt-5.5@xhigh), all tasks in |
| 16 | +``--tasks`` are run and the merged row is just the new tasks — equivalent to |
| 17 | +a fresh partial run. |
| 18 | +
|
| 19 | +Judge cost in the merged ``cost_metrics`` is the sum of the old row's |
| 20 | +``judge_cost_usd`` and the backfill's judge spend (token-level judge counts |
| 21 | +are only available for the backfill portion and are reported as-is). |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import argparse |
| 27 | +import json |
| 28 | +import shutil |
| 29 | +import sys |
| 30 | +from pathlib import Path |
| 31 | +from typing import Any |
| 32 | + |
| 33 | +from runner.aggregator import aggregate |
| 34 | +from runner.dispatcher import TaskRunResult, load_pack, run_task |
| 35 | +from runner.io import write_raw_outputs, write_result |
| 36 | +from scripts.run_models import _build_adapter, _resolve_pack, _safe_slug |
| 37 | + |
| 38 | + |
| 39 | +def _load_existing( |
| 40 | + model_dir: Path, |
| 41 | + skip_task_ids: set[str], |
| 42 | +) -> tuple[list[TaskRunResult], float]: |
| 43 | + """Reconstruct TaskRunResults for tasks NOT being backfilled. |
| 44 | +
|
| 45 | + Args: |
| 46 | + model_dir: Existing per-model result directory. |
| 47 | + skip_task_ids: Task IDs being re-run (excluded from reconstruction). |
| 48 | +
|
| 49 | + Returns: |
| 50 | + ``(kept_results, old_judge_cost_usd)``. Empty list / 0.0 when no |
| 51 | + prior row exists. |
| 52 | + """ |
| 53 | + result_path = model_dir / "result.json" |
| 54 | + raw_path = model_dir / "raw_outputs.jsonl" |
| 55 | + if not result_path.exists(): |
| 56 | + return [], 0.0 |
| 57 | + |
| 58 | + result = json.loads(result_path.read_text(encoding="utf-8")) |
| 59 | + |
| 60 | + outputs_by_task: dict[str, list[dict[str, Any]]] = {} |
| 61 | + if raw_path.exists(): |
| 62 | + with raw_path.open(encoding="utf-8") as fh: |
| 63 | + for line in fh: |
| 64 | + line = line.strip() |
| 65 | + if not line: |
| 66 | + continue |
| 67 | + out = json.loads(line) |
| 68 | + outputs_by_task.setdefault(out["task_id"], []).append(out) |
| 69 | + |
| 70 | + kept: list[TaskRunResult] = [] |
| 71 | + for entry in result.get("per_task_scores", []): |
| 72 | + tid = entry["task_id"] |
| 73 | + if tid in skip_task_ids: |
| 74 | + continue |
| 75 | + kept.append( |
| 76 | + TaskRunResult( |
| 77 | + task_id=tid, |
| 78 | + track=entry["track"], |
| 79 | + pack_id=entry.get("pack_id"), |
| 80 | + run_count=entry["run_count"], |
| 81 | + outputs=outputs_by_task.get(tid, []), |
| 82 | + scores=dict(entry["scores"]), |
| 83 | + composite=entry.get("composite"), |
| 84 | + scorer_flags=list(entry.get("scorer_flags") or []), |
| 85 | + ) |
| 86 | + ) |
| 87 | + |
| 88 | + old_judge_cost = (result.get("cost_metrics") or {}).get("judge_cost_usd") or 0.0 |
| 89 | + return kept, float(old_judge_cost) |
| 90 | + |
| 91 | + |
| 92 | +def main(argv: list[str] | None = None) -> int: |
| 93 | + """CLI entry point: re-run the named tasks and merge into the existing row. |
| 94 | +
|
| 95 | + Args: |
| 96 | + argv: Argument list (defaults to ``sys.argv[1:]`` when ``None``). |
| 97 | +
|
| 98 | + Returns: |
| 99 | + Exit code: 0 on full success, 1 when any backfill task failed. |
| 100 | + """ |
| 101 | + parser = argparse.ArgumentParser( |
| 102 | + prog="python -m scripts.backfill_tasks", |
| 103 | + description="Re-run only the named tasks for one model row and merge results.", |
| 104 | + ) |
| 105 | + parser.add_argument("--model", required=True, help="Model ID (supports @<effort> suffix).") |
| 106 | + parser.add_argument( |
| 107 | + "--tasks", required=True, metavar="T1,T2,...", help="Comma-separated task IDs to re-run." |
| 108 | + ) |
| 109 | + parser.add_argument("--pack", required=True, help="Pack short name or path.") |
| 110 | + parser.add_argument("--adapter", default="openrouter") |
| 111 | + parser.add_argument("--runs", type=int, default=5) |
| 112 | + parser.add_argument("--judge", action="store_true") |
| 113 | + parser.add_argument("--judge-model", default=None) |
| 114 | + parser.add_argument("--temperature", type=float, default=1.0) |
| 115 | + parser.add_argument("--out", required=True, help="Output root (same as the original run).") |
| 116 | + parser.add_argument("--grade-version", default="0.1.0") |
| 117 | + args = parser.parse_args(argv) |
| 118 | + |
| 119 | + wanted_ids = {t.strip() for t in args.tasks.split(",") if t.strip()} |
| 120 | + if not wanted_ids: |
| 121 | + print("ERROR: --tasks must be a non-empty comma-separated list.", file=sys.stderr) |
| 122 | + return 1 |
| 123 | + |
| 124 | + pack_path, pack_id = _resolve_pack(args.pack) |
| 125 | + tasks = [t for t in load_pack(pack_path) if t.get("task_id") in wanted_ids] |
| 126 | + missing = wanted_ids - {t["task_id"] for t in tasks} |
| 127 | + if missing: |
| 128 | + print(f"ERROR: task IDs not found in pack: {sorted(missing)}", file=sys.stderr) |
| 129 | + return 1 |
| 130 | + |
| 131 | + model_dir = Path(args.out) / _safe_slug(args.model) |
| 132 | + kept_results, old_judge_cost = _load_existing(model_dir, wanted_ids) |
| 133 | + print( |
| 134 | + f"Backfilling {len(tasks)} task(s) for {args.model}; " |
| 135 | + f"keeping {len(kept_results)} existing task result(s)." |
| 136 | + ) |
| 137 | + |
| 138 | + adapter = _build_adapter(args.adapter, model=args.model, temperature=args.temperature) |
| 139 | + |
| 140 | + judge_client: Any | None = None |
| 141 | + if args.judge: |
| 142 | + from benchmark.rubrics.judge_client import JudgeClient, select_judge_model |
| 143 | + |
| 144 | + if args.judge_model: |
| 145 | + judge_model, judge_effort = args.judge_model, None |
| 146 | + else: |
| 147 | + judge_model, judge_effort = select_judge_model(args.model) |
| 148 | + print(f" judge: {judge_model}" + (f" (effort: {judge_effort})" if judge_effort else "")) |
| 149 | + judge_client = JudgeClient(model=judge_model, reasoning_effort=judge_effort) |
| 150 | + |
| 151 | + new_results: list[TaskRunResult] = [] |
| 152 | + failures: list[dict[str, str]] = [] |
| 153 | + for i, task in enumerate(tasks, start=1): |
| 154 | + tid = task["task_id"] |
| 155 | + print(f" [{i}/{len(tasks)}] {tid} ...", end=" ", flush=True) |
| 156 | + try: |
| 157 | + tr = run_task( |
| 158 | + task=task, |
| 159 | + adapter=adapter, |
| 160 | + runs=args.runs, |
| 161 | + pack_id=pack_id, |
| 162 | + judge_client=judge_client, |
| 163 | + ) |
| 164 | + except Exception as exc: # noqa: BLE001 |
| 165 | + print(f"FAILED ({exc})", flush=True) |
| 166 | + failures.append({"task_id": tid, "error": str(exc)}) |
| 167 | + continue |
| 168 | + comp = f"{tr.composite:.4f}" if tr.composite is not None else "n/a" |
| 169 | + print(f"composite={comp}", flush=True) |
| 170 | + new_results.append(tr) |
| 171 | + |
| 172 | + if not new_results: |
| 173 | + print("No backfill task succeeded — leaving existing row untouched.", file=sys.stderr) |
| 174 | + return 1 |
| 175 | + |
| 176 | + # Merge, preserving canonical pack order. |
| 177 | + pack_order = {t["task_id"]: i for i, t in enumerate(load_pack(pack_path))} |
| 178 | + merged = sorted( |
| 179 | + kept_results + new_results, |
| 180 | + key=lambda tr: pack_order.get(tr.task_id, 10_000), |
| 181 | + ) |
| 182 | + |
| 183 | + judge_metrics: dict[str, Any] | None = None |
| 184 | + if judge_client is not None: |
| 185 | + judge_metrics = { |
| 186 | + "cumulative_cost_usd": (judge_client.cumulative_cost_usd or 0.0) + old_judge_cost, |
| 187 | + "cumulative_prompt_tokens": judge_client.cumulative_prompt_tokens, |
| 188 | + "cumulative_completion_tokens": judge_client.cumulative_completion_tokens, |
| 189 | + "judge_call_count": judge_client.judge_call_count, |
| 190 | + } |
| 191 | + elif old_judge_cost: |
| 192 | + judge_metrics = {"cumulative_cost_usd": old_judge_cost} |
| 193 | + |
| 194 | + scorecard = aggregate( |
| 195 | + task_results=merged, |
| 196 | + model_id=args.model, |
| 197 | + grade_version=args.grade_version, |
| 198 | + judge_metrics=judge_metrics, |
| 199 | + ) |
| 200 | + |
| 201 | + # Back up originals, then write merged row. |
| 202 | + model_dir.mkdir(parents=True, exist_ok=True) |
| 203 | + for name in ("result.json", "raw_outputs.jsonl", "failures.json"): |
| 204 | + p = model_dir / name |
| 205 | + if p.exists(): |
| 206 | + shutil.copy2(p, p.with_suffix(p.suffix + ".bak")) |
| 207 | + |
| 208 | + all_outputs = [out for tr in merged for out in tr.outputs] |
| 209 | + raw_path = write_raw_outputs(all_outputs, model_dir) |
| 210 | + result_path = write_result(scorecard, model_dir) |
| 211 | + |
| 212 | + failures_path = model_dir / "failures.json" |
| 213 | + if failures: |
| 214 | + failures_path.write_text(json.dumps(failures, indent=2) + "\n", encoding="utf-8") |
| 215 | + elif failures_path.exists(): |
| 216 | + failures_path.unlink() # row is now complete — stale failure list removed |
| 217 | + |
| 218 | + overall = scorecard.get("overall_composite") |
| 219 | + comp_str = f"{overall:.4f}" if overall is not None else "n/a" |
| 220 | + print(f"\nMerged row: {len(merged)} task(s), composite={comp_str}") |
| 221 | + print(f"Raw outputs → {raw_path}") |
| 222 | + print(f"Result JSON → {result_path}") |
| 223 | + if failures: |
| 224 | + print(f"Backfill failures recorded → {failures_path}", file=sys.stderr) |
| 225 | + return 1 if failures else 0 |
| 226 | + |
| 227 | + |
| 228 | +if __name__ == "__main__": |
| 229 | + sys.exit(main()) |
0 commit comments