The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): settle admitted turns off the owner event loop
Teknium637d54e5dc1e
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 62ba57a209a..936c4caaddc 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -578,15 +578,25 @@ class SessionAuthority:response = 'The admitted turn failed.'outcome = 'failed'settled = None+ settlement = {}try:- with live.event_stream.lock:- from gateway.session_results import finish_result- captured = self.pending_results.get(admission_id)- settled, response = finish_result(self.db, epoch=self.epoch, row=row,- response=response, outcome=outcome, result=captured)- self.pending_results.pop(admission_id, None)- from gateway.session_settlement_recovery import publish_terminal- publish_terminal(self, ref, row, settled, response, captured)+ # Redaction, encoding and the SQLite write run off-loop: one turn's settlement must+ # not stall every other session. Commit and completion share one stream-lock hold+ # there; a tracked writer outlives a cancelled drain like the recovery stamp does.+ from gateway.session_runtime_workers import track_mutation+ from gateway.session_settlement_recovery import commit_and_publish+ captured = self.pending_results.get(admission_id)+ try:+ await asyncio.shield(track_mutation(self, asyncio.to_thread(+ commit_and_publish, self, live, ref, row, response, outcome, captured, settlement)))+ finally:+ if 'settled' in settlement:+ settled, response = settlement['settled'], settlement['response']+ self.pending_results.pop(admission_id, None)+ # Idle follows the completion; its bot receipt wakeups are loop tasks. A delete+ # that committed while the write yielded already retired this live entry.+ if self.sessions.get(ref.session_id) is live:+ self._publish_pending(ref)except Exception:import logginglogging.getLogger(__name__).exception(diff --git a/gateway/session_results.py b/gateway/session_results.pyindex f99bca12a88..30b44f4a8ed 100644--- a/gateway/session_results.py+++ b/gateway/session_results.py@@ -46,11 +46,30 @@ def retain_result(db, *, epoch, row, result):generation=row['generation'], outcome='completed', result=_redacted(result))-def finish_result(db, *, epoch, row, response, outcome, result=None):+def prepare_result(row, response, outcome, result=None):+ """``(outcome, stored_result)``: the outcome the result's own flags imply and the compact,+ redacted copy settlement stores. Pure CPU work, safe off-loop and outside the stream lock."""+ if result is None:+ result = {'result': {'final_response': response or '', 'messages': []}, 'usage': {}}+ value = result['result']+ if value.get('interrupted'):+ outcome = 'interrupted'+ elif value.get('failed') or value.get('error'):+ outcome = 'failed'+ if outcome in ('failed', 'interrupted'):+ value['failed' if outcome == 'failed' else 'interrupted'] = True+ value['completed'] = False+ # Compact before redacting, so the walk covers this turn's output, not every earlier turn.+ from hermes_state_terminal import compact_result+ return outcome, _redacted(compact_result(result, user_message=row['payload'].get('text')))+++def finish_result(db, *, epoch, row, response, outcome, result=None, prepared=None):"""Delivery failure cannot rewrite an already committed execution outcome.`result` is the exact structured result captured in-process; the managedworker path commits its own before this runs and is read back here.+ `prepared` is ``prepare_result``'s output computed before the caller took a lock."""with db._read_ctx() as conn:_epoch(conn, epoch)@@ -64,21 +83,9 @@ def finish_result(db, *, epoch, row, response, outcome, result=None):raise RuntimeStoreError('storage_unavailable')result = json.loads(saved[0])return dict(current), result['result'].get('final_response') or ''- if result is None:- result = {'result': {'final_response': response or '', 'messages': []}, 'usage': {}}- value = result['result']- if value.get('interrupted'):- outcome = 'interrupted'- elif value.get('failed') or value.get('error'):- outcome = 'failed'- if outcome in ('failed', 'interrupted'):- value['failed' if outcome == 'failed' else 'interrupted'] = True- value['completed'] = False- # Compact before redacting, so the walk covers this turn's output, not every earlier turn.- from hermes_state_terminal import compact_result- result = compact_result(result, user_message=row['payload'].get('text'))+ outcome, stored = prepared or prepare_result(row, response, outcome, result)settled = settle_session_input(db, epoch=epoch, admission_id=row['admission_id'],- generation=row['generation'], outcome=outcome, result=_redacted(result))+ generation=row['generation'], outcome=outcome, result=stored)return settled, responsediff --git a/gateway/session_settlement_recovery.py b/gateway/session_settlement_recovery.pyindex 616ee1959a7..5b778b8bfae 100644--- a/gateway/session_settlement_recovery.py+++ b/gateway/session_settlement_recovery.py@@ -59,9 +59,8 @@ def completion_payload(row, settled, response, captured):return complete-def publish_terminal(authority, ref, row, settled, response, captured):- """Cleanup cannot withhold a committed outcome; publication is attempted once."""- live = authority.sessions[ref.session_id]+def _publish_completion(authority, live, ref, row, settled, response, captured):+ """Thread-safe half of terminal publication; the caller holds the stream lock."""try:live.controls.snapshot(ref.session_id, None)except Exception:@@ -72,5 +71,31 @@ def publish_terminal(authority, ref, row, settled, response, captured):except Exception:logger.exception('Terminal media cleanup failed for admission %s', row['admission_id'])live.event_stream.publish(ref.session_id, completion_payload(row, settled, response, captured))+++def commit_and_publish(authority, live, ref, row, response, outcome, captured, settlement):+ """Worker-thread settlement: redaction, encoding and the SQLite write never stall the owner loop.++ The commit and its completion frame share one stream-lock hold, so replay/attach (which take+ that lock) never see the terminal row without its completion. ``settlement`` receives the+ committed ``(settled, response)`` before publication, so a publish failure is not a lost commit.+ The caller publishes idle ``session.info`` on the loop afterwards (bot receipt wakeups are tasks).+ """+ from gateway.session_results import finish_result, prepare_result+ # Compaction, redaction and outcome flags are CPU-only: outside the lock, which then+ # covers only the transaction and the completion frame.+ prepared = prepare_result(row, response, outcome, captured)+ # ``live`` is the drain's own entry: a delete committing on the loop after this write may+ # already have dropped it from ``authority.sessions``.+ with live.event_stream.lock:+ settlement['settled'], settlement['response'] = finish_result(+ authority.db, epoch=authority.epoch, row=row, response=response, outcome=outcome,+ result=captured, prepared=prepared)+ _publish_completion(authority, live, ref, row, settlement['settled'], settlement['response'], captured)+++def publish_terminal(authority, ref, row, settled, response, captured):+ """Cleanup cannot withhold a committed outcome; publication is attempted once."""+ _publish_completion(authority, authority.sessions[ref.session_id], ref, row, settled, response, captured)# Idle follows the completion so a viewer cannot mistake a settled turn for a lost frame.authority._publish_pending(ref)diff --git a/tests/gateway/fixtures/terminal_commit_daemon.py b/tests/gateway/fixtures/terminal_commit_daemon.pyindex 2504f037f72..d368e0038c0 100644--- a/tests/gateway/fixtures/terminal_commit_daemon.py+++ b/tests/gateway/fixtures/terminal_commit_daemon.py@@ -7,8 +7,8 @@ from gateway import session_resultsfinish = session_results.finish_result-def stop_after_commit(db, *, epoch, row, response, outcome, result=None):- receipt = finish(db, epoch=epoch, row=row, response=response, outcome=outcome, result=result)+def stop_after_commit(db, *, row, **kwargs):+ receipt = finish(db, row=row, **kwargs)if row['payload'].get('text') == 'BLOCK_STARTED':os.kill(os.getpid(), signal.SIGSTOP)return receiptdiff --git a/tests/gateway/test_settlement_off_loop.py b/tests/gateway/test_settlement_off_loop.pynew file mode 100644index 00000000000..b54c2b4b9e3--- /dev/null+++ b/tests/gateway/test_settlement_off_loop.py@@ -0,0 +1,50 @@+"""Settlement's write runs off the owner loop; completion, idle info and waiters keep their order."""+import asyncio+import threading++import pytest++from gateway.session_contract import Submission+from hermes_state_runtime import get_session_admission+from tests.gateway.test_session_authority_cancel_settlement import _authority, ACTOR, REF+++async def test_settlement_write_leaves_the_loop_free_and_publishes_in_order(tmp_path, monkeypatch):+ from gateway import session_results+ db, authority = _authority(tmp_path, monkeypatch)+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ loop_ran, events, served_during_write = threading.Event(), [], []+ authority.sessions['s'].event_stream.observers.add(+ lambda frame: events.append((frame['params']['type'], frame['params']['payload'].get('running'))))++ async def execute(owner, ref, row):+ owner.pending_results[row['admission_id']] = {'result': {'final_response': 'done'}, 'usage': {}}+ return 'done'+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ settle = session_results.settle_session_input++ def slow_settle(*args, **kwargs):+ # A contended writer: the owner loop must keep serving other work meanwhile.+ served_during_write.append(loop_ran.wait(2))+ return settle(*args, **kwargs)+ monkeypatch.setattr(session_results, 'settle_session_input', slow_settle)++ async def other_session_work():+ await asyncio.sleep(0.01)+ loop_ran.set()++ with db:+ receipt = await authority.submit(ACTOR, Submission('work', REF, {'text': 'work'}, 'queue'))+ waiter = authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())++ def resolved(_):+ events.append(('waiter', get_session_admission(db, admission_id=receipt.admission_id)['status']))+ waiter.add_done_callback(resolved)+ events.clear()+ other = asyncio.create_task(other_session_work())+ await asyncio.wait_for(authority._drain(REF), 5)+ await other+ await asyncio.sleep(0)+ assert served_during_write == [True], 'the settlement write blocked the owner loop'+ assert events[-3:] == [('message.complete', None), ('session.info', False), ('waiter', 'terminal')], events