The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: send a recovered native reply only after its terminal outcome commits
Tekniumb957f6dcc630
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex f136e29cf24..a664a215eb4 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -64,6 +64,8 @@ class SessionAuthority:self.events = {}self.native_waiters = set()self.pending_results = {}+ # Replies of recovered no-waiter turns, sent only once their terminal outcome commits.+ self.pending_deliveries = {}# Stops accepted for a running generation whose agent does not exist yet# (first-turn construction); consumed by adopt_agent, keyed session -> generation.self.pending_stops = {}@@ -699,6 +701,11 @@ class SessionAuthority:with live.event_stream.lock:live.event_stream.execution = {}self.pending_stops.pop(ref.session_id, None)+ 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 deliver_settled+ await deliver_settled(self, admission_id)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_ingress.py b/gateway/session_ingress.pyindex b3c28d3fb99..9349f025864 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -92,18 +92,11 @@ async def execute_admission(authority, ref, row):from gateway.session_automation import restore_local_automationevent = restore_local_automation(authority, ref, row)provenance = row['payload'].get('native_text_v1', {}).get('provenance')- from gateway.run import _profile_runtime_scope- # Under multiplex, owner-side execution runs under the OWNING profile's home (agent build,- # config, secrets, state.db), never the launch profile's ambient scope; native provenance- # refines it. A single-profile gateway keeps its ambient scope byte-for-byte.- scope = nullcontext()- if getattr(getattr(authority.runner, 'config', None), 'multiplex_profiles', False):- from gateway.session_authorities import owner_scope- scope = owner_scope(authority, hydrate_secrets=True)+ home = Noneif provenance is not None:from gateway.session_ingress_context import restore_provenancehome = restore_provenance(authority.runner, event.source, provenance)- scope = _profile_runtime_scope(home)+ scope = _execution_scope(authority, home)from gateway.config import Platformfrom gateway.session_api_turn import api_execution, prepare_api_executionfrom gateway.session_results import execution_result@@ -144,7 +137,11 @@ async def execute_admission(authority, ref, row):if not native and not is_api and response:adapter = authority.runner._adapter_for_source(event.source)if adapter is not None:- await deliver_response(adapter, event, live.route, response)+ # 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)return responsefinally:executing_admission.reset(token)@@ -153,6 +150,36 @@ async def execute_admission(authority, ref, row):admission_author.reset(author_token)+def _execution_scope(authority, home):+ """Under multiplex, owner-side execution runs under the OWNING profile's home (agent build,+ config, secrets, state.db), never the launch profile's ambient scope; native provenance+ (``home``) refines it. A single-profile gateway keeps its ambient scope byte-for-byte."""+ if home is not None:+ from gateway.run import _profile_runtime_scope+ return _profile_runtime_scope(home)+ if getattr(getattr(authority.runner, 'config', None), 'multiplex_profiles', False):+ from gateway.session_authorities import owner_scope+ return owner_scope(authority, hydrate_secrets=True)+ return nullcontext()+++async def deliver_settled(authority, admission_id):+ """Send a recovered no-waiter turn's reply after its terminal outcome committed. A send+ failure cannot rewrite that outcome; it is logged, and inference never runs again."""+ delivery = authority.pending_deliveries.get(admission_id)+ if delivery is None:+ return+ adapter, event, session_key, response, home = delivery+ try:+ with _execution_scope(authority, home):+ await deliver_response(adapter, event, session_key, response)+ except Exception:+ logger.exception('Delivery of settled admission %s failed', admission_id)+ finally:+ # Held until the send returns: an empty map means every settled reply was handed over.+ authority.pending_deliveries.pop(admission_id, None)++async def deliver_response(adapter, event, session_key, response):from gateway.platforms.base import _thread_metadata_for_event, _mark_notify_metadatatext, ttl = adapter._unwrap_ephemeral(response)diff --git a/tests/gateway/test_live_settlement_recovery.py b/tests/gateway/test_live_settlement_recovery.pyindex d18a94edea9..73041f39d5a 100644--- a/tests/gateway/test_live_settlement_recovery.py+++ b/tests/gateway/test_live_settlement_recovery.py@@ -121,3 +121,44 @@ async def test_transient_settlement_failure_commits_the_completed_result(tmp_patassert calls == ['head', 'follower'], 'a settlement retry must never re-run inference'completions = [f['params']['payload'] for f in frames if f['params']['type'] == 'message.complete']assert [c['text'] for c in completions] == ['head done', 'follower done']++[email protected]('storage_down', [False, True])+async def test_recovered_native_reply_is_sent_only_after_its_outcome_commits(tmp_path, monkeypatch, storage_down):+ """A recovered turn with no live delivery waiter is answered by the drain itself. The platform+ send must follow the terminal commit: if settlement cannot commit, the admission is fenced+ unknown and the user is never told an answer the FIFO lost. Inference runs exactly once."""+ 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, get_session_admission(authority.db, admission_id=event.message_id)['status']))+ monkeypatch.setattr(session_ingress, 'deliver_response', deliver)+ if storage_down:+ monkeypatch.setattr(recovery, '_SETTLE_RETRY_DELAYS_S', (0.01,), raising=False)+ def unavailable(*args, **kwargs):+ raise OSError('settlement storage unavailable')+ monkeypatch.setattr(session_results, 'finish_result', unavailable)+ actor = Principal('human', 'p', frozenset({'session:submit'}), 't')+ receipt = await authority.submit(actor, Submission('recovered', SessionRef('p', 's'), {'text': 'hi'}, 'queue'))+ await asyncio.wait_for(authority.sessions['s'].task, 10)+ status = get_session_admission(authority.db, admission_id=receipt.admission_id)['status']+ assert calls == ['hi']+ if storage_down:+ assert status == 'unknown' and sent == [], 'an unsettled admission was answered externally'+ else:+ assert status == 'terminal' and sent == [('model reply', 'terminal')]+ assert receipt.admission_id not in authority.pending_deliveriesdiff --git a/tests/gateway/test_relay_authority.py b/tests/gateway/test_relay_authority.pyindex 8fc446edc5f..cddffcd39bc 100644--- a/tests/gateway/test_relay_authority.py+++ b/tests/gateway/test_relay_authority.py@@ -176,7 +176,7 @@ async def probe(peer):peer.release.set()async with asyncio.timeout(10):while any(not task.done() for task in adapter._background_tasks) or any(r['status'] != 'terminal' for r in- list_session_admissions(authority.db, session_id=sid, pending_only=False)):+ list_session_admissions(authority.db, session_id=sid, pending_only=False)) or authority.pending_deliveries:await asyncio.sleep(.01)rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)assert len(peer.requests) == 4, peer.requests