Skip to content

Official Codebase of 3DCodeVerse

Python

cost/judges: delete compare_many, unread cost attributes, meters_own_calls and the in-package ImportError fallbacks; scene-pack joins the run ledger

gaoypeng383621f8d801
diff --git a/harness/codeverse/cli/texture_cmd.py b/harness/codeverse/cli/texture_cmd.py
index a7ecac39..2239ada7 100644
--- a/harness/codeverse/cli/texture_cmd.py
+++ b/harness/codeverse/cli/texture_cmd.py
@@ -108,7 +108,11 @@ def scene_pack(
scene_texture_pack = C.lazy("codeverse.texturing.plan", "scene_texture_pack")
texture_pack_prompt = C.lazy("codeverse.texturing.plan", "texture_pack_prompt")
model_id = spec.backends.planner if model is None else model
- with C.mutating(ws, what=f"3dcv texture scene-pack {ws.root.name}", action="texture"):
+ from codeverse.cost.instrument import run_ledger
+
+ # like `pass`: the pack's plan + image spend joins the run's ledger when it has one
+ with (C.mutating(ws, what=f"3dcv texture scene-pack {ws.root.name}", action="texture"),
+ run_ledger(ws.root, run=ws.root.name, create=False)):
pack = scene_texture_pack(plan, out or ws.public / "textures", _image_model(image_model), model_id, size=size, n_max=n)
rows = {name: f"{e.file or 'FAILED'} tile={e.tile_size_m:.2f}m {e.material_family}/{e.role} seam={e.seam_score:.3f}"
+ (f" {e.error}" if e.error else "") for name, e in pack.entries.items()}
diff --git a/harness/codeverse/cost/__init__.py b/harness/codeverse/cost/__init__.py
index d64a1b89..ccb42443 100644
--- a/harness/codeverse/cost/__init__.py
+++ b/harness/codeverse/cost/__init__.py
@@ -16,17 +16,13 @@ from __future__ import annotations
from codeverse.cost.audit import audit_runs
from codeverse.cost.context import call_context
-from codeverse.cost.guard import estimate_call, text_tokens
+from codeverse.cost.guard import estimate_call
from codeverse.cost.instrument import run_ledger
-from codeverse.cost.ledger import CostLedger, load_ledger, open_run_ledger, record_call, summarise
+from codeverse.cost.ledger import CostLedger, load_ledger, record_call, summarise
from codeverse.cost.reconstruct import find_runs, reconstruct
-from codeverse.cost.report import markdown
-from codeverse.cost.routing import default_route, pro_break_even
from codeverse.cost.types import Role, Stage
__all__ = [
- "CostLedger", "Role", "Stage", "audit_runs", "call_context", "default_route",
- "estimate_call", "find_runs", "load_ledger", "markdown", "open_run_ledger",
- "pro_break_even", "reconstruct", "record_call", "run_ledger",
- "summarise", "text_tokens",
+ "CostLedger", "Role", "Stage", "audit_runs", "call_context", "estimate_call",
+ "find_runs", "load_ledger", "reconstruct", "record_call", "run_ledger", "summarise",
]
diff --git a/harness/codeverse/cost/audit.py b/harness/codeverse/cost/audit.py
index 89e7951c..2de123f4 100644
--- a/harness/codeverse/cost/audit.py
+++ b/harness/codeverse/cost/audit.py
@@ -25,7 +25,7 @@ from pathlib import Path
from codeverse.cost.ledger import summarise
from codeverse.cost.reconstruct import RunLedger, find_runs, reconstruct
-from codeverse.cost.types import CallCost, CostBucket, Role, Stage, Summary
+from codeverse.cost.types import CallCost, Role, Stage, Summary
#: dimensions the audit always aggregates on
AUDIT_DIMENSIONS = ("run", "track", "language", "stage", "role", "backend", "model", "provider",
@@ -48,11 +48,9 @@ class WasteItem:
class RoundCost:
run: str
index: int
- kind: str
usd: float
score: float | None
prev_score: float | None
- gate_errors: int = 0
promoted: bool = False
@property
@@ -69,7 +67,6 @@ class Audit:
runs: list[RunLedger] = field(default_factory=list)
rows: list[CallCost] = field(default_factory=list)
summary: Summary = field(default_factory=Summary)
- rounds: list[RoundCost] = field(default_factory=list)
waste: list[WasteItem] = field(default_factory=list)
# ---------------------------------------------------------------- totals
@@ -107,9 +104,6 @@ class Audit:
def model_s(self) -> float:
return sum(r.model_s for r in self.runs)
- def bucket(self, dim: str, key: str) -> CostBucket:
- return self.summary.dimension(dim).get(key, CostBucket(key=key))
-
def waste_total(self) -> float:
return sum(w.usd for w in self.waste)
@@ -131,11 +125,8 @@ def _round_costs(led: RunLedger) -> list[RoundCost]:
best = None
for idx, score in enumerate(led.round_scores):
usd = sum(r.cost_usd for r in led.rows if r.round == idx)
- kind = "baseline" if idx == 0 else "refine"
promoted = score is not None and (best is None or score > best)
- rc = RoundCost(run=led.run, index=idx, kind=kind, usd=usd, score=score,
- prev_score=best, gate_errors=led.gate_errors[idx] if idx < len(led.gate_errors) else 0,
- promoted=promoted)
+ rc = RoundCost(run=led.run, index=idx, usd=usd, score=score, prev_score=best, promoted=promoted)
if promoted:
best = score
out.append(rc)
@@ -214,7 +205,6 @@ def audit_runs(paths: Iterable[str | Path], *, recheck: bool = False) -> Audit:
rounds = _round_costs(led)
audit.runs.append(led)
audit.rows += led.rows
- audit.rounds += rounds
audit.waste += _waste(led, rounds)
audit.summary = summarise(audit.rows, dimensions=AUDIT_DIMENSIONS)
audit.runs.sort(key=lambda r: -r.ledger_usd)
diff --git a/harness/codeverse/cost/instrument.py b/harness/codeverse/cost/instrument.py
index a3258c05..7aca0db8 100644
--- a/harness/codeverse/cost/instrument.py
+++ b/harness/codeverse/cost/instrument.py
@@ -10,9 +10,9 @@ Two thin proxies do the whole job:
generation.
* :class:`MeteredAgent` wraps a :class:`~codeverse.agents.registry.CodingAgent`.
It sets the ambient attribution (round / stage / label) for the session so
- the model rows above land in the right bucket and, for backends whose calls we
- cannot see (every subscription CLI that does not declare ``meters_own_calls``),
- records one session row from ``AgentResult.usage``. ``agents.registry
+ the model rows above land in the right bucket and, because every backend is a
+ vendor CLI whose calls we cannot see, records one session row from
+ ``AgentResult.usage``. ``agents.registry
.get_coding_agent`` returns the proxy.
Accounting is never allowed to fail a run: every hook is wrapped, and an
@@ -55,21 +55,6 @@ from codeverse.cost.types import Role, Stage, stage_for_label
log = logging.getLogger(__name__)
-def meters_own_calls(agent: Any) -> bool:
- """True when this backend's individual model calls are already on the ledger.
-
- Declared by the backend itself (a ``meters_own_calls`` attribute) — a property
- of the backend, not of what happened to run alongside it. The old thread-local
- "did anybody write a row while the session ran?" counter was wrong in both
- directions (reproduced by ``adversarial.py``): a CLI session during which an
- in-process tool billed a model (a texture pass, a summariser) looked metered
- and its whole session row was silently dropped, and a session whose turns ran
- in another thread was counted twice. Every shipped backend is a vendor CLI
- billing as ONE session row, so the default is False; the deleted in-process
- api-agent (2026-08-28) was the last one whose turns landed on the ledger by
- themselves."""
- return bool(getattr(agent, "meters_own_calls", False))
-
class MeteredChatModel:
"""ChatModel proxy that appends one ledger row per call."""
@@ -218,8 +203,8 @@ class MeteredAgent:
t0 = time.perf_counter()
with call_context(round=job.round, stage=stage, role=Role.GENERATOR, label=job.label):
result = self._inner.run(job)
- if not meters_own_calls(self._inner): # an opaque CLI: its session row is the only record
- self._record_session(job, result, stage, int((time.perf_counter() - t0) * 1000))
+ # an opaque CLI: its session row is the only record
+ self._record_session(job, result, stage, int((time.perf_counter() - t0) * 1000))
return result
def _record_session(self, job: AgentJob, result: AgentResult, stage: Stage, ms: int) -> None:
diff --git a/harness/codeverse/cost/ledger.py b/harness/codeverse/cost/ledger.py
index 1fd9f75f..7b092370 100644
--- a/harness/codeverse/cost/ledger.py
+++ b/harness/codeverse/cost/ledger.py
@@ -88,12 +88,6 @@ class CostLedger:
log.warning("cost ledger append failed (%s): %s", self.path, e)
return row
- def read(self, *, include_attempts: bool = False) -> list[CallCost]:
- return load_ledger(self.path, include_attempts=include_attempts)
-
- def summarise(self, **kw: Any) -> Summary:
- return summarise(self.read(), **kw)
-
_fallback_lock = threading.Lock()
_fallback: CostLedger | None = None
diff --git a/harness/codeverse/cost/reconstruct.py b/harness/codeverse/cost/reconstruct.py
index 76a991d0..81276f02 100644
--- a/harness/codeverse/cost/reconstruct.py
+++ b/harness/codeverse/cost/reconstruct.py
@@ -94,7 +94,6 @@ class RunLedger:
final_score: float | None = None
n_rounds: int = 0
round_scores: list[float | None] = field(default_factory=list)
- gate_errors: list[int] = field(default_factory=list)
recorded_usd: float = 0.0
wall_s: float = 0.0 # time the run was actually working (budget elapsed / stage+round durations)
span_s: float = 0.0 # first to last event — includes time queued behind other runs
@@ -304,8 +303,6 @@ def reconstruct_run(run_dir: str | Path, *, recheck: bool = False) -> RunLedger:
idx = int(r.get("index") or 0)
judgment = r.get("judgment") or {}
led.round_scores.append((judgment or {}).get("overall"))
- led.gate_errors.append(sum(1 for g in (r.get("gates") or [])
- for f in (g.get("findings") or []) if f.get("severity") == "error"))
ju = _usage(judgment.get("usage"))
if ju.input_tokens or ju.cost_usd:
judged_rounds.add(idx)
diff --git a/harness/codeverse/cost/routing.py b/harness/codeverse/cost/routing.py
index 55306ed7..969881d6 100644
--- a/harness/codeverse/cost/routing.py
+++ b/harness/codeverse/cost/routing.py
@@ -54,7 +54,7 @@ ROUTES: tuple[Route, ...] = (
"graphics track: 5/6 passed, median 0.810, $0.099 per run",
"glsl_shader / opengl_python — one file, compiler feedback, no tool loop needed"),
# the runtime default since 2026-08-28 (contracts.common.Backends.generator):
- # default_route() must name what actually runs, not the arm we measured first
+ # the default=True route must name what actually runs, not the arm we measured first
Route(Role.GENERATOR, "gemini-cli:gemini-3.7-flash", 0.73,
"compare_v1: 0.827 — statistically the same as the since-deleted api-agent arm at 2x the price",
"the default; ~2x the 3.6 arm's price for quality measured as the same, so the number to beat",
@@ -84,15 +84,6 @@ ROUTES: tuple[Route, ...] = (
)
-def routes_for(role: Role | str) -> list[Route]:
- r = Role(role) if not isinstance(role, Role) else role
- return [x for x in ROUTES if x.role is r]
-
-
-def default_route(role: Role | str) -> Route | None:
- return next((x for x in routes_for(role) if x.default), None)
-
-
def samples_for_precision(model: str, target_std: float, *, noise: dict[str, tuple[float, float]] | None = None) -> int:
"""How many samples of ``model`` are needed to reach ``target_std``
(σ_eff = σ / √n). Returns 1 when the model is already precise enough."""
diff --git a/harness/codeverse/cost/types.py b/harness/codeverse/cost/types.py
index 07d13442..5c1f1430 100644
--- a/harness/codeverse/cost/types.py
+++ b/harness/codeverse/cost/types.py
@@ -229,21 +229,12 @@ class CallCost(BaseModel):
#: and counts; a free one is ``source="attempt"`` and is filtered out
discarded: bool = False
- @property
- def total_tokens(self) -> int:
- return self.input_tokens + self.output_tokens + self.thoughts_tokens
-
- @property
- def cached_fraction(self) -> float:
- return (min(self.cached_tokens, self.input_tokens) / self.input_tokens) if self.input_tokens else 0.0
-
class CostBucket(BaseModel):
"""Aggregate of many :class:`CallCost` rows under one key."""
key: str = ""
n_calls: int = 0
- n_rows: int = 0
input_tokens: int = 0
cached_tokens: int = 0
output_tokens: int = 0
@@ -251,13 +242,11 @@ class CostBucket(BaseModel):
tool_calls: int = 0
cost_usd: float = 0.0
latency_ms: int = 0
- approximate_usd: float = 0.0 # spend priced from an approximate/unknown row
attempts: int = 0 # round-trips over the rows that recorded them
n_attempted: int = 0 # calls in those rows
def add(self, row: CallCost) -> None:
self.n_calls += max(1, row.n_calls)
- self.n_rows += 1
if row.attempts:
self.attempts += row.attempts
self.n_attempted += max(1, row.n_calls)
@@ -268,8 +257,6 @@ class CostBucket(BaseModel):
self.tool_calls += row.tool_calls
self.cost_usd += row.cost_usd
self.latency_ms += row.latency_ms
- if row.price_approximate or row.price_source in ("unknown", "provider-reported"):
- self.approximate_usd += row.cost_usd
@property
def cached_fraction(self) -> float:
@@ -283,10 +270,6 @@ class CostBucket(BaseModel):
def usd_per_1k_tokens(self) -> float:
return 1000.0 * self.cost_usd / self.total_tokens if self.total_tokens else 0.0
- @property
- def usd_per_call(self) -> float:
- return self.cost_usd / self.n_calls if self.n_calls else 0.0
-
@property
def attempts_per_call(self) -> float:
"""Mean round-trips per call (1.0 = every call landed first time); 0 when unrecorded."""
diff --git a/harness/codeverse/judges/pairwise.py b/harness/codeverse/judges/pairwise.py
index 3a1ab876..8ee33c76 100644
--- a/harness/codeverse/judges/pairwise.py
+++ b/harness/codeverse/judges/pairwise.py
@@ -5,9 +5,7 @@ orderings run in parallel via ``codeverse.proc``); the winner is declared
only when both orderings agree, otherwise ``tie``. Each call sees the brief,
the rubric's criteria (titles + descriptions) and ONE 2×2 montage per candidate
(the 4 most informative views — never a big sheet: VLM judges flip with many
-tiles). ``compare_many`` ranks N candidates by a round-robin of such
-comparisons (best-of-N), fanning the pairs at 4 workers; results accumulate in
-input order either way.
+tiles).
"""
from __future__ import annotations
@@ -68,21 +66,6 @@ class PairwiseResult(BaseModel):
error: str = ""
-class RankingResult(BaseModel):
- """Round-robin ranking of N candidates (``compare_many``)."""
-
- order: list[int] = Field(description="candidate indices, best first")
- points: dict[int, float] = Field(description="win = 1, tie = 0.5 per pair")
- confidence: dict[int, float] = Field(default_factory=dict, description="mean confidence of the pairs a candidate won")
- pairs: list[dict] = Field(default_factory=list, description="{a, b, winner, confidence, error} per pair")
- usage: Usage = Field(default_factory=Usage)
- errors: list[str] = Field(default_factory=list)
-
- @property
- def best(self) -> int:
- return self.order[0]
-
-
_SYSTEM = """You are a BLIND comparative judge for a 3D-code harness. You see a brief, a rubric and renders of TWO candidates, labelled A and B. Decide which candidate better satisfies the brief, judging ONLY what is visible. Position carries no information: A is not better for being first.
Compare criterion by criterion (intent, structure, detail, proportions, fit, materials, cleanliness as listed), then decide overall. Prefer the candidate with no major defect over the one with more detail but a floating or broken part. Say 'tie' only when the two are genuinely equivalent. Reply with one JSON object: winner ('A'|'B'|'tie'), confidence 0..1, reasons[], criteria_won[{criterion, winner}]."""
@@ -118,9 +101,9 @@ class PairwiseJudge:
# ------------------------------------------------------------------ API
def compare(
self, spec: Spec, renders_a: RenderSet, renders_b: RenderSet, *,
- rubric: str | Rubric = "static_object_v1", label: str = ""
+ rubric: str | Rubric = "static_object_v1"
) -> PairwiseResult:
- """``label`` (optional) tags the two orderings' requests (``pairwise[:label]:fwd/swap``)
+ """The two orderings' requests are tagged ``pairwise:fwd`` / ``pairwise:swap``
so logs — and deterministic fakes — can tell concurrent orderings apart."""
rub = rubric if isinstance(rubric, Rubric) else load_rubric(rubric)
usage = Usage()
@@ -129,7 +112,7 @@ class PairwiseJudge:
errors: list[str] = []
self.model # noqa: B018 — materialise the lazy chat model once, before the threads race
results = fan_out(
- (False, True), lambda swapped: self._ordering(spec, rub, renders_a, renders_b, swapped, label),
+ (False, True), lambda swapped: self._ordering(spec, rub, renders_a, renders_b, swapped),
max_workers=2, label="pairwise:orderings", item_name=lambda s: f"swapped={s}",
)
for res in results: # ordered accumulation: (fwd, swap)
@@ -148,13 +131,12 @@ class PairwiseJudge:
return _combine(verdicts, orderings, usage, errors)
def _ordering(
- self, spec: Spec, rub: Rubric, renders_a: RenderSet, renders_b: RenderSet, swapped: bool, label: str = ""
+ self, spec: Spec, rub: Rubric, renders_a: RenderSet, renders_b: RenderSet, swapped: bool
) -> tuple[Usage, tuple[Winner, float, list[str]] | None, dict | None, str]:
"""One A/B ordering → ``(usage, verdict, ordering, error)`` (never raises for
model/parse failures — the caller aggregates them as errors)."""
first, second = (renders_b, renders_a) if swapped else (renders_a, renders_b)
- tag = ":".join(x for x in ("pairwise", label, "swap" if swapped else "fwd") if x)
- req = self._request(spec, rub, first, second, label=tag)
+ req = self._request(spec, rub, first, second, label="pairwise:swap" if swapped else "pairwise:fwd")
try:
resp = self.model.generate(req)
except ModelError as e:
@@ -173,51 +155,6 @@ class PairwiseJudge:
"criteria_won": {c.criterion: _map_winner(c.winner, swapped) for c in reply.criteria_won}}
return resp.usage, (winner, reply.confidence, reasons), ordering, ""
- def compare_many(
- self, spec: Spec, candidates: list[RenderSet], *, rubric: str | Rubric = "static_object_v1"
- ) -> RankingResult:
- """Rank ``candidates`` by round-robin pairwise comparison (each pair in both orders).
-
- Points: win = 1, tie = 0.5. Ties in points are broken by the mean confidence
- of won pairs, then by the lower index (earlier candidate). One candidate →
- trivial ranking without any call.
- """
- n = len(candidates)
- if n == 0:
- raise ValueError("compare_many needs at least one candidate")
- points = {i: 0.0 for i in range(n)}
- conf_won: dict[int, list[float]] = {i: [] for i in range(n)}
- pairs: list[dict] = []
- usage = Usage()
- errors: list[str] = []
- idx_pairs = [(i, j) for i in range(n) for j in range(i + 1, n)]
- if idx_pairs:
- self.model # noqa: B018 — materialise the lazy chat model once, before the threads race
- results = fan_out(
- idx_pairs, lambda ij: self.compare(spec, candidates[ij[0]], candidates[ij[1]], rubric=rubric,
- label=f"{ij[0]}v{ij[1]}"),
- max_workers=4, label="pairwise:pairs", item_name=lambda ij: f"{ij[0]}v{ij[1]}",
- )
- for (i, j), res in zip(idx_pairs, results, strict=True): # ordered accumulation
- if isinstance(res, Exception):
- raise res # compare() reports model/parse failures in-band; anything else is a bug
- usage = usage + res.usage
- if res.error:
- errors.append(f"{i}v{j}: {res.error}")
- if res.winner == "a":
- points[i] += 1.0
- conf_won[i].append(res.confidence)
- elif res.winner == "b":
- points[j] += 1.0
- conf_won[j].append(res.confidence)
- else:
- points[i] += 0.5
- points[j] += 0.5
- pairs.append({"a": i, "b": j, "winner": res.winner, "confidence": res.confidence, "error": res.error})
- confidence = {i: (round(statistics.fmean(v), 3) if v else 0.0) for i, v in conf_won.items()}
- order = sorted(range(n), key=lambda i: (-points[i], -confidence[i], i))
- return RankingResult(order=order, points=points, confidence=confidence, pairs=pairs, usage=usage, errors=errors)
-
# ------------------------------------------------------------------ prompt
def _request(
self, spec: Spec, rub: Rubric, first: RenderSet, second: RenderSet, *, label: str = "pairwise"
diff --git a/harness/codeverse/judges/vlm_judge.py b/harness/codeverse/judges/vlm_judge.py
index efb14d35..ff1a81f8 100644
--- a/harness/codeverse/judges/vlm_judge.py
+++ b/harness/codeverse/judges/vlm_judge.py
@@ -53,6 +53,8 @@ from codeverse.judges.rubrics import (
)
from codeverse.models.base import ChatModel, ModelError
from codeverse.proc import fan_out
+from codeverse.reference import compare, conflict_note
+from codeverse.spatial.silhouette import best_view_match, compare_silhouette
log = logging.getLogger(__name__)
@@ -356,27 +358,10 @@ def iou_to_score(iou: float) -> float:
return max(0.0, min(1.0, (float(iou) - IOU_LOW) / (IOU_HIGH - IOU_LOW)))
-def _default_silhouette_fn() -> SilhouetteFn | None:
- try:
- from codeverse.spatial.silhouette import compare_silhouette # type: ignore[attr-defined]
- except (ImportError, AttributeError):
- return None
- return compare_silhouette
-
-
def _diff_enabled(flag: bool) -> bool:
return flag and os.environ.get(_ENV_DIFF, "on").strip().lower() not in ("0", "off", "false", "no")
-def _conflict_note(info: dict[str, Any]) -> str:
- try:
- from codeverse.reference import conflict_note
-
- return conflict_note(info)
- except ImportError: # pragma: no cover
- return ""
-
-
def _is_synth(note: str) -> bool:
return note.startswith("SYNTHESIZED")
@@ -402,7 +387,7 @@ class ReferenceJudge(VlmJudge):
**kwargs: Any,
):
super().__init__(rubric, model_id, n_samples, temperature, **kwargs)
- self.silhouette_fn = silhouette_fn or _default_silhouette_fn()
+ self.silhouette_fn = silhouette_fn or compare_silhouette
self.front_view_names = front_view_names
self.best_view = best_view
self.diff = diff
@@ -425,7 +410,7 @@ class ReferenceJudge(VlmJudge):
"It is a shape/part-inventory target only. Where it disagrees with the brief or the stated "
"dimensions, the BRIEF is correct and the render must follow the brief.")
conflict = self.dimension_conflict(inp, refs)
- note = _conflict_note(conflict)
+ note = conflict_note(conflict)
if note:
blocks.append(note)
measured_ids = [c.id for c in self.rubric.measured_criteria()]
@@ -483,10 +468,6 @@ class ReferenceJudge(VlmJudge):
never raises (a failed diff simply contributes no text)."""
if not _diff_enabled(self.diff):
return None
- try:
- from codeverse.reference import compare
- except ImportError: # pragma: no cover - the package is part of the wheel
- return None
targets = [r.path for r in refs if r.role == "target"] or [r.path for r in refs]
renders = self.diff_views(list(inp.renders.views))
measured = dict(info) if "iou" in info else None
@@ -545,8 +526,6 @@ class ReferenceJudge(VlmJudge):
views = list(inp.renders.views)
if not views:
return {"error": "render set has no views"}
- if self.silhouette_fn is None:
- return {"error": "compare_silhouette unavailable (codeverse.spatial.silhouette not importable)"}
res, name = self._measure(views, targets[0].path)
if not isinstance(res, dict) or "iou" not in res:
return {"error": f"compare_silhouette returned no iou: {res!r}"}
@@ -560,19 +539,14 @@ class ReferenceJudge(VlmJudge):
def _measure(self, views: list[RenderView], reference: str) -> tuple[dict[str, Any], str]:
"""(result, view name). Best-matching view when enabled and available."""
- if self.best_view and self.silhouette_fn is _default_silhouette_fn():
- try:
- from codeverse.spatial.silhouette import best_view_match
- except ImportError: # pragma: no cover
- best_view_match = None # type: ignore[assignment]
- if best_view_match is not None:
- res = best_view_match(views, reference)
- if "iou" in res:
- return res, str(res.get("view", ""))
+ if self.best_view and self.silhouette_fn is compare_silhouette:
+ res = best_view_match(views, reference)
+ if "iou" in res:
+ return res, str(res.get("view", ""))
view = self.pick_front_view(views)
if view is None: # pragma: no cover - guarded by the caller
return {}, ""
- return self.silhouette_fn(view.path, reference), view.name # type: ignore[misc]
+ return self.silhouette_fn(view.path, reference), view.name
def _plan_part_names(inp: JudgeInput) -> list[str]:
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 988c0df6..bee6113c 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -155,7 +155,7 @@ codeverse/
calibration share), rubrics.py + rubrics/*.yaml (defect checklists, the wire
schema, caps and scoring), prompt_builder.py (image prep, montages, the
judge messages), vlm_judge.py (+ the reference/likeness judges),
- pairwise.py (compare_many), calibration.py. No Judge Protocol: a judge is
+ pairwise.py, calibration.py. No Judge Protocol: a judge is
duck-typed `.judge(JudgeInput) -> Judgment`
reference.py reference GROUNDING — give the pipeline a picture of what it is building:
synthesis, THE plausibility gate that makes a synthesized
@@ -404,8 +404,8 @@ citation auditable. Floors,
deterministic caps from gate findings (`data["kind"]`), console errors, missing
must-acceptance and
`missing_views` rules apply on top; degraded verdicts are glitches, not scores.
-`PairwiseJudge` (position-swapped, tie on disagreement) also ranks N candidates via
-`compare_many`; `ReferenceJudge` for image-conditioned specs.
+`PairwiseJudge` (position-swapped, tie on disagreement); `ReferenceJudge` for
+image-conditioned specs.
Rubrics: `static_object_v1` (0.72), `articulated_v1` (requires pose sheet),
`scene_v1` (frame-gate caps), `asset_v1`, `reference_v1`, `shader_v1` (0.70).
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
index 23e151ad..f71f9fe4 100644
--- a/harness/docs/COST.md
+++ b/harness/docs/COST.md
@@ -341,7 +341,7 @@ persists. Concretely, the 112 verdicts in this data set cost $6.48 with the pro
judge and would cost $24.2 as "cheap" flash at n=8.
`codeverse/cost/routing.py` holds this table in code
-(`default_route(Role.JUDGE)`, `pro_break_even()`, `samples_for_precision()`).
+(`ROUTES`, `pro_break_even()`, `samples_for_precision()`).
## 9. Ranked optimisation opportunities
@@ -442,9 +442,9 @@ out not to pay.
model — a texture pass, a captioner — looked metered, so its session row was
dropped and **$1.23 of the reproduction vanished**; and an in-process session
whose turns ran in a worker thread looked unmetered and was counted **twice**.
- a backend's own `meters_own_calls` attribute decides it now (every shipped
- backend is a vendor CLI, so none sets it), and
- `tests/cost/test_instrument.py` pins both directions.
+ Every shipped backend is a vendor CLI, so the session row is always written now
+ (the `meters_own_calls` opt-out went with the last in-process agent), and
+ `tests/cost/test_instrument.py` pins the dropped-session direction.
**Attribution.** A call is filed under what *it* says it is, not under what
surrounds it: `cost.context.attribute()` puts an explicit stage/role first, then a
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 7d080a9e..1ef0e111 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -101,12 +101,12 @@ Rules that callers must know:
## cost/ (ledger · profiles · price provenance)
```python
-from codeverse.cost import record_call, load_ledger, summarise, open_run_ledger
+from codeverse.cost import record_call, load_ledger, summarise
record_call(usage, *, run="", round=None, stage=None, role=None, label="", backend="", model="",
outcome="ok", latency_ms=None, n_calls=1, source="live", ledger=None, reprice=False) -> CallCost
# Δ everything left out is resolved from the ambient context + the call label (cost.context);
# unknown model -> $0 and price_source="unknown" (flagged, never silently dropped); never raises.
-from codeverse.cost.instrument import (run_ledger, metered_chat_model, metered_agent, meters_own_calls,
+from codeverse.cost.instrument import (run_ledger, metered_chat_model, metered_agent,
MeteredAgent, MeteredChatModel, metering_enabled)
with run_ledger(ws.root, run=slug): # binds the run, points record_call at <run>/telemetry/cost.jsonl
... # (+ a <run>/cost_ledger.jsonl symlink for the run-layout alias)
@@ -117,12 +117,11 @@ with run_ledger(ws.root, run=slug): # binds the run, points record_call a
# outside the CLI/bench still meters; the CLI/bench ledger for the same run dir is the same file.
# models.get_chat_model returns a MeteredChatModel → ONE row per ChatModel.generate
# agents.get_coding_agent returns a MeteredAgent (registry wrap, from the first call) → ambient
- # round/stage for the session and — iff NOT meters_own_calls(agent), a declaration no shipped
- # backend makes — one source='session' row (n_calls, latency, outcome, AgentResult.turns).
+ # round/stage for the session and one source='session' row (n_calls, latency, outcome,
+ # AgentResult.turns) — every backend is a vendor CLI whose calls the harness cannot see.
# These two are the ONLY ledger writers; BudgetGuard writes no row.
# The rule is the BACKEND, never "did a row get written while it ran": a CLI session with one
- # in-process tool call used to be dropped entirely, an in-process session whose turns ran in
- # another thread used to be counted twice. A backend may declare `meters_own_calls`.
+ # in-process tool call used to be dropped entirely.
from codeverse.cost.context import CallContext, call_context, bound_run, context_from_label, SELF_DESCRIBING
from codeverse.cost.ledger import bound_ledger, process_ledger_path # (Δ 2026-08-30) both are context
# managers holding a ContextVar token; there is no process-wide default any more — a thread that
@@ -372,7 +371,6 @@ from codeverse.judges.rubrics import apply_caps # (rubric, overall, ga
# console_errors=None, views=None, defects_present=None) -> CapResult;
# cap rules add when="missing_views" and ledger lines "defect:<id>"
from codeverse.judges.pairwise import PairwiseJudge # .compare(spec, renders_a, renders_b, *, rubric=…) -> PairwiseResult
-PairwiseJudge.compare_many(spec, candidates: list[RenderSet], *, rubric) -> RankingResult{order, points, confidence, pairs, usage, .best}
from codeverse.judges.calibration import calibrate, CalibrationTable # (run_dirs, *, model_id, n_samples=3, out_dir, geometry_mode,
# rounds, …) -> rows + pearson/spearman(errors vs score), mean_std, cost; CLI: python -m codeverse.judges.calibration RUN… --n 3
from codeverse.judges.vlm_judge import ReferenceJudge # image-conditioned specs
diff --git a/harness/tests/compare_bench/test_infra_failures.py b/harness/tests/compare_bench/test_infra_failures.py
index c077633c..227e3077 100644
--- a/harness/tests/compare_bench/test_infra_failures.py
+++ b/harness/tests/compare_bench/test_infra_failures.py
@@ -331,10 +331,11 @@ def test_the_ab_viewer_refuses_to_call_a_winner_it_cannot_support():
assert head.startswith("Inconclusive") and "1 of 1" in why
def test_the_default_generator_and_the_cost_router_name_the_same_model():
- """`3dcv cost` prints default_route(GENERATOR) as "the default"; if it disagrees with
+ """`3dcv cost` prints the default=True GENERATOR route as "the default"; if it disagrees with
Backends.generator the report is describing a model no run uses."""
from codeverse.contracts.common import Backends
- from codeverse.cost.routing import default_route
+ from codeverse.cost.routing import ROUTES
from codeverse.cost.types import Role
- assert default_route(Role.GENERATOR).model_id == Backends().generator
+ (default,) = [r for r in ROUTES if r.role is Role.GENERATOR and r.default]
+ assert default.model_id == Backends().generator
diff --git a/harness/tests/cost/test_audit_report.py b/harness/tests/cost/test_audit_report.py
index c275680f..3ce19c57 100644
--- a/harness/tests/cost/test_audit_report.py
+++ b/harness/tests/cost/test_audit_report.py
@@ -21,7 +21,7 @@ def test_audit_of_one_run(fake_run: Path):
audit = audit_runs([fake_run.parent])
assert audit.n_runs == 1 and audit.n_passed == 1
assert audit.usd_per_passing_artifact == pytest.approx(audit.total_usd)
- assert audit.bucket("track", "static_object").cost_usd == pytest.approx(audit.total_usd)
+ assert audit.summary.dimension("track")["static_object"].cost_usd == pytest.approx(audit.total_usd)
assert audit.calls_per_round() > 0
cached, total, usd = cached_input_share(audit)
assert 0 < cached < total and usd > 0
diff --git a/harness/tests/cost/test_guard_caching_routing.py b/harness/tests/cost/test_guard_caching_routing.py
index a99559e5..cc0f13ff 100644
--- a/harness/tests/cost/test_guard_caching_routing.py
+++ b/harness/tests/cost/test_guard_caching_routing.py
@@ -5,11 +5,8 @@ from __future__ import annotations
import pytest
-from codeverse.cost import (
- estimate_call,
- text_tokens,
-)
-from codeverse.cost.guard import image_tokens
+from codeverse.cost import estimate_call
+from codeverse.cost.guard import image_tokens, text_tokens
from codeverse.cost.routing import pro_break_even, samples_for_precision
diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.py
index 6927f183..eebb8461 100644
--- a/harness/tests/cost/test_instrument.py
+++ b/harness/tests/cost/test_instrument.py
@@ -49,7 +49,6 @@ class FakeAgent:
"""A backend whose individual calls already reach the ledger."""
kind = "self-metering"
- meters_own_calls = True
model = "gemini:gemini-3.6-flash"
def __init__(self, chat, turns: int = 3):
@@ -73,8 +72,7 @@ class FakeAgent:
class CliAgent(FakeAgent):
- kind = "gemini-cli"
- meters_own_calls = False # a vendor CLI bills as ONE session row
+ kind = "gemini-cli" # a vendor CLI bills as ONE session row
def run(self, job: AgentJob) -> AgentResult:
self.seen_turns = job.max_turns
@@ -219,37 +217,6 @@ def test_a_cli_session_is_recorded_even_when_a_tool_bills_a_model_inside_it(tmp_
assert tool.stage is Stage.TEXTURE # and it is NOT filed under the session's stage
-def test_an_in_process_session_is_never_counted_twice_even_from_another_thread(tmp_path: Path):
- """Worker-thread rows from a self-metered agent are not double counted."""
- from codeverse.proc import fan_out
-
- class ThreadedAgent(FakeAgent):
- def run(self, job: AgentJob) -> AgentResult:
- # fan_out, not a bare Thread: it is the one helper that copies the caller's
- # context, and since 2026-08-30 nothing else can find the run's ledger from
- # a worker thread (the process-global fallback leaked between parallel runs)
- (out,) = fan_out([job], lambda j: FakeAgent.run(self, j), label="agent")
- assert isinstance(out, AgentResult)
- return out
-
- with run_ledger(tmp_path, run="r1"):
- MeteredAgent(ThreadedAgent(MeteredChatModel(FakeChat()))).run(
- AgentJob(workspace=str(tmp_path), prompt="p", label="baseline", round=0, kind="baseline"))
- rows = load_ledger(tmp_path)
- assert len(rows) == 3 and not any(r.source == "session" for r in rows)
- assert sum(r.input_tokens for r in rows) == 36_000 # 3 turns, not 3 turns + a session
-
-
-def test_a_backend_may_declare_that_it_meters_itself(tmp_path: Path):
- from codeverse.cost.instrument import meters_own_calls
-
- cli = CliAgent(FakeChat())
- assert meters_own_calls(cli) is False # a vendor CLI bills as one session
- assert meters_own_calls(FakeAgent(FakeChat())) is True # ...unless it declares otherwise
- cli.meters_own_calls = True # type: ignore[attr-defined]
- assert meters_own_calls(cli) is True
-
-
# ------------------------------------------------------------------- nesting / parallelism
def test_run_ledgers_nest_and_restore_the_outer_one(tmp_path: Path):
"""Closing a nested ledger restores the outer context."""
diff --git a/harness/tests/judges/test_live.py b/harness/tests/judges/test_live.py
index 266cf942..fe6aa14b 100644
--- a/harness/tests/judges/test_live.py
+++ b/harness/tests/judges/test_live.py
@@ -110,24 +110,6 @@ def test_live_pairwise_stool_vs_chair(tmp_path):
assert res.winner == "a"
-def test_live_compare_many_ranks_stool_over_crude(tmp_path):
- from codeverse.judges.pairwise import PairwiseJudge
-
- renders, _, source = _renders_for_test(tmp_path / "stool")
- if "stool" not in source:
- pytest.skip("needs real stool renders")
- from codeverse.conventions import OBJECT_VIEWS_QUICK
- from codeverse.spatial.render import render_glb
-
- clay = render_glb(tmp_path / "stool" / "stool.glb", tmp_path / "clay", views=OBJECT_VIEWS_QUICK, mode="clay", sheet=False)
- crude = make_renders(tmp_path / "crude")
- spec = make_spec(prompt="A simple three-legged wooden stool, 45 cm tall, round seat.")
- rank = PairwiseJudge(MODEL, cache_dir=tmp_path / "cache").compare_many(spec, [crude, renders, clay])
- print(f"\nLIVE ranking order={rank.order} points={rank.points} errors={rank.errors}\nusage={rank.usage}")
- assert rank.order[-1] == 0 # the crude drawing ranks last
- assert len(rank.pairs) == 3
-
-
def test_live_reference_judge(tmp_path):
from codeverse.contracts.spec import ReferenceImage
from codeverse.judges.vlm_judge import ReferenceJudge
diff --git a/harness/tests/judges/test_pairwise.py b/harness/tests/judges/test_pairwise.py
index 54da92ab..86b5af31 100644
--- a/harness/tests/judges/test_pairwise.py
+++ b/harness/tests/judges/test_pairwise.py
@@ -57,32 +57,6 @@ def test_unswap_reasons():
assert _unswap_text("Candidate A beats candidate B", False) == "Candidate A beats candidate B"
-def test_compare_many_round_robin(tmp_path, cache_dir):
- from codeverse.judges.pairwise import RankingResult
- cands = [make_renders(tmp_path / f"c{i}") for i in range(3)]
- # pairs (0,1), (0,2), (1,2); each compare = 2 orderings. Make 2 beat everyone, 0 beat 1.
- replies = {"0v1:fwd": [_reply("A", 0.9)], "0v1:swap": [_reply("B", 0.8)], # 0 v 1 → a (0 wins)
- "0v2:fwd": [_reply("B", 0.9)], "0v2:swap": [_reply("A", 0.9)], # 0 v 2 → b (2 wins)
- "1v2:fwd": [_reply("B", 0.7)], "1v2:swap": [_reply("A", 0.7)]} # 1 v 2 → b (2 wins)
- model = FakeChatModel(by_label=replies)
- rank: RankingResult = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare_many(make_spec(), cands)
- assert rank.order == [2, 0, 1] and rank.best == 2
- assert rank.points == {0: 1.0, 1: 0.0, 2: 2.0}
- assert len(rank.pairs) == 3 and len(model.requests) == 6
- assert rank.usage.cost_usd > 0 and rank.errors == []
- # single candidate → no calls
- solo = PairwiseJudge("fake:fake-1", chat_model=FakeChatModel(), cache_dir=cache_dir).compare_many(make_spec(), cands[:1])
- assert solo.order == [0] and solo.points == {0: 0.0}
-
-
-def test_compare_many_ties_and_errors(tmp_path, cache_dir):
- cands = [make_renders(tmp_path / f"c{i}") for i in range(2)]
- model = FakeChatModel([_reply("A", 0.9), _reply("A", 0.9)]) # position bias → tie
- rank = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare_many(make_spec(), cands)
- assert rank.points == {0: 0.5, 1: 0.5} and rank.order == [0, 1]
- assert rank.errors and "orderings disagree" in rank.errors[0]
-
-
def test_parallel_orderings_accumulate_in_order(tmp_path, cache_dir):
"""The two orderings run concurrently but land in (fwd, swap) order."""
ra, rb = make_renders(tmp_path / "a"), make_renders(tmp_path / "b")
diff --git a/harness/tests/texturing/test_tools_cli.py b/harness/tests/texturing/test_tools_cli.py
index b3930b44..0cd7669e 100644
--- a/harness/tests/texturing/test_tools_cli.py
+++ b/harness/tests/texturing/test_tools_cli.py
@@ -80,3 +80,34 @@ def test_cli_texture_show_and_help(tmp_path, chair_glb, chair_spec, chair_plan):
assert res.exit_code == 0 and "scene-pack" in res.output and "pass" in res.output
res = runner.invoke(app, ["texture", "show", str(tmp_path / "nowhere")])
assert res.exit_code != 0
+
+
+def test_cli_scene_pack_spend_joins_the_runs_ledger(tmp_path, chair_spec, monkeypatch):
+ """`3dcv texture scene-pack` opened no run_ledger (`pass` did), so its plan + image
+ spend went to the per-process log instead of the run's telemetry/cost.jsonl."""
+ from codeverse.cli.main import app
+ from codeverse.contracts.common import Language, Track, Usage
+ from codeverse.contracts.plan import BBox, CameraPlan, ScenePlan, ZonePlan
+ from codeverse.cost.instrument import run_ledger
+ from codeverse.cost.ledger import load_ledger, record_call
+ from codeverse.texturing.plan import ScenePack
+
+ ws = Workspace(tmp_path / "run").create()
+ ws.write_json(ws.spec_path, chair_spec.model_copy(update={"track": Track.SCENE, "language": Language.SCENE_THREEJS}))
+ bb = BBox(center=(0, 0, 0), extents=(30, 10, 30))
+ ws.write_json(ws.plan_path, ScenePlan(
+ title="Zen Garden", summary="a small Kyoto garden", setting="Kyoto", bounds=bb, environment="raked gravel",
+ zones=[ZonePlan(name="Pond", description="koi pond with stepping stones", bbox=bb)],
+ cameras=[CameraPlan(name="main", position=(10, 3, 10), look_at=(0, 0, 0))]))
+ with run_ledger(ws.root, run=ws.root.name): # the run kept a ledger while it ran
+ record_call(Usage(model="gemini-3.7-flash", input_tokens=1000), label="planner")
+
+ def fake_pack(plan, out_dir, image_model, model_id, **_):
+ record_call(Usage(model="gemini-3.1-flash-image", input_tokens=200, cost_usd=0.04), label="texture_pack")
+ return ScenePack(out_dir=str(out_dir))
+
+ monkeypatch.setattr("codeverse.texturing.plan.scene_texture_pack", fake_pack)
+ monkeypatch.setattr("codeverse.cli.texture_cmd._image_model", lambda name: FakeImageModel())
+ res = CliRunner().invoke(app, ["texture", "scene-pack", str(ws.root), "--model", ""])
+ assert res.exit_code == 0, res.output
+ assert [r.label for r in load_ledger(ws.root)] == ["planner", "texture_pack"]