Skip to content

Official Codebase of 3DCodeVerse

Python

models: the RPM/TPM buckets and the storm gate are deleted — neither engaged since the api-agent went

gaoypeng0b5598e72cc6
diff --git a/eval/bench/concurrency_probe.py b/eval/bench/concurrency_probe.py
index efcaded2..d178e204 100644
--- a/eval/bench/concurrency_probe.py
+++ b/eval/bench/concurrency_probe.py
@@ -28,7 +28,7 @@ from codeverse3d.config import get_settings
from codeverse3d.contracts.chat import ChatMessage, ChatRequest
from codeverse3d.cost.guard import CHARS_PER_TOKEN
from codeverse3d.models.gemini import GeminiModel
-from codeverse3d.models.retry import KeyPool, StormGate
+from codeverse3d.models.retry import KeyPool
from codeverse3d.proc import fan_out
#: filler that is cheap to build, incompressible enough not to be cached away, and
@@ -71,9 +71,6 @@ class LevelResult:
input_tokens: int
output_tokens: int
usd: float
- storm_hits: int = 0
- storm_probes: int = 0
- storm_parked_s: float = 0.0
errors: list[str] = field(default_factory=list)
@@ -111,14 +108,9 @@ class _Gauge:
def run_level(
level: int, *, model: str, keys: list[str], calls: int, in_tokens: int, out_tokens: int,
- rpm_per_key: int, tpm_per_key: int | None, storm_gate: bool = True,
) -> LevelResult:
- pool = KeyPool(keys, rpm_per_key=rpm_per_key, tpm_per_key=tpm_per_key)
- gate = StormGate(f"probe:{model}:c{level}") if storm_gate else None
+ pool = KeyPool(keys)
m = GeminiModel(model, pool=pool)
- # assign directly: the constructor takes the process-wide gate (Settings.rate.storm_gate)
- # and has no parameter for it, and this probe has to be able to switch it off entirely
- m.storm_gate = gate
body = filler(in_tokens)
gauge = _Gauge()
lat: list[float] = []
@@ -166,8 +158,6 @@ def run_level(
attempts_ok=st["ok"], attempts_429=st["429"], attempts_5xx=st["5xx"],
attempts_error=st["error"], input_tokens=usage["in"], output_tokens=usage["out"],
usd=round(usage["usd"], 4),
- storm_hits=gate.n_hits if gate else 0, storm_probes=gate.n_probes if gate else 0,
- storm_parked_s=round(gate.parked_s, 1) if gate else 0.0,
errors=[f"{type(e).__name__}: {e}"[:200] for e in bad[:5]],
)
@@ -179,10 +169,6 @@ def main() -> None:
ap.add_argument("--calls", type=int, default=48, help="calls per level (the fixed workload)")
ap.add_argument("--in-tokens", type=int, default=12000, help="prompt size (a generator call)")
ap.add_argument("--out-tokens", type=int, default=512)
- ap.add_argument("--rpm-per-key", type=int, default=1000)
- ap.add_argument("--tpm-per-key", type=int, default=0, help="0 = no TPM bucket")
- ap.add_argument("--storm-gate", dest="storm_gate", action="store_true", default=True)
- ap.add_argument("--no-storm-gate", dest="storm_gate", action="store_false")
ap.add_argument("--out", default="")
a = ap.parse_args()
@@ -194,18 +180,17 @@ def main() -> None:
print(f"{len(keys)} keys · model {a.model} · {a.calls} calls/level · ~{a.in_tokens} in-tokens")
hdr = (f"{'lvl':>4s} {'wall_s':>7s} {'ok':>4s} {'fail':>5s} {'calls/min':>10s} "
f"{'ktok/min':>9s} {'mean_if':>8s} {'p50':>6s} {'p90':>7s} {'max':>7s} "
- f"{'429':>5s} {'5xx':>5s} {'err':>5s} {'park_s':>7s} {'$':>7s}")
+ f"{'429':>5s} {'5xx':>5s} {'err':>5s} {'$':>7s}")
print(hdr)
print("-" * len(hdr))
for lv in levels:
r = run_level(lv, model=a.model, keys=keys, calls=a.calls, in_tokens=a.in_tokens,
- out_tokens=a.out_tokens, rpm_per_key=a.rpm_per_key,
- tpm_per_key=a.tpm_per_key or None, storm_gate=a.storm_gate)
+ out_tokens=a.out_tokens)
rows.append(r)
print(f"{r.level:4d} {r.wall_s:7.1f} {r.n_ok:4d} {r.n_failed:5d} {r.calls_per_min:10.1f} "
f"{r.tokens_per_min / 1000:9.0f} {r.mean_inflight:8.2f} {r.p50_s:6.1f} {r.p90_s:7.1f} "
f"{r.max_s:7.1f} {r.attempts_429:5d} {r.attempts_5xx:5d} {r.attempts_error:5d} "
- f"{r.storm_parked_s:7.0f} {r.usd:7.3f}",
+ f"{r.usd:7.3f}",
flush=True)
if r.errors:
print(f" errors: {r.errors[0]}", flush=True)
@@ -214,7 +199,6 @@ def main() -> None:
out.mkdir(parents=True, exist_ok=True)
(out / "levels.json").write_text(json.dumps(
{"model": a.model, "n_keys": len(keys), "calls": a.calls, "in_tokens": a.in_tokens,
- "storm_gate": a.storm_gate,
"rows": [asdict(r) for r in rows]}, indent=2))
print(f"wrote {out / 'levels.json'}")
best = max(rows, key=lambda r: r.calls_per_min)
diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.py
index cd8968e9..f3ede6fe 100644
--- a/harness/codeverse3d/config.py
+++ b/harness/codeverse3d/config.py
@@ -106,21 +106,16 @@ class Limits(BaseModel):
class Rate(BaseModel):
- """Provider quota the key pool schedules against, and the model-call ceiling.
-
- Measured, not guessed — ``docs/COST.md`` Part III. On this box (22 keys,
- ``gemini-3.7-flash``) ``tpm_per_key`` is the binding limit, not ``rpm_per_key``:
- a generator call averages ~42 k prompt tokens, so 1 M TPM is ~24 calls/min per
- key (528 pool-wide) while the RPM quota would allow 1 000.
-
- ``max_in_flight`` is a process-wide 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.
+ """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:
+ 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).
"""
- rpm_per_key: int = Field(default=1000, ge=1, description="requests/minute allowed per API key")
- tpm_per_key: int = Field(default=1_000_000, ge=0, description="prompt tokens/minute allowed per API key (0 = no TPM bucket)")
max_in_flight: int = Field(
default=64,
ge=0, # NEGATIVE is not "unlimited" here: 0 is. Without this bound -5 survived config,
@@ -131,13 +126,6 @@ class Rate(BaseModel):
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).")
- storm_gate: bool = Field(
- default=False,
- description="share 503 capacity-storm back-pressure across workers. OFF: measured and it "
- "LOST — 30.0/45.4 calls/min without it vs 18.2/20.0 with it, because Gemini's 503s are "
- "intermittent rather than a clean outage, so parking every worker starves the unlucky call "
- "(docs/COST.md §21). The mechanism and its counters are kept so the experiment is "
- "reproducible: C3D_RATE__STORM_GATE=1, or eval/bench/concurrency_probe.py --storm-gate.")
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 "
@@ -424,12 +412,10 @@ def _deep_merge(base: dict, overlay: dict) -> dict:
``dict.update`` replaced a whole sub-dict, so a project ``./3dcodeverse.yaml`` that
merely NAMED a section silently dropped every sibling key the user had set in
``~/.config/3dcodeverse/config.yaml`` — those keys fell back to the built-in Field
- defaults, not to the user's values. Concretely: a user config with
- ``rate.tpm_per_key: 250000`` plus a project file with only ``rate.max_in_flight: 8``
- scheduled the key pool against the built-in 1,000,000 TPM, 4x the operator's real
- quota, even though Rate's own docstring calls tpm_per_key the binding limit on this
- box. docs/INSTALL.md §8.3 documents the order as "built-in defaults < user config <
- project config < env", which every reader takes as per-setting.
+ defaults, not to the user's values (2026-08-24: a user's per-key TPM quota was lost to
+ a project file that set only the in-flight cap). docs/INSTALL.md §8.3 documents the
+ order as "built-in defaults < user config < project config < env", which every reader
+ takes as per-setting.
"""
out = dict(base)
for k, v in overlay.items():
diff --git a/harness/codeverse3d/doctor.py b/harness/codeverse3d/doctor.py
index 21fe33ce..0b033a45 100644
--- a/harness/codeverse3d/doctor.py
+++ b/harness/codeverse3d/doctor.py
@@ -148,47 +148,22 @@ def check_gpu_probe(timeout_s: int = 120) -> list[Row]:
def check_pool(live: bool) -> list[Row]:
- """The key pool's live scheduling picture: quota, headroom, storm counters.
+ """The key pool's live picture: in-flight, and the outcomes this process has seen.
Only meaningful once something has used the pool this process, so it is part
of ``--live`` (``check_keys`` makes one call just before)."""
from codeverse3d.models.gemini import shared_pool
- from codeverse3d.models.retry import all_gates
s = get_settings()
- if not s.gemini_api_keys:
+ if not live or not s.gemini_api_keys:
return []
- r = s.rate
- pool = shared_pool(list(s.gemini_api_keys))
- st = pool.stats()
- rows: list[Row] = [(
- "gemini quota", "OK",
- f"{st['n_keys']} keys x {r.rpm_per_key} RPM / {r.tpm_per_key:,} TPM "
- f"= {st['rpm_capacity']:,} RPM / {st['tpm_capacity']:,} TPM pool-wide"
- f"; max_in_flight={r.max_in_flight or 'off'}",
+ st = shared_pool(list(s.gemini_api_keys)).stats()
+ return [(
+ "gemini pool", "WARN" if st["n_dead"] else "OK",
+ f"{st['n_keys']} keys · in-flight {st['in_flight']} (peak {st['peak_in_flight']}) · "
+ f"{st['acquired']} acquired, {st['ok']} ok, {st['429']} x429, {st['5xx']} x5xx, "
+ f"{st['n_dead']} dead, {st['n_cooling']} cooling (this process)",
)]
- if live:
- used_rpm = 100 * (1 - st["rpm_headroom"])
- used_tpm = "n/a" if st["tpm_headroom"] is None else f"{100 * (1 - st['tpm_headroom']):.1f}%"
- bad = st["429"] + st["5xx"] + st["dead"]
- rows.append((
- "gemini pool", "WARN" if st["n_dead"] else "OK",
- f"in-flight {st['in_flight']} (peak {st['peak_in_flight']}) · "
- f"RPM used {used_rpm:.1f}% · TPM used {used_tpm} · "
- f"{st['acquired']} acquired, {st['ok']} ok, {st['429']} x429, {st['5xx']} x5xx, "
- f"{st['n_dead']} dead, {st['n_cooling']} cooling"
- + ("" if not bad else " (this process)"),
- ))
- for gate in all_gates():
- g = gate.snapshot()
- rows.append((
- f"storm gate {g['name'].split(':')[-1]}"[:24],
- "WARN" if g["storming"] else "OK",
- f"{g['storms']} storm(s), {g['hits']} x503, {g['probes']} probes, "
- f"{g['parked_s']}s parked"
- + (f" — CLOSED for {g['closed_for_s']}s" if g["storming"] else ""),
- ))
- return rows
def check_keys(live: bool) -> list[Row]:
diff --git a/harness/codeverse3d/models/gemini.py b/harness/codeverse3d/models/gemini.py
index d180aeb8..232f151d 100644
--- a/harness/codeverse3d/models/gemini.py
+++ b/harness/codeverse3d/models/gemini.py
@@ -3,8 +3,8 @@
* conversion — ``ChatRequest`` ⇄ google-genai types (``to_contents``, ``build_config``,
``extract_candidate``, ``parse_usage``); pure, unit-testable offline;
* ``GeminiModel`` — the ``ChatModel``: a shared ``KeyPool`` over the configured keys,
- ``rotate_with_retries`` with the storm gate / hedge, streaming with stall detection,
- per-attempt ledger rows;
+ ``rotate_with_retries`` with the hedge, streaming with stall detection, per-attempt
+ ledger rows;
* ``GeminiImageModel`` — text(+reference images) → PIL images on the same pool and
retry machine, priced per generated image (``pricing.per_image_usd``), with a
fallback model when the primary is missing.
@@ -45,10 +45,8 @@ from codeverse3d.models.retry import (
OnAttempt,
Outcome,
_Try,
- request_tokens,
rotate_with_retries,
)
-from codeverse3d.models.retry import storm_gate as storm_gate_for
from codeverse3d.models.schema_utils import JsonParseError, parse_json_lenient, to_gemini_schema
#: INTERFACES.md mapping; ``off`` → 0 where the model allows it
@@ -212,27 +210,15 @@ _clients: dict[tuple[str, int], genai.Client] = {}
_registry_lock = threading.Lock()
-def shared_pool(
- keys: list[str],
- *,
- rpm_per_key: int | None = None,
- tpm_per_key: int | None = None,
- max_in_flight: int | None = None,
-) -> KeyPool:
- """One ``KeyPool`` per distinct (key list, quota) so limiters are process-wide.
-
- Unset arguments come from ``Settings.rate`` — the owner's real per-key quota
- (``docs/COST.md`` Part III), which is what makes the pool TPM-aware: a
- 200 k-token judge verdict reserves 100x what a caption does."""
- rate = _rate()
- rpm = rate.rpm_per_key if rpm_per_key is None else rpm_per_key
- tpm = rate.tpm_per_key if tpm_per_key is None else tpm_per_key
- cap = rate.max_in_flight if max_in_flight is None else max_in_flight
- sig = (*keys, f"|{rpm}|{tpm}|{cap}")
+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``."""
+ 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, rpm_per_key=rpm, tpm_per_key=tpm or None, max_in_flight=cap or 0)
+ pool = KeyPool(keys, max_in_flight=cap or 0)
_pools[sig] = pool
return pool
@@ -418,8 +404,8 @@ def _merge_stream_chunks(
class GeminiModel:
"""ChatModel for ``gemini:<model>``: a shared ``KeyPool``, ``rotate_with_retries``
- (storm gate, hedge, ``ChatRequest.max_wait_s`` deadline), streaming with stall
- detection and per-attempt ledger rows."""
+ (hedge, ``ChatRequest.max_wait_s`` deadline), streaming with stall detection and
+ per-attempt ledger rows."""
provider = "gemini"
@@ -446,7 +432,6 @@ class GeminiModel:
self.hedge = max(1, int(_rate().hedge if hedge is None else hedge))
keys = _keys_or_raise(keys, pool)
self.pool = pool or shared_pool(keys)
- self.storm_gate = storm_gate_for(f"gemini:{model}") if _rate().storm_gate else None
self.timeout_s = _default_timeout_s() if timeout_s is None else timeout_s
self.max_attempts = max(1, max_attempts)
self._sleep = sleep
@@ -494,9 +479,6 @@ class GeminiModel:
sleep=self._sleep,
on_free_retry=downgrade_thinking,
retry_after=_retry_after_s,
- tokens_of=lambda r: r.usage.input_tokens,
- tokens_hint=request_tokens(request, model_id=self.id),
- storm_gate=self.storm_gate,
label=f"gemini {self.model}",
stats=stats,
on_attempt=self._attempt_hook(wasted),
@@ -692,7 +674,6 @@ class GeminiImageModel:
self.hedge = max(1, int(hedge))
keys = _keys_or_raise(keys, pool)
self.pool = pool or shared_pool(keys)
- self.storm_gate = storm_gate_for(f"gemini:{model}") if _rate().storm_gate else None
self.timeout_s = timeout_s
self.max_attempts = max(1, max_attempts)
self._sleep = sleep
@@ -800,8 +781,6 @@ class GeminiImageModel:
hedge=self.hedge,
sleep=self._sleep,
retry_after=_retry_after_s,
- tokens_of=lambda r: r[1].input_tokens,
- storm_gate=self.storm_gate,
label=f"image {model}",
)
diff --git a/harness/codeverse3d/models/retry.py b/harness/codeverse3d/models/retry.py
index 7f2acb95..fa3688f4 100644
--- a/harness/codeverse3d/models/retry.py
+++ b/harness/codeverse3d/models/retry.py
@@ -1,38 +1,31 @@
"""The scheduling machine under every model call (merged 2026-08-28, d512ccc):
-1. ``KeyPool`` (+ ``TokenBucket``): a multi-key pool with per-key RPM/TPM buckets,
- 429 cooldown and a health score — used by ``GeminiModel`` (22 keys on the owner's
+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;
-2. ``StormGate`` + ``storm_gate()`` / ``all_gates()``: the process-wide 503 back-pressure
- one model's callers share (ships OFF, ``Settings.rate.storm_gate``; docs/COST.md §21);
-3. the two retry loops — ``with_retries`` (single key, SDK adapters) and
- ``rotate_with_retries`` (the pool, the gate, hedging, the ``RETRY_DEADLINE_S`` deadline);
-4. ``request_parts`` / ``request_tokens``: the prompt-token estimate the pool reserves.
+2. the two retry loops — ``with_retries`` (single key, SDK adapters) and
+ ``rotate_with_retries`` (the pool, hedging, the ``RETRY_DEADLINE_S`` deadline).
Every wait anywhere in here clips to ``MAX_WAIT_S``.
The pool:
-* ``acquire()`` picks the next healthy key round-robin, honouring per-key
- RPM / TPM token buckets and 429 cool-downs; it blocks (bounded) when every
- key is throttled and raises ``KeyPoolExhausted`` after ``timeout_s``.
- ``tokens_hint`` reserves the pending call's estimated prompt tokens, so a
- 200 k-token judge verdict and a 2 k-token caption are scheduled differently
- (``docs/COST.md`` Part III); ``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.
+* ``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).
* ``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): only the token
- reconciliation runs, health and counters are untouched. ``dead`` is for
- key-scoped auth/permission failures (revoked / suspended / invalid key): the
- key is benched for ``dead_cooldown_s`` (default one hour) and re-probed once
- that elapses — a dead key must never keep failing its share of calls.
- ``report(..., tokens=actual, reserved=hint)`` reconciles the reservation with
- the provider's real prompt-token count (refund or top-up).
-* ``stats()`` exposes counters for logs / ``3dcode doctor --live``: per-key health
- and cooldown, pool RPM/TPM capacity and headroom, in-flight and peak in-flight.
+ failure the key did not cause (bad JSON, empty candidates): health and counters are
+ untouched. ``dead`` is for key-scoped auth/permission failures (revoked / suspended /
+ invalid key): the key is benched for ``dead_cooldown_s`` (default one hour) and
+ re-probed once that elapses — a dead key must never keep failing its share of calls.
+* ``stats()`` exposes counters for logs / ``3dcode doctor --live``: per-key health and
+ cooldown, in-flight and peak in-flight.
Thread-safe; ``clock`` / ``sleep`` are injectable for deterministic tests.
"""
@@ -45,17 +38,15 @@ import threading
import time
from collections.abc import Callable, Sequence
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
-from dataclasses import dataclass, field
+from dataclasses import dataclass
from functools import partial
from typing import TYPE_CHECKING, Any, Literal
-from codeverse3d.contracts.chat import ChatRequest, ImagePart, TextPart
-
Outcome = Literal["ok", "429", "5xx", "error", "dead", "skip"]
class KeyPoolExhausted(RuntimeError):
- """Every key is cooling down / throttled and the wait budget ran out."""
+ """Every key is cooling down (or every slot is busy) and the wait budget ran out."""
MAX_WAIT_S = 3.0
@@ -65,7 +56,7 @@ House rule (owner, 2026-08-24, tightened 5 s -> 3 s on 2026-08-27): with 22 keys
there is always another key to try, so the harness rotates rather than sitting
out a long backoff. Patience comes from the NUMBER of attempts, never from the
length of one sleep. This is the single source for every wait — generic
-backoff, storm sleeps, 429 cooldowns and the storm gate's park all clip to it.
+backoff, storm sleeps and 429 cooldowns all clip to it.
"""
ACQUIRE_TIMEOUT_S = 120.0
@@ -77,58 +68,9 @@ with a deadline passes something smaller (``retry.rotate_with_retries`` passes
"""
-@dataclass
-class TokenBucket:
- """Classic token bucket: ``capacity`` tokens, refilled at ``rate`` per second."""
-
- capacity: float
- rate: float
- tokens: float = field(default=0.0)
- updated: float = field(default=0.0)
-
- def __post_init__(self) -> None:
- self.tokens = self.capacity
-
- def _refill(self, now: float) -> None:
- if now > self.updated:
- self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
- self.updated = now
-
- def try_take(self, n: float, now: float) -> bool:
- self._refill(now)
- if self.tokens >= n:
- self.tokens -= n
- return True
- return False
-
- def charge(self, n: float, now: float) -> None:
- """Take ``n`` tokens unconditionally; ``n < 0`` gives tokens back.
-
- Unlike :meth:`try_take` the bucket is allowed to go negative, so an
- under-estimated reservation is paid off by the next refill instead of
- being silently forgiven. Used to reconcile a TPM reservation with the
- provider's real prompt-token count."""
- self._refill(now)
- self.tokens = min(self.capacity, self.tokens - n)
-
- def wait_for(self, n: float, now: float) -> float:
- """Seconds until ``n`` tokens are available (0 if already)."""
- self._refill(now)
- if self.tokens >= n:
- return 0.0
- return (n - self.tokens) / self.rate if self.rate > 0 else float("inf")
-
- def headroom(self, now: float) -> float:
- """Fraction of capacity currently available (0.0 – 1.0)."""
- self._refill(now)
- return max(0.0, min(1.0, self.tokens / self.capacity)) if self.capacity > 0 else 1.0
-
-
@dataclass
class _KeyState:
key: str
- rpm: TokenBucket
- tpm: TokenBucket | None
health: float = 1.0
cooldown_until: float = 0.0
dead_until: float = 0.0
@@ -138,7 +80,6 @@ class _KeyState:
n_error: int = 0
n_dead: int = 0
n_acquired: int = 0
- tokens_used: int = 0
health_ts: float = 0.0
def recover(self, now: float, rate: float = 0.01) -> None:
@@ -147,24 +88,14 @@ class _KeyState:
self.health = min(1.0, self.health + (now - self.health_ts) * rate)
self.health_ts = now
- def available_at(self, now: float, tokens_hint: int) -> float:
- """Earliest time this key can be used (``now`` if ready)."""
- t = max(now, self.cooldown_until)
- t = max(t, now + self.rpm.wait_for(1.0, now))
- if self.tpm is not None and tokens_hint > 0:
- t = max(t, now + self.tpm.wait_for(float(tokens_hint), now))
- return t
-
class KeyPool:
- """Round-robin key pool with per-key limiters. See module docstring."""
+ """Round-robin key pool with cooldowns and an in-flight ceiling. See module docstring."""
def __init__(
self,
keys: list[str] | tuple[str, ...],
*,
- rpm_per_key: int = 900,
- tpm_per_key: int | None = None,
max_in_flight: int = 0,
cooldown_s: float = MAX_WAIT_S,
dead_cooldown_s: float = 3600.0,
@@ -190,13 +121,7 @@ class KeyPool:
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
now = clock()
- self._states: list[_KeyState] = []
- for k in uniq:
- rpm = TokenBucket(capacity=float(rpm_per_key), rate=rpm_per_key / 60.0, updated=now)
- tpm = None
- if tpm_per_key:
- tpm = TokenBucket(capacity=float(tpm_per_key), rate=tpm_per_key / 60.0, updated=now)
- self._states.append(_KeyState(key=k, rpm=rpm, tpm=tpm, health_ts=now))
+ self._states = [_KeyState(key=k, health_ts=now) for k in uniq]
self._by_key = {s.key: s for s in self._states}
# ------------------------------------------------------------------ public
@@ -210,22 +135,18 @@ class KeyPool:
def acquire(
self,
*,
- tokens_hint: int = 0,
exclude: set[str] | frozenset[str] | None = None,
timeout_s: float | None = ACQUIRE_TIMEOUT_S,
) -> str:
"""Return the next usable key, blocking (bounded by ``timeout_s``) while all
- keys are throttled. ``exclude`` skips keys that already failed this call.
+ keys are cooling down. ``exclude`` skips keys that already failed this call.
Raises ``KeyPoolExhausted`` at once when no key can become available before
the deadline (e.g. every key is dead) — availability only moves later.
- ``tokens_hint`` is the estimated prompt tokens of the pending call: they
- are reserved in the chosen key's TPM bucket now and reconciled by
- :meth:`report`. When ``max_in_flight`` is set the call also waits for a
- free concurrency 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."""
+ When ``max_in_flight`` is set the call also waits for a free concurrency 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:
t0 = self._clock()
if not self._slots.acquire(timeout=timeout_s):
@@ -236,18 +157,13 @@ class KeyPool:
# 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(tokens_hint, exclude, timeout_s)
+ return self._acquire_key(exclude, timeout_s)
except BaseException:
if self._slots is not None:
self._slots.release()
raise
- def try_acquire(
- self,
- *,
- tokens_hint: int = 0,
- exclude: set[str] | frozenset[str] | None = None,
- ) -> str | None:
+ 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
``max_in_flight`` slot), else ``None`` — nothing is reserved or counted then.
@@ -258,7 +174,7 @@ class KeyPool:
if self._slots is not None and not self._slots.acquire(blocking=False):
return None
try:
- return self._acquire_key(tokens_hint, exclude, 0.0)
+ return self._acquire_key(exclude, 0.0)
except KeyPoolExhausted:
if self._slots is not None:
self._slots.release()
@@ -268,45 +184,31 @@ class KeyPool:
self._slots.release()
raise
- def _acquire_key(
- self,
- tokens_hint: int,
- exclude: set[str] | frozenset[str] | None,
- timeout_s: float | None,
- ) -> str:
+ 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
while True:
with self._lock:
now = self._clock()
- chosen = self._pick(now, tokens_hint, exclude or ())
+ chosen = self._pick(now, exclude or ())
if chosen is not None:
- chosen.rpm.try_take(1.0, now)
- if chosen.tpm is not None and tokens_hint > 0:
- chosen.tpm.try_take(float(tokens_hint), now)
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(
- (
- s.available_at(now, tokens_hint)
- for s in self._states
- if s.key not in (exclude or ())
- ),
+ (max(now, s.cooldown_until) for s in self._states if s.key not in (exclude or ())),
default=float("inf"),
)
if soonest == float("inf"):
raise KeyPoolExhausted("all keys excluded")
if deadline is not None and soonest > deadline:
raise KeyPoolExhausted(
- f"all {len(self._states)} keys throttled or dead; the earliest becomes "
+ f"all {len(self._states)} keys cooling or dead; the earliest becomes "
f"available in {soonest - now:.0f}s (> {timeout_s}s wait budget)"
)
wait = max(0.01, min(soonest - now, MAX_WAIT_S))
if deadline is not None and self._clock() + wait > deadline:
- raise KeyPoolExhausted(
- f"all {len(self._states)} keys throttled; waited {timeout_s}s"
- )
+ raise KeyPoolExhausted(f"all {len(self._states)} keys cooling; waited {timeout_s}s")
self._sleep(wait)
def release(self) -> None:
@@ -323,22 +225,9 @@ class KeyPool:
if self._slots is not None:
self._slots.release()
- def report(
- self,
- key: str,
- outcome: Outcome,
- *,
- tokens: int = 0,
- reserved: int = 0,
- retry_after_s: float | None = None,
- ) -> None:
- """Feed back the result of a call made with ``key``.
-
- ``tokens`` is what the provider says the call really cost (prompt
- tokens); ``reserved`` is the ``tokens_hint`` :meth:`acquire` already took
- out of the TPM bucket for it. The pool charges the *difference*, so an
- over-estimate is refunded and an under-estimate is paid off — pass both,
- or neither, and never the same tokens twice."""
+ 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
+ suggested delay, clipped to ``MAX_WAIT_S``)."""
with self._lock:
st = self._by_key.get(key)
if st is None:
@@ -368,11 +257,6 @@ class KeyPool:
elif outcome != "skip":
st.n_error += 1
st.health *= 0.9
- if st.tpm is not None and (tokens or reserved):
- # reconcile the reservation with reality; a call that never reached
- # the model (429 / capacity storm) reports tokens=0 and is refunded
- st.tpm.charge(float(tokens) - float(reserved), now)
- st.tokens_used += max(0, int(tokens))
def stats(self) -> dict[str, Any]:
"""Counters per key (keys are redacted to their last 4 chars)."""
@@ -383,10 +267,6 @@ class KeyPool:
"key": f"…{s.key[-4:]}",
"health": round(s.health, 3),
"cooldown_s": round(max(0.0, s.cooldown_until - now), 1),
- "rpm_tokens": round(s.rpm.tokens, 1),
- "rpm_headroom": round(s.rpm.headroom(now), 3),
- "tpm_headroom": None if s.tpm is None else round(s.tpm.headroom(now), 3),
- "tokens_used": s.tokens_used,
"acquired": s.n_acquired,
"ok": s.n_ok,
"429": s.n_429,
@@ -396,21 +276,12 @@ class KeyPool:
}
for s in self._states
]
- n = len(self._states)
return {
- "n_keys": n,
+ "n_keys": len(self._states),
"n_cooling": sum(1 for s in self._states if s.cooldown_until > now),
"n_dead": sum(1 for s in self._states if s.dead_until > now),
"in_flight": self._in_flight,
"peak_in_flight": self._peak_in_flight,
- "rpm_capacity": int(sum(s.rpm.capacity for s in self._states)),
- "tpm_capacity": int(sum(s.tpm.capacity for s in self._states if s.tpm)),
- "rpm_headroom": round(sum(s.rpm.headroom(now) for s in self._states) / n, 3),
- "tpm_headroom": (
- None if self._states[0].tpm is None
- else round(sum(s.tpm.headroom(now) for s in self._states if s.tpm) / n, 3)
- ),
- "tokens_used": sum(s.tokens_used for s in self._states),
"acquired": sum(s.n_acquired for s in self._states),
"ok": sum(s.n_ok for s in self._states),
"429": sum(s.n_429 for s in self._states),
@@ -421,7 +292,7 @@ class KeyPool:
}
# ----------------------------------------------------------------- private
- def _pick(self, now: float, tokens_hint: int, exclude) -> _KeyState | None:
+ def _pick(self, now: float, exclude) -> _KeyState | None:
"""Round-robin scan; prefer the first healthy, ready key; otherwise the
healthiest ready key. Advances the RR cursor past the chosen key."""
n = len(self._states)
@@ -433,7 +304,7 @@ class KeyPool:
if st.key in exclude:
continue
st.recover(now)
- if st.available_at(now, tokens_hint) > now:
+ if st.cooldown_until > now:
continue
if st.health >= self._min_health:
self._rr = (idx + 1) % n
@@ -445,128 +316,6 @@ class KeyPool:
return best
-# ===================================================================== storm
-class StormGate:
- """Shared 503 back-pressure for one model (section 2 of the module docstring)."""
-
- def __init__(
- self,
- name: str = "model",
- *,
- base_delay: float = 1.0,
- max_wait_s: float = MAX_WAIT_S,
- probe_lease_s: float = 30.0,
- clock: Callable[[], float] = time.monotonic,
- sleep: Callable[[float], None] = time.sleep,
- ) -> None:
- self.name = name
- self._base = float(base_delay)
- self._max_wait = float(max_wait_s)
- self._probe_lease = float(probe_lease_s)
- self._clock = clock
- self._sleep = sleep
- self._lock = threading.Lock()
- self._storm = False
- self._closed_until = 0.0
- self._probe_until = 0.0
- self._streak = 0
- self.n_hits = 0
- self.n_probes = 0
- self.n_storms = 0
- self.parked_s = 0.0
-
- # ------------------------------------------------------------------ public
- def enter(self, deadline: float | None = None) -> float:
- """Block until this thread may issue a call; returns the seconds waited.
-
- ``deadline`` (a point on this gate's ``clock``) bounds the parking: each
- wait is clipped to it and once it passes ``enter`` returns even though the
- storm may still be on — the caller's own deadline machinery
- (``retry.rotate_with_retries``), not the gate, decides to give up."""
- t0 = self._clock()
- while True:
- with self._lock:
- now = self._clock()
- if not self._storm:
- return now - t0
- if deadline is not None and now >= deadline:
- return now - t0 # budget exhausted: hand control back
- if now < self._closed_until:
- wait = min(self._max_wait, self._closed_until - now)
- elif now >= self._probe_until:
- # the window elapsed and no probe is in flight: this thread is it
- self._probe_until = now + self._probe_lease
- self.n_probes += 1
- return now - t0
- else:
- wait = min(self._max_wait, self._probe_until - now)
- wait = max(0.01, wait)
- if deadline is not None:
- wait = min(wait, max(0.01, deadline - now))
- self.parked_s += wait
- self._sleep(wait)
-
- def hit(self, retry_after_s: float | None = None) -> float:
- """Record a capacity 503/529. Returns how long the gate is now closed."""
- with self._lock:
- now = self._clock()
- if not self._storm:
- self._storm = True
- self.n_storms += 1
- self.n_hits += 1
- self._streak += 1
- wanted = retry_after_s if retry_after_s and retry_after_s > 0 else (
- self._base * (2 ** min(self._streak - 1, 8))
- )
- delay = min(self._max_wait, wanted)
- self._closed_until = max(self._closed_until, now + delay)
- self._probe_until = 0.0 # a fresh probe may go once the window elapses
- return self._closed_until - now
-
- def ok(self) -> None:
- """Record a success: the model is answering again, so open the gate."""
- if not self._storm:
- return
- with self._lock:
- self._storm = False
- self._streak = 0
- self._closed_until = 0.0
- self._probe_until = 0.0
-
- def snapshot(self) -> dict[str, Any]:
- with self._lock:
- now = self._clock()
- return {
- "name": self.name,
- "storming": self._storm,
- "closed_for_s": round(max(0.0, self._closed_until - now), 1),
- "storms": self.n_storms,
- "hits": self.n_hits,
- "probes": self.n_probes,
- "parked_s": round(self.parked_s, 1),
- }
-
-
-_gates: dict[str, StormGate] = {}
-_gates_lock = threading.Lock()
-
-
-def storm_gate(name: str) -> StormGate:
- """The process-wide gate for ``name`` (``"gemini:gemini-3.7-flash"``)."""
- with _gates_lock:
- gate = _gates.get(name)
- if gate is None:
- gate = StormGate(name)
- _gates[name] = gate
- return gate
-
-
-def all_gates() -> list[StormGate]:
- """Every gate this process has created (for ``3dcode doctor --live``)."""
- with _gates_lock:
- return list(_gates.values())
-
-
# ===================================================================== retry
#: the longest ONE logical call may spend being retried, waits and timeouts included.
#: The storm branch used to be bounded only in ATTEMPTS: 60 storm attempts x (a 300 s
@@ -692,9 +441,6 @@ def rotate_with_retries[T](
monotonic: Callable[[], float] = time.monotonic,
on_free_retry: Callable[[ModelError], bool] | None = None,
retry_after: Callable[[BaseException], float | None] | None = None,
- tokens_of: Callable[[T], int] | None = None,
- tokens_hint: int = 0,
- storm_gate: StormGate | None = None,
label: str = "model",
stats: dict[str, Any] | None = None,
on_attempt: OnAttempt | None = None,
@@ -703,9 +449,8 @@ def rotate_with_retries[T](
The state machine (shared by ``GeminiModel`` / ``GeminiImageModel``):
- * success → ``pool.report(key, "ok", tokens=tokens_of(result))``; keys that
- looked dead during this call are benched (another key proved the request
- itself is fine) and the result is returned.
+ * success → ``pool.report(key, "ok")``; keys that looked dead during this call are
+ benched (another key proved the request itself is fine) and the result is returned.
* ``on_free_retry(err)`` returning ``True`` → retry at once, for free
(no sleep, no budget) — e.g. a thinking-config downgrade.
* ``outcome_of(err) == "dead"`` (key-scoped auth failure) → rotate at once
@@ -731,10 +476,7 @@ def rotate_with_retries[T](
long sleeps that do NOT consume ``max_attempts`` — all inside the
``RETRY_DEADLINE_S`` / ``max_total_s`` deadline. Observed 2026-08-23: a
multi-minute gemini-3.7-flash "high demand" outage killed 8 bench runs
- under the plain 6-attempt budget. A ``storm_gate`` (:class:`StormGate`
- above) shares that discovery across the process:
- workers park at the gate instead of each spending a round-trip to learn
- the model is out of capacity, and one probe at a time reopens it.
+ under the plain 6-attempt budget.
* other retryable errors → exponential backoff + jitter until
``max_attempts``; non-retryable errors raise immediately.
@@ -754,18 +496,11 @@ def rotate_with_retries[T](
never waits for a partner and every hedged request holds its own slot. The calls
run in a per-attempt ``ThreadPoolExecutor`` that is shut down without waiting: a
loser keeps running until its own round-trip ends, then reports its outcome to
- the pool (a late success still reports its tokens) and releases its slot; the
- winner is returned the moment it lands. When every hedged key fails, the attempt
+ the pool and releases its slot; the winner is returned the moment it lands. When every hedged key fails, the attempt
is ONE attempt for the storm / backoff accounting and the worst error decides the
branch (a non-retryable error first, then a plain retryable one, a 429, a dead
key, and a 503 last).
- ``tokens_hint`` is the estimated **prompt** tokens of the pending call
- (:func:`codeverse3d.models.retry.request_tokens`); the pool reserves them in
- the per-key TPM bucket at ``acquire`` and the reservation is reconciled
- against the provider's real count on ``report``, so a 200 k-token judge call
- and a 2 k-token caption are scheduled differently.
-
``stats`` (optional, caller-owned dict) receives the call's telemetry on the way
out — success or failure: ``attempts`` = round-trips issued (hedged siblings
included; 1 = clean), ``hedged`` = hedged attempts, ``storm`` = storm waits.
@@ -801,20 +536,11 @@ def rotate_with_retries[T](
err = classify(exc)
outcome = outcome_of(err)
# a key that looks dead is reported "error" now and benched only once a
- # sibling proves the request itself is fine (bench()). ``tokens`` is what
- # the failure was billed: a 42k-token invalid reply ("skip") used to be
- # refunded as if it had never reached the model.
- consumed = getattr(err, "usage", None)
- pool.report(
- key,
- "error" if outcome == "dead" else outcome,
- tokens=int(consumed.input_tokens) if consumed is not None else 0,
- reserved=tokens_hint,
- retry_after_s=retry_after(exc) if (outcome == "429" and retry_after) else None,
- )
+ # sibling proves the request itself is fine (bench())
+ pool.report(key, "error" if outcome == "dead" else outcome,
+ retry_after_s=retry_after(exc) if (outcome == "429" and retry_after) else None)
return _Try(key, None, err, exc, outcome)
- pool.report(key, "ok", tokens=tokens_of(result) if tokens_of is not None else 0,
- reserved=tokens_hint)
+ pool.report(key, "ok")
return _Try(key, result, None, None, "ok")
finally:
pool.release()
@@ -883,28 +609,18 @@ def rotate_with_retries[T](
# never go back to a key that looked dead this call; throttled keys are
# excluded while an untried one remains, else acquire() waits for a cooldown
exclude = dead_keys | (failed_keys if len(failed_keys) < len(pool) else set())
- if storm_gate is not None:
- storm_gate.enter(None if deadline == float("inf") else deadline)
- if out_of_time():
- # the gate held us past the budget. The check at the top of the loop
- # cannot cover this: a worker parked at a gate ANOTHER thread closed
- # has no last_err, and would go on to spend a full round-trip.
- log.warning("%s budget of %.0f s spent waiting at the storm gate", label, max_total_s)
- gate_err = last_err or classify(TimeoutError(
- f"{label}: retry budget spent waiting for capacity"))
- raise gate_err from cause_for(gate_err, last_exc)
budget_left = None if deadline == float("inf") else max(0.0, deadline - monotonic())
try:
# the key/slot wait must fit the remaining budget, never outlive it
keys = [pool.acquire(
- exclude=exclude, tokens_hint=tokens_hint,
+ exclude=exclude,
timeout_s=ACQUIRE_TIMEOUT_S if budget_left is None
else min(ACQUIRE_TIMEOUT_S, budget_left),
)]
except KeyPoolExhausted as exc:
raise classify(exc) from exc
while hedging and len(keys) < max(1, hedge):
- extra = pool.try_acquire(exclude=exclude | set(keys), tokens_hint=tokens_hint)
+ extra = pool.try_acquire(exclude=exclude | set(keys))
if extra is None:
break # no fresh key / slot right now: never wait for a hedge partner
keys.append(extra)
@@ -925,8 +641,6 @@ def rotate_with_retries[T](
won = next((t for t in tries if t.err is None), None)
if won is not None:
winner = won
- if storm_gate is not None:
- storm_gate.ok()
bench()
return won.result
# every key of this attempt failed: the worst error decides the branch
@@ -971,17 +685,9 @@ def rotate_with_retries[T](
# "<=5 s" wait land at 6.25 s in the wild (observed 2026-08-24).
raw = base_delay * (2 ** min(storm, 8)) * (0.75 + 0.5 * random.random())
delay = clip(min(storm_max_delay, raw))
- if storm_gate is not None:
- # tell every other worker as well: the next one to arrive parks at
- # the gate instead of spending its own round-trip to find the storm
- delay = max(delay, storm_gate.hit(retry_after(exc) if (retry_after and exc) else None))
- log.warning("%s capacity storm %d/%d (%s); gate closed %.0fs",
- label, storm, storm_attempts, err, delay)
- storm_gate.enter(None if deadline == float("inf") else deadline)
- else:
- log.warning("%s capacity storm %d/%d (%s); waiting %.0fs",
- label, storm, storm_attempts, err, delay)
- sleep(delay)
+ log.warning("%s capacity storm %d/%d (%s); waiting %.0fs",
+ label, storm, storm_attempts, err, delay)
+ sleep(delay)
attempt -= 1
continue
if worst.outcome == "429":
@@ -1069,32 +775,3 @@ def _discard_loser(
except Exception as hook_exc: # noqa: BLE001 - accounting is best-effort
log.debug("on_attempt hook failed for hedge loser: %s", hook_exc)
log.debug("hedge loser …%s finished (%s); discarded", t.key[-4:], t.outcome)
-
-
-# ===================================================================== tokens
-def request_parts(request: ChatRequest) -> tuple[list[str], int]:
- """``(text blocks, number of image parts)`` of a request, system prompt and
- response schema included — everything the provider will count as prompt."""
- blocks: list[str] = []
- images = 0
- if request.system:
- blocks.append(request.system)
- if request.response_schema is not None:
- blocks.append(str(request.response_schema))
- for msg in request.messages:
- for part in msg.parts:
- if isinstance(part, TextPart):
- blocks.append(part.text)
- elif isinstance(part, ImagePart):
- images += 1
- return blocks, images
-
-
-def request_tokens(request: ChatRequest, *, model_id: str = "") -> int:
- """Estimated **input** tokens of ``request`` (never negative). An image part is
- counted at 1024 px, the judge payload cap ``Settings.judge.max_px`` (docs/COST.md §3)."""
- from codeverse3d.cost.guard import estimate_call
-
- blocks, images = request_parts(request)
- est = estimate_call(model_id or "gemini:unknown", prompt=blocks, n_images=images)
- return max(0, est.input_tokens)
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index c8982b32..cc26aba0 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -102,10 +102,10 @@ 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 + TPM reservation/reconcile, StormGate — ships OFF,
- docs/COST.md §21 — with_retries / rotate_with_retries, both bounded by
- max_total_s ≤ RETRY_DEADLINE_S with MAX_WAIT_S ≤ 3 s single waits, and the
- prompt-token estimate); pricing.py (version-suffix-only fallback), health.py (preflight
+ error | dead | skip and the max_in_flight cap — no RPM/TPM buckets since
+ 2026-09-22, docs/COST.md §19 — with_retries / rotate_with_retries, both 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
probe: no retries, no backoff), schema_utils.py (strict schema), registry.py
agents/ registry.py (the CodingAgent protocol + dispatch — every backend is a
vendor CLI; the in-process api-agent died 2026-08-28), backends.py
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
index 09b1f399..c5c7ab83 100644
--- a/harness/docs/COST.md
+++ b/harness/docs/COST.md
@@ -915,6 +915,19 @@ quota would allow 1 000 per key. So the meaningful limiter is a *token* rate:
That is what makes a 200 k judge verdict and a 2 k caption schedule differently, and §20
shows it is not theoretical.
+**Deleted 2026-09-22: the buckets never engaged.** Every number above was measured while
+the in-process api-agent sent the generator's 42 k-token turns through this pool. Since it
+went (2026-08-28) the generator is a vendor CLI that makes its own calls and reserves
+nothing here, and the harness's own traffic is the planner, the judge, captions and
+texture images: over the cost ledgers 2026-08-29 .. 09-22 (2 080 Gemini calls, 11 084
+round-trips) the busiest key peaked at **39 k prompt tokens/min — 3.9 % of its 1 M TPM** —
+and **26 calls/min, 2.6 % of its 1 000 RPM** (re-counted on the ledgers on this box:
+2.7 % and 0.7 %). So the per-key RPM/TPM buckets, the reservation (`tokens_hint`,
+`request_tokens`) and its reconciliation, and `Rate.rpm_per_key` / `tpm_per_key` are
+gone; the pool rotates, cools a 429'd key down, benches a dead one and caps what is in
+flight (§20, §23). If a workload ever comes back that fills a key's quota, the 429 it
+earns is rotated away for free (§27) — that is the signal to measure again.
+
## 20. The measured knee — and why one number is not enough
`eval/bench/concurrency_probe.py` runs a fixed workload at several in-flight levels with a
@@ -1024,10 +1037,11 @@ failure really is all-or-nothing.
The A/B was run during *intermittent* 503s, which is what the logs show most of the
time. A single sustained outage is the case the gate was designed for and is not
covered by this measurement — that is why the mechanism is kept rather than deleted.
-So `Settings.rate.storm_gate` defaults to **False**. The mechanism, its counters and
-the probe flag are kept so the experiment is reproducible
-(`C3D_RATE__STORM_GATE=1`, or `eval/bench/concurrency_probe.py --storm-gate`) — the same
-treatment §13 gave cache-friendly prompt ordering.
+So `Settings.rate.storm_gate` defaulted to **False**, and the mechanism was kept so the
+experiment stayed reproducible — until 2026-09-22, when it was **deleted**: §27 made a
+storm mean "every key in the pool 503'd inside this one call", so the gate could close
+only after a whole pool's worth of failed round-trips, and in four weeks shipped OFF
+nobody switched it on.
**Caveat on the knee under a storm.** §20's knee optimises *throughput* — total calls
per minute. A bench cell is judged on *latency* instead: it has a `--max-minutes`
@@ -1046,8 +1060,7 @@ whole 128-call level costs 6 – 35 storm attempts and **zero failures**, which
justify a scheduler rewrite in `fan_out`.
`3dcode doctor --live` prints the pool's live picture — keys, in-flight and peak in-flight,
-RPM/TPM headroom used, 429/5xx/dead counts this process — plus one row per storm gate
-with its storm count, 503 count, probe count and parked seconds.
+429/5xx/dead counts this process.
## 22. The retry budget was counted in attempts, so a "90-minute" run took 200
diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.md
index 7eb70c02..41756353 100644
--- a/harness/docs/INSTALL.md
+++ b/harness/docs/INSTALL.md
@@ -497,10 +497,8 @@ 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 |
-| `gemini quota` | OK | always informational | the per-key RPM/TPM the pool schedules against x the number of keys (`Settings.rate`, docs/COST.md Part III); tune with `C3D_RATE__TPM_PER_KEY` / `C3D_RATE__MAX_IN_FLIGHT` |
| `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 |
-| `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, RPM/TPM headroom used and this process's 429/5xx counts |
-| `storm gate` (`--live`) | WARN | a capacity storm is running | provider-side (`503 high demand`), not an install problem; the gate is off by default (docs/COST.md §21) and the row only appears when something enabled it |
+| `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>/` |
| `skills routing` | WARN | a routed skill has no installed bundle | restore the missing bundle from the checkout or update the stale route |
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 917688b0..940d10e6 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -62,16 +62,16 @@ means the last OK build. `Workspace.restore_paths(commit, paths)` = per-path
```python
from codeverse3d.models import get_chat_model # (model_id) -> ChatModel, lru-cached, thread-safe
resp = m.generate(ChatRequest(messages=[...], system=..., response_schema=..., temperature=..., thinking=..., label=..., max_wait_s=None))
-# max_wait_s: the longest this ONE call may spend, retries included (None = models.retry.RETRY_DEADLINE_S = 900 s);
+# max_wait_s: the longest this ONE call may spend, retries included (None = models.retry.RETRY_DEADLINE_S = 1800 s);
# GeminiModel clips its retry deadline to it; VlmJudge 240 s per sample, planner 300 s
# 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, *, rpm_per_key=900, tpm_per_key=None, cooldown_s=30, dead_cooldown_s=3600)
-pool.acquire(*, tokens_hint=0, exclude=None, timeout_s=120) -> key # raises immediately when every key is dead/cooling past the deadline
-pool.try_acquire(*, tokens_hint=0, exclude=None) -> key | None # never waits (a hedged retry's extra key); holds a slot like acquire
-pool.report(key, "ok"|"429"|"5xx"|"error"|"dead"|"skip", *, tokens=0, retry_after_s=None) # Δ "dead": health 0, benched dead_cooldown_s,
- # re-probed after; "skip" (a content failure the key did not cause) reconciles tokens only — health and counters untouched
+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
+pool.try_acquire(*, exclude=None) -> key | None # never waits (a hedged retry's extra key); holds a slot like acquire
+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 with_retries, rotate_with_retries, RETRY_DEADLINE_S
with_retries(fn, *, is_retryable, attempts=6, base_delay=1.0, max_delay=3.0, max_total_s=None, ...) # max_total_s =
# ChatRequest.max_wait_s clipped to RETRY_DEADLINE_S on every provider; stops before a backoff would cross it, stamps ModelError.attempts
diff --git a/harness/tests/core/test_config_env_aliases.py b/harness/tests/core/test_config_env_aliases.py
index 911f51d0..3e4ca5c5 100644
--- a/harness/tests/core/test_config_env_aliases.py
+++ b/harness/tests/core/test_config_env_aliases.py
@@ -60,7 +60,7 @@ def test_the_rate_and_limits_dials_carry_their_bounds(monkeypatch):
"""Reject rate/worker values that cannot make progress."""
from codeverse3d.config import Limits, Rate
- for kwargs in ({"max_in_flight": -1}, {"rpm_per_key": 0}, {"tpm_per_key": -1}):
+ for kwargs in ({"max_in_flight": -1}, {"hedge": 0}):
with pytest.raises(ValueError):
Rate(**kwargs)
for kwargs in ({"max_parallel_agents": 0}, {"max_parallel_builds": -2}, {"agent_max_turns": -1}):
@@ -79,24 +79,24 @@ def test_a_project_file_overrides_only_the_keys_it_names(tmp_path, monkeypatch):
home = tmp_path / "fakehome"
(home / ".config" / "3dcodeverse").mkdir(parents=True)
(home / ".config" / "3dcodeverse" / "config.yaml").write_text(
- "rate:\n tpm_per_key: 250000\n rpm_per_key: 300\njudge:\n samples: 4\n")
+ "limits:\n agent_timeout_s: 900\n max_parallel_builds: 3\njudge:\n samples: 4\n")
proj = tmp_path / "proj"
proj.mkdir()
- (proj / "3dcodeverse.yaml").write_text("rate:\n max_in_flight: 8\n")
+ (proj / "3dcodeverse.yaml").write_text("limits:\n max_parallel_agents: 4\n")
monkeypatch.setattr(C, "_USER_CONFIG", home / ".config" / "3dcodeverse" / "config.yaml")
monkeypatch.setattr(C, "_LEGACY_USER_CONFIG", home / ".config" / "codeverse" / "config.yaml")
monkeypatch.chdir(proj)
- for var in ("C3D_MAX_IN_FLIGHT", "C3D_RATE__MAX_IN_FLIGHT", "C3D_RATE__TPM_PER_KEY"):
+ for var in ("C3D_LIMITS__MAX_PARALLEL_AGENTS", "C3D_LIMITS__AGENT_TIMEOUT_S", "C3D_LIMITS__MAX_PARALLEL_BUILDS"):
monkeypatch.delenv(var, raising=False)
C.get_settings.cache_clear()
try:
s = C.get_settings()
# the project file's own key applies ...
- assert s.rate.max_in_flight == 8
+ assert s.limits.max_parallel_agents == 4
# ... and the user's siblings in the SAME section survive it
- assert s.rate.tpm_per_key == 250000, "the binding TPM limit must not silently reset"
- assert s.rate.rpm_per_key == 300
+ assert s.limits.agent_timeout_s == 900, "a sibling the project file never named must not reset"
+ assert s.limits.max_parallel_builds == 3
# a section the project file does not name is untouched (this always worked)
assert s.judge.samples == 4
finally:
@@ -137,21 +137,21 @@ def test_the_config_names_before_d78_are_still_read_under_the_new_ones(tmp_path,
home = tmp_path / "fakehome"
(home / ".config" / "codeverse").mkdir(parents=True)
- (home / ".config" / "codeverse" / "config.yaml").write_text("rate:\n tpm_per_key: 250000\n rpm_per_key: 300\n")
+ (home / ".config" / "codeverse" / "config.yaml").write_text("limits:\n agent_timeout_s: 900\n max_parallel_builds: 3\n")
(home / ".config" / "3dcodeverse").mkdir(parents=True)
- (home / ".config" / "3dcodeverse" / "config.yaml").write_text("rate:\n rpm_per_key: 400\n")
+ (home / ".config" / "3dcodeverse" / "config.yaml").write_text("limits:\n max_parallel_builds: 5\n")
proj = tmp_path / "proj"
proj.mkdir()
(proj / "codeverse.yaml").write_text("rate:\n max_in_flight: 8\n")
monkeypatch.setattr(C, "_USER_CONFIG", home / ".config" / "3dcodeverse" / "config.yaml")
monkeypatch.setattr(C, "_LEGACY_USER_CONFIG", home / ".config" / "codeverse" / "config.yaml")
monkeypatch.chdir(proj)
- for var in ("C3D_MAX_IN_FLIGHT", "C3D_RATE__MAX_IN_FLIGHT", "C3D_RATE__TPM_PER_KEY", "C3D_RATE__RPM_PER_KEY"):
+ for var in ("C3D_MAX_IN_FLIGHT", "C3D_RATE__MAX_IN_FLIGHT", "C3D_LIMITS__AGENT_TIMEOUT_S", "C3D_LIMITS__MAX_PARALLEL_BUILDS"):
monkeypatch.delenv(var, raising=False)
C.get_settings.cache_clear()
try:
s = C.get_settings()
- assert (s.rate.tpm_per_key, s.rate.rpm_per_key, s.rate.max_in_flight) == (250000, 400, 8)
+ assert (s.limits.agent_timeout_s, s.limits.max_parallel_builds, s.rate.max_in_flight) == (900, 5, 8)
finally:
C.get_settings.cache_clear()
diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.py
index fff4e5d8..bc88105a 100644
--- a/harness/tests/cost/test_instrument.py
+++ b/harness/tests/cost/test_instrument.py
@@ -381,7 +381,7 @@ def test_a_hedge_losers_tokens_reach_the_ledger_when_it_lands(tmp_path: Path):
return text_response("late loser")
return text_response("winner")
- pool = KeyPool(["k1", "k2", "k3"], rpm_per_key=10_000)
+ pool = KeyPool(["k1", "k2", "k3"])
m = GeminiModel("gemini-3.7-flash", pool=pool, sleep=lambda s: None, client_factory=Client)
with run_ledger(tmp_path, run="r1"):
resp = MeteredChatModel(m).generate(
diff --git a/harness/tests/install/test_docs.py b/harness/tests/install/test_docs.py
index 79fb2493..4376043d 100644
--- a/harness/tests/install/test_docs.py
+++ b/harness/tests/install/test_docs.py
@@ -235,7 +235,7 @@ def test_doctor_rows_have_troubleshooting_entries(monkeypatch) -> None:
settings = SimpleNamespace(
gemini_api_keys=("fake",), anthropic_api_key="", openai_api_key="",
- rate=SimpleNamespace(rpm_per_key=1, tpm_per_key=1_000, max_in_flight=1),
+ rate=SimpleNamespace(max_in_flight=1),
binaries=SimpleNamespace(node="node", gemini_cli="gemini", claude_cli="claude",
codex_cli="codex", agy_cli="agy"),
resolve_blender=lambda: "blender",
@@ -253,11 +253,6 @@ def test_doctor_rows_have_troubleshooting_entries(monkeypatch) -> None:
lambda model: SimpleNamespace(generate=lambda request: SimpleNamespace(
text="pong", usage=SimpleNamespace(cost_usd=0.0))),
)
- gate = SimpleNamespace(snapshot=lambda: {
- "name": "gemini:test", "storming": False, "storms": 0, "hits": 0,
- "probes": 0, "parked_s": 0, "closed_for_s": 0,
- })
- monkeypatch.setattr("codeverse3d.models.retry.all_gates", lambda: [gate])
monkeypatch.setattr("codeverse3d.skills.registry.ROUTED_SKILLS", ("missing",))
rows = doctor_mod.run_doctor(live=True, gpu=True, skills=True)
@@ -283,7 +278,7 @@ def test_doctor_rows_have_troubleshooting_entries(monkeypatch) -> None:
for name in re.findall(r"`([^`]+)`", line.split("|", 2)[1])
if not name.startswith("--")
}
- names = {"storm gate" if name.startswith("storm gate ") else name for name, _, _ in rows}
+ names = {name for name, _, _ in rows}
missing = sorted(names - documented)
assert not missing, f"doctor rows undocumented in docs/INSTALL.md: {missing}"
diff --git a/harness/tests/models/test_gemini_scheduling.py b/harness/tests/models/test_gemini_scheduling.py
index 2a416601..8dcb8f18 100644
--- a/harness/tests/models/test_gemini_scheduling.py
+++ b/harness/tests/models/test_gemini_scheduling.py
@@ -1,70 +1,25 @@
-"""GeminiModel's side of TPM-aware scheduling and the shared storm gate.
+"""GeminiModel's side of the key pool: slots, the shared pool, the retry budget, the hedge.
Offline: the provider is a fake client, the pool is real, and nothing sleeps.
"""
from __future__ import annotations
-import base64
-
import pytest
from google.genai import errors as genai_errors
-from codeverse3d.contracts.chat import ChatMessage, ChatRequest, ImagePart
+from codeverse3d.contracts.chat import ChatMessage, ChatRequest
from codeverse3d.models.base import ModelError
-from codeverse3d.models.gemini import GeminiModel, shared_pool
-from codeverse3d.models.retry import KeyPool, StormGate, request_tokens
-from tests.models.test_gemini import PNG_1PX, make_model, text_response
+from codeverse3d.models.gemini import shared_pool
+from codeverse3d.models.retry import KeyPool
+from tests.models.test_gemini import make_model, text_response
def api_error(code: int, msg: str = "boom") -> genai_errors.APIError:
return genai_errors.APIError(code, {"error": {"message": msg, "code": code}})
-# ------------------------------------------------------------------ estimates
-def test_request_token_estimates_scale_and_treat_images_as_fixed_cost():
- small = ChatRequest(messages=[ChatMessage.user("caption this")])
- big = ChatRequest(messages=[ChatMessage.user("x" * 800_000)])
- rich = ChatRequest(
- messages=[ChatMessage.user("hi", images=[ImagePart(data_b64="x", label="a")])],
- system="a system prompt that is quite long " * 20,
- response_schema={"type": "object", "properties": {"score": {"type": "number"}}},
- )
- path_only = ChatRequest(messages=[ChatMessage.user("hi", images=[ImagePart(path="/nope.png")])])
- large_image = ChatRequest(
- messages=[
- ChatMessage.user(
- "hi", images=[ImagePart(data_b64=base64.b64encode(PNG_1PX * 500).decode())]
- )
- ]
- )
- assert request_tokens(small) < 100
- assert 150_000 < request_tokens(big) < 250_000
- assert request_tokens(rich) > request_tokens(small) + 1000
- assert request_tokens(path_only) > 1000
- assert request_tokens(large_image) < 2000
-
-
-# --------------------------------------------------------------- reservations
-def test_generate_reserves_and_reconciles_tpm():
- pool = KeyPool(["k1"], tpm_per_key=1_000_000)
- m, _log, _ = make_model([text_response("hi")], pool=pool)
- before = pool._by_key["k1"].tpm.tokens # noqa: SLF001
- m.generate(ChatRequest(messages=[ChatMessage.user("y" * 40_000)]))
- after = pool._by_key["k1"].tpm.tokens # noqa: SLF001
- # the fake provider reports prompt_token_count=100, so the ~10k estimate is
- # refunded down to the real 100 (allow a little refill on the wall clock)
- assert before - after < 500, f"reservation was not reconciled: {before - after}"
-
-
-def test_a_failed_call_gives_its_reservation_back():
- pool = KeyPool(["k1", "k2"], tpm_per_key=1_000_000, cooldown_s=0.0)
- m, _log, _ = make_model([api_error(500), text_response("ok")], pool=pool, max_attempts=3)
- m.generate(ChatRequest(messages=[ChatMessage.user("z" * 40_000)]))
- total = sum(s.tpm.tokens for s in pool._states) # noqa: SLF001
- assert total > 2_000_000 - 5_000 # only the one real 100-token call was charged
-
-
+# ------------------------------------------------------------------ slots
def test_in_flight_returns_to_zero_after_success_and_after_failure():
pool = KeyPool(["k1", "k2"], cooldown_s=0.0)
m, _log, _ = make_model([text_response("hi")], pool=pool)
@@ -77,52 +32,20 @@ def test_in_flight_returns_to_zero_after_success_and_after_failure():
# ---------------------------------------------------------------- shared pool
-def test_shared_pool_is_keyed_by_quota_not_only_by_keys():
- a = shared_pool(["x1", "x2"], rpm_per_key=100, tpm_per_key=1000)
- b = shared_pool(["x1", "x2"], rpm_per_key=100, tpm_per_key=1000)
- c = shared_pool(["x1", "x2"], rpm_per_key=100, tpm_per_key=2000)
+def test_shared_pool_is_keyed_by_the_cap_not_only_by_keys():
+ a = shared_pool(["x1", "x2"], max_in_flight=4)
+ b = shared_pool(["x1", "x2"], max_in_flight=4)
+ c = shared_pool(["x1", "x2"], max_in_flight=8)
assert a is b
- assert a is not c, "a different quota must not silently reuse another pool's buckets"
-
-
-# ----------------------------------------------------------------- storm gate
-def test_a_503_closes_the_shared_gate_and_the_call_still_succeeds():
- # probe_lease_s=0: the free rotation re-enters the gate, so this thread takes the
- # probe slot and would then park on its OWN 30 s lease until the retry deadline —
- # 30 s of wall clock for a test about whether the call survives the storm.
- gate = StormGate("test", base_delay=0.0, max_wait_s=0.0, probe_lease_s=0.0)
- pool = KeyPool(["k1", "k2"], cooldown_s=0.0)
- # a 503 is per key at any instant (retry.py docstring, measured 2026-08-26): the first
- # one rotates to k2 for free; only k2's 503 — no untried key left in this 2-key pool —
- # makes it a storm and closes the gate
- m, _log, _ = make_model(
- [api_error(503, "high demand"), api_error(503, "high demand"), text_response("ok")],
- pool=pool,
- max_attempts=3,
- )
- m.storm_gate = gate
- r = m.generate(ChatRequest(messages=[ChatMessage.user("hi")]))
- assert r.text == "ok"
- assert gate.n_hits == 1 and gate.n_storms == 1
- assert not gate.snapshot()["storming"], "the success must reopen the gate"
+ assert a is not c, "a different cap must not silently reuse another pool's slots"
-def test_rate_settings_control_the_shared_gate_and_hedge(monkeypatch):
+def test_the_hedge_comes_from_settings(monkeypatch):
from codeverse3d.config import Rate, get_settings
- s = get_settings()
- assert s.rate.storm_gate is False
- assert GeminiModel("gemini-3.7-flash", keys=["z1"]).storm_gate is None
assert make_model([])[0].hedge == 2
assert make_model([], hedge=1)[0].hedge == 1
-
- monkeypatch.setattr(s, "rate", Rate(storm_gate=True, hedge=1))
- a = GeminiModel("gemini-3.7-flash", keys=["z1"])
- b = GeminiModel("gemini-3.7-flash", keys=["z1"])
- c = GeminiModel("gemini-3.1-pro-preview", keys=["z1"])
- assert a.storm_gate is not None
- assert a.storm_gate is b.storm_gate
- assert a.storm_gate is not c.storm_gate
+ monkeypatch.setattr(get_settings(), "rate", Rate(hedge=1))
assert make_model([])[0].hedge == 1
diff --git a/harness/tests/models/test_keypool.py b/harness/tests/models/test_keypool.py
index 64bacbbd..8a0d8967 100644
--- a/harness/tests/models/test_keypool.py
+++ b/harness/tests/models/test_keypool.py
@@ -1,4 +1,4 @@
-"""KeyPool: rotation, 429 cooldown, buckets, health, exhaustion, stats."""
+"""KeyPool: rotation, 429 cooldown, health, exhaustion, the in-flight cap, stats."""
from __future__ import annotations
@@ -7,7 +7,7 @@ import time
import pytest
-from codeverse3d.models.retry import MAX_WAIT_S, KeyPool, KeyPoolExhausted, TokenBucket
+from codeverse3d.models.retry import MAX_WAIT_S, KeyPool, KeyPoolExhausted
class Clock:
@@ -58,18 +58,6 @@ def test_exclude_skips_failed_keys():
pool.acquire(exclude={"k1", "k2", "k3"})
-def test_rpm_bucket_blocks_then_refills():
- pool, clock = make(keys=("solo",), rpm_per_key=60) # 1 token / s, capacity 60
- for _ in range(60):
- pool.acquire(timeout_s=0.0)
- with pytest.raises(KeyPoolExhausted):
- pool.acquire(timeout_s=0.0)
- # blocking acquire advances the fake clock until a token refills
- t0 = clock.t
- assert pool.acquire(timeout_s=10.0) == "solo"
- assert clock.t > t0
-
-
def test_all_cooling_blocks_until_cooldown_ends():
# a cooldown longer than the house cap is clipped to it: no single wait may
# exceed MAX_WAIT_S, patience comes from the number of attempts
@@ -101,16 +89,8 @@ def test_health_score_prefers_healthy_keys():
assert s["…bad"]["health"] > 0.9
-def test_tpm_bucket_honours_hint():
- pool, _ = make(keys=("a", "b"), tpm_per_key=1000)
- assert pool.acquire(tokens_hint=800) == "a"
- assert pool.acquire(tokens_hint=800) == "b" # a has only 200 left
- with pytest.raises(KeyPoolExhausted):
- pool.acquire(tokens_hint=800, timeout_s=0.0)
-
-
def test_thread_safety_smoke():
- pool = KeyPool([f"k{i}" for i in range(5)], rpm_per_key=100000)
+ pool = KeyPool([f"k{i}" for i in range(5)])
counts: dict[str, int] = {}
lock = threading.Lock()
@@ -129,13 +109,6 @@ def test_thread_safety_smoke():
assert sum(counts.values()) == 1600 and len(counts) == 5
-def test_token_bucket_math():
- b = TokenBucket(capacity=10, rate=1.0, updated=0.0)
- assert b.try_take(10, 0.0) and not b.try_take(1, 0.0)
- assert b.wait_for(5, 0.0) == 5.0
- assert b.try_take(5, 5.0)
-
-
def test_dead_key_is_benched_for_a_long_time_then_reprobed():
pool, clock = make(keys=("dead", "ok"), cooldown_s=30, dead_cooldown_s=3600)
pool.report("dead", "dead")
@@ -177,10 +150,12 @@ def test_try_acquire_never_waits_for_a_key_or_a_slot():
pool.report("k2", "429")
assert pool.try_acquire() is None, "every key is cooling down: no wait, no key"
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, rpm_per_key=10_000)
+ pool = KeyPool(["a"], max_in_flight=1)
pool.acquire()
t0 = time.monotonic()
with pytest.raises(KeyPoolExhausted):
@@ -190,13 +165,57 @@ def test_the_in_flight_slot_wait_is_bounded_by_timeout():
assert pool.acquire(timeout_s=0.5) == "a", "the slot came back; nothing leaked"
-def test_skip_reconciles_tokens_but_leaves_health_and_counters_alone():
+def test_skip_leaves_health_and_counters_alone():
"""A charged-but-invalid reply (bad JSON) is not the key's fault: it used to be
reported "ok", boosting health and counting as a success in doctor --live."""
- pool, _ = make(keys=("a",), tpm_per_key=100_000)
+ pool, _ = make(keys=("a",))
pool.report("a", "429")
before = {k["key"]: k for k in pool.stats()["keys"]}["…a"]
- pool.report("a", "skip", tokens=7_500, reserved=2_000)
+ pool.report("a", "skip")
after = {k["key"]: k for k in pool.stats()["keys"]}["…a"]
assert after["health"] == before["health"] and after["ok"] == before["ok"] and after["error"] == before["error"]
- assert pool.stats()["tokens_used"] == 7_500
+
+
+# ------------------------------------------------------------- in-flight cap
+def test_in_flight_gauge_tracks_acquire_and_release():
+ pool, _ = make(keys=("a", "b"))
+ pool.acquire()
+ pool.acquire()
+ assert pool.stats()["in_flight"] == 2
+ assert pool.stats()["peak_in_flight"] == 2
+ pool.release()
+ assert pool.stats()["in_flight"] == 1
+ assert pool.stats()["peak_in_flight"] == 2 # peak is a high-water mark
+ pool.release()
+ pool.release() # a stray release is a no-op, not a crash
+ assert pool.stats()["in_flight"] == 0
+
+
+def test_max_in_flight_blocks_the_third_caller():
+ pool = KeyPool(["a", "b", "c"], max_in_flight=2)
+ pool.acquire()
+ pool.acquire()
+ started = threading.Event()
+ got = threading.Event()
+
+ def third() -> None:
+ started.set()
+ pool.acquire()
+ got.set()
+
+ t = threading.Thread(target=third, daemon=True)
+ t.start()
+ started.wait(2)
+ assert not got.wait(0.2), "the 3rd call should be held by the in-flight cap"
+ pool.release()
+ assert got.wait(2), "releasing a slot must let the queued call through"
+ t.join(2)
+
+
+def test_a_failed_acquire_gives_its_slot_back():
+ """KeyPoolExhausted must not leak a concurrency slot."""
+ pool = KeyPool(["a"], max_in_flight=1)
+ 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
diff --git a/harness/tests/models/test_keypool_tpm.py b/harness/tests/models/test_keypool_tpm.py
deleted file mode 100644
index 2e510799..00000000
--- a/harness/tests/models/test_keypool_tpm.py
+++ /dev/null
@@ -1,129 +0,0 @@
-"""TPM-aware scheduling: reservation at ``acquire``, reconciliation at ``report``,
-and the process-wide in-flight cap. Everything runs on a fake clock.
-"""
-
-from __future__ import annotations
-
-import threading
-
-import pytest
-
-from codeverse3d.models.retry import KeyPool, KeyPoolExhausted
-
-
-class Clock:
- def __init__(self) -> None:
- self.t = 1000.0
-
- def __call__(self) -> float:
- return self.t
-
- def sleep(self, s: float) -> None:
- self.t += s
-
-
-def make(keys=("a", "b"), **kw) -> tuple[KeyPool, Clock]:
- c = Clock()
- return KeyPool(list(keys), clock=c, sleep=c.sleep, **kw), c
-
-
-def tpm_left(pool: KeyPool, key: str) -> float:
- return pool._by_key[key].tpm.tokens # noqa: SLF001 - white-box on purpose
-
-
-# --------------------------------------------------------------- reservations
-def test_a_big_call_and_a_small_call_are_scheduled_differently():
- """A judge-sized reservation exhausts a key; a caption-sized one does not."""
- pool, _ = make(keys=("a",), tpm_per_key=250_000)
- assert pool.acquire(tokens_hint=200_000) == "a"
- # 50k left: the 2k caption still fits, another 200k judge call does not
- assert pool.acquire(tokens_hint=2_000) == "a"
- with pytest.raises(KeyPoolExhausted):
- pool.acquire(tokens_hint=200_000, timeout_s=0.0)
-
-
-def test_reservations_reconcile_to_actual_provider_consumption():
- for reserved, outcome, actual, expected in (
- (60_000, "ok", 10_000, 90_000),
- (10_000, "ok", 95_000, 5_000),
- (90_000, "5xx", 0, 100_000),
- (50_000, "error", 42_000, 58_000),
- ):
- pool, _ = make(keys=("a",), tpm_per_key=100_000, cooldown_s=0.0)
- pool.acquire(tokens_hint=reserved)
- pool.report("a", outcome, tokens=actual, reserved=reserved)
- assert tpm_left(pool, "a") == pytest.approx(expected)
-
-
-def test_the_bucket_may_go_negative_and_is_paid_off_by_refill():
- pool, clock = make(keys=("a",), tpm_per_key=60_000) # 1000 tokens/s
- pool.acquire(tokens_hint=1_000)
- pool.report("a", "ok", tokens=100_000, reserved=1_000)
- assert tpm_left(pool, "a") < 0
- with pytest.raises(KeyPoolExhausted):
- pool.acquire(tokens_hint=1_000, timeout_s=0.0)
- clock.t += 60 # a full minute of refill clears the debt
- assert pool.acquire(tokens_hint=1_000) == "a"
-
-
-def test_tpm_stats_reflect_capacity_and_spend():
- pool, _ = make(keys=("a", "b"), tpm_per_key=100_000)
- assert pool.stats()["tpm_headroom"] == 1.0
- pool.acquire(tokens_hint=50_000)
- pool.report("a", "ok", tokens=7_500, reserved=50_000)
- stats = pool.stats()
- assert stats["tokens_used"] == 7_500
- assert stats["tpm_capacity"] == 200_000
- assert stats["tpm_headroom"] == pytest.approx(0.963)
-
-
-def test_no_tpm_bucket_means_no_tpm_accounting():
- pool, _ = make(keys=("a",))
- assert pool.acquire(tokens_hint=10**9) == "a" # unlimited without a bucket
- assert pool.stats()["tpm_headroom"] is None
- assert pool.stats()["tpm_capacity"] == 0
-
-
-# ------------------------------------------------------------- in-flight cap
-def test_in_flight_gauge_tracks_acquire_and_release():
- pool, _ = make(keys=("a", "b"))
- pool.acquire()
- pool.acquire()
- assert pool.stats()["in_flight"] == 2
- assert pool.stats()["peak_in_flight"] == 2
- pool.release()
- assert pool.stats()["in_flight"] == 1
- assert pool.stats()["peak_in_flight"] == 2 # peak is a high-water mark
- pool.release()
- pool.release() # a stray release is a no-op, not a crash
- assert pool.stats()["in_flight"] == 0
-
-
-def test_max_in_flight_blocks_the_third_caller():
- pool = KeyPool(["a", "b", "c"], max_in_flight=2, rpm_per_key=10_000)
- pool.acquire()
- pool.acquire()
- started = threading.Event()
- got = threading.Event()
-
- def third() -> None:
- started.set()
- pool.acquire()
- got.set()
-
- t = threading.Thread(target=third, daemon=True)
- t.start()
- started.wait(2)
- assert not got.wait(0.2), "the 3rd call should be held by the in-flight cap"
- pool.release()
- assert got.wait(2), "releasing a slot must let the queued call through"
- t.join(2)
-
-
-def test_a_failed_acquire_gives_its_slot_back():
- """KeyPoolExhausted must not leak a concurrency slot."""
- pool = KeyPool(["a"], max_in_flight=1, rpm_per_key=10_000)
- 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
diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.py
index 6e269565..b2e2ef7c 100644
--- a/harness/tests/models/test_retry.py
+++ b/harness/tests/models/test_retry.py
@@ -8,7 +8,6 @@ import time
import pytest
-from codeverse3d.contracts.common import Usage
from codeverse3d.models.base import ModelError
from codeverse3d.models.parts import SDK_TIMEOUT_FLOOR_S
from codeverse3d.models.retry import (
@@ -18,7 +17,6 @@ from codeverse3d.models.retry import (
KeyPool,
KeyPoolExhausted,
Outcome,
- StormGate,
backoff_delay,
rotate_with_retries,
with_retries,
@@ -129,8 +127,7 @@ def _503(e: BaseException) -> ModelError:
def _pool(n: int = 3, **kw) -> KeyPool:
- """A pool of ``n`` keys with the per-key RPM limiter effectively off."""
- kw.setdefault("rpm_per_key", 10_000)
+ """A pool of ``n`` keys."""
return KeyPool([f"k{i}" for i in range(1, n + 1)], **kw)
@@ -171,9 +168,9 @@ def _boom(msg: str = "503 high demand"):
return call
-def test_rotate_success_reports_ok_with_tokens():
+def test_rotate_success_reports_ok():
pool = KeyPool(["k1", "k2"])
- out = _rotate(pool, lambda key: f"ok:{key}", tokens_of=lambda r: 42)
+ out = _rotate(pool, lambda key: f"ok:{key}")
assert out == "ok:k1"
st = pool.stats()
assert st["ok"] == 1 and st["429"] == 0 and st["dead"] == 0
@@ -394,7 +391,6 @@ def test_the_deadline_does_not_cut_a_call_that_is_making_progress():
def test_503_rotates_through_every_untried_key_before_it_is_a_storm():
"""A 503 rotates freely while the pool still has an untried key."""
keys = [f"k{i}" for i in range(1, 11)]
- gate = StormGate()
lock = threading.Lock()
calls: list[str] = []
naps: list[float] = []
@@ -407,6 +403,7 @@ def test_503_rotates_through_every_untried_key_before_it_is_a_storm():
raise RuntimeError("503 high demand")
return "ok"
+ stats: dict = {}
out = _rotate503(
_pool(10),
call,
@@ -414,24 +411,23 @@ def test_503_rotates_through_every_untried_key_before_it_is_a_storm():
storm_attempts=10,
storm_max_delay=0.05,
sleep=naps.append,
- storm_gate=gate,
+ stats=stats,
)
# one key per round-trip, never twice: 9 free rotations, then the 10th key lands
assert out == "ok" and len(calls) == len(keys) and set(calls) == set(keys)
assert naps == [], "rotation to a fresh key costs no sleep"
- assert gate.n_storms == 0 and not gate.snapshot()["storming"], "an untried key remains: not a storm"
+ assert stats["storm"] == 0, "an untried key remains: not a storm"
@pytest.mark.parametrize(
- ("hedge", "want_calls", "want_hits", "want_stats"),
+ ("hedge", "want_calls", "want_stats"),
[
- (1, {6}, 3, {"attempts": 6, "hedged": 0, "storm": 3}),
- (2, {6, 7}, 2, {"attempts": 7, "hedged": 3, "storm": 2}),
+ (1, {6}, {"attempts": 6, "hedged": 0, "storm": 3}),
+ (2, {6, 7}, {"attempts": 7, "hedged": 3, "storm": 2}),
],
)
-def test_503_on_every_key_is_still_a_storm(hedge, want_calls, want_hits, want_stats):
+def test_503_on_every_key_is_still_a_storm(hedge, want_calls, want_stats):
"""Exhausting every key engages one bounded wait per hedged attempt."""
- gate = StormGate("t", base_delay=0.0, max_wait_s=0.0, probe_lease_s=0.0) # no real waits
lock = threading.Lock()
n = {"c": 0}
stats: dict = {}
@@ -449,16 +445,12 @@ def test_503_on_every_key_is_still_a_storm(hedge, want_calls, want_hits, want_st
call,
max_attempts=3,
storm_attempts=10,
- storm_max_delay=0.05,
- storm_gate=gate,
+ storm_max_delay=0.0,
hedge=hedge,
stats=stats,
)
assert out == "ok" and n["c"] in want_calls
- assert gate.n_storms == 1 and gate.n_hits == want_hits, (
- "declared only after all three keys failed, then waited out"
- )
- assert stats == want_stats
+ assert stats == want_stats, "declared only after all three keys failed, then waited out"
# --------------------------------------------------------------------------- hedging (audit 2026-08-26 §5.2)
@@ -472,7 +464,7 @@ def _wait_idle(pool, timeout: float = 5.0) -> None:
def test_after_the_first_503_the_next_attempt_is_hedged_and_the_first_success_wins():
"""After a 503, fresh keys race and the first success wins."""
- pool = KeyPool(["k1", "k2", "k3", "k4"], rpm_per_key=10_000, max_in_flight=8)
+ pool = KeyPool(["k1", "k2", "k3", "k4"], max_in_flight=8)
release_k2 = threading.Event()
lock = threading.Lock()
calls: list[str] = []
@@ -497,7 +489,6 @@ def test_after_the_first_503_the_next_attempt_is_hedged_and_the_first_success_wi
max_attempts=3,
storm_attempts=10,
sleep=naps.append,
- tokens_of=lambda r: 7,
stats=stats,
)
assert out == "ok:k3"
@@ -517,9 +508,9 @@ def test_after_the_first_503_the_next_attempt_is_hedged_and_the_first_success_wi
assert st["5xx"] == 2 and st["in_flight"] == 0, "the loser's 503 is reported when it lands"
-def test_a_loser_that_succeeds_later_is_discarded_but_its_tokens_are_reported():
- """A late successful loser is discarded but still charged to its key."""
- pool = KeyPool(["k1", "k2", "k3"], rpm_per_key=10_000, tpm_per_key=1_000_000)
+def test_a_loser_that_succeeds_later_is_discarded_but_reported_to_its_key():
+ """A late successful loser is discarded, and its key still hears the success."""
+ pool = KeyPool(["k1", "k2", "k3"])
release_k2 = threading.Event()
def call(key):
@@ -535,13 +526,12 @@ def test_a_loser_that_succeeds_later_is_discarded_but_its_tokens_are_reported():
call,
max_attempts=3,
storm_attempts=10,
- tokens_of=lambda r: 900 if r.endswith("k2") else 100,
)
assert out == "ok:k3"
release_k2.set()
_wait_idle(pool)
assert pool.stats()["ok"] == 2
- assert pool._by_key["k2"].tokens_used == 900 and pool._by_key["k3"].tokens_used == 100 # noqa: SLF001
+ 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():
@@ -622,11 +612,11 @@ def test_the_key_wait_is_clipped_to_the_remaining_budget():
seen: list[float | None] = []
class SpyPool(KeyPool):
- def acquire(self, *, tokens_hint=0, exclude=None, timeout_s=None):
+ def acquire(self, *, exclude=None, timeout_s=None):
seen.append(timeout_s)
- return super().acquire(tokens_hint=tokens_hint, exclude=exclude, timeout_s=timeout_s)
+ return super().acquire(exclude=exclude, timeout_s=timeout_s)
- pool = SpyPool(["k1"], rpm_per_key=10_000)
+ pool = SpyPool(["k1"])
assert _rotate(pool, lambda key: "ok", max_total_s=50.0) == "ok"
assert _rotate(pool, lambda key: "ok") == "ok" # the default budget: the pool default caps
assert seen[0] == pytest.approx(50.0, abs=1.0)
@@ -670,28 +660,6 @@ def test_free_429_rotation_cannot_outlive_the_deadline():
assert len(calls) <= 5, "ten keys would all have been tried before"
-def test_the_pool_is_not_refunded_for_a_charged_but_invalid_reply():
- """A billed invalid response must consume its actual TPM usage."""
- clock = Clock(1000.0)
- pool = _pool(1, tpm_per_key=100_000, clock=clock, sleep=clock.sleep)
- calls = {"n": 0}
-
- def call(key):
- calls["n"] += 1
- if calls["n"] == 1:
- raise ModelError(
- "structured output is not valid JSON",
- retryable=True,
- usage=Usage(input_tokens=42_000),
- )
- return "ok"
-
- out = _rotate(pool, call, max_attempts=3, tokens_hint=1_000, tokens_of=lambda r: 100)
- assert out == "ok" and calls["n"] == 2
- left = pool._by_key["k1"].tpm.tokens # noqa: SLF001 - white-box on purpose
- assert left == pytest.approx(100_000 - 42_000 - 100)
-
-
# --------------------------------------------------------------------------- on_attempt hook (2026-08-27)
def test_on_attempt_hears_every_round_trip_and_a_late_hedge_loser():
"""The attempt hook reports winners, failures, and late hedge losers."""
@@ -767,32 +735,3 @@ def test_error_causes_avoid_cycles_and_preserve_real_wrapped_errors():
with pytest.raises(ModelError) as ei:
_rotate(_pool(), timeout, max_attempts=1)
assert isinstance(ei.value.__cause__, TimeoutError)
-
-
-def test_a_budget_spent_at_the_storm_gate_issues_no_round_trip():
- """A worker waking past its gate deadline issues no request."""
- clock = Clock(1000.0)
- calls: list[str] = []
-
- class Gate: # parks the caller for longer than the whole budget
- def enter(self, deadline=None):
- clock.t += 30.0
- return 30.0
-
- def hit(self, retry_after=None):
- return 0.0
-
- def ok(self):
- pass
-
- with pytest.raises(ModelError) as e:
- _rotate(
- _pool(1),
- lambda key: calls.append(key),
- max_total_s=5.0,
- monotonic=clock,
- storm_gate=Gate(),
- label="t",
- )
- assert calls == [], "a round-trip was issued after the budget was already spent"
- assert "capacity" in str(e.value)
diff --git a/harness/tests/models/test_storm.py b/harness/tests/models/test_storm.py
deleted file mode 100644
index fb36beeb..00000000
--- a/harness/tests/models/test_storm.py
+++ /dev/null
@@ -1,145 +0,0 @@
-"""StormGate: one shared 503 wait instead of one per worker. Fake clock."""
-
-from __future__ import annotations
-
-import threading
-
-import pytest
-
-from codeverse3d.models.retry import MAX_WAIT_S, StormGate, all_gates, storm_gate
-
-
-class Clock:
- """Fake clock; ``sleep`` just moves time forward (single-threaded tests)."""
-
- def __init__(self) -> None:
- self.t = 100.0
-
- def __call__(self) -> float:
- return self.t
-
- def sleep(self, s: float) -> None:
- self.t += s
-
-
-def make(**kw) -> tuple[StormGate, Clock]:
- c = Clock()
- return StormGate("test", clock=c, sleep=c.sleep, **kw), c
-
-
-def test_a_hit_closes_the_gate_and_the_next_worker_parks():
- gate, clock = make(base_delay=4.0)
- closed = gate.hit()
- assert closed == min(4.0, MAX_WAIT_S) # the house cap clips the gate's own delay
- assert gate.snapshot()["storming"]
- waited = gate.enter()
- assert waited >= closed
- assert gate.parked_s >= closed
-
-
-class Parked(Exception):
- """Raised by the test clock the first time a caller is put to sleep."""
-
-
-def test_one_probe_at_a_time_while_the_storm_lasts():
- """After the window elapses exactly one worker is let through as a probe;
- every other worker parks instead of probing as well."""
- clock = Clock()
-
- def sleep_once(s: float) -> None:
- clock.t += s
- raise Parked
-
- gate = StormGate("test", base_delay=1.0, probe_lease_s=30.0, clock=clock, sleep=sleep_once)
- gate.hit()
- clock.t += 5 # the closure window has passed
- assert gate.enter() == 0.0 # this thread is the probe
- assert gate.n_probes == 1
- with pytest.raises(Parked):
- gate.enter() # a second thread parks on the probe's lease
- assert gate.n_probes == 1
- assert gate.parked_s > 0
-
-
-def test_a_wedged_probe_cannot_block_forever():
- gate, clock = make(base_delay=1.0, probe_lease_s=10.0)
- gate.hit()
- clock.t += 5
- gate.enter() # probe 1, which then dies without reporting
- clock.t += 11 # its lease expires
- assert gate.enter() == 0.0
- assert gate.n_probes == 2
-
-
-def test_a_success_reopens_the_gate_for_everybody():
- gate, clock = make(base_delay=4.0)
- gate.hit()
- gate.ok()
- assert not gate.snapshot()["storming"]
- assert gate.enter() == 0.0
- assert clock.t == 100.0
-
-
-def test_hits_escalate_and_cap_then_success_resets_the_storm():
- gate, _ = make(base_delay=0.5)
- first = gate.hit()
- second = gate.hit()
- assert first <= second <= MAX_WAIT_S
- for _ in range(8):
- assert gate.hit() <= MAX_WAIT_S
- assert gate.snapshot()["storms"] == 1
- gate.ok()
- assert gate.hit() == first
- snap = gate.snapshot()
- assert snap["hits"] == 11
- assert snap["storms"] == 2
- assert snap["name"] == "test"
- capped, _ = make(base_delay=1.0)
- assert capped.hit(retry_after_s=600.0) == MAX_WAIT_S
-
-
-def test_registry_is_per_model_and_shared():
- a = storm_gate("gemini:flash-x")
- b = storm_gate("gemini:flash-x")
- c = storm_gate("gemini:pro-x")
- assert a is b
- assert a is not c
- assert a in all_gates() and c in all_gates()
-
-
-def test_many_workers_share_one_storm_discovery():
- """The point of the gate: N workers meeting a storm cost ONE failed call,
- not N. Here 12 threads race; only the probes may 'call' the provider."""
- gate = StormGate("race", base_delay=0.05, probe_lease_s=0.5)
- calls: list[int] = []
- lock = threading.Lock()
- stop = threading.Event()
- gate.hit() # a storm is already running when the workers arrive
-
- def worker(i: int) -> None:
- gate.enter()
- with lock:
- calls.append(i)
- stop.set()
-
- threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(12)]
- for t in threads:
- t.start()
- stop.wait(3)
- with lock:
- n_first = len(calls)
- assert n_first <= 2, f"{n_first} workers issued a call into a known storm"
- gate.ok()
- for t in threads:
- t.join(3)
- assert len(calls) == 12 # everybody gets through once the gate reopens
-
-
-def test_enter_returns_at_the_deadline_even_mid_storm():
- """A parked worker with a retry deadline gets control back at that deadline
- (rotate_with_retries then raises); the gate never holds it hostage."""
- gate, clock = make(base_delay=4.0)
- gate.hit()
- waited = gate.enter(deadline=clock.t + 1.5)
- assert waited == pytest.approx(1.5)
- assert gate.snapshot()["storming"], "the storm is still on; only this caller's budget ended"