Skip to content

Official Codebase of 3DCodeVerse

Python

lifecycle: salvage the adopted best-of-N winner + honest finalise on a failed rebuild

gaoypeng1eed558b04d3
diff --git a/harness/codeverse/tracks/lifecycle.py b/harness/codeverse/tracks/lifecycle.py
index 1c8e7eff..484142d7 100644
--- a/harness/codeverse/tracks/lifecycle.py
+++ b/harness/codeverse/tracks/lifecycle.py
@@ -249,8 +249,12 @@ class BaseTrack:
def prepare_salvage(self, ctx: RunContext) -> bool:
"""Make the workspace buildable after a stage tripped the budget before
- round 0. Return False (the default) when the track has nothing to salvage."""
- return False
+ round 0. Return False when the track has nothing to salvage. The default
+ says yes exactly when best-of-N adopted a winner (``rounds/candidates.json``
+ is written immediately before adoption): the paid, buildable candidate must
+ not be thrown away by a ceiling trip at the r00 boundary. A bare skeleton
+ still returns False."""
+ return (ctx.ws.root / "rounds" / "candidates.json").is_file()
# ---- planner hooks (tracks/planner.py runs the one loop)
def plan_example(self, spec: Spec) -> dict[str, Any]:
@@ -744,15 +748,24 @@ class BaseTrack:
def finalise(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, stop_reason: str, error: str = "") -> RunRecord:
self._save_budget(ctx) # aborted-round / stage charges must survive for resume
best = ctx.state.best_round
+ rebuild_err = ""
if best is not None and best < len(rounds) and rounds[best].commit and self._needs_restore(ctx, rounds[best].commit):
ctx.ws.restore(rounds[best].commit)
ctx.ws.commit(f"restore best round r{best:02d}")
try:
build = ctx.runtime.build(ctx.ws, timeout_s=ctx.settings.limits.build_timeout_s)
ctx.events.emit("finalise.rebuild", round=best, ok=build.ok)
+ if not build.ok: # the runtime invalidated the canonical artifact FIRST — it is gone
+ rebuild_err = f"{build.error_type or 'BuildFailed'}: {build.error_message}"[:300]
except Exception as e: # noqa: BLE001 — the best round already built once; report, don't fail
- ctx.events.emit("finalise.rebuild_failed", error=f"{type(e).__name__}: {e}")
- if rounds and self._texture_wanted(ctx):
+ rebuild_err = f"{type(e).__name__}: {e}"[:300]
+ ctx.events.emit("finalise.rebuild_failed", error=rebuild_err)
+ if rebuild_err:
+ # keep the earned status + judge scores (they were really paid and judged),
+ # but the record must say the deliverable's artifact could not be rebuilt.
+ ctx.extra["finalise_rebuild_failed"] = rebuild_err
+ error = error or f"finalise rebuild failed: {rebuild_err}"
+ if rounds and not rebuild_err and self._texture_wanted(ctx):
self._texture_pass(ctx)
ctx.state.status, ctx.state.stop_reason, ctx.state.error = status, stop_reason, error
self._save_budget(ctx) # saves state too — AFTER the texture pass charged
@@ -863,6 +876,8 @@ class BaseTrack:
"cost_by_stage": ctx.budget.stage_summary()}
if ctx.extra.get("texturing"):
extra["texturing"] = ctx.extra["texturing"]
+ if ctx.extra.get("finalise_rebuild_failed"):
+ extra["finalise_rebuild_failed"] = ctx.extra["finalise_rebuild_failed"]
if ctx.extra.get("aborted_rounds"):
# rounds the budget (or a crash) cut after the money was spent: they are not
# in ``rounds``, so name them here and keep their dollars in total_usage.
diff --git a/harness/tests/orchestrator_tracks/test_budget_snapshot.py b/harness/tests/orchestrator_tracks/test_budget_snapshot.py
index d27f84ff..0a0ce7b0 100644
--- a/harness/tests/orchestrator_tracks/test_budget_snapshot.py
+++ b/harness/tests/orchestrator_tracks/test_budget_snapshot.py
@@ -196,3 +196,52 @@ def test_planning_error_dollars_are_booked_exactly_once(tmp_path):
n = 1 + MAX_VALIDATION_REASKS # every paid attempt, each booked once
assert guard.spent.cost_usd == pytest.approx(0.01 * n)
assert ei.value.usage.cost_usd == pytest.approx(0.01 * n) # the error still reports the total
+
+
+# --------------------------------------------------------------- ordering: r00 boundary stop
+def test_the_adopted_best_of_n_winner_survives_a_boundary_budget_stop(tmp_path, chair_plan, settings, monkeypatch):
+ """The winner is adopted + committed + candidates.json written, then the boundary
+ ``budget.check()`` trips BEFORE run_round persists r00. prepare_salvage must say
+ yes (the paid, buildable candidate is sitting in src/) so the salvage round
+ delivers ONE scored round instead of a 0-round record that re-pays all N on resume."""
+ import codeverse.tracks.candidates as cand
+
+ real_adopt = cand.adopt_candidate
+
+ def adopt_then_ceiling(ctx, sub_ws):
+ real_adopt(ctx, sub_ws)
+ ctx.budget._active_s = ctx.spec.budget.max_minutes * 60 + 60 # noqa: SLF001 — clock ran out during candidates
+
+ monkeypatch.setattr(cand, "adopt_candidate", adopt_then_ceiling)
+
+ def writer(job, ws_):
+ return {"src/object.js": f"// {job.label} in {ws_.root.name}\n"
+ "export function build(THREE) { return new THREE.Group(); }\n"}
+
+ ws = Workspace(tmp_path / "runs" / "bo")
+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.6,)), agent=FakeAgent(writer),
+ planner_model=FakeChatModel(lambda req: chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=FakeRuntime(Language.THREEJS), n_candidates=2)
+ rec = track.run(make_spec(max_rounds=0), ws)
+ assert rec.status is RunStatus.BUDGET
+ assert len(rec.rounds) == 1 and rec.rounds[0].score == pytest.approx(0.6)
+ assert rec.best_round == 0 and rec.final_score == pytest.approx(0.6)
+ ev = [e["event"] for e in EventLog(ws.events_path).read()]
+ assert "budget.salvage" in ev and "budget.salvage_skipped" not in ev
+
+
+def test_a_skeleton_only_budget_trip_still_salvages_nothing(tmp_path, chair_plan, settings):
+ """No candidate ever finished (the ceiling tripped mid-generation): there is no
+ adopted winner, so the salvage hook must keep saying no off-scene."""
+
+ def writer(job, ws_):
+ raise BudgetExceeded("elapsed 11.0 min exceeds max_minutes 10.0", spent_usd=1.0, elapsed_min=11.0)
+
+ ws = Workspace(tmp_path / "runs" / "bare")
+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.6,)), agent=FakeAgent(writer),
+ planner_model=FakeChatModel(lambda req: chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=FakeRuntime(Language.THREEJS), n_candidates=1)
+ rec = track.run(make_spec(max_rounds=0), ws)
+ assert rec.status is RunStatus.BUDGET and rec.rounds == []
+ ev = [e["event"] for e in EventLog(ws.events_path).read()]
+ assert "budget.salvage_skipped" in ev
diff --git a/harness/tests/orchestrator_tracks/test_fix_batch2.py b/harness/tests/orchestrator_tracks/test_fix_batch2.py
index 30c5f3ca..9e1d317b 100644
--- a/harness/tests/orchestrator_tracks/test_fix_batch2.py
+++ b/harness/tests/orchestrator_tracks/test_fix_batch2.py
@@ -109,6 +109,49 @@ def test_finalise_restores_best_when_aborted_round_dirtied_src(tmp_path, chair_p
assert snap["billed_usd"] == pytest.approx(0.025, abs=1e-6) and snap["calls"] > 0
+# --------------------------------------------------------------------- finding: finalise rebuild fails after invalidation
+def test_a_failed_finalise_rebuild_cannot_finalize_silently(tmp_path, chair_plan, settings, monkeypatch):
+ """Every real runtime invalidates the canonical artifact FIRST in build(), so a
+ failed rebuild of the restored best round leaves object.glb MISSING — yet the run
+ used to finalize with final_score set, ``record.error == ""`` and a deliverable
+ with no model file. The earned status + judge scores are kept; the error and the
+ ``finalise_rebuild_failed`` flag must say what happened, and the texture pass
+ (whose input GLB is gone) must not charge image calls first."""
+ import subprocess
+
+ class RebuildFailsRuntime(FakeRuntime):
+ def build(self, ws, *, timeout_s=None):
+ msg = subprocess.run(["git", "-C", str(ws.root), "log", "-1", "--format=%s"],
+ capture_output=True, text=True).stdout.strip()
+ if msg.startswith("restore best round"):
+ ws.stage_artifacts("object.glb").invalidate() # what the real runtimes do first
+ return BuildResult(ok=False, language=self.language.value, error_type="Timeout",
+ error_message="runtime crashed on rebuild", error_file="src/object.js")
+ return super().build(ws, timeout_s=timeout_s)
+
+ textured = []
+ from codeverse.tracks.lifecycle import BaseTrack
+ monkeypatch.setattr(BaseTrack, "_texture_wanted", staticmethod(lambda ctx: True))
+ monkeypatch.setattr(BaseTrack, "_texture_pass", lambda self, ctx: textured.append(True))
+
+ spec = make_spec(max_rounds=2)
+ ws = Workspace(tmp_path / "runs" / "r")
+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.7, 0.5), targets=("Seat",)),
+ agent=FakeAgent(_writer), planner_model=_planner(chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=RebuildFailsRuntime(Language.THREEJS))
+ rec = track.run(spec, ws)
+ assert rec.status is RunStatus.PLATEAU and rec.best_round == 0 # the earned status stays
+ assert rec.final_score == pytest.approx(0.7) # ...and so do the paid scores
+ assert rec.error.startswith("finalise rebuild failed: Timeout")
+ assert "runtime crashed on rebuild" in rec.extra["finalise_rebuild_failed"]
+ assert not (ws.artifacts / "object.glb").is_file()
+ assert textured == [], "the texture pass must not run against a missing GLB"
+ on_disk = json.loads(ws.record_path.read_text())
+ assert on_disk["error"].startswith("finalise rebuild failed") and on_disk["status"] == "plateau"
+ ev = [e for e in EventLog(ws.events_path).read() if e["event"] == "finalise.rebuild"]
+ assert ev and ev[-1]["ok"] is False
+
+
# --------------------------------------------------------------------- finding: spent usage persisted on crash paths
def test_spent_usage_saved_when_a_round_crashes(tmp_path, chair_plan, settings):
class BoomServices(FakeServices):