The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): retain failed settlements as recoverable unknown admissions
David Dudok de Wit562aeb62f398
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 332dc632f42..62ba57a209a 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -407,6 +407,7 @@ class SessionAuthority:row = resolve_unknown_session_input(self.db, epoch=self.epoch, admission_id=admission_id,generation=generation,_terminal_write=lambda conn, lost: close_discarded_turn(self.db, conn, lost))+ self.pending_results.pop(admission_id, None)# Its own write txn + unlink, so it runs after the resolution commits; a discarded image# would otherwise stay on disk forever (the drain releases only settled turns).from gateway.session_ingress_media import release_admission_media@@ -576,55 +577,61 @@ class SessionAuthority:logging.getLogger(__name__).exception('Admitted turn %s failed', admission_id)response = 'The admitted turn failed.'outcome = 'failed'+ settled = Nonetry:with live.event_stream.lock:from gateway.session_results import finish_result- captured = self.pending_results.pop(admission_id, None)+ captured = self.pending_results.get(admission_id)settled, response = finish_result(self.db, epoch=self.epoch, row=row,response=response, outcome=outcome, result=captured)- live.controls.snapshot(ref.session_id, None)- from gateway.session_ingress_media import release_admission_media- release_admission_media(self.db, admission_id)- # ``status`` is the message.complete contract's TurnStatus: the Desktop- # extends a Stopped bubble to the persisted partial only on 'interrupted'.- complete = {- 'text': response, 'content': response, 'admission_id': admission_id,- 'outcome': 'cancelled' if settled['outcome'] == 'interrupted' else settled['outcome'],- 'status': {'completed': 'complete', 'interrupted': 'interrupted'}.get(- settled['outcome'], 'error')}- # Only the agent's reuse site sets this (never inferred from equal text): the- # final repeats a reply the viewer already painted, so it settles in place.- captured_result = (captured or {}).get('result') or {}- if response and captured_result.get('response_reused'):- complete['response_reused'] = True- # The committed row addresses of the turn: a viewer binds the streamed reply to- # its stored row, so a transcript read racing this frame never paints it twice.- # ``submission_id`` names whose turn it is: the sending viewer binds its optimistic- # prompt (``user-<submission_id>``), which the queued admission ack could not name.- if isinstance(captured_result.get('persisted_turn'), dict):- complete['persisted_turn'] = {**captured_result['persisted_turn'],- 'submission_id': row['request_id']}- live.event_stream.publish(ref.session_id, complete)- # The idle snapshot (running=false) follows the completion, as on every other- # host: a viewer that read running=false first settled the reply as a turn whose- # terminal frame was lost and raced its own transcript read against the real one.- self._publish_pending(ref)+ self.pending_results.pop(admission_id, None)+ from gateway.session_settlement_recovery import publish_terminal+ publish_terminal(self, ref, row, settled, response, captured)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 logginglogging.getLogger(__name__).exception(- 'Settlement of admission %s failed; left for recovery', admission_id)- response = 'The admitted turn could not be settled.'+ 'Settlement or publication of admission %s failed', admission_id)+ if settled is None:+ self.pending_results.setdefault(admission_id, {+ 'result': {'final_response': response, 'failed': outcome == 'failed'}, 'usage': {}})+ from gateway.session_settlement_recovery import recover_failed_settlement+ try:+ status = await recover_failed_settlement(self, row)+ except RuntimeStoreError:+ # Ownership moved; this owner may only release its process-local observers.+ self._pause(ref, 'unknown_execution')+ return+ # Discard can race the off-loop recovery stamp; its terminal decision wins.+ current = get_session_admission(self.db, admission_id=admission_id)+ status = current['status']+ if status == 'unknown':+ self._publish_pending(ref)+ self._pause(ref, 'unknown_execution')+ return+ # A write can commit before reporting failure. Re-read its exact result,+ # then publish the terminal outcome rather than inventing uncertainty.+ from gateway.session_results import admission_result+ from gateway.session_settlement_recovery import publish_terminal+ with live.event_stream.lock:+ captured = admission_result(self.db, admission_id)+ self.pending_results.pop(admission_id, None)+ if captured is None:+ # An operator discarded uncertainty while recovery yielded. There is+ # no committed answer to replay; its queued successor may now run.+ waiter = self.waiters.pop(admission_id, None)+ if waiter is not None and not waiter.done():+ waiter.set_exception(RuntimeStoreError('unknown_execution'))+ continue+ settled = current+ response = captured['result'].get('final_response') or ''+ publish_terminal(self, ref, row, settled, response, captured)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.with live.event_stream.lock:live.event_stream.execution = {}- self.pending_stops.pop(ref.session_id, None)+ self.pending_stops.pop(ref.session_id, None)waiter = self.waiters.pop(admission_id, None)if waiter is not None and not waiter.done():waiter.set_result(response)diff --git a/gateway/session_settlement_recovery.py b/gateway/session_settlement_recovery.pynew file mode 100644index 00000000000..616ee1959a7--- /dev/null+++ b/gateway/session_settlement_recovery.py@@ -0,0 +1,76 @@+"""Fence an unsettled claim in a live owner without inventing a terminal result."""+import asyncio+import logging+import sqlite3++from hermes_state_runtime import RuntimeStoreError, _admission, _epoch++logger = logging.getLogger(__name__)+++def _mark_unknown(authority, row):+ def write(conn):+ _epoch(conn, authority.epoch)+ current = _admission(conn, row['admission_id'])+ if current['owner_epoch'] != authority.epoch or current['generation'] != row['generation']:+ raise RuntimeStoreError('stale_generation')+ if current['status'] in {'terminal', 'unknown'}:+ return current['status']+ if current['status'] != 'started':+ raise RuntimeStoreError('stale_generation')+ conn.execute("UPDATE session_admissions SET status='unknown' WHERE admission_id=?", (row['admission_id'],))+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (row['target_session_id'],))+ return 'unknown'+ return authority.db._execute_write(write)+++async def recover_failed_settlement(authority, row):+ # A full disk or held SQLite writer may also block the recovery stamp. Retain this owner+ # and its captured result until the storage fence can commit; never manufacture a reply.+ while True:+ try:+ from gateway.session_runtime_workers import track_mutation+ writer = track_mutation(authority, asyncio.to_thread(_mark_unknown, authority, row))+ return await asyncio.shield(writer)+ except (OSError, sqlite3.Error):+ await asyncio.sleep(1)+++def completion_payload(row, settled, response, captured):+ # ``status`` is the message.complete contract's TurnStatus: the Desktop+ # extends a Stopped bubble to the persisted partial only on 'interrupted'.+ complete = {+ 'text': response, 'content': response, 'admission_id': row['admission_id'],+ 'outcome': 'cancelled' if settled['outcome'] == 'interrupted' else settled['outcome'],+ 'status': {'completed': 'complete', 'interrupted': 'interrupted'}.get(+ settled['outcome'], 'error')}+ # Only the agent's reuse site sets this (never inferred from equal text): the+ # final repeats a reply the viewer already painted, so it settles in place.+ captured_result = (captured or {}).get('result') or {}+ if response and captured_result.get('response_reused'):+ complete['response_reused'] = True+ # The committed row addresses of the turn: a viewer binds the streamed reply to+ # its stored row, so a transcript read racing this frame never paints it twice.+ # ``submission_id`` names whose turn it is: the sending viewer binds its optimistic+ # prompt (``user-<submission_id>``), which the queued admission ack could not name.+ if isinstance(captured_result.get('persisted_turn'), dict):+ complete['persisted_turn'] = {**captured_result['persisted_turn'],+ 'submission_id': row['request_id']}+ 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]+ try:+ live.controls.snapshot(ref.session_id, None)+ except Exception:+ logger.exception('Terminal control cleanup failed for admission %s', row['admission_id'])+ try:+ from gateway.session_ingress_media import release_admission_media+ release_admission_media(authority.db, row['admission_id'])+ 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))+ # 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/test_adversarial_settlement_review.py b/tests/gateway/test_adversarial_settlement_review.pynew file mode 100644index 00000000000..8d8b32a75f9--- /dev/null+++ b/tests/gateway/test_adversarial_settlement_review.py@@ -0,0 +1,128 @@+"""Independent probes for failed-settlement cleanup and ownership races."""+import asyncio+from pathlib import Path+import threading++import pytest++from gateway.session_contract import Submission+from hermes_state_runtime import RuntimeStoreError, begin_runtime_epoch, get_session_admission+from tests.gateway.test_session_authority_cancel_settlement import _authority, ACTOR, REF+++async def test_commit_then_error_still_releases_terminal_native_media(tmp_path, monkeypatch):+ from gateway import session_results+ from gateway.platforms.base import get_image_cache_dir+ db, authority = _authority(tmp_path, monkeypatch)+ image = get_image_cache_dir() / 'timeout.png'+ image.write_bytes(b'\x89PNG\r\n\x1a\nowned')+ 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)+ original = session_results.finish_result+ def commit_then_error(*args, **kwargs):+ monkeypatch.setattr(session_results, 'finish_result', original)+ original(*args, **kwargs)+ raise OSError('acknowledgement after commit lost')+ monkeypatch.setattr(session_results, 'finish_result', commit_then_error)+ with db:+ receipt = await authority.submit(ACTOR, Submission('image', REF, {+ 'text': 'work', 'attachments': [{'path': str(image), 'mime': 'image/png'}]}, 'queue'))+ row = get_session_admission(db, admission_id=receipt.admission_id)+ retained = Path(row['payload']['attachments_v1']['media'][0]['path'])+ assert retained.exists()+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ assert get_session_admission(db, admission_id=receipt.admission_id)['status'] == 'terminal'+ assert not retained.exists(), 'commit-then-error skipped terminal media cleanup'+++async def test_discard_during_recovery_stamp_does_not_replay_head_or_lose_follower(tmp_path, monkeypatch):+ from gateway import session_results, session_settlement_recovery+ db, authority = _authority(tmp_path, monkeypatch)+ schedule = authority._schedule+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ calls = []+ async def execute(owner, ref, row):+ calls.append(row['request_id'])+ owner.pending_results[row['admission_id']] = {'result': {'final_response': row['request_id']}, 'usage': {}}+ return row['request_id']+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ original = session_results.finish_result+ def unavailable(*args, **kwargs):+ monkeypatch.setattr(session_results, 'finish_result', original)+ raise OSError('lost settlement')+ monkeypatch.setattr(session_results, 'finish_result', unavailable)+ mark = session_settlement_recovery._mark_unknown+ entered, release = threading.Event(), threading.Event()+ def held_mark(*args):+ result = mark(*args)+ entered.set()+ assert release.wait(10)+ return result+ monkeypatch.setattr(session_settlement_recovery, '_mark_unknown', held_mark)+ with db:+ head = await authority.submit(ACTOR, Submission('head', REF, {'text': 'head'}, 'queue'))+ follower = await authority.submit(ACTOR, Submission('follower', REF, {'text': 'follower'}, 'queue'))+ schedule(REF)+ try:+ assert await asyncio.to_thread(entered.wait, 5)+ row = get_session_admission(db, admission_id=head.admission_id)+ await authority.resolve_unknown(ACTOR, REF, head.admission_id, row['generation'])+ finally:+ release.set()+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ assert calls == ['head', 'follower']+ assert get_session_admission(db, admission_id=follower.admission_id)['outcome'] == 'completed'+ assert authority.sessions['s'].event_stream.execution == {}+++async def test_stale_owner_cannot_stamp_a_new_epoch_claim_unknown(tmp_path, monkeypatch):+ from gateway.session_settlement_recovery import recover_failed_settlement+ from hermes_state_runtime import claim_session_input+ db, authority = _authority(tmp_path, monkeypatch)+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ with db:+ receipt = await authority.submit(ACTOR, Submission('work', REF, {'text': 'work'}, 'queue'))+ new_epoch = begin_runtime_epoch(db, instance_id='new-owner')+ row = claim_session_input(db, epoch=new_epoch, session_id='s')+ with pytest.raises(RuntimeStoreError):+ await recover_failed_settlement(authority, row)+ current = get_session_admission(db, admission_id=receipt.admission_id)+ assert current['status'] == 'started' and current['owner_epoch'] == new_epoch++[email protected]('failure_stage', ['cleanup', 'after_completion'])+async def test_post_commit_cleanup_error_still_publishes_the_committed_completion(tmp_path, monkeypatch, failure_stage):+ from gateway import session_ingress_media+ db, authority = _authority(tmp_path, monkeypatch)+ frames = []+ authority.sessions['s'].event_stream.observers.add(frames.append)+ 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)+ if failure_stage == 'cleanup':+ original = session_ingress_media.release_admission_media+ def unavailable_once(*args):+ monkeypatch.setattr(session_ingress_media, 'release_admission_media', original)+ raise OSError('post-commit cleanup temporarily unavailable')+ monkeypatch.setattr(session_ingress_media, 'release_admission_media', unavailable_once)+ else:+ original = authority._publish_pending+ def unavailable_after_completion(ref):+ if any(frame['params']['type'] == 'message.complete' for frame in frames):+ monkeypatch.setattr(authority, '_publish_pending', original)+ raise OSError('idle publication temporarily unavailable')+ return original(ref)+ monkeypatch.setattr(authority, '_publish_pending', unavailable_after_completion)+ with db:+ receipt = await authority.submit(ACTOR, Submission('cleanup', REF, {'text': 'work'}, 'queue'))+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ assert get_session_admission(db, admission_id=receipt.admission_id)['outcome'] == 'completed'+ complete = [f['params']['payload'] for f in frames if f['params']['type'] == 'message.complete']+ assert len(complete) == 1 and complete[0]['text'] == 'done'diff --git a/tests/gateway/test_live_settlement_recovery.py b/tests/gateway/test_live_settlement_recovery.pynew file mode 100644index 00000000000..236bcf95e3d--- /dev/null+++ b/tests/gateway/test_live_settlement_recovery.py@@ -0,0 +1,82 @@+"""An owner that is still alive must expose a failed settlement as recoverable uncertainty."""+import asyncio++import pytest++from gateway.session_contract import Submission+from hermes_state_runtime import RuntimeStoreError, get_session_admission+from tests.gateway.test_session_authority_cancel_settlement import _authority, ACTOR, REF++[email protected]('retry_recovery_write', [False, True])+async def test_failed_commit_retains_result_and_releases_fifo_for_explicit_discard(tmp_path, monkeypatch, retry_recovery_write):+ from gateway import session_results+ db, authority = _authority(tmp_path, monkeypatch)+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ calls = []+ frames = []+ authority.sessions['s'].event_stream.observers.add(frames.append)+ async def execute(owner, ref, row):+ calls.append(row['request_id'])+ owner.pending_results[row['admission_id']] = {+ 'result': {'final_response': row['request_id'] + ' done', 'completed': True}, 'usage': {}}+ return row['request_id'] + ' done'+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ original = session_results.finish_result+ def fail_once(*args, **kwargs):+ monkeypatch.setattr(session_results, 'finish_result', original)+ raise OSError('temporary settlement write failure')+ monkeypatch.setattr(session_results, 'finish_result', fail_once)+ if retry_recovery_write:+ from gateway import session_settlement_recovery+ mark = session_settlement_recovery._mark_unknown+ def unavailable_once(*args):+ monkeypatch.setattr(session_settlement_recovery, '_mark_unknown', mark)+ raise OSError('recovery write temporarily unavailable')+ monkeypatch.setattr(session_settlement_recovery, '_mark_unknown', unavailable_once)+ with db:+ head = await authority.submit(ACTOR, Submission('head', REF, {'text': 'head'}, 'queue'))+ follower = await authority.submit(ACTOR, Submission('follower', REF, {'text': 'follower'}, 'queue'))+ waiting = [authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())+ for receipt in (head, follower)]+ await asyncio.wait_for(authority._drain(REF), 5)+ row = get_session_admission(db, admission_id=head.admission_id)+ assert row['status'] == 'unknown' and row['owner_epoch'] == authority.epoch+ assert authority.pending_results[head.admission_id]['result']['final_response'] == 'head done'+ for waiter in waiting:+ with pytest.raises(RuntimeStoreError, match='unknown_execution'):+ await waiter+ assert not any(frame['params']['type'] == 'message.complete' for frame in frames)+ await authority.resolve_unknown(ACTOR, REF, head.admission_id, row['generation'])+ assert head.admission_id not in authority.pending_results+ await asyncio.wait_for(authority._drain(REF), 5)+ assert calls == ['head', 'follower']+ assert get_session_admission(db, admission_id=follower.admission_id)['status'] == 'terminal'+++async def test_commit_then_error_publishes_the_exact_committed_result(tmp_path, monkeypatch):+ from gateway import session_results+ db, authority = _authority(tmp_path, monkeypatch)+ frames = []+ authority.sessions['s'].event_stream.observers.add(frames.append)+ async def execute(owner, ref, row):+ owner.pending_results[row['admission_id']] = {+ 'result': {'final_response': 'done', 'completed': True, 'response_reused': True}, 'usage': {}}+ return 'done'+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ original = session_results.finish_result+ def fail_after_commit(*args, **kwargs):+ monkeypatch.setattr(session_results, 'finish_result', original)+ original(*args, **kwargs)+ raise OSError('commit response lost')+ monkeypatch.setattr(session_results, 'finish_result', fail_after_commit)+ with db:+ receipt = await authority.submit(ACTOR, Submission('committed', REF, {'text': 'work'}, 'queue'))+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ row = get_session_admission(db, admission_id=receipt.admission_id)+ assert row['status'] == 'terminal' and row['outcome'] == 'completed'+ complete, = [f['params']['payload'] for f in frames if f['params']['type'] == 'message.complete']+ assert complete['text'] == 'done' and complete['response_reused'] is True+ assert receipt.admission_id not in authority.pending_resultsdiff --git a/tests/gateway/test_session_authority_cancel_settlement.py b/tests/gateway/test_session_authority_cancel_settlement.pyindex c779a4f5499..5c9c70d8dca 100644--- a/tests/gateway/test_session_authority_cancel_settlement.py+++ b/tests/gateway/test_session_authority_cancel_settlement.py@@ -202,7 +202,7 @@ async def test_settlement_failure_is_logged_and_does_not_kill_the_drain(tmp_path"""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+ marked unknown rather than silently re-settled, and thedrain task ends without an unretrieved exception so the FIFO can be re-armed."""import logging@@ -227,5 +227,5 @@ async def test_settlement_failure_is_logged_and_does_not_kill_the_drain(tmp_path[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 row['status'] == 'unknown', 'explicit recovery is possible without inventing a terminal result'assert authority.sessions['s'].event_stream.execution == {}, 'stamp cleared even on failure'