The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): end local sessions left with no viewer
unsupportedpastelsb1e7bd0b7c7c
diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex 6cff28aedbf..b506bd1938b 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -1066,6 +1066,11 @@ group_sessions_per_user: true# of the file's pages are reclaimable — a dense database never pays for a full# rewrite to reclaim a few MB.#+# A CLI/TUI/Desktop session left with no viewer (a killed terminal, a dropped+# connection, a gateway restart) is ended by the gateway orphan_end_grace_s+# seconds later, once its running turn settles. It stays resumable, and a viewer+# that comes back within the grace keeps it open. 0 never ends it.+## Uncomment to change the defaults shown; auto_prune: true bounds the file,# auto_prune: false keeps every ended session and silences the low-disk prompt.# sessions:@@ -1074,6 +1079,7 @@ group_sessions_per_user: true# vacuum_after_prune: true# min_vacuum_interval_days: 30# min_interval_hours: 24+# orphan_end_grace_s: 300# Optional direct endpoint for autonomous Bot Mode rooms spanning gateways.# Leave unset for the safe default: Desktop coordinates cross-gateway rooms anddiff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 8f57f05e371..fad1f38ca8c 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -164,6 +164,7 @@ class SessionAuthority:# session id -> end_reason of a last-viewer close still waiting for an idle FIFO# (gateway/session_viewer_close); a viewer attaching again cancels it.self.pending_closes = {}+ self.orphan_closes = {} # session id -> grace timer of a session left with no viewer, never closed# Logical owner rotated away by the exhaustion auto-reset -> its session key: an admission# that reserved it before the rotation commits on that key's current route instead.self.rotated_owners = {}@@ -343,6 +344,8 @@ class SessionAuthority:if member == actor), None) or uuid.uuid4().hexlive.subscribers[subscription] = actorself.pending_closes.pop(ref.session_id, None)+ from gateway.session_viewer_close import cancel_orphan_close+ cancel_orphan_close(self, ref.session_id)from tools.async_delegation import allow_for_sessionallow_for_session((self.profile_id, ref.session_id)) # a closed session's work may start againtransport = self.events.get(actor.transport_id)@@ -390,6 +393,8 @@ class SessionAuthority:# A viewer that attached while the close was off the loop reopens it.await tracked_write(self, partial(end_idle_acp_session, self, session_id),then=partial(reopen_if_reattached, self, session_id))+ from gateway.session_viewer_close import arm_detached_orphan_close+ await arm_detached_orphan_close(self, session_id)returnraise RuntimeStoreError('not_found')diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.pyindex 66ea7e66e9d..21e3231811b 100644--- a/gateway/session_local_recovery.py+++ b/gateway/session_local_recovery.py@@ -362,19 +362,36 @@ def reset_local_session(store, old_entry, session_id, now, display_name):return entry+# The receipts boot restores: an open row (or one compressed away, for its catch-up), unsettled input+# or a stored close. An ended session keeps its receipt and stays resumable; ``authorize`` restores it+# on first touch, so the live registry no longer grows with every session ever opened (#143547 LC-36).+_BOOT_RECEIPTS_SQL = (+ "SELECT m.key FROM state_meta m LEFT JOIN sessions s "+ "ON s.id = CASE WHEN json_valid(m.value) THEN json_extract(m.value, '$.entry.session_id') END "+ "WHERE m.key LIKE ? AND (s.ended_at IS NULL OR s.end_reason = 'compression' "+ "OR EXISTS (SELECT 1 FROM session_admissions a WHERE a.target_session_id = substr(m.key, ?) "+ "AND a.status IN ('queued','started','unknown')) "+ "OR EXISTS (SELECT 1 FROM state_meta c WHERE c.key = ? || substr(m.key, ?)))")++def local_receipt_ids(authority):+ from gateway.session_viewer_close import CLOSE_PREFIX+ start = len(POLICY_PREFIX) + 1with authority.db._read_ctx() as conn:return [row[0][len(POLICY_PREFIX):] for row in conn.execute(- 'SELECT key FROM state_meta WHERE key LIKE ?', (POLICY_PREFIX + '%',))]+ _BOOT_RECEIPTS_SQL, (POLICY_PREFIX + '%', start, CLOSE_PREFIX, start))]def recover_local_sessions(authority, *, schedule=False):+ idle = []for sid in local_receipt_ids(authority):try:ref = restore_local_session(authority, sid)pending = list_session_admissions(authority.db, session_id=sid)if schedule and pending and not any(row['status'] == 'unknown' for row in pending):authority._schedule(ref)+ if not pending:+ idle.append(sid)except (_ReceiptRefused, _CatchUpPending):continue # logged: the check that refused it, or the catch-up handed to a workerexcept RuntimeStoreError as exc:@@ -388,3 +405,5 @@ def recover_local_sessions(authority, *, schedule=False):if any(row['status'] == 'unknown' for row in list_session_admissions(authority.db, session_id=sid)):# A hard-killed owner's turn: the drain pauses on it, so the close resolves it.track_mutation(authority, settle_viewer_close(authority, sid))+ from gateway.session_viewer_close import arm_startup_orphan_closes+ arm_startup_orphan_closes(authority, idle)diff --git a/gateway/session_viewer_close.py b/gateway/session_viewer_close.pyindex 7e9e30962b3..7445d9e11ac 100644--- a/gateway/session_viewer_close.py+++ b/gateway/session_viewer_close.py@@ -14,10 +14,12 @@ record under the owner-epoch fence: a cancelled older close, a reattach or a staremove the record it saw, never a newer close stored since."""import asyncio+import contextlibimport jsonimport loggingimport uuidfrom functools import partial+from pathlib import Pathfrom hermes_state_local import local_receiptfrom hermes_state_mutation_retirement import VIEWER_CLOSE_PREFIX@@ -47,6 +49,9 @@ def _busy(authority, session_id, target):# The viewer's /new: the classic CLI's ``new_session``; Ink's ``tui_close`` (/new or a resume switch,# both of which main's TUI followed with on_session_reset for the session it opened next)._RESET_REASONS = frozenset({'new_session', 'tui_close'})+# Ends nobody asked for (#143547 LC-35/LC-37): the last viewer vanished without closing (a killed+# terminal, a dropped socket), or the previous gateway stopped under it. Both stay resumable.+ORPHAN_REASONS = frozenset({'ws_orphan_reap', 'startup_orphan_reap'})class _PendingClose:@@ -84,6 +89,11 @@ async def close_viewer_session(authority, session_id, reason):for parent in parents:interrupt_for_session(session_key=route, parent_session_id=parent, reason=f'viewer_close:{reason}')authority.pending_closes[session_id] = close = _PendingClose(reason)+ await _store_and_settle(authority, session_id, live, close)+++async def _store_and_settle(authority, session_id, live, close):+ """Persist *close* (already pending in memory), then complete it at once if the FIFO is idle."""await asyncio.to_thread(_persist_close, authority, session_id, close.record)if not _still_pending(authority, session_id, live, close):# A viewer attached during the write: its own clear may have run before this commit. Only@@ -152,6 +162,82 @@ def rearm_persisted_closes(authority):return armed+def orphan_close_grace(authority):+ """Blocking: ``sessions.orphan_end_grace_s`` of the profile that owns *authority*'s store (0 = never)."""+ from hermes_cli.config_defaults import DEFAULT_CONFIG+ from hermes_cli.config_effective import load_user_config_effective+ default = DEFAULT_CONFIG['sessions']['orphan_end_grace_s']+ config = load_user_config_effective(Path(authority.db.db_path).resolve().parent / 'config.yaml')+ with contextlib.suppress(ValueError, TypeError, AttributeError):+ return max(0.0, float((config.get('sessions') or {}).get('orphan_end_grace_s', default)))+ return default+++def orphan_candidate(authority, session_id):+ """Blocking: *session_id* is a local session with an open row. ACP ends on its own at detach."""+ try:+ receipt = local_receipt(authority.db, session_id)+ row = authority.db.get_session(receipt['entry']['session_id'])+ except (RuntimeStoreError, KeyError, TypeError):+ return False # not a local session+ return receipt.get('policy', {}).get('source') != 'acp' and row is not None and row['ended_at'] is None+++def _call_later(loop, delay, callback):+ # The loop's monotonic clock: time the host spends asleep does not count toward the grace.+ return loop.call_later(delay, callback)+++def _stopping(authority):+ return authority.retiring or authority.retired or authority.runner._draining+++def arm_orphan_close(authority, session_id, reason, grace):+ """*session_id* has no viewer and nobody closed it: unless one attaches within *grace* seconds,+ close it as a viewer would, without stopping its turn or its async delegations (#106742). A+ stopping owner arms nothing; the next boot does (``recover_local_sessions``)."""+ live = authority.sessions.get(session_id)+ if not grace or live is None or live.subscribers or live.superseded or _stopping(authority):+ return+ cancel_orphan_close(authority, session_id)+ authority.orphan_closes[session_id] = _call_later(+ asyncio.get_running_loop(), grace, partial(_fire_orphan_close, authority, session_id, reason))+++async def arm_detached_orphan_close(authority, session_id):+ """``session.detach`` with no ``end_reason`` (a killed terminal, a dropped socket) left no viewer."""+ def grace():+ return orphan_close_grace(authority) if orphan_candidate(authority, session_id) else 0+ arm_orphan_close(authority, session_id, 'ws_orphan_reap', await asyncio.to_thread(grace))+++def arm_startup_orphan_closes(authority, session_ids):+ """Boot, after the stored closes are re-armed: the previous owner stopped under these idle+ sessions, so no viewer is left to close them (#143547 LC-37). One that reattaches keeps it open."""+ grace = orphan_close_grace(authority)+ for session_id in session_ids:+ if session_id not in authority.pending_closes and orphan_candidate(authority, session_id):+ arm_orphan_close(authority, session_id, 'startup_orphan_reap', grace)+++def cancel_orphan_close(authority, session_id):+ handle = authority.orphan_closes.pop(session_id, None)+ if handle is not None:+ handle.cancel()+++def _fire_orphan_close(authority, session_id, reason):+ authority.orphan_closes.pop(session_id, None)+ live = authority.sessions.get(session_id)+ if live is None or live.subscribers or session_id in authority.pending_closes or _stopping(authority):+ return+ # The persisted pending close a viewer's own close uses: it completes once the turn settles, and+ # survives a restart. Never ``close_viewer_session``: that would interrupt the delegations.+ authority.pending_closes[session_id] = close = _PendingClose(reason)+ from gateway.session_runtime_workers import track_mutation+ track_mutation(authority, _store_and_settle(authority, session_id, live, close))++async def settle_viewer_close(authority, session_id):"""Complete a pending viewer close once *session_id* has no viewer and an idle FIFO: stamp therow with the viewer's reason, commit the cached agent's memory and fire ``on_session_finalize``.@@ -202,6 +288,8 @@ async def _resolve_abandoned_unknown(authority, session_id, live, close):unknown = [row for row in rows if row['status'] == 'unknown']if not unknown:return True+ if close.reason in ORPHAN_REASONS:+ return False # nobody closed it: the turn waits for its user's own Discardfrom gateway.session_contract import SessionRefref = SessionRef(authority.profile_id, session_id)for row in unknown:diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 0099dce1cdd..4bede216b09 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -2279,11 +2279,8 @@ DEFAULT_CONFIG = {# List delegate_task subagent runs in session lists (desktop sidebar, dashboard, session.list),# nested under their parent. Off by default: they are machinery, not conversations."show_subagents": False,- # VACUUM after a prune that deleted rows (SQLite never reclaims disk on DELETE). VACUUM- # blocks writes (~seconds per 100MB), so it runs only at startup, only when ≥1 session was- # deleted AND freelist/page_count > 25%.- # SQLite does not reclaim disk space on DELETE — freed pages are just reused on subsequent INSERTs —- # so without VACUUM the file stays bloated even after pruning. See #54189.+ # VACUUM after a prune that deleted rows (SQLite never reclaims disk on DELETE, #54189). It blocks+ # writes (~seconds per 100MB): only at startup, only when ≥1 session went AND freelist/page_count > 25%."vacuum_after_prune": True,# Minimum days between VACUUM rewrites; pruning keeps its normal cadence."min_vacuum_interval_days": 30,@@ -2313,6 +2310,9 @@ DEFAULT_CONFIG = {# Max active messages per session for in-memory export (`hermes sessions export`); checked# per session, so full-DB backups of small sessions work."max_export_messages": 20000,+ # Seconds a local CLI/TUI/Desktop session may sit with no viewer (killed terminal, gateway restart)+ # before the gateway ends it, once its turn settles; it stays resumable. 0 = never.+ "orphan_end_grace_s": 300.0,},# First-touch onboarding hints (agent/onboarding.py), each latched under `seen` once shown."onboarding": {diff --git a/tests/gateway/test_local_session_orphan_end.py b/tests/gateway/test_local_session_orphan_end.pynew file mode 100644index 00000000000..b33c7dd4b1d--- /dev/null+++ b/tests/gateway/test_local_session_orphan_end.py@@ -0,0 +1,211 @@+"""Local sessions nobody closed end on the gateway, and only open ones come back at boot (#143547).++LC-35: a killed terminal or dropped socket detached with no ``end_reason``, and nothing ever ended+the row. LC-37: a gateway stop with a viewer attached left the row open for good. LC-36: every+receipt, ended or not, was restored into the live registry on each boot. The turn itself keeps+running (#106742); the row ends once it settles, through the epoch-fenced viewer-close path.+"""+import asyncio+from pathlib import Path+from types import SimpleNamespace++import pytest++from tests.waiting import async_wait_until+++async def _owner(tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ finalized = []++ async def finalize(**kwargs):+ finalized.append(kwargs['reason'])+ return []++ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda route: None, _adapter_for_source=lambda source: None,+ _finalize_session_off_loop=finalize)+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='owner')+ return authority, finalized+++def _viewer(authority):+ from gateway.session_controls import AuthorityConnection+ return AuthorityConnection(authority, SimpleNamespace(write=lambda frame: None), {'user_id': 'owner'})+++async def _attach(authority, sid):+ viewer = _viewer(authority)+ reply = await viewer.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': sid}})+ assert 'result' in reply, reply+ return viewer, reply['result']+++def _create(authority, text='earlier turn'):+ from gateway.session_local import create_local_session+ ref = create_local_session(authority, _viewer(authority).actor, {+ 'request_id': text, 'source': 'gui', 'cwd': str(Path(authority.db.db_path).parent), 'model': 'm',+ 'toolsets': []})+ authority.db.append_message(ref.session_id, 'user', text)+ return ref+++def _capture_timers(monkeypatch):+ """The grace timer's (delay, callback), fired by the test instead of after a real wait."""+ import gateway.session_viewer_close as viewer_close+ armed = []++ def call_later(loop, delay, callback):+ armed.append((delay, callback))+ return loop.call_later(3600, callback)+ monkeypatch.setattr(viewer_close, '_call_later', call_later, raising=False)+ return armed+++def _stored_close(db, sid):+ from gateway.session_viewer_close import CLOSE_PREFIX+ return db.get_meta(CLOSE_PREFIX + sid)+++async def test_a_dropped_viewer_ends_the_session_after_its_turn_settles(tmp_path, monkeypatch):+ import gateway.session_finite as finite+ import tools.async_delegation as delegation+ from hermes_state_runtime import admit_session_input, list_session_admissions++ armed = _capture_timers(monkeypatch)+ authority, finalized = await _owner(tmp_path, monkeypatch)+ db, ref = authority.db, _create(authority)+ sid, user = ref.session_id, authority.sessions[ref.session_id].source.user_id+ viewer, _ = await _attach(authority, sid)+ started, release, executed, refused = asyncio.Event(), asyncio.Event(), [], []++ async def execute(authority, ref, row):+ started.set()+ await release.wait()+ executed.append(row['payload']['text'])+ return 'done'+ monkeypatch.setattr(finite, 'execute_finite_admission', execute)+ monkeypatch.setattr(delegation, 'refuse_for_session', lambda *a, **k: refused.append(a))+ monkeypatch.setattr(delegation, 'interrupt_for_session', lambda *a, **k: refused.append(k))+ admit_session_input(db, epoch=authority.epoch, principal_id=user, session_id=sid,+ request_id='r1', payload={'text': 'long turn'})+ authority._schedule(ref)+ await asyncio.wait_for(started.wait(), 10)++ await viewer.close() # the terminal is killed: no end_reason+ assert [delay for delay, _ in armed] == [300.0]+ armed[0][1]()+ await async_wait_until(lambda: _stored_close(db, sid) is not None)+ # The turn keeps running and nothing it started is refused; the row stays open meanwhile.+ assert db.get_session(sid)['ended_at'] is None and executed == [] and refused == []++ release.set()+ await async_wait_until(lambda: finalized == ['ws_orphan_reap']) # the end hooks run after the stamp+ assert db.get_session(sid)['end_reason'] == 'ws_orphan_reap'+ assert executed == ['long turn'] and _stored_close(db, sid) is None++ admit_session_input(db, epoch=authority.epoch, principal_id=user, session_id=sid,+ request_id='r2', payload={'text': 'next turn'})+ authority._schedule(ref)+ await async_wait_until(lambda: executed == ['long turn', 'next turn'])+ await async_wait_until(lambda: not list_session_admissions(db, session_id=sid))+ assert db.get_session(sid)['ended_at'] is None # reopened on the same id+++async def test_a_viewer_back_within_the_grace_keeps_the_session_open(tmp_path, monkeypatch):+ armed = _capture_timers(monkeypatch)+ authority, finalized = await _owner(tmp_path, monkeypatch)+ sid = _create(authority).session_id+ viewer, _ = await _attach(authority, sid)+ await viewer.close()+ await _attach(authority, sid)+ assert authority.orphan_closes == {}++ armed[0][1]() # a timer that fired anyway finds the viewer back+ await asyncio.sleep(0)+ assert authority.pending_closes == {} and _stored_close(authority.db, sid) is None+ assert authority.db.get_session(sid)['ended_at'] is None and finalized == []+++async def test_an_orphan_end_leaves_an_unknown_turn_for_its_user(tmp_path, monkeypatch):+ """Nobody closed the session, so nobody decided to drop the turn a hard-killed owner lost."""+ from hermes_state_runtime import admit_session_input, claim_session_input, get_session_admission++ armed = _capture_timers(monkeypatch)+ first, _ = await _owner(tmp_path, monkeypatch)+ sid = _create(first).session_id+ admit_session_input(first.db, epoch=first.epoch, principal_id=first.sessions[sid].source.user_id,+ session_id=sid, request_id='r1', payload={'text': 'mid-turn'})+ row = claim_session_input(first.db, epoch=first.epoch, session_id=sid)+ authority, finalized = await _owner(tmp_path, monkeypatch) # SIGKILL, then the next owner+ assert get_session_admission(authority.db, admission_id=row['admission_id'])['status'] == 'unknown'++ viewer, _ = await _attach(authority, sid)+ await viewer.close()+ armed[-1][1]()+ from gateway.session_runtime_workers import mutation_tasks+ await asyncio.gather(*mutation_tasks(authority)) # the close is stored and its settle has run+ assert _stored_close(authority.db, sid) is not None+ assert get_session_admission(authority.db, admission_id=row['admission_id'])['status'] == 'unknown'+ assert authority.db.get_session(sid)['ended_at'] is None and finalized == []+++async def test_boot_restores_only_open_sessions_and_an_ended_one_on_first_touch(tmp_path, monkeypatch):+ from hermes_state_local import end_idle_local_session++ first, _ = await _owner(tmp_path, monkeypatch)+ ended, live = _create(first, 'finished').session_id, _create(first, 'ongoing').session_id+ assert end_idle_local_session(first.db, epoch=first.epoch, session_id=ended, target_id=ended, reason='cli_close')++ authority, _ = await _owner(tmp_path, monkeypatch)+ assert live in authority.sessions and ended not in authority.sessions+ _, resumed = await _attach(authority, ended)+ assert [message['content'] for message in resumed['messages']] == ['finished']+ assert ended in authority.sessions++[email protected]('viewer_returns', [False, True])+async def test_a_session_open_when_the_gateway_stopped_ends_after_boot(tmp_path, monkeypatch, viewer_returns):+ from gateway.session_local_recovery import recover_local_sessions++ armed = _capture_timers(monkeypatch)+ first, _ = await _owner(tmp_path, monkeypatch)+ sid = _create(first).session_id+ await _attach(first, sid) # the gateway stops with this viewer attached: no detach ever runs++ authority, finalized = await _owner(tmp_path, monkeypatch)+ recover_local_sessions(authority, schedule=True)+ assert [delay for delay, _ in armed] == [300.0]+ if viewer_returns:+ await _attach(authority, sid)+ armed[0][1]()+ if viewer_returns:+ await asyncio.sleep(0)+ assert authority.db.get_session(sid)['ended_at'] is None and finalized == []+ else:+ await async_wait_until(lambda: finalized == ['startup_orphan_reap'])+ assert authority.db.get_session(sid)['end_reason'] == 'startup_orphan_reap'+++async def test_a_zero_grace_never_ends_a_detached_session(tmp_path, monkeypatch):+ armed = _capture_timers(monkeypatch)+ authority, _ = await _owner(tmp_path, monkeypatch)+ (Path(authority.db.db_path).parent / 'config.yaml').write_text('sessions:\n orphan_end_grace_s: 0\n')+ sid = _create(authority).session_id+ viewer, _ = await _attach(authority, sid)+ await viewer.close()+ assert armed == [] and authority.orphan_closes == {}+ assert authority.db.get_session(sid)['ended_at'] is Nonediff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.mdindex 1bc637712f5..b4d78d32caa 100644--- a/website/docs/user-guide/sessions.md+++ b/website/docs/user-guide/sessions.md@@ -1194,6 +1194,16 @@ platform sessions (Telegram, Discord, …), TUI/desktop sessions, pinnedsessions, and sessions with a live turn or compression in progress arenever closed by this sweep.+**Local sessions nobody closed.** A CLI, TUI or Desktop session whose last+viewer disappeared without closing it (a killed terminal, a dropped connection,+or a gateway stop or restart while it was open) is ended by the gateway+`sessions.orphan_end_grace_s` seconds later (default `300`; `0` never ends it),+`end_reason: ws_orphan_reap` (or `startup_orphan_reap` after a restart). A turn+still running keeps running, and the session ends once it settles; one paused on+an interrupted turn stays open until you Discard it. A viewer that reconnects+within the grace keeps the session open. Ending is non-destructive: the session+stays resumable, and its next message reopens it on the same id.+### Oversized-Transcript GuardsTwo limits stop a runaway transcript from being loaded into memory all at once