Skip to content

The agent that grows with you

fix(gateway): honour legacy reap opt-outs; startup idle floor for orphan ends

unsupportedpastels96168a2fa811
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index b506bd1938b..b7af85dba72 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -1069,7 +1069,10 @@ group_sessions_per_user: true
# 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.
+# that comes back within the grace keeps it open. 0 never ends it. After a
+# restart it also waits out the rest of 6h since the session's last activity.
+# It replaces dashboard.ws_orphan_reap_grace_s / startup_orphan_sweep for these
+# sessions; while it is unset, their opt-outs (0 / false) still turn it off.
#
# 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.
diff --git a/gateway/session_live_listing.py b/gateway/session_live_listing.py
index 2833d492e91..864276b73e3 100644
--- a/gateway/session_live_listing.py
+++ b/gateway/session_live_listing.py
@@ -1,9 +1,10 @@
"""The live session feeds (``session.list`` live scope, ``session.active_list``) read off the loop.
-Both feeds cover every session in ``authority.sessions``, and a gateway restart refills that registry
-from receipts, so it can hold thousands of rows (mostly finished cron runs). Walking it one row at a
-time on the loop cost three full hydrations plus a receipt JSON parse per session: the loop stalled
-past 10 s, WS writes and the Telegram adapter's ``updater.stop()`` missed their deadlines (#141236).
+Both feeds cover every session in ``authority.sessions``, which can hold thousands of rows (mostly
+finished cron runs; boot restores only open sessions, an ended one comes back on first touch).
+Walking it one row at a time on the loop cost three full hydrations plus a receipt JSON parse per
+session: the loop stalled past 10 s, WS writes and the Telegram adapter's ``updater.stop()`` missed
+their deadlines (#141236).
Here the loop does only in-memory work (authorization and liveness from ``LiveSession``); the store
facts for a batch of sessions are ONE worker-thread read: picker columns, runtime revision and
diff --git a/gateway/session_viewer_close.py b/gateway/session_viewer_close.py
index 8d53c2373e9..725c2349911 100644
--- a/gateway/session_viewer_close.py
+++ b/gateway/session_viewer_close.py
@@ -17,6 +17,7 @@ import asyncio
import contextlib
import json
import logging
+import time
import uuid
from functools import partial
from pathlib import Path
@@ -52,6 +53,8 @@ _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'})
+# The legacy startup sweep's session TTL (tui_gateway ``_SESSION_TTL_S``): see arm_startup_orphan_closes.
+STARTUP_IDLE_S = 6 * 3600.0
class _PendingClose:
@@ -162,19 +165,36 @@ 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)."""
+def _seconds(raw, default):
+ with contextlib.suppress(ValueError, TypeError):
+ return max(0.0, float(raw))
+ return default
+
+
+def _section(config, key):
+ value = config.get(key)
+ return value if isinstance(value, dict) else {}
+
+
+def orphan_close_grace(authority, *, startup=False):
+ """Blocking: ``sessions.orphan_end_grace_s`` of the profile that owns *authority*'s store (0 = never).
+ Unset, the legacy backend's switches for the same reaping still opt out: ``dashboard.
+ ws_orphan_reap_grace_s: 0`` (park forever) and, for *startup* arms, ``startup_orphan_sweep: false``."""
from hermes_cli.config_defaults import DEFAULT_CONFIG
from hermes_cli.config_effective import load_user_config_effective
from gateway.session_local import profile_env_scope
+ from utils import is_truthy_value
default = DEFAULT_CONFIG['sessions']['orphan_end_grace_s']
home = Path(authority.db.db_path).resolve().parent
# A dropped socket detaches outside the RPC's owner scope: expand ``${VAR}`` against this profile.
with profile_env_scope(home):
config = load_user_config_effective(home / '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
+ sessions, dashboard = _section(config, 'sessions'), _section(config, 'dashboard')
+ if 'orphan_end_grace_s' in sessions:
+ return _seconds(sessions['orphan_end_grace_s'], default)
+ legacy_off = _seconds(dashboard.get('ws_orphan_reap_grace_s'), default) == 0 or (
+ startup and not is_truthy_value(dashboard.get('startup_orphan_sweep'), default=True))
+ return 0.0 if legacy_off else default
def orphan_candidate(authority, session_id):
@@ -215,14 +235,25 @@ async def arm_detached_orphan_close(authority, session_id):
arm_orphan_close(authority, session_id, 'ws_orphan_reap', await asyncio.to_thread(grace))
+def _idle_s(authority, session_id):
+ from hermes_state_common import _sql_session_last_active
+ with authority.db._read_ctx() as conn:
+ row = conn.execute(f'SELECT {_sql_session_last_active("s")} FROM sessions s WHERE s.id = ?',
+ (_physical_target(authority, session_id),)).fetchone()
+ return time.time() - row[0] if row and row[0] else 0.0
+
+
def arm_startup_orphan_closes(authority, session_ids):
"""Boot, after the stored closes are re-armed: the previous owner stopped under these sessions
(idle, or with input it left queued), so no viewer is left to close them (#143547 LC-37). One
- that reattaches keeps it open; a fired close still waits for the queued input to settle."""
- grace = orphan_close_grace(authority)
+ that reattaches keeps it open; a fired close still waits for the queued input to settle.
+ An idle classic CLI only redials on its next call, so a session idle less than the legacy
+ sweep's TTL waits out the rest of it, as that sweep did, before its grace starts to count."""
+ grace = orphan_close_grace(authority, startup=True)
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)
+ if grace and session_id not in authority.pending_closes and orphan_candidate(authority, session_id):
+ delay = max(grace, STARTUP_IDLE_S - _idle_s(authority, session_id))
+ arm_orphan_close(authority, session_id, 'startup_orphan_reap', delay)
def cancel_orphan_close(authority, session_id):
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 4bede216b09..5fd79bdf2ef 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -2310,8 +2310,8 @@ 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.
+ # Seconds before a local session with no viewer is ended (resumable) once its turn settles; 0 = never; after a
+ # restart also >= 6h idle. Unset: dashboard.ws_orphan_reap_grace_s: 0 / startup_orphan_sweep: false opt out.
"orphan_end_grace_s": 300.0,
},
# First-touch onboarding hints (agent/onboarding.py), each latched under `seen` once shown.
diff --git a/tests/gateway/test_local_session_orphan_end.py b/tests/gateway/test_local_session_orphan_end.py
index dbe4d2ce558..42230d6256b 100644
--- a/tests/gateway/test_local_session_orphan_end.py
+++ b/tests/gateway/test_local_session_orphan_end.py
@@ -69,6 +69,12 @@ def _capture_timers(monkeypatch):
return armed
+def _stale_rows(monkeypatch):
+ """Every restored row already idle past the legacy TTL, so the startup arm uses the plain grace."""
+ import gateway.session_viewer_close as viewer_close
+ monkeypatch.setattr(viewer_close, 'STARTUP_IDLE_S', 0.0, raising=False)
+
+
def _stored_close(db, sid):
from gateway.session_viewer_close import CLOSE_PREFIX
return db.get_meta(CLOSE_PREFIX + sid)
@@ -181,6 +187,7 @@ async def test_a_session_open_when_the_gateway_stopped_ends_after_boot(tmp_path,
from gateway.session_local_recovery import recover_local_sessions
armed = _capture_timers(monkeypatch)
+ _stale_rows(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
@@ -199,6 +206,48 @@ async def test_a_session_open_when_the_gateway_stopped_ends_after_boot(tmp_path,
assert authority.db.get_session(sid)['end_reason'] == 'startup_orphan_reap'
+async def test_a_session_active_before_the_restart_is_kept_for_its_idle_classic_cli(tmp_path, monkeypatch):
+ """An idle classic CLI redials only on its next call: boot must not end its session in minutes."""
+ from gateway.session_local_recovery import recover_local_sessions
+ from gateway.session_viewer_close import STARTUP_IDLE_S
+
+ armed = _capture_timers(monkeypatch)
+ first, _ = await _owner(tmp_path, monkeypatch)
+ sid = _create(first).session_id
+ await _attach(first, sid)
+
+ authority, _ = await _owner(tmp_path, monkeypatch)
+ recover_local_sessions(authority, schedule=True)
+ [(delay, _)] = armed
+ assert STARTUP_IDLE_S - 60 < delay <= STARTUP_IDLE_S
+
+
[email protected]('config, startup, detach', [
+ ('dashboard:\n ws_orphan_reap_grace_s: 0\n', [], []),
+ ('dashboard:\n startup_orphan_sweep: false\n', [], [300.0]),
+ ('dashboard:\n ws_orphan_reap_grace_s: 0\n startup_orphan_sweep: false\n'
+ 'sessions:\n orphan_end_grace_s: 60\n', [60.0], [60.0]),
+])
+async def test_the_legacy_reap_opt_outs_hold_until_the_new_key_is_set(tmp_path, monkeypatch, config, startup, detach):
+ from gateway.session_local_recovery import recover_local_sessions
+
+ armed = _capture_timers(monkeypatch)
+ _stale_rows(monkeypatch)
+ first, _ = await _owner(tmp_path, monkeypatch)
+ sid = _create(first).session_id
+ await _attach(first, sid)
+ (Path(first.db.db_path).parent / 'config.yaml').write_text(config)
+
+ authority, _ = await _owner(tmp_path, monkeypatch)
+ recover_local_sessions(authority, schedule=True)
+ assert [delay for delay, _ in armed] == startup
+ viewer, _ = await _attach(authority, sid)
+ await viewer.close()
+ assert [delay for delay, _ in armed[len(startup):]] == detach
+
+
@pytest.mark.asyncio
async def test_a_session_left_with_queued_input_ends_after_boot_once_it_drains(tmp_path, monkeypatch):
import gateway.session_finite as finite
@@ -206,6 +255,7 @@ async def test_a_session_left_with_queued_input_ends_after_boot_once_it_drains(t
from hermes_state_runtime import admit_session_input, list_session_admissions
armed = _capture_timers(monkeypatch)
+ _stale_rows(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,
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index b4d78d32caa..2f3c2d93b8e 100644
--- a/website/docs/user-guide/sessions.md
+++ b/website/docs/user-guide/sessions.md
@@ -1198,7 +1198,11 @@ never closed by this sweep.
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
+`end_reason: ws_orphan_reap` (or `startup_orphan_reap` after a restart, no
+sooner than 6 hours after its last activity, since an idle classic CLI only
+reconnects when you next use it). While `orphan_end_grace_s` is unset, the
+legacy `dashboard.ws_orphan_reap_grace_s: 0` turns this off, and
+`dashboard.startup_orphan_sweep: false` turns off the after-restart end. 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