Skip to content

The agent that grows with you

fix(honcho): snapshot the failing bearer before the operation runs

Erosika885e27fbf439
diff --git a/plugins/memory/honcho/session_auth.py b/plugins/memory/honcho/session_auth.py
index 4050c50e537..19faa365b70 100644
--- a/plugins/memory/honcho/session_auth.py
+++ b/plugins/memory/honcho/session_auth.py
@@ -94,9 +94,11 @@ class SessionAuthMixin:
except Exception:
return False
- def _force_reauth(self) -> bool:
+ def _force_reauth(self, failed_access_token: str | None = None) -> bool:
"""Rotate the token after a 401 and rebind the client. False for a static API key, a dead
- grant, or a failed exchange."""
+ grant, or a failed exchange. ``failed_access_token`` is the bearer the failing operation
+ sent, snapshotted by ``_authed_call`` before it ran: the live client's ``api_key`` is
+ rotated in place by sibling waiters, so reading it here would defeat the adopt check."""
try:
from plugins.memory.honcho import oauth
from plugins.memory.honcho.client import reset_honcho_client
@@ -104,12 +106,9 @@ class SessionAuthMixin:
host = getattr(self._config, "host", "") or ""
if not host:
return False
- # Tell the refresher which bearer 401'd so a sibling's rotation is adopted, not replayed.
- try:
- failed = getattr(getattr(self.honcho, "_http", None), "api_key", None)
- except Exception:
- failed = None
- token = oauth.force_refresh_token(self._bound_config_path(), host, failed_access_token=failed)
+ token = oauth.force_refresh_token(
+ self._bound_config_path(), host, failed_access_token=failed_access_token
+ )
if not token:
return False
if not oauth.apply_token_to_client(self.honcho, token):
@@ -132,6 +131,11 @@ class SessionAuthMixin:
exc = HonchoAuthError(_REAUTH_REQUIRED_MESSAGE)
self._record_auth_failure(exc)
raise exc
+ # Snapshot the bearer first: after a 401 the client's api_key may already hold a sibling's rotation.
+ try:
+ failed_token = getattr(getattr(self.honcho, "_http", None), "api_key", None)
+ except Exception:
+ failed_token = None
try:
result = operation()
except HonchoAuthError:
@@ -141,7 +145,7 @@ class SessionAuthMixin:
raise
logger.warning("Honcho %s hit an auth error; forcing token refresh and retrying once: %s",
op_name, _redact_sensitive_text(str(e), force=True))
- if not self._force_reauth():
+ if not self._force_reauth(failed_access_token=failed_token):
self._record_auth_failure(e)
raise HonchoAuthError(_auth_error_message(e)) from e
try:
diff --git a/tests/honcho_plugin/test_auth_recovery.py b/tests/honcho_plugin/test_auth_recovery.py
index 5f50187c444..2f6aaadd6ad 100644
--- a/tests/honcho_plugin/test_auth_recovery.py
+++ b/tests/honcho_plugin/test_auth_recovery.py
@@ -385,7 +385,7 @@ def _make_manager(peer, *, reauth_ok=True):
)
mgr._cache["k"] = session
mgr._get_or_create_peer = lambda peer_id: peer
- mgr._force_reauth = lambda: reauth_ok
+ mgr._force_reauth = lambda **kw: reauth_ok
return mgr
@@ -426,7 +426,7 @@ class TestDialecticAuthRetry:
assert mgr._auth_failure is not None
peer.failures = 0
- mgr._force_reauth = lambda: True
+ mgr._force_reauth = lambda **kw: True
assert mgr.dialectic_query("k", "q") == "synthesized answer"
assert mgr._auth_failure is None
assert mgr.pop_auth_notice() is None
@@ -462,6 +462,45 @@ class TestForceReauth:
mgr = HonchoSessionManager(config=HonchoClientConfig(host="hermes"))
assert mgr._force_reauth() is False
+ def test_passes_pre_call_bearer_not_the_mutated_one(self, tmp_path, monkeypatch):
+ """_authed_call snapshots the bearer BEFORE the operation runs. A
+ sibling waiter's apply_token_to_client mutates the shared client's
+ api_key in place mid-operation; if the post-mutation token were
+ passed, disk would match it and force_refresh_token would exchange
+ again — the exact burst this fix removes."""
+ from plugins.memory.honcho import client as client_mod
+ from plugins.memory.honcho import session as session_mod
+
+ http = SimpleNamespace(api_key="hch-at-old")
+ shared_client = SimpleNamespace(_http=http)
+ monkeypatch.setattr(session_mod, "get_honcho_client", lambda *a, **k: shared_client)
+ monkeypatch.setattr(client_mod, "resolve_config_path", lambda: tmp_path / "honcho.json")
+
+ seen = {}
+
+ def fake_force_refresh(p, h, *, failed_access_token=None):
+ seen["failed"] = failed_access_token
+ return "hch-at-new1"
+
+ monkeypatch.setattr(oauth, "force_refresh_token", fake_force_refresh)
+ monkeypatch.setattr(oauth, "apply_token_to_client", lambda c, t: True)
+
+ mgr = HonchoSessionManager(config=HonchoClientConfig(host="hermes", enabled=True))
+
+ calls = {"n": 0}
+
+ def operation():
+ calls["n"] += 1
+ if calls["n"] == 1:
+ # Sibling waiter rotates the shared client's bearer in place
+ # while our request is failing with the OLD token.
+ http.api_key = "hch-at-new1"
+ raise Exception("Invalid or expired access token")
+ return "ok"
+
+ assert mgr._authed_call("test op", operation) == "ok"
+ assert seen["failed"] == "hch-at-old"
+
# ---------------------------------------------------------------------------
# session: message sync 401 recovery
@@ -488,7 +527,7 @@ def _make_sync_manager(flaky_session, *, reauth_ok=True):
peer.message.side_effect = lambda content: content
mgr._get_or_create_peer = lambda peer_id: peer
mgr._sessions_cache["s"] = flaky_session
- mgr._force_reauth = lambda: reauth_ok
+ mgr._force_reauth = lambda **kw: reauth_ok
session = HonchoSession(
key="k", user_peer_id="u", assistant_peer_id="a", honcho_session_id="s"
)
@@ -526,7 +565,7 @@ class TestSyncAuthRetry:
assert mgr._flush_session(session) is False
assert mgr._auth_failure is not None
- mgr._force_reauth = lambda: True
+ mgr._force_reauth = lambda **kw: True
assert mgr._flush_session(session) is True
assert all(m["_synced"] for m in session.messages)
assert mgr._auth_failure is None
@@ -783,7 +822,7 @@ class TestNonAuthFailuresNotRetried:
_TimeoutPeer.calls = 0
mgr = _make_manager(_TimeoutPeer())
reauths = []
- mgr._force_reauth = lambda: reauths.append(1) or True
+ mgr._force_reauth = lambda **kw: reauths.append(1) or True
ctx = mgr.get_session_context("k")
assert ctx == {"representation": "", "card": []}
@@ -806,7 +845,7 @@ class TestNonAuthFailuresNotRetried:
monkeypatch.setattr(session_mod, "get_honcho_client", lambda *a, **k: client)
mgr = _make_manager(_TimeoutSearchPeer())
reauths = []
- mgr._force_reauth = lambda: reauths.append(1) or True
+ mgr._force_reauth = lambda **kw: reauths.append(1) or True
assert mgr.search_context("k", "q") == ""
assert client.search.call_count == 1