Skip to content

The agent that grows with you

fix(agent): scope Anthropic 429 cooldowns to model

KoNit-Kfb358d437925
diff --git a/agent/agent_init.py b/agent/agent_init.py
index f59f6de6ee3..118162170ad 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -725,7 +725,8 @@ 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"
- effective_key = api_key or (resolve_anthropic_token() if _is_native_anthropic else None) or ""
+ 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 ""
# 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 f1c88d9ef1c..e69d31f2a0c 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -843,6 +843,9 @@ def recover_with_credential_pool(
from agent.credential_pool import FAILURE_REASON_BILLING_UNVERIFIED
failure_reason = FAILURE_REASON_BILLING_UNVERIFIED
kwargs["failure_reason"] = failure_reason
+ model = getattr(agent, "model", None)
+ if isinstance(model, str) and model.strip():
+ kwargs["model"] = model
next_entry = pool.mark_exhausted_and_rotate(**kwargs)
if next_entry is None:
return False
@@ -1039,7 +1042,10 @@ 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
- next_at = getattr(pool, "next_available_at", lambda: None)()
+ 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
+ )
if next_at is not None and next_at > time.time():
if not getattr(agent, "_restore_wait_logged", False):
agent._restore_wait_logged = True
@@ -1083,7 +1089,9 @@ def _rebind_primary_credential_pool(agent, primary_provider, matches_primary, lo
)
agent._credential_pool_entry_id = None
pool = getattr(agent, "_credential_pool", None)
- entry = pool.select() if pool is not None and pool.has_available() else 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
if entry is None or not (getattr(entry, "runtime_api_key", None) or getattr(entry, "access_token", "")):
return
if matches_primary(entry):
@@ -1910,7 +1918,10 @@ 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"
- effective_key = api_key or agent.api_key or (resolve_anthropic_token() if is_native_anthropic else "") or ""
+ 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 ""
+ ) or ""
# MiniMax OAuth: per-request callable token provider survives 15-min expiry (rationale in
# agent_init.py).
if new_provider == "minimax-oauth" and isinstance(effective_key, str) and effective_key:
diff --git a/agent/anthropic_credentials.py b/agent/anthropic_credentials.py
index f1707d73dd1..51969505264 100644
--- a/agent/anthropic_credentials.py
+++ b/agent/anthropic_credentials.py
@@ -442,17 +442,37 @@ def _resolve_anthropic_pool_token(*, skip_borrowed: bool = False) -> Optional[st
return None
-def resolve_anthropic_token() -> Optional[str]:
+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
+ try:
+ from agent.credential_pool import load_pool
+ if load_pool("anthropic").token_is_blocked(token, model=model):
+ return None
+ except Exception:
+ # Credential discovery must remain available when the pool store is
+ # unavailable or malformed.
+ logger.debug("Failed to check Anthropic model cooldown", exc_info=True)
+ return token
+
+
+def resolve_anthropic_token(*, model: Optional[str] = None) -> Optional[str]:
"""Resolve an Anthropic token from all sources in priority order (see module docstring)."""
_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:
- return _prefer_refreshable_claude_code_token(token, _read_creds()) or token
+ return _available_anthropic_token(
+ _prefer_refreshable_claude_code_token(token, _read_creds()) or token, model,
+ )
api_key = _first_env("ANTHROPIC_API_KEY") # an explicit API key must not be shadowed by discovered OAuth creds
if api_key:
- return api_key
+ return _available_anthropic_token(api_key, model)
# The pool's claude_code row mirrors the same externally owned refresh grant.
- return _resolve_anthropic_pool_token(skip_borrowed=True) or _resolve_claude_code_token_from_credentials(_read_creds())
+ return _available_anthropic_token(
+ _resolve_anthropic_pool_token(skip_borrowed=True) or _resolve_claude_code_token_from_credentials(_read_creds()),
+ model,
+ )
def run_oauth_setup_token() -> Optional[str]:
diff --git a/agent/client_lifecycle.py b/agent/client_lifecycle.py
index 9f2202c37fa..39592b7428a 100644
--- a/agent/client_lifecycle.py
+++ b/agent/client_lifecycle.py
@@ -79,7 +79,8 @@ 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"
- effective_key = credential or (resolve_anthropic_token() if is_anthropic else None) or ""
+ 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 ""
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)
@@ -869,7 +870,7 @@ class ClientLifecycleMixin:
return False
try:
from agent.anthropic_credentials import resolve_anthropic_token
- new_token = resolve_anthropic_token()
+ new_token = resolve_anthropic_token(model=self.model)
except Exception as exc:
logger.debug("Anthropic credential refresh failed: %s", exc)
return False
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 790b9c62ae4..2cb956e6ff8 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -224,6 +224,10 @@ class PooledCredential:
agent_key: Optional[str] = None
agent_key_expires_at: Optional[str] = None
request_count: int = 0
+ # A provider may rate-limit one model while the same credential remains
+ # usable for its sibling models. Keep that observation separate from the
+ # credential-wide status used for auth and billing failures.
+ model_cooldowns: Optional[Dict[str, float]] = None
extra: Dict[str, Any] = None # type: ignore[assignment]
def __post_init__(self):
@@ -743,7 +747,7 @@ class CredentialPool(CredentialPoolAdminMixin):
with self._lock:
return bool(self._entries)
- def has_available(self) -> bool:
+ def has_available(self, *, model: Optional[str] = None) -> bool:
"""True if at least one entry is not currently in exhaustion cooldown.
``_available_entries`` is not read-only (it prunes aged-out DEAD
@@ -751,10 +755,10 @@ class CredentialPool(CredentialPoolAdminMixin):
like every other caller or a probe can race a concurrent rotation.
"""
with self._lock:
- available, _pending = self._available_entries()
+ available, _pending = self._available_entries(model=model)
return bool(available)
- def next_available_at(self) -> Optional[float]:
+ def next_available_at(self, *, model: Optional[str] = None) -> Optional[float]:
"""Earliest epoch time (seconds) any entry re-enters rotation.
``None`` when an entry is available now, or when no exhausted entry
@@ -763,7 +767,7 @@ class CredentialPool(CredentialPoolAdminMixin):
Runs under ``self._lock`` for the same reason as ``has_available``.
"""
with self._lock:
- available, _pending = self._available_entries()
+ available, _pending = self._available_entries(model=model)
if available:
return None
# Mirror _available_entries: a sole credential's transient throttle
@@ -779,6 +783,14 @@ 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
+ )
return min(candidates) if candidates else None
def entries(self) -> List[PooledCredential]:
@@ -789,6 +801,18 @@ 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)
@@ -816,6 +840,20 @@ 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:
@@ -1558,20 +1596,20 @@ class CredentialPool(CredentialPoolAdminMixin):
# ---- selection ---------------------------------------------------------
- def select(self) -> Optional[PooledCredential]:
- entry, pending_refresh = self._select_under_lock()
+ def select(self, *, model: Optional[str] = None) -> Optional[PooledCredential]:
+ entry, pending_refresh = self._select_under_lock(model=model)
if pending_refresh:
self._refresh_pending_entries(pending_refresh)
# Re-select now that the refreshed entries are back in the pool.
if entry is None:
- entry, _ = self._select_under_lock()
+ entry, _ = self._select_under_lock(model=model)
if entry is not None:
self._unmatched_rotation_streak = 0
return entry
- def _select_under_lock(self) -> Tuple[Optional[PooledCredential], List[PooledCredential]]:
+ def _select_under_lock(self, *, model: Optional[str] = None) -> Tuple[Optional[PooledCredential], List[PooledCredential]]:
with self._lock:
- return self._select_unlocked()
+ return self._select_unlocked(model=model)
def _refresh_pending_entries(self, pending: List[PooledCredential]) -> None:
"""Refresh deferred single-use-token entries OUTSIDE the pool lock.
@@ -1599,7 +1637,7 @@ class CredentialPool(CredentialPoolAdminMixin):
return self._sync_entry_from_auth_store(entry)
def _available_entries(
- self, *, clear_expired: bool = False, refresh: bool = False,
+ self, *, clear_expired: bool = False, refresh: bool = False, model: Optional[str] = None,
) -> Tuple[List[PooledCredential], List[PooledCredential]]:
"""Return (available, pending_refresh) for entries not in cooldown.
@@ -1645,6 +1683,8 @@ 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:
+ continue
if entry.last_status == STATUS_EXHAUSTED:
exhausted_until = _exhausted_until(entry, sole_credential=sole_credential)
# Codex quota windows can reopen EARLY; a throttled live probe
@@ -1689,14 +1729,14 @@ class CredentialPool(CredentialPoolAdminMixin):
logger.info("credential pool: no available entries (all exhausted or empty)")
def _select_unlocked(
- self, *, refresh: bool = True, count: bool = True,
+ self, *, refresh: bool = True, count: bool = True, model: Optional[str] = None,
) -> Tuple[Optional[PooledCredential], List[PooledCredential]]:
"""Select the best available entry; returns ``(entry, pending_refresh)``.
``count=False`` skips the ``request_count`` bump for selections that are
not going to serve a request (a forced-refresh target lookup).
"""
- available, pending_refresh = self._available_entries(clear_expired=True, refresh=refresh)
+ available, pending_refresh = self._available_entries(clear_expired=True, refresh=refresh, model=model)
if not available:
self._current_id = None
self._log_no_available_entries()
@@ -1814,6 +1854,7 @@ class CredentialPool(CredentialPoolAdminMixin):
api_key_hint: Optional[str] = None,
credential_id: Optional[str] = None,
failure_reason: Optional[str] = None,
+ model: Optional[str] = None,
) -> Optional[PooledCredential]:
with self._lock:
identity_supplied = bool(credential_id or api_key_hint)
@@ -1827,6 +1868,31 @@ 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()
+ self._current_id = None
+ next_entry, _pending = self._select_unlocked(refresh=False, model=model)
+ return next_entry
self._mark_exhausted(entry, status_code, error_context, failure_reason=failure_reason)
# A 402/429/401 is a key-level failure, and the same key can back
# several entries (an explicit entry plus a ``model_config`` row
diff --git a/agent/credential_pool_admin.py b/agent/credential_pool_admin.py
index a24fbf65788..441890a2958 100644
--- a/agent/credential_pool_admin.py
+++ b/agent/credential_pool_admin.py
@@ -11,7 +11,7 @@ if TYPE_CHECKING:
def _cleared_status_copy(entry: PooledCredential) -> PooledCredential:
from agent.credential_pool import _CLEAR_STATUS
- return replace(entry, **_CLEAR_STATUS,
+ return replace(entry, **_CLEAR_STATUS, model_cooldowns=None,
extra={k: v for k, v in entry.extra.items() if k != "failure_reason"})
@@ -39,7 +39,7 @@ class CredentialPoolAdminMixin:
with self._lock:
stale = [
e for e in self._entries
- if e.last_status or e.last_status_at or e.last_error_code or e.failure_reason
+ if e.last_status or e.last_status_at or e.last_error_code or e.failure_reason or e.model_cooldowns
]
if stale:
stale_ids = {e.id for e in stale}
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.py
index 278559d334b..e0c11e1f9d7 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -796,9 +796,22 @@ 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))
+ merged = {**entry, "model_cooldowns": merged_cooldowns} if merged_cooldowns else entry
+
disk_status = disk_entry.get("last_status")
if disk_status not in (STATUS_DEAD, STATUS_EXHAUSTED):
- return entry
+ return merged
# A token change means the caller re-authed this entry and intentionally cleared its status:
# never resurrect the old cooldown onto fresh credentials.
mem_access = entry.get("access_token") or ""
@@ -808,12 +821,12 @@ def _merge_disk_cooldown_state(
disk_ts = _parse_absolute_timestamp(disk_entry.get("last_status_at")) or 0.0
mem_ts = _parse_absolute_timestamp(entry.get("last_status_at")) or 0.0
if disk_ts <= mem_ts:
- return entry
+ return merged
if disk_status == STATUS_EXHAUSTED:
until = _exhausted_until(PooledCredential.from_dict(provider_id, disk_entry))
if until is None or until <= time.time():
- return entry
- return {**entry, **{f: disk_entry.get(f) for f in _POOL_STATUS_FIELDS}}
+ return merged
+ return {**merged, **{f: disk_entry.get(f) for f in _POOL_STATUS_FIELDS}}
except Exception: # pragma: no cover - best-effort merge
return entry
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index c59a57c738a..687c228aac0 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -284,9 +284,9 @@ def _anthropic_cfg_base_url(model_cfg: Dict[str, Any]) -> str:
return cfg_base_url if _anthropic_base_url_override_ok(cfg_base_url) else ""
-def _anthropic_token_or_raise() -> str:
+def _anthropic_token_or_raise(*, model: str | None = None) -> str:
from agent.anthropic_credentials import resolve_anthropic_token
- token = resolve_anthropic_token()
+ token = resolve_anthropic_token(model=model) if model else resolve_anthropic_token()
if not token:
raise AuthError(_NO_ANTHROPIC_CREDENTIALS_MSG)
return token
@@ -538,7 +538,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()
+ entry = pool.select(model=target_model) if provider == "anthropic" and target_model else pool.select()
if entry is None:
return None
pool_api_key = _pool_entry_api_key(entry)
@@ -555,7 +555,7 @@ def _resolve_from_pool(provider: str, requested_provider: str, model_cfg: Dict[s
def _explicit_anthropic(requested_provider, model_cfg, api_key, base_url, target_model):
base_url = base_url or _anthropic_cfg_base_url(model_cfg) or _ANTHROPIC_DEFAULT_BASE_URL
- api_key = api_key or _anthropic_token_or_raise()
+ api_key = api_key or _anthropic_token_or_raise(model=target_model)
return _runtime("anthropic", "anthropic_messages", base_url, api_key, source="explicit", requested_provider=requested_provider)
@@ -715,7 +715,7 @@ def _azure_anthropic_env_key(model_cfg: Dict[str, Any]) -> str:
or get_secret_str("ANTHROPIC_API_KEY", "").strip())
-def _anthropic_env_runtime(requested_provider: str, model_cfg: Dict[str, Any]) -> Dict[str, Any]:
+def _anthropic_env_runtime(requested_provider: str, model_cfg: Dict[str, Any], target_model: str | None = None) -> Dict[str, Any]:
"""Native Anthropic (Messages API) from env/auth store; ``model.base_url`` honoured only when
the configured provider is anthropic (else a Codex endpoint would leak into Anthropic requests)."""
base_url = _anthropic_cfg_base_url(model_cfg) or _ANTHROPIC_DEFAULT_BASE_URL
@@ -727,7 +727,7 @@ def _anthropic_env_runtime(requested_provider: str, model_cfg: Dict[str, Any]) -
raise AuthError("No Azure Anthropic API key found. Set AZURE_ANTHROPIC_KEY or ANTHROPIC_API_KEY, or point "
"key_env/api_key_env in your config.yaml model section at a custom env var.")
else:
- token = _anthropic_token_or_raise()
+ token = _anthropic_token_or_raise(model=target_model)
return _runtime("anthropic", "anthropic_messages", base_url, token, source="env", requested_provider=requested_provider)
@@ -911,7 +911,7 @@ def _ladder_rungs(requested_provider, explicit_api_key, explicit_base_url, targe
if _is_external_process_provider(provider):
yield _resolve_external_process_runtime(provider, requested_provider)
if provider == "anthropic":
- yield _anthropic_env_runtime(requested_provider, model_cfg)
+ yield _anthropic_env_runtime(requested_provider, model_cfg, target_model)
if provider == "bedrock":
yield _resolve_bedrock_runtime(requested_provider, model_cfg, target_model)
pconfig = PROVIDER_REGISTRY.get(provider)
diff --git a/tests/agent/test_anthropic_model_cooldowns.py b/tests/agent/test_anthropic_model_cooldowns.py
new file mode 100644
index 00000000000..ecb9e12f3f6
--- /dev/null
+++ b/tests/agent/test_anthropic_model_cooldowns.py
@@ -0,0 +1,73 @@
+"""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)
+
+ pool.mark_exhausted_and_rotate(
+ status_code=429, api_key_hint="key", model="claude-sonnet-4",
+ )
+
+ 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