Skip to content

Official Codebase of 3DCodeVerse

Python

eval tests: 40 tests go that cover no line of bench/ another test does not (−685 lines)

gaoypeng8f833ed70737
diff --git a/eval/tests/test_ab_plan.py b/eval/tests/test_ab_plan.py
index 42a42806..914e4d20 100644
--- a/eval/tests/test_ab_plan.py
+++ b/eval/tests/test_ab_plan.py
@@ -14,7 +14,6 @@ if str(REPO) not in sys.path:
from bench._ab_report import ( # noqa: E402
CONTROL,
- KEEP_DELTA,
VARIANT,
PairOutcome,
pair_up,
@@ -38,10 +37,8 @@ from bench.ab_plan import ( # noqa: E402
main,
parse_variant_env,
run_ab,
- worker_argv,
)
from bench.run_bench import Battery # noqa: E402
-from bench.stats import n_to_resolve, t975 # noqa: E402
BATTERY = REPO / "bench" / "prompts" / "compare_v1.yaml"
@@ -60,20 +57,17 @@ def _pairs(*deltas: float) -> list[PairOutcome]:
# ----------------------------------------------------------------------------- verdict rule
-def test_keep_needs_mean_gain_and_no_regression():
- assert verdict_of(_pairs(0.03, 0.02, 0.01, 0.04)).decision == "keep"
- # one regression blocks a keep even when the mean clears the bar
- v = verdict_of(_pairs(0.10, 0.10, 0.10, -0.03))
- assert v.decision == "inconclusive" and v.regressions == ["p3"]
- # a mean just under the bar is not a keep
- assert verdict_of(_pairs(0.01, 0.02, 0.02, 0.01)).decision == "inconclusive"
-
-
-def test_revert_on_mean_loss_or_two_regressions():
- assert verdict_of(_pairs(-0.02, -0.02, -0.02)).decision == "revert"
- v = verdict_of(_pairs(0.20, 0.20, -0.03, -0.05)) # mean +0.08 but two prompts lost
- assert v.decision == "revert" and v.regressions == ["p2", "p3"]
- assert verdict_of(_pairs(-0.019, 0.0)).decision == "inconclusive"
[email protected]("deltas, decision, regressions", [
+ ((0.03, 0.02, 0.01, 0.04), "keep", []),
+ ((0.10, 0.10, 0.10, -0.03), "inconclusive", ["p3"]), # one regression blocks a keep
+ ((0.01, 0.02, 0.02, 0.01), "inconclusive", []), # a mean just under the bar
+ ((-0.02, -0.02, -0.02), "revert", []),
+ ((0.20, 0.20, -0.03, -0.05), "revert", ["p2", "p3"]), # mean +0.08 but two prompts lost
+ ((-0.019, 0.0), "inconclusive", []),
+])
+def test_the_verdict_rule(deltas, decision, regressions):
+ v = verdict_of(_pairs(*deltas))
+ assert v.decision == decision and v.regressions == regressions
def test_no_pairs_is_inconclusive_never_keep():
@@ -81,32 +75,8 @@ def test_no_pairs_is_inconclusive_never_keep():
assert v.decision == "inconclusive" and v.n_pairs == 0 and v.mean_delta is None
-# ----------------------------------------------------------------------------- pairing
-def test_a_pair_counts_only_when_both_arms_scored():
- rows = [_row("a", CONTROL, 0.70), _row("a", VARIANT, 0.75),
- _row("b", CONTROL, 0.80), _row("b", VARIANT, None, "infra_failed"),
- _row("c", CONTROL, None, "budget_exhausted"), _row("c", VARIANT, 0.9),
- _row("d", CONTROL, 0.5)]
- pairs = {p.prompt_id: p for p in pair_up(rows)}
- assert pairs["a"].paired and pairs["a"].delta == pytest.approx(0.05)
- assert not pairs["b"].paired and pairs["b"].reason == "variant infra_failed"
- assert not pairs["c"].paired and pairs["c"].reason == "control budget_exhausted"
- assert not pairs["d"].paired and pairs["d"].reason == "variant missing"
- v = verdict_of(list(pairs.values()))
- assert v.n_pairs == 1 and v.mean_delta == pytest.approx(0.05)
-
-
-def test_latest_row_wins_and_order_follows_the_battery():
- rows = [_row("a", CONTROL, 0.1), _row("b", CONTROL, 0.2), _row("b", VARIANT, 0.2),
- _row("a", VARIANT, 0.1), _row("a", CONTROL, 0.9)] # re-appended on a redo
- pairs = pair_up(rows, [("b", "easy"), ("a", "hard")])
- assert [p.prompt_id for p in pairs] == ["b", "a"] and pairs[1].tier == "hard"
- assert pairs[1].delta == pytest.approx(0.1 - 0.9)
-
-
def test_outage_cells_are_excluded_from_every_arm_rate():
- """An arm hit by weather must summarise the same as one that ran in the clear, and
- the loss must stay visible (docs/EVAL.md §7)."""
+ """An arm hit by weather summarises like one that ran in the clear; the loss stays visible (EVAL.md §7)."""
clear = [_row(f"p{i}", CONTROL, 0.8) for i in range(4)]
unlucky = [_row(f"p{i}", VARIANT, 0.8) for i in range(4)] + [_row("p9", VARIANT, None, "infra_failed", wall=3600, cost=0.0)]
by = {s.arm: s for s in arm_stats(clear + unlucky)}
@@ -128,49 +98,18 @@ def test_summary_marks_regressions_and_states_the_rule():
# ----------------------------------------------------------------------------- noise floor
-def test_a_verdict_states_the_spread_it_was_decided_on():
- """The rule fires on a mean, and a mean of stochastic generations has a spread. An
- A/A run of this rig (identical arms) returned +0.344 on one prompt and the rule said
- "keep" — so the report has to carry the noise beside the word."""
- v = verdict_of(_pairs(0.30, -0.20, 0.10, 0.05, -0.10, 0.25, 0.02, -0.15))
- assert v.sd_delta is not None and v.se_delta == pytest.approx(v.sd_delta / 8 ** 0.5, abs=1e-3)
- assert v.ci_half == pytest.approx(t975(7) * v.se_delta, abs=1e-3), "the 95 % t-interval, n - 1 = 7 df"
- assert not v.separated and "NOT separated from noise" in v.caution
- # the honest answer to "would one more prompt settle this?": at this spread, hundreds
- assert v.n_for_power == pytest.approx(n_to_resolve(v.sd_delta, KEEP_DELTA), rel=0.01)
- assert v.n_for_power > 100
-
-
-def test_sign_consistency_catches_the_win_the_mean_rule_throws_away():
- """A change that helps every prompt a little is invisible to a +-0.02 mean at this
- spread, and obvious to the sign test — which is the whole point of reporting it."""
- v = verdict_of(_pairs(*([0.01] * 8)))
- assert v.decision == "inconclusive", "the mean rule cannot see it"
- assert (v.n_up, v.n_down) == (8, 0) and v.sign_p == pytest.approx(2 / 2 ** 8, abs=1e-4)
+def test_a_verdict_carries_its_noise_beside_the_word():
+ """An A/A run once said "keep" on +0.344 from one prompt: the verdict must say when it is noise."""
v = verdict_of(_pairs(0.30, -0.20, 0.10, 0.05, -0.10, 0.25, 0.02, -0.15))
- assert (v.n_up, v.n_down) == (5, 3) and v.sign_p > 0.7, "a big mean with a coin-flip sign pattern"
- assert verdict_of(_pairs(0.0, 0.0)).sign_p is None, "zero deltas are dropped, as the test requires"
-
-
-def test_a_tight_win_is_marked_separated_and_carries_no_caution():
+ assert not v.separated and "NOT separated from noise" in v.caution and v.n_for_power > 100
+ assert (v.n_up, v.n_down) == (5, 3)
v = verdict_of(_pairs(0.10, 0.11, 0.09, 0.12))
assert v.decision == "keep" and v.separated and v.caution == ""
-
-
-def test_one_pair_can_never_be_separated_from_noise():
v = verdict_of(_pairs(0.344))
assert v.decision == "keep", "the blunt rule still fires — that is exactly the danger"
assert v.sd_delta is None and not v.separated and "one pair cannot separate" in v.caution
-def test_summary_prints_the_confidence_block():
- rows = [_row(f"p{i}", arm, s) for i, (c, x) in enumerate([(0.5, 0.9), (0.6, 0.3), (0.7, 0.72)])
- for arm, s in ((CONTROL, c), (VARIANT, x))]
- md = render_summary(pair_up(rows), rows, title="t", variant_env={"K": "v"}, generator="g", judge="j", rounds=1)
- assert "## Confidence" in md and "separated from noise: NO" in md and "NOT separated from noise" in md
- assert "sign consistency: 2 up / 1 down" in md and "sign test p = 1.000" in md
-
-
def test_an_aa_run_is_labelled_so_nobody_reads_it_as_a_decision():
rows = [_row("a", CONTROL, 0.59), _row("a", VARIANT, 0.93)]
md = render_summary(pair_up(rows), rows, title="t", variant_env={}, generator="g", judge="j", rounds=1, aa=True)
@@ -190,18 +129,14 @@ def test_variant_env_is_applied_to_the_variant_arm_only():
def test_children_run_at_exactly_the_cap_the_budget_reserved(monkeypatch):
- """CQ-3: both children run at the cap the driver was given. child_env used
- ``setdefault``, so a shell exporting C3D_MAX_IN_FLIGHT=32 under ``--max-in-flight 8``
- ran a child at 32 (docs/COST.md §23) — three lines after the function deliberately pops
- every variant key so an inherited switch cannot win."""
+ """CQ-3: an explicit --max-in-flight beats the shell's C3D_MAX_IN_FLIGHT (docs/COST.md §23)."""
opts = AbOptions(variant_env={"K": "v"}, max_in_flight=8)
base = {"PATH": "/bin", MAX_IN_FLIGHT_ENV: "32", NESTED_MAX_IN_FLIGHT_ENV: "48"}
for arm in (CONTROL, VARIANT):
env = child_env(arm, opts, base)
assert env[MAX_IN_FLIGHT_ENV] == "8", "an explicit --max-in-flight must beat the shell"
assert NESTED_MAX_IN_FLIGHT_ENV not in env, "the nested spelling must not fight the flat one"
- # without the flag the inherited cap is still honoured — resolved ONCE, into AbOptions,
- # so the number the children get and the number the preflight reserves are the same one
+ # without the flag the inherited cap is honoured, resolved once into AbOptions
monkeypatch.setenv(MAX_IN_FLIGHT_ENV, "6")
monkeypatch.delenv(NESTED_MAX_IN_FLIGHT_ENV, raising=False)
assert inherited_max_in_flight() == 6
@@ -219,14 +154,6 @@ def test_parse_variant_env():
parse_variant_env([f"{name}=64"])
-def test_worker_argv_carries_the_whole_option_block(tmp_path: Path):
- opts = AbOptions(variant_env={"K": "v"}, rounds=1)
- argv = worker_argv(BATTERY, tmp_path, "cmp_easy_stool", VARIANT, opts)
- assert argv[1].endswith("ab_plan.py") and argv[2] == "cell" and "--arm" in argv
- assert AbOptions.model_validate_json(argv[-1]) == opts
- assert cell_dir(tmp_path, CONTROL, "x", "gemini-cli:gemini-3.6-flash").parent.parts[-4:] == ("arms", "control", "cells", "x")
-
-
def test_a_child_that_dies_without_a_cell_is_an_error_not_a_score(tmp_path: Path):
"""Real subprocess, no network: an unknown prompt id makes the worker exit 2 before any
model is touched, and the driver must record that as a scoreless error cell."""
@@ -241,10 +168,7 @@ def test_a_child_that_dies_without_a_cell_is_an_error_not_a_score(tmp_path: Path
def test_a_non_utf8_byte_in_the_worker_log_does_not_kill_the_driver(tmp_path: Path, monkeypatch):
- """CP-1: on the no-cell.json path the log tail is the only evidence there is, and an
- agent CLI is free to print any byte. One 0xff used to raise UnicodeDecodeError out of
- spawn_cell — which run_ab re-raises through fut.result(), ending the whole A/B without
- a summary — for a log that says '503 UNAVAILABLE' and classifies perfectly well."""
+ """CP-1: a 0xff in the log tail used to raise out of spawn_cell and end the whole A/B."""
import bench.ab_plan as ab
from bench.run_bench import BenchPrompt
@@ -352,19 +276,6 @@ def test_cli_refuses_identical_arms_and_wrong_parallel(tmp_path: Path, capsys):
main(["--prompts", str(BATTERY), "--out", str(tmp_path), "--variant-env", "K=v", "--parallel", "8"])
-def test_aa_run_records_two_empty_arms(tmp_path: Path):
- """--aa is the ONLY sanctioned way to run identical arms, and the record must say so
- or a later reader will mistake a noise measurement for a result."""
- b = Battery.load(BATTERY)
- ids = [p.id for p in b.prompts[:2]]
- fake = FakeCells({(ids[0], VARIANT): 0.9})
- run_ab(BATTERY, tmp_path, AbOptions(variant_env={"C3D_PLAN_FEATURES": "all"}, aa=True, ids=ids), run_cell_fn=fake)
- meta = json.loads((tmp_path / "ab.json").read_text())
- assert meta["aa"] is True and meta["arms"] == {"control": {}, "variant": {}}
- assert {r.workspace for r in _journal(tmp_path)} == {""}, "no arm saw the switch"
- assert (tmp_path / "summary.md").read_text().startswith("# A/A: ")
-
-
def test_cli_report_only_rebuilds_from_results(tmp_path: Path, capsys):
(tmp_path / "results.jsonl").write_text("".join(r.model_dump_json() + "\n" for r in
[_row("cmp_easy_stool", CONTROL, 0.5),
@@ -388,12 +299,7 @@ def test_report_only_survives_a_run_dir_with_no_or_broken_ab_json(tmp_path):
def test_a_pinned_plan_that_dies_in_a_storm_records_the_pair_and_continues(tmp_path: Path, monkeypatch):
- """The pinned plan is ONE model call with a 15-minute retry budget. When a 503 storm
- outlasts it the call raises — and that used to propagate out of run_ab's loop and end
- the whole battery. Measured 2026-08-26: a 3-prompt driver died on its first pin, two
- prompts never attempted, while the drivers beside it waited the storm out. An outage is
- not a score (docs/EVAL.md §7): the pair is recorded infra_failed so --redo-status
- infra_failed picks it up, and the loop goes on."""
+ """A pin that dies in a 503 storm records the pair infra_failed and the loop goes on (EVAL.md §7)."""
from bench import ab_plan as ab
from codeverse3d.models.base import ModelError
diff --git a/eval/tests/test_ab_plan_switches.py b/eval/tests/test_ab_plan_switches.py
index da859b46..190568e5 100644
--- a/eval/tests/test_ab_plan_switches.py
+++ b/eval/tests/test_ab_plan_switches.py
@@ -17,31 +17,8 @@ def test_ab_plan_refuses_an_ab_whose_only_switch_is_dead(capsys):
assert "nothing reads" in err and "C3D_PLAN_FEATURES" in err
-def test_ab_plan_still_accepts_a_live_switch(monkeypatch, capsys):
- """The guard must not block a real A/B: it fires only when EVERY key is dead.
-
- Offline — --no-preflight keeps the provider health check out of it, and run_ab itself
- is stubbed."""
- import bench.ab_plan as A
-
- seen: list[dict[str, str]] = []
- class _V:
- decision, reason, caution = "keep", "stubbed", ""
-
- monkeypatch.setattr(A, "run_ab", lambda battery, out, opts, **kw: (seen.append(opts.variant_env), _V())[1])
- for argv in (["--variant-env", "C3D_PLAN_BRIEF=off"],
- ["--variant-env", "C3D_PLAN_FEATURES=all", "--variant-env", "C3D_PLAN_BRIEF=off"]):
- A.main(["--prompts", "p.yaml", "--out", "o", "--no-preflight", *argv])
-
- assert len(seen) == 2, capsys.readouterr()
- assert "C3D_PLAN_BRIEF" in seen[0]
-
-
def test_a_dead_switch_does_not_block_pin_plan(monkeypatch, capsys):
- """C3D_PLAN_FEATURES is read by nothing, so it cannot change a plan: next to a
- generation-side switch it must not make --pin-plan refuse the A/B (until 2026-09-22
- its never-implemented feature names did). The generation-side switch is the skills
- OFF arm: skills are on by default since 2026-09-22, so `C3D_SKILLS=1` would be no switch."""
+ """A dead switch beside a live one (the skills OFF arm) runs, and does not make --pin-plan refuse."""
import bench.ab_plan as A
seen: list[dict[str, str]] = []
@@ -53,28 +30,3 @@ def test_a_dead_switch_does_not_block_pin_plan(monkeypatch, capsys):
A.main(["--prompts", "p.yaml", "--out", "o", "--no-preflight", "--pin-plan",
"--variant-env", "C3D_PLAN_FEATURES=all", "--variant-env", "C3D_SKILLS=0"])
assert seen == [{"C3D_PLAN_FEATURES": "all", "C3D_SKILLS": "0"}], capsys.readouterr()
-
-
-def test_a_skills_ab_spells_its_off_arm_explicitly(monkeypatch):
- """Skills are ON by default since 2026-09-22 (harness docs/SKILLS.md §6). The control
- arm is the driver's env minus every variant key, so the only way to get an arm WITHOUT
- skills is to name `C3D_SKILLS=0` in the variant — and `C3D_SKILLS=1` is now two
- identical arms, the byte-identical-arms trap tracks/plan_features.py exists for."""
- from bench._ab_report import CONTROL, VARIANT
- from bench.ab_plan import AbOptions, child_env
- from codeverse3d.config import Settings
-
- skills = "C3D_SKILLS"
-
- def enabled(env: dict[str, str]) -> bool:
- monkeypatch.delenv(skills, raising=False)
- if skills in env:
- monkeypatch.setenv(skills, env[skills])
- return Settings().skills
-
- shell = {"PATH": "/usr/bin", skills: "0"} # exported in the launching shell: never reaches the control
- off = AbOptions(variant_env={skills: "0"})
- assert enabled(child_env(CONTROL, off, shell)) is True
- assert enabled(child_env(VARIANT, off, shell)) is False
- on = AbOptions(variant_env={skills: "1"})
- assert enabled(child_env(CONTROL, on, shell)) is enabled(child_env(VARIANT, on, shell)) is True
diff --git a/eval/tests/test_articulated_compare.py b/eval/tests/test_articulated_compare.py
index 3996c970..ca306bca 100644
--- a/eval/tests/test_articulated_compare.py
+++ b/eval/tests/test_articulated_compare.py
@@ -5,8 +5,6 @@ from __future__ import annotations
import sys
from pathlib import Path
-import pytest
-
REPO = Path(__file__).resolve().parents[1]
if str(REPO) not in sys.path:
sys.path.insert(0, str(REPO))
@@ -15,8 +13,6 @@ from bench._fixed_eval import FixedEvaluator, rubric_for # noqa: E402
from bench._oneshot import ( # noqa: E402
MODEL_FILE,
URDF_FILE,
- extract_files,
- files_for,
minimal_contract,
oneshot_prompt,
repair_prompt,
@@ -26,7 +22,6 @@ from bench.run_bench import Battery # noqa: E402
from codeverse3d.contracts.artifacts import BuildResult, GateReport # noqa: E402
from codeverse3d.contracts.common import Language, Track # noqa: E402
from codeverse3d.contracts.spec import Constraints, Spec # noqa: E402
-from codeverse3d.tracks.generation import MultiFileParseError # noqa: E402
from codeverse3d.workspace import Workspace # noqa: E402
PROMPTS = REPO / "bench" / "prompts"
@@ -71,23 +66,6 @@ def test_urdf_oneshot_prompt_carries_the_frame_recipe_and_the_two_file_envelope(
assert minimal_contract() == minimal_contract(Language.BLENDER) and URDF_FILE not in minimal_contract()
-def test_files_for_and_extract_files_two_file_answer():
- assert files_for(Language.BLENDER) == [MODEL_FILE] and files_for(Language.URDF_BLENDER) == [MODEL_FILE, URDF_FILE]
- got = extract_files(ENVELOPE, Language.URDF_BLENDER)
- assert got == {MODEL_FILE: PY, URDF_FILE: XML}
- # fenced blocks each preceded by their path also parse
- fenced = f"{MODEL_FILE}\n```python\n{PY}```\n{URDF_FILE}\n```xml\n{XML}```\n"
- assert extract_files(fenced, Language.URDF_BLENDER) == {MODEL_FILE: PY, URDF_FILE: XML}
- f"```python\n{PY}```", # one block, two expected
- f"=== FILE: {MODEL_FILE} ===\n{PY}=== END FILE ===\n", # envelope with the URDF missing
- f"=== FILE: {MODEL_FILE} ===\n{PY}=== END FILE ===\n=== FILE: {URDF_FILE} ===\n\n=== END FILE ===\n", # empty urdf
-])
-def test_a_urdf_answer_without_both_files_is_a_format_failure(text: str):
- with pytest.raises(MultiFileParseError):
- extract_files(text, Language.URDF_BLENDER)
-
-
def test_write_answer_files_writes_both(tmp_path):
ws = Workspace(tmp_path / "ws")
ws.create()
diff --git a/eval/tests/test_bench_shared.py b/eval/tests/test_bench_shared.py
index f1eb8b53..ffb79474 100644
--- a/eval/tests/test_bench_shared.py
+++ b/eval/tests/test_bench_shared.py
@@ -5,11 +5,8 @@ from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
-import pytest
-
-import bench.compare_backends as cb
import bench.run_bench as rb
-from bench.run_bench import Battery, BenchOptions, build_spec, select_prompts, spec_for
+from bench.run_bench import Battery, BenchOptions, select_prompts, spec_for
from tests.conftest import BATTERY
@@ -29,21 +26,6 @@ def test_select_prompts_ids_tiers_limit():
assert select_prompts(b, ids=["nope"]) == []
-def test_select_prompts_is_single_owner_for_both_drivers():
- """compare_backends deleted its private copy; both drivers filter identically."""
- assert cb.select_prompts is select_prompts and cb.default_run_track is rb.default_run_track
-
-
-def test_build_spec_tags_and_budget():
- b = _battery()
- item = b.prompts[0]
- spec = build_spec(b, item, backends=rb.get_settings().backends(), rounds=2,
- max_minutes=10, tag0="compare", extra_tags=("harness",))
- assert spec.tags[:4] == ["compare", b.name, item.tier, item.category] and "harness" in spec.tags
- assert spec.budget.max_rounds == 2 and spec.budget.max_minutes == 10.0
- assert spec.id == f"{b.name}/{item.id}"
-
-
def test_spec_for_routes_through_settings_backends():
b = _battery()
s = rb.get_settings()
@@ -54,34 +36,17 @@ def test_spec_for_routes_through_settings_backends():
assert spec.backends.captioner == s.default_captioner
-# ------------------------------------------------------- the harness arm is not blender-only
def test_the_harness_arm_looks_for_each_languages_own_entry_file():
- """``bench/_oneshot.MODEL_FILE`` is ``src/model.py`` because the ONE-SHOT arms are a
- blender-only comparison. The harness arm is not, and gating it on that constant made
- every glsl / three.js / scene / moderngl cell ``no_code`` **0.0** while the run itself
- came back ``passed`` — measured 2026-08-25 on a glsl_shader A/A whose control wrote
- ``src/shader.frag`` and was scored zero for it.
-
- Four of the seven languages were affected, which is why no graphics or three.js bundle
- has ever had a readable A/B: both arms scored 0.0 and the rig called that "no effect".
- """
+ """Gating on the blender-only MODEL_FILE scored every glsl/three.js/scene cell 0.0 (2026-08-25)."""
from bench.compare_backends import entry_of
- from codeverse3d.contracts.common import ENTRY_FILE, Language
+ from codeverse3d.contracts.common import ENTRY_FILE
for language, entry in ENTRY_FILE.items():
- spec = SimpleNamespace(language=language)
- assert entry_of(spec) == entry, f"{language.value} delivers {entry}"
-
- # the four that the hardcoded constant got wrong, named so the regression is legible
- assert {lang.value for lang, e in ENTRY_FILE.items() if e != "src/model.py"} == {
- "threejs", "scene_threejs", "glsl_shader", "opengl_python"}
- assert entry_of(SimpleNamespace(language=Language.GLSL_SHADER)) == "src/shader.frag"
+ assert entry_of(SimpleNamespace(language=language)) == entry, language.value
def test_a_run_that_scored_nothing_says_so_in_its_row(tmp_path: Path) -> None:
- """A worktree without node_modules made render_glb die, every round skip the judge and
- ten cells come back `status=plateau, score=None` — an arm that reads as healthy and
- measures nothing (2026-09-04). The row carries the reason now."""
+ """An arm whose every round skipped the judge must say so in its row, not read as healthy (2026-09-04)."""
from bench.run_bench import result_from_record
from codeverse3d.contracts.artifacts import Judgment
from codeverse3d.contracts.common import Language, Track, Usage
@@ -104,30 +69,3 @@ def test_a_run_that_scored_nothing_says_so_in_its_row(tmp_path: Path) -> None:
rec.rounds = [judged, rounds[1]]
row = result_from_record(item, rec, ws)
assert row.errors == "" and (row.score_picked, row.picked_round) == (0.6, 0) # one verdict is enough
-
-
-def test_two_bench_run_batteries_pair_by_prompt(tmp_path: Path) -> None:
- """`compare_backends` writes one journal with an arm column; `bench run` writes a
- directory per arm. Two of those directories are a paired comparison, and it must go
- through the same statistics — paired CI, exact sign test, "unsupported when the
- interval crosses zero" — rather than being recomputed by hand."""
- import json as _json
-
- from bench._jsonl import latest
- from bench.paired_compare import paired, rows_from_bench_run
-
- def write(d: Path, scores: dict[str, float]) -> Path:
- d.mkdir(parents=True)
- (d / "results.jsonl").write_text("".join(
- _json.dumps({"id": k, "tier": "hard", "score_final": v, "status": "plateau",
- "cost_usd": 1.0}) + "\n" for k, v in scores.items()))
- return d
-
- a = write(tmp_path / "arm_a", {"p1": 0.6, "p2": 0.4, "p3": 0.5})
- b = write(tmp_path / "arm_b", {"p1": 0.5, "p2": 0.3, "p3": 0.5})
-
- rows = rows_from_bench_run(a, "arm_a") + rows_from_bench_run(b, "arm_b")
- st = paired(latest(rows), "arm_a", "arm_b")
- assert st.n == 3 and st.mean_delta == pytest.approx(0.0667, abs=1e-3)
- assert st.wins == 2 and st.losses == 0 and st.ties == 1
- assert st.verdict == "unsupported" # CI [-0.077, +0.21] crosses zero at n = 3
diff --git a/eval/tests/test_bestofk_report.py b/eval/tests/test_bestofk_report.py
index 455afa78..1d92b4c6 100644
--- a/eval/tests/test_bestofk_report.py
+++ b/eval/tests/test_bestofk_report.py
@@ -1,11 +1,4 @@
-"""``bench/bestofk_report.py``: the compute-matched baseline a harness paper has to answer.
-
-A loop that plans, builds, gates and refines costs ~28x one raw generation on `compare_v4`
-($0.9221 against $0.0327 median generation cost). Spend that on 28 one-shot samples and
-keep the best — does the harness still win? These pin the three things the answer depends
-on: which sample the curve takes, how a maximum over noisy scores is reported, and which
-direction the difference is measured in.
-"""
+"""``bench/bestofk_report.py``: the compute-matched best-of-k baseline — which sample, which k, which sign."""
from __future__ import annotations
@@ -36,8 +29,7 @@ def _rep(root: Path, name: str, scores: dict[str, float | None], *, extra: list[
def test_best_of_takes_the_first_k_and_refuses_to_pad():
- """The reps are independent and unordered, so best-of-k is the best of the FIRST k —
- taking the best of everything available would report best-of-28 as best-of-4."""
+ """Best-of-k is the best of the FIRST k — never of everything available."""
assert best_of([0.1, 0.9, 0.5], 2) == 0.9
assert best_of([0.1, 0.9, 0.5], 3) == 0.9
assert best_of([0.1, 0.9], 3) is None, "fewer samples than k is not a best-of-k"
@@ -45,29 +37,12 @@ def test_best_of_takes_the_first_k_and_refuses_to_pad():
assert best_of([0.1, 0.5, 0.9], 2) == 0.5
-def test_a_rep_that_scored_a_prompt_twice_counts_once(tmp_path: Path):
- """`results.jsonl` is append-only and a resumed cell writes a second row; the last one
- wins, exactly as `paired_compare` dedupes."""
- _rep(tmp_path, "rep01", {"a": 0.2}, extra=[{"prompt_id": "a", "arm": "oneshot:x", "score": 0.7}])
- assert one_shot_samples(tmp_path) == {"a": [0.7]}
-
-
def test_an_unscored_cell_is_dropped_not_zeroed(tmp_path: Path):
- """A cell with no score tests nothing about the model; scoring it 0 would make
- best-of-k look worse for free."""
+ """A cell with no score tests nothing: scoring it 0 would handicap best-of-k."""
_rep(tmp_path, "rep01", {"a": None, "b": 0.4})
assert one_shot_samples(tmp_path) == {"b": [0.4]}
-def test_only_the_harness_arm_is_read_from_the_recorded_battery(tmp_path: Path):
- (tmp_path / "results.jsonl").write_text("\n".join(json.dumps(r) for r in [
- {"prompt_id": "a", "arm": "oneshot:gemini:x", "score": 0.1},
- {"prompt_id": "a", "arm": "harness:api-agent:gemini:x", "score": 0.6},
- {"prompt_id": "b", "arm": "oneshot+repair:gemini:x", "score": 0.3},
- ]))
- assert harness_scores(tmp_path) == {"a": 0.6}
-
-
def test_the_difference_is_harness_minus_baseline_and_the_curse_is_reported():
one = {"a": [0.1, 0.9], "b": [0.2, 0.3]}
harness = {"a": 0.5, "b": 0.5}
@@ -95,13 +70,9 @@ def test_a_prompt_the_harness_never_ran_is_not_paired(tmp_path: Path):
def test_equal_compute_k_is_taken_per_prompt_not_per_row(tmp_path: Path):
- """k is the whole experiment's parameter, and the first pass got it wrong: taking the
- median over every appended row (resumed cells, failed cells) gave 28 where the per-prompt
- basis — the one `paired_compare` pairs on — gives 40. Understating k gives the baseline
- less money than the harness, an error in the harness's favour."""
+ """The median over every appended row gave k=28 where the per-prompt basis gives 40."""
rows = [
- # prompt a: a cheap failed first attempt, then the real one. Per row the median
- # would be dragged down; per prompt only the last row counts.
+ # prompt a: a cheap failed first attempt, then the real one; only the last row counts
{"prompt_id": "a", "arm": "harness:x", "gen_cost_usd": 0.10},
{"prompt_id": "a", "arm": "harness:x", "gen_cost_usd": 2.00},
{"prompt_id": "b", "arm": "harness:x", "gen_cost_usd": 2.00},
@@ -116,8 +87,7 @@ def test_equal_compute_k_is_taken_per_prompt_not_per_row(tmp_path: Path):
def test_a_zero_cost_row_is_not_counted_as_free(tmp_path: Path):
- """A row with no recorded generation cost is missing data, not a free sample; averaging
- it in would inflate k without bound."""
+ """A row with no recorded generation cost is missing data; counting it would inflate k."""
rows = [
{"prompt_id": "a", "arm": "oneshot:x", "gen_cost_usd": 0.05},
{"prompt_id": "b", "arm": "oneshot:x", "gen_cost_usd": 0},
@@ -128,8 +98,7 @@ def test_a_zero_cost_row_is_not_counted_as_free(tmp_path: Path):
def test_the_report_says_when_k_has_not_been_reached(tmp_path: Path):
- """A curve that stops short of equal compute answers a different question, so the table
- says so instead of letting the last row read as the verdict."""
+ """A curve short of equal compute says so, so the last row does not read as the verdict."""
_rep(tmp_path / "reps", "rep01", {"a": 0.2})
(tmp_path / "results.jsonl").write_text("\n".join(json.dumps(r) for r in [
{"prompt_id": "a", "arm": "harness:x", "score": 0.6, "gen_cost_usd": 2.00},
@@ -140,10 +109,7 @@ def test_the_report_says_when_k_has_not_been_reached(tmp_path: Path):
def test_repeated_harness_rows_are_reported_as_duplicates_or_reruns(tmp_path: Path):
- """Whether the aggregation choice can move the comparison is a fact about the data, so
- the report states it. On `compare_v4` the 117 harness rows over 40 prompts have a
- within-prompt spread of exactly 0.000 — they are the same cell written by successive
- report passes, not re-runs — so last-row-wins is safe there."""
+ """The report states whether repeated harness rows are duplicates (spread 0) or real re-runs."""
from bench.bestofk_report import harness_repeat_spread
(tmp_path / "results.jsonl").write_text("\n".join(json.dumps(r) for r in [
diff --git a/eval/tests/test_compare_matrix.py b/eval/tests/test_compare_matrix.py
index 204e69df..0564a5c8 100644
--- a/eval/tests/test_compare_matrix.py
+++ b/eval/tests/test_compare_matrix.py
@@ -18,7 +18,6 @@ from bench._compare_report import ( # noqa: E402
arm_stats,
pair_stats,
)
-from bench._fixed_eval import acceptance_from_spec # noqa: E402
from bench._jsonl import latest, read_jsonl # noqa: E402
from bench.compare_backends import ( # noqa: E402
CompareDeps,
@@ -44,12 +43,6 @@ from tests.conftest import ( # noqa: E402
ARMS = "harness:gemini-cli:gemini-3.6-flash,oneshot:claude-code,oneshot+repair:codex,oneshot:gemini:gemini-3.7-flash"
-def test_battery_compare_v1_is_valid():
- b = Battery.load(BATTERY)
- assert b.name == "compare_v1" and b.track.value == "static_object" and b.language.value == "blender"
- assert all(len(p.must_have) >= 3 for p in b.prompts) # ids, tiers, count: test_bench's corpus contract
-
-
def test_parse_arms():
arms = parse_arms(ARMS)
assert [a.kind for a in arms] == ["harness", "oneshot", "oneshot+repair", "oneshot"]
@@ -70,8 +63,6 @@ def test_spec_for_and_acceptance():
assert harness.backends.generator == "gemini-cli:gemini-3.7-flash" and harness.backends.judge == "gemini:gemini-3.7-flash"
assert harness.budget.max_rounds == 3
assert one.backends.generator == "single-shot:codex" and one.constraints.must_have == b.prompts[0].must_have
- acc = acceptance_from_spec(one)
- assert [a.id for a in acc] == ["must_1", "must_2", "must_3"] and all(a.priority == "must" for a in acc)
def _deps(ev: FakeEvaluator, backends: dict[str, FakeBackend], run_track) -> CompareDeps:
@@ -217,10 +208,7 @@ def test_redo_status_reuses_recorded_answers(tmp_path: Path):
def test_every_cell_and_its_harness_run_open_a_ledger(tmp_path: Path):
- """compare_backends is a run-producing path: its cells must be priced into the
- tree, not into the per-process fallback log (docs/COST.md §12). The harness arm
- gets a nested ledger for its own run; the cell's own ledger holds the spend that
- sits OUTSIDE that run (the fixed evaluator's judge) — the §6 gap."""
+ """Cells are priced into the tree (COST.md §12): the run's own ledger, and the cell's for the fixed judge."""
from codeverse3d.contracts.chat import ChatMessage, ChatRequest
from codeverse3d.cost.instrument import MeteredChatModel
from codeverse3d.cost.ledger import load_ledger
@@ -258,12 +246,7 @@ def test_every_cell_and_its_harness_run_open_a_ledger(tmp_path: Path):
def test_no_resume_starts_the_harness_arm_fresh(tmp_path: Path):
- """`--no-resume` regenerates every other arm, so the harness arm must not resume.
-
- It used to: `_run_harness` only ever asked whether `<cell>/run` existed, so the arm
- that had SUCCEEDED handed back its old score, generated in the old weather, against a
- partner regenerated in today's.
- """
+ """`--no-resume` regenerates every other arm, so the harness arm must not resume either."""
ev = FakeEvaluator()
inner = fake_run_track(0.9)
seen: list[bool] = []
diff --git a/eval/tests/test_complexity_report.py b/eval/tests/test_complexity_report.py
index ecdb1daa..0807b4aa 100644
--- a/eval/tests/test_complexity_report.py
+++ b/eval/tests/test_complexity_report.py
@@ -27,7 +27,6 @@ def _measurement(index: float, parts: int = 8) -> Measurement:
)
-
# ------------------------------------------------------------------ the report
def _write_run(root: Path, slug: str, *, index: float, overall: float, detail: float,
cost: float = 1.0, minutes: float = 10.0) -> Path:
@@ -93,20 +92,6 @@ def test_battery_expectations_flag_out_of_band_runs(tmp_path: Path) -> None:
assert "not run" in table # a prompt with no run is still listed
-def test_real_battery_bands_are_sane() -> None:
- """complexity_v3 is the ladder: every band inside [0,1], ordered, and the
- prompts must actually climb."""
- import yaml
-
- data = yaml.safe_load((REPO / "bench" / "prompts" / "complexity_v3.yaml").read_text())
- bands = [(p["id"], p["expected_complexity"]) for p in data["prompts"]]
- assert len(bands) == 12
- for pid, (lo, hi) in bands:
- assert 0.0 < lo < hi <= 1.0, pid
- lows = [lo for _, (lo, _hi) in bands]
- assert lows == sorted(lows) and lows[-1] > lows[0] + 0.3
-
-
def test_row_recomputes_the_vector_when_the_record_has_none(tmp_path: Path) -> None:
"""The historic corpus predates the vector: the report must fall back to the
GLB rather than skipping the run."""
diff --git a/eval/tests/test_degraded.py b/eval/tests/test_degraded.py
index 9348dd28..62487c36 100644
--- a/eval/tests/test_degraded.py
+++ b/eval/tests/test_degraded.py
@@ -1,9 +1,4 @@
-"""compare_backends.flag_degraded: a harness run that waited on the provider is flagged, not trusted.
-
-compare_v4 (2026-08-25): 37 of 40 harness runs stopped on the 45-minute wall-clock ceiling with
-0–2 completed rounds during a flash 503 storm; the 3 runs that met a calm window did 2–4 rounds
-in 27–40 min and scored 0.92–0.95. A paired mean over the stormed cells measures the weather.
-"""
+"""compare_backends.flag_degraded: a harness run that waited on the provider is flagged, not trusted."""
from __future__ import annotations
@@ -16,7 +11,7 @@ REPO = Path(__file__).resolve().parents[1]
if str(REPO) not in sys.path:
sys.path.insert(0, str(REPO))
-from bench._compare_report import CellResult, arm_stats, compare_markdown # noqa: E402
+from bench._compare_report import CellResult # noqa: E402
from bench.compare_backends import ( # noqa: E402
CompareDeps,
CompareOptions,
@@ -45,9 +40,7 @@ def _track(status: RunStatus, stop_reason: str, rounds: int, cost: float, aborte
@pytest.mark.parametrize("status,stop,rounds,cost,aborted,expect", [
(RunStatus.BUDGET, "budget", 1, 1.2, 1, True), # the storm case: clock stop after 1 round
- (RunStatus.BUDGET, "budget", 0, 0.9, 1, True), # never completed a round
(RunStatus.BUDGET, "budget", 2, 1.5, 1, False), # iterated twice: cut, but not degraded
-
(RunStatus.MAX_ROUNDS, "max_rounds", 1, 0.8, 0, False), # ran every round it was given: fine
])
def test_flag_degraded_rule(tmp_path, status, stop, rounds, cost, aborted, expect):
@@ -71,20 +64,3 @@ def test_degraded_needs_the_wall_clock_floor():
r.wall_s = 45 * 60
flag_degraded(r, CompareOptions(judge="g:x"))
assert r.degraded
-
-
-def test_report_counts_and_marks_degraded_cells(tmp_path):
- rows = [
- CellResult(prompt_id="p0", tier="hard", arm="harness:x", kind="harness", status="scored", score=0.5,
- build_ok=True, degraded=True, degraded_reason="ceiling stop after 0 completed round(s) in 45 min",
- harness_stop_reason="budget", harness_aborted_rounds=1),
- CellResult(prompt_id="p1", tier="hard", arm="harness:x", kind="harness", status="scored", score=0.9,
- build_ok=True, harness_stop_reason="pass"),
- CellResult(prompt_id="p0", tier="hard", arm="oneshot:x", kind="oneshot", status="scored", score=0.4, build_ok=True),
- CellResult(prompt_id="p1", tier="hard", arm="oneshot:x", kind="oneshot", status="scored", score=0.3, build_ok=True),
- ]
- st = {s.arm: s for s in arm_stats(rows)}
- assert st["harness:x"].degraded == 1 and st["harness:x"].ceiling_cut == 1 and st["oneshot:x"].degraded == 0
- md = compare_markdown(tmp_path, rows, [], {"options": {}, "battery": {"name": "t"}})
- assert "| degraded | cut |" in md and "0.50†" in md and "0.90 |" in md
- assert "ceiling stop after 0 completed round(s)" in md
diff --git a/eval/tests/test_infra_failures.py b/eval/tests/test_infra_failures.py
index 6f1d5a08..f7f6c938 100644
--- a/eval/tests/test_infra_failures.py
+++ b/eval/tests/test_infra_failures.py
@@ -1,10 +1,4 @@
-"""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.
-"""
+"""A provider outage must never be scored as a model failure (compare_v2, 2026-08-24)."""
from __future__ import annotations
@@ -36,15 +30,9 @@ MODEL_FAILURES = [
]
[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
[email protected]("err, infra", [(e, True) for e in OUTAGES] + [(e, False) for e in MODEL_FAILURES])
+def test_outages_are_infra_and_capability_failures_keep_their_zero(err, infra):
+ assert is_infra_failure(err) is infra
class ModelError(Exception):
@@ -55,8 +43,7 @@ class ModelError(Exception):
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."""
+ """A .status that raises: the cheapest stand-in for any classifier bug."""
@property
def status(self):
raise RecursionError("cycle")
@@ -82,18 +69,7 @@ def test_structured_exceptions_beat_string_matching():
def test_both_failure_paths_classify_the_same_way(tmp_path):
- """CQ-1, the asymmetry itself: ONE error hits both arms, both must reach one verdict.
-
- The previous version of this test could not fail — it grepped run_cell's code
- constants for the literal "infra_failed" and then compared a single 503 string that
- DOES contain one of the 14 INFRA_MARKERS. It therefore passed straight through the
- real bug: gemini's actual 500 prose ("An internal error has occurred") matches no
- marker, and bench/_oneshot.py stringified the exception into `notes`, throwing away
- the .status the harness path classifies on. Same outage, harness dropped
- (infra_failed / score None), one-shot scored a hard 0.0 — biasing every
- harness-vs-one-shot mean in the harness's favour, which is precisely what this
- module was written to end.
- """
+ """CQ-1: one outage hits both arms and both reach one verdict — gemini's 500 prose matches no marker."""
from bench._oneshot import ApiOneShot
from bench.compare_backends import CompareDeps, CompareOptions, parse_arm, run_cell
from bench.run_bench import Battery
@@ -124,14 +100,12 @@ def test_both_failure_paths_classify_the_same_way(tmp_path):
for i, outage in enumerate((
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, tmp_path / str(i))
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 "
- f"zero for the same downtime that drops the harness arm")
+ f"one error, two verdicts for {outage!s}: {got}")
+
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."""
@@ -182,11 +156,7 @@ def test_preflight_probes_only_models_the_selected_arms_need(monkeypatch, raw_ar
def test_a_repair_lost_to_an_outage_drops_the_cell_instead_of_scoring_the_pre_repair_code(tmp_path):
- """compare_v4, 2026-08-25: four `oneshot+repair` cells whose repair call died in a 503
- storm were recorded build_failed / score 0 — the broken attempt-0 file was already in
- the eval workspace, so the arm was scored on code its protocol had not finished with.
- A truncated one-shot protocol is downtime, not a capability result: infra_failed, and
- --redo-status re-runs only the lost attempt (attempt 0 is cached)."""
+ """A repair call lost to a 503 is downtime, not a score on the unfinished attempt-0 code (compare_v4)."""
from bench._oneshot import OneShotResult
from bench.compare_backends import CompareDeps, CompareOptions, parse_arm, run_cell
from bench.run_bench import Battery
@@ -231,10 +201,7 @@ def test_a_repair_lost_to_an_outage_drops_the_cell_instead_of_scoring_the_pre_re
def test_a_harness_planning_failure_is_a_zero_not_a_dropped_cell(tmp_path):
- """compare_art_v2 (2026-08-25): 5 of 14 articulated harness runs raised PlanningError (the
- plan failed validation twice) and were recorded `error` / score None — dropped from the
- mean, so a third of the harness's failures vanished. The harness delivered nothing by its
- own doing: no_code / 0.0, exactly what a one-shot answer in the wrong format gets."""
+ """PlanningError is the harness's own failure: no_code / 0.0, never dropped (compare_art_v2)."""
from bench.compare_backends import CompareDeps, CompareOptions, parse_arm, run_cell
from bench.run_bench import Battery
from codeverse3d.tracks.planner import PlanningError
@@ -252,19 +219,10 @@ def test_a_harness_planning_failure_is_a_zero_not_a_dropped_cell(tmp_path):
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."""
- # 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`
+ """retry.py's `raise e from e` closes the __cause__ chain into a cycle (compare_art_v3)."""
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 # a two-node cycle
- assert is_infra_failure(a) is False
c = ModelError("wrapped")
c.__cause__ = ModelError("upstream said no", status=503)
c.__cause__.__cause__ = c # cycle through an infra cause
diff --git a/eval/tests/test_oneshot.py b/eval/tests/test_oneshot.py
index cc1545a3..4dc00d0a 100644
--- a/eval/tests/test_oneshot.py
+++ b/eval/tests/test_oneshot.py
@@ -21,12 +21,9 @@ from bench._oneshot import ( # noqa: E402
extract_files,
extract_model_file,
files_for,
- get_oneshot_backend,
minimal_contract,
oneshot_prompt,
- repair_prompt,
)
-from codeverse3d.contracts.artifacts import BuildResult, GateReport # noqa: E402
from codeverse3d.contracts.common import Language, Track # noqa: E402
from codeverse3d.contracts.spec import Constraints, Spec # noqa: E402
from codeverse3d.tracks.generation import MultiFileParseError # noqa: E402
@@ -46,15 +43,22 @@ def test_prompt_is_brief_plus_minimal_contract_only():
assert minimal_contract() in p and p.rstrip().endswith("no partial snippets).")
-def test_repair_prompt_carries_error_and_previous_code():
- build = BuildResult(ok=False, language="blender", error_type="NameError", error_message="name 'foo' is not defined",
- error_file=MODEL_FILE, error_line=7)
- p = repair_prompt(_spec(), "import bpy\nfoo()\n", build, GateReport(gate="lint:blender", passed=True), attempt=1)
- assert "BUILD FAILED" in p and "NameError" in p and "foo()" in p and "previous attempt (1)" in p
[email protected]("spec, opening, needed, harness_only", [
+ (Spec(id="t/harbour", track=Track.SCENE, language=Language.SCENE_THREEJS, prompt="a fishing harbour at dusk"),
+ "Build this scene in raw three.js: a fishing harbour at dusk",
+ (SCENE_FILE, "createScene", "three/addons/*", "scene.fog", "```js"), ("src/lib", "zones/", "public/assets")),
+ (Spec(id="t/aurora", track=Track.GRAPHICS, language=Language.GLSL_SHADER, prompt="an aurora over snow"),
+ "Write this as a Shadertoy-style fragment shader: an aurora over snow",
+ (SHADER_FILE, "mainImage", "u_time", "#version 330 core", "```glsl"), ("recipes.glsl", "buffer_a")),
+])
+def test_scene_and_shader_prompts_are_their_contract_and_nothing_of_the_harness(spec, opening, needed, harness_only):
+ p = oneshot_prompt(spec)
+ assert p.startswith(opening) and minimal_contract(spec.language) in p
+ assert all(s in p for s in needed) and "cookbook" not in p.lower()
+ assert not any(s in p for s in harness_only)
@pytest.mark.parametrize("text", [
- "```python\nimport bpy\nprint(1)\n```",
"Here you go:\n```python\nimport bpy\nprint(1)\n```\nDone.",
"=== FILE: src/model.py ===\nimport bpy\nprint(1)\n=== END FILE ===",
"import bpy\nprint(1)\n",
@@ -97,17 +101,6 @@ def test_codex_oneshot_forces_a_reasoning_effort(tmp_path: Path):
assert "model_reasoning_effort" not in " ".join(plain)
-def test_registry():
- assert isinstance(get_oneshot_backend("claude-code"), ClaudeOneShot)
- assert get_oneshot_backend("claude-code:sonnet").model == "sonnet"
- assert isinstance(get_oneshot_backend("codex"), CodexOneShot)
- api = get_oneshot_backend("gemini:gemini-3.7-flash")
- assert isinstance(api, ApiOneShot) and api.id == "oneshot:gemini:gemini-3.7-flash"
- for bad in ("gemini", "gemini-cli:x", "", "anthropic:"):
- with pytest.raises(ValueError):
- get_oneshot_backend(bad)
-
-
def test_api_oneshot_uses_injected_chat_model(tmp_path: Path):
class M:
def generate(self, req):
@@ -130,42 +123,6 @@ def test_api_oneshot_model_error_is_recorded(tmp_path: Path):
assert not r.ok and "quota" in r.notes
-def test_extract_model_file_from_hallucinated_write_tool_xml():
- text = ('<invoke name="Write">\n<parameter name="file_path">/tmp/x/src/model.py</parameter>\n'
- '<parameter name="content">import bpy\nprint(2)\n</parameter>\n</invoke>\n\nsyntax ok\n')
- assert extract_model_file(text) == "import bpy\nprint(2)\n"
-
-
-# --------------------------------------------------------------------------- scene + graphics (2026-09-07)
-def _scene_spec() -> Spec:
- return Spec(id="t/harbour", track=Track.SCENE, language=Language.SCENE_THREEJS, prompt="a fishing harbour at dusk",
- constraints=Constraints(must_have=["at least 3 boats", "lit windows"]))
-
-
-def _glsl_spec() -> Spec:
- return Spec(id="t/aurora", track=Track.GRAPHICS, language=Language.GLSL_SHADER, prompt="an aurora over snow",
- constraints=Constraints(must_have=["curtains that move"]))
-
-
-def test_scene_prompt_is_the_createscene_contract_and_nothing_of_the_harness():
- """The bare baseline for the scene track: ONE src/scene.js against the createScene shape and
- the import rule — no starter lib, no zones, no cookbook, no assets, no gates table."""
- p = oneshot_prompt(_scene_spec())
- assert p.startswith("Build this scene in raw three.js: a fishing harbour at dusk")
- assert "MUST HAVE: at least 3 boats" in p and SCENE_FILE in p and "createScene" in p
- assert "three/addons/*" in p and "scene.fog" in p and "lookAt" in p and "```js" in p
- assert "cookbook" not in p.lower() and "src/lib" not in p and "zones/" not in p and "public/assets" not in p
- assert minimal_contract(Language.SCENE_THREEJS) in p and p.rstrip().endswith("no partial snippets).")
-
-
-def test_glsl_prompt_is_the_shader_contract_and_nothing_of_the_harness():
- p = oneshot_prompt(_glsl_spec())
- assert p.startswith("Write this as a Shadertoy-style fragment shader: an aurora over snow")
- assert SHADER_FILE in p and "mainImage" in p and "u_time" in p and "#version 330 core" in p and "```glsl" in p
- assert "recipes.glsl" not in p and "cookbook" not in p.lower() and "buffer_a" not in p
- assert minimal_contract(Language.GLSL_SHADER) in p
-
-
def test_single_file_answers_are_extracted_under_their_own_entry():
js = "import * as THREE from 'three';\nexport async function createScene({ THREE }) { return {}; }"
assert extract_files(f"Here you go:\n```js\n{js}\n```\n", Language.SCENE_THREEJS) == {SCENE_FILE: js + "\n"}
diff --git a/eval/tests/test_pin_plan.py b/eval/tests/test_pin_plan.py
index 5dddf584..7f861a47 100644
--- a/eval/tests/test_pin_plan.py
+++ b/eval/tests/test_pin_plan.py
@@ -1,9 +1,4 @@
-"""Sharing one plan between A/B arms (bench/pin_plan.py + the rule that permits it).
-
-docs/EVAL.md §8.1: the A/A's worst pair planned 1 part in one arm and 10 in the other on
-IDENTICAL settings. Pinning removes that term; pinning the wrong switch deletes the
-experiment. Both halves are tested here.
-"""
+"""Sharing one plan between A/B arms (bench/pin_plan.py), and the rule that permits it (EVAL.md §8.1)."""
from __future__ import annotations
@@ -12,7 +7,7 @@ from pathlib import Path
import pytest
-from bench.pin_plan import PinError, plan_artifacts, seed_plan
+from bench.pin_plan import PinError, seed_plan
def _planned_run(root, *, parts, inputs_hash="abc123"):
@@ -30,26 +25,8 @@ def _planned_run(root, *, parts, inputs_hash="abc123"):
return run
-def test_the_target_resumes_from_the_source_plan(tmp_path):
- src = _planned_run(tmp_path, parts=10)
- dst = tmp_path / "dst_run"
- (dst / "stages").mkdir(parents=True)
- (dst / "run_state.json").write_text(json.dumps({"status": "created", "stages": {}}))
-
- got = seed_plan(src, dst)
- assert got == "abc123"
-
- dst_plan, dst_stage, dst_state = plan_artifacts(dst)
- assert json.loads(dst_plan.read_text())["parts"] == json.loads((src / "plan.json").read_text())["parts"]
- assert dst_stage.is_file(), "the stage cache result must exist or the stage is a MISS"
- entry = json.loads(dst_state.read_text())["stages"]["plan"]
- assert entry["inputs_hash"] == "abc123", "the hash is what makes it a cache hit"
- assert entry["result_path"] == str(dst_stage.resolve()), "must point at the TARGET's file"
-
-
def test_the_targets_own_state_survives(tmp_path):
- """Only the plan stage crosses over — status, rounds and other stages are the
- target's own, or seeding would import the source run's history."""
+ """Only the plan stage crosses over, pointing at the TARGET's file; the rest of the state is the target's."""
src = _planned_run(tmp_path, parts=3)
dst = tmp_path / "dst_run"
(dst / "stages").mkdir(parents=True)
@@ -60,7 +37,8 @@ def test_the_targets_own_state_survives(tmp_path):
state = json.loads((dst / "run_state.json").read_text())
assert state["status"] == "created" and state["current_round"] == 0
assert state["stages"]["skeleton"]["inputs_hash"] == "zzz", "the target's other stages were dropped"
- assert "plan" in state["stages"]
+ assert state["stages"]["plan"]["inputs_hash"] == "abc123"
+ assert state["stages"]["plan"]["result_path"] == str((dst / "stages" / "plan.json").resolve())
def test_an_unplanned_source_is_refused_by_name(tmp_path):
@@ -70,8 +48,7 @@ def test_an_unplanned_source_is_refused_by_name(tmp_path):
def test_a_source_without_a_cached_stage_is_refused(tmp_path):
- """plan.json on disk but no stage entry: the target would re-plan and the pair would
- silently stop being pinned — worse than not pinning, because the report would claim it."""
+ """plan.json but no stage entry: the target would silently re-plan while the report claims a pin."""
src = _planned_run(tmp_path, parts=4)
(src / "run_state.json").write_text(json.dumps({"status": "generating", "stages": {}}))
dst = tmp_path / "dst_run"
@@ -81,49 +58,10 @@ def test_a_source_without_a_cached_stage_is_refused(tmp_path):
# --------------------------------------------------------------- the driver's use of it
-def test_pin_pair_seeds_every_arm_from_one_plan(tmp_path, monkeypatch):
- """``--pin-plan`` must plan ONCE and hand the same plan to both arms.
-
- Planning per-arm is what the pinning exists to remove; planning per-arm *while
- reporting itself pinned* is worse than not pinning at all, so the count is asserted.
- """
- from bench import ab_plan
- from bench.run_bench import Battery
-
- battery = Battery.load(Path(ab_plan.__file__).resolve().parent / "prompts" / "compare_v1.yaml")
- item = battery.prompts[0]
- opts = ab_plan.AbOptions(variant_env={"C3D_SKILLS": "0"}, pin_plan=True) # the skills-OFF arm
- calls: list[Path] = []
-
- def fake_plan_once(spec, ws_root):
- calls.append(Path(ws_root))
- run = Path(ws_root)
- (run / "stages").mkdir(parents=True, exist_ok=True)
- body = json.dumps({"object_name": "Chair", "parts": [{"name": "Seat"}]})
- (run / "plan.json").write_text(body)
- (run / "stages" / "plan.json").write_text(body)
- (run / "run_state.json").write_text(json.dumps(
- {"stages": {"plan": {"name": "plan", "inputs_hash": "h1",
- "result_path": str(run / "stages" / "plan.json")}}}))
- return "h1"
-
- monkeypatch.setattr(ab_plan, "plan_once", fake_plan_once)
- got = ab_plan.pin_pair(battery, item, tmp_path, list(ab_plan.ARMS), opts)
-
- assert got == "h1"
- assert len(calls) == 1, f"planned {len(calls)} times, not once: {calls}"
- for arm in ab_plan.ARMS:
- run = Path(ab_plan.cell_dir(tmp_path, arm, item.id, opts.generator)) / "run"
- assert json.loads((run / "plan.json").read_text())["parts"] == [{"name": "Seat"}]
- entry = json.loads((run / "run_state.json").read_text())["stages"]["plan"]
- assert entry["inputs_hash"] == "h1"
- assert entry["result_path"] == str((run / "stages" / "plan.json").resolve())
- assert (run / "spec.json").is_file(), "_run_harness skips writing it once the ws exists"
def test_pin_pair_reuses_the_plan_when_the_pair_is_retried(tmp_path, monkeypatch):
- """A resumed / redone pair must not buy a second plan — and must not get a DIFFERENT
- one, which would make the two attempts incomparable."""
+ """--pin-plan plans ONCE, seeds every arm, and a retried pair neither re-plans nor gets another plan."""
from bench import ab_plan
from bench.run_bench import Battery
@@ -146,17 +84,20 @@ def test_pin_pair_reuses_the_plan_when_the_pair_is_retried(tmp_path, monkeypatch
return "h1"
monkeypatch.setattr(ab_plan, "plan_once", fake_plan_once)
- ab_plan.pin_pair(battery, item, tmp_path, list(ab_plan.ARMS), opts)
+ assert ab_plan.pin_pair(battery, item, tmp_path, list(ab_plan.ARMS), opts) == "h1"
ab_plan.pin_pair(battery, item, tmp_path, list(ab_plan.ARMS), opts)
assert n == 1, "the second pass re-planned; the retry would not be comparable"
- run = Path(ab_plan.cell_dir(tmp_path, "variant", item.id, opts.generator)) / "run"
- assert json.loads((run / "plan.json").read_text())["parts"] == [{"name": "call1"}]
+ for arm in ab_plan.ARMS:
+ run = Path(ab_plan.cell_dir(tmp_path, arm, item.id, opts.generator)) / "run"
+ assert json.loads((run / "plan.json").read_text())["parts"] == [{"name": "call1"}]
+ entry = json.loads((run / "run_state.json").read_text())["stages"]["plan"]
+ assert entry["inputs_hash"] == "h1" and entry["result_path"] == str((run / "stages" / "plan.json").resolve())
+ assert (run / "spec.json").is_file(), "_run_harness skips writing it once the ws exists"
def test_a_plan_side_variant_env_is_refused_by_the_cli():
- """Pinning a plan-side switch deletes the thing under test, and the rig would then
- report 'no effect' with confidence. The refusal is the whole safety property."""
+ """Pinning a plan-side switch deletes the thing under test: the CLI refuses."""
from bench import ab_plan
with pytest.raises(SystemExit):
diff --git a/eval/tests/test_plan_stage.py b/eval/tests/test_plan_stage.py
index 3a00dde2..d62d72de 100644
--- a/eval/tests/test_plan_stage.py
+++ b/eval/tests/test_plan_stage.py
@@ -1,7 +1,4 @@
-"""The loss-event channel's arithmetic: the p-value a paper cites is computed here.
-
-``bench/data/plan_stage/*.jsonl`` carries the 560 recorded plan calls behind D52; this
-pins the statistic that turns them into 0.0067, and the report that prints it."""
+"""The plan-stage report: the Fisher p-value D52 cites and the readouts computed from the recorded calls."""
from __future__ import annotations
@@ -16,14 +13,9 @@ from bench.plan_stage_report import failure_class, fisher_exact, outcome, report
DATA = Path(__file__).resolve().parents[1] / "bench" / "data" / "plan_stage"
-def test_fisher_exact_reproduces_the_number_d52_cites() -> None:
- assert round(fisher_exact(13, 264, 2, 274), 4) == 0.0067
-
-
@pytest.mark.parametrize("table,expected", [
- ((0, 100, 0, 100), 1.0), # nothing happened in either arm
+ ((13, 264, 2, 274), 0.0067), # the number D52 cites
((5, 95, 5, 95), 1.0), # identical arms
- ((10, 90, 0, 100), 0.00154), # a difference this size at n=100 is not noise
((1, 9, 8, 2), 0.0055), # the textbook 2x2, small and lopsided
])
def test_fisher_exact_against_known_tables(table, expected) -> None:
@@ -40,10 +32,7 @@ def test_the_recorded_arms_still_read_out_the_way_d52_says() -> None:
def test_the_failure_class_split_the_re_measurement_reports_is_computed_here() -> None:
- """The 2026-09-03 three-arm readout turns on a CLASS, not the total: the restart only
- ever addresses a plan that references links it never lists. That split was derived by
- hand for the first write-up; it is the report's job, and this pins the number the docs
- quote."""
+ """The 2026-09-03 three-arm readout turns on a failure CLASS; this pins the number the docs quote."""
arms = {p.stem.replace("trigger_", ""): [json.loads(x) for x in p.read_text().splitlines() if x.strip()]
for p in sorted(DATA.glob("trigger_*.jsonl"))}
assert set(arms) == {"narrow", "off", "wide"}
@@ -64,10 +53,7 @@ def test_the_failure_class_split_the_re_measurement_reports_is_computed_here() -
def test_a_harness_side_death_is_a_loss_not_provider_weather() -> None:
- """``provider`` drops a row from the denominator, so it has to name the provider
- failures rather than catch everything that is not a PlanningError. A budget ceiling
- and a harness exception are losses of the run: trigger_narrow carries one
- BudgetExceeded row, and classing it as weather would have hidden it."""
+ """``provider`` leaves the denominator, so a budget ceiling or harness exception must stay a loss."""
rows = [json.loads(x) for x in (DATA / "trigger_narrow.jsonl").read_text().splitlines() if x.strip()]
budget = [r for r in rows if "BudgetExceeded" in r.get("error", "")]
assert len(budget) == 1
@@ -78,8 +64,7 @@ def test_a_harness_side_death_is_a_loss_not_provider_weather() -> None:
def test_a_killed_arm_file_still_reports(tmp_path: Path, capsys) -> None:
- """The report's loader parsed every line strictly: the half-written row a killed
- ``plan_stage_bench`` leaves made the whole arm unreadable."""
+ """A half-written last row from a killed bench does not make the arm unreadable."""
from bench.plan_stage_report import main
arm = tmp_path / "arm.jsonl"
diff --git a/eval/tests/test_replay.py b/eval/tests/test_replay.py
index 6eac28cd..ea6832c5 100644
--- a/eval/tests/test_replay.py
+++ b/eval/tests/test_replay.py
@@ -1,11 +1,4 @@
-"""``bench/rejudge_offline.replay_round`` reproduces a stored verdict from its samples.
-
-The tool's own acceptance test: a Judgment built by ``aggregate_samples`` from two synthetic
-samples and a gate set, written as ``rounds/r00.json`` + ``plan.json``, must replay to the
-same ``overall`` within 1e-9, carry the ``scoring_version`` that wrote it, and expose the
-veto's ``overridden`` list from ``raw`` (the 4ddde32 tool parsed the verdict tail for a
-phrase it never contained and reported no vetoes at all).
-"""
+"""``bench/rejudge_offline.replay_round`` reproduces a stored verdict from its samples, version and vetoes included."""
from __future__ import annotations
@@ -117,20 +110,13 @@ def test_identity_holds_same_version_verdicts_and_reports_older_ones_as_drift(tm
assert "identity OK: 1 of 1" in capsys.readouterr().out
-def test_identity_is_dormant_on_a_pre_stamp_corpus(tmp_path, capsys):
- """Every verdict on disk today is version 0 (written before the stamp): the guard must not print green."""
+def test_a_verdict_written_before_the_stamp_reads_as_version_0(tmp_path):
j = aggregate_samples(R, [_sample(0.9)], gates=GATES, acceptance_items=ITEMS)
raw = json.loads(j.raw)
raw.pop("scoring_version", None)
_write_round(tmp_path, j.model_copy(update={"raw": json.dumps(raw)}))
assert ro.replay_corpus([tmp_path], rubric_name=R.name).rows[0].scoring_version_stored == 0
- assert ro.main([str(tmp_path), "--rubric", R.name, "--identity"]) == 2
- out = capsys.readouterr()
- assert "identity OK" not in out.out
- assert "WARNING: identity guard is DORMANT" in out.err and "1 under an older scoring version" in out.err
- assert ro.main([str(tmp_path), "--rubric", R.name, "--identity", "--allow-empty-identity"]) == 0
-
def test_a_round_without_a_judged_sample_is_skipped(tmp_path):
assert ro.replay_round(_write_round(tmp_path, None)) is None
diff --git a/eval/tests/test_scene_regate.py b/eval/tests/test_scene_regate.py
index b6a8d332..9878ce1c 100644
--- a/eval/tests/test_scene_regate.py
+++ b/eval/tests/test_scene_regate.py
@@ -1,12 +1,4 @@
-"""``bench/scene_regate.py``: re-running a gate over recorded workspaces.
-
-The parts that decide whether the diff means anything, pinned without a browser.
-Both were wrong on the first run of this script over `bench/out/scene_baseline`:
-the layouts envelope was passed through unopened, so `contract_findings` lost its
-basis and coastal_village's REAL "zone VillageQuay holds ~179 instances but its
-layout budgeted 443" appeared in the GONE column as though the gate change had
-removed it.
-"""
+"""``bench/scene_regate.py``: re-running a gate over recorded workspaces, pinned without a browser."""
from __future__ import annotations
diff --git a/eval/tests/test_scene_stats.py b/eval/tests/test_scene_stats.py
index fae66625..a26b79d3 100644
--- a/eval/tests/test_scene_stats.py
+++ b/eval/tests/test_scene_stats.py
@@ -1,12 +1,4 @@
-"""``bench/scene_stats.py``: a gate finding that names a dead browser is the machine.
-
-Measured on `bench/out/scene_baseline` (2026-09-05): three of six scene cells built,
-passed every gate that does not need pixels, and then kept ZERO renders because Chrome
-reaped the tab under a box at load 93 with swap full. Each one left a `render_console`
-ERROR reading "driver: Attempted to use detached Frame '<id>'". Counted as a gate
-failure, that reads as a defective generator; the layer attribution the scene battery
-exists to produce is then wrong for half its cells.
-"""
+"""``bench/scene_stats.py``: a gate finding that names a dead browser is the machine, not a defect (2026-09-05)."""
from __future__ import annotations
@@ -49,17 +41,8 @@ def test_a_dead_browser_is_counted_apart_from_a_defect(tmp_path: Path) -> None:
assert g["rounds_lost_to_the_box"] == 1
-def test_a_round_that_kept_its_browser_reports_no_loss(tmp_path: Path) -> None:
- _run(tmp_path, "clean", [_gate("render_console", True, []),
- _gate("scene_frames", False, ["frame too dark: mean luminance 0.13"])])
- d = layers(runs(tmp_path))
- assert d["gates"]["rounds_lost_to_the_box"] == 0
- assert d["gates"]["scene_frames:FAILED"] == 1 and d["gate_errors"]["scene_frames"] == 1
-
-
def test_a_gate_that_failed_ONLY_on_the_browser_is_not_a_failure(tmp_path: Path) -> None:
- """`scene_frames` fails when it has no frames to look at. With the renders lost
- that is the same event reported twice, not a second defect."""
+ """`scene_frames` with no frames to look at is the same browser loss reported twice."""
_run(tmp_path, "both", [_gate("render_console", False, [DETACHED]),
_gate("scene_frames", False, ["render produced no result: " + DETACHED])])
d = layers(runs(tmp_path))
@@ -68,10 +51,7 @@ def test_a_gate_that_failed_ONLY_on_the_browser_is_not_a_failure(tmp_path: Path)
def test_the_median_score_is_read_off_the_real_Judgment_shape(tmp_path: Path) -> None:
- """`Judgment` has `overall`, never `score`. The script read `score`, so on every real
- record the median line was silently skipped — and no test caught it, because the
- fixtures wrote `judgment: {}`. Building the fixture from the model itself is what
- stops that drifting again."""
+ """The fixture is built from `Judgment` itself: the script once read `score`, which it never has."""
from codeverse3d.contracts.artifacts import Judgment
def judged(name: str, overall: float) -> None:
@@ -92,21 +72,6 @@ def test_the_median_score_is_read_off_the_real_Judgment_shape(tmp_path: Path) ->
assert "scored rounds: 2" in text and "median 0.400" in text
-def test_two_runs_of_one_prompt_do_not_break_the_walk(tmp_path: Path) -> None:
- """A battery with reps records the same prompt id twice. `runs` used to sort the
- (id, record, events) tuples bare, which on a tied id compares two dicts and raises;
- the report never printed for exactly the batteries with enough runs to be worth one."""
- for rep in ("r0", "r1"):
- d = tmp_path / "scn_garden" / rep
- d.mkdir(parents=True)
- (d / "record.json").write_text(json.dumps({
- "spec": {"track": "scene", "id": "scenes_v1/scn_garden"},
- "plan": {"assets": []}, "rounds": [],
- }))
- rows = runs(tmp_path)
- assert [r[0] for r in rows] == ["scn_garden", "scn_garden"]
-
-
def test_the_build_layer_is_attributed(tmp_path: Path) -> None:
"""Between assembly and the gates sits the build: a harness retry and an agent repair
are different defects (`tracks/repair.build_with_repair`), and a survey that skips the
diff --git a/eval/tests/test_session_stats.py b/eval/tests/test_session_stats.py
index c50bfa95..b21b262b 100644
--- a/eval/tests/test_session_stats.py
+++ b/eval/tests/test_session_stats.py
@@ -1,8 +1,4 @@
-"""``bench/session_stats.py``: the tool-error / cache / cost view a battery is read through.
-
-The numbers docs/COST.md §30 reports came from this view computed by hand, and the
-after-side counts were inflated by the ``run/telemetry/trajectories`` symlink — the very
-trap that section warns about. These tests pin the parsing and the dedupe."""
+"""``bench/session_stats.py``: the tool-error / cache / cost view a battery is read through (COST.md §30)."""
from __future__ import annotations
@@ -32,18 +28,6 @@ def _run(root: Path, name: str, costs: list[float]) -> Path:
return run
-def test_the_telemetry_symlink_is_counted_once(tmp_path: Path) -> None:
- run = _run(tmp_path, "cell_a", [1.0, 2.0])
- _session(run, "baseline_r00", tools={"build": (10, 1)}, prompt=1000, cached=700, requests=5)
- (run / "telemetry").mkdir()
- (run / "telemetry" / "trajectories").symlink_to(run / "trajectories", target_is_directory=True)
-
- assert len(_sessions(tmp_path)) == 1 # not 2, though both paths exist
- calls, failed = tool_rates(_sessions(tmp_path))
- assert calls["build"] == 10 and failed["build"] == 1 # doubling here is what corrupted §30
- assert token_rates(_sessions(tmp_path))["requests"] == 5
-
-
def test_rates_and_costs_over_two_sessions(tmp_path: Path) -> None:
run = _run(tmp_path, "cell_a", [1.0, 3.0, 5.0])
_session(run, "baseline_r00", tools={"build": (10, 0), "joint_sweep": (4, 2)},
@@ -59,9 +43,7 @@ def test_rates_and_costs_over_two_sessions(tmp_path: Path) -> None:
def test_a_killed_session_is_counted_as_killed_not_as_a_session(tmp_path: Path) -> None:
- """An empty stdout.json is the CLI dying before it printed its stats. Counting it as a
- session makes every per-session number smaller for a reason that has nothing to do with
- the code under test — 102 of aa_articulated's 162 files are that."""
+ """An empty stdout.json is a CLI killed before its stats: killed, not a session — and never doubled."""
from bench.session_stats import _killed
run = _run(tmp_path, "cell_a", [2.0])
@@ -80,9 +62,7 @@ def test_a_killed_session_is_counted_as_killed_not_as_a_session(tmp_path: Path)
def test_a_sub_workspace_is_not_the_battery_cell_above_it(tmp_path: Path) -> None:
- """A scene asset's own run lives under ``_cand/`` / ``_assets/`` with its own
- trajectories; ``flywheel.record.find_runs`` skips those and so must this, or one cell's
- numbers absorb every candidate it rejected."""
+ """A candidate's own run under ``_cand/`` is not the cell's, as in ``find_runs``."""
run = _run(tmp_path, "cell_a", [1.0])
_session(run, "baseline_r00", tools={"build": (2, 0)}, prompt=100, cached=50, requests=1)
sub = run / "_cand" / "c1" / "run"
@@ -144,10 +124,7 @@ def test_the_coupling_survey_also_reads_the_gate_that_judges_the_poses(tmp_path:
def test_the_coupling_survey_counts_runs_not_copies_of_the_same_urdf(tmp_path: Path) -> None:
- """A run holds robot.urdf three times — src/ (written), artifacts/ (built) and
- deliverable/ (finalised) — and `bench run` lays cells out as runs/<id>/, not
- cells/<id>/. Counting files tripled every mechanical number and named every prompt
- "artifacts"."""
+ """A run holds robot.urdf in src/, artifacts/ and deliverable/: one per run, the built one."""
from bench._records import prompt_of
from bench.coupling_stats import _urdfs
@@ -246,11 +223,7 @@ def test_scene_stats_attributes_a_failure_to_a_layer(tmp_path: Path) -> None:
def test_the_depth_comparison_is_restricted_to_one_pose() -> None:
- """`survey`'s two-probe table used to compare the sweep's worst-over-ALL-poses depth
- with connectivity's rest-pose depth, so "2-3x deeper on the same pairs" was not a
- statement about one pose at all. Over the 374-round corpus, restricted to the pairs
- whose worst sweep pose IS rest, the two probes agree exactly (4.4/4.4, 4.4/4.4,
- 2.2/2.2, 2.5/2.5 mm)."""
+ """The two-probe table compares depths in ONE pose (rest), not the sweep's worst over all poses."""
from bench.penetration_thresholds import survey, sweep_pairs
moved = _sweep("a|b", 0.0088, poses=[{}, {"j": 0.15}], worst_pose={"j": 0.15})
diff --git a/eval/tests/test_skill_targets_readout.py b/eval/tests/test_skill_targets_readout.py
index 5dc2525b..50c2fd67 100644
--- a/eval/tests/test_skill_targets_readout.py
+++ b/eval/tests/test_skill_targets_readout.py
@@ -98,13 +98,6 @@ def test_the_ab_mode_pairs_by_prompt(tmp_path):
assert (r["better"], r["worse"], r["tied"]) == (1, 0, 0)
-def test_a_battery_dir_is_not_mistaken_for_an_ab_dir(tmp_path):
- from bench.skill_targets import ab_arms
-
- root = _battery(tmp_path, {"chair": _record("blender", [])})
- assert ab_arms(root) is None
-
-
def test_the_cli_runs_over_a_synthetic_battery(tmp_path, capsys):
from bench.skill_targets import main
diff --git a/eval/tests/test_v2_batteries.py b/eval/tests/test_v2_batteries.py
index db7fb05d..3ee7d16f 100644
--- a/eval/tests/test_v2_batteries.py
+++ b/eval/tests/test_v2_batteries.py
@@ -1,19 +1,4 @@
-"""Structural validation of the v2 prompt batteries (offline, no runs).
-
-The v2 batteries drop the saturated easy tier and encode their difficulty
-contracts directly in ``must_have``. These tests pin those contracts:
-
-* every file parses through ``bench.run_bench.Battery.load`` (the real loader);
-* every prompt has a tier, a category, a non-empty ``must_have`` and a
- snake_case id containing its tier token;
-* static_objects_v2 / compare_v2: 8-16 must_have parts per prompt, at least
- half carrying a measurable number, and most prompts with ``dimensions_m``;
-* articulated_v2: every prompt names >= 3 quantified motions for the
- pose-sweep judge;
-* scenes_v2: every scene states a luminance band and a camera brief;
-* compare_v2 / compare_v3 prompts are drawn verbatim from static_objects_v2;
- compare_v3 is a strict superset of compare_v2.
-"""
+"""The v2 prompt batteries: schema, the per-prompt language override, and the compare batteries drawn verbatim."""
from __future__ import annotations
@@ -50,14 +35,6 @@ EXPECTED_COUNTS = {
}
ID_RE = re.compile(r"^[a-z0-9]+(_[a-z0-9]+)+$")
-NUMBER_RE = re.compile(r"\d")
-MOTION_RE = re.compile(
- r"\b(slid(?:e|es|ing)|swing(?:s|ing)?|rotat(?:e|es|ing)|swivel(?:s)?|"
- r"pivot(?:s)?|open(?:s|ed|ing)?|fold(?:s|ed|ing)?|travel(?:s)?|"
- r"advanc(?:e|es)|rais(?:e|es)|lower(?:s)?|tilt(?:s)?|extend(?:s)?|"
- r"retract(?:s)?|splay(?:s|ing)?|pan|lift(?:s)?|drop(?:s)?|hinge(?:d)?|"
- r"revolute|prismatic|continuous(?:ly)?)\b"
-)
@pytest.fixture(scope="module", params=sorted(V2_FILES), ids=sorted(V2_FILES))
@@ -88,83 +65,18 @@ def _load(name: str) -> Battery:
return Battery.load(V2_FILES[name])
[email protected]("name", ["static_objects_v2", "compare_v2", "compare_v3"])
-def test_static_prompts_have_dense_dimensioned_checklists(name: str):
- b = _load(name)
- with_dims = 0
- for p in b.prompts:
- n = len(p.must_have)
- assert 8 <= n <= 16, f"{p.id}: {n} must_have items, want 8-16 nameable parts"
- numbered = sum(1 for item in p.must_have if NUMBER_RE.search(item))
- assert numbered * 2 >= n, f"{p.id}: under half of must_have items carry a number"
- if p.dimensions_m:
- with_dims += 1
- assert with_dims * 2 >= len(b.prompts), f"{name}: under half the prompts set dimensions_m"
-
-
-def test_static_v2_has_controls_and_hard_axes():
- b = _load("static_objects_v2")
- controls = [p for p in b.prompts if "control" in p.tags]
- assert len(controls) == 4 and all(p.tier == "medium" for p in controls)
- hard = [p for p in b.prompts if p.tier == "hard"]
- assert len(hard) == 16
- axes = {t for p in b.prompts for t in p.tags if t.startswith("axis:")}
- assert {"axis:decomposition", "axis:thin_features", "axis:curved_organic",
- "axis:arch_detail", "axis:multi_material"} <= axes
-
-
-def test_articulated_prompts_name_quantified_motions():
- b = _load("articulated_v2")
- for p in b.prompts:
- motions = [i for i in p.must_have if MOTION_RE.search(i.lower())]
- assert len(motions) >= 3, f"{p.id}: fewer than 3 motion items for the pose sweep"
- quantified = [i for i in motions if NUMBER_RE.search(i)]
- assert len(quantified) >= 2, f"{p.id}: motions lack quantities (range / travel)"
-
-
-def test_scene_prompts_state_composition_contracts():
- b = _load("scenes_v2")
- for p in b.prompts:
- assert len(p.must_have) >= 10, f"{p.id}: composition contract too thin"
- joined = " ".join(p.must_have).lower()
- assert "zones" in joined, f"{p.id}: no zone list"
- assert "luminance" in joined, f"{p.id}: no measurable lighting band"
- assert "camera" in joined, f"{p.id}: no camera brief"
- counted = [i for i in p.must_have if re.search(r"at least \d+|\b\d+ zones\b", i.lower())]
- assert len(counted) >= 4, f"{p.id}: too few counted asset types"
-
-
def test_graphics_v2_opengl_prompts_carry_language_override():
- """The ogl_* rows must run under opengl_python; the loader forwards the
- per-prompt override into the Spec (BenchPrompt.language or battery.language)."""
+ """The ogl_* rows run under opengl_python: build_spec forwards the per-prompt override."""
from bench.run_bench import build_spec
from codeverse3d.contracts.common import Backends, Language
b = _load("graphics_v2")
- assert b.language == Language.GLSL_SHADER
- backends = Backends()
for prompt in b.prompts:
- if prompt.id.startswith("ogl_"):
- assert prompt.language == Language.OPENGL_PYTHON, f"{prompt.id}: missing language override"
- else:
- assert prompt.language is None, f"{prompt.id}: unexpected language override"
- spec = build_spec(b, prompt, backends=backends, rounds=1, max_minutes=1, tag0="t")
+ spec = build_spec(b, prompt, backends=Backends(), rounds=1, max_minutes=1, tag0="t")
want = Language.OPENGL_PYTHON if prompt.id.startswith("ogl_") else Language.GLSL_SHADER
assert spec.language == want, f"{prompt.id}: spec language {spec.language} != {want}"
-def test_compare_is_a_subset_of_static_v2():
- """compare_v3 holds compare_v2 verbatim (the test below), so v3 covers both."""
- static = {p.id.split("_", 1)[1]: p for p in _load("static_objects_v2").prompts}
- for p in _load("compare_v3").prompts:
- key = p.id.split("_", 1)[1] # cmp_hard_violin -> hard_violin == prefix-stripped static key
- src = static.get(key)
- assert src is not None, f"{p.id}: no matching static_objects_v2 prompt"
- assert p.prompt == src.prompt, f"{p.id}: prompt text drifted from static_objects_v2"
- assert p.must_have == src.must_have, f"{p.id}: must_have drifted"
- assert p.dimensions_m == src.dimensions_m, f"{p.id}: dimensions drifted"
-
-
def test_compare_v3_extends_compare_v2_verbatim():
"""Recorded compare_v2 cells are reused on compare_v3 runs, so the shared 8 must
match exactly; the 4 extras widen category coverage (>=1 medium, >=3 hard)."""
@@ -180,15 +92,12 @@ def test_compare_v3_extends_compare_v2_verbatim():
assert not {p.category for p in extra} & {p.category for p in v2.values()}
-# ----------------------------------------------------------------------------- compare_v4 (2026-08-25)
def _norm(text: str) -> str:
return re.sub(r"\s+", " ", text.strip().lower())
def test_compare_v4_is_the_union_of_the_static_batteries_by_prompt_text():
- """compare_v4 = every static_objects_v2 prompt + every static_objects_v1 prompt whose text
- is not already in v2, ids and must_have kept VERBATIM from the source battery (docs/report.html:
- an 8-prompt paired battery resolves ~0.25, so the compare batteries had to grow)."""
+ """compare_v4 = static_objects_v2 + every v1 prompt whose text is not in v2, kept VERBATIM."""
v4 = _load_any("compare_v4")
v2 = _load("static_objects_v2")
v1 = _load_any("static_objects_v1")
@@ -210,4 +119,3 @@ def test_compare_v4_is_the_union_of_the_static_batteries_by_prompt_text():
def _load_any(name: str) -> Battery:
return _load(name) if name in V2_FILES else Battery.load(PROMPTS / f"{name}.yaml")
-
diff --git a/eval/tests/test_worktree_import.py b/eval/tests/test_worktree_import.py
index 9a268a75..8fbdc230 100644
--- a/eval/tests/test_worktree_import.py
+++ b/eval/tests/test_worktree_import.py
@@ -1,17 +1,8 @@
"""A bench script run from a worktree must use THAT worktree's `codeverse3d`.
-WHY this is worth a test of its own: it has silently voided two A/B runs.
-``ab_plan.spawn_cell`` starts each child as a FILE path, so ``sys.path[0]`` is ``bench/``
-and the cwd is not on the path. Any ``import codeverse3d`` before the script's own
-``sys.path`` bootstrap therefore resolves through whatever editable install is present
-(``__editable__.3dcodeverse-<v>.pth`` installs a meta-path finder pinned to the tree it was
-installed from). Both arms then run the same foreign code, every switch under test is
-inert, and the report looks completely healthy — the failure has no symptom at all.
-
-Caught on 2026-08-25 in `bench/out/plan_loop/C0/invalid_attempt1_maintree_import` (worked
-around in a launch script) and again in the skills wave's first A/B, where the variant arm
-ran a tree with no skills package and materialised nothing. A launch-script workaround
-protects whoever remembers it; these two checks protect the run.
+A child spawned by file path that imports codeverse3d before its sys.path bootstrap resolves the
+editable install instead: both A/B arms run the same foreign code and the report looks healthy
+(voided two A/Bs, 2026-08-25 and the skills wave).
"""
from __future__ import annotations
@@ -29,10 +20,6 @@ SCRIPTS = sorted(p for p in BENCH.glob("*.py")
if "sys.path.insert" in p.read_text() and CODEVERSE_IMPORT.search(p.read_text()))
-def test_there_is_at_least_one_such_script():
- assert SCRIPTS, "no bench script bootstraps sys.path any more — has the layout changed?"
-
-
@pytest.mark.parametrize("script", SCRIPTS, ids=[p.name for p in SCRIPTS])
def test_the_sys_path_bootstrap_comes_before_any_codeverse_import(script: Path):
text = script.read_text()
@@ -47,12 +34,7 @@ def test_the_sys_path_bootstrap_comes_before_any_codeverse_import(script: Path):
def test_the_guard_refuses_a_foreign_codeverse_for_real(tmp_path: Path):
- """Not "the string is in the file": actually make the bad thing happen.
-
- A foreign ``codeverse3d`` is pre-imported into ``sys.modules``, then ab_plan is run as
- ``__main__``. It must die with its own message rather than proceed to compare a tree
- with itself.
- """
+ """A foreign ``codeverse3d`` pre-imported, then ab_plan run as ``__main__``: it must refuse."""
import subprocess
import sys
@@ -70,12 +52,3 @@ def test_the_guard_refuses_a_foreign_codeverse_for_real(tmp_path: Path):
p = subprocess.run([sys.executable, "-c", src], cwd=HARNESS, capture_output=True, text=True, check=False)
assert p.returncode != 0
assert "refusing to run" in (p.stdout + p.stderr)
-
-
-def test_the_guard_actually_compares_the_resolved_package_to_this_tree():
- import codeverse3d
- from bench.ab_plan import REPO, _assert_local_codeverse
-
- assert Path(codeverse3d.__file__).resolve().parent == REPO / "codeverse3d", (
- "the test suite itself is importing a foreign codeverse3d")
- _assert_local_codeverse() # must not raise in a correctly-resolved tree