Official Codebase of 3DCodeVerse
Python
budget: resume restores what was spent; paid results are persisted before enforcement
gaoypeng195275ce3d8e
diff --git a/harness/codeverse/cli/main.py b/harness/codeverse/cli/main.pyindex 87c33d18..31cfbe69 100644--- a/harness/codeverse/cli/main.py+++ b/harness/codeverse/cli/main.py@@ -396,7 +396,9 @@ def resume(max_usd: Annotated[float | None,typer.Option(- "--max-usd", min=0, help="raise the budget cap before resuming (rewrites spec.json)"+ "--max-usd", min=0,+ help="raise the budget cap before resuming (rewrites spec.json; prior spend is "+ "restored on resume, so the run gets the new cap MINUS what it already spent)",),] = None,max_minutes: Annotated[diff --git a/harness/codeverse/fanout.py b/harness/codeverse/fanout.pyindex c5fb217e..a9a5a0af 100644--- a/harness/codeverse/fanout.py+++ b/harness/codeverse/fanout.py@@ -15,7 +15,7 @@ import timefrom collections.abc import Callable, Iterable, Sequencefrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass, field-from typing import Any, TypeVar+from typing import TypeVarlog = logging.getLogger(__name__)@@ -34,13 +34,6 @@ class FanOutReport:durations_s: list[float] = field(default_factory=list)total_s: float = 0.0- def as_dict(self) -> dict[str, Any]:- return {- "label": self.label, "n_items": self.n_items, "n_ok": self.n_ok,- "n_failed": self.n_failed, "total_s": round(self.total_s, 2),- "max_item_s": round(max(self.durations_s), 2) if self.durations_s else 0.0,- }-def _in_caller_context(snapshot: contextvars.Context, fn: Callable[[int], None], i: int) -> None:"""Run ``fn(i)`` with the values the caller's context held at fan-out time.diff --git a/harness/codeverse/orchestrator/budget.py b/harness/codeverse/orchestrator/budget.pyindex cc48956e..312a8535 100644--- a/harness/codeverse/orchestrator/budget.py+++ b/harness/codeverse/orchestrator/budget.py@@ -32,6 +32,8 @@ import timefrom pathlib import Pathfrom typing import Any+from pydantic import BaseModel+from codeverse.contracts.common import Budget, Usagefrom codeverse.cost.billing import bills_usd@@ -69,6 +71,9 @@ class BudgetGuard:):self.budget = budgetself.start_time = time.time() if start_time is None else start_time+ #: ACTIVE seconds carried over from previous sessions of this run (``restore``+ #: sets it from the snapshot); downtime between sessions never counts.+ self._active_s: float = 0.0self.spent = Usage()#: the share of ``spent.cost_usd`` that is money someone is actually charged.#: The ceilings enforce THIS, not ``spent.cost_usd`` — a backend on a flat-rate@@ -186,8 +191,41 @@ class BudgetGuard:"""``{stage: USD}`` charged against one round index (empty when none)."""return dict(self.by_round.get(int(round_index), {}))+ # ----------------------------------------------------------------- resume snapshot+ def snapshot(self) -> BudgetSnapshot:+ """Point-in-time guard state for ``run_state.json`` so a resume continues the+ SAME budget instead of a fresh one. Grace and config are deliberately absent:+ grace is one attempt's salvage headroom — persisting it would ratchet the hard+ ceiling run over run, and the ceilings always come from the current spec."""+ with self._lock:+ return BudgetSnapshot(+ spent=self.spent.model_copy(deep=True),+ billed_usd=self.billed_usd,+ calls=self.calls,+ by_stage=dict(self.by_stage),+ by_round={r: dict(per) for r, per in self.by_round.items()},+ active_s=self._active_s + (time.time() - self.start_time),+ )++ def restore(self, snap: BudgetSnapshot) -> None:+ """Adopt a snapshot: money, calls and buckets keep counting; ``start_time``+ stays *now*, so ``elapsed_minutes`` is prior ACTIVE seconds plus this session+ — never the downtime in between. The ceilings come from the (possibly raised)+ spec budget, so a raised ``--max-usd`` grants exactly the difference, never a+ fresh full cap."""+ with self._lock:+ self.spent = snap.spent.model_copy(deep=True)+ self.billed_usd = float(snap.billed_usd)+ self.calls = int(snap.calls)+ self.by_stage = dict(snap.by_stage)+ self.by_round = {int(r): dict(per) for r, per in snap.by_round.items()}+ self._active_s = float(snap.active_s)+ self.start_time = time.time()+def elapsed_minutes(self) -> float:- return (time.time() - self.start_time) / 60.0+ """Cumulative ACTIVE minutes: prior sessions' seconds (restored from the+ snapshot) plus this session's wall clock. Downtime costs nothing."""+ return (self._active_s + (time.time() - self.start_time)) / 60.0# ----------------------------------------------------------------- ceilings@property@@ -297,6 +335,25 @@ class BudgetGuard:return {k: round(v, 6) for k, v in sorted(self.by_stage.items(), key=lambda kv: -kv[1])}+class BudgetSnapshot(BaseModel):+ """What survives a resume (``run_state.extra["budget_snapshot"]``).++ The five accumulator fields of :class:`BudgetGuard` plus cumulative ACTIVE+ seconds. Grace (``grace_usd``/``grace_minutes``) and config (ceilings, soft+ fraction, run, ledger) are EXCLUDED on purpose: grace is per-attempt salvage+ headroom — persisting it would ratchet the hard ceiling — and config always+ comes from the current spec/settings."""++ version: int = 1+ spent: Usage+ billed_usd: float+ calls: int+ by_stage: dict[str, float]+ #: matches the ``BudgetGuard.by_round`` / ``round_costs()`` shape+ by_round: dict[int, dict[str, float]]+ active_s: float++def usage_delta(after: Usage, before: Usage) -> Usage:"""``after - before`` field by field (never negative). Used to report what around burned when it raised before it could fold its own usage together."""diff --git a/harness/codeverse/tracks/candidates.py b/harness/codeverse/tracks/candidates.pyindex e606248a..ab411527 100644--- a/harness/codeverse/tracks/candidates.py+++ b/harness/codeverse/tracks/candidates.py@@ -81,10 +81,14 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],results[k] = rrecords: list[CandidateRecord] = []renders: dict[int, RenderSet] = {}+ budget_stop: BudgetExceeded | None = Nonefor k, r in enumerate(results):- if isinstance(r, BudgetExceeded):- raise rif isinstance(r, Exception):+ # a candidate that tripped the ceiling is a failed candidate, not the+ # round's verdict: the sibling's finished work is still selected, adopted+ # and persisted below; the guard's boundary check stops the run afterwards.+ if isinstance(r, BudgetExceeded) and budget_stop is None:+ budget_stop = rrecords.append(CandidateRecord(index=k, label=f"c{k}", workspace=str(subs[k].ws.root),notes=f"{type(r).__name__}: {r}"[:300]))ctx.events.emit("candidate.failed", candidate=k, error=f"{type(r).__name__}: {r}"[:300])@@ -94,6 +98,8 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],if rs is not None:renders[k] = rsif not any(r.commit for r in records):+ if budget_stop is not None:+ raise budget_stop # nothing usable survived: the budget stop standsraise RoundFailed("; ".join(f"{r.label}: {r.notes}" for r in records) or "every candidate failed")best, note = select_candidate(ctx, records, renders)records[best].selected = True@@ -118,6 +124,7 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],f"(quick score {records[best].score if records[best].score is None else round(records[best].score, 3)}; others: {others or '-'})"]if note is not None:notes.append(note.line())+ ctx.budget.check() # boundary: the winner is adopted + persisted; a real ceiling stop lands herereturn run_round(ctx, index=0, kind="baseline", tasks=[], pipeline=pipeline, files_hint=list(files_hint),extra_usage=usage, extra_notes=notes)diff --git a/harness/codeverse/tracks/generation.py b/harness/codeverse/tracks/generation.pyindex 83b1589f..e5c3ce49 100644--- a/harness/codeverse/tracks/generation.py+++ b/harness/codeverse/tracks/generation.py@@ -251,7 +251,11 @@ def generate_files()resp = model.generate(req)usage = resp.usage- _charge(budget, usage, task=task, label=task.label, outcome=str(resp.finish_reason or "ok"))+ # book the money WITHOUT enforcing: the response is already paid for, and raising+ # here would discard it before transcript/parse/write_files. The ceiling is+ # enforced at the round's phase boundary instead (steps._run_phase).+ _charge(budget, usage, task=task, label=task.label, outcome=str(resp.finish_reason or "ok"),+ enforce=False)if _is_truncated(resp):# cut off by max_output_tokens: the envelope is unterminated — one retry with# a doubled budget beats writing a half-file and burning repair attempts on it@@ -265,7 +269,8 @@ def generate_files(req = req.model_copy(update={"max_output_tokens": min(task.max_output_tokens * 2, 65536)})resp = model.generate(req)usage = usage + resp.usage- _charge(budget, resp.usage, task=task, label=f"{task.label}.retry", outcome="truncated")+ _charge(budget, resp.usage, task=task, label=f"{task.label}.retry", outcome="truncated",+ enforce=False)traj = ws.trajectory_dir(task.label.replace("/", "_"), task.round)(traj / "prompt.md").write_text(f"# system\n{system}\n\n# user\n{task.prompt}\n")(traj / "response.md").write_text(resp.text or "")@@ -353,9 +358,14 @@ def task_stage(task: GenerationTask) -> str:def _charge(- budget: Any | None, usage: Usage, *, task: GenerationTask, label: str, outcome: str = "ok"+ budget: Any | None, usage: Usage, *, task: GenerationTask, label: str, outcome: str = "ok",+ enforce: bool = True,) -> None:- """Spend through the guard with the stage/label/round this task belongs to."""+ """Spend through the guard with the stage/label/round this task belongs to.++ ``enforce=False`` books the dollar without raising — the single-shot path uses it+ so a paid response is still parsed and written to disk; the ceiling is enforced at+ the round's phase boundary (``steps._run_phase``) after the work is persisted."""if budget is None:returnbudget.charge(@@ -365,6 +375,7 @@ def _charge(label=label,round_index=task.round,outcome=outcome,+ enforce=enforce,)diff --git a/harness/codeverse/tracks/lifecycle.py b/harness/codeverse/tracks/lifecycle.pyindex 8a922373..92e8376f 100644--- a/harness/codeverse/tracks/lifecycle.py+++ b/harness/codeverse/tracks/lifecycle.py@@ -26,7 +26,7 @@ from codeverse.contracts.plan import Planfrom codeverse.contracts.run import RoundRecord, RunRecord, RunStatusfrom codeverse.contracts.spec import Specfrom codeverse.events import EventLog-from codeverse.orchestrator.budget import BudgetExceeded, BudgetGuard+from codeverse.orchestrator.budget import BudgetExceeded, BudgetGuard, BudgetSnapshotfrom codeverse.orchestrator.rounds import (BestSelector,RefineTask,@@ -330,7 +330,7 @@ class BaseTrack:except Exception as e: # noqa: BLE001 — persist a FAILED record, then fail louderror = f"{type(e).__name__}: {e}"events.emit("run.failed", error=error, traceback=traceback.format_exc()[-3000:])- self._save_spent(ctx) # mid-round charges must survive for resume+ self._save_budget(ctx) # mid-round charges must survive for resumestate.status, state.error = RunStatus.FAILED, errorstate.save(ws)rec = self._record(ctx, rounds, RunStatus.FAILED, error=error, stop_reason="failed")@@ -346,9 +346,15 @@ class BaseTrack:runtime = self._runtime or self.services.runtime(spec.language)budget = BudgetGuard(spec.budget, soft_fraction=self.soft_budget_fraction,run=ws.root.name, ledger=run_ledger_path(ws))- spent = state.extra.get("spent_usage")- if spent:- budget.spent = Usage.model_validate(spent)+ snap = state.extra.get("budget_snapshot")+ if snap:+ # full guard state: money, calls, buckets AND active minutes keep counting,+ # so a raised --max-usd grants only the difference, never a fresh full cap.+ budget.restore(BudgetSnapshot.model_validate(snap))+ else:+ spent = state.extra.get("spent_usage") # legacy run dirs (pre-snapshot)+ if spent:+ budget.spent = Usage.model_validate(spent)n_cand = self._resolve_candidates(spec, state, settings)policy = ((self._policy or RoundPolicy(max_rounds=spec.budget.max_rounds)).with_candidates(n_cand).with_judge(spec.backends.judge))@@ -419,7 +425,7 @@ class BaseTrack:plan = run_planner(ctx.spec, ctx.spec.backends.planner, self.plan_model, ctx.ws, model=self._planner_model,events=ctx.events, budget=ctx.budget, runtime=ctx.runtime, **self._plan_kwargs(ctx.spec))finally:- self._save_spent(ctx) # charged on success AND PlanningError+ self._save_budget(ctx) # charged on success AND PlanningErrorreturn plandef _plan_kwargs(self, spec: Spec) -> dict[str, Any]:@@ -493,7 +499,7 @@ class BaseTrack:best = choose_best_round(ctx, rounds, selector, last.index)if best is not None and ctx.state.update_best(best, rounds[best].commit, rounds[best].score):ctx.events.emit("best.updated", round=best, score=rounds[best].score)- self._save_spent(ctx)+ self._save_budget(ctx)continue # decide() re-runs with the recovered scoretasks, instructions = self.refine_tasks(ctx, last, rounds, strategy=decision.strategy)kind = kind_for_strategy(decision.strategy)@@ -528,7 +534,7 @@ class BaseTrack:best = choose_best_round(ctx, rounds, selector, index)if best is not None and ctx.state.update_best(best, rounds[best].commit, rounds[best].score):ctx.events.emit("best.updated", round=best, score=rounds[best].score)- self._save_spent(ctx)+ self._save_budget(ctx)def _salvage_baseline(self, ctx: RunContext, rounds: list[RoundRecord]) -> None:"""A stage tripped the budget BEFORE round 0 ever ran (the greenhouse scene:@@ -563,15 +569,18 @@ class BaseTrack:ctx.state.mark_round_done(0, rec.commit)if ctx.state.update_best(0, rec.commit, rec.score):ctx.events.emit("best.updated", round=0, score=rec.score)- self._save_spent(ctx)+ self._save_budget(ctx)- def _save_spent(self, ctx: RunContext) -> None:- ctx.state.extra["spent_usage"] = ctx.budget.spent.model_dump(mode="json")+ def _save_budget(self, ctx: RunContext) -> None:+ snap = ctx.budget.snapshot()+ ctx.state.extra["budget_snapshot"] = snap.model_dump(mode="json")+ # legacy mirror, kept for one release: older tooling/tests still read spent_usage+ ctx.state.extra["spent_usage"] = snap.spent.model_dump(mode="json")ctx.state.save(ctx.ws)# ------------------------------------------------------------------ finalisedef finalise(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, stop_reason: str, error: str = "") -> RunRecord:- self._save_spent(ctx) # aborted-round / stage charges must survive for resume+ self._save_budget(ctx) # aborted-round / stage charges must survive for resumebest = ctx.state.best_roundif 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)diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.pyindex 0e8dce47..a691ff6c 100644--- a/harness/codeverse/tracks/planner.py+++ b/harness/codeverse/tracks/planner.py@@ -120,23 +120,20 @@ def plan[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Worksevent_stats: EventStats | None = None) -> P:"""Plan and write ``ws.plan_path``. ``model`` may be injected (tests).- The money budget is charged on success AND on ``PlanningError`` — a failed- re-ask (and the brief that preceded it) is still paid for."""- try:- result, usage = plan_with_usage(spec, model_id, plan_model, ws, model=model, events=events, runtime=runtime,- template=template, example=example, temperature=temperature,- max_output_tokens=max_output_tokens, finalise=finalise, event_stats=event_stats)- except PlanningError as e:- if budget is not None:- budget.charge(e.usage)- raise+ Every attempt's money is booked inside ``plan_with_usage`` the moment it is+ paid (brief, first call, each re-ask) — success, ``PlanningError`` and a crash+ on a LATER attempt all leave the earlier dollars in the guard. The ceilings+ are enforced once here, after the plan is written."""+ result, _ = plan_with_usage(spec, model_id, plan_model, ws, model=model, events=events, guard=budget,+ runtime=runtime, template=template, example=example, temperature=temperature,+ max_output_tokens=max_output_tokens, finalise=finalise, event_stats=event_stats)if budget is not None:- budget.charge(usage)+ budget.check()return resultdef plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Workspace, *, model: Any | None = None,- events: Any | None = None, runtime: Any | None = None, template: str | None = None,+ events: Any | None = None, guard: Any | None = None, runtime: Any | None = None, template: str | None = None,example: dict[str, Any] | None = None, temperature: float = 0.4, max_output_tokens: int = 24000,finalise: FinalisePlan | None = None, event_stats: EventStats | None = None) -> tuple[P, Usage]:"""Optional brief expansion → one structured planner call → up to two re-asks.@@ -155,7 +152,14 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]Output room comes from :func:`plan_tokens` (the budget sizes it), and a``finish_reason=MAX_TOKENS`` error buys ONE more attempt with half again as much roominstead of killing the run — the deeper plan is longer JSON and Gemini bills thinking- against the same ceiling."""+ against the same ceiling.++ ``guard`` (a ``BudgetGuard``; named so because ``budget`` is this function's local+ PlanBudget) is booked with a non-enforcing ``add`` the moment each call is PAID —+ brief, first call, every re-ask — so a later attempt that raises can never erase an+ earlier attempt's dollars. ``PlanningError`` still carries the total usage for+ guard-less callers; when ``guard`` is given those dollars are already booked and the+ caller must NOT charge them again (:func:`plan` just runs one final ``check()``)."""if model is None:from codeverse.models import get_chat_model@@ -163,6 +167,8 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]brief, usage = (None, Usage())if brief_enabled(spec):brief, usage = expand_brief(spec, model_id, model=model, events=events)+ if guard is not None and (usage.cost_usd or usage.input_tokens or usage.output_tokens):+ guard.add(usage, stage="plan", role="planner", label="planner-brief")budget = plan_budget(spec, brief)unit = "passes" if spec.track is Track.GRAPHICS else "parts"system = build_system_prompt(spec, plan_model, runtime=runtime, template=template, example=example, budget=budget)@@ -188,6 +194,10 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]events.emit("plan.truncated", attempt=attempt, max_output_tokens=tokens)continueusage = usage + resp.usage+ if guard is not None:+ # booked where it is paid: a later attempt that raises cannot erase this dollar+ guard.add(resp.usage, stage="plan", role="planner",+ label=f"planner{'-retry' if attempt else ''}")raw = resp.parsed if resp.parsed is not None else _parse_json(resp.text)try:if not isinstance(raw, dict):diff --git a/harness/codeverse/tracks/scene.py b/harness/codeverse/tracks/scene.pyindex 5e440937..c5958b6e 100644--- a/harness/codeverse/tracks/scene.py+++ b/harness/codeverse/tracks/scene.py@@ -298,10 +298,8 @@ class SceneTrack(BaseTrack):out: dict[str, Any] = {}for batch, r in zip(batches, results, strict=True):if isinstance(r, Exception):- from codeverse.orchestrator.budget import BudgetExceeded-- if isinstance(r, BudgetExceeded):- raise r+ # BudgetExceeded included: the sibling zones' paid modules are still+ # recorded + committed; the guard's boundary check below stops the run.for zone in batch:out[zone.name] = {"ok": False, "notes": f"{type(r).__name__}: {r}"}else:@@ -316,6 +314,7 @@ class SceneTrack(BaseTrack):self._record_skills(zone_gen, "zone")ctx.ws.commit("zones")ctx.events.emit("zones.done", ok=[k for k, v in out.items() if v["ok"]], failed=[k for k, v in out.items() if not v["ok"]])+ ctx.budget.check() # stage boundary: stop only after the finished zones are committedreturn outdef _zone_task(self, ctx: RunContext, batch: list[ZonePlan]) -> GenerationTask:diff --git a/harness/codeverse/tracks/scene_assets.py b/harness/codeverse/tracks/scene_assets.pyindex e8b2a2d7..c04b1c52 100644--- a/harness/codeverse/tracks/scene_assets.py+++ b/harness/codeverse/tracks/scene_assets.py@@ -143,10 +143,9 @@ def run_asset_stage(ctx: RunContext, *, judge_assets: bool = True) -> dict[str,out: dict[str, AssetResult] = {}for asset, r in zip(assets, results, strict=True):if isinstance(r, Exception):- from codeverse.orchestrator.budget import BudgetExceeded-- if isinstance(r, BudgetExceeded):- raise r+ # a BudgetExceeded worker is a failed asset like any other: the siblings'+ # finished modules are still shimmed + committed below, and the guard's own+ # boundary check stops the run AFTER the paid work is persisted.out[asset.name] = AssetResult(name=asset.name, kind=asset.kind, ok=False, notes=f"{type(r).__name__}: {r}")ctx.events.emit("asset.failed", asset=asset.name, error=f"{type(r).__name__}: {r}")else:@@ -155,6 +154,7 @@ def run_asset_stage(ctx: RunContext, *, judge_assets: bool = True) -> dict[str,ctx.ws.commit("assets")ctx.events.emit("assets.done", ok=[n for n, r in out.items() if r.ok], failed=[n for n, r in out.items() if not r.ok],strategies={n: r.strategy for n, r in out.items() if r.strategy}, variant_shims=shims)+ ctx.budget.check() # stage boundary: stop only after the finished assets are committedreturn out@@ -355,9 +355,12 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rendeexcept Exception as e: # noqa: BLE001events.emit("asset.judge_failed", asset=asset.name, error=f"{type(e).__name__}: {e}")return result- ctx.budget.charge(verdict.usage)+ # persist the verdict on the result FIRST, then book the money non-enforcing like+ # every other judge site (steps.py, candidates.py): the verdict is already paid+ # for, and raising here would discard it. The stage boundary enforces the ceiling.result.score = verdict.overallresult.judged = True+ ctx.budget.add(verdict.usage, stage="judge", role="judge", label=f"asset_{to_snake(asset.name)}")events.emit("asset.judged", asset=asset.name, score=round(verdict.overall, 3), passed=verdict.passed)if verdict.passed or not verdict.improvement_plan:return resultdiff --git a/harness/codeverse/tracks/steps.py b/harness/codeverse/tracks/steps.pyindex 4212904e..c2a8bb46 100644--- a/harness/codeverse/tracks/steps.py+++ b/harness/codeverse/tracks/steps.py@@ -126,18 +126,22 @@ def _run_phase(ctx: RunContext, tasks: Sequence[GenerationTask]) -> list[Generatresults = fan_out(list(tasks), _one, max_workers=ctx.settings.limits.max_parallel_agents,label="generate", item_name=lambda t: t.label)out: list[GenerationResult] = []+ budget_stop: Exception | None = Nonefor task, r in zip(tasks, results, strict=True):if isinstance(r, Exception):from codeverse.orchestrator.budget import BudgetExceeded- if isinstance(r, BudgetExceeded):- raise r+ if isinstance(r, BudgetExceeded) and budget_stop is None:+ budget_stop = r # a failed item; the siblings' paid results still land in ``out``ctx.events.emit("generate.failed", label=task.label, error=f"{type(r).__name__}: {r}")out.append(GenerationResult(ok=False, notes=f"{type(r).__name__}: {r}", label=task.label))else:out.append(r)if not any(r.ok for r in out):+ if budget_stop is not None:+ raise budget_stop # nothing usable survived the phaseraise RoundFailed("; ".join(f"{r.label}: {r.notes}" for r in out) or "no generation task succeeded")+ ctx.budget.check() # phase boundary: single-shot money is booked non-enforcing upstreamreturn outdiff --git a/harness/docs/COST.md b/harness/docs/COST.mdindex f71d6243..521b887a 100644--- a/harness/docs/COST.md+++ b/harness/docs/COST.md@@ -406,8 +406,10 @@ Two helpers exist for the callers:but no tokens, so those rows have no token composition ($2.50 of $86.30).Wiring `record_call` at those call sites fixes it.* Wall clock per run is the sum of the stage/round clocks (the event span- includes hours a bench run spent queued behind other runs, and- `budget.elapsed_min` restarts on `3dcv resume`).+ includes hours a bench run spent queued behind other runs). `budget.elapsed_min`+ is cumulative ACTIVE minutes: the budget snapshot carries `active_s` across+ `3dcv resume`, so prior sessions' minutes still count against `max_minutes`+ and downtime between sessions never does.* "Regression" waste is an upper bound: a round that scored worse still producedthe diff that informed the next refine task.* The compare battery is only 2 prompts × 5 arms; its per-arm numbers arediff --git a/harness/docs/DECISIONS.md b/harness/docs/DECISIONS.mdindex 6208a6ed..52d3b0f6 100644--- a/harness/docs/DECISIONS.md+++ b/harness/docs/DECISIONS.md@@ -47,8 +47,12 @@ written) that were accepted because the code works that way and the tests pin it* **D6 Finalise restores the best commit and rebuilds.** Artifacts always match thedelivered code; export copies `artifacts/object.glb` trusting that.* **D7 Stage cache by input hash.** `StageRunner` stores `stages/<name>.json` keyed by a- hash of the inputs, so `3dcv resume` re-runs only what changed; spent budget is- restored from `run_state.extra.spent_usage`.+ hash of the inputs, so `3dcv resume` re-runs only what changed; the budget guard is+ restored from `run_state.extra.budget_snapshot` (`BudgetSnapshot`: spent usage, billed+ USD, call count, per-stage/per-round buckets, cumulative ACTIVE seconds — grace is+ deliberately NOT persisted). Prior spend and active minutes still count after a+ resume, so a raised `--max-usd` grants only the difference; `spent_usage` is mirrored+ for one release, and old run dirs without a snapshot fall back to it (spent only).* **D8 Events carry `event`, not `kind` (Δ).** `EventLog.emit(event, **data)` so payloadsmay include `kind=` (round kind). `3dcv status` and tests follow.* **D9 `materialize_workspace` returns `Materialized` (Δ).** Callers need codex `-c`diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.mdindex e780258c..8f5faa9f 100644--- a/harness/docs/RUNBOOK.md+++ b/harness/docs/RUNBOOK.md@@ -144,7 +144,9 @@ unless you type `--host` yourself; it never serves a path outside the declared r## 5. Resume, re-render, re-judge, texture, export```bash-3dcv resume <slug> [--candidates N] # continues from run_state + stages/*.json (input-hash cached; budget restored)+3dcv resume <slug> [--candidates N] # continues from run_state + stages/*.json (input-hash cached). The budget+ # SNAPSHOT is restored: money/calls/active-minutes already spent still count,+ # so a raised --max-usd grants only the difference (downtime is never billed)3dcv render <slug> [--round N] [--mode shaded|wire|normals|clay|silhouette] [--out dir]3dcv judge <slug> [--round N] [--rubric static_object_v1] [--model gemini:gemini-3.1-pro-preview] [--n 3]# re-judges a round's recorded renders → artifacts/judge/rNN_cli.jsondiff --git a/harness/tests/orchestrator_tracks/test_budget_snapshot.py b/harness/tests/orchestrator_tracks/test_budget_snapshot.pynew file mode 100644index 00000000..cb0e3f95--- /dev/null+++ b/harness/tests/orchestrator_tracks/test_budget_snapshot.py@@ -0,0 +1,178 @@+"""Budget continuity across resume + charge-before-persist ordering.++A resume used to rebuild the guard with only ``spent`` restored: ``billed_usd``,+``calls``, the stage/round buckets and the wall clock all restarted at zero, so+after a resume the money/time already spent no longer constrained new work and a+raised ``--max-usd`` granted a FULL fresh cap. The guard now snapshots and+restores its whole accumulator state (``BudgetSnapshot``), and paid work is+persisted BEFORE the ceiling is enforced: single-shot responses are written to+disk, fan-out siblings are arbitrated/adopted, and planner attempts are booked+the moment each call is paid.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from codeverse.contracts.common import Budget, Language, Usage+from codeverse.contracts.plan import StaticPlan+from codeverse.contracts.run import RunStatus+from codeverse.events import EventLog+from codeverse.orchestrator.budget import BudgetExceeded, BudgetGuard, BudgetSnapshot+from codeverse.orchestrator.state import RunState+from codeverse.tracks.generation import GenerationTask, generate_files+from codeverse.tracks.planner import MAX_VALIDATION_REASKS, PlanningError+from codeverse.tracks.planner import plan as run_planner+from codeverse.tracks.static_object import StaticObjectTrack+from codeverse.workspace import Workspace+from tests.orchestrator_tracks.conftest import make_spec+from tests.orchestrator_tracks.fakes import (+ FakeAgent,+ FakeChatModel,+ FakeJudge,+ FakeRuntime,+ FakeServices,+)+++# --------------------------------------------------------------- snapshot / restore+def test_resume_restores_money_calls_and_active_time_but_not_downtime():+ g1 = BudgetGuard(Budget(max_usd=1.0, max_minutes=10.0))+ g1.charge(Usage(backend="gemini", cost_usd=0.6), stage="baseline", round_index=0, label="baseline")+ g1.add(Usage(backend="gemini", cost_usd=0.05), stage="judge", role="judge", round_index=0)+ g1.start_time -= 120 # two minutes of ACTIVE work in the first session+ snap = g1.snapshot()+ assert snap.version == 1 and snap.active_s == pytest.approx(120, abs=2)++ # the exact round-trip run_state.json takes: model_dump(mode="json") → validate+ revived = BudgetSnapshot.model_validate(json.loads(json.dumps(snap.model_dump(mode="json"))))+ g2 = BudgetGuard(Budget(max_usd=1.0, max_minutes=10.0))+ g2.restore(revived)+ assert g2.billed_usd == pytest.approx(0.65) and g2.calls == 2+ assert g2.by_stage == {"baseline": pytest.approx(0.6), "judge": pytest.approx(0.05)}+ assert g2.round_costs(0) == {"baseline": pytest.approx(0.6), "judge": pytest.approx(0.05)}+ # ACTIVE minutes carry over; the downtime between the sessions cost nothing+ assert g2.elapsed_minutes() == pytest.approx(2.0, abs=0.1)+ g2.start_time -= 60 # one more ACTIVE minute in THIS session accumulates on top+ assert g2.elapsed_minutes() == pytest.approx(3.0, abs=0.1)+ # prior spend still constrains new work: 0.65 + 0.5 > 1.0+ with pytest.raises(BudgetExceeded):+ g2.charge(Usage(backend="gemini", cost_usd=0.5), stage="refine")++ # prior ACTIVE time still constrains the wall clock immediately after a resume+ g3 = BudgetGuard(Budget(max_usd=10.0, max_minutes=1.0))+ g3.restore(revived)+ with pytest.raises(BudgetExceeded):+ g3.check()+++def test_a_raised_cap_grants_only_the_difference_and_grace_never_persists():+ g1 = BudgetGuard(Budget(max_usd=1.0, max_minutes=10.0))+ g1.charge(Usage(backend="gemini", cost_usd=0.9), stage="baseline")+ g1.grant_grace(usd=5.0, minutes=30.0) # per-attempt salvage headroom — must NOT survive+ snap = g1.snapshot()+ assert "grace_usd" not in snap.model_dump() and "soft_fraction" not in snap.model_dump()++ g2 = BudgetGuard(Budget(max_usd=1.5, max_minutes=10.0)) # --max-usd raised 1.0 → 1.5+ g2.restore(snap)+ assert g2.grace_usd == 0.0 and g2.grace_minutes == 0.0+ assert g2.remaining()["usd"] == pytest.approx(0.6) # the difference, never a fresh $1.50+ g2.charge(Usage(backend="gemini", cost_usd=0.5), stage="refine") # fits+ with pytest.raises(BudgetExceeded):+ g2.charge(Usage(backend="gemini", cost_usd=0.2), stage="refine")+++def test_build_context_restores_the_snapshot_and_falls_back_to_legacy_spent(tmp_path, settings):+ spec = make_spec(max_usd=1.0)+ ws = Workspace(tmp_path / "runs" / "r").create()+ track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.THREEJS))++ g = BudgetGuard(Budget(max_usd=1.0, max_minutes=10.0))+ g.charge(Usage(backend="gemini", cost_usd=0.4), stage="baseline", round_index=0)+ state = RunState()+ state.extra["budget_snapshot"] = g.snapshot().model_dump(mode="json")+ ctx = track.build_context(spec, ws, EventLog(ws.events_path), state)+ assert ctx.budget.billed_usd == pytest.approx(0.4) and ctx.budget.calls == 1+ assert ctx.budget.round_costs(0)["baseline"] == pytest.approx(0.4)++ # legacy fallback: an old run dir carries only spent_usage (spent restored, as before)+ state2 = RunState()+ state2.extra["spent_usage"] = Usage(backend="gemini", cost_usd=0.3).model_dump(mode="json")+ ctx2 = track.build_context(spec, ws, EventLog(ws.events_path), state2)+ assert ctx2.budget.spent.cost_usd == pytest.approx(0.3)+++# --------------------------------------------------------------- ordering: single-shot+def test_a_paid_single_shot_response_is_persisted_when_the_budget_trips(tmp_path):+ ws = Workspace(tmp_path / "ws").create()+ guard = BudgetGuard(Budget(max_usd=0.01, max_minutes=10.0))+ answer = ("=== FILE: src/object.js ===\n"+ "export function build(THREE) { return new THREE.Group(); }\n"+ "=== END FILE ===")+ model = FakeChatModel(lambda req: answer, cost=0.05) # this ONE call crosses max_usd+ task = GenerationTask(label="baseline", prompt="p", files_hint=["src/object.js"])+ res = generate_files(ws, model=model, task=task, budget=guard) # must NOT raise+ assert res.ok and (ws.src / "object.js").is_file()+ assert res.transcript_path and Path(res.transcript_path).is_file()+ assert guard.spent.cost_usd == pytest.approx(0.05) # booked, dollar for dollar+ assert not guard.ok() # the phase boundary (steps._run_phase) turns this into the stop+++# --------------------------------------------------------------- ordering: fan-out siblings+def test_a_budget_tripped_candidate_still_lets_the_sibling_be_adopted(tmp_path, chair_plan, settings):+ spec = make_spec(max_rounds=0)+ ws = Workspace(tmp_path / "runs" / "bo2")++ def writer(job, ws_):+ if ws_.root.name == "c0": # <ws>/_cand/c0 trips the ceiling mid-generation+ raise BudgetExceeded("cost $9.99 exceeds max_usd $5.00", spent_usd=9.99, elapsed_min=1.0)+ return {"src/object.js": f"// {job.label} in {ws_.root.name}\n"+ "export function build(THREE) { return new THREE.Group(); }\n"}++ 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(spec, ws)+ assert rec.status in (RunStatus.PLATEAU, RunStatus.PASSED)+ assert len(rec.rounds) == 1 and "best-of-2: selected c1" in rec.rounds[0].notes+ assert "c1" in (ws.src / "object.js").read_text() # the sibling's code was adopted+ cands = json.loads((ws.root / "rounds" / "candidates.json").read_text())+ assert cands["selected"] == 1 and "BudgetExceeded" in cands["candidates"][0]["notes"]+++# --------------------------------------------------------------- ordering: planner attempts+def test_planner_attempt_zero_usage_reaches_the_guard_when_attempt_one_raises(tmp_path):+ guard = BudgetGuard(Budget(max_usd=5.0, max_minutes=10.0))+ ws = Workspace(tmp_path / "run").create()+ calls = {"n": 0}++ def responder(req):+ calls["n"] += 1+ if calls["n"] == 1:+ return {"object_name": "Chair"} # schema-invalid → one re-ask+ raise RuntimeError("model fell over mid-retry")++ with pytest.raises(RuntimeError, match="fell over"):+ run_planner(make_spec(), "fake:planner", StaticPlan, ws,+ model=FakeChatModel(responder, cost=0.01), budget=guard)+ assert calls["n"] == 2+ assert guard.spent.cost_usd == pytest.approx(0.01) # attempt 0's dollars are booked+ assert guard.by_stage.get("plan") == pytest.approx(0.01) and guard.calls == 1+++def test_planning_error_dollars_are_booked_exactly_once(tmp_path):+ guard = BudgetGuard(Budget(max_usd=5.0, max_minutes=10.0))+ ws = Workspace(tmp_path / "run").create()++ def responder(req):+ return {"object_name": "Chair"} # never validates++ with pytest.raises(PlanningError) as ei:+ run_planner(make_spec(), "fake:planner", StaticPlan, ws,+ model=FakeChatModel(responder, cost=0.01), budget=guard)+ 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 totaldiff --git a/harness/tests/orchestrator_tracks/test_cost_latency.py b/harness/tests/orchestrator_tracks/test_cost_latency.pyindex 76aa6f29..cd675c1f 100644--- a/harness/tests/orchestrator_tracks/test_cost_latency.py+++ b/harness/tests/orchestrator_tracks/test_cost_latency.py@@ -286,14 +286,15 @@ def test_a_budget_stop_before_round_zero_still_delivers_a_judged_round(tmp_path,services = FakeServices(assemble=True)def writer(job, ws_):- if job.label.startswith("zones_") or job.label.startswith("zone_"):- # the greenhouse hole: the zone fan-out crosses the ceiling mid-stage- raise BudgetExceeded("cost $9.99 exceeds max_usd $5.00", spent_usd=9.99, elapsed_min=61.0)if job.label == "env":return {"src/env.js": "export function buildEnv(){}\n"}+ if job.label.startswith("zones_") or job.label.startswith("zone_"):+ return {rel: "export function build(){}\n" for rel in (job.files_hint or ["src/zones/x.js"])}return {f"src/assets/{job.label[6:]}.js": f"export function build(){{}} // {job.label}\n"}- track = SceneTrack(services=services, judge=FakeJudge(scores=(0.58,)), agent=FakeAgent(writer),+ # the greenhouse hole: 2 asset sessions + env stay under $5; the zone session's own+ # (real, guard-enforced) charge crosses the ceiling mid-stage: $1.30 × 4 = $5.20+ track = SceneTrack(services=services, judge=FakeJudge(scores=(0.58,)), agent=FakeAgent(writer, cost=1.3),planner_model=_planner(plan.model_dump(mode="json")), settings=settings,runtime=FakeRuntime(Language.SCENE_THREEJS))rec = track.run(spec, ws)diff --git a/harness/tests/orchestrator_tracks/test_fix_batch2.py b/harness/tests/orchestrator_tracks/test_fix_batch2.pyindex ef405174..2f5ceff6 100644--- a/harness/tests/orchestrator_tracks/test_fix_batch2.py+++ b/harness/tests/orchestrator_tracks/test_fix_batch2.py@@ -102,8 +102,11 @@ def test_finalise_restores_best_when_aborted_round_dirtied_src(tmp_path, chair_passert "baseline r0" in text and "refine" not in text # restored, not the aborted round's editsassert ws.changed_files() == [] # tree clean at the delivered commit# finding lifecycle.py:256 — the aborted round's charges survive into run_state for resume- spent = RunState.load(ws).extra["spent_usage"]+ state = RunState.load(ws)+ spent = state.extra["spent_usage"] # legacy mirror, kept one releaseassert spent["cost_usd"] == pytest.approx(0.025, abs=1e-6)+ snap = state.extra["budget_snapshot"]+ assert snap["billed_usd"] == pytest.approx(0.025, abs=1e-6) and snap["calls"] > 0# --------------------------------------------------------------------- finding: spent usage persisted on crash paths@@ -126,9 +129,11 @@ def test_spent_usage_saved_when_a_round_crashes(tmp_path, chair_plan, settings):runtime=FakeRuntime(Language.THREEJS))with pytest.raises(RuntimeError, match="gate exploded"):track.run(spec, ws)- spent = RunState.load(ws).extra["spent_usage"]+ state = RunState.load(ws)+ spent = state.extra["spent_usage"] # legacy mirror, kept one release# planner 0.002 + r0 agent 0.01 + r0 judge 0.003 + r1 agent 0.01 — the r1 charge must not vanishassert spent["cost_usd"] == pytest.approx(0.025, abs=1e-6)+ assert state.extra["budget_snapshot"]["billed_usd"] == pytest.approx(0.025, abs=1e-6)# --------------------------------------------------------------------- finding: degraded judge verdicts are glitches, not scores