Skip to content

Official Codebase of 3DCodeVerse

Python

tests: models, cost — 52 tests go that cover no line another test does not (−1 023 lines)

gaoypengb20cd06b85e4
diff --git a/harness/tests/cost/test_audit_report.py b/harness/tests/cost/test_audit_report.py
index 2dba80d0..907d3909 100644
--- a/harness/tests/cost/test_audit_report.py
+++ b/harness/tests/cost/test_audit_report.py
@@ -3,35 +3,19 @@
from __future__ import annotations
import json
+import shutil
from pathlib import Path
import pytest
from codeverse3d.addons.costreport.audit import (
audit_runs,
- cached_input_share,
- price_confidence,
- stage_latency,
- uncached_if_no_cache,
)
from codeverse3d.addons.costreport.report import console, markdown
-def test_audit_of_one_run(fake_run: Path):
- audit = audit_runs([fake_run.parent])
- assert audit.n_runs == 1 and audit.usd_per_run == pytest.approx(audit.total_usd)
- assert audit.summary.dimension("track")["static_object"].cost_usd == pytest.approx(audit.total_usd)
- assert audit.calls_per_round() > 0
- cached, total, usd = cached_input_share(audit)
- assert 0 < cached < total and usd > 0
- assert uncached_if_no_cache(audit) > audit.total_usd
- assert sum(price_confidence(audit).values()) == pytest.approx(audit.total_usd)
- assert stage_latency(audit)
-
-
def test_a_run_that_booked_no_money_still_reports(tmp_path: Path):
- """Every session killed before it reported usage books $0 (a killed gemini-cli says nothing);
- the report divided by the run's total and `3dcode cost` died of ZeroDivisionError on it."""
+ """A $0 run (every session killed before it reported usage) must not divide by zero."""
ws = tmp_path / "free_run"
ws.mkdir()
(ws / "record.json").write_text(json.dumps({
@@ -47,10 +31,7 @@ def test_a_run_that_booked_no_money_still_reports(tmp_path: Path):
def test_a_lower_scoring_round_is_not_waste_but_a_repair_that_never_built_is(fake_run: Path, tmp_path: Path):
- """Every round is kept and any can be handed over (2026-09-22), so scoring below an
- earlier round is no longer waste; repair money in a round that still did not build is."""
- import shutil
-
+ """Any round can be handed over, so a lower score is not waste; a failed repair is."""
ws = tmp_path / "regressed"
shutil.copytree(fake_run, ws)
record = json.loads((ws / "record.json").read_text())
@@ -73,12 +54,3 @@ def test_a_lower_scoring_round_is_not_waste_but_a_repair_that_never_built_is(fak
assert kinds["repair_no_converge"] == (1, pytest.approx(0.05))
-def test_report_renders(fake_run: Path):
- audit = audit_runs([fake_run])
- md = markdown(audit)
- for heading in ("Per stage", "Per role", "Where a dollar bought nothing"):
- assert f"## {heading}" in md
- assert "per passing artifact" not in md and "per run" in md
- assert "judge" in console(audit)
-
-
diff --git a/harness/tests/cost/test_cli.py b/harness/tests/cost/test_cli.py
index 4ab509e3..66917f7a 100644
--- a/harness/tests/cost/test_cli.py
+++ b/harness/tests/cost/test_cli.py
@@ -12,16 +12,6 @@ from codeverse3d.cli.main import app
runner = CliRunner()
-def test_cost_show(fake_run: Path, tmp_path: Path):
- out = tmp_path / "report.md"
- r = runner.invoke(app, ["cost", "show", str(fake_run), "--md", str(out)])
- assert r.exit_code == 0, r.output
- assert "per run" in r.stdout and "passing" not in r.stdout and "judge" in r.stdout
- assert out.is_file() and "## Per stage" in out.read_text()
- r = runner.invoke(app, ["cost", "show", str(fake_run), "--no-per-run"])
- assert r.exit_code == 0 and "| fake_run | static_object |" not in r.stdout # the per-run table
-
-
def test_cost_show_recheck_reports_drift(fake_run: Path):
r = runner.invoke(app, ["cost", "show", str(fake_run), "--recheck"])
assert r.exit_code == 0 and "re-priced total" in r.output
@@ -62,7 +52,7 @@ def test_cost_runs_dir_aggregates_a_battery(fake_run: Path, tmp_path: Path):
def test_the_ledger_is_the_money(fake_run: Path):
- """The run wrote its own rows while it ran: they ARE the money, whatever the record says."""
+ """The ledger rows are the money, whatever the record says (D84)."""
_live_ledger(fake_run, [
{"run": fake_run.name, "round": 0, "stage": "baseline", "role": "generator",
"backend": "gemini", "provider": "gemini", "model": "gemini-3.7-flash",
@@ -78,9 +68,6 @@ def test_the_ledger_is_the_money(fake_run: Path):
def test_cost_reports_the_calls_per_key_when_the_ledger_recorded_them(fake_run: Path, tmp_path: Path):
- """audit 2026-08-26 §4: no row said which key served a call, so 'is one key hammered' could
- only be probed. Live rows now carry the key suffix and the round-trip count; the report
- shows both, and a ledger without them (older, or reconstructed) simply has no key section."""
base = {"run": fake_run.name, "round": 0, "stage": "baseline", "role": "generator", "backend": "gemini",
"provider": "gemini", "model": "gemini-3.7-flash", "input_tokens": 1_000, "output_tokens": 10,
"cost_usd": 0.001, "price_source": "exact"}
diff --git a/harness/tests/cost/test_context.py b/harness/tests/cost/test_context.py
index 4188663b..bf9b378d 100644
--- a/harness/tests/cost/test_context.py
+++ b/harness/tests/cost/test_context.py
@@ -24,10 +24,10 @@ def test_label_tells_stage_role_and_round():
assert context_from_label("texture_plan").stage is Stage.TEXTURE
assert context_from_label("captioner").role is Role.CAPTIONER
assert context_from_label("").stage is None
-
-
-def test_repair_label_wins_over_the_label_it_repairs():
- assert context_from_label("baseline_repair1").stage is Stage.REPAIR
+ assert context_from_label("baseline_repair1").stage is Stage.REPAIR # repair wins
+ assert attribute(label="detail_seat_edge").stage is Stage.REFINE # the static detail round
+ zl = attribute(label="zone-layout") # the ledger agrees with the guard's stage='plan'
+ assert zl.stage is Stage.PLAN and zl.role is Role.PLANNER
def test_a_generation_label_yields_to_the_session_and_explicit_beats_both():
@@ -41,8 +41,7 @@ def test_a_generation_label_yields_to_the_session_and_explicit_beats_both():
def test_a_call_that_names_its_own_job_beats_the_session_it_runs_inside():
- """The verifier's finding: a spatial tool that bills a model inside a refine
- session was recorded as stage=refine / role=generator."""
+ """A spatial tool that bills a model inside a refine session is not a refine call."""
with call_context(round=2, stage=Stage.REFINE, role=Role.GENERATOR, label="refine_seat"):
tex = attribute(label="texture_plan")
assert tex.stage is Stage.TEXTURE and tex.role is Role.OTHER and tex.round == 2
@@ -57,21 +56,8 @@ def test_a_call_that_names_its_own_job_beats_the_session_it_runs_inside():
assert anon.stage is Stage.REFINE and anon.role is Role.GENERATOR
-def test_nested_contexts_merge_and_unwind():
- with bound_run("run-a"):
- assert current().run == "run-a"
- with call_context(stage=Stage.BASELINE, round=0):
- with call_context(label="inner"):
- inner = current()
- assert inner.stage is Stage.BASELINE and inner.round == 0 and inner.label == "inner"
- assert current().label == ""
- assert current().stage is None and current().run == "run-a"
- assert current().run == ""
-
-
def test_a_run_bound_in_a_thread_is_never_published_to_the_others():
- """The 2026-08-30 leak: the binding also lived in a process global, so once the
- first parallel run exited it republished ITS name for every later caller."""
+ """The 2026-08-30 leak: a process-global binding republished one parallel run's name."""
import threading
ready, seen = threading.Barrier(3), {}
@@ -91,16 +77,3 @@ def test_a_run_bound_in_a_thread_is_never_published_to_the_others():
assert current().run == "" # ...and the main thread never inherited either of them
-def test_role_is_derived_from_stage_when_unstated():
- assert attribute(CallContext(stage=Stage.ZONES)).role is Role.GENERATOR
- assert attribute(CallContext(stage=Stage.PAIRWISE)).role is Role.JUDGE
- # the scene track's compose task is an agent session, not deterministic assembly
- assert attribute(CallContext(stage=Stage.ASSEMBLE)).role is Role.GENERATOR
-
-
-def test_the_static_track_detail_round_is_a_refine_pass():
- """``DEFAULT_DETAIL_ROUNDS=1``, so every static run bills one of these; until
- 2026-08-30 no prefix matched and the whole round landed under ``other``."""
- for label in ("detail", "detail_seat_edge"):
- got = attribute(label=label)
- assert got.stage is Stage.REFINE and got.role is Role.GENERATOR, label
diff --git a/harness/tests/cost/test_guard.py b/harness/tests/cost/test_guard.py
index bb09ca4a..7953ac77 100644
--- a/harness/tests/cost/test_guard.py
+++ b/harness/tests/cost/test_guard.py
@@ -9,13 +9,6 @@ from codeverse3d.cost.guard import image_tokens, text_tokens
# ------------------------------------------------------------------ guard
-def test_estimate_matches_the_price_table():
- est = estimate_call("gemini:gemini-3.7-flash", input_tokens=100_000, cached_tokens=80_000,
- output_tokens=1_000)
- assert abs(est.usd - (0.015 + 0.006 + 0.00375)) < 1e-9
- assert est.provider == "gemini" and est.model == "gemini-3.7-flash" and not est.approximate
-
-
def test_estimate_from_text_and_images():
est = estimate_call("gemini:gemini-3.1-pro-preview", prompt="x" * 4000, n_images=4, output_tokens=2000)
assert est.input_tokens == 1000 + image_tokens(4)
diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.py
index 70402d61..c381584f 100644
--- a/harness/tests/cost/test_instrument.py
+++ b/harness/tests/cost/test_instrument.py
@@ -101,18 +101,7 @@ def test_a_failed_call_is_recorded_and_re_raised(tmp_path: Path):
assert row.outcome == "timeout" and row.stage is Stage.PLAN and row.cost_usd == 0.0
-def test_a_cli_agent_we_cannot_see_inside_gets_one_session_row(tmp_path: Path):
- with run_ledger(tmp_path, run="r1"):
- MeteredAgent(CliAgent(FakeChat())).run(
- AgentJob(workspace=str(tmp_path), prompt="p", label="baseline", round=0, kind="baseline"))
- (row,) = load_ledger(tmp_path)
- assert row.source == "session" and row.backend == "gemini-cli" and row.n_calls == 4
- assert row.stage is Stage.BASELINE and row.round == 0 and row.input_tokens == 50_000
-
-
def test_a_session_row_is_filed_by_the_task_kind(tmp_path: Path):
- """``job.kind`` is a bare task kind (``zone``, ``rebuild``, ``asset``); until 2026-08-29
- only the label PREFIXES were known here, so every scene zone session was ``other``."""
with run_ledger(tmp_path, run="r1"):
for kind, label in (("zone", "zone_courtyard"), ("rebuild", "rebuild"),
("asset", "asset_koi"), ("candidate", "baseline_c1")):
@@ -209,21 +198,6 @@ def test_a_cli_session_is_recorded_even_when_a_tool_bills_a_model_inside_it(tmp_
# ------------------------------------------------------------------- nesting / parallelism
-def test_run_ledgers_nest_and_restore_the_outer_one(tmp_path: Path):
- """Closing a nested ledger restores the outer context."""
- outer, inner = tmp_path / "cell", tmp_path / "cell" / "run"
- with run_ledger(outer, run="cell"):
- MeteredChatModel(FakeChat()).generate(ChatRequest(messages=[ChatMessage.user("x")], label="planner"))
- with run_ledger(inner, run="cell:run"):
- MeteredChatModel(FakeChat()).generate(
- ChatRequest(messages=[ChatMessage.user("x")], label="baseline"))
- MeteredChatModel(FakeChat()).generate(
- ChatRequest(messages=[ChatMessage.user("x")], label="judge:static_object_v1:r00:s0"))
- assert [r.stage for r in load_ledger(inner)] == [Stage.BASELINE]
- assert [r.stage for r in load_ledger(outer)] == [Stage.PLAN, Stage.JUDGE]
- assert {r.run for r in load_ledger(outer)} == {"cell"}
-
-
def test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Path,
monkeypatch: pytest.MonkeyPatch):
"""`bench.run_bench` runs N prompts in N threads; their rows must not mix."""
@@ -243,10 +217,7 @@ def test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Pat
for name in names:
rows = load_ledger(tmp_path / name)
assert len(rows) == 3 and {r.run for r in rows} == {name}
- # ...and neither binding leaked out of its worker. Until 2026-08-30 the run name
- # and the default ledger were ALSO process globals that the first thread to exit
- # republished, so this plain main-thread call appended to a finished run's file
- # under that run's name instead of going to the per-process log.
+ # ...and neither binding leaked out of its worker (the 2026-08-30 process-global leak)
monkeypatch.setattr(ledger_mod, "_fallback", ledger_mod.CostLedger(tmp_path / "process.jsonl"))
assert run_binding().run == ""
record_call(Usage(cost_usd=0.5), label="baseline")
@@ -255,7 +226,6 @@ def test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Pat
assert len(load_ledger(tmp_path / name)) == 3
-# ------------------------------------------------------- key + attempts on the row (audit 2026-08-26 §4)
class KeyedChat(FakeChat):
"""A gemini-shaped response: ``raw`` names the key that answered and the round-trips."""
@@ -268,15 +238,6 @@ class KeyedChat(FakeChat):
return ChatResponse(text="ok", usage=_usage(), raw=dict(self.raw))
-def test_the_row_says_which_key_served_the_call_and_how_many_round_trips(tmp_path: Path):
- """Safe key identity and retry counts reach telemetry rows."""
- with run_ledger(tmp_path, run="r1"):
- MeteredChatModel(KeyedChat({"key": "…ab12", "attempts": 3, "hedged": 1})).generate(
- ChatRequest(messages=[ChatMessage.user("x")], label="planner"))
- (row,) = load_ledger(tmp_path)
- assert row.key == "…ab12" and row.attempts == 3
-
-
def test_a_full_key_never_reaches_the_ledger(tmp_path: Path):
with run_ledger(tmp_path, run="r1"):
MeteredChatModel(KeyedChat({"key": "AIzaSy-a-whole-secret-key-9999"})).generate(
@@ -296,28 +257,6 @@ def test_a_failed_call_records_its_attempts_but_no_key(tmp_path: Path):
assert row.outcome == "error" and row.attempts == 7 and row.key == ""
-def test_per_key_buckets_and_tries_per_call(tmp_path: Path):
- from types import SimpleNamespace
-
- from codeverse3d.addons.costreport.report import BUCKET_HEADERS, bucket_rows, keyed_buckets
- from codeverse3d.cost.ledger import record_call, summarise
-
- led = tmp_path / "cost.jsonl"
- rows = [
- record_call(_usage(), label="planner", ledger=led, key="…k1", attempts=1),
- record_call(_usage(), label="planner", ledger=led, key="…k1", attempts=3),
- record_call(_usage(), label="planner", ledger=led, key="…k2", attempts=1),
- record_call(_usage(), label="baseline", ledger=led, n_calls=4, source="session"), # a CLI session: no key
- ]
- by = summarise(rows, dimensions=("key",)).dimension("key")
- assert by["…k1"].n_calls == 2 and by["…k1"].attempts_per_call == 2.0
- assert by["…k2"].attempts_per_call == 1.0
- assert by["(none)"].n_calls == 4 and by["(none)"].attempts_per_call == 0.0
- audit = SimpleNamespace(summary=summarise(rows, dimensions=("key",)))
- assert [b.key for b in keyed_buckets(audit)] == ["…k1", "…k2"], "most calls first, unkeyed rows left out"
- table = bucket_rows(keyed_buckets(audit), total=1.0)
- assert BUCKET_HEADERS[-1] == "tries/call" and table[0][-1] == "2.00" and table[1][-1] == "1.00"
-# ------------------------------------------------------- per-attempt rows (audit 2026-08-27)
def test_a_billed_but_invalid_attempt_is_in_the_total_exactly_once(tmp_path: Path):
"""A charged invalid attempt is counted exactly once beside its winner."""
from codeverse3d.cost.ledger import summarise
@@ -343,76 +282,8 @@ def test_a_billed_but_invalid_attempt_is_in_the_total_exactly_once(tmp_path: Pat
assert not win.discarded and win.attempt == 2
-def test_a_hedge_losers_tokens_reach_the_ledger_when_it_lands(tmp_path: Path):
- """A late hedge loser's billed tokens reach the ledger total."""
- import threading
- import time as _time
-
- from codeverse3d.models.base import ModelError
- from codeverse3d.models.gemini import GeminiModel
- from codeverse3d.models.retry import KeyPool
- from tests.models.test_gemini import text_response
-
- release_k2 = threading.Event()
-
- class Client:
- def __init__(self, key: str):
- self.key, self.models = key, self
-
- def generate_content_stream(self, **kw):
- yield self.generate_content(**kw)
-
- def generate_content(self, *, model, contents, config):
- if self.key == "k1":
- raise ModelError("503 high demand", retryable=True, status=503)
- if self.key == "k2":
- assert release_k2.wait(5.0)
- return text_response("late loser")
- return text_response("winner")
-
- pool = KeyPool(["k1", "k2", "k3"])
- m = GeminiModel("gemini-3.7-flash", pool=pool, sleep=lambda s: None, client_factory=Client)
- with run_ledger(tmp_path, run="r1"):
- resp = MeteredChatModel(m).generate(
- ChatRequest(messages=[ChatMessage.user("x")], label="planner"))
- assert resp.text == "winner"
- release_k2.set()
- deadline = _time.monotonic() + 5.0
- loser = None
- while _time.monotonic() < deadline:
- rows = load_ledger(tmp_path)
- loser = next((r for r in rows if r.source == "extra" and r.key == "…k2"), None)
- if loser is not None:
- break
- _time.sleep(0.01)
- assert loser is not None, "the loser's row never arrived"
- assert loser.discarded and loser.input_tokens == 100, "the loser's paid tokens are on the ledger"
- logical, = [r for r in load_ledger(tmp_path) if r.source == "live"]
- # endswith, not ==: the 2-char fake key is shorter than the …last-4 redaction
- assert logical.key.endswith("k3") and logical.call_id == loser.call_id
- from codeverse3d.cost.ledger import summarise
- assert summarise(load_ledger(tmp_path)).total.cost_usd == pytest.approx(
- logical.cost_usd + loser.cost_usd), "the loser is in the total exactly once"
-
-
-def test_zone_layout_rows_agree_with_the_guard(tmp_path: Path):
- """tracks/zone_layout.py labels its planner calls 'zone-layout' and charges the
- guard as stage='plan' — unclassified, the ledger filed the same dollars under
- other/other, so the two owners disagreed on every zone-layout cent (V10c)."""
- from codeverse3d.cost.types import role_for_stage, stage_for_label
-
- assert stage_for_label("zone-layout") is Stage.PLAN
- assert role_for_stage(stage_for_label("zone-layout")) is Role.PLANNER
- with run_ledger(tmp_path, run="r1"):
- record_call(_usage(cost_usd=0.02), label="zone-layout")
- row, = load_ledger(tmp_path)
- assert row.stage is Stage.PLAN and row.role is Role.PLANNER
-
-
def test_a_late_hedge_loser_keeps_its_stage_role_and_round(tmp_path: Path):
- """The loser lands AFTER generate() returned, from its own thread with empty
- contextvars: its 'extra' row used to fall back to what the label alone says
- (baseline/None) instead of the originating call's candidate/r0 attribution."""
+ """The loser lands after generate() returned, in a thread with empty contextvars."""
import threading
from codeverse3d.cost.context import AttemptRecord, attempt_sink, call_context
diff --git a/harness/tests/cost/test_ledger.py b/harness/tests/cost/test_ledger.py
index 0cea7513..d45e31e4 100644
--- a/harness/tests/cost/test_ledger.py
+++ b/harness/tests/cost/test_ledger.py
@@ -5,9 +5,8 @@ from __future__ import annotations
from pathlib import Path
from codeverse3d.contracts.common import Usage
-from codeverse3d.cost import CostLedger, load_ledger, record_call, summarise
-from codeverse3d.cost.ledger import bound_ledger, existing_ledger_path, open_run_ledger
-from codeverse3d.cost.types import Role, Stage
+from codeverse3d.cost import load_ledger, record_call
+from codeverse3d.cost.ledger import existing_ledger_path, open_run_ledger
def _usage(**kw: object) -> Usage:
@@ -17,16 +16,6 @@ def _usage(**kw: object) -> Usage:
return Usage(**base) # type: ignore[arg-type]
-def test_record_call_prices_and_stamps_provenance(tmp_path: Path):
- row = record_call(_usage(), run="r1", stage="judge", ledger=tmp_path / "l.jsonl")
- # 20k uncached * 0.75 + 80k cached * 0.075 + 1k out * 3.75, per 1M
- assert abs(row.cost_usd - (0.015 + 0.006 + 0.00375)) < 1e-9
- assert row.role is Role.JUDGE and row.stage is Stage.JUDGE # role inferred from stage
- assert row.provider == "gemini" and row.model == "gemini-3.7-flash"
- assert row.price_source == "exact" and row.price_approximate is False and row.price_checked
- assert row.cache_hit is True and row.n_calls == 1
-
-
def test_keeps_the_billed_cost_but_can_reprice(tmp_path: Path):
billed = record_call(_usage(cost_usd=0.123), run="r", stage="baseline", ledger=tmp_path / "a.jsonl")
assert billed.cost_usd == 0.123 and billed.recorded_usd == 0.123
@@ -35,16 +24,6 @@ def test_keeps_the_billed_cost_but_can_reprice(tmp_path: Path):
assert abs(repriced.cost_usd - 0.02475) < 1e-9 and repriced.recorded_usd == 0.123
-def test_append_only_and_reload(tmp_path: Path):
- led = CostLedger(tmp_path / "l.jsonl")
- for i in range(3):
- record_call(_usage(), run="r", round=i, stage="refine", ledger=led)
- rows = load_ledger(tmp_path / "l.jsonl")
- assert len(rows) == 3 and [r.round for r in rows] == [0, 1, 2]
- record_call(_usage(), run="r", round=3, stage="refine", ledger=led)
- assert len(load_ledger(tmp_path / "l.jsonl")) == 4 # nothing rewritten
-
-
def test_bad_line_does_not_lose_the_file(tmp_path: Path):
p = tmp_path / "l.jsonl"
record_call(_usage(), run="r", stage="plan", ledger=p)
@@ -54,11 +33,6 @@ def test_bad_line_does_not_lose_the_file(tmp_path: Path):
assert len(load_ledger(p)) == 2
-def test_unknown_model_is_recorded_not_raised(tmp_path: Path):
- row = record_call(_usage(model="totally-made-up-9"), run="r", stage="plan", ledger=tmp_path / "l.jsonl")
- assert row.cost_usd == 0.0 and row.price_source == "unknown" and row.price_approximate is True
-
-
def test_provider_reported_cost_is_flagged(tmp_path: Path):
"""A subscription CLI bills us a cost our table cannot reproduce: keep the
dollar, mark it unauditable."""
@@ -67,25 +41,6 @@ def test_provider_reported_cost_is_flagged(tmp_path: Path):
assert row.cost_usd == 1.17 and row.price_source == "provider-reported"
-def test_summarise_dimensions(tmp_path: Path):
- p = tmp_path / "l.jsonl"
- record_call(_usage(), run="a", stage="baseline", ledger=p)
- record_call(_usage(model="gemini-3.1-pro-preview", cached_tokens=0), run="a", stage="judge", ledger=p)
- s = summarise(load_ledger(p))
- assert set(s.dimension("stage")) == {"baseline", "judge"}
- assert abs(s.total.cost_usd - sum(b.cost_usd for b in s.dimension("role").values())) < 1e-12
- assert s.dimension("stage")["baseline"].cached_fraction == 0.8
- assert s.total.usd_per_1k_tokens > 0
-
-
-def test_a_bound_ledger_takes_the_calls_that_name_no_file(tmp_path: Path):
- with bound_ledger(tmp_path / "default.jsonl"):
- record_call(_usage(), run="r", stage="plan")
- assert len(load_ledger(tmp_path / "default.jsonl")) == 1
- record_call(_usage(), run="r", stage="plan", ledger=tmp_path / "after.jsonl")
- assert len(load_ledger(tmp_path / "default.jsonl")) == 1 # the binding is gone with the block
-
-
def test_a_run_has_exactly_one_ledger_file(tmp_path: Path):
"""``open_run_ledger`` writes only ``telemetry/cost.jsonl``, and that is the only name read."""
led = open_run_ledger(tmp_path)
diff --git a/harness/tests/cost/test_price_hygiene.py b/harness/tests/cost/test_price_hygiene.py
index 63d402d3..8a84d8bd 100644
--- a/harness/tests/cost/test_price_hygiene.py
+++ b/harness/tests/cost/test_price_hygiene.py
@@ -6,11 +6,9 @@ import pytest
from codeverse3d.contracts.common import Usage
from codeverse3d.models.pricing import (
- IMAGE_USD_BY_SIZE,
PRICES,
SOURCES,
estimate_cost,
- per_image_usd,
price_provenance,
unit_prices,
)
@@ -44,26 +42,6 @@ def test_every_price_row_has_provenance():
assert (price.source or provider) in SOURCES, model
-def test_provenance_flags_the_rows_we_cannot_stand_behind():
- for key, price in PRICES.items():
- row = price_provenance(*key)
- if price.approximate:
- assert row.approximate, key
- assert price_provenance("gemini", "gemini-3.7-flash").approximate is False
- assert price_provenance("anthropic", "claude-haiku-4").approximate is True
- assert price_provenance("gemini", "not-a-model").status == "unknown"
-
-
-def test_image_models_have_a_per_image_price():
- for provider, model in (("gemini", "gemini-3.1-flash-image"), ("gemini", "gemini-2.5-flash-image")):
- assert PRICES[(provider, model)].image_usd > 0, model
- assert per_image_usd(provider, model) == PRICES[(provider, model)].image_usd
- assert per_image_usd(provider, model, size=512) > 0
- assert (provider, model) in IMAGE_USD_BY_SIZE
- # version suffixes resolve too (the image model is often pinned with -preview)
- assert per_image_usd("gemini", "gemini-2.5-flash-image-preview") == 0.039
-
-
def test_long_context_tier_is_applied():
small = Usage(input_tokens=100_000, output_tokens=1_000)
big = Usage(input_tokens=300_000, output_tokens=1_000)
@@ -97,9 +75,7 @@ def test_the_bracketed_context_variant_prices_on_its_own_row():
# --------------------------------------------------------------- staleness maintenance
def test_every_price_row_was_checked_within_the_maintenance_window():
- """A price nobody re-checked for 90 days is not evidence. When this fails,
- re-read the providers' pricing pages, update PRICES and bump
- ``CHECKED`` — do not raise the threshold."""
+ """When this fails, re-check the providers' pages and bump CHECKED — not the threshold."""
from datetime import date, datetime
from codeverse3d.cli.cost_cmd import STALE_AFTER_DAYS
diff --git a/harness/tests/cost/test_profiles.py b/harness/tests/cost/test_profiles.py
index 123e2e79..477bd7ea 100644
--- a/harness/tests/cost/test_profiles.py
+++ b/harness/tests/cost/test_profiles.py
@@ -11,7 +11,7 @@ from typer.testing import CliRunner
from codeverse3d.cli._common import resolve_dial
from codeverse3d.cli.main import app
from codeverse3d.config import Settings, get_settings
-from codeverse3d.cost.profiles import PROFILE_NAMES, PROFILES, get_profile, profile_table
+from codeverse3d.cost.profiles import PROFILE_NAMES, PROFILES, profile_table
runner = CliRunner()
@@ -24,16 +24,6 @@ def _fresh_settings():
get_settings.cache_clear()
-def test_the_three_profiles_are_a_monotone_dial():
- usd = [PROFILES[n].expected_usd for n in PROFILE_NAMES]
- assert usd == sorted(usd) and usd[0] < usd[-1]
- rounds = [PROFILES[n].rounds for n in PROFILE_NAMES]
- assert rounds == sorted(rounds)
- # every profile explains itself and cites what it was measured at
- for p in PROFILES.values():
- assert p.expected_score and p.note and p.generator and p.judge
-
-
def test_balanced_is_todays_defaults():
p = PROFILES["balanced"]
s = Settings()
@@ -69,8 +59,7 @@ def test_one_stated_judge_field_does_not_disable_the_whole_judge_block(monkeypat
def test_no_profile_touches_the_judge_payload_or_the_turn_cap(monkeypatch):
- """Neither cut paid when measured (docs/COST.md §14, §17), so they are not dials: even
- `--profile X`, which forces the dial, leaves a stated payload and turn cap alone."""
+ """Not dials (docs/COST.md §14, §17): even a forced profile leaves them alone."""
monkeypatch.setenv("C3D_JUDGE__MAX_PX", "800")
monkeypatch.setenv("C3D_LIMITS__AGENT_MAX_TURNS", "12")
for name in PROFILE_NAMES:
@@ -78,19 +67,6 @@ def test_no_profile_touches_the_judge_payload_or_the_turn_cap(monkeypatch):
assert (d.judge_max_px, d.judge_montages, d.judge_detail_crops, d.agent_max_turns) == (800, 5, 2, 12)
-def test_applying_a_profile_twice_is_idempotent():
- """Profile defaults do not masquerade as user-stated fields."""
- s = Settings()
- s.apply_profile("quality")
- s.apply_profile("economy")
- assert s.judge.samples == 2 and s.judge.max_px == 1024
-
-
-def test_unknown_profile_is_a_clear_error():
- with pytest.raises(ValueError, match="unknown profile"):
- get_profile("cheapest")
-
-
def test_a_bogus_profile_name_is_a_typed_cli_error_not_a_traceback(monkeypatch):
"""An invalid environment profile yields one clean validation error."""
runner = CliRunner()
@@ -126,17 +102,6 @@ def test_an_explicit_flag_beats_the_profile(tmp_path: Path):
assert spec["backends"]["judge"] == "gemini:gemini-3.7-flash" # unstated → still the profile's
-def test_no_profile_flag_leaves_the_defaults_alone(tmp_path: Path):
- runs = tmp_path / "runs"
- r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", "--slug", "pot"])
- assert r.exit_code == 0, r.output
- spec = json.loads((runs / "pot" / "spec.json").read_text())
- # the resolved dial is recorded whichever way it was named, so `3dcode resume`
- # reproduces it; with no flag and no env that dial is the default, balanced
- assert spec["options"]["profile"] == "balanced" and spec["options"]["texture"] is False
- assert spec["budget"]["max_rounds"] == 4 and spec["budget"]["max_minutes"] > 0
-
-
def test_judge_samples_reach_the_round_policy_only_when_a_profile_asks(tmp_path: Path):
from codeverse3d.cli import _common as C
from codeverse3d.contracts.common import Budget, Language, Track
@@ -202,7 +167,7 @@ def test_each_profile_resolves_to_its_documented_dial(name, expected, monkeypatc
assert getattr(dial, field) == want, f"{name}.{field}"
[email protected]("name", PROFILE_NAMES)
[email protected]("name", ["quality"])
def test_the_env_var_reaches_the_spec_a_make_writes(name, tmp_path: Path, monkeypatch):
"""End to end: C3D_PROFILE alone must produce the same spec shape as --profile."""
from codeverse3d.cost.profiles import PROFILES
diff --git a/harness/tests/cost/test_tally.py b/harness/tests/cost/test_tally.py
index 8847d6ad..582da5df 100644
--- a/harness/tests/cost/test_tally.py
+++ b/harness/tests/cost/test_tally.py
@@ -113,18 +113,6 @@ def test_a_clean_call_loses_nothing_and_a_503_before_the_answer_is_lost(tmp_path
assert lost == 0.0
-def test_a_backend_that_reports_no_round_trips_is_charged_everything_outside_its_answer(tmp_path: Path):
- class Sdk:
- provider, model, id = "openai", "gpt-5", "openai:gpt-5"
-
- def generate(self, request: ChatRequest) -> ChatResponse:
- time.sleep(0.08) # a retried attempt and its back-off, invisible from here
- return ChatResponse(text="ok", usage=Usage(model="gpt-5", latency_ms=20))
-
- wall, lost = _lost(Sdk(), tmp_path)
- assert lost == pytest.approx(wall - 0.020, abs=0.01)
-
-
def test_an_agent_session_books_what_its_cli_lost_to_the_provider(tmp_path: Path):
class Cli:
kind, model, id = "gemini-cli", "gemini-3.7-flash", "gemini-cli:gemini-3.7-flash"
diff --git a/harness/tests/models/test_anthropic.py b/harness/tests/models/test_anthropic.py
index 8109b443..e18c5019 100644
--- a/harness/tests/models/test_anthropic.py
+++ b/harness/tests/models/test_anthropic.py
@@ -21,7 +21,6 @@ from codeverse3d.models.anthropic import (
to_messages,
)
from codeverse3d.models.base import ModelError
-from codeverse3d.models.retry import MAX_WAIT_S
PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
@@ -182,36 +181,6 @@ def test_images_base64_and_message_merging():
assert msgs[0]["content"][2]["source"]["media_type"] == "image/png"
-def test_retry_on_429_529_5xx_and_not_on_400():
- naps: list[float] = []
- fc = FakeClient([api_error(429), api_error(529), api_error(500), msg([text("ok")])])
- m = AnthropicModel("claude-opus-5", client=fc, sleep=naps.append)
- assert (
- m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"
- and len(fc.calls) == 4
- )
- # one backoff per failure, each <= MAX_WAIT_S: a 529 is not a storm on a one-key
- # pool and a 429 waits for no cooldown (the loop the SDK adapters always had)
- assert len(naps) == 3 and all(0 < d <= MAX_WAIT_S for d in naps), naps
- m, fc = make([api_error(529)] * 3, max_attempts=3)
- with pytest.raises(ModelError) as ei:
- m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
- assert ei.value.status == 529 and len(fc.calls) == 3 and ei.value.attempts == 3
- m, fc = make([api_error(400, "bad"), msg([text("never")])])
- with pytest.raises(ModelError) as ei:
- m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
- assert not ei.value.retryable and ei.value.status == 400 and len(fc.calls) == 1
-
-
-def test_refusal_and_empty():
- m, _ = make([msg([], stop="refusal")])
- with pytest.raises(ModelError) as ei:
- m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
- assert not ei.value.retryable
- m, fc = make([msg([], stop="end_turn"), msg([text("ok")])])
- assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"
-
-
def test_classify_connection_errors():
import anthropic
@@ -239,8 +208,7 @@ def test_assistant_first_gets_user_prefix():
def test_a_failed_reply_carries_what_it_was_billed():
- """Three raise sites built a real Usage from ``msg.usage`` and threw it away, so a
- refusal / bad-JSON / empty reply looked FREE to the ledger and to the key pool."""
+ """A refusal / bad-JSON / empty reply is billed on the error (D84)."""
for script, req in (
([msg([], stop="refusal")], ChatRequest(messages=[ChatMessage.user("x")])),
(
@@ -256,10 +224,7 @@ def test_a_failed_reply_carries_what_it_was_billed():
def test_each_attempt_gets_what_is_left_of_the_call_budget():
- """``max_wait_s`` is the whole call's deadline, and the retry loop only checks it
- BETWEEN attempts — so the attempt itself must carry it. The client is built once with
- a fixed 600 s timeout, so a judge with 20 s of budget left used to hold a socket for
- 600 s. Floor: a long completion (the 930 s plan) keeps the full client timeout."""
+ """Every SDK adapter (SdkModel) passes the call's remaining max_wait_s to each attempt."""
m, fc = make([msg([text("hi")])], timeout_s=600.0)
m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=25.0))
assert 20.0 <= fc.calls[0]["timeout"] <= 25.0
diff --git a/harness/tests/models/test_control_chars.py b/harness/tests/models/test_control_chars.py
index d636afec..458499a5 100644
--- a/harness/tests/models/test_control_chars.py
+++ b/harness/tests/models/test_control_chars.py
@@ -1,13 +1,5 @@
-"""Control characters in model output (codeverse3d/models/schema_utils.strip_control_chars).
-
-Regression (2026-08-24): a gemini-3.7-flash plan emitted five ``\\u0000`` escapes where the
-model meant glyphs it could not encode — "0.078 × 0.300 × 0.240 m" became
-"0.078 \\x00 0.300 \\x00 0.240 m", and "0.240 m ± 0.005 m" became "0.240 m \\x00 0.005 m".
-That is legal JSON, so it passed the parser, passed pydantic validation, and was written to
-plan.json. It detonated four stages later in a codex cell: every generation task died with
-``ValueError: embedded null byte`` raised by subprocess.Popen, an error naming no file, no
-field and no value. The whole cell was lost.
-"""
+"""Control characters in model output: a 2026-08-24 plan carried \\u0000 where it meant ×/±,
+and the NUL killed a codex cell at Popen. strip_control_chars + the argv backstop."""
from __future__ import annotations
@@ -55,84 +47,3 @@ def test_the_subprocess_backstop_names_the_offender(tmp_path):
run_with_watchdog(["echo", "ok", poisoned], cwd=tmp_path, env=None, soft_timeout_s=5)
-def test_the_anthropic_submit_tool_path_is_sanitised_too():
- """Parsed Anthropic submit-tool input is sanitized before use."""
- from types import SimpleNamespace as NS
-
- from codeverse3d.contracts.chat import ChatMessage, ChatRequest
- from codeverse3d.models.anthropic import SUBMIT_TOOL, AnthropicModel
-
- block = NS(
- type="tool_use", id="t1", name=SUBMIT_TOOL, input={"description": "0.078 \x00 0.300 slab"}
- )
- reply = NS(
- id="m1",
- model="claude-opus-5",
- content=[block],
- stop_reason="tool_use",
- stop_details=None,
- usage=NS(
- input_tokens=10,
- output_tokens=2,
- cache_read_input_tokens=0,
- cache_creation_input_tokens=0,
- ),
- )
-
- class FakeClient:
- def __init__(self):
- self.messages = NS(create=lambda **kw: reply)
-
- model = AnthropicModel("claude-opus-5", client=FakeClient(), sleep=lambda s: None)
- resp = model.generate(
- ChatRequest(
- messages=[ChatMessage.user("hi")],
- response_schema={"type": "object", "properties": {"description": {"type": "string"}}},
- )
- )
- assert "\x00" not in resp.parsed["description"]
- assert resp.parsed["description"] == "0.078 0.300 slab"
- # the text mirror the harness derives from it must be clean as well
- assert "\x00" not in (resp.text or "")
-
-
-def test_the_brief_text_fallback_is_sanitised(tmp_path):
- """Plain-text brief JSON is sanitized before fallback parsing."""
- from codeverse3d.contracts.chat import ChatResponse
- from codeverse3d.contracts.common import Language, Track, Usage
- from codeverse3d.contracts.plan import EngineeringBrief, RefDimension, SubAssembly
- from codeverse3d.contracts.spec import Spec
- from codeverse3d.tracks.planner import expand_brief
-
- clean = EngineeringBrief(
- object_name="Grinder",
- reference="Peugeot 1920s box grinder",
- one_line="a wooden box grinder",
- dimensions_m=[RefDimension(name="width", meters=0.14)],
- sub_assemblies=[SubAssembly(name="burr", purpose="grinds", parts=["burr"])],
- mechanism="the crank turns the shaft",
- visible_from_outside=["the drawer seam"],
- signature_features=["open hopper", "front drawer"],
- materials=["body: beech"],
- )
- payload = json.loads(clean.model_dump_json())
- payload["mechanism"] = "the crank turns 0.078 \x00 0.300 the shaft"
-
- class TextOnlyModel:
- """Returns JSON as TEXT with parsed=None — the json.loads fallback branch."""
-
- provider, model = "fake", "fake-1"
-
- def generate(self, request):
- return ChatResponse(text=json.dumps(payload), parsed=None, usage=Usage())
-
- spec = Spec(
- id="s1",
- track=Track.STATIC_OBJECT,
- language=Language.BLENDER,
- prompt="a hand-crank coffee grinder",
- )
- brief, _ = expand_brief(spec, "fake:planner", model=TextOnlyModel(), cache_dir=tmp_path)
- assert brief is not None, "the brief must still be produced, only cleaned"
- assert "\x00" not in brief.mechanism
- assert brief.mechanism == "the crank turns 0.078 0.300 the shaft"
diff --git a/harness/tests/models/test_gemini.py b/harness/tests/models/test_gemini.py
index 6f69aacb..5570a575 100644
--- a/harness/tests/models/test_gemini.py
+++ b/harness/tests/models/test_gemini.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import base64
-import json
from typing import Any
import pytest
@@ -16,11 +15,9 @@ from codeverse3d.contracts.chat import (
ImagePart,
TextPart,
)
-from codeverse3d.contracts.plan import StaticPlan
from codeverse3d.models.base import ModelError
from codeverse3d.models.gemini import (
GeminiModel,
- build_config,
classify_exception,
to_contents,
)
@@ -85,19 +82,32 @@ def make_model(script: list[Any], keys=("k1", "k2", "k3"), pool: KeyPool | None
return m, log, pool
-def test_read_timeout_comes_from_settings(monkeypatch):
- """C3D_MODEL_TIMEOUT_S raises the per-attempt HTTP read timeout (degraded-provider escape hatch)."""
- from codeverse3d.config import Settings, get_settings
- from codeverse3d.models.gemini import GeminiModel
+def _api_error(code: int, message: str, status: str) -> genai_errors.APIError:
+ return genai_errors.APIError(code, {"error": {"message": message, "status": status}})
+
- monkeypatch.setenv("GEMINI_API_KEYS", "k1")
- get_settings.cache_clear()
- assert GeminiModel("gemini-3.7-flash").timeout_s == Settings().model_timeout_s
- monkeypatch.setenv("C3D_MODEL_TIMEOUT_S", "900")
- get_settings.cache_clear()
- assert GeminiModel("gemini-3.7-flash").timeout_s == 900.0
- assert GeminiModel("gemini-3.7-flash", timeout_s=42.0).timeout_s == 42.0
- get_settings.cache_clear()
+SUSPENDED = _api_error(
+ 403, "PERMISSION_DENIED: Consumer 'api_key:xxx' has been suspended.", "PERMISSION_DENIED"
+)
+THROTTLED = genai_errors.APIError(
+ 429,
+ {
+ "error": {
+ "message": "quota",
+ "status": "RESOURCE_EXHAUSTED",
+ "details": [{"retryDelay": "7s"}],
+ }
+ },
+)
+
+
+def test_429_rotates_keys_and_honours_retry_delay():
+ m, log, pool = make_model([THROTTLED, THROTTLED, text_response("third time lucky")])
+ assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "third time lucky"
+ assert [e["key"] for e in log] == ["k1", "k2", "k3"]
+ st = pool.stats()
+ assert st["429"] == 2 and st["ok"] == 1 and st["n_cooling"] == 2
+ assert 0 < {k["key"]: k["cooldown_s"] for k in st["keys"]}["…k1"] <= 7.0
def test_text_usage_cost_and_raw():
@@ -117,84 +127,6 @@ def test_text_usage_cost_and_raw():
assert r.raw["key"] == "…k1"
-def test_structured_output_parsed_and_schema_sanitised():
- payload = {
- "object_name": "Stool",
- "summary": "s",
- "overall_bbox": {"center": [0, 0, 0.25], "extents": [0.4, 0.4, 0.5]},
- "parts": [
- {
- "name": "Seat",
- "role": "r",
- "description": "d",
- "bbox": {"center": [0, 0, 0.45], "extents": [0.4, 0.4, 0.05]},
- }
- ],
- }
- m, log, _ = make_model([text_response("```json\n" + json.dumps(payload) + "\n```")])
- r = m.generate(
- ChatRequest(
- messages=[ChatMessage.user("plan")], response_schema=StaticPlan.model_json_schema()
- )
- )
- assert StaticPlan.model_validate(r.parsed).object_name == "Stool"
- cfg = log[0]["config"]
- assert cfg.response_mime_type == "application/json"
- assert "$defs" not in json.dumps(
- cfg.response_schema
- if isinstance(cfg.response_schema, dict)
- else cfg.response_schema.model_dump()
- )
-
-
-def test_bad_json_is_retried():
- m, log, _ = make_model([text_response("not json"), text_response('{"ok": true}')])
- r = m.generate(
- ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"})
- )
- assert r.parsed == {"ok": True} and len(log) == 2
-
-
-def test_429_rotates_keys_and_cools_down():
- err = genai_errors.APIError(
- 429,
- {
- "error": {
- "message": "quota",
- "status": "RESOURCE_EXHAUSTED",
- "details": [{"retryDelay": "7s"}],
- }
- },
- )
- m, log, pool = make_model([err, err, text_response("third time lucky")])
- r = m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
- assert r.text == "third time lucky"
- assert [e["key"] for e in log] == ["k1", "k2", "k3"]
- st = pool.stats()
- assert st["429"] == 2 and st["ok"] == 1 and st["n_cooling"] == 2
- cooling = {k["key"]: k["cooldown_s"] for k in st["keys"]}
- assert 0 < cooling["…k1"] <= 7.0 # retryDelay honoured
-
-
-def _api_error(code: int, message: str, status: str) -> genai_errors.APIError:
- return genai_errors.APIError(code, {"error": {"message": message, "status": status}})
-
-
-SUSPENDED = _api_error(
- 403, "PERMISSION_DENIED: Consumer 'api_key:xxx' has been suspended.", "PERMISSION_DENIED"
-)
-THROTTLED = genai_errors.APIError(
- 429,
- {
- "error": {
- "message": "quota",
- "status": "RESOURCE_EXHAUSTED",
- "details": [{"retryDelay": "7s"}],
- }
- },
-)
-
-
def test_api_key_invalid_400_is_treated_as_dead_key():
bad = _api_error(400, "API key not valid. Please pass a valid API key.", "INVALID_ARGUMENT")
m, log, pool = make_model([bad, text_response("ok")], keys=("k1", "k2"))
@@ -207,16 +139,6 @@ def test_api_key_invalid_400_is_treated_as_dead_key():
assert failure_outcome(ModelError("bad json", retryable=True)) == "skip" # not the key's fault: no health nudge
-def test_400_is_not_retried():
- err = genai_errors.APIError(
- 400, {"error": {"message": "Invalid argument", "status": "INVALID_ARGUMENT"}}
- )
- m, log, _ = make_model([err, text_response("never")])
- with pytest.raises(ModelError) as ei:
- m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
- assert not ei.value.retryable and len(log) == 1
-
-
def test_thinking_rejected_falls_back_without_thinking_config():
err = genai_errors.APIError(
400,
@@ -301,17 +223,6 @@ def test_to_contents_merges_same_role_and_requires_content():
to_contents([ChatMessage(role="user", parts=[])])
-def test_build_config_thinking_off_budget_zero():
- cfg = build_config(
- ChatRequest(messages=[ChatMessage.user("x")], thinking="off"), timeout_ms=1000
- )
- assert cfg.thinking_config.thinking_budget == 0
- cfg = build_config(
- ChatRequest(messages=[ChatMessage.user("x")]), timeout_ms=1000, use_thinking=False
- )
- assert cfg.thinking_config is None
-
-
def test_no_keys_is_loud():
with pytest.raises(ModelError):
GeminiModel("gemini-3.7-flash", keys=[])
diff --git a/harness/tests/models/test_gemini_scheduling.py b/harness/tests/models/test_gemini_scheduling.py
index 63b64fea..2a9f3748 100644
--- a/harness/tests/models/test_gemini_scheduling.py
+++ b/harness/tests/models/test_gemini_scheduling.py
@@ -20,17 +20,6 @@ def api_error(code: int, msg: str = "boom") -> genai_errors.APIError:
# ------------------------------------------------------------------ slots
-def test_in_flight_returns_to_zero_after_success_and_after_failure():
- pool = KeyPool(["k1", "k2"], cooldown_s=0.0)
- m, _log, _ = make_model([text_response("hi")], pool=pool)
- m.generate(ChatRequest(messages=[ChatMessage.user("hi")]))
- assert pool.stats()["in_flight"] == 0
- m2, _log2, _ = make_model([api_error(400, "bad request")], pool=pool, max_attempts=1)
- with pytest.raises(ModelError):
- m2.generate(ChatRequest(messages=[ChatMessage.user("hi")]))
- assert pool.stats()["in_flight"] == 0
-
-
# ---------------------------------------------------------------- shared pool
def test_shared_pool_is_keyed_by_the_cap_not_only_by_keys():
a = shared_pool(["x1", "x2"], max_in_flight=4)
@@ -40,20 +29,9 @@ def test_shared_pool_is_keyed_by_the_cap_not_only_by_keys():
assert a is not c, "a different cap must not silently reuse another pool's slots"
-def test_the_hedge_comes_from_settings(monkeypatch):
- from codeverse3d.config import Rate, get_settings
-
- assert make_model([])[0].hedge == 2
- assert make_model([], hedge=1)[0].hedge == 1
- monkeypatch.setattr(get_settings(), "rate", Rate(hedge=1))
- assert make_model([])[0].hedge == 1
-
-
# ------------------------------------------------ retry budget + hedge (audit 2026-08-26 §5.1 / §5.2)
def test_max_wait_s_clips_the_retry_deadline_and_never_extends_it(monkeypatch):
- """Audit 2026-08-26 §5.1: 66 give-up spans of the model's 900 s deadline (x3 outer retries)
- were 30 % of a storm day's waiting. ``ChatRequest.max_wait_s`` is the caller's budget for
- the whole call; the model clips its deadline to it and never goes above its own ceiling."""
+ """ChatRequest.max_wait_s clips the model's retry deadline, never raises it."""
import codeverse3d.models.gemini as gm
from codeverse3d.models.retry import RETRY_DEADLINE_S
@@ -72,15 +50,6 @@ def test_max_wait_s_clips_the_retry_deadline_and_never_extends_it(monkeypatch):
assert seen == [RETRY_DEADLINE_S, 30.0, RETRY_DEADLINE_S]
-def test_max_wait_s_must_be_positive():
- """0 would mean "no deadline" to rotate_with_retries — the opposite of what a caller
- that is out of time wants — so the contract refuses it."""
- import pydantic
-
- with pytest.raises(pydantic.ValidationError):
- ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=0)
-
-
def test_a_clean_call_reports_one_attempt_and_a_failed_call_carries_its_count():
m, _log, _ = make_model([text_response("hi")])
r = m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
diff --git a/harness/tests/models/test_health.py b/harness/tests/models/test_health.py
index 8db3a30e..6c7a5491 100644
--- a/harness/tests/models/test_health.py
+++ b/harness/tests/models/test_health.py
@@ -20,8 +20,7 @@ def test_health_threshold_requires_a_real_success_rate():
def test_the_probe_prompt_is_the_size_of_real_work():
- """A five-token probe answers when a 12 k-token planner call does not — that false
- green light is exactly what this gate must not give."""
+ """A five-token probe answers when a 12 k-token planner call does not."""
from codeverse3d.models.health import PROBE_TOKENS, _probe_prompt
prompt = _probe_prompt()
@@ -57,10 +56,7 @@ def test_probe_never_raises_when_every_call_fails(monkeypatch):
def test_probe_model_treats_a_503_as_final(monkeypatch):
- """ "No retries" must include the storm branch. rotate_with_retries' capacity-storm
- branch does NOT consume max_attempts, so max_attempts=1 alone still retried a 503
- up to 60 times (bounded only by the 900 s deadline) — a "30-second" probe that could
- take 15 minutes. Observed 2026-08-24 in the parked compare_v2 preflight log."""
+ """"No retries" includes the storm branch, which max_attempts alone does not bound."""
import codeverse3d.models.gemini as gm
from codeverse3d.models.health import _bare_model
@@ -71,9 +67,7 @@ def test_probe_model_treats_a_503_as_final(monkeypatch):
return "unused"
monkeypatch.setattr(gm, "rotate_with_retries", fake_rotate)
- # a non-live test must pass with NO credentials in the environment (a fresh clone,
- # the CI runner): _bare_model builds a real GeminiModel, which refuses to construct
- # without keys, so hand it a fake one instead of borrowing this box's (PORT-2).
+ # a non-live test must pass with no credentials (PORT-2)
monkeypatch.setattr(gm, "_default_keys", lambda: ["fake-key-for-tests"])
m = _bare_model("gemini:gemini-3.7-flash", 30.0)
assert m.storm_attempts == 0 and m.max_attempts == 1
diff --git a/harness/tests/models/test_keypool.py b/harness/tests/models/test_keypool.py
index f09f02a6..b6a7f87b 100644
--- a/harness/tests/models/test_keypool.py
+++ b/harness/tests/models/test_keypool.py
@@ -26,11 +26,6 @@ def make(keys=("k1", "k2", "k3"), **kw) -> tuple[KeyPool, Clock]:
return KeyPool(list(keys), clock=c, sleep=c.sleep, **kw), c
-def test_round_robin_order():
- pool, _ = make()
- assert [pool.acquire() for _ in range(4)] == ["k1", "k2", "k3", "k1"]
-
-
def test_dedupes_and_rejects_empty():
pool, _ = make(keys=("a", "a", "", "b"))
assert pool.keys == ["a", "b"]
@@ -38,26 +33,6 @@ def test_dedupes_and_rejects_empty():
KeyPool([])
-def test_429_cools_key_down_and_rotates():
- pool, clock = make(cooldown_s=30)
- k = pool.acquire()
- assert k == "k1"
- pool.report(k, "429")
- # next acquires skip k1 while it cools
- assert [pool.acquire() for _ in range(4)] == ["k2", "k3", "k2", "k3"]
- clock.t += 31
- assert "k1" in [pool.acquire() for _ in range(3)]
- st = pool.stats()
- assert st["429"] == 1 and st["n_keys"] == 3
-
-
-def test_exclude_skips_failed_keys():
- pool, _ = make()
- assert pool.acquire(exclude={"k1", "k2"}) == "k3"
- with pytest.raises(KeyPoolExhausted):
- pool.acquire(exclude={"k1", "k2", "k3"})
-
-
def test_all_cooling_blocks_until_cooldown_ends():
# a cooldown longer than the house cap is clipped to it: no single wait may
# exceed MAX_WAIT_S, patience comes from the number of attempts
@@ -89,26 +64,6 @@ def test_health_score_prefers_healthy_keys():
assert s["…bad"]["health"] > 0.9
-def test_thread_safety_smoke():
- pool = KeyPool([f"k{i}" for i in range(5)])
- counts: dict[str, int] = {}
- lock = threading.Lock()
-
- def worker():
- for _ in range(200):
- k = pool.acquire()
- pool.report(k, "ok")
- with lock:
- counts[k] = counts.get(k, 0) + 1
-
- ts = [threading.Thread(target=worker) for _ in range(8)]
- for t in ts:
- t.start()
- for t in ts:
- t.join()
- assert sum(counts.values()) == 1600 and len(counts) == 5
-
-
def test_dead_key_is_benched_for_a_long_time_then_reprobed():
pool, clock = make(keys=("dead", "ok"), cooldown_s=30, dead_cooldown_s=3600)
pool.report("dead", "dead")
@@ -153,8 +108,6 @@ def test_try_acquire_never_waits_for_a_key_or_a_slot(tmp_path):
def test_the_in_flight_slot_wait_is_bounded_by_timeout(tmp_path):
- """acquire()'s max_in_flight wait used to be unbounded; the same timeout budget now
- bounds it and raises the pool's own error shape."""
pool = KeyPool(["a"], max_in_flight=1, slots_dir=tmp_path)
pool.acquire()
t0 = time.monotonic()
@@ -166,8 +119,7 @@ def test_the_in_flight_slot_wait_is_bounded_by_timeout(tmp_path):
def test_skip_leaves_health_and_counters_alone():
- """A charged-but-invalid reply (bad JSON) is not the key's fault: it used to be
- reported "ok", boosting health and counting as a success in doctor --live."""
+ """A charged-but-invalid reply (bad JSON) is not the key's fault."""
pool, _ = make(keys=("a",))
pool.report("a", "429")
before = {k["key"]: k for k in pool.stats()["keys"]}["…a"]
diff --git a/harness/tests/models/test_openai.py b/harness/tests/models/test_openai.py
index 27863b63..1cf94667 100644
--- a/harness/tests/models/test_openai.py
+++ b/harness/tests/models/test_openai.py
@@ -207,8 +207,7 @@ def test_base_url_from_settings(monkeypatch):
def test_a_failed_reply_carries_what_it_was_billed():
- """Both raise sites had ``usage`` in hand (built two lines above) and dropped it:
- a bad-JSON or empty completion is billed exactly like a good one."""
+ """A bad-JSON or empty completion is billed on the error, reasoning split out (D84)."""
for script, req in (
(
[completion("not json", finish="length")],
@@ -226,21 +225,3 @@ def test_a_failed_reply_carries_what_it_was_billed():
assert u.input_tokens == 100 and u.output_tokens == 20 and u.thoughts_tokens == 10
-def test_each_attempt_gets_what_is_left_of_the_call_budget():
- """Same deadline contract as the anthropic adapter: the SDK client is built once with
- a fixed 600 s timeout, so the per-call ``max_wait_s`` has to reach ``create()``."""
- m, fc = make([completion("hi")], timeout_s=600.0)
- m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=25.0))
- assert 20.0 <= fc.calls[0]["timeout"] <= 25.0
-
- m, fc = make([completion("hi")], timeout_s=600.0)
- m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=5.0))
- assert fc.calls[0]["timeout"] == 20.0, "a near-dead budget still buys ONE real attempt"
-
- m, fc = make([completion("hi")], timeout_s=600.0)
- m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=930.0))
- assert fc.calls[0]["timeout"] == 600.0, "a long plan is bounded by the client, not clipped"
-
- m, fc = make([completion("hi")], timeout_s=600.0)
- m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
- assert fc.calls[0]["timeout"] == 600.0
diff --git a/harness/tests/models/test_pricing.py b/harness/tests/models/test_pricing.py
index ffd25d6d..e7ea0889 100644
--- a/harness/tests/models/test_pricing.py
+++ b/harness/tests/models/test_pricing.py
@@ -4,8 +4,10 @@ from __future__ import annotations
import logging
+import pytest
+
from codeverse3d.contracts.common import Usage
-from codeverse3d.models.pricing import PRICES, cache_write_surcharge, estimate_cost, lookup_price
+from codeverse3d.models.pricing import PRICES, estimate_cost, lookup_price
def test_gemini_cost_math():
@@ -16,62 +18,36 @@ def test_gemini_cost_math():
assert abs(estimate_cost("gemini", "gemini-3.7-flash", u) - (0.45 + 0.03 + 0.5625)) < 1e-9
-def test_price_lookup_respects_family_boundaries(caplog):
- caplog.set_level(logging.WARNING)
- assert (
- lookup_price("anthropic", "claude-opus-5-20260301")
- is PRICES[("anthropic", "claude-opus-5")]
- )
- assert lookup_price("openai", "gpt-5.5-2026") is PRICES[("openai", "gpt-5.5")]
- assert lookup_price("openai", "gpt-5") is PRICES[("openai", "gpt-5")]
- assert lookup_price("openai", "gpt-55") is None
- assert (
- lookup_price("gemini", "gemini-3.7-flash-preview-09")
- is PRICES[("gemini", "gemini-3.7-flash")]
- )
- assert lookup_price("openai", "gpt-4.1-nano") is PRICES[("openai", "gpt-4.1-nano")]
- assert lookup_price("openai", "o3-mini") is PRICES[("openai", "o3-mini")]
- assert lookup_price("openai", "o3-pro") is PRICES[("openai", "o3-pro")]
- assert lookup_price("openai", "gpt-5-codex") is PRICES[("openai", "gpt-5-codex")]
- u = Usage(input_tokens=1_000_000, output_tokens=1_000_000)
- assert abs(estimate_cost("openai", "gpt-4.1-nano", u) - 0.50) < 1e-9
- for prov, m in [
- ("openai", "gpt-5.4-mini"),
- ("openai", "gpt-5.7"), # ".7" is a different minor version, not a date tag
- ("gemini", "gemini-3.7-flash-lite"),
- ("gemini", "gemini-2.5-flash-imagine"),
- ("anthropic", "claude-opus-5-turbo"),
- ]:
- assert lookup_price(prov, m) is None, m
- assert estimate_cost(prov, m, u) == 0.0, m
- assert any(m in r.message for r in caplog.records), m
- assert lookup_price("openai", "gpt-4o-2024-08-06") is PRICES[("openai", "gpt-4o")]
- assert (
- lookup_price("gemini", "gemini-2.5-flash-preview-05-20")
- is PRICES[("gemini", "gemini-2.5-flash")]
- )
- assert (
- lookup_price("gemini", "gemini-2.5-flash-image-preview")
- is PRICES[("gemini", "gemini-2.5-flash-image")]
- )
- assert (
- lookup_price("anthropic", "claude-sonnet-5@20260301")
- is PRICES[("anthropic", "claude-sonnet-5")]
- )
- assert (
- lookup_price("gemini", "gemini-3.7-flash-latest") is PRICES[("gemini", "gemini-3.7-flash")]
- )
-def test_unknown_model_zero_and_warns_once(caplog):
- caplog.set_level(logging.WARNING)
- u = Usage(input_tokens=10, output_tokens=10)
- assert estimate_cost("gemini", "nope-model-x", u) == 0.0
- assert estimate_cost("gemini", "nope-model-x", u) == 0.0
- assert sum("nope-model-x" in r.message for r in caplog.records) == 1
+ ("provider", "model", "row"),
+ [
+ ("anthropic", "claude-opus-5-20260301", "claude-opus-5"),
+ ("anthropic", "claude-sonnet-5@20260301", "claude-sonnet-5"),
+ ("openai", "gpt-5.5-2026", "gpt-5.5"),
+ ("openai", "gpt-5", "gpt-5"),
+ ("openai", "gpt-4o-2024-08-06", "gpt-4o"),
+ ("gemini", "gemini-3.7-flash-preview-09", "gemini-3.7-flash"),
+ ("gemini", "gemini-3.7-flash-latest", "gemini-3.7-flash"),
+ ("gemini", "gemini-2.5-flash-image-preview", "gemini-2.5-flash-image"),
+ ],
+)
+def test_a_dated_or_tagged_id_prices_on_its_family_row(provider, model, row):
+ assert lookup_price(provider, model) is PRICES[(provider, row)]
-def test_cache_write_surcharge():
- # opus-5: write 6.25 vs input 5.00 → 1.25 per 1M extra
- assert abs(cache_write_surcharge("anthropic", "claude-opus-5", 1_000_000) - 1.25) < 1e-9
- assert cache_write_surcharge("gemini", "gemini-3.7-flash", 1000) == 0.0
+ ("provider", "model"),
+ [
+ ("openai", "gpt-55"),
+ ("openai", "gpt-5.7"), # ".7" is a different minor version, not a date tag
+ ("gemini", "gemini-3.7-flash-lite"),
+ ("anthropic", "claude-opus-5-turbo"),
+ ],
+)
+def test_a_different_family_is_unpriced_and_warned(provider, model, caplog):
+ caplog.set_level(logging.WARNING)
+ assert lookup_price(provider, model) is None
+ assert estimate_cost(provider, model, Usage(input_tokens=10, output_tokens=10)) == 0.0
+ assert any(model in r.message for r in caplog.records)
diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.py
index 90456eef..04232fb2 100644
--- a/harness/tests/models/test_retry.py
+++ b/harness/tests/models/test_retry.py
@@ -11,7 +11,6 @@ import pytest
from codeverse3d.models.base import ModelError
from codeverse3d.models.parts import SDK_TIMEOUT_FLOOR_S
from codeverse3d.models.retry import (
- ACQUIRE_TIMEOUT_S,
MAX_WAIT_S,
RETRY_DEADLINE_S,
KeyPool,
@@ -95,14 +94,6 @@ def _boom(msg: str = "503 high demand"):
return call
-def test_rotate_success_reports_ok():
- pool = KeyPool(["k1", "k2"])
- out = _rotate(pool, lambda key: f"ok:{key}")
- assert out == "ok:k1"
- st = pool.stats()
- assert st["ok"] == 1 and st["429"] == 0 and st["dead"] == 0
-
-
def test_rotate_dead_key_is_free_and_benched_after_sibling_success():
pool = KeyPool(["k1", "k2"])
calls: list[str] = []
@@ -159,57 +150,6 @@ def test_rotate_429_is_free_while_untried_keys_remain():
assert max(key["cooldown_s"] for key in stats["keys"]) <= MAX_WAIT_S
-def test_rotate_on_free_retry_hook_consumes_no_budget():
- pool = KeyPool(["k1"])
- state = {"fixed": False}
- calls: list[int] = []
-
- def call(key: str) -> str:
- calls.append(1)
- if not state["fixed"]:
- raise ModelError("thinking not supported", retryable=False, status=400)
- return "ok"
-
- def free(err: ModelError) -> bool:
- if "thinking" in str(err) and not state["fixed"]:
- state["fixed"] = True
- return True
- return False
-
- assert _rotate(pool, call, max_attempts=1, on_free_retry=free) == "ok"
- assert len(calls) == 2
-
-
-def test_rotate_retryable_backoff_and_nonretryable_failure_modes():
- pool = KeyPool(["k1"])
- slept: list[float] = []
-
- def retryable(key: str) -> str:
- raise ModelError("unavailable", retryable=True, status=500)
-
- with pytest.raises(ModelError) as ei:
- _rotate(
- pool,
- retryable,
- max_attempts=3,
- base_delay=1.0,
- max_delay=4.0,
- sleep=slept.append,
- )
- assert ei.value.status == 500 and len(slept) == 2 # backoff between the 3 attempts
- assert ei.value.attempts == 3, "the raised error says how many round-trips it took (the ledger's error row)"
-
- calls: list[str] = []
-
- def nonretryable(key: str) -> str:
- calls.append(key)
- raise ModelError("bad request", retryable=False, status=400)
-
- with pytest.raises(ModelError):
- _rotate(KeyPool(["k1", "k2"]), nonretryable, max_attempts=5)
- assert calls == ["k1"]
-
-
# --------------------------------------------------------------------------- 503 storms
@pytest.mark.parametrize(("hedge", "want_calls", "want_naps"), [(1, {9}, 7), (2, {9, 10}, 4)])
def test_503_storm_has_its_own_patience_budget(hedge, want_calls, want_naps):
@@ -303,71 +243,6 @@ def test_the_deadline_does_not_cut_a_call_that_is_making_progress():
assert out == "ok" and calls["n"] == 3
-def test_503_rotates_through_every_untried_key_before_it_is_a_storm():
- """A 503 rotates freely while the pool still has an untried key."""
- keys = [f"k{i}" for i in range(1, 11)]
- lock = threading.Lock()
- calls: list[str] = []
- naps: list[float] = []
-
- def call(key):
- with lock: # hedged siblings run in threads
- calls.append(key)
- nth = len(set(calls))
- if nth < len(keys): # only the LAST untried key answers
- raise RuntimeError("503 high demand")
- return "ok"
-
- stats: dict = {}
- out = _rotate503(
- _pool(10),
- call,
- max_attempts=3,
- storm_attempts=10,
- storm_max_delay=0.05,
- sleep=naps.append,
- stats=stats,
- )
- # one key per round-trip, never twice: 9 free rotations, then the 10th key lands
- assert out == "ok" and len(calls) == len(keys) and set(calls) == set(keys)
- assert naps == [], "rotation to a fresh key costs no sleep"
- assert stats["storm"] == 0, "an untried key remains: not a storm"
-
-
- ("hedge", "want_calls", "want_stats"),
- [
- (1, {6}, {"attempts": 6, "hedged": 0, "storm": 3}),
- (2, {6, 7}, {"attempts": 7, "hedged": 3, "storm": 2}),
- ],
-)
-def test_503_on_every_key_is_still_a_storm(hedge, want_calls, want_stats):
- """Exhausting every key engages one bounded wait per hedged attempt."""
- lock = threading.Lock()
- n = {"c": 0}
- stats: dict = {}
-
- def call(key):
- with lock:
- n["c"] += 1
- i = n["c"]
- if i <= 5:
- raise RuntimeError("503 high demand")
- return "ok"
-
- out = _rotate503(
- _pool(3),
- call,
- max_attempts=3,
- storm_attempts=10,
- storm_max_delay=0.0,
- hedge=hedge,
- stats=stats,
- )
- assert out == "ok" and n["c"] in want_calls
- assert stats == want_stats, "declared only after all three keys failed, then waited out"
-
-
# --------------------------------------------------------------------------- hedging (audit 2026-08-26 §5.2)
def _wait_idle(pool, timeout: float = 5.0) -> None:
"""Block until every hedged loser has finished and released its slot."""
@@ -423,72 +298,6 @@ def test_after_the_first_503_the_next_attempt_is_hedged_and_the_first_success_wi
assert st["5xx"] == 2 and st["in_flight"] == 0, "the loser's 503 is reported when it lands"
-def test_a_loser_that_succeeds_later_is_discarded_but_reported_to_its_key():
- """A late successful loser is discarded, and its key still hears the success."""
- pool = KeyPool(["k1", "k2", "k3"])
- release_k2 = threading.Event()
-
- def call(key):
- if key == "k1":
- raise ModelError("503 high demand", retryable=True, status=503)
- if key == "k2":
- assert release_k2.wait(5.0)
- return "late:k2"
- return "ok:k3"
-
- out = _rotate(
- pool,
- call,
- max_attempts=3,
- storm_attempts=10,
- )
- assert out == "ok:k3"
- release_k2.set()
- _wait_idle(pool)
- assert pool.stats()["ok"] == 2
- assert pool._by_key["k2"].n_ok == 1 and pool._by_key["k3"].n_ok == 1 # noqa: SLF001
-
-
-def test_hedge_1_disables_and_a_full_pool_of_slots_degrades_to_one_key(tmp_path):
- lock = threading.Lock()
-
- def make_call():
- n = {"c": 0}
-
- def call(key):
- with lock:
- n["c"] += 1
- i = n["c"]
- if i <= 3:
- raise ModelError("503 high demand", retryable=True, status=503)
- return "ok"
-
- return call
-
- stats: dict = {}
- _rotate(
- _pool(3),
- make_call(),
- max_attempts=3,
- storm_attempts=10,
- storm_max_delay=0.0,
- hedge=1,
- stats=stats,
- )
- assert stats["hedged"] == 0 and stats["attempts"] == 4
- # max_in_flight=1: the primary holds the only slot, so a partner is never waited for
- pool = _pool(3, max_in_flight=1, slots_dir=tmp_path / "one")
- stats = {}
- _rotate(pool, make_call(), max_attempts=3, storm_attempts=10, storm_max_delay=0.0, stats=stats)
- assert stats["hedged"] == 0 and stats["attempts"] == 4 and pool.stats()["peak_in_flight"] == 1
- # max_in_flight=2: a hedged attempt holds both slots
- pool = _pool(3, max_in_flight=2, slots_dir=tmp_path / "two")
- stats = {}
- _rotate(pool, make_call(), max_attempts=3, storm_attempts=10, storm_max_delay=0.0, stats=stats)
- _wait_idle(pool)
- assert stats["hedged"] >= 1 and pool.stats()["peak_in_flight"] == 2
-
-
def test_the_worst_error_decides_a_hedged_attempt():
"""A nonretryable hedge error outranks a sibling 503."""
pool = _pool(3)
@@ -504,40 +313,7 @@ def test_the_worst_error_decides_a_hedged_attempt():
assert ei.value.status == 400 and stats == {"attempts": 3, "hedged": 1, "storm": 0}
-def test_a_dead_key_among_the_hedge_is_benched_once_the_sibling_wins():
- pool = _pool(3)
-
- def call(key):
- if key == "k1":
- raise ModelError("503 high demand", retryable=True, status=503)
- if key == "k2":
- raise ModelError("suspended", retryable=False, status=403)
- return "ok:k3"
-
- assert _rotate(pool, call, max_attempts=3, storm_attempts=10) == "ok:k3"
- _wait_idle(pool)
- assert pool.stats()["n_dead"] == 1, (
- "k3 proved the request fine, so k2's 403 was the key's fault"
- )
-
-
# --------------------------------------------------------------------------- deadline threading (2026-08-27)
-def test_the_key_wait_is_clipped_to_the_remaining_budget():
- """Pool acquisition cannot outwait the remaining call budget."""
- seen: list[float | None] = []
-
- class SpyPool(KeyPool):
- def acquire(self, *, exclude=None, timeout_s=None):
- seen.append(timeout_s)
- return super().acquire(exclude=exclude, timeout_s=timeout_s)
-
- pool = SpyPool(["k1"])
- assert _rotate(pool, lambda key: "ok", max_total_s=50.0) == "ok"
- assert _rotate(pool, lambda key: "ok") == "ok" # the default budget: the pool default caps
- assert seen[0] == pytest.approx(50.0, abs=1.0)
- assert seen[1] == pytest.approx(ACQUIRE_TIMEOUT_S, abs=1.0)
-
-
def test_a_storm_wait_is_clipped_to_the_remaining_budget():
"""Sleeping past the deadline only to give up on waking helps nobody."""
clock = Clock()
diff --git a/harness/tests/models/test_schema_utils.py b/harness/tests/models/test_schema_utils.py
index 55166122..0832e7fc 100644
--- a/harness/tests/models/test_schema_utils.py
+++ b/harness/tests/models/test_schema_utils.py
@@ -6,14 +6,13 @@ import json
import pytest
from google.genai import types
-from pydantic import BaseModel, ValidationError
+from pydantic import BaseModel
from codeverse3d.contracts.plan import ArticulatedPlan, ScenePlan, StaticPlan
from codeverse3d.models.schema_utils import (
JsonParseError,
inline_refs,
parse_json_lenient,
- to_anthropic_schema,
to_gemini_schema,
to_openai_strict_schema,
)
@@ -150,45 +149,6 @@ def _accepts_null(sub) -> bool:
)
-def test_openai_strict_schema_rejects_nulls_that_pydantic_rejects():
- jsonschema = pytest.importorskip("jsonschema")
- strict = to_openai_strict_schema(StaticPlan.model_json_schema())
- bbox = {"center": [0, 0, 0.5], "extents": [1, 1, 1]}
- part = {
- "name": "Seat",
- "role": "r",
- "description": "d",
- "bbox": bbox,
- "material": "",
- "attach_to": None,
- "symmetry": "none",
- "instances": 1,
- "children": [],
- "detail_hint": "",
- }
- good = {
- "object_name": "Chair",
- "summary": "x",
- "overall_bbox": bbox,
- "style_notes": "",
- "parts": [part],
- "acceptance": [],
- }
- jsonschema.validate(good, strict)
- StaticPlan.model_validate(good)
- bad = {**good, "style_notes": None, "parts": [{**part, "material": None, "instances": None}]}
- with pytest.raises(jsonschema.ValidationError):
- jsonschema.validate(bad, strict) # the model is not allowed to answer like this
- with pytest.raises(ValidationError):
- StaticPlan.model_validate(bad) # … because the contract would reject it
-
-
-def test_anthropic_schema_shape():
- s = to_anthropic_schema(ScenePlan.model_json_schema())
- assert "$defs" not in s and s["additionalProperties"] is False
- assert s["properties"]["bounds"]["properties"]["center"]["items"] == {"type": "number"}
-
-
def test_parse_json_lenient_accepts_wrappers_and_rejects_non_json():
for text in (
'{"a": 1}',
@@ -208,9 +168,7 @@ def test_parse_json_lenient_accepts_wrappers_and_rejects_non_json():
def test_ask_structured_returns_the_triple_for_prose_it_cannot_parse():
- """The five callers branch on the error string; none of them catches. Every shipped
- provider raises ModelError on unparseable structured output, but this must not depend
- on all three keeping that half of the ChatModel contract."""
+ """The callers branch on the error string; a provider that returns prose must not raise."""
from codeverse3d.contracts.chat import ChatResponse
from codeverse3d.contracts.common import Usage
from codeverse3d.models.schema_utils import ask_structured
@@ -219,8 +177,6 @@ def test_ask_structured_returns_the_triple_for_prose_it_cannot_parse():
ok: bool
class Prose:
- """A ChatModel that hands back text instead of raising (base.py:22-30 says it should)."""
-
def generate(self, request):
return ChatResponse(text="I refuse.", usage=Usage(cost_usd=0.01))
@@ -229,10 +185,7 @@ def test_ask_structured_returns_the_triple_for_prose_it_cannot_parse():
def test_ask_structured_returns_the_usage_a_failed_call_was_billed():
- """A bad-JSON reply is charged like a good one — ModelError carries that usage, and
- ask_structured used to drop it (return Usage()), so every caller-side tally
- (BudgetGuard.charge, refset.usage, record.json spend) undercounted while the
- metered ledger recorded the real bill."""
+ """A bad-JSON reply is charged like a good one: the caller's tally gets the billed usage."""
from codeverse3d.contracts.common import Usage
from codeverse3d.models.base import ModelError
from codeverse3d.models.schema_utils import ask_structured
diff --git a/harness/tests/models/test_slots.py b/harness/tests/models/test_slots.py
index 729aa9f7..1144a655 100644
--- a/harness/tests/models/test_slots.py
+++ b/harness/tests/models/test_slots.py
@@ -12,13 +12,10 @@ import os
import signal
import subprocess
import sys
-import threading
import time
from pathlib import Path
-import pytest
-
-from codeverse3d.models.retry import KeyPoolExhausted, Slots
+from codeverse3d.models.retry import Slots
HARNESS = Path(__file__).resolve().parents[2]
@@ -97,33 +94,6 @@ def test_n_plus_k_processes_never_have_more_than_n_in_flight(tmp_path: Path) ->
assert wall >= (n + k) * holds * hold_s / n - 0.05, "finished faster than 4 slots allow"
-def test_a_smaller_cap_uses_only_its_own_first_slots(tmp_path: Path) -> None:
- """Processes with different caps share one directory: three at N=2 and three at N=4 never
- exceed 4 together, and the N=2 three never exceed 2 among themselves — the machine is
- held to the largest cap anyone asks for, and each process to its own."""
- small = [_python(_CONTENDER, tmp_path, 2, 4, 0.1) for _ in range(3)]
- big = [_python(_CONTENDER, tmp_path, 4, 4, 0.1) for _ in range(3)]
- runs: dict[str, list[tuple[float, float]]] = {"small": [], "big": []}
- try:
- for p in small + big:
- assert p.stdout.readline().strip() == "ready", p.stderr.read()
- for p in small + big:
- p.stdin.write("go\n")
- p.stdin.flush()
- for name, group in (("small", small), ("big", big)):
- for p in group:
- out, err = p.communicate(timeout=60)
- assert p.returncode == 0, err
- runs[name] += [tuple(json.loads(line)) for line in out.splitlines() if line.startswith("[")]
- finally:
- for p in small + big:
- p.kill()
- both, alone = _peak(runs["small"] + runs["big"]), _peak(runs["small"])
- print(f"\n(a') caps 2 and 4 in one directory: peak {both} together, {alone} among the N=2 processes")
- assert len(runs["small"]) == len(runs["big"]) == 12
- assert both <= 4 and alone <= 2
-
-
def test_a_process_killed_holding_a_slot_frees_it_at_once(tmp_path: Path) -> None:
"""(b) SIGKILL runs no cleanup code; the kernel drops a dead process's flock anyway, so
a waiter gets the slot within one poll — no stale-lock timeout, no pid file to reap."""
@@ -145,64 +115,3 @@ def test_a_process_killed_holding_a_slot_frees_it_at_once(tmp_path: Path) -> Non
assert freed_after < 1.0
-def test_threads_of_one_process_share_the_slots(tmp_path: Path) -> None:
- """(c) flock locks an open file DESCRIPTION and every take opens its own, so threads of
- one process exclude each other exactly like processes do: 12 threads on 3 slots never
- hold more than 3, and two threads cannot both hold a 1-slot pool."""
- one = Slots(1, tmp_path / "one")
- fd = one.take(1.0)
- got: list[int | None] = []
- t = threading.Thread(target=lambda: got.append(one.try_take()))
- t.start()
- t.join(5)
- assert got == [None], "a second thread of the same process took the held slot"
- Slots.give(fd)
-
- n, threads, holds, hold_s = 3, 12, 4, 0.05
- slots = Slots(n, tmp_path / "three")
- lock = threading.Lock()
- intervals: list[tuple[float, float]] = []
-
- def worker() -> None:
- for _ in range(holds):
- fd = slots.take(30.0)
- t0 = time.monotonic()
- time.sleep(hold_s)
- t1 = time.monotonic()
- Slots.give(fd)
- with lock:
- intervals.append((t0, t1))
-
- t_go = time.monotonic()
- pool = [threading.Thread(target=worker) for _ in range(threads)]
- for w in pool:
- w.start()
- for w in pool:
- w.join(60)
- wall = time.monotonic() - t_go
- peak = _peak(intervals)
- print(f"\n(c) {threads} threads x {holds} holds x {hold_s}s on {n} slots: peak {peak}, "
- f"wall {wall:.2f}s (floor {threads * holds * hold_s / n:.2f}s)")
- assert len(intervals) == threads * holds and peak == n
- assert slots.busy() == 0, "every slot came back"
-
-
[email protected]("timeout_s", [0.0, 0.3])
-def test_a_waiter_gives_up_at_its_deadline(tmp_path: Path, timeout_s: float) -> None:
- """(d) Every slot held by another process: a waiter raises the pool's own error at its
- deadline — not before it, and without sleeping on past it (the last nap is clipped)."""
- slots = Slots(2, tmp_path)
- holders = [_python(_HOLDER, tmp_path, 2) for _ in range(2)]
- try:
- for h in holders:
- assert h.stdout.readline().strip() == "held", h.stderr.read()
- t0 = time.monotonic()
- with pytest.raises(KeyPoolExhausted, match="in-flight slots"):
- slots.take(timeout_s=timeout_s)
- waited = time.monotonic() - t0
- finally:
- for h in holders:
- h.kill()
- h.wait(10)
- print(f"\n(d) deadline {timeout_s}s: gave up after {waited:.3f}s")
- assert timeout_s <= waited < timeout_s + 0.2