Skip to content

Official Codebase of 3DCodeVerse

Python

bench: the outage rule is written once, and the classifier cannot cost a caller its cell

gaoypenga8e7f8bae6c9
diff --git a/harness/bench/_compare_report.py b/harness/bench/_compare_report.py
index 04729b93..8fb1984d 100644
--- a/harness/bench/_compare_report.py
+++ b/harness/bench/_compare_report.py
@@ -80,6 +80,12 @@ class CellResult(BaseModel):
a resume / ``--redo-status`` re-run appends a SECOND row for the same key."""
return (self.prompt_id, self.arm)
+ def note(self, msg: str) -> None:
+ """Append to the error trail. The row is the record of last resort: the failure,
+ classifying it and writing cell.json can each go wrong in one cell, and every one
+ of them has to survive into results.jsonl."""
+ self.error = f"{self.error}; {msg}" if self.error else msg
+
class PairRow(BaseModel):
prompt_id: str
diff --git a/harness/bench/_infra.py b/harness/bench/_infra.py
index 799c501b..abe920a2 100644
--- a/harness/bench/_infra.py
+++ b/harness/bench/_infra.py
@@ -19,6 +19,11 @@ failure — that is a real capability result and keeps its zero.
from __future__ import annotations
+import logging
+from collections.abc import Iterator
+
+log = logging.getLogger(__name__)
+
#: substrings that identify a provider-side outage in a *stringified* error. Kept
#: narrow on purpose: anything matched here is excluded from the comparison, so a
#: loose pattern would hide genuine model failures.
@@ -56,46 +61,60 @@ INFRA_MARKERS: tuple[str, ...] = (
INFRA_STATUSES: frozenset[int] = frozenset({408, 429, 500, 502, 503, 504, 529})
+def _has_marker(text: str) -> bool:
+ return any(marker in text.lower() for marker in INFRA_MARKERS)
+
+
+def _looks_infra(exc: BaseException) -> bool:
+ """The outage rules, applied to ONE exception. Structured first — a ``ModelError`` /
+ ``KeyPoolExhausted`` carries its status, and trusting that beats guessing from prose —
+ with the string markers as the fallback. ONE copy: this ran as two hand-kept copies
+ (head vs each wrapped cause) until 2026-08-28, which is how a rule reaches one path
+ and not the other."""
+ if type(exc).__name__ == "KeyPoolExhausted" or isinstance(exc, TimeoutError):
+ return True
+ status = getattr(exc, "status", None)
+ if isinstance(status, int) and status in INFRA_STATUSES:
+ return True
+ return _has_marker(f"{type(exc).__name__}: {exc}")
+
+
+def _chain(err: BaseException, limit: int = 32) -> Iterator[BaseException]:
+ """``err`` and every exception it was raised from, each yielded once.
+
+ A wrapped cause is common (``raise ModelError(...) from urllib.error.HTTPError``), and
+ retry.py's ``raise err from exc`` can close the chain into a CYCLE — classify() returns
+ an already-classified ModelError unchanged, so ``err is exc`` and ``err.__cause__ is
+ err``. compare_art_v3 (2026-08-27): walking that chain recursively hit RecursionError
+ inside run_cell's except handler, the matrix loop died and 11 finished cells went
+ unrecorded. Hence iterative, seen-set, bounded.
+ """
+ seen: set[int] = set()
+ exc: BaseException | None = err
+ while exc is not None and id(exc) not in seen and len(seen) < limit:
+ seen.add(id(exc))
+ yield exc
+ exc = exc.__cause__ if exc.__cause__ is not None else exc.__context__
+
+
def is_infra_failure(err: object) -> bool:
"""True when ``err`` (an exception or an error string) is a provider outage.
- Structured first — a ``ModelError``/``KeyPoolExhausted`` carries its status, and
- trusting that beats guessing from prose. The string markers are the fallback for
- errors that reach the recorder already stringified.
+ TOTAL by contract: four bench drivers call this from inside an ``except`` handler,
+ where a raise escapes the handler itself and takes the driver's whole result loop
+ with it (compare_art_v3, 2026-08-27). So anything the walk raises — a pathological
+ ``__str__``, a property behind ``.status`` — is logged and answered False.
"""
if err is None:
return False
- if isinstance(err, BaseException):
- if type(err).__name__ == "KeyPoolExhausted":
- return True
- status = getattr(err, "status", None)
- if isinstance(status, int) and status in INFRA_STATUSES:
- return True
- if isinstance(err, TimeoutError):
- return True
- # a wrapped cause is common: `raise ModelError(...) from urllib.error.HTTPError`.
- # Walk the chain ITERATIVELY with a visited set: retry.py's `raise err from exc`
- # can close the chain into a cycle (compare_art_v3, 2026-08-27: a truncated plan's
- # ModelError → RecursionError inside run_cell's except handler → the matrix loop
- # died and 11 finished cells went unrecorded).
- seen: set[int] = {id(err)}
- cause = err.__cause__ if err.__cause__ is not None else err.__context__
- while cause is not None and id(cause) not in seen and len(seen) < 32:
- seen.add(id(cause))
- if isinstance(cause, BaseException):
- if type(cause).__name__ == "KeyPoolExhausted" or isinstance(cause, TimeoutError):
- return True
- status = getattr(cause, "status", None)
- if isinstance(status, int) and status in INFRA_STATUSES:
- return True
- if any(marker in f"{type(cause).__name__}: {cause}".lower() for marker in INFRA_MARKERS):
- return True
- cause = cause.__cause__ if cause.__cause__ is not None else cause.__context__
- else:
- break
- err = f"{type(err).__name__}: {err}"
- text = str(err).lower()
- return any(marker in text for marker in INFRA_MARKERS)
+ try:
+ if isinstance(err, BaseException):
+ return any(_looks_infra(exc) for exc in _chain(err))
+ return _has_marker(str(err))
+ except Exception: # noqa: BLE001 — a classifier bug must not cost the caller its cell
+ log.exception("is_infra_failure could not classify a %s; recording it as a real failure",
+ type(err).__name__)
+ return False
#: a run that hit its wall-clock / dollar ceiling before producing anything. Distinct
diff --git a/harness/bench/compare_backends.py b/harness/bench/compare_backends.py
index 78313e3a..a922213f 100644
--- a/harness/bench/compare_backends.py
+++ b/harness/bench/compare_backends.py
@@ -33,6 +33,7 @@ from __future__ import annotations
import argparse
import json
+import logging
import shutil
import sys
import time
@@ -90,6 +91,8 @@ from codeverse.tracks.generation import MultiFileParseError # noqa: E402
from codeverse.tracks.planner import PlanningError # noqa: E402
from codeverse.workspace import Workspace # noqa: E402
+log = logging.getLogger(__name__)
+
ArmKind = Literal["harness", "oneshot", "oneshot+repair"]
@@ -255,12 +258,18 @@ def _run_harness(spec: Spec, cell: Path, eval_ws: Workspace, deps: CompareDeps,
shutil.copytree(run_ws.src, eval_ws.src, dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
-def run_cell(battery: Battery, item: BenchPrompt, arm: Arm, out: Path, opts: CompareOptions, deps: CompareDeps) -> CellResult:
+def _new_cell(item: BenchPrompt, arm: Arm, out: Path, opts: CompareOptions) -> tuple[Path, CellResult]:
+ """The cell's directory and its identity row. ONE place knows what identifies a row,
+ so run_matrix's synthesized last-resort row is shaped like every real one."""
cell = out / "cells" / item.id / arm.slug
+ return cell, CellResult(prompt_id=item.id, tier=item.tier, arm=arm.raw, kind=arm.kind,
+ target=arm.target, judge=opts.judge, workspace=str(cell))
+
+
+def run_cell(battery: Battery, item: BenchPrompt, arm: Arm, out: Path, opts: CompareOptions, deps: CompareDeps) -> CellResult:
+ cell, res = _new_cell(item, arm, out, opts)
cell.mkdir(parents=True, exist_ok=True)
spec = spec_for(battery, item, arm, opts)
- res = CellResult(prompt_id=item.id, tier=item.tier, arm=arm.raw, kind=arm.kind, target=arm.target,
- judge=opts.judge, workspace=str(cell))
t0 = time.time()
eval_ws = _fresh_ws(cell / "eval")
eval_ws.write_json(eval_ws.spec_path, spec)
@@ -302,19 +311,17 @@ def run_cell(battery: Battery, item: BenchPrompt, arm: Arm, out: Path, opts: Com
res.status, res.score, res.passed, res.build_ok = "no_code", 0.0, False, False
res.error = f"PlanningError: {e}"
except Exception as e: # noqa: BLE001 — one cell must never kill the matrix
- try:
- infra = is_infra_failure(e)
- except Exception as classify_error: # noqa: BLE001 — a classifier bug is not a reason to lose the cell
- infra = False
- res.error = (res.error + "; " if res.error else "") + f"[classifier failed: {type(classify_error).__name__}] "
- res.status = "infra_failed" if infra else "error" # same rule as the no-code path
- res.error = (res.error + "; " if res.error else "") + f"{type(e).__name__}: {e}\n{traceback.format_exc()[-1200:]}"
+ # is_infra_failure is total (bench/_infra.py): a classifier bug answers False and
+ # logs, it does not raise out of this handler and take the matrix loop with it.
+ res.status = "infra_failed" if is_infra_failure(e) else "error" # same rule as the no-code path
+ res.note(f"{type(e).__name__}: {e}\n{traceback.format_exc()[-1200:]}")
res.wall_s = round(time.time() - t0, 1)
try:
flag_degraded(res, opts)
eval_ws.write_json(cell / "cell.json", res)
except Exception as e: # noqa: BLE001 — the row is the record of last resort
- res.error = (res.error + "; " if res.error else "") + f"[cell.json not written: {type(e).__name__}: {e}]"
+ log.exception("cell.json not written for %s", res.workspace)
+ res.note(f"[cell.json not written: {type(e).__name__}: {e}]")
return res
@@ -348,12 +355,12 @@ def _fill_from_outcome(res: CellResult, o: EvalOutcome) -> None:
res.glb = o.build.glb_path or ""
if not o.build.ok:
res.status, res.score, res.passed = "build_failed", 0.0, False
- res.error = (res.error + "; " if res.error else "") + f"{o.build.error_type}: {o.build.error_message[:400]}"
+ res.note(f"{o.build.error_type}: {o.build.error_message[:400]}")
return
j = o.judgment
if j is None or j.n_samples == 0:
res.status, res.score, res.passed = "judge_error", None, None
- res.error = (res.error + "; " if res.error else "") + (o.error or (j.summary if j else "no judgment"))[:400]
+ res.note((o.error or (j.summary if j else "no judgment"))[:400])
return
res.judge_cost_usd = j.usage.cost_usd
res.score, res.passed, res.score_std, res.status = j.overall, j.passed, j.score_std, "scored"
@@ -435,8 +442,10 @@ def run_matrix(battery_path: Path | str, out_dir: Path | str, arms: Sequence[Arm
r = fut.result()
except Exception as e: # noqa: BLE001 — run_cell must not raise; if it does, record the cell, keep the matrix
p, a = futs[fut]
- r = CellResult(prompt_id=p.id, tier=p.tier, arm=a.raw, kind=a.kind, target=a.target, judge=opts.judge,
- status="error", error=f"run_cell raised {type(e).__name__}: {e}"[:800])
+ log.exception("run_cell raised for %s / %s", p.id, a.raw)
+ _, r = _new_cell(p, a, out, opts)
+ r.status = "error"
+ r.note(f"run_cell raised {type(e).__name__}: {e}"[:800])
done[(r.prompt_id, r.arm)] = r
fh.write(r.model_dump_json() + "\n")
fh.flush()
diff --git a/harness/tests/compare_bench/test_infra_failures.py b/harness/tests/compare_bench/test_infra_failures.py
index 4219a059..ded3be79 100644
--- a/harness/tests/compare_bench/test_infra_failures.py
+++ b/harness/tests/compare_bench/test_infra_failures.py
@@ -8,6 +8,8 @@ downtime pushed one-shot means down while leaving harness means untouched.
from __future__ import annotations
+from pathlib import Path
+
import pytest
from bench._compare_report import CellResult, arm_stats
@@ -42,12 +44,22 @@ def test_model_failures_are_not_infra(err):
assert is_infra_failure(err) is False
-def test_structured_exceptions_beat_string_matching():
- class ModelError(Exception):
- def __init__(self, msg, status):
- super().__init__(msg)
- self.status = status
+class ModelError(Exception):
+ """Stands in for codeverse.models.base.ModelError: the .status the classifier reads."""
+ def __init__(self, msg, status=None):
+ super().__init__(msg)
+ self.status = status
+
+
+class ClassifierTrap(Exception):
+ """.status is the first thing is_infra_failure reads — a property that raises is the
+ cheapest stand-in for any classifier bug, and getattr's default does not swallow it."""
+ @property
+ def status(self):
+ raise RecursionError("cycle")
+
+def test_structured_exceptions_beat_string_matching():
# no recognisable prose at all — only the status says what happened
assert is_infra_failure(ModelError("upstream said no", status=503)) is True
assert is_infra_failure(ModelError("bad request: prompt too long", status=400)) is False
@@ -293,14 +305,15 @@ def test_a_cyclic_cause_chain_does_not_recurse():
"""compare_art_v3 (2026-08-27): retry.py's `raise err from exc` closed the __cause__ chain
into a cycle; is_infra_failure recursed to RecursionError inside run_cell's except
handler, the matrix loop died, and 11 finished cells went unrecorded."""
- class ModelError(Exception):
- def __init__(self, msg, status=None):
- super().__init__(msg)
- self.status = status
+ # the shape production actually makes: classify() returns an already-classified
+ # ModelError unchanged, so retry.py's `raise err from exc` is `raise e from e`
+ self_loop = ModelError("structured output unavailable (finish_reason=MAX_TOKENS)")
+ self_loop.__cause__ = self_loop
+ assert is_infra_failure(self_loop) is False
a = ModelError("structured output unavailable (finish_reason=MAX_TOKENS)")
b = ModelError("attempt failed")
- a.__cause__, b.__cause__ = b, a # the cycle
+ a.__cause__, b.__cause__ = b, a # a two-node cycle
assert is_infra_failure(a) is False
c = ModelError("wrapped")
c.__cause__ = ModelError("upstream said no", status=503)
@@ -308,18 +321,24 @@ def test_a_cyclic_cause_chain_does_not_recurse():
assert is_infra_failure(c) is True
-def test_a_classifier_crash_still_records_the_cell(tmp_path, monkeypatch):
+def test_the_classifier_is_total_so_a_caller_never_loses_its_cell():
+ """is_infra_failure runs inside four drivers' `except` handlers, where a raise escapes
+ the handler itself. A bug in it answers False; it does not propagate."""
+ assert is_infra_failure(ClassifierTrap("boom")) is False
+
+
+def test_a_classifier_crash_still_records_the_cell(tmp_path):
+ """End to end: a failure whose classification blows up is still a row on disk."""
from bench import compare_backends as cb
from bench.run_bench import Battery
from tests.compare_bench.conftest import BATTERY, FakeEvaluator
def boom(spec, ws, resume):
- raise RuntimeError("planner died")
+ raise ClassifierTrap("planner died")
- monkeypatch.setattr(cb, "is_infra_failure", lambda e: (_ for _ in ()).throw(RecursionError("cycle")))
battery = Battery.load(BATTERY)
- r = cb.run_cell(battery, battery.prompts[0], cb.parse_arm("harness:api-agent:gemini:gemini-3.7-flash"), tmp_path,
+ r = cb.run_cell(battery, battery.prompts[0], cb.parse_arm("harness:gemini-cli:gemini-3.6-flash"), tmp_path,
cb.CompareOptions(judge="gemini:x", loop_judge="gemini:x"), cb.CompareDeps(FakeEvaluator(), run_track=boom))
- assert r.status == "error" and "classifier failed: RecursionError" in r.error and "planner died" in r.error
- assert (tmp_path / "cells" / battery.prompts[0].id / "harness_api-agent_gemini_gemini-3.7-flash" / "cell.json").is_file()
+ assert r.status == "error" and "planner died" in r.error
+ assert (Path(r.workspace) / "cell.json").is_file()
diff --git a/harness/tests/cost/test_profiles.py b/harness/tests/cost/test_profiles.py
index c5f84cc7..53d3b13a 100644
--- a/harness/tests/cost/test_profiles.py
+++ b/harness/tests/cost/test_profiles.py
@@ -152,9 +152,9 @@ def test_profile_table_and_cli():
def test_make_profile_writes_the_whole_shape_onto_the_spec(tmp_path: Path):
runs = tmp_path / "runs"
- r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", "--profile", "quality"])
+ r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", "--profile", "quality", "--slug", "pot"])
assert r.exit_code == 0, r.output
- spec = json.loads(next(p for p in sorted(runs.iterdir()) if not p.name.startswith(".")).joinpath("spec.json").read_text())
+ spec = json.loads((runs / "pot" / "spec.json").read_text())
assert spec["options"] == {"candidates": 2, "texture": True, "profile": "quality"}
assert spec["budget"]["max_rounds"] == 4 and spec["budget"]["max_usd"] == 8.0
assert spec["backends"]["judge"] == "gemini:gemini-3.1-pro-preview"
@@ -162,11 +162,11 @@ def test_make_profile_writes_the_whole_shape_onto_the_spec(tmp_path: Path):
def test_an_explicit_flag_beats_the_profile(tmp_path: Path):
runs = tmp_path / "runs"
- r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run",
+ r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", "--slug", "pot",
"--profile", "economy", "--rounds", "4", "--max-usd", "9",
"--generator", "gemini-cli:gemini-3.6-flash"])
assert r.exit_code == 0, r.output
- spec = json.loads(next(p for p in sorted(runs.iterdir()) if not p.name.startswith(".")).joinpath("spec.json").read_text())
+ spec = json.loads((runs / "pot" / "spec.json").read_text())
assert spec["budget"]["max_rounds"] == 4 and spec["budget"]["max_usd"] == 9.0
assert spec["backends"]["generator"] == "gemini-cli:gemini-3.6-flash"
assert spec["backends"]["judge"] == "gemini:gemini-3.7-flash" # unstated → still the profile's
@@ -174,9 +174,9 @@ def test_an_explicit_flag_beats_the_profile(tmp_path: Path):
def test_no_profile_flag_leaves_the_defaults_alone(tmp_path: Path):
runs = tmp_path / "runs"
- r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run"])
+ r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", "--slug", "pot"])
assert r.exit_code == 0, r.output
- spec = json.loads(next(p for p in sorted(runs.iterdir()) if not p.name.startswith(".")).joinpath("spec.json").read_text())
+ spec = json.loads((runs / "pot" / "spec.json").read_text())
# the resolved dial is recorded whichever way it was named, so `3dcv resume`
# reproduces it; with no flag and no env that dial is the default, balanced
assert spec["options"]["profile"] == "balanced" and spec["options"]["texture"] is False
@@ -264,9 +264,9 @@ def test_the_env_var_reaches_the_spec_a_make_writes(name, tmp_path: Path, monkey
monkeypatch.setenv("CV3D_PROFILE", name)
get_settings.cache_clear()
runs = tmp_path / "runs"
- r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run"])
+ r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", "--slug", "pot"])
assert r.exit_code == 0, r.output
- spec = json.loads(next(p for p in sorted(runs.iterdir()) if not p.name.startswith(".")).joinpath("spec.json").read_text())
+ spec = json.loads((runs / "pot" / "spec.json").read_text())
assert spec["options"] == {"candidates": p.candidates, "texture": p.texture, "profile": name}
assert spec["budget"]["max_rounds"] == p.rounds and spec["budget"]["max_usd"] == p.max_usd
assert spec["backends"]["judge"] == p.judge and spec["backends"]["generator"] == p.generator
diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.py
index edc488f8..19dbf339 100644
--- a/harness/tests/flywheel_cli/test_cli.py
+++ b/harness/tests/flywheel_cli/test_cli.py
@@ -23,7 +23,7 @@ def made_run(tmp_path: Path):
runs = tmp_path / "runs"
r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", *extra])
assert r.exit_code == 0, r.output
- return runs, next(d for d in runs.iterdir() if d.is_dir())
+ return runs, next(d for d in runs.iterdir() if d.is_dir() and not d.name.startswith("."))
return make
@@ -242,7 +242,7 @@ def test_make_texture_flag_sets_spec_options(tmp_path: Path):
runs = tmp_path / "runs"
r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", "--texture", "--candidates", "3"])
assert r.exit_code == 0, r.output
- ws = next(d for d in runs.iterdir() if d.is_dir())
+ ws = next(d for d in runs.iterdir() if d.is_dir() and not d.name.startswith("."))
spec = Spec.model_validate_json((ws / "spec.json").read_text())
# run-shape options are frozen on the spec (no more magic 'texture' tag)
assert spec.options.texture is True and spec.options.candidates == 3
@@ -253,7 +253,7 @@ def test_make_language_defaults_to_the_tracks_first(tmp_path: Path):
runs = tmp_path / "runs"
r = runner.invoke(app, ["make", "a harbour at night", "--track", "scene", "--runs-dir", str(runs), "--no-run"])
assert r.exit_code == 0, r.output
- ws = next(d for d in runs.iterdir() if d.is_dir())
+ ws = next(d for d in runs.iterdir() if d.is_dir() and not d.name.startswith("."))
spec = Spec.model_validate_json((ws / "spec.json").read_text())
assert spec.language.value == "scene_threejs"