The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): end idle ACP sessions when the last viewer detaches or the gateway stops
Teknium5b1d34f9c53f
diff --git a/acp_adapter/entry.py b/acp_adapter/entry.pyindex 35f1bf6a93b..88b5d2a85fd 100644--- a/acp_adapter/entry.py+++ b/acp_adapter/entry.py@@ -216,8 +216,9 @@ def main(argv: list[str] | None = None) -> None:except Exception:logger.exception("ACP agent crashed")sys.exit(1)- # No ended_at stamp here (#118216 is the in-process adapter's): sessions are daemon-owned and- # may have other viewers or background work, so the daemon's reset lifecycle ends them.+ # No ended_at stamp here: sessions are daemon-owned and may have other viewers or queued work.+ # The owner ends an ACP session when its last viewer detaches with an idle FIFO, and at gateway+ # stop (gateway/session_acp_lifecycle.py, #118216).if __name__ == "__main__":diff --git a/gateway/run_runtime.py b/gateway/run_runtime.pyindex 55d59d7bd4e..11eded4ee4f 100644--- a/gateway/run_runtime.py+++ b/gateway/run_runtime.py@@ -327,3 +327,14 @@ async def settle_gateway_runtime(runner):tasks = [task for authority in _authorities(runner) for task in _authority_tasks(authority)]if tasks:await asyncio.gather(*tasks, return_exceptions=True)+ # Sockets closed in drain_gateway_runtime; work settled above. ACP has no per-session destroy,+ # so the stop is the end of every ACP session nobody is viewing (#118216).+ from gateway.session_acp_lifecycle import end_idle_acp_sessions+ for authority in _authorities(runner):+ try:+ end_idle_acp_sessions(authority)+ except Exception:+ # Best-effort bookkeeping: a store that cannot answer must not abort the stop sequence.+ import logging+ logging.getLogger(__name__).warning('ACP sessions of %s not ended at shutdown',+ getattr(authority, 'profile_id', '?'), exc_info=True)diff --git a/gateway/session_acp_lifecycle.py b/gateway/session_acp_lifecycle.pynew file mode 100644index 00000000000..6eb4cb95723--- /dev/null+++ b/gateway/session_acp_lifecycle.py@@ -0,0 +1,40 @@+"""ACP v0.9 has no per-session destroy: the last viewer leaving an idle ACP session ends it (#118216).++The in-process adapter stamped ``ended_at`` at its stdio shutdown; under the gateway the ACP process+is only a viewer, so the owner stamps it when the last subscription goes or the gateway stops. Without+a writer, source='acp' rows stay open forever and the ended-session guard keeps prune/archive away.+A later ``session/load`` + prompt reopens the row (``session_local_recovery.reopen_local_session``).+"""+import logging++from hermes_state_local import POLICY_PREFIX, end_idle_local_session, local_receipt+from hermes_state_runtime import RuntimeStoreError++ACP_END_REASON = 'acp_disconnect'+++def end_idle_acp_session(authority, session_id):+ """End *session_id* iff it is an ACP-created local session with no viewer and an idle FIFO."""+ live = authority.sessions.get(session_id)+ if live is not None and live.subscribers:+ return False+ try:+ receipt = local_receipt(authority.db, session_id)+ except RuntimeStoreError:+ return False # not a local session: no ACP policy to end+ if receipt.get('policy', {}).get('source') != 'acp':+ return False+ try:+ return bool(end_idle_local_session(authority.db, epoch=authority.epoch, session_id=session_id,+ target_id=receipt['entry']['session_id'], reason=ACP_END_REASON))+ except (RuntimeStoreError, KeyError, TypeError):+ logging.getLogger(__name__).warning('ACP session %s not ended', session_id, exc_info=True)+ return False+++def end_idle_acp_sessions(authority):+ """Gateway shutdown: every ACP session nobody is viewing, attached this run or not."""+ with authority.db._read_ctx() as conn:+ ids = [row[0][len(POLICY_PREFIX):] for row in conn.execute(+ 'SELECT key FROM state_meta WHERE key LIKE ?', (POLICY_PREFIX + '%',))]+ return sum(end_idle_acp_session(authority, sid) for sid in ids)diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 245bb518796..0ad4e3e00bc 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -163,7 +163,7 @@ class SessionAuthority:del live.subscribers[subscription]async def detach(self, actor, subscription_id):- for live in self.sessions.values():+ for session_id, live in self.sessions.items():if subscription_id in live.subscribers:if live.subscribers[subscription_id] != actor:raise RuntimeStoreError('permission_denied')@@ -171,6 +171,9 @@ class SessionAuthority:transport = self.events.get(actor.transport_id)if transport is not None:live.event_stream.fanout.detach(transport)+ if not live.subscribers:+ from gateway.session_acp_lifecycle import end_idle_acp_session+ end_idle_acp_session(self, session_id)returnraise RuntimeStoreError('not_found')diff --git a/hermes_state_local.py b/hermes_state_local.pyindex ee96cefa2c0..1884db545e4 100644--- a/hermes_state_local.py+++ b/hermes_state_local.py@@ -1,5 +1,6 @@"""Private local creation receipts in the canonical runtime transaction owner."""import json+import timefrom hermes_state_runtime import RuntimeStoreError, _epoch, _json@@ -61,3 +62,21 @@ def local_receipt(db, session_id):return valueexcept (TypeError, ValueError) as exc:raise RuntimeStoreError('storage_unavailable') from exc+++def end_idle_local_session(db, *, epoch, session_id, target_id, reason):+ """Stamp ``ended_at`` on *target_id* only while the logical *session_id*'s FIFO is idle.++ The idle check and the stamp share one owner write txn, so an admission committed first keeps+ the row open; one committed after is reopened by the drain (``reopen_local_session``)."""+ def write(conn):+ _epoch(conn, epoch)+ if conn.execute("SELECT 1 FROM session_admissions WHERE target_session_id=? AND status!='terminal'",+ (session_id,)).fetchone():+ return 0+ if conn.execute("SELECT 1 FROM worker_executions WHERE session_id IN (?,?) AND status!='terminal'",+ (session_id, target_id)).fetchone():+ return 0+ return db._end_and_bump(conn, 'UPDATE sessions SET ended_at=?, end_reason=? WHERE id=? AND ended_at IS NULL',+ (time.time(), reason, target_id), target_id, reason)+ return db._execute_write(write)diff --git a/tests/acp_adapter/test_gateway_acp_session_end.py b/tests/acp_adapter/test_gateway_acp_session_end.pynew file mode 100644index 00000000000..ec2738be3d9--- /dev/null+++ b/tests/acp_adapter/test_gateway_acp_session_end.py@@ -0,0 +1,76 @@+"""ACP v0.9 has no per-session destroy: the last viewer leaving an idle ACP session is its end (#118216).++Real authority + SQLite. Without an ``ended_at`` writer on the gateway path, source='acp' rows stay+open forever and the ended-session guard keeps prune/archive away from them.+"""+from types import SimpleNamespace++import pytest+++async def test_last_viewer_or_shutdown_ends_only_idle_acp_sessions(tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.run_runtime import settle_gateway_runtime+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_contract import Submission+ from gateway.session_controls import AuthorityConnection+ from gateway.session_local import create_local_session+ from hermes_state_local import local_receipt++ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': [], 'acp': []}})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda route: None)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='owner')+ db = authority.db++ def viewer():+ return AuthorityConnection(authority, object(), {'user_id': 'human', 'profile_id': 'fixture'})++ owner = viewer().actor++ def create(source, request_id):+ ref = create_local_session(authority, owner, {'request_id': request_id, 'source': source,+ 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []})+ return ref, local_receipt(db, ref.session_id)['entry']['session_id']++ def ended(target):+ row = db.get_session(target)+ return row['ended_at'] is not None, row['end_reason']++ async def resume(connection, ref):+ reply = await connection.dispatch({'id': 1, 'method': 'session.resume',+ 'params': {'session_id': ref.session_id}})+ assert 'result' in reply, reply++ try:+ acp, acp_row = create('acp', 'editor')+ gui, gui_row = create('gui', 'desktop')+ busy, busy_row = create('acp', 'busy-editor')+ unseen, unseen_row = create('acp', 'unseen-editor')+ first, second = viewer(), viewer()+ for connection in (first, second):+ await resume(connection, acp)+ await resume(connection, gui)+ await resume(first, busy)+ authority._schedule = lambda ref: None+ await authority.submit(first.actor, Submission('queued', busy, {'text': 'later'}, 'queue'))++ await first.close()+ assert ended(acp_row) == (False, None), 'another viewer still holds the ACP session'+ assert ended(busy_row) == (False, None), 'a queued admission keeps the ACP session open'+ await second.close()+ assert ended(acp_row) == (True, 'acp_disconnect')+ assert ended(gui_row) == (False, None), 'only ACP sessions end on disconnect'+ assert ended(busy_row) == (False, None)++ # Gateway shutdown ends the ACP sessions nobody is viewing (never attached this run included).+ await settle_gateway_runtime(runner)+ assert ended(unseen_row) == (True, 'acp_disconnect')+ assert ended(busy_row) == (False, None) and ended(gui_row) == (False, None)+ finally:+ store.close_all_db_handles()