Skip to content

The agent that grows with you

fix(gateway): make a serial reader's command wait for a non-burst input queued behind a capture

David Dudok de Witda5e6117373b
diff --git a/gateway/session_ingress.py b/gateway/session_ingress.py
index d02039468bd..e1911f75180 100644
--- a/gateway/session_ingress.py
+++ b/gateway/session_ingress.py
@@ -405,10 +405,13 @@ async def dispatch_shared_busy(adapter, event, session_key, *, durable=False):
capturing (its position is then fixed; acceptance still waits for the commit); a tracked
observer delivers its one reply. *durable*: return only once the row is committed (or the input
was refused, fenced or answered), never on the earlier position release: a busy burst's commit
- task, which a command barrier (``/restart`` closing admission) waits on."""
+ task, which a command barrier (``/restart`` closing admission) waits on. Otherwise an input
+ released before its commit is held until it commits or its handler ends, and a serial reader's
+ next command waits for that too (``burst_gate``): a non-burst busy input (a second video, a voice
+ note, text outside queue mode) has no burst commit task to wait on."""
delivery_event = replace(event, source=replace(event.source))
accepted = asyncio.get_running_loop().create_future()
- committed = asyncio.get_running_loop().create_future() if durable else None
+ committed = asyncio.get_running_loop().create_future()
async def observe():
# Like the first message's lifecycle, this sender adopts the turn's crash marker and
@@ -441,7 +444,7 @@ async def dispatch_shared_busy(adapter, event, session_key, *, durable=False):
task.add_done_callback(adapter._background_tasks.discard)
try:
await asyncio.wait({accepted, task}, return_when=asyncio.FIRST_COMPLETED)
- if committed is not None and not task.done():
+ if durable and not task.done():
await asyncio.wait({committed, task}, return_when=asyncio.FIRST_COMPLETED)
except asyncio.CancelledError:
if not accepted.done():
@@ -449,3 +452,21 @@ async def dispatch_shared_busy(adapter, event, session_key, *, durable=False):
raise
if task.done():
task.result() # refused, consumed or answered inline before any durable acceptance
+ elif not committed.done():
+ _hold_until_committed(adapter, committed, task)
+
+
+def _hold_until_committed(adapter, committed, task):
+ """Released before its commit: the reader reads on, but this input is not durable yet. A serial
+ reader's next command waits for its commit or its handler's end (``burst_gate``), so /restart never
+ closes admission, and /new never cancels the chat's rows, before it lands."""
+ settled = asyncio.get_running_loop().create_future()
+
+ def settle(_):
+ if not settled.done():
+ settled.set_result(None)
+ committed.add_done_callback(settle)
+ task.add_done_callback(settle)
+ held = adapter.__dict__.setdefault('_uncommitted_inputs', set())
+ held.add(settled)
+ settled.add_done_callback(held.discard)
diff --git a/gateway/session_ingress_burst.py b/gateway/session_ingress_burst.py
index 0dfc9c450f1..79f35fd9507 100644
--- a/gateway/session_ingress_burst.py
+++ b/gateway/session_ingress_burst.py
@@ -69,6 +69,8 @@ async def burst_gate(adapter, event, session_key):
_flush(adapter, key, burst)
if pending := list(adapter.__dict__.get('_shared_burst_commits', {}).values()):
await asyncio.wait(pending)
+ if held := list(adapter.__dict__.get('_uncommitted_inputs', ())):
+ await asyncio.wait(held) # a non-burst input released behind an earlier one, not durable yet
return False
diff --git a/tests/gateway/test_busy_burst_serial_reader.py b/tests/gateway/test_busy_burst_serial_reader.py
index b0c5425387c..db7fdc122a5 100644
--- a/tests/gateway/test_busy_burst_serial_reader.py
+++ b/tests/gateway/test_busy_burst_serial_reader.py
@@ -222,3 +222,56 @@ async def test_restart_waits_for_a_held_text_queued_behind_a_slow_capture(monkey
await async_wait_until(lambda: all(row['status'] == 'terminal' for row in _rows(authority)), timeout=15,
what='both turns to run')
await asyncio.to_thread(authority.db.close)
+
+
+async def test_restart_waits_for_a_direct_busy_input_queued_behind_a_slow_capture(monkeypatch, tmp_path):
+ """The same with the default busy mode: the text is no burst, so it goes straight to the shared
+ runtime, queues behind the capture and releases the reader before it is durable. With no burst commit
+ to wait on, the /restart it reads next must still wait for that row (Signal live: both lost)."""
+ from gateway import session_ingress_burst
+ from gateway.session_authority import SessionAuthority
+ from gateway.session_runtime_workers import mutation_tasks
+ adapter, source = _signal(monkeypatch)
+ entered, release = _hold_capture(monkeypatch)
+ monkeypatch.setattr(SessionAuthority, '_schedule', lambda self, ref: None) # no drain: rows stay queued
+ runner = GatewayRunner(GatewayConfig())
+
+ async def send(chat_id, content, reply_to=None, metadata=None):
+ return SendResult(success=True, message_id='sent')
+ monkeypatch.setattr(adapter, 'send', send)
+ adapter.gateway_runner = runner
+ runner.adapters = {adapter.platform: adapter}
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='owner')
+ runner._wire_adapter_handlers(adapter) # no text burst: B goes straight to dispatch_shared_busy
+ monkeypatch.setattr(runner, 'request_restart', lambda **kw: setattr(runner, '_draining', True))
+ passed, real_gate = [], session_ingress_burst.burst_gate
+
+ async def gate(adapter, event, session_key): # the rows when the command passes the reader's barrier
+ behind = await real_gate(adapter, event, session_key)
+ if event.get_command() == 'restart':
+ passed.append(sorted(row['request_id'] for row in _rows(authority)))
+ return behind
+ monkeypatch.setattr(session_ingress_burst, 'burst_gate', gate)
+ clip = tmp_path / 'clip.mp4'
+ clip.write_bytes(b'video bytes' * 100)
+ key = runner._session_key_for_source(source)
+ try:
+ await adapter.handle_message(MessageEvent(text='A', source=source, message_id='A', message_type=MessageType.VIDEO,
+ media_urls=[str(clip)], media_types=['video/mp4']))
+ assert await asyncio.to_thread(entered.wait, 5)
+ await adapter.handle_message(MessageEvent(text='B', source=source, message_id='B'))
+ restart = asyncio.create_task(adapter.handle_message(MessageEvent(text='/restart', source=source,
+ message_id='R')))
+ await async_wait_until(lambda: passed or authority._route_turns.get(key, (None, 0))[1] >= 2,
+ what='B to queue behind the capture')
+ finally:
+ release.set()
+ await asyncio.wait_for(restart, 10)
+ try:
+ assert passed == [['A', 'B']], passed
+ finally:
+ runner._draining = False
+ await adapter.cancel_background_tasks()
+ await async_wait_until(lambda: not mutation_tasks(authority), timeout=10)
+ runner.session_store.close_all_db_handles()