Skip to content

The agent that grows with you

fix(auth): concurrent Nous 401 recovery adopts a peer's refresh instead of re-rotating the shared grant

Teknium3312947e1427
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 2d8768d60bb..df2f1fdd80a 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -1962,11 +1962,19 @@ class CredentialPool:
last_refresh=refreshed.get("last_refresh"),
)
elif self.provider == "nous":
+ stale_key = entry.runtime_api_key or entry.agent_key or entry.access_token
synced = self._sync_nous_entry_from_auth_store(entry)
if synced is not entry:
entry = synced
+ # A peer already rotated and persisted a usable key while
+ # this process was still holding the failed one: adopt it
+ # without consuming the (single-use) refresh token again.
+ if force and entry.runtime_api_key and entry.runtime_api_key != stale_key:
+ logger.debug("Nous entry %s: adopting peer-rotated token, skipping refresh", entry.id)
+ return entry
auth_mod.resolve_nous_runtime_credentials(
force_refresh=force,
+ stale_access_token=stale_key or None,
)
updated = self._sync_nous_entry_from_auth_store(entry)
else:
@@ -2217,6 +2225,15 @@ class CredentialPool:
self._persist()
self._sync_device_code_entry_to_auth_store(updated)
return updated
+ if isinstance(exc, TimeoutError):
+ # Lost the auth-store lock race under heavy fan-out. That
+ # says nothing about the credential — benching it here is
+ # what emptied the pool for ~120 sessions on Sep 2 2026
+ # ("matched no nous entry ... pool size 0"). Leave the
+ # entry untouched; the caller's retry re-syncs once the
+ # winner has persisted.
+ logger.debug("Nous refresh skipped: auth store lock busy; not benching entry")
+ return entry
if auth_mod._is_terminal_nous_refresh_error(exc):
logger.debug("Nous refresh token is terminally invalid; clearing local token state")
try:
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.py
index 1f056199a70..d2935755192 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -7018,6 +7018,7 @@ def resolve_nous_runtime_credentials(
insecure: Optional[bool] = None,
ca_bundle: Optional[str] = None,
force_refresh: bool = False,
+ stale_access_token: Optional[str] = None,
) -> Dict[str, Any]:
"""
Resolve Nous inference credentials for runtime use.
@@ -7025,8 +7026,14 @@ def resolve_nous_runtime_credentials(
Ensures access_token is a valid inference-scoped JWT, refreshing it when
needed. Concurrent processes coordinate through the auth store file lock.
- Returns dict with: provider, base_url, api_key, key_id, expires_at,
- expires_in, source ("invoke_jwt"), and auth_path.
+ ``stale_access_token`` is the bearer that just failed upstream (401). When
+ set together with ``force_refresh``, the refresh POST is skipped if the
+ store — re-read under the lock — already holds a *different*, usable
+ token: another process won the rotation, so this caller adopts it
+ instead of rotating the shared grant again. Without this, N concurrent
+ processes hitting the same hourly expiry issue N refreshes, and each
+ rotation invalidates the token a sibling just adopted (Sep 2026: 120
+ subagents, 81 refreshes, ~540 401s in eight minutes).
"""
sequence_id = uuid.uuid4().hex[:12]
@@ -7040,6 +7047,20 @@ def resolve_nous_runtime_credentials(
raise AuthError("Hermes is not logged into Nous Portal.",
provider="nous", relogin_required=True)
+ def _already_rotated_by_peer(token: Any) -> bool:
+ return bool(
+ force_refresh
+ and stale_access_token
+ and isinstance(token, str)
+ and token
+ and token != stale_access_token
+ and _nous_invoke_jwt_status(
+ token,
+ scope=state.get("scope"),
+ expires_at=state.get("expires_at"),
+ ) is None
+ )
+
persisted_state = dict(state)
state_persisted = False
@@ -7185,6 +7206,16 @@ def resolve_nous_runtime_credentials(
scope=state.get("scope"),
expires_at=state.get("expires_at"),
)
+ # Under the store lock: if the bearer that failed upstream is no
+ # longer the one on disk and the on-disk one is usable, a peer
+ # already rotated — adopt, never re-POST the shared grant.
+ if _already_rotated_by_peer(access_token):
+ _oauth_trace(
+ "refresh_skipped_peer_rotated",
+ sequence_id=sequence_id,
+ access_token_fp=_token_fingerprint(access_token),
+ )
+ force_refresh = False
if force_refresh or invoke_jwt_status is not None:
with _nous_shared_store_lock(timeout_seconds=max(timeout_seconds + 5.0, AUTH_LOCK_TIMEOUT_SECONDS)):
if _merge_shared_nous_oauth_state(state):
@@ -7202,6 +7233,13 @@ def resolve_nous_runtime_credentials(
expires_at=state.get("expires_at"),
)
_persist_state("post_shared_merge_access_unusable")
+ if _already_rotated_by_peer(access_token):
+ _oauth_trace(
+ "refresh_skipped_peer_rotated",
+ sequence_id=sequence_id,
+ access_token_fp=_token_fingerprint(access_token),
+ )
+ force_refresh = False
if force_refresh or invoke_jwt_status is not None:
if not isinstance(refresh_token, str) or not refresh_token:
diff --git a/tests/agent/test_credential_pool_nous_refresh_stampede.py b/tests/agent/test_credential_pool_nous_refresh_stampede.py
new file mode 100644
index 00000000000..fa328fa4a94
--- /dev/null
+++ b/tests/agent/test_credential_pool_nous_refresh_stampede.py
@@ -0,0 +1,101 @@
+"""Concurrent Nous 401 recovery must not stampede the shared OAuth grant.
+
+Sep 2 2026 incident: ~120 subagent processes shared one Nous OAuth pool entry
+whose access token hit its hourly expiry. Every process got a 401, every
+process force-refreshed, and each rotation invalidated the token a sibling had
+just adopted — 81 refreshes and ~540 401s in eight minutes. Processes that
+lost the auth-store flock race had their only entry benched ("matched no nous
+entry ... pool size 0") and surfaced the 401 to the user as "out of funds".
+
+Two invariants pinned here:
+
+1. ``resolve_nous_runtime_credentials(force_refresh=True, stale_access_token=X)``
+ does NOT POST a refresh when the store already holds a usable token that
+ is not X — a peer already rotated; adopt it.
+2. A lock-timeout during a pool-level Nous refresh leaves the entry
+ untouched instead of marking it exhausted.
+"""
+
+import json
+import logging
+
+import hermes_cli.auth as auth_mod
+from agent.credential_pool import CredentialPool, PooledCredential
+
+from tests.hermes_cli.test_auth_nous_provider import _invoke_jwt, _setup_nous_auth
+
+
+def test_forced_refresh_adopts_peer_rotation_instead_of_reposting(tmp_path, monkeypatch):
+ hermes_home = tmp_path / "hermes"
+ peer_token = _invoke_jwt(seconds=3600)
+ failed_token = _invoke_jwt(seconds=3000) # what THIS process still holds
+ _setup_nous_auth(
+ hermes_home,
+ access_token=peer_token,
+ refresh_token="rt-after-peer-rotation",
+ scope=auth_mod.DEFAULT_NOUS_SCOPE,
+ expires_at=auth_mod.datetime.fromtimestamp(
+ auth_mod.time.time() + 3600, tz=auth_mod.timezone.utc
+ ).isoformat(),
+ expires_in=3600,
+ )
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+
+ posts = []
+
+ def _fake_refresh_access_token(*, client, portal_base_url, client_id, refresh_token):
+ posts.append(refresh_token)
+ return {
+ "access_token": _invoke_jwt(seconds=7200),
+ "refresh_token": "rt-should-not-happen",
+ "expires_in": 7200,
+ "token_type": "Bearer",
+ "scope": auth_mod.DEFAULT_NOUS_SCOPE,
+ }
+
+ monkeypatch.setattr(auth_mod, "_refresh_access_token", _fake_refresh_access_token)
+
+ creds = auth_mod.resolve_nous_runtime_credentials(
+ force_refresh=True, stale_access_token=failed_token
+ )
+
+ assert posts == [], "peer already rotated — must not consume the refresh token again"
+ assert creds["api_key"] == peer_token
+
+ # Same call WITHOUT the hint keeps the pre-existing force semantics.
+ auth_mod.resolve_nous_runtime_credentials(force_refresh=True)
+ assert posts == ["rt-after-peer-rotation"]
+
+
+def test_lock_timeout_during_nous_refresh_does_not_bench_entry(monkeypatch, caplog):
+ entry = PooledCredential(
+ id="267aed",
+ provider="nous",
+ auth_type="oauth",
+ access_token=_invoke_jwt(seconds=3600),
+ refresh_token="rt",
+ label="test@nous",
+ source="device_code",
+ priority=0,
+ )
+ pool = CredentialPool.__new__(CredentialPool)
+ pool._lock = __import__("threading").RLock()
+ pool._entries = [entry]
+ pool._active_leases = {}
+ pool._current_id = None
+ pool._max_concurrent = 2
+ pool._unmatched_rotation_streak = 0
+ pool.provider = "nous"
+
+ monkeypatch.setattr(pool, "_sync_nous_entry_from_auth_store", lambda e: e)
+ monkeypatch.setattr(pool, "_persist", lambda *a, **k: None)
+
+ def _busy(*a, **k):
+ raise TimeoutError("Timed out waiting for auth store lock")
+
+ monkeypatch.setattr(auth_mod, "resolve_nous_runtime_credentials", _busy)
+
+ result = pool._refresh_entry_impl(entry, force=True)
+
+ assert result is entry
+ assert pool._entries[0].last_status is None, "lock contention is not a credential failure"
diff --git a/website/docs/user-guide/features/credential-pools.md b/website/docs/user-guide/features/credential-pools.md
index f66f2a624a9..05c0e988b61 100644
--- a/website/docs/user-guide/features/credential-pools.md
+++ b/website/docs/user-guide/features/credential-pools.md
@@ -208,6 +208,8 @@ This means subagents benefit from the same rate-limit resilience as the parent,
The credential pool uses a threading lock for all state mutations (`select()`, `mark_exhausted_and_rotate()`, `try_refresh_current()`, `mark_used()`). This ensures safe concurrent access when the gateway handles multiple chat sessions simultaneously.
+Across processes (many subagents, a gateway plus a CLI, cron jobs), OAuth refreshes are serialized through a file lock on `auth.json`. When one shared OAuth grant expires under many concurrent processes, exactly one process performs the refresh; the others detect that the on-disk token no longer matches the one that failed and adopt it instead of rotating the single-use refresh token again. A process that loses the lock race keeps its entry healthy and retries — lock contention is never recorded as a credential failure.
+
## Architecture
For the full data flow diagram, see [`docs/credential-pool-flow.excalidraw`](https://excalidraw.com/#json=2Ycqhqpi6f12E_3ITyiwh,c7u9jSt5BwrmiVzHGbm87g) in the repository.