The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: revert a quota-benched credential through the pool, not a private probe; cover /model and chained rotations
teknium192bb5b92b853
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 3f944c3205b..06e08b522e7 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -857,14 +857,14 @@ def recover_with_credential_pool(if (swappedand credential_id- and getattr(next_entry, "id", None) != credential_id+ and not getattr(agent, "_credential_pool_revert_id", None)and effective_reason in (FailoverReason.rate_limit, FailoverReason.billing)):- # Transient quota bench (429 / 402): the benched credential recovers when- # its cooldown expires. Arm the per-turn hook to swap back (#114501);- # auth and other failures keep today's behavior.+ # A quota bench (429/402) lifts when the window reopens, and a fresh session's+ # select() would go straight back to this entry; arm the per-turn hook so the live+ # session does too (#114501). Keep the FIRST benched entry across chained rotations+ # — it is the preferred one. Auth benches are not windows; they stay as they are.agent._credential_pool_revert_id = credential_id- agent._credential_pool_rotated_to = getattr(next_entry, "id", None)return swappedif effective_reason == FailoverReason.upstream_rate_limit:# Upstream (e.g. DeepSeek behind OpenRouter) is throttling the aggregator; the credential is@@ -1120,48 +1120,31 @@ def _rebind_primary_credential_pool(agent, primary_provider, primary_model, matc)-def _maybe_revert_credential_rotation(agent) -> None:- """Swap back to a transiently benched credential once it is available again (#114501).-- Best-effort and exception-proof: the per-turn restore hook calls this every turn,- so it must never raise. Uses the read-only ``_available_entries()`` check (the same- side-effect profile as ``pool.peek()``) — never ``select()``, which would bump- request counts and rotate round-robin order on a mere check.- """- try:- revert_id = getattr(agent, "_credential_pool_revert_id", None)- if not revert_id:- return- pool = getattr(agent, "_credential_pool", None)- if pool is None:- agent._credential_pool_revert_id = None- return- if getattr(agent, "_provider_fallback_active", False):- return # A provider fallback owns the binding right now; don't fight it.- bound = getattr(agent, "_credential_pool_entry_id", None)- if bound == revert_id:- # Already home (manual switch-back or another path restored it).- agent._credential_pool_revert_id = None- agent._credential_pool_rotated_to = None- return- if bound != getattr(agent, "_credential_pool_rotated_to", None):- # The binding moved elsewhere by hand; stand down rather than yank it.- agent._credential_pool_revert_id = None- agent._credential_pool_rotated_to = None- return- available, _pending = pool._available_entries(model=getattr(agent, "model", None))- target = next((e for e in available if getattr(e, "id", None) == revert_id), None)- if target is None:- return # Preferred still cooling (or gone); keep waiting.- if agent._swap_credential(target) is not False:- logger.info(- "credential pool: preferred credential %s available again, reverted",- getattr(target, "label", None) or revert_id[:8],- )+def _revert_credential_rotation(agent) -> None:+ """Move a live session back onto the credential a quota bench rotated it off, once the bench+ lifts. New sessions already do this through ``select()``; without it a long-lived (gateway)+ session keeps billing the fallback for its whole life (#114501). Credential-only: the+ model/base_url/compressor restore stays gated on ``_fallback_activated``."""+ revert_id = getattr(agent, "_credential_pool_revert_id", None)+ if not revert_id:+ return+ pool = getattr(agent, "_credential_pool", None)+ if pool is None or getattr(agent, "_credential_pool_entry_id", None) == revert_id:agent._credential_pool_revert_id = None- agent._credential_pool_rotated_to = None- except Exception:- logger.debug("credential pool revert check failed", exc_info=True)+ return+ try:+ entry = pool.reclaim(revert_id, model=getattr(agent, "model", None))+ except Exception as exc:+ logger.warning("Credential revert check failed: %s", exc)+ return+ if entry is None:+ return # still cooling down; check again next turn+ if agent._swap_credential(entry) is not False:+ logger.info(+ "Credential %s (%s) available again — reverted pool rotation",+ getattr(entry, "id", "?"), getattr(entry, "label", "?"),+ )+ agent._credential_pool_revert_id = Nonedef restore_primary_runtime(agent) -> bool:@@ -1171,7 +1154,7 @@ def restore_primary_runtime(agent) -> bool:# Reset the index even without activation: a failed _try_activate_fallback() can strand# _fallback_index past the chain end and silently block future fallbacks.agent._fallback_index = 0- _maybe_revert_credential_rotation(agent)+ _revert_credential_rotation(agent)return False# Reset the chain index even when no fallback was activated this turn. Without this, a turn where# _try_activate_fallback() was called but returned False (chain exhausted or provider not configured)@@ -2171,6 +2154,7 @@ def _finish_switch(agent, new_provider, old_norm, new_norm) -> None:agent._provider_fallback_active = Falseagent._provider_fallback_route = Noneagent._fallback_index = 0+ agent._credential_pool_revert_id = None# On a deliberate provider swap, prune fallback entries targeting the OLD or NEW primary;# otherwise a failed turn silently re-activates the provider the user just rejected.fallback_chain = list(getattr(agent, "_fallback_chain", []) or [])diff --git a/agent/credential_pool.py b/agent/credential_pool.pyindex ef2d9f4b520..458c8c62aae 100644--- a/agent/credential_pool.py+++ b/agent/credential_pool.py@@ -1788,6 +1788,18 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)available, _pending = self._available_entries()return available[0] if available else None+ def reclaim(self, credential_id: str, *, model: Optional[str] = None) -> Optional[PooledCredential]:+ """Entry *credential_id* once its cooldown has lifted (cleared and token-refreshed the way+ ``select`` would), else ``None``. Never bumps ``request_count`` or round-robin order: a+ live session asking "may I go back?" every turn is not a request."""+ with self._lock:+ available, pending = self._available_entries(clear_expired=True, refresh=True, model=model)+ if any(e.id == credential_id for e in pending):+ self._refresh_pending_entries([e for e in pending if e.id == credential_id])+ with self._lock:+ available, _pending = self._available_entries(clear_expired=True, refresh=True, model=model)+ return next((e for e in available if e.id == credential_id), None)+# ---- rotation ----------------------------------------------------------def _identify_failed_entry(diff --git a/tests/agent/test_pool_revert_after_cooldown.py b/tests/agent/test_pool_revert_after_cooldown.pyindex e1a188482bc..3e81bae4ce2 100644--- a/tests/agent/test_pool_revert_after_cooldown.py+++ b/tests/agent/test_pool_revert_after_cooldown.py@@ -1,106 +1,100 @@-"""Regression tests for #114501 — pool rotation never reverts after cooldown.+# Copyright 2025 Nous Research (Licensed under the Apache License, Version 2.0)+"""A live session rotated off a quota-benched credential moves back once the bench lifts.-A transient quota bench (429 / 402) rotates the agent onto a fallback-credential via ``mark_exhausted_and_rotate`` + ``_swap_credential``, but the-per-turn ``restore_primary_runtime`` hook early-returns when no model/provider-fallback is active — so the agent stays on the fallback credential forever,-burning the wrong billing bucket.--The fix arms ``agent._credential_pool_revert_id`` at rotation time and lets-the per-turn hook swap back once the preferred entry is available again.+New sessions already do this (``load_pool().select()`` prefers the priority-0 entry again once+its 429/402 cooldown has elapsed); the per-turn ``restore_primary_runtime`` hook must do the same+for the session that took the rotation, or a long-lived gateway agent bills the fallback for+its whole life. Credential-only: it must not touch the model/base_url/compressor restore path."""-from types import SimpleNamespace--import pytest+import time-from agent.agent_runtime_helpers import _maybe_revert_credential_rotation+import agent.credential_pool as cp+from agent.agent_runtime_helpers import recover_with_credential_pool, restore_primary_runtime+from agent.credential_pool import EXHAUSTED_TTL_429_SECONDS, CredentialPool, PooledCredential+_BASE = "https://api.anthropic.com"-def _entry(entry_id, label=None):- return SimpleNamespace(id=entry_id, label=label or entry_id[:8])+def _entry(entry_id, label, *, priority, auth_type, token):+ raw = {+ "id": entry_id, "label": label, "auth_type": auth_type, "priority": priority,+ "access_token": token, "base_url": _BASE, "source": "manual",+ }+ if auth_type == "oauth":+ raw["refresh_token"] = f"rt-{entry_id}"+ raw["expires_at_ms"] = int((time.time() + 30 * 86400) * 1000)+ return PooledCredential.from_dict("anthropic", raw)-class _FakePool:- """Mirrors ``_available_entries()``'s contract: (available, pending)."""- def __init__(self, available):- self._available = list(available)- self.calls = 0+class _LiveAgent:+ """Long-lived session stand-in: real pool + real recovery/restore helpers, no client build."""- def _available_entries(self, *, model=None):- self.calls += 1- return list(self._available), []+ _fallback_activated = False+ _fallback_index = 0+ _primary_runtime = {"provider": "anthropic", "model": "claude-opus-5", "base_url": _BASE}+ provider = "anthropic"+ model = "claude-opus-5"+ base_url = _BASE+ def __init__(self, pool):+ self._credential_pool = pool+ first = pool.select()+ self._credential_pool_entry_id = first.id+ self.api_key = first.runtime_api_key-def _make_agent(pool, bound_id, revert_id, rotated_to):- agent = SimpleNamespace(- _credential_pool=pool,- _credential_pool_entry_id=bound_id,- _credential_pool_revert_id=revert_id,- _credential_pool_rotated_to=rotated_to,- _provider_fallback_active=False,- model="claude-opus-4-6",- swapped=[],- )-- def _swap(entry):- agent.swapped.append(entry.id)- agent._credential_pool_entry_id = entry.id+ def _swap_credential(self, entry):+ self.api_key = entry.runtime_api_key+ self._credential_pool_entry_id = entry.idreturn True- agent._swap_credential = _swap- return agent---def test_reverts_when_preferred_available_again():- """Preferred cooled down: swap back once, clear the armed flags."""- preferred = _entry("pref-1")- pool = _FakePool([preferred])- agent = _make_agent(pool, bound_id="fb-2", revert_id="pref-1", rotated_to="fb-2")-- _maybe_revert_credential_rotation(agent)-- assert agent.swapped == ["pref-1"]- assert agent._credential_pool_entry_id == "pref-1"- assert agent._credential_pool_revert_id is None- assert agent._credential_pool_rotated_to is None---def test_waits_while_preferred_still_cooling():- """Preferred absent from available: no swap, flags stay armed."""- fallback = _entry("fb-2")- pool = _FakePool([fallback])- agent = _make_agent(pool, bound_id="fb-2", revert_id="pref-1", rotated_to="fb-2")-- _maybe_revert_credential_rotation(agent)+ def _is_entitlement_failure(self, error_context, status_code):+ return False- assert agent.swapped == []- assert agent._credential_pool_revert_id == "pref-1"- assert pool.calls == 1+def _expire_cooldowns(monkeypatch):+ real = time.time+ monkeypatch.setattr(cp.time, "time", lambda: real() + EXHAUSTED_TTL_429_SECONDS + 120)-def test_manual_move_stands_down_without_swap():- """User moved the binding elsewhere: clear flags, never yank."""- preferred = _entry("pref-1")- pool = _FakePool([preferred])- agent = _make_agent(pool, bound_id="manual-9", revert_id="pref-1", rotated_to="fb-2")-- _maybe_revert_credential_rotation(agent)-- assert agent.swapped == []- assert agent._credential_pool_revert_id is None- assert pool.calls == 0+def test_live_session_reverts_to_quota_benched_credential_once_cooldown_lifts(monkeypatch):+ pool = CredentialPool(provider="anthropic", entries=[+ _entry("pref0000", "subscription-oauth", priority=0, auth_type="oauth", token="sk-ant-oat01-PREF"),+ _entry("fall0000", "paid-api-key", priority=1, auth_type="api_key", token="sk-ant-api03-FALL"),+ ])+ agent = _LiveAgent(pool)+ assert agent.api_key == "sk-ant-oat01-PREF"-def test_already_home_clears_flag():- """Binding already back on preferred: clear, no redundant swap."""- preferred = _entry("pref-1")- pool = _FakePool([preferred])- agent = _make_agent(pool, bound_id="pref-1", revert_id="pref-1", rotated_to="fb-2")+ # 429 twice = retry once, then rotate (the real rate-limit ladder).+ recover_with_credential_pool(agent, status_code=429, has_retried_429=False, error_context={"message": "Error"})+ recovered, _ = recover_with_credential_pool(agent, status_code=429, has_retried_429=True, error_context={"message": "Error"})+ assert recovered and agent.api_key == "sk-ant-api03-FALL"- _maybe_revert_credential_rotation(agent)+ # Control: while the bench is still active the session stays on the fallback.+ assert restore_primary_runtime(agent) is False+ assert agent.api_key == "sk-ant-api03-FALL"- assert agent.swapped == []+ _expire_cooldowns(monkeypatch)+ assert restore_primary_runtime(agent) is False # credential-only: no primary-runtime restore ran+ assert agent.api_key == "sk-ant-oat01-PREF"+ assert agent._credential_pool_entry_id == "pref0000"+ assert agent._fallback_activated is False and agent.model == "claude-opus-5"assert agent._credential_pool_revert_id is None- assert pool.calls == 0+ # The pool agrees the preferred entry is healthy again (cooldown cleared, not merely elapsed).+ assert next(e for e in pool.entries() if e.id == "pref0000").last_status != cp.STATUS_EXHAUSTED+++def test_auth_bench_does_not_arm_a_revert(monkeypatch):+ """A 401 bench is not a quota window: the session keeps the credential it rotated to."""+ pool = CredentialPool(provider="anthropic", entries=[+ _entry("pref0000", "primary-key", priority=0, auth_type="api_key", token="sk-ant-api03-PREF"),+ _entry("fall0000", "backup-key", priority=1, auth_type="api_key", token="sk-ant-api03-FALL"),+ ])+ agent = _LiveAgent(pool)+ recovered, _ = recover_with_credential_pool(agent, status_code=401, has_retried_429=False, error_context={"message": "invalid"})+ assert recovered and agent.api_key == "sk-ant-api03-FALL"++ _expire_cooldowns(monkeypatch)+ assert restore_primary_runtime(agent) is False+ assert agent.api_key == "sk-ant-api03-FALL"+ assert getattr(agent, "_credential_pool_revert_id", None) is Nonediff --git a/website/docs/user-guide/features/credential-pools.md b/website/docs/user-guide/features/credential-pools.mdindex 4967040eb70..07322cf4eb9 100644--- a/website/docs/user-guide/features/credential-pools.md+++ b/website/docs/user-guide/features/credential-pools.md@@ -181,6 +181,13 @@ Provider-supplied `reset_at` timestamps override these default cooldowns.The `has_retried_429` flag resets on every successful API call, so a single transient 429 doesn't trigger rotation.+**Quota benches are temporary for the live session too.** When a 429/402 rotates a session off a+credential, that session checks at the start of each turn whether the benched credential is back in+rotation and moves back to it as soon as its cooldown lifts — the same choice a new session would make.+A long-running chat (the gateway keeps agents cached) therefore returns to a subscription seat once+its window reopens instead of billing the metered fallback for the rest of its life. A `401` bench+does not trigger this; an explicit `/model` switch cancels a pending switch-back.+**Anthropic 429s are per model.** Anthropic enforces its rate limits per model, so a generic 429 forone Claude model cools that credential down for *that model only* — the same key keeps serving everyother Claude model, and `ANTHROPIC_API_KEY` / borrowed Claude Code tokens honour the same per-model