Skip to content

The agent that grows with you

fix(auth): leave a lock-free window between deferred refresh holds

Brooklyn Nicholsone89164233f17
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index cd64a15a1a7..6d25ab4d504 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -974,6 +974,12 @@ REFRESHABLE_OAUTH_PROVIDERS = frozenset({"anthropic", "nous", *_TOKENS_SINGLETON
# its refresh path serializes on its own auth-store lock (``_refresh_entry_impl`` nous branch).
_SINGLE_USE_REFRESH_PROVIDERS = ("openai-codex", "xai-oauth", "anthropic")
+# Lock-free window between consecutive auth-store holds in a deferred refresh sweep
+# (_refresh_pending_entries): a waiter with a shorter timeout (Desktop assistant start,
+# AUTH_LOCK_TIMEOUT_SECONDS = 15s) can acquire between two entries' holds instead of
+# starving behind the whole chain of single-use refreshes (#124533).
+_REFRESH_SWEEP_SPACING_SECONDS = 0.5
+
_REFRESH_TIMEOUT_ENV_VARS = {
"openai-codex": "HERMES_CODEX_REFRESH_TIMEOUT_SECONDS",
"xai-oauth": "HERMES_XAI_REFRESH_TIMEOUT_SECONDS",
@@ -2004,8 +2010,20 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
Each refresh takes the cross-process ``_auth_store_lock`` (20+ s
possible) and merges into the pool through the self-locking mutation
primitives; failures are silently skipped.
+
+ Entries are refreshed one at a time with a lock-free spacing window
+ between consecutive holds: ``_refresh_entry`` legitimately keeps the
+ store lock across its POST (single-use-token safety — sync -> POST ->
+ write-back must be atomic across processes), so a back-to-back chain
+ of N holds can starve a waiter on the same profile's auth.json whose
+ timeout is shorter (a Desktop assistant start, AUTH_LOCK_TIMEOUT_SECONDS
+ = 15s, vs the holder's max(15s, refresh_timeout + 5s)) for the whole
+ sweep (#124533). A short window between holds lets the waiter's
+ 50ms poll cadence interleave; the chain still finishes promptly.
"""
- for entry in pending:
+ for index, entry in enumerate(pending):
+ if index:
+ time.sleep(_REFRESH_SWEEP_SPACING_SECONDS)
self._refresh_entry(entry, force=False)
def _reset_cleared_after(self, entry: PooledCredential) -> Optional[float]:
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.py
index 70a13529ac4..4e4937f9e3e 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -622,7 +622,7 @@ def _lock_holder_hint(lock_path: Path) -> str:
Holders stamp their pid on acquire and clear it on release, so a leftover pid from a dead
process is filtered by a liveness probe — stay silent instead of blaming a ghost."""
try:
- first_token = lock_path.read_text(encoding="utf-8", errors="replace").split()[0]
+ first_token = lock_path.read_text(encoding="utf-8-sig", errors="replace").split()[0]
pid = int(first_token)
except (OSError, ValueError, IndexError):
return ""
@@ -630,7 +630,7 @@ def _lock_holder_hint(lock_path: Path) -> str:
return ""
if os.name == "posix":
try:
- os.kill(pid, 0) # existence probe only; on Windows sig 0 would terminate the process
+ os.kill(pid, 0) # windows-footgun: ok — inside `if os.name == "posix"` gate
except ProcessLookupError:
return ""
except OSError:
diff --git a/tests/agent/test_credential_pool_refresh_sweep_spacing.py b/tests/agent/test_credential_pool_refresh_sweep_spacing.py
new file mode 100644
index 00000000000..b486e123c7d
--- /dev/null
+++ b/tests/agent/test_credential_pool_refresh_sweep_spacing.py
@@ -0,0 +1,44 @@
+"""A multi-entry deferred refresh sweep must leave waiter windows between holds (#124533).
+
+``_refresh_entry`` legitimately holds the cross-process auth-store lock across its refresh POST
+(single-use-token safety is test-pinned), but ``_refresh_pending_entries`` used to chain N holds
+back-to-back, so a waiter with a shorter timeout (a Desktop assistant start waiting on the same
+profile auth.json, AUTH_LOCK_TIMEOUT_SECONDS = 15s) starved behind the whole chain. The sweep must
+leave a bounded lock-free window between consecutive holds so a waiter can interleave.
+"""
+
+from __future__ import annotations
+
+import time
+
+import hermes_cli.auth as auth
+from agent.credential_pool import CredentialPool
+
+
+def test_pending_refresh_sweep_leaves_waiter_windows_between_holds(tmp_path):
+ auth_path = tmp_path / "profiles" / "coder" / "auth.json"
+ auth_path.parent.mkdir(parents=True)
+
+ pool = object.__new__(CredentialPool)
+ hold_events = []
+
+ def fake_refresh(entry, *, force):
+ # Same shape as a real single-use refresh: the cross-process lock is held
+ # across the "POST" (the sleep), released only when the entry is done.
+ with auth._auth_store_lock(timeout_seconds=30.0, target_path=auth_path):
+ hold_events.append(("acquired", time.monotonic()))
+ time.sleep(0.05)
+ hold_events.append(("released", time.monotonic()))
+
+ pool._refresh_entry = fake_refresh
+ CredentialPool._refresh_pending_entries(pool, [object(), object(), object()])
+
+ acquires = [t for kind, t in hold_events if kind == "acquired"]
+ releases = [t for kind, t in hold_events if kind == "released"]
+ assert len(acquires) == 3 # every entry refreshed
+ inter_hold_windows = [a - r for r, a in zip(releases, acquires[1:])]
+ # A waiter polling every 50ms (the _file_lock retry cadence) must get a real
+ # window between two consecutive holds of the sweep, not a scheduling artifact.
+ assert max(inter_hold_windows) >= 0.4, (
+ f"deferred refresh sweep left no waiter window between holds: {inter_hold_windows}"
+ )