fix(credential-pool): rotate Codex failures to a usable sibling
Three rotation paths gave up or handed back an unusable login while a healthy sibling sat idle, sending the turn to fallback_providers: - Unmatched-identity rotation declined whenever only one entry was available, even when the pool had a second login that was merely cooling (#127722). Decline only for a true single-entry pool; repeats stay bounded by the #70401 streak cap. - A 429 on the priority-0 account let a cached "quota restored" probe verdict lift the bench it had just written; the #97315 guard then saw the failed entry come back and returned None instead of trying the next account (#134327). Rotation now excludes the just-marked entries, and a live quota 429 pins the cached probe verdict (including one still in flight) to "not restored", so the next turn does not bounce back. - Rotation selected with token refresh deferred, so an expired Codex access token was handed out and the retry 401'd again (#142473). The rotation target is refreshed before it is returned. _rotate_unmatched moves next to the selection code so credential_pool.py shrinks. Fixes #127722, fixes #134327, fixes #142473 Co-authored-by: Yagna Vudathu <yagnavudathu@gmail.com> Co-authored-by: skyeyesec333 <36165556+skyeyesec333@users.noreply.github.com>
This commit is contained in:
@@ -24,6 +24,7 @@ from hermes_constants import OPENROUTER_BASE_URL
|
||||
from hermes_cli.config import load_env
|
||||
from agent.secret_scope import get_secret as _get_secret, get_secret_str
|
||||
from hermes_cli.auth_plugin_providers import plugin_refresh_hook
|
||||
from hermes_cli.auth_codex import _record_codex_quota_exhausted
|
||||
from agent.credential_pool_plugin import apply_plugin_refresh_result, plugin_row_is_expiring, recover_failed_plugin_refresh
|
||||
from agent.credential_persistence import (
|
||||
fingerprint_secret_value,
|
||||
@@ -2111,45 +2112,6 @@ class CredentialPool(CredentialPoolSelectionMixin, CredentialPoolAdminMixin, Cre
|
||||
entry = self._find(lambda e: e.runtime_api_key == api_key_hint)
|
||||
return entry
|
||||
|
||||
def _rotate_unmatched(self) -> Optional[PooledCredential]:
|
||||
"""Rotate without marking anything when the failed identity matches no entry.
|
||||
|
||||
Falling through to current()/_select_unlocked() would bench an
|
||||
innocent healthy key for the full TTL. But this must be BOUNDED
|
||||
(#70401): with OAuth-token auth the 401's key hint never matches any
|
||||
``runtime_api_key``, so every retry lands here, nothing is marked, and
|
||||
the caller retries the same dead token forever (~6/sec, starving the
|
||||
event loop). Cap consecutive no-mark rotations at one lap of the
|
||||
available entries, then surface the error; no cooldown is written.
|
||||
"""
|
||||
self._unmatched_rotation_streak += 1
|
||||
available_count = len(self._available_entries()[0])
|
||||
if self._unmatched_rotation_streak > max(available_count, 1):
|
||||
logger.warning(
|
||||
"credential pool: failed credential identity matched no "
|
||||
"%s entry for %d consecutive rotations (pool size %d) — "
|
||||
"surfacing the error instead of rotating again",
|
||||
self.provider, self._unmatched_rotation_streak, available_count,
|
||||
)
|
||||
self._unmatched_rotation_streak = 0
|
||||
self._current_id = None
|
||||
return None
|
||||
logger.info(
|
||||
"credential pool: failed credential identity matched no %s "
|
||||
"entry; rotating without marking any credential exhausted",
|
||||
self.provider,
|
||||
)
|
||||
self._current_id = None
|
||||
next_entry, _pending = self._select_unlocked(refresh=False)
|
||||
if next_entry is not None and len(self._available_entries()[0]) == 1:
|
||||
# A single-entry pool cannot rotate: returning its only entry would
|
||||
# report a recovery without changing the credential, and the
|
||||
# caller retries the same 401 indefinitely.
|
||||
self._unmatched_rotation_streak = 0
|
||||
self._current_id = None
|
||||
return None
|
||||
return next_entry
|
||||
|
||||
def mark_exhausted_and_rotate(
|
||||
self,
|
||||
*,
|
||||
@@ -2179,8 +2141,7 @@ class CredentialPool(CredentialPoolSelectionMixin, CredentialPoolAdminMixin, Cre
|
||||
self._cool_down_model(entry, model, error_context, failure_reason=failure_reason)
|
||||
logger.info("credential pool: %s unavailable 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
|
||||
return self._rotation_target(model=model)
|
||||
self._mark_exhausted(entry, status_code, error_context, failure_reason=failure_reason, bench=bench)
|
||||
# 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
|
||||
@@ -2189,6 +2150,7 @@ class CredentialPool(CredentialPoolSelectionMixin, CredentialPoolAdminMixin, Cre
|
||||
# the depleted key, and rotation never converges (~2.5 min hang).
|
||||
# Mark every entry sharing the failed key.
|
||||
failed_runtime_key = entry.runtime_api_key
|
||||
siblings: list[PooledCredential] = []
|
||||
if identity_supplied and failed_runtime_key:
|
||||
siblings = [
|
||||
s for s in self._entries if s.id != entry.id and s.runtime_api_key == failed_runtime_key
|
||||
@@ -2209,21 +2171,12 @@ class CredentialPool(CredentialPoolSelectionMixin, CredentialPoolAdminMixin, Cre
|
||||
)
|
||||
else:
|
||||
logger.info("credential pool: marking %s exhausted (status=%s), rotating", _label, status_code)
|
||||
if self.provider == "openai-codex": # a live 429 outranks a cached early-reopen verdict (#134327)
|
||||
_record_codex_quota_exhausted(updated_entry)
|
||||
self._current_id = None
|
||||
next_entry, _pending = self._select_unlocked(refresh=False)
|
||||
if next_entry is not None and next_entry.id == entry.id:
|
||||
# No-recovery guard (#97315): selection handed back the very entry that was
|
||||
# just marked (the auth-store sync adopted fresher tokens, or a quota probe
|
||||
# false-positive lifted the bench mid-selection). Returning it reports a
|
||||
# successful rotation without changing the credential, so the caller retries
|
||||
# the same 429 forever (~2 req/s for hours). Mirror the single-entry guard on
|
||||
# the unmatched-identity branch: surface the failure instead.
|
||||
logger.warning(
|
||||
"credential pool: rotation returned the just-marked entry %s — "
|
||||
"treating as no-recovery so the failure surfaces", _label,
|
||||
)
|
||||
self._current_id = None
|
||||
return None
|
||||
# Never re-admit the just-marked entries (#97315): a token sync or a stale quota probe can lift their
|
||||
# bench mid-selection; returning one retries the same failure, giving up strands a healthy sibling.
|
||||
next_entry = self._rotation_target(exclude_ids=frozenset({entry.id, *(s.id for s in siblings)}))
|
||||
if next_entry:
|
||||
logger.info("credential pool: rotated to %s", next_entry.label or next_entry.id[:8])
|
||||
return next_entry
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
import random
|
||||
import threading
|
||||
from dataclasses import replace
|
||||
@@ -11,6 +12,9 @@ from typing import Any, Callable, Iterator, Optional, TYPE_CHECKING
|
||||
if TYPE_CHECKING:
|
||||
from agent.credential_pool import PooledCredential
|
||||
|
||||
# The pool's own logger: rotation lines read as one subsystem in the log.
|
||||
logger = logging.getLogger("agent.credential_pool")
|
||||
|
||||
# Maps a row's stored base URL to the URL a client built from it calls (MiniMax rows store
|
||||
# ``/anthropic``; a chat-completions client calls the ``/v1`` sibling).
|
||||
AsCalled = Optional[Callable[[str], str]]
|
||||
@@ -199,15 +203,16 @@ class CredentialPoolSelectionMixin:
|
||||
|
||||
def _select_unlocked(
|
||||
self, *, refresh: bool = True, count: bool = True, model: Optional[str] = None,
|
||||
endpoint_url: Optional[str] = None,
|
||||
endpoint_url: Optional[str] = None, exclude_ids: frozenset = frozenset(),
|
||||
) -> 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).
|
||||
``exclude_ids`` are never picked (the entries a rotation is moving away from).
|
||||
"""
|
||||
available, pending_refresh = self._available_entries(clear_expired=True, refresh=refresh, model=model)
|
||||
available = _serving(available, endpoint_url)
|
||||
available = [e for e in _serving(available, endpoint_url) if e.id not in exclude_ids]
|
||||
if not available:
|
||||
self._current_id = None
|
||||
self._log_no_available_entries()
|
||||
@@ -218,6 +223,60 @@ class CredentialPoolSelectionMixin:
|
||||
self._last_no_entries_log_at = None
|
||||
return self._record_pick(self._strategy_pick(available), available, count=count), pending_refresh
|
||||
|
||||
def _rotation_target(
|
||||
self, *, exclude_ids: frozenset = frozenset(), model: Optional[str] = None,
|
||||
) -> Optional[PooledCredential]:
|
||||
"""The entry a rotation hands out, never one in ``exclude_ids`` (the entries it moves away from).
|
||||
|
||||
Rotation runs under the pool lock, so the selection defers single-use-token refreshes; an entry whose
|
||||
access token is expiring is refreshed here before it is returned (#142473), or the caller retries an
|
||||
expired bearer and gives up. An entry whose refresh fails is skipped for the next one.
|
||||
"""
|
||||
tried = set(exclude_ids)
|
||||
while True:
|
||||
entry, _pending = self._select_unlocked(refresh=False, model=model, exclude_ids=frozenset(tried))
|
||||
if entry is None or not self._entry_needs_refresh(entry):
|
||||
return entry
|
||||
refreshed = self._refresh_entry(entry, force=False)
|
||||
if refreshed is not None:
|
||||
self._current_id = refreshed.id
|
||||
return refreshed
|
||||
tried.add(entry.id)
|
||||
self._current_id = None
|
||||
|
||||
def _rotate_unmatched(self) -> Optional[PooledCredential]:
|
||||
"""Rotate without marking anything when the failed identity matches no entry.
|
||||
|
||||
Falling through to current()/_select_unlocked() would bench an innocent healthy key for the full TTL. But
|
||||
this must be BOUNDED (#70401): with OAuth-token auth the 401's key hint never matches any
|
||||
``runtime_api_key``, so every retry lands here, nothing is marked, and the caller retries the same dead token
|
||||
forever. Cap consecutive no-mark rotations at one lap of the available entries, then surface the error; no
|
||||
cooldown is written.
|
||||
"""
|
||||
self._unmatched_rotation_streak += 1
|
||||
available_count = len(self._available_entries()[0])
|
||||
if self._unmatched_rotation_streak > max(available_count, 1):
|
||||
logger.warning(
|
||||
"credential pool: failed credential identity matched no %s entry for %d consecutive rotations "
|
||||
"(pool size %d) — surfacing the error instead of rotating again",
|
||||
self.provider, self._unmatched_rotation_streak, available_count,
|
||||
)
|
||||
self._unmatched_rotation_streak = 0
|
||||
self._current_id = None
|
||||
return None
|
||||
logger.info(
|
||||
"credential pool: failed credential identity matched no %s entry; rotating without marking any "
|
||||
"credential exhausted", self.provider,
|
||||
)
|
||||
self._current_id = None
|
||||
if len(self._entries) == 1:
|
||||
# A single-entry pool cannot rotate: returning its only entry would report a recovery without changing
|
||||
# the credential. Key on pool size, not availability (#127722): with siblings cooling, the one available
|
||||
# entry still differs from the unmatched failed identity, and repeats stay bounded by the cap above.
|
||||
self._unmatched_rotation_streak = 0
|
||||
return None
|
||||
return self._rotation_target()
|
||||
|
||||
def _strategy_pick(self, available: list[PooledCredential]) -> PooledCredential:
|
||||
from agent.credential_pool import STRATEGY_LEAST_USED, STRATEGY_RANDOM
|
||||
if self._strategy == STRATEGY_RANDOM:
|
||||
|
||||
@@ -815,6 +815,21 @@ def _codex_usage_probe_url(base_url: Optional[str]) -> str:
|
||||
return prefix + "/usage"
|
||||
|
||||
|
||||
def _record_codex_quota_exhausted(entry: Any) -> None:
|
||||
"""Pin a pool entry's cached probe verdict to "not restored" after a live quota 429 (#134327).
|
||||
|
||||
The 429 is first-hand and newer than any cached probe: a "restored" verdict cached minutes before the
|
||||
account hit its cap (or a probe still in flight) would otherwise lift the fresh bench on the next selection.
|
||||
"""
|
||||
from hermes_cli.auth import _codex_quota_probe_cache
|
||||
token = _stripped(getattr(entry, "access_token", None))
|
||||
if token and _is_codex_rate_limit_shaped(
|
||||
getattr(entry, "last_error_code", None), getattr(entry, "last_error_reason", None),
|
||||
getattr(entry, "last_error_message", None)):
|
||||
with _codex_quota_probe_lock:
|
||||
_codex_quota_probe_cache[_codex_quota_probe_cache_key(token)] = (time.monotonic(), False)
|
||||
|
||||
|
||||
def _probe_codex_quota_restored(
|
||||
access_token: Any, *, base_url: Optional[str] = None,
|
||||
min_interval_seconds: float = CODEX_QUOTA_PROBE_MIN_INTERVAL_SECONDS) -> Optional[bool]:
|
||||
@@ -836,7 +851,8 @@ def _probe_codex_quota_restored(
|
||||
if cached is not None and (now - cached[0]) < min_interval_seconds:
|
||||
return cached[1]
|
||||
# Reserve the slot immediately so concurrent selectors don't stampede the endpoint.
|
||||
_codex_quota_probe_cache[cache_key] = (now, None)
|
||||
reservation = (now, None)
|
||||
_codex_quota_probe_cache[cache_key] = reservation
|
||||
result: Optional[bool] = None
|
||||
try:
|
||||
# Account/residency headers from the JWT (required for some account shapes).
|
||||
@@ -868,6 +884,9 @@ def _probe_codex_quota_restored(
|
||||
logger.debug("Codex quota probe failed", exc_info=True)
|
||||
result = None
|
||||
with _codex_quota_probe_lock:
|
||||
current = _codex_quota_probe_cache.get(cache_key)
|
||||
if current is not reservation: # a live 429 replaced the slot while this probe was in flight
|
||||
return current[1] if current is not None else None
|
||||
_codex_quota_probe_cache[cache_key] = (now, result)
|
||||
return result
|
||||
|
||||
|
||||
99
tests/agent/test_credential_pool_codex_rotation_targets.py
Normal file
99
tests/agent/test_credential_pool_codex_rotation_targets.py
Normal file
@@ -0,0 +1,99 @@
|
||||
"""Codex rotation hands out a usable sibling instead of giving up or an expired bearer.
|
||||
|
||||
#127722: an unmatched-identity rotation declined whenever only one entry was available, even in a
|
||||
multi-entry pool whose other login was cooling. #134327: a stale cached "quota restored" verdict lifted
|
||||
the bench a 429 had just written, the no-recovery guard saw the failed entry come back and gave up instead
|
||||
of trying the next account. #142473: rotation selected with token refresh deferred, so an expired Codex
|
||||
access token was handed out and the retry 401'd again.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import hermes_cli.auth as auth_mod
|
||||
from hermes_cli import auth_codex
|
||||
|
||||
|
||||
def _jwt(account: str, expires_in: float) -> str:
|
||||
def part(payload: dict) -> str:
|
||||
return base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
|
||||
|
||||
claims = {"exp": time.time() + expires_in, "sub": account,
|
||||
"https://api.openai.com/auth": {"chatgpt_account_id": account}}
|
||||
return f"{part({'alg': 'none'})}.{part(claims)}.sig"
|
||||
|
||||
|
||||
def _row(idx: int, token: str, **extra) -> dict:
|
||||
return {"id": f"codex-{idx}", "label": f"codex-{idx}", "auth_type": "oauth", "priority": idx,
|
||||
"source": "manual:device_code", "access_token": token, "refresh_token": f"rt-{idx}", **extra}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def load(tmp_path, monkeypatch):
|
||||
auth_mod._codex_quota_probe_cache.clear()
|
||||
def offline(**_kw):
|
||||
raise ConnectionError("synthetic: no network in this test")
|
||||
|
||||
monkeypatch.setattr(auth_codex, "_codex_http_client", offline)
|
||||
|
||||
def _load(rows: list[dict]):
|
||||
home = tmp_path / "hermes"
|
||||
home.mkdir(exist_ok=True)
|
||||
(home / "auth.json").write_text(json.dumps({"version": 1, "credential_pool": {"openai-codex": rows}}), encoding="utf-8")
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
from agent.credential_pool import load_pool
|
||||
return load_pool("openai-codex")
|
||||
|
||||
yield _load
|
||||
auth_mod._codex_quota_probe_cache.clear()
|
||||
|
||||
|
||||
def test_unmatched_rotation_uses_the_one_available_sibling(load):
|
||||
now = time.time()
|
||||
pool = load([
|
||||
_row(0, _jwt("A", 7200), last_status="exhausted", last_status_at=now, last_error_code=429,
|
||||
last_error_reset_at=now + 3600),
|
||||
_row(1, _jwt("B", 7200)),
|
||||
])
|
||||
|
||||
nxt = pool.mark_exhausted_and_rotate(
|
||||
status_code=429, error_context={"reason": "usage_limit_reached"}, api_key_hint="matches-no-entry")
|
||||
|
||||
assert nxt is not None and nxt.id == "codex-1"
|
||||
|
||||
|
||||
def test_429_rotates_past_a_stale_restored_probe_and_stays_rotated(load):
|
||||
primary = _jwt("primary", 7 * 86400)
|
||||
pool = load([_row(0, primary), _row(1, _jwt("secondary", 7 * 86400))])
|
||||
# A probe that ran a minute before the account hit its cap.
|
||||
auth_mod._codex_quota_probe_cache[auth_codex._codex_quota_probe_cache_key(primary)] = (time.monotonic() - 60, True)
|
||||
|
||||
nxt = pool.mark_exhausted_and_rotate(
|
||||
status_code=429, credential_id="codex-0", failure_reason="rate_limit",
|
||||
error_context={"reason": "usage_limit_reached", "message": "The usage limit has been reached",
|
||||
"reset_at": time.time() + 3600})
|
||||
|
||||
assert nxt is not None and nxt.id == "codex-1"
|
||||
assert pool.select().id == "codex-1"
|
||||
|
||||
|
||||
def test_unmatched_401_rotation_refreshes_an_expired_codex_token(load, monkeypatch):
|
||||
posts = []
|
||||
|
||||
def fake_refresh(access_token, refresh_token, **_kw):
|
||||
posts.append(refresh_token)
|
||||
return {"access_token": _jwt("same", 7200), "refresh_token": refresh_token + "-next"}
|
||||
|
||||
monkeypatch.setattr(auth_mod, "refresh_codex_oauth_pure", fake_refresh)
|
||||
pool = load([_row(0, _jwt("same", -60)), _row(1, _jwt("same", -60))])
|
||||
|
||||
nxt = pool.mark_exhausted_and_rotate(
|
||||
status_code=401, error_context={"reason": "unauthorized"}, api_key_hint="expired-bearer")
|
||||
|
||||
assert nxt is not None and len(posts) == 1
|
||||
assert not auth_codex._codex_access_token_is_expiring(nxt.access_token, 0)
|
||||
Reference in New Issue
Block a user