Skip to content

Official Codebase of 3DCodeVerse

Python

tracks: a paid verdict survives a resume, and the guard stops bucketing what it never reads

gaoypeng4f7bda3be3b5
diff --git a/harness/codeverse/contracts/agent.py b/harness/codeverse/contracts/agent.py
index 2e62bf98..7008e01e 100644
--- a/harness/codeverse/contracts/agent.py
+++ b/harness/codeverse/contracts/agent.py
@@ -10,7 +10,6 @@ from __future__ import annotations
from pydantic import BaseModel, Field
-from codeverse.contracts.chat import ImagePart
from codeverse.contracts.common import Usage
@@ -55,12 +54,6 @@ class AgentJob(BaseModel):
"and the language entry file stay allowed). Refine tasks set this so a session fixing one "
"part cannot rewrite its neighbours.",
)
- images: list[ImagePart] = Field(
- default_factory=list,
- description="images for this task (reference photos; the contact sheet the judge scored). "
- "No vendor CLI takes an image on argv: ``tracks/generation.run_agent_task`` lists their "
- "paths in the prompt for the agent's own file/image tools.",
- )
always_writable: list[str] = Field(
default_factory=list,
description="files exempt from edit_only (the entry file, and only when the task OWNS it — "
diff --git a/harness/codeverse/contracts/artifacts.py b/harness/codeverse/contracts/artifacts.py
index b1c82138..70a61862 100644
--- a/harness/codeverse/contracts/artifacts.py
+++ b/harness/codeverse/contracts/artifacts.py
@@ -131,7 +131,6 @@ class RenderView(BaseModel):
class RenderSet(BaseModel):
views: list[RenderView] = Field(default_factory=list)
contact_sheet: str | None = Field(default=None, description="one labelled grid image of all views")
- turntable: str | None = None
renderer: str = ""
duration_ms: int = 0
console_errors: list[str] = Field(default_factory=list, description="(scenes) JS/WebGL errors seen")
diff --git a/harness/codeverse/contracts/run.py b/harness/codeverse/contracts/run.py
index 9acff9c8..7422b502 100644
--- a/harness/codeverse/contracts/run.py
+++ b/harness/codeverse/contracts/run.py
@@ -13,7 +13,7 @@ from __future__ import annotations
from datetime import UTC, datetime
from enum import StrEnum
from pathlib import PurePosixPath
-from typing import Any
+from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
@@ -31,7 +31,6 @@ class SkillRead(BaseModel):
deep: bool = Field(default=False, description="a references/*.md atime > mtime: the body was read and followed")
deep_measurable: bool = Field(default=True, description="False when the bundle ships no references/ file to probe")
body_tokens: int = 0
- first_seen_turn: int | None = Field(default=None, description="HISTORICAL, read-only: only the api-agent (deleted 2026-08-28) knew the exact turn of the first read; CLI agents leave it None")
reason: str = Field(default="", description="which route attached it, and which finding")
@@ -166,6 +165,28 @@ class RunStatus(StrEnum):
FAILED = "failed"
+class PairwiseNote(BaseModel):
+ """What a tie-break compared and what it concluded.
+
+ Lives on the round record because the comparison is a PAID judge call (~$0.05):
+ ``rNN.json`` is the durable artifact, so a resume replays the verdict instead of
+ re-ranking on score alone and silently reversing it
+ (``tracks.candidates.replay_best_round``)."""
+
+ a: str = Field(description="label of the incumbent (current best)")
+ b: str = Field(description="label of the challenger (new round / other candidate)")
+ winner: Literal["a", "b", "tie"] = "tie"
+ confidence: float = 0.0
+ accepted: bool = Field(default=False, description="True when the challenger replaces the incumbent")
+ reasons: list[str] = Field(default_factory=list)
+ usage: Usage = Field(default_factory=Usage)
+ error: str = ""
+
+ def line(self) -> str:
+ verdict = {"a": f"{self.a} wins", "b": f"{self.b} wins", "tie": "tie"}[self.winner]
+ return f"pairwise {self.a} vs {self.b}: {verdict} (confidence {self.confidence:.2f}) → {'replace' if self.accepted else 'keep'}"
+
+
class RoundRecord(BaseModel):
index: int
kind: str = Field(description="baseline | refine | repair | texture | asset:<name> ...")
@@ -183,6 +204,9 @@ class RoundRecord(BaseModel):
started_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
duration_s: float = 0.0
notes: str = ""
+ pairwise: PairwiseNote | None = Field(
+ default=None, description="the paid tie-break verdict that ranked this round against the "
+ "incumbent best, when one was bought; None = ranked on score alone")
@property
def score(self) -> float | None:
diff --git a/harness/codeverse/contracts/spec.py b/harness/codeverse/contracts/spec.py
index ed2c21b3..02bf72d1 100644
--- a/harness/codeverse/contracts/spec.py
+++ b/harness/codeverse/contracts/spec.py
@@ -32,8 +32,8 @@ class Constraints(BaseModel):
class RunOptions(BaseModel):
"""Run-shape options frozen on the spec (distinct from Budget and Backends).
- ``None`` / ``False`` means "not stated": resolution falls through to
- ``run_state.extra`` (legacy runs) and then ``Settings`` defaults.
+ ``None`` / ``False`` means "not stated": the resolver falls through to its
+ ``Settings`` default (``BaseTrack._resolve_candidates``, ``cost.profiles``).
"""
candidates: int | None = Field(default=None, ge=1, description="best-of-N baseline candidates")
diff --git a/harness/codeverse/flywheel/sample.py b/harness/codeverse/flywheel/sample.py
index f870d17a..30b51b8c 100644
--- a/harness/codeverse/flywheel/sample.py
+++ b/harness/codeverse/flywheel/sample.py
@@ -8,7 +8,7 @@ Sample folder (STORAGE_RULES §3/§8 compatible)::
robot.urdf (urdf_blender) copy of src/robot.urdf
meta.json SampleMeta (typed, below)
captions.json {detailed, instruction, factory} or {} when not captioned
- renders/ view_*.png, sheet.png, turntable.mp4, object.glb (< 20 MB)
+ renders/ view_*.png, sheet.png, object.glb (< 20 MB)
meshes/<link>.glb (urdf_blender) per-link meshes referenced by robot.urdf
"""
@@ -178,7 +178,7 @@ def write_code_tree(dest: Path, files: dict[str, bytes], language: Language) ->
def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str]:
- """Copy the round's views, contact sheet, turntable and a small object.glb."""
+ """Copy the round's views, contact sheet and a small object.glb."""
out: list[str] = []
rdir = dest / "renders"
rdir.mkdir(parents=True, exist_ok=True)
@@ -205,9 +205,6 @@ def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str
sheet = ws.rebase(rnd.renders.contact_sheet or "")
if sheet.is_file():
_cp(sheet, f"sheet{sheet.suffix or '.png'}")
- tt = ws.rebase(rnd.renders.turntable or "")
- if tt.is_file():
- _cp(tt, f"turntable{tt.suffix or '.mp4'}")
if not any(o.startswith("renders/sheet") for o in out):
packaged = ws.deliverable / "sheet.png" # new layout keeps the best sheet here
_cp(packaged if packaged.is_file() else None, "sheet.png")
diff --git a/harness/codeverse/orchestrator.py b/harness/codeverse/orchestrator.py
index 4671ee69..6fe92e0c 100644
--- a/harness/codeverse/orchestrator.py
+++ b/harness/codeverse/orchestrator.py
@@ -813,33 +813,24 @@ class BudgetGuard:
self.soft_fraction = min(1.0, max(0.0, float(soft_fraction)))
#: one-off extension of the HARD wall-clock ceiling (finalise/salvage headroom)
self.grace_minutes = 0.0
- #: stage -> USD and round -> {stage -> USD}, so a round can report what it burned
+ #: stage -> USD, so a stop can say where the money went
self.by_stage: dict[str, float] = {}
- self.by_round: dict[int, dict[str, float]] = {}
# ----------------------------------------------------------------- accounting
- def charge(
- self,
- usage: Usage | None,
- *,
- stage: str = OTHER_STAGE,
- role: str | None = None,
- label: str = "",
- round_index: int | None = None,
- outcome: str = "ok",
- enforce: bool = True,
- ) -> None:
+ def charge(self, usage: Usage | None, *, stage: str = OTHER_STAGE, enforce: bool = True) -> None:
"""THE door every dollar goes through — for bucketing and enforcement only.
- Accumulates ``usage``, buckets it by ``stage`` (and by round) and — when
- ``enforce`` — raises ``BudgetExceeded`` if a hard ceiling is now crossed.
+ Accumulates ``usage``, buckets it by ``stage`` and — when ``enforce`` — raises
+ ``BudgetExceeded`` if a hard ceiling is now crossed.
The ledger row is NOT written here: ``cost.instrument`` (MeteredAgent /
MeteredChatModel) is the one writer, one priced row per real call. Until
2026-08-29 this method kept a second, aggregate writer that fired whenever no
``run_ledger()`` was active — a direct ``track.run()`` without the CLI, or any
run with ``CV3D_COST_LEDGER=off`` (the guard's own ledger was opened
unconditionally), so ledger-off runs of that era carry one unpriced row per
- charge; a ledger-off run now writes nothing at all."""
+ charge; a ledger-off run now writes nothing at all. Role, label and round
+ went with that second writer (2026-08-30): ``CallCost`` carries all three per
+ call, so the guard bucketing them a second time fed nothing but itself."""
if usage is None:
return
with self._lock:
@@ -849,13 +840,10 @@ class BudgetGuard:
self.calls += 1
key = stage or OTHER_STAGE
self.by_stage[key] = self.by_stage.get(key, 0.0) + float(usage.cost_usd)
- if round_index is not None:
- per = self.by_round.setdefault(int(round_index), {})
- per[key] = per.get(key, 0.0) + float(usage.cost_usd)
if enforce:
self.check()
- def add(self, usage: Usage | None, **kw: Any) -> None:
+ def add(self, usage: Usage | None, *, stage: str = OTHER_STAGE) -> None:
"""Account for ``usage`` WITHOUT enforcing the ceilings.
For work that is already done and persisted (a completed judge verdict,
@@ -863,8 +851,7 @@ class BudgetGuard:
and raising here would throw away a finished, paid-for result. The
round loop stops at its next ``ok()`` check instead. The dollar is
still bucketed — "not enforced" never means "not seen"."""
- kw["enforce"] = False
- self.charge(usage, **kw)
+ self.charge(usage, stage=stage, enforce=False)
def mark(self) -> Usage:
"""Snapshot of the running total — diff it with :func:`usage_delta` to see
@@ -883,7 +870,6 @@ class BudgetGuard:
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),
)
@@ -898,7 +884,6 @@ class BudgetGuard:
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()
@@ -995,7 +980,7 @@ class BudgetGuard:
class BudgetSnapshot(BaseModel):
"""What survives a resume (``run_state.extra["budget_snapshot"]``).
- The five accumulator fields of :class:`BudgetGuard` plus cumulative ACTIVE
+ The four accumulator fields of :class:`BudgetGuard` plus cumulative ACTIVE
seconds. Grace (``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
@@ -1006,8 +991,6 @@ class BudgetSnapshot(BaseModel):
billed_usd: float
calls: int
by_stage: dict[str, float]
- #: matches the ``BudgetGuard.by_round`` shape
- by_round: dict[int, dict[str, float]]
active_s: float
diff --git a/harness/codeverse/tracks/candidates.py b/harness/codeverse/tracks/candidates.py
index 0ded9c03..1a066530 100644
--- a/harness/codeverse/tracks/candidates.py
+++ b/harness/codeverse/tracks/candidates.py
@@ -31,8 +31,9 @@ from pydantic import BaseModel, Field
from codeverse.contracts.artifacts import BuildResult, Measurement, RenderSet
from codeverse.contracts.common import Usage
-from codeverse.contracts.run import RoundRecord
+from codeverse.contracts.run import PairwiseNote, RoundRecord
from codeverse.conventions import OBJECT_VIEWS_QUICK
+from codeverse.cost.types import Stage
from codeverse.orchestrator import BestSelector, BudgetExceeded, gate_error_count
from codeverse.proc import EventLog, fan_out
from codeverse.tracks.common import RunContext
@@ -212,7 +213,7 @@ def select_candidate(ctx: RunContext, records: Sequence[CandidateRecord], render
decision, note = decide_best(a.score, b.score, margin=ctx.policy.pairwise_margin,
min_confidence=ctx.policy.pairwise_min_confidence, compare=compare, labels=(a.label, b.label))
if note is not None:
- ctx.budget.add(note.usage, stage="judge", role="judge", round_index=0, label="pairwise") # post-hoc: a finished comparison
+ ctx.budget.add(note.usage, stage=Stage.PAIRWISE) # post-hoc: a finished comparison
ctx.events.emit("pairwise.done", stage="candidates", a=note.a, b=note.b, winner=note.winner, confidence=note.confidence,
accepted=note.accepted, error=note.error, cost_usd=round(note.usage.cost_usd, 4))
if decision == "pairwise":
@@ -243,7 +244,8 @@ def choose_best_round(ctx: RunContext, rounds: list[RoundRecord], selector: Best
within ``policy.pairwise_margin`` of the current best: then a pairwise
comparison of the two render sets decides, and the new round replaces the
best only when it wins with ``confidence ≥ policy.pairwise_min_confidence``.
- The verdict is appended to the new round's notes and re-persisted."""
+ The verdict is stored on the round (``RoundRecord.pairwise``, plus a notes line)
+ and re-persisted, so :func:`replay_best_round` can reproduce it on resume."""
incumbent = ctx.state.best_round
if incumbent is None or incumbent >= len(rounds) or incumbent == new_index:
return selector.pick(rounds)
@@ -255,8 +257,9 @@ def choose_best_round(ctx: RunContext, rounds: list[RoundRecord], selector: Best
min_confidence=ctx.policy.pairwise_min_confidence, compare=compare,
labels=(f"r{incumbent:02d}", f"r{new_index:02d}"))
if note is not None:
- ctx.budget.add(note.usage, stage="judge", role="judge", round_index=new_index, label="pairwise") # post-hoc
+ ctx.budget.add(note.usage, stage=Stage.PAIRWISE) # post-hoc
new.usage = new.usage + note.usage
+ new.pairwise = note
new.notes = (new.notes + "; " if new.notes else "") + note.line()
ctx.ws.write_json(round_record_path(ctx, new_index), new)
ctx.events.emit("pairwise.done", stage="rounds", a=note.a, b=note.b, winner=note.winner, confidence=note.confidence,
@@ -266,6 +269,27 @@ def choose_best_round(ctx: RunContext, rounds: list[RoundRecord], selector: Best
return new_index if decision == "pairwise" else incumbent
+def replay_best_round(journal: Sequence[RoundRecord]) -> int | None:
+ """The best index the loop chose, replaying the paid pairwise verdicts it stored.
+
+ ``rNN.json`` + the git commit are durable BEFORE the best is promoted and the state
+ saved (``lifecycle._round_loop``), so a kill in that gap — or any resume of a run
+ whose state predates ``best_considered_through`` — used to re-rank on score alone
+ and reverse a ~$0.05 judgement the run had already bought (18 such runs on disk,
+ 2026-08-30). Walking the journal the way the live loop did keeps it: a round that
+ carries a :class:`PairwiseNote` was decided inside ``policy.pairwise_margin``, where
+ score ranking has nothing to say, so the stored verdict — replace or keep — wins;
+ every other round falls back to the same ``BestSelector`` ranking."""
+ selector = BestSelector()
+ best: int | None = None
+ for i, rec in enumerate(journal):
+ if rec.pairwise is None or best is None or best == i:
+ best = selector.pick(journal[:i + 1])
+ elif rec.pairwise.accepted:
+ best = i
+ return best
+
+
def _pairwise_fn(ctx: RunContext, renders_a: RenderSet | None, renders_b: RenderSet | None):
if renders_a is None or renders_b is None:
return None
@@ -303,23 +327,6 @@ def rank_candidates(records: Sequence[CandidateRecord]) -> list[int]:
return [r.index for r in sorted(records, key=lambda r: r.sort_key(), reverse=True)]
-class PairwiseNote(BaseModel):
- """What a tie-break compared and what it concluded (persisted in round notes)."""
-
- a: str = Field(description="label of the incumbent (current best)")
- b: str = Field(description="label of the challenger (new round / other candidate)")
- winner: Literal["a", "b", "tie"] = "tie"
- confidence: float = 0.0
- accepted: bool = Field(default=False, description="True when the challenger replaces the incumbent")
- reasons: list[str] = Field(default_factory=list)
- usage: Usage = Field(default_factory=Usage)
- error: str = ""
-
- def line(self) -> str:
- verdict = {"a": f"{self.a} wins", "b": f"{self.b} wins", "tie": "tie"}[self.winner]
- return f"pairwise {self.a} vs {self.b}: {verdict} (confidence {self.confidence:.2f}) → {'replace' if self.accepted else 'keep'}"
-
-
Decision = Literal["score", "pairwise", "keep"]
#: ``compare()`` → any object with ``winner`` ('a'|'b'|'tie'), ``confidence``, ``reasons``, ``usage``.
@@ -370,5 +377,6 @@ def decide_best(
return ("pairwise" if note.accepted else "keep"), note
-__all__ = ["CAND_DIR", "CandidateRecord", "PairwiseNote", "adopt_candidate", "choose_best_round", "decide_best",
- "make_candidate_context", "quick_render", "rank_candidates", "run_best_of_n", "select_candidate"]
+__all__ = ["CAND_DIR", "CandidateRecord", "adopt_candidate", "choose_best_round", "decide_best",
+ "make_candidate_context", "quick_render", "rank_candidates", "replay_best_round", "run_best_of_n",
+ "select_candidate"]
diff --git a/harness/codeverse/tracks/generation.py b/harness/codeverse/tracks/generation.py
index 4c9d51f8..0ceea7dd 100644
--- a/harness/codeverse/tracks/generation.py
+++ b/harness/codeverse/tracks/generation.py
@@ -25,10 +25,11 @@ A caller may still set one (``GenerationTask.max_turns`` > ``generate(max_turns=
profile sets), and a cap that IS set stays **graceful**: the session is not killed
but asked, in a short wrap-up (``agent_wrapup_turns``), for one last build + summary.
-**Every dollar is charged.** Both strategies spend through
-``BudgetGuard.charge`` with their stage / label / round, so a retried session
-(``<label>.a2``) and a wrap-up session are visible to the guard, the record and
-the ledger even when the *next* attempt then raises.
+**Every dollar is charged.** Both strategies spend through ``BudgetGuard.charge`` in
+the stage the task belongs to, so a retried session (``<label>.a2``) and a wrap-up
+session are visible to the guard, the record and the ledger even when the *next*
+attempt then raises. The label, round and outcome of each call are on the ledger row
+``cost.instrument`` writes, not on the guard (2026-08-30).
"""
from __future__ import annotations
@@ -391,8 +392,7 @@ def generate_files(
# 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)
+ _charge(budget, usage, task=task, 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. Already at the 65,536 model ceiling
@@ -411,7 +411,7 @@ def generate_files(
req = req.model_copy(update={"max_output_tokens": grown})
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,
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")
@@ -485,26 +485,19 @@ def task_stage(task: GenerationTask) -> str:
return str(stage) if stage is not Stage.OTHER else (task.label or "other")
-def _charge(
- 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.
+def _charge(budget: Any | None, usage: Usage, *, task: GenerationTask, enforce: bool = True) -> None:
+ """Spend through the guard in the stage 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."""
+ the round's phase boundary (``steps._run_phase``) after the work is persisted.
+
+ Label, round and outcome are NOT passed on (2026-08-30): the guard buckets by stage
+ and enforces, and the per-call record with all three is the ledger row
+ ``cost.instrument`` writes."""
if budget is None:
return
- budget.charge(
- usage,
- stage=task_stage(task),
- role="generator",
- label=label,
- round_index=task.round,
- outcome=outcome,
- enforce=enforce,
- )
+ budget.charge(usage, stage=task_stage(task), enforce=enforce)
_TRUNCATED_FINISH = {"max_tokens", "max_output_tokens", "length"}
@@ -579,7 +572,6 @@ def run_agent_task(
edit_only=task.edit_only,
always_writable=_always_writable(language, task),
read_only=_read_only(language),
- images=list(task.images),
**({"max_turns": turns_cap} if turns_cap > 0 else {}),
)
acc = _SessionAcc(task=task, budget=budget)
@@ -695,7 +687,7 @@ class _SessionAcc:
self.usage = self.usage + res.usage
self.turns += session_turns(res)
if res.usage.cost_usd or res.usage.input_tokens or res.usage.output_tokens: # an empty session books no call
- _charge(self.budget, res.usage, task=self.task, label=label, outcome=res.exit_reason or "ok")
+ _charge(self.budget, res.usage, task=self.task)
return res
@@ -718,8 +710,9 @@ def session_turns(res: Any) -> int:
def _images_block(images: list[ImagePart], ws: Workspace) -> str:
"""The task's images (reference photos, the judged contact sheet) as a prompt
section. No vendor CLI takes an image on argv, so the agent opens the files with
- its own file/image tools; until 2026-08-29 ``AgentJob.images`` was filled and read
- by nobody, so the contact sheet the judge scored reached no CLI session.
+ its own file/image tools; until 2026-08-29 the only carrier was ``AgentJob.images``,
+ which no backend read, so the contact sheet the judge scored reached no CLI session
+ (that field is gone since 2026-08-30 — this block IS the delivery).
Every image is copied into ``.3dcv/images/`` first, exactly as the cookbook is (D9),
and listed workspace-relative: a CLI reads only INSIDE its workspace (``--image
@@ -807,9 +800,7 @@ def _attributed_fallback(ws: Workspace, task: GenerationTask, before: str) -> li
from codeverse.agents.cli_common import attribute_changes
except ImportError: # pragma: no cover — agents package always ships with tracks
return raw
- return attribute_changes(
- raw, write_roots=list(task.write_roots), own_hints=frozenset(task.files_hint)
- )
+ return attribute_changes(raw, write_roots=list(task.write_roots))
def generate(
diff --git a/harness/codeverse/tracks/lifecycle.py b/harness/codeverse/tracks/lifecycle.py
index 17a1ddad..11ef426d 100644
--- a/harness/codeverse/tracks/lifecycle.py
+++ b/harness/codeverse/tracks/lifecycle.py
@@ -21,7 +21,7 @@ from typing import Any
from codeverse.config import Settings, get_settings
from codeverse.contracts.artifacts import GateReport
-from codeverse.contracts.common import Track, Usage
+from codeverse.contracts.common import Track
from codeverse.contracts.plan import Plan
from codeverse.contracts.run import RoundRecord, RunRecord, RunStatus
from codeverse.contracts.spec import Spec
@@ -48,7 +48,7 @@ from codeverse.orchestrator import (
)
from codeverse.proc import EventLog
from codeverse.prompts import render
-from codeverse.tracks.candidates import choose_best_round, run_best_of_n
+from codeverse.tracks.candidates import choose_best_round, replay_best_round, run_best_of_n
from codeverse.tracks.common import (
RunContext,
Services,
@@ -116,10 +116,10 @@ def _reconcile_billed_from_ledger(budget: BudgetGuard, ws: Workspace, events: Ev
row), and so do subscription-backend rows: their ``cost_usd`` is notional, not money
(the same ``bills_usd`` predicate the live path uses — ``BudgetGuard.charge``), so a
codex/claude/agy run resumed offline keeps billed at $0. A missing or unreadable
- ledger simply leaves the snapshot alone. ``load_ledger(root)`` reads the ledger the
- metered models/agents write (``telemetry/cost.jsonl``), else the root
- ``cost_ledger.jsonl`` that runs before 2026-08-23 wrote directly (bench/out keeps
- hundreds of those)."""
+ ledger simply leaves the snapshot alone. ``load_ledger(root)`` reads the one ledger
+ the metered models/agents write, ``telemetry/cost.jsonl``; the root-level
+ ``cost_ledger.jsonl`` leg went on 2026-08-30 (an audit of every run under $HOME found
+ 677 symlinks to that name and zero real files — ``LEDGER_NAME`` is the alias only)."""
try:
from codeverse.cost.billing import bills_usd
from codeverse.cost.ledger import load_ledger
@@ -402,10 +402,10 @@ class BaseTrack:
dropped (half-written journal), with a ``resume.dropped_rounds`` event.
3. **Rebuild.** ``completed_rounds``/``round_commits`` come from the journal;
when the state disagrees with it (rounds it never promoted, a best pointing
- at the wrong commit) the best is recomputed with ``BestSelector`` — the
- same ranking ``choose_best_round`` starts from, with no paid pairwise call.
- A state that already agrees keeps its best untouched (it may embody a paid
- pairwise keep-the-incumbent decision the pure ranking lacks).
+ at the wrong commit) the best is recomputed with :func:`replay_best_round`,
+ which re-walks the journal applying the pairwise verdicts the rounds stored
+ — never buying a new one, never reversing one already paid for.
+ A state that already agrees keeps its best untouched.
Returns the loop's initial round history. A fresh (non-resume) run only
stamps the fingerprint and starts empty."""
@@ -461,11 +461,11 @@ class BaseTrack:
best_changed = False
# an empty journal used to have its own arm; it is subsumed — with journal == []
# this condition is always true (best_invalid when a best is set, `best is None`
- # otherwise) and BestSelector().pick([]) is None, which clears the best the same
+ # otherwise) and replay_best_round([]) is None, which clears the best the same
# way. The only divergence, blanking a stale best_commit while best_round is
# None, is unobservable: no reader touches best_commit without best_round.
if stale or best_invalid or unranked or best is None:
- pick = BestSelector().pick(journal)
+ pick = replay_best_round(journal)
if pick is None:
best_changed = best is not None
state.best_round, state.best_commit, state.best_score = None, "", None
@@ -509,10 +509,6 @@ class BaseTrack:
# so a raised cap (--max-minutes / --rounds) 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)
_reconcile_billed_from_ledger(budget, ws, events)
policy = self._policy or RoundPolicy(max_rounds=spec.budget.max_rounds)
policy = replace(policy, n_candidates=self._resolve_candidates(spec, settings), judge_model=spec.backends.judge,
@@ -747,7 +743,7 @@ class BaseTrack:
if rounds and self._texture_wanted(ctx):
self._texture_pass(ctx)
ctx.state.status, ctx.state.stop_reason, ctx.state.error = status, stop_reason, error
- ctx.state.save(ctx.ws)
+ self._save_budget(ctx) # saves state too — AFTER the texture pass charged
rec = self._record(ctx, rounds, status, error=error, stop_reason=stop_reason)
self.services.finalize_record(ctx.ws, rec)
ctx.events.emit("run.done", status=status.value, stop=stop_reason, best_round=rec.best_round,
@@ -805,7 +801,7 @@ class BaseTrack:
log.warning("texture pass failed: %s", e)
ctx.events.emit("texture.failed", error=f"{type(e).__name__}: {e}")
return
- ctx.budget.add(trep.usage, stage="texture", role="image", label="texture_pass")
+ ctx.budget.add(trep.usage, stage="texture")
ctx.extra["texturing"] = trep.summary()
if not ctx.budget.ok():
# visible, but NOT `budget.exceeded`: that event means "the loop stopped",
diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.py
index a976c44c..949e6975 100644
--- a/harness/codeverse/tracks/planner.py
+++ b/harness/codeverse/tracks/planner.py
@@ -699,7 +699,7 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]
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")
+ guard.add(usage, stage="plan")
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)
@@ -727,8 +727,7 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]
usage = 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 ''}")
+ guard.add(resp.usage, stage="plan")
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_assets.py b/harness/codeverse/tracks/scene_assets.py
index 2bb77e76..bd706e68 100644
--- a/harness/codeverse/tracks/scene_assets.py
+++ b/harness/codeverse/tracks/scene_assets.py
@@ -358,7 +358,7 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
# 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.
- ctx.budget.add(verdict.usage, stage="judge", role="judge", label=f"asset_{to_snake(asset.name)}")
+ ctx.budget.add(verdict.usage, stage="judge")
if is_degraded(verdict):
# a degraded verdict is no verdict: score stays None and `judged` False, and the
# fix pass is skipped (its improvement_plan is empty by construction).
diff --git a/harness/codeverse/tracks/steps.py b/harness/codeverse/tracks/steps.py
index d33a3926..cc0550bd 100644
--- a/harness/codeverse/tracks/steps.py
+++ b/harness/codeverse/tracks/steps.py
@@ -287,8 +287,7 @@ def _run_round(
# add, never charge: the verdict exists and is paid for — raising here
# would drop a fully judged round before it is committed/recorded
# (the loop stops at its next budget_ok check instead, AFTER best promotion).
- ctx.budget.add(rec.judgment.usage, stage="judge", role="judge", round_index=index,
- label=rec.judgment.rubric or "judge")
+ ctx.budget.add(rec.judgment.usage, stage="judge")
else:
notes.append(f"build failed: {outcome.build.error_type}: {outcome.build.error_message[:200]}")
rec.gates = gates
@@ -462,8 +461,7 @@ def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildRes
paid = paid if isinstance(paid, Usage) else Usage()
if paid.cost_usd:
# the provider billed the failed attempt (ModelError.usage): book it
- ctx.budget.add(paid, stage="judge", role="judge", round_index=index,
- label="judge", outcome="failed")
+ ctx.budget.add(paid, stage="judge")
ctx.events.emit("judge.failed", round=index, error=f"{type(e).__name__}: {e}",
cost_usd=round(paid.cost_usd, 4))
notes.append(f"judge failed: {type(e).__name__}: {e}")
@@ -472,8 +470,7 @@ def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildRes
if is_degraded(judgment):
# a glitch, never a score: keep the raw verdict on disk, pay for it, but do not
# let 0.0 poison plateau/best/refine (judges/rubrics.degraded_judgment contract)
- ctx.budget.add(judgment.usage, stage="judge", role="judge", round_index=index,
- label=judgment.rubric or "judge", outcome="degraded")
+ ctx.budget.add(judgment.usage, stage="judge")
ctx.events.emit("judge.degraded", round=index, error=judgment.summary[:300],
cost_usd=round(judgment.usage.cost_usd, 4))
notes.append(f"judge degraded: {judgment.summary[:200]}")
@@ -512,8 +509,7 @@ def rejudge_round(ctx: RunContext, pipeline: RoundPipeline, rec: RoundRecord, pr
rec.judgment = judgment
rec.usage = rec.usage + judgment.usage
rec.notes = "; ".join(notes)
- ctx.budget.add(judgment.usage, stage="judge", role="judge", round_index=rec.index,
- label=judgment.rubric or "judge", outcome="rejudge")
+ ctx.budget.add(judgment.usage, stage="judge")
ctx.ws.write_json(round_record_path(ctx, rec.index), rec)
# the round's original cost.round went out as wasted=unjudged; emit the corrected
# one so the audit stream stops counting a now-scored round as wasted.
diff --git a/harness/tests/core/test_contract_additions.py b/harness/tests/core/test_contract_additions.py
index d883ecb6..dde19d12 100644
--- a/harness/tests/core/test_contract_additions.py
+++ b/harness/tests/core/test_contract_additions.py
@@ -93,3 +93,26 @@ def test_spec_options_do_not_change_the_plan_stage_hash():
plain = Spec(id="x", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a chair")
opted = plain.model_copy(update={"options": RunOptions(candidates=4, texture=True)})
assert hash_inputs(plan_stage_inputs(plain)) == hash_inputs(plan_stage_inputs(opted))
+
+
+def test_records_written_before_the_2026_08_30_field_retirements_still_load():
+ """RenderSet.turntable (360 records carry the key, none non-null), SkillRead.
+ first_seen_turn (an api-agent leftover) and AgentJob.images (dead once image staging
+ moved to .3dcv/images/) were deleted. Every model here ignores unknown keys, so the
+ stored runs on disk must keep re-reading — that is the whole licence for the delete."""
+ from codeverse.contracts.agent import AgentJob
+ from codeverse.contracts.run import RoundRecord, SkillRead
+
+ rs = RenderSet.model_validate({"renderer": "blender", "turntable": "renders/turntable.mp4",
+ "contact_sheet": "renders/sheet.png"})
+ assert rs.contact_sheet == "renders/sheet.png" and not hasattr(rs, "turntable")
+ sk = SkillRead.model_validate({"name": "bpy_modifiers", "surfaced": True, "first_seen_turn": None})
+ assert sk.surfaced and not hasattr(sk, "first_seen_turn")
+ job = AgentJob.model_validate({"workspace": "/w", "prompt": "p",
+ "images": [{"path": "renders/sheet.png", "label": "sheet"}]})
+ assert job.prompt == "p" and not hasattr(job, "images")
+ # and the field this batch ADDED round-trips through the round journal
+ rec = RoundRecord.model_validate({"index": 1, "kind": "refine",
+ "pairwise": {"a": "r00", "b": "r01", "winner": "a", "confidence": 0.9}})
+ assert rec.pairwise is not None and rec.pairwise.accepted is False
+ assert RoundRecord(index=0, kind="baseline").pairwise is None
diff --git a/harness/tests/orchestrator_tracks/test_budget_snapshot.py b/harness/tests/orchestrator_tracks/test_budget_snapshot.py
index b0c6f734..d27f84ff 100644
--- a/harness/tests/orchestrator_tracks/test_budget_snapshot.py
+++ b/harness/tests/orchestrator_tracks/test_budget_snapshot.py
@@ -4,12 +4,14 @@ from __future__ import annotations
import json
from pathlib import Path
+from types import SimpleNamespace
import pytest
from codeverse.contracts.common import Budget, Language, Usage
from codeverse.contracts.plan import StaticPlan
from codeverse.contracts.run import RunStatus
+from codeverse.contracts.spec import RunOptions
from codeverse.orchestrator import BudgetExceeded, BudgetGuard, BudgetSnapshot, RunState
from codeverse.proc import EventLog
from codeverse.tracks.generation import GenerationTask, generate_files
@@ -30,8 +32,8 @@ from tests.orchestrator_tracks.fakes import (
# --------------------------------------------------------------- snapshot / restore
def test_resume_restores_money_calls_and_active_time_but_not_downtime():
g1 = BudgetGuard(Budget(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.charge(Usage(backend="gemini", cost_usd=0.6), stage="baseline")
+ g1.add(Usage(backend="gemini", cost_usd=0.05), stage="judge")
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)
@@ -42,7 +44,6 @@ def test_resume_restores_money_calls_and_active_time_but_not_downtime():
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.by_round.get(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
@@ -74,24 +75,52 @@ def test_a_raised_cap_grants_only_the_difference_and_grace_never_persists():
assert g2.remaining()["minutes"] == pytest.approx(7.0, abs=0.1) # 15 − 8, never a fresh 15
-def test_build_context_restores_the_snapshot_and_falls_back_to_legacy_spent(tmp_path, settings):
+def test_build_context_restores_the_budget_snapshot(tmp_path, settings):
spec = make_spec()
ws = Workspace(tmp_path / "runs" / "r").create()
track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.THREEJS))
g = BudgetGuard(Budget(max_minutes=10.0))
- g.charge(Usage(backend="gemini", cost_usd=0.4), stage="baseline", round_index=0)
+ g.charge(Usage(backend="gemini", cost_usd=0.4), stage="baseline")
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.by_round.get(0, {})["baseline"] == pytest.approx(0.4)
+ assert ctx.budget.by_stage["baseline"] == pytest.approx(0.4)
- # legacy fallback: an old run dir carries only spent_usage (spent restored, as before)
+ # a snapshot written before by_round was retired (2026-08-30) still loads: extra keys are ignored
+ legacy = dict(state.extra["budget_snapshot"], by_round={"0": {"baseline": 0.4}})
state2 = RunState()
- state2.extra["spent_usage"] = Usage(backend="gemini", cost_usd=0.3).model_dump(mode="json")
+ state2.extra["budget_snapshot"] = legacy
ctx2 = track.build_context(spec, ws, EventLog(ws.events_path), state2)
- assert ctx2.budget.spent.cost_usd == pytest.approx(0.3)
+ assert ctx2.budget.billed_usd == pytest.approx(0.4)
+
+
+def test_the_texture_pass_spend_reaches_the_snapshot_a_resume_restores(tmp_path, chair_plan, settings, monkeypatch):
+ """finalise saved the state BEFORE the texture pass charged, so the snapshot a resume
+ restored was the PRE-texture one and a $0.12 pack simply vanished from the run's money
+ (reproduced 2026-08-30: total_usage 0.217 with cost_by_stage[texture], 0.097 after)."""
+ import codeverse.texturing.run as texrun
+
+ monkeypatch.setattr(texrun, "texture_pass",
+ lambda *a, **kw: SimpleNamespace(usage=Usage(backend="gemini", cost_usd=0.12),
+ summary=lambda: {"shipped": True}))
+ spec = make_spec(max_rounds=0, options=RunOptions(texture=True))
+ ws = Workspace(tmp_path / "runs" / "tex")
+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.6,)),
+ agent=FakeAgent(lambda job, ws_: {"src/object.js": "export function build(THREE) "
+ "{ return new THREE.Group(); }\n"}),
+ planner_model=FakeChatModel(lambda req: chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=FakeRuntime(Language.THREEJS))
+ rec = track.run(spec, ws)
+ assert rec.extra["texturing"] == {"shipped": True}, "the pass must have run at all"
+
+ snap = RunState.load(ws).extra["budget_snapshot"]
+ assert snap["by_stage"]["texture"] == pytest.approx(0.12)
+ assert snap["spent"]["cost_usd"] == pytest.approx(rec.total_usage.cost_usd, abs=1e-6)
+ # and the guard a resume rebuilds starts from that number, not from the pre-texture one
+ ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState.load(ws))
+ assert ctx.budget.by_stage["texture"] == pytest.approx(0.12)
# --------------------------------------------------------------- ordering: single-shot
diff --git a/harness/tests/orchestrator_tracks/test_cost_accounting.py b/harness/tests/orchestrator_tracks/test_cost_accounting.py
index aec530e5..3d4bc4a9 100644
--- a/harness/tests/orchestrator_tracks/test_cost_accounting.py
+++ b/harness/tests/orchestrator_tracks/test_cost_accounting.py
@@ -63,12 +63,12 @@ def replay(name: str, root: Path | None, *, texture: bool = True) -> BudgetGuard
for j in fx["judges"]: # steps.run_round: the judge's MeteredChatModel writes, the guard buckets
u = Usage(cost_usd=j["cost_usd"], input_tokens=j["input_tokens"], output_tokens=j["output_tokens"])
record_call(u, round=j["round"], stage="judge", role="judge", label=j["rubric"])
- guard.add(u, stage="judge", role="judge", round_index=j["round"], label=j["rubric"])
+ guard.add(u, stage="judge")
if texture:
for t in fx["post_hoc_texture_passes"]: # lifecycle._texture_pass
u = Usage(cost_usd=t["cost_usd"])
record_call(u, stage="texture", role="image", label="texture_pass")
- guard.add(u, stage="texture", role="image", label="texture_pass")
+ guard.add(u, stage="texture")
return guard
@@ -91,15 +91,18 @@ def test_every_recorded_dollar_reaches_the_guard_and_the_ledger(name, tmp_path):
assert sum(1 for r in rows if r.label.endswith(".a2")) == len(retried)
-def test_the_round_the_budget_cut_is_still_reported():
+def test_the_round_the_budget_cut_is_still_reported(tmp_path):
fx = FIXTURES["tool_med_hand_drill"]
assert fx["rounds_in_record"] == [0, 1]
cut = [s for s in fx["sessions"] if s["round"] == 2]
assert cut, "fixture must contain the round the budget cut"
- guard = replay("tool_med_hand_drill", None)
+ guard = replay("tool_med_hand_drill", tmp_path)
burned = sum(s["cost_usd"] for s in cut)
- assert guard.by_round.get(2, {})["refine"] == pytest.approx(burned, abs=1e-6)
+ # per-round money lives in the ledger (CallCost.round), the one place that keeps it;
+ # the guard totals and enforces, and its own by_round map was retired 2026-08-30
+ assert sum(r.cost_usd for r in load_ledger(tmp_path) if r.round == 2) == pytest.approx(burned, abs=1e-6)
assert burned > 0.8 # $0.86 that record.rounds never mentioned
+ assert guard.spent.cost_usd > burned # and it is inside the run total, not beside it
def test_post_hoc_texture_passes_are_inside_the_total_now():
@@ -113,16 +116,15 @@ def test_post_hoc_texture_passes_are_inside_the_total_now():
# ----------------------------------------------------------------------------- guard mechanics
-def test_spend_buckets_by_stage_and_round_and_only_charge_enforces():
+def test_spend_buckets_by_stage_and_only_charge_enforces():
g0 = BudgetGuard(Budget(max_minutes=60))
- g0.charge(Usage(cost_usd=0.4), stage="baseline", round_index=0, label="baseline")
- g0.add(Usage(cost_usd=0.05), stage="judge", role="judge", round_index=0)
+ g0.charge(Usage(cost_usd=0.4), stage="baseline")
+ g0.add(Usage(cost_usd=0.05), stage="judge")
assert g0.by_stage == {"baseline": pytest.approx(0.4), "judge": pytest.approx(0.05)}
- assert g0.by_round.get(0, {})["judge"] == pytest.approx(0.05) and g0.by_round.get(9, {}) == {}
assert list(g0.stage_summary())[0] == "baseline" # biggest bucket first
g = BudgetGuard(Budget(max_minutes=1.0), start_time=time.time() - 600) # already past
- g.add(Usage(cost_usd=0.9), stage="texture", role="image") # over the ceiling, never raises
+ g.add(Usage(cost_usd=0.9), stage="texture") # over the ceiling, never raises
assert not g.ok() and g.spent.cost_usd == pytest.approx(0.9)
with pytest.raises(BudgetExceeded):
g.charge(Usage(cost_usd=0.01), stage="refine")
@@ -144,7 +146,7 @@ def test_the_guard_never_writes_a_ledger_row_itself(tmp_path, monkeypatch):
monkeypatch.setattr(ledger_mod, "_fallback_read", False)
quiet = BudgetGuard(Budget(max_minutes=60))
- quiet.charge(Usage(cost_usd=0.1), stage="plan", role="planner")
+ quiet.charge(Usage(cost_usd=0.1), stage="plan")
assert quiet.spent.cost_usd == pytest.approx(0.1)
assert not (tmp_path / "process.jsonl").exists() and not any(tmp_path.glob("**/*.jsonl"))
diff --git a/harness/tests/orchestrator_tracks/test_graphics_recipes.py b/harness/tests/orchestrator_tracks/test_graphics_recipes.py
index d057cbe9..89f65763 100644
--- a/harness/tests/orchestrator_tracks/test_graphics_recipes.py
+++ b/harness/tests/orchestrator_tracks/test_graphics_recipes.py
@@ -11,7 +11,6 @@ import pytest
from codeverse.config import Settings, seed_recipes_enabled
from codeverse.contracts.common import HARNESS_OWNED_SRC, Language, Track
from codeverse.contracts.plan import GraphicsPlan
-from codeverse.languages.file_lint import lint_one_file
from codeverse.languages.glsl_shader import (
COMMON_GLSL,
GlslShaderRuntime,
@@ -372,9 +371,6 @@ def test_lint_flags_a_redefinition_of_a_seeded_recipe(tmp_path) -> None:
rep = lint_workspace(ws)
assert not rep.passed and [f.data["file"] for f in rep.findings if f.data["kind"] == "redefines_recipe"] == ["src/buffer_a.frag"]
assert not any(f.data["kind"] == "stray_file" for f in rep.findings)
- # the per-file verdict a write_file hands back says it too
- verdict = lint_one_file("glsl_shader", "src/common.glsl", common, ws.src / "common.glsl")
- assert verdict.checked and any("`aurora` is already provided by src/recipes.glsl" in e for e in verdict.errors)
def test_prompt_block_lists_the_seeded_names(tmp_path) -> None:
diff --git a/harness/tests/orchestrator_tracks/test_resume_reconcile.py b/harness/tests/orchestrator_tracks/test_resume_reconcile.py
index db473e3b..b6014266 100644
--- a/harness/tests/orchestrator_tracks/test_resume_reconcile.py
+++ b/harness/tests/orchestrator_tracks/test_resume_reconcile.py
@@ -24,6 +24,7 @@ from tests.orchestrator_tracks.fakes import (
FakeAgent,
FakeChatModel,
FakeJudge,
+ FakePairwise,
FakeRuntime,
FakeServices,
)
@@ -97,6 +98,41 @@ def test_crash_between_round_write_and_state_save_delivers_the_newer_round(compl
assert ev and ev[-1]["state_was_stale"] is True and ev[-1]["best_changed"] is True
+def test_a_paid_pairwise_verdict_survives_the_crash_window(tmp_path, chair_plan, settings):
+ """``choose_best_round`` re-persists rNN.json WITH its verdict and only THEN does
+ ``_promote_best`` save the state, so a kill in that gap (or any state predating
+ ``best_considered_through``) left a paid ~$0.05 judgement on disk that reconcile
+ could not see — and score-only re-ranking silently reversed it. 18 runs on disk
+ were in that shape (2026-08-30)."""
+ plan = chair_plan.model_dump(mode="json")
+
+ def build(pairwise):
+ return StaticObjectTrack(services=FakeServices(pairwise=pairwise), judge=FakeJudge(scores=(0.70, 0.72)),
+ agent=FakeAgent(_writer), planner_model=_planner(plan), settings=settings,
+ runtime=FakeRuntime(Language.BLENDER),
+ policy=RoundPolicy(max_rounds=1, target=0.9))
+
+ spec = make_spec(language=Language.BLENDER, max_rounds=1)
+ ws = Workspace(tmp_path / "runs" / "r")
+ paid = FakePairwise([("a", 0.9)]) # r1 outscores r0 by 0.02 (inside the margin); the judge says r0
+ rec1 = build(paid).run(spec, ws)
+ assert len(paid.calls) == 1 and rec1.best_round == 0 and rec1.final_score == pytest.approx(0.70)
+ note = rec1.rounds[1].pairwise
+ assert note is not None and note.winner == "a" and note.accepted is False
+ on_disk = json.loads((ws.root / "rounds" / "r01.json").read_text())
+ assert on_disk["pairwise"]["winner"] == "a", "the verdict must be durable, not just in notes"
+
+ state = json.loads(ws.state_path.read_text()) # ...killed before _promote_best saved
+ state["best_considered_through"] = 0
+ ws.state_path.write_text(json.dumps(state))
+
+ again = FakePairwise([("b", 0.99)]) # a second verdict would flip it
+ rec2 = build(again).run(spec, ws, resume=True)
+ assert again.calls == [], "resume replays the stored verdict, it never buys another"
+ assert rec2.best_round == 0 and rec2.final_score == pytest.approx(0.70)
+ assert RunState.load(ws).best_round == 0
+
+
def test_a_self_consistent_state_with_an_unranked_round_still_re_ranks(completed_run):
"""The sharper crash shape (reproduced by review, 2026-08-27): the round was saved
BEFORE best selection, so completed_rounds/round_commits matched the journal exactly
@@ -237,7 +273,7 @@ def test_resume_charges_for_spend_the_snapshot_missed(tmp_path, chair_plan, sett
led.append(CallCost(run=ws.root.name, model="gemini:flash", label="planner", cost_usd=cost))
guard = BudgetGuard(make_spec().budget)
guard.restore(BudgetSnapshot(spent=guard.spent, billed_usd=0.10, # the boundary save missed 0.32
- calls=1, by_stage={}, by_round={}, active_s=0.0))
+ calls=1, by_stage={}, active_s=0.0))
_reconcile_billed_from_ledger(guard, ws, EventLog(ws.events_path))
assert guard.billed_usd == pytest.approx(0.42), "resume must charge for every billed call"
guard.billed_usd = 5.0 # a snapshot AHEAD of the ledger wins
diff --git a/harness/tests/orchestrator_tracks/test_round_economics.py b/harness/tests/orchestrator_tracks/test_round_economics.py
index bb62674c..ab18f391 100644
--- a/harness/tests/orchestrator_tracks/test_round_economics.py
+++ b/harness/tests/orchestrator_tracks/test_round_economics.py
@@ -223,7 +223,7 @@ def test_hitting_the_cap_asks_for_a_landing_instead_of_killing_the_session(tmp_w
assert res.ok and res.turn_capped and res.sessions == 2
# both sessions are paid for and both are in the guard, under their own labels
assert res.usage.cost_usd == pytest.approx(0.4) and guard.spent.cost_usd == pytest.approx(0.4)
- assert guard.by_round.get(1, {})["refine"] == pytest.approx(0.4)
+ assert guard.by_stage["refine"] == pytest.approx(0.4)
kinds = [e["event"] for e in events.read()]
assert "generate.turn_cap" in kinds
done = next(e for e in events.read() if e["event"] == "generate.done")
@@ -244,7 +244,7 @@ def test_a_crashing_second_session_never_erases_what_the_first_one_spent(tmp_ws)
budget=guard)
assert len(agent.jobs) == 2 and not res.ok
assert guard.spent.cost_usd == pytest.approx(0.2) and res.usage.cost_usd == pytest.approx(0.2)
- assert "503 storm" in res.notes and guard.by_round.get(2, {})["refine"] == pytest.approx(0.2)
+ assert "503 storm" in res.notes and guard.by_stage["refine"] == pytest.approx(0.2)
def _result_of(agent, i):
@@ -268,6 +268,9 @@ def test_task_stage_names_the_cost_bucket_a_task_spends_in():
assert t("rebuild") == "repair" # regenerating after a failed build IS repair money
assert t("zone") == "zones" and t("asset") == "assets" and t("asset_fix") == "assets"
assert t("compose") == "assemble" and t("env") == "env"
+ # the static track's surface-detail round is refine money, not "other" — it filed as
+ # Stage.OTHER until 2026-08-30 because _LABEL_STAGES had no "detail" prefix
+ assert t("detail") == "refine" and t("detail", "detail_seat") == "refine"
# an unknown kind falls back to the label, which record_call maps by prefix
assert t("something_new", "asset_koi") == "asset_koi"