Skip to content

The agent that grows with you

fix(auth): throttle the pre-probe Codex refresh and pin the pool-side wiring

teknium1a70053d9d739
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 281be8e5fd9..f40fe2fd92a 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -1677,9 +1677,15 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
# expired by probe time (401 -> None -> cooldown kept, #89415): refresh it first.
fresh = auth_mod._refresh_expired_codex_probe_token(token, entry.refresh_token)
if fresh:
+ # Persist the rotated pair on both sides the way ``_refresh_entry`` does:
+ # ``last_refresh`` plus the singleton write-back, or the next selection's
+ # auth-store sync re-adopts the consumed pair from ``providers.openai-codex``
+ # and clears the cooldown with it.
entry = self._adopt(
entry, access_token=fresh["access_token"], refresh_token=fresh["refresh_token"],
+ last_refresh=fresh.get("last_refresh") or entry.last_refresh,
)
+ self._sync_device_code_entry_to_auth_store(entry)
token = entry.access_token or token
return bool(auth_mod._probe_codex_quota_restored(token, base_url=entry.base_url))
except Exception:
diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.py
index 68ed44ff99b..75593f3cca0 100644
--- a/hermes_cli/auth_codex.py
+++ b/hermes_cli/auth_codex.py
@@ -617,6 +617,10 @@ _codex_quota_probe_cache: Dict[str, Tuple[float, Optional[bool]]] = {}
_codex_quota_probe_lock = threading.Lock()
+def _codex_quota_probe_cache_key(token: str) -> str:
+ return hashlib.sha256(token.encode("utf-8")).hexdigest()[:16]
+
+
def _codex_usage_probe_url(base_url: Optional[str]) -> str:
"""Resolve the Codex usage endpoint for a probe.
@@ -645,7 +649,7 @@ def _probe_codex_quota_restored(
# network calls for corrupt/placeholder entries (and keeps hermetic test fixtures offline).
if not token or not _decode_jwt_claims(token):
return None
- cache_key = hashlib.sha256(token.encode("utf-8")).hexdigest()[:16]
+ cache_key = _codex_quota_probe_cache_key(token)
now = time.monotonic()
with _codex_quota_probe_lock:
cached = _codex_quota_probe_cache.get(cache_key)
@@ -682,7 +686,8 @@ def _probe_codex_quota_restored(
def _refresh_expired_codex_probe_token(
- access_token: Any, refresh_token: Any) -> Optional[Dict[str, Any]]:
+ access_token: Any, refresh_token: Any, *,
+ min_interval_seconds: float = CODEX_QUOTA_PROBE_MIN_INTERVAL_SECONDS) -> Optional[Dict[str, Any]]:
"""Refresh an EXPIRED stored access token so the quota probe can get a real answer.
Exhausted pool entries are skipped by the proactive refresh chain (#44799), so by the time
@@ -691,14 +696,29 @@ def _refresh_expired_codex_probe_token(
``last_error_reset_at`` no matter what happened upstream (top-up, plan upgrade) — #89415.
Returns the rotated token pair (callers MUST persist it: refresh tokens are single-use) or
None when no refresh was needed/possible. The cooldown itself is left untouched.
+
+ Shares the probe's per-token throttle: a refresh that keeps failing (revoked grant, network
+ down) would otherwise POST to the token endpoint on every credential selection, while the
+ probe itself is capped at one call per ``min_interval_seconds``. A failed attempt reserves
+ the stale token's probe slot, so neither the refresh nor the doomed 401 probe fire again
+ until the interval has elapsed.
"""
+ from hermes_cli.auth import _codex_quota_probe_cache
token, refresh = _stripped(access_token), _stripped(refresh_token)
if not token or not refresh or not _codex_access_token_is_expiring(token, 0):
return None
+ cache_key = _codex_quota_probe_cache_key(token)
+ now = time.monotonic()
+ with _codex_quota_probe_lock:
+ cached = _codex_quota_probe_cache.get(cache_key)
+ if cached is not None and (now - cached[0]) < min_interval_seconds:
+ return None
try:
return refresh_codex_oauth_pure(token, refresh)
except Exception:
logger.debug("Codex pre-probe token refresh failed", exc_info=True)
+ with _codex_quota_probe_lock:
+ _codex_quota_probe_cache[cache_key] = (now, None)
return None
diff --git a/tests/hermes_cli/test_auth_codex_quota_probe.py b/tests/hermes_cli/test_auth_codex_quota_probe.py
index 115cafc12db..461f6d8ee43 100644
--- a/tests/hermes_cli/test_auth_codex_quota_probe.py
+++ b/tests/hermes_cli/test_auth_codex_quota_probe.py
@@ -381,21 +381,61 @@ def test_resolver_refreshes_expired_token_before_probe(tmp_path, monkeypatch):
assert entry["last_status"] is None
-def test_resolver_keeps_cooldown_when_fresh_probe_still_exhausted(tmp_path, monkeypatch):
- """Control: refresh succeeds, live probe still says 100% -> cooldown stays, but the
- rotated (single-use) token pair is persisted so the grant is not burned."""
+def test_pool_selection_refreshes_expired_token_before_probe(tmp_path, monkeypatch):
+ """Control at the pool's hot selection path: refresh succeeds, live probe still says 100%
+ -> cooldown stays, the rotated (single-use) pair is what the probe used and it is persisted
+ on BOTH sides (pool row + ``providers.openai-codex`` singleton) so the next selection's
+ auth-store sync cannot re-adopt the consumed pair and lift the cooldown with it."""
now = time.time()
hermes_home = tmp_path / "hermes"
- _write_auth_store(hermes_home, _expired_jwt_pool_store(now))
+ store = _expired_jwt_pool_store(now)
+ stale = store["credential_pool"]["openai-codex"][0]
+ store["providers"]["openai-codex"] = {
+ "tokens": {"access_token": stale["access_token"], "refresh_token": "rf-old"}}
+ _write_auth_store(hermes_home, store)
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
fresh = _jwt({"exp": now + 3600})
- _fake_refresh(monkeypatch, fresh, [])
- _patch_expiry_aware_httpx(monkeypatch, _StubResponse(200, _usage_payload(0.0, 100.0)))
+ refresh_calls: list = []
+ _fake_refresh(monkeypatch, fresh, refresh_calls)
+ http_calls = _patch_expiry_aware_httpx(monkeypatch, _StubResponse(200, _usage_payload(0.0, 100.0)))
+ from agent.credential_pool import load_pool
- with pytest.raises(AuthError, match="quota exhausted"):
- resolve_codex_runtime_credentials()
+ pool = load_pool("openai-codex")
+
+ assert pool.select() is None
+ assert pool.select() is None # second pass: auth-store sync must not resurrect rf-old
+
+ assert refresh_calls == ["rf-old"]
+ assert [c["headers"]["Authorization"] for c in http_calls] == [f"Bearer {fresh}"]
+ entry = pool._entries[0]
+ assert (entry.access_token, entry.refresh_token, entry.last_status) == (fresh, "rf-new", "exhausted")
+ disk = json.loads((hermes_home / "auth.json").read_text())
+ assert disk["credential_pool"]["openai-codex"][0]["refresh_token"] == "rf-new"
+ assert disk["providers"]["openai-codex"]["tokens"]["refresh_token"] == "rf-new"
+
+
+def test_pool_selection_throttles_failing_pre_probe_refresh(tmp_path, monkeypatch):
+ """Regression control: a frozen entry whose refresh keeps failing (revoked grant, network
+ down) must not POST to the token endpoint on every selection — at most one attempt per
+ probe interval, the same budget the probe itself has (<= 1 network call per 5 min)."""
+ now = time.time()
+ hermes_home = tmp_path / "hermes"
+ _write_auth_store(hermes_home, _expired_jwt_pool_store(now))
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ attempts: list = []
+
+ def _failing_refresh(access_token, refresh_token, **kw):
+ attempts.append(refresh_token)
+ raise RuntimeError("invalid_grant")
+
+ monkeypatch.setattr(auth_codex, "refresh_codex_oauth_pure", _failing_refresh)
+ http_calls = _patch_expiry_aware_httpx(monkeypatch, _StubResponse(200, _usage_payload(0.0, 0.0)))
+ from agent.credential_pool import load_pool
+
+ pool = load_pool("openai-codex")
+ for _ in range(5):
+ assert pool.select() is None
+
+ assert attempts == ["rf-old"]
+ assert len(http_calls) <= 1
- entry = json.loads((hermes_home / "auth.json").read_text())["credential_pool"]["openai-codex"][0]
- assert entry["access_token"] == fresh
- assert entry["refresh_token"] == "rf-new"
- assert entry["last_status"] == "exhausted"