Skip to content

The agent that grows with you

fix(gateway): IRC/Signal keep reading while a busy follow-up waits its turn

Teknium3e72c222b59e
diff --git a/gateway/session_ingress.py b/gateway/session_ingress.py
index c664c46143f..4afcc2d9c69 100644
--- a/gateway/session_ingress.py
+++ b/gateway/session_ingress.py
@@ -1,5 +1,6 @@
"""Trusted messaging admission and the existing TurnRunner invocation boundary."""
import asyncio
+import logging
from contextvars import ContextVar
from contextlib import nullcontext
from dataclasses import replace
@@ -8,17 +9,25 @@ from gateway.platforms.event import MessageEvent
from gateway.session_envelope import restore_native
from hermes_state_runtime import RuntimeStoreError
+logger = logging.getLogger(__name__)
+
admission_author = ContextVar('admission_author', default=None)
executing_admission = ContextVar('executing_admission', default=False)
+# Set by a busy-path caller that must be released once its input is durably queued.
+busy_acceptance = ContextVar('busy_acceptance', default=None)
async def admit_message(authority, event):
+ accepted = busy_acceptance.get()
+ busy_acceptance.set(None) # the drain task this schedules must not inherit the busy caller's future
receipt = await authority.admit_native(event)
if receipt.status == 'terminal':
return None
# Only the delivery waiter is process-local; execution reads the committed snapshot.
authority.native_waiters.add(receipt.admission_id)
waiter = authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())
+ if accepted is not None and not accepted.done():
+ accepted.set_result(None)
try:
return await asyncio.shield(waiter)
except RuntimeStoreError as exc:
@@ -155,6 +164,33 @@ async def deliver_response(adapter, event, session_key, response):
async def dispatch_shared_busy(adapter, event, session_key):
+ """Serial receive loops (IRC, Signal) await this before reading their next frame, so return
+ once the follow-up is committed to the FIFO; a tracked observer delivers its one reply."""
delivery_event = replace(event, source=replace(event.source))
- response = await adapter._message_handler(event)
- await deliver_response(adapter, delivery_event, session_key, response)
+ accepted = asyncio.get_running_loop().create_future()
+
+ async def observe():
+ try:
+ response = await adapter._message_handler(event)
+ await deliver_response(adapter, delivery_event, session_key, response)
+ except Exception as exc:
+ if not accepted.done():
+ raise # nothing was queued: the receive loop sees the failure as before
+ logger.error('[%s] Queued busy follow-up failed: %s', adapter.name, exc, exc_info=True)
+ await adapter._notify_turn_error(delivery_event, exc)
+
+ token = busy_acceptance.set(accepted)
+ try:
+ task = asyncio.create_task(observe())
+ finally:
+ busy_acceptance.reset(token)
+ adapter._background_tasks.add(task)
+ task.add_done_callback(adapter._background_tasks.discard)
+ try:
+ await asyncio.wait({accepted, task}, return_when=asyncio.FIRST_COMPLETED)
+ except asyncio.CancelledError:
+ if not accepted.done():
+ task.cancel() # cancelled before commit: the input was never ACKed
+ raise
+ if task.done():
+ task.result() # refused, consumed or answered inline before any durable acceptance
diff --git a/tests/gateway/test_shared_busy_receive_loop.py b/tests/gateway/test_shared_busy_receive_loop.py
new file mode 100644
index 00000000000..20c9f48c795
--- /dev/null
+++ b/tests/gateway/test_shared_busy_receive_loop.py
@@ -0,0 +1,133 @@
+"""A busy-session follow-up releases the adapter's serial receive loop once it is durably queued.
+
+IRC and Signal await ``handle_message`` before reading their next frame. With the shared runtime
+a busy follow-up is admitted into the session FIFO; the adapter must return as soon as that row
+is committed, not when the queued turn finally answers, while still delivering exactly one reply.
+"""
+import asyncio
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+from gateway.platforms.base import BasePlatformAdapter, SendResult
+from gateway.platforms.event import MessageEvent
+
+
+class Adapter(BasePlatformAdapter):
+ def __init__(self):
+ super().__init__(PlatformConfig(enabled=True, token='owned-fixture'), Platform.TELEGRAM)
+ self.sent = []
+
+ async def connect(self, *, is_reconnect=False):
+ return True
+
+ async def disconnect(self):
+ pass
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ self.sent.append(content)
+ return SendResult(success=True, message_id=f'sent-{len(self.sent)}')
+
+ async def edit_message(self, chat_id, message_id, content, *, finalize=False):
+ return SendResult(success=True, message_id=message_id)
+
+ async def send_typing(self, chat_id, metadata=None):
+ pass
+
+ async def get_chat_info(self, chat_id):
+ return {'id': chat_id}
+
+
+async def _busy_owner(monkeypatch, turns):
+ """Real runner + authority over SQLite; turn production is a gated stand-in (no model)."""
+ import gateway.session_finite as finite
+ from gateway.run import GatewayRunner
+ from gateway.session_authority import initialize_session_authority
+
+ monkeypatch.setenv('TELEGRAM_ALLOWED_USERS', 'fixture-user')
+
+ async def produce(authority, ref, row):
+ return await turns[row['payload']['text']]()
+ monkeypatch.setattr(finite, 'execute_finite_admission', produce)
+ runner = GatewayRunner(GatewayConfig())
+ adapter = Adapter()
+ runner.adapters = {Platform.TELEGRAM: adapter}
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='busy-owner')
+ runner._wire_adapter_handlers(adapter)
+ source = adapter.build_source(chat_id='busy-chat', chat_type='dm', user_id='fixture-user')
+ return authority, adapter, source
+
+
+def _statuses(authority):
+ from hermes_state_runtime import list_session_admissions
+ return {row['payload']['text']: row['status'] for session_id in authority.sessions
+ for row in list_session_admissions(authority.db, session_id=session_id, pending_only=False)}
+
+
+async def _wait_for(predicate, timeout=5):
+ deadline = asyncio.get_running_loop().time() + timeout
+ while not predicate():
+ assert asyncio.get_running_loop().time() < deadline, 'condition not reached'
+ await asyncio.sleep(0.01)
+
+
+async def test_busy_follow_up_returns_after_commit_and_is_answered_once(monkeypatch):
+ first_gate, second_gate = asyncio.Event(), asyncio.Event()
+
+ async def first():
+ await first_gate.wait()
+ return 'FIRST_REPLY'
+
+ async def second():
+ await second_gate.wait()
+ return 'SECOND_REPLY'
+ authority, adapter, source = await _busy_owner(monkeypatch, {'one': first, 'two': second})
+ await adapter.handle_message(MessageEvent(text='one', source=source, message_id='m1'))
+ await _wait_for(lambda: _statuses(authority).get('one') == 'started')
+ # The receive loop hands over the follow-up while the first turn is still running.
+ receive = asyncio.create_task(adapter.handle_message(MessageEvent(text='two', source=source, message_id='m2')))
+ done, _ = await asyncio.wait({receive}, timeout=3)
+ assert receive in done, 'receive loop parked until the queued turn completes'
+ receive.result()
+ assert _statuses(authority) == {'one': 'started', 'two': 'queued'}
+ assert adapter.sent == []
+ first_gate.set()
+ await _wait_for(lambda: _statuses(authority).get('two') == 'started')
+ second_gate.set()
+ await _wait_for(lambda: 'SECOND_REPLY' in adapter.sent and not adapter._background_tasks)
+ assert adapter.sent == ['FIRST_REPLY', 'SECOND_REPLY']
+ assert _statuses(authority) == {'one': 'terminal', 'two': 'terminal'}
+
+
+async def test_detached_busy_completion_failure_still_tells_the_user(monkeypatch):
+ first_gate = asyncio.Event()
+ unhandled = []
+ asyncio.get_running_loop().set_exception_handler(lambda loop, ctx: unhandled.append(ctx))
+
+ async def first():
+ await first_gate.wait()
+ return 'FIRST_REPLY'
+
+ async def second():
+ return 'SECOND_REPLY'
+ authority, adapter, source = await _busy_owner(monkeypatch, {'one': first, 'two': second})
+ extract = adapter._extract_response_content
+
+ async def broken_extract(text, *args, **kwargs):
+ if text == 'SECOND_REPLY':
+ raise RuntimeError('render exploded')
+ return await extract(text, *args, **kwargs)
+ monkeypatch.setattr(adapter, '_extract_response_content', broken_extract)
+ await adapter.handle_message(MessageEvent(text='one', source=source, message_id='m1'))
+ await _wait_for(lambda: _statuses(authority).get('one') == 'started')
+ # The receive loop must neither park nor see the later delivery failure.
+ await asyncio.wait_for(adapter.handle_message(MessageEvent(text='two', source=source, message_id='m2')), 3)
+ first_gate.set()
+ await _wait_for(lambda: len(adapter.sent) == 2 and not adapter._background_tasks)
+ # Exactly one reply per input; the error notice may race the first turn's own delivery.
+ assert 'FIRST_REPLY' in adapter.sent
+ assert sum('render exploded' in text for text in adapter.sent) == 1, adapter.sent
+ assert _statuses(authority) == {'one': 'terminal', 'two': 'terminal'}
+ assert unhandled == []