Skip to content

The agent that grows with you

fix(auxiliary): a rate-limited auxiliary call backs off before its same-key retry

Teknium15df08e6c17b
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index f6c9e5fe1ba..34401444a87 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -7732,11 +7732,10 @@ def _ladder_credential_rungs(
# is skipped and ``first_err`` is handed to the provider-fallback chain as-is.
if pool_provider and _credential_rung_accepts(first_err):
recovery_err = first_err
- # Skip the extra retry for clear payment/quota errors — the endpoint won't accept
- # another request with the same exhausted key.
+ # No backoff retry for a payment/quota error: the same exhausted key stays refused.
if _is_rate_limit_error(first_err) and not _is_payment_error(first_err):
- resp, recovery_err = yield from _rung(
- _LadderStep("call", (client, kwargs)), _credential_rung_accepts)
+ from agent.auxiliary_rate_limit_backoff import rate_limit_retry_rungs
+ resp, recovery_err = yield from rate_limit_retry_rungs(first_err, client, kwargs, f"{task or 'call'}{tag}")
if recovery_err is None:
return resp, None
if _recover_provider_pool(pool_provider, recovery_err, failed_api_key=_client_api_key):
@@ -7926,12 +7925,12 @@ def _aux_recovery_ladder(
def _drive_ladder(ladder, perform: Callable[[_LadderStep], Any]) -> Any:
- """Run a ladder generator, feeding each step's result (or exception) back in."""
+ """Run a ladder generator, feeding each step's result (or exception) back in; a ``wait`` step sleeps."""
try:
step = next(ladder)
while True:
try:
- result = perform(step)
+ result = time.sleep(step.args[0]) if step.kind == "wait" else perform(step)
except Exception as exc:
step = ladder.throw(exc)
else:
@@ -7942,11 +7941,12 @@ def _drive_ladder(ladder, perform: Callable[[_LadderStep], Any]) -> Any:
async def _drive_ladder_async(ladder, perform: Callable[[_LadderStep], Any]) -> Any:
"""Async twin of :func:`_drive_ladder` (``perform`` is awaited)."""
+ import asyncio
try:
step = next(ladder)
while True:
try:
- result = await perform(step)
+ result = await (asyncio.sleep(step.args[0]) if step.kind == "wait" else perform(step))
except Exception as exc:
step = ladder.throw(exc)
else:
diff --git a/agent/auxiliary_rate_limit_backoff.py b/agent/auxiliary_rate_limit_backoff.py
new file mode 100644
index 00000000000..2fda9b62f51
--- /dev/null
+++ b/agent/auxiliary_rate_limit_backoff.py
@@ -0,0 +1,71 @@
+"""Same-credential backoff for an auxiliary call refused by a rate limit (429, Bedrock throttle).
+
+Auxiliary clients make one attempt per call (OpenAI SDK ``max_retries=0``, botocore
+``total_max_attempts: 1``), so the recovery ladder owns the wait. An immediate re-send lands in the
+same throttle window and spends the retry, then credential rotation and the provider fallback chain
+see a provider that would have answered a moment later. The ladder yields a ``wait`` step; the sync
+and async ladder drivers sleep it, so both caller kinds share one schedule.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Optional
+
+from agent import retry_utils
+
+logger = logging.getLogger(__name__)
+
+# One same-credential retry, then credential-pool rotation and the provider fallback chain take over.
+RATE_LIMIT_RETRIES = 1
+# Jittered exponential backoff (seconds): 1-1.5 before the first retry, doubling up to the cap.
+RATE_LIMIT_BACKOFF_BASE = 1.0
+RATE_LIMIT_BACKOFF_CAP = 4.0
+# A provider-declared cooldown longer than this is not worth sitting through inside an auxiliary
+# call (compression, titles, summaries): rotate or fall back instead.
+RATE_LIMIT_RETRY_AFTER_CAP = 5.0
+
+
+def rate_limit_retry_after(exc: Exception) -> Optional[float]:
+ """Provider-declared cooldown in seconds: ``Retry-After`` / a ``retry_after`` body field, or the
+ ``retry-after`` header botocore keeps in ``ResponseMetadata.HTTPHeaders``; None when absent."""
+ value = retry_utils.provider_retry_after_seconds(exc)
+ response = getattr(exc, "response", None)
+ if value is None and isinstance(response, dict): # botocore ClientError: the parsed response dict
+ value = retry_utils.parse_retry_after_seconds(response.get("ResponseMetadata", {}).get("HTTPHeaders"))
+ return value if value is not None and value > 0 else None
+
+
+def rate_limit_wait(exc: Exception, attempt: int) -> Optional[float]:
+ """Seconds to wait before same-credential retry ``attempt`` (1-based), or None when the provider
+ declared a cooldown longer than ``RATE_LIMIT_RETRY_AFTER_CAP``."""
+ declared = rate_limit_retry_after(exc)
+ if declared is not None:
+ return declared if declared <= RATE_LIMIT_RETRY_AFTER_CAP else None
+ return retry_utils.jittered_backoff(
+ attempt, base_delay=RATE_LIMIT_BACKOFF_BASE, max_delay=RATE_LIMIT_BACKOFF_CAP)
+
+
+def rate_limit_retry_rungs(first_err: Exception, client: Any, kwargs: dict[str, Any], label: str):
+ """Ladder rungs: wait, then re-send on the same client, up to ``RATE_LIMIT_RETRIES`` times while
+ the refusal stays a rate limit. Returns ``(response, None)`` or ``(None, last_err)``."""
+ from agent.auxiliary_client import (
+ _LadderStep, _credential_rung_accepts, _is_payment_error, _is_rate_limit_error, _rung,
+ )
+
+ err = first_err
+ for attempt in range(1, RATE_LIMIT_RETRIES + 1):
+ wait = rate_limit_wait(err, attempt)
+ if wait is None:
+ logger.info("Auxiliary %s: provider asked for a %.0fs cooldown; not waiting it out",
+ label, rate_limit_retry_after(err) or 0.0)
+ break
+ logger.info("Auxiliary %s: rate limited (attempt %d/%d); retrying after %.2fs",
+ label, attempt, RATE_LIMIT_RETRIES, wait)
+ yield _LadderStep("wait", (wait,))
+ resp, err = yield from _rung(_LadderStep("call", (client, kwargs)), _credential_rung_accepts)
+ if err is None:
+ return resp, None
+ if not _is_rate_limit_error(err) or _is_payment_error(err):
+ break
+ return None, err
diff --git a/tests/agent/test_bedrock_no_sdk_retry.py b/tests/agent/test_bedrock_no_sdk_retry.py
index 077b909ac2c..72c042e6059 100644
--- a/tests/agent/test_bedrock_no_sdk_retry.py
+++ b/tests/agent/test_bedrock_no_sdk_retry.py
@@ -6,8 +6,10 @@ backoff. These tests drive the real boto3 client the adapter builds against a lo
and count the requests that reach it.
"""
+import asyncio
import json
import threading
+import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
@@ -30,13 +32,15 @@ CONVERSE_OK = {"output": {"message": {"role": "assistant", "content": [{"text":
def fake_bedrock(monkeypatch):
"""Local bedrock-runtime endpoint; ``mode`` is ``hang`` (never answers until teardown) or
``throttle`` (400 ThrottlingException) / ``unavailable`` (503) for the first ``fail_first``
- requests, then a Converse answer. Yields the list of request paths it received."""
- state = {"mode": "hang", "hits": [], "fail_first": 10**6}
+ requests, or until ``fail_for`` seconds after the first request, then a Converse answer.
+ Yields the state; ``hits`` lists request paths, ``times`` their monotonic arrival."""
+ state = {"mode": "hang", "hits": [], "times": [], "fail_first": 10**6, "fail_for": None}
release = threading.Event()
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
state["hits"].append(self.path)
+ state["times"].append(time.monotonic())
self.rfile.read(int(self.headers.get("content-length", 0)))
if state["mode"] == "hang":
release.wait(30)
@@ -45,7 +49,9 @@ def fake_bedrock(monkeypatch):
"throttle": (400, "ThrottlingException", {"message": "Too many requests, please wait before trying again."}),
"unavailable": (503, "ServiceUnavailableException", {"message": "Service unavailable, try later."}),
}[state["mode"]]
- if len(state["hits"]) > state["fail_first"]:
+ window = state["fail_for"]
+ if (len(state["hits"]) > state["fail_first"] if window is None
+ else state["times"][-1] - state["times"][0] >= window):
status, error_type, payload = 200, None, CONVERSE_OK
body = json.dumps(payload).encode()
self.send_response(status)
@@ -127,3 +133,33 @@ def test_auxiliary_call_recovers_from_one_transient_bedrock_refusal(fake_bedrock
assert response.choices[0].message.content == "pong"
assert len(fake_bedrock["hits"]) == 2
+
+
[email protected]_retry_backoff
[email protected]("caller", ["sync", "async"])
+def test_auxiliary_call_waits_out_a_bedrock_throttle_window(fake_bedrock, monkeypatch, caller):
+ """A throttle lasting ~300ms is backed off, not re-sent at once: botocore no longer waits
+ between attempts, so an immediate re-send lands in the same window and the task fails."""
+ from agent import auxiliary_client
+ from agent.auxiliary_client import (
+ AsyncBedrockAuxiliaryClient, BedrockAuxiliaryClient, async_call_llm, call_llm,
+ )
+
+ _use_config(monkeypatch, {})
+ fake_bedrock.update(mode="throttle", fail_for=0.3)
+ client = BedrockAuxiliaryClient(REGION, MODEL)
+ monkeypatch.setattr(auxiliary_client, "_get_auxiliary_task_config",
+ lambda task: {"provider": "bedrock", "model": MODEL, "max_output_tokens": 0})
+ monkeypatch.setattr(
+ auxiliary_client, "_get_cached_client",
+ lambda *a, async_mode=False, **k: (AsyncBedrockAuxiliaryClient(client) if async_mode else client, MODEL))
+ messages = [{"role": "user", "content": "ping"}]
+
+ if caller == "sync":
+ response = call_llm(task="session_search", messages=messages)
+ else:
+ response = asyncio.run(async_call_llm(task="session_search", messages=messages))
+
+ assert response.choices[0].message.content == "pong"
+ times = fake_bedrock["times"]
+ assert times[1] - times[0] >= 0.25, "the throttled call was re-sent without a backoff"