Skip to content

Official Codebase of 3DCodeVerse

Python

key pool: the limiter is per-PROCESS, so N concurrent batteries multiply the quota by N

gaoypeng9c60c210b401
diff --git a/harness/codeverse/cli/doctor.py b/harness/codeverse/cli/doctor.py
index 56e69a07..38087906 100644
--- a/harness/codeverse/cli/doctor.py
+++ b/harness/codeverse/cli/doctor.py
@@ -170,10 +170,29 @@ def check_pool(live: bool) -> list[Row]:
return rows
+def _rate_cap() -> int:
+ from codeverse.config import get_settings
+
+ return int(getattr(get_settings().rate, "max_in_flight", 0) or 0)
+
+
def check_keys(live: bool) -> list[Row]:
s = get_settings()
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
+
+ sib = sibling_processes()
+ 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",
+ ))
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/codeverse/models/health.py b/harness/codeverse/models/health.py
index 7bb943c4..ae9fc847 100644
--- a/harness/codeverse/models/health.py
+++ b/harness/codeverse/models/health.py
@@ -77,3 +77,58 @@ def _bare_model(model_id: str, timeout_s: float):
from codeverse.models import get_chat_model # other providers: no bare constructor needed yet
return get_chat_model(model_id)
+
+
+# --------------------------------------------------------------------------- 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.
+_MODULE = "codeverse.cli.main"
+_SCRIPTS = ("compare_backends.py", "run_bench.py")
+_ENTRY_POINTS = ("3dcv", "3dcodeverse")
+
+
+def _is_harness_argv(args: list[str]) -> bool:
+ if not args:
+ return False
+ from pathlib import PurePath
+
+ if PurePath(args[0]).name in _ENTRY_POINTS:
+ return True
+ for i, a in enumerate(args):
+ if a == "-m" and i + 1 < len(args) and args[i + 1] == _MODULE:
+ return True
+ if PurePath(a).name in _SCRIPTS:
+ return True
+ return False
+
+
+def sibling_processes() -> int:
+ """How many OTHER harness processes are running on this machine.
+
+ ``shared_pool`` keeps one KeyPool per PROCESS, so each sibling believes it owns the
+ whole key quota and gets its own ``max_in_flight``. N siblings multiply the real
+ concurrency by N against a quota that is shared: on 2026-08-24 six concurrent
+ batteries took gemini-3.7-flash from 25 % success to 0 % (``docs/COST.md`` §23).
+
+ Best-effort — reads /proc and returns 0 when it cannot tell, because a wrong number
+ here must never block a run.
+ """
+ import os
+ from pathlib import Path
+
+ me, found = os.getpid(), 0
+ try:
+ entries = list(Path("/proc").iterdir())
+ except OSError:
+ return 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 # exited between listing and reading
+ if _is_harness_argv([a for a in raw.decode(errors="replace").split("\0") if a]):
+ found += 1
+ return found
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
index 4899d10b..c390b392 100644
--- a/harness/docs/COST.md
+++ b/harness/docs/COST.md
@@ -1035,3 +1035,56 @@ evaluated again — but the residual remains real: **`max_minutes` is enforced a
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
+
+§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
+configures is per-process by construction:
+
+```python
+_pools: dict[tuple[str, ...], KeyPool] = {} # codeverse/models/gemini.py — MODULE level
+def shared_pool(...): """One KeyPool per distinct (key list, quota) so limiters are process-wide."""
+```
+
+Process-wide is not machine-wide. Every `3dcv bench run`, every `compare_backends.py`
+and every `3dcv make` is its own OS process with its own pool, each believing it owns the
+whole 22-key quota and each allowing its own 64 in-flight. On 2026-08-24 six batteries
+from different waves ran at once: **~384 concurrent calls against a quota sized for 64**.
+
+What that did, measured on the same keys and the same model within 15 minutes:
+
+| condition | `gemini-3.7-flash` trivial call |
+|---|---|
+| ~15 of our processes running | **0 / 8 succeeded** |
+| machine quiet (we killed everything) | **3 / 12 succeeded** (25 %), 7.4 – 25.5 s |
+| machine quiet, `gemini-3.1-pro-preview` | **4 / 4 succeeded**, 3.1 – 29.7 s |
+
+Read it honestly, in both directions:
+
+* **The provider really was degraded.** 25 % success at four concurrent trivial calls is
+ not something we caused, and pro was healthy on the same keys at the same moment, so
+ this was flash-specific capacity on Google's side — not our key quota.
+* **Our own concurrency turned a degraded service into a total outage.** 0/8 under load
+ versus 3/12 quiet is the same model, same keys, minutes apart.
+
+Three consequences:
+
+1. **The knee is a per-process number and must be divided by the number of concurrent
+ harness processes.** Running six batteries at `max_in_flight = 64` is asking for
+ 6 × the concurrency the sweep found optimal — well past the point where §20 measured
+ throughput *falling* (128 in-flight was worse than 64).
+2. **It reframes §21's negative result.** The StormGate lost its A/B, and the conclusion
+ was "gemini's 503s are intermittent, so parking is a waste". But that A/B ran inside
+ ONE process while five other batteries kept hammering: a per-process gate can neither
+ see nor slow the traffic actually causing the storm, so the polite process paid the
+ 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**: run ONE battery at a time,
+ or set `CV3D_MAX_IN_FLIGHT` to `64 / (concurrent processes)`.
+
+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
+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.
diff --git a/harness/tests/models/test_health.py b/harness/tests/models/test_health.py
index dd055c56..fec3daf2 100644
--- a/harness/tests/models/test_health.py
+++ b/harness/tests/models/test_health.py
@@ -38,3 +38,34 @@ def test_probe_never_raises_when_every_call_fails(monkeypatch):
h = health.probe("gemini:gemini-3.7-flash", sample=3, timeout_s=1)
assert not h.ok and h.n_ok == 0 and h.n_tried == 3
assert h.reasons and "provider on fire" in h.reasons[0]
+
+
+# --------------------------------------------------------------------------- siblings
+def test_sibling_detection_matches_arguments_not_the_repo_path():
+ """The repo path itself contains "3dcodeverse", so a substring test over the whole
+ command line counts every shell that merely cd'd into the tree — the first version
+ of this reported 4 siblings on an idle machine."""
+ from codeverse.models.health import _is_harness_argv
+
+ assert _is_harness_argv(["python", "-m", "codeverse.cli.main", "bench", "run"])
+ assert _is_harness_argv(["python", "bench/compare_backends.py", "--arms", "x"])
+ assert _is_harness_argv(["/home/u/.local/bin/3dcv", "doctor"])
+ assert _is_harness_argv(["/usr/bin/python3", "/x/y/run_bench.py"])
+ # the false positives
+ assert not _is_harness_argv(["/bin/bash", "-c", "cd /home/u/3dcodeverse/harness && ls"])
+ assert not _is_harness_argv(["vim", "/home/u/3dcodeverse/harness/codeverse/cli/main.py"])
+ assert not _is_harness_argv(["python", "-m", "pytest", "tests/"])
+ assert not _is_harness_argv([])
+
+
+def test_sibling_count_never_raises(monkeypatch):
+ """A wrong number here must never block a run, so /proc trouble returns 0."""
+ from pathlib import Path
+
+ import codeverse.models.health as health
+
+ def boom(_self):
+ raise OSError("no /proc on this platform")
+
+ monkeypatch.setattr(Path, "iterdir", boom)
+ assert health.sibling_processes() == 0