Skip to content

The agent that grows with you

fix(credential_pool): defer single-use-token refresh outside threading lock

dsad9cd605f30321
diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.py
index 5a9ad164683..9ba37bd39b3 100644
--- a/agent/anthropic_adapter.py
+++ b/agent/anthropic_adapter.py
@@ -1334,7 +1334,7 @@ def _resolve_anthropic_pool_token() -> Optional[str]:
# to auth.json or trigger a network refresh from a bare resolve. select()
# is deliberately NOT used — it runs clear_expired=True, refresh=True,
# which would violate this read-only contract.
- entries = pool._available_entries(clear_expired=False, refresh=False)
+ entries, _pending = pool._available_entries(clear_expired=False, refresh=False)
except Exception:
logger.debug("Failed to read Anthropic credential_pool", exc_info=True)
return None
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 5841cab5e00..e1abb2db482 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -618,7 +618,8 @@ class CredentialPool:
# otherwise a status probe here can race a concurrent ``select`` /
# rotation and tear ``self._entries`` or double-write auth.json.
with self._lock:
- return bool(self._available_entries())
+ available, _pending = self._available_entries()
+ return bool(available)
def next_available_at(self) -> Optional[float]:
"""Earliest epoch time (seconds) any entry re-enters rotation.
@@ -1673,26 +1674,61 @@ class CredentialPool:
return False
def select(self) -> Optional[PooledCredential]:
- with self._lock:
- entry = self._select_unlocked()
+ entry, pending_refresh = self._select_under_lock()
+ if pending_refresh:
+ self._refresh_pending_entries(pending_refresh)
+ if entry is not None:
+ self._unmatched_rotation_streak = 0
+ return entry
+ # If no entry was available but we just refreshed some, re-select
+ # now that the refreshed entries are back in the pool.
+ if pending_refresh:
+ entry, _ = self._select_under_lock()
if entry is not None:
- # A normal (non-recovery) selection starts a fresh episode —
- # don't let a leftover unmatched-rotation streak from an old
- # failure trip the #70401 bound early next time.
self._unmatched_rotation_streak = 0
- return entry
+ return entry
+
+ def _select_under_lock(self) -> Tuple[Optional[PooledCredential], List[tuple]]:
+ """Run selection under the lock, returning entry + pending refreshes."""
+ with self._lock:
+ return self._select_unlocked()
+
+ def _refresh_pending_entries(self, pending: List[tuple]) -> None:
+ """Refresh deferred single-use-token entries outside the lock.
+
+ Each entry is refreshed under the cross-process ``_auth_store_lock``
+ (which can block for 20+ seconds) and then merged into the pool.
+ On failure the entry is silently skipped.
+ """
+ for entry, sync_fn in pending:
+ refreshed = self._refresh_entry(entry, force=False)
+ if refreshed is not None:
+ with self._lock:
+ self._replace_entry(entry, refreshed)
- def _available_entries(self, *, clear_expired: bool = False, refresh: bool = False) -> List[PooledCredential]:
- """Return entries not currently in exhaustion cooldown.
+ def _available_entries(
+ self, *, clear_expired: bool = False, refresh: bool = False,
+ ) -> Tuple[List[PooledCredential], List[tuple]]:
+ """Return (available, pending_refresh) for entries not in cooldown.
When *clear_expired* is True, entries whose cooldown has elapsed are
reset to STATUS_OK and persisted. When *refresh* is True, entries
that need a token refresh are refreshed (skipped on failure).
+
+ Single-use-token refreshes (openai-codex, xai-oauth) are returned as
+ *pending_refresh* tuples so the caller can execute them outside the
+ lock, avoiding stalling all pool consumers during cross-process flock
+ acquisition + OAuth network I/O.
"""
now = time.time()
cleared_any = False
entries_to_prune: List[str] = []
available: List[PooledCredential] = []
+ # Entries that need an OAuth refresh via a single-use token provider
+ # (openai-codex, xai-oauth). These require a cross-process file lock
+ # 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)
for entry in self._entries:
# Borrowed credentials persist as metadata-only references and are
# hydrated from their live source on load. A stale duplicate row
@@ -1801,6 +1837,16 @@ class CredentialPool:
entry = cleared
cleared_any = True
if refresh and self._entry_needs_refresh(entry):
+ if self.provider in ("openai-codex", "xai-oauth"):
+ # Defer single-use-token refresh to avoid holding the
+ # threading lock during cross-process flock + network I/O.
+ sync_fn = (
+ self._sync_codex_entry_from_auth_store
+ if self.provider == "openai-codex"
+ else self._sync_xai_oauth_entry_from_pool_store
+ )
+ pending_refresh.append((entry, sync_fn))
+ continue
refreshed = self._refresh_entry(entry, force=False)
if refreshed is None:
continue
@@ -1811,7 +1857,7 @@ class CredentialPool:
self._entries = [e for e in self._entries if e.id not in pruned_ids]
if cleared_any:
self._persist(removed_ids=entries_to_prune)
- return available
+ return available, pending_refresh
def _log_no_available_entries(self) -> None:
"""Emit the empty-pool INFO line at most once per throttle window.
@@ -1827,12 +1873,17 @@ class CredentialPool:
self._last_no_entries_log_at = now
logger.info("credential pool: no available entries (all exhausted or empty)")
- def _select_unlocked(self, *, refresh: bool = True) -> Optional[PooledCredential]:
- available = self._available_entries(clear_expired=True, refresh=refresh)
+ def _select_unlocked(self, *, refresh: bool = True) -> Tuple[Optional[PooledCredential], List[tuple]]:
+ """Select the best available credential entry.
+
+ Returns ``(entry, pending_refresh)`` where *pending_refresh* contains
+ single-use-token entries that must be refreshed outside the lock.
+ """
+ available, pending_refresh = self._available_entries(clear_expired=True, refresh=refresh)
if not available:
self._current_id = None
self._log_no_available_entries()
- return None
+ return None, pending_refresh
# A successful selection means the pool recovered; re-arm the throttle
# so a later re-exhaustion logs immediately rather than being silenced
@@ -1842,7 +1893,7 @@ class CredentialPool:
if self._strategy == STRATEGY_RANDOM:
entry = random.choice(available)
self._current_id = entry.id
- return entry
+ return entry, pending_refresh
if self._strategy == STRATEGY_LEAST_USED and len(available) > 1:
entry = min(available, key=lambda e: e.request_count)
@@ -1850,7 +1901,7 @@ class CredentialPool:
updated = replace(entry, request_count=entry.request_count + 1)
self._replace_entry(entry, updated)
self._current_id = entry.id
- return updated
+ return updated, pending_refresh
if self._strategy == STRATEGY_ROUND_ROBIN and len(available) > 1:
entry = available[0]
@@ -1859,11 +1910,11 @@ class CredentialPool:
self._entries = [replace(candidate, priority=idx) for idx, candidate in enumerate(rotated)]
self._persist()
self._current_id = entry.id
- return self._current_unlocked() or entry
+ return self._current_unlocked() or entry, pending_refresh
entry = available[0]
self._current_id = entry.id
- return entry
+ return entry, pending_refresh
def peek(self) -> Optional[PooledCredential]:
# Single lock acquisition for the whole read; call the unlocked
@@ -1872,7 +1923,7 @@ class CredentialPool:
current = self._current_unlocked()
if current is not None:
return current
- available = self._available_entries()
+ available, _pending = self._available_entries()
return available[0] if available else None
def mark_exhausted_and_rotate(
@@ -1921,7 +1972,8 @@ class CredentialPool:
# guessing and surface the error (no cooldown is written for
# anybody — healthy keys stay available for the next turn).
self._unmatched_rotation_streak += 1
- available_count = len(self._available_entries())
+ available_count, _ = self._available_entries()
+ available_count = len(available_count)
if self._unmatched_rotation_streak > max(available_count, 1):
logger.warning(
"credential pool: failed credential identity matched no "
@@ -1940,8 +1992,9 @@ class CredentialPool:
self.provider,
)
self._current_id = None
- next_entry = self._select_unlocked()
- if next_entry is not None and len(self._available_entries()) == 1:
+ next_entry, _pending = self._select_unlocked(refresh=False)
+ avail, _ = self._available_entries()
+ if next_entry is not None and len(avail) == 1:
# A single-entry pool cannot rotate. Returning its only
# entry reports a successful recovery without changing
# the credential, so the caller retries the same 401
@@ -1954,7 +2007,7 @@ class CredentialPool:
# streak is stale (this mark WILL advance pool state).
self._unmatched_rotation_streak = 0
if entry is None:
- entry = self._current_unlocked() or self._select_unlocked()
+ entry = self._current_unlocked() or self._select_unlocked(refresh=False)[0]
if entry is None:
return None
_label = entry.label or entry.id[:8]
@@ -1999,7 +2052,7 @@ class CredentialPool:
_label, status_code,
)
self._current_id = None
- next_entry = self._select_unlocked()
+ next_entry, _pending = self._select_unlocked(refresh=False)
if next_entry:
_next_label = next_entry.label or next_entry.id[:8]
logger.info("credential pool: rotated to %s", _next_label)
@@ -2013,15 +2066,24 @@ class CredentialPool:
a stable tie-breaker. When every credential is already at the soft cap,
still return the least-leased one instead of blocking.
"""
+ chosen_id, pending_refresh = self._acquire_lease_under_lock(credential_id)
+ if pending_refresh:
+ self._refresh_pending_entries(pending_refresh)
+ return chosen_id
+
+ def _acquire_lease_under_lock(
+ self, credential_id: Optional[str],
+ ) -> Tuple[Optional[str], List[tuple]]:
+ """Run lease acquisition under the lock, returning id + pending refreshes."""
with self._lock:
if credential_id:
self._active_leases[credential_id] = self._active_leases.get(credential_id, 0) + 1
self._current_id = credential_id
- return credential_id
+ return credential_id, []
- available = self._available_entries(clear_expired=True, refresh=True)
+ available, pending_refresh = self._available_entries(clear_expired=True, refresh=True)
if not available:
- return None
+ return None, pending_refresh
below_cap = [
entry for entry in available
@@ -2034,7 +2096,7 @@ class CredentialPool:
)
self._active_leases[chosen.id] = self._active_leases.get(chosen.id, 0) + 1
self._current_id = chosen.id
- return chosen.id
+ return chosen.id, pending_refresh
def release_lease(self, credential_id: str) -> None:
"""Release a previously acquired credential lease."""
@@ -2086,7 +2148,7 @@ class CredentialPool:
else:
entry = self._current_unlocked() or self._select_unlocked(
refresh=False
- )
+ )[0]
if entry is None:
return None
self._current_id = entry.id
diff --git a/tests/agent/test_anthropic_adapter.py b/tests/agent/test_anthropic_adapter.py
index 876f9b77aed..cad2d371ab3 100644
--- a/tests/agent/test_anthropic_adapter.py
+++ b/tests/agent/test_anthropic_adapter.py
@@ -239,7 +239,7 @@ class TestResolveAnthropicToken:
access_token="pool-oauth-token",
)
pool = SimpleNamespace(
- _available_entries=lambda **_kwargs: [pool_entry],
+ _available_entries=lambda **_kwargs: ([pool_entry], []),
)
monkeypatch.setattr("agent.credential_pool.load_pool", lambda provider: pool)
@@ -260,7 +260,7 @@ class TestResolveAnthropicToken:
access_token="pool-oauth-token",
)
pool = SimpleNamespace(
- _available_entries=lambda **_kwargs: [pool_entry],
+ _available_entries=lambda **_kwargs: ([pool_entry], []),
)
monkeypatch.setattr("agent.credential_pool.load_pool", lambda provider: pool)
@@ -279,7 +279,7 @@ class TestResolveAnthropicToken:
broken_entry = SimpleNamespace(auth_type="oauth", access_token=None)
pool = SimpleNamespace(
- _available_entries=lambda **_kwargs: [broken_entry],
+ _available_entries=lambda **_kwargs: ([broken_entry], []),
)
monkeypatch.setattr("agent.credential_pool.load_pool", lambda provider: pool)
@@ -299,7 +299,7 @@ class TestResolveAnthropicToken:
api_key_entry = SimpleNamespace(auth_type="api_key", access_token="sk-pool-apikey")
pool = SimpleNamespace(
- _available_entries=lambda **_kwargs: [api_key_entry],
+ _available_entries=lambda **_kwargs: ([api_key_entry], []),
)
monkeypatch.setattr("agent.credential_pool.load_pool", lambda provider: pool)
@@ -322,7 +322,7 @@ class TestResolveAnthropicToken:
def _available_entries(**kwargs):
captured.update(kwargs)
- return [pool_entry]
+ return ([pool_entry], [])
pool = SimpleNamespace(_available_entries=_available_entries)
monkeypatch.setattr("agent.credential_pool.load_pool", lambda provider: pool)