Skip to content

Official Codebase of 3DCodeVerse

Python

pool sharing: a budget, not a head-count — counting processes stalled a whole A/B wave behind two parked batteries

gaoypeng902b70956d2b
diff --git a/harness/bench/ab_plan.py b/harness/bench/ab_plan.py
index db45b9a5..4a949236 100644
--- a/harness/bench/ab_plan.py
+++ b/harness/bench/ab_plan.py
@@ -313,11 +313,14 @@ def main(argv: Sequence[str] | None = None) -> int:
return 0
if not opts.variant_env:
_parser().error("--variant-env KEY=VALUE is required: an A/B with identical arms measures only the judge")
- from codeverse.models.health import sibling_processes
-
- if (sib := sibling_processes()) and not ns.allow_siblings:
- print(f"refusing to start: {sib} other harness process(es) are running and would share the key quota "
- "(docs/COST.md §23). Wait for them, or pass --allow-siblings.", flush=True)
+ from codeverse.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/harness/codeverse/cli/doctor.py b/harness/codeverse/cli/doctor.py
index 38087906..167f3e99 100644
--- a/harness/codeverse/cli/doctor.py
+++ b/harness/codeverse/cli/doctor.py
@@ -181,17 +181,17 @@ 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 codeverse.models.health import sibling_processes
+ from codeverse.models.health import pool_budget
- sib = sibling_processes()
+ pb = pool_budget()
cap = _rate_cap()
rows.append((
"pool sharing",
- "OK" if sib == 0 else "WARN",
- f"{sib} other harness process(es) running — each keeps its OWN key pool, so the real "
- f"concurrency is ~{(sib + 1) * cap} in-flight against one shared quota "
- f"(docs/COST.md §23; run one battery at a time or set CV3D_MAX_IN_FLIGHT={max(1, cap // (sib + 1))})"
- if sib else "sole harness process: max_in_flight applies as configured",
+ "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 CV3D_MAX_IN_FLIGHT={max(1, pb.headroom)} or wait") + ")")
+ if pb.siblings else "sole harness process: max_in_flight applies as configured",
))
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)"))
diff --git a/harness/codeverse/models/health.py b/harness/codeverse/models/health.py
index aaf62cde..e8c46a75 100644
--- a/harness/codeverse/models/health.py
+++ b/harness/codeverse/models/health.py
@@ -22,6 +22,7 @@ from __future__ import annotations
import concurrent.futures as cf
import logging
from dataclasses import dataclass
+from pathlib import Path
log = logging.getLogger(__name__)
@@ -148,7 +149,6 @@ def sibling_processes() -> int:
here must never block a run.
"""
import os
- from pathlib import Path
me, found = os.getpid(), 0
try:
@@ -165,3 +165,83 @@ def sibling_processes() -> int:
if _is_harness_argv([a for a in raw.decode(errors="replace").split("\0") if a]):
found += 1
return found
+
+
+#: 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 = ("CV3D_MAX_IN_FLIGHT", "CV3D_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).
+ """
+ from codeverse.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:
+ return int(val)
+ except ValueError:
+ return default
+ 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 like
+ :func:`sibling_processes`: 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
+ if _is_harness_argv([a for a in raw.decode(errors="replace").split("\0") if a]):
+ n += 1
+ used += _cap_of(entry)
+ return PoolBudget(n, used)
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
index a46880da..d1ccc202 100644
--- a/harness/docs/COST.md
+++ b/harness/docs/COST.md
@@ -1085,8 +1085,13 @@ Three consequences:
`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
`CV3D_MAX_IN_FLIGHT=<n>` (`CV3D_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). `3dcv doctor`'s
- `pool sharing` row prints the current sibling count and the value to use.
+ read by nothing until 2026-08-24 — three launches that "set" it ran at 64).
+ `codeverse.models.health.pool_budget()` reads every sibling's cap from `/proc/<pid>/environ`
+ and reports used / headroom; `3dcv doctor`'s `pool sharing` row prints it, and
+ `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.
The real fix is a machine-wide limiter — a file-locked token bucket under
`~/.cache/codeverse/` that every process shares — so the quota is enforced where it
diff --git a/harness/tests/models/test_health.py b/harness/tests/models/test_health.py
index c4c34a5e..a9d02492 100644
--- a/harness/tests/models/test_health.py
+++ b/harness/tests/models/test_health.py
@@ -113,3 +113,72 @@ 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 codeverse.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_sums_caps_not_heads(monkeypatch):
+ """Two siblings at 16 each leave 32 of headroom; a third at 16 fits, one at 64 does not.
+ Head-counting (the first rule) would have refused both — and on 2026-08-24 it stalled
+ an entire A/B wave behind two batteries that were themselves parked."""
+ health = _fake_proc(monkeypatch, {
+ 101: (["python", "-m", "codeverse.cli.main", "bench", "run"], {"CV3D_MAX_IN_FLIGHT": "16"}),
+ 102: (["python", "bench/compare_backends.py", "--arms", "x"], {"CV3D_RATE__MAX_IN_FLIGHT": "16"}),
+ 103: (["/bin/bash", "-c", "cd /home/u/3dcodeverse && sleep 1"], {}), # not a harness process
+ })
+ 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)
+
+
+def test_a_sibling_that_set_no_cap_counts_at_the_default(monkeypatch):
+ """An unconfigured battery runs at Rate().max_in_flight (64) and fills the whole budget."""
+ health = _fake_proc(monkeypatch, {
+ 201: (["python", "-m", "codeverse.cli.main", "make", "a chair"], {}),
+ })
+ pb = health.pool_budget()
+ assert pb.used == 64 and pb.headroom == 0 and not pb.fits(1)
+
+
+def test_pool_budget_never_raises(monkeypatch):
+ from pathlib import Path
+
+ import codeverse.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)