The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a native reply is sent once when a running drain claims it first
Teknium650148dfa39d
diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex 507c62c3cf6..a6046d594e2 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -31,6 +31,18 @@ async def admit_message(authority, event):# The adapter lifecycle that sends this reply releases the turn's crash marker only once# the reply is in the delivery ledger; the drain hands its marker to this event.adopters[receipt.admission_id] = event+ # A drain already running can claim, run and settle the row before this caller resumes; one+ # that settled it already sent (or owes) the reply itself and resolves no waiter registered now.+ from hermes_state_runtime import get_session_admission+ row = get_session_admission(authority.db, admission_id=receipt.admission_id)+ status = 'terminal' if row is None else row['status'] # None: deleted with its chat, nothing owed+ if status in ('terminal', 'unknown'):+ authority.native_waiters.discard(receipt.admission_id)+ if authority.waiters.get(receipt.admission_id) is waiter:+ del authority.waiters[receipt.admission_id]+ if adopters.get(receipt.admission_id) is event:+ del adopters[receipt.admission_id]+ return None if status == 'terminal' else pause_notice(authority, receipt.ref, 'unknown_execution')if accepted is not None and not accepted.done():accepted.set_result(None)try:@@ -281,6 +293,16 @@ async def deliver_settled(authority, admission_id):failure cannot rewrite that outcome; it is logged, and inference never runs again."""held = _held_markers(authority).pop(admission_id, None)delivery = authority.pending_deliveries.get(admission_id)+ if delivery is not None and admission_id in authority.native_waiters:+ # ``admit_message`` registered its delivery waiter after this turn started: the drain+ # hands that waiter the reply and its adapter lifecycle sends it, so this send is not owed.+ authority.native_waiters.discard(admission_id)+ authority.pending_deliveries.pop(admission_id)+ adopter = _marker_adopters(authority).get(admission_id)+ if held is not None and adopter is not None:+ _move_marker(held, adopter)+ held = None+ delivery = Noneif delivery is None:if held is not None:# Fenced unknown: no answer is owed, so no later boot may deliver one either.diff --git a/tests/gateway/test_busy_durable_acceptance.py b/tests/gateway/test_busy_durable_acceptance.pyindex 2e54b9ac1b2..16bf82cdee5 100644--- a/tests/gateway/test_busy_durable_acceptance.py+++ b/tests/gateway/test_busy_durable_acceptance.py@@ -21,10 +21,12 @@ async def test_busy_receive_returns_after_acceptance_but_delivers_once_after_comawait release.wait()return SimpleNamespace(status='queued', admission_id='queued')- authority = SimpleNamespace(admit_native=admit, native_waiters=set(), waiters={})+ authority = SimpleNamespace(admit_native=admit, native_waiters=set(), waiters={}, db=None)adapter = SimpleNamespace(_background_tasks=set(), _message_handler=lambda event: admit_message(authority, event))delivery = AsyncMock()monkeypatch.setattr(ingress, 'deliver_response', delivery)+ # admit_message re-reads the committed row (a drain may already have settled it); still queued.+ monkeypatch.setattr('hermes_state_runtime.get_session_admission', lambda db, admission_id: {'status': 'queued'})event = MessageEvent(text='next', source=SessionSource(platform=Platform.TELEGRAM, chat_id='chat'))receive = asyncio.create_task(dispatch_shared_busy(adapter, event, 'route'))await asyncio.wait_for(accepted.wait(), 5)diff --git a/tests/gateway/test_native_reply_delivered_once.py b/tests/gateway/test_native_reply_delivered_once.pynew file mode 100644index 00000000000..5d30e167605--- /dev/null+++ b/tests/gateway/test_native_reply_delivered_once.py@@ -0,0 +1,49 @@+"""A native reply reaches the chat exactly once even when an already-running drain claims and+runs the admission before ``admit_message`` resumes to register its delivery waiter+(andrexibiza-6, andrexibiza-5480238075-1). Every native reply goes through one of two senders:+the drain's ``deliver_settled`` (no live waiter) or the waiting adapter lifecycle."""+import asyncio++import pytest++from gateway.session_contract import Submission+++async def test_native_waiter_registered_after_the_claim_still_gets_the_only_delivery(tmp_path, monkeypatch):+ from gateway import session_ingress+ from gateway.config import Platform+ from gateway.platforms.event import MessageEvent+ 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++ turn_started = asyncio.Event()++ async def answer(event):+ turn_started.set()+ return 'model reply'+ authority = await _store_authority(tmp_path, monkeypatch, answer)+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='c')+ authority.sessions['s'] = LiveSession(source, 's')+ authority.runner._adapter_for_source = lambda source: object()+ drain_sent = []++ async def deliver(adapter, event, session_key, response):+ drain_sent.append(response)+ monkeypatch.setattr(session_ingress, 'deliver_response', deliver)+ actor = Principal('human', 'p', frozenset({'session:submit'}), 't')++ async def admit_native(event):+ receipt = await authority.submit(actor, Submission('m1', SessionRef('p', 's'), {'text': 'hi'}, 'queue'))+ # The admitting caller resumes only after the drain already claimed and started the turn.+ await turn_started.wait()+ return receipt+ monkeypatch.setattr(authority, 'admit_native', admit_native)+ adapter_sent = await asyncio.wait_for(+ session_ingress.admit_message(authority, MessageEvent(text='hi', source=source)), 10)+ await asyncio.wait_for(authority.sessions['s'].task, 10)+ deliveries = drain_sent + ([adapter_sent] if adapter_sent else [])+ assert deliveries == ['model reply'], f'the reply was sent {len(deliveries)} times: {deliveries}'+ assert not authority.native_waiters and not authority.pending_deliveries