fix(gateway): /stop ends a turn still in pre-agent setup (#138358)

A turn wedged before its agent starts (session resolve, turn prepare, an
agent:start hook) held the pending slot; /stop released the classic slot
but the setup kept awaiting, so the session's durable FIFO drain stayed
parked on it: the next DM was never answered and shutdown reported an
authority task that did not settle.

The setup bound now lives in run_turn_setup_guard.py and publishes a
stop handle on the turn slot. /stop and /new (both through
_interrupt_and_clear_session, plus the pending-sentinel HARD STOP path)
end the setup; the turn returns normally, so its finally blocks release
the slot, lease and marker and the drain settles and advances. A real
cancellation (shutdown, the drain's own) is never swallowed. Moving the
guarded setup into the sibling keeps run_turn.py and run_inbound.py at
or under main's length.
This commit is contained in:
Teknium
2026-11-11 08:56:17 -08:00
parent b74158ddd2
commit 3d1d7c2dac
6 changed files with 253 additions and 110 deletions

View File

@@ -555,6 +555,10 @@ class GatewayAgentCacheMixin:
session_key, interrupt_reason=interrupt_reason, invalidation_reason=invalidation_reason,
)
from gateway.run import _AGENT_PENDING_SENTINEL
if running_agent is _AGENT_PENDING_SENTINEL:
# No agent to interrupt yet: end the setup itself, or the turn keeps its FIFO claim (#138358).
from gateway.run_turn_setup_guard import cancel_preagent_setup
cancel_preagent_setup(self, session_key)
# The turn's hard interrupt reaches only its in-turn children; background delegations were
# detached at dispatch and would otherwise run to completion and wake the session later.
# Each interrupted unit still returns as a completion (status=interrupted, partial output).

View File

@@ -28,6 +28,7 @@ from gateway.run_inbound_media import rehome_inbound_media
from gateway.run_inbound_hooks import GatewayInboundHooksMixin
from gateway.run_inbound_transcription import GatewayInboundTranscriptionMixin
from gateway.run_plugin_injection import GatewayPluginInjectionMixin
from gateway.run_turn_setup_guard import cancel_preagent_setup, pending_setup_busy_notice
from gateway.run_inbound_unauthorized import (
UnauthorizedOwnerNotifier, pairing_code_reply, pairing_profile_arg, pairing_rate_limited_reply,
unauthorized_owner_hint,
@@ -835,32 +836,6 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayInboundTranscriptionM
await self._busy_interrupt_and_ack(event, _quick_key, adapter, state, running_agent, outcome)
return bool(outcome.steered or outcome.redirected)
def _pending_setup_busy_notice(self, session_key: str) -> Optional[str]:
"""Visible busy ack when a follow-up arrives behind a wedged pre-agent turn.
Fresh PENDING setup stays silent (the historical race-avoidance). After
``session_stall_timeout`` with no agent activity the user gets the same
class of notice as a stalled running turn (#138358). 0 disables.
"""
from gateway.run import _float_env
if os.environ.get("HERMES_GATEWAY_BUSY_ACK_ENABLED", "true").lower() != "true":
return None
timeout = _float_env("HERMES_SESSION_STALL_TIMEOUT", 300)
if timeout <= 0:
return None
state = self._peek_session_state(session_key)
started = float(getattr(getattr(state, "turn", None), "started_ts", 0.0) or 0.0)
if state is None or not started:
return None
now = time.time()
age = now - started
if age < timeout:
return None
if now - float(state.turn.busy_ack_ts or 0.0) < 30:
return None
state.turn.busy_ack_ts = now
return t("gateway.busy.setup_waiting", minutes=max(1, int(age // 60)))
async def _hm_handle_running_session_message(
self, event: MessageEvent, source: SessionSource, _quick_key: str
) -> Optional[str]:
@@ -887,11 +862,12 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayInboundTranscriptionM
running_agent = _ra_state.turn.agent if _ra_state else None
if running_agent is _AGENT_PENDING_SENTINEL: # agent still being set up
if event.get_command() == "stop": # force-clean the sentinel so the session is unlocked
cancel_preagent_setup(self, _quick_key) # and end the setup still holding its claim
self._release_running_agent_state(_quick_key)
logger.info("HARD STOP (pending) for session %s — sentinel cleared", _quick_key)
return EphemeralReply(t("gateway.stop.force_stopped_pending"))
self._hm_merge_pending_for_source(source, _quick_key, event, merge_text=True) # picked up after start
return self._pending_setup_busy_notice(_quick_key)
return pending_setup_busy_notice(self, _quick_key)
if self._draining:
queue_during_drain = self._queue_during_drain_enabled(effective_busy_input_mode)
if queue_during_drain:

View File

@@ -16,11 +16,10 @@ import os
import queue
import threading
import time
import traceback
from agent.i18n import t
from agent.session_activity import format_iteration_progress
from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE
from contextlib import asynccontextmanager, nullcontext, suppress
from contextlib import nullcontext, suppress
from contextvars import copy_context
from gateway.bot_peer_notices import automatic_notices_allowed
from gateway.config import Platform
@@ -53,61 +52,6 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
# Log-record parity with the origin module.
logger = logging.getLogger("gateway.run")
@asynccontextmanager
async def _preagent_setup_timeout(session_key: str):
"""Bound session-resolve / turn-prepare / agent:start on the current task.
The inactivity watchdog starts only inside ``_run_agent``; a hang before
that holds ``_AGENT_PENDING_SENTINEL`` forever (#138358). ``delay <= 0``
(HERMES_AGENT_TIMEOUT=0) restores the unbounded legacy. Same-task so
session ContextVars set during prepare remain visible to ``_run_agent``.
"""
from gateway.run import _dump_wedged_turn_stacks, _float_env
delay = _float_env("HERMES_AGENT_TIMEOUT", 1800)
if delay <= 0:
yield
return
loop = asyncio.get_running_loop()
task = asyncio.current_task()
fired = False
def _fire() -> None:
nonlocal fired
fired = True
if task is None or task.done():
return
try:
frames = task.get_stack(limit=25)
stack = "".join(traceback.format_stack(frames[-1]) if frames else [])
logger.error(
"Pre-agent setup timed out for %s after %.0fs "
"(HERMES_AGENT_TIMEOUT / agent.gateway_timeout); "
"cancelling the wedged turn:\n%s",
session_key, delay, stack or "<no asyncio stack>",
)
_dump_wedged_turn_stacks(session_key)
except Exception:
logger.error(
"Pre-agent setup timed out for %s after %.0fs "
"(HERMES_AGENT_TIMEOUT / agent.gateway_timeout); stack dump failed",
session_key, delay, exc_info=True,
)
task.cancel()
handle = loop.call_later(delay, _fire)
try:
yield
except asyncio.CancelledError:
if fired:
if task is not None:
task.uncancel()
raise TimeoutError from None
raise
finally:
handle.cancel()
_tool_call_logger_lock = threading.Lock()
@@ -254,31 +198,12 @@ class GatewayTurnMixin(GatewayBackgroundMixin, GatewayTurnPrepareMixin, GatewayT
(getattr(event, "reply_to_text", None) or "")[:80].replace("\n", " "),
)
try:
async with _preagent_setup_timeout(_quick_key):
resolved = await self._hmwa_resolve_session(event, source)
if resolved is None:
return
source, session_entry, session_key = resolved
prepared, _session_env_tokens = await self._hmwa_prepare_turn(
event, source, session_entry, session_key, _quick_key, run_generation,
)
if not isinstance(prepared, self._PreparedTurn):
return prepared
history, message_text = prepared.history, prepared.message_text
hook_ctx = {
"platform": source.platform.value if source.platform else "",
"user_id": source.user_id,
"chat_id": source.chat_id or "",
"thread_id": str(source.thread_id) if getattr(source, "thread_id", None) else "",
"chat_type": getattr(source, "chat_type", "") or "",
"session_id": session_entry.session_id,
"message": message_text[:500],
}
await self.hooks.emit("agent:start", hook_ctx)
except TimeoutError:
return t("gateway.busy.setup_timeout")
from gateway.run_turn_setup_guard import run_preagent_setup
setup, reply = await run_preagent_setup(self, event, source, _quick_key, run_generation)
if setup is None:
return reply
source, session_entry, session_key, prepared, _session_env_tokens, hook_ctx = setup
history, message_text = prepared.history, prepared.message_text
try:
# Capture the launch session id so post-run compression publication is identity-guarded

View File

@@ -0,0 +1,152 @@
"""The pre-agent setup guard (#138358): session resolve, turn prepare and the ``agent:start`` hooks
run before the inactivity watchdog exists, so a hang there held the turn's slot (and the session's
durable FIFO behind it) forever. The guard bounds that phase and lets /stop or /new end it.
It runs on the turn's own task, so ContextVars set during prepare stay visible to the agent run.
Ending setup cancels that task and converts the cancellation at the guard, so the turn returns
normally: its finally blocks release the slot, lease and marker, and a FIFO drain awaiting it
settles the admission and moves on.
"""
from __future__ import annotations
import asyncio
import logging
import traceback
from contextlib import asynccontextmanager
from typing import Any, Optional
from agent.i18n import t
logger = logging.getLogger("gateway.run")
_TIMEOUT = "timeout"
_STOPPED = "stopped"
class PreagentSetupStopped(Exception):
"""/stop or /new ended the turn while it was still in setup; their own reply already told the user."""
@asynccontextmanager
async def preagent_setup_guard(runner, session_key: str):
"""Bound setup by ``HERMES_AGENT_TIMEOUT`` (``agent.gateway_timeout``; ``<= 0`` = unbounded) and
publish a stop handle on the turn slot. Raises ``TimeoutError`` past the deadline and
``PreagentSetupStopped`` after ``cancel_preagent_setup``."""
from gateway.run import _dump_wedged_turn_stacks, _float_env
delay = _float_env("HERMES_AGENT_TIMEOUT", 1800)
task = asyncio.current_task()
turn = runner._session_state(session_key).turn
reason = None
def _end(why: str) -> bool:
nonlocal reason
if reason is not None or task is None or task.done():
return False
reason = why
task.cancel()
return True
def _fire() -> None:
try:
frames = task.get_stack(limit=25) if task is not None else []
stack = "".join(traceback.format_stack(frames[-1])) if frames else ""
logger.error(
"Pre-agent setup timed out for %s after %.0fs (HERMES_AGENT_TIMEOUT / "
"agent.gateway_timeout); cancelling the wedged turn:\n%s",
session_key, delay, stack or "<no asyncio stack>",
)
_dump_wedged_turn_stacks(session_key)
except Exception:
logger.error("Pre-agent setup timed out for %s after %.0fs; stack dump failed",
session_key, delay, exc_info=True)
_end(_TIMEOUT)
handle = asyncio.get_running_loop().call_later(delay, _fire) if delay > 0 else None
def stop() -> bool:
return _end(_STOPPED)
turn.setup_stop = stop
try:
try:
yield
except asyncio.CancelledError:
if reason is None or (task is not None and task.cancelling() > 1):
raise # a real cancellation (shutdown, the drain's) is never swallowed
if reason is not None:
# Also when setup swallowed the cancel and finished: the turn was ended either way, and
# the pending cancel request must not outlive it on this (possibly the drain's) task.
if task is not None:
task.uncancel()
if reason == _TIMEOUT:
raise TimeoutError from None
raise PreagentSetupStopped from None
finally:
if handle is not None:
handle.cancel()
if turn.setup_stop is stop:
turn.setup_stop = None
def cancel_preagent_setup(runner, session_key: str) -> bool:
"""End the session's turn if it is still in setup (before any agent ran). True when it was."""
state = runner._peek_session_state(session_key)
stop = state.turn.setup_stop if state is not None else None
if stop is None or not stop():
return False
logger.info("Cancelled pre-agent setup for session %s", session_key)
return True
async def run_preagent_setup(runner, event, source, quick_key: str, run_generation: int) -> tuple[Optional[tuple], Any]:
"""Session resolve, turn prepare and ``agent:start`` under the guard. ``(setup, None)`` to run
the agent, setup = ``(source, session_entry, session_key, prepared, env_tokens, hook_ctx)``;
``(None, reply)`` when the turn ends here. A deadline ends it with a visible resend notice, so
a person's message is never dropped silently; a /stop or /new answers for itself."""
try:
async with preagent_setup_guard(runner, quick_key):
resolved = await runner._hmwa_resolve_session(event, source)
if resolved is None:
return None, None
source, session_entry, session_key = resolved
prepared, env_tokens = await runner._hmwa_prepare_turn(
event, source, session_entry, session_key, quick_key, run_generation,
)
if not isinstance(prepared, runner._PreparedTurn):
return None, prepared
hook_ctx = {
"platform": source.platform.value if source.platform else "",
"user_id": source.user_id,
"chat_id": source.chat_id or "",
"thread_id": str(source.thread_id) if getattr(source, "thread_id", None) else "",
"chat_type": getattr(source, "chat_type", "") or "",
"session_id": session_entry.session_id,
"message": prepared.message_text[:500],
}
await runner.hooks.emit("agent:start", hook_ctx)
except (TimeoutError, PreagentSetupStopped) as ended:
runner._clear_session_env([]) # prepare may have bound them before the hang
return None, (t("gateway.busy.setup_timeout") if isinstance(ended, TimeoutError) else None)
return (source, session_entry, session_key, prepared, env_tokens, hook_ctx), None
def pending_setup_busy_notice(runner, session_key: str) -> Optional[str]:
"""Visible busy ack for a follow-up queued behind a turn still in setup. Fresh setup stays
silent (the historical race-avoidance); past ``session_stall_timeout`` (0 disables) the user
gets the same class of notice as a stalled running turn, debounced to one per 30 s."""
import os
import time
from gateway.run import _float_env
if os.environ.get("HERMES_GATEWAY_BUSY_ACK_ENABLED", "true").lower() != "true":
return None
timeout = _float_env("HERMES_SESSION_STALL_TIMEOUT", 300)
state = runner._peek_session_state(session_key)
started = float(getattr(getattr(state, "turn", None), "started_ts", 0.0) or 0.0)
if timeout <= 0 or state is None or not started:
return None
now = time.time()
age = now - started
if age < timeout or now - float(state.turn.busy_ack_ts or 0.0) < 30:
return None
state.turn.busy_ack_ts = now
return t("gateway.busy.setup_waiting", minutes=max(1, int(age // 60)))

View File

@@ -30,6 +30,8 @@ class TurnState:
started_ts: float = 0.0 # 0.0 = not running
lease: Any = None # cross-process active-session slot lease
busy_ack_ts: float = 0.0 # debounce; 0.0 = never acked
# Ends the turn while it is still in pre-agent setup (``run_turn_setup_guard``); None otherwise.
setup_stop: Optional[Callable[[], bool]] = None
# Held turn-lease tokens keyed by acquiring run generation: release/rebind resolve the
# token for their own generation, so a displaced turn's unwind frees only its own lease and
# never a successor's (an evicted turn and its replacement may both hold one briefly).
@@ -56,7 +58,7 @@ class TurnState:
def clear(self) -> None:
"""Reset the per-turn slot. The caller pops ``lease`` first to release it."""
self.agent = self.lease = self.event = self.ctx = self.follow_up_event = None
self.agent = self.lease = self.event = self.ctx = self.follow_up_event = self.setup_stop = None
self.started_ts = self.busy_ack_ts = 0.0

View File

@@ -0,0 +1,84 @@
"""Invariant (#138358): a turn still in pre-agent setup (session resolve, turn prepare,
``agent:start`` hooks) is ended by /stop, and by its own deadline, instead of holding the
session's slot and the durable FIFO behind it forever.
Real ``GatewayRunner`` + real ``BasePlatformAdapter`` subclass; only the setup step that hangs is
replaced, since any unbounded await there is the bug's trigger.
"""
import asyncio
import pytest
from gateway.config import GatewayConfig, Platform, PlatformConfig
from gateway.platforms.base import BasePlatformAdapter, SendResult
from gateway.platforms.event import MessageEvent, MessageType
from gateway.run import GatewayRunner, _AGENT_PENDING_SENTINEL
from gateway.session import SessionSource
class _Adapter(BasePlatformAdapter):
def __init__(self):
super().__init__(PlatformConfig(enabled=True, token="x"), Platform.TELEGRAM)
@property
def name(self):
return "telegram"
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):
return SendResult(success=True)
async def get_chat_info(self, chat_id):
return {"id": chat_id, "type": "private"}
def _wedged_turn(monkeypatch, timeout: str):
monkeypatch.setenv("HERMES_AGENT_TIMEOUT", timeout)
adapter = _Adapter()
runner = GatewayRunner(config=GatewayConfig(platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="x")}))
runner.adapters = {Platform.TELEGRAM: adapter}
source = SessionSource(platform=Platform.TELEGRAM, chat_id="c1", chat_type="dm", user_id="u1", user_name="tester")
event = MessageEvent(text="hello", message_type=MessageType.TEXT, source=source, message_id="m1")
key = adapter._event_session_key(event)
entered = asyncio.Event()
async def _hang(*_args, **_kwargs):
entered.set()
await asyncio.sleep(3600)
runner._hmwa_resolve_session = _hang
state = runner._session_state(key)
state.turn.agent = _AGENT_PENDING_SENTINEL # the claim _handle_message makes before setup
generation = runner._begin_session_run_generation(key)
task = asyncio.ensure_future(runner._handle_message_with_agent(event, source, key, generation))
return runner, source, key, task, entered
@pytest.mark.asyncio
async def test_stop_ends_a_turn_wedged_in_setup(monkeypatch):
runner, source, key, task, entered = _wedged_turn(monkeypatch, "600") # deadline far away
await asyncio.wait_for(entered.wait(), 5)
await runner._interrupt_and_clear_session(key, source, interrupt_reason="stop", invalidation_reason="stop_command")
# The turn returns (no second reply: /stop's own answers the user), so whatever awaits it,
# the session's FIFO drain included, settles and moves on.
assert await asyncio.wait_for(task, 5) is None
assert not task.cancelled()
assert runner._peek_session_state(key).turn.setup_stop is None
@pytest.mark.asyncio
async def test_setup_past_its_deadline_ends_with_a_visible_notice(monkeypatch):
runner, _source, key, task, entered = _wedged_turn(monkeypatch, "0.2")
await asyncio.wait_for(entered.wait(), 5)
reply = await asyncio.wait_for(task, 5)
assert "Turn setup stalled" in reply and "resend" in reply # never dropped silently
assert runner._peek_session_state(key).turn.setup_stop is None