Skip to content

The agent that grows with you

fix: digest only the peeked entry's key in the aux client cache hint

teknium17d57fbfca978
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index c5b56d0ac72..4d8ac341b4b 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -3395,20 +3395,24 @@ 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.
+def _pool_credential_digest(pool: Any, entry: Any = None) -> str:
+ """Secret-safe digest over the runtime key(s) backing the cache hint.
+
+ When ``entry`` (the peeked selection) carries a key, only THAT key is digested: rotating a
+ sibling account must not churn this entry's cached client. Otherwise every pool entry
+ contributes, taken WITHOUT availability filters (``pool.entries()``, not ``peek()``): an entry
+ benched by a per-model cooldown still counts, 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)
+ keys = [k for k in (_pool_runtime_api_key(entry),) if k] if entry is not None else []
+ if not keys:
+ 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)
@@ -3421,8 +3425,9 @@ def _pool_credential_digest(pool: Any) -> str:
def _pool_cache_hint(provider: str, *, main_runtime: Optional[Dict[str, Any]] = None) -> str:
"""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
+ ``<provider>:<entry id>:<digest of that entry's key>`` when ``peek()`` names an entry,
+ ``<provider>::<digest of every entry's key>`` 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).
"""
@@ -3435,8 +3440,8 @@ def _pool_cache_hint(provider: str, *, main_runtime: Optional[Dict[str, Any]] =
pool = _load_pool_with_credentials(normalized, " (cache hint)")
if pool is None:
return ""
- digest = _pool_credential_digest(pool)
entry = _peek_pool_entry(normalized, pool)
+ digest = _pool_credential_digest(pool, entry)
entry_id = str(getattr(entry, "id", "") or "").strip() if entry is not None else ""
if not entry_id and not digest:
return ""
diff --git a/tests/agent/test_async_httpx_del_neuter.py b/tests/agent/test_async_httpx_del_neuter.py
index c6213116029..12d2f7f1961 100644
--- a/tests/agent/test_async_httpx_del_neuter.py
+++ b/tests/agent/test_async_httpx_del_neuter.py
@@ -112,6 +112,7 @@ class TestCleanupStaleAsyncClients:
def test_awaits_async_close_for_closed_loop(self):
from agent.auxiliary_client import (
_client_cache,
+ _client_cache_key,
_client_cache_lock,
cleanup_stale_async_clients,
)
@@ -128,7 +129,7 @@ class TestCleanupStaleAsyncClients:
loop = asyncio.new_event_loop()
loop.close()
client = AsyncClient()
- key = ("test_async_close", True, "", "", "", (), False)
+ key = _client_cache_key("test_async_close", async_mode=True)
with _client_cache_lock:
_client_cache[key] = (client, "test-model", loop)
@@ -143,6 +144,7 @@ class TestCleanupStaleAsyncClients:
def test_shutdown_closes_outside_cache_lock(self):
from agent.auxiliary_client import (
_client_cache,
+ _client_cache_key,
_client_cache_lock,
shutdown_cached_clients,
)
@@ -158,7 +160,7 @@ class TestCleanupStaleAsyncClients:
if acquired:
_client_cache_lock.release()
- key = ("test_shutdown_lock", False, "", "", "", (), False)
+ key = _client_cache_key("test_shutdown_lock", async_mode=False)
with _client_cache_lock:
previous = dict(_client_cache)
_client_cache.clear()
@@ -176,6 +178,7 @@ class TestCleanupStaleAsyncClients:
def test_shutdown_does_not_await_live_foreign_loop_client(self):
from agent.auxiliary_client import (
_client_cache,
+ _client_cache_key,
_client_cache_lock,
shutdown_cached_clients,
)
@@ -190,7 +193,7 @@ class TestCleanupStaleAsyncClients:
self.awaited = True
client = Client()
- key = ("test_shutdown_foreign_loop", True, "", "", "", (), False)
+ key = _client_cache_key("test_shutdown_foreign_loop", async_mode=True)
with _client_cache_lock:
previous = dict(_client_cache)
_client_cache.clear()
@@ -209,6 +212,7 @@ class TestCleanupStaleAsyncClients:
"""Entries with an open loop should be preserved."""
from agent.auxiliary_client import (
_client_cache,
+ _client_cache_key,
_client_cache_lock,
cleanup_stale_async_clients,
)
@@ -216,7 +220,7 @@ class TestCleanupStaleAsyncClients:
loop = asyncio.new_event_loop() # NOT closed
mock_client = MagicMock()
- key = ("test_live", True, "", "", "", (), False)
+ key = _client_cache_key("test_live", async_mode=True)
with _client_cache_lock:
_client_cache[key] = (mock_client, "test-model", loop)
@@ -233,12 +237,13 @@ class TestCleanupStaleAsyncClients:
"""Sync entries (cached_loop=None) should be preserved."""
from agent.auxiliary_client import (
_client_cache,
+ _client_cache_key,
_client_cache_lock,
cleanup_stale_async_clients,
)
mock_client = MagicMock()
- key = ("test_sync", False, "", "", "", (), False)
+ key = _client_cache_key("test_sync", async_mode=False)
with _client_cache_lock:
_client_cache[key] = (mock_client, "test-model", None)
@@ -308,10 +313,11 @@ class TestClientCacheBoundedGrowth:
"""Multiple event loops for the same provider should NOT create multiple entries."""
from agent.auxiliary_client import (
_client_cache,
+ _client_cache_key,
_client_cache_lock,
)
- key = ("test_no_grow", True, "", "", "", (), False)
+ key = _client_cache_key("test_no_grow", async_mode=True)
loops = []
try:
diff --git a/tests/agent/test_auxiliary_client_cache_follows_credential.py b/tests/agent/test_auxiliary_client_cache_follows_credential.py
index 36c0eefae6f..6fe11964ce0 100644
--- a/tests/agent/test_auxiliary_client_cache_follows_credential.py
+++ b/tests/agent/test_auxiliary_client_cache_follows_credential.py
@@ -57,3 +57,27 @@ def test_pool_cache_hint_follows_rotation_during_per_model_cooldown(isolated_hom
assert before.startswith("anthropic::") and after.startswith("anthropic::")
assert before != after
assert "tok-" not in before + after
+
+
+def _seed_two(provider: str, first_token: str, second_token: str) -> None:
+ rows = []
+ for idx, token in ((1, first_token), (2, second_token)):
+ rows.append({
+ "id": f"entry-{idx}", "label": f"pooled-{idx}", "auth_type": "oauth", "priority": idx,
+ "source": "manual", "access_token": token, "refresh_token": f"rt-{token}",
+ "expires_at": time.time() + 3600,
+ })
+ write_credential_pool(provider, rows)
+
+
+def test_sibling_entry_rotation_does_not_churn_selected_entry_key(isolated_home):
+ """Only the peeked entry's key is digested: rotating entry-2 keeps entry-1's client cached."""
+ _seed_two("anthropic", "tok-a1", "tok-b1")
+ before = aux._pool_cache_hint("anthropic")
+ assert before.startswith("anthropic:entry-1:")
+ _seed_two("anthropic", "tok-a1", "tok-b2") # sibling rotated, selection unchanged
+ assert aux._pool_cache_hint("anthropic") == before
+ _seed_two("anthropic", "tok-a2", "tok-b2") # the selected entry itself rotated
+ after = aux._pool_cache_hint("anthropic")
+ assert after.startswith("anthropic:entry-1:") and after != before
+ assert "tok-" not in before + after