Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

test(e2e/claude_code): retry rate-limit-shaped CLI failures with backoff

mateo-berric4fee0eafe66
diff --git a/tests/e2e/claude_code/_driver_unit_tests/test_cli_driver.py b/tests/e2e/claude_code/_driver_unit_tests/test_cli_driver.py
index 786f6029993..f1a0534906e 100644
--- a/tests/e2e/claude_code/_driver_unit_tests/test_cli_driver.py
+++ b/tests/e2e/claude_code/_driver_unit_tests/test_cli_driver.py
@@ -19,6 +19,7 @@ from claude_code.cli_driver import (
ClaudeCLIError,
DriverResult,
failure_diagnostic,
+ is_rate_limit_shaped,
run_claude,
run_claude_models_parallel,
)
@@ -793,3 +794,199 @@ def test_failure_diagnostic_uses_last_result_event_status():
diag = failure_diagnostic(result)
assert "api_status=429" in diag
assert "500" not in diag
+
+
+_RATE_LIMITED_STDOUT = (
+ json.dumps(
+ {
+ "type": "assistant",
+ "message": {
+ "content": [
+ {"type": "text", "text": "API Error: 429 Too Many Requests"}
+ ]
+ },
+ }
+ )
+ + "\n"
+ + json.dumps({"type": "result", "api_error_status": 429})
+ + "\n"
+)
+
+_OK_STDOUT = (
+ json.dumps(
+ {
+ "type": "assistant",
+ "message": {"content": [{"type": "text", "text": "pong"}]},
+ }
+ )
+ + "\n"
+)
+
+
+class _FlakyRunner:
+ """Fake runner that rate-limits each model N times before succeeding.
+
+ Keeps a per-model call count so tests can assert exactly how many
+ attempts the retry loop made — the load-bearing detail a canned
+ single-response runner can't express.
+ """
+
+ def __init__(self, failures_before_success: dict):
+ self.failures_before_success = dict(failures_before_success)
+ self.calls: dict = {}
+
+ def __call__(self, cmd, env, capture_output, text, timeout, check, input=None):
+ model = cmd[cmd.index("--model") + 1]
+ self.calls[model] = self.calls.get(model, 0) + 1
+ if self.calls[model] <= self.failures_before_success.get(model, 0):
+ return _Completed(returncode=1, stdout=_RATE_LIMITED_STDOUT)
+ return _Completed(returncode=0, stdout=_OK_STDOUT)
+
+
+ "outcome,expected",
+ [
+ (ClaudeCLIError("claude CLI timed out after 120.0s"), True),
+ (ClaudeCLIError("claude CLI not found at 'claude'"), False),
+ (
+ DriverResult(
+ text="",
+ events=[{"type": "result", "api_error_status": 429}],
+ exit_code=1,
+ ),
+ True,
+ ),
+ (DriverResult(text="Too Many Requests", exit_code=1), True),
+ (DriverResult(text="", stderr="throttled by upstream", exit_code=1), True),
+ (DriverResult(text="rate limit exceeded", exit_code=0), False),
+ (DriverResult(text="", stderr="auth failed", exit_code=2), False),
+ ],
+)
+def test_is_rate_limit_shaped_classification(outcome, expected):
+ """The retry trigger must match 429/throttle/timeout markers on
+ failures only — a passing result mentioning '429' in its reply text
+ must never be classified as retryable."""
+ assert is_rate_limit_shaped(outcome) is expected
+
+
+def test_run_claude_models_parallel_retries_rate_limited_model_until_success():
+ """A model that 429s once must be retried after the backoff sleep and
+ end up green, while an untroubled sibling model runs exactly once."""
+ runner = _FlakyRunner({"flaky": 1})
+ sleeps: List[float] = []
+
+ outcomes = run_claude_models_parallel(
+ models=["flaky", "steady"],
+ prompt="hi",
+ base_url="http://x",
+ api_key="k",
+ runner=runner,
+ rate_limit_retries=2,
+ rate_limit_backoff_seconds=0.5,
+ sleep=sleeps.append,
+ )
+
+ assert isinstance(outcomes["flaky"], DriverResult)
+ assert outcomes["flaky"].exit_code == 0
+ assert outcomes["flaky"].text == "pong"
+ assert runner.calls == {"flaky": 2, "steady": 1}
+ assert sleeps == [0.5]
+
+
+def test_run_claude_models_parallel_does_not_retry_non_rate_limit_failures():
+ """A deterministic failure (bad auth) must fail fast: no sleeps, one
+ attempt — retrying it would just triple the matrix wall time."""
+
+ def runner(cmd, env, capture_output, text, timeout, check, input=None):
+ return _Completed(returncode=2, stdout="", stderr="auth failed")
+
+ sleeps: List[float] = []
+ outcomes = run_claude_models_parallel(
+ models=["a"],
+ prompt="hi",
+ base_url="http://x",
+ api_key="k",
+ runner=runner,
+ rate_limit_retries=2,
+ rate_limit_backoff_seconds=0.5,
+ sleep=sleeps.append,
+ )
+
+ assert outcomes["a"].exit_code == 2
+ assert sleeps == []
+
+
+def test_run_claude_models_parallel_returns_last_failure_when_retries_exhausted():
+ """A persistently rate-limited model exhausts its budget (initial
+ attempt + N retries, each preceded by one backoff sleep) and still
+ surfaces the 429 diagnostic instead of masking it."""
+ runner = _FlakyRunner({"stuck": 99})
+ sleeps: List[float] = []
+
+ outcomes = run_claude_models_parallel(
+ models=["stuck"],
+ prompt="hi",
+ base_url="http://x",
+ api_key="k",
+ runner=runner,
+ rate_limit_retries=2,
+ rate_limit_backoff_seconds=0.25,
+ sleep=sleeps.append,
+ )
+
+ assert runner.calls == {"stuck": 3}
+ assert sleeps == [0.25, 0.25]
+ assert outcomes["stuck"].exit_code == 1
+ assert "429" in failure_diagnostic(outcomes["stuck"])
+
+
+def test_run_claude_models_parallel_retries_timeout_shaped_cli_errors():
+ """CLI timeouts are how saturated upstreams usually present (the CLI
+ retries 429s internally until the harness kills it), so a timeout
+ must be retried like an explicit 429."""
+ calls: List[int] = []
+
+ def runner(cmd, env, capture_output, text, timeout, check, input=None):
+ calls.append(1)
+ if len(calls) == 1:
+ raise subprocess.TimeoutExpired(cmd="claude", timeout=1)
+ return _Completed(returncode=0, stdout=_OK_STDOUT)
+
+ sleeps: List[float] = []
+ outcomes = run_claude_models_parallel(
+ models=["a"],
+ prompt="hi",
+ base_url="http://x",
+ api_key="k",
+ runner=runner,
+ rate_limit_retries=1,
+ rate_limit_backoff_seconds=0.5,
+ sleep=sleeps.append,
+ )
+
+ assert isinstance(outcomes["a"], DriverResult)
+ assert outcomes["a"].text == "pong"
+ assert len(calls) == 2
+ assert sleeps == [0.5]
+
+
+def test_run_claude_models_parallel_zero_retries_disables_backoff():
+ """`rate_limit_retries=0` must restore the old single-attempt
+ behavior exactly: one call, no sleeps, failure returned as-is."""
+ runner = _FlakyRunner({"stuck": 99})
+ sleeps: List[float] = []
+
+ outcomes = run_claude_models_parallel(
+ models=["stuck"],
+ prompt="hi",
+ base_url="http://x",
+ api_key="k",
+ runner=runner,
+ rate_limit_retries=0,
+ rate_limit_backoff_seconds=0.5,
+ sleep=sleeps.append,
+ )
+
+ assert runner.calls == {"stuck": 1}
+ assert sleeps == []
+ assert outcomes["stuck"].exit_code == 1
diff --git a/tests/e2e/claude_code/cli_driver.py b/tests/e2e/claude_code/cli_driver.py
index 97eaa0e6847..5b18c1c291a 100644
--- a/tests/e2e/claude_code/cli_driver.py
+++ b/tests/e2e/claude_code/cli_driver.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import json
import os
+import re
import shutil
import subprocess
import sys
@@ -40,6 +41,29 @@ DEFAULT_TIMEOUT_SECONDS = float(
os.environ.get("LITELLM_COMPAT_CLI_TIMEOUT_SECONDS") or 120
)
+RATE_LIMIT_SHAPED_RE = re.compile(
+ r"(?:\b429\b|rate[\s_-]?limit|too\s+many\s+requests|throttl(?:ed|ing)|"
+ r"claude\s+CLI\s+timed\s+out)",
+ re.IGNORECASE,
+)
+"""Heuristic shared with the conftest rate-limit summary: 429s and
+throttle markers anywhere in the failure text, plus CLI timeouts --
+the CLI retries 429s internally until the harness timeout kills it,
+so a saturated upstream usually surfaces as a timeout rather than a
+clean 429."""
+
+DEFAULT_RATE_LIMIT_RETRIES = int(
+ os.environ.get("LITELLM_COMPAT_RATE_LIMIT_RETRIES") or 2
+)
+DEFAULT_RATE_LIMIT_BACKOFF_SECONDS = float(
+ os.environ.get("LITELLM_COMPAT_RATE_LIMIT_BACKOFF_SECONDS") or 65
+)
+"""Rate-limit-shaped failures are retried after a backoff long enough
+for a per-minute quota window (the dominant 429 source across
+Anthropic / Bedrock / Vertex) to reset. Both knobs are env-tunable so
+a matrix run can trade wall time for resilience without code edits;
+retries=0 disables the behavior entirely."""
+
# Env vars the `claude` Node CLI legitimately needs to function:
# locating its own binary + node, basic locale/terminal plumbing.
# Deliberately excludes every credential-bearing var that the
@@ -265,6 +289,22 @@ def run_claude(
ModelResult = Union[DriverResult, ClaudeCLIError]
+def is_rate_limit_shaped(outcome: ModelResult) -> bool:
+ """Classify an outcome as a retryable rate-limit-shaped failure.
+
+ A `ClaudeCLIError` matches on its message (which is where the
+ driver's own timeout diagnostic lands); a failing `DriverResult`
+ matches on its full `failure_diagnostic` so 429s buried in the
+ CLI's stdout text or `api_error_status` are both caught. Passing
+ results are never rate-limit-shaped.
+ """
+ if isinstance(outcome, ClaudeCLIError):
+ return bool(RATE_LIMIT_SHAPED_RE.search(str(outcome)))
+ if outcome.exit_code == 0:
+ return False
+ return bool(RATE_LIMIT_SHAPED_RE.search(failure_diagnostic(outcome)))
+
+
def run_claude_models_parallel(
*,
models: Sequence[str],
@@ -277,6 +317,9 @@ def run_claude_models_parallel(
cli_path: str = CLAUDE_CLI_DEFAULT,
timeout: float = DEFAULT_TIMEOUT_SECONDS,
runner: Optional[Callable[..., Any]] = None,
+ rate_limit_retries: Optional[int] = None,
+ rate_limit_backoff_seconds: Optional[float] = None,
+ sleep: Callable[[float], None] = time.sleep,
) -> Dict[str, ModelResult]:
"""Invoke `run_claude` for every `models[i]` concurrently and collect outcomes.
@@ -290,6 +333,14 @@ def run_claude_models_parallel(
keep the synchronous CLI driver unchanged so unit tests can keep
injecting a fake `runner`.
+ Rate-limit-shaped failures (see `is_rate_limit_shaped`) are retried
+ per model up to `rate_limit_retries` times, sleeping
+ `rate_limit_backoff_seconds` before each retry so per-minute quota
+ windows can reset; both default to the `LITELLM_COMPAT_RATE_LIMIT_*`
+ env knobs. Each retry goes back through `run_claude`, so it
+ re-acquires a token from the provider rate limiter like any other
+ invocation. `sleep` is an injection seam for unit tests.
+
Returns a dict keyed by model id. Each value is either the
`DriverResult` produced by `run_claude` or the `ClaudeCLIError`
that aborted that model's run — callers decide how to map either
@@ -300,14 +351,20 @@ def run_claude_models_parallel(
if not models:
raise ValueError("models must be a non-empty sequence")
- def _one(model: str) -> Tuple[str, ModelResult, float]:
- # Per-model wall clock: this is what the matrix run actually pays for.
- # We record it whether the run succeeded or raised so the breakdown
- # log below covers both code paths and surfaces "which model is the
- # long pole?" without requiring per-test instrumentation.
- started = time.monotonic()
+ retries = (
+ DEFAULT_RATE_LIMIT_RETRIES
+ if rate_limit_retries is None
+ else max(0, rate_limit_retries)
+ )
+ backoff = (
+ DEFAULT_RATE_LIMIT_BACKOFF_SECONDS
+ if rate_limit_backoff_seconds is None
+ else max(0.0, rate_limit_backoff_seconds)
+ )
+
+ def _run_once(model: str) -> ModelResult:
try:
- result = run_claude(
+ return run_claude(
prompt=prompt,
model=model,
base_url=base_url,
@@ -319,14 +376,8 @@ def run_claude_models_parallel(
timeout=timeout,
runner=runner,
)
- elapsed = time.monotonic() - started
- # Stamp the duration onto the DriverResult so callers (tests,
- # diagnostics) can attribute slow cells without re-timing.
- result.duration_ms = int(elapsed * 1000)
- return model, result, elapsed
except ClaudeCLIError as exc:
- elapsed = time.monotonic() - started
- return model, exc, elapsed
+ return exc
except Exception as exc:
# Honor the documented "errors as values" contract for any
# exception type — not just ClaudeCLIError. The rate
@@ -334,13 +385,38 @@ def run_claude_models_parallel(
# raise ValueError on edge-case model strings, and a future
# bug elsewhere in the call stack must not abort the entire
# parallel batch and lose the other models' outcomes.
- elapsed = time.monotonic() - started
wrapped = ClaudeCLIError(
f"unexpected error running model {model!r}: "
f"{type(exc).__name__}: {exc}"
)
wrapped.__cause__ = exc
- return model, wrapped, elapsed
+ return wrapped
+
+ def _one(model: str) -> Tuple[str, ModelResult, float]:
+ # Per-model wall clock: this is what the matrix run actually pays
+ # for, retries and backoff sleeps included. We record it whether
+ # the run succeeded or raised so the breakdown log below covers
+ # both code paths and surfaces "which model is the long pole?"
+ # without requiring per-test instrumentation.
+ started = time.monotonic()
+ outcome = _run_once(model)
+ for attempt in range(retries):
+ if not is_rate_limit_shaped(outcome):
+ break
+ print(
+ f"[retry] {model}: rate-limit-shaped failure; sleeping "
+ f"{backoff:.0f}s before attempt {attempt + 2}/{retries + 1}",
+ file=sys.stderr,
+ flush=True,
+ )
+ sleep(backoff)
+ outcome = _run_once(model)
+ elapsed = time.monotonic() - started
+ if isinstance(outcome, DriverResult):
+ # Stamp the duration onto the DriverResult so callers (tests,
+ # diagnostics) can attribute slow cells without re-timing.
+ outcome.duration_ms = int(elapsed * 1000)
+ return model, outcome, elapsed
outcomes: Dict[str, ModelResult] = {}
durations: Dict[str, float] = {}
diff --git a/tests/e2e/claude_code/conftest.py b/tests/e2e/claude_code/conftest.py
index d2bfa1a54bf..6ee8b940648 100644
--- a/tests/e2e/claude_code/conftest.py
+++ b/tests/e2e/claude_code/conftest.py
@@ -33,7 +33,6 @@ from __future__ import annotations
import functools
import json
import os
-import re
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass, field
@@ -43,6 +42,8 @@ from typing import Any, Dict, FrozenSet, List, Optional, Tuple
import pytest
import yaml
+from claude_code.cli_driver import RATE_LIMIT_SHAPED_RE
+
VALID_STATUSES = {"pass", "fail", "not_applicable", "not_tested"}
RESULTS_ARTIFACT_ENV = "COMPAT_RESULTS_PATH"
DEFAULT_ARTIFACT_PATH = "compat-results.json"
@@ -62,11 +63,10 @@ DEFAULT_RATE_LIMIT_SUMMARY_PATH = "compat-rate-limit-summary.json"
# the rate limiter is supposed to back off from. False positives on a
# genuinely slow upstream are tolerable here because the worst case is
# the binary search runs at a slightly lower rate than necessary.
-_RATE_LIMIT_RE = re.compile(
- r"(?:\b429\b|rate[\s_-]?limit|too\s+many\s+requests|throttl(?:ed|ing)|"
- r"claude\s+CLI\s+timed\s+out)",
- re.IGNORECASE,
-)
+#
+# The pattern lives in `cli_driver` so the driver's retry-on-rate-limit
+# logic and this summary classify failures identically.
+_RATE_LIMIT_RE = RATE_LIMIT_SHAPED_RE
@dataclass