Skip to content

Official Codebase of 3DCodeVerse

Python

retry: a 503 is per key at any instant — rotate to a fresh key before waiting out a storm

gaoypeng610814b4f66d
diff --git a/harness/codeverse/models/retry.py b/harness/codeverse/models/retry.py
index 5e898a47..d35bbcff 100644
--- a/harness/codeverse/models/retry.py
+++ b/harness/codeverse/models/retry.py
@@ -101,6 +101,7 @@ def rotate_with_retries[T](
max_delay: float = MAX_WAIT_S,
storm_attempts: int = 60,
storm_max_delay: float = MAX_WAIT_S,
+ storm_quorum: int = 6,
max_total_s: float = RETRY_DEADLINE_S,
sleep: Callable[[float], None] = time.sleep,
monotonic: Callable[[], float] = time.monotonic,
@@ -126,8 +127,14 @@ def rotate_with_retries[T](
* ``"429"`` → cool the key down (honouring ``retry_after``); rotation is
FREE while an untried key remains (0.5 s courtesy pause), otherwise the
429 counts against ``max_attempts`` with exponential backoff.
- * a **capacity storm** (HTTP 503/529 — model-wide, key rotation cannot
- help) gets its own patience budget: up to ``storm_attempts`` waits with
+ * a 503/529 is tried on a FRESH key first, for free (no sleep, no budget):
+ measured 2026-08-26 with one tiny request per key in parallel, three rounds
+ 20 s apart, during the day's "high demand" storm — gemini-3.7-flash answered
+ on 15/22, 18/22 and 21/22 keys while 5, 4 and 1 keys said 503 at the same
+ instant. A 503 is per key at any moment, so the next key is the cure and a
+ wait is the last resort. Only once ``storm_quorum`` distinct keys (capped
+ at the pool size) have 503'd within this call is it a
+ * **capacity storm**: that gets its own patience budget — up to ``storm_attempts`` waits with
backoff capped at ``storm_max_delay`` = 5 s per wait (the house rule), so
patience comes from the NUMBER of waits (60 x <=5 s ~ 5 min) rather than
from long sleeps that do NOT consume ``max_attempts``. Observed 2026-08-23: a
@@ -207,8 +214,16 @@ def rotate_with_retries[T](
retry_after_s=retry_after(exc) if (outcome == "429" and retry_after) else None,
)
if err.retryable and err.status in (503, 529) and storm < storm_attempts and not out_of_time():
- # capacity storm: model-wide, so waiting (on a rotated key) is the
- # only cure — paid from its own budget, not max_attempts
+ failed_keys.add(key)
+ if len(failed_keys) < min(max(1, storm_quorum), len(pool)):
+ # a 503 is per key at any instant (see the docstring): the next
+ # key is the cure — free rotation, no sleep, no storm yet
+ attempt -= 1
+ log.warning("%s key …%s 503 (%s); rotating to a fresh key (%d/%d tried)",
+ label, key[-4:], err, len(failed_keys), len(pool))
+ continue
+ # capacity storm: enough distinct keys said 503 in this call, so
+ # waiting is the only cure — paid from its own budget, not max_attempts
storm += 1
# jitter FIRST, cap LAST: capping before a >1 jitter factor let a
# "<=5 s" wait land at 6.25 s in the wild (observed 2026-08-24).
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
index 697e5694..72748235 100644
--- a/harness/docs/COST.md
+++ b/harness/docs/COST.md
@@ -1200,3 +1200,23 @@ scarce resource — the runaway is still stopped, by the ceiling that actually a
it. Note the corollary for benchmarking: an arm on a subscription backend and an arm on
an API backend are not being held to the same ceiling, so compare them on
`notional_usd`, never on `spent_usd`.
+
+
+## 24. A 503 is per key at any instant — rotate before you wait (2026-08-26)
+
+The retry path treated Gemini's *"This model is currently experiencing high demand"* (503) as
+model-wide: no rotation, a ≤ 5 s sleep per storm attempt (60 of them), the 900 s per-call
+deadline — and, when the gate was on, every worker in the process parked. Measured with one
+tiny request per key fired in parallel, three rounds 20 s apart, in the middle of the day's
+storm: `gemini-3.7-flash` answered on **15/22, 18/22 and 21/22 keys** while **5, 4 and 1**
+keys returned 503 at the same instant (successful latencies 1.3–38 s; the slow ones were the
+same few keys). So at any moment most keys work and the next key is the cure.
+
+`rotate_with_retries` now adds the 503'd key to the call's failed set and rotates to a fresh
+key for free (no sleep, no budget); only once `storm_quorum` (6, capped at the pool size)
+distinct keys have 503'd within one call is it a storm and the old wait budget applies. What
+this buys per call is the whole storm wait it used to pay first (median 5 s × the storm
+streak, up to 900 s); what it costs is one more round-trip on a fresh key. Follow-ups worth
+measuring: rank keys by recent latency (the 30 s keys are consistent), and record the key
+index in `telemetry/usage.jsonl` so the distribution of calls per key can be read instead of
+probed.
diff --git a/harness/tests/models/test_gemini_scheduling.py b/harness/tests/models/test_gemini_scheduling.py
index f13e04a5..02954bb0 100644
--- a/harness/tests/models/test_gemini_scheduling.py
+++ b/harness/tests/models/test_gemini_scheduling.py
@@ -103,7 +103,9 @@ def test_shared_pool_takes_its_defaults_from_settings():
def test_a_503_closes_the_shared_gate_and_the_call_still_succeeds():
gate = StormGate("test", base_delay=0.0, max_wait_s=0.0)
pool = KeyPool(["k1", "k2"], cooldown_s=0.0)
- m, _log, _ = make_model([api_error(503, "high demand"), text_response("ok")],
+ # 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 completes the 2-key quorum 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")]))
diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.py
index 40b13c94..893b1d9c 100644
--- a/harness/tests/models/test_retry.py
+++ b/harness/tests/models/test_retry.py
@@ -236,7 +236,8 @@ def test_503_storm_has_its_own_patience_budget():
sleep=naps.append,
)
assert out == "ok" and calls["n"] == 9
- assert len(naps) == 8 and all(d <= 0.05 for d in naps) # the cap is the cap
+ # the first 503 rotates to k2 for free (no nap); k2's 503 completes the 2-key quorum
+ assert len(naps) == 7 and all(d <= 0.05 for d in naps) # the cap is the cap
def test_storm_waits_never_exceed_the_house_limit_at_production_defaults():
@@ -360,3 +361,55 @@ def test_the_deadline_does_not_cut_a_call_that_is_making_progress():
monotonic=lambda: clock["t"],
)
assert out == "ok" and calls["n"] == 3
+
+
+def test_503_rotates_to_a_fresh_key_before_it_is_a_storm():
+ """Measured 2026-08-26: one tiny request per key in parallel during the day's storm —
+ flash answered on 15/22, 18/22, 21/22 keys while 5/4/1 keys said 503 at the same instant.
+ A 503 is per key at any moment; the next key is the cure, the storm wait the last resort."""
+ from codeverse.models.base import ModelError
+ from codeverse.models.keypool import KeyPool
+ from codeverse.models.retry import rotate_with_retries
+ from codeverse.models.storm import StormGate
+
+ pool = KeyPool(["k1", "k2", "k3", "k4"], rpm_per_key=10_000)
+ gate = StormGate()
+ calls: list[str] = []
+ naps: list[float] = []
+
+ def call(key):
+ calls.append(key)
+ if key in ("k1", "k2"):
+ raise RuntimeError("503 high demand")
+ return "ok"
+
+ out = rotate_with_retries(pool, call, classify=lambda e: ModelError(str(e), retryable=True, status=503),
+ outcome_of=lambda e: "5xx", max_attempts=3, storm_attempts=10, storm_max_delay=0.05,
+ sleep=naps.append, storm_gate=gate)
+ assert out == "ok" and calls == ["k1", "k2", "k3"]
+ assert naps == [], "rotation to a fresh key costs no sleep"
+ assert gate.n_storms == 0 and not gate.storming, "two keys' 503s are not a storm for the whole process"
+
+
+def test_503_on_every_key_is_still_a_storm():
+ from codeverse.models.base import ModelError
+ from codeverse.models.keypool import KeyPool
+ from codeverse.models.retry import rotate_with_retries
+ from codeverse.models.storm import StormGate
+
+ pool = KeyPool(["k1", "k2", "k3"], rpm_per_key=10_000)
+ gate = StormGate()
+ n = {"c": 0}
+ naps: list[float] = []
+
+ def call(key):
+ n["c"] += 1
+ if n["c"] <= 5:
+ raise RuntimeError("503 high demand")
+ return "ok"
+
+ out = rotate_with_retries(pool, call, classify=lambda e: ModelError(str(e), retryable=True, status=503),
+ outcome_of=lambda e: "5xx", max_attempts=3, storm_attempts=10, storm_max_delay=0.05,
+ sleep=naps.append, storm_gate=gate)
+ assert out == "ok" and n["c"] == 6
+ assert gate.n_storms == 1 and gate.n_hits == 3, "the storm is declared after all three keys failed, then waited out"