Skip to content

Official Codebase of 3DCodeVerse

Python

tests: models, cost, agents, third pass — 20 exceptions did not hold, 15 twins fold (233 → 198, −319 lines)

gaoypeng79ec0b41c9f1
diff --git a/harness/tests/agents/test_cli_common.py b/harness/tests/agents/test_cli_common.py
index 985978ac..d667caeb 100644
--- a/harness/tests/agents/test_cli_common.py
+++ b/harness/tests/agents/test_cli_common.py
@@ -6,7 +6,6 @@ import json
import os
from codeverse3d.agents.cli_common import (
- attribute_changes,
begin_session,
clean_env,
finish_session,
@@ -17,12 +16,12 @@ from codeverse3d.agents.cli_common import (
is_transient_failure,
provider_wait,
)
-from codeverse3d.contracts.agent import AgentJob, FileChange
+from codeverse3d.contracts.agent import AgentJob
from codeverse3d.contracts.common import Usage
from codeverse3d.workspace import Workspace
-def test_clean_env_drops_secrets_but_the_kept_ones(monkeypatch):
+def test_clean_and_hardened_env_drop_secrets_but_the_kept_ones(monkeypatch, tmp_ws: Workspace):
for name in ("OPENAI_API_KEY", "FOO_TOKEN", "GEMINI_API_KEYS", "CODEX_API_KEY"):
monkeypatch.setenv(name, "s")
monkeypatch.setenv("NODE_OPTIONS", "--x")
@@ -30,9 +29,7 @@ def test_clean_env_drops_secrets_but_the_kept_ones(monkeypatch):
assert not {"OPENAI_API_KEY", "FOO_TOKEN", "GEMINI_API_KEYS"} & set(env)
assert env["CODEX_API_KEY"] == "s" and env["NODE_OPTIONS"] == "--x" and "PATH" in env and "HOME" in env
assert env["C3D_AGENT_CONTEXT"] == "1" and "GIT_CEILING_DIRECTORIES" not in env
-
-
-def test_hardened_env_adds_the_job_env_and_the_git_ceiling(tmp_ws: Workspace):
+ # the hardened env adds the job's env and the git ceiling, and still drops the secrets
env = hardened_env(tmp_ws, AgentJob(workspace=str(tmp_ws.root), prompt="p", env={"EXTRA": "2"}), keep=set())
assert env["EXTRA"] == "2" and env["GIT_CEILING_DIRECTORIES"] == str(tmp_ws.root.parent)
assert "FAKE_SERVICE_API_KEY" not in env
@@ -58,15 +55,6 @@ def test_retry_same_label_round_keeps_first_attempt_trajectory(tmp_ws: Workspace
assert "agent:baseline.a2" in log and "pre:baseline" in log
-def test_attribute_changes_pure():
- files = [FileChange(path=p, status="modified") for p in (
- "src/zones/a.js", "src/zones/b.js", "src/assets/x.js", "events.jsonl", "artifacts/census.json",
- "trajectories/zone_a_r00/result.json", "public/assets/y.glb", "README.md", "AGENTS.md")]
- got = attribute_changes(files, write_roots=["src", "public"])
- assert [f.path for f in got] == ["src/zones/a.js", "src/zones/b.js", "src/assets/x.js", "public/assets/y.glb"]
- assert [f.path for f in attribute_changes(files, write_roots=["public"])] == ["public/assets/y.glb"]
-
-
def test_the_prompt_goes_on_stdin_byte_for_byte_and_never_on_argv(tmp_ws: Workspace):
"""A 200 kB, 2 500-line prompt (past argv's 128 KiB cap) reaches the CLI whole."""
import sys
diff --git a/harness/tests/agents/test_codex.py b/harness/tests/agents/test_codex.py
index 6b4c61e3..ae2bd90f 100644
--- a/harness/tests/agents/test_codex.py
+++ b/harness/tests/agents/test_codex.py
@@ -67,20 +67,16 @@ def test_reasoning_tokens_are_not_billed_twice():
assert u.cost_usd == pytest.approx(1000 * 4.0 / 1e6 + 9000 * 20.0 / 1e6)
-def test_argv_sandboxes_the_workspace_and_approves_mcp_calls(tmp_ws: Workspace):
+def test_argv_sandboxes_the_workspace_approves_mcp_calls_and_states_the_effort(tmp_ws: Workspace):
a = CodexAgent("gpt-5.6-sol", binary="codex")
argv = a.build_argv(begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p"), "codex"))
assert argv[argv.index("--sandbox") + 1] == "workspace-write"
# codex exec has nobody to answer the per-tool approval elicitation → every MCP call would be cancelled
assert 'mcp_servers.3dcode.default_tools_approval_mode="approve"' in argv
- s2 = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", spatial_tools=False), "codex")
- assert "mcp_servers" not in " ".join(a.build_argv(s2))
-
-
-def test_reasoning_effort_is_explicit(tmp_ws: Workspace, monkeypatch):
- """`codex exec` defaults to medium; every harness call states the effort instead."""
s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", spatial_tools=False), "codex")
- argv = CodexAgent("gpt-5.6-sol", binary="codex").build_argv(s)
+ argv = a.build_argv(s)
+ assert "mcp_servers" not in " ".join(argv)
+ # `codex exec` defaults to medium; every harness call states the effort instead
assert argv[argv.index("-c") + 1] == "model_reasoning_effort=high"
a = CodexAgent("gpt-5.6-terra@medium", binary="codex")
assert (a.model, a.reasoning_effort, a.id) == ("gpt-5.6-terra", "medium", "codex:gpt-5.6-terra")
@@ -92,7 +88,7 @@ def test_reasoning_effort_is_explicit(tmp_ws: Workspace, monkeypatch):
CodexAgent("gpt-5.6-sol", binary="codex", reasoning_effort="ludicrous")
-def test_fake_run(tmp_ws: Workspace, fake_bin, monkeypatch):
+def test_fake_run_and_every_failure_is_typed(tmp_ws: Workspace, fake_bin, monkeypatch):
a = CodexAgent("gpt-5.6-sol", binary=fake_bin("codex", FAKE_CODEX))
res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="x", timeout_s=30))
assert res.ok and res.exit_reason == "completed" and res.text == "Done." and res.tool_calls == 2, res.errors
@@ -105,10 +101,7 @@ def test_fake_run(tmp_ws: Workspace, fake_bin, monkeypatch):
res2 = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="y", timeout_s=30))
assert not res2.ok and res2.exit_reason == "error" and "boom" in res2.errors[0]
assert not res2.transient and not res2.quota # the task's own failure
-
-
-def test_a_codex_failure_is_typed_quota_or_transient(tmp_ws: Workspace, fake_bin, monkeypatch):
- a = CodexAgent("gpt-5.6-sol", binary=fake_bin("codex", FAKE_CODEX))
+ # a provider failure is typed quota or transient
monkeypatch.setenv("FAKE_MODE", "usage_limit")
res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="q", timeout_s=30))
assert not res.ok and res.quota and not res.transient
diff --git a/harness/tests/agents/test_gemini_cli.py b/harness/tests/agents/test_gemini_cli.py
index a6e8e610..e2d2668e 100644
--- a/harness/tests/agents/test_gemini_cli.py
+++ b/harness/tests/agents/test_gemini_cli.py
@@ -187,13 +187,6 @@ def test_agent_planted_mcp_server_never_reaches_the_cli(tmp_ws: Workspace, agent
assert settings["security"]["folderTrust"]["enabled"] is False
-def test_model_substitution_detected(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
- monkeypatch.setenv("FAKE_MODE", "substitute")
- res = agent.run(_job(tmp_ws))
- assert not res.ok and res.exit_reason == "model_substituted"
- assert "gemini-9-pro" in res.errors[0]
-
-
def test_single_key_transient_failure_retries_same_key_and_never_raises(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
"""Settings with ONE key: the retry must reuse it (no KeyPoolExhausted out of run())."""
@@ -242,23 +235,6 @@ def test_pool_exhausted_before_first_attempt_is_a_budget_result(tmp_ws: Workspac
assert not res.ok and res.exit_reason == "budget" and "exhausted" in res.errors[0]
-def test_a_cli_session_holds_no_in_flight_slot(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
- """The machine-wide in-flight slots are for API calls; a session takes only its key."""
- from codeverse3d.agents import backends as gc
-
- pool = gc._key_pool(get_settings().gemini_api_keys) # noqa: SLF001
- seen: list[int] = []
-
- def boom(*a, **k):
- seen.append(pool.stats()["in_flight"])
- raise OSError("cannot spawn")
-
- monkeypatch.setattr(gc, "invoke", boom)
- with pytest.raises(OSError, match="cannot spawn"):
- agent.run(_job(tmp_ws))
- assert seen == [0] and pool.stats()["in_flight"] == 0
-
-
def test_a_timeout_after_a_503_streak_is_marked_transient(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
"""A 503 storm inside the CLI's own retry loop ends on the wall: the result says why (2026-09-07)."""
monkeypatch.setenv("FAKE_MODE", "storm")
@@ -280,6 +256,8 @@ def test_the_key_pool_hears_a_5xx_only_when_the_failure_was_transient(tmp_ws: Wo
monkeypatch.setenv("FAKE_MODE", mode)
res = agent.run(_job(tmp_ws, timeout_s=timeout_s, label=mode))
assert not res.ok and res.transient is False, mode
+ if mode == "substitute": # the served model is checked against the requested one
+ assert res.exit_reason == "model_substituted" and "gemini-9-pro" in res.errors[0]
st = pool.stats()
assert (st["5xx"], st["ok"], st["error"]) == (0, 0, 0), st
monkeypatch.setenv("FAKE_MODE", "fail_once_503") # a real 503, then a rotated success
diff --git a/harness/tests/agents/test_materialize.py b/harness/tests/agents/test_materialize.py
index 7aafaee1..30328781 100644
--- a/harness/tests/agents/test_materialize.py
+++ b/harness/tests/agents/test_materialize.py
@@ -3,10 +3,9 @@
from __future__ import annotations
import json
-import logging
from codeverse3d.agents.cli_common import default_mcp_command
-from codeverse3d.agents.materialize import C3D_DIR, materialize_workspace
+from codeverse3d.agents.materialize import materialize_workspace
from codeverse3d.workspace import Workspace
CONTRACT = "## blender contract\nWrite pure bpy into src/model.py."
@@ -17,17 +16,6 @@ def _mat(ws: Workspace, kind: str = "gemini-cli", spatial: bool = True, cookbook
spatial_tools=spatial, mcp_command=default_mcp_command(ws))
-def test_writes_three_bodies_same_content(tmp_ws: Workspace):
- _mat(tmp_ws)
- bodies = [(tmp_ws.root / n).read_text() for n in ("AGENTS.md", "GEMINI.md", "CLAUDE.md")]
- assert bodies[0] == bodies[1] == bodies[2]
- body = bodies[0]
- assert "ONLY under `src/` and `public/`" in body
- assert "never import from `codeverse3d`" in body.lower()
- assert CONTRACT.splitlines()[0] in body
- assert "Spatial tools (3dcode)" in body
-
-
def test_bodies_document_only_this_tracks_tools(tmp_ws: Workspace):
"""Scene/graphics agents were once taught dead-end object-GLB tools (V11a)."""
tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "scene", "language": "scene_threejs", "prompt": "p"}))
@@ -62,7 +50,7 @@ def test_no_mcp_server_is_written_into_the_workspace(tmp_ws: Workspace):
assert data["context"]["fileFiltering"]["respectGitIgnore"] is False # .gitignore hides artifacts/ + trajectories/
-def test_ignore_files_keep_agent_facing_paths_readable(tmp_ws: Workspace):
+def test_ignore_files_keep_agent_facing_paths_readable_and_a_missing_cookbook_is_said(tmp_ws: Workspace):
"""gemini-cli refuses read_file on ignored paths: census and tool renders stay readable."""
import fnmatch
@@ -91,32 +79,14 @@ def test_ignore_files_keep_agent_facing_paths_readable(tmp_ws: Workspace):
"trajectories/baseline_r00/prompt.md", "trajectories/baseline_r00/gemini_settings.json",
"trajectories/baseline_r00/stderr.log", "node_modules/three/x.js", ".git/HEAD"):
assert ignored(hidden, lines), hidden
-
-
-def test_spatial_disabled_documents_absence(tmp_ws: Workspace):
- _mat(tmp_ws, spatial=False)
- assert "No spatial tools are available" in (tmp_ws.root / "AGENTS.md").read_text()
-
-
-def test_cookbook_copied_when_found(tmp_ws: Workspace, caplog):
- with caplog.at_level(logging.WARNING, logger="codeverse3d.agents.materialize"):
- _mat(tmp_ws, cookbook="# cookbook\nsnippet")
- assert (tmp_ws.root / C3D_DIR / "cookbook.md").read_text() == "# cookbook\nsnippet"
- assert f"{C3D_DIR}/cookbook.md" in (tmp_ws.root / "AGENTS.md").read_text()
- assert not [r for r in caplog.records if r.name == "codeverse3d.agents.materialize"], \
- "a resolved cookbook must not warn"
-
-
-def test_missing_cookbook_warns_where_someone_can_see_it(tmp_ws: Workspace, caplog):
- """The log line is the only signal of an unresolved cookbook."""
- with caplog.at_level(logging.WARNING, logger="codeverse3d.agents.materialize"):
- _mat(tmp_ws, cookbook="")
- assert any("cookbook not found" in r.getMessage() for r in caplog.records)
+ # no cookbook resolved (the default here): the body says so rather than naming a missing file
assert "No cookbook is available" in (tmp_ws.root / "AGENTS.md").read_text()
-def test_kind_specific_tool_hint(tmp_ws: Workspace):
+def test_kind_specific_tool_hint_and_spatial_disabled_documents_absence(tmp_ws: Workspace):
_mat(tmp_ws, kind="claude-code")
assert "mcp__3dcode__" in (tmp_ws.root / "CLAUDE.md").read_text()
_mat(tmp_ws, kind="agy")
assert "codeverse3d.cli.main tools" in (tmp_ws.root / "AGENTS.md").read_text()
+ _mat(tmp_ws, spatial=False)
+ assert "No spatial tools are available" in (tmp_ws.root / "AGENTS.md").read_text()
diff --git a/harness/tests/agents/test_tool_trace.py b/harness/tests/agents/test_tool_trace.py
index 94e43b87..e75243f0 100644
--- a/harness/tests/agents/test_tool_trace.py
+++ b/harness/tests/agents/test_tool_trace.py
@@ -81,28 +81,7 @@ def test_claude_is_launched_streaming(tmp_ws: Workspace):
argv = ClaudeCodeAgent("sonnet", binary="claude").build_argv(s)
assert "Skill" in argv[argv.index("--allowedTools") + 1].split(",")
assert "--disable-slash-commands" not in argv # claude-code: "Disable all skills"
-
-
-FAKE_STREAMING_CLAUDE = r'''
-args = sys.argv[1:]
-assert args[args.index("--output-format") + 1] == "stream-json" and "--verbose" in args
-for ev in json.loads(os.environ["FAKE_EVENTS"]):
- print(json.dumps(ev), flush=True)
-'''
-
-
-def test_a_claude_session_writes_its_trace_into_the_transcript(tmp_ws: Workspace, fake_bin, monkeypatch):
- monkeypatch.setenv("FAKE_EVENTS", json.dumps(CLAUDE_STREAM))
- res = ClaudeCodeAgent("sonnet", binary=fake_bin("claude", FAKE_STREAMING_CLAUDE)).run(
- AgentJob(workspace=str(tmp_ws.root), prompt="build it", label="c", timeout_s=30, spatial_tools=False))
- assert res.ok and res.turns == 25, res.errors
- rows = [json.loads(x) for x in Path(res.transcript_path).read_text().splitlines()]
- calls = [r for r in rows if r["kind"] == TOOL_CALL_ROW]
- trace = [r for r in rows if r["kind"] == TOOL_TRACE_ROW]
- assert [c["tool"] for c in calls] == ["Skill", "Read", "mcp__3dcode__check_contract"]
- assert calls[0]["skill"] == "c3d-bbox-contract" and calls[2]["failed"] is True
- assert trace == [{**trace[0], "calls": 3, "source": "claude-code stream-json"}]
- assert "zz-c3d-read-control" in trace[0]["skills_index"]
+ assert argv[argv.index("--output-format") + 1] == "stream-json" and "--verbose" in argv
# --------------------------------------------------------------------------- gemini-cli
diff --git a/harness/tests/cost/test_audit_read.py b/harness/tests/cost/test_audit_read.py
index 925951ee..52aa8c46 100644
--- a/harness/tests/cost/test_audit_read.py
+++ b/harness/tests/cost/test_audit_read.py
@@ -14,16 +14,14 @@ from codeverse3d.cost.ledger import load_ledger, record_call
from codeverse3d.cost.types import Stage
-def test_a_run_reads_as_its_ledger_rows_and_its_record_facts(fake_run: Path):
+def test_a_run_reads_as_its_ledger_rows_and_its_record_facts(fake_run: Path, tmp_path: Path):
led = read_run(fake_run)
assert led.ledger_usd == pytest.approx(sum(r.cost_usd for r in load_ledger(fake_run)))
assert {r.stage for r in led.rows} == {Stage.PLAN, Stage.BASELINE, Stage.JUDGE}
assert led.track == "static_object" and led.stop_reason == "max_rounds" and led.round_built == [None]
assert led.minutes == pytest.approx((20.0 + 60.0) / 60), "the run's minutes, not its span"
assert led.model_s == pytest.approx(47.0)
-
-
-def test_a_run_without_a_ledger_is_left_out(fake_run: Path, tmp_path: Path):
+ # a run without a ledger is left out of the audit
bare = tmp_path / "pre_ledger"
shutil.copytree(fake_run, bare)
shutil.rmtree(bare / "telemetry")
diff --git a/harness/tests/cost/test_cli.py b/harness/tests/cost/test_cli.py
index 66917f7a..b48dbfbc 100644
--- a/harness/tests/cost/test_cli.py
+++ b/harness/tests/cost/test_cli.py
@@ -38,15 +38,12 @@ def _live_ledger(run: Path, rows: list[dict]) -> None:
p.write_text("".join(json.dumps(r) + "\n" for r in rows))
-def test_cost_takes_a_bare_run_path_or_slug(fake_run: Path):
+def test_cost_takes_a_bare_run_path_a_slug_or_a_battery(fake_run: Path):
r = runner.invoke(app, ["cost", str(fake_run)])
assert r.exit_code == 0, r.output
assert "| fake_run | static_object |" in r.output
r = runner.invoke(app, ["cost", fake_run.name, "--runs-dir", str(fake_run.parent)])
assert r.exit_code == 0 and "| fake_run | static_object |" in r.output
-
-
-def test_cost_runs_dir_aggregates_a_battery(fake_run: Path, tmp_path: Path):
r = runner.invoke(app, ["cost", "--runs-dir", str(fake_run.parent)])
assert r.exit_code == 0 and "runs: 1" in r.output
@@ -101,4 +98,3 @@ def test_cost_prices_flags_stale_and_approximate_rows():
assert "flags" in r.stdout and ("approximate" in r.stdout or "none older than" in r.stdout)
r = runner.invoke(app, ["cost", "prices", "--days", "-1"])
assert r.exit_code == 0 and "stale>-1d" in r.stdout # nothing is younger than -1 days
-
diff --git a/harness/tests/cost/test_context.py b/harness/tests/cost/test_context.py
index bf9b378d..042bf020 100644
--- a/harness/tests/cost/test_context.py
+++ b/harness/tests/cost/test_context.py
@@ -30,7 +30,7 @@ def test_label_tells_stage_role_and_round():
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():
+def test_session_beats_a_generation_label_a_named_job_beats_the_session_explicit_beats_all():
# best-of-N: the session knows it is a candidate, a call inside it only says "baseline"
with call_context(round=3, stage=Stage.CANDIDATE, label="cand_c1"):
got = attribute(label="baseline")
@@ -38,10 +38,7 @@ def test_a_generation_label_yields_to_the_session_and_explicit_beats_both():
assert got.label == "baseline" # the most specific label is kept
forced = attribute(CallContext(stage=Stage.REPAIR, round=9), label="baseline")
assert forced.stage is Stage.REPAIR and forced.round == 9
-
-
-def test_a_call_that_names_its_own_job_beats_the_session_it_runs_inside():
- """A spatial tool that bills a model inside a refine session is not a refine call."""
+ # 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
@@ -75,5 +72,3 @@ def test_a_run_bound_in_a_thread_is_never_published_to_the_others():
t.join(timeout=5)
assert seen == {"a": "a", "b": "b"}
assert current().run == "" # ...and the main thread never inherited either of them
-
-
diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.py
index 7faabaf7..052e0e7d 100644
--- a/harness/tests/cost/test_instrument.py
+++ b/harness/tests/cost/test_instrument.py
@@ -92,22 +92,18 @@ def test_a_metered_call_becomes_one_priced_row(tmp_path: Path):
assert row.latency_ms == 1234 and row.cost_usd > 0
-def test_a_failed_call_is_recorded_and_re_raised(tmp_path: Path):
- with run_ledger(tmp_path, run="r1"), pytest.raises(TimeoutError):
- MeteredChatModel(FakeChat(TimeoutError("boom"))).generate(
- ChatRequest(messages=[ChatMessage.user("x")], label="planner"))
- (row,) = load_ledger(tmp_path)
- assert row.outcome == "timeout" and row.stage is Stage.PLAN and row.cost_usd == 0.0
-
-
-
-
-def test_get_coding_agent_hands_out_a_metered_agent(monkeypatch: pytest.MonkeyPatch):
+def test_both_registries_hand_out_metered_backends(monkeypatch: pytest.MonkeyPatch):
from codeverse3d.agents import registry
+ from codeverse3d.models import registry as model_registry
monkeypatch.setattr(registry, "_build_agent", lambda aid: CliAgent(FakeChat()))
assert isinstance(registry.get_coding_agent("gemini-cli:m"), MeteredAgent)
-
+ monkeypatch.setattr(model_registry, "build_chat_model", lambda mid: FakeChat())
+ model_registry.get_chat_model.cache_clear()
+ try:
+ assert isinstance(model_registry.get_chat_model("gemini:gemini-3.7-flash"), MeteredChatModel)
+ finally:
+ model_registry.get_chat_model.cache_clear()
def test_accounting_never_breaks_a_call(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
@@ -130,17 +126,6 @@ def test_the_proxy_forwards_everything_else():
assert agent.kind == "self-metering" and agent.available() == (True, "ok")
-def test_get_chat_model_hands_out_a_metered_model(monkeypatch: pytest.MonkeyPatch):
- from codeverse3d.models import registry
-
- monkeypatch.setattr(registry, "build_chat_model", lambda mid: FakeChat())
- registry.get_chat_model.cache_clear()
- try:
- assert isinstance(registry.get_chat_model("gemini:gemini-3.7-flash"), MeteredChatModel)
- finally:
- registry.get_chat_model.cache_clear()
-
-
def test_post_hoc_work_never_creates_a_partial_ledger(tmp_path: Path):
"""Post-hoc work never creates a misleading partial ledger."""
with run_ledger(tmp_path, run="old", create=False) as led:
@@ -228,16 +213,6 @@ def test_a_full_key_never_reaches_the_ledger(tmp_path: Path):
assert "secret" not in (tmp_path / "telemetry" / "cost.jsonl").read_text()
-def test_a_failed_call_records_its_attempts_but_no_key(tmp_path: Path):
- from codeverse3d.models.base import ModelError
-
- err = ModelError("503 high demand", retryable=True, status=503, attempts=7)
- with run_ledger(tmp_path, run="r1"), pytest.raises(ModelError):
- MeteredChatModel(FakeChat(err)).generate(ChatRequest(messages=[ChatMessage.user("x")], label="planner"))
- (row,) = load_ledger(tmp_path)
- assert row.outcome == "error" and row.attempts == 7 and row.key == ""
-
-
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
@@ -298,14 +273,23 @@ def test_a_late_hedge_loser_keeps_its_stage_role_and_round(tmp_path: Path):
assert loser.role is Role.GENERATOR and loser.round == 0
-def test_a_failed_calls_error_row_carries_what_was_billed(tmp_path: Path):
- """A final ModelError carries its billed usage into the error row."""
+def test_a_failed_call_is_recorded_re_raised_and_carries_what_was_billed(tmp_path: Path):
+ """A failure is one error row: its outcome, its attempts, no key, and the usage it was billed."""
from codeverse3d.models.base import ModelError
- err = ModelError("bad json after retries", retryable=True, attempts=6, usage=_usage())
- with run_ledger(tmp_path, run="r1"), pytest.raises(ModelError):
- MeteredChatModel(FakeChat(err)).generate(
- ChatRequest(messages=[ChatMessage.user("x")], label="planner"))
- (row,) = load_ledger(tmp_path)
- assert row.outcome == "error" and row.attempts == 6
- assert row.input_tokens == 12_000 and row.cost_usd > 0, "a billed failure is no longer a $0 row"
+ cases = (
+ (TimeoutError("boom"), dict(outcome="timeout", attempts=0, input_tokens=0)),
+ (ModelError("503 high demand", retryable=True, status=503, attempts=7),
+ dict(outcome="error", attempts=7, input_tokens=0)),
+ (ModelError("bad json after retries", retryable=True, attempts=6, usage=_usage()),
+ dict(outcome="error", attempts=6, input_tokens=12_000)),
+ )
+ for i, (err, want) in enumerate(cases):
+ ws = tmp_path / str(i)
+ with run_ledger(ws, run="r1"), pytest.raises(type(err)):
+ MeteredChatModel(FakeChat(err)).generate(
+ ChatRequest(messages=[ChatMessage.user("x")], label="planner"))
+ (row,) = load_ledger(ws)
+ assert row.stage is Stage.PLAN and row.key == ""
+ assert (row.outcome, row.attempts, row.input_tokens) == tuple(want.values()), err
+ assert (row.cost_usd > 0) is (want["input_tokens"] > 0), "a billed failure is no longer a $0 row"
diff --git a/harness/tests/cost/test_price_hygiene.py b/harness/tests/cost/test_price_hygiene.py
index 4040843b..518346b7 100644
--- a/harness/tests/cost/test_price_hygiene.py
+++ b/harness/tests/cost/test_price_hygiene.py
@@ -35,8 +35,6 @@ SUPPORTED_MODEL_IDS = (
)
-
-
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)
@@ -89,4 +87,3 @@ def test_every_price_row_was_checked_within_the_maintenance_window():
if age > STALE_AFTER_DAYS:
stale.append(f"{prov}:{model} ({age} days)")
assert not stale, f"price rows older than {STALE_AFTER_DAYS} days: {stale}"
-
diff --git a/harness/tests/cost/test_profiles.py b/harness/tests/cost/test_profiles.py
index 76fc0ce1..6e3adcf4 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, profile_table
+from codeverse3d.cost.profiles import PROFILE_NAMES, profile_table
runner = CliRunner()
@@ -24,24 +24,14 @@ def _fresh_settings():
get_settings.cache_clear()
-def test_balanced_is_todays_defaults():
- p = PROFILES["balanced"]
- s = Settings()
- assert (p.generator, p.planner, p.judge) == (s.default_generator, s.default_planner, s.default_judge)
- assert p.candidates == s.default_candidates
-
-
-def test_a_value_the_user_configured_survives_the_profile_unless_forced():
+def test_a_value_the_user_configured_survives_the_profile_unless_forced(monkeypatch):
s = Settings(default_generator="codex:gpt-5.6-sol")
s.apply_profile("economy")
assert s.default_generator == "codex:gpt-5.6-sol" # config.yaml / C3D_* wins over a default dial
assert s.default_judge == "gemini:gemini-3.7-flash" # everything unstated still moves
s.apply_profile("economy", force=True)
assert s.default_generator == "single-shot:gemini:gemini-3.7-flash"
-
-
-def test_one_stated_judge_field_does_not_disable_the_whole_judge_block(monkeypatch):
- """A stated judge field freezes only itself, not the whole section."""
+ # a stated judge field freezes only itself, not the whole judge section
monkeypatch.setenv("C3D_JUDGE__MAX_PX", "800")
s = Settings()
s.apply_profile("quality")
@@ -157,4 +147,3 @@ def test_each_profile_resolves_to_its_documented_dial(name, expected, monkeypatc
assert dial.profile == name
for field, want in expected.items():
assert getattr(dial, field) == want, f"{name}.{field}"
-
diff --git a/harness/tests/models/test_anthropic.py b/harness/tests/models/test_anthropic.py
index d4378c9a..9d998665 100644
--- a/harness/tests/models/test_anthropic.py
+++ b/harness/tests/models/test_anthropic.py
@@ -150,20 +150,17 @@ def test_structured_output_via_forced_submit_tool():
kw["tools"][0]["name"] == "submit"
and kw["tools"][0]["input_schema"]["additionalProperties"] is False
)
-
-
-def test_structured_output_with_thinking_uses_auto_and_text_fallback():
- schema = {"type": "object"}
+ # with thinking on, a forced tool is refused: tool_choice is auto and the text is parsed
m, fc = make([msg([text('```json\n{"b": 2}\n```')])])
r = m.generate(
- ChatRequest(messages=[ChatMessage.user("x")], response_schema=schema, thinking="low")
+ ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"}, thinking="low")
)
assert r.parsed == {"b": 2}
kw = fc.calls[0]
assert "tool_choice" not in kw and "submit" in kw["system"]
-def test_images_base64_and_message_merging():
+def test_images_base64_message_merging_and_user_first():
msgs = to_messages(
[
ChatMessage.user(
@@ -179,6 +176,8 @@ def test_images_base64_and_message_merging():
"text",
]
assert msgs[0]["content"][2]["source"]["media_type"] == "image/png"
+ msgs = to_messages([ChatMessage.assistant("hi")]) # assistant first gets a user prefix
+ assert msgs[0]["role"] == "user" and msgs[1]["role"] == "assistant"
def test_classify_connection_errors():
@@ -202,11 +201,6 @@ def test_missing_key_is_loud(monkeypatch):
get_settings.cache_clear()
-def test_assistant_first_gets_user_prefix():
- msgs = to_messages([ChatMessage.assistant("hi")])
- assert msgs[0]["role"] == "user" and msgs[1]["role"] == "assistant"
-
-
def test_a_failed_reply_carries_what_it_was_billed():
"""A refusal / bad-JSON / empty reply is billed on the error (D84)."""
for script, req in (
@@ -222,17 +216,3 @@ def test_a_failed_reply_carries_what_it_was_billed():
m.generate(req)
assert e.value.usage.input_tokens == 100 and e.value.usage.output_tokens == 20
-
-def test_each_attempt_gets_what_is_left_of_the_call_budget():
- """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
-
- m, fc = make([msg([text("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([msg([text("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"
diff --git a/harness/tests/models/test_control_chars.py b/harness/tests/models/test_control_chars.py
index 458499a5..118b26a1 100644
--- a/harness/tests/models/test_control_chars.py
+++ b/harness/tests/models/test_control_chars.py
@@ -20,21 +20,9 @@ def test_the_plan_that_killed_a_cell_now_parses_clean():
# a space, never deletion: "0.078" and "0.300" must not fuse into "0.0780.300"
assert out["summary"] == "Overall envelope is 0.078 0.300 0.240 m"
assert out["acceptance"][0]["text"] == "height is 0.240 m 0.005 m"
-
-
-def test_strip_control_chars_recurses_and_preserves_safe_text():
- dirty = {"a": "x\x00y", "b": ["p\x07q", {"c": "r\x1bs"}], "n": 3, "ok": None, "t": True}
- assert strip_control_chars(dirty) == {
- "a": "x y",
- "b": ["p q", {"c": "r s"}],
- "n": 3,
- "ok": None,
- "t": True,
- }
- keep = "def f():\n\tx = 1\r\n"
- assert strip_control_chars(keep) == keep
- text = "0.078 × 0.300 m ± 0.005 — café 日本語 🔧"
- assert strip_control_chars(text) == text
+ # what the plan meant to say, and the code a model writes, pass through untouched
+ for safe in ("def f():\n\tx = 1\r\n", "0.078 × 0.300 m ± 0.005 — café 日本語 🔧"):
+ assert strip_control_chars(safe) == safe
def test_the_subprocess_backstop_names_the_offender(tmp_path):
diff --git a/harness/tests/models/test_gemini_scheduling.py b/harness/tests/models/test_gemini_scheduling.py
index a695aba6..2558dd0c 100644
--- a/harness/tests/models/test_gemini_scheduling.py
+++ b/harness/tests/models/test_gemini_scheduling.py
@@ -10,7 +10,6 @@ from google.genai import errors as genai_errors
from codeverse3d.contracts.chat import ChatMessage, ChatRequest
from codeverse3d.models.base import ModelError
-from codeverse3d.models.gemini import shared_pool
from codeverse3d.models.retry import KeyPool
from tests.models.test_gemini import make_model, text_response
@@ -19,15 +18,6 @@ def api_error(code: int, msg: str = "boom") -> genai_errors.APIError:
return genai_errors.APIError(code, {"error": {"message": msg, "code": code}})
-# ---------------------------------------------------------------- shared pool
-def test_shared_pool_is_keyed_by_the_cap_not_only_by_keys():
- a = shared_pool(["x1", "x2"], max_in_flight=4)
- b = shared_pool(["x1", "x2"], max_in_flight=4)
- c = shared_pool(["x1", "x2"], max_in_flight=8)
- assert a is b
- assert a is not c, "a different cap must not silently reuse another pool's slots"
-
-
# ------------------------------------------------ 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):
"""ChatRequest.max_wait_s clips the model's retry deadline, never raises it."""
diff --git a/harness/tests/models/test_health.py b/harness/tests/models/test_health.py
index 6c7a5491..40173cb2 100644
--- a/harness/tests/models/test_health.py
+++ b/harness/tests/models/test_health.py
@@ -5,7 +5,7 @@ from __future__ import annotations
from codeverse3d.models.health import DEFAULT_MIN_OK, Health
-def test_health_threshold_requires_a_real_success_rate():
+def test_health_threshold_requires_a_real_success_rate_and_names_the_reason():
for n_ok, n_tried, expected in (
(6, 6, True),
(3, 4, True),
@@ -17,6 +17,15 @@ def test_health_threshold_requires_a_real_success_rate():
assert Health("m", n_ok=n_ok, n_tried=n_tried).ok is expected, (
f"{n_ok}/{n_tried}; threshold={DEFAULT_MIN_OK:.0%}"
)
+ # the doctor line carries the provider's reason
+ h = Health(
+ "gemini:gemini-3.7-flash",
+ n_ok=0,
+ n_tried=4,
+ reasons=("ModelError: Gemini API error 504: Deadline expired",),
+ )
+ text = str(h)
+ assert "0/4" in text and "504" in text, text
def test_the_probe_prompt_is_the_size_of_real_work():
@@ -31,17 +40,6 @@ def test_the_probe_prompt_is_the_size_of_real_work():
)
-def test_the_message_carries_the_provider_reason():
- h = Health(
- "gemini:gemini-3.7-flash",
- n_ok=0,
- n_tried=4,
- reasons=("ModelError: Gemini API error 504: Deadline expired",),
- )
- text = str(h)
- assert "0/4" in text and "504" in text, text
-
-
def test_probe_never_raises_when_every_call_fails(monkeypatch):
import codeverse3d.models.health as health
diff --git a/harness/tests/models/test_keypool.py b/harness/tests/models/test_keypool.py
index 9587ea8f..fc179e84 100644
--- a/harness/tests/models/test_keypool.py
+++ b/harness/tests/models/test_keypool.py
@@ -47,23 +47,7 @@ def test_all_cooling_blocks_until_cooldown_ends():
pool.acquire(timeout_s=1.0)
-def test_health_score_prefers_healthy_keys():
- pool, clock = make(keys=("bad", "good"), cooldown_s=0.0)
- for _ in range(3):
- pool.report("bad", "429") # health 0.125, cooldown 0 → still "available"
- picks = [pool.acquire() for _ in range(4)]
- assert picks == ["good"] * 4
- pool.report("good", "ok")
- s = {k["key"]: k for k in pool.stats()["keys"]}
- assert s["…good"]["health"] == 1.0 and s["…bad"]["health"] < 0.3
- # passive recovery over time
- clock.t += 200
- assert pool.acquire() in ("bad", "good")
- s = {k["key"]: k for k in pool.stats()["keys"]}
- assert s["…bad"]["health"] > 0.9
-
-
-def test_dead_key_is_benched_for_a_long_time_then_reprobed():
+def test_dead_key_is_benched_for_an_hour_and_all_dead_raises_at_once():
pool, clock = make(keys=("dead", "ok"), cooldown_s=30, dead_cooldown_s=3600)
pool.report("dead", "dead")
# passive health recovery must not bring it back: it stays benched for an hour
@@ -76,9 +60,7 @@ def test_dead_key_is_benched_for_a_long_time_then_reprobed():
clock.t += 1801
assert "dead" in [pool.acquire() for _ in range(3)] # re-probed once the bench ends
assert pool.stats()["n_dead"] == 0
-
-
-def test_all_keys_dead_raises_immediately_instead_of_waiting_out_the_timeout():
+ # every key dead: raise at once instead of waiting out the timeout
pool, clock = make(keys=("a", "b"), dead_cooldown_s=3600)
pool.report("a", "dead")
pool.report("b", "dead")
@@ -106,7 +88,7 @@ def test_try_acquire_never_waits_for_a_key_or_a_slot(tmp_path):
assert pool.stats()["in_flight"] == 0, "a refused try_acquire holds nothing"
-def test_the_in_flight_slot_wait_is_bounded_by_timeout(tmp_path):
+def test_the_in_flight_slot_wait_is_bounded_and_a_failed_acquire_gives_it_back(tmp_path):
pool = KeyPool(["a"], max_in_flight=1, slots_dir=tmp_path)
pool.acquire()
t0 = time.monotonic()
@@ -115,27 +97,8 @@ def test_the_in_flight_slot_wait_is_bounded_by_timeout(tmp_path):
assert time.monotonic() - t0 < 2.0, "the slot wait must honour the timeout"
pool.release()
assert pool.acquire(timeout_s=0.5) == "a", "the slot came back; nothing leaked"
-
-
-def test_skip_leaves_health_and_counters_alone():
- """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"]
- pool.report("a", "skip")
- after = {k["key"]: k for k in pool.stats()["keys"]}["…a"]
- assert after["health"] == before["health"] and after["ok"] == before["ok"] and after["error"] == before["error"]
-
-
-# ------------------------------------------------------------- in-flight cap
-
-
-
-
-def test_a_failed_acquire_gives_its_slot_back(tmp_path):
- """KeyPoolExhausted must not leak a concurrency slot."""
- pool = KeyPool(["a"], max_in_flight=1, slots_dir=tmp_path)
- for _ in range(3):
+ pool.release()
+ for _ in range(3): # KeyPoolExhausted must not leak a concurrency slot either
with pytest.raises(KeyPoolExhausted):
pool.acquire(exclude={"a"}, timeout_s=0.0)
assert pool.acquire(timeout_s=0.0) == "a" # the slot is still free
diff --git a/harness/tests/models/test_openai.py b/harness/tests/models/test_openai.py
index f5515106..e79bb673 100644
--- a/harness/tests/models/test_openai.py
+++ b/harness/tests/models/test_openai.py
@@ -149,14 +149,6 @@ def test_json_schema_strict_then_fallback_to_non_strict():
assert fc.calls[2]["response_format"]["json_schema"]["strict"] is False
-def test_bad_json_retried():
- m, fc = make([completion("garbage"), completion('{"ok": 1}')])
- r = m.generate(
- ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"})
- )
- assert r.parsed == {"ok": 1} and len(fc.calls) == 2
-
-
def test_images_data_urls():
msgs = to_messages(
[
@@ -170,11 +162,14 @@ def test_images_data_urls():
assert [b["type"] for b in c] == ["text", "text", "image_url"]
-
-
-def test_empty_and_classify():
+def test_bad_json_and_empty_replies_are_retried_and_classify():
import openai
+ m, fc = make([completion("garbage"), completion('{"ok": 1}')])
+ r = m.generate(
+ ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"})
+ )
+ assert r.parsed == {"ok": 1} and len(fc.calls) == 2
m, fc = make([completion(None), completion("ok")])
assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"
req = httpx.Request("POST", "https://api.openai.com")
@@ -213,5 +208,3 @@ def test_a_failed_reply_carries_what_it_was_billed():
m.generate(req)
u = e.value.usage
assert u.input_tokens == 100 and u.output_tokens == 20 and u.thoughts_tokens == 10
-
-
diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.py
index 04232fb2..f258729a 100644
--- a/harness/tests/models/test_retry.py
+++ b/harness/tests/models/test_retry.py
@@ -94,22 +94,6 @@ def _boom(msg: str = "503 high demand"):
return call
-def test_rotate_dead_key_is_free_and_benched_after_sibling_success():
- pool = KeyPool(["k1", "k2"])
- calls: list[str] = []
-
- def call(key: str) -> str:
- calls.append(key)
- if key == "k1":
- raise ModelError("suspended", retryable=False, status=403)
- return key
-
- assert _rotate(pool, call, max_attempts=1) == "k2" # dead rotation burnt no budget
- assert calls == ["k1", "k2"]
- st = pool.stats()
- assert st["dead"] == 1 and st["n_dead"] == 1 # k1 benched only after k2 proved the request
-
-
def test_rotate_every_key_dead_raises_without_benching():
pool = KeyPool(["k1", "k2", "k3"])
calls: list[str] = []
@@ -124,32 +108,6 @@ def test_rotate_every_key_dead_raises_without_benching():
assert pool.stats()["dead"] == 0 # the request, not the keys, is suspect
-def test_rotate_429_is_free_while_untried_keys_remain():
- clock = Clock()
- pool = KeyPool(["k1", "k2", "k3"], cooldown_s=30, clock=clock, sleep=clock.sleep)
- calls: list[str] = []
- hinted: list[BaseException] = []
-
- def call(key: str) -> str:
- calls.append(key)
- if key in ("k1", "k2"):
- raise ModelError("quota", retryable=True, status=429)
- return key
-
- out = _rotate(
- pool,
- call,
- max_attempts=1,
- sleep=clock.sleep,
- retry_after=lambda error: hinted.append(error) or 7.0,
- )
- assert out == "k3" and calls == ["k1", "k2", "k3"]
- assert clock.naps == [0.5, 0.5]
- stats = pool.stats()
- assert len(hinted) == 2 and stats["n_cooling"] == 2
- assert max(key["cooldown_s"] for key in stats["keys"]) <= MAX_WAIT_S
-
-
# --------------------------------------------------------------------------- 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):
@@ -314,26 +272,6 @@ def test_the_worst_error_decides_a_hedged_attempt():
# --------------------------------------------------------------------------- deadline threading (2026-08-27)
-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()
- with pytest.raises(ModelError):
- _rotate503(
- _pool(1),
- _boom(),
- max_attempts=6,
- storm_attempts=60,
- base_delay=4.0,
- storm_max_delay=5.0,
- max_total_s=3.0,
- sleep=clock.sleep,
- monotonic=clock,
- hedge=1,
- )
- assert clock.naps, "expected the storm path to sleep"
- assert clock.t <= 3.0 + 1e-6, f"slept past the deadline: {clock.t}"
-
-
def test_free_429_rotation_cannot_outlive_the_deadline():
"""Free key rotation still consumes wall-clock budget."""
clock = Clock()
@@ -399,30 +337,3 @@ def test_a_broken_on_attempt_hook_never_breaks_the_call():
assert _rotate(pool, lambda key: "ok", on_attempt=hook) == "ok"
-
-def test_error_causes_avoid_cycles_and_preserve_real_wrapped_errors():
- """Classified errors avoid self-cycles while preserving genuine causes."""
-
- def call(key):
- raise ModelError(
- "structured output unavailable (finish_reason=MAX_TOKENS)", retryable=False, status=None
- )
-
- with pytest.raises(ModelError) as ei:
- _rotate(_pool(), call, max_attempts=1)
- err = ei.value
- assert err.__cause__ is not err, "the classified error became its own __cause__"
-
- # walk the whole chain: no link may repeat, whatever the branch
- seen, node = set(), err
- while node is not None and id(node) not in seen:
- seen.add(id(node))
- node = node.__cause__ if node.__cause__ is not None else node.__context__
- assert node is None, "the cause chain closes into a cycle"
-
- def timeout(key):
- raise TimeoutError("read timed out")
-
- with pytest.raises(ModelError) as ei:
- _rotate(_pool(), timeout, max_attempts=1)
- assert isinstance(ei.value.__cause__, TimeoutError)
diff --git a/harness/tests/models/test_schema_utils.py b/harness/tests/models/test_schema_utils.py
index 9a0668d5..b426ab0f 100644
--- a/harness/tests/models/test_schema_utils.py
+++ b/harness/tests/models/test_schema_utils.py
@@ -92,8 +92,6 @@ def test_inline_refs_and_recursion_guard():
inline_refs(rec)
-
-
def test_openai_strict_schemas_never_add_null():
"""Wire contract == pydantic contract: a field accepts null on the wire iff the
source schema does (``x: T | None``) — never because it merely has a default /
@@ -145,10 +143,12 @@ def test_parse_json_lenient_accepts_wrappers_and_rejects_non_json():
assert json.dumps(parse_json_lenient('{"n": {"x": [1]}}')) == '{"n": {"x": [1]}}'
-def test_ask_structured_returns_the_triple_for_prose_it_cannot_parse():
- """The callers branch on the error string; a provider that returns prose must not raise."""
+def test_ask_structured_returns_the_triple_and_the_billed_usage_on_failure():
+ """The callers branch on the error string, so a provider that returns prose must not
+ raise; a bad-JSON reply is charged like a good one: the caller's tally gets the usage."""
from codeverse3d.contracts.chat import ChatResponse
from codeverse3d.contracts.common import Usage
+ from codeverse3d.models.base import ModelError
from codeverse3d.models.schema_utils import ask_structured
class Answer(BaseModel):
@@ -161,16 +161,6 @@ def test_ask_structured_returns_the_triple_for_prose_it_cannot_parse():
out, usage, err = ask_structured(Prose(), Answer, system="s", text="t", temperature=0.2, label="l")
assert out is None and usage.cost_usd == 0.01 and err.startswith("answer unparsable:")
-
-def test_ask_structured_returns_the_usage_a_failed_call_was_billed():
- """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
-
- class Answer(BaseModel):
- ok: bool
-
billed = Usage(input_tokens=42_000, output_tokens=100, cost_usd=0.123, backend="gemini")
class Failing: