Skip to content

The agent that grows with you

fix(cli): retry a keyed resume plain only on admission_conflict

David Dudok de Witd8af054d1427
diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.py
index 99fa6693d32..7166ea49904 100644
--- a/hermes_cli/gateway_connection.py
+++ b/hermes_cli/gateway_connection.py
@@ -26,6 +26,10 @@ DISCONNECTED = ("Gateway disconnected; turn outcome is unknown. Resume the print
NOT_SENT = "Gateway disconnected before the request was sent; nothing was sent."
# Resume refusals meaning the session itself is gone for this viewer (gateway/session_controls).
_GONE = frozenset({"not_found", "permission_denied", "profile_mismatch"})
+# Keyed-resume refusals a plain resume answers as main did: the key does not apply to this session
+# (``rebind_launch_key``: keyless or non-local, another key held, another fingerprint), or the viewer
+# lacks the ``session:control`` a rebind needs but may still read. Any other refusal is the resume's.
+_KEY_NOT_TAKEN = frozenset({"admission_conflict", "permission_denied"})
class CallStopped(GatewayClientError):
@@ -247,27 +251,34 @@ class GatewayConnection:
that resumed it. Resume each session this viewer had open; one gone meanwhile is dropped. Any
other failure fails the reconnect: ready without the subscription, every prompt is refused on a
live socket that never redials, while a failed redial is retried by the next call."""
+ loop = asyncio.get_running_loop()
+
+ def call(method, **params): # :meth:`resume` runs on a worker thread; this loop carries its requests
+ return asyncio.run_coroutine_threadsafe(client.rpc(method, **params), loop).result()
for session_id, state in list(self.states.items()):
if state.subscription_id is None:
continue
try:
- state.adopt_snapshot(await self._resume(client, session_id))
+ state.adopt_snapshot(await asyncio.to_thread(self.resume, call, session_id))
except GatewayClientError as exc:
if str(exc) not in _GONE:
raise
logger.debug("session.resume %s after reconnect: %s", session_id, exc)
state.subscription_id = None
- async def _resume(self, client, session_id):
- """``session.resume`` carrying :attr:`launch_api_key`. An owner refusal of the keyed resume (a session
- launched without that key: a keyed startup alias on a Desktop/TUI session) resumes it as is."""
+ def resume(self, call, session_id):
+ """``session.resume`` through ``call`` (the store's attach; :meth:`_resubscribe`), re-supplying
+ :attr:`launch_api_key`. Only a refusal in ``_KEY_NOT_TAKEN`` resumes plain (a keyed startup alias on
+ a Desktop/TUI session); any other is raised, not hidden by a keyless attach whose first turn fails."""
key = self.launch_api_key
- try:
- return await client.rpc("session.resume", session_id=session_id, **({"api_key": key} if key else {}))
- except GatewayRPCError:
- if not key:
- raise
- return await client.rpc("session.resume", session_id=session_id)
+ if key:
+ try:
+ return call("session.resume", session_id=session_id, api_key=key)
+ except GatewayRPCError as exc:
+ if str(exc) not in _KEY_NOT_TAKEN:
+ raise
+ logger.debug("session.resume %s: launch key not taken (%s); resuming without it", session_id, exc)
+ return call("session.resume", session_id=session_id)
async def _pump(self, client):
while True:
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.py
index 86da19a0f15..980ac622011 100644
--- a/hermes_cli/gateway_session_store.py
+++ b/hermes_cli/gateway_session_store.py
@@ -22,7 +22,7 @@ import re
import sys
import uuid
-from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
+from hermes_cli.gateway_client import GatewayClientError
from hermes_cli.gateway_connection import GatewayConnection
logger = logging.getLogger(__name__)
@@ -123,17 +123,11 @@ class GatewaySessionStore:
def attach(self, session_id):
"""``session.resume`` once per session id this viewer uses (idempotent), carrying this CLI's launch
- key as the thin client does. An owner refusal of the keyed resume (a session launched without that
- key: a keyed startup alias resuming a Desktop/TUI session) attaches as is; its frozen route decides."""
+ key as the thin client does (``GatewayConnection.resume``, the reconnect's too). A session that does
+ not take the key (a keyed startup alias resuming a Desktop/TUI session) attaches as is."""
if session_id in self.snapshots:
return self.snapshots[session_id]
- key = self.connection.launch_api_key
- try:
- snapshot = self.call("session.resume", session_id=session_id, **({"api_key": key} if key else {}))
- except GatewayRPCError:
- if not key:
- raise
- snapshot = self.call("session.resume", session_id=session_id)
+ snapshot = self.connection.resume(self.call, session_id)
self._adopt(snapshot)
return snapshot
diff --git a/tests/hermes_cli/test_gateway_resume_launch_key.py b/tests/hermes_cli/test_gateway_resume_launch_key.py
index 5ee14a6a9af..5c3bb641350 100644
--- a/tests/hermes_cli/test_gateway_resume_launch_key.py
+++ b/tests/hermes_cli/test_gateway_resume_launch_key.py
@@ -9,12 +9,13 @@ Real owners (``initialize_session_authority`` again on the same DB is the restar
``AuthorityConnection.dispatch``, real ``GatewayConnection`` and ``GatewaySessionStore``: each dial of the
CLI's connection reaches the current owner through a bridge client."""
import asyncio
+import logging
from contextlib import asynccontextmanager
from types import SimpleNamespace
import pytest
-from hermes_cli.gateway_client import GatewayClientError, rpc_error
+from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError, rpc_error
from hermes_cli.gateway_connection import GatewayConnection
from hermes_cli.gateway_session_store import GatewaySessionStore
@@ -48,6 +49,7 @@ class _Owners:
from gateway.session_local import create_local_session
monkeypatch.setattr(run, '_load_gateway_config', lambda *a, **k: {'platform_toolsets': {'cli': []}})
self.profile, self.loop, self.lives = str(tmp_path), asyncio.get_running_loop(), []
+ self.identity = {'user_id': 'owner'} # the CLI's principal on each dial
self.store = SessionStore(tmp_path / 'sessions', GatewayConfig())
first = await self.boot('first')
actor = AuthorityConnection(first, object(), {'user_id': 'owner'}).actor
@@ -67,7 +69,7 @@ class _Owners:
async def _open(self):
from gateway.session_controls import AuthorityConnection
- self.lives.append(_Life(AuthorityConnection(self.current, object(), {'user_id': 'owner'}), self.loop))
+ self.lives.append(_Life(AuthorityConnection(self.current, object(), self.identity), self.loop))
return self.lives[-1]
@asynccontextmanager
@@ -127,3 +129,75 @@ async def test_a_reconnect_after_a_restart_resupplies_the_launch_key(tmp_path, m
assert conn.states[owners.plain].subscription_id not in (None, before)
finally:
await owners.close(conn)
+
+
+def _refuse_the_rebind(monkeypatch, code):
+ """The owner refuses the keyed resume with ``code`` where it takes the key back (a receipt read that
+ fails is ``storage_unavailable``); a plain resume never gets there."""
+ from gateway import session_policy
+ from hermes_state_runtime import RuntimeStoreError
+
+ def refuse(*_a):
+ raise RuntimeStoreError(code)
+ monkeypatch.setattr(session_policy, 'rebind_launch_key', refuse)
+
+
+def _plain_retries(caplog):
+ return [r.getMessage() for r in caplog.records if r.name == 'hermes_cli.gateway_connection']
+
+
[email protected]('path', ['attach', 'reconnect'])
[email protected]('code, plain', [('admission_conflict', True), ('permission_denied', True),
+ ('storage_unavailable', False)])
+async def test_a_refused_keyed_resume_retries_plain_only_when_the_key_does_not_apply(
+ tmp_path, monkeypatch, caplog, path, code, plain):
+ """A key the session does not take (``admission_conflict``) or a viewer without ``session:control``
+ (``permission_denied``) resumes plain as main did, with a debug line naming the code, never the key. Any
+ other refusal fails the resume, on ``/resume`` and on a reconnect alike (one helper): a plain retry would
+ hide it, and the first turn would fail ``launch_credentials_unavailable`` with nothing in the log."""
+ caplog.set_level(logging.DEBUG, logger='hermes_cli.gateway_connection')
+ owners = await _Owners().start(tmp_path, monkeypatch)
+ conn = GatewayConnection(connect=owners.dial)
+ store = GatewaySessionStore(conn)
+ cli = SimpleNamespace(_resumed=True, session_id=owners.keyed)
+ try:
+ before = None
+ if path == 'reconnect':
+ await asyncio.to_thread(store.open_session, cli, LAUNCH)
+ before = conn.states[owners.keyed].subscription_id
+ await owners.hang_up(conn)
+ await owners.boot('restarted')
+ _refuse_the_rebind(monkeypatch, code)
+ resume = (lambda: conn.start(10)) if path == 'reconnect' else (lambda: store.open_session(cli, LAUNCH))
+ if plain:
+ await asyncio.to_thread(resume)
+ assert conn.states[owners.keyed].subscription_id not in (None, before)
+ assert any(code in line for line in _plain_retries(caplog))
+ else:
+ with pytest.raises(GatewayRPCError, match=code):
+ await asyncio.to_thread(resume)
+ assert RAW not in caplog.text
+ finally:
+ await owners.close(conn)
+
+
+async def test_a_read_only_viewer_still_gets_the_plain_attach(tmp_path, monkeypatch, caplog):
+ """The owner checks ``session:control`` before it takes a key back: a read-only viewer's keyed resume is
+ ``permission_denied``, and it still gets main's ``session:read`` attach, binding nothing."""
+ from hermes_state_runtime import RuntimeStoreError
+ caplog.set_level(logging.DEBUG, logger='hermes_cli.gateway_connection')
+ owners = await _Owners().start(tmp_path, monkeypatch)
+ await owners.boot('restarted')
+ owners.identity = {'user_id': 'owner', 'capabilities': ['session:read']}
+ conn = GatewayConnection(connect=owners.dial)
+ try:
+ store = GatewaySessionStore(conn)
+ cli = SimpleNamespace(_resumed=True, session_id=owners.keyed)
+ assert await asyncio.to_thread(store.open_session, cli, LAUNCH) == owners.keyed
+ assert any('permission_denied' in line for line in _plain_retries(caplog))
+ with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable'):
+ owners.key_of(owners.keyed)
+ finally:
+ await owners.close(conn)
diff --git a/tests/hermes_cli/test_resume_compressed_gateway_id.py b/tests/hermes_cli/test_resume_compressed_gateway_id.py
index 070b7f413d0..aff545772a7 100644
--- a/tests/hermes_cli/test_resume_compressed_gateway_id.py
+++ b/tests/hermes_cli/test_resume_compressed_gateway_id.py
@@ -59,12 +59,13 @@ def _gateway_store(loop, authority, tmp_path):
the real read-only state.db reader, as the classic CLI's does."""
from gateway.session_controls import AuthorityConnection
from hermes_cli.gateway_client import GatewayClientError
- from hermes_cli.gateway_connection import SessionState
+ from hermes_cli.gateway_connection import GatewayConnection, SessionState
from hermes_cli.gateway_session_store import GatewaySessionStore
from hermes_state import SessionDB
states = {}
connection = types.SimpleNamespace(final=False, launch_api_key=None,
state=lambda sid: states.setdefault(sid, SessionState(sid)))
+ connection.resume = types.MethodType(GatewayConnection.resume, connection) # the store's attach helper
gateway = AuthorityConnection(authority, object(), {
'provider': 'local', 'user_id': 'owner', 'profile_id': 'fixture', 'instance_id': authority.instance_id,
'capabilities': ['session:create', 'session:read', 'session:control']})