Skip to content

The agent that grows with you

fix(aux): walk every configured fallback_providers entry after a candidate quota error

teknium1639fb57527a1
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index d8763472ea6..2806872968a 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -110,7 +110,9 @@ def aux_probe_mode():
from agent.credential_pool import load_pool
from agent.model_metadata import MINIMUM_CONTEXT_LENGTH, get_model_context_length
from hermes_cli.config import get_hermes_home
-from agent.auxiliary_health import _custom_health_base_url, _unhealthy_cache_key
+from agent.auxiliary_health import (
+ _custom_health_base_url, _unhealthy_cache_key, fallback_candidate_unavailable_reason,
+)
from agent.auxiliary_unavailable import (
AuxiliaryClientUnavailable, clear_nous_credential_failure, nous_credential_failure_detail,
record_nous_credential_failure)
@@ -3921,12 +3923,13 @@ def _plan_fallback_candidate(
def _quarantine_fallback_candidate(
task: Optional[str], fb_label: str, fb_provider: str, fb_err: Exception, *,
- base_url: str = "", tag: str = "",
+ base_url: str = "", tag: str = "", why: str = "has a stale/unrefreshable credential",
) -> None:
- """Refresh unavailable or still 401s: token is dead. Quarantine the candidate so the caller moves on."""
+ """The candidate cannot serve this walk (dead token, or a capacity error such as a quota 429):
+ mark it unhealthy so the ordered re-walk skips it and the caller moves on to the next entry."""
_mark_provider_unhealthy(fb_provider or fb_label, base_url=base_url, reason="stale fallback credential")
- logger.warning("Auxiliary %s%s: fallback candidate %s has a stale/unrefreshable "
- "credential (%s) — skipping to next fallback", task or "call", tag, fb_label, fb_err)
+ logger.warning("Auxiliary %s%s: fallback candidate %s %s (%s) — skipping to next fallback",
+ task or "call", tag, fb_label, why, fb_err)
def _plan_fallback_auth_retry(
@@ -3957,7 +3960,9 @@ def _call_fallback_candidate_sync(
) -> Optional[Any]:
"""Call one fallback candidate with stale-credential recovery: on an auth error refresh its
credentials and retry once with a rebuilt client; if that also auth-fails, quarantine the
- provider and return None so the caller moves on. Non-auth errors raise.
+ provider and return None so the caller moves on. A capacity error (quota/rate-limit 429, 402,
+ connection, route-incompatible model, malformed response) also quarantines and returns None so
+ the ordered chain advances to the next configured entry (#106367); other errors raise.
``effective_timeout`` is the task-level deadline; a configured-chain candidate with its own ``timeout``
entry gets that instead, so a fallback tuned differently from the primary is allowed its own budget
@@ -3990,7 +3995,13 @@ def _call_fallback_candidate_sync(
return _send_recovering(fb_client, fb_kwargs, destination)
except Exception as fb_err:
if not _is_auth_error(fb_err):
- raise
+ capacity = fallback_candidate_unavailable_reason(fb_err)
+ if capacity is None:
+ raise
+ _quarantine_fallback_candidate(
+ task, fb_label, destination.provider, fb_err, base_url=destination.base_url,
+ why=f"is out of capacity ({capacity})")
+ return None
fb_provider, retry = _plan_fallback_auth_retry(
destination, rebuild, async_mode=False, failed_api_key=getattr(fb_client, "api_key", ""))
failed_destination = destination
@@ -3999,7 +4010,7 @@ def _call_fallback_candidate_sync(
try:
return _send_recovering(*retry)
except Exception as retry_err:
- if not _is_auth_error(retry_err):
+ if not _is_auth_error(retry_err) and fallback_candidate_unavailable_reason(retry_err) is None:
raise
_quarantine_fallback_candidate(
task, fb_label, fb_provider, fb_err, base_url=failed_destination.base_url,
@@ -4034,7 +4045,13 @@ async def _call_fallback_candidate_async(
return await _send_recovering(fb_client, fb_kwargs, destination)
except Exception as fb_err:
if not _is_auth_error(fb_err):
- raise
+ capacity = fallback_candidate_unavailable_reason(fb_err)
+ if capacity is None:
+ raise
+ _quarantine_fallback_candidate(
+ task, fb_label, destination.provider, fb_err, base_url=destination.base_url,
+ tag=" (async)", why=f"is out of capacity ({capacity})")
+ return None
fb_provider, retry = _plan_fallback_auth_retry(
destination, rebuild, async_mode=True, failed_api_key=getattr(fb_client, "api_key", ""))
failed_destination = destination
@@ -4043,7 +4060,7 @@ async def _call_fallback_candidate_async(
try:
return await _send_recovering(*retry)
except Exception as retry_err:
- if not _is_auth_error(retry_err):
+ if not _is_auth_error(retry_err) and fallback_candidate_unavailable_reason(retry_err) is None:
raise
_quarantine_fallback_candidate(
task, fb_label, fb_provider, fb_err,
@@ -7376,9 +7393,10 @@ def _next_fallback_after_quarantine(
task: Optional[str], resolved_provider: str, is_auto: bool, route: _LadderRoute,
failed_model: Optional[str], failure_scope: Any,
) -> Tuple[Optional[Any], Optional[str], str]:
- """Next candidate after a fallback entry was quarantined mid-request: remaining configured
- entries (task chain, then main chain on auto) before the discovery chain."""
- reason = "stale fallback credential"
+ """Next candidate after a fallback entry was quarantined mid-request (dead credential or a
+ capacity error): remaining configured entries (task chain, then main chain on auto) before the
+ discovery chain."""
+ reason = "fallback candidate unavailable"
fb = _try_configured_fallback_chain(
task, resolved_provider or "auto", reason=reason, failed_model=failed_model,
failed_base_url=route.base_info, failure_scope=failure_scope)
@@ -7453,20 +7471,23 @@ def _ladder_provider_fallback(first_err: Exception, route: _LadderRoute):
fb_client, fb_model, fb_label = _try_main_agent_model_fallback(
resolved_provider, task, reason=reason, failed_model=_chain_failed_model,
failed_base_url=route.base_info, failure_scope=_chain_failure_scope)
- if fb_client is not None:
- # Second pass: the candidate credential was stale and quarantined — re-walk the CONFIGURED
- # chains first (the quarantined entry is now unhealthy and skipped, so later entries get
- # their turn), then discovery where the selection policy allows it.
- for _pass in range(2):
- _record_route_info(route.route_info, _fallback_provider_from_label(fb_label), fb_model)
- fb_resp = yield _LadderStep("fallback", (fb_client, fb_model, fb_label))
- if fb_resp is not None:
- return fb_resp
- if _pass == 0:
- fb_client, fb_model, fb_label = _next_fallback_after_quarantine(
- task, resolved_provider, is_auto, route, _chain_failed_model, _chain_failure_scope)
- if fb_client is None:
- break
+ # Ordered walk: a candidate that returns None was quarantined (dead credential or a capacity
+ # error such as a quota 429) and is now unhealthy, so re-walking the CONFIGURED chains first
+ # lands on the next entry, then discovery where the selection policy allows it (#106367).
+ # Bounded by construction: every pass quarantines its candidate and the walk stops as soon as
+ # re-selection hands back a lane already tried, so each lane is attempted at most once.
+ tried_lanes: set = set()
+ while fb_client is not None:
+ lane = (fb_label, fb_model, str(getattr(fb_client, "base_url", "") or ""))
+ if lane in tried_lanes:
+ break
+ tried_lanes.add(lane)
+ _record_route_info(route.route_info, _fallback_provider_from_label(fb_label), fb_model)
+ fb_resp = yield _LadderStep("fallback", (fb_client, fb_model, fb_label))
+ if fb_resp is not None:
+ return fb_resp
+ fb_client, fb_model, fb_label = _next_fallback_after_quarantine(
+ task, resolved_provider, is_auto, route, _chain_failed_model, _chain_failure_scope)
# All fallback layers exhausted — one user-visible warning, then re-raise.
logger.warning("Auxiliary %s%s: %s on %s and all fallbacks exhausted "
# All fallback layers exhausted — emit a single user-visible warning so the operator
diff --git a/agent/auxiliary_health.py b/agent/auxiliary_health.py
index 9b6c0418257..7301f337826 100644
--- a/agent/auxiliary_health.py
+++ b/agent/auxiliary_health.py
@@ -38,3 +38,18 @@ def _custom_health_base_url(provider: str, explicit_base_url: Optional[str] = No
return ""
+
+
+def fallback_candidate_unavailable_reason(exc: Exception) -> Optional[str]:
+ """Why a fallback candidate cannot serve this walk (``_FALLBACK_REASONS`` label), or None.
+
+ The same capacity classes that admitted the primary failure into the chain (payment/quota,
+ rate limit, connection, route-incompatible model, malformed response) mean "this lane is out
+ for now, try the next configured one"; anything else (a 400 request-shape error, a ValueError)
+ is the caller's bug and must still propagate. Auth errors are excluded on purpose: they have
+ their own refresh-then-quarantine path in the candidate helpers (#106367)."""
+ from agent.auxiliary_client import _FALLBACK_REASONS
+ return next(
+ (label for predicate, label in _FALLBACK_REASONS if label != "auth error" and predicate(exc)),
+ None,
+ )
diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.py
index 71d98f157f9..1b8e8784f6a 100644
--- a/tests/agent/test_auxiliary_client.py
+++ b/tests/agent/test_auxiliary_client.py
@@ -1835,7 +1835,7 @@ class TestStaleFallbackCandidateSkip:
assert result.choices[0].message.content == "openrouter-serves"
assert mock_fb.call_count == 2
- assert mock_fb.call_args_list[1].kwargs.get("reason") == "stale fallback credential"
+ assert mock_fb.call_args_list[1].kwargs.get("reason") == "fallback candidate unavailable"
mock_mark.assert_called_once_with(
"anthropic", base_url="https://api.anthropic.com", reason="stale fallback credential",
)
diff --git a/tests/agent/test_auxiliary_fallback_multihop.py b/tests/agent/test_auxiliary_fallback_multihop.py
new file mode 100644
index 00000000000..a0878dec155
--- /dev/null
+++ b/tests/agent/test_auxiliary_fallback_multihop.py
@@ -0,0 +1,90 @@
+"""Auxiliary ``provider: auto`` fallback walk is multi-hop (#106367).
+
+When a ``fallback_providers`` candidate itself fails with a quota/rate-limit/payment/capacity
+error, the walk must advance to the next configured entry instead of letting the candidate's
+exception escape after a single hop. Every lane is attempted at most once; when the whole chain
+is exhausted the last error still surfaces as a controlled failure. Sync and async share the walk.
+"""
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from agent.auxiliary_client import async_call_llm, call_llm
+
+
+def _quota_429(lane: str) -> Exception:
+ exc = Exception(
+ f"Error code: 429 - {{'error': {{'message': 'Weekly usage limit reached', "
+ f"'type': 'usage_limit_reached', 'code': 'rate_limit_exceeded', 'lane': '{lane}'}}}}"
+ )
+ exc.status_code = 429
+ return exc
+
+
+def _client(base_url: str, create):
+ client = MagicMock()
+ client.base_url = base_url
+ client.chat.completions.create = create
+ return client
+
+
+def _ok_response(text: str):
+ resp = MagicMock()
+ resp.choices = [MagicMock()]
+ resp.choices[0].message.content = text
+ resp.choices[0].message.tool_calls = None
+ return resp
+
+
+def _walk_patches(primary, main_chain_selections):
+ """``provider: auto`` primary; per-task chain empty; main ``fallback_providers`` hands out the
+ given (client, model, label) tuples in order and then reports exhaustion; discovery is empty."""
+ return (
+ patch("agent.auxiliary_client._resolve_task_provider_model",
+ return_value=("auto", None, None, None, None)),
+ patch("agent.auxiliary_client._get_cached_client", return_value=(primary, "modelA")),
+ patch("agent.auxiliary_client._try_configured_fallback_chain", return_value=(None, None, "")),
+ patch("agent.auxiliary_client._try_main_fallback_chain",
+ side_effect=list(main_chain_selections) + [(None, None, "")]),
+ patch("agent.auxiliary_client._try_payment_fallback", return_value=(None, None, "")),
+ patch("agent.auxiliary_client._mark_provider_unhealthy"),
+ )
+
+
+def test_sync_walk_advances_past_quota_limited_candidate_to_next_configured_entry():
+ """T3: primary 429 → fallback_providers[0] 429 → fallback_providers[1] serves."""
+ primary = _client("http://127.0.0.1:1/v1", MagicMock(side_effect=_quota_429("A")))
+ lane_b = _client("http://127.0.0.1:2/v1", MagicMock(side_effect=_quota_429("B")))
+ lane_c = _client("http://127.0.0.1:3/v1", MagicMock(return_value=_ok_response("OK")))
+
+ patches = _walk_patches(primary, [(lane_b, "modelB", "custom"), (lane_c, "modelC", "custom")])
+ with patches[0], patches[1], patches[2], patches[3], patches[4], patches[5] as mark_unhealthy:
+ result = call_llm(task="title_generation", messages=[{"role": "user", "content": "Reply OK"}])
+
+ assert result.choices[0].message.content == "OK"
+ assert lane_b.chat.completions.create.call_count == 1
+ assert lane_c.chat.completions.create.call_count == 1
+ # The quota-limited candidate is quarantined so the ordered re-walk skips it.
+ assert ("custom",) in {c.args for c in mark_unhealthy.call_args_list}
+ assert any(c.kwargs.get("base_url") == "http://127.0.0.1:2/v1" for c in mark_unhealthy.call_args_list)
+
+
+async def test_async_walk_exhausts_every_configured_lane_once_then_raises_last_error():
+ """T4: primary 429 → fallback[0] 429 → fallback[1] 429 → controlled exhaustion; each lane once."""
+ primary = _client("http://127.0.0.1:1/v1", AsyncMock(side_effect=_quota_429("A")))
+ lane_b = _client("http://127.0.0.1:2/v1", AsyncMock(side_effect=_quota_429("B")))
+ lane_c = _client("http://127.0.0.1:3/v1", AsyncMock(side_effect=_quota_429("C")))
+
+ patches = _walk_patches(primary, [(lane_b, "modelB", "custom"), (lane_c, "modelC", "custom")])
+ with patches[0], patches[1], patches[2], patches[3] as main_chain, patches[4] as discovery, patches[5], \
+ patch("agent.auxiliary_client._to_async_client", side_effect=lambda c, m, **kw: (c, m)):
+ with pytest.raises(Exception, match="usage_limit_reached"):
+ await async_call_llm(task="compression", messages=[{"role": "user", "content": "summarize"}])
+
+ assert lane_b.chat.completions.create.call_count == 1
+ assert lane_c.chat.completions.create.call_count == 1
+ # Walk stopped once the configured chain reported exhaustion — no lane was re-tried.
+ assert main_chain.call_count == 3
+ # Exhaustion is controlled: discovery was consulted and found nothing, no fourth lane appended.
+ assert discovery.call_count >= 1