The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): revert pool rotation after transient quota cooldown expires (#114501)
Yagna Vudathu0dd153ba2ee7
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex ac9a95bb42b..3f944c3205b 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -853,7 +853,19 @@ def recover_with_credential_pool("Credential %s (%s) — rotated to pool entry %s",rotate_status, label, getattr(next_entry, "id", "?"),)- return agent._swap_credential(next_entry) is not False+ swapped = agent._swap_credential(next_entry) is not False+ if (+ swapped+ and credential_id+ and getattr(next_entry, "id", None) != credential_id+ 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.+ 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# healthy. Do not rotate/exhaust; let fallback switch models.@@ -1108,6 +1120,50 @@ 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],+ )+ agent._credential_pool_revert_id = None+ agent._credential_pool_rotated_to = None+ except Exception:+ logger.debug("credential pool revert check failed", exc_info=True)++def restore_primary_runtime(agent) -> bool:"""Restore the primary runtime at the start of a new turn so fallback stays turn-scoped(long-lived CLI agents and the gateway's cached agents)."""@@ -1115,6 +1171,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)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)diff --git a/tests/agent/test_pool_revert_after_cooldown.py b/tests/agent/test_pool_revert_after_cooldown.pynew file mode 100644index 00000000000..e1a188482bc--- /dev/null+++ b/tests/agent/test_pool_revert_after_cooldown.py@@ -0,0 +1,106 @@+"""Regression tests for #114501 — pool rotation never reverts after cooldown.++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.+"""++from types import SimpleNamespace++import pytest++from agent.agent_runtime_helpers import _maybe_revert_credential_rotation+++def _entry(entry_id, label=None):+ return SimpleNamespace(id=entry_id, label=label or entry_id[:8])+++class _FakePool:+ """Mirrors ``_available_entries()``'s contract: (available, pending)."""++ def __init__(self, available):+ self._available = list(available)+ self.calls = 0++ def _available_entries(self, *, model=None):+ self.calls += 1+ return list(self._available), []+++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+ return 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)++ assert agent.swapped == []+ assert agent._credential_pool_revert_id == "pref-1"+ assert pool.calls == 1+++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_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")++ _maybe_revert_credential_rotation(agent)++ assert agent.swapped == []+ assert agent._credential_pool_revert_id is None+ assert pool.calls == 0