Skip to content

The agent that grows with you

fix(aux): cached auxiliary client follows the pooled credential after rotation

teknium13fe9e8ff0fe9
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 3f64241cdb4..c5b56d0ac72 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -993,9 +993,13 @@ def _select_pool_entry(provider: str) -> Tuple[bool, Optional[Any]]:
return True, None
-def _peek_pool_entry(provider: str) -> Optional[Any]:
- """Best-effort current/next pool entry without mutating selection order."""
- pool = _load_pool_with_credentials(provider, " (peek)")
+def _peek_pool_entry(provider: str, pool: Any = None) -> Optional[Any]:
+ """Best-effort current/next pool entry without mutating selection order.
+
+ ``pool`` skips the disk re-read when the caller already loaded it.
+ """
+ if pool is None:
+ pool = _load_pool_with_credentials(provider, " (peek)")
if pool is None:
return None
try:
@@ -3391,19 +3395,52 @@ def _evict_cached_client_instance(target: Any) -> bool:
return evicted
+def _pool_credential_digest(pool: Any) -> str:
+ """Secret-safe digest over the runtime keys of every pool entry.
+
+ Taken WITHOUT availability filters (``pool.entries()``, not ``peek()``): an entry benched by a
+ per-model cooldown still contributes, so a token rotated while the cooldown is active changes
+ the digest too (#113022 point 5). Only the blake2b of the keys enters the cache key.
+ """
+ try:
+ entries_fn = getattr(pool, "entries", None)
+ entries = entries_fn() if callable(entries_fn) else []
+ except Exception as exc:
+ logger.debug("Auxiliary client: could not list pool entries for digest: %s", exc)
+ return ""
+ keys = sorted(k for k in (_pool_runtime_api_key(e) for e in entries or ()) if k)
+ if not keys:
+ return ""
+ digest = hashlib.blake2b(digest_size=16)
+ for key in keys:
+ digest.update(key.encode("utf-8"))
+ digest.update(b"\0")
+ return digest.hexdigest()
+
+
def _pool_cache_hint(provider: str, *, main_runtime: Optional[Dict[str, Any]] = None) -> str:
- """Return a stable cache discriminator for pooled providers."""
+ """Return a cache discriminator that follows the pooled credential, not just its entry id.
+
+ ``<provider>:<entry id>:<digest>`` when ``peek()`` names an entry, ``<provider>::<digest>``
+ when every entry is filtered out (cooldown) but keyed entries exist. A token rotated or
+ refreshed by another process yields a new client instead of a 401 round trip on the cached
+ one; the stale entry ages out through the non-closing FIFO cap (#113022).
+ """
normalized = _normalize_aux_provider(provider)
if normalized == "auto":
runtime = _normalize_main_runtime(main_runtime)
normalized = _normalize_aux_provider(runtime.get("provider") or _read_main_provider())
if normalized in {"", "auto", "custom"}:
return ""
- entry = _peek_pool_entry(normalized)
- if entry is None:
+ pool = _load_pool_with_credentials(normalized, " (cache hint)")
+ if pool is None:
+ return ""
+ digest = _pool_credential_digest(pool)
+ entry = _peek_pool_entry(normalized, pool)
+ entry_id = str(getattr(entry, "id", "") or "").strip() if entry is not None else ""
+ if not entry_id and not digest:
return ""
- entry_id = str(getattr(entry, "id", "") or "").strip()
- return f"{normalized}:{entry_id}" if entry_id else ""
+ return f"{normalized}:{entry_id}:{digest}"
# Ordered (host, provider) tables for inferring a backend from a client base URL.
diff --git a/tests/agent/test_async_httpx_del_neuter.py b/tests/agent/test_async_httpx_del_neuter.py
index 1583d94fbf7..c6213116029 100644
--- a/tests/agent/test_async_httpx_del_neuter.py
+++ b/tests/agent/test_async_httpx_del_neuter.py
@@ -81,6 +81,7 @@ class TestCleanupStaleAsyncClients:
"""Entries with a closed loop should be evicted."""
from agent.auxiliary_client import (
_client_cache,
+ _client_cache_key,
_client_cache_lock,
cleanup_stale_async_clients,
)
@@ -94,7 +95,7 @@ class TestCleanupStaleAsyncClients:
mock_client._client = MagicMock()
mock_client._client.is_closed = False
- key = ("test_stale", True, "", "", "", (), False)
+ key = _client_cache_key("test_stale", async_mode=True)
with _client_cache_lock:
_client_cache[key] = (mock_client, "test-model", loop)
@@ -347,6 +348,7 @@ class TestClientCacheBoundedGrowth:
"""Cache should not exceed _CLIENT_CACHE_MAX_SIZE."""
from agent.auxiliary_client import (
_client_cache,
+ _client_cache_key,
_client_cache_lock,
_CLIENT_CACHE_MAX_SIZE,
)
@@ -356,13 +358,16 @@ class TestClientCacheBoundedGrowth:
saved = dict(_client_cache)
_client_cache.clear()
+ def key_for(i: int) -> tuple:
+ return _client_cache_key(f"evict_test_{i}", async_mode=False)
+
try:
# Fill to max + 5
for i in range(_CLIENT_CACHE_MAX_SIZE + 5):
mock_client = MagicMock()
mock_client._client = MagicMock()
mock_client._client.is_closed = False
- key = (f"evict_test_{i}", False, "", "", "", (), False)
+ key = key_for(i)
with _client_cache_lock:
# Inline the eviction logic (same as _get_cached_client)
while len(_client_cache) >= _CLIENT_CACHE_MAX_SIZE:
@@ -374,9 +379,9 @@ class TestClientCacheBoundedGrowth:
assert len(_client_cache) <= _CLIENT_CACHE_MAX_SIZE, \
f"Cache size {len(_client_cache)} exceeds max {_CLIENT_CACHE_MAX_SIZE}"
# The earliest entries should have been evicted
- assert ("evict_test_0", False, "", "", "", (), False) not in _client_cache
+ assert key_for(0) not in _client_cache
# The latest entries should be present
- assert (f"evict_test_{_CLIENT_CACHE_MAX_SIZE + 4}", False, "", "", "", (), False) in _client_cache
+ assert key_for(_CLIENT_CACHE_MAX_SIZE + 4) in _client_cache
finally:
with _client_cache_lock:
_client_cache.clear()
diff --git a/tests/agent/test_auxiliary_client_cache_follows_credential.py b/tests/agent/test_auxiliary_client_cache_follows_credential.py
new file mode 100644
index 00000000000..36c0eefae6f
--- /dev/null
+++ b/tests/agent/test_auxiliary_client_cache_follows_credential.py
@@ -0,0 +1,59 @@
+"""Regression coverage: the auxiliary client cache key follows the pooled credential (#113022).
+
+Points 1/2/5 of the issue: a token rotated or refreshed by another process must yield a new
+client instead of a 401 round trip on the cached one, including while a per-model cooldown
+hides the entry from ``peek()``.
+"""
+
+import time
+
+import pytest
+
+import agent.auxiliary_client as aux
+from hermes_cli.auth import write_credential_pool
+
+MODEL = "claude-sonnet-4-5"
+
+
+def _seed(provider: str, token: str, *, model_cooldown: str | None = None) -> None:
+ row = {
+ "id": "entry-1", "label": "pooled", "auth_type": "oauth", "priority": 1, "source": "manual",
+ "access_token": token, "refresh_token": f"rt-{token}", "expires_at": time.time() + 3600,
+ }
+ if model_cooldown:
+ row["model_cooldowns"] = {model_cooldown: time.time() + 600}
+ write_credential_pool(provider, [row])
+
+
+def isolated_home(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
+ monkeypatch.setattr(aux, "_client_cache", {})
+ return tmp_path / "hermes"
+
+
[email protected]("provider", ["anthropic", "openai-codex"])
+def test_pool_token_rotation_changes_cache_key_and_hides_the_secret(isolated_home, provider):
+ """Same entry id, new token -> different key; the token itself never enters the key."""
+ _seed(provider, "tok-old")
+ before = aux._client_cache_key(provider, async_mode=False, model=MODEL)
+ _seed(provider, "tok-new")
+ after = aux._client_cache_key(provider, async_mode=False, model=MODEL)
+
+ assert before != after
+ flat = repr(before) + repr(after)
+ assert "tok-old" not in flat and "tok-new" not in flat
+ # unchanged credentials still hit the same entry (control)
+ assert aux._client_cache_key(provider, async_mode=False, model=MODEL) == after
+
+
+def test_pool_cache_hint_follows_rotation_during_per_model_cooldown(isolated_home):
+ """A per-model cooldown hides the entry from peek(); the hint must still track the token."""
+ _seed("anthropic", "tok-old", model_cooldown=MODEL)
+ before = aux._pool_cache_hint("anthropic")
+ _seed("anthropic", "tok-new", model_cooldown=MODEL)
+ after = aux._pool_cache_hint("anthropic")
+
+ assert before.startswith("anthropic::") and after.startswith("anthropic::")
+ assert before != after
+ assert "tok-" not in before + after