Skip to content

Official Codebase of 3DCodeVerse

Python

models: one retry loop — the SDK adapters run rotate_with_retries over a one-key pool

gaoypengbdf8ccc15197
diff --git a/harness/codeverse3d/models/anthropic.py b/harness/codeverse3d/models/anthropic.py
index f7f3a41a..faf4e700 100644
--- a/harness/codeverse3d/models/anthropic.py
+++ b/harness/codeverse3d/models/anthropic.py
@@ -12,7 +12,6 @@ Model-family rules (Anthropic API, 2026-08):
from __future__ import annotations
import json
-import logging
import threading
import time
from collections.abc import Callable
@@ -33,10 +32,9 @@ from codeverse3d.models.parts import (
classify_sdk_exception,
image_b64,
retry_budget_s,
- with_logged_retries,
+ retry_one_key,
)
from codeverse3d.models.pricing import cache_write_surcharge, estimate_cost
-from codeverse3d.models.retry import cause_for
from codeverse3d.models.schema_utils import (
JsonParseError,
parse_json_lenient,
@@ -180,9 +178,6 @@ def parse_content(content: list[Any]) -> tuple[str, Any]:
# ===================================================================== anthropic
-log = logging.getLogger(__name__)
-
-
def classify_exception(exc: BaseException) -> ModelError:
"""Map anthropic SDK exceptions onto ``ModelError`` (the shared ladder in parts.py)."""
import anthropic
@@ -235,16 +230,9 @@ class AnthropicModel:
def generate(self, request: ChatRequest) -> ChatResponse:
kwargs = build_kwargs(request, self.model)
deadline = time.monotonic() + retry_budget_s(request.max_wait_s)
-
- def attempt() -> ChatResponse:
- try:
- return self._once(kwargs, request, deadline)
- except Exception as exc: # noqa: BLE001 - classified
- err = classify_exception(exc)
- raise err from cause_for(err, exc)
-
- return with_logged_retries(attempt, label="anthropic", model=self.model, attempts=self.max_attempts,
- sleep=self._sleep, log=log, max_wait_s=request.max_wait_s)
+ return retry_one_key(lambda: self._once(kwargs, request, deadline), label=f"anthropic {self.model}",
+ classify=classify_exception, attempts=self.max_attempts, sleep=self._sleep,
+ max_wait_s=request.max_wait_s)
def _once(self, kwargs: dict[str, Any], request: ChatRequest, deadline: float) -> ChatResponse:
client = self.client()
diff --git a/harness/codeverse3d/models/gemini.py b/harness/codeverse3d/models/gemini.py
index 232f151d..79470237 100644
--- a/harness/codeverse3d/models/gemini.py
+++ b/harness/codeverse3d/models/gemini.py
@@ -39,14 +39,7 @@ from codeverse3d.contracts.common import Usage
from codeverse3d.models.base import ModelError
from codeverse3d.models.parts import Stopwatch, attempt_timeout_s, image_bytes, retry_budget_s
from codeverse3d.models.pricing import estimate_cost, per_image_usd
-from codeverse3d.models.retry import (
- KeyPool,
- KeyPoolExhausted,
- OnAttempt,
- Outcome,
- _Try,
- rotate_with_retries,
-)
+from codeverse3d.models.retry import KeyPool, KeyPoolExhausted, OnAttempt, _Try, rotate_with_retries
from codeverse3d.models.schema_utils import JsonParseError, parse_json_lenient, to_gemini_schema
#: INTERFACES.md mapping; ``off`` → 0 where the model allows it
@@ -287,43 +280,6 @@ def classify_exception(exc: BaseException) -> ModelError:
return ModelError(f"Gemini unexpected error: {type(exc).__name__}: {exc}", retryable=False)
-# message fragments of key-scoped failures (revoked / suspended / expired / disabled
-# project); HTTP 401 / 403 are key-scoped regardless of wording
-_DEAD_KEY_MARKERS = (
- "api_key_invalid",
- "api key not valid",
- "api key expired",
- "permission_denied",
- "unauthenticated",
- "suspended",
- "leaked",
- "service_disabled",
- "has not been used in project",
-)
-
-
-def is_dead_key_error(err: ModelError) -> bool:
- """True when ``err`` indicts the API key rather than the request, so the call
- should move to another key instead of failing."""
- if err.status in (401, 403):
- return True
- text = str(err).lower()
- return err.status == 400 and any(m in text for m in _DEAD_KEY_MARKERS)
-
-
-def failure_outcome(err: ModelError) -> Outcome:
- """``KeyPool.report`` outcome for a failed call. Content-level failures (bad JSON,
- empty candidates) carry no status and are not the key's fault: ``skip`` reconciles
- the tokens they were billed and leaves health / counters alone."""
- if err.status == 429:
- return "429"
- if (err.status or 0) >= 500:
- return "5xx"
- if is_dead_key_error(err):
- return "dead"
- return "error" if err.status else "skip"
-
-
def _retry_after_s(exc: BaseException) -> float | None:
"""Gemini 429 bodies carry ``details[].retryDelay: "7s"``; honour it (capped)."""
m = _RETRY_DELAY_RE.search(str(exc))
@@ -464,29 +420,24 @@ class GeminiModel:
deadline = time.monotonic() + budget # mirrors rotate_with_retries' own deadline
stats: dict[str, Any] = {}
wasted: list[Usage] = [] # discarded round-trips the provider still billed
- try:
- resp = rotate_with_retries(
- self.pool,
- lambda key: self._once(
- key, contents, self._attempt_config(state["config"], deadline),
- request, warnings,
- ),
- classify=classify_exception,
- outcome_of=failure_outcome,
- max_attempts=self.max_attempts,
- max_total_s=budget,
- hedge=self.hedge,
- sleep=self._sleep,
- on_free_retry=downgrade_thinking,
- retry_after=_retry_after_s,
- label=f"gemini {self.model}",
- stats=stats,
- on_attempt=self._attempt_hook(wasted),
- **({} if self.storm_attempts is None else {"storm_attempts": self.storm_attempts}),
- )
- except ModelError as err:
- err.attempts = int(stats.get("attempts", 0)) # the ledger's error row wants it too
- raise
+ resp = rotate_with_retries(
+ self.pool,
+ lambda key: self._once(
+ key, contents, self._attempt_config(state["config"], deadline),
+ request, warnings,
+ ),
+ classify=classify_exception,
+ max_attempts=self.max_attempts,
+ max_total_s=budget,
+ hedge=self.hedge,
+ sleep=self._sleep,
+ on_free_retry=downgrade_thinking,
+ retry_after=_retry_after_s,
+ label=f"gemini {self.model}",
+ stats=stats,
+ on_attempt=self._attempt_hook(wasted),
+ **({} if self.storm_attempts is None else {"storm_attempts": self.storm_attempts}),
+ )
# how hard the call was, next to which key served it (``_once``): ledger fields
resp.raw["attempts"] = int(stats.get("attempts", 0))
resp.raw["hedged"] = int(stats.get("hedged", 0))
@@ -775,7 +726,6 @@ class GeminiImageModel:
self.pool,
lambda key: self._call(key, model, contents, _attempt_config(), size, _GENERATED_PX[token]),
classify=classify_exception,
- outcome_of=failure_outcome,
max_attempts=self.max_attempts,
max_total_s=budget,
hedge=self.hedge,
diff --git a/harness/codeverse3d/models/openai.py b/harness/codeverse3d/models/openai.py
index b443b725..952f8d51 100644
--- a/harness/codeverse3d/models/openai.py
+++ b/harness/codeverse3d/models/openai.py
@@ -28,7 +28,7 @@ from codeverse3d.models.parts import (
classify_sdk_exception,
image_b64,
retry_budget_s,
- with_logged_retries,
+ retry_one_key,
)
from codeverse3d.models.pricing import estimate_cost
from codeverse3d.models.retry import cause_for
@@ -226,8 +226,8 @@ class OpenAIModel:
raise err2 from cause_for(err2, exc2)
raise err from cause_for(err, exc)
- return with_logged_retries(attempt, label="openai", model=self.model, attempts=self.max_attempts,
- sleep=self._sleep, log=log, max_wait_s=request.max_wait_s)
+ return retry_one_key(attempt, label=f"openai {self.model}", classify=classify_exception,
+ attempts=self.max_attempts, sleep=self._sleep, max_wait_s=request.max_wait_s)
def _once(self, kwargs: dict[str, Any], request: ChatRequest, deadline: float) -> ChatResponse:
client = self.client()
diff --git a/harness/codeverse3d/models/parts.py b/harness/codeverse3d/models/parts.py
index 3ee0793c..3de00de4 100644
--- a/harness/codeverse3d/models/parts.py
+++ b/harness/codeverse3d/models/parts.py
@@ -108,7 +108,7 @@ def attempt_timeout_s(deadline: float, ceiling: float) -> float:
"""The SDK timeout for ONE attempt: what is left of ``deadline``, capped at the
client's ``timeout_s`` and floored at :data:`SDK_TIMEOUT_FLOOR_S`.
- ``with_retries`` checks the deadline only BETWEEN attempts and both SDK clients are
+ The retry loop checks the deadline only BETWEEN attempts and both SDK clients are
built once with a fixed ``timeout`` (600 s), so a judge told it had 20 s of budget
left held a socket for 600 s (audit 2026-08-29). The floor is what keeps a legitimate
long completion (the 930 s plan budget) on its full ``timeout_s`` — this shortens an
@@ -117,20 +117,15 @@ def attempt_timeout_s(deadline: float, ceiling: float) -> float:
return min(ceiling, max(SDK_TIMEOUT_FLOOR_S, deadline - time.monotonic()))
-def with_logged_retries(attempt: Any, *, label: str, model: str, attempts: int,
- sleep: Any, log: Any, max_wait_s: float | None = None) -> Any:
- """``with_retries`` plus the one log line both SDK adapters write.
+def retry_one_key(attempt: Any, *, label: str, classify: Any, attempts: int, sleep: Any,
+ max_wait_s: float | None = None) -> Any:
+ """The SDK adapters' retry loop: ``rotate_with_retries`` over a fresh one-key pool with no
+ cooldown, no storm patience and no hedge — so a 429 / 5xx / 529 / timeout is retried
+ ``attempts`` times with the ≤ ``MAX_WAIT_S`` backoff, inside the request's ``max_wait_s``
+ deadline (``None`` = ``RETRY_DEADLINE_S``), and a raised ``ModelError`` says how many
+ round-trips it took. ``label`` names the call in the log ("anthropic <model>")."""
+ from codeverse3d.models.retry import KeyPool, rotate_with_retries
- ``max_wait_s`` is the request's ``ChatRequest.max_wait_s`` deadline (retries and
- their waits included; ``None`` = ``RETRY_DEADLINE_S``); the backoff itself is
- ``attempts`` x <= ``MAX_WAIT_S`` (3 s), the round-trips are the real cost.
- """
- from codeverse3d.models.retry import with_retries
-
- def on_retry(n: int, exc: BaseException, delay: float) -> None:
- log.warning("%s %s attempt %d/%d failed (%s); retrying in %.1fs",
- label, model, n, attempts, exc, delay)
-
- budget = retry_budget_s(max_wait_s)
- return with_retries(attempt, is_retryable=lambda e: isinstance(e, ModelError) and e.retryable,
- attempts=attempts, max_total_s=budget, on_retry=on_retry, sleep=sleep)
+ return rotate_with_retries(KeyPool([label], cooldown_s=0.0), lambda _key: attempt(), classify=classify,
+ max_attempts=attempts, max_total_s=retry_budget_s(max_wait_s),
+ storm_attempts=0, hedge=1, sleep=sleep, label=label)
diff --git a/harness/codeverse3d/models/retry.py b/harness/codeverse3d/models/retry.py
index fa3688f4..fc2abb40 100644
--- a/harness/codeverse3d/models/retry.py
+++ b/harness/codeverse3d/models/retry.py
@@ -3,8 +3,8 @@
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. the two retry loops — ``with_retries`` (single key, SDK adapters) and
- ``rotate_with_retries`` (the pool, hedging, the ``RETRY_DEADLINE_S`` deadline).
+2. ``rotate_with_retries``, the one retry loop (the pool, hedging, the ``RETRY_DEADLINE_S``
+ deadline) — the SDK adapters run it over a one-key pool (``parts.retry_one_key``).
Every wait anywhere in here clips to ``MAX_WAIT_S``.
@@ -49,6 +49,43 @@ class KeyPoolExhausted(RuntimeError):
"""Every key is cooling down (or every slot is busy) and the wait budget ran out."""
+# message fragments of key-scoped failures (revoked / suspended / expired / disabled
+# project); HTTP 401 / 403 are key-scoped regardless of wording
+_DEAD_KEY_MARKERS = (
+ "api_key_invalid",
+ "api key not valid",
+ "api key expired",
+ "permission_denied",
+ "unauthenticated",
+ "suspended",
+ "leaked",
+ "service_disabled",
+ "has not been used in project",
+)
+
+
+def is_dead_key_error(err: ModelError) -> bool:
+ """True when ``err`` indicts the API key rather than the request, so the call
+ should move to another key instead of failing."""
+ if err.status in (401, 403):
+ return True
+ text = str(err).lower()
+ return err.status == 400 and any(m in text for m in _DEAD_KEY_MARKERS)
+
+
+def failure_outcome(err: ModelError) -> Outcome:
+ """``KeyPool.report`` outcome for a failed call (``rotate_with_retries``' default
+ ``outcome_of``). Content-level failures (bad JSON, empty candidates) carry no status
+ and are not the key's fault: ``skip`` leaves health / counters alone."""
+ if err.status == 429:
+ return "429"
+ if (err.status or 0) >= 500:
+ return "5xx"
+ if is_dead_key_error(err):
+ return "dead"
+ return "error" if err.status else "skip"
+
+
MAX_WAIT_S = 3.0
"""The longest any single retry / cooldown wait may be (seconds).
@@ -341,9 +378,6 @@ if TYPE_CHECKING: # pragma: no cover
log = logging.getLogger(__name__)
-OnRetry = Callable[[int, BaseException, float], None]
-
-
def cause_for(err: BaseException, exc: BaseException | None) -> BaseException | None:
"""The cause to raise ``err`` from — ``None`` when it would be ``err`` itself.
@@ -377,59 +411,12 @@ def backoff_delay(
return random.uniform(raw / 2.0, raw)
-def with_retries[T](
- fn: Callable[[], T],
- *,
- is_retryable: Callable[[BaseException], bool],
- attempts: int = 6,
- base_delay: float = 1.0,
- max_delay: float = MAX_WAIT_S,
- max_total_s: float | None = None,
- on_retry: OnRetry | None = None,
- sleep: Callable[[float], None] = time.sleep,
- jitter: bool = True,
-) -> T:
- """Call ``fn`` up to ``attempts`` times, within ``max_total_s`` when given.
-
- Re-raises the last exception when it is not retryable (per ``is_retryable``),
- when attempts are exhausted, or when the next backoff would cross the deadline
- (``ChatRequest.max_wait_s`` on the SDK adapters). ``on_retry(attempt, exc, delay)``
- is called before each sleep (attempt is the 1-based index of the attempt that
- failed). A raised exception carrying an ``attempts`` attribute (``ModelError``)
- is stamped with the number of round-trips issued.
- """
- if attempts < 1:
- raise ValueError("attempts must be >= 1")
- deadline = None if max_total_s is None else time.monotonic() + max_total_s
- last: BaseException | None = None
- for attempt in range(1, attempts + 1):
- try:
- return fn()
- except BaseException as exc: # noqa: BLE001 - classification is delegated
- last = exc
- if hasattr(exc, "attempts"):
- exc.attempts = attempt
- if attempt >= attempts or not is_retryable(exc):
- raise
- delay = backoff_delay(
- attempt, base_delay=base_delay, max_delay=max_delay, jitter=jitter
- )
- if deadline is not None and time.monotonic() + delay >= deadline:
- raise
- if on_retry is not None:
- on_retry(attempt, exc, delay)
- sleep(delay)
- # unreachable, but keeps type-checkers happy
- assert last is not None
- raise last
-
-
def rotate_with_retries[T](
pool: KeyPool,
call: Callable[[str], T],
*,
classify: Callable[[BaseException], ModelError],
- outcome_of: Callable[[ModelError], Outcome],
+ outcome_of: Callable[[ModelError], Outcome] = failure_outcome,
max_attempts: int = 6,
base_delay: float = 1.0,
max_delay: float = MAX_WAIT_S,
@@ -496,16 +483,16 @@ 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 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).
+ 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).
``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.
- ``GeminiModel`` copies ``attempts`` into ``ChatResponse.raw`` and onto the raised
- ``ModelError`` so the cost ledger can say how hard each call was.
+ included; 1 = clean), ``hedged`` = hedged attempts, ``storm`` = storm waits. A
+ raised ``ModelError`` carries ``attempts`` itself (the cost ledger's error row);
+ ``GeminiModel`` copies it into ``ChatResponse.raw`` on success.
``on_attempt`` (optional) hears every round-trip exactly once — see
:data:`OnAttempt`; the cost layer uses it to write per-attempt ledger rows so a
@@ -719,6 +706,10 @@ def rotate_with_retries[T](
assert last_err is not None
bench()
raise last_err
+ except BaseException as exc:
+ if hasattr(exc, "attempts"): # a ModelError: how hard the call tried
+ exc.attempts = counts["attempts"]
+ raise
finally:
if stats is not None:
stats.update(counts)
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index cc26aba0..de03adf9 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -103,8 +103,9 @@ codeverse3d/
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 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
+ 2026-09-22, docs/COST.md §19 — and rotate_with_retries, the one retry loop, which
+ the SDK adapters run over a one-key pool; 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
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
index c5c7ab83..18962022 100644
--- a/harness/docs/COST.md
+++ b/harness/docs/COST.md
@@ -1299,9 +1299,11 @@ sessions overshot their timeout by 182 s median / 1 154 s p90); a judge sample g
`SAMPLE_BUDGET_S = 240` for all its attempts (the verdict is 42 s p50 / 73 s p90, 50 / 103 s under
the storm; two rounds lost 1 162 s and 927 s to 3 × 300 s timeouts before a second sample answered
in 128 s); the planner 300 s (13.7 s p50 / 32 s p90, max 76 s; the storm-day plan stage waited
-492 s median for 39 s of model time). Anthropic / OpenAI go through `with_retries`, which
-since 2026-08-29 takes the same `max_total_s = ChatRequest.max_wait_s` (clipped to
-`RETRY_DEADLINE_S`) and stamps `ModelError.attempts` — the field is honoured on every provider.
+492 s median for 39 s of model time). Anthropic / OpenAI honour the same `max_total_s =
+ChatRequest.max_wait_s` (clipped to `RETRY_DEADLINE_S`) and a raised `ModelError` carries
+`attempts` on every provider: since 2026-09-22 they run `rotate_with_retries` itself over a
+fresh one-key pool (`parts.retry_one_key`: no cooldown, no storm patience, no hedge — the
+same `max_attempts` × ≤ 3 s backoff their own `with_retries` loop gave them, now deleted).
*The retry of a 503 is hedged across keys* (`rotate_with_retries(hedge=2)`; `Settings.rate.hedge`,
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 940d10e6..375cb9c2 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -72,9 +72,10 @@ pool.acquire(*, exclude=None, timeout_s=120) -> key # raises immediately when
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
+from codeverse3d.models.retry import rotate_with_retries, RETRY_DEADLINE_S
+rotate_with_retries(pool, call, *, classify, outcome_of=failure_outcome, max_attempts=6, max_total_s=RETRY_DEADLINE_S, hedge=2, ...)
+ # the ONE retry loop; the SDK adapters run it over a one-key pool (parts.retry_one_key: no cooldown, no storm
+ # patience, no hedge). max_total_s = ChatRequest.max_wait_s clipped to RETRY_DEADLINE_S; a raised ModelError carries .attempts
from codeverse3d.models.pricing import estimate_cost # (provider, model, usage) -> usd (unknown model -> 0.0 + one warning)
from codeverse3d.models.schema_utils import to_gemini_schema, to_openai_strict_schema, to_anthropic_schema, parse_json_lenient
from codeverse3d.models.schema_utils import ask_structured # (model, Schema, *, system, text, images=(), temperature, label)
diff --git a/harness/tests/models/test_anthropic.py b/harness/tests/models/test_anthropic.py
index 9fdd0f16..8109b443 100644
--- a/harness/tests/models/test_anthropic.py
+++ b/harness/tests/models/test_anthropic.py
@@ -21,6 +21,7 @@ from codeverse3d.models.anthropic import (
to_messages,
)
from codeverse3d.models.base import ModelError
+from codeverse3d.models.retry import MAX_WAIT_S
PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
@@ -182,11 +183,20 @@ def test_images_base64_and_message_merging():
def test_retry_on_429_529_5xx_and_not_on_400():
- m, fc = make([api_error(429), api_error(529), api_error(500), msg([text("ok")])])
+ naps: list[float] = []
+ fc = FakeClient([api_error(429), api_error(529), api_error(500), msg([text("ok")])])
+ m = AnthropicModel("claude-opus-5", client=fc, sleep=naps.append)
assert (
m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"
and len(fc.calls) == 4
)
+ # one backoff per failure, each <= MAX_WAIT_S: a 529 is not a storm on a one-key
+ # pool and a 429 waits for no cooldown (the loop the SDK adapters always had)
+ assert len(naps) == 3 and all(0 < d <= MAX_WAIT_S for d in naps), naps
+ m, fc = make([api_error(529)] * 3, max_attempts=3)
+ with pytest.raises(ModelError) as ei:
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert ei.value.status == 529 and len(fc.calls) == 3 and ei.value.attempts == 3
m, fc = make([api_error(400, "bad"), msg([text("never")])])
with pytest.raises(ModelError) as ei:
m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
@@ -246,7 +256,7 @@ def test_a_failed_reply_carries_what_it_was_billed():
def test_each_attempt_gets_what_is_left_of_the_call_budget():
- """``max_wait_s`` is the whole call's deadline, and ``with_retries`` only checks it
+ """``max_wait_s`` is the whole call's deadline, and the retry loop only checks it
BETWEEN attempts — so the attempt itself must carry it. The client is built once with
a fixed 600 s timeout, so a judge with 20 s of budget left used to hold a socket for
600 s. Floor: a long completion (the 930 s plan) keeps the full client timeout."""
diff --git a/harness/tests/models/test_gemini.py b/harness/tests/models/test_gemini.py
index 6e193c47..950493a7 100644
--- a/harness/tests/models/test_gemini.py
+++ b/harness/tests/models/test_gemini.py
@@ -22,10 +22,9 @@ from codeverse3d.models.gemini import (
GeminiModel,
build_config,
classify_exception,
- failure_outcome,
to_contents,
)
-from codeverse3d.models.retry import KeyPool
+from codeverse3d.models.retry import KeyPool, failure_outcome
PNG_1PX = base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.py
index b2e2ef7c..f0bd4294 100644
--- a/harness/tests/models/test_retry.py
+++ b/harness/tests/models/test_retry.py
@@ -1,4 +1,4 @@
-"""with_retries / backoff_delay / rotate_with_retries."""
+"""backoff_delay / rotate_with_retries."""
from __future__ import annotations
@@ -19,7 +19,6 @@ from codeverse3d.models.retry import (
Outcome,
backoff_delay,
rotate_with_retries,
- with_retries,
)
@@ -30,78 +29,6 @@ def test_backoff_grows_and_caps():
assert 2.0 <= j <= 4.0
-def test_retries_until_success_and_reports():
- calls: list[int] = []
- slept: list[float] = []
- seen: list[tuple[int, float]] = []
-
- def fn():
- calls.append(1)
- if len(calls) < 3:
- raise TimeoutError("flaky")
- return "ok"
-
- out = with_retries(
- fn,
- is_retryable=lambda e: isinstance(e, TimeoutError),
- attempts=5,
- base_delay=0.5,
- max_delay=2.0,
- on_retry=lambda n, e, d: seen.append((n, d)),
- sleep=slept.append,
- jitter=False,
- )
- assert out == "ok" and len(calls) == 3
- assert slept == [0.5, 1.0]
- assert [n for n, _ in seen] == [1, 2]
-
-
-def test_with_retries_stops_on_non_retryable_and_exhaustion():
- calls = 0
-
- def non_retryable():
- nonlocal calls
- calls += 1
- raise ValueError("bad")
-
- with pytest.raises(ValueError):
- with_retries(
- non_retryable, is_retryable=lambda error: False, attempts=5, sleep=lambda _: None
- )
- assert calls == 1
-
- def exhausted():
- nonlocal calls
- calls += 1
- raise TimeoutError("always")
-
- with pytest.raises(TimeoutError):
- with_retries(exhausted, is_retryable=lambda error: True, attempts=3, sleep=lambda _: None)
- assert calls == 4
-
-
-def test_with_retries_honours_a_deadline_and_stamps_attempts():
- """The SDK adapters' loop: ``ChatRequest.max_wait_s`` bounds the whole call and the
- raised ModelError says how many round-trips were issued (the ledger's error row)."""
- from codeverse3d.models.base import ModelError
-
- calls = 0
-
- def flaky():
- nonlocal calls
- calls += 1
- raise ModelError("busy", retryable=True, status=503)
-
- with pytest.raises(ModelError) as ei:
- with_retries(flaky, is_retryable=lambda e: True, attempts=6, base_delay=1.0, max_delay=1.0,
- max_total_s=0.0, sleep=lambda _: None, jitter=False)
- assert calls == 1 and ei.value.attempts == 1 # the first backoff would already cross the deadline
- calls = 0
- with pytest.raises(ModelError) as ei:
- with_retries(flaky, is_retryable=lambda e: True, attempts=3, sleep=lambda _: None)
- assert calls == 3 and ei.value.attempts == 3
-
-
# --------------------------------------------------------------------------- rotate_with_retries
def _classify(exc: BaseException) -> ModelError:
if isinstance(exc, ModelError):
@@ -270,6 +197,7 @@ def test_rotate_retryable_backoff_and_nonretryable_failure_modes():
sleep=slept.append,
)
assert ei.value.status == 500 and len(slept) == 2 # backoff between the 3 attempts
+ assert ei.value.attempts == 3, "the raised error says how many round-trips it took (the ledger's error row)"
calls: list[str] = []