Skip to content

The agent that grows with you

test(gateway): pin the drain re-check for a wake the busy handler queued

calvinnwq65b3493dc2b8
diff --git a/gateway/wake.py b/gateway/wake.py
index 4bea4183df5..bdb6e7ff374 100644
--- a/gateway/wake.py
+++ b/gateway/wake.py
@@ -107,10 +107,10 @@ async def admit_internal_event(adapter: Any, event: Any) -> None:
await adapter.handle_message(event)
if event._gateway_accepted is not True:
raise WakeNotAccepted()
- # handle_message can await (Telegram topic recovery, the busy handler's profile scope)
- # before it claims or queues the event. The in-tree adapters do not await after the claim,
- # so this read sees the drain state the claim was made under: a drain that began
- # mid-admission dooms the claimed turn the same way.
+ # handle_message can await before it claims or queues the event (Telegram topic recovery)
+ # and after (the busy handler's later awaits). A drain seen here, whenever it began, still
+ # dooms the stored event: the drain gate refuses the claimed turn and the queued follow-up
+ # is discarded. Refuse it so the producer retries it after the restart.
if _runner_draining(adapter):
raise WakeNotAccepted("gateway began draining during admission; retry after restart")
diff --git a/tests/gateway/test_wake_during_restart_drain.py b/tests/gateway/test_wake_during_restart_drain.py
index bc68f4ff1ce..a81fcc4820c 100644
--- a/tests/gateway/test_wake_during_restart_drain.py
+++ b/tests/gateway/test_wake_during_restart_drain.py
@@ -133,3 +133,27 @@ async def test_wake_is_refused_when_drain_starts_during_admission():
await admission
await drain(adapter)
assert turns == []
+
+
+async def test_wake_is_refused_when_drain_starts_after_the_busy_handler_queued_it():
+ """The busy handler can await after it stores the wake: a drain that begins there dooms the
+ queued follow-up, so the wake must be refused (and retried), not receipted and discarded."""
+ runner, adapter, source, _turns = wake_route()
+ key = adapter._event_session_key(MessageEvent(text="", source=source))
+ adapter._active_sessions[key] = asyncio.Event() # a turn is still running in this chat
+ store = adapter._busy_session_handler
+
+ async def store_then_drain(event, session_key):
+ handled = await store(event, session_key) # the wake is now the pending follow-up
+ runner._draining = True # /restart begins during the handler's later awaits
+ await asyncio.sleep(0)
+ return handled
+
+ adapter._busy_session_handler = store_then_drain
+ with pytest.raises(WakeNotAccepted):
+ await deliver_wake(adapter, text="[kanban] Task t_1 completed.", source=source)
+ event, text = await runner._run_agent_drain_pending(
+ {"final_response": "done"}, adapter, source, key
+ )
+ assert (event, text) == (None, None) # discarded by the drain, so it runs only on the retry