The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): deferred-pick acceptance and cleanup run off the event loop
Teknium56cb6d3367b3
diff --git a/gateway/session_deferred_pick.py b/gateway/session_deferred_pick.pyindex e9a3a790a0e..a79711b9cda 100644--- a/gateway/session_deferred_pick.py+++ b/gateway/session_deferred_pick.py@@ -56,8 +56,11 @@ async def apply_deferred_pick(authority, ref, live):from gateway.session_mutations import write_mutationfrom hermes_state_mutation_retirement import has_mutation_receiptkey = _PREFIX + ref.session_id- with authority.db._read_ctx() as conn:- stored = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()++ def read():+ with authority.db._read_ctx() as conn:+ return conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()+ stored = await asyncio.to_thread(read)if stored is None:returnpick = json.loads(stored[0])@@ -82,7 +85,7 @@ async def apply_deferred_pick(authority, ref, live):if exc.reason == 'session_busy':returnresult = {'session_id': ref.session_id, 'operation': 'model', 'status': 'refused', 'reason': exc.reason}- authority.db._execute_write(lambda conn: conn.execute(+ await asyncio.to_thread(authority.db._execute_write, lambda conn: conn.execute('DELETE FROM state_meta WHERE key=? AND value=?', (key, stored[0])))if result.get('status') in {'refused', 'confirmation_required'}:logger.warning('Deferred model pick on %s not applied: %s', ref.session_id,diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex 505cc34ea15..210722fdd2a 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -100,7 +100,8 @@ async def _owned_mutation(authority, actor, ref, params):if params.get('operation') != 'model' or getattr(exc, 'reason', 'session_busy') != 'session_busy':raisefrom gateway.session_deferred_pick import defer_pick- return defer_pick(authority, actor, ref, params)+ # Its own BEGIN IMMEDIATE: off the loop, like the receipt commit.+ return await asyncio.to_thread(defer_pick, authority, actor, ref, params)if params.get('operation') in {*_POLICY, 'compress', 'reset'}:authority._schedule(ref)return resultdiff --git a/tests/gateway/test_session_mutation_model_busy.py b/tests/gateway/test_session_mutation_model_busy.pyindex 3d4268263d5..c73693c9ecf 100644--- a/tests/gateway/test_session_mutation_model_busy.py+++ b/tests/gateway/test_session_mutation_model_busy.py@@ -185,3 +185,47 @@ async def test_a_newer_idle_pick_replaces_an_older_pending_pick(tmp_path, monkeyfinally:await owner.close()store.close_all_db_handles()+++async def test_pending_pick_writes_do_not_stall_the_event_loop(tmp_path, monkeypatch):+ import time+ from gateway.session_contract import Submission+ started, release = threading.Event(), asyncio.Event()+ state = {}++ async def handle(event):+ if event.text == 'RUNNING':+ started.set()+ await release.wait()+ return 'ok'+ store, db, authority, owner, ref = _owner(tmp_path, monkeypatch, handle)+ state.update(authority=authority, ref=ref)+ gaps = []++ async def heartbeat():+ while True:+ before = time.monotonic()+ await asyncio.sleep(0.01)+ gaps.append(time.monotonic() - before)+ try:+ await authority.submit(owner.actor, Submission('running', ref, {'text': 'RUNNING'}, 'queue'))+ await async_wait_until(started.is_set, timeout=10, what='the first turn is running')+ write = db._execute_write++ def contended(fn, *a, **k): # a writer lock held elsewhere (transcript write, maintenance)+ time.sleep(0.4)+ return write(fn, *a, **k)+ monkeypatch.setattr(db, '_execute_write', contended)+ beat = asyncio.create_task(heartbeat())+ reply = await _mutate(owner, db, ref, 'pick', 'picked')+ assert reply['result']['status'] == 'deferred', reply+ release.set()+ await async_wait_until(lambda: _running_model(authority, ref) == 'picked',+ timeout=20, what='the pick published at the turn boundary')+ beat.cancel()+ assert max(gaps) < 0.3, max(gaps)+ finally:+ release.set()+ await owner.close()+ store.close_all_db_handles()