The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): Discard of a captured answer delivers it to the chat it was owed to, once
Tekniumd49b9f06f453
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 10f3965671b..f8a075caeca 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -517,6 +517,10 @@ class SessionAuthority:# would otherwise stay on disk forever (the drain releases only settled turns).from gateway.session_ingress_media import release_admission_mediarelease_admission_media(self.db, admission_id)+ # Before the successor can run: a committed captured answer reaches the chat it was+ # owed to (a turn fenced unknown already released its delivery waiter), exactly once.+ from gateway.session_ingress import deliver_resolved+ await deliver_resolved(self, admission_id, owed=prepared is not None and row['owner_epoch'] == self.epoch)self._publish_pending(ref)self._schedule(ref)return self._receipt(row)@@ -753,6 +757,8 @@ class SessionAuthority:current = get_session_admission(self.db, admission_id=admission_id)status = current['status']if status == 'unknown':+ from gateway.session_ingress import retain_unsettled_delivery+ retain_unsettled_delivery(self, admission_id)self._publish_pending(ref)self._pause(ref, 'unknown_execution')return@@ -784,6 +790,8 @@ class SessionAuthority:if settled is None:# Uncommitted (unknown or discarded): the user is not told an answer the FIFO lost.self.pending_deliveries.pop(admission_id, None)+ from gateway.session_ingress import waiter_replies+ waiter_replies(self).pop(admission_id, None)from gateway.session_ingress import deliver_settledawait deliver_settled(self, admission_id)waiter = self.waiters.pop(admission_id, None)diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex 42859553c00..507c62c3cf6 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -61,10 +61,7 @@ async def _hand_over_turn_marker(authority, admission_id, event):no-waiter reply keeps it until ``deliver_settled``; any other turn releases it here."""adopter = _marker_adopters(authority).get(admission_id)if adopter is not None:- for name in _MARKER_FIELDS:- if hasattr(event, name):- setattr(adopter, name, getattr(event, name))- delattr(event, name)+ _move_marker(event, adopter)returnif admission_id in authority.pending_deliveries:# Released by ``deliver_settled``, also when settlement failed and dropped the delivery.@@ -73,6 +70,13 @@ async def _hand_over_turn_marker(authority, admission_id, event):await _release_turn_marker(authority, event)+def _move_marker(source, target):+ for name in _MARKER_FIELDS:+ if hasattr(source, name):+ setattr(target, name, getattr(source, name))+ delattr(source, name)++def _held_markers(authority):held = getattr(authority, 'held_turn_markers', None)if held is None:@@ -80,6 +84,51 @@ def _held_markers(authority):return held+def _registry(authority, name):+ found = getattr(authority, name, None)+ if found is None:+ found = {}+ setattr(authority, name, found)+ return found+++def waiter_replies(authority):+ """admission -> the reply a live native waiter is about to send, kept only until the drain+ settles the turn, so a turn fenced ``unknown`` can still owe it to the chat."""+ return _registry(authority, 'waiter_replies')+++def retain_unsettled_delivery(authority, admission_id):+ """Settlement could not commit and the turn is fenced ``unknown``, but this owner keeps its+ captured answer for Discard (``resolve_unknown``). The reply stays owed to its destination,+ and so does the turn's crash marker: the live waiter is released with a pause notice, so the+ marker is taken back from it. Restart while unknown clears the marker (no answer is owed,+ ``release_unknown_turn_markers``); a Discard that commits the captured answer makes it owed,+ sent once by ``deliver_resolved`` or, after a kill before that send, by the boot ledger."""+ delivery = waiter_replies(authority).pop(admission_id, None)+ if delivery is not None:+ adopter = _marker_adopters(authority).get(admission_id)+ if adopter is not None:+ _move_marker(adopter, delivery[1])+ _held_markers(authority)[admission_id] = delivery[1]+ else:+ delivery = authority.pending_deliveries.pop(admission_id, None)+ if delivery is not None:+ _registry(authority, 'unsettled_deliveries')[admission_id] = delivery+++async def deliver_resolved(authority, admission_id, *, owed):+ """After a Discard committed: send the retained reply when its captured answer committed with+ the resolution (``owed``), else release its marker and drop it. Popped first, so a repeated+ resolution never sends twice; a turn the drain still owns is delivered by the drain."""+ delivery = _registry(authority, 'unsettled_deliveries').pop(admission_id, None)+ if delivery is None:+ return+ if owed:+ authority.pending_deliveries[admission_id] = delivery+ await deliver_settled(authority, admission_id)++async def _release_turn_marker(authority, event):if getattr(event, '_gateway_active_turn_token', None):await authority.runner._clear_durable_active_turn(event)@@ -190,14 +239,18 @@ async def execute_admission(authority, ref, row):# The drain commits this under the stream lock so no viewer reads `terminal`# before the completion event exists in the replay ring.authority.pending_results[row['admission_id']] = {'result': result, 'usage': captured.get('usage', {})}- if not native and not is_api and response:+ if not is_api and response:adapter = authority.runner._adapter_for_source(event.source)if adapter is not None:# A recovered turn with no live delivery waiter: the drain sends this only after# it commits the terminal outcome (deliver_settled), so a failed settlement never- # leaves an externally answered admission started -> unknown.- authority.pending_deliveries[row['admission_id']] = (- adapter, event, live.route, response, home)+ # leaves an externally answered admission started -> unknown. A live waiter+ # sends its own; the record only outlives a settlement fenced unknown.+ delivery = (adapter, event, live.route, response, home)+ if native:+ waiter_replies(authority)[row['admission_id']] = delivery+ else:+ authority.pending_deliveries[row['admission_id']] = deliveryhanded = Trueawait _hand_over_turn_marker(authority, row['admission_id'], event)return responsediff --git a/tests/gateway/test_discard_delivers_captured_answer.py b/tests/gateway/test_discard_delivers_captured_answer.pynew file mode 100644index 00000000000..d9ca2386d7b--- /dev/null+++ b/tests/gateway/test_discard_delivers_captured_answer.py@@ -0,0 +1,59 @@+"""Discard of a turn whose settlement failed commits its captured answer AND delivers it to the chat+the answer was owed to, exactly once; nothing is sent while the turn is unknown."""+import asyncio++import pytest++from gateway.session_contract import Submission+from hermes_state_runtime import RuntimeStoreError, get_session_admission++[email protected]('live_waiter', [True, False])+async def test_discard_of_a_captured_answer_delivers_it_once(tmp_path, monkeypatch, live_waiter):+ from gateway import session_ingress, session_results+ from gateway import session_settlement_recovery as recovery+ from gateway.config import Platform+ from gateway.session import SessionSource+ from gateway.session_authority import LiveSession+ from gateway.session_contract import Principal, SessionRef+ from tests.gateway.test_prompt_attachments import _authority as _store_authority++ calls, sent = [], []+ async def answer(event):+ calls.append(event.text)+ return 'model reply'+ authority = await _store_authority(tmp_path, monkeypatch, answer)+ authority.sessions['s'] = LiveSession(SessionSource(platform=Platform.TELEGRAM, chat_id='c'), 's')+ authority.runner._adapter_for_source = lambda source: object()+ async def deliver(adapter, event, session_key, response):+ sent.append((response, event.source.chat_id,+ get_session_admission(authority.db, admission_id=event.message_id)['status']))+ monkeypatch.setattr(session_ingress, 'deliver_response', deliver)+ monkeypatch.setattr(recovery, '_SETTLE_RETRY_DELAYS_S', (0.01,), raising=False)+ original = session_results.finish_result+ def unavailable(*args, **kwargs):+ raise OSError('database is locked')+ monkeypatch.setattr(session_results, 'finish_result', unavailable)+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ actor = Principal('human', 'p', frozenset({'session:submit', 'session:control'}), 't')+ ref = SessionRef('p', 's')+ receipt = await authority.submit(actor, Submission('owed', ref, {'text': 'hi'}, 'queue'))+ waiter = None+ if live_waiter: # the native ingress delivery waiter (admit_message) for this admission+ authority.native_waiters.add(receipt.admission_id)+ waiter = authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())+ await asyncio.wait_for(authority._drain(ref), 10)+ monkeypatch.setattr(session_results, 'finish_result', original)+ row = get_session_admission(authority.db, admission_id=receipt.admission_id)+ assert row['status'] == 'unknown' and sent == [], 'an unsettled admission was answered externally'+ if waiter is not None:+ with pytest.raises(RuntimeStoreError, match='unknown_execution'):+ await waiter # the chat got the paused notice instead+ await authority.resolve_unknown(actor, ref, receipt.admission_id, row['generation'])+ resolved = get_session_admission(authority.db, admission_id=receipt.admission_id)+ assert (resolved['status'], resolved['outcome']) == ('terminal', 'completed')+ assert sent == [('model reply', 'c', 'terminal')], 'Discard committed the answer but never delivered it'+ await authority.resolve_unknown(actor, ref, receipt.admission_id, row['generation'])+ assert len(sent) == 1, 'a repeated resolution sent the answer twice'+ assert calls == ['hi'], 'inference must never re-run'