Official Codebase of 3DCodeVerse
Python
scene track review fixes: rebuilds outlive the repair budget, the pack is on the budget, one walker for scene_stats
Claude8893b4a3c25e
diff --git a/harness/bench/scene_stats.py b/harness/bench/scene_stats.pyindex 01085e78..ce05543c 100644--- a/harness/bench/scene_stats.py+++ b/harness/bench/scene_stats.py@@ -26,6 +26,7 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # this tree's codeverse, not the editable install+from codeverse.flywheel.record import unique_files # noqa: E402from codeverse.spatial.node import browser_was_lost # noqa: E402#: pipeline stages in the order the scene track runs them@@ -34,13 +35,8 @@ STAGES = ("plan", "skeleton", "assets", "env", "layouts", "assemble", "generate"def runs(root: Path) -> list[tuple[str, dict, list[dict]]]:"""``(prompt id, record, events)`` per scene run under ``root``, once per run."""- out, seen = [], set()- # same rule as `penetration_thresholds.records`; both move to- # `flywheel.record.unique_files` when the review branch lands- for rec in root.rglob("record.json"):- if rec.resolve() in seen or any(w in rec.parts for w in ("_cand", "_assets")):- continue- seen.add(rec.resolve())+ out = []+ for rec in unique_files(root, "record.json"):try:data = json.loads(rec.read_text())except (OSError, ValueError):@@ -56,12 +52,17 @@ def runs(root: Path) -> list[tuple[str, dict, list[dict]]]:except ValueError:continueout.append((str((data.get("spec") or {}).get("id", rec.parent.name)).split("/")[-1], data, events))- return sorted(out)+ # by id, then by path: two runs of one prompt (a battery with reps) share the id, and a+ # bare sorted() would then compare their record dicts and raise. unique_files yields+ # paths sorted, and the sort is stable, so the key is the id alone.+ out.sort(key=lambda row: row[0])+ return outdef layers(rows: list[tuple[str, dict, list[dict]]]) -> dict:"""One counter per layer, over every run."""plan = Counter()+ build = Counter()assets = Counter()asset_kind = Counter()tris: list[int] = []@@ -91,6 +92,12 @@ def layers(rows: list[tuple[str, dict, list[dict]]]) -> dict:placements.append(int(e.get("placements") or 0))if e.get("reasked"):plan["layout_reask"] += 1+ elif kind == "build.done":+ build["ok" if e.get("ok") else "failed"] += 1+ elif kind == "build.harness_retry":+ build["harness_retry"] += 1+ elif kind == "repair.attempt":+ build["repair"] += 1elif kind == "render.failed":gates["render_failed"] += 1for a in (rec.get("plan") or {}).get("assets") or []:@@ -123,7 +130,7 @@ def layers(rows: list[tuple[str, dict, list[dict]]]) -> dict:scores.append(float(j["overall"]))for issue in j.get("issues") or []:judge[f"{issue.get('severity', '?')}/{issue.get('kind', '?')}"] += 1- return {"plan": plan, "assets": assets, "asset_kind": asset_kind, "tris": tris,+ return {"plan": plan, "build": build, "assets": assets, "asset_kind": asset_kind, "tris": tris,"placements": placements, "gates": gates, "gate_errors": gate_errors,"judge": judge, "scores": scores}@@ -147,6 +154,10 @@ def report(root: Path) -> str:if d["placements"]:out.append(f"\n## layout\n placements per zone: median {statistics.median(d['placements']):.0f}, "f"zones {len(d['placements'])}")+ # the layer between assembly and the gates: a build that failed in the harness and was+ # re-run, and a build that failed in the scene and went to a repair, are different+ # defects (tracks/repair.build_with_repair)+ out += ["", "## build", f" {dict(d['build'])}"]out += ["", "## gates", "| gate | ran | failed | ERROR findings | lost to the box |", "|---|--:|--:|--:|--:|"]skip = (":FAILED", ":LOST", ":BOX")for name in sorted(n for n in d["gates"] if not n.endswith(skip) and n != "rounds_lost_to_the_box"):diff --git a/harness/codeverse/tracks/repair.py b/harness/codeverse/tracks/repair.pyindex c41c68da..52ef610e 100644--- a/harness/codeverse/tracks/repair.py+++ b/harness/codeverse/tracks/repair.py@@ -167,7 +167,9 @@ def build_with_repair(ctx: RunContext, *, round_index: int, label: str, files_hirepeats = 0attempt = 0rebuilds = 0- while not outcome.ok and attempt < max_attempts:+ # the rebuilds are gated by their OWN bound, not by the repair budget: a round run+ # with max_repair_attempts=0 (a baseline arm) still gets its harness retries+ while not outcome.ok and (attempt < max_attempts or build.harness_failure):# A build that failed because the HARNESS could not run it is not a defect the# agent can fix, and handing it over costs the round its whole repair budget on# working code. Measured 2026-09-05 (scene_textures/japanese_garden): threediff --git a/harness/codeverse/tracks/scene.py b/harness/codeverse/tracks/scene.pyindex f844d9c8..94958e0b 100644--- a/harness/codeverse/tracks/scene.py+++ b/harness/codeverse/tracks/scene.py@@ -326,6 +326,9 @@ class SceneTrack(BaseTrack):ctx.events.emit("textures.stage_failed", error=f"{type(e).__name__}: {e}"[:300])return {}manifest = pack.manifest()+ # post-hoc, like the object texture pass (lifecycle): the images are on disk either+ # way, and the round loop's next ok() check is where a crossed ceiling stops the run+ ctx.budget.add(pack.usage, stage="texture")ctx.ws.commit("textures")ctx.events.emit("textures.done", n=len(manifest), cost_usd=round(pack.usage.cost_usd, 4), source=pack.source)return manifestdiff --git a/harness/tests/compare_bench/test_scene_stats.py b/harness/tests/compare_bench/test_scene_stats.pyindex a7616f2e..1e66b31b 100644--- a/harness/tests/compare_bench/test_scene_stats.py+++ b/harness/tests/compare_bench/test_scene_stats.py@@ -90,3 +90,38 @@ def test_the_median_score_is_read_off_the_real_Judgment_shape(tmp_path: Path) ->assert d["scores"] == [0.30, 0.50] or d["scores"] == [0.50, 0.30]text = report(tmp_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+ layer reads both as "the gates failed"."""+ d = tmp_path / "scn_cliff" / "run"+ d.mkdir(parents=True)+ (d / "record.json").write_text(json.dumps({"spec": {"track": "scene", "id": "scn_cliff"},+ "plan": {"assets": []}, "rounds": []}))+ (d / "events.jsonl").write_text("\n".join(json.dumps(e) for e in [+ {"event": "build.done", "ok": False},+ {"event": "build.harness_retry", "attempt": 1},+ {"event": "build.done", "ok": False, "harness_retry": 1},+ {"event": "repair.attempt", "attempt": 1},+ {"event": "build.done", "ok": True, "attempt": 1},+ ]))+ b = layers(runs(tmp_path))["build"]+ assert dict(b) == {"failed": 2, "harness_retry": 1, "repair": 1, "ok": 1}+ assert "## build" in report(tmp_path)diff --git a/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py b/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.pyindex 4c6b868c..081cd733 100644--- a/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py+++ b/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py@@ -108,3 +108,22 @@ def test_a_real_build_failure_is_still_repaired(monkeypatch):monkeypatch.setattr(R, "build_once", fake_build_once)out = R.build_with_repair(_ctx(), round_index=0, label="r00")assert out.ok is True and len(seen) == 1, "a real error still gets one repair"+++def test_a_harness_failure_is_rebuilt_even_with_no_repair_budget(monkeypatch, no_generate):+ """The rebuilds are bounded by MAX_HARNESS_REBUILDS, not by the repair budget: a+ baseline arm that runs with max_repair_attempts=0 must still get its retries, or a+ dropped stdout tail costs it the whole round."""+ seq = [(_build(ok=False, harness=True, msg="scene probe produced no result (driver output lost)"),+ GateReport(gate="lint", passed=True, findings=[])),+ (_build(ok=True), GateReport(gate="lint", passed=True, findings=[]))]+ calls = {"n": 0}++ def fake_build_once(ctx):+ calls["n"] += 1+ return seq[min(calls["n"] - 1, len(seq) - 1)]++ monkeypatch.setattr(R, "build_once", fake_build_once)+ ctx = _ctx(spec=SimpleNamespace(budget=SimpleNamespace(max_repair_attempts=0)))+ out = R.build_with_repair(ctx, round_index=0, label="r00")+ assert out.ok is True and calls["n"] == 2 and out.attempts == []diff --git a/harness/tests/scene_gates/test_scene_textures_stage.py b/harness/tests/scene_gates/test_scene_textures_stage.pyindex 55760a1a..97a1efee 100644--- a/harness/tests/scene_gates/test_scene_textures_stage.py+++ b/harness/tests/scene_gates/test_scene_textures_stage.py@@ -154,3 +154,32 @@ def test_the_pack_has_the_last_word_over_the_recipes(template: str):"""The cookbook's ground chapter is long and specific; whichever comes last wins."""out = _render(template, textures="TEXTURE_BLOCK_MARKER", recipes="RECIPE_MARKER")assert out.index("RECIPE_MARKER") < out.index("TEXTURE_BLOCK_MARKER")+++def test_the_stage_puts_the_pack_on_the_run_budget(monkeypatch, tmp_path):+ """The pack is an image-model call the run pays for; every other paid stage goes+ through the guard (`BudgetGuard.add`, post-hoc, like the object texture pass), so a+ ceiling can be crossed by a paid stage the run never saw."""+ from types import SimpleNamespace++ import codeverse.reference as reference+ import codeverse.texturing.plan as plan_mod+ import codeverse.tracks.scene as S+ from codeverse.contracts.common import Usage++ usage = Usage(cost_usd=0.07)+ pack = SimpleNamespace(manifest=lambda: MANIFEST, usage=usage, source="vlm")+ monkeypatch.setattr(plan_mod, "scene_texture_pack", lambda *a, **k: pack)+ monkeypatch.setattr(reference, "_image_model", lambda _m: None)++ added: list[tuple[Usage, str]] = []+ ctx = SimpleNamespace(+ plan=None,+ ws=SimpleNamespace(public=tmp_path / "public", commit=lambda *_a, **_k: None),+ spec=SimpleNamespace(backends=SimpleNamespace(planner=None)),+ settings=SimpleNamespace(cache_dir=tmp_path / "cache"),+ events=SimpleNamespace(emit=lambda *a, **k: None),+ budget=SimpleNamespace(add=lambda u, *, stage: added.append((u, stage))),+ )+ assert S.SceneTrack()._textures_stage(ctx) == MANIFEST # type: ignore[arg-type]+ assert added == [(usage, "texture")]