Skip to content

Official Codebase of 3DCodeVerse

Python

tests: models, cost, second pass — seven more exceptions did not hold (−121 lines)

gaoypeng4962a4bc38e6
diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.py
index c381584f..7faabaf7 100644
--- a/harness/tests/cost/test_instrument.py
+++ b/harness/tests/cost/test_instrument.py
@@ -9,13 +9,12 @@ import pytest
from codeverse3d.contracts.agent import AgentJob, AgentResult
from codeverse3d.contracts.chat import ChatMessage, ChatRequest, ChatResponse
from codeverse3d.contracts.common import Usage
-from codeverse3d.cost.context import run_binding
from codeverse3d.cost.instrument import (
MeteredAgent,
MeteredChatModel,
run_ledger,
)
-from codeverse3d.cost.ledger import load_ledger, record_call
+from codeverse3d.cost.ledger import load_ledger
from codeverse3d.cost.types import Role, Stage
@@ -101,14 +100,6 @@ 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_session_row_is_filed_by_the_task_kind(tmp_path: Path):
- with run_ledger(tmp_path, run="r1"):
- for kind, label in (("zone", "zone_courtyard"), ("rebuild", "rebuild"),
- ("asset", "asset_koi"), ("candidate", "baseline_c1")):
- MeteredAgent(CliAgent(FakeChat())).run(
- AgentJob(workspace=str(tmp_path), prompt="p", label=label, round=0, kind=kind))
- assert [r.stage for r in load_ledger(tmp_path)] == [Stage.ZONES, Stage.REPAIR,
- Stage.ASSETS, Stage.CANDIDATE]
def test_get_coding_agent_hands_out_a_metered_agent(monkeypatch: pytest.MonkeyPatch):
@@ -198,13 +189,10 @@ def test_a_cli_session_is_recorded_even_when_a_tool_bills_a_model_inside_it(tmp_
# ------------------------------------------------------------------- nesting / parallelism
-def test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch):
+def test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Path):
"""`bench.run_bench` runs N prompts in N threads; their rows must not mix."""
from concurrent.futures import ThreadPoolExecutor
- from codeverse3d.cost import ledger as ledger_mod
-
def one(name: str) -> None:
with run_ledger(tmp_path / name, run=name):
for _ in range(3):
@@ -217,13 +205,6 @@ 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 (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")
- assert [r.run for r in load_ledger(tmp_path / "process.jsonl")] == [""]
- for name in names:
- assert len(load_ledger(tmp_path / name)) == 3
class KeyedChat(FakeChat):
diff --git a/harness/tests/cost/test_price_hygiene.py b/harness/tests/cost/test_price_hygiene.py
index 8a84d8bd..4040843b 100644
--- a/harness/tests/cost/test_price_hygiene.py
+++ b/harness/tests/cost/test_price_hygiene.py
@@ -35,11 +35,6 @@ SUPPORTED_MODEL_IDS = (
)
-def test_every_price_row_has_provenance():
- for (provider, model), price in PRICES.items():
- assert price.checked and price.checked[:2] == "20", model
- assert price.status in ("verified", "inferred", "unverified"), model
- assert (price.source or provider) in SOURCES, model
def test_long_context_tier_is_applied():
@@ -79,11 +74,13 @@ def test_every_price_row_was_checked_within_the_maintenance_window():
from datetime import date, datetime
from codeverse3d.cli.cost_cmd import STALE_AFTER_DAYS
- from codeverse3d.models.pricing import PRICES, price_provenance
+ from codeverse3d.models.pricing import price_provenance
stale = []
for prov, model in sorted(PRICES):
row = price_provenance(prov, model)
+ assert row.status in ("verified", "inferred", "unverified"), model
+ assert (PRICES[(prov, model)].source or prov) in SOURCES, model
try:
age = (date.today() - datetime.strptime(row.checked, "%Y-%m-%d").date()).days
except (TypeError, ValueError):
diff --git a/harness/tests/cost/test_profiles.py b/harness/tests/cost/test_profiles.py
index 477bd7ea..76fc0ce1 100644
--- a/harness/tests/cost/test_profiles.py
+++ b/harness/tests/cost/test_profiles.py
@@ -48,14 +48,6 @@ def test_one_stated_judge_field_does_not_disable_the_whole_judge_block(monkeypat
assert s.judge.max_px == 800, "the field the user stated wins"
assert s.judge.samples == 3, "every field the user did NOT state still follows the profile"
assert s.judge.montages == 5 and s.judge.detail_crops == 2
- # and the same dial, whichever way the profile was named (cost/profiles.py's invariant)
- monkeypatch.setenv("C3D_PROFILE", "quality")
- get_settings.cache_clear()
- try:
- settings = get_settings()
- assert resolve_dial(settings, None).judge_samples == resolve_dial(settings, "quality").judge_samples == 3
- finally:
- get_settings.cache_clear()
def test_no_profile_touches_the_judge_payload_or_the_turn_cap(monkeypatch):
@@ -166,19 +158,3 @@ def test_each_profile_resolves_to_its_documented_dial(name, expected, monkeypatc
for field, want in expected.items():
assert getattr(dial, field) == want, f"{name}.{field}"
-
[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
-
- p = PROFILES[name]
- monkeypatch.setenv("C3D_PROFILE", name)
- get_settings.cache_clear()
- 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())
- assert spec["options"] == {"candidates": p.candidates, "texture": p.texture, "profile": name}
- assert spec["budget"]["max_rounds"] == p.rounds and spec["budget"]["max_minutes"] == p.max_minutes
- assert spec["backends"]["judge"] == p.judge and spec["backends"]["generator"] == p.generator
diff --git a/harness/tests/models/test_anthropic.py b/harness/tests/models/test_anthropic.py
index e18c5019..d4378c9a 100644
--- a/harness/tests/models/test_anthropic.py
+++ b/harness/tests/models/test_anthropic.py
@@ -236,7 +236,3 @@ def test_each_attempt_gets_what_is_left_of_the_call_budget():
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"
-
- m, fc = make([msg([text("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_gemini_scheduling.py b/harness/tests/models/test_gemini_scheduling.py
index 2a9f3748..a695aba6 100644
--- a/harness/tests/models/test_gemini_scheduling.py
+++ b/harness/tests/models/test_gemini_scheduling.py
@@ -19,7 +19,6 @@ def api_error(code: int, msg: str = "boom") -> genai_errors.APIError:
return genai_errors.APIError(code, {"error": {"message": msg, "code": code}})
-# ------------------------------------------------------------------ slots
# ---------------------------------------------------------------- shared pool
def test_shared_pool_is_keyed_by_the_cap_not_only_by_keys():
a = shared_pool(["x1", "x2"], max_in_flight=4)
@@ -50,11 +49,7 @@ 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_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")]))
- assert r.raw["attempts"] == 1 and r.raw["key"] == "…k1"
-
+def test_a_recovered_call_reports_its_attempts_and_a_failed_call_carries_its_count():
hedged, log, _ = make_model(
[api_error(503), api_error(503), text_response("recovered")],
pool=KeyPool(["k1", "k2", "k3"], cooldown_s=0.0),
diff --git a/harness/tests/models/test_keypool.py b/harness/tests/models/test_keypool.py
index b6a7f87b..9587ea8f 100644
--- a/harness/tests/models/test_keypool.py
+++ b/harness/tests/models/test_keypool.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import threading
import time
import pytest
@@ -129,39 +128,8 @@ def test_skip_leaves_health_and_counters_alone():
# ------------------------------------------------------------- in-flight cap
-def test_in_flight_gauge_tracks_acquire_and_release():
- pool, _ = make(keys=("a", "b"))
- pool.acquire()
- pool.acquire()
- assert pool.stats()["in_flight"] == 2
- assert pool.stats()["peak_in_flight"] == 2
- pool.release()
- assert pool.stats()["in_flight"] == 1
- assert pool.stats()["peak_in_flight"] == 2 # peak is a high-water mark
- pool.release()
- pool.release() # a stray release is a no-op, not a crash
- assert pool.stats()["in_flight"] == 0
-def test_max_in_flight_blocks_the_third_caller(tmp_path):
- pool = KeyPool(["a", "b", "c"], max_in_flight=2, slots_dir=tmp_path)
- pool.acquire()
- pool.acquire()
- started = threading.Event()
- got = threading.Event()
-
- def third() -> None:
- started.set()
- pool.acquire()
- got.set()
-
- t = threading.Thread(target=third, daemon=True)
- t.start()
- started.wait(2)
- assert not got.wait(0.2), "the 3rd call should be held by the in-flight cap"
- pool.release()
- assert got.wait(2), "releasing a slot must let the queued call through"
- t.join(2)
def test_a_failed_acquire_gives_its_slot_back(tmp_path):
diff --git a/harness/tests/models/test_openai.py b/harness/tests/models/test_openai.py
index 1cf94667..f5515106 100644
--- a/harness/tests/models/test_openai.py
+++ b/harness/tests/models/test_openai.py
@@ -170,16 +170,6 @@ def test_images_data_urls():
assert [b["type"] for b in c] == ["text", "text", "image_url"]
-def test_retry_matrix():
- m, fc = make([api_error(429), api_error(500), completion("ok")])
- assert (
- m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"
- and len(fc.calls) == 3
- )
- m, fc = make([api_error(400, "nope")])
- with pytest.raises(ModelError) as ei:
- m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
- assert not ei.value.retryable and ei.value.status == 400
def test_empty_and_classify():
diff --git a/harness/tests/models/test_pricing.py b/harness/tests/models/test_pricing.py
index e7ea0889..c76350a6 100644
--- a/harness/tests/models/test_pricing.py
+++ b/harness/tests/models/test_pricing.py
@@ -18,8 +18,6 @@ def test_gemini_cost_math():
assert abs(estimate_cost("gemini", "gemini-3.7-flash", u) - (0.45 + 0.03 + 0.5625)) < 1e-9
-
-
@pytest.mark.parametrize(
("provider", "model", "row"),
[
diff --git a/harness/tests/models/test_schema_utils.py b/harness/tests/models/test_schema_utils.py
index 0832e7fc..9a0668d5 100644
--- a/harness/tests/models/test_schema_utils.py
+++ b/harness/tests/models/test_schema_utils.py
@@ -92,28 +92,6 @@ def test_inline_refs_and_recursion_guard():
inline_refs(rec)
-def test_openai_strict_schema_shape():
- s = to_openai_strict_schema(StaticPlan.model_json_schema())
-
- def check(n):
- if isinstance(n, dict) and "properties" in n:
- assert n["additionalProperties"] is False
- assert set(n["required"]) == set(n["properties"].keys())
-
- _walk(s, check)
- part = s["properties"]["parts"]["items"]["properties"]
- # optional-without-default (``str | None = None``) is nullable on the wire …
- assert {"type": "null"} in part["attach_to"]["anyOf"]
- # … but defaulted fields stay non-null (pydantic rejects null there) with a hint
- assert (
- part["material"]["type"] == "string" and '[default: ""]' in part["material"]["description"]
- )
- assert (
- part["instances"]["type"] == "integer"
- and "[default: 1]" in part["instances"]["description"]
- )
- assert part["symmetry"]["type"] == "string" and "null" not in json.dumps(part["symmetry"])
- assert s["properties"]["style_notes"]["type"] == "string"
def test_openai_strict_schemas_never_add_null():