"""Append-only, provenance-carrying result store and the run driver every instrument shares. bench/results//// (never overwritten: a fresh run_id per run) run.json lane record (no secrets) + server snapshot + harness git sha/dirty + host + args + item_set + started/ended + complete flag items.jsonl one row per attempt (row contract: CONTRACT.md) summary.json written by finish() Rows are read back deduped (see dedupe) and with read-time status rules (effective_status). """ import json import os import platform import socket import subprocess import threading import time import uuid import urllib.parse import urllib.request from concurrent.futures import ThreadPoolExecutor from bench.core import client, stats from bench.core import lane as lane_mod from bench.core.reporting import RESULTS_DIR, safe_label # Not a grade of the model's answer. ctx_overflow is listed here for quality comparisons, # but oracle-label derivation treats it as "this lane cannot take this job". INFRA_STATUSES = {"timeout", "oom", "ctx_overflow", "conn_error", "budget_stop", "guard_refused", "bad_response", "harness_error", "skipped", "stripped"} # "stripped": the server generated answer tokens but returned none of them (no content, no # tool call) -- a provider-side parser ate the output: DeepInfra's Qwen tool # parser swallows a plain-text ... even with no tools declared (3/3 # probes on the tc-xml probe, now in conformance's preflight). Needs reported reasoning_tokens to tell answer tokens from # thinking, so llama-server lanes (which don't report them) stay "empty". One tool call is # ~27 tokens; a genuinely empty answer is a few end-of-turn tokens. STRIPPED_MIN_ANSWER_TOKENS = 16 def is_infra(status): return status in INFRA_STATUSES or str(status).startswith("http_") def effective_status(row): """The row's status, with "empty" upgraded to "stripped" when answer tokens went missing. Applied when rows are written and again when they are read, so stored rows reclassify.""" st = row.get("status") ct, rt = row.get("completion_tokens"), row.get("reasoning_tokens") if st == "empty" and rt is not None and ct and ct - rt >= STRIPPED_MIN_ANSWER_TOKENS: return "stripped" return st def _git_info(): here = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) try: sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=here, capture_output=True, text=True, timeout=10).stdout.strip() dirty = subprocess.run(["git", "status", "--porcelain", "--", "."], cwd=here, capture_output=True, text=True, timeout=10).stdout.strip() return {"git_sha": sha or None, "dirty": bool(dirty)} except Exception: # noqa: BLE001 — provenance is best effort return {"git_sha": None, "dirty": None} def _get_json(url, timeout=10): try: with urllib.request.urlopen(url, timeout=timeout) as r: return json.load(r) except Exception as e: # noqa: BLE001 return {"_error": repr(e)[:200]} def server_snapshot(lane): """What the server says about itself, at run start. Large blobs are hashed.""" kind = lane.snapshot_kind base = lane.base_url() snap = {"kind": kind, "taken_at": time.strftime("%Y-%m-%dT%H:%M:%S")} if kind == "llama-server": # ?model= lets a multi-backend gateway (one port, several models) answer for the right # backend; a bare llama-server ignores the query string. props = _get_json(base + "/props?model=" + urllib.parse.quote(lane.model)) tmpl = props.pop("chat_template", None) if isinstance(props, dict) else None if tmpl: import hashlib props["chat_template_sha256"] = hashlib.sha256(tmpl.encode()).hexdigest() snap["props"] = props snap["models"] = _get_json(base + "/v1/models") elif kind == "mtplx": snap["models"] = _get_json(base + "/v1/models") elif kind == "openrouter": snap["endpoints"] = _get_json(f"https://openrouter.ai/api/v1/models/{lane.model}/endpoints") return snap class RunStore: def __init__(self, instrument, *, item_set=None, args=None, lane=None): self.lane = lane or lane_mod.current() self.instrument = instrument stamp = time.strftime("%Y%m%d-%H%M%S") self.run_id = f"{stamp}-{uuid.uuid4().hex[:6]}" self.dir = os.path.join(RESULTS_DIR, safe_label(instrument), safe_label(self.lane.lane_id), self.run_id) os.makedirs(self.dir, exist_ok=False) self.items_path = os.path.join(self.dir, "items.jsonl") self._lock = threading.Lock() self.n_rows = 0 self.run = { "run_id": self.run_id, "instrument": instrument, "item_set": item_set, "lane": self.lane.record(), "server": server_snapshot(self.lane), "harness": dict(_git_info(), host=socket.gethostname(), python=platform.python_version()), "args": args or {}, "started_at": time.strftime("%Y-%m-%dT%H:%M:%S"), "ended_at": None, "complete": False, } self._write_run() def _write_run(self): tmp = os.path.join(self.dir, "run.json.tmp") with open(tmp, "w") as f: json.dump(self.run, f, indent=2) os.replace(tmp, os.path.join(self.dir, "run.json")) def add(self, *, item_id, sample_idx=0, category=None, correct=None, score=None, **fields): row = {"run_id": self.run_id, "lane_id": self.lane.lane_id, "instrument": self.instrument, "item_id": item_id, "sample_idx": sample_idx, "category": category, "correct": correct, "score": score, "ts": time.strftime("%Y-%m-%dT%H:%M:%S")} row.update(fields) row.setdefault("status", "ok") row["status"] = effective_status(row) if is_infra(row["status"]) and correct is not None: # An infra failure is never a grade. row["correct"] = None with self._lock: with open(self.items_path, "a") as f: f.write(json.dumps(row, default=str) + "\n") self.n_rows += 1 return row @classmethod def resume(cls, run_dir, *, lane=None): """Reopen an interrupted run to append the attempts it is missing. The lane must match the one the run started with.""" self = cls.__new__(cls) with open(os.path.join(run_dir, "run.json")) as f: self.run = json.load(f) self.lane = lane or lane_mod.current() if self.lane.lane_id != self.run["lane"]["lane_id"]: raise ValueError(f"resume: run is lane {self.run['lane']['lane_id']!r}, " f"active lane is {self.lane.lane_id!r}") self.instrument = self.run["instrument"] self.run_id = self.run["run_id"] self.dir = run_dir self.items_path = os.path.join(run_dir, "items.jsonl") self._lock = threading.Lock() self.n_rows = sum(1 for _ in open(self.items_path)) if os.path.exists(self.items_path) else 0 self.run.setdefault("resumed_at", []).append(time.strftime("%Y-%m-%dT%H:%M:%S")) self._write_run() return self def rows(self): return dedupe(_read(self.items_path)) def done_keys(self): """(item_id, sample_idx) pairs already recorded with a non-infra status — a resumed run skips these and retries everything else.""" return {(r["item_id"], r.get("sample_idx", 0)) for r in self.rows() if not is_infra(r.get("status"))} def sidecar(self, name, obj): """Write a per-item artifact (e.g. an agentic turn log) next to items.jsonl.""" path = os.path.join(self.dir, safe_label(name) + ".json") with open(path, "w") as f: json.dump(obj, f, indent=2, default=str) return os.path.basename(path) def finish(self, summary=None, *, complete=True): if summary is not None: with open(os.path.join(self.dir, "summary.json"), "w") as f: json.dump(summary, f, indent=2, default=str) self.run["ended_at"] = time.strftime("%Y-%m-%dT%H:%M:%S") self.run["complete"] = complete self.run["n_rows"] = self.n_rows self._write_run() return self.dir def _read(items_path): rows = [] if os.path.exists(items_path): with open(items_path) as f: rows = [json.loads(line) for line in f if line.strip()] for r in rows: # rows stored before a status rule existed get it on read r["status"] = effective_status(r) return rows def dedupe(rows): """Keep, per (run_id, item_id, sample_idx), the last non-infra row else the last row.""" best = {} order = [] for r in rows: k = (r.get("run_id"), r.get("item_id"), r.get("sample_idx", 0)) cur = best.get(k) if cur is None: order.append(k) best[k] = r elif not is_infra(r.get("status")) or is_infra(cur.get("status")): best[k] = r return [best[k] for k in order] def load_runs(instruments=None, lanes=None, include_incomplete=False): """[(run_json, rows)] for every run dir under the results root (rows not deduped).""" out = [] for dirpath, _dirs, files in sorted(os.walk(RESULTS_DIR)): if "run.json" not in files or "items.jsonl" not in files: continue with open(os.path.join(dirpath, "run.json")) as f: run = json.load(f) if not include_incomplete and not run.get("complete"): continue if instruments and run.get("instrument") not in instruments: continue if lanes and run["lane"]["lane_id"] not in lanes: continue out.append((dict(run, _dir=dirpath), _read(os.path.join(dirpath, "items.jsonl")))) return out def load_rows(instrument, lane_id): """Deduped rows of every complete run of `instrument` on `lane_id`.""" return [r for _run, rows in load_runs({instrument}, {lane_id}) for r in dedupe(rows)] # ---------------------------------------------------------------- summaries def summarize(rows, extra=None): """Totals + per-category counts over deduped rows. extra = {field: fn(rows of a category)} adds instrument-specific per-category values.""" def counts(rs): graded = [bool(r["correct"]) for r in rs if r.get("correct") is not None] return {"n": len(rs), "graded": len(graded), "correct": sum(graded), "mean_correct": stats.mean(graded), "mean_score": stats.mean(r["score"] for r in rs if r.get("score") is not None), "truncated": sum(r.get("status") == "truncated" for r in rs), "infra": sum(is_infra(r.get("status")) for r in rs)} by = {} for r in rows: by.setdefault(r.get("category"), []).append(r) cats = {c: dict(counts(by[c]), **{k: fn(by[c]) for k, fn in (extra or {}).items()}) for c in sorted(by, key=str)} return dict(counts(rows), by_category=cats) def print_summary(summary, extra=(), log=print): """The per-category table every instrument prints; `extra` names more per-category fields.""" def fmt(v): return "-" if v is None else "%.1f" % v if isinstance(v, float) else str(v) log("\n%-30s %5s %9s %6s %5s %5s" % ("category", "n", "correct", "score", "trunc", "infra") + "".join(" %*s" % (max(8, len(k)), k) for k in extra)) for cat, c in list(summary["by_category"].items()) + [("TOTAL", summary)]: score = "-" if c["mean_score"] is None else "%.3f" % c["mean_score"] log("%-30s %5d %4d/%-4d %6s %5d %5d" % (cat, c["n"], c["correct"], c["graded"], score, c["truncated"], c["infra"]) + "".join(" %*s" % (max(8, len(k)), fmt(c.get(k))) for k in extra)) def print_report(instrument, extra=None): """` report`: the summary over every complete run of the active lane.""" print_summary(summarize(load_rows(instrument, lane_mod.current().lane_id), extra), extra or ()) # ---------------------------------------------------------------- the run driver def add_run_args(p, samples=1, concurrency=1): """The CONTRACT.md `run` flags.""" p.add_argument("--samples", type=int, default=samples) p.add_argument("--concurrency", type=int, default=concurrency) p.add_argument("--items", default="", help="comma-separated item ids") p.add_argument("--resume", default=None, metavar="RUN_DIR") def run_args(ns, **more): """The args a `run` records in run.json (see add_run_args).""" return dict(samples=ns.samples, concurrency=ns.concurrency, items=ns.items, **more) _print_lock = threading.Lock() def call_attempt(store, lane, item_id, sample_idx, category, messages, grade, fields=None, **call_kw): """One model call -> one row. grade(resp) -> row fields (correct, score, ...). A failed call is recorded under its CallError label (any other exception: harness_error, as is a grade() that raises); budget_stop is recorded and re-raised so the run stops.""" row = dict(fields or {}, item_id=item_id, sample_idx=sample_idx, category=category) t0, err = time.time(), None try: resp, dt = client.call_model(messages, item_id=item_id, run_id=store.run_id, lane=lane, **call_kw) row.update(client.meta(resp, dt)) try: row.update(grade(resp)) except Exception as e: # noqa: BLE001 — a grader bug is not a model failure row.update(client.error_meta(e, dt), correct=None) except Exception as e: # noqa: BLE001 — one bad item must not kill the run err = e row.update(client.error_meta(e, time.time() - t0)) row = store.add(**row) with _print_lock: print(" %-24s #%d %-4s %-12s %ss ctok=%s" % ( item_id, sample_idx, {True: "PASS", False: "FAIL"}.get(row["correct"], "-"), row["status"], row.get("wall_s"), row.get("completion_tokens")), flush=True) if isinstance(err, client.CallError) and err.label() == "budget_stop": raise err return row def run_attempts(instrument, args, plan, attempt, *, resume=None, lane=None, extra=None, log=print): """Run every (item, sample) not yet done -> (store, summary). args what the run records in run.json: samples, concurrency, items (ids, list or comma string; None = all) + instrument settings. --resume restores them from run.json (only concurrency follows the command line) and refuses a changed item_set. plan plan(args) -> (item_set, [(item_id, payload), ...]) for the whole set attempt attempt(store, lane, payload, sample_idx) records one row; a client.CallError escaping it (budget_stop) stops the run after the attempts in flight extra per-category summary fields (see summarize) """ lane = lane or lane_mod.current() if not resume and instrument != "conformance": from bench.tasks import conformance # preflight: rule out non-model problems first conformance.require(lane, log) store = RunStore.resume(resume, lane=lane) if resume else None if store and store.instrument != instrument: raise SystemExit(f"resume: {resume} is a {store.instrument!r} run, not {instrument!r}; " "pass a run dir of this instrument.") if store: args = dict(store.run.get("args") or {}, concurrency=args.get("concurrency")) iset, items = plan(args) want = args.get("items") want = set(want.split(",") if isinstance(want, str) else want or ()) - {""} unknown = sorted(want - {iid for iid, _ in items}) if unknown: raise SystemExit(f"unknown item ids {unknown}; pass ids of this instrument's item set.") if store is None: store = RunStore(instrument, item_set=iset, args=args, lane=lane) elif store.run.get("item_set") != iset: raise SystemExit(f"resume: run item_set {store.run.get('item_set')} != current {iset}; " "start a new run instead of mixing definitions.") done = store.done_keys() jobs = [(p, k) for iid, p in items if not want or iid in want for k in range(args.get("samples") or 1) if (iid, k) not in done] conc = max(1, min(args.get("concurrency") or lane.max_concurrency, lane.max_concurrency)) log(f"{instrument}: run {store.run_id} lane={lane.lane_id} item_set={iset} " f"attempts={len(jobs)} (skipping {len(done)} done) concurrency={conc}\n dir: {store.dir}") stop = threading.Event() def work(job): if not stop.is_set(): try: attempt(store, lane, *job) except client.CallError: stop.set() complete = False try: if conc == 1: # in the main thread, so Ctrl-C stops the attempt in flight for job in jobs: work(job) else: with ThreadPoolExecutor(max_workers=conc) as ex: list(ex.map(work, jobs)) complete = not stop.is_set() finally: summary = summarize(store.rows(), extra) summary["stopped"] = "budget_stop" if stop.is_set() else None if complete else "interrupted" store.finish(summary, complete=complete) print_summary(summary, tuple(extra or ()), log) log(f"results: {store.dir}" if complete else f"BUDGET STOP: run incomplete; resume with --resume {store.dir}") return store, summary