Skip to content

Official Codebase of 3DCodeVerse

Python

parallel runs: one agy session per key machine-wide, agy's own timeout no longer pre-empts the watchdog, a stop signal kills the run's child trees

gaoypeng09ee33878925
diff --git a/harness/codeverse3d/agents/backends.py b/harness/codeverse3d/agents/backends.py
index bdcaf721..7c499662 100644
--- a/harness/codeverse3d/agents/backends.py
+++ b/harness/codeverse3d/agents/backends.py
@@ -22,6 +22,7 @@ from pathlib import Path
from typing import Any
from codeverse3d.agents.cli_common import (
+ HARD_GRACE_S,
CompletedProc,
Session,
SessionEnd,
@@ -554,6 +555,10 @@ def parse_agy_json(stdout: str) -> dict[str, Any] | None:
return find_json_object(stdout, lambda d: "response" in d or "status" in d)
+#: what agy prints on stderr when its own ``--print-timeout`` stops a turn in progress (1.3.4:
+#: ``[agy] print timeout after 8m0s with turn in progress; returning partial output``) — the
+#: envelope still says ``SUCCESS``, with whatever response there was (usually none)
+AGY_PRINT_TIMEOUT = "print timeout after"
#: the per-session CLI log agy writes into the trajectory dir (``--log-file``)
AGY_LOG = "agy.log"
#: where agy keeps each conversation under its HOME: one SQLite file named by the envelope's
@@ -767,8 +772,11 @@ class AntigravityAgent(_CliAgent):
def build_argv(self, s: Session) -> list[str]:
"""No ``--print``: agy reads the prompt from a piped stdin, byte for byte, and still
answers as print mode (``--print -`` would send the prompt "-"). ``--log-file`` keeps
- its CLI log with the session — the record of the retries it made."""
- minutes = max(1, int(s.job.timeout_s // 60) + 1)
+ its CLI log with the session — the record of the retries it made. ``--print-timeout``
+ sits a minute past the watchdog's hard limit: at ``timeout_s + 1 min`` (as it was) agy
+ cut off every session still working, with ``status: SUCCESS`` and an empty response
+ (live, argon scene sessions, 2026-10-13), before the watchdog's grace began."""
+ minutes = max(1, int((s.job.timeout_s + HARD_GRACE_S) // 60) + 1)
return [self.binary, "--dangerously-skip-permissions",
"--print-timeout", f"{minutes}m", "--output-format", "json",
"--add-dir", str(s.ws.root), "--disable-slash-commands", "--log-file", str(s.traj.dir / AGY_LOG),
@@ -818,13 +826,13 @@ class AntigravityAgent(_CliAgent):
which takes a fresh key, the 429'd one cooling in the pool."""
ok, why = self.available()
s = begin_session(job, self.kind)
- home = None
+ home, lease = None, None
try:
if not ok:
return failed(s, "error", why)
pool = _key_pool()
try:
- key = pool.session_key()
+ key, lease = pool.lease_session_key(get_settings().cache_dir / "slots" / "agy_keys")
except KeyPoolExhausted as e: # every key throttled for the whole wait budget
return failed(s, "budget", f"Gemini key pool exhausted: {e}")
home = self.build_home(s)
@@ -844,7 +852,10 @@ class AntigravityAgent(_CliAgent):
died = agy_error(proc.stderr)
said = (json.dumps(died), str((env or {}).get("error") or ""), proc.stderr)
ok = False
- if proc.timed_out:
+ if AGY_PRINT_TIMEOUT in proc.stderr: # agy's own clock stopped a turn in progress
+ proc = dataclasses.replace(proc, timed_out=True, killed_reason="agy_print_timeout")
+ errors.append(f"agy's own --print-timeout stopped the turn after {proc.duration_s:.0f}s")
+ elif proc.timed_out:
errors.append(watchdog_error(proc))
elif proc.rc != 0 or (env is not None and str(env.get("status", "SUCCESS")).upper() not in ("SUCCESS", "OK")):
errors.append(f"rc={proc.rc}; status={(env or {}).get('status')}; error={(env or {}).get('error', '')}; "
@@ -867,6 +878,7 @@ class AntigravityAgent(_CliAgent):
finally:
if home is not None:
shutil.rmtree(home, ignore_errors=True)
+ KeyPool.end_lease(lease)
release_session(s)
diff --git a/harness/codeverse3d/agents/cli_common.py b/harness/codeverse3d/agents/cli_common.py
index 239b89ae..e3e10295 100644
--- a/harness/codeverse3d/agents/cli_common.py
+++ b/harness/codeverse3d/agents/cli_common.py
@@ -535,6 +535,10 @@ def failed(s: Session, reason: str, message: str, usage: Usage | None = None) ->
#: seconds without output or workspace activity before the watchdog kills a CLI agent;
#: read at call time by :func:`invoke` so a test can monkeypatch it here.
IDLE_GRACE_S = 300.0
+#: how far past its soft timeout a session that is still working may run before the watchdog
+#: kills it whatever it is doing — the hard limit is ``timeout_s + HARD_GRACE_S``. A CLI with
+#: a clock of its own must be set past it (agy ``--print-timeout``), or that clock decides.
+HARD_GRACE_S = 300.0
#: watchdog poll period. A real vendor CLI runs for minutes, so 1 s of latency on
#: noticing it exited is free — but a FAKE cli in a test exits in milliseconds and then
@@ -574,7 +578,7 @@ def invoke(
plus ``invoke_extra`` (agy in API mode adds ``model`` and ``key_tail``).
"""
soft = float(s.job.timeout_s)
- hard = soft + 300.0
+ hard = soft + HARD_GRACE_S
if s.job.hard_deadline_s is not None:
# This runs AFTER begin_session's workspace lock. A queued job must not regain the window it had before waiting for a peer.
hard = min(hard, max(0.0, s.job.hard_deadline_s - time.monotonic()))
diff --git a/harness/codeverse3d/cli/main.py b/harness/codeverse3d/cli/main.py
index 12fdaf6d..2addd844 100644
--- a/harness/codeverse3d/cli/main.py
+++ b/harness/codeverse3d/cli/main.py
@@ -500,8 +500,10 @@ def _no_best_of_n(track: Track) -> C.CliError:
def _run_track(spec: Spec, ws, *, resume: bool, candidates: int | None = None, force: bool = False,
pick: bool = True) -> None:
from codeverse3d.cost.instrument import run_ledger
+ from codeverse3d.proc import install_stop_handlers
from codeverse3d.tracks import get_track
+ install_stop_handlers() # a stop signal kills the run's agent / build trees too
options: dict = {"n_candidates": candidates} if candidates else {}
try:
# already inside the run mutex (make / resume take it); every model call and
diff --git a/harness/codeverse3d/models/gemini.py b/harness/codeverse3d/models/gemini.py
index f56b6bbf..a546af76 100644
--- a/harness/codeverse3d/models/gemini.py
+++ b/harness/codeverse3d/models/gemini.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import io
import logging
+import random
import re
import threading
import time
@@ -220,7 +221,10 @@ def shared_pool(keys: list[str], *, max_in_flight: int | None = None) -> KeyPool
pool = _pools.get(sig)
if pool is None:
slots = get_settings().cache_dir / "slots" / "gemini" if cap else None
- pool = KeyPool(keys, max_in_flight=cap or 0, slots_dir=slots)
+ # a random first key: every process makes the same calls in the same order, so
+ # parallel runs starting at key 0 all put their planner calls and agy sessions
+ # on the same few keys (live, 2026-10-13: 4 parallel runs, one planner key)
+ pool = KeyPool(keys, max_in_flight=cap or 0, slots_dir=slots, start=random.randrange(len(keys)))
_pools[sig] = pool
return pool
diff --git a/harness/codeverse3d/models/retry.py b/harness/codeverse3d/models/retry.py
index b3309257..17deda8d 100644
--- a/harness/codeverse3d/models/retry.py
+++ b/harness/codeverse3d/models/retry.py
@@ -36,6 +36,7 @@ Thread-safe; ``clock`` / ``sleep`` are injectable for deterministic tests.
from __future__ import annotations
import fcntl
+import hashlib
import logging
import os
import random
@@ -232,7 +233,9 @@ class KeyPool:
min_health: float = 0.3,
clock: Callable[[], float] = time.monotonic,
sleep: Callable[[float], None] = time.sleep,
+ start: int = 0,
) -> None:
+ """``start``: the key the round-robin begins at (``shared_pool`` draws it at random)."""
uniq = [k for i, k in enumerate(keys) if k and k not in keys[:i]]
if not uniq:
raise ValueError("KeyPool needs at least one non-empty key")
@@ -242,7 +245,7 @@ class KeyPool:
self._dead_cooldown_s = float(dead_cooldown_s)
self._min_health = min_health
self._lock = threading.Lock()
- self._rr = 0
+ self._rr = start % len(uniq)
self._in_flight = 0
self._peak_in_flight = 0
# Machine-wide ceiling on concurrent model calls, independent of the caller's
@@ -332,6 +335,42 @@ class KeyPool:
on the box (docs/COST.md §23)."""
return self._acquire_key(exclude, timeout_s)
+ def lease_session_key(self, leases: Path | str, *, timeout_s: float | None = ACQUIRE_TIMEOUT_S) -> tuple[str, int | None]:
+ """:meth:`session_key`, one live session per key MACHINE-wide while there are keys enough.
+
+ A key's per-minute quota is what a long CLI session runs out of (live, 2026-10-13: one
+ agy session, 11 M prompt tokens in 18 min, 429'd), and every parallel ``3dcode make``
+ is its own process with its own pool — so a session holds ``fcntl.flock`` on
+ ``<leases>/<key hash>.lock`` for its length, and the next one, in any process, skips a
+ key that is held. Only when every ready key is in a session is one shared (lease
+ ``None``). Returns ``(key, lease)``; close the lease with :meth:`end_lease`. The kernel
+ drops a dead holder's lock, so a killed run never strands a key (as :class:`Slots`)."""
+ root = Path(leases)
+ root.mkdir(parents=True, exist_ok=True)
+ busy: set[str] = set()
+ while True:
+ try:
+ key = self._acquire_key(busy, 0.0 if busy else timeout_s)
+ except KeyPoolExhausted:
+ if not busy:
+ raise
+ return self._acquire_key(None, timeout_s), None # every ready key is in a session
+ fd = os.open(root / f"{hashlib.sha256(key.encode()).hexdigest()[:16]}.lock", os.O_RDWR | os.O_CREAT, 0o666)
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ os.close(fd)
+ busy.add(key)
+ with self._lock:
+ self._by_key[key].n_acquired -= 1 # passed over, not handed out
+ continue
+ return key, fd
+
+ @staticmethod
+ def end_lease(lease: int | None) -> None:
+ if lease is not None:
+ os.close(lease)
+
def _hold(self, slot: int | None) -> None:
with self._lock:
self._in_flight += 1
diff --git a/harness/codeverse3d/proc.py b/harness/codeverse3d/proc.py
index 13e33b78..1dd7ffb6 100644
--- a/harness/codeverse3d/proc.py
+++ b/harness/codeverse3d/proc.py
@@ -210,16 +210,22 @@ class ManagedProcess:
self._stop = threading.Event() # tells an abandoned pump to quit feeding
self._abandoned = "" # the truncation note to append, once we know which one
self._sinks = {"stdout": _BoundedSink(stream_budget), "stderr": _BoundedSink(stream_budget)}
- self.proc: subprocess.Popen[bytes] = subprocess.Popen(
- list(cmd),
- cwd=str(cwd),
- env=dict(env) if env is not None else None,
- stdin=subprocess.PIPE if stdin_text is not None else subprocess.DEVNULL,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- start_new_session=True,
- preexec_fn=preexec_fn,
- )
+ # started and registered under the guard: a stop between the two can neither miss
+ # this group nor let a worker start a new one once the stop has begun
+ with _LIVE_GUARD:
+ if _STOPPING.is_set():
+ raise ProcessStopping(f"not starting {cmd[0]!r}: this process is stopping")
+ self.proc: subprocess.Popen[bytes] = subprocess.Popen(
+ list(cmd),
+ cwd=str(cwd),
+ env=dict(env) if env is not None else None,
+ stdin=subprocess.PIPE if stdin_text is not None else subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ start_new_session=True,
+ preexec_fn=preexec_fn,
+ )
+ _LIVE.add(self)
assert self.proc.stdout is not None and self.proc.stderr is not None
self._pumps = [
threading.Thread(target=self._pump, args=(self.proc.stdout, "stdout"), daemon=True),
@@ -329,10 +335,14 @@ class ManagedProcess:
# orphaned blender/node/chrome tree. Never swallows exc. LEADER liveness is the
# wrong question — one that exits 0 leaves its same-group grandchildren running;
# reap it (a zombie still counts as a member), then ask if the GROUP exists.
- self.proc.poll()
- if _group_alive(self.proc.pid):
- self.terminate()
- self._drain_and_reap()
+ try:
+ self.proc.poll()
+ if _group_alive(self.proc.pid):
+ self.terminate()
+ self._drain_and_reap()
+ finally:
+ with _LIVE_GUARD:
+ _LIVE.discard(self)
def _drain_and_reap(self) -> None:
deadline = time.monotonic() + DRAIN_TIMEOUT_S # module global on purpose: tests dial it down
@@ -347,6 +357,57 @@ class ManagedProcess:
self._abandoned = _STILL_HELD if _group_alive(self.proc.pid) else _ABANDONED
+#: every :class:`ManagedProcess` whose group may still be alive, in THIS process — what a stop
+#: signal kills. A run's agent sessions and builds run in worker threads, and a signal is
+#: delivered to the main thread only: ``__exit__`` never ran for them, so SIGTERM (and Ctrl-C,
+#: while the main thread waited on the pool) left agy / blender / chrome trees running and
+#: billing (live, 2026-10-13: a SIGTERM'd ``3dcode make`` orphaned its agy session).
+_LIVE: set[ManagedProcess] = set()
+_LIVE_GUARD = threading.Lock()
+#: set once a stop began: no new child is started after it (a worker thread whose session was
+#: just killed would otherwise go on to its retry or its next build)
+_STOPPING = threading.Event()
+#: how long a stopping process may take to unwind before it is ended outright. Exit joins the
+#: worker threads, and one inside a model call can hold it for that call's whole timeout (20 min)
+STOP_GRACE_S = 30.0
+
+
+class ProcessStopping(RuntimeError):
+ """A child was asked for after this process began to stop."""
+
+
+def kill_live_children() -> int:
+ """Refuse new children from now on and SIGKILL every live child group; how many there were."""
+ with _LIVE_GUARD:
+ _STOPPING.set()
+ live = list(_LIVE)
+ for mp in live:
+ mp.kill()
+ return len(live)
+
+
+def install_stop_handlers() -> None:
+ """SIGTERM and SIGINT kill every live child group and refuse new ones, then end the process
+ as they would (``KeyboardInterrupt`` / exit 143) so the run records its stop — and, should
+ the unwinding outlast :data:`STOP_GRACE_S` (exit waits on worker threads), end it outright
+ with the same status. Main thread only — a no-op elsewhere."""
+ if threading.current_thread() is not threading.main_thread():
+ return
+
+ def stop(signum: int, _frame: object) -> None:
+ kill_live_children()
+ status = 130 if signum == signal.SIGINT else 128 + signum
+ backstop = threading.Timer(STOP_GRACE_S, os._exit, args=(status,))
+ backstop.daemon = True
+ backstop.start()
+ if signum == signal.SIGINT:
+ raise KeyboardInterrupt
+ raise SystemExit(status)
+
+ for sig in (signal.SIGTERM, signal.SIGINT):
+ signal.signal(sig, stop)
+
+
# ------------------------------------------------------------------ env scrubbing
#: The ONE owner of the credential patterns: ``agents/cli_common.clean_env`` (the vendor CLIs'
#: env) calls :func:`scrub_secrets` too.
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 84667684..37744046 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -74,6 +74,8 @@ KeyPool(keys, *, max_in_flight=0, slots_dir=None, cooldown_s=3, dead_cooldown_s=
pool.acquire(*, exclude=None, timeout_s=120) -> key # a slot + a key; raises immediately when every key is dead/cooling past the deadline
pool.try_acquire(*, exclude=None) -> key | None # never waits (a hedged retry's extra key); holds a slot like acquire
pool.session_key(*, exclude=None, timeout_s=120) -> key # a vendor CLI session's key: no slot, nothing to release
+pool.lease_session_key(leases_dir, *, timeout_s=120) -> (key, lease|None) # + one live session per key machine-wide (flock); KeyPool.end_lease(lease)
+KeyPool(keys, ..., start=0) # shared_pool passes a random start: parallel processes spread
pool.report(key, "ok"|"429"|"5xx"|"error"|"dead"|"skip", *, retry_after_s=None) # Δ "dead": health 0, benched dead_cooldown_s,
# re-probed after; "skip" (a content failure the key did not cause) leaves health and counters untouched
from codeverse3d.models.retry import rotate_with_retries, RETRY_DEADLINE_S
@@ -230,7 +232,8 @@ same label+round lands in `<label>.a2_rNN` (then `.a3` …) — the first attemp
`result.json` records `attempt` + `job_label`. Each session makes two git commits (`pre:`/`agent:<label>`).
agy specifics (**Δ D103**, which deleted the gemini-cli backend): Gemini-API mode only — no keys →
`available()` false; a bare `agy` runs `DEFAULT_AGY_MODEL` = `gemini-4-argon`. One key per session from THE shared pool
-(`models.gemini.shared_pool`, `pool.session_key()`, no in-flight slot), outcome reported back
+(`models.gemini.shared_pool`, `pool.lease_session_key(<cache_dir>/slots/agy_keys)`, no in-flight slot, one
+live session per key machine-wide while keys last), outcome reported back
(`_pool_outcome`: 401/403/API_KEY_INVALID → dead, 429 → cooldown, 5xx, ok, skip); a fresh HOME under
`<cache_dir>/agy_homes/` holds `.gemini/antigravity-cli/settings.json` = `{"modelProvider": "gemini"}` (without
it agy ignores `GEMINI_API_KEY` and asks for a login) + the MCP config, and is deleted after the session (the
diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.md
index 02b6dbab..9489a08e 100644
--- a/harness/docs/RUNBOOK.md
+++ b/harness/docs/RUNBOOK.md
@@ -75,7 +75,9 @@ round, then ≈ $0.36 / ~7 min per refine (give scenes `--max-minutes 60`).
* API mode only (owner, 2026-10-13: no subscription sign-in, no Claude models; no keys →
`available()` is false and the session fails at once). `agy` with no model = `gemini-4-argon`
(`DEFAULT_AGY_MODEL`). One key
- per session from THE shared pool (`KeyPool.session_key`, no in-flight slot) as `GEMINI_API_KEY`,
+ per session from THE shared pool (`KeyPool.lease_session_key`: no in-flight slot, but a machine-wide
+ flock lease under `<cache_dir>/slots/agy_keys/`, so parallel runs put one session per key until every
+ key is in one; the shared pool also starts each process's rotation at a random key) as `GEMINI_API_KEY`,
its outcome reported back (429 → cooldown, 401/403/`API_KEY_INVALID` → dead, 5xx, ok, skip);
other credential env stripped; KeyPoolExhausted → `exit_reason=budget`, never raised.
* Each session gets a fresh HOME under `<cache_dir>/agy_homes/…` holding
@@ -89,6 +91,10 @@ round, then ≈ $0.36 / ~7 min per refine (give scenes `--max-minutes 60`).
default `high` (the Gemini API's own default).
* Cost: priced at Gemini list price; agy's `output_tokens` already include `thinking_tokens`, so
output = output − thinking, thoughts = thinking (billed once).
+* `--print-timeout` = `timeout_s` + the watchdog's `HARD_GRACE_S` (5 min) + 1 min, so the watchdog
+ decides; agy's own clock stopping a turn (stderr `[agy] print timeout after …`, envelope still
+ `SUCCESS` with an empty response) is booked `exit_reason=timeout`. At `timeout_s + 1 min` it cut off
+ every argon scene asset/env session still working at 8 min (2026-10-13).
* No retry loop in the backend: agy retries its own model calls (≤ 30 s waits since 1.3.4, stops
at once on a spent daily quota); a transient death goes to the round loop's ONE transport retry,
which takes a fresh key. There is no single-shot storm fallback (deleted in D103).
@@ -271,7 +277,11 @@ says `no verdict in any of N round(s)` when this happens.
A run that crashed outside its own handling leaves `record.json` with `status=failed`;
`3dcode resume` retries from the last completed stage/round (cached plan/skeleton/scene
-stages are reused — this also recovers from Gemini 503 storms). Ctrl-C is safe.
+stages are reused — this also recovers from Gemini 503 storms). Ctrl-C and `kill <pid>` (SIGTERM)
+are safe: `make` / `resume` kill every agent / build process group the run has open — worker
+threads' included — refuse new ones, record the stop, and end within `proc.STOP_GRACE_S` (30 s) even
+if a worker is inside a long model call. Before 2026-10-13 a SIGTERM left the agy session running
+and billing.
## 6. Texture pass
diff --git a/harness/tests/agents/test_antigravity.py b/harness/tests/agents/test_antigravity.py
index 71924356..a9b44d37 100644
--- a/harness/tests/agents/test_antigravity.py
+++ b/harness/tests/agents/test_antigravity.py
@@ -53,6 +53,10 @@ if mode == "died": # a turn that ended on the API: AGY_ERROR on stderr, exi
print('AGY_ERROR: {"short_error":"generating: Error 503","status":"UNAVAILABLE","error_code":503,'
'"code_kind":"http","retryable":true,"error_id":"x"}', file=sys.stderr)
sys.exit(3)
+if mode == "print_timeout": # agy 1.3.4's own clock: SUCCESS, no response, one stderr line
+ print(json.dumps({"conversation_id": "c8", "status": "SUCCESS", "response": "", "num_turns": 1}))
+ print("[agy] print timeout after 8m0s with turn in progress; returning partial output", file=sys.stderr)
+ sys.exit(0)
if mode == "text":
print("plain text answer")
else:
@@ -60,11 +64,11 @@ else:
'''
-def test_argv_sets_the_print_timeout_a_minute_past_the_session(tmp_ws: Workspace):
+def test_argv_sets_the_print_timeout_a_minute_past_the_watchdogs_hard_limit(tmp_ws: Workspace):
a = AntigravityAgent("gemini-4-argon-high", binary="agy")
s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", timeout_s=1800), "agy")
argv = a.build_argv(s)
- assert argv[argv.index("--print-timeout") + 1] == "31m"
+ assert argv[argv.index("--print-timeout") + 1] == "36m" # 30 min + the 5 min grace + 1
def test_fake_run_json_and_text(tmp_ws: Workspace, fake_bin, monkeypatch):
@@ -111,6 +115,14 @@ def test_agy_says_itself_whether_a_dead_turn_is_worth_a_retry(tmp_ws: Workspace,
assert rec["agy_error"]["retryable"] is True and rec["agy_error"]["error_code"] == 503
+def test_agys_own_print_timeout_is_a_timeout_not_an_empty_answer(tmp_ws: Workspace, fake_bin, monkeypatch):
+ a = AntigravityAgent("gemini-4-argon-high", binary=fake_bin("agy", FAKE_AGY))
+ monkeypatch.setenv("FAKE_MODE", "print_timeout")
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="pt", timeout_s=30))
+ assert not res.ok and res.exit_reason == "timeout" and not res.transient
+ assert "--print-timeout" in res.errors[0] and "empty response" not in " ".join(res.errors)
+
+
@pytest.mark.live
def test_live_agy_tiny(tmp_ws: Workspace):
if not shutil.which("agy"):
diff --git a/harness/tests/core/test_proc.py b/harness/tests/core/test_proc.py
index f96708fa..31f0906b 100644
--- a/harness/tests/core/test_proc.py
+++ b/harness/tests/core/test_proc.py
@@ -180,3 +180,50 @@ def test_managed_process_reaps_on_exit_no_zombie(tmp_path: Path):
assert mp.stdout_text.strip() == "hi"
with pytest.raises(ChildProcessError):
os.waitpid(pid, os.WNOHANG) # __exit__ already reaped it — no zombie left
+
+
+def test_a_stop_signal_kills_the_children_refuses_new_ones_and_cannot_hang(tmp_path):
+ """A run's sessions and builds run in worker threads; SIGTERM reaches the main thread
+ only, and used to leave their trees running (a SIGTERM'd make orphaned its agy session).
+ Now: the live child group dies, a worker cannot start another one (its retry, its next
+ build), and a worker stuck in a long call cannot hold the exit past STOP_GRACE_S."""
+ import subprocess
+
+ marker = tmp_path / "refused"
+ script = tmp_path / "victim.py"
+ script.write_text(
+ "import threading, time\n"
+ "from codeverse3d import proc\n"
+ "proc.STOP_GRACE_S = 1.0\n"
+ "proc.install_stop_handlers()\n"
+ "def session():\n"
+ " with proc.ManagedProcess(['sleep', '120'], cwd='.') as mp:\n"
+ " print(mp.proc.pid, flush=True)\n"
+ " mp.proc.wait()\n"
+ " try:\n"
+ " proc.ManagedProcess(['sleep', '120'], cwd='.') # the retry after the kill\n"
+ " except proc.ProcessStopping:\n"
+ f" open({str(marker)!r}, 'w').write('refused')\n"
+ "threading.Thread(target=session).start()\n"
+ "threading.Thread(target=time.sleep, args=(120,)).start() # a model call that never ends\n"
+ "time.sleep(120)\n")
+ victim = subprocess.Popen([sys.executable, str(script)], stdout=subprocess.PIPE, text=True)
+ child = int(victim.stdout.readline())
+ t0 = time.monotonic()
+ os.kill(victim.pid, signal.SIGTERM)
+ assert victim.wait(timeout=20) == 128 + signal.SIGTERM
+ assert time.monotonic() - t0 < 10, "a stuck worker thread held the exit"
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline and _alive(child):
+ time.sleep(0.05)
+ assert not _alive(child), "the worker thread's sleep survived its parent's SIGTERM"
+ assert marker.read_text() == "refused", "a new child started after the stop"
+
+
+def _alive(pid: int) -> bool:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ with open(f"/proc/{pid}/stat") as f: # a zombie is dead
+ return f.read().split()[2] != "Z"
diff --git a/harness/tests/models/test_keypool.py b/harness/tests/models/test_keypool.py
index fc179e84..12f8110c 100644
--- a/harness/tests/models/test_keypool.py
+++ b/harness/tests/models/test_keypool.py
@@ -118,3 +118,38 @@ def test_a_capped_pool_names_its_slot_directory_and_a_session_key_takes_no_slot(
assert pool.stats()["in_flight"] == 1 and pool.slots.busy() == 1
pool.release()
assert pool.stats()["in_flight"] == 0 and pool.slots.busy() == 0
+
+
+def test_the_rotation_starts_where_it_is_told_and_the_shared_pool_starts_anywhere(monkeypatch, tmp_path):
+ """Parallel ``3dcode make`` processes make the same calls in the same order: every pool
+ starting at key 0 put four runs' planner calls on one key (live, 2026-10-13)."""
+ from codeverse3d.config import get_settings
+ from codeverse3d.models import gemini
+
+ pool, _ = make(start=4)
+ assert [pool.session_key() for _ in range(3)] == ["k2", "k3", "k1"]
+ monkeypatch.setattr(get_settings(), "cache_dir", tmp_path)
+ firsts = set()
+ for _ in range(40):
+ gemini._pools.clear()
+ firsts.add(gemini.shared_pool([f"s{j}" for j in range(12)], max_in_flight=0).session_key())
+ assert len(firsts) > 3
+ gemini._pools.clear()
+
+
+def test_a_session_lease_keeps_one_session_per_key_across_pools_until_keys_run_out(tmp_path):
+ """Two pools stand in for two ``3dcode make`` processes: each session leases a key no
+ other live session holds; with every key leased the next one shares (lease ``None``);
+ closing a lease frees its key for the next session."""
+ a, _ = make(keys=("k1", "k2"))
+ b, _ = make(keys=("k1", "k2"))
+ k1, l1 = a.lease_session_key(tmp_path)
+ k2, l2 = b.lease_session_key(tmp_path)
+ assert {k1, k2} == {"k1", "k2"} and l1 is not None and l2 is not None
+ k3, l3 = a.lease_session_key(tmp_path)
+ assert k3 in ("k1", "k2") and l3 is None # every key in a session: shared, not refused
+ KeyPool.end_lease(l1)
+ k4, l4 = b.lease_session_key(tmp_path)
+ assert (k4, l4 is not None) == (k1, True)
+ KeyPool.end_lease(l2)
+ KeyPool.end_lease(l4)