The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a failed settlement no longer kills the session drain silently
teknium1fdb57cabd0e7
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex a72835421e8..688c722ab2c 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -36,6 +36,14 @@ class LiveSession:self.controls = PendingControls(self.event_stream)+def _log_drain_failure(task):+ """A dead pump is the one failure this module must never swallow."""+ if task.cancelled() or task.exception() is None:+ return+ import logging+ logging.getLogger(__name__).error('Session drain task died: %r', task.exception())++class SessionAuthority:def __init__(self, runner, *, profile_id, instance_id, db, epoch):self.runner = runner@@ -53,6 +61,9 @@ class SessionAuthority:self.pending_stops = {}def authorize(self, actor, ref, capability):+ """Every handler calls this first, so a later ``self.sessions[ref.session_id]`` is+ safe: a deleted/evicted live entry surfaces here as ``not_found``, not as a KeyError+ deeper in the handler."""if actor.profile_id != self.profile_id or ref.profile_id != self.profile_id:raise RuntimeStoreError('profile_mismatch')if capability not in actor.capabilities:@@ -191,6 +202,7 @@ class SessionAuthority:live = self.sessions[ref.session_id]if live.task is None or live.task.done():live.task = asyncio.create_task(self._drain(ref))+ live.task.add_done_callback(_log_drain_failure)async def admit_automation(self, adapter, event, identity):from gateway.session_automation import admit_automation@@ -463,22 +475,34 @@ class SessionAuthority:logging.getLogger(__name__).exception('Admitted turn %s failed', admission_id)response = 'The admitted turn failed.'outcome = 'failed'- with live.event_stream.lock:- from gateway.session_results import finish_result- settled, response = finish_result(self.db, epoch=self.epoch, row=row,- response=response, outcome=outcome,- result=self.pending_results.pop(admission_id, None))- live.controls.snapshot(ref.session_id, None)- from gateway.session_ingress_media import release_admission_media- release_admission_media(self.db, admission_id)- self._publish_pending(ref)- live.event_stream.publish(ref.session_id, {- 'text': response, 'content': response, 'admission_id': admission_id,- 'outcome': 'cancelled' if settled['outcome'] == 'interrupted' else settled['outcome']})+ try:+ with live.event_stream.lock:+ from gateway.session_results import finish_result+ settled, response = finish_result(self.db, epoch=self.epoch, row=row,+ response=response, outcome=outcome,+ result=self.pending_results.pop(admission_id, None))+ live.controls.snapshot(ref.session_id, None)+ from gateway.session_ingress_media import release_admission_media+ release_admission_media(self.db, admission_id)+ self._publish_pending(ref)+ live.event_stream.publish(ref.session_id, {+ 'text': response, 'content': response, 'admission_id': admission_id,+ 'outcome': 'cancelled' if settled['outcome'] == 'interrupted' else settled['outcome']})+ except Exception:+ # The settle fence lost (a reset/compression moved runtime_generation under+ # the turn). The row stays `started` for recovery -> `unknown`; re-settling+ # it here would forge an outcome the ledger refused. The pump itself must+ # not die silently: log with the id and fall through to release observers.+ import logging+ logging.getLogger(__name__).exception(+ 'Settlement of admission %s failed; left for recovery', admission_id)+ response = 'The admitted turn could not be settled.'+ finally:# The stamp names a claimed, unsettled execution. Left in place, idle# mutations (session.updated) would carry a terminal generation and# a versioned viewer fence would discard them as late frames.- live.event_stream.execution = {}+ with live.event_stream.lock:+ live.event_stream.execution = {}self.pending_stops.pop(ref.session_id, None)waiter = self.waiters.pop(admission_id, None)if waiter is not None and not waiter.done():diff --git a/gateway/session_hosted_transport.py b/gateway/session_hosted_transport.pyindex 010649764a2..01b023c237f 100644--- a/gateway/session_hosted_transport.py+++ b/gateway/session_hosted_transport.py@@ -209,6 +209,10 @@ def install_hosted_transport(server, authority, loop, *, attest):attested = _attest(binding, operation, params)binding['owner'] = attested['owner']principal = _principal(authority, binding)+ # Authorization already happened: every operation, including each attachment+ # chunk, is re-attested at the SOURCE owner above before anything runs here, so+ # the RPC's own authorize hook has nothing left to decide. A new operation must+ # be added to _OPERATIONS (and therefore attested) before it can reach _call.rpc = HostedRoomAuthorityRPC(authority, loop, **selector, principal=principal,authorize=lambda *args: True)key = _BINDING + rpc.ref.session_iddiff --git a/tests/gateway/test_session_authority_cancel_settlement.py b/tests/gateway/test_session_authority_cancel_settlement.pyindex 3c7ad79c372..76aebf44c52 100644--- a/tests/gateway/test_session_authority_cancel_settlement.py+++ b/tests/gateway/test_session_authority_cancel_settlement.py@@ -193,3 +193,37 @@ async def test_stop_before_the_turn_agent_exists_reaches_the_agent_once_it_is_wistopped.set()await asyncio.wait_for(authority.sessions['s'].task, 5)assert agent.interrupted == 0+++async def test_settlement_failure_is_logged_and_does_not_kill_the_drain(tmp_path, monkeypatch, caplog):+ """finish_result can raise (a concurrent reset/compression moved runtime_generation).++ The pump must survive that: the failure is logged with the admission id, the row is+ left for recovery (owner restart -> unknown) rather than silently re-settled, and the+ drain task ends without an unretrieved exception so the FIFO can be re-armed.+ """+ import logging+ from gateway import session_finite++ db, authority = _authority(tmp_path, monkeypatch)++ async def execute(authority, ref, row):+ # Simulate a concurrent lineage move while the turn ran: the settle fence+ # (settle_session_input) compares sessions.runtime_generation to the claim.+ authority.db._execute_write(lambda conn: conn.execute(+ "UPDATE sessions SET runtime_generation=runtime_generation+1 WHERE id='s'"))+ return 'done'+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)++ with db, caplog.at_level(logging.ERROR, logger='gateway.session_authority'):+ head = await _submit(authority, 'moved-under-us')+ task = authority.sessions['s'].task+ await asyncio.wait_for(task, 5)+ assert task.exception() is None, 'a settlement failure must not escape the drain task'+ assert any(head.admission_id in rec.getMessage() for rec in caplog.records), \+ [rec.getMessage() for rec in caplog.records]+ row, = [r for r in list_session_admissions(db, session_id='s', pending_only=False)+ if r['admission_id'] == head.admission_id]+ assert row['status'] == 'started', 'left for recovery, never silently re-settled'+ assert authority.sessions['s'].event_stream.execution == {}, 'stamp cleared even on failure'