Skip to content

Official Codebase of 3DCodeVerse

Python

Delete pick --by pairwise, PairwiseJudge + Stage.PAIRWISE, the eval pairwise arena, the render and cost cache/estimate commands, ReferenceJudge's second vision call and the judge command's prompt-image count

gaoypeng2f3226b35632
diff --git a/eval/bench/_compare_report.py b/eval/bench/_compare_report.py
index 8b91cf96..a9d048db 100644
--- a/eval/bench/_compare_report.py
+++ b/eval/bench/_compare_report.py
@@ -1,9 +1,8 @@
"""Result rows + report.md / report.html for ``bench/compare_backends.py``.
-``CellResult`` is one (prompt, arm) cell; ``PairRow`` one pairwise verdict.
-``build_compare_report(out_dir)`` reads ``results.jsonl`` + ``pairwise.jsonl``
-and writes the arm summary table, the per-prompt score matrix, the pairwise
-arena (win rates) and an HTML gallery of the contact sheets side by side.
+``CellResult`` is one (prompt, arm) cell. ``build_compare_report(out_dir)`` reads
+``results.jsonl`` and writes the arm summary table, the per-prompt score matrix and an
+HTML gallery of the contact sheets side by side.
"""
from __future__ import annotations
@@ -96,26 +95,6 @@ def cell_minutes(r: CellResult) -> float:
return r.wall_s / 60 if r.minutes is None else r.minutes
-class PairRow(BaseModel):
- prompt_id: str
- arm_a: str
- arm_b: str
- winner: str = Field(description="a | b | tie | unavailable")
- confidence: float = 0.0
- reasons: list[str] = Field(default_factory=list)
- orderings: list[dict] = Field(default_factory=list)
- cost_usd: float = 0.0
- judged: bool = Field(default=True, description="False when decided by a missing build (no judge call)")
- error: str = ""
- eligible: bool = Field(default=True, description="False when an infrastructure-failed cell makes this pair unavailable")
- exclusion_reason: str = ""
- rubric: str = Field(default="", description="Track rubric used by the pairwise judge; empty on historical rows")
-
- def natural_key(self) -> tuple[str, ...]:
- """Row identity: one pairwise verdict is one (prompt, arm A, arm B)."""
- return (self.prompt_id, self.arm_a, self.arm_b)
-
-
# ----------------------------------------------------------------------------- aggregates
class ArmStats(BaseModel):
arm: str
@@ -138,17 +117,6 @@ class ArmStats(BaseModel):
ceiling_cut: int = Field(default=0, description="harness cells whose run had a round cut by the ceiling")
-class PairStats(BaseModel):
- arm_a: str
- arm_b: str
- n: int
- wins_a: int
- wins_b: int
- ties: int
- win_rate_a: float | None = Field(description="wins_a / (wins_a + wins_b); ties excluded")
- mean_confidence: float
-
-
def _mean(xs: list[float]) -> float | None:
return round(statistics.fmean(xs), 4) if xs else None
@@ -180,21 +148,6 @@ def arm_stats(rows: list[CellResult]) -> list[ArmStats]:
return sorted(out, key=lambda s: (s.kind != "harness", -(s.mean_score or -1)))
-def pair_stats(pairs: list[PairRow]) -> list[PairStats]:
- groups: dict[tuple[str, str], list[PairRow]] = {}
- for p in pairs:
- if not p.eligible:
- continue
- groups.setdefault((p.arm_a, p.arm_b), []).append(p)
- out = []
- for (a, b), ps in groups.items():
- wa, wb = sum(p.winner == "a" for p in ps), sum(p.winner == "b" for p in ps)
- out.append(PairStats(arm_a=a, arm_b=b, n=len(ps), wins_a=wa, wins_b=wb, ties=len(ps) - wa - wb,
- win_rate_a=round(wa / (wa + wb), 4) if wa + wb else None,
- mean_confidence=round(statistics.fmean(p.confidence for p in ps), 3)))
- return out
-
-
# ----------------------------------------------------------------------------- markdown
def _prompt_order(rows: list[CellResult], meta: dict) -> list[str]:
"""Battery order, restricted to prompts that have at least one cell."""
@@ -223,7 +176,7 @@ def _cell_text(r: CellResult | None) -> str:
return f"{r.score:.2f}{'✓' if r.passed else ''}{flag}{'†' if r.degraded else ''}"
-def compare_markdown(out: Path, rows: list[CellResult], pairs: list[PairRow], meta: dict) -> str:
+def compare_markdown(out: Path, rows: list[CellResult], meta: dict) -> str:
opts = meta.get("options", {})
arms = _arm_order(rows, meta)
prompts = _prompt_order(rows, meta)
@@ -253,15 +206,6 @@ def compare_markdown(out: Path, rows: list[CellResult], pairs: list[PairRow], me
for pid in prompts:
tier = next((r.tier for r in rows if r.prompt_id == pid), "")
md.append(f"| {pid} | {tier} | " + " | ".join(_cell_text(cells.get((pid, a))) for a in arms) + " |")
- md += ["", "## pairwise arena (PairwiseJudge, both orders; ties = orderings disagree or equal)", "",
- "| harness arm (A) | one-shot arm (B) | n | A wins | B wins | ties | A win rate | conf |", "|---|---|---|---|---|---|---|---|"]
- for s in pair_stats(pairs):
- md.append(f"| {s.arm_a} | {s.arm_b} | {s.n} | {s.wins_a} | {s.wins_b} | {s.ties} | {_f(s.win_rate_a, '.0%')} | {s.mean_confidence:.2f} |")
- if pairs:
- md += ["", "### pairwise verdicts", "", "| prompt | A | B | winner | conf | judged | reason |", "|---|---|---|---|---|---|---|"]
- for p in sorted(pairs, key=lambda p: (p.prompt_id, p.arm_a, p.arm_b)):
- md.append(f"| {p.prompt_id} | {p.arm_a} | {p.arm_b} | {p.winner} | {p.confidence:.2f} | {'yes' if p.judged else 'no'} | "
- f"{html.escape((p.reasons[0] if p.reasons else p.error)[:160])} |")
hr = [r for r in rows if r.kind == "harness"]
if hr:
md += ["", "## harness runs (loop judge score vs fixed judge score)", "",
@@ -269,8 +213,8 @@ def compare_markdown(out: Path, rows: list[CellResult], pairs: list[PairRow], me
md += [f"| {r.prompt_id} | {r.arm} | {r.harness_status} | {r.harness_stop_reason} | {r.harness_rounds} | {r.harness_aborted_rounds or ''} | "
f"{_f(r.harness_loop_score)} | {_f(r.score)} | {r.gen_cost_usd:.2f} | {cell_minutes(r):.1f} | {'† ' + r.degraded_reason if r.degraded else ''} |"
for r in sorted(hr, key=lambda r: (r.prompt_id, r.arm))]
- total_gen, total_judge, total_pw = sum(r.gen_cost_usd for r in rows), sum(r.judge_cost_usd for r in rows), sum(p.cost_usd for p in pairs)
- md += ["", f"**Total cost**: generation ${total_gen:.2f} · fixed judge ${total_judge:.2f} · pairwise ${total_pw:.2f} "
+ total_gen, total_judge = sum(r.gen_cost_usd for r in rows), sum(r.judge_cost_usd for r in rows)
+ md += ["", f"**Total cost**: generation ${total_gen:.2f} · fixed judge ${total_judge:.2f} "
f"(subscription CLIs report their own cost figure or 0)."]
errs = [r for r in rows if r.error]
if errs:
@@ -286,7 +230,7 @@ _STYLE = ("body{font-family:system-ui,sans-serif;margin:24px;background:#111;col
"pre{white-space:pre-wrap;font-size:11px;color:#bbb}")
-def compare_html(out: Path, rows: list[CellResult], pairs: list[PairRow], meta: dict) -> str:
+def compare_html(out: Path, rows: list[CellResult], meta: dict) -> str:
assets = out / "report_assets"
assets.mkdir(exist_ok=True)
arms = _arm_order(rows, meta)
@@ -295,8 +239,6 @@ def compare_html(out: Path, rows: list[CellResult], pairs: list[PairRow], meta:
head = "<tr><th>arm</th><th>n</th><th>mean</th><th>pass</th><th>build ok</th><th>$gen</th><th>min</th></tr>"
summ = "".join(f"<tr><td>{html.escape(s.arm)}</td><td>{s.n}</td><td>{_f(s.mean_score)}</td><td>{_f(s.pass_rate, '.0%')}</td>"
f"<td>{s.build_ok_rate:.0%}</td><td>{s.mean_gen_usd:.2f}</td><td>{s.mean_minutes:.1f}</td></tr>" for s in arm_stats(rows))
- pw = "".join(f"<tr><td>{html.escape(s.arm_a)}</td><td>{html.escape(s.arm_b)}</td><td>{s.wins_a}/{s.wins_b}/{s.ties}</td>"
- f"<td>{_f(s.win_rate_a, '.0%')}</td></tr>" for s in pair_stats(pairs))
grid = ["<table class='g'><tr><th>prompt</th>" + "".join(f"<th>{html.escape(a)}</th>" for a in arms) + "</tr>"]
for pid in prompts:
tds = []
@@ -320,20 +262,18 @@ def compare_html(out: Path, rows: list[CellResult], pairs: list[PairRow], meta:
name = meta.get("battery", {}).get("name", out.name)
return (f"<!doctype html><meta charset='utf-8'><title>compare {html.escape(name)}</title><style>{_STYLE}</style>"
f"<h1>harness vs one-shot — {html.escape(name)}</h1><p>fixed judge {html.escape(str(meta.get('options', {}).get('judge')))}</p>"
- f"<table>{head}{summ}</table><h2>pairwise (A wins / B wins / ties)</h2><table><tr><th>A (harness)</th><th>B (one-shot)</th>"
- f"<th>w/l/t</th><th>A win rate</th></tr>{pw}</table><h2>gallery</h2>{''.join(grid)}")
+ f"<table>{head}{summ}</table><h2>gallery</h2>{''.join(grid)}")
def build_compare_report(out_dir: Path | str) -> tuple[str, str]:
out = Path(out_dir)
rows = list(latest(read_jsonl(out / "results.jsonl", CellResult)).values())
- pairs = list(latest(read_jsonl(out / "pairwise.jsonl", PairRow)).values())
meta = json.loads((out / "matrix.json").read_text()) if (out / "matrix.json").is_file() else {}
- md = compare_markdown(out, rows, pairs, meta)
- page = compare_html(out, rows, pairs, meta)
+ md = compare_markdown(out, rows, meta)
+ page = compare_html(out, rows, meta)
(out / "report.md").write_text(md)
(out / "report.html").write_text(page)
return md, page
-__all__ = ["ArmStats", "CellResult", "PairRow", "PairStats", "arm_stats", "build_compare_report", "pair_stats"]
+__all__ = ["ArmStats", "CellResult", "arm_stats", "build_compare_report"]
diff --git a/eval/bench/ab_plan.py b/eval/bench/ab_plan.py
index eaf21913..b25f4608 100644
--- a/eval/bench/ab_plan.py
+++ b/eval/bench/ab_plan.py
@@ -190,7 +190,6 @@ class AbOptions(BaseModel):
max_minutes=self.max_minutes,
n_samples=self.n_samples,
resume=self.resume,
- pairwise=False,
)
diff --git a/eval/bench/compare_backends.py b/eval/bench/compare_backends.py
index c755971c..85c468ef 100644
--- a/eval/bench/compare_backends.py
+++ b/eval/bench/compare_backends.py
@@ -20,12 +20,10 @@ Every arm ends with a ``src/model.py`` that is copied into a fresh eval workspac
and scored by the SAME fixed evaluator: BlenderRuntime lint+build → measure →
connectivity gate → 14-view ``render_glb`` → ``VlmJudge(static_object, judge,
n_samples=2)`` whose acceptance checklist is the battery's ``must_have`` list.
-A failed build (or unparseable answer) scores 0 with the error recorded. Then a
-pairwise arena (``PairwiseJudge``, same judge model, both orders) runs every
-harness arm against every one-shot arm per prompt.
+A failed build (or unparseable answer) scores 0 with the error recorded.
Layout of ``--out``: ``matrix.json`` · ``results.jsonl`` (cells; resume source) ·
-``pairwise.jsonl`` · ``cells/<prompt>/<arm>/{run,gen,eval}`` · ``report.md`` ·
+``cells/<prompt>/<arm>/{run,gen,eval}`` · ``report.md`` ·
``report.html`` (+ ``report_assets/``).
"""
@@ -56,8 +54,8 @@ for _p in (REPO, Path(__file__).resolve().parents[1]): # its codeverse3d +
from datetime import UTC # noqa: E402
-from bench._compare_report import CellResult, PairRow, build_compare_report # noqa: E402
-from bench._fixed_eval import EvalOutcome, FixedEvaluator, rubric_for # noqa: E402
+from bench._compare_report import CellResult, build_compare_report # noqa: E402
+from bench._fixed_eval import EvalOutcome, FixedEvaluator # noqa: E402
from bench._infra import is_budget_exhaustion, is_infra_failure, judge_outage # noqa: E402
from bench._jsonl import latest, read_jsonl, seal_for_append # noqa: E402
from bench._oneshot import ( # noqa: E402
@@ -80,7 +78,6 @@ from bench.run_bench import ( # noqa: E402
)
from codeverse3d.addons import select # noqa: E402
from codeverse3d.config import get_settings # noqa: E402
-from codeverse3d.contracts.artifacts import RenderSet # noqa: E402
from codeverse3d.contracts.common import ENTRY_FILE, Backends, Track, Usage # noqa: E402
from codeverse3d.contracts.run import RunRecord, RunStatus # noqa: E402
from codeverse3d.contracts.spec import Spec # noqa: E402
@@ -146,7 +143,6 @@ class CompareOptions(BaseModel):
gen_timeout_s: float = 900.0
repair_attempts: int = 2
n_samples: int = 2
- pairwise: bool = True
degraded_min_wall_s: float = Field(default=40 * 60, description="flag_degraded: a harness run this long that never iterated waited, it did not work")
degraded_max_rounds: int = Field(default=1, description="flag_degraded: completed rounds at or below this count")
redo_status: list[str] = Field(default_factory=list, description="re-run cells whose status is one of these")
@@ -168,18 +164,10 @@ class CompareDeps:
"""Everything that touches a model / Blender / Chrome; tests swap these for fakes."""
def __init__(self, evaluator: FixedEvaluator | Any, *, run_track: RunTrackFn | None = None,
- oneshot_backend: Callable[[str], OneShotBackend] | None = None,
- pairwise_judge: Callable[[str], Any] | None = None):
+ oneshot_backend: Callable[[str], OneShotBackend] | None = None):
self.evaluator = evaluator
self.run_track = run_track or default_run_track
self.oneshot_backend = oneshot_backend or get_oneshot_backend
- self.pairwise_judge = pairwise_judge or _default_pairwise
-
-
-def _default_pairwise(model_id: str) -> Any:
- from codeverse3d.judges.pairwise import PairwiseJudge
-
- return PairwiseJudge(model_id)
# ----------------------------------------------------------------------------- one cell
@@ -493,71 +481,7 @@ def _fill_from_outcome(res: CellResult, o: EvalOutcome) -> None:
res.criteria = {k: round(v, 3) for k, v in j.scores.items()}
-# ----------------------------------------------------------------------------- pairwise arena
-def _renders_of(out: Path, r: CellResult) -> RenderSet | None:
- p = Path(r.workspace) / "eval" / "eval.json"
- if not p.is_file():
- return None
- o = EvalOutcome.model_validate(json.loads(p.read_text()))
- return o.renders if o.renders and o.renders.views else None
-
-
-def run_pairwise(battery: Battery, cells: dict[tuple[str, str], CellResult], arms: Sequence[Arm], out: Path,
- opts: CompareOptions, deps: CompareDeps) -> list[PairRow]:
- path = out / "pairwise.jsonl"
- done = latest(read_jsonl(path, PairRow)) if opts.resume else {}
- harness = [a for a in arms if a.kind == "harness"]
- oneshot = [a for a in arms if a.kind != "harness"]
- judge = None
- seal_for_append(path) # a kill left the last row unterminated; do not glue onto it
- with path.open("a") as fh:
- for item in battery.prompts:
- for ha in harness:
- for oa in oneshot:
- key = (item.id, ha.raw, oa.raw)
- ca, cb = cells.get((item.id, ha.raw)), cells.get((item.id, oa.raw))
- if ca is None or cb is None:
- continue
- infra = any(c.status == "infra_failed" or c.error_is_infra for c in (ca, cb))
- if infra:
- if key in done and not done[key].eligible:
- continue
- # A provider outage is unavailable evidence, even if it left
- # a partial render. Supersede cached automatic wins as well.
- row = PairRow(prompt_id=item.id, arm_a=ha.raw, arm_b=oa.raw,
- winner="unavailable", judged=False, eligible=False,
- exclusion_reason="A cell failed because of infrastructure; no quality comparison.",
- reasons=["excluded: infrastructure failure"])
- else:
- if key in done and done[key].eligible:
- continue
- spec = spec_for(battery, item, ha, opts)
- ra, rb = _renders_of(out, ca), _renders_of(out, cb)
- if ra is None or rb is None:
- winner = "tie" if ra is None and rb is None else ("a" if rb is None else "b")
- row = PairRow(prompt_id=item.id, arm_a=ha.raw, arm_b=oa.raw, winner=winner, confidence=1.0,
- reasons=["decided without the judge: a side has no renders (build failed)"], judged=False)
- else:
- judge = judge or deps.pairwise_judge(opts.judge)
- pr = judge.compare(spec, ra, rb, rubric=rubric_for(spec))
- row = PairRow(prompt_id=item.id, arm_a=ha.raw, arm_b=oa.raw, winner=pr.winner, confidence=pr.confidence,
- reasons=list(pr.reasons), orderings=list(pr.orderings), cost_usd=pr.usage.cost_usd,
- error=pr.error, judged=True, rubric=rubric_for(spec))
- done[key] = row
- fh.write(row.model_dump_json() + "\n")
- fh.flush()
- return list(done.values())
-
-
# ----------------------------------------------------------------------------- matrix
-def _drop_pairs(path: Path, key: tuple[str, str]) -> None:
- """Forget pairwise rows touching a cell that is about to be re-run."""
- rows = [p for p in latest(read_jsonl(path, PairRow)).values()
- if not (p.prompt_id == key[0] and key[1] in (p.arm_a, p.arm_b))]
- if path.is_file():
- write_text_atomic(path, "".join(p.model_dump_json() + "\n" for p in rows))
-
-
def run_matrix(battery_path: Path | str, out_dir: Path | str, arms: Sequence[Arm], opts: CompareOptions,
deps: CompareDeps, *, on_result: Callable[[CellResult], None] | None = None) -> list[CellResult]:
battery = Battery.load(battery_path)
@@ -569,7 +493,6 @@ def run_matrix(battery_path: Path | str, out_dir: Path | str, arms: Sequence[Arm
results = out / "results.jsonl"
done = latest(read_jsonl(results, CellResult)) if opts.resume else {}
for key in [k for k, r in done.items() if r.status in set(opts.redo_status)]:
- _drop_pairs(out / "pairwise.jsonl", key)
del done[key]
selected = select_prompts(battery, ids=opts.ids, tiers=opts.tiers, limit=opts.limit)
todo = [(p, a) for a in sorted(arms, key=lambda a: a.kind == "harness") # cheap one-shots first
@@ -591,10 +514,6 @@ def run_matrix(battery_path: Path | str, out_dir: Path | str, arms: Sequence[Arm
fh.flush()
if on_result:
on_result(r)
- if opts.pairwise:
- # the arena is battery-level spend: its own ledger at <out>/telemetry/cost.jsonl
- with run_ledger(out, run=f"{battery.name}:pairwise"):
- run_pairwise(battery, done, arms, out, opts, deps)
build_compare_report(out)
return list(done.values())
@@ -662,7 +581,6 @@ def main(argv: Sequence[str] | None = None) -> int:
ap.add_argument("--judge-samples", type=int, default=2,
help="FIXED judge samples per cell (default 2 — kept for resumable batteries; use an odd "
"n for a true majority on the defect checklist, see docs/DECISIONS.md D36)")
- ap.add_argument("--no-pairwise", action="store_true")
ap.add_argument("--no-preflight", action="store_true",
help="skip the provider health check (see --wait-for-provider)")
ap.add_argument("--wait-for-provider", type=float, default=0.0, metavar="MIN",
@@ -681,7 +599,7 @@ def main(argv: Sequence[str] | None = None) -> int:
max_minutes=ns.max_minutes, parallel=ns.parallel,
limit=ns.limit, ids=[i for i in ns.ids.split(",") if i],
tiers=[t for t in ns.tiers.split(",") if t], resume=not ns.no_resume,
- gen_timeout_s=ns.gen_timeout, repair_attempts=ns.repair_attempts, pairwise=not ns.no_pairwise,
+ gen_timeout_s=ns.gen_timeout, repair_attempts=ns.repair_attempts,
n_samples=max(1, ns.judge_samples),
redo_status=[x for x in ns.redo_status.split(",") if x])
arms = parse_arms(ns.arms)
diff --git a/eval/bench/complexity_report.py b/eval/bench/complexity_report.py
index 43a65a2f..1b465336 100644
--- a/eval/bench/complexity_report.py
+++ b/eval/bench/complexity_report.py
@@ -81,7 +81,7 @@ def _vector_for(run: Path, rnd: dict[str, Any] | None) -> ComplexityVector | Non
"""
ws, one = Workspace(run), RoundRecord(index=int((rnd or {}).get("index") or 0), kind="")
own = (((rnd or {}).get("measurement") or {}).get("extra") or {}).get("complexity")
- for block in (own, select.round_complexity_block(ws, one)):
+ for block in (own, select.round_complexity_block(one)):
if isinstance(block, dict):
try:
return ComplexityVector.model_validate(block)
diff --git a/eval/tests/conftest.py b/eval/tests/conftest.py
index cfca99bc..60180490 100644
--- a/eval/tests/conftest.py
+++ b/eval/tests/conftest.py
@@ -151,15 +151,3 @@ def fake_run_track(score: float = 0.8):
run.calls = calls # type: ignore[attr-defined]
return run
-
-
-class FakePairwise:
- def __init__(self, model_id: str):
- self.model_id = model_id
- self.calls = 0
-
- def compare(self, spec: Spec, ra: RenderSet, rb: RenderSet, *, rubric: Any = None):
- from codeverse3d.judges.pairwise import PairwiseResult
-
- self.calls += 1
- return PairwiseResult(winner="a", confidence=0.8, reasons=["Candidate A is cleaner"], usage=Usage(cost_usd=0.03))
diff --git a/eval/tests/test_compare_matrix.py b/eval/tests/test_compare_matrix.py
index d7f408ce..6397ab6d 100644
--- a/eval/tests/test_compare_matrix.py
+++ b/eval/tests/test_compare_matrix.py
@@ -1,4 +1,4 @@
-"""Matrix runner: cells, resume, pairwise arena, report (offline, fakes)."""
+"""Matrix runner: cells, resume, report (offline, fakes)."""
from __future__ import annotations
@@ -14,11 +14,8 @@ if str(REPO) not in sys.path:
from bench._compare_report import ( # noqa: E402
CellResult,
- PairRow,
arm_stats,
- pair_stats,
)
-from bench._jsonl import latest, read_jsonl # noqa: E402
from bench.compare_backends import ( # noqa: E402
CompareDeps,
CompareOptions,
@@ -35,7 +32,6 @@ from tests.conftest import ( # noqa: E402
GOOD,
FakeBackend,
FakeEvaluator,
- FakePairwise,
GeminiChat,
fake_run_track,
)
@@ -66,15 +62,7 @@ def test_spec_for_and_acceptance():
def _deps(ev: FakeEvaluator, backends: dict[str, FakeBackend], run_track) -> CompareDeps:
- pw = {}
-
- def _pw(model_id: str):
- pw.setdefault(model_id, FakePairwise(model_id))
- return pw[model_id]
-
- deps = CompareDeps(ev, run_track=run_track, oneshot_backend=lambda t: backends[t], pairwise_judge=_pw)
- deps.pw = pw # type: ignore[attr-defined]
- return deps
+ return CompareDeps(ev, run_track=run_track, oneshot_backend=lambda t: backends[t])
def test_matrix_end_to_end_with_fakes(tmp_path: Path):
@@ -109,14 +97,6 @@ def test_matrix_end_to_end_with_fakes(tmp_path: Path):
assert len(repairs) == 4 and all("BOOM" in c and "PREVIOUS `src/model.py`" in c for c in repairs)
# the fixed evaluator ran once per cell that had code (6 of 8)
assert len(ev.evaluated) == 6
- # pairwise: 1 harness arm × 3 one-shot arms × 2 prompts = 6 rows; the no-code arm is auto-decided
- pairs = list(latest(read_jsonl(out / "pairwise.jsonl", PairRow)).values())
- assert len(pairs) == 6
- auto = [p for p in pairs if p.arm_b == "oneshot:gemini:gemini-3.8-flash"]
- assert all(p.winner == "a" and not p.judged for p in auto)
- judged = [p for p in pairs if p.judged]
- assert len(judged) == 4 and all(p.winner == "a" and p.cost_usd == pytest.approx(0.03) for p in judged)
- assert deps.pw["gemini:fixed"].calls == 4
# report
md = (out / "report.md").read_text()
assert "fixed judge: **gemini:fixed**" in md
@@ -125,7 +105,6 @@ def test_matrix_end_to_end_with_fakes(tmp_path: Path):
assert "| arm | kind | n | dropped | over budget | mean |" in md, md
assert "| harness:agy:gemini-3.8-flash | harness | 2 | | | 0.900 |" in md, md
assert "| cmp_easy_stool | easy | 0.90✓ | 0.60 | 0.75✓ | 0.00 ✗build |" in md
- assert "| harness:agy:gemini-3.8-flash | oneshot:claude-code | 2 | 2 | 0 | 0 | 100% |" in md
page = (out / "report.html").read_text()
assert "report_assets/cmp_easy_stool__harness_agy_gemini-3.8-flash.png" in page
assert len(list((out / "report_assets").glob("*.png"))) == 6
@@ -134,12 +113,11 @@ def test_matrix_end_to_end_with_fakes(tmp_path: Path):
run_track2 = fake_run_track(0.1)
deps2 = _deps(FakeEvaluator(), {k: FakeBackend(["x"]) for k in backends}, run_track2)
rows2 = run_matrix(BATTERY, out, parse_arms(ARMS), opts, deps2)
- assert len(rows2) == 8 and not run_track2.calls and deps2.evaluator.evaluated == [] and not deps2.pw
+ assert len(rows2) == 8 and not run_track2.calls and deps2.evaluator.evaluated == []
assert {(r.prompt_id, r.arm): r.score for r in rows2} == {(r.prompt_id, r.arm): r.score for r in rows}
# ---- adding a prompt (limit 3) only runs the new cells
rows3 = run_matrix(BATTERY, out, parse_arms(ARMS), opts.model_copy(update={"limit": 3}), deps2)
assert len(rows3) == 12 and run_track2.calls == ["compare_v1/cmp_med_dining_chair"]
- assert len(latest(read_jsonl(out / "pairwise.jsonl", PairRow))) == 9
def test_cell_errors_are_recorded_not_raised(tmp_path: Path):
@@ -153,8 +131,7 @@ def test_cell_errors_are_recorded_not_raised(tmp_path: Path):
def failing_track(spec, ws, resume):
raise RuntimeError("planner down")
- deps = CompareDeps(Exploding(), run_track=failing_track, oneshot_backend=lambda t: FakeBackend([GOOD.format(score=0.5)]),
- pairwise_judge=FakePairwise)
+ deps = CompareDeps(Exploding(), run_track=failing_track, oneshot_backend=lambda t: FakeBackend([GOOD.format(score=0.5)]))
rows = run_matrix(BATTERY, tmp_path / "o", parse_arms("harness:agy:gemini-3.8-flash,oneshot:codex"),
CompareOptions(limit=1, parallel=1), deps)
by = {r.arm: r for r in rows}
@@ -171,10 +148,6 @@ def test_stats_math():
assert s["a"].mean_score == pytest.approx(0.4) and s["a"].pass_rate == 0.5 and s["a"].build_ok_rate == 0.5
assert s["a"].mean_gen_usd == 0.75 and s["a"].mean_minutes == 1.5
assert s["b"].mean_score is None and s["b"].errors == 1
- ps = pair_stats([PairRow(prompt_id="p1", arm_a="a", arm_b="b", winner="a", confidence=0.9),
- PairRow(prompt_id="p2", arm_a="a", arm_b="b", winner="tie", confidence=0.3),
- PairRow(prompt_id="p3", arm_a="a", arm_b="b", winner="b", confidence=0.6)])[0]
- assert (ps.wins_a, ps.wins_b, ps.ties, ps.win_rate_a) == (1, 1, 1, 0.5) and ps.mean_confidence == pytest.approx(0.6)
def test_cli_report_only(tmp_path: Path):
@@ -207,16 +180,16 @@ def test_redo_status_reuses_recorded_answers(tmp_path: Path):
"""A redo of failed cells re-evaluates without a second generation call; a failed generation is not cached."""
ev = FakeEvaluator()
be = FakeBackend([BAD])
- deps = CompareDeps(ev, run_track=fake_run_track(), oneshot_backend=lambda t: be, pairwise_judge=FakePairwise)
+ deps = CompareDeps(ev, run_track=fake_run_track(), oneshot_backend=lambda t: be)
out = tmp_path / "o"
- opts = CompareOptions(limit=1, parallel=1, pairwise=False)
+ opts = CompareOptions(limit=1, parallel=1)
rows = run_matrix(BATTERY, out, parse_arms("oneshot:codex"), opts, deps)
assert rows[0].status == "build_failed" and len(be.calls) == 1
assert (out / "cells" / "cmp_easy_stool" / "oneshot_codex" / "gen" / "attempt0" / "result.json").is_file()
rows2 = run_matrix(BATTERY, out, parse_arms("oneshot:codex"), opts.model_copy(update={"redo_status": ["build_failed"]}), deps)
assert rows2[0].status == "build_failed" and len(be.calls) == 1 and len(ev.evaluated) == 2 # re-evaluated, not re-generated
empty = FakeBackend([""])
- deps3 = CompareDeps(ev, run_track=fake_run_track(), oneshot_backend=lambda t: empty, pairwise_judge=FakePairwise)
+ deps3 = CompareDeps(ev, run_track=fake_run_track(), oneshot_backend=lambda t: empty)
rows3 = run_matrix(BATTERY, out, parse_arms("oneshot:claude-code"), opts, deps3)
r3 = next(r for r in rows3 if r.arm == "oneshot:claude-code")
assert r3.status == "no_code" and "empty" in r3.error
@@ -248,7 +221,7 @@ def test_every_cell_and_its_harness_run_open_a_ledger(tmp_path: Path):
deps = _deps(ev, {"claude-code": FakeBackend(["```python\n" + GOOD.format(score=0.6) + "```"])}, run_track)
out = tmp_path / "cmp"
- opts = CompareOptions(judge="gemini:fixed", limit=1, parallel=2, pairwise=False)
+ opts = CompareOptions(judge="gemini:fixed", limit=1, parallel=2)
rows = run_matrix(BATTERY, out, parse_arms("harness:agy:gemini-3.8-flash,oneshot:claude-code"),
opts, deps)
assert len(rows) == 2
@@ -274,7 +247,7 @@ def test_no_resume_starts_the_harness_arm_fresh(tmp_path: Path):
out = tmp_path / "cmp"
arms = parse_arms("harness:agy:gemini-3.8-flash")
deps = _deps(ev, {}, run)
- opts = CompareOptions(judge="gemini:fixed", limit=1, parallel=1, pairwise=False)
+ opts = CompareOptions(judge="gemini:fixed", limit=1, parallel=1)
cell = Path(run_matrix(BATTERY, out, arms, opts, deps)[0].workspace)
(cell / "run" / "src" / "stale.py").write_text("# stale")
run_matrix(BATTERY, out, arms, opts, deps)
diff --git a/eval/tests/test_import_arm.py b/eval/tests/test_import_arm.py
index db187aa4..8f03f59e 100644
--- a/eval/tests/test_import_arm.py
+++ b/eval/tests/test_import_arm.py
@@ -70,7 +70,7 @@ def test_the_report_names_an_import_arms_assets_without_its_path(tmp_path):
(src / f"{item.id}.py").write_text(GOOD.format(score=0.7))
from bench.compare_backends import run_matrix
run_matrix(BATTERY, tmp_path / "out", [parse_arm(f"import:{src}")],
- CompareOptions(judge="gemini:x", loop_judge="gemini:x", ids=[item.id], pairwise=False),
+ CompareOptions(judge="gemini:x", loop_judge="gemini:x", ids=[item.id]),
CompareDeps(FakeEvaluator()))
assets = list((tmp_path / "out" / "report_assets").glob("*"))
assert assets and all("/" not in a.name and a.is_file() for a in assets)
diff --git a/eval/tests/test_infra_failures.py b/eval/tests/test_infra_failures.py
index b018c2c6..aa13c7a5 100644
--- a/eval/tests/test_infra_failures.py
+++ b/eval/tests/test_infra_failures.py
@@ -9,64 +9,6 @@ import pytest
from bench._compare_report import CellResult, arm_stats
from bench._infra import is_infra_failure
-
[email protected]("failed_side", [0, 1])
-def test_pairwise_outage_is_unavailable_even_with_cached_win(tmp_path, monkeypatch, failed_side):
- from bench import compare_backends as cb
- from bench._compare_report import PairRow, pair_stats
- from bench.run_bench import Battery
- from tests.conftest import BATTERY, FakeEvaluator
-
- battery = Battery.load(BATTERY)
- battery = battery.model_copy(update={"prompts": battery.prompts[:1]})
- prompt = battery.prompts[0].id
- arms = cb.parse_arms("harness:codex:gpt-6-astra@high,agent:agy:gemini-3.8-flash")
- rows = [CellResult(prompt_id=prompt, arm=a.raw, kind=a.kind, status="scored", score=0.6) for a in arms]
- rows[failed_side] = rows[failed_side].model_copy(update={"status": "infra_failed", "error_is_infra": True, "score": None})
- cells = {(r.prompt_id, r.arm): r for r in rows}
- old = PairRow(prompt_id=prompt, arm_a=arms[0].raw, arm_b=arms[1].raw, winner="a", judged=False)
- path = tmp_path / "pairwise.jsonl"
- path.write_text(old.model_dump_json() + "\n")
-
- def no_render_lookup(*args):
- pytest.fail("An outage cannot enter the missing-render or partial-render comparison path")
-
- monkeypatch.setattr(cb, "_renders_of", no_render_lookup)
- deps = cb.CompareDeps(FakeEvaluator())
- pairs = cb.run_pairwise(battery, cells, arms, tmp_path, cb.CompareOptions(), deps)
- assert len(pairs) == 1 and not pairs[0].eligible
- assert pairs[0].winner == "unavailable" and not pairs[0].judged
- assert pair_stats(pairs) == [] # neither a loss nor a tie in any denominator
- assert len(path.read_text().splitlines()) == 2 # old evidence retained, superseded
- cb.run_pairwise(battery, cells, arms, tmp_path, cb.CompareOptions(), deps)
- assert len(path.read_text().splitlines()) == 2 # resume does not duplicate the exclusion
-
-
-def test_scene_pairwise_uses_the_same_track_rubric_as_fixed_evaluation(tmp_path, monkeypatch):
- from bench import compare_backends as cb
- from bench.run_bench import Battery
- from codeverse3d.contracts.common import Language, Track
- from tests.conftest import BATTERY, FakeEvaluator, FakePairwise
-
- battery = Battery.load(BATTERY)
- battery = battery.model_copy(update={"prompts": battery.prompts[:1], "track": Track.SCENE,
- "language": Language.SCENE_THREEJS})
- arms = cb.parse_arms("harness:codex:gpt-6-astra@high,agent:agy:gemini-3.8-flash")
- cells = {(battery.prompts[0].id, a.raw): CellResult(prompt_id=battery.prompts[0].id,
- arm=a.raw, kind=a.kind, status="scored", score=0.6) for a in arms}
- monkeypatch.setattr(cb, "_renders_of", lambda *args: object())
- seen = []
-
- class Judge(FakePairwise):
- def compare(self, spec, ra, rb, *, rubric=None):
- seen.append(rubric)
- return super().compare(spec, ra, rb, rubric=rubric)
-
- pairs = cb.run_pairwise(battery, cells, arms, tmp_path, cb.CompareOptions(),
- cb.CompareDeps(FakeEvaluator(), pairwise_judge=Judge))
- assert seen == ["scene"]
- assert pairs[0].rubric == "scene"
-
OUTAGES = [
"ModelError: Gemini API error 503: This model is currently experiencing high demand.",
"ModelError: Gemini request timed out: The read operation timed out",
diff --git a/eval/tests/test_live_compare.py b/eval/tests/test_live_compare.py
index 6cb8c22c..cbb53f59 100644
--- a/eval/tests/test_live_compare.py
+++ b/eval/tests/test_live_compare.py
@@ -20,7 +20,7 @@ pytestmark = [pytest.mark.live, pytest.mark.blender, pytest.mark.node]
@pytest.mark.skipif(not get_settings().gemini_api_keys, reason="no gemini keys")
def test_oneshot_gemini_cell_scores(tmp_path: Path):
- opts = CompareOptions(judge="gemini:gemini-3.8-flash", n_samples=1, limit=1, parallel=1, pairwise=False)
+ opts = CompareOptions(judge="gemini:gemini-3.8-flash", n_samples=1, limit=1, parallel=1)
deps = CompareDeps(FixedEvaluator(opts.judge, n_samples=1))
rows = run_matrix(REPO / "bench" / "prompts" / "compare_v1.yaml", tmp_path / "o",
parse_arms("oneshot:gemini:gemini-3.8-flash"), opts, deps)
diff --git a/harness/codeverse3d/addons/costreport/__init__.py b/harness/codeverse3d/addons/costreport/__init__.py
index cdaafda2..c9cd657e 100644
--- a/harness/codeverse3d/addons/costreport/__init__.py
+++ b/harness/codeverse3d/addons/costreport/__init__.py
@@ -2,7 +2,6 @@
* ``audit`` ``audit_runs(paths)`` → ``Audit`` (every run's ledger under the paths, aggregated, + waste)
* ``report`` ``console(audit)`` · ``markdown(audit)``
-* ``caching`` what prompt caching saved, per session
-Booking the money WHILE a run happens (ledger, guard, billing, instrument) is ``codeverse3d.cost``.
+Booking the money WHILE a run happens (ledger, billing, instrument) is ``codeverse3d.cost``.
"""
diff --git a/harness/codeverse3d/addons/costreport/caching.py b/harness/codeverse3d/addons/costreport/caching.py
deleted file mode 100644
index 28fd7d12..00000000
--- a/harness/codeverse3d/addons/costreport/caching.py
+++ /dev/null
@@ -1,58 +0,0 @@
-"""Per-session cache behaviour, read back out of the ledger."""
-
-from __future__ import annotations
-
-from collections.abc import Sequence
-from dataclasses import dataclass
-
-
-# --------------------------------------------------------------------------- ledger view
-@dataclass
-class SessionCache:
-
- key: str
- n_calls: int = 0
- first_input: int = 0
- first_cached: int = 0
- input_tokens: int = 0
- cached_tokens: int = 0
- cost_usd: float = 0.0
- price_input: float = 0.0
- price_cached: float = 0.0
-
- @property
- def cached_fraction(self) -> float:
- return self.cached_tokens / self.input_tokens if self.input_tokens else 0.0
-
- @property
- def saved_usd(self) -> float:
- return self.cached_tokens * max(0.0, self.price_input - self.price_cached) / 1e6
-
- @property
- def cold_usd(self) -> float:
- return self.first_input * self.price_input / 1e6 if not self.first_cached else 0.0
-
-
-def session_key(label: str) -> str:
- parts = [p for p in (label or "").split(":") if p]
- while parts and len(parts[-1]) > 1 and parts[-1][0] in "tsr" and parts[-1][1:].isdigit():
- parts = parts[:-1]
- return ":".join(parts)
-
-
-def session_cache(rows: Sequence[object]) -> list[SessionCache]:
- out: dict[tuple[object, str], SessionCache] = {}
- for row in rows:
- k = (getattr(row, "round", None), session_key(str(getattr(row, "label", "") or "")))
- s = out.get(k)
- if s is None:
- s = out[k] = SessionCache(key=f"r{k[0] if k[0] is not None else '-'}:{k[1]}",
- first_input=int(getattr(row, "input_tokens", 0)),
- first_cached=int(getattr(row, "cached_tokens", 0)),
- price_input=float(getattr(row, "price_input", 0.0)),
- price_cached=float(getattr(row, "price_cached", 0.0)))
- s.n_calls += 1
- s.input_tokens += int(getattr(row, "input_tokens", 0))
- s.cached_tokens += min(int(getattr(row, "cached_tokens", 0)), int(getattr(row, "input_tokens", 0)))
- s.cost_usd += float(getattr(row, "cost_usd", 0.0))
- return list(out.values())
diff --git a/harness/codeverse3d/addons/dataset/sample.py b/harness/codeverse3d/addons/dataset/sample.py
index d2d728e0..b1c94d1e 100644
--- a/harness/codeverse3d/addons/dataset/sample.py
+++ b/harness/codeverse3d/addons/dataset/sample.py
@@ -244,7 +244,7 @@ def build_meta(
code_files = [f for f in files if f.startswith("src/")]
gates = gate_error_summary(rnd)
n_gate_errors = sum(gates.values())
- cx = select.round_complexity_block(ws, rnd)
+ cx = select.round_complexity_block(rnd)
name = ""
if record.plan is not None:
name = getattr(record.plan, "object_name", "") or getattr(record.plan, "title", "")
diff --git a/harness/codeverse3d/addons/gallery/index.py b/harness/codeverse3d/addons/gallery/index.py
index 310ad592..5bcd9cf1 100644
--- a/harness/codeverse3d/addons/gallery/index.py
+++ b/harness/codeverse3d/addons/gallery/index.py
@@ -155,7 +155,7 @@ _CX_AXES = ("part_count", "assembly_depth", "tri_count", "materials",
def _complexity(ws: Workspace, rec: RunRecord, picked: int | None) -> tuple[float | None, str, dict[str, float]]:
try:
- block = select.round_complexity_block(ws, next((r for r in rec.rounds if r.index == picked), None))
+ block = select.round_complexity_block(next((r for r in rec.rounds if r.index == picked), None))
except Exception: # noqa: BLE001
block = None
if block is None or block.get("index") is None:
diff --git a/harness/codeverse3d/addons/select.py b/harness/codeverse3d/addons/select.py
index dbf405a5..ce982e10 100644
--- a/harness/codeverse3d/addons/select.py
+++ b/harness/codeverse3d/addons/select.py
@@ -2,29 +2,23 @@
from __future__ import annotations
-import hashlib
import logging
from collections.abc import Iterable
from datetime import UTC, datetime
from pathlib import Path
-from typing import Any, Literal
+from typing import Literal
from pydantic import BaseModel, Field
-from codeverse3d.contracts.common import Usage
from codeverse3d.contracts.run import RoundRecord, RunRecord
from codeverse3d.contracts.spec import FIXED_PARTS_GATE, PROJECT_GATE_PREFIX
-from codeverse3d.cost.context import call_context
-from codeverse3d.cost.types import Role, Stage
-from codeverse3d.judges.base import judged_subset, resolve_paths
-from codeverse3d.proc import EventLog, read_json_or_none, sha256_file
+from codeverse3d.proc import EventLog, read_json_or_none
from codeverse3d.record.deliverable import build_deliverable, round_outputs
from codeverse3d.record.record import (
effective_judgment,
load_record,
repackage,
round_complexity,
- rubric_of,
stop_reason,
)
from codeverse3d.workspace import Workspace
@@ -32,11 +26,7 @@ from codeverse3d.workspace import Workspace
log = logging.getLogger(__name__)
SELECTION_NAME = "selection.json"
-PAIRWISE_MARGIN = 0.03
-PAIRWISE_MIN_CONFIDENCE = 0.6
-
-PickBy = Literal["score", "pairwise"]
-Method = Literal["score", "pairwise", "round"]
+Method = Literal["score", "round"]
class RoundRow(BaseModel):
@@ -76,18 +66,6 @@ class Selection(BaseModel):
selected_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
-class PairwiseNote(BaseModel):
-
- a: str = Field(description="label of the top-scored round")
- b: str = Field(description="label of the runner-up")
- winner: Literal["a", "b", "tie"] = "tie"
- confidence: float = 0.0
- accepted: bool = Field(default=False, description="True when the runner-up is picked instead")
- reasons: list[str] = Field(default_factory=list)
- usage: Usage = Field(default_factory=Usage)
- error: str = ""
-
-
# --------------------------------------------------------------------------- rows
def _load(run_dir: Path | str, record: RunRecord | None) -> RunRecord:
return record if record is not None else load_record(Workspace(run_dir))
@@ -123,61 +101,15 @@ def round_file(ws: Workspace, rnd: RoundRecord | None, name: str = "object.glb")
return p if p is not None and p.is_file() else None
-def round_complexity_block(ws: Workspace, rnd: RoundRecord | None) -> dict | None:
+def round_complexity_block(rnd: RoundRecord | None) -> dict | None:
block = round_complexity(rnd) if rnd is not None else None
return block if isinstance(block, dict) else None
# --------------------------------------------------------------------------- pick
-def pick(run_dir: Path | str, *, by: PickBy = "score", pairwise_model: str | None = None,
- record: RunRecord | None = None, judge: Any | None = None) -> int | None:
- rec = _load(run_dir, record)
- ranked = _ranked(round_rows(run_dir, record=rec))
- if not ranked:
- return None
- top = ranked[0]
- if (by != "pairwise" or len(ranked) < 2 or (ranked[1].project_errors > 0) != (top.project_errors > 0)
- or (top.score or 0.0) - (ranked[1].score or 0.0) > PAIRWISE_MARGIN):
- return top.index
- note = pairwise_verdict(Workspace(run_dir), rec, top.index, ranked[1].index,
- model=pairwise_model or rec.spec.backends.judge, judge=judge)
- return ranked[1].index if note.accepted else top.index
-
-
-def pairwise_verdict(ws: Workspace, rec: RunRecord, a: int, b: int, *, model: str, judge: Any | None = None) -> PairwiseNote:
- cache = ws.judge_path(a, f"_vs_r{b:02d}_pairwise")
- rounds = {r.index: r for r in rec.rounds}
- renders = [judged_subset(resolve_paths(ws, rounds[i].renders)) for i in (a, b)]
- note = PairwiseNote(a=f"r{a:02d}", b=f"r{b:02d}")
- if renders[0] is None or renders[1] is None:
- note.error = "a round has no renders to compare"
- return note
- seen = hashlib.sha256("\n".join(sha256_file(v.path) if Path(v.path).is_file() else v.path
- for rs in renders for v in rs.views).encode()).hexdigest()
- stored = read_json_or_none(cache) or {}
- try:
- if judge is None:
- from codeverse3d.judges.pairwise import PairwiseJudge
-
- judge = PairwiseJudge(model)
- if (stored.get("model") == model and stored.get("renders") == seen
- and stored.get("thinking") == judge.thinking and isinstance(stored.get("note"), dict)):
- return PairwiseNote.model_validate(stored["note"])
- with call_context(stage=Stage.PAIRWISE, role=Role.JUDGE, label="pick"):
- res = judge.compare(rec.spec, renders[0], renders[1],
- rubric=rubric_of(rec))
- except Exception as e: # noqa: BLE001
- log.warning("pairwise pick failed: %s", e)
- note.error = f"{type(e).__name__}: {e}"
- return note
- note.winner, note.confidence = res.winner, float(res.confidence or 0.0)
- note.reasons, note.usage, note.error = list(res.reasons or [])[:6], res.usage or Usage(), res.error or ""
- note.accepted = note.winner == "b" and note.confidence >= PAIRWISE_MIN_CONFIDENCE
- ws.write_json(cache, {"model": model, "renders": seen, "thinking": judge.thinking,
- "note": note.model_dump(mode="json")})
- EventLog(ws.events_path).emit("pick.pairwise", a=a, b=b, winner=note.winner, confidence=note.confidence,
- accepted=note.accepted, cost_usd=round(note.usage.cost_usd, 4))
- return note
+def pick(run_dir: Path | str, *, record: RunRecord | None = None) -> int | None:
+ ranked = _ranked(round_rows(run_dir, record=_load(run_dir, record)))
+ return ranked[0].index if ranked else None
def fallback_round(rounds: Iterable[RoundRecord]) -> int | None:
diff --git a/harness/codeverse3d/cli/_judge.py b/harness/codeverse3d/cli/_judge.py
index 0c6e27dc..63d5def5 100644
--- a/harness/codeverse3d/cli/_judge.py
+++ b/harness/codeverse3d/cli/_judge.py
@@ -95,19 +95,3 @@ def make_judge(spec: Spec, rubric_name: str, model_id: str, n: int, **options: A
raise C.CliError(f"cannot load rubric {rubric_name!r}: {e}") from e
cls = vlm_judge.judge_for(spec.track, rubric, references=bool(spec.references))
return cls(model_id=model_id, n_samples=n, rubric=rubric_name, **options)
-
-
-def count_prompt_images(inp: Any, rubric_name: str, judge: Any = None) -> int | None:
- """Number of image parts a single judge sample sends (None on failure), including
- ``judge``'s slice payload when given."""
- try:
- from codeverse3d.contracts.chat import ImagePart
- from codeverse3d.judges.prompt_builder import build_judge_messages
- from codeverse3d.judges.rubrics import load_rubric
-
- slices, elicit = judge.slice_payload(inp) if judge is not None else ([], False)
- _, messages = build_judge_messages(inp, load_rubric(rubric_name),
- slice_images=slices, provenance_elicitation=elicit)
- return sum(1 for m in messages for p in m.parts if isinstance(p, ImagePart))
- except Exception: # noqa: BLE001 — informational only
- return None
diff --git a/harness/codeverse3d/cli/cost_cmd.py b/harness/codeverse3d/cli/cost_cmd.py
index bd5b8432..6b0ee5d7 100644
--- a/harness/codeverse3d/cli/cost_cmd.py
+++ b/harness/codeverse3d/cli/cost_cmd.py
@@ -7,7 +7,6 @@
3dcodeverse cost show runs/ --md report.md # the same, explicit + full markdown
3dcodeverse cost runs/ --recheck # re-price with today's table (drift vs what was billed)
3dcodeverse cost prices [--stale] [--unverified]
- 3dcodeverse cost estimate gemini:… --in 12000 --out 800
"""
from __future__ import annotations
@@ -157,54 +156,3 @@ def _age_days(checked: str) -> int | None:
return (date.today() - datetime.strptime(checked, "%Y-%m-%d").date()).days
except (TypeError, ValueError):
return None
-
-
-# --------------------------------------------------------------------------- cache
-@cost_app.command("cache")
-def cache(
- paths: Annotated[list[Path], typer.Argument(help="run slugs or run dirs")],
- runs_dir: Annotated[Path | None, typer.Option("--runs-dir")] = None,
-) -> None:
- """Did prompt caching happen? Per session: cold first call, cached share, dollars saved."""
- from codeverse3d.addons.costreport.caching import session_cache
- from codeverse3d.cost.ledger import load_ledger
-
- for arg in paths:
- root = _resolve(str(arg), runs_dir)
- rows = load_ledger(root)
- sessions = session_cache(rows)
- if not sessions:
- warn(f"{root}: no priced calls found")
- continue
- console.print(f"[bold]{root.name}[/bold] ({len(rows)} calls, {len(sessions)} sessions)")
- header = ("session", "calls", "first in", "first cached", "cached", "saved $", "cold $")
- table = [header] + [
- (s.key, str(s.n_calls), f"{s.first_input:,}", f"{s.first_cached:,}",
- f"{s.cached_fraction:.0%}", f"{s.saved_usd:.4f}", f"{s.cold_usd:.4f}") for s in sessions]
- widths = [max(len(r[i]) for r in table) for i in range(len(header))]
- for r in table:
- console.print(" " + " ".join(c.rjust(w) if i else c.ljust(w)
- for i, (c, w) in enumerate(zip(r, widths, strict=True))),
- soft_wrap=True)
- tot_in = sum(s.input_tokens for s in sessions)
- tot_cached = sum(s.cached_tokens for s in sessions)
- console.print(f" → {tot_cached:,} of {tot_in:,} input tokens cached ({tot_cached / tot_in if tot_in else 0:.0%}), "
- f"saved ${sum(s.saved_usd for s in sessions):.4f}, "
- f"cold heads cost ${sum(s.cold_usd for s in sessions):.4f}\n")
-
-
-# --------------------------------------------------------------------------- estimate
-@cost_app.command("estimate")
-def estimate(
- model: Annotated[str, typer.Argument(help="model id, e.g. gemini:gemini-3.1-pro-preview")],
- input_tokens: Annotated[int, typer.Option("--in", help="prompt tokens")] = 0,
- output_tokens: Annotated[int, typer.Option("--out", help="expected output tokens")] = 0,
- cached: Annotated[int, typer.Option("--cached")] = 0,
- images: Annotated[int, typer.Option("--images", help="input images at 1024px")] = 0,
-) -> None:
- """What one call would cost before you send it."""
- from codeverse3d.cost import estimate_call
-
- est = estimate_call(model, input_tokens=input_tokens, output_tokens=output_tokens,
- cached_tokens=cached, n_images=images)
- console.print(est.line())
diff --git a/harness/codeverse3d/cli/inspect_cmd.py b/harness/codeverse3d/cli/inspect_cmd.py
index 5569ea38..0173c1bd 100644
--- a/harness/codeverse3d/cli/inspect_cmd.py
+++ b/harness/codeverse3d/cli/inspect_cmd.py
@@ -1,5 +1,4 @@
-"""``3dcodeverse render`` / ``3dcodeverse judge`` — act on one existing run: re-render its working
-tree, or re-judge a round into ``artifacts/judge/rNN_cli.json``."""
+"""``3dcodeverse judge`` — re-judge a round of one existing run into ``artifacts/judge/rNN_cli.json``."""
from __future__ import annotations
@@ -11,75 +10,6 @@ import typer
from codeverse3d.cli import _common as C
from codeverse3d.cli._common import RunsDirOpt, console, kv_table
from codeverse3d.config import get_settings
-from codeverse3d.contracts.artifacts import RENDER_MODES
-from codeverse3d.contracts.common import Track
-from codeverse3d.contracts.plan import ScenePlan
-from codeverse3d.contracts.spec import Spec
-
-
-# --------------------------------------------------------------------------- render / judge
-def render(
- slug: str,
- mode: Annotated[
- str, typer.Option("--mode", help="shaded | wire | normals | clay | silhouette")
- ] = "shaded",
- out: Annotated[Path | None, typer.Option("--out")] = None,
- width: Annotated[
- int | None,
- typer.Option("--width", min=1, help="default: render.width (scene: render.scene_width)"),
- ] = None,
- height: Annotated[
- int | None,
- typer.Option("--height", min=1, help="default: render.height (scene: render.scene_height)"),
- ] = None,
- runs_dir: RunsDirOpt = None,
-) -> None:
- """Render the current artifact (object.glb or the scene) with the canonical rig."""
- ws = C.open_workspace(slug, runs_dir)
- spec = C.load_spec(ws)
- if mode not in RENDER_MODES:
- raise C.CliError(f"--mode must be one of {' | '.join(RENDER_MODES)}, not {mode!r}", code=2)
- if mode != "shaded" and spec.track in (Track.SCENE, Track.GRAPHICS):
- raise C.CliError(f"--mode {mode} is for object runs; a {spec.track.value} run renders shaded only", code=2)
- if spec.track is Track.GRAPHICS and (width or height):
- raise C.CliError("--width/--height do not apply to a graphics run: its frames are rendered at the runtime's size",
- code=2)
- idx = max(ws.rendered_rounds(), default=0)
- out_dir = out or ws.renders_dir(idx) / ("cli" if mode == "shaded" else f"cli_{mode}")
- # a graphics render rebuilds the run: one writer per run dir
- with C.mutating(ws, what=f"3dcodeverse render {ws.root.name}", action="render"):
- if spec.track is Track.GRAPHICS:
- _render_graphics(ws, spec, out_dir)
- return
- r = get_settings().render
- if spec.track is Track.SCENE:
- from codeverse3d.languages import get_runtime
- from codeverse3d.spatial.tool_common import load_plan
- from codeverse3d.tracks.scene import SCENE_TIMES
-
- plan = load_plan(ws.plan_path) if ws.plan_path.is_file() else None
- rs = get_runtime(spec.language).render_scene(
- ws, out_dir, cameras=list(plan.cameras) if isinstance(plan, ScenePlan) else None,
- times=SCENE_TIMES, width=width or r.scene_width, height=height or r.scene_height)
- else:
- glb = ws.artifacts / "object.glb"
- if not glb.is_file():
- raise C.CliError(f"no artifact to render: {glb} (run a build first)")
- from codeverse3d.spatial.render import render_glb
-
- rs = render_glb(glb, out_dir, mode=mode, width=width or r.width, height=height or r.height)
- console.print(
- kv_table(
- "renders",
- {
- "views": len(rs.views),
- "sheet": rs.contact_sheet,
- "dir": out_dir,
- "renderer": rs.renderer,
- "ms": rs.duration_ms,
- },
- )
- )
def judge(
@@ -89,7 +19,7 @@ def judge(
str | None, typer.Option("--rubric", help="default: the rubric the round was judged with")
] = None,
model: Annotated[str | None, typer.Option("--model", help="judge chat model id")] = None,
- n: Annotated[int, typer.Option("--n", min=1)] = 1,
+ n: Annotated[int | None, typer.Option("--n", min=1, help="samples (default: Settings.judge.samples)")] = None,
thinking: Annotated[
str | None, typer.Option("--thinking", help="off | low | medium | high (default: Settings.judge.thinking, "
"C3D_JUDGE__THINKING; gemini-4-argon thinks only from medium)"),
@@ -120,11 +50,11 @@ def judge(
raise C.CliError(f"round {idx}: {len(missing)} of its {len(inp.renders.views)} judged renders are not on disk "
f"(e.g. {missing[0]}): nothing to re-judge it from", code=2)
try:
- judge_obj = J.make_judge(rec.spec, rubric_name, model or rec.spec.backends.judge, n,
+ judge_obj = J.make_judge(rec.spec, rubric_name, model or rec.spec.backends.judge,
+ n or get_settings().judge.samples,
**({"thinking": thinking} if thinking else {}))
except ValueError as e:
raise C.CliError(str(e), code=2) from e
- n_images = J.count_prompt_images(inp, rubric_name, judge_obj)
# writes into the run: one writer per run dir; judged under the run's variant
with C.mutating(ws, what=f"3dcodeverse judge {ws.root.name}", action="judge"), C.replay_variant(rec):
try:
@@ -149,7 +79,6 @@ def judge(
"passed": verdict.passed,
"std": verdict.score_std,
"thinking": getattr(judge_obj, "thinking", "-"),
- "prompt images": n_images if n_images is not None else "?",
"stored score": f"{rnd.judgment.overall:.3f}" if rnd.judgment else "-",
"summary": verdict.summary,
"cost": f"${verdict.usage.cost_usd:.4f}",
@@ -158,36 +87,3 @@ def judge(
)
for it in verdict.improvement_plan:
console.print(f" [{it.priority}] {it.target}: {it.instruction}")
-
-
-def _render_graphics(ws, spec: Spec, out_dir: Path) -> None:
- import shutil
-
- from codeverse3d.languages import get_runtime
-
- br = get_runtime(spec.language).build(ws)
- if not br.ok:
- raise C.CliError(f"graphics build failed: {br.error_type}: {br.error_message}")
- out_dir.mkdir(parents=True, exist_ok=True)
- frames_dir = Path(br.extra_paths.get("frames") or (ws.artifacts / "frames"))
- n = 0
- for p in sorted(frames_dir.glob("*.png")) if frames_dir.is_dir() else []:
- shutil.copy2(p, out_dir / p.name)
- n += 1
- sheet = br.extra_paths.get("sheet") or ""
- if sheet and Path(sheet).is_file():
- shutil.copy2(sheet, out_dir / "sheet.png")
- sheet = str(out_dir / "sheet.png")
- renderer = br.census.get("renderer", "moderngl") if isinstance(br.census, dict) else "moderngl"
- console.print(
- kv_table(
- "renders",
- {
- "views": n,
- "sheet": sheet or "-",
- "dir": out_dir,
- "renderer": renderer,
- "ms": br.duration_ms,
- },
- )
- )
diff --git a/harness/codeverse3d/cli/main.py b/harness/codeverse3d/cli/main.py
index 11cfaf21..0682b62f 100644
--- a/harness/codeverse3d/cli/main.py
+++ b/harness/codeverse3d/cli/main.py
@@ -417,26 +417,25 @@ def _run_track(spec: Spec, ws, *, resume: bool, candidates: int | None = None, f
) from e
if pick:
with run_ledger(ws.root, run=ws.root.name):
- _pick_and_package(ws, by="score")
+ _pick_and_package(ws)
print_record_summary(record, ws.root)
if record.status.value == "failed":
raise typer.Exit(code=1)
-def _pick_and_package(ws, *, by: str, round_index: int | None = None,
- judge_model: str | None = None) -> int | None:
+def _pick_and_package(ws, *, round_index: int | None = None) -> int | None:
"""Choose the round (or take ``round_index``) and package it."""
from codeverse3d.addons import select
- idx = round_index if round_index is not None else select.pick(ws.root, by=by, pairwise_model=judge_model)
+ idx = round_index if round_index is not None else select.pick(ws.root)
if idx is None:
warn("no round was judged, so none was picked: name one with `3dcodeverse pick <slug> --round N`")
return None
try:
- select.package(ws.root, idx, method="round" if round_index is not None else by)
+ select.package(ws.root, idx, method="round" if round_index is not None else "score")
except ValueError as e:
raise C.CliError(str(e), code=2) from e
- ok(f"picked round {idx} ({'named' if round_index is not None else f'by {by}'}) → {ws.deliverable}")
+ ok(f"picked round {idx} ({'named' if round_index is not None else 'by score'}) → {ws.deliverable}")
return idx
@@ -543,10 +542,7 @@ def resume(
@app.command()
def pick(
slug: str,
- by: Annotated[str, typer.Option("--by", help="score | pairwise (the pairwise judge decides "
- "between the top two when they are within judge noise)")] = "score",
round_index: Annotated[int | None, typer.Option("--round", min=0, help="hand over this round instead")] = None,
- judge: Annotated[str | None, typer.Option("--judge", help="pairwise judge model (default: the run's judge)")] = None,
runs_dir: RunsDirOpt = None,
) -> None:
"""Choose the round of a finished run to hand over and package it: deliverable/ + selection.json."""
@@ -554,16 +550,12 @@ def pick(
from codeverse3d.cost.instrument import run_ledger
from codeverse3d.record.record import RecordError
- if by not in ("score", "pairwise"):
- raise C.CliError(f"--by must be score or pairwise, not {by!r}", code=2)
- if judge and (by != "pairwise" or round_index is not None):
- raise C.CliError("--judge is the pairwise judge: it goes with --by pairwise (and no --round)", code=2)
ws = C.open_workspace(slug, runs_dir)
# writes deliverable/ + selection.json: one writer per run dir
with (C.mutating(ws, what=f"3dcodeverse pick {ws.root.name}", action="pick"),
run_ledger(ws.root, run=ws.root.name, create=False)):
try:
- idx = _pick_and_package(ws, by=by, round_index=round_index, judge_model=judge)
+ idx = _pick_and_package(ws, round_index=round_index)
rows = select.round_rows(ws.root)
except RecordError as e:
raise C.CliError(str(e), code=2) from e
@@ -572,10 +564,9 @@ def pick(
console.print(C.rounds_table(rows, idx))
-# --------------------------------------------------------------------------- render / judge
-from codeverse3d.cli.inspect_cmd import judge, render # noqa: E402
+# --------------------------------------------------------------------------- judge
+from codeverse3d.cli.inspect_cmd import judge # noqa: E402
-app.command()(render)
app.command()(judge)
diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.py
index e4079527..9bff3b48 100644
--- a/harness/codeverse3d/config.py
+++ b/harness/codeverse3d/config.py
@@ -174,7 +174,7 @@ class Judge(BaseModel):
"Slice render is local CPU; no profile touches this dial (the channel measured ≤ $0).")
thinking: Annotated[Literal["off", "low", "medium", "high"], BeforeValidator(lambda v: str(v).strip().lower())] = Field(
default="medium",
- description="VLM and pairwise judges' thinking level (C3D_JUDGE__THINKING; models/gemini.THINKING_BUDGET). "
+ description="VLM judge's thinking level (C3D_JUDGE__THINKING; models/gemini.THINKING_BUDGET). "
"The default gemini-4-argon thinks only from 'medium' "
"(4096) — measured 2026-10-14 on 19 scene/object rounds: argon@medium within-sd .012 vs .029 at low, "
"same cost, same mean (D105). `3dcodeverse judge --thinking` replays with another level.")
@@ -288,7 +288,6 @@ class Settings(BaseSettings):
"(object tracks)")
plan_restart: Flag = Field(default=True, description="re-sample a degenerate plan from the original "
"prompt instead of editing it in context (docs/COST.md §30)")
- reference_diff: Flag = Field(default=True, description="the judge's reference-image mismatch pass")
zone_layouts: Flag = Field(default=True, description="scene track: the L2 zone-layout planner calls")
axis_repair: Flag = Field(default=True, description="articulated track: rewrite a joint axis the "
"measured motion proves wrong, before the sweep renders")
diff --git a/harness/codeverse3d/cost/__init__.py b/harness/codeverse3d/cost/__init__.py
index e11f280b..e7fdb05f 100644
--- a/harness/codeverse3d/cost/__init__.py
+++ b/harness/codeverse3d/cost/__init__.py
@@ -1,5 +1,5 @@
-"""Cost accounting: a typed ledger of every model call, a price-provenance layer on
-top of ``models/pricing.py``, and a pre-send cost guard. (The audit of FINISHED runs and
+"""Cost accounting: a typed ledger of every model call, and a price-provenance layer on
+top of ``models/pricing.py``. (The audit of FINISHED runs and
its report are ``codeverse3d.addons.costreport``.)
This package re-exports only the names other packages actually import through it.
@@ -13,9 +13,8 @@ Nothing here imports tracks/ or orchestrator/, so any layer may use it.
from __future__ import annotations
from codeverse3d.cost.context import call_context
-from codeverse3d.cost.guard import estimate_call
from codeverse3d.cost.instrument import run_ledger
from codeverse3d.cost.ledger import load_ledger, record_call
from codeverse3d.cost.types import Role, Stage
-__all__ = ["Role", "Stage", "call_context", "estimate_call", "load_ledger", "record_call", "run_ledger"]
+__all__ = ["Role", "Stage", "call_context", "load_ledger", "record_call", "run_ledger"]
diff --git a/harness/codeverse3d/cost/context.py b/harness/codeverse3d/cost/context.py
index 1915a1be..576edbe6 100644
--- a/harness/codeverse3d/cost/context.py
+++ b/harness/codeverse3d/cost/context.py
@@ -113,7 +113,6 @@ _LABEL_HINTS: tuple[tuple[str, Stage, Role], ...] = (
("planner", Stage.PLAN, Role.PLANNER),
("plan", Stage.PLAN, Role.PLANNER),
("judge", Stage.JUDGE, Role.JUDGE),
- ("pairwise", Stage.PAIRWISE, Role.JUDGE),
("caption", Stage.CAPTION, Role.CAPTIONER),
("calibrate", Stage.JUDGE, Role.JUDGE),
)
@@ -151,7 +150,7 @@ def _round_from_label(label: str) -> int | None:
#: Stages whose label names a job of its own: they outrank the ambient session context.
SELF_DESCRIBING: frozenset[Stage] = frozenset(
- {Stage.PLAN, Stage.JUDGE, Stage.PAIRWISE, Stage.CAPTION})
+ {Stage.PLAN, Stage.JUDGE, Stage.CAPTION})
def attribute(explicit: CallContext | None = None, *, label: str = "") -> CallContext:
diff --git a/harness/codeverse3d/cost/guard.py b/harness/codeverse3d/cost/guard.py
index ec47f586..5bab3180 100644
--- a/harness/codeverse3d/cost/guard.py
+++ b/harness/codeverse3d/cost/guard.py
@@ -1,71 +1,14 @@
-"""Estimate what a call will cost before sending it (token counts are ~4 chars/token, +-15%)."""
+"""Prompt-size estimate (~4 chars/token, +-15%) for the skills' token accounting."""
from __future__ import annotations
-from collections.abc import Iterable, Sequence
-from dataclasses import dataclass
-
-from codeverse3d.contracts.common import Usage
-from codeverse3d.cost.types import normalise_ids
-from codeverse3d.models.pricing import estimate_cost, price_provenance
+from collections.abc import Iterable
CHARS_PER_TOKEN = 4.0
-#: tokens billed for one image part, by longest edge
-IMAGE_TOKENS: dict[int, int] = {256: 258, 512: 258, 768: 1032, 1024: 1290, 2048: 5160}
-
def text_tokens(text: str | Iterable[str]) -> int:
"""Estimated prompt tokens for one string or a bag of blocks."""
if isinstance(text, str):
return int(len(text) / CHARS_PER_TOKEN + 0.5)
return sum(text_tokens(t) for t in text)
-
-
-def image_tokens(n: int = 1, *, px: int = 1024) -> int:
- """Estimated input tokens for ``n`` images whose longest edge is ``px``."""
- step = min(IMAGE_TOKENS, key=lambda k: abs(k - px))
- return n * IMAGE_TOKENS[step]
-
-
-@dataclass(frozen=True)
-class CostEstimate:
-
- model_id: str
- provider: str
- model: str
- input_tokens: int
- cached_tokens: int
- output_tokens: int
- usd: float = 0.0
- price_source: str = "unknown"
- approximate: bool = True
-
- def line(self) -> str:
- flag = " (approx)" if self.approximate else ""
- return (f"{self.model_id}: ~{self.input_tokens:,} in ({self.cached_tokens:,} cached) "
- f"+ {self.output_tokens:,} out ⇒ ${self.usd:.4f}{flag}")
-
-
-def estimate_call(
- model_id: str,
- *,
- input_tokens: int = 0,
- output_tokens: int = 0,
- cached_tokens: int = 0,
- prompt: str | Sequence[str] = "",
- n_images: int = 0,
-) -> CostEstimate:
- """Price a call that has not happened yet, from token counts or ``prompt`` text plus ``n_images``."""
- kind, provider, model = normalise_ids("", model_id)
- if not provider:
- kind, provider, model = normalise_ids(model_id, model_id)
- tokens_in = (input_tokens or text_tokens(prompt)) + image_tokens(n_images)
- cached = max(0, min(cached_tokens, tokens_in))
- usd = estimate_cost(provider, model, Usage(input_tokens=tokens_in, cached_tokens=cached, output_tokens=output_tokens))
- row = price_provenance(provider, model)
- return CostEstimate(model_id=model_id, provider=provider, model=model, input_tokens=tokens_in,
- cached_tokens=cached, output_tokens=output_tokens,
- usd=usd, price_source=row.match if row.price else "unknown",
- approximate=row.approximate)
-
diff --git a/harness/codeverse3d/cost/types.py b/harness/codeverse3d/cost/types.py
index 939f5690..7f33c37d 100644
--- a/harness/codeverse3d/cost/types.py
+++ b/harness/codeverse3d/cost/types.py
@@ -24,7 +24,6 @@ class Stage(StrEnum):
GATES = "gates"
RENDER = "render"
JUDGE = "judge"
- PAIRWISE = "pairwise"
CAPTION = "caption"
OTHER = "other"
@@ -88,7 +87,7 @@ def stage_for_label(label: str) -> Stage:
def role_for_stage(stage: Stage) -> Role:
if stage is Stage.PLAN:
return Role.PLANNER
- if stage in (Stage.JUDGE, Stage.PAIRWISE):
+ if stage is Stage.JUDGE:
return Role.JUDGE
if stage is Stage.CAPTION:
return Role.CAPTIONER
diff --git a/harness/codeverse3d/judges/__init__.py b/harness/codeverse3d/judges/__init__.py
index 927534d7..69e86d0f 100644
--- a/harness/codeverse3d/judges/__init__.py
+++ b/harness/codeverse3d/judges/__init__.py
@@ -1 +1 @@
-"""Judges: VLM rubric judge, pairwise judge, reference-fidelity judge, metrics."""
+"""Judges: VLM rubric judge, reference-fidelity judge, metrics."""
diff --git a/harness/codeverse3d/judges/base.py b/harness/codeverse3d/judges/base.py
index 17aa6973..3a882384 100644
--- a/harness/codeverse3d/judges/base.py
+++ b/harness/codeverse3d/judges/base.py
@@ -42,7 +42,6 @@ class JudgeInput(BaseModel):
gates: list[GateReport] = Field(default_factory=list)
acceptance: list[AcceptanceItem] = Field(default_factory=list)
plan_summary: str = Field(default="", description="short plan digest (parts/zones/joints) for grounding")
- part_names: list[str] = Field(default_factory=list, description="an object plan's part names (the reference diff)")
round_index: int = 0
previous: Judgment | None = Field(default=None, description="last verdict (for delta framing)")
extra_context: str = ""
@@ -84,7 +83,6 @@ def round_input(spec: Spec, plan: Plan | None, rnd: RoundRecord, *, renders: Ren
return JudgeInput(
spec=spec, renders=renders, measurement=rnd.measurement, gates=list(gates),
acceptance=list(getattr(plan, "acceptance", None) or []), plan_summary=plan_summary(plan, spec.language),
- part_names=[p.name for p in plan.parts] if isinstance(plan, StaticPlan) else [],
round_index=rnd.index, previous=previous, extra_context=extra_context, geometry_views=geometry_views,
glb_path=glb_path if spec.track.value in SLICE_TRACKS else None,
)
diff --git a/harness/codeverse3d/judges/pairwise.py b/harness/codeverse3d/judges/pairwise.py
deleted file mode 100644
index 0445dd1d..00000000
--- a/harness/codeverse3d/judges/pairwise.py
+++ /dev/null
@@ -1,204 +0,0 @@
-"""``PairwiseJudge``: which of two candidates better satisfies the spec?
-
-The comparison runs twice with A/B swapped; a winner needs both orderings to agree, else ``tie``.
-Each call sees one 2×2 montage per candidate.
-"""
-
-from __future__ import annotations
-
-import logging
-import re
-import statistics
-from pathlib import Path
-from typing import Literal
-
-from pydantic import BaseModel, Field
-
-from codeverse3d.config import get_settings
-from codeverse3d.contracts.artifacts import RenderSet
-from codeverse3d.contracts.chat import ChatMessage, ChatRequest, ImagePart, TextPart
-from codeverse3d.contracts.common import Track, Usage
-from codeverse3d.contracts.spec import Spec
-from codeverse3d.judges.base import judged_subset
-from codeverse3d.judges.prompt_builder import (
- MAX_PX,
- MONTAGE_TILE_PX,
- brief_section,
- image_part,
- montage_label,
- plan_montages,
- prepare_image,
- render_montage,
-)
-from codeverse3d.judges.rubrics import Rubric, load_rubric
-from codeverse3d.models import get_chat_model
-from codeverse3d.models.base import ChatModel, ModelError
-from codeverse3d.models.schema_utils import JsonParseError, parse_json_lenient
-from codeverse3d.proc import fan_out
-
-log = logging.getLogger(__name__)
-
-Winner = Literal["a", "b", "tie"]
-TEMPERATURE = 0.2
-
-
-class CriterionWinner(BaseModel):
- criterion: str
- winner: Literal["A", "B", "tie"]
-
-
-class PairwiseReply(BaseModel):
- """Wire schema for one ordering."""
-
- winner: Literal["A", "B", "tie"] = Field(description="which candidate better satisfies the brief overall")
- confidence: float = Field(ge=0.0, le=1.0, description="0.5 = coin flip, 1.0 = certain")
- reasons: list[str] = Field(description="2-5 short, evidence-based reasons citing candidate and view")
- criteria_won: list[CriterionWinner] = Field(default_factory=list, description="one entry per rubric criterion")
-
-
-class PairwiseResult(BaseModel):
- winner: Winner
- confidence: float = Field(ge=0.0, le=1.0)
- reasons: list[str] = Field(default_factory=list)
- orderings: list[dict] = Field(default_factory=list, description="per-ordering raw verdicts (mapped to a/b)")
- usage: Usage = Field(default_factory=Usage)
- error: str = ""
-
-
-_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 over the CRITERIA 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}]."""
-
-
-class PairwiseJudge:
- name = "pairwise"
-
- def __init__(self, model_id: str | None = None, *, chat_model: ChatModel | None = None,
- cache_dir: Path | None = None):
- self.model_id = model_id or get_settings().default_judge
- self.thinking = get_settings().judge.thinking
- self._model = chat_model
- self.cache_dir = cache_dir
-
- @property
- def model(self) -> ChatModel:
- if self._model is None:
- self._model = get_chat_model(self.model_id)
- return self._model
-
- # ------------------------------------------------------------------ API
- def compare(
- self, spec: Spec, renders_a: RenderSet, renders_b: RenderSet, *,
- rubric: str | Rubric = "static_object"
- ) -> PairwiseResult:
- rub = rubric if isinstance(rubric, Rubric) else load_rubric(rubric)
- usage = Usage()
- verdicts: list[tuple[Winner, float, list[str]]] = []
- orderings: list[dict] = []
- errors: list[str] = []
- self.model # noqa: B018
- results = fan_out(
- (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:
- if isinstance(res, Exception):
- raise res
- u, verdict, ordering, error = res
- usage = usage + u
- if error:
- errors.append(error)
- continue
- assert verdict is not None and ordering is not None
- verdicts.append(verdict)
- orderings.append(ordering)
- if not verdicts:
- return PairwiseResult(winner="tie", confidence=0.0, usage=usage, error=" || ".join(errors))
- return _combine(verdicts, orderings, usage, errors)
-
- def _ordering(
- self, spec: Spec, rub: Rubric, renders_a: RenderSet, renders_b: RenderSet, swapped: bool
- ) -> tuple[Usage, tuple[Winner, float, list[str]] | None, dict | None, str]:
- first, second = (renders_b, renders_a) if swapped else (renders_a, renders_b)
- 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:
- return getattr(e, "usage", None) or Usage(), None, None, f"ModelError: {e}"
- try:
- payload = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text)
- reply = PairwiseReply.model_validate(payload)
- except JsonParseError as e:
- return resp.usage, None, None, f"parse: no JSON object in reply: {e}"
- except ValueError as e:
- return resp.usage, None, None, f"parse: {e}"
- winner = _map_winner(reply.winner, swapped)
- reasons = [_unswap_text(r, swapped) for r in reply.reasons]
- ordering = {"swapped": swapped, "winner": winner, "confidence": reply.confidence,
- "reasons": reasons,
- "criteria_won": {c.criterion: _map_winner(c.winner, swapped) for c in reply.criteria_won}}
- return resp.usage, (winner, reply.confidence, reasons), ordering, ""
-
- def _request(
- self, spec: Spec, rub: Rubric, first: RenderSet, second: RenderSet, *, label: str = "pairwise"
- ) -> ChatRequest:
- crit = "\n".join(f"- {c.id}: {c.description.strip()}" for c in rub.visual_criteria())
- text = (
- brief_section(spec)
- + "\n\nCRITERIA (from rubric " + rub.name + "):\n" + crit
- + "\n\nImages follow: CANDIDATE A first, then CANDIDATE B. Each image is labelled."
- )
- parts: list[TextPart | ImagePart] = [TextPart(text=text)]
- for tag, rs in (("A", first), ("B", second)):
- for lbl, ip in self._side_images(tag, rs, scene=spec.track is Track.SCENE):
- parts.append(TextPart(text=lbl))
- parts.append(ip)
- parts.append(TextPart(text="Compare A and B and return the JSON object."))
- return ChatRequest(
- messages=[ChatMessage(role="user", parts=parts)], system=_SYSTEM,
- response_schema=PairwiseReply.model_json_schema(), temperature=TEMPERATURE,
- thinking=self.thinking, max_wait_s=900.0, label=label,
- )
-
- def _side_images(self, tag: str, rs: RenderSet, *, scene: bool) -> list[tuple[str, ImagePart]]:
- """One 2×2 montage of the candidate's most informative views, ranked for the track."""
- montages = plan_montages(judged_subset(rs), scene=scene, max_montages=2, detail_crops=0)
- out: list[tuple[str, ImagePart]] = []
- for i, m in enumerate(montages, 1):
- lbl = f"CANDIDATE {tag} — " + montage_label(m, i, len(montages))
- strip = f"CANDIDATE {tag} — {m.title.split(' (')[0]}"
- png = render_montage(m, cache_dir=self.cache_dir, tile_px=MONTAGE_TILE_PX)
- out.append((lbl, image_part(prepare_image(png, label=strip, max_px=MAX_PX, cache_dir=self.cache_dir), lbl)))
- return out
-
-
-_CAND = re.compile(r"\b([Cc]andidate)\s+([AB])\b")
-
-
-def _unswap_text(text: str, swapped: bool) -> str:
- """Rewrite 'Candidate A/B' mentions from a swapped ordering back to the caller's a/b labels."""
- if not swapped:
- return text
- return _CAND.sub(lambda m: f"{m.group(1)} {'B' if m.group(2) == 'A' else 'A'}", text)
-
-
-def _map_winner(w: str, swapped: bool) -> Winner:
- if w == "tie":
- return "tie"
- if not swapped:
- return "a" if w == "A" else "b"
- return "b" if w == "A" else "a"
-
-
-def _combine(
- verdicts: list[tuple[Winner, float, list[str]]], orderings: list[dict], usage: Usage, errors: list[str]
-) -> PairwiseResult:
- winners = {v[0] for v in verdicts}
- reasons = [r for v in verdicts for r in v[2]][:8]
- conf = statistics.fmean(v[1] for v in verdicts)
- if len(verdicts) == 1:
- return PairwiseResult(winner=verdicts[0][0], confidence=round(conf * 0.5, 3), reasons=reasons,
- orderings=orderings, usage=usage, error=" || ".join(errors))
- if len(winners) == 1:
- return PairwiseResult(winner=verdicts[0][0], confidence=round(conf, 3), reasons=reasons, orderings=orderings, usage=usage)
- return PairwiseResult(winner="tie", confidence=round(min(0.4, 1.0 - conf), 3), reasons=reasons, orderings=orderings,
- usage=usage, error="orderings disagree")
diff --git a/harness/codeverse3d/judges/vlm_judge.py b/harness/codeverse3d/judges/vlm_judge.py
index 757299be..80a7e24b 100644
--- a/harness/codeverse3d/judges/vlm_judge.py
+++ b/harness/codeverse3d/judges/vlm_judge.py
@@ -17,10 +17,9 @@ from pathlib import Path
from typing import Any, Literal
from codeverse3d.config import get_settings
-from codeverse3d.contracts.artifacts import Judgment, RenderView
+from codeverse3d.contracts.artifacts import Judgment
from codeverse3d.contracts.chat import ChatRequest, ChatResponse
from codeverse3d.contracts.common import TRACK_INFO, Track, Usage
-from codeverse3d.conventions import views_by_preference
from codeverse3d.judges.base import SLICE_TRACKS, JudgeInput
from codeverse3d.judges.prompt_builder import (
_key,
@@ -43,7 +42,7 @@ from codeverse3d.judges.rubrics import (
from codeverse3d.models import get_chat_model
from codeverse3d.models.base import ChatModel, ModelError
from codeverse3d.proc import fan_out, unique_tmp
-from codeverse3d.reference import compare, conflict_note, dimension_conflict
+from codeverse3d.reference import conflict_note, dimension_conflict
from codeverse3d.spatial.silhouette import (
CompareFn,
ReferenceMatch,
@@ -292,18 +291,10 @@ IOU_LOW, IOU_HIGH = 0.25, 0.85
#: score the measured criterion gets when the measurement cannot be trusted
NEUTRAL_SCORE = 0.5
-#: views handed to the mismatch pass (front-ish first, then a 3/4 and a side)
-DIFF_VIEW_NAMES: tuple[str, ...] = ("front", "front_right_high", "front_left_high", "right", "left")
-
-
def iou_to_score(iou: float) -> float:
return max(0.0, min(1.0, (float(iou) - IOU_LOW) / (IOU_HIGH - IOU_LOW)))
-def _diff_enabled(flag: bool) -> bool:
- return flag and get_settings().reference_diff
-
-
class ReferenceJudge(VlmJudge):
name = "reference"
@@ -316,12 +307,10 @@ class ReferenceJudge(VlmJudge):
*,
rubric: str | Rubric = "reference",
silhouette_fn: CompareFn | None = None,
- diff: bool = True,
**kwargs: Any,
):
super().__init__(rubric, model_id, n_samples, temperature, **kwargs)
self.silhouette_fn = silhouette_fn or compare_silhouette
- self.diff = diff
def context(self, inp: JudgeInput) -> JudgeContext:
refs = [r for r in inp.spec.references if Path(r.path).is_file()]
@@ -336,7 +325,7 @@ class ReferenceJudge(VlmJudge):
blocks.append(note)
measured_ids = [c.id for c in self.rubric.measured_criteria()]
measured_scores: dict[str, float] = {}
- match = measure_reference(inp.renders.views, inp.spec, compare=self.silhouette_fn) if refs else None
+ match = measure_reference(inp.renders.views, inp.spec, compare=self.silhouette_fn, conflict=conflict) if refs else None
if measured_ids:
if match is None:
raise ReferenceJudgeError(f"cannot score measured criteria {measured_ids}: "
@@ -347,11 +336,7 @@ class ReferenceJudge(VlmJudge):
blocks.append(
f"MEASURED SILHOUETTE (harness): {match.view} render vs reference {Path(match.reference).name}: "
f"IoU {match.iou:.3f} → silhouette_match score {score:.2f}{why}. extra: {extra}")
- diff = self.reference_diff(inp, refs, match) if refs else None
- if diff is not None and diff.as_text():
- blocks.append(diff.as_text())
- return JudgeContext(measured_scores=measured_scores, extra_text="\n\n".join(blocks), extra_images=images,
- usage=diff.usage if diff is not None else Usage())
+ return JudgeContext(measured_scores=measured_scores, extra_text="\n\n".join(blocks), extra_images=images)
def dimension_conflict(self, inp: JudgeInput, refs: list[Any]) -> dict[str, Any]:
"""Does the target reference's own outline contradict the brief's dimensions? If so the brief wins."""
@@ -372,30 +357,6 @@ class ReferenceJudge(VlmJudge):
return NEUTRAL_SCORE, " (NEUTRAL: the background mask was unreliable)"
return iou_to_score(match.iou), ""
- def reference_diff(self, inp: JudgeInput, refs: list[Any], match: ReferenceMatch | None) -> Any | None:
- """One extra vision call naming concrete mismatches; ``None`` when disabled; never raises."""
- if not _diff_enabled(self.diff):
- 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 = None if match is None else {"iou": match.iou, "aspect_ratio_err": match.aspect_ratio_err, "reliable": match.reliable,
- "view": match.view, "reference": Path(match.reference).name}
- try:
- return compare(inp.spec, targets, renders, model=self.model,
- part_names=inp.part_names, measured=measured, thinking=self.thinking) # type: ignore[arg-type]
- except Exception as e: # noqa: BLE001
- log.warning("reference diff pass failed: %s", e)
- return None
-
- def diff_views(self, views: list[RenderView]) -> list[str]:
- picked = [v.path for v in views_by_preference(views, DIFF_VIEW_NAMES)]
- for v in views:
- if len(picked) >= 3:
- break
- if v.path not in picked:
- picked.append(v.path)
- return picked[:3]
-
LIKENESS_NOTE = (
"REAL-WORLD REFERENCE PHOTOS are attached (labelled REAL-WORLD REFERENCE n/N). They are not a "
diff --git a/harness/codeverse3d/reference.py b/harness/codeverse3d/reference.py
index edcbe071..a9d5b8f9 100644
--- a/harness/codeverse3d/reference.py
+++ b/harness/codeverse3d/reference.py
@@ -1,127 +1,12 @@
-"""Reference comparison: judge a render against the user's own ``--image`` pictures.
-
-Measures and names the distance between a ``spec.references`` image and a render: the brief's
-dimension band vs the picture's outline (:func:`dimension_conflict`; the BRIEF wins on a conflict)
-and one vision call listing concrete mismatches (:func:`compare`).
-"""
+"""Reference comparison: the brief's dimension band vs the outline of the user's own ``--image``
+picture (:func:`dimension_conflict`; the BRIEF wins on a conflict)."""
from __future__ import annotations
-import logging
-from collections.abc import Sequence
from pathlib import Path
-from typing import Any, Literal
-
-from pydantic import BaseModel, Field
+from typing import Any
-from codeverse3d.contracts.chat import ImagePart
-from codeverse3d.contracts.common import Usage
from codeverse3d.contracts.spec import Spec
-from codeverse3d.models.schema_utils import ask_structured
-
-log = logging.getLogger(__name__)
-
-
-# ===================================================================== types
-MismatchKind = Literal[
- "missing_feature", "extra_feature", "wrong_part_count", "wrong_proportion",
- "wrong_shape", "wrong_material", "wrong_placement",
-]
-
-_SEVERITY_ORDER = {"critical": 0, "major": 1, "minor": 2}
-
-
-class Mismatch(BaseModel):
- kind: MismatchKind
- target: str = Field(default="overall", description="part name from the plan, or 'overall'")
- detail: str = Field(description="what the reference shows vs what the render shows")
- severity: Literal["critical", "major", "minor"] = "major"
-
- def as_line(self) -> str:
- return f"[{self.severity}] {self.target} — {self.kind.replace('_', ' ')}: {self.detail}"
-
-
-class ReferenceDiff(BaseModel):
- """Render-vs-reference comparison: measured IoU + named mismatches."""
-
- iou: float | None = None
- aspect_ratio_err: float | None = None
- reliable: bool = True
- view: str = ""
- reference: str = ""
- mismatches: list[Mismatch] = Field(default_factory=list)
- matches: list[str] = Field(default_factory=list, description="what the render already gets right")
- model_id: str = ""
- usage: Usage = Field(default_factory=Usage)
- error: str = ""
-
- def top(self, n: int = 3) -> list[Mismatch]:
- return sorted(self.mismatches, key=lambda m: _SEVERITY_ORDER.get(m.severity, 3))[:n]
-
- def as_text(self, n: int = 6) -> str:
- if self.error or not (self.mismatches or self.matches):
- return ""
- lines = ["REFERENCE DIFF (harness vision pass, target = the REFERENCE image):"]
- if self.iou is not None:
- lines.append(f"- measured silhouette IoU {self.iou:.3f}"
- + (f", aspect error {self.aspect_ratio_err:.0%}" if self.aspect_ratio_err is not None else "")
- + ("" if self.reliable else " (mask unreliable — judge visually)"))
- for m in self.top(n):
- lines.append(f"- {m.as_line()}")
- if self.matches:
- lines.append("- already matching: " + "; ".join(self.matches[:4]))
- return "\n".join(lines)
-
-
-# ===================================================================== spec_text
-def brief_text(spec: Spec) -> str:
- lines = [spec.prompt.strip()]
- c = spec.constraints
- if c.style:
- lines.append(f"Style: {c.style}")
- if c.dimensions_m:
- lines.append("Overall dimensions (metres): "
- + ", ".join(f"{k} {v:g}" for k, v in sorted(c.dimensions_m.items())))
- for m in c.must_have:
- lines.append(f"MUST HAVE: {m}")
- for m in c.must_not:
- lines.append(f"MUST NOT: {m}")
- return "\n".join(lines)
-
-
-# --------------------------------------------------------------------------- reference diff
-DIFF_SYSTEM = (
- "You compare a 3D render against a reference image and name concrete, fixable differences. "
- "You never comment on background, lighting, camera framing or image style — only on the object's "
- "shape, its parts, their counts, their proportions, their placement and their materials. "
- "Answer with JSON only."
-)
-
-DIFF_USER = """\
-The images labelled REFERENCE are the shape target. The images labelled RENDER are the current 3D model.
-
-BRIEF
------
-{brief}
-{measured}
-List the differences that make the RENDER read as less like the real object than the REFERENCE does.
-For each, give:
-- `kind`: missing_feature | extra_feature | wrong_part_count | wrong_proportion | wrong_shape |
- wrong_material | wrong_placement
-- `target`: the part name it concerns (use a name from this list when one fits: {parts}), else "overall"
-- `detail`: what the REFERENCE shows and what the RENDER shows instead — one sentence, concrete and
- checkable (name the count, the ratio or the shape, e.g. "reference has 8 flutes around the body,
- render has a smooth cylinder")
-- `severity`: critical (the object no longer reads as the right thing) | major | minor
-
-Rules:
-- At most 6 mismatches; order them so the most identity-destroying comes first.
-- Ignore anything the brief overrides: where the brief states a dimension, a count or a material, the BRIEF
- wins and the reference does not.
-- Do not report background, lighting, shadow, reflection, resolution or camera-angle differences.
-- `matches`: up to 4 short phrases naming what the render already gets right (so the builder does not undo it).
-"""
-
# ===================================================================== proportions
@@ -186,78 +71,3 @@ def conflict_note(info: dict[str, Any]) -> str:
f"or the object resting in a different orientation. The BRIEF's dimensions are correct; use the "
f"reference for the part inventory and the shape of each part, NOT for the overall proportions. "
f"The measured silhouette score is therefore neutral and must not be read as a proportion verdict.")
-
-# ===================================================================== mismatch
-
-MAX_MISMATCHES = 6
-
-
-class DiffAnswer(BaseModel):
- mismatches: list[Mismatch] = Field(default_factory=list)
- matches: list[str] = Field(default_factory=list)
-
-
-def compare(
- spec: Spec,
- reference_images: Sequence[Path | str],
- render_images: Sequence[Path | str],
- *,
- model: Any,
- part_names: Sequence[str] = (),
- measured: dict[str, Any] | None = None,
- temperature: float = 0.1,
- thinking: Literal["off", "low", "medium", "high"] = "low",
- max_reference: int = 2,
- max_renders: int = 3,
-) -> ReferenceDiff:
- """One vision call: REFERENCE images + RENDER images → named mismatches."""
- refs = [Path(p) for p in reference_images if Path(p).is_file()][:max_reference]
- rens = [Path(p) for p in render_images if Path(p).is_file()][:max_renders]
- diff = ReferenceDiff(model_id=getattr(model, "id", "") if model else "")
- if measured:
- diff.iou = _as_float(measured.get("iou"))
- diff.aspect_ratio_err = _as_float(measured.get("aspect_ratio_err"))
- diff.reliable = bool(measured.get("reliable", True))
- diff.view = str(measured.get("view", "") or measured.get("render", ""))
- diff.reference = str(measured.get("reference", ""))
- if not refs or not rens:
- diff.error = "nothing to compare (missing reference or render images)"
- return diff
- if model is None:
- diff.error = "no vision model for the reference diff"
- return diff
- text = DIFF_USER.format(
- brief=brief_text(spec),
- measured=_measured_block(diff),
- parts=", ".join(list(part_names)[:40]) or "(no part list)",
- )
- images = [ImagePart(path=str(p), label=f"REFERENCE {i + 1}") for i, p in enumerate(refs)]
- images += [ImagePart(path=str(p), label=f"RENDER {i + 1} ({p.stem})") for i, p in enumerate(rens)]
- ans, usage, err = ask_structured(model, DiffAnswer, system=DIFF_SYSTEM, text=text, images=images,
- temperature=temperature, thinking=thinking, label="reference_diff")
- diff.usage = usage
- if err:
- log.warning("reference diff %s", err)
- diff.error = f"diff {err}"
- return diff
- diff.mismatches = ans.mismatches[:MAX_MISMATCHES]
- diff.matches = [m.strip()[:120] for m in ans.matches if m.strip()][:4]
- return diff
-
-
-def _as_float(v: Any) -> float | None:
- try:
- return float(v)
- except (TypeError, ValueError):
- return None
-
-
-def _measured_block(diff: ReferenceDiff) -> str:
- if diff.iou is None:
- return ""
- line = f"\nMEASURED BY THE HARNESS: outline IoU of the front render vs the reference = {diff.iou:.3f}"
- if diff.aspect_ratio_err is not None:
- line += f", width/height error {diff.aspect_ratio_err:.0%}"
- if not diff.reliable:
- line += " (background mask unreliable — trust your eyes over this number)"
- return line + ". This is a fact; do not re-estimate it.\n"
diff --git a/harness/codeverse3d/spatial/silhouette.py b/harness/codeverse3d/spatial/silhouette.py
index 5b3d5b24..f902e78f 100644
--- a/harness/codeverse3d/spatial/silhouette.py
+++ b/harness/codeverse3d/spatial/silhouette.py
@@ -226,9 +226,11 @@ class ReferenceMatch(BaseModel):
return self.reliable and not self.conflict
-def measure_reference(renders: Sequence[RenderView], spec: Spec, *, compare: CompareFn | None = None) -> ReferenceMatch | None:
+def measure_reference(renders: Sequence[RenderView], spec: Spec, *, compare: CompareFn | None = None,
+ conflict: dict[str, Any] | None = None) -> ReferenceMatch | None:
""":class:`ReferenceMatch` of ``renders`` against ``spec``'s target reference, or ``None``
- when the spec has no readable reference or no render view could be compared."""
+ when the spec has no readable reference or no render view could be compared. ``conflict`` is
+ the caller's own :func:`dimension_conflict` of the same reference, when it already has it."""
from codeverse3d.reference import dimension_conflict # reference.py imports this module
ref = target_reference(spec.references)
@@ -239,4 +241,4 @@ def measure_reference(renders: Sequence[RenderView], spec: Spec, *, compare: Com
return None
num = {k: float(res[k]) for k in ("ref_fill", "render_fill", "aspect_ratio_err", "ref_aspect", "render_aspect") if isinstance(res.get(k), int | float)}
return ReferenceMatch(iou=float(res["iou"]), view=str(res.get("view", "")), reference=ref, reliable=bool(res.get("reliable", True)),
- conflict=bool(dimension_conflict(spec, ref).get("conflict")), per_view=res.get("per_view") or {}, **num)
+ conflict=bool((conflict if conflict is not None else dimension_conflict(spec, ref)).get("conflict")), per_view=res.get("per_view") or {}, **num)
diff --git a/harness/codeverse3d/tracks/plan_features.py b/harness/codeverse3d/tracks/plan_features.py
index 48fb5f73..be39fb87 100644
--- a/harness/codeverse3d/tracks/plan_features.py
+++ b/harness/codeverse3d/tracks/plan_features.py
@@ -6,7 +6,7 @@ from __future__ import annotations
from codeverse3d.config import Settings
GENERATION_SIDE_ENV: frozenset[str] = frozenset({"C3D_SKILLS", "C3D_SKILLS_MAX", "C3D_SKILLS_UNVERIFIED",
- "C3D_SKILLS_ONLY", "C3D_REFERENCE_DIFF"})
+ "C3D_SKILLS_ONLY"})
NODE_SIDE_ENV: frozenset[str] = frozenset({"C3D_BROWSER_REUSE", "C3D_PAGE_TTL_MS"})
diff --git a/harness/codeverse3d/workspace.py b/harness/codeverse3d/workspace.py
index a95350c5..df0d0458 100644
--- a/harness/codeverse3d/workspace.py
+++ b/harness/codeverse3d/workspace.py
@@ -156,9 +156,6 @@ class Workspace:
def renders_dir(self, round_index: int) -> Path:
return self.artifacts / "renders" / f"r{round_index:02d}"
- def rendered_rounds(self) -> list[int]:
- return sorted(int(p.name[1:]) for p in (self.artifacts / "renders").glob("r[0-9][0-9]") if p.is_dir())
-
def gates_dir(self, round_index: int) -> Path:
return self.artifacts / "gates" / f"r{round_index:02d}"
diff --git a/harness/tests/core/test_cli_render_size.py b/harness/tests/core/test_cli_render_size.py
deleted file mode 100644
index 79dcfa9e..00000000
--- a/harness/tests/core/test_cli_render_size.py
+++ /dev/null
@@ -1,76 +0,0 @@
-"""The render CLI honors configured dimensions and explicit overrides."""
-
-from __future__ import annotations
-
-from pathlib import Path
-from typing import Any
-
-import pytest
-from typer.testing import CliRunner
-
-import codeverse3d.spatial.render as R
-import codeverse3d.spatial.render_scene as RS
-from codeverse3d.cli.main import app
-from codeverse3d.contracts.artifacts import RenderSet
-from codeverse3d.contracts.common import Backends, Language, Track
-from codeverse3d.contracts.spec import Spec
-from codeverse3d.workspace import Workspace
-
-runner = CliRunner()
-
-
[email protected](autouse=True)
-def _isolated_cache(tmp_path, monkeypatch):
- """render_glb memoizes into <cache_dir>/renders, so without this the fake renders
- land in (and are served from) the developer's real ~/.cache/codeverse3d."""
- from codeverse3d.config import get_settings
-
- monkeypatch.setenv("C3D_CACHE_DIR", str(tmp_path / "cache"))
- get_settings.cache_clear()
- yield
- get_settings.cache_clear()
-
-
-def captured(monkeypatch) -> dict[str, Any]:
- """Intercept the low-level renderer; nothing here needs node."""
- seen: dict[str, Any] = {}
-
- def fake_run_render(glb, out_dir, params, *, gpu, timeout_s):
- seen.update(params)
- return {"views": [], "renderer": "fake", "duration_ms": 1}
-
- def fake_scene(ws, out_dir, **kw):
- seen.update(kw)
- return RenderSet(views=[], renderer="fake")
-
- monkeypatch.setattr(R, "_run_render", fake_run_render)
- monkeypatch.setattr(RS, "render_scene", fake_scene)
- return seen
-
-
-def _run(runs: Path, slug: str, language: Language, track: Track) -> None:
- ws = Workspace(runs / slug).create()
- ws.write_json(ws.spec_path, Spec(id=slug, track=track, language=language, prompt="a stool",
- backends=Backends(generator="gemini-cli:gemini-3.8-flash")))
- (ws.artifacts / "object.glb").write_bytes(b"glTF\x02\x00\x00\x00")
-
-
-def test_render_uses_the_configured_object_and_scene_sizes_and_explicit_flags_win(tmp_path, captured, monkeypatch):
- runs = tmp_path / "runs"
- _run(runs, "obj", Language.BLENDER, Track.STATIC_OBJECT)
- _run(runs, "scn", Language.SCENE_THREEJS, Track.SCENE)
- for name, value in (("WIDTH", "1600"), ("HEIGHT", "1200"), ("SCENE_WIDTH", "1920"), ("SCENE_HEIGHT", "1080")):
- monkeypatch.setenv(f"C3D_RENDER__{name}", value)
- from codeverse3d.config import get_settings
-
- get_settings.cache_clear()
- res = runner.invoke(app, ["render", "obj", "--runs-dir", str(runs)])
- assert res.exit_code == 0, res.output
- assert (captured.get("width"), captured.get("height")) == (1600, 1200)
- res = runner.invoke(app, ["render", "obj", "--runs-dir", str(runs), "--width", "320", "--height", "240"])
- assert res.exit_code == 0, res.output
- assert (captured.get("width"), captured.get("height")) == (320, 240)
- res = runner.invoke(app, ["render", "scn", "--runs-dir", str(runs)])
- assert res.exit_code == 0, res.output
- assert (captured.get("width"), captured.get("height")) == (1920, 1080)
diff --git a/harness/tests/cost/test_cli.py b/harness/tests/cost/test_cli.py
index c0d98fef..dd52f77c 100644
--- a/harness/tests/cost/test_cli.py
+++ b/harness/tests/cost/test_cli.py
@@ -12,13 +12,9 @@ from codeverse3d.cli.main import app
runner = CliRunner()
-def test_cost_prices_and_estimate():
+def test_cost_prices():
r = runner.invoke(app, ["cost", "prices", "--provider", "gemini"])
assert r.exit_code == 0 and "gemini:gemini-3.8-flash" in r.stdout and "verified" in r.stdout
- r = runner.invoke(app, ["cost", "estimate", "gemini:gemini-3.8-flash", "--in", "100000", "--out", "1000"])
- assert r.exit_code == 0 and "$0.0788" in r.stdout
- r = runner.invoke(app, ["cost", "estimate", "gemini:gemini-3.8-flash", "--in", "12000", "--images", "8"])
- assert r.exit_code == 0 and "~22,320 in" in r.stdout, r.stdout # 12 000 + 8 x 1 290
# --------------------------------------------------------------------- the live ledger
diff --git a/harness/tests/cost/test_context.py b/harness/tests/cost/test_context.py
index d443ebbf..de362b48 100644
--- a/harness/tests/cost/test_context.py
+++ b/harness/tests/cost/test_context.py
@@ -16,7 +16,6 @@ def test_label_tells_stage_role_and_round():
c = context_from_label("judge:static_object:r02:s1")
assert c.stage is Stage.JUDGE and c.role is Role.JUDGE and c.round == 2
assert context_from_label("planner-retry").stage is Stage.PLAN
- assert context_from_label("pairwise:0v1:fwd").stage is Stage.PAIRWISE
assert context_from_label("captioner").role is Role.CAPTIONER
assert context_from_label("").stage is None
assert context_from_label("baseline_repair1").stage is Stage.REPAIR # repair wins
diff --git a/harness/tests/cost/test_guard.py b/harness/tests/cost/test_guard.py
index c7a78eb6..a00fb76f 100644
--- a/harness/tests/cost/test_guard.py
+++ b/harness/tests/cost/test_guard.py
@@ -1,18 +1,10 @@
-"""The pre-send cost estimate."""
+"""The prompt-size estimate."""
from __future__ import annotations
-import pytest
+from codeverse3d.cost.guard import text_tokens
-from codeverse3d.cost import estimate_call
-from codeverse3d.cost.guard import image_tokens, text_tokens
-
-def test_estimate_from_text_and_images():
- est = estimate_call("gemini:gemini-3.1-pro-preview", prompt="x" * 4000, n_images=4, output_tokens=2000)
- assert est.input_tokens == 1000 + image_tokens(4)
- assert est.usd == pytest.approx((est.input_tokens * 2.0 + 2000 * 12.0) / 1e6)
+def test_text_tokens():
+ assert text_tokens("x" * 4000) == 1000
assert text_tokens(["ab" * 2, "cd" * 2]) == 2
- # a token count and images add up: `cost estimate --in 12000 --images 8` dropped the images
- est = estimate_call("gemini:gemini-3.1-pro-preview", input_tokens=12_000, n_images=8)
- assert est.input_tokens == 12_000 + image_tokens(8)
diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.py
index a96c9f95..0f28406f 100644
--- a/harness/tests/flywheel_cli/test_cli.py
+++ b/harness/tests/flywheel_cli/test_cli.py
@@ -156,7 +156,6 @@ def test_commands_over_a_runs_dir(runs_dir: Path, tmp_path: Path, monkeypatch):
assert inp.gates and inp.renders.views
assert inp.geometry_views is not None and inp.geometry_views.views[0].mode == "clay"
assert (ws.artifacts / "judge" / "r01_cli.json").is_file()
- assert "prompt images" in r.output
# a measured rubric goes to the reference judge
class _FakeRef(_FakeVlm):
@@ -269,7 +268,7 @@ def test_a_replay_judges_the_picked_round_on_the_runs_rubric_and_books_into_the_
record_call(Usage(backend="gemini", model="gemini-3.8-flash", cost_usd=cost), stage="judge", label="t", ledger=ledger)
return ledger_usage(load_ledger(ws.root)).cost_usd
- total = paid(0.03) # a pairwise verdict `pick` paid: the pick re-packages the record
+ total = paid(0.03) # a paid call: the pick re-packages the record
assert runner.invoke(app, ["pick", "stool_img", "--round", "0", "--runs-dir", str(runs)]).exit_code == 0
assert load_record(ws).total_usage.cost_usd == pytest.approx(total)
diff --git a/harness/tests/flywheel_cli/test_select.py b/harness/tests/flywheel_cli/test_select.py
index e7497c1f..7727c9c2 100644
--- a/harness/tests/flywheel_cli/test_select.py
+++ b/harness/tests/flywheel_cli/test_select.py
@@ -5,7 +5,6 @@ from __future__ import annotations
import json
from pathlib import Path
-from types import SimpleNamespace
import pytest
from typer.testing import CliRunner
@@ -93,19 +92,6 @@ def test_an_unjudged_run_shows_one_fallback_round_in_every_reader(tmp_path, monk
assert asked == [0] # `3dcodeverse judge`'s default round
-class _Pairwise:
- def __init__(self, winner: str, confidence: float, *, fail: bool = False, thinking: str = "medium"):
- self.winner, self.confidence, self.fail, self.calls = winner, confidence, fail, []
- self.thinking = thinking
-
- def compare(self, spec, renders_a, renders_b, *, rubric):
- self.calls.append((renders_a.views[0].path, renders_b.views[0].path, rubric))
- if self.fail:
- raise RuntimeError("judge down")
- return SimpleNamespace(winner=self.winner, confidence=self.confidence, reasons=["r"], usage=Usage(cost_usd=0.05),
- error="")
-
-
# --------------------------------------------------------------------------- package
def test_a_scene_or_graphics_round_packages_from_its_own_commit_and_renders(tmp_path):
"""A scene or graphics hand-over of round 0 of two is round 0's bytes, never the last's."""
@@ -144,7 +130,7 @@ def test_a_scene_or_graphics_round_packages_from_its_own_commit_and_renders(tmp_
# --------------------------------------------------------------------------- CLI
-def test_pick_command_by_score_by_round_and_by_pairwise(tmp_path, monkeypatch):
+def test_pick_command_by_score_and_by_round(tmp_path, monkeypatch):
runs = tmp_path / "runs"
ws = _run(runs / "stool", [(0.70, 0), (0.72, 0), (0.50, 0)])
r = runner.invoke(app, ["pick", "stool", "--runs-dir", str(runs)])
@@ -154,29 +140,6 @@ def test_pick_command_by_score_by_round_and_by_pairwise(tmp_path, monkeypatch):
assert r.exit_code == 0 and json.loads((ws.root / "selection.json").read_text())["method"] == "round"
assert (ws.deliverable / "src" / "model.py").read_text() == "import bpy # round 2\n"
- import codeverse3d.judges.pairwise as pw
-
- pairwise = _Pairwise("b", 0.95, thinking="low")
- monkeypatch.setattr(pw, "PairwiseJudge", lambda model: pairwise)
- args = ["pick", "stool", "--runs-dir", str(runs), "--by", "pairwise", "--judge", "fake:pairwise"]
- r = runner.invoke(app, args)
- assert r.exit_code == 0, r.output
- sel = json.loads((ws.root / "selection.json").read_text())
- assert (sel["round"], sel["method"]) == (0, "pairwise")
- assert runner.invoke(app, args).exit_code == 0 and len(pairwise.calls) == 1
- cache = ws.judge_path(1, "_vs_r00_pairwise")
- assert json.loads(cache.read_text())["thinking"] == "low"
-
- # A new thinking level must run the comparison again, even with identical model and renders.
- pairwise.thinking, pairwise.winner = "medium", "a"
- assert runner.invoke(app, args).exit_code == 0 and len(pairwise.calls) == 2
- assert json.loads((ws.root / "selection.json").read_text())["round"] == 1
- assert runner.invoke(app, args).exit_code == 0 and len(pairwise.calls) == 2
- cached = json.loads(cache.read_text())
- assert cached.pop("thinking") == "medium"
- ws.write_json(cache, cached) # old caches did not record the level and cannot prove a match
- assert runner.invoke(app, args).exit_code == 0 and len(pairwise.calls) == 3
- assert runner.invoke(app, ["pick", "stool", "--runs-dir", str(runs), "--by", "vibes"]).exit_code == 2
assert runner.invoke(app, ["pick", "stool", "--runs-dir", str(runs), "--round", "9"]).exit_code == 2
_run(runs / "blank", [(None, 0)])
@@ -223,7 +186,7 @@ def test_round_outputs_are_the_rounds_own_never_the_last_builds(tmp_path: Path):
ws.write_json(ws.artifacts / "measurement.json", {"extra": {"complexity": {"index": 0.9}}})
assert select.round_file(ws, rec.rounds[0]) == ws.round_artifacts(0) / "object.glb"
assert select.round_file(ws, rec.rounds[0], "preview.gif") is None
- assert select.round_complexity_block(ws, rec.rounds[0]) is None # never the canonical file's
+ assert select.round_complexity_block(rec.rounds[0]) is None # never the canonical file's
# Missing snapshots cannot borrow the canonical build, even with an obsolete best_round key.
for i in (0, 1):
(ws.round_artifacts(i) / "object.glb").unlink()
@@ -232,7 +195,7 @@ def test_round_outputs_are_the_rounds_own_never_the_last_builds(tmp_path: Path):
ws.write_json(ws.record_path, {**data, "best_round": 1})
assert select.round_file(ws, rec.rounds[0]) is None
assert select.round_file(ws, rec.rounds[1]) is None
- assert select.round_complexity_block(ws, rec.rounds[1]) is None
+ assert select.round_complexity_block(rec.rounds[1]) is None
@pytest.mark.parametrize("gate,rounds,want", [
@@ -252,18 +215,3 @@ def test_a_round_failing_the_projects_own_checks_loses_to_one_that_passes(tmp_pa
assert select.pick(ws.root) == want
rows = select.round_rows(ws.root)
assert [r.project_errors for r in rows] == ([e for _, e in rounds] if gate != "contract" else [0] * len(rounds))
-
-
-def test_pairwise_never_overturns_the_project_tier(tmp_path):
- """Within the pairwise margin, a round failing a project check is never asked against a clean one."""
- ws = _run(tmp_path / "r", [(0.70, 0), (0.71, 0)])
- rec = json.loads(ws.record_path.read_text())
- rec["rounds"][1]["gates"].append({"gate": "project:survey", "passed": False, "findings": [
- {"gate": "project:survey", "severity": "error", "message": "eaves 0.9 m off"}]})
- ws.record_path.write_text(json.dumps(rec))
-
- class Never:
- def judge(self, *a, **k):
- raise AssertionError("pairwise asked across tiers")
-
- assert select.pick(ws.root, by="pairwise", judge=Never()) == 0
diff --git a/harness/tests/judges/conftest.py b/harness/tests/judges/conftest.py
index f8c28e4b..f58050dc 100644
--- a/harness/tests/judges/conftest.py
+++ b/harness/tests/judges/conftest.py
@@ -32,7 +32,6 @@ def judge_settings(monkeypatch):
monkeypatch.delenv(name)
settings = Settings()
monkeypatch.setattr("codeverse3d.judges.vlm_judge.get_settings", lambda: settings)
- monkeypatch.setattr("codeverse3d.judges.pairwise.get_settings", lambda: settings)
return settings
diff --git a/harness/tests/judges/test_pairwise.py b/harness/tests/judges/test_pairwise.py
deleted file mode 100644
index 9d9fa042..00000000
--- a/harness/tests/judges/test_pairwise.py
+++ /dev/null
@@ -1,47 +0,0 @@
-import pytest
-
-from codeverse3d.judges.pairwise import PairwiseJudge
-from codeverse3d.models.base import ModelError
-from tests.judges.conftest import FakeChatModel, image_parts, make_renders, make_spec
-
-
-def _reply(w, conf=0.8):
- return {"winner": w, "confidence": conf, "reasons": [f"{w} has four legs"], "criteria_won": [{"criterion": "intent_fidelity", "winner": w}]}
-
-
-def test_the_swap_decides_the_winner_and_its_confidence(tmp_path, cache_dir, judge_settings):
- ra, rb = make_renders(tmp_path / "a"), make_renders(tmp_path / "b")
- # ordering 1: A=ra,B=rb → "A" wins; ordering 2 (swapped): A=rb,B=ra → "B" wins → both say ra
- model = FakeChatModel(by_label={":fwd": [_reply("A", 0.9)], ":swap": [_reply("B", 0.7)]})
- judge = PairwiseJudge(chat_model=model, cache_dir=cache_dir)
- assert judge.model_id == "gemini:gemini-4-argon"
- res = judge.compare(make_spec(), ra, rb)
- assert res.winner == "a" and res.confidence == 0.8
- # the two orderings run concurrently but land in (fwd, swap) order; usage sums across both
- assert [(o["swapped"], o["confidence"]) for o in res.orderings] == [(False, 0.9), (True, 0.7)]
- assert res.usage.cost_usd == pytest.approx(0.002) and res.usage.input_tokens == 2000
- reqs = {r.label: r for r in model.requests} # orderings run in parallel: look up by label
- assert {r.thinking for r in model.requests} == {"medium"}
- labels = [p.label for p in image_parts(reqs["pairwise:fwd"])]
- assert len(labels) == 2 # one 2×2 montage per side
- assert labels[0].startswith("CANDIDATE A — MONTAGE 1/1 — SHADED views: top-left = front_right_high") and labels[1].startswith("CANDIDATE B — MONTAGE")
- # swapped ordering puts rb first as "A"
- labels2 = [p.label for p in image_parts(reqs["pairwise:swap"])]
- assert labels2[0].startswith("CANDIDATE A — MONTAGE")
-
- # the orderings disagree (position bias: always first) → a tie
- judge_settings.judge.thinking = "off"
- model = FakeChatModel([_reply("A", 0.9), _reply("A", 0.9)])
- judge = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir)
- assert judge.model_id == "fake:fake-1"
- res = judge.compare(make_spec(), ra, rb)
- assert res.winner == "tie" and res.confidence <= 0.4 and res.error == "orderings disagree"
- assert {r.thinking for r in model.requests} == {"off"}
-
- # one ordering fails → the other's verdict at half confidence
- model = FakeChatModel(by_label={":fwd": [ModelError("x", retryable=True)],
- ":swap": [_reply("A", 0.8)]}) # swapped ordering: A=rb → b wins
- res = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare(make_spec(), ra, rb)
- assert res.winner == "b" and res.confidence == 0.4
-
-
diff --git a/harness/tests/judges/test_reference.py b/harness/tests/judges/test_reference.py
index c9f482ea..82f471ca 100644
--- a/harness/tests/judges/test_reference.py
+++ b/harness/tests/judges/test_reference.py
@@ -18,8 +18,7 @@ def test_reference_judge_measures_silhouette_and_adds_reference_images(judge_inp
return {"iou": 0.7, "aspect_ratio_delta": 0.05}
model = FakeChatModel([good_reply(REF, ["A1", "A2"], 0.8)])
- # diff=False: the mismatch pass is a SECOND model call (covered in tests/reference/test_judge_diff.py)
- j = ReferenceJudge("fake:fake-1", chat_model=model, silhouette_fn=fake_sil, cache_dir=cache_dir, diff=False).judge(judge_input)
+ j = ReferenceJudge("fake:fake-1", chat_model=model, silhouette_fn=fake_sil, cache_dir=cache_dir).judge(judge_input)
assert calls and calls[0][0].endswith("view_front.png") and calls[0][1] == str(ref_png)
assert j.scores["silhouette_match"] == pytest.approx(0.75)
assert iou_to_score(0.9) == 1.0 and iou_to_score(0.1) == 0.0
diff --git a/harness/tests/reference/test_judge_diff.py b/harness/tests/reference/test_judge_diff.py
deleted file mode 100644
index 64442d54..00000000
--- a/harness/tests/reference/test_judge_diff.py
+++ /dev/null
@@ -1,66 +0,0 @@
-"""ReferenceJudge: the reference labelling, the mismatch pass, best-view IoU."""
-
-from __future__ import annotations
-
-import pytest
-
-from codeverse3d.contracts.plan import AcceptanceItem
-from codeverse3d.contracts.spec import ReferenceImage
-from codeverse3d.judges.base import JudgeInput
-from codeverse3d.judges.rubrics import load_rubric
-from codeverse3d.judges.vlm_judge import ReferenceJudge
-from tests.judges.conftest import (
- FakeChatModel,
- draw_chair,
- good_reply,
- make_measurement,
- make_renders,
- make_spec,
-)
-
-REF = load_rubric("reference")
-
-DIFF = {"mismatches": [{"kind": "wrong_part_count", "target": "Legs",
- "detail": "reference shows 4 legs, render shows 2", "severity": "critical"}],
- "matches": ["the backrest slats are right"]}
-
-
-def ref_input(tmp_path):
- png = draw_chair(tmp_path / "ref.png", legs=4, color=(30, 30, 30))
- spec = make_spec(references=[ReferenceImage(path=str(png), role="target",
- note="my photo")])
- return JudgeInput(
- spec=spec, renders=make_renders(tmp_path / "renders"), measurement=make_measurement(),
- acceptance=[AcceptanceItem(id="A1", text="four legs", how="measure", priority="must")])
-
-
-def _judge(model, **kw):
- return ReferenceJudge("fake:fake-1", chat_model=model, silhouette_fn=lambda a, b: {"iou": 0.6, "reliable": True},
- **kw)
-
-
[email protected](("thinking", "expected"), [(None, "medium"), ("off", "off")])
-def test_reference_that_contradicts_the_brief_scores_neutral(tmp_path, switch, thinking, expected):
- from codeverse3d.contracts.spec import Constraints
- from codeverse3d.judges.vlm_judge import NEUTRAL_SCORE
-
- switch("C3D_JUDGE__THINKING", "medium")
- switch("C3D_REFERENCE_DIFF", "1")
- png = draw_chair(tmp_path / "wide.png", legs=4) # ~2:1 wide silhouette
- spec = make_spec(references=[ReferenceImage(path=str(png), role="target", note="my photo")],
- constraints=Constraints(dimensions_m={"width": 0.45, "height": 2.0})) # implies 0.22 w/h
- inp = JudgeInput(spec=spec, renders=make_renders(tmp_path / "r"), measurement=make_measurement(),
- acceptance=[AcceptanceItem(id="A1", text="t", how="visual", priority="must")])
- model = FakeChatModel(by_label={"reference_diff": [DIFF], "judge": [good_reply(REF, ["A1"], 0.8)]})
- j = ReferenceJudge("fake:fake-1", chat_model=model, cache_dir=tmp_path / "cache", thinking=thinking)
- verdict = j.judge(inp)
- assert {r.label: r.thinking for r in model.requests} == {
- "reference_diff": expected, "judge:reference:r00:s0": expected,
- }
- assert verdict.scores["silhouette_match"] == NEUTRAL_SCORE
- text = [r for r in model.requests if r.label.startswith("judge")][0].messages[0].parts[0].text
- assert "REFERENCE PROPORTIONS DISAGREE WITH THE BRIEF" in text
- assert "NEUTRAL" in text
-
-
diff --git a/harness/tests/reference/test_mismatch.py b/harness/tests/reference/test_mismatch.py
deleted file mode 100644
index 361eb179..00000000
--- a/harness/tests/reference/test_mismatch.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""The render-vs-reference diff."""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-from PIL import Image
-
-from codeverse3d.models.base import ModelError
-from codeverse3d.reference import compare
-from tests.orchestrator_tracks.fakes import FakeChatModel
-from tests.reference.conftest import make_spec
-
-
-def _png(p: Path) -> Path:
- Image.new("RGB", (64, 64), (200, 200, 200)).save(p)
- return p
-
-
-def test_a_failed_or_impossible_diff_is_soft(tmp_path: Path):
- ref, ren = _png(tmp_path / "ref.png"), _png(tmp_path / "ren.png")
- d = compare(make_spec(), [ref], [ren], model=FakeChatModel(by_label={"reference_diff": [ModelError("nope")]}))
- assert d.mismatches == [] and "diff call failed" in d.error and d.as_text() == ""
- d = compare(make_spec(), [tmp_path / "gone.png"], [ren], model=FakeChatModel())
- assert "nothing to compare" in d.error
diff --git a/harness/tests/reference/test_silhouette_best_view.py b/harness/tests/reference/test_silhouette_best_view.py
index 4056b186..4fd283ef 100644
--- a/harness/tests/reference/test_silhouette_best_view.py
+++ b/harness/tests/reference/test_silhouette_best_view.py
@@ -48,5 +48,5 @@ def test_the_gate_and_the_judge_read_one_measurement(tmp_path: Path) -> None:
ctx = SimpleNamespace(spec=spec, services=SimpleNamespace(silhouette=compare_silhouette))
(finding,) = silhouette_gate(ctx, RenderSet(views=views)).findings
assert finding.data["view"] == "right" and finding.data["iou"] > 0.8 and finding.severity == Severity.INFO
- jc = ReferenceJudge("fake:fake-1", chat_model=FakeChatModel([]), diff=False).context(JudgeInput(spec=spec, renders=RenderSet(views=views)))
+ jc = ReferenceJudge("fake:fake-1", chat_model=FakeChatModel([])).context(JudgeInput(spec=spec, renders=RenderSet(views=views)))
assert f"right render vs reference ref.png: IoU {finding.data['iou']:.3f}" in jc.extra_text