Skip to content

The agent that grows with you

fix(anthropic): model-scoped 429 cooldowns live in a pool sibling; restore path no longer NameErrors

teknium16de6e6da9926
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 118162170ad..5454570e120 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -725,8 +725,7 @@ def _init_anthropic_client(agent, api_key, base_url, _provider_timeout):
# must use their own key or Anthropic credentials leak to third-party endpoints.
# Falling back would send Anthropic credentials to third-party endpoints (Fixes #1739, #minimax-401).
_is_native_anthropic = agent.provider == "anthropic"
- resolved_model = agent.model if isinstance(getattr(agent, "model", None), str) else None
- effective_key = api_key or (resolve_anthropic_token(model=resolved_model) if _is_native_anthropic else None) or ""
+ effective_key = api_key or (resolve_anthropic_token(model=getattr(agent, "model", None)) if _is_native_anthropic else None) or ""
# MiniMax OAuth tokens live ~15 min and the SDK freezes api_key at construction, so use a
# callable provider: build_anthropic_client mints a fresh bearer per request (re-reading
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index e69d31f2a0c..e0fa31554fb 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -1042,10 +1042,8 @@ def _primary_reset_gate_blocks(agent, rt, primary_provider, primary_runtime_base
if not matches_primary(pool):
prefetched_pool = pool = load_primary_pool()
prefetched = True
- primary_model = rt.get("model")
- next_at = getattr(pool, "next_available_at", lambda **_kwargs: None)(
- model=primary_model if isinstance(primary_model, str) and primary_model else None
- )
+ primary_model = str(rt.get("model") or "").strip()
+ next_at = getattr(pool, "next_available_at", lambda **_kwargs: None)(model=primary_model or None)
if next_at is not None and next_at > time.time():
if not getattr(agent, "_restore_wait_logged", False):
agent._restore_wait_logged = True
@@ -1070,7 +1068,7 @@ def _restore_runtime_capabilities(agent, rt: Dict[str, Any]) -> None:
logger.warning("Ignoring malformed runtime capabilities snapshot")
-def _rebind_primary_credential_pool(agent, primary_provider, matches_primary, load_primary_pool, prefetched_pool, prefetched) -> None:
+def _rebind_primary_credential_pool(agent, primary_provider, primary_model, matches_primary, load_primary_pool, prefetched_pool, prefetched) -> None:
"""Rebind and re-select the primary credential pool after a fallback turn. A cross-provider
fallback attaches its own pool, which would trip the provider-mismatch guard on the next
401/429: reload the primary pool, else clear it. The snapshot api_key may be stale after
@@ -1089,9 +1087,7 @@ def _rebind_primary_credential_pool(agent, primary_provider, matches_primary, lo
)
agent._credential_pool_entry_id = None
pool = getattr(agent, "_credential_pool", None)
- primary_model = rt.get("model")
- model_kwargs = {"model": primary_model} if isinstance(primary_model, str) and primary_model else {}
- entry = pool.select(**model_kwargs) if pool is not None and pool.has_available(**model_kwargs) else None
+ entry = pool.select(model=primary_model or None) if pool is not None and pool.has_available(model=primary_model or None) else None
if entry is None or not (getattr(entry, "runtime_api_key", None) or getattr(entry, "access_token", "")):
return
if matches_primary(entry):
@@ -1178,7 +1174,7 @@ def restore_primary_runtime(agent) -> bool:
provider=rt["compressor_provider"], api_mode=rt.get("compressor_api_mode", ""),
)
_rebind_primary_credential_pool(
- agent, primary_provider, _matches_primary, _load_primary_pool, prefetched_pool, prefetched
+ agent, primary_provider, primary_model, _matches_primary, _load_primary_pool, prefetched_pool, prefetched
)
# Older snapshots have no reasoning_config; keep the current value.
saved_reasoning = rt.get("reasoning_config")
@@ -1918,9 +1914,8 @@ def _build_switched_client(agent, new_provider, api_key, base_url, api_mode, new
# Only fall back to ANTHROPIC_TOKEN for native Anthropic; other anthropic_messages providers
# must never receive Anthropic credentials.
is_native_anthropic = new_provider == "anthropic"
- resolved_model = getattr(agent, "model", None)
effective_key = api_key or agent.api_key or (
- resolve_anthropic_token(model=resolved_model) if is_native_anthropic else ""
+ resolve_anthropic_token(model=getattr(agent, "model", None)) if is_native_anthropic else ""
) or ""
# MiniMax OAuth: per-request callable token provider survives 15-min expiry (rationale in
# agent_init.py).
diff --git a/agent/anthropic_credentials.py b/agent/anthropic_credentials.py
index 51969505264..8b579114b55 100644
--- a/agent/anthropic_credentials.py
+++ b/agent/anthropic_credentials.py
@@ -443,9 +443,13 @@ def _resolve_anthropic_pool_token(*, skip_borrowed: bool = False) -> Optional[st
def _available_anthropic_token(token: Optional[str], model: Optional[str]) -> Optional[str]:
- """Return a token unless the pool records an active cooldown for it."""
- if not token:
- return None
+ """Return *token* unless the pool holds an active cooldown for it on *model*.
+
+ Only model-aware callers (the API-call paths) are gated: diagnostics that
+ resolve a token without a model (usage display, model discovery) keep it.
+ """
+ if not token or not model:
+ return token or None
try:
from agent.credential_pool import load_pool
if load_pool("anthropic").token_is_blocked(token, model=model):
@@ -458,7 +462,10 @@ def _available_anthropic_token(token: Optional[str], model: Optional[str]) -> Op
def resolve_anthropic_token(*, model: Optional[str] = None) -> Optional[str]:
- """Resolve an Anthropic token from all sources in priority order (see module docstring)."""
+ """Resolve an Anthropic token from all sources in priority order (see module docstring).
+
+ With *model*, a token the credential pool has benched for that model resolves to ``None``
+ instead of being handed straight back to the caller that just saw it rate-limited."""
_read_creds = functools.cache(read_claude_code_credentials) # read the file at most once per resolve
token = _first_env("ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN")
if token:
diff --git a/agent/client_lifecycle.py b/agent/client_lifecycle.py
index 39592b7428a..8d1b76337f4 100644
--- a/agent/client_lifecycle.py
+++ b/agent/client_lifecycle.py
@@ -79,8 +79,7 @@ def _swap_fallback_clients(agent, fb_client, fb_provider: str, fb_model: str, fb
from agent.anthropic_adapter import build_anthropic_client
from agent.anthropic_credentials import resolve_anthropic_token, _is_oauth_token
is_anthropic = fb_provider == "anthropic"
- resolved_model = agent.model if isinstance(getattr(agent, "model", None), str) else None
- effective_key = credential or (resolve_anthropic_token(model=resolved_model) if is_anthropic else None) or ""
+ effective_key = credential or (resolve_anthropic_token(model=getattr(agent, "model", None)) if is_anthropic else None) or ""
agent.api_key = agent._anthropic_api_key = effective_key
agent._anthropic_base_url = fb_base_url
agent._anthropic_client = build_anthropic_client(effective_key, fb_base_url, timeout=timeout)
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 2cb956e6ff8..424cb773ffd 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from agent.credential_pool_admin import CredentialPoolAdminMixin
+from agent.credential_pool_model_cooldowns import CredentialPoolModelCooldownMixin, model_cooldown_until
import logging
import os
@@ -717,7 +718,7 @@ class _RefreshDone(Exception):
self.result = result
-class CredentialPool(CredentialPoolAdminMixin):
+class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin):
def __init__(self, provider: str, entries: List[PooledCredential]):
self.provider = provider
self._entries = sorted(entries, key=lambda entry: entry.priority)
@@ -783,13 +784,12 @@ class CredentialPool(CredentialPoolAdminMixin):
)
if until is not None
]
- now = time.time()
candidates.extend(
until
for entry in self._entries
if entry.last_status != STATUS_DEAD
- for until in (self._model_cooldown_until(entry, model),)
- if until is not None and until > now
+ for until in (model_cooldown_until(entry, model),)
+ if until is not None
)
return min(candidates) if candidates else None
@@ -801,18 +801,6 @@ class CredentialPool(CredentialPoolAdminMixin):
"""DEAD entries never re-enter rotation, so <=1 non-DEAD entry means nothing to rotate to."""
return sum(1 for e in self._entries if e.last_status != STATUS_DEAD) <= 1
- @staticmethod
- def _model_cooldown_until(entry: PooledCredential, model: Optional[str]) -> Optional[float]:
- """Return the active model cooldown relevant to this selection.
-
- Callers without a model remain conservative: a known model cooldown
- prevents them from reusing the credential through an unscoped route.
- """
- cooldowns = entry.model_cooldowns or {}
- values = cooldowns.values() if not model else (cooldowns.get(model),)
- active = [float(until) for until in values if isinstance(until, (int, float)) and until > time.time()]
- return max(active) if active else None
-
def _find(self, predicate: Callable[[PooledCredential], bool]) -> Optional[PooledCredential]:
return next((e for e in self._entries if predicate(e)), None)
@@ -840,20 +828,6 @@ class CredentialPool(CredentialPoolAdminMixin):
matches = [e for e in self._entries if e.runtime_api_key == api_key_hint]
return matches[0].id if len(matches) == 1 else None
- def token_is_blocked(self, token: str, *, model: Optional[str] = None) -> bool:
- """Whether a known cooldown blocks *token* for this model.
-
- This closes paths that resolve a native Anthropic token directly rather
- than selecting it from the pool. Unknown tokens fail open because no
- pool row can safely attribute their cooldown.
- """
- with self._lock:
- return any(
- entry.runtime_api_key == token
- and self._model_cooldown_until(entry, model) is not None
- for entry in self._entries
- )
-
# ---- mutation primitives (self-locking) --------------------------------
def _replace_entry(self, old: PooledCredential, new: PooledCredential) -> None:
@@ -1683,7 +1657,7 @@ class CredentialPool(CredentialPoolAdminMixin):
entries_to_prune.append(entry.id) # can't mutate while iterating
cleared_any = True
continue
- if self._model_cooldown_until(entry, model) is not None:
+ if model_cooldown_until(entry, model) is not None:
continue
if entry.last_status == STATUS_EXHAUSTED:
exhausted_until = _exhausted_until(entry, sole_credential=sole_credential)
@@ -1868,28 +1842,11 @@ class CredentialPool(CredentialPoolAdminMixin):
if entry is None:
return None
_label = entry.label or entry.id[:8]
- # Anthropic's generic 429 does not establish account-wide quota
- # exhaustion. Record it against the requested model only; explicit
- # account scope, billing, auth, and payment failures remain global.
- if (
- self.provider == "anthropic" and status_code == 429 and model
- and failure_reason != FAILURE_REASON_BILLING
- and (error_context or {}).get("quota_scope") != "account"
- ):
- normalized = _normalize_error_context(error_context)
- until = normalized.get("reset_at") or time.time() + EXHAUSTED_TTL_429_SECONDS
- failed_key = entry.runtime_api_key
- scoped_entries = [entry]
- if failed_key:
- scoped_entries.extend(
- sibling for sibling in self._entries
- if sibling.id != entry.id and sibling.runtime_api_key == failed_key
- )
- for scoped in scoped_entries:
- cooldowns = dict(scoped.model_cooldowns or {})
- cooldowns[model] = max(float(until), float(cooldowns.get(model, 0) or 0))
- self._adopt(scoped, persist=False, model_cooldowns=cooldowns)
- self._persist()
+ if self._is_model_scoped_rate_limit(status_code, model, failure_reason):
+ # A generic Anthropic 429 is a per-model rate limit: bench this
+ # model only, the credential stays available for its siblings.
+ self._cool_down_model(entry, model, error_context)
+ logger.info("credential pool: %s rate-limited for model %s; other models stay available", _label, model)
self._current_id = None
next_entry, _pending = self._select_unlocked(refresh=False, model=model)
return next_entry
diff --git a/agent/credential_pool_model_cooldowns.py b/agent/credential_pool_model_cooldowns.py
new file mode 100644
index 00000000000..89439d6a3a2
--- /dev/null
+++ b/agent/credential_pool_model_cooldowns.py
@@ -0,0 +1,88 @@
+"""Model-scoped rate-limit cooldowns for pooled credentials.
+
+Anthropic enforces its API rate limits (requests / tokens per minute) per
+model, so a generic 429 for one Claude model says nothing about the same
+credential's standing for its sibling models. Such a 429 is recorded as a
+cooldown on the requested model only, beside the credential-wide status that
+auth, billing and payment failures keep benching the whole credential with.
+"""
+from __future__ import annotations
+
+import time
+from typing import Any, Dict, Optional, TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from agent.credential_pool import PooledCredential
+
+
+def model_cooldown_until(entry: "PooledCredential", model: Optional[str]) -> Optional[float]:
+ """Active cooldown blocking *entry* for *model*, or ``None``.
+
+ Callers that do not know the model stay conservative: any active model
+ cooldown blocks them, so an unscoped route cannot reuse the credential.
+ """
+ cooldowns = entry.model_cooldowns or {}
+ values = cooldowns.values() if not model else (cooldowns.get(model),)
+ now = time.time()
+ active = [float(until) for until in values if isinstance(until, (int, float)) and until > now]
+ return max(active) if active else None
+
+
+def merge_model_cooldowns(*maps: Any) -> Dict[str, float]:
+ """Latest reset per model across snapshots — each writer only observed its own model."""
+ merged: Dict[str, float] = {}
+ for cooldowns in maps:
+ if not isinstance(cooldowns, dict):
+ continue
+ for model, until in cooldowns.items():
+ if isinstance(until, (int, float)):
+ merged[model] = max(float(until), merged.get(model, 0.0))
+ return merged
+
+
+class CredentialPoolModelCooldownMixin:
+ def token_is_blocked(self, token: str, *, model: Optional[str] = None) -> bool:
+ """Whether a pool cooldown blocks *token* for *model*.
+
+ Closes the paths that hand out a native Anthropic token without
+ selecting it from the pool (env / borrowed credentials). Tokens the
+ pool does not know fail open: no row can attribute a cooldown to them.
+ """
+ with self._lock:
+ return any(
+ entry.runtime_api_key == token and model_cooldown_until(entry, model) is not None
+ for entry in self._entries
+ )
+
+ def _is_model_scoped_rate_limit(
+ self, status_code: Optional[int], model: Optional[str], failure_reason: Optional[str],
+ ) -> bool:
+ from agent.credential_pool import FAILURE_REASON_BILLING, FAILURE_REASON_BILLING_UNVERIFIED
+
+ return (
+ self.provider == "anthropic" and status_code == 429 and bool(model)
+ and failure_reason not in (FAILURE_REASON_BILLING, FAILURE_REASON_BILLING_UNVERIFIED)
+ )
+
+ def _cool_down_model(
+ self, entry: "PooledCredential", model: str, error_context: Optional[Dict[str, Any]],
+ ) -> None:
+ """Record a cooldown for *model* on *entry* and every sibling sharing its key.
+
+ Same TTL policy as a credential-wide 429 (provider ``reset_at`` wins, a
+ sole credential keeps its short bench). Siblings matter because a
+ ``model_config`` twin seeded from the same key would otherwise be
+ re-selected for the very model that just failed. Caller holds the lock.
+ """
+ from agent.credential_pool import _exhausted_ttl, _normalize_error_context
+
+ until = _normalize_error_context(error_context).get("reset_at") or (
+ time.time() + _exhausted_ttl(429, sole_credential=self._is_sole_credential())
+ )
+ failed_key = entry.runtime_api_key
+ for scoped in list(self._entries):
+ if scoped.id != entry.id and not (failed_key and scoped.runtime_api_key == failed_key):
+ continue
+ cooldowns = merge_model_cooldowns(scoped.model_cooldowns, {model: until})
+ self._adopt(scoped, persist=False, model_cooldowns=cooldowns)
+ self._persist()
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.py
index e0c11e1f9d7..a2491062f21 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -796,17 +796,10 @@ def _merge_disk_cooldown_state(
PooledCredential, STATUS_DEAD, STATUS_EXHAUSTED, _exhausted_until, _parse_absolute_timestamp,
)
- # Model cooldowns are independent observations. Merge their latest
- # reset for every model so a writer that just cooled Sonnet cannot
- # erase another process's Haiku cooldown.
- memory_cooldowns = entry.get("model_cooldowns")
- disk_cooldowns = disk_entry.get("model_cooldowns")
- merged_cooldowns = dict(disk_cooldowns) if isinstance(disk_cooldowns, dict) else {}
- if isinstance(memory_cooldowns, dict):
- for model, until in memory_cooldowns.items():
- if isinstance(until, (int, float)):
- previous = merged_cooldowns.get(model)
- merged_cooldowns[model] = max(float(until), float(previous or 0))
+ # Model cooldowns are independent observations: keep the latest reset per model so a
+ # writer that just cooled one model cannot erase another process's cooldown for another.
+ from agent.credential_pool_model_cooldowns import merge_model_cooldowns
+ merged_cooldowns = merge_model_cooldowns(disk_entry.get("model_cooldowns"), entry.get("model_cooldowns"))
merged = {**entry, "model_cooldowns": merged_cooldowns} if merged_cooldowns else entry
disk_status = disk_entry.get("last_status")
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index 687c228aac0..0659b061e77 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -286,8 +286,13 @@ def _anthropic_cfg_base_url(model_cfg: Dict[str, Any]) -> str:
def _anthropic_token_or_raise(*, model: str | None = None) -> str:
from agent.anthropic_credentials import resolve_anthropic_token
- token = resolve_anthropic_token(model=model) if model else resolve_anthropic_token()
+ token = resolve_anthropic_token(model=model)
if not token:
+ # A key the pool benched for *this* model is not a missing credential; telling the
+ # user to re-authenticate would send them chasing a cooldown that lifts on its own.
+ if model and resolve_anthropic_token():
+ raise AuthError(f"Anthropic credentials are rate-limited for {model}; "
+ "other Claude models remain available (see `hermes auth list`).")
raise AuthError(_NO_ANTHROPIC_CREDENTIALS_MSG)
return token
@@ -538,7 +543,7 @@ def _resolve_from_pool(provider: str, requested_provider: str, model_cfg: Dict[s
pool = None
if not (pool and pool.has_credentials()):
return None
- entry = pool.select(model=target_model) if provider == "anthropic" and target_model else pool.select()
+ entry = pool.select(model=target_model or None)
if entry is None:
return None
pool_api_key = _pool_entry_api_key(entry)
diff --git a/tests/agent/test_anthropic_model_cooldowns.py b/tests/agent/test_anthropic_model_cooldowns.py
index ecb9e12f3f6..959e41125d3 100644
--- a/tests/agent/test_anthropic_model_cooldowns.py
+++ b/tests/agent/test_anthropic_model_cooldowns.py
@@ -1,73 +1,70 @@
-"""Regression coverage for Anthropic model-scoped 429 cooldowns (#111769)."""
-
-from agent.credential_pool import CredentialPool, PooledCredential, STATUS_EXHAUSTED
-
-
-def _pool():
- return CredentialPool(
- "anthropic",
- [
- PooledCredential(
- provider="anthropic", id="credential", label="credential",
- auth_type="api_key", priority=0, source="manual", access_token="key",
- )
- ],
- )
-
-
-def test_anthropic_429_only_cools_the_failed_model(monkeypatch):
- pool = _pool()
- monkeypatch.setattr("agent.credential_pool.time.time", lambda: 1_000.0)
+"""A generic Anthropic 429 benches only the model that was rate-limited (#111769, #61451).
+
+Real ``agent.credential_pool`` against a real temp auth store: one API-key credential,
+one ``mark_exhausted_and_rotate(status_code=429, model=A)``.
+"""
+import json
+
+import pytest
+
+KEY = "sk-ant-api03-synthetic-test-key-0000"
+MODEL_A = "claude-sonnet-4-5"
+MODEL_B = "claude-haiku-4-5"
+
+
+def pool(tmp_path, monkeypatch):
+ root = tmp_path / "hermes-root"
+ root.mkdir()
+ (tmp_path / "fakehome").mkdir()
+ monkeypatch.setenv("HOME", str(tmp_path / "fakehome"))
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / "fakehome"))
+ for var in ("ANTHROPIC_TOKEN", "ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ import hermes_constants
+ hermes_constants._default_hermes_root_memo = None # type: ignore[attr-defined]
+ (root / "auth.json").write_text(json.dumps({"credential_pool": {"anthropic": [{
+ "id": "seat", "label": "seat", "auth_type": "api_key", "priority": 0,
+ "source": "manual", "access_token": KEY,
+ }]}}))
+ from agent.credential_pool import load_pool
+ return load_pool("anthropic")
+
+
+def test_generic_429_benches_only_the_rate_limited_model(pool, monkeypatch):
+ from agent.anthropic_credentials import resolve_anthropic_token
+ from agent.credential_pool import load_pool
+
+ ctx = {"message": "This request would exceed your account's rate limit. Please try again later."}
+ assert pool.mark_exhausted_and_rotate(
+ status_code=429, error_context=ctx, api_key_hint=KEY, failure_reason="rate_limit", model=MODEL_A,
+ ) is None # a sole credential has nothing to rotate to for model A
+
+ assert pool.entries()[0].last_status is None # credential-wide state untouched
+ assert pool.select(model=MODEL_A) is None
+ assert pool.select(model=MODEL_B) is not None
+ assert pool.select() is None # a caller that names no model honours every active cooldown
+ assert pool.next_available_at(model=MODEL_A) is not None
+ assert pool.next_available_at(model=MODEL_B) is None
+
+ # The cooldown is persisted, so another process (and the env/borrowed token resolver,
+ # which reads the store fresh) sees the same per-model verdict.
+ fresh = load_pool("anthropic")
+ assert fresh.select(model=MODEL_A) is None and fresh.select(model=MODEL_B) is not None
+ monkeypatch.setenv("ANTHROPIC_API_KEY", KEY)
+ assert resolve_anthropic_token(model=MODEL_A) is None
+ assert resolve_anthropic_token(model=MODEL_B) == KEY
+ assert resolve_anthropic_token() == KEY # model-less diagnostics keep the key
+
+
[email protected]("status_code, failure_reason", [(401, None), (402, "billing"), (429, "billing")])
+def test_auth_and_billing_failures_stay_credential_wide(pool, status_code, failure_reason):
+ from agent.credential_pool import STATUS_EXHAUSTED
pool.mark_exhausted_and_rotate(
- status_code=429, api_key_hint="key", model="claude-sonnet-4",
+ status_code=status_code, api_key_hint=KEY, failure_reason=failure_reason, model=MODEL_A,
)
-
- entry = pool.entries()[0]
- assert entry.last_status is None
- assert pool.select(model="claude-haiku-4").id == entry.id
- assert pool.select(model="claude-sonnet-4") is None
- assert pool.next_available_at(model="claude-sonnet-4") == 4_600.0
-
-
-def test_anthropic_model_cooldown_expiry_restores_selection(monkeypatch):
- pool = _pool()
- now = [1_000.0]
- monkeypatch.setattr("agent.credential_pool.time.time", lambda: now[0])
- pool.mark_exhausted_and_rotate(status_code=429, api_key_hint="key", model="claude-sonnet-4")
-
- now[0] = 4_601.0
- assert pool.select(model="claude-sonnet-4") is pool.entries()[0]
-
-
-def test_reset_status_clears_anthropic_model_cooldown(monkeypatch):
- pool = _pool()
- monkeypatch.setattr("agent.credential_pool.time.time", lambda: 1_000.0)
- pool.mark_exhausted_and_rotate(status_code=429, api_key_hint="key", model="claude-sonnet-4")
-
- pool.reset_status("credential")
-
- assert pool.select(model="claude-sonnet-4") is not None
-
-
-def test_persisted_model_cooldowns_merge_by_model():
- from hermes_cli.auth import _merge_disk_cooldown_state
-
- merged = _merge_disk_cooldown_state(
- {"access_token": "key", "model_cooldowns": {"claude-haiku-4": 2_000.0}},
- {"access_token": "key", "model_cooldowns": {"claude-sonnet-4": 3_000.0}},
- "anthropic",
- )
-
- assert merged["model_cooldowns"] == {"claude-haiku-4": 2_000.0, "claude-sonnet-4": 3_000.0}
-
-
-def test_anthropic_401_and_billing_402_remain_credential_wide():
- for status_code, failure_reason in ((401, None), (402, "billing")):
- pool = _pool()
- pool.mark_exhausted_and_rotate(
- status_code=status_code, api_key_hint="key", model="claude-sonnet-4",
- failure_reason=failure_reason,
- )
- assert pool.entries()[0].last_status == STATUS_EXHAUSTED
- assert pool.select(model="claude-haiku-4") is None
+ assert pool.entries()[0].last_status == STATUS_EXHAUSTED
+ assert not pool.entries()[0].model_cooldowns
+ assert pool.select(model=MODEL_B) is None
diff --git a/tests/agent/test_codex_xai_oauth_recovery.py b/tests/agent/test_codex_xai_oauth_recovery.py
index ecbe658eebc..d4af5e675d4 100644
--- a/tests/agent/test_codex_xai_oauth_recovery.py
+++ b/tests/agent/test_codex_xai_oauth_recovery.py
@@ -403,7 +403,7 @@ def test_recover_with_credential_pool_skips_refresh_on_entitlement_403():
def mark_exhausted_and_rotate(self, **_kwargs):
return None
- def has_available(self):
+ def has_available(self, **_kwargs):
return False
agent._credential_pool = _FakePool()
@@ -457,6 +457,7 @@ def test_recover_with_credential_pool_rotates_on_xai_spending_limit_403():
error_context=None,
api_key_hint=None,
failure_reason=None,
+ model=None,
):
assert status_code == 403
assert api_key_hint == "test-key"
diff --git a/tests/agent/test_credential_pool_provider_boundary.py b/tests/agent/test_credential_pool_provider_boundary.py
index 1a5f5cfd31b..5e05a96543c 100644
--- a/tests/agent/test_credential_pool_provider_boundary.py
+++ b/tests/agent/test_credential_pool_provider_boundary.py
@@ -208,7 +208,7 @@ def test_runtime_ignores_pool_loaded_for_different_provider(monkeypatch):
pool = SimpleNamespace(
provider="openai-codex",
has_credentials=lambda: True,
- select=lambda: entry,
+ select=lambda **_kwargs: entry,
)
monkeypatch.setattr(rp, "load_pool", lambda _provider: pool)
monkeypatch.setattr(rp, "resolve_provider", lambda *_a, **_kw: "deepseek")
diff --git a/tests/agent/test_primary_runtime_restore.py b/tests/agent/test_primary_runtime_restore.py
index 0ea4b946f18..e66d186bcf1 100644
--- a/tests/agent/test_primary_runtime_restore.py
+++ b/tests/agent/test_primary_runtime_restore.py
@@ -321,10 +321,10 @@ class TestRestorePrimaryRuntime:
class _Pool:
provider = "openrouter"
- def has_available(self):
+ def has_available(self, **_kwargs):
return True
- def select(self):
+ def select(self, **_kwargs):
return _Entry()
agent = _make_agent(
@@ -369,10 +369,10 @@ class TestRestorePrimaryRuntime:
class _DeepseekPool:
provider = "deepseek"
- def has_available(self):
+ def has_available(self, **_kwargs):
return True
- def select(self):
+ def select(self, **_kwargs):
return _DeepseekEntry()
agent = _make_agent(
@@ -448,10 +448,10 @@ class TestRestorePrimaryRuntime:
class _Pool:
provider = "custom:myllm"
- def has_available(self):
+ def has_available(self, **_kwargs):
return True
- def select(self):
+ def select(self, **_kwargs):
return _Entry()
agent = _make_agent(provider="custom", base_url="https://my-llm.example.com/v1")
diff --git a/tests/agent/test_reset_aware_primary_restore.py b/tests/agent/test_reset_aware_primary_restore.py
index 6d7599fea12..5124f0f9c1c 100644
--- a/tests/agent/test_reset_aware_primary_restore.py
+++ b/tests/agent/test_reset_aware_primary_restore.py
@@ -64,7 +64,7 @@ class _FakePool:
self._raise = raise_on_next
self.next_available_calls = 0
- def next_available_at(self):
+ def next_available_at(self, **_kwargs):
self.next_available_calls += 1
if self._raise:
raise RuntimeError("boom")
@@ -73,10 +73,10 @@ class _FakePool:
def has_credentials(self):
return True
- def has_available(self):
+ def has_available(self, **_kwargs):
return self._available
- def select(self):
+ def select(self, **_kwargs):
return None
diff --git a/tests/hermes_cli/test_anthropic_oauth_routes_to_messages_api.py b/tests/hermes_cli/test_anthropic_oauth_routes_to_messages_api.py
index da08a873f2e..b68aef02e9c 100644
--- a/tests/hermes_cli/test_anthropic_oauth_routes_to_messages_api.py
+++ b/tests/hermes_cli/test_anthropic_oauth_routes_to_messages_api.py
@@ -143,7 +143,7 @@ class TestCustomProviderUrlFallback:
def has_credentials(self):
return True
- def select(self):
+ def select(self, **_kwargs):
return _Entry()
monkeypatch.setattr(rp, "custom_provider_pool_key_candidates", lambda *a, **k: ["custom:my-claude"])
diff --git a/tests/hermes_cli/test_authenticated_providers_exhausted_pool.py b/tests/hermes_cli/test_authenticated_providers_exhausted_pool.py
index d9f7079ddde..497703dde7e 100644
--- a/tests/hermes_cli/test_authenticated_providers_exhausted_pool.py
+++ b/tests/hermes_cli/test_authenticated_providers_exhausted_pool.py
@@ -19,7 +19,7 @@ class _FakePool:
# The pool still holds entries...
return True
- def has_available(self) -> bool:
+ def has_available(self, **_kwargs) -> bool:
# ...but none of them are usable when exhausted/dead.
return self._available
diff --git a/tests/hermes_cli/test_runtime_provider_resolution.py b/tests/hermes_cli/test_runtime_provider_resolution.py
index 1315cfb6f25..d09c6b280c4 100644
--- a/tests/hermes_cli/test_runtime_provider_resolution.py
+++ b/tests/hermes_cli/test_runtime_provider_resolution.py
@@ -72,7 +72,7 @@ def test_resolve_runtime_provider_uses_credential_pool(monkeypatch):
def has_credentials(self):
return True
- def select(self):
+ def select(self, **_kwargs):
return _Entry()
monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "openai-codex")
@@ -97,7 +97,7 @@ def test_codex_pool_honors_hermes_codex_base_url(monkeypatch):
def has_credentials(self):
return True
- def select(self):
+ def select(self, **_kwargs):
return _Entry()
monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "openai-codex")
@@ -129,7 +129,7 @@ class TestCustomProviderPoolLoopbackNoKeyExemption:
def has_credentials(self):
return True
- def select(self):
+ def select(self, **_kwargs):
return entry
return _Pool()
@@ -443,7 +443,7 @@ def test_resolve_runtime_provider_auto_uses_openrouter_pool(monkeypatch):
def has_credentials(self):
return True
- def select(self):
+ def select(self, **_kwargs):
return _Entry()
monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "openrouter")
@@ -473,7 +473,7 @@ def test_resolve_runtime_provider_openrouter_explicit_api_key_skips_pool(monkeyp
def has_credentials(self):
return True
- def select(self):
+ def select(self, **_kwargs):
return _Entry()
monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "openrouter")
@@ -988,7 +988,7 @@ def test_explicit_openrouter_config_mirror_bypasses_pool(monkeypatch):
def has_credentials(self):
return True
- def select(self):
+ def select(self, **_kwargs):
return _Entry()
monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "openrouter")
@@ -1370,7 +1370,7 @@ class TestAzureAnthropicEnvVarHint:
})
monkeypatch.setattr(rp, "load_pool", lambda provider: None)
called = {"resolve_anthropic_token": False}
- def _fake_resolve():
+ def _fake_resolve(**_kwargs):
called["resolve_anthropic_token"] = True
return "token-from-resolver"
monkeypatch.setattr(
@@ -1489,7 +1489,7 @@ def test_minimax_oauth_pool_forces_anthropic_messages_despite_stale_config(monke
def has_credentials(self):
return True
- def select(self):
+ def select(self, **_kwargs):
return _Entry()
monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "minimax-oauth")
@@ -1851,7 +1851,7 @@ def test_resolve_runtime_provider_opencode_free_keyless_despite_exhausted_pool(m
def has_credentials(self):
return True
- def select(self):
+ def select(self, **_kwargs):
return None
monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "opencode-free")
diff --git a/website/docs/user-guide/features/credential-pools.md b/website/docs/user-guide/features/credential-pools.md
index f44a42572f7..f8999acc0b0 100644
--- a/website/docs/user-guide/features/credential-pools.md
+++ b/website/docs/user-guide/features/credential-pools.md
@@ -178,6 +178,11 @@ 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.
+**Anthropic 429s are per model.** Anthropic enforces its rate limits per model, so a generic 429 for
+one Claude model cools that credential down for *that model only* — the same key keeps serving every
+other Claude model, and `ANTHROPIC_API_KEY` / borrowed Claude Code tokens honour the same per-model
+cooldown. Billing (`402`, usage-limit) and auth (`401`) failures still bench the whole credential.
+
## Custom Endpoint Pools
Custom OpenAI-compatible endpoints (Together.ai, RunPod, local servers) get their own pools, keyed by the endpoint name from the `providers:` dict in config.yaml (or the legacy `custom_providers` list, which is auto-migrated).
@@ -255,7 +260,7 @@ For the full data flow diagram, see [`docs/credential-pool-flow.excalidraw`](htt
The credential pool integrates at the provider resolution layer:
-1. **`agent/credential_pool.py`** — Pool manager: storage, selection, rotation, cooldowns; **`agent/credential_pool_admin.py`** owns locked target resolution, reset, add, removal, and priority mutations
+1. **`agent/credential_pool.py`** — Pool manager: storage, selection, rotation, cooldowns; **`agent/credential_pool_admin.py`** owns locked target resolution, reset, add, removal, and priority mutations; **`agent/credential_pool_model_cooldowns.py`** owns the per-model Anthropic 429 cooldowns
2. **`hermes_cli/auth_commands.py`** — CLI commands and interactive wizard
3. **`hermes_cli/runtime_provider.py`** — Pool-aware credential resolution
4. **`agent/turn_api_error.py`** — Error recovery: 429/402/401 → pool rotation → fallback