Skip to content

Official Codebase of 3DCodeVerse

Python

tests: judges, reference, texturing — cut to the rules asserted once; cap tables parametrized (−722 lines)

gaoypeng54b9c82b4d38
diff --git a/harness/tests/judges/test_calibration.py b/harness/tests/judges/test_calibration.py
index 3ba38f5f..2d707abf 100644
--- a/harness/tests/judges/test_calibration.py
+++ b/harness/tests/judges/test_calibration.py
@@ -102,9 +102,7 @@ def test_calibrate_offline(tmp_path):
def test_run_labels_stay_distinct_across_battery_layouts():
- """Bench cells all end in .../run: compare_backends cells for DIFFERENT prompts
- (and ab_plan's control vs treatment arms) used to collapse to one label, so
- their judgment sidecars overwrote each other (V9c)."""
+ """V9c: bench cells all end in .../run; their labels (and judgment sidecars) must not collide."""
from codeverse3d.addons.calibration import _run_label
# compare_backends: <battery>/cells/<prompt>/<arm>/run
diff --git a/harness/tests/judges/test_caps.py b/harness/tests/judges/test_caps.py
index fd31c4fe..3a20d594 100644
--- a/harness/tests/judges/test_caps.py
+++ b/harness/tests/judges/test_caps.py
@@ -1,161 +1,98 @@
-from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity
+import pytest
+
+from codeverse3d.contracts.artifacts import GateFinding, GateReport, RenderView, Severity
from codeverse3d.contracts.plan import AcceptanceItem
-from codeverse3d.judges.rubrics import apply_caps, load_rubric
+from codeverse3d.judges.rubrics import (
+ AcceptanceVerdict,
+ CriterionScore,
+ JudgeOutput,
+ aggregate_samples,
+ apply_caps,
+ load_rubric,
+ measured_absent,
+ veto_measured_defects,
+)
R = load_rubric("static_object_v1")
+A = load_rubric("articulated_v1")
+S = load_rubric("scene_v1")
+POSE = [RenderView(name="pose_rest", path="p")]
-def _gate(name, sev, msg, **data):
+def _gate(name, sev, msg, target="", **data):
return GateReport(gate=name, passed=sev != Severity.ERROR,
- findings=[GateFinding(gate=name, severity=sev, message=msg, data=data)])
-
-
-def test_no_caps_when_clean():
- res = apply_caps(R, 0.9, [GateReport(gate="connectivity", passed=True)], {}, [])
- assert res.overall == 0.9 and not res.caps_applied
-
-
-def test_build_error_caps_to_zero():
- res = apply_caps(R, 0.9, [_gate("build:blender", Severity.ERROR, "Traceback ... NameError")], {}, [])
- assert res.overall == 0.0
- assert res.caps_applied[0].rule == "build_error"
-
-
-def test_floating_via_data_kind_and_message():
- res = apply_caps(R, 0.9, [_gate("connectivity", Severity.ERROR, "part Leg1 is 3cm above others", kind="floating")], {}, [])
- assert res.overall == 0.6 and res.caps_applied[0].rule == "floating_part"
- res2 = apply_caps(R, 0.9, [_gate("connectivity", Severity.ERROR, "Leg1 has no_contact with any part")], {}, [])
- assert res2.overall == 0.6
-
-
-def test_warn_does_not_cap():
- res = apply_caps(R, 0.9, [_gate("connectivity", Severity.WARN, "floating sliver")], {}, [])
- assert res.overall == 0.9
-
+ findings=[GateFinding(gate=name, severity=sev, target=target, message=msg, data=data)])
-def test_penetration_and_multiple_caps_take_min():
- gates = [_gate("connectivity", Severity.ERROR, "penetration Seat/Leg 12mm"),
- _gate("connectivity", Severity.ERROR, "Arm floating", kind="floating")]
- res = apply_caps(R, 0.95, gates, {}, [])
- assert res.overall == 0.6
- assert {c.rule for c in res.caps_applied} == {"floating_part", "penetration_error"}
-
-def test_missing_must_acceptance_caps():
- items = [AcceptanceItem(id="M1", text="x", priority="must"), AcceptanceItem(id="S1", text="y", priority="should")]
- res = apply_caps(R, 0.9, [], {"M1": False, "S1": False}, items)
- assert res.overall == 0.6 and res.caps_applied[0].rule == "missing_must_acceptance"
- res2 = apply_caps(R, 0.9, [], {"M1": True, "S1": False}, items)
- assert res2.overall == 0.9
- res3 = apply_caps(R, 0.9, [], {}, items) # missing → not verified
- assert res3.overall == 0.6
-
-
-def test_scene_console_and_shader_caps():
- S = load_rubric("scene_v1")
- res = apply_caps(S, 0.9, [], {}, [], console_errors=["TypeError: x is undefined"])
- assert res.overall == 0.6 and res.caps_applied[0].rule == "console_error"
- res2 = apply_caps(S, 0.9, [_gate("shader_probe", Severity.ERROR, "GLSL compile failed in water.js", kind="shader")], {}, [])
- assert res2.overall == 0.5
-
-
-# ------------------------------------------- a passed gate vetoes the checklist's claim
def _connectivity(passed: bool, *msgs: tuple[str, str]):
- from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity
sev = {"error": Severity.ERROR, "warn": Severity.WARN, "info": Severity.INFO}
return GateReport(gate="connectivity", passed=passed,
findings=[GateFinding(gate="connectivity", severity=sev[s], target="", message=m) for s, m in msgs])
-def test_a_floating_claim_the_connectivity_gate_measured_absent_neither_penalises_nor_caps():
- """Measured 2026-08-26 (fancy_v1 gas_street_lamp, plan-pinned pair): gate said
- 'all 9 parts connected, gap <= 2 mm'; the judge marked floating_part present on a dark
- seam and defect:floating_part capped the run at 0.6 (uncapped 0.72) against 0.96 for a
- sibling the eye cannot tell apart. Gates decide geometry (law 3)."""
- from codeverse3d.judges.rubrics import load_rubric, measured_absent, veto_measured_defects
-
- rubric = load_rubric("static_object_v1")
- passed = [_connectivity(True, ("info", "all 9 parts are connected (9 contacts, gap <= 2 mm)"),
- ("warn", "part 'GasBurner' contains 7 tiny disconnected island(s)"))]
- assert measured_absent(rubric, "floating_part", passed)
- kept, overridden = veto_measured_defects(rubric, {"floating_part": True, "wrong_object": True}, passed)
- assert overridden == ["floating_part"]
- assert kept == {"floating_part": False, "wrong_object": True}, "only what a gate measures can be vetoed"
-
-
-def test_a_real_floating_part_still_caps():
- from codeverse3d.judges.rubrics import load_rubric, measured_absent
-
- rubric = load_rubric("static_object_v1")
- failed = [_connectivity(False, ("error", "part 'Seat' is floating 12 mm above 'Leg'"))]
- assert not measured_absent(rubric, "floating_part", failed)
- assert not measured_absent(rubric, "floating_part", []), "a gate that did not run measured nothing"
- assert not measured_absent(rubric, "wrong_object", [_connectivity(True)]), "no gate measures 'wrong object'"
-
-
-def test_scene_placement_gate_measures_the_floating_asset_claim():
- """scene_v1 (2026-08-26): the placement gate and the checklist defect share an id, so a passed
- gate vetoes the VLM's floating/sunken claim and an ERROR there caps the round at 0.7."""
- from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity
- from codeverse3d.judges.rubrics import apply_caps, load_rubric, measured_absent
-
- rubric = load_rubric("scene_v1")
- passed = [GateReport(gate="scene_placement", passed=True, findings=[GateFinding(
- gate="scene_placement", severity=Severity.INFO, target="scene", message="13 assets checked: 0 floating, 0 sunken")])]
- assert measured_absent(rubric, "floating_or_sunken_asset", passed)
- failed = [GateReport(gate="scene_placement", passed=False, findings=[GateFinding(
- gate="scene_placement", severity=Severity.ERROR, target="Pondside/Lantern", message="Pondside/Lantern is floating 0.30 m above PondWater")])]
- assert not measured_absent(rubric, "floating_or_sunken_asset", failed)
- res = apply_caps(rubric, 0.9, failed, {}, [], defects_present={})
- assert res.overall == 0.6, "the older floating_part rule (gate *, cap 0.6) fires too; the tighter cap wins"
- assert any(c.rule == "floating_or_sunken_asset" for c in res.caps_applied)
-
-
-# ------------------------------------------- 2026-08-30: the veto reaches interpenetration
-def test_a_passed_connectivity_gate_vetoes_the_interpenetration_claim():
- """Audited 2026-08-30 over 420 static_object verdicts: 237 interpenetration flags, 110 of
- them citing only WARNs the rubric says to ignore, and this veto had fired for it 0 times —
- the cap rule is ``penetration_error``, the defect ``interpenetration``, and the match was
- on id. ``CapRule.measures`` now carries the defect id."""
- from codeverse3d.judges.rubrics import measured_absent, veto_measured_defects
-
- passed = [_connectivity(True, ("info", "all 9 parts are connected (9 contacts, gap <= 2 mm)"),
- ("warn", "'Seat' and 'Leg' overlap by 1.4 mm (weld)"))]
- assert measured_absent(R, "interpenetration", passed)
- kept, overridden = veto_measured_defects(R, {"interpenetration": True, "floating_part": True, "wrong_object": True}, passed)
+E, W = Severity.ERROR, Severity.WARN
+
+
[email protected](("rubric", "gates", "kw", "overall", "rules"), [
+ (R, [_gate("build:blender", E, "Traceback ... NameError")], {}, 0.0, {"build_error"}),
+ (R, [_gate("connectivity", E, "part Leg1 is 3cm above others", kind="floating")], {}, 0.6, {"floating_part"}),
+ (R, [_gate("connectivity", E, "Leg1 has no_contact with any part")], {}, 0.6, {"floating_part"}),
+ (R, [_gate("connectivity", W, "floating sliver")], {}, 0.9, set()),
+ (R, [_gate("connectivity", E, "penetration Seat/Leg 12mm"), _gate("connectivity", E, "Arm floating", kind="floating")],
+ {}, 0.6, {"floating_part", "penetration_error"}),
+ (R, [_gate("connectivity", E, "'Leg' and 'Seat' interpenetrate by ≈15 mm", target="Leg")], {}, 0.7, {"penetration_error"}),
+ (A, [_gate("connectivity", E, "'Leg' and 'Seat' interpenetrate by ≈15 mm", target="Leg")], {"views": POSE}, 0.7,
+ {"penetration_error"}),
+ (A, [_gate("joint_sweep", E, "link 'DrawerKnob' touches nothing connected to the root at pose rest "
+ "(nearest 'Carcass' at 56.4 mm)", target="DrawerKnob")],
+ {"views": POSE}, 0.6, {"floating_part"}),
+ (S, [], {"console_errors": ["TypeError: x is undefined"]}, 0.6, {"console_error"}),
+ (S, [_gate("shader_probe", E, "GLSL compile failed in water.js", kind="shader")], {}, 0.5, {"shader_error"}),
+ # the older floating_part rule (gate *, cap 0.6) fires too; the tighter cap wins
+ (S, [_gate("scene_placement", E, "Pondside/Lantern is floating 0.30 m above PondWater", target="Pondside/Lantern")],
+ {"defects_present": {}}, 0.6, {"floating_or_sunken_asset"}),
+])
+def test_gate_caps(rubric, gates, kw, overall, rules):
+ res = apply_caps(rubric, 0.9, gates, {}, [], **kw)
+ assert res.overall == overall
+ applied = {c.rule for c in res.caps_applied}
+ assert applied == rules if rules == set() else rules <= applied
+
+
+PASSED = _connectivity(True, ("info", "all 9 parts are connected (9 contacts, gap <= 2 mm)"),
+ ("warn", "'Seat' and 'Leg' overlap by 1.4 mm (weld)"))
+CONTRACT_ERR = GateReport(gate="contract", passed=False, findings=[GateFinding(
+ gate="contract", severity=E, target="bbox", message="height 0.31 m vs plan 0.45 m (31% off)")])
+
+
[email protected](("rubric", "defect", "gates", "absent"), [
+ (R, "floating_part", [PASSED], True),
+ (R, "interpenetration", [PASSED], True),
+ (R, "floating_part", [_connectivity(False, ("error", "part 'Seat' is floating 12 mm above 'Leg'"))], False),
+ (R, "interpenetration", [_connectivity(False, ("error", "'Leg' and 'Seat' interpenetrate by ≈15 mm"))], False),
+ (R, "floating_part", [], False), # a gate that did not run measured nothing
+ (R, "wrong_object", [_connectivity(True)], False), # no gate measures 'wrong object'
+ # a contract ERROR about the bbox does not switch off the veto connectivity earned
+ (R, "floating_part", [CONTRACT_ERR, _connectivity(True, ("info", "all 4 parts are connected"))], True),
+ (R, "interpenetration", [CONTRACT_ERR, _connectivity(True, ("info", "all 4 parts are connected"))], True),
+ (S, "floating_or_sunken_asset", [GateReport(gate="scene_placement", passed=True, findings=[GateFinding(
+ gate="scene_placement", severity=Severity.INFO, target="scene", message="13 assets checked: 0 floating")])], True),
+])
+def test_measured_absent(rubric, defect, gates, absent):
+ """Gates decide geometry (law 3): a passed gate vetoes the VLM's claim of what it measured."""
+ assert measured_absent(rubric, defect, gates) is absent
+
+
+def test_veto_switches_off_only_measured_defects_and_the_contract_cap_still_applies():
+ kept, overridden = veto_measured_defects(R, {"interpenetration": True, "floating_part": True, "wrong_object": True}, [PASSED])
assert overridden == ["interpenetration", "floating_part"]
assert kept == {"interpenetration": False, "floating_part": False, "wrong_object": True}
- failed = [_connectivity(False, ("error", "'Leg' and 'Seat' interpenetrate by ≈15 mm (5% of surface samples inside)"))]
- assert not measured_absent(R, "interpenetration", failed), "a measured penetration is not vetoed"
- assert not measured_absent(R, "interpenetration", []), "a gate that did not run measured nothing"
-
-
-def test_a_failing_contract_gate_does_not_disable_the_connectivity_veto():
- """53 of the 62 blocked cases (2026-08-30): the rules watched gate "*", so a contract ERROR
- about the bbox switched off a veto the connectivity gate had earned."""
- from codeverse3d.judges.rubrics import measured_absent
-
- contract = GateReport(gate="contract", passed=False, findings=[GateFinding(
- gate="contract", severity=Severity.ERROR, target="bbox", message="height 0.31 m vs plan 0.45 m (31% off)")])
- gates = [contract, _connectivity(True, ("info", "all 4 parts are connected (4 contacts)"))]
- assert measured_absent(R, "floating_part", gates)
- assert measured_absent(R, "interpenetration", gates)
+ gates = [CONTRACT_ERR, _connectivity(True, ("info", "all 4 parts are connected"))]
res = apply_caps(R, 0.9, gates, {}, [], defects_present={"floating_part": False})
- assert res.overall == 0.75 and [c.rule for c in res.caps_applied] == ["contract_violation"], "the contract cap itself still applies"
+ assert res.overall == 0.75 and [c.rule for c in res.caps_applied] == ["contract_violation"]
def test_graded_acceptance_cap_keeps_the_gradient_but_not_the_pass():
- """The flat 0.6 was the decisive cap on 121 of 424 verdicts (28.6 %, 2026-08-30): one
- unverified must item out of ten scored exactly like ten out of ten."""
- import pytest
-
- from codeverse3d.judges.rubrics import (
- AcceptanceVerdict,
- CriterionScore,
- JudgeOutput,
- aggregate_samples,
- )
-
ten = [AcceptanceItem(id=f"M{i}", text="x", priority="must") for i in range(10)]
nine_ok = {a.id: True for a in ten} | {"M3": False}
res = apply_caps(R, 0.99, [], nine_ok, ten)
@@ -163,8 +100,10 @@ def test_graded_acceptance_cap_keeps_the_gradient_but_not_the_pass():
assert res.caps_applied[0].evidence.startswith("9 of 10 must items verified; not verified: M3")
assert apply_caps(R, 0.99, [], {}, ten[:2]).overall == pytest.approx(0.6), "0 of 2 verified is the floor"
assert apply_caps(R, 0.99, [], {"M0": True}, ten[:2]).overall == pytest.approx(0.8)
- assert apply_caps(load_rubric("scene_v1"), 0.99, [], nine_ok, ten).overall == 0.6, "an ungraded rule keeps its flat cap"
- # pass/fail is the owner's policy and unchanged: the verdict still fails on must_missing
+ should = [AcceptanceItem(id="S1", text="y", priority="should")]
+ assert apply_caps(R, 0.9, [], {"S1": False}, should).overall == 0.9, "a should item never caps"
+ assert apply_caps(S, 0.99, [], nine_ok, ten).overall == 0.6, "an ungraded rule keeps its flat cap"
+ # pass/fail is the owner's policy: the verdict still fails on must_missing
sample = JudgeOutput(criteria={c.id: CriterionScore(score=0.99, evidence="") for c in R.criteria},
acceptance={k: AcceptanceVerdict(verified=v) for k, v in nine_ok.items()},
defects={d.id: False for d in R.defects})
diff --git a/harness/tests/judges/test_defects.py b/harness/tests/judges/test_defects.py
index 2b6052ba..c8b41002 100644
--- a/harness/tests/judges/test_defects.py
+++ b/harness/tests/judges/test_defects.py
@@ -90,26 +90,8 @@ def test_penalties_and_caps_computed_in_code(judge_input, cache_dir):
assert raw2["samples"][0]["defects"]["floating_part"] is True
-def test_defect_majority_vote_with_odd_n(judge_input, cache_dir):
- model = FakeChatModel(by_label={":s0": [_reply(0.9, ["render_artifacts"])], ":s1": [_reply(0.9)],
- ":s2": [_reply(0.9)]})
- j = VlmJudge("static_object_v1", chat_model=model, n_samples=3, cache_dir=cache_dir).judge(judge_input)
- raw = json.loads(j.raw)
- assert raw["defects"]["render_artifacts"] is False and raw["defect_votes"]["render_artifacts"] == [True, False, False]
- assert raw["tie_broken"] == [] and j.overall == pytest.approx(0.9)
- # per-criterion std is reported for n-sample runs
- assert set(raw["per_criterion_std"]) == set(R.weights)
-
-
def test_defect_vote_ties_are_absent(judge_input, cache_dir, caplog):
- """An exact defect-vote tie is ABSENT (2026-08-30; was: the representative sample, D36).
-
- At n=2 the representative is whichever sample's overall sits nearer the mean — a
- float comparison, not evidence — so a 1-1 tie was a coin flip on a defect that caps
- the run at 0.7. The rubric already puts the burden on the defect ("mark an item
- present only when an image or a gate finding shows it"); a tie has not met it.
- Acceptance ties still follow the representative (the test below): a must-item tie
- decides pass/fail, and that policy is the owner's."""
+ """D36: an exact defect-vote tie is ABSENT, whichever sample flagged it."""
flagged_first = FakeChatModel(by_label={":s0": [_reply(0.9, ["render_artifacts"])], ":s1": [_reply(0.9)]})
with caplog.at_level("WARNING", logger="codeverse3d.judges.vlm_judge"):
j = VlmJudge("static_object_v1", chat_model=flagged_first, n_samples=2, cache_dir=cache_dir).judge(judge_input)
@@ -129,7 +111,7 @@ def test_defect_vote_ties_are_absent(judge_input, cache_dir, caplog):
def test_acceptance_vote_ties_follow_the_representative_sample(judge_input, cache_dir):
- """Same rule for acceptance items: the old ties → False failed a must item on one dissent."""
+ """D36: an acceptance tie follows the representative sample."""
a_ok, a_no = _reply(0.9), _reply(0.9)
a_no["acceptance"]["A1"]["verified"] = False
j = VlmJudge("static_object_v1", chat_model=FakeChatModel(by_label={":s0": [a_ok], ":s1": [a_no]}),
@@ -156,20 +138,3 @@ def test_missing_views_cap_for_articulated():
assert j.overall == 0.5 and "missing_pose_sheet≤0.50" in j.summary
j2 = aggregate_samples(A, samples, gates=[], acceptance_items=[], views=list(RenderSet(views=rest + [RenderView(name="pose_rest", path="p")]).views))
assert j2.overall == pytest.approx(0.9)
-
-
-def test_interpenetrate_message_matches_penetration_cap():
- from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity
- g = GateReport(gate="connectivity", passed=False, findings=[GateFinding(
- gate="connectivity", severity=Severity.ERROR, target="Leg", message="'Leg' and 'Seat' interpenetrate by ≈15 mm")])
- assert apply_caps(R, 0.9, [g], {}, []).overall == 0.7
- assert apply_caps(A, 0.9, [g], {}, [], views=[RenderView(name="pose_rest", path="p")]).overall == 0.7
-
-
-def test_joint_sweep_touches_nothing_caps_articulated():
- from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity
- g = GateReport(gate="joint_sweep", passed=False, findings=[GateFinding(
- gate="joint_sweep", severity=Severity.ERROR, target="DrawerKnob",
- message="link 'DrawerKnob' touches nothing connected to the root at pose rest (nearest 'Carcass' at 56.4 mm)")])
- res = apply_caps(A, 0.9, [g], {}, [], views=[RenderView(name="pose_rest", path="p")])
- assert res.overall == 0.6 and res.caps_applied[0].rule == "floating_part"
diff --git a/harness/tests/judges/test_detail_anchors.py b/harness/tests/judges/test_detail_anchors.py
index 23ec881f..c8119b1c 100644
--- a/harness/tests/judges/test_detail_anchors.py
+++ b/harness/tests/judges/test_detail_anchors.py
@@ -1,13 +1,4 @@
-"""The geometry-detail anchors must stay *countable*.
-
-The corpus study (eval/docs/COMPLEXITY.md) found geometry_detail to be the weakest
-criterion (static mean 0.667, 2 of 44 runs at ≥ 0.9) and, worse, almost blind to
-objective geometry: r = +0.05 against the complexity index and +0.19 against
-feature density. The fix was to make the anchors count REFINEMENT KINDS and
-coverage instead of asking for a vibe. These tests are the guard rail: they fail
-if the countable ladder, the "colour is not geometry" rule or the
-"score the object BUILT" rule is quietly removed again.
-"""
+"""Guard rail (eval/docs/COMPLEXITY.md): the geometry-detail anchors stay countable and caps stay put."""
from __future__ import annotations
@@ -27,53 +18,29 @@ DETAIL_CRITERION = {
@pytest.mark.parametrize(("rubric", "criterion"), sorted(DETAIL_CRITERION.items()))
-def test_detail_anchor_ladder_is_graded(rubric: str, criterion: str) -> None:
- """Enough rungs to place a partly-detailed artifact, and strictly ordered."""
- c = load_rubric(rubric).criterion(criterion)
+def test_detail_anchors_are_a_graded_countable_geometry_ladder(rubric: str, criterion: str) -> None:
+ r = load_rubric(rubric)
+ c = r.criterion(criterion)
levels = sorted((float(k) for k in c.anchors), reverse=True)
- assert len(levels) >= 5, f"{rubric}.{criterion} needs intermediate anchors, got {levels}"
- assert levels[0] == 1.0 and levels[-1] == 0.1
- assert levels == sorted(levels, reverse=True)
- assert all(a > b for a, b in zip(levels, levels[1:], strict=False))
-
-
[email protected](("rubric", "criterion"), sorted(DETAIL_CRITERION.items()))
-def test_top_anchor_is_reachable_and_countable(rubric: str, criterion: str) -> None:
- """0.9+ must be earnable by a stated, countable amount of geometry — not by
- 'reads as a crafted asset'."""
- top = load_rubric(rubric).criterion(criterion).anchors["1.0"].lower()
+ assert len(levels) >= 5 and levels[0] == 1.0 and levels[-1] == 0.1, levels
+ top = c.anchors["1.0"].lower()
assert any(w in top for w in ("five or more", "nearly every")), top
assert any(w in top for w in ("kind", "detail")), top
+ text = (c.description + " " + r.extra_instructions).lower()
+ assert "colour" in text and ("not" in text or "never" in text), "colour is not geometry"
[email protected](("rubric", "criterion"), sorted(DETAIL_CRITERION.items()))
-def test_detail_is_geometry_not_colour(rubric: str, criterion: str) -> None:
- """The strongest confound in the corpus: the judge read 'detail' off material
- variety. The criterion text must say colour does not count."""
- text = (load_rubric(rubric).criterion(criterion).description
- + " " + load_rubric(rubric).extra_instructions).lower()
- assert "colour" in text
- assert "not" in text or "never" in text
-
-
-def test_static_notes_carry_the_refinement_kinds_and_reach_the_judge() -> None:
+def test_static_notes_carry_the_refinement_kinds_and_the_majority_primitive_rule() -> None:
r = load_rubric("static_object_v1")
prompt = build_system_prompt(r)
- assert "REFINEMENT KINDS" in prompt
- for kind in ("bevel", "taper", "cut-out", "wall thickness", "surface relief", "hardware"):
+ for kind in ("REFINEMENT KINDS", "bevel", "taper", "cut-out", "wall thickness", "surface relief", "hardware",
+ "DETAIL AND SIZE", "box-stack"):
assert kind in prompt, kind
- # the ceiling rule: a rich object must be allowed to outscore a clean box-stack
- assert "DETAIL AND SIZE" in prompt
- assert "box-stack" in prompt
-
-
-def test_primitive_stack_defect_fires_on_a_majority_not_on_perfection() -> None:
- """The old text ('every part ... no refinement anywhere') let one token chamfer
- exempt a box stack. The new one is a majority rule."""
- d = next(d for d in load_rubric("static_object_v1").defects if d.id == "primitive_only")
- assert "two thirds" in d.text.lower()
- assert "colour" in d.text.lower()
- assert d.penalty == pytest.approx(0.08)
+ text = r.defect("primitive_only").text.lower()
+ assert "two thirds" in text and "colour" in text
+ for rubric in ("static_object_v1", "articulated_v1"):
+ c = load_rubric(rubric).criterion("craftsmanship_no_artifacts")
+ assert "detail scale" in c.anchors["1.0"].lower() and "0.85" in c.anchors
def test_physical_plausibility_caps_are_untouched() -> None:
@@ -91,12 +58,7 @@ def test_physical_plausibility_caps_are_untouched() -> None:
@pytest.mark.parametrize("rubric", ["static_object_v1", "articulated_v1"])
def test_acceptance_cap_is_graded_with_the_floor_pinned(rubric: str) -> None:
- """The acceptance cap is GRADED since 2026-08-30 (DECISIONS D46 b): 0.6 + 0.4·verified/total.
-
- The first version of the guard above pinned ``.cap`` alone and so waved that change
- through without noticing. This one pins both halves: the flag, so a rubric edit cannot
- silently fall back to the flat cap, and the floor, so 0 of n verified still scores 0.6.
- """
+ """D46 b: the acceptance cap is graded, 0.6 + 0.4·verified/total — the flag and the floor pinned."""
rule = next(c for c in load_rubric(rubric).caps if c.id == "missing_must_acceptance")
assert rule.when == "acceptance" and rule.cap == 0.6 and rule.graded is True
items = [AcceptanceItem(id=f"M{i}", text=f"must {i}", priority="must") for i in range(10)]
@@ -110,10 +72,3 @@ def test_acceptance_cap_is_graded_with_the_floor_pinned(rubric: str) -> None:
assert cap_at(0) == pytest.approx(0.6)
assert cap_at(9) == pytest.approx(0.96)
assert _rule_hit(rule, [], {a.id: True for a in items}, items, [], []) is None
-
-
-def test_craftsmanship_top_anchor_is_detail_scale() -> None:
- for rubric in ("static_object_v1", "articulated_v1"):
- top = load_rubric(rubric).criterion("craftsmanship_no_artifacts").anchors["1.0"].lower()
- assert "detail scale" in top or "including at detail scale" in top
- assert "0.85" in load_rubric(rubric).criterion("craftsmanship_no_artifacts").anchors
diff --git a/harness/tests/judges/test_judge_slices.py b/harness/tests/judges/test_judge_slices.py
index 1ae1e56e..45fcf10e 100644
--- a/harness/tests/judges/test_judge_slices.py
+++ b/harness/tests/judges/test_judge_slices.py
@@ -1,12 +1,4 @@
-"""D48: conditional cross-section slices in the judge payload.
-
-The load-bearing invariant is byte-identity: a round WITHOUT a connectivity
-gate ERROR must build exactly the pre-D48 messages (same system prompt, same
-parts, same ``judge_prompt_hash``) whatever the knob or ``glb_path`` say. A
-gate-ERROR round on an object track appends the slice images AFTER the
-montages and detail crops, describes them in the view-rig text, and adds the
-provenance-elicitation sentence to the defect-checklist bullet exactly once.
-"""
+"""D48: conditional cross-section slices — a round without a connectivity ERROR builds the exact pre-D48 payload."""
from __future__ import annotations
@@ -141,10 +133,6 @@ def test_dirty_gates_append_slices_after_crops_with_rig_text_and_one_elicitation
text = text_of(req)
assert "After the crops, 2 cross-section slice(s) show the interior" in text
assert "A gap between parts IN THE CUT PLANE is not evidence of disconnection" in text
- # the 2026-08-31 watch-item battery: the generic caveat did not stop a 2.4 mm open join
- # and section-cut islands being marked floating_part, so the text names the views that
- # CAN decide instead of merely denying the slice (a bare prohibition would suppress the
- # true marks the channel is there to win)
assert "Judge floating_part and holes_or_inverted_faces from the shaded" in text
assert f"- slice 1: {SLICE_LABELS['front_back']}" in text
assert req.system.count(PROVENANCE_ELICITATION) == 1
@@ -175,8 +163,7 @@ def test_error_pair_extraction_reads_target_and_other(tmp_path):
def test_a_dirty_round_with_a_floating_only_error_still_elicits(tmp_path, cache_dir):
- """The trigger is ANY connectivity ERROR; with no penetration pair the slices carry
- no hatch but the elicitation sentence still applies (the tested v3 semantics)."""
+ """The trigger is ANY connectivity ERROR, not only a penetration pair."""
gates = [GateReport(gate="connectivity", passed=False, findings=[
GateFinding(gate="connectivity", severity=Severity.ERROR, target="B",
message="part 'B' is floating", data={"kind": "floating"})])]
diff --git a/harness/tests/judges/test_likeness.py b/harness/tests/judges/test_likeness.py
index deb42a6a..e3d771dd 100644
--- a/harness/tests/judges/test_likeness.py
+++ b/harness/tests/judges/test_likeness.py
@@ -10,8 +10,6 @@ from tests.judges.conftest import FakeChatModel, draw_chair, good_reply, image_p
def test_likeness_context_attaches_the_photos_and_the_note(judge_input, tmp_path, cache_dir):
- """Measured 2026-08-26 (teaser aurora ×3, flash + codex): 0.78–0.94 with empty issues while
- nothing looked like an aurora — the rubric had no photo to hold the frames against."""
ref = tmp_path / "aurora_green_spiral_sea.png"
draw_chair(ref)
judge_input.spec = make_spec(track=Track.GRAPHICS, language=Language.GLSL_SHADER,
@@ -28,10 +26,6 @@ def test_likeness_context_attaches_the_photos_and_the_note(judge_input, tmp_path
labels = [p.label for p in image_parts(req)]
assert labels[0].startswith("REAL-WORLD REFERENCE 1/1"), labels
assert "REAL-WORLD REFERENCE PHOTOS are attached" in req.messages[0].parts[0].text
-
-
-def test_no_photos_means_a_plain_judge(judge_input, cache_dir):
- judge_input.spec = make_spec(track=Track.GRAPHICS, language=Language.GLSL_SHADER)
- j = LikenessJudge("fake:fake-1", rubric="shader_v1", chat_model=FakeChatModel([good_reply(load_rubric("shader_v1"), ["A1", "A2"], 0.8)]), cache_dir=cache_dir)
+ judge_input.spec = make_spec(track=Track.GRAPHICS, language=Language.GLSL_SHADER) # no photos: a plain judge
ctx = j.context(judge_input)
assert ctx.extra_images == [] and ctx.extra_text == ""
diff --git a/harness/tests/judges/test_montage.py b/harness/tests/judges/test_montage.py
index bb1e3034..e5ee4a9b 100644
--- a/harness/tests/judges/test_montage.py
+++ b/harness/tests/judges/test_montage.py
@@ -6,9 +6,6 @@ from PIL import Image
from codeverse3d.contracts.artifacts import RenderSet, RenderView
from codeverse3d.judges.prompt_builder import (
JudgeImageError,
- describe_montages,
- montage_label,
- montage_strip,
plan_montages,
rank_views,
render_montage,
@@ -44,22 +41,8 @@ def test_rank_views_objects_and_scenes():
assert [v.name for v in rank_views(sv, scene=True)] == ["Establishing", "BridgeView", "cam_b", "overview_top", "eye_front"]
-def test_plan_montages_object_rig(tmp_path):
- rs = RenderSet(views=_views(tmp_path, OBJ))
- ms = plan_montages(rs)
- kinds = [m.kind for m in ms]
- assert kinds == ["shaded", "shaded", "shaded", "shaded", "detail", "detail"]
- assert [v.name for v in ms[0].tiles] == ["front_right_high", "back_left_high", "top", "bottom"]
- assert [v.name for v in ms[1].tiles] == ["front", "right", "back", "left"]
- assert [v.name for v in ms[2].tiles] == ["front_right_low", "back_left_low", "front_left_high", "back_right_high"]
- assert [v.name for v in ms[3].tiles] == ["front_left_low", "back_right_low"]
- assert ms[4].crop == (0.25, 0.25, 0.75, 0.75) and ms[5].tiles[0].name == "bottom"
- assert "- image 2: SHADED views (remaining)" in describe_montages(ms)
-
-
def test_plan_montages_full_rig_plus_clay_is_the_measured_cprod_plan(tmp_path):
- """14 shaded + 4 clay -> exactly 5 montages + 2 crops; montage 1 keeps the underside
- even under a montage-cap truncation, and one crop is anchored on ``bottom`` (D47)."""
+ """D47: 14 shaded + 4 clay -> 5 montages + 2 crops; montage 1 keeps the underside, one crop on ``bottom``."""
rs = RenderSet(views=_views(tmp_path, OBJ))
clay = RenderSet(views=_views(tmp_path, CLAY, mode="clay", prefix="c"))
ms = plan_montages(rs, geometry_views=clay) # defaults: max_montages=5, detail_crops=2
@@ -105,24 +88,6 @@ def test_shuffle_keeps_sets_and_details_last(tmp_path):
assert len(seeds) >= 3
-def test_labels_and_render(tmp_path):
- rs = RenderSet(views=_views(tmp_path, ("front_right_high", "back_left_high", "front")))
- m = plan_montages(rs, detail_crops=1)[0]
- lbl = montage_label(m, 1, 1)
- assert lbl.startswith("MONTAGE 1/1 — SHADED views: top-left = front_right_high · az 45° el 30°, top-right = back_left_high")
- assert "bottom-left = front · az 0° el 0°" in lbl
- assert montage_strip(m, 1, 1) == "MONTAGE 1/1 — SHADED views"
- png = render_montage(m, cache_dir=tmp_path / "cache", tile_px=256)
- assert png.is_file() and render_montage(m, cache_dir=tmp_path / "cache", tile_px=256) == png # cached
- with Image.open(png) as im:
- assert im.size[0] == 2 * 256 + 3 * 6 and im.size[1] > 2 * 256 # 2 cols × 2 rows with labels
- crop = plan_montages(rs, detail_crops=1)[-1]
- cpng = render_montage(crop, cache_dir=tmp_path / "cache", tile_px=400)
- with Image.open(cpng) as im:
- assert max(im.size) >= 400
- assert "look for bevels" in montage_label(crop, 1, 1)
-
-
def test_missing_tile_is_judge_image_error(tmp_path):
m = plan_montages(RenderSet(views=[RenderView(name="front", path="/nonexistent/x.png")]), detail_crops=0)[0]
with pytest.raises(JudgeImageError):
@@ -144,12 +109,7 @@ def test_sheet_helpers(tmp_path):
def test_a_stored_pre_d47_render_set_still_leads_with_its_hero_views():
- """PR #3 review: OBJECT_RANK forgot the legacy names, so a re-judged stored 8-view
- run put {top, front, right, back} in montage 1 and anchored the centre crop on
- 'top' — its four sibling constants all kept the legacy names for stored runs."""
- from codeverse3d.contracts.artifacts import RenderView
- from codeverse3d.judges.prompt_builder import rank_views
-
+ """A re-judged stored 8-view run ranks its legacy hero names first."""
legacy = ["front_right_34", "back_left_34", "front", "right", "back", "left", "top", "low_front_left"]
ranked = [v.name for v in rank_views([RenderView(name=n, path=f"/x/{n}.png") for n in legacy], scene=False)]
assert ranked[:2] == ["front_right_34", "back_left_34"], ranked
diff --git a/harness/tests/judges/test_output_schema.py b/harness/tests/judges/test_output_schema.py
index eb6e4df4..ee355c7d 100644
--- a/harness/tests/judges/test_output_schema.py
+++ b/harness/tests/judges/test_output_schema.py
@@ -1,4 +1,3 @@
-import json
import pytest
@@ -20,29 +19,8 @@ def test_wire_schema_has_fixed_keys_and_no_overall():
assert set(crit["required"]) == {c.id for c in R.criteria}
acc = s["$defs"]["Acceptance"]
assert set(acc["properties"]) == set(IDS)
- assert "overall" not in s["properties"] and "passed" not in s["properties"]
-
-
-def test_wire_schema_without_acceptance_omits_block():
- s = wire_schema(R, [])
- assert "acceptance" not in s["properties"]
-
-
-def test_parse_dict_form():
- out = parse_judge_output(good_reply(R, IDS, 0.8), R, IDS)
- assert set(out.scores) == {c.id for c in R.criteria}
- assert out.acceptance_bools == {"A1": True, "must-2": True}
- assert out.improvement_plan[0].target == "Seat"
-
-
-def test_parse_list_form_and_fenced_text():
- rep = good_reply(R, IDS, 0.7)
- rep["criteria"] = [{"id": k, **v} for k, v in rep["criteria"].items()]
- rep["acceptance"] = [{"id": k, "verified": v["verified"]} for k, v in rep["acceptance"].items()]
- text = "Here you go:\n```json\n" + json.dumps(rep) + "\n```"
- out = parse_judge_output(text, R, IDS)
- assert out.scores["materials"] == 0.7
- assert out.acceptance_bools["A1"] is True
+ assert "overall" not in s["properties"] and "passed" not in s["properties"] # law 3: scored in code
+ assert "acceptance" not in wire_schema(R, [])["properties"]
def test_parse_bare_bool_acceptance_and_numeric_scores():
@@ -77,17 +55,6 @@ def test_out_of_range_score_raises():
parse_judge_output(rep, R, IDS)
-def test_measured_injection():
- ref = load_rubric("reference_v1")
- rep = good_reply(ref, [], 0.8) # visual criteria only
- out = parse_judge_output(rep, ref, [], measured_scores={"silhouette_match": 0.55})
- assert out.scores["silhouette_match"] == 0.55
- with pytest.raises(JudgeParseError):
- parse_judge_output(rep, ref, []) # measured criterion missing
-
-
def test_text_reply_without_json_raises_judge_parse_error():
- """String payloads go through the shared lenient parser; its JsonParseError is
- re-raised as JudgeParseError so callers keep one exception surface."""
with pytest.raises(JudgeParseError, match="no JSON object"):
parse_judge_output("no json here", R, IDS)
diff --git a/harness/tests/judges/test_pairwise.py b/harness/tests/judges/test_pairwise.py
index cc2098e2..35d7397e 100644
--- a/harness/tests/judges/test_pairwise.py
+++ b/harness/tests/judges/test_pairwise.py
@@ -53,16 +53,8 @@ def test_single_ordering_success_halves_confidence(tmp_path, cache_dir):
assert res.winner == "b" and res.confidence == 0.4
-def test_unswap_reasons():
- from codeverse3d.judges.pairwise import _unswap_text
- assert _unswap_text("Candidate A beats candidate B", True) == "Candidate B beats candidate A"
- assert _unswap_text("Candidate A beats candidate B", False) == "Candidate A beats candidate B"
-
-
def test_a_scene_pair_is_ranked_as_a_scene_from_the_views_the_judge_saw(tmp_path, cache_dir):
- """Every candidate used to be ranked as an OBJECT from its whole render set: a scene's
- own camera sank behind the overview rig, and a view the verdict judge never saw
- (``judge=False``) could fill a montage slot."""
+ """A scene's own camera leads, and a view the verdict judge never saw (judge=False) is left out."""
from codeverse3d.contracts.artifacts import RenderSet, RenderView
from codeverse3d.contracts.common import Language, Track
from tests.judges.conftest import draw_chair
diff --git a/harness/tests/judges/test_prompt_builder.py b/harness/tests/judges/test_prompt_builder.py
index 9dad2403..0e8eb0ee 100644
--- a/harness/tests/judges/test_prompt_builder.py
+++ b/harness/tests/judges/test_prompt_builder.py
@@ -16,12 +16,10 @@ from codeverse3d.judges.prompt_builder import (
TEXT_BUDGET_CHARS,
build_judge_messages,
build_system_prompt,
- montage_image_parts,
- prepare_image,
view_az_el,
)
from codeverse3d.judges.rubrics import load_rubric
-from tests.judges.conftest import draw_chair, make_renders
+from tests.judges.conftest import draw_chair
R = load_rubric("static_object_v1")
@@ -35,9 +33,6 @@ def _images(msgs):
def test_the_scene_rig_rule_names_every_harness_camera_and_no_authored_prefix():
- """Authored cameras carry the plan's names (``cam_i`` is only scene_host's fallback for an
- unnamed one) and the eye-level rig is the harness's too: the judge was told authored views
- are ``cam_*`` and nothing about ``eye_*``."""
from codeverse3d.conventions import SCENE_VIEWS
from codeverse3d.judges.prompt_builder import RIG_RULES
@@ -85,28 +80,8 @@ def test_user_message_layout(judge_input, cache_dir):
assert 900 <= im.size[0] <= 1024 and im.size[1] > im.size[0] # 2×2 grid + strip
-def test_shuffle_is_deterministic_and_changes_order(tmp_path, judge_input, cache_dir):
- rs = make_renders(tmp_path / "eight", n=4)
- extra = []
- for name in ("right", "back", "left", "low_front_left"):
- p = draw_chair(tmp_path / f"v_{name}.png", az_hint=1)
- extra.append(RenderView(name=name, path=str(p)))
- judge_input.renders = RenderSet(views=rs.views + extra)
- _, a = build_judge_messages(judge_input, R, shuffle_seed=1, cache_dir=cache_dir)
- _, b = build_judge_messages(judge_input, R, shuffle_seed=1, cache_dir=cache_dir)
- _, c = build_judge_messages(judge_input, R, shuffle_seed=None, cache_dir=cache_dir)
- la, lb, lc = ([p.label for p in _images(m)] for m in (a, b, c))
- assert la == lb
- assert len(lc) == 4 # 2 montages + 2 crops
- assert lc[0].startswith("MONTAGE 1/2 — SHADED views:") and lc[1].startswith("MONTAGE 2/2 — SHADED views (remaining)")
- # canonical order puts the 3/4 views first; the seeded order differs somewhere (montage or tile order)
- assert la != lc
- assert la[-2:] == lc[-2:] # detail crops are never shuffled
-
-
def test_geometry_views_add_a_montage(tmp_path, judge_input, cache_dir):
- """The clay montage rides the pipeline's OWN cameras (OBJECT_CLAY_VIEWS) and labels
- them — the clay 'top' is el 88 while the rig's shaded 'top' is el 90 (D47)."""
+ """D47: the clay montage is labelled from the clay rig's own cameras (top at el 88, not 90)."""
from codeverse3d.conventions import OBJECT_CLAY_VIEWS
clay = []
@@ -127,19 +102,6 @@ def test_geometry_views_add_a_montage(tmp_path, judge_input, cache_dir):
assert any(p.label.startswith("MONTAGE 2/2 — GEOMETRY-ONLY") for p in _images(msgs2))
-def test_montage_cap_and_crop_knobs(tmp_path, judge_input, cache_dir):
- views = []
- for i in range(14):
- p = draw_chair(tmp_path / f"v{i}.png", az_hint=i)
- views.append(RenderView(name=f"v{i}", path=str(p), camera_position=(1.0, 0.5, 1.0), look_at=(0, 0.3, 0)))
- judge_input.renders = RenderSet(views=views)
- pairs, montages = montage_image_parts(judge_input.renders, cache_dir=cache_dir, max_montages=3, detail_crops=0)
- assert len(pairs) == 3 and all(m.kind == "shaded" for m in montages)
- assert "top-left = v0 · az 45° el" in pairs[0][0] # az/el computed from camera geometry
- pairs2, _ = montage_image_parts(judge_input.renders, cache_dir=cache_dir, max_montages=1, detail_crops=1)
- assert len(pairs2) == 2 and pairs2[1][0].startswith("DETAIL CROP — centre of v0")
-
-
def test_gates_previous_and_budget(judge_input, cache_dir):
judge_input.gates = [GateReport(gate="connectivity", passed=False, findings=[
GateFinding(gate="connectivity", severity=Severity.ERROR, target="LegBackLeft", message="floating 3 cm"),
@@ -178,38 +140,8 @@ def test_view_az_el_geometry():
assert view_az_el(RenderView(name="zzz", path="x")) is None
-def test_prepare_image_label_and_cache(tmp_path):
- src = draw_chair(tmp_path / "a.png", size=1600)
- out = prepare_image(src, label="VIEW 1/1 — front", max_px=768, cache_dir=tmp_path / "c")
- with Image.open(out) as im:
- assert im.size[0] == 768 and im.size[1] > 768 # strip added below label
- assert prepare_image(src, label="VIEW 1/1 — front", max_px=768, cache_dir=tmp_path / "c") == out
-
-
-def test_a_passed_connectivity_gate_tells_the_judge_a_seam_is_not_daylight():
- """Measured 2026-08-26 (fancy_v1 gas_street_lamp, plan-pinned pair): the connectivity gate
- said 'all 9 parts connected, gap <= 2 mm'; the judge read the dark seam under the pedestal
- as 'floating in mid-air, a clear daylight gap' (CRITICAL) and scored structure_plausibility
- 0.4 against 1.0 for the near-identical sibling. A measured contact outranks a shadow."""
- from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity
- from codeverse3d.judges.prompt_builder import gates_section
-
- ok = GateReport(gate="connectivity", passed=True, findings=[
- GateFinding(gate="connectivity", severity=Severity.INFO, target="", message="all 9 parts are connected")])
- text = gates_section([ok])
- assert "CONNECTIVITY PASSED" in text and "not daylight" in text and "Do NOT report any part as floating" in text
-
- failed = GateReport(gate="connectivity", passed=False, findings=[
- GateFinding(gate="connectivity", severity=Severity.ERROR, target="Seat", message="part 'Seat' floats 12 mm above 'Leg'")])
- assert "CONNECTIVITY PASSED" not in gates_section([failed]), "a real floating part is still reported as one"
- assert "CONNECTIVITY PASSED" not in gates_section([GateReport(gate="contract", passed=True)]), "only the contact gate earns it"
-
-
# ===================================================================== the contact ledger (2026-08-30)
-#: the connectivity gate's ledger for a real p90 round — eval/bench/out/codex_tiers_v3/cells/
-#: cmp_hard_violin/harness_codex_gpt-5.6-sol r00 (16 parts, 26 contacts), re-run through
-#: ``check_connectivity(planned_edges=planned_joins(plan, measurement))`` on 2026-08-30.
-#: 23 overlaps, one open planned join (the tailpiece never reaches the endpin button).
+#: a real p90 round's connectivity ledger (16 parts, 26 contacts, 23 overlaps, one open planned join)
LEDGER_VIOLIN = {"parts": ["Chinrest", "Strings", "Tailpiece", "Bridge", "TuningPegs_3", "TuningPegs_2", "TuningPegs_1", "TuningPegs_0", "PegboxAndScroll", "Nut", "Fingerboard", "NeckRoot", "EndpinButton", "TopPlate", "RibStructure", "BackPlate"], "contact_gap_mm": 2.0, "contacts": [["Chinrest", "TopPlate", 0.0], ["Chinrest", "RibStructure", 0.0], ["Strings", "Tailpiece", 0.0], ["Strings", "Bridge", 0.8], ["Strings", "TuningPegs_2", 0.0], ["Strings", "TuningPegs_1", 0.6], ["Strings", "PegboxAndScroll", 0.0], ["Strings", "Nut", 0.0], ["Strings", "NeckRoot", 0.0], ["Tailpiece", "TopPlate", 0.0], ["Bridge", "TopPlate", 0.0], ["TuningPegs_3", "PegboxAndScroll", 0.0], ["TuningPegs_2", "PegboxAndScroll", 0.0], ["TuningPegs_1", "PegboxAndScroll", 0.0], ["TuningPegs_0", "PegboxAndScroll", 0.0], ["PegboxAndScroll", "Nut", 0.0], ["PegboxAndScroll", "Fingerboard", 0.0], ["PegboxAndScroll", "NeckRoot", 0.0], ["Nut", "Fingerboard", 0.0], ["Nut", "NeckRoot", 0.0], ["Fingerboard", "NeckRoot", 0.0], ["NeckRoot", "TopPlate", 0.0], ["NeckRoot", "RibStructure", 0.0], ["EndpinButton", "RibStructure", 0.0], ["TopPlate", "RibStructure", 0.0], ["RibStructure", "BackPlate", 0.0]], "overlaps": [["Chinrest", "TopPlate", 1.8, 0.08], ["Strings", "Tailpiece", 3.1, 0.02], ["Strings", "TuningPegs_2", 2.4, 0.02], ["Strings", "PegboxAndScroll", 5.1, 0.0], ["Strings", "Nut", 0.4, 0.02], ["Strings", "NeckRoot", 1.5, 0.02], ["Tailpiece", "TopPlate", 1.7, 0.23], ["Bridge", "TopPlate", 1.5, 0.36], ["TuningPegs_3", "PegboxAndScroll", 6.6, 0.17], ["TuningPegs_2", "PegboxAndScroll", 9.0, 0.33], ["TuningPegs_1", "PegboxAndScroll", 8.3, 0.27], ["TuningPegs_0", "PegboxAndScroll", 3.9, 0.19], ["PegboxAndScroll", "Nut", 2.5, 0.11], ["PegboxAndScroll", "Fingerboard", 2.7, 0.1], ["PegboxAndScroll", "NeckRoot", 4.1, 0.2], ["Nut", "Fingerboard", 1.0, 0.23], ["Nut", "NeckRoot", 1.0, 0.07], ["Fingerboard", "NeckRoot", 8.4, 0.55], ["NeckRoot", "TopPlate", 1.0, 0.0], ["NeckRoot", "RibStructure", 0.1, 0.0], ["EndpinButton", "RibStructure", 3.0, 0.0], ["TopPlate", "RibStructure", 1.6, 0.05], ["RibStructure", "BackPlate", 2.5, 0.07]], "ground_gap_mm": {"Chinrest": 33.0, "Strings": 43.0, "Tailpiece": 37.0, "Bridge": 37.5, "TuningPegs_3": 55.0, "TuningPegs_2": 45.0, "TuningPegs_1": 45.0, "TuningPegs_0": 55.0, "PegboxAndScroll": 33.0, "Nut": 51.0, "Fingerboard": 44.2, "NeckRoot": 21.3, "EndpinButton": 14.0, "TopPlate": 31.0, "RibStructure": 3.0, "BackPlate": 0.0}, "planned": [["RibStructure", "BackPlate", 0.0, "contact"], ["TopPlate", "RibStructure", 0.0, "contact"], ["EndpinButton", "RibStructure", 0.0, "contact"], ["NeckRoot", "RibStructure", 0.0, "contact"], ["Fingerboard", "NeckRoot", 0.0, "contact"], ["Nut", "Fingerboard", 0.0, "contact"], ["PegboxAndScroll", "NeckRoot", 0.0, "contact"], ["TuningPegs_3", "PegboxAndScroll", 0.0, "contact"], ["TuningPegs_2", "PegboxAndScroll", 0.0, "contact"], ["TuningPegs_1", "PegboxAndScroll", 0.0, "contact"], ["TuningPegs_0", "PegboxAndScroll", 0.0, "contact"], ["Bridge", "TopPlate", 0.0, "contact"], ["Tailpiece", "EndpinButton", 24.9, "open"], ["Strings", "Bridge", 0.8, "contact"], ["Chinrest", "TopPlate", 0.0, "contact"]], "planned_unresolved": []}
@@ -240,9 +172,7 @@ CONTRACT_FAIL = GateReport(gate="contract", passed=False, findings=[
def test_ledger_turns_penetration_warn_prose_into_one_measured_line():
- """The audit (eval/docs/EVAL.md §6): 110 of 237 interpenetration flags cited only WARNs the rubric
- says to ignore; same images with the gate text removed flipped 13 of 24. The eleven
- 'interpenetrate by' sentences of this round become one measured line, ERRORs stay."""
+ """eval/docs/EVAL.md §6: the WARN 'interpenetrate by' sentences become one measured line; ERRORs stay."""
from codeverse3d.judges.prompt_builder import gates_section
rep = _ledger_report()
@@ -346,9 +276,7 @@ def test_ledger_ground_line_and_single_part_and_grouped_warnings():
def test_gates_section_without_a_ledger_is_byte_identical_to_the_pre_ledger_text():
- """A recorded round has no ledger finding: ``3dcode judge <old-slug>`` must build the exact text
- the stored verdict saw. Expected strings were captured from ``gates_section`` at 4ddde32,
- before the ledger path existed (scratch capture_baseline.py, 2026-08-30)."""
+ """A replay of a pre-ledger round builds the exact text its stored verdict saw (captured at 4ddde32)."""
from codeverse3d.judges.prompt_builder import gates_section
C = "connectivity"
@@ -375,18 +303,3 @@ def test_gates_section_without_a_ledger_is_byte_identical_to_the_pre_ledger_text
many = [GateReport(gate=C, passed=False, findings=[F(Severity.ERROR, f"error {i}", f"P{i}") for i in range(14)] + [F(Severity.WARN, f"warn {i}", f"W{i}") for i in range(11)])]
assert gates_section(many) == 'GATE FINDINGS (deterministic; treat as facts): connectivity=FAIL\nerrors (14):\n- connectivity [P0]: error 0\n- connectivity [P1]: error 1\n- connectivity [P2]: error 2\n- connectivity [P3]: error 3\n- connectivity [P4]: error 4\n- connectivity [P5]: error 5\n- connectivity [P6]: error 6\n- connectivity [P7]: error 7\n- connectivity [P8]: error 8\n- connectivity [P9]: error 9\n- connectivity [P10]: error 10\n- connectivity [P11]: error 11\n- … 2 more errors\nwarnings (11):\n- connectivity [W0]: warn 0\n- connectivity [W1]: warn 1\n- connectivity [W2]: warn 2\n- connectivity [W3]: warn 3\n- connectivity [W4]: warn 4\n- connectivity [W5]: warn 5\n- connectivity [W6]: warn 6\n- connectivity [W7]: warn 7\n- … 3 more warnings'
assert gates_section(many, max_errors=3, max_warns=2) == 'GATE FINDINGS (deterministic; treat as facts): connectivity=FAIL\nerrors (14):\n- connectivity [P0]: error 0\n- connectivity [P1]: error 1\n- connectivity [P2]: error 2\n- … 11 more errors\nwarnings (11):\n- connectivity [W0]: warn 0\n- connectivity [W1]: warn 1\n- … 9 more warnings'
-
-
-def test_judge_prompt_hash_does_not_cover_the_per_run_gate_text():
- """The ledger block rides on v1's hash: ``judge_prompt_hash`` covers the system prompt, the
- rig rules and the wire schema only, so a paired re-judge, not the hash, is what measures it."""
- from codeverse3d.judges.prompt_builder import judge_prompt_hash
-
- h = judge_prompt_hash(R)
- import codeverse3d.judges.prompt_builder as pb
- original = pb.gates_section
- try:
- pb.gates_section = lambda gates, **kw: "NOT THE SAME TEXT"
- assert judge_prompt_hash(R) == h
- finally:
- pb.gates_section = original
diff --git a/harness/tests/judges/test_reference.py b/harness/tests/judges/test_reference.py
index 7c5cb308..5dda0338 100644
--- a/harness/tests/judges/test_reference.py
+++ b/harness/tests/judges/test_reference.py
@@ -8,11 +8,6 @@ from tests.judges.conftest import FakeChatModel, draw_chair, good_reply, image_p
REF = load_rubric("reference_v1")
-def test_iou_mapping():
- assert iou_to_score(0.9) == 1.0 and iou_to_score(0.1) == 0.0
- assert iou_to_score(0.55) == pytest.approx(0.5)
-
-
def test_reference_judge_measures_silhouette_and_adds_reference_images(judge_input, tmp_path, cache_dir):
ref_png = draw_chair(tmp_path / "ref.png", legs=4, color=(30, 30, 30))
judge_input.spec = judge_input.spec.model_copy(update={"references": [ReferenceImage(path=str(ref_png), note="target chair")]})
@@ -27,6 +22,7 @@ def test_reference_judge_measures_silhouette_and_adds_reference_images(judge_inp
j = ReferenceJudge("fake:fake-1", chat_model=model, silhouette_fn=fake_sil, cache_dir=cache_dir, diff=False).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
expected = sum(REF.weights[c] * (0.75 if c == "silhouette_match" else 0.8) for c in REF.weights)
assert j.overall == pytest.approx(round(expected, 4))
req = model.requests[0]
diff --git a/harness/tests/judges/test_rubrics.py b/harness/tests/judges/test_rubrics.py
index 84e5dafc..a2c10573 100644
--- a/harness/tests/judges/test_rubrics.py
+++ b/harness/tests/judges/test_rubrics.py
@@ -1,27 +1,6 @@
import pytest
-from codeverse3d.judges.rubrics import RubricError, list_rubrics, load_rubric, rubric_from_dict
-
-EXPECTED = {"static_object_v1", "articulated_v1", "scene_v1", "asset_v1", "reference_v1"}
-
-
-def test_all_rubrics_load_and_validate():
- assert set(list_rubrics()) >= EXPECTED
- for name in EXPECTED:
- r = load_rubric(name)
- assert abs(sum(c.weight for c in r.criteria) - 1.0) < 0.02
- for c in r.criteria:
- assert set(c.anchors) >= {"1.0", "0.7", "0.4", "0.1"}
- assert any(c.id == "build_error" and c.cap == 0.0 for c in r.caps)
- assert any(c.when == "acceptance" for c in r.caps)
-
-
-def test_static_rubric_shape():
- r = load_rubric("static_object_v1")
- assert r.pass_threshold == 0.72
- assert r.weights["intent_fidelity"] == 0.22
- assert r.criterion("intent_fidelity").floor == 0.30
- assert [c.id for c in r.criteria][:3] == ["intent_fidelity", "structure_plausibility", "geometry_detail"]
+from codeverse3d.judges.rubrics import RubricError, load_rubric, rubric_from_dict
def test_reference_rubric_has_measured_silhouette():
@@ -53,13 +32,8 @@ def test_unknown_and_invalid_rubric():
rubric_from_dict(bad)
-def test_content_hash_stable():
- assert load_rubric("scene_v1").content_hash() != load_rubric("asset_v1").content_hash()
-
-
def test_cap_rule_measures_defaults_to_its_own_id_and_the_object_rubrics_name_interpenetration():
- """2026-08-30: ``penetration_error`` had never vetoed ``interpenetration`` because the veto
- matched on id; the object rubrics now say which checklist defect each gate rule measures."""
+ """The object rubrics say which checklist defect each gate rule measures (the veto matches on it)."""
from codeverse3d.judges.rubrics import CapRule
assert CapRule(id="floating_part", cap=0.6).measures == ["floating_part"]
@@ -80,8 +54,7 @@ def test_cap_rule_measures_defaults_to_its_own_id_and_the_object_rubrics_name_in
def test_cap_rules_are_not_part_of_the_judge_prompt():
- """The 2026-08-30 cap changes move ``content_hash`` but not ``judge_prompt_hash``: cap rules
- are scored in code and never rendered to the judge (prompt_builder._rubric_block)."""
+ """D37: cap rules move ``content_hash`` but not ``judge_prompt_hash`` — they are scored in code."""
import yaml
from codeverse3d.judges.prompt_builder import judge_prompt_hash
diff --git a/harness/tests/judges/test_vlm_judge.py b/harness/tests/judges/test_vlm_judge.py
index bea83860..c473cbf2 100644
--- a/harness/tests/judges/test_vlm_judge.py
+++ b/harness/tests/judges/test_vlm_judge.py
@@ -2,7 +2,6 @@ import json
import pytest
-from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity
from codeverse3d.judges.rubrics import load_rubric
from codeverse3d.judges.vlm_judge import VlmJudge
from codeverse3d.models.base import ModelError
@@ -37,40 +36,20 @@ def test_full_path_single_sample(judge_input, cache_dir):
assert raw["defects"] == {d.id: False for d in R.defects} and raw["defect_penalty"] == 0.0
-def test_overall_is_code_computed_weighted_mean(judge_input, cache_dir):
- over = {"intent_fidelity": 1.0, "materials": 0.5}
- model = FakeChatModel([good_reply(R, IDS, 0.8, overrides=over)])
- j = _judge(model, cache_dir=cache_dir).judge(judge_input)
- expected = sum(R.weights[c] * over.get(c, 0.8) for c in R.weights)
- assert j.overall == pytest.approx(round(expected, 4))
-
-
-def test_n_samples_mean_std_and_shuffle(judge_input, cache_dir):
- # samples fan out in parallel: route replies by the request's :s<k> label
[email protected]("fixed_order", [False, True])
+def test_n_samples_mean_std_and_view_order(judge_input, cache_dir, fixed_order):
+ """Samples fan out by :s<k> label; fixed_order (the calibration mode) shows every sample the same order."""
model = FakeChatModel(by_label={":s0": [good_reply(R, IDS, 0.7)], ":s1": [good_reply(R, IDS, 0.9)],
":s2": [good_reply(R, IDS, 0.8)]})
- j = _judge(model, n_samples=3, cache_dir=cache_dir).judge(judge_input)
+ j = _judge(model, n_samples=3, cache_dir=cache_dir, fixed_order=fixed_order).judge(judge_input)
assert j.n_samples == 3 and j.overall == pytest.approx(0.8) and j.score_std == pytest.approx(0.0816, abs=1e-3)
assert j.usage.cost_usd == pytest.approx(0.003) and j.usage.input_tokens == 3000
- orders = [[p.label for p in image_parts(r)] for r in model.requests]
- assert len({tuple(o) for o in orders}) >= 2 # montage tile order differs between samples
- raw = json.loads(j.raw)
- assert raw["per_sample_overall"] == [0.7, 0.9, 0.8]
- # representative sample (closest to mean) supplies the narrative
- assert j.summary.startswith("A recognisable chair.")
-
-
-def test_fixed_order_sends_the_identical_prompt_to_every_sample(judge_input, cache_dir):
- """The σ the loop keys its stop thresholds to must be the model's re-judge noise; the
- default per-sample shuffle measures view-order robustness instead (JUDGE_NOISE was
- tabulated from that). fixed_order is the mode the calibration battery uses."""
- model = FakeChatModel(by_label={":s0": [good_reply(R, IDS, 0.7)], ":s1": [good_reply(R, IDS, 0.9)],
- ":s2": [good_reply(R, IDS, 0.8)]})
- j = _judge(model, n_samples=3, cache_dir=cache_dir, fixed_order=True).judge(judge_input)
- assert j.n_samples == 3
- orders = [[p.label for p in image_parts(r)] for r in model.requests]
- assert len({tuple(o) for o in orders}) == 1, "every sample must see the montages in the same order"
- assert len({r.system for r in model.requests}) == 1
+ assert json.loads(j.raw)["per_sample_overall"] == [0.7, 0.9, 0.8]
+ assert j.summary.startswith("A recognisable chair.") # the representative sample's narrative
+ orders = {tuple(p.label for p in image_parts(r)) for r in model.requests}
+ assert (len(orders) == 1) if fixed_order else (len(orders) >= 2)
+ if fixed_order:
+ assert len({r.system for r in model.requests}) == 1
def test_floor_fails_even_if_mean_high(judge_input, cache_dir):
@@ -80,45 +59,6 @@ def test_floor_fails_even_if_mean_high(judge_input, cache_dir):
assert "floors: intent_fidelity 0.20<0.30" in j.summary
-def test_caps_from_gates(judge_input, cache_dir):
- judge_input.gates = [GateReport(gate="connectivity", passed=False, findings=[
- GateFinding(gate="connectivity", severity=Severity.ERROR, target="LegBackLeft", message="part floating 30 mm above the rest", data={"kind": "floating"})])]
- model = FakeChatModel([good_reply(R, IDS, 0.9)])
- j = _judge(model, cache_dir=cache_dir).judge(judge_input)
- assert j.overall == 0.6 and not j.passed
- raw = json.loads(j.raw)
- assert raw["caps"]["caps_applied"][0]["rule"] == "floating_part"
- assert raw["overall_uncapped"] == pytest.approx(0.9)
- assert "caps: floating_part≤0.60" in j.summary
-
-
-def test_must_acceptance_missing_fails(judge_input, cache_dir):
- rep = good_reply(R, IDS, 0.9)
- rep["acceptance"]["A1"]["verified"] = False # A1 is must
- j = _judge(FakeChatModel([rep]), cache_dir=cache_dir).judge(judge_input)
- assert not j.passed and j.overall == 0.6 # capped by missing_must_acceptance
- assert "must items unverified: A1" in j.summary
- rep2 = good_reply(R, IDS, 0.9)
- rep2["acceptance"]["A2"]["verified"] = False # A2 is should → no effect on pass
- j2 = _judge(FakeChatModel([rep2]), cache_dir=cache_dir).judge(judge_input)
- assert j2.passed and j2.acceptance_results == {"A1": True, "A2": False}
-
-
-def test_acceptance_majority_vote(judge_input, cache_dir):
- a = good_reply(R, IDS, 0.9)
- a["acceptance"]["A1"]["verified"] = False
- b = good_reply(R, IDS, 0.9)
- c = good_reply(R, IDS, 0.9)
- j = _judge(FakeChatModel([a, b, c]), n_samples=3, cache_dir=cache_dir).judge(judge_input)
- assert j.acceptance_results["A1"] is True and j.passed
- a2 = good_reply(R, IDS, 0.9)
- a2["acceptance"]["A1"]["verified"] = False
- b2 = good_reply(R, IDS, 0.9)
- b2["acceptance"]["A1"]["verified"] = False
- j2 = _judge(FakeChatModel([a2, b2, c]), n_samples=3, cache_dir=cache_dir).judge(judge_input)
- assert j2.acceptance_results["A1"] is False and not j2.passed
-
-
def test_retry_on_parse_failure_then_success(judge_input, cache_dir):
model = FakeChatModel(["not json at all", good_reply(R, IDS, 0.8)])
j = _judge(model, cache_dir=cache_dir).judge(judge_input)
@@ -127,28 +67,13 @@ def test_retry_on_parse_failure_then_success(judge_input, cache_dir):
assert j.usage.cost_usd == pytest.approx(0.002) # failed attempt still charged
-def test_degraded_after_exhausting_attempts(judge_input, cache_dir):
- model = FakeChatModel(default=ModelError("boom", retryable=True))
[email protected](("retryable", "calls"), [(True, 3), (False, 1)])
+def test_a_failing_model_degrades_the_verdict(judge_input, cache_dir, retryable, calls):
+ model = FakeChatModel(default=ModelError("boom", retryable=retryable))
j = _judge(model, cache_dir=cache_dir).judge(judge_input)
assert not j.passed and j.overall == 0.0 and j.summary.startswith("judge_error:")
- assert j.degraded and json.loads(j.raw)["status"] == "degraded"
- assert len(model.requests) == 3 # max_attempts
- assert j.n_samples == 0
-
-
-def test_partial_samples_still_score(judge_input, cache_dir):
- # sample 0 fails all 3 attempts; sample 1 succeeds → judgment from 1 sample, errors recorded
- model = FakeChatModel(["bad", "bad", "bad", good_reply(R, IDS, 0.8)])
- j = _judge(model, n_samples=2, cache_dir=cache_dir).judge(judge_input)
- assert j.passed and j.n_samples == 1
- raw = json.loads(j.raw)
- assert raw["n_requested"] == 2 and raw["n_used"] == 1 and len(raw["sample_errors"]) == 1
-
-
-def test_non_retryable_error_stops_at_once(judge_input, cache_dir):
- model = FakeChatModel(default=ModelError("bad request", retryable=False))
- j = _judge(model, cache_dir=cache_dir).judge(judge_input)
- assert j.degraded and len(model.requests) == 1
+ assert j.degraded and json.loads(j.raw)["status"] == "degraded" and j.n_samples == 0
+ assert len(model.requests) == calls # max_attempts, or at once when not retryable
def test_base_judge_rejects_measured_rubric(judge_input, cache_dir):
@@ -156,25 +81,9 @@ def test_base_judge_rejects_measured_rubric(judge_input, cache_dir):
VlmJudge("reference_v1", chat_model=FakeChatModel(), cache_dir=cache_dir).judge(judge_input)
-def test_missing_render_is_loud(judge_input, cache_dir):
- from codeverse3d.judges.prompt_builder import JudgeImageError
- judge_input.renders.views[0].path = "/nonexistent/x.png"
- with pytest.raises(JudgeImageError):
- _judge(FakeChatModel([good_reply(R, IDS)]), cache_dir=cache_dir).judge(judge_input)
-
-
-def test_no_acceptance_items(judge_input, cache_dir):
- judge_input.acceptance = []
- model = FakeChatModel([good_reply(R, [], 0.8)])
- j = _judge(model, cache_dir=cache_dir).judge(judge_input)
- assert j.passed and j.acceptance_results == {}
- assert "acceptance" not in model.requests[0].response_schema["properties"]
-
-
# --------------------------------------------------------------- payload size (docs/COST.md §3)
def test_judge_payload_size_comes_from_the_settings_dial(monkeypatch):
- """``Settings.judge`` (set coherently by a cost profile) sizes the verdict's
- images unless the caller states its own."""
+ """``Settings.judge`` sizes the verdict's images unless the caller states its own (docs/COST.md §3)."""
from codeverse3d.config import Settings, get_settings
from codeverse3d.judges.vlm_judge import VlmJudge
@@ -182,9 +91,7 @@ def test_judge_payload_size_comes_from_the_settings_dial(monkeypatch):
s.apply_profile("economy", force=True)
monkeypatch.setattr("codeverse3d.judges.vlm_judge.get_settings", lambda: s)
j = VlmJudge(rubric="static_object_v1", model_id="fake:fake-1")
- # no profile shrinks the payload: 768 px bills the same as 1024 on Gemini and is
- # noisier, the 2→1 crop cut did not survive a second draw (docs/COST.md §14), and
- # fewer than 5 montages would silently drop the rig's low ring + poles (D47)
+ # no profile shrinks the payload (docs/COST.md §14, D47)
assert j.max_px == 1024 and j.detail_crops == 2 and j.max_montages == 5
# a caller that states a size still gets it — the dial is the default, not a cap
explicit = VlmJudge(rubric="static_object_v1", model_id="fake:fake-1", max_px=768, detail_crops=1)
@@ -230,7 +137,7 @@ def test_judge_prompt_hash_tracks_the_protocol_not_the_run(monkeypatch):
assert judge_prompt_hash(R) not in (base, edited_role)
-# -------------------------------------------------------- per-sample retry budget (audit 2026-08-26 §5.1)
+# ---------------------------------------------------------------------- per-sample retry budget
def _fake_clock(monkeypatch):
import time as real_time
from types import SimpleNamespace
@@ -243,26 +150,6 @@ def _fake_clock(monkeypatch):
return clock
-def test_each_sample_has_a_retry_budget_and_hands_what_is_left_to_the_model(judge_input, cache_dir, monkeypatch):
- """The verdict call is 42 s p50 / 73 s p90 on a normal day, 50 / 103 s under a storm
- (audit 2026-08-26 §2); two storm-day rounds lost 1 162 s and 927 s to 3 x 300 s timeouts
- before a second sample answered in 128 s. A sample now has SAMPLE_BUDGET_S = 240 s for all
- its attempts, and every attempt tells the model how much of it remains."""
- from codeverse3d.judges.vlm_judge import SAMPLE_BUDGET_S
-
- clock = _fake_clock(monkeypatch)
-
- def slow_503(request):
- clock["t"] += 100.0
- return ModelError("503 high demand", retryable=True, status=503)
-
- model = FakeChatModel([slow_503, slow_503, good_reply(R, IDS, 0.8)])
- j = _judge(model, cache_dir=cache_dir).judge(judge_input)
- assert j.passed and len(model.requests) == 3
- # each retry gets what is LEFT of the sample budget (the fake clock burns 100 s a call)
- assert [r.max_wait_s for r in model.requests] == [SAMPLE_BUDGET_S, SAMPLE_BUDGET_S - 100.0, SAMPLE_BUDGET_S - 200.0]
-
-
def test_a_sample_stops_when_its_budget_is_spent(judge_input, cache_dir, monkeypatch):
from codeverse3d.judges.vlm_judge import SAMPLE_BUDGET_S
@@ -286,7 +173,6 @@ def test_a_sample_stops_when_its_budget_is_spent(judge_input, cache_dir, monkeyp
def test_the_last_attempt_still_gets_a_real_try(judge_input, cache_dir, monkeypatch):
- """A few seconds of budget would be a deadline the model cannot use; the floor is 20 s."""
from codeverse3d.judges.vlm_judge import SAMPLE_BUDGET_S, SAMPLE_MIN_WAIT_S
clock = _fake_clock(monkeypatch)
@@ -301,8 +187,7 @@ def test_the_last_attempt_still_gets_a_real_try(judge_input, cache_dir, monkeypa
def test_scene_and_graphics_keep_the_pre_d47_montage_ceiling():
- """PR #3 review: montages 3→5 was measured only on the D47 object rig; the other
- tracks keep 3 until someone measures them, and an explicit caller value wins."""
+ """D47's 5 montages were measured on the object rig only; the other tracks keep 3."""
from codeverse3d.contracts.artifacts import RenderSet
from codeverse3d.contracts.common import Language, Track
from codeverse3d.contracts.spec import Spec
diff --git a/harness/tests/reference/test_attach.py b/harness/tests/reference/test_attach.py
index 756f2c7b..793a2038 100644
--- a/harness/tests/reference/test_attach.py
+++ b/harness/tests/reference/test_attach.py
@@ -4,6 +4,8 @@ from __future__ import annotations
from pathlib import Path
+import pytest
+
from codeverse3d.contracts.spec import ReferenceImage
from codeverse3d.reference import (
SYNTH_NOTE,
@@ -49,14 +51,9 @@ def test_attach_marks_synthesized_everywhere_and_keeps_constraints(tmp_path: Pat
assert spec.references == [] # the input spec is not mutated
-def test_front_elevation_is_the_silhouette_target(tmp_path: Path):
- """The gate measures IoU against a straight-on render, so the straight-on photo
- must be the ``target`` and the 3/4 shot only a ``detail`` image."""
- refs = reference_images(_set(tmp_path, ("three_quarter", "front")))
- assert [r.role for r in refs] == ["target", "detail"]
- assert Path(refs[0].path).name == "front.png"
-
-
-def test_three_quarter_is_the_target_when_it_is_the_only_survivor(tmp_path: Path):
- refs = reference_images(_set(tmp_path, ("three_quarter", "front"), accepted=(True, False)))
- assert len(refs) == 1 and refs[0].role == "target" and Path(refs[0].path).name == "three_quarter.png"
[email protected](("accepted", "target"), [((True, True), "front.png"), ((True, False), "three_quarter.png")])
+def test_the_straight_on_photo_is_the_silhouette_target(tmp_path: Path, accepted, target):
+ """The gate measures IoU against a straight-on render; the 3/4 shot is the target only when alone."""
+ refs = reference_images(_set(tmp_path, ("three_quarter", "front"), accepted=accepted))
+ assert refs[0].role == "target" and Path(refs[0].path).name == target
+ assert [r.role for r in refs[1:]] == ["detail"] * (len(refs) - 1) and len(refs) == sum(accepted)
diff --git a/harness/tests/reference/test_judge_diff.py b/harness/tests/reference/test_judge_diff.py
index 24a0a68f..ed334cff 100644
--- a/harness/tests/reference/test_judge_diff.py
+++ b/harness/tests/reference/test_judge_diff.py
@@ -45,23 +45,15 @@ def _judge(model, **kw):
**kw)
-def test_diff_pass_reaches_the_scoring_call(ref_input, cache_dir):
+def test_the_diff_and_the_synthesized_caveat_reach_the_scoring_call(ref_input, cache_dir):
model = FakeChatModel(by_label={"reference_diff": [DIFF], "judge": [good_reply(REF, ["A1", "A2"], 0.8)]})
- j = _judge(model, cache_dir=cache_dir).judge(ref_input)
- assert j.overall > 0
+ assert _judge(model, cache_dir=cache_dir).judge(ref_input).overall > 0
scoring = [r for r in model.requests if r.label.startswith("judge")][0]
text = scoring.messages[0].parts[0].text
assert "REFERENCE DIFF" in text and "reference shows 4 legs, render shows 2" in text
assert "already matching: the backrest slats are right" in text
-
-
-def test_synthesized_reference_is_labelled_and_caveated(ref_input, cache_dir):
- model = FakeChatModel(by_label={"reference_diff": [DIFF], "judge": [good_reply(REF, ["A1", "A2"], 0.8)]})
- _judge(model, cache_dir=cache_dir).judge(ref_input)
- scoring = [r for r in model.requests if r.label.startswith("judge")][0]
assert image_parts(scoring)[0].label.startswith("SYNTHESIZED REFERENCE 1/1 (target)")
- assert "SYNTHESIZED from the brief" in scoring.messages[0].parts[0].text
- assert "the BRIEF is correct" in scoring.messages[0].parts[0].text
+ assert "SYNTHESIZED from the brief" in text and "the BRIEF is correct" in text
def test_a_failing_diff_never_breaks_the_verdict(ref_input, cache_dir):
@@ -79,31 +71,15 @@ def test_diff_can_be_switched_off(ref_input, cache_dir):
@pytest.mark.parametrize(("value", "diffed"), [("off", False), ("OFF", False), ("of", True)])
def test_diff_off_via_env(ref_input, cache_dir, switch, value, diffed):
- """``C3D_REFERENCE_DIFF=off`` switches the pass off; a typo warns and keeps the default
- (ON) — the arm that never set the switch, which is what D44 (c) asks of a typo."""
+ """D44 (c): ``C3D_REFERENCE_DIFF=off`` switches the pass off; a typo keeps the default (on)."""
switch("C3D_REFERENCE_DIFF", value)
model = FakeChatModel(by_label={"reference_diff": [DIFF], "judge": [good_reply(REF, ["A1", "A2"], 0.8)]})
_judge(model, cache_dir=cache_dir).judge(ref_input)
assert any(r.label.startswith("reference_diff") for r in model.requests) is diffed
-def test_best_view_iou_beats_a_fixed_front_view(ref_input, cache_dir, tmp_path):
- """The default silhouette fn is the real one, so the judge scores the render view
- that best matches the reference's camera and says which one it used."""
- model = FakeChatModel(by_label={"reference_diff": [DIFF], "judge": [good_reply(REF, ["A1", "A2"], 0.8)]})
- j = ReferenceJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir)
- verdict = j.judge(ref_input)
- scoring = [r for r in model.requests if r.label.startswith("judge")][0]
- text = scoring.messages[0].parts[0].text
- assert "MEASURED SILHOUETTE" in text and verdict.scores["silhouette_match"] > 0
- info = j.measure_silhouette(ref_input)
- assert info["render"] in {v.name for v in ref_input.renders.views}
- assert info["iou"] == max(info["per_view"].values())
-
-
def test_reference_that_contradicts_the_brief_scores_neutral(tmp_path, cache_dir):
- """A picture whose proportions disagree with the stated dimensions must not drag
- the score down: the brief wins and the measured criterion goes neutral."""
+ """The brief wins: the measured criterion goes neutral."""
from codeverse3d.contracts.spec import Constraints
from codeverse3d.judges.vlm_judge import NEUTRAL_SCORE
@@ -122,8 +98,7 @@ def test_reference_that_contradicts_the_brief_scores_neutral(tmp_path, cache_dir
def test_the_diff_call_names_every_part_of_an_articulated_plan(ref_input, cache_dir):
- """The part list came from a regex over plan_summary, whose articulated digest runs on
- 'Parts: Base, Lid. Root link Base. Joints: …' — so the last part was always dropped."""
+ """The part list comes from the plan, not a regex over plan_summary (which dropped the last part)."""
from codeverse3d.contracts.plan import ArticulatedPlan
from codeverse3d.contracts.run import RoundRecord
from codeverse3d.contracts.spec import Track
diff --git a/harness/tests/reference/test_mismatch.py b/harness/tests/reference/test_mismatch.py
index be67f0cf..fe2cee65 100644
--- a/harness/tests/reference/test_mismatch.py
+++ b/harness/tests/reference/test_mismatch.py
@@ -44,11 +44,6 @@ def test_compare_names_mismatches_and_builds_text(tmp_path: Path):
assert labels == ["REFERENCE 1", "RENDER 1 (ren)"]
assert "Hopper, Body" in req.messages[0].parts[0].text
assert "the BRIEF wins" in req.messages[0].parts[0].text # synthesized caveat
-
-
-def test_top_orders_by_severity(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": [ANSWER]}))
assert [m.severity for m in d.top(3)] == ["critical", "major", "minor"]
diff --git a/harness/tests/reference/test_proportions.py b/harness/tests/reference/test_proportions.py
index fb042535..014dda71 100644
--- a/harness/tests/reference/test_proportions.py
+++ b/harness/tests/reference/test_proportions.py
@@ -14,7 +14,6 @@ from codeverse3d.reference import (
expected_aspect_range,
expected_front_aspect,
)
-from codeverse3d.spatial.silhouette import silhouette_aspect
from tests.reference.conftest import make_spec
@@ -26,11 +25,6 @@ def _box(path: Path, w: int, h: int) -> Path:
return path
-def test_silhouette_aspect(tmp_path: Path):
- assert silhouette_aspect(_box(tmp_path / "a.png", 100, 200)) == pytest.approx(0.5, abs=0.02)
- assert silhouette_aspect(_box(tmp_path / "b.png", 200, 100)) == pytest.approx(2.0, abs=0.08)
-
-
def test_expected_aspect_is_a_band_over_every_horizontal_extent():
"""A brief never says which face a photo shows, so the expectation is a range."""
from codeverse3d.contracts.spec import Constraints
@@ -44,26 +38,23 @@ def test_expected_aspect_is_a_band_over_every_horizontal_extent():
assert expected_aspect_range(make_spec(constraints=Constraints(dimensions_m={"height": 0.65}))) is None
-def test_a_slightly_wide_photo_inside_the_band_is_not_a_conflict(tmp_path: Path):
- """The measured chair case: brief band 0.50-0.56, photo 0.64 -> 16 % outside, kept."""
- from codeverse3d.contracts.spec import Constraints
+CHAIR = {"width": 0.45, "depth": 0.50, "height": 0.9}
- chair = make_spec(constraints=Constraints(dimensions_m={"width": 0.45, "depth": 0.50, "height": 0.9}))
- info = dimension_conflict(chair, _box(tmp_path / "chair.png", 128, 200)) # 0.64 w/h
- assert not info["conflict"] and info["relative_error"] < ASPECT_TOL
[email protected](("dims", "w", "h"), [
+ (None, 100, 200), # brief implies 0.467 w/h; the picture is 0.5 → 7 % off
+ (CHAIR, 128, 200), # the measured chair: band 0.50-0.56, photo 0.64 → 16 % outside, kept
+])
+def test_a_photo_within_the_tolerance_is_not_a_conflict(tmp_path: Path, dims, w, h):
+ from codeverse3d.contracts.spec import Constraints
-def test_agreeing_picture_is_no_conflict(tmp_path: Path):
- # brief implies 0.467 w/h; the picture is 0.5 → 7% off
- info = dimension_conflict(make_spec(), _box(tmp_path / "ok.png", 100, 200))
- assert not info["conflict"] and info["relative_error"] < ASPECT_TOL
- assert info["expected_range"] == [0.14 / 0.30, 0.14 / 0.30]
- assert conflict_note(info) == ""
+ spec = make_spec(constraints=Constraints(dimensions_m=dims)) if dims else make_spec()
+ info = dimension_conflict(spec, _box(tmp_path / "p.png", w, h))
+ assert not info["conflict"] and info["relative_error"] < ASPECT_TOL and conflict_note(info) == ""
def test_the_coffee_grinder_case_is_flagged(tmp_path: Path):
- """The real failure: the brief says 0.14 x 0.30 (0.47 w/h) but the studio photo
- includes the crank arm and comes out near 0.70 — 49 % wider than the brief."""
+ """The brief says 0.47 w/h; the studio photo includes the crank arm and is ~0.70."""
info = dimension_conflict(make_spec(), _box(tmp_path / "crank.png", 210, 300))
assert info["conflict"] and info["relative_error"] > 0.4
note = conflict_note(info)
@@ -71,12 +62,6 @@ def test_the_coffee_grinder_case_is_flagged(tmp_path: Path):
assert "0.47-0.47" in note
-def test_no_stated_dimensions_is_never_a_conflict(tmp_path: Path):
- from codeverse3d.contracts.spec import Constraints
- spec = make_spec(constraints=Constraints())
- assert dimension_conflict(spec, _box(tmp_path / "x.png", 300, 100))["conflict"] is False
-
-
def test_unreadable_image_is_never_a_conflict(tmp_path: Path):
info = dimension_conflict(make_spec(), tmp_path / "missing.png")
assert info["conflict"] is False and info["error"]
diff --git a/harness/tests/reference/test_run_and_cli.py b/harness/tests/reference/test_run_and_cli.py
index c420346d..cb5957fd 100644
--- a/harness/tests/reference/test_run_and_cli.py
+++ b/harness/tests/reference/test_run_and_cli.py
@@ -72,12 +72,3 @@ def test_cli_flag_calls_the_grounding_and_never_kills_the_run(tmp_path: Path, mo
"--runs-dir", str(tmp_path), "--no-run"])
assert res.exit_code == 0, res.output
assert seen["n_views"] == 1 and "reference grounding: nope" in res.output
-
-
-def test_cli_without_the_flag_never_touches_the_reference_package(tmp_path: Path, monkeypatch):
- from codeverse3d.cli.main import app
-
- monkeypatch.setattr("codeverse3d.reference.ground_spec",
- lambda *a, **k: (_ for _ in ()).throw(AssertionError("must not be called")))
- res = CliRunner().invoke(app, ["make", "a stool", "--runs-dir", str(tmp_path), "--no-run"])
- assert res.exit_code == 0, res.output
diff --git a/harness/tests/reference/test_silhouette_best_view.py b/harness/tests/reference/test_silhouette_best_view.py
index 56785c0e..7d3390e8 100644
--- a/harness/tests/reference/test_silhouette_best_view.py
+++ b/harness/tests/reference/test_silhouette_best_view.py
@@ -26,16 +26,6 @@ def _views(tmp: Path) -> list[RenderView]:
for n, b in boxes.items()]
-def test_picks_the_matching_view_not_the_first(tmp_path: Path) -> None:
- ref = _shape(tmp_path / "ref.png", (20, 95, 236, 165)) # wide and flat
- res = best_view_match(_views(tmp_path / "r"), ref)
- assert res["view"] == "right"
- assert res["iou"] == max(res["per_view"].values())
- assert set(res["per_view"]) == {"front", "front_right_high", "right"}
- # the fixed-front comparison would have scored much worse
- assert res["iou"] > res["per_view"]["front"] + 0.2
-
-
def test_candidate_filter_excludes_top_and_low_cameras(tmp_path: Path) -> None:
assert "top" not in CANDIDATE_VIEWS and "bottom" not in CANDIDATE_VIEWS
assert "low_front_left" not in CANDIDATE_VIEWS and "front_right_low" not in CANDIDATE_VIEWS
diff --git a/harness/tests/texturing/test_apply.py b/harness/tests/texturing/test_apply.py
index 122b7b6a..c3b3cbae 100644
--- a/harness/tests/texturing/test_apply.py
+++ b/harness/tests/texturing/test_apply.py
@@ -8,19 +8,12 @@ import numpy as np
import trimesh
from codeverse3d.spatial.measure import measure_glb
-from codeverse3d.texturing.apply import apply_textures, node_part_lookup
+from codeverse3d.texturing.apply import apply_textures
from codeverse3d.texturing.generate import generate_textures
from codeverse3d.texturing.plan import default_plan
from tests.texturing.conftest import FakeImageModel
-def test_node_part_lookup_instances_and_links(chair_plan):
- tp = default_plan(chair_plan)
- lk = node_part_lookup(["Seat", "Leg_0", "Leg_3", "Knob", "Back__1", "Mystery"], tp.by_part())
- assert lk["Leg_0"].part == "Leg" and lk["Leg_3"].part == "Leg" and lk["Back__1"].part == "Back"
- assert lk["Mystery"] is None
-
-
def test_apply_textures_end_to_end(tmp_path: Path, chair_glb: Path, chair_plan):
tp = default_plan(chair_plan)
ts = generate_textures(tp, tmp_path / "tex", FakeImageModel(), size=64, cache_dir=tmp_path / "c")
diff --git a/harness/tests/texturing/test_gate.py b/harness/tests/texturing/test_gate.py
index ddd3f741..0128928c 100644
--- a/harness/tests/texturing/test_gate.py
+++ b/harness/tests/texturing/test_gate.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from pathlib import Path
-from codeverse3d.texturing.generate import TextureAsset, judge_gate, material_criterion, seam_gate
+from codeverse3d.texturing.generate import TextureAsset, judge_gate, material_criterion
from tests.texturing.conftest import FakeJudge, fake_render
@@ -12,13 +12,6 @@ def _asset(tid: str, seam: float, ok_path: Path) -> TextureAsset:
return TextureAsset(texture_id=tid, path=str(ok_path), prompt="p", prompt_hash="h", seam_score=seam)
-def test_seam_gate(tmp_path: Path):
- p = tmp_path / "a.png"
- p.write_bytes(b"x")
- res = seam_gate({"a": _asset("a", 0.01, p), "b": _asset("b", 0.5, p), "c": _asset("c", 0.0, tmp_path / "none.png")})
- assert res.passed == {"a": 0.01} and res.failed == {"b": 0.5}
-
-
def test_material_criterion_lookup():
assert material_criterion({"intent_fidelity": 1, "materials": 0.5}) == "materials"
assert material_criterion({"a": 1, "materials_shaders_effects": 0.2}) == "materials_shaders_effects"
@@ -34,14 +27,6 @@ def _run(tmp_path, chair_spec, chair_plan, chair_glb, verdicts, **kw):
return res
-def test_judge_gate_ships_on_material_gain(tmp_path, chair_spec, chair_plan, chair_glb):
- res = _run(tmp_path, chair_spec, chair_plan, chair_glb,
- [(0.70, {"materials": 0.6, "x": 0.7}), (0.71, {"materials": 0.7, "x": 0.7})])
- assert res.shipped and res.delta == 0.01 and res.materials_delta == 0.1 and res.materials_criterion == "materials"
- assert res.renders_before and res.renders_after and res.usage.cost_usd == 0.02
- assert Path(res.renders_after.contact_sheet).is_file()
-
-
def test_judge_gate_rejects_overall_drop_or_flat_materials(tmp_path, chair_spec, chair_plan, chair_glb):
res = _run(tmp_path, chair_spec, chair_plan, chair_glb, [(0.70, {"materials": 0.6}), (0.65, {"materials": 0.9})])
assert not res.shipped and "Δoverall" in res.reason
diff --git a/harness/tests/texturing/test_generate.py b/harness/tests/texturing/test_generate.py
index 2f50c3a7..d2501e85 100644
--- a/harness/tests/texturing/test_generate.py
+++ b/harness/tests/texturing/test_generate.py
@@ -27,14 +27,6 @@ def test_generate_dedupes_caches_and_accounts(tmp_path: Path):
assert len(model.calls) == 2 and ts2.usage.cost_usd == 0.0 and all(a.cached for a in ts2.textures.values())
-def test_generate_records_failures_per_texture(tmp_path: Path):
- model = FakeImageModel(fail_on=("forbidden",))
- ts = generate_textures({"ok": "oak", "bad": "forbidden pattern"}, tmp_path, model, size=64, cache_dir=tmp_path / "c")
- assert ts.textures["ok"].ok and not ts.textures["bad"].ok
- assert "ModelError" in ts.textures["bad"].error and ts.failed() == {"bad": ts.textures["bad"].error}
- assert set(ts.paths()) == {"ok"}
-
-
def test_generate_accepts_texture_plan_and_empty(tmp_path: Path, chair_plan):
from codeverse3d.texturing.plan import default_plan
@@ -45,8 +37,7 @@ def test_generate_accepts_texture_plan_and_empty(tmp_path: Path, chair_plan):
def test_seed_is_part_of_the_cache_key(tmp_path: Path):
- """seed=2 used to be served seed=1's cached pixels: the key omitted the seed, so
- any caller varying it got silently identical textures (V9b)."""
+ """V9b: seed=2 must not be served seed=1's cached pixels."""
model = FakeImageModel(usd_per_image=0.01)
generate_textures({"oak": "oak wood grain"}, tmp_path / "o1", model, size=64, cache_dir=tmp_path / "c", seed=1)
ts2 = generate_textures({"oak": "oak wood grain"}, tmp_path / "o2", model, size=64, cache_dir=tmp_path / "c", seed=2)
diff --git a/harness/tests/texturing/test_maps.py b/harness/tests/texturing/test_maps.py
index 1c1d8303..53ba8e55 100644
--- a/harness/tests/texturing/test_maps.py
+++ b/harness/tests/texturing/test_maps.py
@@ -6,15 +6,9 @@ import numpy as np
from PIL import Image
from codeverse3d.texturing.apply import (
- DEFAULT_VARIATION,
- VARIATION,
- is_flat,
metallic_roughness_image,
normal_image,
- roughness_array,
- variation_for,
)
-from codeverse3d.texturing.materials import MATERIALS
def _grain(size: int = 64) -> Image.Image:
@@ -26,29 +20,6 @@ def _grain(size: int = 64) -> Image.Image:
return Image.fromarray(np.round(rgb * 255).astype(np.uint8), mode="RGB")
-def test_every_table_family_has_a_variation_row():
- assert set(VARIATION) == set(MATERIALS)
- assert variation_for("no_such_family") == DEFAULT_VARIATION
- assert variation_for("cast_iron")[0] > variation_for("chrome")[0] # pitted iron varies more
-
-
-def test_roughness_follows_the_grain_dark_is_rough():
- img = _grain()
- r = roughness_array(img, 0.45, "hardwood")
- assert r.shape == (64, 64) and r.min() >= 0.0 and r.max() <= 1.0
- lum = np.asarray(img.convert("L"), dtype=np.float32)[0]
- assert r[0][lum.argmin()] > r[0][lum.argmax()], "dark bands must be rougher than bright ones"
- assert abs(float(r.mean()) - 0.45) < 0.06, "the base roughness must survive as the mean"
- quiet = roughness_array(img, 0.45, "chrome")
- assert quiet.std() < r.std(), "the family amplitude controls how far roughness swings"
-
-
-def test_roughness_is_clamped_for_extreme_bases():
- img = _grain()
- assert roughness_array(img, 0.0, "cast_iron").min() >= 0.0
- assert roughness_array(img, 1.0, "cast_iron").max() <= 1.0
-
-
def test_metallic_roughness_image_uses_the_gltf_channel_packing():
img = _grain()
mr = metallic_roughness_image(img, 0.62, 1.0, "cast_iron")
@@ -68,8 +39,3 @@ def test_normal_map_is_tangent_space_and_tiles():
assert abs(float(n[:, 0, 0].mean() - n[:, -1, 0].mean())) < 0.35
flat = normal_image(img, "cast_iron", strength=0.0)
assert np.asarray(flat)[..., 0].std() < 1e-6
-
-
-def test_flat_tiles_are_detected_so_no_noise_maps_are_written():
- assert is_flat(Image.new("RGB", (32, 32), (120, 90, 40)))
- assert not is_flat(_grain())
diff --git a/harness/tests/texturing/test_materials.py b/harness/tests/texturing/test_materials.py
index 62deee5d..c01a9f2c 100644
--- a/harness/tests/texturing/test_materials.py
+++ b/harness/tests/texturing/test_materials.py
@@ -9,7 +9,6 @@ from codeverse3d.texturing.materials import (
COARSE_TO_FINE,
MATERIALS,
family_for,
- is_framework_default,
is_warm_metal_hue,
looks_painted,
out_of_band,
@@ -31,8 +30,6 @@ def test_every_family_is_self_consistent():
def test_coarse_families_of_the_texture_planner_all_resolve():
- """plan.py speaks 11 coarse families; every one must map to a row here, or the
- texture pass and the normaliser would disagree about the same surface."""
assert set(COARSE_TO_FINE) == set(FAMILY_DEFAULTS)
for coarse, fine in COARSE_TO_FINE.items():
assert fine in MATERIALS, coarse
@@ -59,23 +56,13 @@ def test_family_for_resolves_substrate_then_finish(text, family):
def test_family_for_prefers_the_first_text_that_resolves():
- """The material's own name outranks the plan's prose: a chrome steam wand must
- not become silicone because the plan sentence mentions a silicone tip."""
+ """The material's own name outranks the plan's prose."""
assert family_for("SteamWandChrome", "SteamWand", "chrome wand with a silicone tip").family == "chrome"
assert family_for("Unnamed", "SteamWand", "silicone tip").family == "rubber"
assert family_for("", "", "") is None
assert family_for("Widget42") is None
-def test_framework_defaults_are_the_untouched_pairs():
- assert is_framework_default(None, None) # glTF omits 1.0/1.0
- assert is_framework_default(1.0, 1.0)
- assert is_framework_default(0.0, 1.0) # three MeshStandardMaterial
- assert is_framework_default(0.0, 0.5) # Blender Principled
- assert not is_framework_default(0.0, 0.45)
- assert not is_framework_default(0.95, 0.15)
-
-
def test_out_of_band_names_the_offending_factor():
chrome = MATERIALS["chrome"]
assert out_of_band(chrome, 0.95, 0.10) == []
diff --git a/harness/tests/texturing/test_normalise.py b/harness/tests/texturing/test_normalise.py
index 00d88fba..b685dab8 100644
--- a/harness/tests/texturing/test_normalise.py
+++ b/harness/tests/texturing/test_normalise.py
@@ -7,7 +7,6 @@ from pathlib import Path
import trimesh
from PIL import Image
-from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan
from codeverse3d.spatial.measure import load_scene, measure_glb
from codeverse3d.texturing.apply import classify, normalise_materials
@@ -32,30 +31,10 @@ def _glb(tmp_path: Path, rows) -> Path:
# --------------------------------------------------------------------------- classify
-def test_untouched_defaults_snap_to_the_family_numbers():
- v = classify("Seat", "OakSeat", "", 0.0, 0.5) # Blender Principled default
- assert v is not None and v.reason == "untouched" and v.family == "hardwood"
- assert (v.metallic, v.roughness) == (0.0, 0.45)
- v = classify("Rail", "ChromeRail", "", None, None) # glTF default (1.0 / 1.0)
- assert v.reason == "untouched" and (v.metallic, v.roughness) == (1.0, 0.06)
-
-
-def test_impossible_values_are_only_clamped_to_the_band_edge():
- v = classify("Post", "CastIronPost", "", 0.20, 0.65)
- assert v.reason == "impossible" and v.metallic == 0.5 and v.roughness == 0.65 # roughness kept
- assert classify("Post", "CastIronPost", "", 0.85, 0.65) is None # already plausible
-
-
-def test_plausible_material_is_left_alone():
- assert classify("Bit", "PolishedSteelBit", "", 0.98, 0.15) is None
- assert classify("Body", "VarnishedBeechBody", "", 0.0, 0.38) is None
def test_plan_prose_may_only_fix_a_never_configured_default():
- """The plan's ``material`` string describes a whole part, so it is weak evidence:
- good enough to spot an untouched default, never good enough to overrule numbers
- somebody actually typed (an aluminium lid piece must not become glass because the
- part's sentence mentions a glass display)."""
+ """The plan's prose may spot an untouched default, never overrule typed numbers."""
assert classify("lid__0", "SpaceGray", "glass display panel in an aluminium lid", 0.88, 0.30) is None
v = classify("lid__0", "SpaceGray", "glass display panel", 0.0, 1.0)
assert v is not None and v.reason == "untouched" and v.family == "glass"
@@ -68,10 +47,6 @@ def test_a_saturated_colour_turns_bare_iron_into_paint():
assert grey is not None and grey.family == "cast_iron" and grey.metallic == 0.5
-def test_unknown_material_names_are_never_touched():
- assert classify("Widget", "Mat.001", "", 0.0, 0.5) is None
-
-
# --------------------------------------------------------------------------- the pass
def test_normalise_materials_rewrites_only_the_factors(tmp_path: Path):
glb = _glb(tmp_path, [
@@ -115,15 +90,3 @@ def test_a_textured_material_is_never_second_guessed(tmp_path: Path):
scene.export(textured)
rep = normalise_materials(textured, tmp_path / "out.glb")
assert not rep.changed() and rep.n_unchanged == 1
-
-
-def test_plan_material_strings_resolve_parts_with_neutral_names(tmp_path: Path):
- glb = _glb(tmp_path, [("Frame", "Mat.002", 0.0, 1.0, (90, 90, 95, 255))])
- plan = StaticPlan(
- object_name="Thing", summary="s",
- overall_bbox=BBox(center=(0, 0, 0), extents=(1, 1, 1)),
- parts=[PartPlan(name="Frame", role="frame", description="d",
- bbox=BBox(center=(0, 0, 0), extents=(1, 1, 1)), material="powder-coated steel")],
- )
- rep = normalise_materials(glb, tmp_path / "out.glb", plan=plan)
- assert [c.family for c in rep.changes] == ["painted_metal"]
diff --git a/harness/tests/texturing/test_plan.py b/harness/tests/texturing/test_plan.py
index 36756b1a..ded5d4d9 100644
--- a/harness/tests/texturing/test_plan.py
+++ b/harness/tests/texturing/test_plan.py
@@ -8,16 +8,13 @@ import pytest
from PIL import Image
from codeverse3d.texturing.plan import (
- STYLE_SUFFIX,
PlannerOutput,
PlannerPart,
TexturePlan,
compose_image_prompt,
- default_plan,
family_from_text,
finalize_plan,
material_plan,
- plan_table,
)
from tests.orchestrator_tracks.fakes import FakeChatModel
@@ -29,19 +26,6 @@ def test_family_keywords_are_whole_words():
assert family_from_text("oiled") == "other" # 'led' must not match
-def test_default_plan_shares_ids_and_skips(chair_plan):
- tp = default_plan(chair_plan)
- by = tp.by_part()
- assert by["seat"].texture_id == by["back"].texture_id # same material → same texture
- assert by["seat"].material_family == "wood" and by["leg"].material_family == "metal"
- assert by["leg"].metallic == 1.0 and by["leg"].roughness < 0.5
- assert by["knob"].skip # tiny + glass
- assert len(tp.texture_ids()) == 2
- assert tp.source == "default"
- assert STYLE_SUFFIX in by["seat"].prompt and "oak" in by["seat"].prompt
- assert "Seat" in plan_table(tp)
-
-
def test_finalize_plan_defaults_and_unification(chair_plan):
out = PlannerOutput(parts=[
PlannerPart(part="Seat", texture_id="oak", material_family="wood", subject="light oak, straight grain"),
@@ -95,7 +79,3 @@ def test_material_plan_invalid_payload_fails_loud(tmp_path, chair_plan, chair_sp
chat = FakeChatModel(default={"nope": 1})
with pytest.raises(ValueError):
material_plan(chair_spec, chair_plan, None, "fake:fake", model=chat, cache_dir=tmp_path, use_cache=False)
-
-
-def test_material_plan_without_model_is_default(chair_plan, chair_spec):
- assert material_plan(chair_spec, chair_plan, None, "").source == "default"
diff --git a/harness/tests/texturing/test_run.py b/harness/tests/texturing/test_run.py
index c10b8f75..47be0237 100644
--- a/harness/tests/texturing/test_run.py
+++ b/harness/tests/texturing/test_run.py
@@ -51,19 +51,6 @@ def test_texture_pass_ships_and_records(tmp_path, chair_glb, chair_spec, chair_p
assert latest_sheet(ws) is None and (ws.artifacts / "textures" / "planner_views" / "sheet.png").is_file()
-def test_texture_pass_not_shipped_keeps_report_but_no_canonical_glb(tmp_path, chair_glb, chair_spec, chair_plan):
- ws = _ws(tmp_path, chair_glb, chair_spec, chair_plan)
- (ws.artifacts / "object_textured.glb").write_bytes(b"stale earlier pass") # e.g. a pass that DID ship before
- judge = FakeJudge([(0.70, {"materials": 0.6}), (0.60, {"materials": 0.6})])
- rep = texture_pass(ws, chair_spec, chair_plan, model_id="", image_model=FakeImageModel(), judge_obj=judge,
- render=fake_render, cache_dir=tmp_path / "cache")
- assert not rep.shipped and rep.gate is not None and rep.glb_out.endswith("object_textured.glb")
- # not shipped → NO canonical object_textured.glb, not even the earlier pass's;
- # the report keeps all its fields (glb_out names the canonical home)
- assert not (ws.artifacts / "object_textured.glb").exists()
- assert json.loads(ws.record_path.read_text())["extra"]["texturing"]["shipped"] is False
-
-
def test_texture_pass_no_judge_and_all_failed(tmp_path, chair_glb, chair_spec, chair_plan):
ws = _ws(tmp_path, chair_glb, chair_spec, chair_plan)
rep = texture_pass(ws, chair_spec, chair_plan, model_id="", image_model=FakeImageModel(), judge=False, render=fake_render,
diff --git a/harness/tests/texturing/test_scene_pack.py b/harness/tests/texturing/test_scene_pack.py
index 638527d6..7ad4392c 100644
--- a/harness/tests/texturing/test_scene_pack.py
+++ b/harness/tests/texturing/test_scene_pack.py
@@ -9,7 +9,6 @@ import pytest
from codeverse3d.contracts.plan import AssetPlan, BBox, CameraPlan, ScenePlan, ZonePlan
from codeverse3d.texturing.plan import (
- default_scene_pack_plan,
scene_pack_plan,
scene_texture_pack,
texture_pack_prompt,
@@ -31,14 +30,6 @@ def garden_plan() -> ScenePlan:
)
-def test_default_pack_plan_picks_keywords(garden_plan):
- entries = default_scene_pack_plan(garden_plan, n_min=6, n_max=12)
- names = [e.name for e in entries]
- assert "moss_ground" in names and "fine_gravel" in names and "pond_bed" in names and "weathered_planks" in names
- assert 6 <= len(entries) <= 12 and len(set(names)) == len(names)
- assert all(e.prompt.endswith("1:1 square") and e.tile_size_m > 0 for e in entries)
-
-
def test_scene_pack_plan_with_model_and_cap(garden_plan):
payload = {"textures": [
{"name": "Moss Ground", "material_family": "other", "subject": "green moss carpet", "tile_size_m": 1.2, "role": "ground"},
diff --git a/harness/tests/texturing/test_tile.py b/harness/tests/texturing/test_tile.py
index 58625e34..0315ca3f 100644
--- a/harness/tests/texturing/test_tile.py
+++ b/harness/tests/texturing/test_tile.py
@@ -15,18 +15,6 @@ from codeverse3d.texturing.generate import (
from tests.texturing.conftest import procedural_texture
-def _tileable(size: int = 64) -> Image.Image:
- y, x = np.mgrid[0:size, 0:size] / size
- a = 0.5 + 0.4 * np.sin(2 * np.pi * 3 * x) * np.cos(2 * np.pi * 2 * y)
- return Image.fromarray((np.stack([a, a, a], 2) * 255).astype(np.uint8), "RGB")
-
-
-def test_seam_score_tileable_is_low_and_gradient_is_high():
- assert seam_score(_tileable()) < 0.02
- bad = procedural_texture("x", size=64) # carries a horizontal gradient → seam
- assert seam_score(bad) > seam_score(_tileable())
-
-
def test_make_tileable_makes_wrap_edges_equal_and_lowers_score():
bad = procedural_texture("wood", size=128)
before = seam_score(bad)
diff --git a/harness/tests/texturing/test_uv.py b/harness/tests/texturing/test_uv.py
index db6c3814..68e80c4f 100644
--- a/harness/tests/texturing/test_uv.py
+++ b/harness/tests/texturing/test_uv.py
@@ -6,7 +6,7 @@ import numpy as np
import pytest
import trimesh
-from codeverse3d.texturing.apply import choose_projection, split_by_key, unwrap
+from codeverse3d.texturing.apply import choose_projection, unwrap
def test_choose_projection_rules():
@@ -50,16 +50,6 @@ def test_cylinder_projection_seam_and_caps():
assert (uw.uv[:, 1].max() - uw.uv[:, 1].min()) >= 5.0 - 1e-6
-def test_split_by_key_preserves_geometry_and_normals():
- m = trimesh.creation.box()
- normals = np.asarray(m.vertex_normals)
- uv_c = np.zeros((len(m.faces), 3, 2))
- key = np.zeros((len(m.faces), 3), dtype=int)
- v, f, n, uv, n_split = split_by_key(m.vertices, m.faces, normals, uv_c, key)
- assert n_split == 0 and len(v) == len(m.vertices) and np.allclose(n, normals)
- assert np.allclose(v[f], m.vertices[m.faces])
-
-
def test_unwrap_rejects_bad_input():
with pytest.raises(ValueError):
unwrap(np.zeros((3, 3)), np.zeros((0, 3), dtype=int), np.eye(4))