The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): let the live session listing give the loop a turn, and stop hydrating a row per session
qby2d7f9b5f2a57
diff --git a/gateway/session_active_list.py b/gateway/session_active_list.pyindex f19b1c8757a..2aa7298311f 100644--- a/gateway/session_active_list.py+++ b/gateway/session_active_list.py@@ -9,7 +9,9 @@ turn that was still running. Rows keep ``server._session_live_item``'s shape; ``"""from __future__ import annotations-from gateway.session_contract import SessionRef+import asyncio++from gateway.session_contract import LISTING_YIELD_EVERY, SessionReffrom hermes_state_runtime import RuntimeStoreError@@ -31,7 +33,11 @@ async def active_list(connection, ref, params):authority = connection.authoritycurrent = str(params.get('current_session_id') or '')rows = []- for sid, live in tuple(authority.sessions.items()):+ for index, (sid, live) in enumerate(tuple(authority.sessions.items())):+ if index and not index % LISTING_YIELD_EVERY:+ # Same reason as ``session.list``: this walks every live session on the loop that also+ # serves the turns' own I/O, so a long list must give it a turn per batch.+ await asyncio.sleep(0)candidate = SessionRef(connection.actor.profile_id, sid)try:handle = await authority.resolve(connection.actor, candidate)@@ -39,7 +45,7 @@ async def active_list(connection, ref, params):if exc.reason not in {'permission_denied', 'profile_mismatch', 'not_found'}:raisecontinue- row = authority.db.get_session(sid) or {}+ row = authority.db.get_session_list_row(sid) or {}# The same population as the live ``session.list`` feed, hidden chats included: a hidden# chat open in a pane still needs its turn's liveness.if row.get('source') in INTERNAL_LISTING_SOURCES or closed_and_unviewed(authority, sid, handle):diff --git a/gateway/session_contract.py b/gateway/session_contract.pyindex dda3763a395..8fb7697a7d9 100644--- a/gateway/session_contract.py+++ b/gateway/session_contract.py@@ -8,6 +8,11 @@ JsonObject = Mapping[str, object]# Authenticated local WebSocket family, separate from the legacy Desktop API contract.CANONICAL_GATEWAY_PROTOCOL = 'hermes-gateway-v1'+# The live listings (`session.list`, `session.active_list`) walk every live session in one request+# on the gateway's loop, the thread that also serves platform I/O, WS dispatch and delivery. Yield+# this often so a long list interleaves instead of holding the thread for its whole duration.+LISTING_YIELD_EVERY = 64+@dataclass(frozen=True)class Principal:diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 3e535162fa9..8b16b3c36b6 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -9,7 +9,8 @@ import sqlite3import uuidfrom gateway.config import Platform-from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL, Principal, SessionRef, Submission+from gateway.session_contract import (+ CANONICAL_GATEWAY_PROTOCOL, LISTING_YIELD_EVERY, Principal, SessionRef, Submission)from gateway.session_llm_oneshot import DeferredReplyfrom hermes_constants import profile_name_for_homefrom hermes_state_runtime import RuntimeStoreError@@ -540,7 +541,11 @@ class AuthorityConnection:'scope': 'stored'}from hermes_state_sessions import INTERNAL_LISTING_SOURCESsessions = []- for sid in tuple(self.authority.sessions):+ for index, sid in enumerate(tuple(self.authority.sessions)):+ if index and not index % LISTING_YIELD_EVERY:+ # A few thousand live rows must not hold the loop: platform I/O, the adapter's stop+ # path and WS writes share this thread, and a stall there reads as their own failure.+ await asyncio.sleep(0)candidate = SessionRef(self.actor.profile_id, sid)try:handle = await self.authority.resolve(self.actor, candidate)@@ -548,7 +553,7 @@ class AuthorityConnection:if exc.reason not in {'permission_denied', 'profile_mismatch', 'not_found'}:raisecontinue- row = self.authority.db.get_session(sid)+ row = self.authority.db.get_session_list_row(sid) or {}# The human picker feed (TUI switcher): kanban workers, `--source tool` integrations and# finite one-shot runs are not conversations, as on every other picker.if row.get('source') in INTERNAL_LISTING_SOURCES or (diff --git a/gateway/session_local_close.py b/gateway/session_local_close.pyindex 4be14557305..156902f628b 100644--- a/gateway/session_local_close.py+++ b/gateway/session_local_close.py@@ -17,12 +17,16 @@ def _local_target(authority, session_id):def closed_and_unviewed(authority, session_id, handle):- """A live-feed row main would list as resumable: closed, idle and with no viewer left."""+ """A live-feed row main would list as resumable: closed, idle and with no viewer left.++ Reads the local target's own columns rather than hydrating the row: the listing asks this per+ session on the gateway's loop, where a ``get_session`` (prompt/tool JOIN + token flush) per+ candidate is the cost the sweep must not pay."""live = authority.sessions.get(session_id)if live is None or live.subscribers or handle.execution_state != 'idle':return Falseif live.superseded:return True # an old messaging conversation opened read-only: history once no one views ittarget = _local_target(authority, session_id)- row = authority.db.get_session(target) if target else None+ row = authority.db.get_session_list_row(target) if target else Nonereturn bool(row and row.get('ended_at') is not None)diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex 6bffd01cede..71351917175 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -841,6 +841,18 @@ class SessionSessionsMixin:)return self._session_row_dict(row) if row else None+ def get_session_list_row(self, session_id: str) -> Optional[dict[str, Any]]:+ """The picker fields only, without ``get_session``'s prompt/tool JOIN and token flush.++ The live listing reads one row per listed session on the gateway's loop; a full hydration+ there is the cost the sweep does not need (title/source/activity/is-it-closed are columns)."""+ row = self._read_one(+ "SELECT id, source, title, started_at, ended_at, message_count, model, hidden, archived "+ "FROM sessions WHERE id = ?",+ (session_id,),+ )+ return dict(row) if row else None+def get_recent_session_model_route(self, session_id: str) -> Optional[dict[str, Any]]:"""Most recently used main-loop model route as one coherent per-call tuple(``session_model_usage`` keeps model+provider together; ``sessions`` mixes route changes).diff --git a/tests/gateway/test_authority_listing_loop_turns.py b/tests/gateway/test_authority_listing_loop_turns.pynew file mode 100644index 00000000000..932942313b9--- /dev/null+++ b/tests/gateway/test_authority_listing_loop_turns.py@@ -0,0 +1,141 @@+"""The live listings walk every live session, on the loop the gateway serves I/O from.++A gateway can hold thousands of live session rows; ``session.list`` / ``session.active_list`` walk+the authority's sessions in one request, and every step of that walk was synchronous DB work with+no suspension point, so the whole listing ran as one uninterruptible block on the loop thread.+Anything that needed the loop meanwhile — a platform adapter's stop path, a WS write, delivery —+waited for it; measured on a 4,049-row store the loop stalled past 10 s, the Telegram adapter's+``updater.stop()`` missed its deadline and the adapter was declared fatal (#141236).++These tests pin the two properties the sweep needs: it gives the loop a turn every batch, and it+reads the picker's own columns instead of hydrating a full row (prompt/tool JOIN + token flush)+per session.+"""+import asyncio+from types import SimpleNamespace++import pytest+import pytest_asyncio++from gateway.session_contract import SessionRef++SESSION_COUNT = 130 # more than one LISTING_YIELD_EVERY batch+++@pytest_asyncio.fixture+async def owner(tmp_path, monkeypatch):+ from gateway.config import GatewayConfig, Platform+ from gateway.session import SessionSource, SessionStore+ from gateway.session_authority import LiveSession, initialize_session_authority+ from gateway.session_controls import AuthorityConnection++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(_session_db=store._db, session_store=store, _draining=False,+ _handle_message=None, _adapter_for_source=lambda source: None)+ authority = await initialize_session_authority(runner, profile_id='live', instance_id='owner')+ sids = []+ for index in range(SESSION_COUNT):+ sid = f'sess-{index:03d}'+ store._db.create_session(sid, source='telegram')+ authority.sessions[sid] = LiveSession(SessionSource(platform=Platform.TELEGRAM, chat_id=sid), sid)+ sids.append(sid)+ connection = AuthorityConnection(authority, object(), {'user_id': 'viewer'})++ async def listing(method, **params):+ reply = await connection.dispatch({'id': 1, 'method': method, 'params': params})+ assert 'result' in reply, reply+ return reply['result']['sessions']++ yield SimpleNamespace(authority=authority, db=store._db, sids=sids, listing=listing,+ connection=connection)+++async def test_the_live_listing_gives_the_loop_a_turn_before_it_returns(owner):+ """A listing must not hold the loop for the whole walk: another task runs while it is in flight."""+ order = []++ async def sweep():+ await owner.listing('session.list', limit=200)+ order.append('listing')++ async def competing():+ order.append('competing')++ # Scheduled in this order, so an unyielding sweep appends first and the loop only gets the+ # competing task after the whole walk.+ await asyncio.gather(sweep(), competing())+ assert order == ['competing', 'listing'], order+++async def test_the_active_listing_gives_the_loop_a_turn_before_it_returns(owner):+ order = []++ async def sweep():+ await owner.listing('session.active_list')+ order.append('listing')++ async def competing():+ order.append('competing')++ await asyncio.gather(sweep(), competing())+ assert order == ['competing', 'listing'], order+++async def test_the_live_listing_does_not_hydrate_a_row_per_session(owner, monkeypatch):+ """``get_session`` is a full hydration; the walk needs columns, not the row."""+ hydrated = []+ original = type(owner.db).get_session++ def counting_get_session(db, session_id):+ hydrated.append(session_id)+ return original(db, session_id)++ monkeypatch.setattr(type(owner.db), 'get_session', counting_get_session)+ rows = await owner.listing('session.list', limit=200)+ assert len(rows) == SESSION_COUNT+ # One hydration per session is ``resolve``/``_handle``'s own read (it needs the runtime+ # revision/generation). The listing's own reads must not add any.+ assert len(hydrated) <= SESSION_COUNT, (len(hydrated), SESSION_COUNT)+++def test_closed_and_unviewed_reads_the_row_without_hydrating(monkeypatch):+ """The per-candidate close test reads ``ended_at``, and must not hydrate the whole row."""+ from gateway import session_local_close++ monkeypatch.setattr(session_local_close, 'local_receipt',+ lambda db, session_id: {'entry': {'session_id': 'target'}})++ class Db:+ def __init__(self):+ self.hydrated = []++ def get_session(self, session_id):+ self.hydrated.append(session_id)+ return {'id': session_id, 'ended_at': 1.0}++ def get_session_list_row(self, session_id):+ return {'id': session_id, 'ended_at': 1.0}++ db = Db()+ authority = SimpleNamespace(sessions={'live-1': SimpleNamespace(subscribers={})}, db=db)+ handle = SimpleNamespace(execution_state='idle')+ assert session_local_close.closed_and_unviewed(authority, 'live-1', handle) is True+ assert db.hydrated == []+++def test_closed_and_unviewed_keeps_an_open_row_listed(monkeypatch):+ """The light read keeps the rule: an open target is listed, a closed one is not."""+ from gateway import session_local_close++ monkeypatch.setattr(session_local_close, 'local_receipt',+ lambda db, session_id: {'entry': {'session_id': 'target'}})+ authority = SimpleNamespace(+ sessions={'live-1': SimpleNamespace(subscribers={})},+ db=SimpleNamespace(get_session_list_row=lambda session_id: {'id': session_id, 'ended_at': None},+ get_session=lambda session_id: {'id': session_id, 'ended_at': None}))+ assert session_local_close.closed_and_unviewed(+ authority, 'live-1', SimpleNamespace(execution_state='idle')) is False