The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): Discard commits its transcript boundary with the terminal transition
Teknium3fbaf35eddf0
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 3682d41c9f3..980683e7de0 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -381,12 +381,12 @@ class SessionAuthority:finish; the paused FIFO behind it resumes. Never requeues the lost input."""self.authorize(actor, ref, 'session:control')await self.receipt(actor, ref, admission_id)- row = resolve_unknown_session_input(self.db, epoch=self.epoch, admission_id=admission_id,- generation=generation)- # Before the follower is scheduled: its request must not carry the discarded text merged in.- from gateway.session_local_recovery import transcript_target+ # The transcript boundary commits WITH the terminal transition: a follower can never be+ # claimed with the discarded text left open to be merged into its request.from gateway.session_results import close_discarded_turn- close_discarded_turn(self.db, transcript_target(self, ref))+ 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._publish_pending(ref)self._schedule(ref)return self._receipt(row)diff --git a/gateway/session_results.py b/gateway/session_results.pyindex 8edc1936ae7..870d543240d 100644--- a/gateway/session_results.py+++ b/gateway/session_results.py@@ -70,18 +70,26 @@ def admission_result(db, admission_id):return json.loads(saved[0]) if saved else None-def close_discarded_turn(db, target_id):- """Close a discarded ``unknown`` turn the way a failed turn is closed.+def close_discarded_turn(db, conn, row):+ """Close a discarded ``unknown`` turn the way a failed turn is closed, on the resolution's+ own transaction (``resolve_unknown_session_input(_terminal_write=...)``).The lost input stays in the transcript for the user to resend, but an open ``user`` tail would bemerged into the follower's provider request by consecutive-user repair, re-sending the discardedturn as context. A Hermes-authored boundary (``display_kind=failed_turn``, stripped of its type- before the wire) ends it. Its side effects are unknown, so the hedged copy. Idempotent on the- durable tail, like the gateway and core failed-turn closers."""- if db.latest_conversation_role(target_id) != 'user':- return False+ before the wire) ends it. Its side effects are unknown, so the hedged copy. The boundary lands on+ the CURRENT physical transcript (local reset/compression lineage tip), resolved on this+ connection. Idempotent on the durable tail, like the gateway and core failed-turn closers."""import timefrom agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, PARTIAL_FAILED_TURN_NOTICE- db.append_message(target_id, 'assistant', PARTIAL_FAILED_TURN_NOTICE, timestamp=time.time(),- display_kind=FAILED_TURN_DISPLAY_KIND)+ from hermes_state_local_lineage import local_physical_target+ from hermes_state_runtime import _canonical_chain+ target = _canonical_chain(conn, local_physical_target(conn, row['target_session_id']))[-1]+ tail = conn.execute("SELECT role FROM messages WHERE session_id=? AND active=1 "+ "AND role NOT IN ('session_meta','system') ORDER BY id DESC LIMIT 1", (target,)).fetchone()+ if tail is None or tail[0] != 'user':+ return False+ db._append_messages_in_transaction(conn, target, [{+ 'role': 'assistant', 'content': PARTIAL_FAILED_TURN_NOTICE, 'timestamp': time.time(),+ 'display_kind': FAILED_TURN_DISPLAY_KIND}])return Truediff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex 53e884d535d..4f669dc468f 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -368,13 +368,20 @@ def import_legacy_session_admissions(db, *, epoch: int, source_path, principal_ireturn db._execute_write(write)-def resolve_unknown_session_input(db, *, epoch: int, admission_id: str, generation: int) -> dict:- """Explicit operator acknowledgement; resolves uncertainty, never requeues it."""+def resolve_unknown_session_input(db, *, epoch: int, admission_id: str, generation: int,+ _terminal_write=None) -> dict:+ """Explicit operator acknowledgement; resolves uncertainty, never requeues it.++ ``_terminal_write(conn, row)`` is the owner's same-transaction effect (the discarded turn's+ transcript boundary): it must not commit, may run again on SQLite retry, and raising rolls+ the whole resolution back, so the FIFO can never advance past an unclosed lost turn."""def write(conn):_epoch(conn, epoch)row = _admission(conn, admission_id)if type(generation) is not int or row['status'] != 'unknown' or row['generation'] != generation:raise RuntimeStoreError('stale_generation')+ if _terminal_write is not None:+ _terminal_write(conn, row)_retire_admission_workers(conn, row, row['owner_epoch'])conn.execute("UPDATE session_admissions SET status='terminal',outcome='interrupted' WHERE admission_id=?", (admission_id,))conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (row['target_session_id'],))diff --git a/tests/gateway/test_authority_unknown_resolution.py b/tests/gateway/test_authority_unknown_resolution.pyindex 5d1a8c293d1..f7a72d9db21 100644--- a/tests/gateway/test_authority_unknown_resolution.py+++ b/tests/gateway/test_authority_unknown_resolution.py@@ -10,7 +10,7 @@ from gateway.session import SessionSource, SessionStorefrom gateway.session_authority import LiveSession, initialize_session_authorityfrom gateway.session_contract import SessionRef, Submissionfrom gateway.session_controls import AuthorityConnection-from hermes_state_runtime import claim_session_input, list_session_admissions+from hermes_state_runtime import RuntimeStoreError, claim_session_input, list_session_admissionsclass Peer:@@ -120,6 +120,40 @@ async def test_resolve_unknown_is_fenced_by_generation_and_capability(tmp_path,store.close_all_db_handles()+async def test_discard_and_its_transcript_boundary_commit_atomically_on_the_physical_tip(tmp_path, monkeypatch):+ """R1: a failure writing the boundary must not leave the lost admission terminal (its exact+ Discard retry refused, the follower claimable onto an open user tail). The boundary lands on+ the rotated physical transcript, not the logical owner."""+ store, authority, ref, unknown, follower = await _restarted_owner_with_unknown_head(tmp_path, monkeypatch, [])+ db = authority.db+ db.create_session('s-tip', source='telegram', parent_session_id='s')+ db.end_session('s', 'compression')+ db.append_message('s-tip', 'user', 'LOST_OPERATION')+ authority._schedule = lambda ref: None+ db._execute_write(lambda c: c.execute("CREATE TRIGGER deny_boundary BEFORE INSERT ON messages "+ "WHEN NEW.role='assistant' BEGIN SELECT RAISE(ABORT,'boundary failed'); END"))+ viewer = AuthorityConnection(authority, Peer(), {'user_id': 'human'})+ params = {'session_id': 's', 'admission_id': unknown['admission_id'], 'execution_generation': unknown['generation']}+ try:+ await viewer.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})+ failed = await viewer.dispatch({'id': 2, 'method': 'prompt.resolve_unknown', 'params': params})+ assert 'error' in failed, failed+ rows = {r['admission_id']: r['status'] for r in list_session_admissions(db, session_id='s')}+ assert rows.get(unknown['admission_id']) == 'unknown', 'Discard committed without its transcript boundary'+ with pytest.raises(RuntimeStoreError, match='unknown_execution'):+ claim_session_input(db, epoch=authority.epoch, session_id='s')+ db._execute_write(lambda c: c.execute('DROP TRIGGER deny_boundary'))+ retried = await viewer.dispatch({'id': 3, 'method': 'prompt.resolve_unknown', 'params': params})+ assert retried['result']['outcome'] == 'interrupted', retried+ assert db.latest_conversation_role('s-tip') == 'assistant'+ assert [m['role'] for m in db.get_messages('s') if m['role'] == 'assistant'] == []+ assert claim_session_input(db, epoch=authority.epoch, session_id='s')['admission_id'] == follower.admission_id+ finally:+ await viewer.close()+ store.close_all_db_handles()++@pytest.mark.asyncioasync def test_discarded_lost_turn_is_closed_and_never_merged_into_the_follower_request(tmp_path, monkeypatch):"""Discard keeps the lost text visible for resending, but the next provider request must not