Skip to content

The agent that grows with you

fix(cli): keep one live subscription per session across reconnects

unsupportedpastels34deb00db4cd
diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.py
index 6dcb335cf5a..d61776099f7 100644
--- a/hermes_cli/gateway_connection.py
+++ b/hermes_cli/gateway_connection.py
@@ -21,6 +21,8 @@ logger = logging.getLogger(__name__)
DISCONNECTED = ("Gateway disconnected; turn outcome is unknown. Resume the printed session ID to check "
"whether it completed or was interrupted; do not resend the work.")
+# Resume refusals meaning the session itself is gone for this viewer (gateway/session_controls).
+_GONE = frozenset({"not_found", "permission_denied", "profile_mismatch"})
def lost_before(frame, epoch) -> bool:
@@ -181,14 +183,19 @@ class GatewayConnection:
async def _resubscribe(self, client):
"""A new socket is a new viewer: the gateway streams a session's frames only to connections
- that resumed it. Resume each session this viewer had open; one deleted meanwhile is skipped."""
+ 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."""
for session_id, state in list(self.states.items()):
if state.subscription_id is None:
continue
try:
state.adopt_snapshot(await client.rpc("session.resume", session_id=session_id))
- except (GatewayClientError, TimeoutError) as exc:
- logger.debug("session.resume %s after reconnect failed: %s", session_id, exc)
+ 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 _pump(self, client):
while True:
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.py
index a640091d828..7e2d8b68938 100644
--- a/hermes_cli/gateway_session_store.py
+++ b/hermes_cli/gateway_session_store.py
@@ -242,16 +242,26 @@ class GatewaySessionStore:
row = conn.execute("SELECT id FROM sessions WHERE title = ? AND id != ?", (title, session_id)).fetchone()
return row[0] if row else None
+ def _leave(self, session_id):
+ """Drop this viewer's subscription record and return its id. The connection's SessionState holds
+ the live id (a reconnect resubscribes under a new one); cleared, no later reconnect resumes it."""
+ state = self.connection.states.get(session_id)
+ subscription = state.subscription_id if state is not None else None
+ if state is not None:
+ state.subscription_id = None
+ return subscription
+
def delete_session(self, session_id, sessions_dir=None):
self.snapshots.pop(session_id, None)
self._mutate(session_id, "delete", {})
+ self._leave(session_id)
return True
def end_session(self, session_id, reason=None):
"""Main's ``end_session(sid, reason)``: detach this viewer with ``end_reason``; the owner ends
the idle local row with that reason once no viewer is left (``ended_at`` / ``end_reason``)."""
snapshot = self.snapshots.pop(session_id, None)
- subscription = (snapshot or {}).get("subscription_id")
+ subscription = self._leave(session_id)
if subscription and not self.connection.closed:
params = {"end_reason": reason} if reason else {}
try:
diff --git a/tests/hermes_cli/test_gateway_connection_reconnect.py b/tests/hermes_cli/test_gateway_connection_reconnect.py
index 0607015636e..c6ecbeae814 100644
--- a/tests/hermes_cli/test_gateway_connection_reconnect.py
+++ b/tests/hermes_cli/test_gateway_connection_reconnect.py
@@ -25,14 +25,17 @@ def _frame(kind, payload):
class Life:
"""One gateway process as one client sees it: from a dial until it hangs up."""
- def __init__(self, number, *, drop_on_submit=False):
+ def __init__(self, number, *, drop_on_submit=False, resume_errors=None):
self.number = number
self.events = asyncio.Queue()
self.calls = []
self.drop_on_submit = drop_on_submit
+ self.resume_errors = resume_errors if resume_errors is not None else []
async def rpc(self, method, *, _timeout=None, **params):
self.calls.append((method, params))
+ if method == "session.resume" and self.resume_errors:
+ raise self.resume_errors.pop(0)
if method == "session.resume":
return {"stored_session_id": params["session_id"], "subscription_id": f"sub-{self.number}",
"revision": 1, "execution_generation": 7, "messages": []}
@@ -56,13 +59,14 @@ class Gateway:
self.lives = []
self.refusals = 0
self.drop_next_submit = False
+ self.resume_errors = [] # raised by the next session.resume calls, across lives
@asynccontextmanager
async def dial(self):
if self.refusals:
self.refusals -= 1
raise GatewayClientError("Gateway starting: deadline. Your message was not sent.")
- life = Life(len(self.lives) + 1, drop_on_submit=self.drop_next_submit)
+ life = Life(len(self.lives) + 1, drop_on_submit=self.drop_next_submit, resume_errors=self.resume_errors)
self.drop_next_submit = False
self.lives.append(life)
yield life
@@ -151,6 +155,76 @@ def test_the_previous_connections_loss_never_fails_a_live_turn(gateway, conn):
assert not result.get("failed") and result["final_response"] == "reply 2"
+def _resumes(life):
+ return [params["session_id"] for method, params in life.calls if method == "session.resume"]
+
+
+def store(conn):
+ from hermes_cli.gateway_session_store import GatewaySessionStore
+ db = GatewaySessionStore(conn)
+ db.attach(SID)
+ return db
+
+
+def test_ending_a_session_after_a_reconnect_detaches_its_current_subscription(gateway, conn, store):
+ """The redial resubscribed under a new id; detaching with the first one is refused gateway-side,
+ leaving a closed session attached and its close bookkeeping skipped."""
+ gateway.hang_up(conn)
+ conn.call("status")
+ store.end_session(SID, "new_session")
+ assert gateway.lives[1].calls[-1] == ("session.detach", {
+ "session_id": SID, "subscription_id": "sub-2", "end_reason": "new_session"})
+ # Left by this viewer: a later reconnect does not resume it again.
+ gateway.hang_up(conn)
+ conn.call("status")
+ assert _resumes(gateway.lives[2]) == []
+
+
+def test_a_deleted_session_is_not_resumed_by_later_reconnects(gateway, conn, store):
+ gateway.hang_up(conn)
+ conn.call("status")
+ store.delete_session(SID)
+ gateway.hang_up(conn)
+ conn.call("status")
+ assert _resumes(gateway.lives[2]) == []
+
+
+def test_a_session_gone_during_the_restart_is_skipped_and_not_retried(gateway, conn):
+ gateway.resume_errors.append(GatewayClientError("not_found"))
+ gateway.hang_up(conn)
+ assert conn.call("status") == {"status": "ok", "life": 2}
+ assert conn.state(SID).subscription_id is None
+ gateway.hang_up(conn)
+ assert conn.call("status") == {"status": "ok", "life": 3}
+ assert _resumes(gateway.lives[2]) == []
+
+
[email protected]("failure", [GatewayClientError("storage_unavailable"), TimeoutError()],
+ ids=["storage_unavailable", "timeout"])
+def test_a_transient_resume_failure_fails_the_reconnect_and_the_next_call_retries(gateway, conn, failure):
+ """Ready without the subscription, every later prompt.submit is refused (permission_denied) on a
+ live socket that never redials: the reconnect must fail instead, so the next call dials again."""
+ gateway.resume_errors.append(failure)
+ gateway.hang_up(conn)
+ with pytest.raises(GatewayClientError):
+ conn.call("status")
+ assert conn.call("status") == {"status": "ok", "life": 3}
+ assert _resumes(gateway.lives[2]) == [SID]
+ assert conn.state(SID).subscription_id == "sub-3"
+
+
+def test_close_after_a_failed_resume_is_still_final(gateway, conn):
+ gateway.resume_errors.append(GatewayClientError("storage_unavailable"))
+ gateway.hang_up(conn)
+ with pytest.raises(GatewayClientError):
+ conn.call("status")
+ conn.close()
+ with pytest.raises(GatewayClientError):
+ conn.call("status")
+ assert len(gateway.lives) == 2
+
+
def test_lost_before():
error = GatewayClientError("Gateway disconnected")
assert not lost_before(error, 2) # untagged: a live loss