The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): honor Retry-After on retryable 5xx
Mauvis Ledforda22748490628
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.pyindex 5aed02349a0..417feac8ce2 100644--- a/agent/turn_recovery.py+++ b/agent/turn_recovery.py@@ -974,26 +974,31 @@ def compute_error_backoff(agent: Any, api_error: Exception, *, retry_count: int, max_retries: int, is_rate_limited: bool,is_zai_coding_overload: bool, base_url: Any, model: Any,) -> float:- """Pick the wait before the next API retry and announce it. Retry-After wins for rate- limits (capped at 600s: Anthropic Tier 1 buckets reset in ~171s, so a 120s cap re-tripped- the limit); otherwise jittered backoff, replaced by the adaptive policy for 429s / Z.AI- overloads. Normal retries are buffered; long Z.AI Coding waits surface immediately."""+ """Pick the wait before the next API retry and announce it. Retry-After wins for+ rate limits and any other retryable error (capped at 600s: Anthropic Tier 1 buckets+ reset in ~171s, so a 120s cap re-tripped the limit); otherwise jittered backoff,+ replaced by the adaptive policy for 429s / Z.AI overloads. Normal retries are+ buffered; long Z.AI Coding waits surface immediately."""# Imported lazily so tests that patch ``agent.retry_utils.jittered_backoff`` /# ``adaptive_rate_limit_backoff`` (incl. the run_agent conftest fast-backoff fixture) intercept.- from agent.retry_utils import adaptive_rate_limit_backoff, jittered_backoff-- _retry_after = None- _resp_headers = getattr(getattr(api_error, "response", None), "headers", None) if is_rate_limited else None- if _resp_headers and hasattr(_resp_headers, "get"):- _ra_raw = _resp_headers.get("retry-after") or _resp_headers.get("Retry-After")- if _ra_raw:- try:- # Cap at 10 minutes. Anthropic Tier 1 input-token buckets reset in ~171s, so a 120s cap- # caused us to retry before the actual reset window and re-trip the limit. 600s covers all- # realistic provider reset windows while still rejecting pathological values. (#26293)- _retry_after = min(float(_ra_raw), 600)- except (TypeError, ValueError):- pass+ from agent.retry_utils import adaptive_rate_limit_backoff, jittered_backoff, parse_retry_after_seconds++ # Respect Retry-After on every retryable provider error, not just 429s. Retryable+ # 5xx responses (e.g. Cloudflare 520/524) also carry the header or a structured+ # ``retry_after`` problem-detail body field; ignoring either turns an origin+ # outage into a retry storm.+ _retry_after = parse_retry_after_seconds(+ getattr(getattr(api_error, "response", None), "headers", None)+ )+ if _retry_after is None:+ _error_body = getattr(api_error, "body", None)+ if isinstance(_error_body, dict):+ _retry_after = parse_retry_after_seconds(_error_body.get("retry_after"))+ if _retry_after is not None:+ # Cap at 10 minutes. Anthropic Tier 1 input-token buckets reset in ~171s, so a 120s cap+ # caused us to retry before the actual reset window and re-trip the limit. 600s covers all+ # realistic provider reset windows while still rejecting pathological values. (#26293)+ _retry_after = min(_retry_after, 600)wait_time = _retry_after if _retry_after else jittered_backoff(retry_count, base_delay=2.0, max_delay=60.0)_backoff_policy = None_adaptive = is_rate_limited or is_zai_coding_overloaddiff --git a/tests/run_agent/test_run_agent.py b/tests/run_agent/test_run_agent.pyindex 0da74057bd2..a2b7443ee37 100644--- a/tests/run_agent/test_run_agent.py+++ b/tests/run_agent/test_run_agent.py@@ -1961,9 +1961,10 @@ class TestExecuteToolCalls:class TestRetryAfterCap:- """#26293: the conversation loop owns rate-limit backoff and honors the- Retry-After header up to a 600s ceiling (was 120s, which retried before- Tier-1 reset windows of ~171s and re-tripped the limit)."""+ """The loop honors provider cooldowns up to a 600-second ceiling.++ This covers rate-limit headers (#26293) and retryable 5xx responses.+ """def _drive_once(self, agent, retry_after_value):"""Raise one 429 carrying ``Retry-After`` and capture the wait the loop@@ -2004,6 +2005,50 @@ class TestRetryAfterCap:status = self._drive_once(agent, 300)assert "Waiting 300.0s" in status+ @pytest.mark.parametrize(+ ("headers", "body"),+ [+ ({"Retry-After": "120"}, {}),+ ({}, {"status": 524, "retry_after": 120}),+ ],+ ids=("header", "problem-detail-body"),+ )+ def test_retry_after_on_cloudflare_524_is_honored(+ self, agent, headers, body+ ):+ """A retryable 5xx must not bypass the provider's cooldown."""++ class _CloudflareTimeout(Exception):+ status_code = 524++ def __str__(self):+ return "Error code: 524 - origin response timeout"++ error = _CloudflareTimeout()+ error.response = SimpleNamespace(headers=headers)+ error.body = body++ def _fake_api_call(api_kwargs):+ raise error++ agent._interruptible_api_call = _fake_api_call+ agent._persist_session = lambda *args, **kwargs: None+ agent._save_trajectory = lambda *args, **kwargs: None++ captured = []+ original_buffer = agent._buffer_status++ def _capture_status(msg, *args, **kwargs):+ captured.append(msg)+ if "Retrying in" in msg:+ agent._interrupt_requested = True+ return original_buffer(msg, *args, **kwargs)++ agent._buffer_status = _capture_status+ agent.run_conversation("hello")++ assert any("Retrying in 120.0s" in msg for msg in captured)+class TestConcurrentToolExecution: