Skip to content

Official Codebase of 3DCodeVerse

Python

retry: bound one call in TIME, not just in attempts — a storm could hold a single call for 5.6 hours

gaoypeng63f765adab46
diff --git a/harness/codeverse/models/retry.py b/harness/codeverse/models/retry.py
index 3caf0eaf..386d087a 100644
--- a/harness/codeverse/models/retry.py
+++ b/harness/codeverse/models/retry.py
@@ -20,6 +20,15 @@ from typing import TYPE_CHECKING, TypeVar
from codeverse.models.keypool import MAX_WAIT_S, KeyPoolExhausted
+#: 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
+#: read timeout + a <=5 s wait) is **5.1 hours** for a single call, though the docstring
+#: claimed "~5 min". Measured 2026-08-24: that, plus a wall-clock ceiling only checked
+#: when a call is BILLED (a stalled call bills nothing), let a run with --max-minutes 90
+#: reach 200 minutes during a flash outage. Past this deadline the call gives up and the
+#: cell is recorded infra_failed, which is re-runnable (`--redo-status infra_failed`).
+RETRY_DEADLINE_S = 900.0
+
if TYPE_CHECKING: # pragma: no cover
from codeverse.models.base import ModelError
from codeverse.models.keypool import KeyPool, Outcome
@@ -92,7 +101,9 @@ def rotate_with_retries(
max_delay: float = MAX_WAIT_S,
storm_attempts: int = 60,
storm_max_delay: float = MAX_WAIT_S,
+ max_total_s: float = RETRY_DEADLINE_S,
sleep: Callable[[float], None] = time.sleep,
+ 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,
@@ -147,6 +158,11 @@ def rotate_with_retries(
last_err: ModelError | None = None
attempt = 0
storm = 0
+ deadline = monotonic() + max_total_s if max_total_s > 0 else float("inf")
+
+ def out_of_time() -> bool:
+ return monotonic() >= deadline
+
while attempt < max_attempts:
attempt += 1
# never go back to a key that looked dead this call; throttled keys are
@@ -190,7 +206,7 @@ def rotate_with_retries(
reserved=tokens_hint,
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:
+ 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
storm += 1
@@ -224,6 +240,9 @@ def rotate_with_retries(
if not err.retryable or attempt >= max_attempts:
bench()
raise err from exc
+ if out_of_time():
+ log.warning("%s giving up after %.0f s of retrying (%s)", label, max_total_s, err)
+ raise err from exc
delay = backoff_delay(attempt, base_delay=base_delay, max_delay=max_delay)
log.warning(
"%s attempt %d/%d failed (%s); retrying in %.1fs",
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
index 4b0fb097..4899d10b 100644
--- a/harness/docs/COST.md
+++ b/harness/docs/COST.md
@@ -1002,3 +1002,36 @@ justify a scheduler rewrite in `fan_out`.
`3dcv 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.
+
+## 22. The retry budget was counted in attempts, so a "90-minute" run took 200
+
+Two independent bugs let a single provider outage burn hours of paid wall clock on
+2026-08-24. Both are cost-control failures, not model failures.
+
+**The storm budget was never a time budget.** §21's storm branch is bounded by
+`storm_attempts = 60` with each wait capped at `MAX_WAIT_S`, and its docstring claimed
+patience of "60 × ≤5 s ≈ 5 min". It never counted the read timeout each doomed
+attempt burns first: with `model_timeout_s = 300`, one logical call is
+60 × (300 + 5) s = **5.1 hours**. Measured on a fake clock, a call in a sustained
+storm consumed **5.59 h**; with the deadline it consumes **15.1 min**:
+
+| | one call in a sustained storm |
+|---|---|
+| attempts-only budget (before) | 5.59 h |
+| `RETRY_DEADLINE_S = 900 s` (after) | 15.1 min |
+
+`rotate_with_retries` now takes `max_total_s` and stops retrying once the wall clock
+says so, in both the storm branch and ordinary backoff. A slow call that is *making
+progress* is never cut — the deadline bounds retrying, not the call. Past it the cell
+is `infra_failed`, which is excluded from every rate and re-runnable with
+`--redo-status infra_failed` (`docs/EVAL.md` §7).
+
+**The wall-clock ceiling is only checked when money is spent.** `BudgetGuard.check()`
+is called from `spend()`/`charge()`, so a run whose calls never *complete* is never
+tested against `max_minutes`: nothing is billed, so nothing is checked. That is how a
+`--max-minutes 90` run reached **200 minutes**. The retry deadline is the root fix —
+every call now terminates within ~15 min and charges or raises, so the ceiling is
+evaluated again — but the residual remains real: **`max_minutes` is enforced at
+billing points, not on a timer.** Closing it properly means giving the runner a
+reference to the guard and checking at stage boundaries; not done here, because it is
+plumbing through several layers and deserves its own measured change.
diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.py
index 2b0baf93..aeac6e95 100644
--- a/harness/tests/models/test_retry.py
+++ b/harness/tests/models/test_retry.py
@@ -299,3 +299,65 @@ def test_live_tests_are_opt_in_by_default():
addopts = cfg["tool"]["pytest"]["ini_options"].get("addopts", [])
joined = " ".join(addopts) if isinstance(addopts, list) else str(addopts)
assert "not live" in joined, "live tests must be deselected by default (see pyproject addopts)"
+
+
+def test_one_call_cannot_retry_for_hours():
+ """The storm branch was bounded in ATTEMPTS, not in time.
+
+ 60 storm attempts x (a 300 s read timeout + a <=5 s wait) is 5.1 hours for ONE
+ logical call, while the docstring claimed "~5 min". Measured 2026-08-24: combined
+ with a wall-clock ceiling that is only checked when a call is BILLED (a stalled
+ call bills nothing), a run with --max-minutes 90 reached 200 minutes.
+ """
+ from codeverse.models.base import ModelError
+ from codeverse.models.keypool import KeyPool
+ from codeverse.models.retry import RETRY_DEADLINE_S, rotate_with_retries
+
+ clock = {"t": 0.0}
+ naps: list[float] = []
+
+ def sleep(d): # every wait advances the fake clock
+ naps.append(d)
+ clock["t"] += d
+
+ def call(_key):
+ clock["t"] += 300.0 # the read timeout each doomed attempt burns
+ raise RuntimeError("503 high demand")
+
+ with pytest.raises(ModelError):
+ rotate_with_retries(
+ KeyPool(["k1", "k2"], rpm_per_key=10_000), call,
+ classify=lambda e: ModelError(str(e), retryable=True, status=503),
+ outcome_of=lambda e: "5xx", max_attempts=6, storm_attempts=60,
+ sleep=sleep, monotonic=lambda: clock["t"],
+ )
+ # the whole point: bounded by the clock, not by 60 x (timeout + wait)
+ assert clock["t"] <= RETRY_DEADLINE_S + 305.0, (
+ f"one call burned {clock['t'] / 3600:.1f} h; the deadline is {RETRY_DEADLINE_S / 60:.0f} min")
+ assert clock["t"] < 5 * 3600, "this is the 5.1-hour regression"
+
+
+def test_the_deadline_does_not_cut_a_call_that_is_making_progress():
+ """A slow-but-succeeding call must not be killed by the retry deadline."""
+ from codeverse.models.base import ModelError
+ from codeverse.models.keypool import KeyPool
+ from codeverse.models.retry import rotate_with_retries
+
+ clock = {"t": 0.0}
+ calls = {"n": 0}
+
+ def call(_key):
+ calls["n"] += 1
+ clock["t"] += 280.0 # slow, but under the per-attempt timeout
+ if calls["n"] < 3:
+ raise RuntimeError("503 high demand")
+ return "ok"
+
+ out = rotate_with_retries(
+ KeyPool(["k1", "k2"], rpm_per_key=10_000), call,
+ classify=lambda e: ModelError(str(e), retryable=True, status=503),
+ outcome_of=lambda e: "5xx", max_attempts=6, storm_attempts=60,
+ sleep=lambda d: clock.__setitem__("t", clock["t"] + d),
+ monotonic=lambda: clock["t"],
+ )
+ assert out == "ok" and calls["n"] == 3