Official Codebase of 3DCodeVerse
Python
tests: consolidate duplicated setup and merged cases (-302 lines)
gaoypeng7f55df1900cc
diff --git a/harness/tests/agents/conftest.py b/harness/tests/agents/conftest.pyindex 0ed88b30..e7e9ed4f 100644--- a/harness/tests/agents/conftest.py+++ b/harness/tests/agents/conftest.py@@ -30,6 +30,17 @@ def fake_bin(tmp_path: Path):return make+def scoped_ws(tmp_ws):+ """A workspace with an entry file and two part files — the tree every write-scope+ test (CLI post-hoc restore and in-process FileTools alike) needs."""+ (tmp_ws.src / "parts").mkdir(parents=True, exist_ok=True)+ (tmp_ws.src / "model.py").write_text("# entry\n")+ (tmp_ws.src / "parts" / "seat.py").write_text("# seat\n")+ (tmp_ws.src / "parts" / "leg.py").write_text("# leg\n")+ return tmp_ws++@pytest.fixture(autouse=True)def _clean_agent_env(monkeypatch):"""Make sure host secrets in the test process do not leak assumptions into tests."""diff --git a/harness/tests/agents/test_cli_write_scope.py b/harness/tests/agents/test_cli_write_scope.pyindex c665f87a..cda0a3ed 100644--- a/harness/tests/agents/test_cli_write_scope.py+++ b/harness/tests/agents/test_cli_write_scope.py@@ -14,9 +14,6 @@ from __future__ import annotationsimport threadingimport time-import pytest--from codeverse.agents.api_tools import FileTools, PathDeniedfrom codeverse.agents.cli_common import EXCLUSIVE_KINDS, begin_session, finish_sessionfrom codeverse.contracts.agent import AgentJobfrom codeverse.contracts.common import Usage@@ -80,16 +77,8 @@ def test_same_thread_can_begin_again_without_finishing(tmp_ws: Workspace):# --------------------------------------------------------------------------- post-hoc scope-def _scoped_ws(tmp_ws: Workspace) -> Workspace:- (tmp_ws.src / "parts").mkdir(parents=True, exist_ok=True)- (tmp_ws.src / "model.py").write_text("# entry\n")- (tmp_ws.src / "parts" / "seat.py").write_text("# seat\n")- (tmp_ws.src / "parts" / "leg.py").write_text("# leg\n")- return tmp_ws---def test_out_of_scope_cli_write_is_restored_and_fails_the_session(tmp_ws: Workspace):- ws = _scoped_ws(tmp_ws)+def test_out_of_scope_cli_write_is_restored_and_fails_the_session(scoped_ws: Workspace):+ ws = scoped_wsjob = _job(ws, "detail_seat", edit_only=True, files_hint=["src/parts/seat.py"])s = begin_session(job, "codex")(ws.src / "parts" / "seat.py").write_text("# new seat\n") # hinted: kept@@ -104,12 +93,12 @@ def test_out_of_scope_cli_write_is_restored_and_fails_the_session(tmp_ws: Workspassert sorted(f.path for f in res.files_changed) == ["src/parts/bolt.py", "src/parts/seat.py"]-def test_write_roots_are_enforced_without_edit_only(tmp_ws: Workspace):+def test_write_roots_are_enforced_without_edit_only(scoped_ws: Workspace):"""``write_roots`` was enforced for the api-agent (api_tools) and single-shot but NOTfor CLI agents: ``_enforce_scope`` returned early unless edit_only+files_hint, so aplain codex session wrote and COMMITTED root-level evil.py / conftest.py and``attribute_changes`` then hid them from files_changed (audit 2026-08-27)."""- ws = _scoped_ws(tmp_ws)+ ws = scoped_ws(ws.root / "notes.md").write_text("original\n")s = begin_session(_job(ws, "baseline"), "codex") # edit_only=False, write_roots=["src", "public"](ws.src / "parts" / "leg.py").write_text("# in scope\n")@@ -126,8 +115,8 @@ def test_write_roots_are_enforced_without_edit_only(tmp_ws: Workspace):assert [f.path for f in res.files_changed] == ["src/parts/leg.py"]-def test_entry_file_writes_need_ownership(tmp_ws: Workspace):- ws = _scoped_ws(tmp_ws)+def test_entry_file_writes_need_ownership(scoped_ws: Workspace):+ ws = scoped_wsjob = _job(ws, "part", edit_only=True, files_hint=["src/parts/seat.py"])s = begin_session(job, "gemini-cli")(ws.src / "model.py").write_text("# hijacked entry\n")@@ -142,25 +131,9 @@ def test_entry_file_writes_need_ownership(tmp_ws: Workspace):assert res2.ok and (ws.src / "model.py").read_text() == "# entry + import\n"-def test_unscoped_cli_sessions_keep_the_old_behaviour(tmp_ws: Workspace):- ws = _scoped_ws(tmp_ws)+def test_unscoped_cli_sessions_keep_the_old_behaviour(scoped_ws: Workspace):+ ws = scoped_wss = begin_session(_job(ws, "baseline"), "codex") # edit_only=False(ws.src / "parts" / "leg.py").write_text("# fine\n")res = _finish(s)assert res.ok and (ws.src / "parts" / "leg.py").read_text() == "# fine\n"---# --------------------------------------------------------------------------- FileTools mirror-def test_filetools_denies_the_entry_without_ownership(tmp_path):- """The api-agent side of entry ownership: no ``always_writable`` (owns_entry=False)- means the entry file is just another out-of-scope existing file."""- ws = Workspace(tmp_path / "run").create()- (ws.root / "src" / "parts").mkdir(parents=True, exist_ok=True)- (ws.root / "src" / "model.py").write_text("# entry\n")- (ws.root / "src" / "parts" / "seat.py").write_text("# seat\n")- denied = FileTools(ws, ["src", "public"], edit_only=["src/parts/seat.py"])- with pytest.raises(PathDenied):- denied.write_file("src/model.py", "# hijack\n")- owner = FileTools(ws, ["src", "public"], edit_only=["src/parts/seat.py"],- always_writable=["src/model.py"])- assert not owner.write_file("src/model.py", "# entry + import\n").is_errordiff --git a/harness/tests/agents/test_edit_scope.py b/harness/tests/agents/test_edit_scope.pyindex 32a24a0c..072bc768 100644--- a/harness/tests/agents/test_edit_scope.py+++ b/harness/tests/agents/test_edit_scope.py@@ -12,21 +12,10 @@ from __future__ import annotationsimport pytestfrom codeverse.agents.api_tools import FileTools, PathDenied-from codeverse.workspace import Workspace-def _ws(tmp_path):- ws = Workspace(tmp_path / "run")- ws.create()- (ws.root / "src" / "parts").mkdir(parents=True, exist_ok=True)- (ws.root / "src" / "model.py").write_text("# entry\n")- (ws.root / "src" / "parts" / "seat.py").write_text("# seat\n")- (ws.root / "src" / "parts" / "leg.py").write_text("# leg\n")- return ws---def test_a_scoped_session_cannot_overwrite_a_neighbouring_part(tmp_path):- ws = _ws(tmp_path)+def test_a_scoped_session_cannot_overwrite_a_neighbouring_part(scoped_ws):+ ws = scoped_wsft = FileTools(ws, ["src", "public"], edit_only=["src/parts/seat.py"], always_writable=["src/model.py"])assert not ft.write_file("src/parts/seat.py", "# new seat\n").is_error, "the named file is editable"with pytest.raises(PathDenied) as ei: # the agent loop turns PathDenied into a tool error@@ -36,26 +25,30 @@ def test_a_scoped_session_cannot_overwrite_a_neighbouring_part(tmp_path):assert ft.scope_denials == ["src/parts/leg.py"], "denials are counted so the rate can be measured"-def test_new_files_and_the_entry_file_stay_writable(tmp_path):- """Adding a part means a new file AND an import line in the entry: both must work."""- ws = _ws(tmp_path)+def test_the_entry_file_is_writable_only_by_its_owner(scoped_ws):+ """Adding a part means a new file AND an import line in the entry: both must work for+ the owner. Without ``always_writable`` (owns_entry=False) the entry is just another+ out-of-scope existing file — the api-agent side of CLI entry ownership."""+ ws = scoped_wsft = FileTools(ws, ["src", "public"], edit_only=["src/parts/seat.py"], always_writable=["src/model.py"])assert not ft.write_file("src/parts/armrest.py", "# new part\n").is_errorassert not ft.write_file("src/model.py", "# entry + import\n").is_errorassert ft.scope_denials == []+ denied = FileTools(ws, ["src", "public"], edit_only=["src/parts/seat.py"])+ with pytest.raises(PathDenied):+ denied.write_file("src/model.py", "# hijack\n")-def test_no_scope_means_the_old_behaviour(tmp_path):+def test_no_scope_means_the_old_behaviour(scoped_ws):"""Baseline sessions and unscoped refines (target 'overall') keep the whole tree."""- ws = _ws(tmp_path)- ft = FileTools(ws, ["src", "public"])+ ft = FileTools(scoped_ws, ["src", "public"])assert ft.edit_only is Noneassert not ft.write_file("src/parts/leg.py", "# fine\n").is_error-def test_scope_never_widens_the_write_roots(tmp_path):+def test_scope_never_widens_the_write_roots(scoped_ws):"""edit_only narrows; it must not let a listed path escape src/ or public/."""- ws = _ws(tmp_path)+ ws = scoped_ws(ws.root / "artifacts").mkdir(exist_ok=True)ft = FileTools(ws, ["src", "public"], edit_only=["artifacts/x.txt"])with pytest.raises(PathDenied, match="only allowed under"):diff --git a/harness/tests/agents/test_watchdog.py b/harness/tests/agents/test_watchdog.pyindex fcb79fb7..8469d284 100644--- a/harness/tests/agents/test_watchdog.py+++ b/harness/tests/agents/test_watchdog.py@@ -1,9 +1,12 @@-"""run_with_watchdog: streaming, idle kill, hard kill, process-group kill, stdin."""+"""run_with_watchdog's CLOCKS: idle kill, activity extension, hard timeout.++The process lifecycle underneath (pipes, stdin writer thread, group kill,+KeyboardInterrupt cleanup, drain/reap) is ``proc.ManagedProcess`` and is owned by+tests/core/test_proc.py; this module keeps one integration smoke plus the clocks.+"""from __future__ import annotations-import os-import signalimport sysimport timefrom pathlib import Path@@ -11,35 +14,45 @@ from pathlib import Pathimport pytestfrom codeverse.agents.watchdog import run_with_watchdog+from tests.conftest import assert_pid_gonePY = sys.executable+#: spawns a grandchild (pid to argv[1]), prints nothing, then hangs — the shape that+#: proves a timeout kill takes the whole session, not just the leader.+_SPAWN_THEN_HANG = (+ "import subprocess, sys, time\n"+ "p = subprocess.Popen(['sleep', '300'])\n"+ "open(sys.argv[1], 'w').write(str(p.pid))\n"+ "time.sleep(300)\n"+)+-def test_normal_run_streams_lines(tmp_path: Path):+def test_normal_run_streams_lines_and_delivers_stdin(tmp_path: Path):+ """The integration smoke: stdin reaches the child, every line reaches ``on_line``+ and the bounded texts, and stdout/stderr stay separate."""seen = []res = run_with_watchdog(- [PY, "-c", "import sys; print('a'); print('b', file=sys.stderr); print('c')"],- cwd=tmp_path, env=os.environ, soft_timeout_s=10, idle_grace_s=5, hard_timeout_s=20,- on_line=lambda stream, text: seen.append((stream, text)),+ [PY, "-c", "import sys; print(sys.stdin.read().upper()); print('b', file=sys.stderr); print('c')"],+ cwd=tmp_path, env=None, soft_timeout_s=10, idle_grace_s=5, hard_timeout_s=20,+ stdin="hello", on_line=lambda stream, text: seen.append((stream, text)),)assert res.rc == 0 and not res.timed_out- assert res.stdout.splitlines() == ["a", "c"]+ assert res.stdout.splitlines() == ["HELLO", "c"]assert res.stderr.strip() == "b"- assert ("stdout", "a") in seen and ("stderr", "b") in seen-+ assert ("stdout", "HELLO") in seen and ("stderr", "b") in seen-def test_stdin_is_delivered(tmp_path: Path):- res = run_with_watchdog([PY, "-c", "import sys; print(sys.stdin.read().upper())"], cwd=tmp_path, env=None,- soft_timeout_s=10, idle_grace_s=5, stdin="hello")- assert res.stdout.strip() == "HELLO"--def test_idle_kill_after_soft_timeout(tmp_path: Path):+def test_idle_kill_after_soft_timeout_takes_the_whole_group(tmp_path: Path):+ """Silent past soft+grace → ``killed_reason="idle"``, and the grandchild dies with+ it (``start_new_session`` means only a group kill can reach it)."""+ marker = tmp_path / "child.pid"t0 = time.time()- res = run_with_watchdog([PY, "-c", "import time; time.sleep(60)"], cwd=tmp_path, env=None,+ res = run_with_watchdog([PY, "-c", _SPAWN_THEN_HANG, str(marker)], cwd=tmp_path, env=None,soft_timeout_s=1, idle_grace_s=1, hard_timeout_s=30, poll_s=0.2)assert res.timed_out and res.killed_reason == "idle"assert time.time() - t0 < 15+ assert_pid_gone(int(marker.read_text()))def test_activity_extends_past_soft_timeout(tmp_path: Path):@@ -59,30 +72,6 @@ def test_hard_timeout_kills_active_process(tmp_path: Path):assert time.time() - t0 < 15-def test_process_group_is_killed(tmp_path: Path):- """A grandchild (sleep) must die with the parent on timeout."""- marker = tmp_path / "child.pid"- code = (- "import subprocess, time, sys\n"- f"p = subprocess.Popen(['sleep', '300']); open({str(marker)!r}, 'w').write(str(p.pid)); sys.stdout.flush()\n"- "time.sleep(300)"- )- res = run_with_watchdog([PY, "-c", code], cwd=tmp_path, env=None, soft_timeout_s=1, idle_grace_s=1,- hard_timeout_s=30, poll_s=0.2)- assert res.timed_out- pid = int(marker.read_text())- time.sleep(0.5)- alive = True- try:- os.kill(pid, 0)- # zombie check: /proc/<pid>/status State- st = Path(f"/proc/{pid}/status").read_text() if Path(f"/proc/{pid}/status").exists() else "State:\tZ"- alive = "State:\tZ" not in st- except ProcessLookupError:- alive = False- assert not alive--def test_file_mtime_counts_as_activity(tmp_path: Path):src = tmp_path / "src"src.mkdir()@@ -97,49 +86,11 @@ def test_file_mtime_counts_as_activity(tmp_path: Path):assert res.rc == 0 and not res.timed_out-def _raise_ki(signum: int, frame: object) -> None:- raise KeyboardInterrupt--[email protected](60, method="thread") # thread method: the test drives SIGALRM itself-def test_keyboard_interrupt_kills_the_group(tmp_path: Path):- """A KI in the poll loop used to leak the whole start_new_session tree (no- try/finally anywhere) — and Ctrl-C's SIGINT never reaches that tree on its own.- The group must die and the KI must still propagate."""- pid_file = tmp_path / "pid"- code = (- "import os, pathlib, sys, time\n"- "pathlib.Path(sys.argv[1]).write_text(str(os.getpid()))\n"- "time.sleep(300)\n"- )- old = signal.signal(signal.SIGALRM, _raise_ki)- try:- signal.setitimer(signal.ITIMER_REAL, 0.8) # lands in time.sleep(poll_s)- with pytest.raises(KeyboardInterrupt):- run_with_watchdog([PY, "-c", code, str(pid_file)], cwd=tmp_path, env=None,- soft_timeout_s=120, idle_grace_s=120, hard_timeout_s=300, poll_s=0.1)- finally:- signal.setitimer(signal.ITIMER_REAL, 0.0)- signal.signal(signal.SIGALRM, old)- pgid = int(pid_file.read_text())- deadline = time.monotonic() + 10- while time.monotonic() < deadline:- try:- os.killpg(pgid, 0)- except ProcessLookupError:- return # gone and reaped- time.sleep(0.05)- raise AssertionError(f"process group {pgid} survived the KeyboardInterrupt")--@pytest.mark.timeout(60, method="thread")def test_child_that_never_reads_a_big_stdin_still_times_out(tmp_path: Path):- """The prompt used to be written SYNCHRONOUSLY in the main thread before the- poll loop started: a child that doesn't read >64 KiB of stdin blocked- proc.stdin.write() forever and BOTH timeouts were dead. Reachable for real:- codex delivers prompts via stdin exactly when they exceed STDIN_PROMPT_BYTES- (100 kB). 1 MB of stdin into a child that never reads it must still die on- the clocks."""+ """The prompt used to be written synchronously before the poll loop: a child that+ never reads >64 KiB of stdin blocked ``stdin.write`` forever and BOTH clocks were+ dead (codex pipes prompts over 100 kB this way). 1 MB in, must still die."""t0 = time.monotonic()res = run_with_watchdog([PY, "-c", "import time; time.sleep(300)"], cwd=tmp_path, env=None,soft_timeout_s=0.5, idle_grace_s=0.5, hard_timeout_s=8, poll_s=0.2,diff --git a/harness/tests/conftest.py b/harness/tests/conftest.pyindex 23b8184a..656225c8 100644--- a/harness/tests/conftest.py+++ b/harness/tests/conftest.py@@ -2,6 +2,8 @@from __future__ import annotations+import os+import timefrom pathlib import Pathimport pytest@@ -13,3 +15,24 @@ from codeverse.workspace import Workspacedef tmp_ws(tmp_path: Path) -> Workspace:"""A fresh, git-initialised workspace under a temp dir."""return Workspace(tmp_path / "run").create()+++def assert_pid_gone(pid: int, *, group: bool = False, timeout_s: float = 10.0) -> None:+ """Block until ``pid`` (``group=True``: its whole process group) is dead and reaped.++ A reaped zombie still answers ``kill(pid, 0)`` on some kernels, so ``State: Z``+ counts as gone for a single pid; for a GROUP it does not — an unreaped zombie+ leader keeps the group "alive" and is exactly the bug the group probes watch for.+ """+ probe = os.killpg if group else os.kill+ deadline = time.monotonic() + timeout_s+ while time.monotonic() < deadline:+ try:+ probe(pid, 0)+ except ProcessLookupError:+ return+ status = Path(f"/proc/{pid}/status")+ if not group and status.exists() and "State:\tZ" in status.read_text():+ return+ time.sleep(0.05)+ raise AssertionError(f"{'process group' if group else 'pid'} {pid} survived the kill")diff --git a/harness/tests/core/test_proc.py b/harness/tests/core/test_proc.pyindex 57d954ff..574f0eb8 100644--- a/harness/tests/core/test_proc.py+++ b/harness/tests/core/test_proc.py@@ -1,4 +1,9 @@-"""codeverse/proc.py — subprocess primitives (Batch-1 foundations)."""+"""codeverse/proc.py — subprocess primitives (Batch-1 foundations).++This module owns the ManagedProcess lifecycle: stdin delivery, group kill,+KeyboardInterrupt cleanup, drain/reap and bounded capture. ``agents/watchdog``+only adds clocks on top, so tests/agents/test_watchdog.py does not repeat them.+"""from __future__ import annotations@@ -26,6 +31,7 @@ from codeverse.proc import (tail,write_json_atomic,)+from tests.conftest import assert_pid_gonedef test_run_subprocess_captures_output(tmp_path: Path):@@ -43,40 +49,27 @@ def test_run_subprocess_stdin(tmp_path: Path):assert r.stdout == "hello"-def _assert_pid_gone(pid: int, timeout_s: float = 5.0) -> None:- deadline = time.monotonic() + timeout_s- while time.monotonic() < deadline:- try:- os.kill(pid, 0)- except ProcessLookupError:- return # gone — the group kill reached it- time.sleep(0.05)- raise AssertionError(f"pid {pid} survived the group kill")--def test_timeout_kills_the_whole_process_group(tmp_path: Path):"""A timed-out child AND its grandchildren die (killpg on the new session)."""r = run_subprocess(["bash", "-c", "sleep 30 & echo $!; wait"], cwd=tmp_path, timeout_s=0.4)assert r.timed_outassert r.returncode != 0- _assert_pid_gone(int(r.stdout.strip().splitlines()[0]))+ assert_pid_gone(int(r.stdout.strip().splitlines()[0]), timeout_s=5.0)def test_a_leader_that_exits_0_still_takes_its_grandchildren_down(tmp_path: Path):- """``__exit__`` asked "is the LEADER still running?", so a leader that exited 0 left- its same-group grandchildren (pgid == leader pid) alive — the exact incident this- module exists to end. Detached-stdio shape: nothing holds the pipes."""+ """``__exit__`` asked "is the LEADER still running?", so a leader that exited 0 left its+ same-group grandchildren alive. Detached-stdio shape: nothing holds the pipes."""pid_file = tmp_path / "pid"r = run_subprocess(["bash", "-c", f"sleep 300 >/dev/null 2>&1 & echo $! > {pid_file}; exit 0"],cwd=tmp_path, timeout_s=10)assert r.returncode == 0 and not r.timed_out- _assert_pid_gone(int(pid_file.read_text()))+ assert_pid_gone(int(pid_file.read_text()), timeout_s=5.0)def test_a_leader_that_exits_0_does_not_burn_the_drain_window(tmp_path: Path, monkeypatch):- """Same shape with the grandchild holding the INHERITED pipes: the drain used to- wait out DRAIN_TIMEOUT_S for a process nobody had signalled, then blame a- "detached descendant" that had never left the group."""+ """Same shape with the grandchild holding the INHERITED pipes: the drain used to wait out+ DRAIN_TIMEOUT_S for a process nobody had signalled, then blame a "detached descendant"."""import codeverse.proc as proc_modmonkeypatch.setattr(proc_mod, "DRAIN_TIMEOUT_S", 3.0)@@ -87,15 +80,13 @@ def test_a_leader_that_exits_0_does_not_burn_the_drain_window(tmp_path: Path, moassert r.returncode == 0 and "done" in r.stdoutassert time.monotonic() - t0 < 2.5, "the drain window was burned on a live group member"assert "detached descendant" not in r.stderr- _assert_pid_gone(int(pid_file.read_text()))+ assert_pid_gone(int(pid_file.read_text()), timeout_s=5.0)def test_a_detached_descendant_holding_the_pipes_cannot_extend_the_timeout(tmp_path: Path, monkeypatch):- """CP-4: after TimeoutExpired the code called a SECOND communicate() with no- timeout. killpg reaps only the child's own session, so a descendant that- setsid'd while inheriting stdout keeps the pipe open and that call blocked until- IT exited — unbounded. A caller passing timeout_s=N was never released at N.- """+ """CP-4: after TimeoutExpired a SECOND, untimed communicate() ran; a descendant that+ setsid'd while inheriting stdout kept the pipe open and blocked it unboundedly, so a+ caller passing timeout_s=N was never released at N."""import codeverse.proc as proc_mod# raising=False so this test still RUNS (and fails on the hang) against the@@ -132,7 +123,6 @@ def test_preexec_fn_runs_in_the_child(tmp_path: Path):assert r.stdout.strip() == str(soft)-def test_tail_caps_lines_and_chars():text = "\n".join(f"line{i}" for i in range(100))t = tail(text, max_lines=5)@@ -140,11 +130,14 @@ def test_tail_caps_lines_and_chars():assert len(tail("x" * 10000, max_chars=100)) == 100-def test_write_json_atomic_no_partial_file(tmp_path: Path):+# --------------------------------------------------------------------------- atomic writes+def test_write_json_atomic_round_trips_into_a_new_dir(tmp_path: Path):+ """Parents are created, non-JSON values go through ``default=str``, and the published+ directory holds the file and nothing else (no ``.tmp`` litter)."""p = tmp_path / "deep" / "out.json"write_json_atomic(p, {"a": 1, "p": Path("b")})assert json.loads(p.read_text()) == {"a": 1, "p": "b"}- assert not p.with_suffix(".json.tmp").exists()+ assert [q.name for q in p.parent.iterdir()] == ["out.json"]def test_workspace_write_json_delegates(tmp_ws):@@ -178,14 +171,10 @@ print(bad)def test_write_json_atomic_survives_concurrent_writers(tmp_path: Path):- """RS-1: `tmp = path.with_suffix('.tmp')` was ONE name for every writer, so writer A- renamed B's half-written tmp into place (readers saw truncated / zero-byte JSON at the- published path) and B's own replace() then died with FileNotFoundError. Real callers- share a path: the scene track fans zone agents out over one workspace root and each- agent's MCP `build` tool writes artifacts/build_last.json through this function.-- Three processes, same path. With a private tmp per writer this cannot fail; on the old- code it fails within a few dozen iterations."""+ """RS-1: one shared ``<name>.tmp`` per destination meant writer A renamed B's+ half-written tmp into place (readers saw truncated JSON) and B's replace() died with+ FileNotFoundError. Real callers share a path (zone agents → artifacts/build_last.json).+ Three PROCESSES, one path: on the old code this failed within a few dozen iterations."""import subprocessharness = Path(__file__).resolve().parents[2]@@ -199,20 +188,14 @@ def test_write_json_atomic_survives_concurrent_writers(tmp_path: Path):assert out.strip() == "0", f"a reader saw a partial file {out.strip()} time(s)"assert json.loads(target.read_text())["writer"] in ("A", "B", "C") # last writer wins, wholeassert not list(tmp_path.glob("*.tmp")), "no temp file left behind"-# --------------------------------------------------------------------------- atomic writes++def test_unique_tmp_is_per_process_and_per_thread(tmp_path: Path):- """A FIXED '<name>.tmp' is what made concurrent writers of one destination race.-- The threads are held at a BARRIER so all 8 are alive when they name their temp file.- That is the property CQ-2 actually needs — two writers racing on one destination at- the same instant must not choose the same name — and it is the only one- ``threading.get_ident()`` promises: an ident is unique among *living* threads and is- explicitly documented as recyclable once a thread exits. Without the barrier these- 8 one-line threads finish before the next starts, CPython hands out the same ident- every time, and the assertion reduces to 1 != 8 — which is exactly how this failed- on the Python 3.10 floor job (it happened to pass on 3.13) on the sign-off clean- clone, 2026-08-24. The fix under test was never wrong; the test was.- """+ """CQ-2's naming half: two writers racing on ONE destination must not pick the same+ temp name. The barrier is load-bearing — ``threading.get_ident()`` is unique only+ among LIVING threads, so without it CPython recycles one ident, the assertion decays+ to 1 != 8 and it fails only on some interpreters (seen on 3.10, passed on 3.13,+ 2026-08-24). The fix under test was never wrong; the test was."""from codeverse.proc import unique_tmpout = tmp_path / "cache" / "checker.mjs"@@ -239,8 +222,8 @@ def test_unique_tmp_is_per_process_and_per_thread(tmp_path: Path):def test_concurrent_writers_of_one_destination_all_succeed(tmp_path: Path):- """CQ-2: the second writer's replace() used to find its source already renamed- away -> FileNotFoundError. Barrier-synchronised, this failed ~half the time."""+ """CQ-2's write half: the second writer's replace() used to find its source already+ renamed away -> FileNotFoundError. Barrier-synchronised, this failed ~half the time."""from codeverse.proc import write_text_atomicout = tmp_path / "shared.txt"@@ -266,13 +249,7 @@ def test_concurrent_writers_of_one_destination_all_succeed(tmp_path: Path):assert list(tmp_path.iterdir()) == [out] # no temp litter left behind-def test_write_json_atomic_round_trips(tmp_path: Path):- out = tmp_path / "d" / "x.json"- write_json_atomic(out, {"a": 1})- assert json.loads(out.read_text()) == {"a": 1}- assert [p.name for p in out.parent.iterdir()] == ["x.json"]--+# --------------------------------------------------------------------------- tolerant readsdef test_read_json_or_none_is_none_unless_a_dict_parses(tmp_path: Path):assert read_json_or_none(tmp_path / "missing.json") is None(tmp_path / "bad.json").write_text("{not json")@@ -281,7 +258,7 @@ def test_read_json_or_none_is_none_unless_a_dict_parses(tmp_path: Path):assert read_json_or_none(tmp_path / "list.json") is None(tmp_path / "ok.json").write_bytes(b'{"a": "caf\xc3\xa9", "b": "\xff"}')assert read_json_or_none(tmp_path / "ok.json") is None # undecodable byte -> ValueError- assert read_json_or_none(tmp_path / "ok.json", errors="replace") == {"a": "café", "b": "\ufffd"}+ assert read_json_or_none(tmp_path / "ok.json", errors="replace") == {"a": "café", "b": "�"}def test_jsonl_helpers_round_trip_and_skip_bad_lines(tmp_path: Path):@@ -316,33 +293,27 @@ def test_scrub_secrets_keeps_everything_generated_code_needs():assert scrub_secrets(dict(env)) == env--def _assert_group_gone(pgid: int, timeout_s: float = 10.0) -> None:- deadline = time.monotonic() + timeout_s- while time.monotonic() < deadline:- try:- os.killpg(pgid, 0)- except ProcessLookupError:- return # every member is dead AND reaped- time.sleep(0.05)- raise AssertionError(f"process group {pgid} is still alive")---#: writes its own pid to argv[1], then hangs — a child that ignores nothing.+# --------------------------------------------------------------------------- ManagedProcess lifecycle+#: spawns a grandchild, writes its OWN pid (== the new session's pgid) to argv[1] and+#: hangs — so the probe below is a real GROUP probe, not just "the leader died"._PID_THEN_SLEEP = (- "import os, pathlib, sys, time\n"+ "import os, pathlib, subprocess, sys, time\n"+ "subprocess.Popen(['sleep', '300'])\n""pathlib.Path(sys.argv[1]).write_text(str(os.getpid()))\n""time.sleep(300)\n")+def _raise_ki(signum: int, frame: object) -> None:+ raise KeyboardInterrupt++@pytest.mark.timeout(60, method="thread") # thread method: the test drives SIGALRM itselfdef test_keyboard_interrupt_kills_the_group(tmp_path: Path):- """``start_new_session`` puts the child outside the terminal's foreground group,- so Ctrl-C's SIGINT NEVER reaches it — the parent's KeyboardInterrupt must kill- the group itself. Pre-fix there was no try/finally around communicate(): every- interrupt during a blender/node run orphaned the whole tree (the wedged-browser- incident). The KI must still propagate to the caller."""+ """``start_new_session`` puts the child outside the terminal's foreground group, so+ Ctrl-C's SIGINT NEVER reaches it — the parent's KeyboardInterrupt must kill the group+ itself (pre-fix: no try/finally around communicate(), so every interrupt during a+ blender/node run orphaned the tree). The KI must still propagate to the caller."""pid_file = tmp_path / "pid"old = signal.signal(signal.SIGALRM, _raise_ki)try:@@ -353,7 +324,7 @@ def test_keyboard_interrupt_kills_the_group(tmp_path: Path):finally:signal.setitimer(signal.ITIMER_REAL, 0.0)signal.signal(signal.SIGALRM, old)- _assert_group_gone(int(pid_file.read_text()))+ assert_pid_gone(int(pid_file.read_text()), group=True)def test_invalid_utf8_replaces_instead_of_raising(tmp_path: Path):@@ -390,11 +361,6 @@ def test_huge_output_is_bounded_head_and_tail(tmp_path: Path):assert "x" * 1000 in r.stdout[:cut] and "x" * 1000 in r.stdout[cut:]-# --------------------------------------------------------------------------- ManagedProcess lifecycle-def _raise_ki(signum: int, frame: object) -> None:- raise KeyboardInterrupt--def test_managed_process_reaps_on_exit_no_zombie(tmp_path: Path):with ManagedProcess([sys.executable, "-c", "print('hi')"], cwd=tmp_path) as mp:mp.wait(timeout=30)diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.pyindex db2688ba..c40ba59d 100644--- a/harness/tests/core/test_run_layout.py+++ b/harness/tests/core/test_run_layout.py@@ -82,6 +82,44 @@ def test_record_blocks_are_additive(tmp_path: Path):# --------------------------------------------------------------------------- relocation+def _moved_run(tmp_path: Path):+ """A run written at A/run1 with one contact sheet, then MOVED to B/run1 — the SMOKE2+ shape. Returns ``(old root, new root, the stored sheet path, a record naming it)``."""+ import shutil++ from codeverse.contracts.artifacts import RenderSet+ from codeverse.contracts.common import Backends, Language, Track+ from codeverse.contracts.run import RoundRecord, RunStatus++ a = tmp_path / "A" / "run1"+ (a / "artifacts" / "renders" / "r01").mkdir(parents=True)+ sheet_a = a / "artifacts" / "renders" / "r01" / "sheet.png"+ sheet_a.write_bytes(b"PNG")+ spec = Spec(id="run1", track=Track.STATIC_OBJECT, language=Language.BLENDER,+ prompt="a wooden chair", backends=Backends(generator="api-agent:gemini:x"))+ rec = RunRecord(spec=spec, workspace=str(a), status=RunStatus.PASSED, best_round=0,+ rounds=[RoundRecord(index=0, kind="generate",+ renders=RenderSet(views=[], contact_sheet=str(sheet_a)))])+ b = tmp_path / "B" / "run1"+ b.parent.mkdir(parents=True)+ shutil.move(str(a), str(b))+ return a, b, sheet_a, rec+++def _captured(render) -> str:+ """rich's Console holds its own stream, so capsys never sees it; widen it too so the+ panel cannot wrap the path under assertion."""+ from codeverse.cli._fmt import console++ old_width, console.width = console.width, 400+ try:+ with console.capture() as cap:+ render()+ finally:+ console.width = old_width+ return cap.get()++def test_a_relocated_run_still_resolves_its_stored_paths(tmp_path):"""SMOKE2: record.json stores ABSOLUTE host paths (29 per run — rounds[].renders[].path, contact_sheet, build.glb_path, build.extra_paths, census exports — plus@@ -94,20 +132,10 @@ def test_a_relocated_run_still_resolves_its_stored_paths(tmp_path):The intended repair, _judge.resolve_paths, only rebased paths for which``Path(p).is_absolute()`` was False — a no-op against every record the harness itselfwrites — and _fmt, which is what show/status actually use, never called it at all."""- import shutil-from codeverse.workspace import Workspace- a = tmp_path / "A" / "run1"- (a / "artifacts" / "renders" / "r01").mkdir(parents=True)- sheet_a = a / "artifacts" / "renders" / "r01" / "sheet.png"- sheet_a.write_bytes(b"PNG")+ _a, b, sheet_a, _rec = _moved_run(tmp_path)stored = str(sheet_a) # what the writer puts in record.json-- b = tmp_path / "B" / "run1"- b.parent.mkdir(parents=True)- shutil.move(str(a), str(b))-ws = Workspace(b)got = ws.rebase(stored)assert got.exists(), f"a moved run must still find its own sheet, got {got}"@@ -126,39 +154,11 @@ def test_a_relocated_run_still_resolves_its_stored_paths(tmp_path):def test_show_prints_the_sheet_that_exists_after_a_move(tmp_path):"""The user-visible half: `3dcv show` must not print a path that is not there."""- import shutil-- from codeverse.cli._fmt import console, print_record_summary- from codeverse.contracts.artifacts import RenderSet- from codeverse.contracts.common import Backends, Language, Track- from codeverse.contracts.run import RoundRecord, RunRecord, RunStatus- from codeverse.contracts.spec import Spec+ from codeverse.cli._fmt import print_record_summaryfrom codeverse.workspace import Workspace- a = tmp_path / "A" / "run1"- (a / "artifacts" / "renders" / "r01").mkdir(parents=True)- sheet_a = a / "artifacts" / "renders" / "r01" / "sheet.png"- sheet_a.write_bytes(b"PNG")-- spec = Spec(id="run1", track=Track.STATIC_OBJECT, language=Language.BLENDER,- prompt="a wooden chair", backends=Backends(generator="api-agent:gemini:x"))- rec = RunRecord(spec=spec, workspace=str(a), status=RunStatus.PASSED, best_round=0,- rounds=[RoundRecord(index=0, kind="generate",- renders=RenderSet(views=[], contact_sheet=str(sheet_a)))])-- b = tmp_path / "B" / "run1"- b.parent.mkdir(parents=True)- shutil.move(str(a), str(b))-- # rich's Console holds its own stream, so capsys does not see it; widen it so the- # panel does not wrap the path we are asserting on- old_width, console.width = console.width, 400- try:- with console.capture() as cap:- print_record_summary(rec, Workspace(b).root)- finally:- console.width = old_width- printed = cap.get()+ _a, b, _sheet, rec = _moved_run(tmp_path)+ printed = _captured(lambda: print_record_summary(rec, Workspace(b).root))line = next(ln for ln in printed.splitlines() if "sheet:" in ln)shown = line.split("sheet:", 1)[1].strip().rstrip("│ ").strip()assert shown.endswith("sheet.png"), f"the panel wrapped the path: {line!r}"@@ -236,37 +236,10 @@ def test_show_itself_prints_the_relocated_sheet_not_the_stored_one(tmp_path):the raw stored ABSOLUTE path, so `3dcv show` on a moved run still printed a sheetunder the original root while ``object.glb`` beside it resolved correctly. Verifiedon the real e2e_chair_blender run before this line existed."""- import shutil-- from codeverse.cli._fmt import consolefrom codeverse.cli.layout_cmd import print_evidence- from codeverse.contracts.artifacts import RenderSet- from codeverse.contracts.common import Backends, Language, Track- from codeverse.contracts.run import RoundRecord, RunRecord, RunStatus- from codeverse.contracts.spec import Specfrom codeverse.workspace import Workspace- a = tmp_path / "A" / "run1"- (a / "artifacts" / "renders" / "r01").mkdir(parents=True)- sheet_a = a / "artifacts" / "renders" / "r01" / "sheet.png"- sheet_a.write_bytes(b"PNG")-- spec = Spec(id="run1", track=Track.STATIC_OBJECT, language=Language.BLENDER,- prompt="a wooden chair", backends=Backends(generator="api-agent:gemini:x"))- rec = RunRecord(spec=spec, workspace=str(a), status=RunStatus.PASSED, best_round=0,- rounds=[RoundRecord(index=0, kind="generate",- renders=RenderSet(views=[], contact_sheet=str(sheet_a)))])-- b = tmp_path / "B" / "run1"- b.parent.mkdir(parents=True)- shutil.move(str(a), str(b))-- old_width, console.width = console.width, 400- try:- with console.capture() as cap:- print_evidence(Workspace(b), rec)- finally:- console.width = old_width- out = cap.get()+ a, b, _sheet, rec = _moved_run(tmp_path)+ out = _captured(lambda: print_evidence(Workspace(b), rec))assert str(b / "artifacts" / "renders" / "r01" / "sheet.png") in outassert str(a) not in out, "`3dcv show` must not print a path under the old root"diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.pyindex 09cd2713..5e2092d7 100644--- a/harness/tests/flywheel_cli/test_cli.py+++ b/harness/tests/flywheel_cli/test_cli.py@@ -16,6 +16,37 @@ from codeverse.contracts.spec import Specrunner = CliRunner()+def made_run(tmp_path: Path):+ """`3dcv make --no-run` into a fresh runs dir → ``(runs_dir, run_dir)``."""+ def make(*extra: str) -> tuple[Path, Path]:+ runs = tmp_path / "runs"+ r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", *extra])+ assert r.exit_code == 0, r.output+ return runs, next(d for d in runs.iterdir() if d.is_dir())++ return make+++def stub_track(monkeypatch):+ """Replace ``tracks.get_track`` with a stub whose ``run`` calls ``on_run(spec, resume,+ force)`` and then raises ``exc`` — KeyboardInterrupt by default, which the CLI turns+ into exit code 130, so the resume path is exercised without any real work."""+ import codeverse.tracks as tracks_pkg++ def install(on_run=None, exc: BaseException | None = None):+ class _T:+ def run(self, spec, ws_, *, resume=False, force=False):+ if on_run is not None:+ on_run(spec, resume, force)+ raise exc if exc is not None else KeyboardInterrupt++ monkeypatch.setattr(tracks_pkg, "get_track", lambda track, **options: _T())++ return install++def test_help_and_version():r = runner.invoke(app, ["--help"])assert r.exit_code == 0 and "flywheel" in r.output and "doctor" in r.output@@ -235,25 +266,10 @@ def test_make_invalid_combo_leaves_no_orphan_workspace(tmp_path: Path):assert not (runs / "bad").exists(), "invalid spec must not leave an orphan run dir"-def test_resume_budget_flags_rewrite_spec_and_emit_event(tmp_path: Path, monkeypatch):- runs = tmp_path / "runs"- r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", "--max-usd", "1.0", "--rounds", "1"])- assert r.exit_code == 0, r.output- ws = next(d for d in runs.iterdir() if d.is_dir())-+def test_resume_budget_flags_rewrite_spec_and_emit_event(made_run, stub_track):+ runs, ws = made_run("--max-usd", "1.0", "--rounds", "1")seen = {}-- def fake_get_track(track, **options):- class _T:- def run(self, spec, ws_, *, resume=False, force=False):- seen["spec"] = spec- raise KeyboardInterrupt # stop before any real work-- return _T()-- import codeverse.tracks as tracks_pkg-- monkeypatch.setattr(tracks_pkg, "get_track", fake_get_track)+ stub_track(lambda spec, resume, force: seen.__setitem__("spec", spec))r2 = runner.invoke(app, ["resume", ws.name, "--runs-dir", str(runs), "--max-usd", "4.5", "--rounds", "3"])assert r2.exit_code == 130spec = Spec.model_validate_json((ws / "spec.json").read_text())@@ -264,7 +280,7 @@ def test_resume_budget_flags_rewrite_spec_and_emit_event(tmp_path: Path, monkeypassert raised and raised[0]["max_usd"] == 4.5 and raised[0]["max_rounds"] == 3-def test_resume_refuses_a_finished_run_and_never_re_enters_it(tmp_path: Path, monkeypatch):+def test_resume_refuses_a_finished_run_and_never_re_enters_it(made_run, stub_track):"""SMOKE1: `3dcv resume` called _run_track unconditionally, with no look atrun_state. On a run that had ended stop_reason='pass' it re-entered the pipeline,re-ran the plan stage as a real billed model call and rewrote status from 'passed'@@ -274,25 +290,12 @@ def test_resume_refuses_a_finished_run_and_never_re_enters_it(tmp_path: Path, mofrom codeverse.orchestrator.state import RunStatefrom codeverse.workspace import Workspace- runs = tmp_path / "runs"- assert runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run"]).exit_code == 0- ws = Workspace(next(d for d in runs.iterdir() if d.is_dir()))- state = RunState(status=RunStatus.PASSED, stop_reason="pass", best_score=0.7436)- state.save(ws)+ runs, run_dir = made_run()+ ws = Workspace(run_dir)+ RunState(status=RunStatus.PASSED, stop_reason="pass", best_score=0.7436).save(ws)entered = []-- def fake_get_track(track, **options):- class _T:- def run(self, spec, ws_, *, resume=False, force=False):- entered.append(resume)- raise KeyboardInterrupt-- return _T()-- import codeverse.tracks as tracks_pkg-- monkeypatch.setattr(tracks_pkg, "get_track", fake_get_track)+ stub_track(lambda spec, resume, force: entered.append(resume))r = runner.invoke(app, ["resume", ws.root.name, "--runs-dir", str(runs)])assert r.exit_code == 1 and "already finished" in r.outputassert entered == [], "the pipeline must not be re-entered"@@ -311,51 +314,26 @@ def test_resume_refuses_a_finished_run_and_never_re_enters_it(tmp_path: Path, moassert runner.invoke(app, ["resume", ws.root.name, "--runs-dir", str(runs)]).exit_code == 130-def test_resume_threads_force_through_to_the_track(tmp_path: Path, monkeypatch):+def test_resume_threads_force_through_to_the_track(made_run, stub_track):"""reconcile_resume (tracks/lifecycle.py) needs the CLI's --force to decide betweenrefusing a spec edit (SpecChanged) and archiving the old rounds underrounds/pre_force/ — so `3dcv resume --force` must reach BaseTrack.run(force=...)."""- runs = tmp_path / "runs"- assert runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run"]).exit_code == 0- ws = next(d for d in runs.iterdir() if d.is_dir())+ runs, ws = made_run()seen = {}-- def fake_get_track(track, **options):- class _T:- def run(self, spec, ws_, *, resume=False, force=False):- seen["resume"], seen["force"] = resume, force- raise KeyboardInterrupt-- return _T()-- import codeverse.tracks as tracks_pkg-- monkeypatch.setattr(tracks_pkg, "get_track", fake_get_track)+ stub_track(lambda spec, resume, force: seen.update(resume=resume, force=force))assert runner.invoke(app, ["resume", ws.name, "--runs-dir", str(runs)]).exit_code == 130assert seen == {"resume": True, "force": False}assert runner.invoke(app, ["resume", ws.name, "--runs-dir", str(runs), "--force"]).exit_code == 130assert seen == {"resume": True, "force": True}-def test_a_spec_change_refusal_is_a_clean_cli_error(tmp_path: Path, monkeypatch):+def test_a_spec_change_refusal_is_a_clean_cli_error(made_run, stub_track):"""SpecChanged is a refusal with instructions (fork, or --force to archive), not acrash: no traceback, and the CLI's typed configuration-error exit code."""from codeverse.tracks.lifecycle import SpecChanged- runs = tmp_path / "runs"- assert runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run"]).exit_code == 0- ws = next(d for d in runs.iterdir() if d.is_dir())-- def fake_get_track(track, **options):- class _T:- def run(self, spec, ws_, *, resume=False, force=False):- raise SpecChanged("spec.json changed under this run; fork a new run or resume with --force")-- return _T()-- import codeverse.tracks as tracks_pkg-- monkeypatch.setattr(tracks_pkg, "get_track", fake_get_track)+ runs, ws = made_run()+ stub_track(exc=SpecChanged("spec.json changed under this run; fork a new run or resume with --force"))r = runner.invoke(app, ["resume", ws.name, "--runs-dir", str(runs)])out = r.output + str(getattr(r, "stderr", "") or "")assert r.exit_code == 2 and "--force" in outdiff --git a/harness/tests/flywheel_cli/test_manifest_pack.py b/harness/tests/flywheel_cli/test_manifest_pack.pyindex 52ff01ae..a0d70040 100644--- a/harness/tests/flywheel_cli/test_manifest_pack.py+++ b/harness/tests/flywheel_cli/test_manifest_pack.py@@ -32,6 +32,21 @@ from codeverse.flywheel.pack import PackError, pack_samples, verify_locatorsCHAIR_ID = "3dcodeverse/static_object/blender/wooden_chair_ab12cd34"+def exported_ds(runs_dir: Path, tmp_path: Path) -> Path:+ """A freshly exported dataset: 3 samples + a hashed manifest, not packed yet."""+ out = tmp_path / "ds"+ export_samples(runs_dir, out)+ return out+++def packed_ds(exported_ds: Path) -> Path:+ """...and packed once — the previous GOOD dataset every failure window must leave intact."""+ pack_samples(exported_ds)+ return exported_ds++def _tar_member_names(out: Path) -> list[str]:names: list[str] = []for tp in sorted(out.glob("samples-*.tar")):@@ -105,82 +120,64 @@ def _packed_state(out: Path) -> dict[str, bytes]:for p in [*out.glob("samples-*.tar"), out / "metadata.jsonl", out / "metadata.parquet"]}-def test_a_failure_inside_the_pack_loop_leaves_the_old_tar_and_index_intact(runs_dir: Path, tmp_path: Path):- out = tmp_path / "ds"- export_samples(runs_dir, out)- pack_samples(out)- before = _packed_state(out)+def test_a_failure_inside_the_pack_loop_leaves_the_old_tar_and_index_intact(packed_ds: Path):+ before = _packed_state(packed_ds)# corrupt the recorded hash of a file in the LAST entry: the mismatch fires# mid-pack, after earlier samples were already added to the new tmp archive- m = load_manifest(out)+ m = load_manifest(packed_ds)victim = m.entries[-1]rel = sorted(victim.files)[0]victim.files[rel] = "0" * 64- write_manifest(m, out)+ write_manifest(m, packed_ds)with pytest.raises(PackError, match=re.escape(rel)):- pack_samples(out)- assert _packed_state(out) == before # old archives AND index untouched- assert not list(out.glob("*.tmp")) # the half-written tmp tar is cleaned up- assert verify_locators(out) == 3 # the previous pack still round-trips+ pack_samples(packed_ds)+ assert _packed_state(packed_ds) == before # old archives AND index untouched+ assert not list(packed_ds.glob("*.tmp")) # the half-written tmp tar is cleaned up+ assert verify_locators(packed_ds) == 3 # the previous pack still round-trips-def test_a_failure_after_the_pack_loop_publishes_nothing(runs_dir: Path, tmp_path: Path, monkeypatch):+def test_a_failure_after_the_pack_loop_publishes_nothing(packed_ds: Path, monkeypatch):"""The window the tar loop does NOT cover: every tar is written, then the indexwrite fails. Publishing the tars alone left the OLD index resolving to the newtars' byte offsets — six rows pointing at the wrong bytes, and verify_locatorshappily passing a corrupt dataset."""import codeverse.flywheel.pack as P- out = tmp_path / "ds"- export_samples(runs_dir, out)- pack_samples(out)- before = _packed_state(out)+ before = _packed_state(packed_ds)monkeypatch.setattr(P, "write_parquet", lambda *a, **k: (_ for _ in ()).throw(OSError("No space left on device")))with pytest.raises(OSError, match="No space left"):- pack_samples(out)- assert _packed_state(out) == before- assert not list(out.glob("*.tmp"))- assert verify_locators(out) == 3+ pack_samples(packed_ds)+ assert _packed_state(packed_ds) == before+ assert not list(packed_ds.glob("*.tmp"))+ assert verify_locators(packed_ds) == 3-def test_a_repack_with_fewer_shards_leaves_no_orphan_tar(runs_dir: Path, tmp_path: Path):- out = tmp_path / "ds"- export_samples(runs_dir, out)- assert pack_samples(out, max_tar_bytes=1).tars == ["samples-000.tar", "samples-001.tar", "samples-002.tar"]- prep = pack_samples(out) # one shard now: 001/002 are dead bytes the index never names- assert prep.tars == ["samples-000.tar"]- assert sorted(p.name for p in out.glob("samples-*.tar")) == ["samples-000.tar"]- assert verify_locators(out) == 3+def test_repacking_over_an_existing_archive_succeeds_and_leaves_no_orphan_tar(packed_ds: Path):+ """Re-packing used to truncate the previous archive at open; and a repack into FEWER+ shards left 001/002 on disk as dead bytes the new index never names."""+ assert pack_samples(packed_ds, max_tar_bytes=1).tars == ["samples-000.tar", "samples-001.tar", "samples-002.tar"]+ prep = pack_samples(packed_ds)+ assert prep.tars == ["samples-000.tar"] and prep.n_samples == 3+ assert sorted(p.name for p in packed_ds.glob("samples-*.tar")) == ["samples-000.tar"]+ assert verify_locators(packed_ds) == 3+ assert not list(packed_ds.glob("*.tmp"))-def test_a_tampered_sample_file_fails_fast_and_names_it(runs_dir: Path, tmp_path: Path):- out = tmp_path / "ds"- export_samples(runs_dir, out)- (out / "static_object" / "blender" / "wooden_chair_ab12cd34" / "code.py").write_text("tampered")+def test_a_tampered_sample_file_fails_fast_and_names_it(exported_ds: Path):+ (exported_ds / "static_object" / "blender" / "wooden_chair_ab12cd34" / "code.py").write_text("tampered")with pytest.raises(PackError, match="code.py"):- pack_samples(out)- assert not list(out.glob("samples-*.tar")) and not list(out.glob("*.tmp"))---def test_repack_over_an_existing_archive_succeeds_atomically(runs_dir: Path, tmp_path: Path):- out = tmp_path / "ds"- export_samples(runs_dir, out)- assert pack_samples(out).n_samples == 3- prep2 = pack_samples(out) # re-pack over the existing archive (used to truncate it at open)- assert prep2.n_samples == 3 and verify_locators(out) == 3- assert not list(out.glob("*.tmp"))+ pack_samples(exported_ds)+ assert not list(exported_ds.glob("samples-*.tar")) and not list(exported_ds.glob("*.tmp"))# --------------------------------------------------------------------------- phantom rows-def test_planted_src_meta_json_is_not_a_row_and_not_packed(runs_dir: Path, tmp_path: Path):- out = tmp_path / "ds"- export_samples(runs_dir, out)- sdir = out / "static_object" / "blender" / "wooden_chair_ab12cd34"+def test_planted_src_meta_json_is_not_a_row_and_not_packed(exported_ds: Path):+ sdir = exported_ds / "static_object" / "blender" / "wooden_chair_ab12cd34"(sdir / "src" / "meta.json").write_text(json.dumps({"id": "phantom", "key": "phantom"}))- rows = collect_rows(out) # the recovery/debug rescan is exactly 3 levels deep+ rows = collect_rows(exported_ds) # the recovery/debug rescan is exactly 3 levels deepassert len(rows) == 3 and all(r["id"] != "phantom" for r in rows)- pack_samples(out) # and pack never looks at the directory tree at all- assert verify_locators(out) == 3- assert "wooden_chair_ab12cd34/src/meta.json" not in _tar_member_names(out)- keys = {json.loads(ln)["key"] for ln in (out / "metadata.jsonl").read_text().splitlines()}+ pack_samples(exported_ds) # and pack never looks at the directory tree at all+ assert verify_locators(exported_ds) == 3+ assert "wooden_chair_ab12cd34/src/meta.json" not in _tar_member_names(exported_ds)+ keys = {json.loads(ln)["key"] for ln in (exported_ds / "metadata.jsonl").read_text().splitlines()}assert keys == {"wooden_chair_ab12cd34", "wooden_chair_codex", "lamp_three"}diff --git a/harness/tests/models/test_gemini.py b/harness/tests/models/test_gemini.pyindex 81c4193a..e1907795 100644--- a/harness/tests/models/test_gemini.py+++ b/harness/tests/models/test_gemini.py@@ -28,6 +28,10 @@ PNG_1PX = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==")+#: the one tool spec every tool-call test uses.+MEASURE_TOOL = ToolSpec(name="measure", description="m",+ parameters={"type": "object", "properties": {"part": {"type": "string"}}})+def text_response(text: str, *, finish: str = "STOP", thoughts: int = 3@@ -372,11 +376,7 @@ def test_thinking_rejected_falls_back_without_thinking_config():def test_tool_call_roundtrip_and_signature_cache():- tool = ToolSpec(- name="measure",- description="m",- parameters={"type": "object", "properties": {"part": {"type": "string"}}},- )+ tool = MEASURE_TOOLm, log, _ = make_model([call_response("measure", {"part": "all"}), text_response("45 cm")])req = ChatRequest(messages=[ChatMessage.user("measure it")], tools=[tool])r = m.generate(req)@@ -542,42 +542,6 @@ def _resp_with_calls(parts: list[types.Part]) -> types.GenerateContentResponse:)-def test_provider_call_id_round_trips_verbatim():- """A GENUINE provider function_call.id must be echoed unchanged on BOTH the- function_call replay and the function_response (both used to drop it)."""- from codeverse.models.gemini_convert import is_synthetic_call_id-- tool = ToolSpec(- name="measure",- description="m",- parameters={"type": "object", "properties": {"part": {"type": "string"}}},- )- part = types.Part(- function_call=types.FunctionCall(name="measure", args={"part": "all"}, id="prov-42")- )- part.thought_signature = b"sig-prov"- m, log, _ = make_model([_resp_with_calls([part]), text_response("45 cm")])- req = ChatRequest(messages=[ChatMessage.user("measure it")], tools=[tool])- r = m.generate(req)- call = r.tool_calls[0]- assert call.id == "prov-42" and not is_synthetic_call_id(call.id)- assert SIGNATURES.get("prov-42") == b"sig-prov"- msgs = [- *req.messages,- ChatMessage(role="assistant", parts=[call]),- ChatMessage(- role="tool",- parts=[- ToolResultPart(call_id=call.id, name="measure", content=json.dumps({"h": 0.45}))- ],- ),- ]- m.generate(ChatRequest(messages=msgs, tools=[tool]))- contents = log[1]["contents"]- assert contents[1].parts[0].function_call.id == "prov-42"- assert contents[2].parts[0].function_response.id == "prov-42"--def test_synthetic_call_ids_are_never_echoed_to_the_provider():"""When the provider sent NO id we mint one for local pairing — and it mustnever travel back to Gemini (an id the provider did not issue)."""@@ -601,23 +565,23 @@ def test_synthetic_call_ids_are_never_echoed_to_the_provider():def test_two_parallel_same_name_calls_keep_their_provider_ids():- """Two calls to the SAME tool in one turn: only the echoed ids pair each- response with its call, and each call keeps its own thought_signature."""+ """Two calls to the SAME tool in one turn: a GENUINE provider id is echoed verbatim on+ BOTH the function_call replay and the function_response (both used to drop it), and only+ those ids pair a response with its call — each keeping its own thought_signature."""+ from codeverse.models.gemini_convert import is_synthetic_call_id+parts = []for cid, target in (("id-a", "seat"), ("id-b", "leg")):p = types.Part(function_call=types.FunctionCall(name="measure", args={"part": target}, id=cid))p.thought_signature = f"sig-{cid}".encode()parts.append(p)- tool = ToolSpec(- name="measure",- description="m",- parameters={"type": "object", "properties": {"part": {"type": "string"}}},- )+ tool = MEASURE_TOOLm, log, _ = make_model([_resp_with_calls(parts), text_response("done")])req = ChatRequest(messages=[ChatMessage.user("measure both")], tools=[tool])r = m.generate(req)a, b = r.tool_callsassert (a.id, b.id) == ("id-a", "id-b") and a.name == b.name == "measure"+ assert not is_synthetic_call_id(a.id), "a provider id must not be mistaken for a minted one"assert SIGNATURES.get("id-a") == b"sig-id-a" and SIGNATURES.get("id-b") == b"sig-id-b"msgs = [*req.messages,diff --git a/harness/tests/models/test_health.py b/harness/tests/models/test_health.pyindex 9c3859a7..0dcb3bf0 100644--- a/harness/tests/models/test_health.py+++ b/harness/tests/models/test_health.py@@ -184,23 +184,11 @@ def test_pool_budget_sums_caps_not_heads(monkeypatch):"""Two siblings at 16 each leave 32 of headroom; a third at 16 fits, one at 64 does not.Head-counting (the first rule) would have refused both — and on 2026-08-24 it stalledan entire A/B wave behind two batteries that were themselves parked."""- health = _fake_proc(- monkeypatch,- {- 101: (- ["python", "-m", "codeverse.cli.main", "bench", "run"],- {"CV3D_MAX_IN_FLIGHT": "16"},- ),- 102: (- ["python", "bench/compare_backends.py", "--arms", "x"],- {"CV3D_RATE__MAX_IN_FLIGHT": "16"},- ),- 103: (- ["/bin/bash", "-c", "cd /home/u/3dcodeverse && sleep 1"],- {},- ), # not a harness process- },- )+ health = _fake_proc(monkeypatch, {+ 101: (["python", "-m", "codeverse.cli.main", "bench", "run"], {"CV3D_MAX_IN_FLIGHT": "16"}),+ 102: (["python", "bench/compare_backends.py", "--arms", "x"], {"CV3D_RATE__MAX_IN_FLIGHT": "16"}),+ 103: (["/bin/bash", "-c", "cd /home/u/3dcodeverse && sleep 1"], {}), # not a harness process+ })pb = health.pool_budget()assert (pb.siblings, pb.used, pb.headroom) == (2, 32, 32), str(pb)assert pb.fits(16) and pb.fits(32) and not pb.fits(33) and not pb.fits(64)@@ -208,12 +196,7 @@ def test_pool_budget_sums_caps_not_heads(monkeypatch):def test_a_sibling_that_set_no_cap_counts_at_the_default(monkeypatch):"""An unconfigured battery runs at Rate().max_in_flight (64) and fills the whole budget."""- health = _fake_proc(- monkeypatch,- {- 201: (["python", "-m", "codeverse.cli.main", "make", "a chair"], {}),- },- )+ health = _fake_proc(monkeypatch, {201: (["python", "-m", "codeverse.cli.main", "make", "a chair"], {})})pb = health.pool_budget()assert pb.used == 64 and pb.headroom == 0 and not pb.fits(1)@@ -224,42 +207,21 @@ def test_an_ab_plan_driver_is_not_charged_for_its_children(monkeypatch):It sets no cap on itself (``--max-in-flight`` is the CHILD cap), so charging it wouldbook the 64 default — the whole knee — on top of the children that actually hold thetraffic, and every sibling would refuse to launch."""- health = _fake_proc(- monkeypatch,- {- 301: (- ["python", "-m", "bench.ab_plan", "--prompts", "p.yaml", "--max-in-flight", "16"],- {},- ),- 302: (- ["python", "-m", "bench.ab_plan", "cell", "--arm", "control"],- {"CV3D_MAX_IN_FLIGHT": "16"},- ),- 303: (- ["python", "-m", "bench.ab_plan", "cell", "--arm", "variant"],- {"CV3D_MAX_IN_FLIGHT": "16"},- ),- },- )+ health = _fake_proc(monkeypatch, {+ 301: (["python", "-m", "bench.ab_plan", "--prompts", "p.yaml", "--max-in-flight", "16"], {}),+ 302: (["python", "-m", "bench.ab_plan", "cell", "--arm", "control"], {"CV3D_MAX_IN_FLIGHT": "16"}),+ 303: (["python", "-m", "bench.ab_plan", "cell", "--arm", "variant"], {"CV3D_MAX_IN_FLIGHT": "16"}),+ })pb = health.pool_budget()assert (pb.siblings, pb.used, pb.headroom) == (3, 32, 32), str(pb)# the same three processes under the script spelling read identically- health = _fake_proc(- monkeypatch,- {- 311: (["python", "bench/ab_plan.py", "--prompts", "p.yaml"], {}),- 312: (- ["python", "bench/ab_plan.py", "cell", "--arm", "control"],- {"CV3D_MAX_IN_FLIGHT": "8"},- ),- },- )+ health = _fake_proc(monkeypatch, {+ 311: (["python", "bench/ab_plan.py", "--prompts", "p.yaml"], {}),+ 312: (["python", "bench/ab_plan.py", "cell", "--arm", "control"], {"CV3D_MAX_IN_FLIGHT": "8"}),+ })assert health.pool_budget().used == 8# a compare_backends driver runs its cells in THREADS, in itself: it is charged- health = _fake_proc(- monkeypatch,- {321: (["python", "-m", "bench.compare_backends"], {"CV3D_MAX_IN_FLIGHT": "16"})},- )+ health = _fake_proc(monkeypatch, {321: (["python", "-m", "bench.compare_backends"], {"CV3D_MAX_IN_FLIGHT": "16"})})assert health.pool_budget().used == 16@@ -268,15 +230,9 @@ def test_a_sibling_running_unlimited_is_charged_the_whole_knee(monkeypatch):`doctor` prints max_in_flight=off), so the one process with NO ceiling at allwas accounted as holding NOTHING and pool_budget handed the next launcher thefull 64 — straight past the measured knee."""- health = _fake_proc(- monkeypatch,- {- 401: (- ["python", "-m", "codeverse.cli.main", "bench", "run"],- {"CV3D_MAX_IN_FLIGHT": "0"},- ),- },- )+ health = _fake_proc(monkeypatch, {+ 401: (["python", "-m", "codeverse.cli.main", "bench", "run"], {"CV3D_MAX_IN_FLIGHT": "0"}),+ })pb = health.pool_budget()assert (pb.siblings, pb.used, pb.headroom) == (1, 64, 0), str(pb)assert not pb.fits(1)@@ -285,16 +241,10 @@ def test_a_sibling_running_unlimited_is_charged_the_whole_knee(monkeypatch):def test_a_negative_cap_does_not_grow_the_headroom(monkeypatch):"""A negative cap used to be SUBTRACTED from `used`, so a sibling made themachine look emptier than with no sibling at all."""- health = _fake_proc(- monkeypatch,- {- 501: (- ["python", "-m", "codeverse.cli.main", "bench", "run"],- {"CV3D_MAX_IN_FLIGHT": "16"},- ),- 502: (["python", "-m", "bench.compare_backends"], {"CV3D_MAX_IN_FLIGHT": "-8"}),- },- )+ health = _fake_proc(monkeypatch, {+ 501: (["python", "-m", "codeverse.cli.main", "bench", "run"], {"CV3D_MAX_IN_FLIGHT": "16"}),+ 502: (["python", "-m", "bench.compare_backends"], {"CV3D_MAX_IN_FLIGHT": "-8"}),+ })pb = health.pool_budget()assert pb.used == 16 + health.POOL_KNEE and pb.headroom == 0, str(pb)diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.pyindex c200daa7..5f4892f0 100644--- a/harness/tests/models/test_retry.py+++ b/harness/tests/models/test_retry.py@@ -1,4 +1,4 @@-"""with_retries / backoff_delay."""+"""with_retries / backoff_delay / rotate_with_retries."""from __future__ import annotations@@ -8,7 +8,23 @@ import timeimport pytest-from codeverse.models.retry import backoff_delay, with_retries+from codeverse.contracts.common import Usage+from codeverse.models.base import ModelError+from codeverse.models.gemini import HTTP_TIMEOUT_FLOOR_S+from codeverse.models.keypool import (+ ACQUIRE_TIMEOUT_S,+ MAX_WAIT_S,+ KeyPool,+ KeyPoolExhausted,+ Outcome,+)+from codeverse.models.retry import (+ RETRY_DEADLINE_S,+ backoff_delay,+ rotate_with_retries,+ with_retries,+)+from codeverse.models.storm import StormGatedef test_backoff_grows_and_caps():@@ -66,12 +82,6 @@ def test_exhausted_raises_last():# --------------------------------------------------------------------------- rotate_with_retries-from codeverse.models.base import ModelError # noqa: E402-from codeverse.models.keypool import KeyPool, KeyPoolExhausted, Outcome # noqa: E402-from codeverse.models.retry import rotate_with_retries # noqa: E402-from codeverse.models.storm import StormGate # noqa: E402--def _classify(exc: BaseException) -> ModelError:if isinstance(exc, ModelError):return exc@@ -90,6 +100,17 @@ def _outcome(err: ModelError) -> Outcome:return "error" if err.status else "ok"+def _503(e: BaseException) -> ModelError:+ """Read every exception as a retryable 503 — the storm/hedge tests' classifier."""+ return ModelError(str(e), retryable=True, status=503)+++def _pool(n: int = 3, **kw) -> KeyPool:+ """A pool of ``n`` keys with the per-key RPM limiter effectively off."""+ kw.setdefault("rpm_per_key", 10_000)+ return KeyPool([f"k{i}" for i in range(1, n + 1)], **kw)++def _rotate(pool, call, **kw):kw.setdefault("classify", _classify)kw.setdefault("outcome_of", _outcome)@@ -97,6 +118,36 @@ def _rotate(pool, call, **kw):return rotate_with_retries(pool, call, **kw)+def _rotate503(pool, call, **kw):+ """``_rotate`` under the 503 classifier + ``"5xx"`` outcome every storm test wants."""+ kw.setdefault("outcome_of", lambda e: "5xx")+ return _rotate(pool, call, classify=_503, **kw)+++class Clock:+ """Fake monotonic clock: pass it as ``monotonic``, its ``sleep`` records the nap and+ advances it, and a test may advance ``.t`` itself to simulate time inside a call."""++ def __init__(self, t: float = 0.0) -> None:+ self.t = t+ self.naps: list[float] = []++ def __call__(self) -> float:+ return self.t++ def sleep(self, d: float) -> None:+ self.naps.append(d)+ self.t += d+++def _boom(msg: str = "503 high demand"):+ """A ``call`` that always raises ``msg``."""+ def call(_key):+ raise RuntimeError(msg)++ return call++def test_rotate_success_reports_ok_with_tokens():pool = KeyPool(["k1", "k2"])out = _rotate(pool, lambda key: f"ok:{key}", tokens_of=lambda r: 42)@@ -199,8 +250,8 @@ def test_rotate_nonretryable_raises_immediately():def test_rotate_retry_after_hint_reaches_the_pool():- clock = {"t": 0.0}- pool = KeyPool(["k1", "k2"], cooldown_s=30, clock=lambda: clock["t"], sleep=lambda s: clock.__setitem__("t", clock["t"] + s))+ clock = Clock()+ pool = KeyPool(["k1", "k2"], cooldown_s=30, clock=clock, sleep=clock.sleep)seen: list[BaseException] = []def call(key: str) -> str:@@ -214,19 +265,14 @@ def test_rotate_retry_after_hint_reaches_the_pool():assert 0 < cooling["…k1"] <= 7.0+# --------------------------------------------------------------------------- 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):- """A model-wide 503 storm must not burn the normal attempt budget.-- hedge=1: eight sequential 503s then ok — seven storm waits, more than max_attempts=3- could survive. hedge=2 (the default, audit 2026-08-26 §5.2): from the second 503 on- every attempt races both keys, so the same eight failures are waited out in FOUR storm- waits, and the winning attempt's sibling may land too (a tenth call, discarded)."""- from codeverse.models.base import ModelError- from codeverse.models.keypool import KeyPool- from codeverse.models.retry import rotate_with_retries-- pool = KeyPool(["k1", "k2"], rpm_per_key=10_000)+ """A model-wide 503 storm must not burn the normal attempt budget. hedge=1: eight+ sequential 503s then ok — seven storm waits, more than max_attempts=3 could survive.+ hedge=2 (the default, audit 2026-08-26 §5.2) races both keys from the second 503 on, so+ the same eight failures cost FOUR waits and the winner's sibling may land (a 10th call,+ discarded)."""lock = threading.Lock()calls = {"n": 0}naps: list[float] = []@@ -239,14 +285,8 @@ def test_503_storm_has_its_own_patience_budget(hedge, want_calls, want_naps):raise RuntimeError("503 storm")return "ok"- def classify(exc):- return ModelError(str(exc), retryable=True, status=503)-- out = rotate_with_retries(- pool, call, classify=classify, outcome_of=lambda e: "5xx",- max_attempts=3, base_delay=0.01, storm_attempts=10, storm_max_delay=0.05,- sleep=naps.append, hedge=hedge,- )+ out = _rotate503(_pool(2), call, max_attempts=3, base_delay=0.01, storm_attempts=10,+ storm_max_delay=0.05, sleep=naps.append, hedge=hedge)assert out == "ok" and calls["n"] in want_calls# the first 503 rotates to k2 for free (no nap); k2's 503 leaves no untried key in the# 2-key pool, so that one is the storm@@ -254,57 +294,32 @@ def test_503_storm_has_its_own_patience_budget(hedge, want_calls, want_naps):def test_storm_waits_never_exceed_the_house_limit_at_production_defaults():- """Jitter must be applied BEFORE the cap. Regression: the storm branch capped- first and then multiplied by up to 1.25, so a documented "<=5 s" wait was- observed at 6 s in a live bench run (2026-08-24)."""- from codeverse.models.base import ModelError- from codeverse.models.keypool import MAX_WAIT_S, KeyPool- from codeverse.models.retry import rotate_with_retries-+ """Jitter must be applied BEFORE the cap. Regression: the storm branch capped first and+ then multiplied by up to 1.25, so a documented "<=5 s" wait was observed at 6 s in a live+ bench run (2026-08-24). 50 seeds, so this is not one lucky jitter draw."""naps: list[float] = []- for seed in range(50): # exercise many jitter draws, not one lucky one+ for seed in range(50):random.seed(seed)- pool = KeyPool(["k1", "k2"], rpm_per_key=10_000)with pytest.raises(ModelError):- rotate_with_retries(- pool,- lambda key: (_ for _ in ()).throw(RuntimeError("503 high demand")),- classify=lambda e: ModelError(str(e), retryable=True, status=503),- outcome_of=lambda e: "5xx",- max_attempts=2,- storm_attempts=12, # deep enough that the exponent saturates the cap- sleep=naps.append,- )+ # storm_attempts deep enough that the exponent saturates the cap+ _rotate503(_pool(2), _boom(), max_attempts=2, storm_attempts=12, sleep=naps.append)assert naps, "expected the storm path to sleep"assert max(naps) <= MAX_WAIT_S, f"a storm wait exceeded {MAX_WAIT_S}s: {max(naps)}"assert max(naps) > MAX_WAIT_S * 0.9, "the cap should still be reached, not just respected"def test_503_storm_budget_exhausts_then_normal_budget_applies():- from codeverse.models.base import ModelError- from codeverse.models.keypool import KeyPool- from codeverse.models.retry import rotate_with_retries-- pool = KeyPool(["k1"], rpm_per_key=10_000)-- def call(key):- raise RuntimeError("503 forever")-+ """The storm patience is finite: once ``storm_attempts`` is spent the normal budget+ applies again and the call gives up instead of looping forever."""with pytest.raises(ModelError):- rotate_with_retries(- pool, call, classify=lambda e: ModelError(str(e), retryable=True, status=503),- outcome_of=lambda e: "5xx", max_attempts=2, base_delay=0.0,- storm_attempts=3, storm_max_delay=0.0, sleep=lambda d: None,- )+ _rotate503(_pool(1), _boom("503 forever"), max_attempts=2, base_delay=0.0,+ storm_attempts=3, storm_max_delay=0.0)def test_live_tests_are_opt_in_by_default():- """A bare `pytest` must never fire real API calls.-- On 2026-08-24 a plain run on a keyed machine hung for the whole timeout because- the live suite was selected by default and the provider was in a capacity storm.- """- import tomllib # 3.10 floor: stdlib tomllib is 3.11++ """A bare `pytest` must never fire real API calls: on 2026-08-24 a plain run on a keyed+ machine hung for the whole timeout because the live suite was selected by default."""+ import tomllibfrom pathlib import Pathroot = Path(__file__).resolve().parents[2]@@ -315,94 +330,56 @@ def test_live_tests_are_opt_in_by_default():def test_one_call_cannot_retry_for_hours():- """The storm branch was bounded in ATTEMPTS, not in time.-- 60 storm attempts x (a 300 s read timeout + a <=5 s wait) is 5.1 hours for ONE- logical call, while the docstring claimed "~5 min". Measured 2026-08-24: combined- with a wall-clock ceiling that is only checked when a call is BILLED (a stalled- call bills nothing), a run with --max-minutes 90 reached 200 minutes.-- Since 2026-08-27 the deadline is threaded through every branch of the loop and- ``GeminiModel`` clips each attempt's HTTP read timeout to the remaining budget,- floored at ``HTTP_TIMEOUT_FLOOR_S`` (simulated by ``call`` below) — so ONE call- may overshoot by at most one floored in-flight attempt, never by a full 300 s- socket.- """- from codeverse.models.base import ModelError- from codeverse.models.gemini import HTTP_TIMEOUT_FLOOR_S- from codeverse.models.keypool import KeyPool- from codeverse.models.retry import RETRY_DEADLINE_S, rotate_with_retries-- clock = {"t": 0.0}- naps: list[float] = []-- def sleep(d): # every wait advances the fake clock- naps.append(d)- clock["t"] += d+ """The storm branch was bounded in ATTEMPTS, not in time: 60 storm attempts x (a 300 s+ read timeout + a <=5 s wait) is 5.1 hours for ONE logical call while the docstring+ claimed "~5 min" — and the wall-clock ceiling is only checked when a call is BILLED, so+ (measured 2026-08-24) a run with --max-minutes 90 reached 200 minutes. The deadline is+ now threaded through every branch and ``GeminiModel`` clips each attempt's HTTP read+ timeout to the remaining budget, floored at ``HTTP_TIMEOUT_FLOOR_S`` (simulated below)."""+ clock = Clock()def call(_key):- # the budget-clipped read timeout each doomed attempt burns- # (gemini.py _attempt_config: min(300 s, remaining), floored at 20 s)- remaining = RETRY_DEADLINE_S - clock["t"]- clock["t"] += min(300.0, max(HTTP_TIMEOUT_FLOOR_S, remaining))+ # gemini.py _attempt_config: min(300 s, remaining), floored at HTTP_TIMEOUT_FLOOR_S+ clock.t += min(300.0, max(HTTP_TIMEOUT_FLOOR_S, RETRY_DEADLINE_S - clock.t))raise RuntimeError("503 high demand")with pytest.raises(ModelError):- rotate_with_retries(- KeyPool(["k1", "k2"], rpm_per_key=10_000), call,- classify=lambda e: ModelError(str(e), retryable=True, status=503),- outcome_of=lambda e: "5xx", max_attempts=6, storm_attempts=60,- sleep=sleep, monotonic=lambda: clock["t"],- hedge=1, # the fake clock is serial; two hedged 300 s calls would add 600 s, not 300- )- # the whole point: bounded by the clock — the ONLY legal overshoot is the one- # floored attempt that was already in flight when the deadline passed- assert clock["t"] <= RETRY_DEADLINE_S + HTTP_TIMEOUT_FLOOR_S, (- f"one call burned {clock['t'] / 3600:.2f} h; the deadline is {RETRY_DEADLINE_S / 60:.0f} min")- assert clock["t"] < 5 * 3600, "this is the 5.1-hour regression"+ # hedge=1: the fake clock is serial, so two hedged 300 s calls would add 600 s+ _rotate503(_pool(2), call, max_attempts=6, storm_attempts=60, sleep=clock.sleep,+ monotonic=clock, hedge=1)+ # bounded by the clock: the ONLY legal overshoot is the one floored attempt that was+ # already in flight when the deadline passed+ assert clock.t <= RETRY_DEADLINE_S + HTTP_TIMEOUT_FLOOR_S, (+ f"one call burned {clock.t / 3600:.2f} h; the deadline is {RETRY_DEADLINE_S / 60:.0f} min")+ assert clock.t < 5 * 3600, "this is the 5.1-hour regression"def test_the_deadline_does_not_cut_a_call_that_is_making_progress():"""A slow-but-succeeding call must not be killed by the retry deadline."""- from codeverse.models.base import ModelError- from codeverse.models.keypool import KeyPool- from codeverse.models.retry import rotate_with_retries-- clock = {"t": 0.0}+ clock = Clock()calls = {"n": 0}def call(_key):calls["n"] += 1- clock["t"] += 280.0 # slow, but under the per-attempt timeout+ clock.t += 280.0 # slow, but under the per-attempt timeoutif calls["n"] < 3:raise RuntimeError("503 high demand")return "ok"- out = rotate_with_retries(- KeyPool(["k1", "k2"], rpm_per_key=10_000), call,- classify=lambda e: ModelError(str(e), retryable=True, status=503),- outcome_of=lambda e: "5xx", max_attempts=6, storm_attempts=60,- sleep=lambda d: clock.__setitem__("t", clock["t"] + d),- monotonic=lambda: clock["t"],- hedge=1, # serial fake clock and call counter (see the hedge tests for the raced form)- )+ # hedge=1: serial fake clock and call counter (see the hedge tests for the raced form)+ out = _rotate503(_pool(2), call, max_attempts=6, storm_attempts=60, sleep=clock.sleep,+ monotonic=clock, hedge=1)assert out == "ok" and calls["n"] == 3def test_503_rotates_through_every_untried_key_before_it_is_a_storm():- """Owner's rule (2026-08-27): a 503 on one key is simply replaced by the next key —- exactly like the 429 path, free while an untried key remains. Measured 2026-08-26:- one tiny request per key in parallel during the day's storm — flash answered on- 15/22, 18/22, 21/22 keys while only 5/4/1 keys said 503 at the same instant. So with- a 10-key pool, NINE consecutive 503s on distinct keys still rotate: no sleep, no- storm, no ``max_attempts`` spent (``max_attempts=3`` here proves the budget is free)."""- from codeverse.models.base import ModelError- from codeverse.models.keypool import KeyPool- from codeverse.models.retry import rotate_with_retries- from codeverse.models.storm import StormGate-+ """Owner's rule (2026-08-27): a 503 on one key is simply replaced by the next key — free+ while an untried key remains, exactly like the 429 path. Measured 2026-08-26, one tiny+ request per key in parallel during the day's storm: flash answered on 15/22, 18/22, 21/22+ keys while only 5/4/1 keys said 503 at the same instant. So with a 10-key pool NINE+ consecutive 503s still rotate: no sleep, no storm, no ``max_attempts`` spent+ (``max_attempts=3`` here proves the budget is free)."""keys = [f"k{i}" for i in range(1, 11)]- pool = KeyPool(keys, rpm_per_key=10_000)gate = StormGate()lock = threading.Lock()calls: list[str] = []@@ -416,33 +393,28 @@ def test_503_rotates_through_every_untried_key_before_it_is_a_storm():raise RuntimeError("503 high demand")return "ok"- out = rotate_with_retries(pool, call, classify=lambda e: ModelError(str(e), retryable=True, status=503),- outcome_of=lambda e: "5xx", max_attempts=3, storm_attempts=10, storm_max_delay=0.05,- sleep=naps.append, storm_gate=gate)+ out = _rotate503(_pool(10), call, max_attempts=3, storm_attempts=10, storm_max_delay=0.05,+ sleep=naps.append, storm_gate=gate)# one key per round-trip, never twice: 9 free rotations, then the 10th key landsassert out == "ok" and len(calls) == len(keys) and set(calls) == set(keys)assert naps == [], "rotation to a fresh key costs no sleep"assert gate.n_storms == 0 and not gate.storming, "an untried key remains: not a storm"[email protected](("hedge", "want_calls", "want_hits"), [(1, {6}, 3), (2, {6, 7}, 2)])-def test_503_on_every_key_is_still_a_storm(hedge, want_calls, want_hits):- """The backstop: once EVERY key in the pool has 503'd inside this one call there is- no untried key left to rotate to, so the bounded storm wait engages.- hedge=1: k1, k2, k3 fail one by one (the whole pool), then two storm waits, then ok.- hedge=2: k1 fails alone, k2+k3 fail together (pool exhausted: storm 1), two more fail- together (storm 2), then the raced pair lands — one storm wait per hedged attempt,- not per key."""- from codeverse.models.base import ModelError- from codeverse.models.keypool import KeyPool- from codeverse.models.retry import rotate_with_retries- from codeverse.models.storm import StormGate-- pool = KeyPool(["k1", "k2", "k3"], rpm_per_key=10_000)[email protected](("hedge", "want_calls", "want_hits", "want_stats"), [+ (1, {6}, 3, {"attempts": 6, "hedged": 0, "storm": 3}),+ (2, {6, 7}, 2, {"attempts": 7, "hedged": 3, "storm": 2}),+])+def test_503_on_every_key_is_still_a_storm(hedge, want_calls, want_hits, want_stats):+ """The backstop: once EVERY key in the pool has 503'd inside this one call there is no+ untried key left to rotate to, so the bounded storm wait engages — one wait per hedged+ ATTEMPT, not per key. hedge=1: k1, k2, k3 fail one by one (the whole pool), then two+ storm waits, then ok. hedge=2: k1 fails alone, k2+k3 fail together (pool exhausted:+ storm 1), two more together (storm 2), then the raced pair lands."""gate = StormGate("t", base_delay=0.0, max_wait_s=0.0, probe_lease_s=0.0) # no real waitslock = threading.Lock()n = {"c": 0}- naps: list[float] = []+ stats: dict = {}def call(key):with lock:@@ -452,11 +424,11 @@ def test_503_on_every_key_is_still_a_storm(hedge, want_calls, want_hits):raise RuntimeError("503 high demand")return "ok"- out = rotate_with_retries(pool, call, classify=lambda e: ModelError(str(e), retryable=True, status=503),- outcome_of=lambda e: "5xx", max_attempts=3, storm_attempts=10, storm_max_delay=0.05,- sleep=naps.append, storm_gate=gate, hedge=hedge)+ out = _rotate503(_pool(3), call, max_attempts=3, storm_attempts=10, storm_max_delay=0.05,+ storm_gate=gate, hedge=hedge, stats=stats)assert out == "ok" and n["c"] in want_calls- assert gate.n_storms == 1 and gate.n_hits == want_hits, "the storm is declared only after all three keys failed, then waited out"+ assert gate.n_storms == 1 and gate.n_hits == want_hits, "declared only after all three keys failed, then waited out"+ assert stats == want_stats# --------------------------------------------------------------------------- hedging (audit 2026-08-26 §5.2)@@ -468,10 +440,6 @@ def _wait_idle(pool, timeout: float = 5.0) -> None:assert pool.stats()["in_flight"] == 0-def _503(e):- return ModelError(str(e), retryable=True, status=503)--def test_after_the_first_503_the_next_attempt_is_hedged_and_the_first_success_wins():"""Measured 2026-08-26: a failed 503 costs the 21-50 s round-trip the provider holdsbefore rejecting, not the <= 5 s sleep (logged sleep was 13 % of the wait), and storm@@ -533,30 +501,6 @@ def test_a_loser_that_succeeds_later_is_discarded_but_its_tokens_are_reported():assert pool._by_key["k2"].tokens_used == 900 and pool._by_key["k3"].tokens_used == 100 # noqa: SLF001-def test_a_hedged_attempt_that_fails_on_every_key_is_one_storm_attempt():- pool = KeyPool(["k1", "k2", "k3"], rpm_per_key=10_000)- gate = StormGate("t", base_delay=0.0, max_wait_s=0.0, probe_lease_s=0.0) # no real waits- 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 = rotate_with_retries(pool, call, classify=_503, outcome_of=lambda e: "5xx", max_attempts=3,- storm_attempts=10, storm_max_delay=0.05, sleep=lambda d: None, storm_gate=gate,- stats=stats)- assert out == "ok"- # k1 alone; k2+k3 (all 3 keys 503'd → storm 1); two more (storm 2); the raced pair lands- assert stats == {"attempts": 7, "hedged": 3, "storm": 2}- assert gate.n_hits == 2, "two hedged failures = two storm waits, not four"--def test_hedge_1_disables_and_a_full_pool_of_slots_degrades_to_one_key():lock = threading.Lock()@@ -573,16 +517,16 @@ def test_hedge_1_disables_and_a_full_pool_of_slots_degrades_to_one_key():return callstats: dict = {}- _rotate(KeyPool(["k1", "k2", "k3"], rpm_per_key=10_000), make_call(), max_attempts=3, storm_attempts=10,+ _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 = KeyPool(["k1", "k2", "k3"], rpm_per_key=10_000, max_in_flight=1)+ pool = _pool(3, max_in_flight=1)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 = KeyPool(["k1", "k2", "k3"], rpm_per_key=10_000, max_in_flight=2)+ pool = _pool(3, max_in_flight=2)stats = {}_rotate(pool, make_call(), max_attempts=3, storm_attempts=10, storm_max_delay=0.0, stats=stats)_wait_idle(pool)@@ -592,7 +536,7 @@ def test_hedge_1_disables_and_a_full_pool_of_slots_degrades_to_one_key():def test_the_worst_error_decides_a_hedged_attempt():"""One key says 503 and the other says the request itself is bad: raise the 400 at onceinstead of storming on a request that can never succeed."""- pool = KeyPool(["k1", "k2", "k3"], rpm_per_key=10_000)+ pool = _pool(3)stats: dict = {}def call(key):@@ -606,7 +550,7 @@ def test_the_worst_error_decides_a_hedged_attempt():def test_a_dead_key_among_the_hedge_is_benched_once_the_sibling_wins():- pool = KeyPool(["k1", "k2", "k3"], rpm_per_key=10_000)+ pool = _pool(3)def call(key):if key == "k1":@@ -618,12 +562,12 @@ def test_a_dead_key_among_the_hedge_is_benched_once_the_sibling_wins():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.acquire used to be called with its own 120 s default no matter how littlebudget the call had left; now it gets min(ACQUIRE_TIMEOUT_S, remaining)."""- from codeverse.models.keypool import ACQUIRE_TIMEOUT_S-seen: list[float | None] = []class SpyPool(KeyPool):@@ -640,49 +584,29 @@ def test_the_key_wait_is_clipped_to_the_remaining_budget():def test_a_storm_wait_is_clipped_to_the_remaining_budget():"""Sleeping past the deadline only to give up on waking helps nobody."""- clock = {"t": 0.0}- naps: list[float] = []-- def sleep(d):- naps.append(d)- clock["t"] += d-+ clock = Clock()with pytest.raises(ModelError):- rotate_with_retries(- KeyPool(["k1"], rpm_per_key=10_000),- lambda key: (_ for _ in ()).throw(RuntimeError("503 high demand")),- classify=lambda e: ModelError(str(e), retryable=True, status=503),- outcome_of=lambda e: "5xx", max_attempts=6, storm_attempts=60,- base_delay=4.0, storm_max_delay=5.0, max_total_s=3.0,- sleep=sleep, monotonic=lambda: clock["t"], hedge=1,- )- assert naps, "expected the storm path to sleep"- assert clock["t"] <= 3.0 + 1e-6, f"slept past the deadline: {clock['t']}"+ _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 rotation costs no attempts but DOES cost wall clock (0.5 s per hop):with many keys it used to spin long past the budget."""- clock = {"t": 0.0}- keys = [f"k{i}" for i in range(1, 11)]- pool = KeyPool(keys, rpm_per_key=10_000, cooldown_s=0.0,- clock=lambda: clock["t"], sleep=lambda s: clock.__setitem__("t", clock["t"] + s))+ clock = Clock()+ pool = _pool(10, cooldown_s=0.0, clock=clock, sleep=clock.sleep)calls: list[str] = []def call(key):calls.append(key)raise ModelError("quota", retryable=True, status=429)- def sleep(d):- clock["t"] += d-with pytest.raises(ModelError) as ei:- rotate_with_retries(- pool, call, classify=_classify, outcome_of=_outcome, max_attempts=6,- max_total_s=2.0, sleep=sleep, monotonic=lambda: clock["t"],- )+ _rotate(pool, call, max_attempts=6, max_total_s=2.0, sleep=clock.sleep, monotonic=clock)assert ei.value.status == 429- assert clock["t"] <= 2.5, f"free rotation outlived the deadline: {clock['t']}"+ assert clock.t <= 2.5, f"free rotation outlived the deadline: {clock.t}"assert len(calls) <= 5, "ten keys would all have been tried before"@@ -690,11 +614,8 @@ def test_the_pool_is_not_refunded_for_a_charged_but_invalid_reply():"""retry.py used to report tokens=0 for a bad-JSON failure, refunding a TPMreservation the provider had actually consumed — a 42k-token invalid replyhanded the key 42k TPM back. ``ModelError.usage`` now carries the real bill."""- from codeverse.contracts.common import Usage-- clock = {"t": 1000.0}- pool = KeyPool(["k1"], rpm_per_key=10_000, tpm_per_key=100_000,- clock=lambda: clock["t"], sleep=lambda s: clock.__setitem__("t", clock["t"] + s))+ clock = Clock(1000.0)+ pool = _pool(1, tpm_per_key=100_000, clock=clock, sleep=clock.sleep)calls = {"n": 0}def call(key):@@ -716,7 +637,7 @@ def test_on_attempt_hears_every_round_trip_and_a_late_hedge_loser():as discarded, and a hedge loser still in flight reports (discarded — a latesuccess included) when it lands. That is how a loser's paid tokens reach thecost ledger at all."""- pool = KeyPool(["k1", "k2", "k3", "k4"], rpm_per_key=10_000)+ pool = _pool(4)release_k2 = threading.Event()lock = threading.Lock()recs: list[tuple[int, str, str, bool]] = [] # (attempt_no, key, outcome, discarded)@@ -754,7 +675,7 @@ def test_on_attempt_hears_every_round_trip_and_a_late_hedge_loser():def test_a_broken_on_attempt_hook_never_breaks_the_call():- pool = KeyPool(["k1"], rpm_per_key=10_000)+ pool = _pool(1)def hook(t, no, discarded):raise RuntimeError("accounting on fire")@@ -766,12 +687,12 @@ def test_a_budget_spent_at_the_storm_gate_issues_no_round_trip():"""A worker parked at a gate ANOTHER thread closed carries no ``last_err``, so theguard at the top of the loop (which requires one) let it through: it woke past itsdeadline and still spent a full round-trip (measured: 25 s on a 5 s budget)."""- now = {"t": 1000.0}+ clock = Clock(1000.0)calls: list[str] = []class Gate: # parks the caller for longer than the whole budgetdef enter(self, deadline=None):- now["t"] += 30.0+ clock.t += 30.0return 30.0def hit(self, retry_after=None):@@ -781,8 +702,7 @@ def test_a_budget_spent_at_the_storm_gate_issues_no_round_trip():passwith pytest.raises(ModelError) as e:- _rotate(KeyPool(["k1"], rpm_per_key=10_000), lambda key: calls.append(key),- max_total_s=5.0, monotonic=lambda: now["t"], storm_gate=Gate(), label="t")+ _rotate(_pool(1), lambda key: calls.append(key),+ max_total_s=5.0, monotonic=clock, storm_gate=Gate(), label="t")assert calls == [], "a round-trip was issued after the budget was already spent"assert "capacity" in str(e.value)-diff --git a/harness/tests/orchestrator_tracks/test_cost_latency.py b/harness/tests/orchestrator_tracks/test_cost_latency.pyindex 613eeae7..bcf38aa0 100644--- a/harness/tests/orchestrator_tracks/test_cost_latency.py+++ b/harness/tests/orchestrator_tracks/test_cost_latency.py@@ -276,11 +276,17 @@ def _planner(payload):return FakeChatModel(lambda req: payload)-def test_a_budget_stop_before_round_zero_still_delivers_a_judged_round(tmp_path, settings):+def _threejs_scene_plan() -> ScenePlan:+ """The scene example narrowed to its three.js assets — the only kind these fakes build."""plan = ScenePlan.model_validate(plan_example(Track.SCENE))plan.assets = [a for a in plan.assets if a.kind == "threejs"]for z in plan.zones:z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]+ return plan+++def test_a_budget_stop_before_round_zero_still_delivers_a_judged_round(tmp_path, settings):+ plan = _threejs_scene_plan()spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=1, max_usd=5.0)ws = Workspace(tmp_path / "runs" / "greenhouse")services = FakeServices(assemble=True)@@ -311,10 +317,7 @@ def test_a_budget_stop_before_round_zero_still_delivers_a_judged_round(tmp_path,def test_soft_budget_notes_land_in_the_round_record(tmp_path, settings):- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- plan.assets = [a for a in plan.assets if a.kind == "threejs"]- for z in plan.zones:- z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]+ plan = _threejs_scene_plan()spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0, max_usd=5.0)ws = Workspace(tmp_path / "runs" / "degraded")services = FakeServices(assemble=True)@@ -429,10 +432,7 @@ def test_a_scene_round_judged_at_the_ceiling_is_still_promoted(tmp_path, setting"""The batch-2 promotion order must hold for scenes too: the verdict is paid for,recorded and promoted BEFORE the loop notices the budget is gone — and the salvagemust not then run a second round 0 on top of it."""- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- plan.assets = [a for a in plan.assets if a.kind == "threejs"]- for z in plan.zones:- z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]+ plan = _threejs_scene_plan()spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=2, max_usd=0.10)ws = Workspace(tmp_path / "runs" / "ceiling")judge = FakeJudge(scores=(0.61,), cost=0.5) # the single verdict blows max_usd