The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(credential-pool): short cooldown for sole credential on transient throttle
A.Alzarodcd750434958
diff --git a/agent/credential_pool.py b/agent/credential_pool.pyindex 7a4214fb59f..6d2cd42c3c0 100644--- a/agent/credential_pool.py+++ b/agent/credential_pool.py@@ -124,6 +124,12 @@ SUPPORTED_POOL_STRATEGIES = {EXHAUSTED_TTL_401_SECONDS = 5 * 60 # 5 minutesEXHAUSTED_TTL_429_SECONDS = 60 * 60 # 1 hourEXHAUSTED_TTL_DEFAULT_SECONDS = 60 * 60 # 1 hour+# When a pool has no other credential to rotate to (the offending key is the+# sole non-DEAD entry), a 1-hour bench means an hour of hard failures with+# nothing to fall back to. Throttles (429/403/5xx) are transient and reset in+# seconds, so a sole credential cools down briefly instead — same rationale as+# the short 401 cooldown above. Provider-supplied reset_at still overrides.+EXHAUSTED_TTL_SOLE_CREDENTIAL_SECONDS = 60 # 1 minute# Throttle window for the "no available entries" INFO line. Credential# selection runs on a hot path (every model call, plus auxiliary tasks like@@ -289,13 +295,25 @@ def _is_manual_source(source: str) -> bool:return normalized == SOURCE_MANUAL or normalized.startswith(f"{SOURCE_MANUAL}:")-def _exhausted_ttl(error_code: Optional[int]) -> int:- """Return cooldown seconds based on the HTTP status that caused exhaustion."""+def _exhausted_ttl(error_code: Optional[int], *, sole_credential: bool = False) -> int:+ """Return cooldown seconds based on the HTTP status that caused exhaustion.++ When *sole_credential* is True the pool has no other entry to rotate to, so+ a long bench just blocks the only key. Transient throttles (429 and the+ catch-all default, which covers 403/5xx/unknown) are capped to a brief+ cooldown so the sole key can recover — mirroring the short 401 path. 401+ keeps its own (already short) TTL; 402 (billing/quota) keeps the full bench+ since a quick retry can't help.+ """if error_code == 401:return EXHAUSTED_TTL_401_SECONDS- if error_code == 429:- return EXHAUSTED_TTL_429_SECONDS- return EXHAUSTED_TTL_DEFAULT_SECONDS+ base = EXHAUSTED_TTL_429_SECONDS if error_code == 429 else EXHAUSTED_TTL_DEFAULT_SECONDS+ # Sole credential: shorten only TRANSIENT throttles (429 rate-limit, 403+ # edge-throttle, 5xx server, or unknown). 402 (billing/quota) is a genuine+ # exhaustion where a quick retry can't help, so it keeps the full bench.+ if sole_credential and error_code != 402:+ return min(base, EXHAUSTED_TTL_SOLE_CREDENTIAL_SECONDS)+ return basedef _parse_absolute_timestamp(value: Any) -> Optional[float]:@@ -376,14 +394,16 @@ def _normalize_error_context(error_context: Optional[Dict[str, Any]]) -> Dict[streturn normalized-def _exhausted_until(entry: PooledCredential) -> Optional[float]:+def _exhausted_until(entry: PooledCredential, *, sole_credential: bool = False) -> Optional[float]:if entry.last_status != STATUS_EXHAUSTED:return Nonereset_at = _parse_absolute_timestamp(getattr(entry, "last_error_reset_at", None))if reset_at is not None:return reset_atif entry.last_status_at:- return entry.last_status_at + _exhausted_ttl(entry.last_error_code)+ return entry.last_status_at + _exhausted_ttl(+ entry.last_error_code, sole_credential=sole_credential+ )return None@@ -1759,6 +1779,12 @@ class CredentialPool:# that can block for 20+ seconds. We collect them under self._lock# and refresh outside the lock to avoid stalling all pool consumers.pending_refresh: List[tuple] = [] # (entry, sync_entry_fn)+ # DEAD entries never re-enter rotation, so if at most one non-DEAD entry+ # exists there is nothing to rotate to: an exhausted sole credential+ # should cool down briefly rather than bench the only key for an hour.+ sole_credential = sum(+ 1 for e in self._entries if e.last_status != STATUS_DEAD+ ) <= 1for entry in self._entries:# Borrowed credentials persist as metadata-only references and are# hydrated from their live source on load. A stale duplicate row@@ -1839,7 +1865,7 @@ class CredentialPool:# the re-auth case for OAuth singletons.continueif entry.last_status == STATUS_EXHAUSTED:- exhausted_until = _exhausted_until(entry)+ exhausted_until = _exhausted_until(entry, sole_credential=sole_credential)if exhausted_until is not None and now < exhausted_until:# Codex quota windows can reopen EARLY: the user redeems a# banked rate-limit reset (Codex CLI / ChatGPT UI), upgradesdiff --git a/tests/agent/test_credential_pool_sole_cooldown.py b/tests/agent/test_credential_pool_sole_cooldown.pynew file mode 100644index 00000000000..37b134bc2ae--- /dev/null+++ b/tests/agent/test_credential_pool_sole_cooldown.py@@ -0,0 +1,91 @@+"""Sole-credential cooldown: a pool with nothing to rotate to should not bench+its only key for an hour on a transient throttle (429/403/5xx).++Regression for the case where removing fallbacks / running a single API key+turned a transient rate-limit into an hour of hard failures.+"""++from __future__ import annotations++import json+import time++import pytest+++def _write_auth_store(tmp_path, payload: dict) -> None:+ hermes_home = tmp_path / "hermes"+ hermes_home.mkdir(parents=True, exist_ok=True)+ (hermes_home / "auth.json").write_text(json.dumps(payload, indent=2))+++def _entry(error_code: int, *, age_seconds: float, cred_id: str = "cred-1", priority: int = 0) -> dict:+ return {+ "id": cred_id,+ "label": cred_id,+ "auth_type": "api_key",+ "priority": priority,+ "source": "manual",+ "access_token": "***",+ "base_url": "https://openrouter.ai/api/v1",+ "last_status": "exhausted",+ "last_status_at": time.time() - age_seconds,+ "last_error_code": error_code,+ }+++def _load(tmp_path, monkeypatch, entries: list[dict]):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))+ monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)+ _write_auth_store(+ tmp_path,+ {"version": 1, "credential_pool": {"openrouter": entries}},+ )+ from agent.credential_pool import load_pool++ return load_pool("openrouter")+++def test_sole_credential_429_recovers_after_short_cooldown(tmp_path, monkeypatch):+ """A single 429-throttled key recovers within ~1 min, not 1 hour.++ Exhausted 90s ago: under the old 1-hour TTL this stays benched (and a+ single-key pool would have nothing to return); the sole-credential short+ cooldown lets it recover.+ """+ pool = _load(tmp_path, monkeypatch, [_entry(429, age_seconds=90)])+ entry = pool.select()+ assert entry is not None+ assert entry.id == "cred-1"+ assert entry.last_status == "ok"+++def test_sole_credential_403_recovers_after_short_cooldown(tmp_path, monkeypatch):+ """403 (edge-throttle variant, hits the catch-all default TTL) also recovers."""+ pool = _load(tmp_path, monkeypatch, [_entry(403, age_seconds=90)])+ entry = pool.select()+ assert entry is not None+ assert entry.last_status == "ok"+++def test_sole_credential_402_keeps_full_bench(tmp_path, monkeypatch):+ """402 (billing/quota) is genuine exhaustion — a quick retry can't help, so+ the sole-credential short cooldown must NOT apply."""+ pool = _load(tmp_path, monkeypatch, [_entry(402, age_seconds=90)])+ assert pool.has_available() is False+ assert pool.select() is None+++def test_multi_key_429_keeps_full_bench(tmp_path, monkeypatch):+ """With more than one non-DEAD entry there IS something to rotate to, so the+ short cooldown must not kick in — both recently-throttled keys stay benched."""+ pool = _load(+ tmp_path,+ monkeypatch,+ [+ _entry(429, age_seconds=90, cred_id="cred-1", priority=0),+ _entry(429, age_seconds=90, cred_id="cred-2", priority=1),+ ],+ )+ assert pool.has_available() is False+ assert pool.select() is None