Official Codebase of 3DCodeVerse
Python
3dcv bench: a 60-minute 503 storm was reported as model latency
gaoypeng098acba31501
diff --git a/harness/bench/report.py b/harness/bench/report.pyindex dccea21e..5e3f59b7 100644--- a/harness/bench/report.py+++ b/harness/bench/report.py@@ -29,6 +29,8 @@ class GroupStats(BaseModel):group: strn: intn_scored: int+ n_evaluated: int = Field(default=0, description="rows that actually ran (n minus provider outages)")+ infra_failed: int = Field(default=0, description="rows dropped: the provider, not the model, failed")baseline_mean: float | Nonefinal_mean: float | Nonefinal_median: float | None@@ -65,17 +67,25 @@ def _mean(xs: list[float]) -> float | None:def _stats(group: str, rs: list[BenchItemResult]) -> GroupStats:- finals = [r.score_final for r in rs if r.score_final is not None]- bases = [r.score_baseline for r in rs if r.score_baseline is not None]- deltas = [r.score_final - r.score_baseline for r in rs if r.score_final is not None and r.score_baseline is not None]- passed = [r.passed for r in rs if r.passed is not None]+ # A provider outage never tested the model, so it lands in NO rate — the same rule+ # bench/_compare_report.arm_stats has always applied ("an hour spent retrying a 503+ # is not model latency"). final_mean/pass_rate were already safe because an outage+ # has no score; $/run and min/run were not, and one 60-minute storm cell inflated+ # min/run 12.8x. It is also not an `error`: that column must keep meaning "a real+ # crash", or a storm and a bug read the same in the report.+ ev = [r for r in rs if r.status != "infra_failed"]+ finals = [r.score_final for r in ev if r.score_final is not None]+ bases = [r.score_baseline for r in ev if r.score_baseline is not None]+ deltas = [r.score_final - r.score_baseline for r in ev if r.score_final is not None and r.score_baseline is not None]+ passed = [r.passed for r in ev if r.passed is not None]return GroupStats(- group=group, n=len(rs), n_scored=len(finals), baseline_mean=_mean(bases), final_mean=_mean(finals),+ group=group, n=len(rs), n_scored=len(finals), n_evaluated=len(ev), infra_failed=len(rs) - len(ev),+ baseline_mean=_mean(bases), final_mean=_mean(finals),final_median=round(statistics.median(finals), 4) if finals else None, delta_mean=_mean(deltas),pass_rate=round(sum(passed) / len(passed), 4) if passed else None,- cost_mean=round(statistics.fmean([r.cost_usd for r in rs]), 4) if rs else 0.0,- minutes_mean=round(statistics.fmean([r.minutes for r in rs]), 2) if rs else 0.0,- errors=sum(1 for r in rs if r.status in ("error", "failed") or r.errors),+ cost_mean=round(statistics.fmean([r.cost_usd for r in ev]), 4) if ev else 0.0,+ minutes_mean=round(statistics.fmean([r.minutes for r in ev]), 2) if ev else 0.0,+ errors=sum(1 for r in ev if r.status in ("error", "failed") or r.errors),)@@ -92,12 +102,13 @@ def _fmt(v: float | None, spec: str = ".3f") -> str:def _md_table(title: str, stats: list[GroupStats]) -> str:- lines = [f"### {title}", "", "| group | n | scored | baseline | final | median | Δ | pass | $/run | min/run | errors |",- "|---|---|---|---|---|---|---|---|---|---|---|"]+ lines = [f"### {title}", "",+ "| group | n | scored | baseline | final | median | Δ | pass | $/run | min/run | errors | outage |",+ "|---|---|---|---|---|---|---|---|---|---|---|---|"]for s in stats:lines.append(f"| {s.group} | {s.n} | {s.n_scored} | {_fmt(s.baseline_mean)} | {_fmt(s.final_mean)} | "f"{_fmt(s.final_median)} | {_fmt(s.delta_mean, '+.3f')} | {_fmt(s.pass_rate, '.0%')} | "- f"{s.cost_mean:.2f} | {s.minutes_mean:.1f} | {s.errors} |")+ f"{s.cost_mean:.2f} | {s.minutes_mean:.1f} | {s.errors} | {s.infra_failed} |")return "\n".join(lines) + "\n"@@ -154,11 +165,11 @@ def _html_table(stats: list[GroupStats]) -> str:rows = "".join(f"<tr><td>{html.escape(s.group)}</td><td>{s.n}</td><td>{_fmt(s.baseline_mean)}</td><td>{_fmt(s.final_mean)}</td>"f"<td>{_fmt(s.delta_mean, '+.3f')}</td><td>{_fmt(s.pass_rate, '.0%')}</td><td>{s.cost_mean:.2f}</td>"- f"<td>{s.minutes_mean:.1f}</td><td>{s.errors}</td></tr>"+ f"<td>{s.minutes_mean:.1f}</td><td>{s.errors}</td><td>{s.infra_failed}</td></tr>"for s in stats)return ("<table><tr><th>group</th><th>n</th><th>baseline</th><th>final</th><th>Δ</th><th>pass</th><th>$/run</th>"- f"<th>min/run</th><th>errors</th></tr>{rows}</table>")+ f"<th>min/run</th><th>errors</th><th>outage</th></tr>{rows}</table>")def _html_gallery(out: Path, name: str, results: list[BenchItemResult], rep: BenchReport) -> str:diff --git a/harness/bench/run_bench.py b/harness/bench/run_bench.pyindex 8bbe763d..a5ad8be3 100644--- a/harness/bench/run_bench.py+++ b/harness/bench/run_bench.py@@ -32,6 +32,7 @@ from typing import Anyimport yamlfrom pydantic import BaseModel, Field+from bench._infra import is_infra_failurefrom bench._jsonl import read_jsonl, seal_for_appendfrom codeverse._compat import UTCfrom codeverse.config import get_settings@@ -103,6 +104,9 @@ class BenchOptions(BaseModel):ids: list[str] = Field(default_factory=list)tiers: list[str] = Field(default_factory=list)resume: bool = True+ redo_status: list[str] = Field(default_factory=list,+ description="re-run prompts already recorded with one of these statuses "+ "(the point of `infra_failed`: retry what the weather lost)")def build_spec(@@ -190,6 +194,9 @@ def run_battery("started_at": datetime.now(UTC).isoformat()}, indent=2))results_jsonl = out / "results.jsonl"done = _load_done(results_jsonl) if opts.resume else {}+ # `--redo-status infra_failed` re-runs the cells the weather lost, once it clears+ for pid in [k for k, r in done.items() if r.status in set(opts.redo_status)]:+ del done[pid]todo = [p for p in select_prompts(battery, ids=opts.ids, tiers=opts.tiers, limit=opts.limit) if p.id not in done]def _one(item: BenchPrompt) -> BenchItemResult:@@ -205,7 +212,13 @@ def run_battery(with run_ledger(ws.root, run=item.id):rec = run_fn(spec, ws, resume)except Exception as e: # one failing prompt must not kill the battery- return BenchItemResult(id=item.id, tier=item.tier, category=item.category, status="error",+ # A provider outage is not a result: an hour spent retrying a 503 is not model+ # latency and not a crash. compare_backends has classified this since+ # 2026-08-24; this driver never adopted it, so a 60-minute storm cell was+ # averaged into min/run (12.8x inflation, measured) and counted in the same+ # `errors` column as a genuine failure.+ status = "infra_failed" if is_infra_failure(e) else "error"+ return BenchItemResult(id=item.id, tier=item.tier, category=item.category, status=status,errors=f"{type(e).__name__}: {e}\n{traceback.format_exc()[-1500:]}",minutes=round((time.time() - t0) / 60, 2), workspace=str(ws.root),generator=spec.backends.generator, judge=spec.backends.judge)diff --git a/harness/codeverse/cli/bench_cmd.py b/harness/codeverse/cli/bench_cmd.pyindex 255ddb7f..8ce9eab2 100644--- a/harness/codeverse/cli/bench_cmd.py+++ b/harness/codeverse/cli/bench_cmd.py@@ -27,6 +27,8 @@ def run_cmd(ids: Annotated[list[str] | None, typer.Option("--id", help="only these prompt ids")] = None,tiers: Annotated[list[str] | None, typer.Option("--tier")] = None,no_resume: Annotated[bool, typer.Option("--no-resume")] = False,+ redo_status: Annotated[str, typer.Option("--redo-status", help="comma list of recorded statuses to re-run, "+ "e.g. infra_failed once the provider recovers")] = "",report: Annotated[bool, typer.Option("--report/--no-report")] = True,) -> None:"""Run every prompt of a battery through its track (N parallel workers); resumable."""@@ -35,7 +37,8 @@ def run_cmd(b = C.import_bench()run_bench = C.lazy("bench.run_bench")opts = run_bench.BenchOptions(generator=generator, planner=planner, judge=judge, rounds=rounds, max_usd=max_usd,- parallel=parallel, limit=limit, ids=ids or [], tiers=tiers or [], resume=not no_resume)+ parallel=parallel, limit=limit, ids=ids or [], tiers=tiers or [], resume=not no_resume,+ redo_status=[x for x in redo_status.split(",") if x])out_dir = out or (C.REPO_ROOT / "bench" / "out" / battery.stem)console.print(f"battery={battery} out={out_dir} generator={generator or 'default'} judge={judge or 'default'}")diff --git a/harness/tests/compare_bench/test_infra_failures.py b/harness/tests/compare_bench/test_infra_failures.pyindex 243e91c5..0071bb41 100644--- a/harness/tests/compare_bench/test_infra_failures.py+++ b/harness/tests/compare_bench/test_infra_failures.py@@ -94,12 +94,7 @@ def test_both_failure_paths_classify_the_same_way(tmp_path):from codeverse.models.base import ModelErrorfrom tests.compare_bench.conftest import BATTERY, FakeEvaluator- for outage in (- ModelError("Gemini API error 500: An internal error has occurred.", retryable=True, status=500),- ModelError("Gemini transport error: [Errno 104] Connection reset by peer", retryable=True),- ModelError("Anthropic connection error: TLS handshake failed", retryable=True),- ModelError("Gemini request timed out: 600s", retryable=True, status=408),- ):+ def verdicts(outage: Exception, out: Path) -> dict[str, tuple[str, float | None]]:class DeadModel: # the real ApiOneShot around a model that raises the outageprovider, model = "gemini", "gemini-3.7-flash"@@ -116,12 +111,20 @@ def test_both_failure_paths_classify_the_same_way(tmp_path):deps = CompareDeps(FakeEvaluator(), run_track=dying_track,oneshot_backend=lambda t: ApiOneShot("gemini:gemini-3.7-flash", chat_model=DeadModel()))opts = CompareOptions(judge="gemini:x", loop_judge="gemini:x")- out = Path(tempfile.mkdtemp(dir=tmp_path))got = {}for raw in ("harness:api-agent:gemini:gemini-3.7-flash", "oneshot:gemini:gemini-3.7-flash"):arm = parse_arm(raw)r = run_cell(battery, battery.prompts[0], arm, out, opts, deps)got[arm.kind] = (r.status, r.score)+ return got++ for outage in (+ ModelError("Gemini API error 500: An internal error has occurred.", retryable=True, status=500),+ ModelError("Gemini transport error: [Errno 104] Connection reset by peer", retryable=True),+ ModelError("Anthropic connection error: TLS handshake failed", retryable=True),+ ModelError("Gemini request timed out: 600s", retryable=True, status=408),+ ):+ got = verdicts(outage, Path(tempfile.mkdtemp(dir=tmp_path)))assert got["harness"] == ("infra_failed", None), f"{outage} / harness -> {got}"assert got["oneshot"] == got["harness"], (f"one error, two verdicts for {outage!s}: {got} — the one-shot arm takes a hard "diff --git a/harness/tests/flywheel_cli/test_bench.py b/harness/tests/flywheel_cli/test_bench.pyindex d9080014..a38b2ecc 100644--- a/harness/tests/flywheel_cli/test_bench.py+++ b/harness/tests/flywheel_cli/test_bench.py@@ -147,3 +147,58 @@ def test_a_truncated_last_line_does_not_cost_the_whole_resume(tmp_path: Path):assert len(res) == 2# and the already-paid rows remain reportableassert {r.id for r in load_results(out)} == {json.loads(ln)["id"] for ln in good}+++def test_a_provider_outage_is_not_model_latency_and_not_an_error(tmp_path: Path):+ """CQ-4: `3dcv bench` is the third battery driver and it never adopted+ bench/_infra.py. run_bench.py:210 recorded status='error' for ANY escaping+ exception and report.py averaged r.minutes over every row including that one, so a+ single 60-minute 503 storm cell inflated min/run 12.8x (1.0 -> 12.8) and was counted+ in the same `errors` column as a genuine crash. compare_backends has classified+ this since 2026-08-24 and its own test states the invariant in words — "an hour+ spent retrying a 503 is not model latency" — but only for the compare reporter."""+ from bench.report import _stats+ from bench.run_bench import BenchItemResult++ clear = [BenchItemResult(id=f"p{i}", tier="easy", score_baseline=0.5, score_final=0.8,+ passed=True, minutes=1.0, cost_usd=0.10, status="passed") for i in range(4)]+ storm = BenchItemResult(+ id="p_storm", tier="easy", minutes=60.0, cost_usd=0.03, status="infra_failed",+ errors="ModelError: Gemini API error 503: The model is overloaded. Please try again later.")++ base, with_storm = _stats("easy", clear), _stats("easy", clear + [storm])+ assert base.minutes_mean == 1.0 and base.cost_mean == 0.10+ assert with_storm.minutes_mean == 1.0, "someone else's downtime is not this model's latency"+ assert with_storm.cost_mean == 0.10+ # the loss stays visible, in its own column, and is NOT an error+ assert with_storm.n == 5 and with_storm.n_evaluated == 4 and with_storm.infra_failed == 1+ assert with_storm.errors == 0, "a provider outage must not read as a crash"+ # the scored rates were already safe; they must stay so+ assert with_storm.final_mean == base.final_mean and with_storm.pass_rate == base.pass_rate+++def test_the_runner_classifies_the_outage_that_reaches_it(tmp_path: Path):+ """The status has to be recorded in the first place — the reporter can only honour+ what run_battery wrote."""+ from codeverse.models.base import ModelError++ battery = REPO / "bench" / "prompts" / "static_objects_v1.yaml"+ out = tmp_path / "bench_out"++ def storm(spec, ws, resume):+ raise ModelError("Gemini API error 503: The model is overloaded.", retryable=True, status=503)++ res = run_battery(battery, out, BenchOptions(parallel=1, limit=1), run_fn=storm)+ assert [r.status for r in res] == ["infra_failed"]++ # ... and --redo-status makes it actionable, the way compare_backends' already is+ calls: list[str] = []++ def counting(spec, ws, resume):+ calls.append(spec.id)+ return _fake_run_fn({})(spec, ws, resume)++ run_battery(battery, out, BenchOptions(parallel=1, limit=1), run_fn=counting)+ assert calls == [], "a plain resume still skips every recorded row"+ run_battery(battery, out, BenchOptions(parallel=1, limit=1, redo_status=["infra_failed"]), run_fn=counting)+ assert len(calls) == 1, "--redo-status infra_failed re-runs what the weather lost"