The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): no synchronous SQLite write on the owner loop (class sweep)
Tekniumce9a3cfc4913
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 42bf2000830..d0ecd63c40f 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -153,13 +153,22 @@ class SessionAuthority:return self.db.get_compression_tip(ref.session_id) or ref.session_iddef register(self, source):+ return self._publish_route(source, *self._reserve_route(source))++ def _reserve_route(self, source):+ """The durable half of ``register`` (routing entry + reserved row): thread-safe, so async+ callers run it off the owner loop and publish the live entry on the loop."""self._require_admission_open()entry = self.runner.session_store.get_or_create_session(source)sid = self.logical_owner(entry.session_id)- self.sessions.setdefault(sid, LiveSession(source, entry.session_key))# SessionStore reserves routing metadata before the first AIAgent exists.if self.db.get_session(sid) is None:self.db.create_session(sid, source=source.platform.value)+ return sid, entry.session_key++ def _publish_route(self, source, sid, route):+ self._require_admission_open()+ self.sessions.setdefault(sid, LiveSession(source, route))return SessionRef(self.profile_id, sid)def agent(self, ref):@@ -230,7 +239,7 @@ class SessionAuthority: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)+ await asyncio.to_thread(end_idle_acp_session, self, session_id)returnraise RuntimeStoreError('not_found')@@ -311,7 +320,7 @@ class SessionAuthority:payload = await prepare_native(self.runner, event)self._require_admission_open()source = restore_native(payload).source- ref = self.register(source)+ ref = self._publish_route(source, *await asyncio.to_thread(self._reserve_route, source))identity = json.dumps([source.profile, source.platform.value, source.chat_id,source.thread_id, source.user_id], separators=(',', ':'))from gateway.session_runtime_workers import tracked_write@@ -765,7 +774,11 @@ class SessionAuthority:live.pause_notified = Falseif row is None:from gateway.session_acp_lifecycle import end_idle_acp_session- end_idle_acp_session(self, ref.session_id)+ # A write (idle check + stamp in one txn): off-loop. Input scheduled meanwhile set+ # ``rescan`` on this still-live drain, which must claim it rather than exit.+ await asyncio.to_thread(end_idle_acp_session, self, ref.session_id)+ if live.rescan:+ continuereturnadmission_id = row['admission_id']try:@@ -888,8 +901,9 @@ async def initialize_session_authority(runner, *, profile_id, instance_id, db=No# yielding, so no other task observes a half-registered authority.from pathlib import Pathdb_key = await asyncio.to_thread(Path(db.db_path).resolve)- epoch = begin_runtime_epoch(db, instance_id=instance_id)- recover_session_inputs(db, epoch=epoch)+ epoch = await asyncio.to_thread(begin_runtime_epoch, db, instance_id=instance_id)+ # Hot-serve builds a profile while the loop serves the others: both writes stay off it.+ await asyncio.to_thread(recover_session_inputs, db, epoch=epoch)authority = SessionAuthority(runner, profile_id=profile_id, instance_id=instance_id, db=db, epoch=epoch)if register:runner.session_authority = authoritydiff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 56e301b7a81..5cca84a4c8e 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -1,4 +1,5 @@"""Authenticated WS projection of the gateway authority; no TUI execution fallback."""+import asynciofrom dataclasses import asdictfrom pathlib import Pathimport sqlite3@@ -261,7 +262,6 @@ class AuthorityConnection:if 'skills' in params:# Skill files are read off the owner loop, once per NEW session (a retried# request_id resumes the frozen policy and never re-renders).- import asynciofrom gateway.session_local_recovery import local_identityfrom gateway.session_policy import render_launch_skillsparams.setdefault('request_id', uuid.uuid4().hex)@@ -270,15 +270,14 @@ class AuthorityConnection:skills_prompt = await asyncio.to_thread(render_launch_skills, params, sid)ref = create_local_session(self.authority, self.actor, params, skills_prompt=skills_prompt)if params.get('accept_hooks') is True:- import asynciofrom gateway.session_policy import accept_launch_hooks, restore_policyfrom hermes_state_local import local_receiptpolicy = restore_policy(local_receipt(self.authority.db, ref.session_id)['policy'])await asyncio.to_thread(accept_launch_hooks, policy)if title:- title_new_session(self.authority, ref, title)+ await asyncio.to_thread(title_new_session, self.authority, ref, title)if hidden:- self.authority.db.set_session_hidden(ref.session_id, True)+ await asyncio.to_thread(self.authority.db.set_session_hidden, ref.session_id, True)return await self.resume(ref, {})async def ping(self, ref, params):diff --git a/tests/gateway/test_owner_loop_writes_class.py b/tests/gateway/test_owner_loop_writes_class.pynew file mode 100644index 00000000000..f7fee79af62--- /dev/null+++ b/tests/gateway/test_owner_loop_writes_class.py@@ -0,0 +1,165 @@+"""Bug class: a synchronous SQLite write reached from an ``async def`` on the owner loop.++Every row drives the real authority verb end to end and asserts the named write ran off the+owner-loop thread (the population is listed in SWEEP_owner_loop_writes.md; the contended-writer+stall itself is shown by test_mutation_prepare_off_loop / test_claim_reopen_off_loop).+"""+import asyncio+import threading+from types import SimpleNamespace++import pytest+++def _owner(tmp_path, monkeypatch, handle):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import SessionAuthority+ from gateway.session_controls import AuthorityConnection+ import hermes_state_runtime as rt+ monkeypatch.setattr(run, '_load_gateway_config', lambda *a: {})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ db = store._db+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,+ _evict_cached_agent=lambda route: None, _handle_message=handle,+ _cached_agent_for=lambda route: None,+ _resolve_session_agent_runtime=lambda **k: ('frozen', {}))+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db,+ epoch=rt.begin_runtime_epoch(db, instance_id='owner'))+ return store, authority, AuthorityConnection(authority, object(), {'user_id': 'human'})+++def _local(authority, owner, tmp_path, source='cli', request_id='m'):+ from gateway.session_local import create_local_session+ return create_local_session(authority, owner.actor, dict(+ request_id=request_id, source=source, cwd=str(tmp_path), model='frozen', toolsets=[]))+++async def _terminal(db, receipt):+ import hermes_state_runtime as rt+ async with asyncio.timeout(10):+ while rt.get_session_admission(db, admission_id=receipt.admission_id)['status'] != 'terminal':+ await asyncio.sleep(0.02)+++async def _model_prepare(authority, owner, tmp_path, db):+ from hermes_cli import model_switch+ model_switch_real = model_switch.switch_model+ model_switch.switch_model = lambda **k: model_switch.ModelSwitchResult(+ success=True, new_model='switched', target_provider='custom', base_url='http://127.0.0.1:9/v1')+ try:+ ref = _local(authority, owner, tmp_path)+ snap = db.get_session(ref.session_id)+ reply = await owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {+ 'session_id': ref.session_id, 'request_id': 'switch', 'expected_revision': snap['runtime_revision'],+ 'expected_generation': snap['runtime_generation'], 'operation': 'model',+ 'payload': {'model': 'switched'}}})+ finally:+ model_switch.switch_model = model_switch_real+ assert reply['result']['model'] == 'switched', reply+++async def _claim_reopen(authority, owner, tmp_path, db):+ from gateway.session_contract import Submission+ ref = _local(authority, owner, tmp_path)+ db.end_session(ref.session_id, 'tui_shutdown')+ await _terminal(db, await authority.submit(owner.actor, Submission('first', ref, {'text': 'FIRST'}, 'queue')))+ assert db.get_session(ref.session_id)['end_reason'] is None+++async def _acp_idle_after_turn(authority, owner, tmp_path, db):+ from gateway.session_contract import Submission+ ref = _local(authority, owner, tmp_path, source='acp')+ await _terminal(db, await authority.submit(owner.actor, Submission('acp', ref, {'text': 'ACP'}, 'queue')))+ async with asyncio.timeout(10):+ await authority.sessions[ref.session_id].task+ assert db.get_session(ref.session_id)['end_reason'] is not None+++async def _acp_detach(authority, owner, tmp_path, db):+ ref = _local(authority, owner, tmp_path, source='acp')+ snapshot = await authority.attach(owner.actor, ref)+ await authority.detach(owner.actor, snapshot.subscription_id)+ assert db.get_session(ref.session_id)['end_reason'] is not None+++async def _create_titled_hidden(authority, owner, tmp_path, db):+ reply = await owner.dispatch({'id': 1, 'method': 'session.create', 'params': {+ 'request_id': 'titled', 'source': 'cli', 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': [],+ 'title': 'My Title', 'hidden': True}})+ assert 'result' in reply, reply+++async def _native_register(authority, owner, tmp_path, db):+ from gateway.config import Platform+ from gateway.session import SessionSource+ from gateway import session_envelope+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='c', user_id='u')+ payload = {'native_text_v1': {'event': {'message_id': 'm1', 'text': 'hi'}}}++ async def prepare_native(runner, event):+ return payload+ session_envelope_prepare = session_envelope.prepare_native+ session_envelope.prepare_native = prepare_native+ original_restore = session_envelope.restore_native+ session_envelope.restore_native = lambda payload, runner=None: SimpleNamespace(source=source)+ authority._admit_native_write = lambda **k: {'admission_id': 'a', 'status': 'queued'}+ authority._admitted = lambda ref, event, row: row+ authority._schedule = lambda ref: None+ try:+ await authority.admit_native(SimpleNamespace())+ finally:+ session_envelope.prepare_native = session_envelope_prepare+ session_envelope.restore_native = original_restore+++async def _initialize(authority, owner, tmp_path, db):+ from gateway.session_authority import initialize_session_authority+ authority.runner.session_authority = None+ authority.runner._session_db = db+ await initialize_session_authority(authority.runner, profile_id='owned', instance_id='second')+++# (case, module holding the write's name, name, driver): the writer lock is taken just before+# the named call runs.+CASES = [+ ('model-prepare', 'gateway.session_mutations', 'mutate_runtime_session', _model_prepare),+ ('claim-reopen', 'gateway.session_local_recovery', 'reopen_local_session', _claim_reopen),+ ('acp-idle-after-turn', 'gateway.session_acp_lifecycle', 'end_idle_local_session', _acp_idle_after_turn),+ ('acp-detach', 'gateway.session_acp_lifecycle', 'end_idle_local_session', _acp_detach),+ ('create-title-hidden', 'gateway.session_local_title', 'title_new_session', _create_titled_hidden),+ ('native-register', 'gateway.session.SessionStore', 'get_or_create_session', _native_register),+ ('initialize-epoch', 'gateway.session_authority', 'begin_runtime_epoch', _initialize),+]++[email protected]('case,module,name,drive', CASES, ids=[c[0] for c in CASES])+async def test_in_class_write_never_runs_on_the_owner_loop_thread(tmp_path, monkeypatch, case, module, name, drive):+ """Each in-class write is wrapped where it is called; the wrapper records the thread it ran on.+ On the owner-loop thread, a contended writer lock (up to _WRITE_PATIENCE_S) freezes every session."""+ import importlib+ async def handle(event):+ return 'ok'+ store, authority, owner = _owner(tmp_path, monkeypatch, handle)+ loop_thread = threading.get_ident()+ if module.endswith('.SessionStore'):+ target = importlib.import_module(module.rsplit('.', 1)[0]).SessionStore+ else:+ target = importlib.import_module(module)+ real, threads = getattr(target, name), []++ def recorded(*args, **kwargs):+ if name != 'mutate_runtime_session' or kwargs.get('_prepare_only'):+ threads.append(threading.get_ident())+ return real(*args, **kwargs)+ monkeypatch.setattr(target, name, recorded)+ try:+ await drive(authority, owner, tmp_path, store._db)+ assert threads, f'{case}: the in-class write never ran'+ assert loop_thread not in threads, f'{case}: the write ran on the owner loop thread'+ finally:+ await owner.close()+ store.close_all_db_handles()