Skip to content

Official Codebase of 3DCodeVerse

Python

models: max_in_flight is machine-wide — flock'd slot files replace the per-process semaphore and the /proc sibling scan

gaoypengef298f1872f3
diff --git a/eval/bench/ab_plan.py b/eval/bench/ab_plan.py
index f92bd47d..8b6f2212 100644
--- a/eval/bench/ab_plan.py
+++ b/eval/bench/ab_plan.py
@@ -22,9 +22,10 @@ Why each arm is a child PROCESS rather than a thread: the switches under test ar
from the environment (``codeverse3d.tracks.planner.brief_enabled`` reads ``os.environ`` at
call time; anything under ``Settings`` is read once through an ``lru_cache``), so two
threads in one interpreter cannot hold different values of them. A child gets exactly
-the env its arm needs and nothing leaks across. Each child owns a key pool, so the
-driver caps every child at ``C3D_MAX_IN_FLIGHT`` (default 16) — two children at
-16 stay inside the 64 knee measured for one process (``docs/COST.md`` §23).
+the env its arm needs and nothing leaks across. The driver pins both children at
+``C3D_MAX_IN_FLIGHT`` (default 16); the in-flight slots are machine-wide lock files, so
+the two arms share those 16 with each other and with every other harness process
+(``docs/COST.md`` §23).
Why the arms launch as simultaneous PAIRS: provider weather changes by the hour, and a
verdict that compares an arm run in a storm against one run in the clear measures the
@@ -227,12 +228,11 @@ def child_env(arm: str, opts: AbOptions, base: dict[str, str] | None = None) ->
The variant gets ``variant_env`` on top of the driver's env; the control gets the
driver's env with those same keys REMOVED, so a switch that happens to be set in
the launching shell cannot silently turn the control into a second variant. Both
- are PINNED to ``opts.max_in_flight`` (both spellings), never merely defaulted to it:
- ``main`` refuses to start unless ``pool_budget().fits(2 * opts.max_in_flight)``, so a
- child that inherited a different cap from the launching shell would make that
- reservation a fiction — with ``--max-in-flight 8`` under a shell exporting 32 the A/B
- reserved 16 of the 64-call knee and consumed 64 (docs/COST.md §23). ``opts`` already
- carries the inherited value when no flag was passed (:func:`inherited_max_in_flight`).
+ are PINNED to ``opts.max_in_flight`` (both spellings), never merely defaulted to it: a
+ child that inherited a different cap from the launching shell would run the two arms
+ under different ceilings — with ``--max-in-flight 8`` under a shell exporting 32 one
+ child drew from 32 machine-wide slots (docs/COST.md §23). ``opts`` already carries the
+ inherited value when no flag was passed (:func:`inherited_max_in_flight`).
Under ``--aa`` the variant arm gets the CONTROL environment: the two arms then run
byte-identical code and the measured delta is the rig's own noise floor, which is the
@@ -587,8 +587,8 @@ def _parser() -> argparse.ArgumentParser:
"--max-in-flight",
type=int,
default=None,
- help=f"per child; wins over an inherited {MAX_IN_FLIGHT_ENV} "
- f"(default: that variable, else {DEFAULT_MAX_IN_FLIGHT}). The preflight reserves 2x it",
+ help=f"both children's cap; wins over an inherited {MAX_IN_FLIGHT_ENV} "
+ f"(default: that variable, else {DEFAULT_MAX_IN_FLIGHT}). The slots are machine-wide",
)
ap.add_argument(
"--parallel", type=int, default=PARALLEL, help="accepted for symmetry; must be 2 (one pair)"
@@ -620,11 +620,6 @@ def _parser() -> argparse.ArgumentParser:
"--no-preflight", action="store_true", help="skip the provider health check (do not)"
)
ap.add_argument("--wait-for-provider", type=float, default=0.0, metavar="MIN")
- ap.add_argument(
- "--allow-siblings",
- action="store_true",
- help="launch even when other harness processes are running (they share the quota)",
- )
ap.add_argument(
"--report-only", action="store_true", help="only rebuild pairs.json / summary.md"
)
@@ -727,18 +722,6 @@ def main(argv: Sequence[str] | None = None) -> int:
"thing under test and the rig would report 'no effect' with confidence — "
+ "; ".join(blockers)
)
- from codeverse3d.models.health import pool_budget
-
- # the rule is a BUDGET, not a head-count: the provider sees one machine, so the sum of
- # every process's in-flight cap must stay at the knee. Two children run at once here.
- need = 2 * opts.max_in_flight
- if not (pb := pool_budget()).fits(need) and not ns.allow_siblings:
- print(
- f"refusing to start: {pb}; this A/B needs {need} (2 children x {opts.max_in_flight}) "
- f"(docs/COST.md §23). Wait, lower --max-in-flight, or pass --allow-siblings.",
- flush=True,
- )
- return 3
if not ns.no_preflight and not preflight(opts, wait_minutes=ns.wait_for_provider):
return 2
diff --git a/eval/tests/test_ab_plan.py b/eval/tests/test_ab_plan.py
index c0d84240..fe3c8a47 100644
--- a/eval/tests/test_ab_plan.py
+++ b/eval/tests/test_ab_plan.py
@@ -189,11 +189,10 @@ def test_variant_env_is_applied_to_the_variant_arm_only():
def test_children_run_at_exactly_the_cap_the_budget_reserved(monkeypatch):
- """CQ-3: main() refuses to start unless ``pool_budget().fits(2 * opts.max_in_flight)``,
- so both children must run at THAT number. child_env used ``setdefault``, so a shell
- exporting C3D_MAX_IN_FLIGHT=32 under ``--max-in-flight 8`` reserved 16 of the 64-call
- knee and then consumed 64 (docs/COST.md §23) — three lines after the function
- deliberately pops every variant key so an inherited switch cannot win."""
+ """CQ-3: both children run at the cap the driver was given. child_env used
+ ``setdefault``, so a shell exporting C3D_MAX_IN_FLIGHT=32 under ``--max-in-flight 8``
+ ran a child at 32 (docs/COST.md §23) — three lines after the function deliberately pops
+ every variant key so an inherited switch cannot win."""
opts = AbOptions(variant_env={"K": "v"}, max_in_flight=8)
base = {"PATH": "/bin", MAX_IN_FLIGHT_ENV: "32", NESTED_MAX_IN_FLIGHT_ENV: "48"}
for arm in (CONTROL, VARIANT):
diff --git a/eval/tests/test_ab_plan_switches.py b/eval/tests/test_ab_plan_switches.py
index 10d7091d..1f0b5925 100644
--- a/eval/tests/test_ab_plan_switches.py
+++ b/eval/tests/test_ab_plan_switches.py
@@ -20,8 +20,8 @@ def test_ab_plan_refuses_an_ab_whose_only_switch_is_dead(capsys):
def test_ab_plan_still_accepts_a_live_switch(monkeypatch, capsys):
"""The guard must not block a real A/B: it fires only when EVERY key is dead.
- Offline — --no-preflight and --allow-siblings keep the provider health check and the
- docs/COST.md §23 admission check out of it, and run_ab itself is stubbed."""
+ Offline — --no-preflight keeps the provider health check out of it, and run_ab itself
+ is stubbed."""
import bench.ab_plan as A
seen: list[dict[str, str]] = []
@@ -31,7 +31,7 @@ def test_ab_plan_still_accepts_a_live_switch(monkeypatch, capsys):
monkeypatch.setattr(A, "run_ab", lambda battery, out, opts, **kw: (seen.append(opts.variant_env), _V())[1])
for argv in (["--variant-env", "C3D_PLAN_BRIEF=off"],
["--variant-env", "C3D_PLAN_FEATURES=all", "--variant-env", "C3D_PLAN_BRIEF=off"]):
- A.main(["--prompts", "p.yaml", "--out", "o", "--no-preflight", "--allow-siblings", *argv])
+ A.main(["--prompts", "p.yaml", "--out", "o", "--no-preflight", *argv])
assert len(seen) == 2, capsys.readouterr()
assert "C3D_PLAN_BRIEF" in seen[0]
@@ -50,7 +50,7 @@ def test_a_dead_switch_does_not_block_pin_plan(monkeypatch, capsys):
decision, reason, caution = "keep", "stubbed", ""
monkeypatch.setattr(A, "run_ab", lambda battery, out, opts, **kw: (seen.append(opts.variant_env), _V())[1])
- A.main(["--prompts", "p.yaml", "--out", "o", "--no-preflight", "--allow-siblings", "--pin-plan",
+ A.main(["--prompts", "p.yaml", "--out", "o", "--no-preflight", "--pin-plan",
"--variant-env", "C3D_PLAN_FEATURES=all", "--variant-env", "C3D_SKILLS=0"])
assert seen == [{"C3D_PLAN_FEATURES": "all", "C3D_SKILLS": "0"}], capsys.readouterr()
diff --git a/harness/codeverse3d/agents/backends.py b/harness/codeverse3d/agents/backends.py
index d409948a..3ac9933f 100644
--- a/harness/codeverse3d/agents/backends.py
+++ b/harness/codeverse3d/agents/backends.py
@@ -102,10 +102,10 @@ def retry_window_left(timeout_s: float, elapsed_s: float) -> float | None:
def _key_pool(keys: list[str]) -> KeyPool:
"""THE process-wide pool for these keys — ``models.gemini.shared_pool``, i.e. the
- same limiter the API path uses, with quotas from ``Settings.rate``. This module
- used to build its own ``KeyPool(keys)`` with library defaults (900 RPM, no TPM
- bucket), so the CLI agent and the API path scheduled the same 22 keys under two
- different quotas (found by review 2026-08-28)."""
+ same cooldowns and dead-key bench the API path uses (a session takes its key with
+ ``session_key``: no in-flight slot). This module used to build its own
+ ``KeyPool(keys)`` with library defaults, so the CLI agent and the API path scheduled
+ the same 22 keys under two different quotas (found by review 2026-08-28)."""
from codeverse3d.models.gemini import shared_pool
return shared_pool(keys)
@@ -211,7 +211,7 @@ def _retry_key(pool: KeyPool, used: set[str]) -> str | None:
``None`` when every key is throttled (429 cooldown) — the caller then stops."""
for exclude in (used, None):
try:
- return pool.acquire(exclude=exclude or None, timeout_s=RETRY_KEY_WAIT_S)
+ return pool.session_key(exclude=exclude or None, timeout_s=RETRY_KEY_WAIT_S)
except KeyPoolExhausted:
continue
return None
@@ -287,7 +287,7 @@ class GeminiCliAgent(_CliAgent):
prompt = deliver_prompt(s, _compose_prompt(job))
pool = _key_pool(get_settings().gemini_api_keys)
try:
- key = pool.acquire()
+ key = pool.session_key() # no in-flight slot: the CLI makes its own calls
except KeyPoolExhausted as e: # every key throttled for the whole wait budget
return failed(s, "budget", f"Gemini key pool exhausted before the first attempt: {e}")
attempts = 0
@@ -298,21 +298,16 @@ class GeminiCliAgent(_CliAgent):
while True:
attempts += 1
used.add(key)
- try:
- started, env = time.time(), self.build_env(s, key)
- proc = invoke(s, self.build_argv(prompt), env, prompt=prompt, attempt=attempts,
- soft_timeout_s=next_soft, model=self.model, key_tail=key[-4:])
- self._record_trace(s, started, env)
- outcome = self._interpret(s, proc)
- usage_total = usage_total + outcome["usage"]
- # the pool is shared with every API call: a hang, a substituted model or the
- # agent's own failure is not the key's fault ("skip" = counters untouched)
- pool.report(key, "429" if outcome["quota"] else "ok" if outcome["ok"]
- else "5xx" if outcome["transient"] else "skip")
- finally:
- # one acquire per attempt: keep the pool's in-flight gauge honest — also when
- # invoke raises, or one slot of the PROCESS-WIDE pool is gone for good
- pool.release()
+ started, env = time.time(), self.build_env(s, key)
+ proc = invoke(s, self.build_argv(prompt), env, prompt=prompt, attempt=attempts,
+ soft_timeout_s=next_soft, model=self.model, key_tail=key[-4:])
+ self._record_trace(s, started, env)
+ outcome = self._interpret(s, proc)
+ usage_total = usage_total + outcome["usage"]
+ # the pool is shared with every API call: a hang, a substituted model or the
+ # agent's own failure is not the key's fault ("skip" = counters untouched)
+ pool.report(key, "429" if outcome["quota"] else "ok" if outcome["ok"]
+ else "5xx" if outcome["transient"] else "skip")
# a per-minute 429 on the single key a CLI process holds clears within the
# rotated retry's wait; ab_fewer_turns (2026-08-29) lost 4 of 10 cells to
# two 429s in a row, so a quota failure gets one more rotated attempt
diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.py
index f3ede6fe..502e46db 100644
--- a/harness/codeverse3d/config.py
+++ b/harness/codeverse3d/config.py
@@ -108,10 +108,12 @@ class Limits(BaseModel):
class Rate(BaseModel):
"""The model-call ceiling and the 503 hedge (``docs/COST.md`` Part III).
- ``max_in_flight`` is a ceiling on *concurrent model calls* and is deliberately
- separate from ``Limits.max_parallel_agents`` / ``max_parallel_builds``: blender /
- node / chrome are CPU-bound and sized by cores, model calls are network-bound and
- sized by the provider. 0 = unlimited. There is no RPM / TPM quota here any more:
+ ``max_in_flight`` is a MACHINE-WIDE ceiling on the harness's own concurrent model calls
+ (flock'd slot files under ``<cache_dir>/slots/``, shared by every process — COST §23)
+ and is deliberately separate from ``Limits.max_parallel_agents`` /
+ ``max_parallel_builds``: blender / node / chrome are CPU-bound and sized by cores, model
+ calls are network-bound and sized by the provider. 0 = unlimited. A vendor CLI
+ session takes a key from the pool but no slot. There is no RPM / TPM quota here any more:
since the api-agent went the harness's own calls peaked at 2.6 % of one key's RPM
and 3.9 % of its TPM, so the buckets they fed never engaged (COST §19).
"""
@@ -123,9 +125,10 @@ class Rate(BaseModel):
# in-flight accounting, and finally died as a bare ValueError from
# threading.BoundedSemaphore inside KeyPool -- at the first model call, long
# after the workspace and spec.json were written.
- description="process-wide cap on concurrent model calls (0 = off). Measured knee: a "
- "128-call burst of 12k-token prompts ran 29.6 calls/min at 16 in-flight, 43.9 at 32, "
- "72.9 at 64 and fell back to 47.2 at 128 (docs/COST.md Part III).")
+ description="machine-wide cap on concurrent model calls (0 = off): every process draws "
+ "from the same N slot files, so the machine never exceeds the largest N any process runs "
+ "with. Measured knee: a 128-call burst of 12k-token prompts ran 29.6 calls/min at 16 "
+ "in-flight, 43.9 at 32, 72.9 at 64 and fell back to 47.2 at 128 (docs/COST.md Part III).")
hedge: int = Field(
default=2, ge=1,
description="keys a retry is raced on once a call has met its first 503 (1 = off). Measured "
diff --git a/harness/codeverse3d/doctor.py b/harness/codeverse3d/doctor.py
index 0b033a45..5b7ca6d8 100644
--- a/harness/codeverse3d/doctor.py
+++ b/harness/codeverse3d/doctor.py
@@ -1,5 +1,5 @@
"""Environment checks behind ``3dcode doctor`` — python deps, Blender, node/three/
-puppeteer, the GPU probe, keys, the pool admission numbers, the vendor CLIs, MCP
+puppeteer, the GPU probe, keys, the machine-wide in-flight slots, the vendor CLIs, MCP
and the skill library wiring. Moved out of ``cli/`` 2026-08-28: only the typer
shim is a CLI concern (tests/install imports these checks as documentation facts).
"""
@@ -171,18 +171,15 @@ def check_keys(live: bool) -> list[Row]:
n = len(s.gemini_api_keys)
rows: list[Row] = [("gemini keys", "OK" if n else "FAIL", f"{n} key(s)")]
if n:
- from codeverse3d.models.health import pool_budget
-
- pb = pool_budget()
- cap = int(s.rate.max_in_flight or 0)
- rows.append((
- "pool sharing",
- "OK" if pb.fits(cap) else "WARN",
- (f"{pb}; this process at {cap} {'fits' if pb.fits(cap) else 'does NOT fit'} "
- f"(docs/COST.md §23: keep the SUM at or under {pb.knee}"
- + ("" if pb.fits(cap) else f" — set C3D_MAX_IN_FLIGHT={max(1, pb.headroom)} or wait") + ")")
- if pb.siblings else "sole harness process: max_in_flight applies as configured",
- ))
+ from codeverse3d.models.gemini import shared_pool
+
+ slots = shared_pool(list(s.gemini_api_keys)).slots
+ if slots is None:
+ rows.append(("in-flight slots", "WARN", "max_in_flight=0: no cap on concurrent model calls"))
+ else:
+ busy = slots.busy()
+ rows.append(("in-flight slots", "WARN" if busy >= slots.n else "OK",
+ f"{busy}/{slots.n} busy machine-wide ({slots.root}; docs/COST.md §23)"))
rows.append(("anthropic key", "OK" if s.anthropic_api_key else "WARN", "set" if s.anthropic_api_key else "not set (anthropic:* backends unavailable)"))
rows.append(("openai key", "OK" if s.openai_api_key else "WARN", "set" if s.openai_api_key else "not set (openai:* backends unavailable)"))
if live and n:
diff --git a/harness/codeverse3d/models/gemini.py b/harness/codeverse3d/models/gemini.py
index 79470237..b6226d58 100644
--- a/harness/codeverse3d/models/gemini.py
+++ b/harness/codeverse3d/models/gemini.py
@@ -204,14 +204,18 @@ _registry_lock = threading.Lock()
def shared_pool(keys: list[str], *, max_in_flight: int | None = None) -> KeyPool:
- """One ``KeyPool`` per distinct (key list, in-flight cap) so limiters are process-wide;
- an unset cap comes from ``Settings.rate.max_in_flight``."""
+ """One ``KeyPool`` per distinct (key list, in-flight cap) per process; an unset cap comes
+ from ``Settings.rate.max_in_flight``. Its slots are machine-wide: every process draws
+ from the same ``<cache_dir>/slots/gemini/NN.lock`` files (``retry.Slots``, COST §23)."""
+ from codeverse3d.config import get_settings
+
cap = _rate().max_in_flight if max_in_flight is None else max_in_flight
sig = (*keys, f"|{cap}")
with _registry_lock:
pool = _pools.get(sig)
if pool is None:
- pool = KeyPool(keys, max_in_flight=cap or 0)
+ slots = get_settings().cache_dir / "slots" / "gemini" if cap else None
+ pool = KeyPool(keys, max_in_flight=cap or 0, slots_dir=slots)
_pools[sig] = pool
return pool
diff --git a/harness/codeverse3d/models/health.py b/harness/codeverse3d/models/health.py
index 99be9edf..7d12d026 100644
--- a/harness/codeverse3d/models/health.py
+++ b/harness/codeverse3d/models/health.py
@@ -22,7 +22,6 @@ from __future__ import annotations
import concurrent.futures as cf
import logging
from dataclasses import dataclass
-from pathlib import Path
log = logging.getLogger(__name__)
@@ -128,195 +127,3 @@ def _bare_model(model_id: str, timeout_s: float):
from codeverse3d.models.openai import OpenAIModel # everything else, as models.registry does
return OpenAIModel(name, timeout_s=timeout_s, max_attempts=1)
-
-
-# --------------------------------------------------------------------------- siblings
-#: how a harness process appears in its own argv. Matched on ARGUMENTS, never on the
-#: whole command line: the repo path itself contains "3dcodeverse", so a substring test
-#: counts every shell that merely `cd`s into the tree.
-#:
-#: BOTH spellings of every entry point are listed, because a program launched two ways is
-#: still one program. Measured 2026-08-24: an eight-prompt A/B running as
-#: ``python -m bench.ab_plan`` (driver + two 16-in-flight cell children) was invisible to
-#: :func:`pool_budget`, which reported "headroom 48" on a machine already sitting at the
-#: 64 knee — the exact over-launch ``docs/COST.md`` §23 exists to prevent.
-_MODULES = ("codeverse3d.cli.main", "bench.ab_plan", "bench.compare_backends", "bench.run_bench")
-_SCRIPTS = ("compare_backends.py", "run_bench.py", "ab_plan.py")
-_ENTRY_POINTS = ("3dcode", "3dcodeverse")
-
-
-def _program_slots(args: list[str]) -> list[str]:
- """The argv tokens that can legitimately BE the program name.
-
- Only argv[0] and, behind a python interpreter, the script slot after it. Both bounds
- matter and each was a real bug:
-
- * Too narrow (argv[0] only) is how ``3dcode`` went uncounted from the start. A console
- script installed by pip is a shebang file, so the kernel rewrites ``3dcode make …``
- into ``<python> /…/bin/3dcode make …`` and the entry point lands at argv[1] — argv[0]
- is the interpreter. Measured 2026-08-25: 21 live ``3dcode make`` processes, and
- :func:`pool_budget` reported "0 siblings, headroom 64". Every lane then sized
- ``C3D_MAX_IN_FLIGHT`` off a number that was structurally always 64, which is the
- over-launch ``docs/COST.md`` §23 exists to prevent.
- * Too wide (scanning all of argv) fails the other way: ``--runs-dir
- /home/yipeng/3dcodeverse`` has basename ``3dcodeverse``, so a shell or an editor
- holding that path would be charged as a harness process and every sibling would
- refuse to launch.
- """
- from pathlib import PurePath
-
- if not args:
- return []
- slots = [args[0]]
- if not PurePath(args[0]).name.startswith("python"):
- return slots
- i = 1
- while i < len(args) and args[i].startswith("-"):
- if args[i] in ("-m", "-c"): # module / inline code: not a script slot
- return slots
- i += 1
- if i < len(args):
- slots.append(args[i])
- return slots
-
-
-def _harness_token(args: list[str]) -> str | None:
- """The argv token that makes this a harness process, or ``None`` if it is not one.
-
- Returned rather than a bool so callers can ask WHICH entry point is running without
- re-scanning the command line (see :func:`_is_delegating_driver`).
- """
- if not args:
- return None
- from pathlib import PurePath
-
- for slot in _program_slots(args):
- if PurePath(slot).name in _ENTRY_POINTS:
- return slot
- for i, a in enumerate(args):
- if a == "-m" and i + 1 < len(args) and args[i + 1] in _MODULES:
- return args[i + 1]
- if PurePath(a).name in _SCRIPTS:
- return a
- return None
-
-
-def _is_harness_argv(args: list[str]) -> bool:
- return _harness_token(args) is not None
-
-
-#: the ``ab_plan`` entry point under either spelling
-_AB_PLAN = ("ab_plan.py", "bench.ab_plan")
-
-
-def _is_delegating_driver(args: list[str]) -> bool:
- """Does this process spend its in-flight budget only through capped CHILDREN?
-
- ``eval/bench/ab_plan.py`` in driver mode spawns one ``… cell`` child per arm and makes no
- model calls of its own past a 6-key preflight probe; the children carry the caps and
- are counted in their own right. Charging the driver as well would double-count the
- same traffic — and since ``--max-in-flight`` is the cap it hands its children, not one
- it sets on itself, :func:`_cap_of` would charge it the 64 default, i.e. the whole knee,
- and every sibling would refuse to launch. Counting heads instead of budget is the
- failure that stalled a whole A/B wave on 2026-08-24; this is its mirror image.
- """
- from pathlib import PurePath
-
- tok = _harness_token(args)
- if tok is None or PurePath(tok).name not in _AB_PLAN:
- return False
- i = args.index(tok)
- return args[i + 1 : i + 2] != ["cell"]
-
-
-#: the measured per-process knee (docs/COST.md §20); the machine-wide budget is the same
-#: number, because the provider sees one machine's worth of traffic, not one process's
-POOL_KNEE = 64
-_CAP_ENVS = ("C3D_MAX_IN_FLIGHT", "C3D_RATE__MAX_IN_FLIGHT")
-
-
-def _cap_of(pid_dir: Path) -> int:
- """The in-flight cap a sibling process runs under, read from its environment.
-
- A process that set neither name runs at the default; one that set an unparsable value
- is counted at the default too (the child itself would have refused to start).
-
- ``0`` is the documented "off = unlimited" value (``Rate.max_in_flight``; ``doctor``
- prints ``max_in_flight=off``), so the one sibling with NO ceiling at all has to be
- charged the whole knee — counting it as 0 handed the next launcher the full budget.
- A negative cap is charged the same way rather than being SUBTRACTED from ``used``,
- where it grew the headroom it should have shrunk.
- """
- from codeverse3d.config import Rate
-
- default = Rate().max_in_flight
- try:
- raw = (pid_dir / "environ").read_bytes()
- except OSError:
- return default
- env = dict(kv.split(b"=", 1) for kv in raw.split(b"\0") if b"=" in kv)
- for name in _CAP_ENVS:
- val = env.get(name.encode())
- if val:
- try:
- n = int(val)
- except ValueError:
- return default
- return POOL_KNEE if n <= 0 else n
- return default
-
-
-@dataclass(frozen=True)
-class PoolBudget:
- """How much of the machine-wide in-flight budget the running siblings already hold."""
-
- siblings: int
- used: int
- knee: int = POOL_KNEE
-
- @property
- def headroom(self) -> int:
- return max(0, self.knee - self.used)
-
- def fits(self, my_cap: int) -> bool:
- return my_cap <= self.headroom
-
- def __str__(self) -> str:
- return (
- f"{self.siblings} sibling harness process(es) hold {self.used}/{self.knee} in-flight; "
- f"headroom {self.headroom}"
- )
-
-
-def pool_budget() -> PoolBudget:
- """Sum the in-flight caps of every OTHER harness process on this machine.
-
- This is the quantity docs/COST.md §23 is actually about: the provider sees one machine,
- so the SUM of ``max_in_flight`` across processes must stay at the knee, not each
- process alone. Counting *processes* (the first version) made every agent refuse to
- launch while any sibling existed, and on 2026-08-24 that stalled a whole A/B wave
- behind two batteries that were themselves parked. Best-effort: on any /proc
- trouble it reports no siblings and no usage.
- """
- import os
-
- me, used, n = os.getpid(), 0, 0
- try:
- entries = list(Path("/proc").iterdir())
- except OSError:
- return PoolBudget(0, 0)
- for entry in entries:
- if not entry.name.isdigit() or int(entry.name) == me:
- continue
- try:
- raw = (entry / "cmdline").read_bytes()
- except OSError:
- continue
- argv = [a for a in raw.decode(errors="replace").split("\0") if a]
- if not _is_harness_argv(argv):
- continue
- n += 1
- if _is_delegating_driver(argv):
- continue # its capped children are counted separately; see _is_delegating_driver
- used += _cap_of(entry)
- return PoolBudget(n, used)
diff --git a/harness/codeverse3d/models/retry.py b/harness/codeverse3d/models/retry.py
index fc2abb40..740cb3e9 100644
--- a/harness/codeverse3d/models/retry.py
+++ b/harness/codeverse3d/models/retry.py
@@ -1,8 +1,9 @@
"""The scheduling machine under every model call (merged 2026-08-28, d512ccc):
1. ``KeyPool``: a multi-key pool with 429 cooldown, dead-key benching, a health score
- and the ``max_in_flight`` ceiling — used by ``GeminiModel`` (22 keys on the owner's
- box) but provider-neutral;
+ and the ``max_in_flight`` ceiling, which is machine-wide (``Slots``: flock'd lock
+ files every process shares) — used by ``GeminiModel`` (22 keys on the owner's box)
+ but provider-neutral;
2. ``rotate_with_retries``, the one retry loop (the pool, hedging, the ``RETRY_DEADLINE_S``
deadline) — the SDK adapters run it over a one-key pool (``parts.retry_one_key``).
@@ -13,11 +14,13 @@ The pool:
* ``acquire()`` picks the next healthy key round-robin, honouring 429 cool-downs; it
blocks (bounded) when every key is cooling and raises ``KeyPoolExhausted`` after
``timeout_s``. ``max_in_flight`` additionally caps how many calls may be out at
- once, and :meth:`KeyPool.release` (a ``finally`` in ``rotate_with_retries``) hands the
- slot back. ``try_acquire()`` is the never-waiting variant a hedged retry uses for
- its extra keys. There is no RPM / TPM bucket: the ledgers since the api-agent went
- (2026-08-29 .. 09-22, 2 080 calls) peaked at 3.9 % of one key's TPM and 2.6 % of its
- RPM, so the buckets never engaged (docs/COST.md §19).
+ once on the whole machine, and :meth:`KeyPool.release` (a ``finally`` in
+ ``rotate_with_retries``) hands the slot back. ``try_acquire()`` is the never-waiting
+ variant a hedged retry uses for its extra keys; ``session_key()`` picks a key for a
+ vendor CLI session, which makes its own calls and holds no slot. There is no RPM /
+ TPM bucket: the ledgers since the api-agent went (2026-08-29 .. 09-22, 2 080 calls)
+ peaked at 3.9 % of one key's TPM and 2.6 % of its RPM, so the buckets never engaged
+ (docs/COST.md §19).
* ``report(key, outcome)`` feeds back ``ok | 429 | 5xx | error | dead | skip`` so the
pool can cool a key down and adjust its health score. ``skip`` is a content
failure the key did not cause (bad JSON, empty candidates): health and counters are
@@ -32,7 +35,9 @@ Thread-safe; ``clock`` / ``sleep`` are injectable for deterministic tests.
from __future__ import annotations
+import fcntl
import logging
+import os
import random
import threading
import time
@@ -40,6 +45,7 @@ from collections.abc import Callable, Sequence
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from functools import partial
+from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
Outcome = Literal["ok", "429", "5xx", "error", "dead", "skip"]
@@ -126,6 +132,92 @@ class _KeyState:
self.health_ts = now
+class Slots:
+ """``n`` machine-wide in-flight slots: the docs/COST.md §20 knee, enforced across processes.
+
+ One lock file per slot, ``<root>/NN.lock``, held with ``fcntl.flock`` while ONE model call
+ is out. Every process pointed at the same ``root`` draws from ``00 .. n-1``, so the
+ machine never has more calls in flight than the largest ``n`` any of them runs with, and
+ a process with a smaller cap only ever uses its own first ``n`` files. flock locks an
+ open file DESCRIPTION and every take opens its own, so two threads of one process
+ exclude each other exactly as two processes do. The kernel drops the lock when its
+ holder dies — SIGKILL and the OOM killer included — so a dead process never strands a
+ slot: the staleness problem that kept a machine-wide limiter deferred in §23 does not
+ exist for flock (``proc.exclusive`` relies on the same property).
+ """
+
+ #: how long a waiter naps between two sweeps of the files while every slot is busy
+ #: (seconds, jittered x0.5..1.5). A model call takes seconds, so this bounds the extra
+ #: latency a free slot costs a waiter, and a sweep is n non-blocking flock calls.
+ POLL_S = 0.05
+
+ def __init__(self, n: int, root: Path | str) -> None:
+ if n < 1:
+ raise ValueError(f"Slots needs n >= 1, got {n}")
+ self.n = int(n)
+ self.root = Path(root)
+ self.root.mkdir(parents=True, exist_ok=True)
+
+ def _path(self, i: int) -> Path:
+ return self.root / f"{i:02d}.lock"
+
+ def try_take(self) -> int | None:
+ """A held slot (its file descriptor), or ``None`` when all ``n`` are busy — never
+ waits. The sweep starts at a random slot, so a process with a small cap is not
+ starved by a big one that always fills the low numbers first."""
+ start = random.randrange(self.n)
+ for step in range(self.n):
+ fd = os.open(self._path((start + step) % self.n), os.O_RDWR | os.O_CREAT, 0o666)
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ os.close(fd)
+ continue
+ except BaseException:
+ os.close(fd)
+ raise
+ return fd
+ return None
+
+ def take(self, timeout_s: float | None) -> int:
+ """Wait for a slot, at most ``timeout_s`` (``None`` = forever); its descriptor.
+ Raises ``KeyPoolExhausted`` once the wait is over."""
+ deadline = None if timeout_s is None else time.monotonic() + timeout_s
+ while (fd := self.try_take()) is None:
+ left = None if deadline is None else deadline - time.monotonic()
+ if left is not None and left <= 0:
+ raise KeyPoolExhausted(f"all {self.n} in-flight slots in {self.root} busy; waited {timeout_s}s")
+ nap = random.uniform(0.5, 1.5) * self.POLL_S
+ time.sleep(nap if left is None else min(nap, left))
+ return fd
+
+ @staticmethod
+ def give(fd: int) -> None:
+ """Hand a slot back. LOCK_UN first: a descriptor a forked child inherited must not
+ keep the slot held after this process is done with it."""
+ try:
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ finally:
+ os.close(fd)
+
+ def busy(self) -> int:
+ """How many slots somebody holds right now, machine-wide (``3dcode doctor``). A
+ shared probe per file, released at once: it never takes a slot from a caller."""
+ n = 0
+ for i in range(self.n):
+ try:
+ fd = os.open(self._path(i), os.O_RDONLY)
+ except OSError:
+ continue # never created, so never taken
+ try:
+ fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
+ except BlockingIOError:
+ n += 1
+ finally:
+ os.close(fd)
+ return n
+
+
class KeyPool:
"""Round-robin key pool with cooldowns and an in-flight ceiling. See module docstring."""
@@ -134,6 +226,7 @@ class KeyPool:
keys: list[str] | tuple[str, ...],
*,
max_in_flight: int = 0,
+ slots_dir: Path | str | None = None,
cooldown_s: float = MAX_WAIT_S,
dead_cooldown_s: float = 3600.0,
min_health: float = 0.3,
@@ -152,11 +245,15 @@ class KeyPool:
self._rr = 0
self._in_flight = 0
self._peak_in_flight = 0
- # Process-wide ceiling on concurrent model calls, independent of the caller's
+ # Machine-wide ceiling on concurrent model calls, independent of the caller's
# thread pools: blender/node/chrome workers are CPU-bound and sized by cores,
# while this is sized by the provider (docs/COST.md Part III). 0 = unlimited.
self._max_in_flight = int(max_in_flight or 0)
- self._slots = threading.BoundedSemaphore(self._max_in_flight) if self._max_in_flight else None
+ if self._max_in_flight and slots_dir is None:
+ raise ValueError("max_in_flight needs slots_dir: the slots are lock files every process shares")
+ #: the machine-wide slots (``None`` when uncapped); ``3dcode doctor`` reads it
+ self.slots = Slots(self._max_in_flight, slots_dir) if self._max_in_flight else None
+ self._held: list[int] = [] # slot descriptors of this process's in-flight calls
now = clock()
self._states = [_KeyState(key=k, health_ts=now) for k in uniq]
self._by_key = {s.key: s for s in self._states}
@@ -180,25 +277,25 @@ class KeyPool:
Raises ``KeyPoolExhausted`` at once when no key can become available before
the deadline (e.g. every key is dead) — availability only moves later.
- When ``max_in_flight`` is set the call also waits for a free concurrency slot;
+ When ``max_in_flight`` is set the call also waits for a free machine-wide slot;
:meth:`release` hands it back. ``timeout_s`` bounds the slot wait AND the key
wait together (``None`` = wait forever): the slot wait used to be unbounded, so
a caller 20 s from its deadline could sit on the semaphore for minutes."""
- if self._slots is not None:
+ slot = None
+ if self.slots is not None:
t0 = self._clock()
- if not self._slots.acquire(timeout=timeout_s):
- raise KeyPoolExhausted(
- f"all {self._max_in_flight} in-flight slots busy; waited {timeout_s}s"
- )
+ slot = self.slots.take(timeout_s)
if timeout_s is not None:
# the slot wait spent part of the budget; the key wait gets the rest
timeout_s = max(0.0, timeout_s - (self._clock() - t0))
try:
- return self._acquire_key(exclude, timeout_s)
+ key = self._acquire_key(exclude, timeout_s)
except BaseException:
- if self._slots is not None:
- self._slots.release()
+ if slot is not None:
+ Slots.give(slot)
raise
+ self._hold(slot)
+ return key
def try_acquire(self, *, exclude: set[str] | frozenset[str] | None = None) -> str | None:
""":meth:`acquire` that never waits: a key usable *right now* (and a free
@@ -208,18 +305,39 @@ class KeyPool:
primary request is already in flight, so a partner that is not free at once
is not worth waiting for. A returned key holds a slot like any other and
must be :meth:`release`-d."""
- if self._slots is not None and not self._slots.acquire(blocking=False):
+ slot = None
+ if self.slots is not None and (slot := self.slots.try_take()) is None:
return None
try:
- return self._acquire_key(exclude, 0.0)
- except KeyPoolExhausted:
- if self._slots is not None:
- self._slots.release()
- return None
- except BaseException:
- if self._slots is not None:
- self._slots.release()
+ key = self._acquire_key(exclude, 0.0)
+ except BaseException as exc:
+ if slot is not None:
+ Slots.give(slot)
+ if isinstance(exc, KeyPoolExhausted):
+ return None
raise
+ self._hold(slot)
+ return key
+
+ def session_key(
+ self,
+ *,
+ exclude: set[str] | frozenset[str] | None = None,
+ timeout_s: float | None = ACQUIRE_TIMEOUT_S,
+ ) -> str:
+ """A key for a session that makes its own calls — a vendor CLI: rotation, 429
+ cooldowns and dead-key benching exactly like :meth:`acquire`, but no in-flight slot
+ and nothing to release. A session is minutes of agent time; a machine-wide slot
+ held that long would let a few dozen sessions starve every planner and judge call
+ on the box (docs/COST.md §23)."""
+ return self._acquire_key(exclude, timeout_s)
+
+ def _hold(self, slot: int | None) -> None:
+ with self._lock:
+ self._in_flight += 1
+ self._peak_in_flight = max(self._peak_in_flight, self._in_flight)
+ if slot is not None:
+ self._held.append(slot)
def _acquire_key(self, exclude: set[str] | frozenset[str] | None, timeout_s: float | None) -> str:
deadline = None if timeout_s is None else self._clock() + timeout_s
@@ -229,8 +347,6 @@ class KeyPool:
chosen = self._pick(now, exclude or ())
if chosen is not None:
chosen.n_acquired += 1
- self._in_flight += 1
- self._peak_in_flight = max(self._peak_in_flight, self._in_flight)
return chosen.key
soonest = min(
(max(now, s.cooldown_until) for s in self._states if s.key not in (exclude or ())),
@@ -251,16 +367,18 @@ class KeyPool:
def release(self) -> None:
"""Mark one :meth:`acquire`-d call finished (call it in a ``finally``).
- Frees the in-flight gauge and the ``max_in_flight`` slot; outcome
- accounting is :meth:`report`, which may legitimately be called more than
- once for one call (a key that looked dead is reported again once a
- sibling proves the request fine). A stray ``release`` is a no-op."""
+ Frees the in-flight gauge and one of this process's slots (they are
+ interchangeable: the count is what the machine sees); outcome accounting is
+ :meth:`report`, which may legitimately be called more than once for one call (a
+ key that looked dead is reported again once a sibling proves the request fine).
+ A stray ``release`` is a no-op."""
with self._lock:
if self._in_flight <= 0:
return
self._in_flight -= 1
- if self._slots is not None:
- self._slots.release()
+ slot = self._held.pop() if self._held else None
+ if slot is not None:
+ Slots.give(slot)
def report(self, key: str, outcome: Outcome, *, retry_after_s: float | None = None) -> None:
"""Feed back the result of a call made with ``key`` (``retry_after_s``: a 429's
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index de03adf9..cb11b6d0 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -102,8 +102,9 @@ codeverse3d/
request/response shapes, dead-key + free 429 rotation, the image model);
anthropic.py openai.py (each with its own request/response shapes);
retry.py (the scheduling machine: KeyPool with outcomes ok | 429 | 5xx |
- error | dead | skip and the max_in_flight cap — no RPM/TPM buckets since
- 2026-09-22, docs/COST.md §19 — and rotate_with_retries, the one retry loop, which
+ error | dead | skip and the max_in_flight cap as machine-wide flock'd
+ slots (Slots, docs/COST.md §23) — no RPM/TPM buckets since 2026-09-22,
+ docs/COST.md §19 — and rotate_with_retries, the one retry loop, which
the SDK adapters run over a one-key pool; bounded by max_total_s ≤
RETRY_DEADLINE_S with MAX_WAIT_S ≤ 3 s single waits); pricing.py
(version-suffix-only fallback), health.py (preflight
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
index 18962022..16b15a45 100644
--- a/harness/docs/COST.md
+++ b/harness/docs/COST.md
@@ -974,8 +974,9 @@ renderer's own tail, not parallelism. Renders are treated as "1.5 – 3 s typic
minutes-long tail" and the subprocess pools are sized from the clean build number.
**64 model calls vs 16 subprocesses is 4x apart, so the two are capped separately:**
-`Settings.rate.max_in_flight` is a semaphore inside `KeyPool` (network-bound, provider-
-sized), `Settings.limits.max_parallel_*` size the thread pools (CPU-bound, core-sized).
+`Settings.rate.max_in_flight` is the number of machine-wide in-flight slots `KeyPool` takes
+(network-bound, provider-sized — §23), `Settings.limits.max_parallel_*` size the thread pools
+(CPU-bound, core-sized).
### Defaults changed, each from a number above
@@ -1095,19 +1096,7 @@ billing points, not on a timer.** Closing it properly means giving the runner a
reference to the guard and checking at stage boundaries; not done here, because it is
plumbing through several layers and deserves its own measured change.
-## 23. The key pool is per-PROCESS, so N batteries multiply the quota by N
-
-> **Count processes with `pool_budget()`, never with a hand-rolled `pgrep`.** A gate like
-> `pgrep -af 'bin/3dcode make' | grep -c 'codex:'` **counts itself**: the pattern text is in
-> the checking shell's own command line, so it sees phantom runs. Measured 2026-08-25 on an
-> idle box — zero `3dcode` processes running, the naive gate returned **3**, and even the
-> bracket trick `pgrep -f '[b]in/3dcode make'` returned **2**, because the wrapper shell's
-> argv also carries the string. Used in `while [ $(gate) -ge 3 ]; do sleep 60; done` that
-> blocks forever on nothing. `codeverse3d.models.health.pool_budget()` reads `/proc`,
-> excludes its own pid and does the in-flight arithmetic:
-> ```
-> python3 -c "from codeverse3d.models.health import pool_budget; print(pool_budget())"
-> ```
+## 23. The key pool was per-PROCESS, so N batteries multiplied the quota by N — the slots are machine-wide now
§20 measured the concurrency knee at 64 in-flight and shipped it as the default. That
number was measured with **one process and nothing else running**, and the limiter it
@@ -1152,34 +1141,42 @@ Three consequences:
latency and its siblings took the capacity it freed. The gate was measured in a
setting where it could not win. Its negative result stands for the configuration
tested and should NOT be read as "back-pressure does not help".
-3. **Operational rule until a cross-process limiter exists**: keep the SUM of
- `max_in_flight` across every harness process on the machine at or below the measured
- knee (64). One battery at 64, or N batteries at `64 / N` each via
- `C3D_MAX_IN_FLIGHT=<n>` (`C3D_RATE__MAX_IN_FLIGHT` is the same knob; the flat name was
- read by nothing until 2026-08-24 — three launches that "set" it ran at 64).
- `codeverse3d.models.health.pool_budget()` reads every sibling's cap from `/proc/<pid>/environ`
- and reports used / headroom; `3dcode doctor`'s `pool sharing` row prints it, and
- `eval/bench/ab_plan.py` refuses to start only when its own need does not FIT the headroom.
- The first version of this rule counted *processes* and made every agent wait for an
- empty machine — which stalled an entire A/B wave behind two batteries that were
- themselves parked. A budget, not a head-count.
-4. **The accounting only works if every process is visible to it.** `pool_budget()`
- matches on argv, and until 2026-08-24 it matched only the *script path* spelling
- (`python eval/bench/ab_plan.py`). A live eight-prompt A/B launched as
- `python -m bench.ab_plan` — driver plus two 16-in-flight cell children — was therefore
- invisible: the budget read `16/64, headroom 48` on a machine already at 48, and the
- next agent to check it would have launched 32 more and taken the machine to 80. Both
- spellings of every entry point are now listed (`health._MODULES` / `_SCRIPTS`). The
- mirror-image error is just as bad: an `ab_plan` *driver* spends its budget only through
- capped children, and it sets no cap on itself, so charging it too would book the 64
- default on top of the children and stall every sibling — `_is_delegating_driver` skips
- it. Whenever an entry point is added or renamed, update both lists.
-
-The real fix is a machine-wide limiter — a file-locked token bucket under
-`~/.cache/codeverse3d/` that every process shares — so the quota is enforced where it
-actually lives. Not built here: it needs crash/staleness handling and its own A/B, and
-it should be measured against the operational rule above rather than assumed better.
-
+3. **The operational rule until 2026-09-22** was to keep the SUM of `max_in_flight` across
+ every harness process at or below the knee (64), with `health.pool_budget()` reading each
+ sibling's cap out of `/proc/<pid>/environ`. It was advice — `eval/bench/ab_plan.py`
+ refused to start on it, `3dcode make` and `bench run` never looked — and it guessed
+ siblings from argv against a hard-coded list of eval entry points, which missed
+ `python -m bench.ab_plan` for a day, missed every pip console script for longer, had
+ to learn not to charge an ab_plan driver for its children, and could not see a process
+ whose cap was unparsable.
+
+**Machine-wide slots (2026-09-22).** `max_in_flight` is now N lock files,
+`<cache_dir>/slots/gemini/00.lock …`, and a harness API call holds one with
+`fcntl.flock(LOCK_EX | LOCK_NB)` for exactly as long as it is out (`models.retry.Slots`,
+taken inside `KeyPool.acquire` / `try_acquire`, handed back by `release`). Every process
+draws from the same files, starting its sweep at a random slot, so the machine never has
+more calls in flight than the largest N any process runs with, and a process with a smaller
+N only ever uses its own first N. A process that finds every slot busy waits inside the
+call's own budget; nothing refuses to start any more, and the `/proc` scan, its entry-point
+lists and ab_plan's admission check are gone. ab_plan still pins both children to its
+`--max-in-flight` (16 by default) — the two arms now share those 16 slots.
+
+What a slot guards is one harness API call — planner, judge, caption, texture image,
+single-shot generation — the unit §20 measured. A vendor CLI session takes its key from the
+same pool (rotation, cooldowns, the dead-key bench) but no slot: a session is minutes of
+agent time, and 64 of them holding slots would starve every judge and planner call on the
+box. Their concurrency stays bounded per process by `Limits.max_parallel_agents`.
+
+The deferral this section used to end on was about staleness — a crashed holder stranding
+its share of a file-locked bucket. flock has none: the kernel drops the lock when the
+holder's descriptors close, SIGKILL and the OOM killer included (`proc.exclusive` relies on
+the same property). `tests/models/test_slots.py`, six runs on this box: 8 processes × 6 holds
+× 0.15 s on 4 slots peaked at exactly 4 in flight (mean 3.84 – 3.93, wall 1.83 – 1.87 s
+against a 1.80 s floor); caps of 2 and 4 in one directory peaked at 4 together and 2 among
+the N=2 processes; a slot held by a SIGKILLed process came back 37 – 70 ms after the kill
+(one 50 ms poll); 12 threads of one process on 3 slots peaked at exactly 3; with every slot
+held elsewhere a waiter gave up at 0.000 s and 0.300 s for deadlines of 0 and 0.3 s.
+`3dcode doctor` prints the `in-flight slots` row: how many are busy machine-wide right now.
## 24. A preflight probe must look like the work it is guarding
diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.md
index 41756353..cd2c8eae 100644
--- a/harness/docs/INSTALL.md
+++ b/harness/docs/INSTALL.md
@@ -497,7 +497,7 @@ that the keys work end to end):
| `git` | FAIL | git missing | install git — run workspaces are git repos |
| `mcp` | WARN | `mcp` package or the server module missing | `pip install -e 'harness[mcp]'`; only affects the agentic CLI backends |
| `gemini live call` (`--live`) | FAIL | key rejected / no network | check the key value and outbound access; a `503 … high demand` is transient, not an install problem |
-| `pool sharing` | WARN | this process's configured concurrency does not fit beside sibling harness processes | wait for the siblings or set `C3D_MAX_IN_FLIGHT` to the headroom printed in the row |
+| `in-flight slots` | WARN | every machine-wide slot is held right now (`busy n/n`), or `max_in_flight=0` switched the cap off | busy: other harness processes are mid-call and new calls wait for a slot (docs/COST.md §23) — nothing to fix unless it stays full; a slot is held only while a call is out and a killed process frees its slots at once. Off: unset `C3D_MAX_IN_FLIGHT` |
| `gemini pool` (`--live`) | WARN | a key is benched as dead | that key 401/403'd; rotate or remove it — the pool re-probes it after an hour. The row also shows in-flight and this process's 429/5xx counts |
| `skills switch` | WARN | skills are disabled (`C3D_SKILLS=0`) | skills are on by default since 2026-09-22; unset `C3D_SKILLS` unless this is an A/B control arm |
| `skills library` | WARN / FAIL | no bundles were found, or one or more bundles are invalid | use a full checkout and validate the named bundle under `codeverse3d/skills/<name>/` |
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 375cb9c2..f0acb1b6 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -67,9 +67,11 @@ resp = m.generate(ChatRequest(messages=[...], system=..., response_schema=..., t
# resp.raw["key"] = "…ab12" (the key that answered), resp.raw["attempts"] = round-trips issued (hedged siblings included)
resp.parsed / resp.text / resp.usage # Usage always has cost_usd (models.pricing)
from codeverse3d.models.retry import KeyPool, KeyPoolExhausted
-KeyPool(keys, *, max_in_flight=0, cooldown_s=3, dead_cooldown_s=3600)
-pool.acquire(*, exclude=None, timeout_s=120) -> key # raises immediately when every key is dead/cooling past the deadline
+KeyPool(keys, *, max_in_flight=0, slots_dir=None, cooldown_s=3, dead_cooldown_s=3600) # a cap needs slots_dir:
+ # the slots are flock'd files every process shares (Slots(n, root): try_take / take(timeout) / give / busy)
+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.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
diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.md
index e1b4b87e..0c62ad64 100644
--- a/harness/docs/RUNBOOK.md
+++ b/harness/docs/RUNBOOK.md
@@ -417,6 +417,8 @@ Rules:
3. After landing anything, check every driver's `results.jsonl` for `ImportError` rows and redo
them from a **fresh** driver with `--redo-status error` (the old driver's own modules are
stale too).
-4. Count harness processes with `codeverse3d.models.health.pool_budget()`, never `pgrep | grep`
- (it counts its own shell — measured: 3 phantoms on an idle box); kill by PID, never by
- pattern (13 unrelated runs died to one `pkill -f "3dcode make"`).
+4. You do not need to count harness processes to protect the provider: the in-flight slots are
+ machine-wide (`docs/COST.md` §23; `3dcode doctor` prints how many are busy). If you list
+ processes anyway, never with `pgrep | grep` (it counts its own shell — measured: 3 phantoms
+ on an idle box); kill by PID, never by pattern (13 unrelated runs died to one
+ `pkill -f "3dcode make"`).
diff --git a/harness/tests/agents/test_gemini_cli.py b/harness/tests/agents/test_gemini_cli.py
index a8fa4de0..7c93d166 100644
--- a/harness/tests/agents/test_gemini_cli.py
+++ b/harness/tests/agents/test_gemini_cli.py
@@ -184,7 +184,7 @@ def test_pool_exhausted_before_first_attempt_is_a_budget_result(tmp_ws: Workspac
from codeverse3d.models.retry import KeyPoolExhausted
class Dead:
- def acquire(self, **kw):
+ def session_key(self, **kw):
raise KeyPoolExhausted("all 2 keys throttled; waited 120s")
def report(self, *a, **k):
@@ -195,17 +195,24 @@ def test_pool_exhausted_before_first_attempt_is_a_budget_result(tmp_ws: Workspac
assert not res.ok and res.exit_reason == "budget" and "exhausted" in res.errors[0]
-def test_a_raising_invoke_gives_its_pool_slot_back(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
- """The pool is process-wide: a slot leaked here is gone for every later session."""
+def test_a_cli_session_holds_no_in_flight_slot(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
+ """The slots are machine-wide and a session is minutes long: one held per session would
+ let a few dozen sessions starve every planner and judge call on the box. The session
+ takes its KEY from the shared pool (rotation, cooldowns) and nothing else — so nothing
+ can leak either, even when invoke raises."""
from codeverse3d.agents import backends as gc
+ pool = gc._key_pool(get_settings().gemini_api_keys) # noqa: SLF001
+ seen: list[int] = []
+
def boom(*a, **k):
+ seen.append(pool.stats()["in_flight"])
raise OSError("cannot spawn")
monkeypatch.setattr(gc, "invoke", boom)
with pytest.raises(OSError, match="cannot spawn"):
agent.run(_job(tmp_ws))
- assert gc._key_pool(get_settings().gemini_api_keys).stats()["in_flight"] == 0 # noqa: SLF001
+ assert seen == [0] and pool.stats()["in_flight"] == 0
def test_timeout_is_reported(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
diff --git a/harness/tests/install/test_docs.py b/harness/tests/install/test_docs.py
index 4376043d..ba9fbf0b 100644
--- a/harness/tests/install/test_docs.py
+++ b/harness/tests/install/test_docs.py
@@ -229,8 +229,6 @@ def test_doctor_checks_every_module_of_every_optional_extra(monkeypatch) -> None
def test_doctor_rows_have_troubleshooting_entries(monkeypatch) -> None:
"""Run real checks under deterministic stand-ins; require every row in the fix table."""
from codeverse3d import doctor as doctor_mod
- from codeverse3d.config import Settings
- from codeverse3d.models.health import PoolBudget
from codeverse3d.proc import ProcResult
settings = SimpleNamespace(
@@ -247,7 +245,11 @@ def test_doctor_rows_have_troubleshooting_entries(monkeypatch) -> None:
"codeverse3d.proc.run_subprocess",
lambda *args, **kwargs: ProcResult(0, '{"gpu": true, "renderer": "fake"}', "", False, 1),
)
- monkeypatch.setattr("codeverse3d.models.health.pool_budget", lambda: PoolBudget(1, 64))
+ busy = SimpleNamespace(n=1, root="/fake/slots", busy=lambda: 1) # saturated: the WARN wording
+ monkeypatch.setattr("codeverse3d.models.gemini.shared_pool",
+ lambda keys, **kw: SimpleNamespace(slots=busy, stats=lambda: {
+ "n_keys": 1, "in_flight": 0, "peak_in_flight": 0, "acquired": 0, "ok": 0,
+ "429": 0, "5xx": 0, "n_dead": 0, "n_cooling": 0}))
monkeypatch.setattr(
"codeverse3d.models.get_chat_model",
lambda model: SimpleNamespace(generate=lambda request: SimpleNamespace(
@@ -266,11 +268,6 @@ def test_doctor_rows_have_troubleshooting_entries(monkeypatch) -> None:
)
rows += doctor_mod.check_node() # the alternate row when runtime_js cannot resolve
- pool_detail = next(detail for name, _, detail in rows if name == "pool sharing")
- mentioned_settings = set(re.findall(r"\b(C3D_[A-Z0-9_]+)=", pool_detail))
- assert mentioned_settings and mentioned_settings <= set(Settings._FLAT_ALIASES), (
- f"doctor recommends setting unknown variables: {sorted(mentioned_settings - set(Settings._FLAT_ALIASES))}")
-
troubleshooting = INSTALL.read_text().split("### Troubleshooting table", 1)[1].split("\n---", 1)[0]
documented = {
name
diff --git a/harness/tests/models/test_health.py b/harness/tests/models/test_health.py
index 0aa484cf..8db3a30e 100644
--- a/harness/tests/models/test_health.py
+++ b/harness/tests/models/test_health.py
@@ -56,34 +56,6 @@ def test_probe_never_raises_when_every_call_fails(monkeypatch):
assert h.reasons and "provider on fire" in h.reasons[0]
-# --------------------------------------------------------------------------- siblings
-def test_sibling_detection_matches_arguments_not_the_repo_path():
- from codeverse3d.models.health import _is_harness_argv
-
- harness_commands = (
- ["python", "-m", "codeverse3d.cli.main", "bench", "run"],
- ["python", "bench/compare_backends.py", "--arms", "x"],
- ["/home/u/.local/bin/3dcode", "doctor"],
- ["/usr/bin/python3", "/x/y/run_bench.py"],
- ["/home/u/miniconda3/bin/python3.13", "/home/u/miniconda3/bin/3dcode", "make"],
- ["/usr/bin/python3", "/usr/local/bin/3dcodeverse", "doctor"],
- ["python", "-m", "bench.ab_plan", "--prompts", "x"],
- ["python", "-m", "bench.compare_backends", "--arms", "x"],
- ["python", "-m", "bench.run_bench", "b.yaml"],
- )
- other_commands = (
- ["/bin/bash", "-c", "cd /home/u/3dcodeverse/harness && ls"],
- ["vim", "/home/u/3dcodeverse/harness/codeverse3d/cli/main.py"],
- ["python", "-m", "pytest", "tests/"],
- [],
- ["ls", "-la", "/home/u/3dcodeverse"],
- ["tar", "czf", "b.tgz", "/home/u/.local/bin/3dcode"],
- ["python", "-c", "print(1)", "/home/u/.local/bin/3dcode"],
- )
- assert all(map(_is_harness_argv, harness_commands))
- assert not any(map(_is_harness_argv, other_commands))
-
-
def test_probe_model_treats_a_503_as_final(monkeypatch):
""" "No retries" must include the storm branch. rotate_with_retries' capacity-storm
branch does NOT consume max_attempts, so max_attempts=1 alone still retried a 503
@@ -113,149 +85,3 @@ def test_probe_model_treats_a_503_as_final(monkeypatch):
m.generate(ChatRequest(messages=[ChatMessage.user("pong")], max_output_tokens=8))
assert captured.get("storm_attempts") == 0, captured.keys()
assert captured.get("max_attempts") == 1
-
-
-# --------------------------------------------------------------------------- pool budget
-def _fake_proc(monkeypatch, procs):
- """procs: {pid: (argv list, env dict)} — a fake /proc for pool_budget()."""
- import os
- from pathlib import Path
-
- import codeverse3d.models.health as health
-
- me = os.getpid()
-
- class Entry:
- def __init__(self, pid):
- self.name = str(pid)
- self._pid = pid
-
- def __truediv__(self, leaf):
- argv, env = procs[self._pid]
- data = {
- "cmdline": "\0".join(argv).encode() + b"\0",
- "environ": b"\0".join(f"{k}={v}".encode() for k, v in env.items()),
- }[leaf]
- return _Blob(data)
-
- class _Blob:
- def __init__(self, data):
- self._data = data
-
- def read_bytes(self):
- return self._data
-
- monkeypatch.setattr(Path, "iterdir", lambda self: [Entry(p) for p in procs if p != me])
- return health
-
-
-def test_pool_budget_accounts_for_caps_defaults_and_unlimited_siblings(monkeypatch):
- health = _fake_proc(
- monkeypatch,
- {
- 101: (
- ["python", "-m", "codeverse3d.cli.main", "bench", "run"],
- {"C3D_MAX_IN_FLIGHT": "16"},
- ),
- 102: (
- ["python", "bench/compare_backends.py", "--arms", "x"],
- {"C3D_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)
-
- health = _fake_proc(
- monkeypatch, {201: (["python", "-m", "codeverse3d.cli.main", "make", "a chair"], {})}
- )
- pb = health.pool_budget()
- assert pb.used == 64 and pb.headroom == 0 and not pb.fits(1)
-
- health = _fake_proc(
- monkeypatch,
- {
- 401: (
- ["python", "-m", "codeverse3d.cli.main", "bench", "run"],
- {"C3D_MAX_IN_FLIGHT": "0"},
- ),
- },
- )
- pb = health.pool_budget()
- assert (pb.siblings, pb.used, pb.headroom) == (1, 64, 0)
-
- health = _fake_proc(
- monkeypatch,
- {
- 501: (
- ["python", "-m", "codeverse3d.cli.main", "bench", "run"],
- {"C3D_MAX_IN_FLIGHT": "16"},
- ),
- 502: (["python", "-m", "bench.compare_backends"], {"C3D_MAX_IN_FLIGHT": "-8"}),
- },
- )
- pb = health.pool_budget()
- assert pb.used == 16 + health.POOL_KNEE and pb.headroom == 0
-
-
-def test_an_ab_plan_driver_is_not_charged_for_its_children(monkeypatch):
- """The driver spawns one capped cell child per arm and makes no model calls of its own.
-
- It sets no cap on itself (``--max-in-flight`` is the CHILD cap), so charging it would
- book the 64 default — the whole knee — on top of the children that actually hold the
- traffic, 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"],
- {"C3D_MAX_IN_FLIGHT": "16"},
- ),
- 303: (
- ["python", "-m", "bench.ab_plan", "cell", "--arm", "variant"],
- {"C3D_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"],
- {"C3D_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"], {"C3D_MAX_IN_FLIGHT": "16"})},
- )
- assert health.pool_budget().used == 16
-
-
-def test_pool_budget_never_raises(monkeypatch):
- from pathlib import Path
-
- import codeverse3d.models.health as health
-
- def boom(_self):
- raise OSError("no /proc")
-
- monkeypatch.setattr(Path, "iterdir", boom)
- pb = health.pool_budget()
- assert pb.siblings == 0 and pb.used == 0 and pb.fits(64)
diff --git a/harness/tests/models/test_keypool.py b/harness/tests/models/test_keypool.py
index 8a0d8967..f09f02a6 100644
--- a/harness/tests/models/test_keypool.py
+++ b/harness/tests/models/test_keypool.py
@@ -134,11 +134,11 @@ def test_all_keys_dead_raises_immediately_instead_of_waiting_out_the_timeout():
assert clock.t == t0 # no pointless 120 s wait: availability only moves later
-def test_try_acquire_never_waits_for_a_key_or_a_slot():
+def test_try_acquire_never_waits_for_a_key_or_a_slot(tmp_path):
"""The extra keys of a hedged retry (``rotate_with_retries(hedge=...)``) come from
``try_acquire``: a key that is usable right now, else None — never a wait."""
never = lambda s: (_ for _ in ()).throw(AssertionError(f"try_acquire slept {s}s")) # noqa: E731
- pool = KeyPool(["k1", "k2"], max_in_flight=2, cooldown_s=30, sleep=never)
+ pool = KeyPool(["k1", "k2"], max_in_flight=2, slots_dir=tmp_path, cooldown_s=30, sleep=never)
a = pool.try_acquire()
assert a == "k1" and pool.stats()["in_flight"] == 1
assert pool.try_acquire(exclude={a}) == "k2"
@@ -152,10 +152,10 @@ def test_try_acquire_never_waits_for_a_key_or_a_slot():
assert pool.stats()["in_flight"] == 0, "a refused try_acquire holds nothing"
-def test_the_in_flight_slot_wait_is_bounded_by_timeout():
- """acquire()'s max_in_flight semaphore used to be an unbounded wait; the same
- timeout budget now bounds it and raises the pool's own error shape."""
- pool = KeyPool(["a"], max_in_flight=1)
+def test_the_in_flight_slot_wait_is_bounded_by_timeout(tmp_path):
+ """acquire()'s max_in_flight wait used to be unbounded; the same timeout budget now
+ bounds it and raises the pool's own error shape."""
+ pool = KeyPool(["a"], max_in_flight=1, slots_dir=tmp_path)
pool.acquire()
t0 = time.monotonic()
with pytest.raises(KeyPoolExhausted):
@@ -191,8 +191,8 @@ def test_in_flight_gauge_tracks_acquire_and_release():
assert pool.stats()["in_flight"] == 0
-def test_max_in_flight_blocks_the_third_caller():
- pool = KeyPool(["a", "b", "c"], max_in_flight=2)
+def test_max_in_flight_blocks_the_third_caller(tmp_path):
+ pool = KeyPool(["a", "b", "c"], max_in_flight=2, slots_dir=tmp_path)
pool.acquire()
pool.acquire()
started = threading.Event()
@@ -212,10 +212,26 @@ def test_max_in_flight_blocks_the_third_caller():
t.join(2)
-def test_a_failed_acquire_gives_its_slot_back():
+def test_a_failed_acquire_gives_its_slot_back(tmp_path):
"""KeyPoolExhausted must not leak a concurrency slot."""
- pool = KeyPool(["a"], max_in_flight=1)
+ pool = KeyPool(["a"], max_in_flight=1, slots_dir=tmp_path)
for _ in range(3):
with pytest.raises(KeyPoolExhausted):
pool.acquire(exclude={"a"}, timeout_s=0.0)
assert pool.acquire(timeout_s=0.0) == "a" # the slot is still free
+
+
+def test_a_capped_pool_names_its_slot_directory_and_a_session_key_takes_no_slot(tmp_path):
+ """The slots are machine-wide lock files, so a cap without a directory is refused rather
+ than silently becoming a per-process cap; a vendor CLI session picks a key (rotation and
+ cooldowns included) but holds no slot and has nothing to release."""
+ with pytest.raises(ValueError, match="slots_dir"):
+ KeyPool(["a"], max_in_flight=1)
+ pool = KeyPool(["a", "b"], max_in_flight=1, slots_dir=tmp_path)
+ assert pool.acquire(timeout_s=0.0) == "a"
+ assert pool.session_key(timeout_s=0.0) == "b", "the only slot is held, a session still gets a key"
+ pool.report("a", "429")
+ assert pool.session_key(timeout_s=0.0) == "b", "and it skips a cooling key like acquire does"
+ assert pool.stats()["in_flight"] == 1 and pool.slots.busy() == 1
+ pool.release()
+ assert pool.stats()["in_flight"] == 0 and pool.slots.busy() == 0
diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.py
index f0bd4294..179b7d37 100644
--- a/harness/tests/models/test_retry.py
+++ b/harness/tests/models/test_retry.py
@@ -390,9 +390,9 @@ def _wait_idle(pool, timeout: float = 5.0) -> None:
assert pool.stats()["in_flight"] == 0
-def test_after_the_first_503_the_next_attempt_is_hedged_and_the_first_success_wins():
+def test_after_the_first_503_the_next_attempt_is_hedged_and_the_first_success_wins(tmp_path):
"""After a 503, fresh keys race and the first success wins."""
- pool = KeyPool(["k1", "k2", "k3", "k4"], max_in_flight=8)
+ pool = KeyPool(["k1", "k2", "k3", "k4"], max_in_flight=8, slots_dir=tmp_path)
release_k2 = threading.Event()
lock = threading.Lock()
calls: list[str] = []
@@ -462,7 +462,7 @@ def test_a_loser_that_succeeds_later_is_discarded_but_reported_to_its_key():
assert pool._by_key["k2"].n_ok == 1 and pool._by_key["k3"].n_ok == 1 # noqa: SLF001
-def test_hedge_1_disables_and_a_full_pool_of_slots_degrades_to_one_key():
+def test_hedge_1_disables_and_a_full_pool_of_slots_degrades_to_one_key(tmp_path):
lock = threading.Lock()
def make_call():
@@ -490,12 +490,12 @@ def test_hedge_1_disables_and_a_full_pool_of_slots_degrades_to_one_key():
)
assert stats["hedged"] == 0 and stats["attempts"] == 4
# max_in_flight=1: the primary holds the only slot, so a partner is never waited for
- pool = _pool(3, max_in_flight=1)
+ pool = _pool(3, max_in_flight=1, slots_dir=tmp_path / "one")
stats = {}
_rotate(pool, make_call(), max_attempts=3, storm_attempts=10, storm_max_delay=0.0, stats=stats)
assert stats["hedged"] == 0 and stats["attempts"] == 4 and pool.stats()["peak_in_flight"] == 1
# max_in_flight=2: a hedged attempt holds both slots
- pool = _pool(3, max_in_flight=2)
+ pool = _pool(3, max_in_flight=2, slots_dir=tmp_path / "two")
stats = {}
_rotate(pool, make_call(), max_attempts=3, storm_attempts=10, storm_max_delay=0.0, stats=stats)
_wait_idle(pool)
diff --git a/harness/tests/models/test_slots.py b/harness/tests/models/test_slots.py
new file mode 100644
index 00000000..729aa9f7
--- /dev/null
+++ b/harness/tests/models/test_slots.py
@@ -0,0 +1,208 @@
+"""The machine-wide in-flight slots (``retry.Slots``): flock'd lock files every process shares.
+
+Real processes, real threads, real clocks — the owner asked for the file lock to be tested,
+not assumed. Every test measures with ``time.monotonic`` (CLOCK_MONOTONIC is one clock for
+the whole machine on Linux) and prints what it measured (``pytest -s`` shows it).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import signal
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+from codeverse3d.models.retry import KeyPoolExhausted, Slots
+
+HARNESS = Path(__file__).resolve().parents[2]
+
+#: a child that takes a slot ``holds`` times for ``hold_s`` each, after a "go" on stdin,
+#: and prints one JSON line per hold: [monotonic taken, monotonic about to give]
+_CONTENDER = """
+import json, sys, time
+from codeverse3d.models.retry import Slots
+root, n, holds, hold_s = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), float(sys.argv[4])
+slots = Slots(n, root)
+print("ready", flush=True)
+sys.stdin.readline()
+for _ in range(holds):
+ fd = slots.take(30.0)
+ t0 = time.monotonic()
+ time.sleep(hold_s)
+ t1 = time.monotonic()
+ Slots.give(fd)
+ print(json.dumps([t0, t1]), flush=True)
+"""
+
+#: a child that takes a slot, says so, and then sleeps until it is killed
+_HOLDER = """
+import sys, time
+from codeverse3d.models.retry import Slots
+fd = Slots(int(sys.argv[2]), sys.argv[1]).take(10.0)
+print("held", flush=True)
+time.sleep(600)
+"""
+
+
+def _python(code: str, *args: object) -> subprocess.Popen:
+ """A child on THIS tree's codeverse3d (the editable install may point at another checkout)."""
+ env = {**os.environ, "PYTHONPATH": str(HARNESS)}
+ return subprocess.Popen([sys.executable, "-c", code, *map(str, args)], cwd=HARNESS, env=env,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+
+
+def _peak(intervals: list[tuple[float, float]]) -> int:
+ """Most intervals open at one instant; a give at the same instant as a take is not overlap."""
+ events = sorted([(t0, 1) for t0, _ in intervals] + [(t1, -1) for _, t1 in intervals])
+ peak = cur = 0
+ for _, d in events:
+ cur += d
+ peak = max(peak, cur)
+ return peak
+
+
+def test_n_plus_k_processes_never_have_more_than_n_in_flight(tmp_path: Path) -> None:
+ """(a) 8 processes contend for 4 slots, 6 holds of 0.15 s each: at no instant do more
+ than 4 hold one, all 4 are used, and the whole workload drains at the rate 4 slots allow."""
+ n, k, holds, hold_s = 4, 4, 6, 0.15
+ procs = [_python(_CONTENDER, tmp_path, n, holds, hold_s) for _ in range(n + k)]
+ try:
+ for p in procs:
+ assert p.stdout.readline().strip() == "ready", p.stderr.read()
+ t_go = time.monotonic()
+ for p in procs:
+ p.stdin.write("go\n")
+ p.stdin.flush()
+ intervals: list[tuple[float, float]] = []
+ for p in procs:
+ out, err = p.communicate(timeout=60)
+ assert p.returncode == 0, err
+ intervals += [tuple(json.loads(line)) for line in out.splitlines() if line.startswith("[")]
+ finally:
+ for p in procs:
+ p.kill()
+ wall = max(t1 for _, t1 in intervals) - t_go
+ busy_s = sum(t1 - t0 for t0, t1 in intervals)
+ peak = _peak(intervals)
+ print(f"\n(a) {n + k} processes x {holds} holds x {hold_s}s on {n} slots: peak {peak} in flight, "
+ f"mean {busy_s / wall:.2f}, wall {wall:.2f}s (floor {(n + k) * holds * hold_s / n:.2f}s)")
+ assert len(intervals) == (n + k) * holds
+ assert peak == n, f"{peak} in flight at once on {n} slots"
+ assert wall >= (n + k) * holds * hold_s / n - 0.05, "finished faster than 4 slots allow"
+
+
+def test_a_smaller_cap_uses_only_its_own_first_slots(tmp_path: Path) -> None:
+ """Processes with different caps share one directory: three at N=2 and three at N=4 never
+ exceed 4 together, and the N=2 three never exceed 2 among themselves — the machine is
+ held to the largest cap anyone asks for, and each process to its own."""
+ small = [_python(_CONTENDER, tmp_path, 2, 4, 0.1) for _ in range(3)]
+ big = [_python(_CONTENDER, tmp_path, 4, 4, 0.1) for _ in range(3)]
+ runs: dict[str, list[tuple[float, float]]] = {"small": [], "big": []}
+ try:
+ for p in small + big:
+ assert p.stdout.readline().strip() == "ready", p.stderr.read()
+ for p in small + big:
+ p.stdin.write("go\n")
+ p.stdin.flush()
+ for name, group in (("small", small), ("big", big)):
+ for p in group:
+ out, err = p.communicate(timeout=60)
+ assert p.returncode == 0, err
+ runs[name] += [tuple(json.loads(line)) for line in out.splitlines() if line.startswith("[")]
+ finally:
+ for p in small + big:
+ p.kill()
+ both, alone = _peak(runs["small"] + runs["big"]), _peak(runs["small"])
+ print(f"\n(a') caps 2 and 4 in one directory: peak {both} together, {alone} among the N=2 processes")
+ assert len(runs["small"]) == len(runs["big"]) == 12
+ assert both <= 4 and alone <= 2
+
+
+def test_a_process_killed_holding_a_slot_frees_it_at_once(tmp_path: Path) -> None:
+ """(b) SIGKILL runs no cleanup code; the kernel drops a dead process's flock anyway, so
+ a waiter gets the slot within one poll — no stale-lock timeout, no pid file to reap."""
+ slots = Slots(1, tmp_path)
+ child = _python(_HOLDER, tmp_path, 1)
+ try:
+ assert child.stdout.readline().strip() == "held", child.stderr.read()
+ assert slots.try_take() is None and slots.busy() == 1, "the child holds the only slot"
+ t_kill = time.monotonic()
+ os.kill(child.pid, signal.SIGKILL)
+ fd = slots.take(timeout_s=5.0)
+ freed_after = time.monotonic() - t_kill
+ finally:
+ child.kill()
+ child.wait(10)
+ Slots.give(fd)
+ print(f"\n(b) slot back {freed_after * 1000:.0f} ms after SIGKILL (poll {Slots.POLL_S * 1000:.0f} ms)")
+ assert child.returncode == -signal.SIGKILL
+ assert freed_after < 1.0
+
+
+def test_threads_of_one_process_share_the_slots(tmp_path: Path) -> None:
+ """(c) flock locks an open file DESCRIPTION and every take opens its own, so threads of
+ one process exclude each other exactly like processes do: 12 threads on 3 slots never
+ hold more than 3, and two threads cannot both hold a 1-slot pool."""
+ one = Slots(1, tmp_path / "one")
+ fd = one.take(1.0)
+ got: list[int | None] = []
+ t = threading.Thread(target=lambda: got.append(one.try_take()))
+ t.start()
+ t.join(5)
+ assert got == [None], "a second thread of the same process took the held slot"
+ Slots.give(fd)
+
+ n, threads, holds, hold_s = 3, 12, 4, 0.05
+ slots = Slots(n, tmp_path / "three")
+ lock = threading.Lock()
+ intervals: list[tuple[float, float]] = []
+
+ def worker() -> None:
+ for _ in range(holds):
+ fd = slots.take(30.0)
+ t0 = time.monotonic()
+ time.sleep(hold_s)
+ t1 = time.monotonic()
+ Slots.give(fd)
+ with lock:
+ intervals.append((t0, t1))
+
+ t_go = time.monotonic()
+ pool = [threading.Thread(target=worker) for _ in range(threads)]
+ for w in pool:
+ w.start()
+ for w in pool:
+ w.join(60)
+ wall = time.monotonic() - t_go
+ peak = _peak(intervals)
+ print(f"\n(c) {threads} threads x {holds} holds x {hold_s}s on {n} slots: peak {peak}, "
+ f"wall {wall:.2f}s (floor {threads * holds * hold_s / n:.2f}s)")
+ assert len(intervals) == threads * holds and peak == n
+ assert slots.busy() == 0, "every slot came back"
+
+
[email protected]("timeout_s", [0.0, 0.3])
+def test_a_waiter_gives_up_at_its_deadline(tmp_path: Path, timeout_s: float) -> None:
+ """(d) Every slot held by another process: a waiter raises the pool's own error at its
+ deadline — not before it, and without sleeping on past it (the last nap is clipped)."""
+ slots = Slots(2, tmp_path)
+ holders = [_python(_HOLDER, tmp_path, 2) for _ in range(2)]
+ try:
+ for h in holders:
+ assert h.stdout.readline().strip() == "held", h.stderr.read()
+ t0 = time.monotonic()
+ with pytest.raises(KeyPoolExhausted, match="in-flight slots"):
+ slots.take(timeout_s=timeout_s)
+ waited = time.monotonic() - t0
+ finally:
+ for h in holders:
+ h.kill()
+ h.wait(10)
+ print(f"\n(d) deadline {timeout_s}s: gave up after {waited:.3f}s")
+ assert timeout_s <= waited < timeout_s + 0.2