Debian Codegraph @

src/anthropic/lib/_retry.py

raw
1 """Shared backoff / jitter / retry-classification helpers for the runner helpers.
2
3 Extracted so the control-plane poller, the session tool runner, and the worker
4 heartbeat all compute backoff and classify retryable failures the same way.
5 Consumed by the runner helpers only.
6 """
7
8 from __future__ import annotations
9
10 import random
11
12 import httpx2
13
14 from .._exceptions import APIError, APIStatusError
15
16 __all__ = ["backoff", "jitter", "is_fatal_status_error", "TRANSIENT_ERRORS"]
17
18 # The only exceptions a runner-helper retry loop should swallow and retry:
19 # transport-level httpx failures (connect/read timeouts, connection resets) and
20 # any SDK API error (covers APIConnectionError / APITimeoutError / APIStatusError
21 # — the 4xx-vs-transient split is then made by `is_fatal_status_error`).
22 # Anything else (AttributeError, KeyError, …) is a real bug and must propagate
23 # instead of being silently retried forever.
24 TRANSIENT_ERRORS: tuple[type[Exception], ...] = (httpx2.HTTPError, APIError)
25
26 # 4xx codes that are still worth retrying: request timeout, conflict, and rate
27 # limit. This matches the core client's retry policy — notably 409 is retryable
28 # there, so the runner helpers must not treat it as fatal either.
29 _RETRYABLE_4XX = frozenset({408, 409, 429})
30
31
32 def backoff(attempt: int, *, cap: float, base: float = 2.0) -> float:
33 """Exponential backoff for `attempt` (1-indexed), capped at `cap`."""
34 return min(cap, base**attempt)
35
36
37 def jitter(low: float, high: float) -> float:
38 """Uniform random delay in `[low, high)` — spreads out retry storms."""
39 return random.uniform(low, high)
40
41
42 def is_fatal_status_error(err: Exception) -> bool:
43 """True for a 4xx that retrying will not fix (bad key, missing resource).
44
45 Aligns with the core client's `_should_retry` policy: 408 / 409 / 429 are
46 transient and worth retrying; every other 4xx is fatal.
47 """
48 return isinstance(err, APIStatusError) and 400 <= err.status_code < 500 and err.status_code not in _RETRYABLE_4XX