Skip to content

Official Codebase of 3DCodeVerse

Python

bench integrity: a provider outage is not a model failure — and it was being scored as one, asymmetrically

gaoypeng0c9fe4e385f1
diff --git a/harness/bench/_compare_report.py b/harness/bench/_compare_report.py
index db6f0f35..d9383c26 100644
--- a/harness/bench/_compare_report.py
+++ b/harness/bench/_compare_report.py
@@ -27,7 +27,9 @@ class CellResult(BaseModel):
kind: str
target: str = ""
judge: str = ""
- status: str = Field(default="", description="scored | build_failed | no_code | judge_error | error")
+ status: str = Field(default="",
+ description="scored | build_failed | no_code | judge_error | error | infra_failed "
+ "(provider outage: excluded from every rate, see bench/_infra.py)")
score: float | None = Field(default=None, description="fixed-judge overall (0 when the build failed)")
score_std: float = 0.0
passed: bool | None = None
@@ -78,7 +80,10 @@ def load_jsonl(path: Path, model: type[T]) -> list[T]:
class ArmStats(BaseModel):
arm: str
kind: str
- n: int
+ n: int = Field(description="cells attempted")
+ n_evaluated: int = Field(default=0, description="cells that actually ran (n minus provider outages)")
+ infra_failed: int = Field(default=0, description="cells dropped: the provider, not the model, failed")
+ budget_exhausted: int = Field(default=0, description="cells that ran out of time/money with no artifact")
mean_score: float | None
median_score: float | None
pass_rate: float | None
@@ -111,17 +116,22 @@ def arm_stats(rows: list[CellResult]) -> list[ArmStats]:
by_arm.setdefault(r.arm, []).append(r)
out = []
for arm, rs in by_arm.items():
- scores = [r.score for r in rs if r.score is not None]
- passed = [r.passed for r in rs if r.passed is not None]
+ # a provider outage never tested the model: it must not land in ANY rate, or
+ # an arm unlucky with the weather looks worse than one that ran in the clear
+ ev = [r for r in rs if r.status != "infra_failed"]
+ scores = [r.score for r in ev if r.score is not None]
+ passed = [r.passed for r in ev if r.passed is not None]
out.append(ArmStats(
- arm=arm, kind=rs[0].kind, n=len(rs), mean_score=_mean(scores),
+ arm=arm, kind=rs[0].kind, n=len(rs), n_evaluated=len(ev),
+ infra_failed=len(rs) - len(ev),
+ budget_exhausted=sum(1 for r in ev if r.status == "budget_exhausted"), mean_score=_mean(scores),
median_score=round(statistics.median(scores), 4) if scores else None,
pass_rate=round(sum(passed) / len(passed), 4) if passed else None,
- build_ok_rate=round(sum(r.build_ok for r in rs) / len(rs), 4),
- mean_gen_usd=round(statistics.fmean(r.gen_cost_usd for r in rs), 4),
- mean_judge_usd=round(statistics.fmean(r.judge_cost_usd for r in rs), 4),
- mean_minutes=round(statistics.fmean(r.wall_s for r in rs) / 60, 2),
- tool_calls=sum(r.tool_calls for r in rs), errors=sum(1 for r in rs if r.status in ("error", "judge_error")),
+ build_ok_rate=round(sum(r.build_ok for r in ev) / len(ev), 4) if ev else 0.0,
+ mean_gen_usd=round(statistics.fmean(r.gen_cost_usd for r in ev), 4) if ev else 0.0,
+ mean_judge_usd=round(statistics.fmean(r.judge_cost_usd for r in ev), 4) if ev else 0.0,
+ mean_minutes=round(statistics.fmean(r.wall_s for r in ev) / 60, 2) if ev else 0.0,
+ tool_calls=sum(r.tool_calls for r in ev), errors=sum(1 for r in rs if r.status in ("error", "judge_error")),
))
return sorted(out, key=lambda s: (s.kind != "harness", -(s.mean_score or -1)))
@@ -178,11 +188,14 @@ def compare_markdown(out: Path, rows: list[CellResult], pairs: list[PairRow], me
f"harness rounds ≤ {opts.get('rounds', '?')}, ≤ ${opts.get('max_usd', '?')} · cells: {len(rows)}", "",
"Every arm's final `src/model.py` is re-built, re-rendered and judged by the same evaluator; a failed "
"build scores 0. `$gen` for harness arms is the whole run (planner + generator + its loop judge); for "
- "one-shot arms it is the single call (subscription CLIs report 0 unless the CLI returns a cost).", "",
- "## arms", "", "| arm | kind | n | mean | median | pass | build ok | $gen | $judge | min | tool calls | errors |",
- "|---|---|---|---|---|---|---|---|---|---|---|---|"]
+ "one-shot arms it is the single call (subscription CLIs report 0 unless the CLI returns a cost). "
+ "`n` counts cells that actually ran; `dropped` counts cells lost to a provider outage "
+ "(503 storm, timeout, exhausted pool) — those test nothing about the model and are excluded "
+ "from every rate on this page rather than scored 0.", "",
+ "## arms", "", "| arm | kind | n | dropped | over budget | mean | median | pass | build ok | $gen | $judge | min | tool calls | errors |",
+ "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
for s in arm_stats(rows):
- md.append(f"| {s.arm} | {s.kind} | {s.n} | {_f(s.mean_score)} | {_f(s.median_score)} | {_f(s.pass_rate, '.0%')} | "
+ md.append(f"| {s.arm} | {s.kind} | {s.n_evaluated} | {s.infra_failed or ''} | {s.budget_exhausted or ''} | {_f(s.mean_score)} | {_f(s.median_score)} | {_f(s.pass_rate, '.0%')} | "
f"{s.build_ok_rate:.0%} | {s.mean_gen_usd:.2f} | {s.mean_judge_usd:.3f} | {s.mean_minutes:.1f} | "
f"{s.tool_calls} | {s.errors} |")
md += ["", "## per prompt (score, ✓ = passed, ✗build = build failed)", "",
diff --git a/harness/bench/_infra.py b/harness/bench/_infra.py
new file mode 100644
index 00000000..2853ee00
--- /dev/null
+++ b/harness/bench/_infra.py
@@ -0,0 +1,93 @@
+"""Did the *provider* fail, or did the *model* fail?
+
+A capacity storm (503/529), a read timeout, or an exhausted key pool says nothing
+about the model under test: the cell was never really attempted, so it must be
+DROPPED from the comparison rather than scored 0.
+
+Getting this wrong is not a rounding error. ``compare_backends`` has two failure
+paths — a one-shot arm that produced no code, and an exception escaping a harness
+arm — and until 2026-08-24 they recorded *the same outage* as ``score=0.0``
+(counted in the mean) for the one-shot arm and ``score=None`` (dropped) for the
+harness arm. During the multi-hour gemini-3.7-flash outage of that morning, six
+one-shot cells took hard zeros while the harness cells hit by the identical 503
+were quietly excluded, biasing every harness-vs-one-shot mean in the harness's
+favour. Both paths now classify through here.
+
+A model that answers with prose, or with code that will not parse, is NOT an infra
+failure — that is a real capability result and keeps its zero.
+"""
+
+from __future__ import annotations
+
+#: 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.
+INFRA_MARKERS: tuple[str, ...] = (
+ "currently experiencing high demand",
+ "is overloaded",
+ "service unavailable",
+ "internal server error",
+ "request timed out",
+ "read operation timed out",
+ "deadline exceeded",
+ "connection reset",
+ "connection aborted",
+ "remote end closed connection",
+ "keypoolexhausted",
+ "resource has been exhausted",
+ "quota exceeded",
+ "capacity storm",
+)
+
+#: HTTP statuses that mean "the provider could not serve this", not "the model was bad".
+INFRA_STATUSES: frozenset[int] = frozenset({429, 500, 502, 503, 504, 529})
+
+
+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.
+ """
+ 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`
+ if err.__cause__ is not None and is_infra_failure(err.__cause__):
+ return True
+ err = f"{type(err).__name__}: {err}"
+ text = str(err).lower()
+ return any(marker in text for marker in INFRA_MARKERS)
+
+
+#: a run that hit its wall-clock / dollar ceiling before producing anything. Distinct
+#: from an outage: we DID ask the model, it just never delivered inside the budget.
+BUDGET_MARKERS: tuple[str, ...] = (
+ "exceeds max_minutes",
+ "exceeds max_usd",
+ "budget exhausted",
+ "wall-clock ceiling",
+)
+
+
+def is_budget_exhaustion(err: object, *, rounds: int = 0) -> bool:
+ """True when the cell ran out of time/money with no artifact to show.
+
+ Scoring these 0 is wrong for the same reason an outage is — no artifact was ever
+ judged — but they are NOT excused the way an outage is: the arm still failed to
+ deliver, so ``build_ok`` counts the miss and the report gives them their own
+ column. (Observed 2026-08-24: a harness cell spent 50 min losing to a 503 storm,
+ produced $0.03 of tokens and zero rounds, and was recorded as a hard 0.0.)
+ """
+ if rounds > 0:
+ return False
+ text = str(err or "").lower()
+ return any(marker in text for marker in BUDGET_MARKERS)
diff --git a/harness/bench/compare_backends.py b/harness/bench/compare_backends.py
index a5adde58..f43dfbf0 100644
--- a/harness/bench/compare_backends.py
+++ b/harness/bench/compare_backends.py
@@ -3,7 +3,7 @@
python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml \\
--arms harness:api-agent:gemini:gemini-3.7-flash,harness:gemini-cli:gemini-3.7-flash,\\
oneshot:claude-code,oneshot:codex,oneshot:gemini:gemini-3.7-flash \\
- --judge gemini:gemini-3.1-pro-preview --out <dir> [--parallel 3] [--limit N]
+ --judge gemini:gemini-3.1-pro-preview --out <dir> [--parallel 8] [--limit N]
Arms
* ``harness:<generator-id>`` — the full static_object track (plan → generate →
@@ -58,6 +58,7 @@ from bench._compare_report import ( # noqa: E402
load_jsonl,
)
from bench._fixed_eval import RUBRIC, EvalOutcome, FixedEvaluator # noqa: E402
+from bench._infra import is_budget_exhaustion, is_infra_failure # noqa: E402
from bench._oneshot import ( # noqa: E402
MODEL_FILE,
OneShotBackend,
@@ -121,7 +122,7 @@ class CompareOptions(BaseModel):
rounds: int = 3
max_usd: float = 2.5
max_minutes: float = 45.0
- parallel: int = 3
+ parallel: int = 8 # measured knee, see BenchOptions.parallel / docs/COST.md Part III
limit: int | None = None
ids: list[str] = Field(default_factory=list)
tiers: list[str] = Field(default_factory=list)
@@ -248,10 +249,18 @@ def run_cell(battery: Battery, item: BenchPrompt, arm: Arm, out: Path, opts: Com
outcome = deps.evaluator.evaluate(eval_ws, spec)
eval_ws.write_json(eval_ws.root / "eval.json", outcome)
_fill_from_outcome(res, outcome)
+ elif is_budget_exhaustion(res.error, rounds=res.harness_rounds):
+ # nothing was ever built, so there is no score to average — but the arm
+ # DID fail to deliver, so this still counts against its build rate
+ res.status, res.score, res.passed, res.build_ok = "budget_exhausted", None, False, False
+ elif is_infra_failure(res.error):
+ # a provider outage is not a capability result: drop the cell (score
+ # None) instead of scoring the model 0 for someone else's downtime
+ res.status, res.score, res.passed, res.build_ok = "infra_failed", None, None, False
else:
res.status, res.score, res.passed, res.build_ok = "no_code", 0.0, False, False
except Exception as e: # noqa: BLE001 — one cell must never kill the matrix
- res.status = "error"
+ res.status = "infra_failed" if is_infra_failure(e) 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:]}"
res.wall_s = round(time.time() - t0, 1)
eval_ws.write_json(cell / "cell.json", res)
@@ -362,23 +371,57 @@ def run_matrix(battery_path: Path | str, out_dir: Path | str, arms: Sequence[Arm
# ----------------------------------------------------------------------------- CLI
+def _preflight(judge: str, arms: Sequence[Arm], *, wait_minutes: float = 0.0) -> bool:
+ """Refuse to start a battery against a model that is not serving.
+
+ A dead provider does not fail fast on its own: every cell burns its full retry
+ budget first. On 2026-08-24 that cost ~9 hours of wall clock and a contaminated
+ battery. One 20-second probe per model is the whole cure.
+ """
+ from codeverse.models.health import probe
+
+ models = {judge, *(a.target for a in arms if a.target.startswith(("gemini:", "anthropic:", "openai:")))}
+ models |= {a.target.split(":", 1)[1] for a in arms if a.target.startswith("api-agent:")}
+ deadline = time.time() + wait_minutes * 60
+ while True:
+ sick = [h for h in (probe(m) for m in sorted(models)) if not h.ok]
+ if not sick:
+ return True
+ for h in sick:
+ print(f"preflight: {h}", flush=True)
+ if time.time() >= deadline:
+ print("\nrefusing to start: the cells would spend their whole retry budget losing to this.\n"
+ " wait for it: --wait-for-provider 60\n"
+ " start anyway: --no-preflight", flush=True)
+ return False
+ print(f"preflight: parking 120 s (up to {wait_minutes:.0f} min) for the provider…", flush=True)
+ time.sleep(120)
+
+
def main(argv: Sequence[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--prompts", required=True)
ap.add_argument("--arms", required=True, help="comma-separated arm ids")
ap.add_argument("--judge", default="gemini:gemini-3.1-pro-preview", help="FIXED judge model id")
ap.add_argument("--out", required=True)
- ap.add_argument("--parallel", type=int, default=3)
+ ap.add_argument("--parallel", type=int, default=8)
ap.add_argument("--limit", type=int, default=None)
ap.add_argument("--ids", default="", help="comma-separated prompt ids")
ap.add_argument("--tiers", default="", help="comma-separated tiers (easy,medium,hard)")
ap.add_argument("--rounds", type=int, default=3)
ap.add_argument("--max-usd", type=float, default=2.5)
+ ap.add_argument("--max-minutes", type=float, default=45.0, help="wall-clock ceiling for ONE harness run")
ap.add_argument("--loop-judge", default=None, help="harness in-loop judge (default: settings default)")
ap.add_argument("--repair-attempts", type=int, default=2)
ap.add_argument("--gen-timeout", type=float, default=900.0)
ap.add_argument("--no-pairwise", action="store_true")
- ap.add_argument("--redo-status", default="", help="comma list of statuses to re-run (error,no_code,build_failed,judge_error); "
+ ap.add_argument("--no-preflight", action="store_true",
+ help="skip the provider health check (see --wait-for-provider)")
+ ap.add_argument("--wait-for-provider", type=float, default=0.0, metavar="MIN",
+ help="if the preflight fails, park up to MIN minutes for the provider to recover "
+ "instead of refusing to start")
+ ap.add_argument("--redo-status", default="", help="comma list of statuses to re-run "
+ "(error,no_code,build_failed,judge_error,infra_failed); "
"recorded one-shot answers are re-used, not re-generated")
ap.add_argument("--no-resume", action="store_true")
ap.add_argument("--report-only", action="store_true", help="only rebuild report.md/html from results")
@@ -386,12 +429,15 @@ def main(argv: Sequence[str] | None = None) -> int:
if ns.report_only:
build_compare_report(Path(ns.out))
return 0
- opts = CompareOptions(judge=ns.judge, loop_judge=ns.loop_judge, rounds=ns.rounds, max_usd=ns.max_usd, parallel=ns.parallel,
+ opts = CompareOptions(judge=ns.judge, loop_judge=ns.loop_judge, rounds=ns.rounds, max_usd=ns.max_usd,
+ max_minutes=ns.max_minutes, parallel=ns.parallel,
limit=ns.limit, ids=[i for i in ns.ids.split(",") if i],
tiers=[t for t in ns.tiers.split(",") if t], resume=not ns.no_resume,
gen_timeout_s=ns.gen_timeout, repair_attempts=ns.repair_attempts, pairwise=not ns.no_pairwise,
redo_status=[x for x in ns.redo_status.split(",") if x])
arms = parse_arms(ns.arms)
+ if not ns.no_preflight and not _preflight(opts.judge, arms, wait_minutes=ns.wait_for_provider):
+ return 2
deps = CompareDeps(FixedEvaluator(opts.judge, n_samples=opts.n_samples))
def _log(r: CellResult) -> None:
@@ -400,6 +446,13 @@ def main(argv: Sequence[str] | None = None) -> int:
run_matrix(ns.prompts, ns.out, arms, opts, deps, on_result=_log)
print(f"report: {Path(ns.out) / 'report.md'}")
+ dropped = [r for r in load_jsonl(Path(ns.out) / "results.jsonl", CellResult) if r.status == "infra_failed"]
+ if dropped:
+ # never let downtime pass as a result: say what was lost and how to get it back
+ print(f"\n{len(dropped)} cell(s) lost to provider outages and EXCLUDED from every rate: "
+ + ", ".join(sorted({f"{r.prompt_id}/{r.arm}" for r in dropped})[:6])
+ + (" ..." if len(dropped) > 6 else "")
+ + "\nre-run them once the provider recovers with: --redo-status infra_failed")
return 0
diff --git a/harness/codeverse/models/health.py b/harness/codeverse/models/health.py
new file mode 100644
index 00000000..7bb943c4
--- /dev/null
+++ b/harness/codeverse/models/health.py
@@ -0,0 +1,79 @@
+"""Is a model actually serving right now?
+
+A batch job is the worst place to discover a provider outage. On 2026-08-24 a
+``gemini-3.7-flash`` capacity storm ran for hours; eight bench cells were launched
+into it and each spent 56-87 minutes losing to 503s before recording a failure, and
+the judge model went down with it. The provider was unreachable within seconds of
+the first call — the cost was entirely in not asking.
+
+``probe`` asks once per key, cheaply and in parallel, with a short timeout and no
+retries: the point is a fast verdict, not a successful call. Callers use it as a
+preflight gate before spending real money.
+"""
+
+from __future__ import annotations
+
+import concurrent.futures as cf
+import logging
+from dataclasses import dataclass
+
+log = logging.getLogger(__name__)
+
+#: enough of the pool to tell an outage from one unlucky key, without a long probe
+DEFAULT_SAMPLE = 4
+#: a healthy model answers a 5-token prompt well inside this
+DEFAULT_TIMEOUT_S = 20.0
+#: below this share of answering keys, treat the model as down
+DEFAULT_MIN_OK = 0.5
+
+
+@dataclass(frozen=True)
+class Health:
+ model: str
+ n_ok: int
+ n_tried: int
+ reasons: tuple[str, ...] = ()
+
+ @property
+ def ok(self) -> bool:
+ return self.n_tried > 0 and self.n_ok / self.n_tried >= DEFAULT_MIN_OK
+
+ def __str__(self) -> str:
+ head = f"{self.model}: {self.n_ok}/{self.n_tried} keys answering"
+ return head if self.ok else f"{head} — {'; '.join(self.reasons[:2]) or 'no reason reported'}"
+
+
+def probe(model: str = "gemini:gemini-3.7-flash", *, sample: int = DEFAULT_SAMPLE,
+ timeout_s: float = DEFAULT_TIMEOUT_S) -> Health:
+ """One tiny call per sampled key, in parallel, no retries. Never raises."""
+ from codeverse.contracts.chat import ChatMessage, ChatRequest
+
+ def one(_: int) -> str | None:
+ try:
+ # built directly, not via get_chat_model: a probe must NOT retry or back off
+ m = _bare_model(model, timeout_s)
+ m.generate(ChatRequest(messages=[ChatMessage.user("Reply with the single word: pong")],
+ temperature=0.0, max_output_tokens=256, thinking="off", label="health"))
+ return None
+ except Exception as e: # noqa: BLE001 — a probe reports, it does not propagate
+ return f"{type(e).__name__}: {str(e)[:100]}"
+
+ n = max(1, sample)
+ with cf.ThreadPoolExecutor(max_workers=n) as pool:
+ out = list(pool.map(one, range(n)))
+ reasons = tuple(dict.fromkeys(r for r in out if r)) # de-duplicated, order kept
+ return Health(model=model, n_ok=sum(r is None for r in out), n_tried=n, reasons=reasons)
+
+
+def _bare_model(model_id: str, timeout_s: float):
+ """The model with retries switched off — a probe that retries measures nothing."""
+ provider, _, name = model_id.partition(":")
+ if not name:
+ provider, name = "gemini", provider
+ if provider == "gemini":
+ from codeverse.models.gemini import GeminiModel
+
+ return GeminiModel(name, timeout_s=timeout_s, max_attempts=1)
+ from codeverse.models import get_chat_model # other providers: no bare constructor needed yet
+
+ return get_chat_model(model_id)
diff --git a/harness/docs/EVAL.md b/harness/docs/EVAL.md
index 19e7634a..1c0d5ffa 100644
--- a/harness/docs/EVAL.md
+++ b/harness/docs/EVAL.md
@@ -42,6 +42,7 @@ fooling ourselves. Tools: `3dcv bench`, `bench/compare_backends.py`,
| `articulated_v1.yaml` | articulated_object / urdf_blender | 12 | tiers |
| `scenes_v1.yaml` | scene / scene_threejs | 12 | tiers |
| `compare_v1.yaml` | static_object / blender | 8 | 2 easy / 3 medium / 3 hard; for harness-vs-one-shot |
+| `compare_v2.yaml` | static_object / blender | 8 | 2 medium controls / 6 hard (one per v2 difficulty axis); harness-vs-one-shot on hard prompts |
Each prompt: `{id, tier, category, prompt, must_have[], dimensions_m?}`. `must_have`
becomes acceptance items (planner-appended in the loop, fixed-judge checklist in
@@ -104,8 +105,13 @@ cost and wall time per prompt; arena: wins/ties/losses with mean confidence. Cl
harness advantage only when (a) the fixed-judge mean and pass rate are higher **and**
(b) the pairwise arena agrees, at comparable or lower cost.
-Subscription-backed one-shot arms (`claude-code`, `codex`) have estimated or zero USD;
-report token counts alongside. Run them sparingly.
+Subscription-backed arms (`claude-code`, `codex`) bill no dollars: their USD is a
+notional API-rate estimate from the tokens the CLI reports, so report tokens and
+wall-clock alongside it and never compare it to an API arm's real spend without
+saying so. Run them sparingly. `codex` arms always state their reasoning effort
+(`-c model_reasoning_effort=`, default `high` from `Settings.agents.codex_reasoning_effort`,
+per-arm override `codex:<model>@<effort>`) — the CLI's own default is *medium*, so an
+unstated effort silently changes what a codex arm measures.
## 5. Comparing backends inside the harness
@@ -153,9 +159,42 @@ Notes: the earlier criteria-first schema compressed flash to 0.6–0.7 (std 0.01
* Never tune rubric text against the battery you report on; bump the rubric version
(`*_v2`) instead and re-run.
-## 7. Reporting checklist
+## 7. Failures that are not results
+
+A cell can end without a score for reasons that say nothing about the model, and
+counting those as zeros silently rigs a comparison. `bench/_infra.py` classifies
+them, and `compare_backends` applies the SAME rule to every arm:
+
+| status | what happened | score | build rate | wall clock |
+|---|---|---|---|---|
+| `infra_failed` | provider outage — 503/529 storm, read timeout, exhausted key pool | excluded | excluded | excluded |
+| `budget_exhausted` | ran out of minutes/dollars with zero rounds and no artifact | excluded | **counts as a miss** | excluded |
+| `no_code` | the model answered, but with prose or unparseable code | **0.0** | counts | counts |
+| `build_failed` | the code ran and the build failed | **0.0** | counts | counts |
+
+The distinction is not academic. Before 2026-08-24 the two failure paths in
+`run_cell` disagreed: a one-shot cell that got no answer recorded `score=0.0` while a
+harness cell killed by the *same* 503 recorded `score=None`. During a multi-hour
+`gemini-3.7-flash` capacity storm this put five hard zeros on the one-shot arm of
+`compare_v2_full` and quietly dropped four harness cells — a bias worth roughly a
+quarter of a point, pointing the same way as the claim being tested. `compare_v1_full`
+and `compare_v1_live2` were audited and are unaffected.
+
+Rules that follow from it:
+
+* an outage cell is **re-run, never reported** — `--redo-status infra_failed`; the run
+ summary prints the exact command and the arm table carries a `dropped` column, so a
+ loss can never be mistaken for a result;
+* never compare arms measured in different weather. If one arm ran during a storm and
+ another did not, re-run the affected cells before putting the two in one table;
+* `budget_exhausted` is deliberately *not* excused on the build rate: the provider is
+ not at fault for a model that cannot finish inside the cap.
+
+## 8. Reporting checklist
battery name + git sha of prompts; judge id, rubric name + hash, `n_samples`; per-arm
generator/planner ids; rounds and budget caps; per-tier table (n, mean ± std, pass
rate, build-fail rate, cost, minutes); pairwise table; number of degraded verdicts
-re-run; links to `record.json` / `report.html` under `bench/out/`.
+re-run; **cells dropped as `infra_failed` and `budget_exhausted`, per arm** (§7 — an
+omitted drop count is an unreadable table); links to `record.json` / `report.html`
+under `bench/out/`.
diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.md
index 7b93b313..64f43711 100644
--- a/harness/docs/INSTALL.md
+++ b/harness/docs/INSTALL.md
@@ -149,10 +149,14 @@ Run the offline test suite to confirm the install:
```bash
cd harness
-python -m pytest tests -q -m "not live" # needs node + Blender for the full set
-python -m pytest tests -q -m "not live and not blender and not node" # pure-python subset
+python -m pytest tests -q # needs node + Blender for the full set
+python -m pytest tests -q -m "not blender and not node" # pure-python subset
+python -m pytest tests -q -m live # OPT-IN: real API calls, needs keys
```
+Live tests are deselected by default (`addopts = ["-m", "not live"]` in `pyproject.toml`),
+so a bare `pytest` never spends money and never hangs waiting on a provider outage.
+
---
## 5. runtime_js — the node side
@@ -487,6 +491,9 @@ that the keys work end to end):
| `ffmpeg` | WARN | not found | optional; turntables become GIFs. `sudo apt-get install ffmpeg` (or `conda install -c conda-forge ffmpeg`) |
| `mcp` | WARN | `mcp` package or the server module missing | `pip install -e 'harness[mcp]'`; only affects the agentic CLI backends |
| `gemini live call` (`--live`) | FAIL | key rejected / no network | check the key value and outbound access; a `503 … high demand` is transient, not an install problem |
+| `gemini quota` | OK | always informational | the per-key RPM/TPM the pool schedules against x the number of keys (`Settings.rate`, docs/COST.md Part III); tune with `CV3D_RATE__TPM_PER_KEY` / `CV3D_RATE__MAX_IN_FLIGHT` |
+| `gemini pool` (`--live`) | WARN | a key is benched as dead | that key 401/403'd; rotate or remove it — the pool re-probes it after an hour. The row also shows in-flight, RPM/TPM headroom used and this process's 429/5xx counts |
+| `storm gate` (`--live`) | WARN | a capacity storm is running | provider-side (`503 high demand`), not an install problem; the gate is off by default (docs/COST.md §21) and the row only appears when something enabled it |
---
diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.md
index 726d4507..296f00cb 100644
--- a/harness/docs/RUNBOOK.md
+++ b/harness/docs/RUNBOOK.md
@@ -12,8 +12,9 @@ pip install -e /home/yipeng/3dcodeverse/harness # once; entry points 3dcode
cd /home/yipeng/3dcodeverse/harness/runtime_js && npm install # [email protected], puppeteer (chrome cached)
3dcv doctor # python deps (incl. python-fcl, moderngl), blender, node/three/puppeteer, chrome WebGL, keys, CLIs, git, ffmpeg, mcp
3dcv doctor --live # + one tiny Gemini call ("pong", ~$0.00001)
-python -m pytest tests -q -m "not live" # ~860 offline tests (blender/node/GL tests run when the binaries exist)
-python -m pytest tests -q -m "not live and not blender and not node" # pure-python subset
+python -m pytest tests -q # offline suite; live tests are opt-in (blender/node/GL run when the binaries exist)
+python -m pytest tests -q -m "not blender and not node" # pure-python subset
+python -m pytest tests -q -m live # OPT-IN: real API calls
```
### Keys and settings
@@ -76,7 +77,7 @@ round, then ≈ $0.36 / ~7 min per refine (give scenes `--max-minutes 60 --max-u
| `single-shot:gemini:gemini-3.7-flash` | one structured-output call → multi-file envelope, no tools | fastest/cheapest; baseline for "raw model" deltas |
| `gemini-cli:gemini-3.7-flash` | `gemini -p … --approval-mode yolo --skip-trust --output-format json` | see gotchas below |
| `claude-code:<model>` | `claude -p … --dangerously-skip-permissions --mcp-config ws/.mcp.json …` | local subscription — test lightly |
-| `codex:<model>` | `codex exec --json -C ws --sandbox workspace-write … -c mcp_servers.3dcv.…` | subscription; MCP tools need `default_tools_approval_mode="approve"` (harness passes it) |
+| `codex:<model>[@<effort>]` | `codex exec --json -C ws --sandbox workspace-write -c model_reasoning_effort=high … -c mcp_servers.3dcv.…` | subscription; MCP tools need `default_tools_approval_mode="approve"` (harness passes it); reasoning effort is always stated (`Settings.agents.codex_reasoning_effort`, default `high`; `codex:gpt-5.6-sol@medium` per id, `""` to defer to `~/.codex/config.toml`) |
| `agy:<model>` | `agy --print … --add-dir ws` | no per-workspace MCP: tools via `3dcv tools <name> --json … --workspace .`; no served-model or cost reporting |
| `gemini:* / anthropic:* / openai:*` | ChatModel for planner / judge / captioner / single-shot | Anthropic/OpenAI untested live here |
@@ -186,6 +187,13 @@ Results stream to `results.jsonl` (resumable). Batteries: `static_objects_v1` (
`articulated_v1` (12), `scenes_v1` (12), `compare_v1` (8, harness-vs-one-shot).
Protocol and judge calibration: `docs/EVAL.md`.
+`compare_backends` **preflights every model it needs** (one ~20 s probe each) and
+refuses to start when one is not serving — a dead provider does not fail fast on its
+own, it lets each cell burn its full retry budget first. `--wait-for-provider 60`
+parks until it recovers instead; `--no-preflight` skips the check. Cells that a
+provider outage kills anyway are recorded `infra_failed`, excluded from every rate,
+and re-run with `--redo-status infra_failed` (see `docs/EVAL.md` §7).
+
## 8. Extending (plugin paths)
* **New language**: enum in `contracts/common.py::Language` (+ `TRACK_LANGUAGES`,
diff --git a/harness/pyproject.toml b/harness/pyproject.toml
index 2abcb8b3..5041746a 100644
--- a/harness/pyproject.toml
+++ b/harness/pyproject.toml
@@ -73,6 +73,11 @@ ignore = ["E501"]
[tool.pytest.ini_options]
testpaths = ["tests"]
timeout = 600
+# Live tests are OPT-IN (`pytest -m live`). Without this, a bare `pytest` on a machine
+# that happens to have API keys configured fires real requests, and during a provider
+# outage it hangs instead of failing — which is exactly what happened on 2026-08-24.
+# Everyone's default run is now the offline suite CI runs.
+addopts = ["-m", "not live"]
markers = [
"live: needs network + API keys (deselect with -m 'not live')",
"blender: needs a Blender binary",
diff --git a/harness/tests/compare_bench/test_compare_matrix.py b/harness/tests/compare_bench/test_compare_matrix.py
index 7c1f7437..d924bb47 100644
--- a/harness/tests/compare_bench/test_compare_matrix.py
+++ b/harness/tests/compare_bench/test_compare_matrix.py
@@ -129,7 +129,11 @@ def test_matrix_end_to_end_with_fakes(tmp_path: Path):
assert deps.pw["gemini:fixed"].calls == 4
# report
md = (out / "report.md").read_text()
- assert "fixed judge: **gemini:fixed**" in md and "| harness:api-agent:gemini:gemini-3.7-flash | harness | 2 | 0.900 |" in md
+ assert "fixed judge: **gemini:fixed**" in md
+ # the arm row is n | dropped | over budget | mean: the two loss columns stay blank when
+ # nothing was lost, but must always be PRESENT so a drop can never hide (docs/EVAL.md §7)
+ assert "| arm | kind | n | dropped | over budget | mean |" in md, md
+ assert "| harness:api-agent:gemini:gemini-3.7-flash | harness | 2 | | | 0.900 |" in md, md
assert "| cmp_easy_stool | easy | 0.90✓ | 0.60 | 0.75✓ | 0.00 ✗build |" in md
assert "| harness:api-agent:gemini:gemini-3.7-flash | oneshot:claude-code | 2 | 2 | 0 | 0 | 100% |" in md
page = (out / "report.html").read_text()
diff --git a/harness/tests/compare_bench/test_infra_failures.py b/harness/tests/compare_bench/test_infra_failures.py
new file mode 100644
index 00000000..19083838
--- /dev/null
+++ b/harness/tests/compare_bench/test_infra_failures.py
@@ -0,0 +1,106 @@
+"""A provider outage must never be scored as a model failure.
+
+Regression (2026-08-24): a multi-hour gemini-3.7-flash 503 storm hit both arms of
+compare_v2. ``compare_backends`` recorded it as ``score=0.0`` on the one-shot path
+(counted in the mean) and ``score=None`` on the harness path (dropped), so the same
+downtime pushed one-shot means down while leaving harness means untouched.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from bench._compare_report import CellResult, arm_stats
+from bench._infra import is_infra_failure
+
+OUTAGES = [
+ "ModelError: Gemini API error 503: This model is currently experiencing high demand.",
+ "ModelError: Gemini request timed out: The read operation timed out",
+ "ModelError: Gemini API error 529: is overloaded",
+ "KeyPoolExhausted: every key is cooling down",
+ "APIError: 500 Internal server error",
+ "ConnectionError: Connection reset by peer",
+]
+MODEL_FAILURES = [
+ "unparseable answer: no python block in the response",
+ "empty answer",
+ "SyntaxError: invalid syntax. Perhaps you forgot a comma? (model.py, line 261)",
+ "BuildError: bpy.data.objects['Cube'] not found",
+ "the model returned prose instead of code",
+]
+
+
[email protected]("err", OUTAGES)
+def test_provider_outages_are_infra(err):
+ assert is_infra_failure(err) is True
+
+
[email protected]("err", MODEL_FAILURES)
+def test_model_failures_are_not_infra(err):
+ """These are real capability results and must keep their zero."""
+ 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
+
+ # 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
+ assert is_infra_failure(TimeoutError("read timed out")) is True
+ # a wrapped cause still counts
+ err = ValueError("generation failed")
+ err.__cause__ = ModelError("overloaded", status=529)
+ assert is_infra_failure(err) is True
+
+
+def test_outage_cells_leave_every_rate_alone():
+ """The bug in one assertion: an arm hit by downtime must score the same as one
+ that ran in the clear, and the loss must be reported rather than hidden."""
+ clear = [CellResult(prompt_id=f"p{i}", arm="A", kind="oneshot", status="scored",
+ score=0.8, passed=True, build_ok=True, wall_s=60.0) for i in range(4)]
+ unlucky = [*[c.model_copy(update={"arm": "B"}) for c in clear],
+ CellResult(prompt_id="p9", arm="B", kind="oneshot", status="infra_failed",
+ score=None, passed=None, build_ok=False, wall_s=3600.0)]
+ a, b = {s.arm: s for s in arm_stats([*clear, *unlucky])}["A"], {s.arm: s for s in arm_stats([*clear, *unlucky])}["B"]
+ assert a.mean_score == b.mean_score, "downtime changed the score"
+ assert a.build_ok_rate == b.build_ok_rate, "downtime changed the build rate"
+ assert a.mean_minutes == b.mean_minutes, "an hour spent retrying a 503 is not model latency"
+ assert b.infra_failed == 1 and b.n_evaluated == 4 and b.n == 5, "the loss must stay visible"
+
+
+def test_both_failure_paths_classify_the_same_way():
+ """The asymmetry itself: whichever path records the outage, the verdict matches."""
+ from bench import compare_backends as cb
+
+ src = cb.run_cell.__code__.co_consts
+ assert any(c == "infra_failed" for c in src if isinstance(c, str)), \
+ "the no-code path must be able to record infra_failed"
+ outage = "Gemini API error 503: This model is currently experiencing high demand."
+ assert is_infra_failure(outage) == is_infra_failure(RuntimeError(outage))
+
+
+def test_budget_exhaustion_is_scoreless_but_still_counts_against_build_rate():
+ """The 50-minutes-for-nothing case: no score to average, but the arm did miss."""
+ from bench._compare_report import CellResult, arm_stats
+
+ rows = [CellResult(prompt_id="p1", arm="A", kind="harness", status="scored",
+ score=0.9, passed=True, build_ok=True),
+ CellResult(prompt_id="p2", arm="A", kind="harness", status="budget_exhausted",
+ score=None, passed=False, build_ok=False)]
+ s = arm_stats(rows)[0]
+ assert s.mean_score == 0.9, "a cell with no artifact cannot contribute a score"
+ assert s.build_ok_rate == 0.5, "but it must not be excused on the build rate either"
+ assert s.budget_exhausted == 1 and s.infra_failed == 0, "and it is reported separately from an outage"
+
+
+def test_budget_and_outage_are_different_buckets():
+ from bench._infra import is_budget_exhaustion, is_infra_failure
+
+ budget = "harness run produced no src/model.py (status budget: elapsed 50.2 min exceeds max_minutes 45.0)"
+ outage = "ModelError: Gemini API error 503: This model is currently experiencing high demand."
+ assert is_budget_exhaustion(budget) and not is_infra_failure(budget)
+ assert is_infra_failure(outage) and not is_budget_exhaustion(outage)
diff --git a/harness/tests/models/test_health.py b/harness/tests/models/test_health.py
new file mode 100644
index 00000000..dd055c56
--- /dev/null
+++ b/harness/tests/models/test_health.py
@@ -0,0 +1,40 @@
+"""Provider health probe (codeverse/models/health.py)."""
+
+from __future__ import annotations
+
+from codeverse.models.health import DEFAULT_MIN_OK, Health
+
+
+def test_a_model_answering_on_most_keys_is_healthy():
+ assert Health("m", n_ok=3, n_tried=4).ok
+ assert Health("m", n_ok=2, n_tried=4).ok, f"the bar is {DEFAULT_MIN_OK:.0%} of sampled keys"
+
+
+def test_a_model_answering_on_almost_nothing_is_not():
+ assert not Health("m", n_ok=1, n_tried=4).ok
+ assert not Health("m", n_ok=0, n_tried=4).ok
+
+
+def test_no_keys_probed_is_not_reported_as_healthy():
+ """An empty probe must never read as a green light."""
+ assert not Health("m", n_ok=0, n_tried=0).ok
+
+
+def test_the_message_carries_the_provider_reason():
+ h = Health("gemini:gemini-3.7-flash", n_ok=0, n_tried=4,
+ reasons=("ModelError: Gemini API error 504: Deadline expired",))
+ text = str(h)
+ assert "0/4" in text and "504" in text, text
+
+
+def test_probe_never_raises_when_every_call_fails(monkeypatch):
+ import codeverse.models.health as health
+
+ class Boom:
+ def generate(self, _req):
+ raise RuntimeError("provider on fire")
+
+ monkeypatch.setattr(health, "_bare_model", lambda *a, **k: Boom())
+ h = health.probe("gemini:gemini-3.7-flash", sample=3, timeout_s=1)
+ assert not h.ok and h.n_ok == 0 and h.n_tried == 3
+ assert h.reasons and "provider on fire" in h.reasons[0]
diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.py
index 6da3ca55..2b0baf93 100644
--- a/harness/tests/models/test_retry.py
+++ b/harness/tests/models/test_retry.py
@@ -282,3 +282,20 @@ def test_503_storm_budget_exhausts_then_normal_budget_applies():
outcome_of=lambda e: "5xx", max_attempts=2, base_delay=0.0,
storm_attempts=3, storm_max_delay=0.0, sleep=lambda d: None,
)
+
+
+def test_live_tests_are_opt_in_by_default():
+ """A bare `pytest` must never fire real API calls.
+
+ On 2026-08-24 a plain run on a keyed machine hung for the whole timeout because
+ the live suite was selected by default and the provider was in a capacity storm.
+ """
+ from pathlib import Path
+
+ from codeverse._compat import tomllib # 3.10 floor: stdlib tomllib is 3.11+
+
+ root = Path(__file__).resolve().parents[2]
+ cfg = tomllib.loads((root / "pyproject.toml").read_text())
+ addopts = cfg["tool"]["pytest"]["ini_options"].get("addopts", [])
+ joined = " ".join(addopts) if isinstance(addopts, list) else str(addopts)
+ assert "not live" in joined, "live tests must be deselected by default (see pyproject addopts)"