Official Codebase of 3DCodeVerse
Python
bench: ab_plan --pin-plan — the driver seeds one plan into both arms, instead of a helper nothing called
gaoypeng3f1831acd37b
diff --git a/harness/bench/ab_plan.py b/harness/bench/ab_plan.pyindex 13569c6d..0f8dd6f3 100644--- a/harness/bench/ab_plan.py+++ b/harness/bench/ab_plan.py@@ -102,8 +102,12 @@ from bench.compare_backends import ( # noqa: E402CompareOptions,_preflight,run_cell,+ spec_for, # noqa: E402)+from bench.pin_plan import PLAN_JSON, PinError, plan_once, seed_plan # noqa: E402from bench.run_bench import Battery, BenchPrompt, select_prompts # noqa: E402+from codeverse.tracks.plan_features import pin_plan_blockers # noqa: E402+from codeverse.workspace import Workspace # noqa: E402DEFAULT_GENERATOR = "api-agent:gemini:gemini-3.7-flash"DEFAULT_JUDGE = "gemini:gemini-3.1-pro-preview"@@ -136,6 +140,8 @@ class AbOptions(BaseModel):max_in_flight: int = DEFAULT_MAX_IN_FLIGHTaa: bool = Field(default=False, description="calibration: run BOTH arms as the control, so the delta IS the noise")redo_fresh: bool = Field(default=True, description="a redo regenerates both arms instead of resuming them")+ pin_plan: bool = Field(default=False, description="plan ONCE per prompt and seed both arms with it "+ "(generation-side switches only: see pin_plan_blockers)")def compare_options(self) -> CompareOptions:"""The per-cell options handed to ``compare_backends.run_cell`` (both arms identical)."""@@ -328,6 +334,36 @@ def archive_cell(out: Path, arm: str, item_id: str, opts: AbOptions) -> Path | Nraise AssertionError("unreachable") # pragma: no cover — count() is infinite+def pin_pair(battery: Battery, item: BenchPrompt, out: Path, arms: Sequence[str], opts: AbOptions) -> str:+ """Plan ``item`` ONCE and seed that plan into every arm about to run; return its hash.++ The A/A of this rig measured paired sd 0.202 on the judged score and traced it to the+ PLANNER — its worst pair planned 1 part against 10 on identical settings (docs/EVAL.md+ §8.1). A generation-side switch cannot change planning, so both arms may share one plan+ and the paired difference stops carrying that spread. ``pin_plan_blockers`` decides+ whether that is true of THIS variant_env; ``main`` refuses the run when it is not.++ Both arms are seeded from the same third workspace rather than the variant from the+ control's run, so the pair still launches together and sees the same provider weather.+ The returned ``inputs_hash`` is asserted equal for every arm: it is derived from the+ spec, so a mismatch means the arms were not planning the same thing and the seed would+ be a cache MISS — a silently UNpinned pair, which is the one failure this must not have.+ """+ spec = spec_for(battery, item, _harness_arm(opts.generator), opts.compare_options())+ src = Workspace(out / "plans" / item.id / "run")+ if not (src.root / PLAN_JSON).is_file():+ plan_once(spec, src.root)+ want = json.loads((src.root / "run_state.json").read_text())["stages"]["plan"]["inputs_hash"]+ for arm in arms:+ dst = Workspace(cell_dir(out, arm, item.id, opts.generator) / "run")+ dst.create()+ dst.write_json(dst.spec_path, spec) # _run_harness only writes it when it creates the ws+ got = seed_plan(src.root, dst.root)+ if got != want: # pragma: no cover — same spec both sides; the assert is the point+ raise PinError(f"{item.id}/{arm}: seeded plan hash {got} != {want}; the pair would be unpinned")+ return want++def run_ab(battery_path: Path | str, out_dir: Path | str, opts: AbOptions, *, run_cell_fn: CellRunner = spawn_cell,on_result: Callable[[CellResult], None] | None = None) -> Verdict:"""Run (or resume) the A/B, one prompt-pair at a time; write pairs.json + summary.md."""@@ -348,6 +384,8 @@ def run_ab(battery_path: Path | str, out_dir: Path | str, opts: AbOptions, *, ruif fresh:for a in arms:archive_cell(out, a, item.id, opts)+ if opts.pin_plan:+ pin_pair(battery, item, out, arms, opts)futs = [pool.submit(run_cell_fn, battery_path, out, item, a, opts) for a in arms]for fut in futs:r = fut.result()@@ -400,6 +438,9 @@ def _parser() -> argparse.ArgumentParser:ap.add_argument("--redo-resume", action="store_true",help="let a redo RESUME the old cells instead of regenerating them (cheap, but the pair then ""spans two weathers — see archive_cell)")+ ap.add_argument("--pin-plan", action="store_true",+ help="plan once per prompt and seed BOTH arms with it, removing the planner's "+ "spread from the pairing; refused for a plan-side --variant-env")ap.add_argument("--aa", action="store_true",help="calibration run: both arms identical, so the measured delta IS this rig's noise floor")ap.add_argument("--no-resume", action="store_true")@@ -436,7 +477,7 @@ def main(argv: Sequence[str] | None = None) -> int:limit=ns.limit, resume=not ns.no_resume, redo_status=[s for s in ns.redo_status.split(",") if s],variant_env=parse_variant_env(ns.variant_env),max_in_flight=ns.max_in_flight if ns.max_in_flight is not None else inherited_max_in_flight(),- aa=ns.aa, redo_fresh=not ns.redo_resume)+ aa=ns.aa, redo_fresh=not ns.redo_resume, pin_plan=ns.pin_plan)out = Path(ns.out)if ns.report_only:battery = Battery.load(ns.prompts)@@ -465,6 +506,11 @@ def main(argv: Sequence[str] | None = None) -> int:"--variant-env only sets switches nothing reads, so both arms would be identical: "+ "; ".join(f"{k} ({DEAD_SWITCHES[k]})" for k in dead)+ " (pass --aa if an identical-arms calibration run is the point)")+ if opts.pin_plan and (blockers := pin_plan_blockers(opts.variant_env)):+ _parser().error(+ "--pin-plan is refused for a PLAN-side switch: sharing one plan across the arms would delete the very "+ "thing under test and the rig would report 'no effect' with confidence — "+ + "; ".join(blockers))from codeverse.models.health import pool_budget# the rule is a BUDGET, not a head-count: the provider sees one machine, so the sum of@@ -493,7 +539,8 @@ def main(argv: Sequence[str] | None = None) -> int:__all__ = ["DEFAULT_GENERATOR", "DEFAULT_JUDGE", "MAX_IN_FLIGHT_ENV", "NESTED_MAX_IN_FLIGHT_ENV", "PARALLEL","AbOptions", "CellRunner", "Todo", "archive_cell", "cell_dir", "cell_main", "child_env",- "inherited_max_in_flight", "main", "parse_variant_env", "preflight", "run_ab", "spawn_cell", "worker_argv"]+ "inherited_max_in_flight", "main", "parse_variant_env", "pin_pair", "preflight", "run_ab", "spawn_cell",+ "worker_argv"]if __name__ == "__main__":raise SystemExit(main())diff --git a/harness/bench/pin_plan.py b/harness/bench/pin_plan.pyindex 7150cb1f..9cdc95e9 100644--- a/harness/bench/pin_plan.py+++ b/harness/bench/pin_plan.py@@ -21,8 +21,9 @@ from __future__ import annotationsimport jsonimport shutilfrom pathlib import Path+from typing import Any-__all__ = ["PinError", "plan_artifacts", "seed_plan"]+__all__ = ["PinError", "plan_artifacts", "plan_once", "seed_plan"]#: what a planned run leaves behind that a later run resumes fromPLAN_JSON = "plan.json"@@ -74,3 +75,40 @@ def seed_plan(src_run: Path, dst_run: Path) -> str:target["stages"] = stagesdst_state.write_text(json.dumps(target, indent=1))return str(entry["inputs_hash"])+++def plan_once(spec: Any, ws_root: Path) -> str:+ """Run ONLY the plan stage of ``spec``'s track into ``ws_root``; return its inputs_hash.++ The A/B driver calls this once per prompt and :func:`seed_plan`s the result into BOTH+ arms, so neither arm pays a planner call and neither one's plan is the other's. Seeding+ the variant from the *control's* finished run would work too, but it serialises the pair+ — and the pair runs together precisely so both arms see the same provider weather.++ Goes through ``StageRunner`` rather than ``track.plan`` so the artefacts are the ones a+ real run leaves (``stages/plan.json`` + the ``run_state`` entry that makes the stage a+ cache HIT); and through ``_plan_stage`` rather than the bare planner so the call is+ charged to a budget and its spend is saved, exactly as in a run.+ """+ from codeverse.events import EventLog+ from codeverse.orchestrator.runner import StageRunner+ from codeverse.orchestrator.state import RunState+ from codeverse.tracks import get_track+ from codeverse.tracks.lifecycle import plan_stage_inputs+ from codeverse.workspace import Workspace++ ws = Workspace(Path(ws_root))+ ws.create()+ ws.write_json(ws.spec_path, spec)+ events = EventLog(ws.events_path)+ state = RunState.load_or_new(ws, resume=True)+ track = get_track(spec.track)+ ctx = track.build_context(spec, ws, events, state)+ runner = StageRunner(ws, events, state)+ runner.stage("plan", lambda: track._plan_stage(ctx), # noqa: SLF001 — see docstring+ inputs={"spec": plan_stage_inputs(spec), "track": track.track.value},+ model=track.plan_model)+ entry = state.stages.get(STAGE_NAME)+ if entry is None or not entry.inputs_hash: # pragma: no cover — stage() always records one+ raise PinError(f"plan stage left no state entry in {ws_root}")+ return str(entry.inputs_hash)diff --git a/harness/docs/EVAL.md b/harness/docs/EVAL.mdindex c4e3f397..0439ec36 100644--- a/harness/docs/EVAL.md+++ b/harness/docs/EVAL.md@@ -297,6 +297,46 @@ Two consequences, and the first is worth more than any extra prompt:out-score a plan that did the work. (Not a licence to fail the run — that was C1, revertedthe same day for turning recoverable planning slips into total losses.)+### 8.2 `--pin-plan`: the driver actually does it now++8.1 said to pin the plan; `bench/pin_plan.py` had the seeding and nothing called it.+`bench/ab_plan.py --pin-plan` closes that: before a pair is launched, `pin_pair` plans the+prompt ONCE into `<out>/plans/<id>/run` and seeds that result into both arms' `run/`+workspaces, so the plan stage is a cache HIT (`StageRunner.stage` keys on+`inputs_hash` + result file) and neither arm pays a planner call.++Three details are the whole correctness of it:++* **Both arms are seeded from a third workspace**, not the variant from the control's+ finished run. Seeding off the control would serialise the pair, and the pair is launched+ together precisely so both arms see the same provider weather.+* **The `inputs_hash` is asserted equal for every arm.** It is derived from the spec+ (`plan_stage_inputs`), so a mismatch means the seed is a cache MISS and the pair would+ re-plan per arm while reporting itself pinned — the one failure this must not have.+* **`pin_plan_blockers` gates the flag** and `main` refuses the run when it is non-empty.+ Pinning a plan-side switch deletes the thing under test and the rig would then report+ "no effect" with confidence. `CV3D_SKILLS*` are in `GENERATION_SIDE_ENV`, so the skills+ wave is pinnable; `CV3D_PLAN_BRIEF` is not, and `--pin-plan` rejects it.++Pinning is orthogonal to `--aa`, and an A/A that will be read against a pinned A/B must be+pinned too — otherwise the floor carries a variance term the A/B has already removed and+every delta looks smaller than its own noise.++### 8.3 A metric with no headroom is not an underpowered A/B++`bench/skill_targets.py` prints `n to resolve 25%` for each bundle's own target, and for a+count that is mostly zero the number is not a hurdle, it is a refusal. Measured over the+recorded corpus, before spending anything:++| target | baseline | paired sd (est.) | pairs to resolve a 25% move |+|---|---|---|---|+| `cv3d-glsl-craft` / mean_edge_density | 0.234, spread 0.031–0.464 | 0.207 unpaired | ~50 unpaired — pinning + pairing is what makes it affordable |+| `cv3d-urdf-joints` / joint_sweep_errors | 6.91 mean, 20 of 23 runs at **0**, tail 8/50/101 | ~32.6 | **~1420** (~89 even to see the metric go to zero) |+| `cv3d-scene-composition` / camera_placement_findings | 0.25 on round 1, **0.00** by the last round | ~0.71 | **~512** (~32 to eliminate every fault) |++Two of those three are answered by arithmetic, not by a battery. Running them anyway and+reporting "no effect" would be the rig lying about what it can see.+## 9. Reporting checklistbattery name + git sha of prompts; judge id, rubric name + hash, `n_samples`; per-armdiff --git a/harness/tests/compare_bench/test_pin_plan.py b/harness/tests/compare_bench/test_pin_plan.pyindex b886b573..291373c9 100644--- a/harness/tests/compare_bench/test_pin_plan.py+++ b/harness/tests/compare_bench/test_pin_plan.py@@ -8,6 +8,7 @@ experiment. Both halves are tested here.from __future__ import annotationsimport json+from pathlib import Pathimport pytest@@ -102,3 +103,95 @@ def test_pinning_a_plan_side_switch_would_delete_the_experiment(tmp_path):# ...which is why the caller must refuse it for a switch that changes planningassert pin_plan_blockers({"CV3D_PLAN_FEATURES": "fit"}) == ["CV3D_PLAN_FEATURES=fit changes the plan itself"]+++# --------------------------------------------------------------- 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(ab_plan.REPO / "bench" / "prompts" / "compare_v1.yaml")+ item = battery.prompts[0]+ opts = ab_plan.AbOptions(variant_env={"CV3D_SKILLS": "1"}, pin_plan=True)+ 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."""+ from bench import ab_plan+ from bench.run_bench import Battery++ battery = Battery.load(ab_plan.REPO / "bench" / "prompts" / "compare_v1.yaml")+ item = battery.prompts[0]+ opts = ab_plan.AbOptions(variant_env={"CV3D_SKILLS": "1"}, pin_plan=True)+ n = 0++ def fake_plan_once(spec, ws_root):+ nonlocal n+ n += 1+ run = Path(ws_root)+ (run / "stages").mkdir(parents=True, exist_ok=True)+ body = json.dumps({"object_name": "Chair", "parts": [{"name": f"call{n}"}]})+ (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)+ ab_plan.pin_pair(battery, item, tmp_path, list(ab_plan.ARMS), opts)+ 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"}]+++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."""+ from bench import ab_plan++ with pytest.raises(SystemExit):+ ab_plan.main(["--prompts", str(ab_plan.REPO / "bench" / "prompts" / "compare_v1.yaml"),+ "--out", "/tmp/never", "--pin-plan", "--no-preflight",+ "--variant-env", "CV3D_PLAN_BRIEF=1"])+++def test_a_generation_side_variant_env_is_permitted():+ """The premise of this whole wave: CV3D_SKILLS acts after planning, so it is pinnable."""+ from codeverse.tracks.plan_features import pin_plan_blockers++ assert pin_plan_blockers({"CV3D_SKILLS": "1", "CV3D_SKILLS_MAX": "1"}) == []