The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): recover session.interrupt when the compute host is dead
Brooklyn Nicholson53bc70c5ee85
diff --git a/tests/tui_gateway/test_interrupt_dead_compute_host.py b/tests/tui_gateway/test_interrupt_dead_compute_host.pynew file mode 100644index 00000000000..a3d65da6757--- /dev/null+++ b/tests/tui_gateway/test_interrupt_dead_compute_host.py@@ -0,0 +1,127 @@+"""session.interrupt on a compute host that is gone (hermes-agent 82603).++A dead host (broken pipe, respawn exhausted) can never deliver the ``turn.end`` that clears+``running``. Stop used to return 5019 and leave the session busy forever, so every later+``prompt.submit`` queued with no way back short of a backend restart. Stop now recovers the+session unless the supervisor still owes it a completion or a successor turn owns it.+"""++from __future__ import annotations++import threading++from tui_gateway import server+++class _DeadComputeHost:+ """Supervisor whose interrupt() raises and which owes a completion only for ``pending_sids``."""++ def __init__(self, pending_sids=()):+ self._pending_sids = set(pending_sids)++ def interrupt(self, sid, *, request_id=None):+ raise RuntimeError("compute host is not running")++ def has_pending_turn(self, sid):+ return sid in self._pending_sids+++def _isolated_session(sid, monkeypatch, host, **extra):+ session = {+ "agent": None,+ "agent_ready": threading.Event(),+ "session_key": "session-key",+ "history": [],+ "history_lock": threading.Lock(),+ "running": True,+ "_compute_host_active": True,+ **extra,+ }+ server._sessions[sid] = session+ monkeypatch.setattr(server, "_load_cfg", lambda: {"dashboard": {"turn_isolation": True}})+ monkeypatch.setattr(server, "_get_compute_host_supervisor", lambda _cfg=None: host)+ return session+++def _interrupt(sid):+ try:+ return server.handle_request({"id": "1", "method": "session.interrupt", "params": {"session_id": sid}})+ finally:+ server._sessions.pop(sid, None)+++def test_dead_host_stop_clears_the_stuck_turn(monkeypatch):+ session = _isolated_session(+ "iso-dead", monkeypatch, _DeadComputeHost(),+ queued_prompt={"text": "stale next", "transport": None},+ inflight_turn={"user": "hi", "assistant": "", "streaming": True},+ )++ resp = _interrupt("iso-dead")++ assert resp.get("result") == {"status": "interrupted", "turn_isolation": True}, resp+ assert session["running"] is False+ assert session["_turn_cancel_requested"] is True+ assert session.get("queued_prompt") is None+ assert session.get("inflight_turn") is None+++def test_a_pending_host_completion_keeps_its_own_teardown(monkeypatch):+ session = _isolated_session(+ "iso-pending", monkeypatch, _DeadComputeHost(pending_sids=("iso-pending",)),+ inflight_turn={"user": "hi", "assistant": "", "streaming": True},+ )++ resp = _interrupt("iso-pending")++ assert resp.get("result") == {"status": "interrupted", "turn_isolation": True}, resp+ assert session["running"] is True+ assert session["_turn_cancel_requested"] is True+ assert session.get("inflight_turn") is not None+++def test_after_teardown_running_belongs_to_the_drain(monkeypatch):+ # The crash waiter already cleared inflight; a successor drain may own `running` for its queued prompt.+ session = _isolated_session("iso-post", monkeypatch, _DeadComputeHost(), inflight_turn=None)++ resp = _interrupt("iso-post")++ assert resp.get("result") == {"status": "interrupted", "turn_isolation": True}, resp+ assert session["running"] is True+ assert session["_turn_cancel_requested"] is True+++def test_a_successor_turn_that_replaced_inflight_is_not_clobbered(monkeypatch):+ old_inflight = {"user": "old", "assistant": "", "streaming": True}+ new_inflight = {"user": "new", "assistant": "", "streaming": True}+ host = _DeadComputeHost()+ session = _isolated_session("iso-race", monkeypatch, host, inflight_turn=old_inflight)++ def interrupt_and_swap(sid, *, request_id=None):+ # prompt.submit replaces inflight after history_lock is released, before submit_turn registers it.+ with session["history_lock"]:+ session["inflight_turn"] = new_inflight+ session["_turn_cancel_requested"] = False+ raise RuntimeError("compute host is not running")++ host.interrupt = interrupt_and_swap++ resp = _interrupt("iso-race")++ assert resp.get("result") == {"status": "interrupted", "turn_isolation": True}, resp+ assert session["running"] is True+ assert session.get("inflight_turn") is new_inflight+ assert session["_turn_cancel_requested"] is True+++def test_supervisor_reports_pending_turns_per_session():+ from tui_gateway.host_supervisor import HostSupervisor++ supervisor = HostSupervisor.__new__(HostSupervisor) # __init__ would spawn a child+ supervisor._lock = threading.RLock()+ supervisor._pending_turns = {"req-a": ("sid-a", None), "req-b": ("sid-b", None)}++ assert supervisor.has_pending_turn("sid-a") is True+ assert supervisor.has_pending_turn("sid-c") is False+ supervisor._pending_turns.pop("req-a")+ assert supervisor.has_pending_turn("sid-a") is Falsediff --git a/tests/tui_gateway/test_interrupt_does_not_wait_for_agent.py b/tests/tui_gateway/test_interrupt_does_not_wait_for_agent.pyindex c5c22e2edd5..2ba97819700 100644--- a/tests/tui_gateway/test_interrupt_does_not_wait_for_agent.py+++ b/tests/tui_gateway/test_interrupt_does_not_wait_for_agent.py@@ -55,6 +55,17 @@ def test_stop_succeeds_after_the_agent_build_failed(sid):assert response.get("result", {}).get("status") == "interrupted", response+def test_stop_frees_a_running_session_whose_build_failed(sid):+ """A failed build with no run thread left must not stay busy: every later submit would queue (#82603)."""+ session = record(sid, agent_build_started=True, agent_error=REMOVED_PROVIDER, running=True)+ session["agent_ready"].set()++ response = interrupt(sid)++ assert response.get("result", {}).get("status") == "interrupted", response+ assert session["running"] is False++def test_stop_cancels_a_turn_parked_on_an_unfinished_build(sid):"""The handler returns while the build event is still unset, and the parked turn sees the cancel."""session = record(sid, agent_build_started=True, running=True,diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex 51fc3f418cc..c270a0e7639 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -14332,7 +14332,7 @@ def test_interrupt_error_after_tts_stop_still_resumes_wake(monkeypatch):{"id": "host", "method": "session.interrupt", "params": {"session_id": "sid"}},transport=owner,)- assert failed["error"]["code"] == 5019+ assert failed["result"] == {"status": "interrupted", "turn_isolation": True}assert state["paused"] is Falseassert state["resumed"] == [owner, owner]finally:diff --git a/tui_gateway/host_supervisor.py b/tui_gateway/host_supervisor.pyindex 6e2f9aa26bb..76e6182f9d1 100644--- a/tui_gateway/host_supervisor.py+++ b/tui_gateway/host_supervisor.py@@ -255,6 +255,17 @@ class HostSupervisor:self._send_frame({"type": "interrupt", "sid": sid, "request_id": request_id or uuid.uuid4().hex})+ def has_pending_turn(self, sid: str) -> bool:+ """True when a host completion callback is still registered for ``sid``.++ Read by the serving process to tell "the host still owes this session a+ terminal frame" from "nothing will ever call back for it". Entries are+ added in :meth:`submit_turn` and removed by ``turn.end``/``turn.error``+ handling or :meth:`_fail_pending_turns`, all under ``self._lock``.+ """+ with self._lock:+ return any(s == sid for s, _cb in self._pending_turns.values())+def _await_reply(self, frame: dict[str, Any], request_id: str, timeout: float) -> dict:"""Send ``frame`` and block for the host reply carrying ``request_id``."""q: queue.Queue[dict] = queue.Queue(maxsize=1)diff --git a/tui_gateway/methods_session_interrupt.py b/tui_gateway/methods_session_interrupt.pyindex 40cd1a06088..43ba3505ede 100644--- a/tui_gateway/methods_session_interrupt.py+++ b/tui_gateway/methods_session_interrupt.py@@ -38,6 +38,35 @@ def _note_user_input(session: dict) -> None:session["_turn_user_input"] = True+def _recover_unreachable_compute_host_turn(sid: str, session: dict, inflight_at_interrupt) -> None:+ """Stop on a compute host that is gone (broken pipe, respawn exhausted, #82603).++ The failed dial raised before ``_interrupt_session_turn`` purged the queue, and no ``turn.end`` will ever+ clear ``running``, so every later submit would queue forever. Clear the turn only when the supervisor owes+ no completion for it and the inflight dict is still the one this Stop saw (a successor turn keeps its own).+ The probe runs outside ``history_lock``: compute-host calls never run under it.+ """+ try:+ pending = _get_compute_host_supervisor().has_pending_turn(sid)+ except Exception as exc: # health: allow BLE001 -- an unreadable supervisor is not proof the turn ended; fail closed+ logger.warning("session.interrupt: compute-host pending-turn probe failed for %s: %s", sid, exc)+ pending = True+ with session["history_lock"]:+ session["_turn_cancel_requested"] = True+ session["queued_prompt"] = None+ session.pop("queued_prompts", None)+ session["_queued_prompt_generation"] = int(session.get("_queued_prompt_generation", 0)) + 1+ inflight_now = session.get("inflight_turn")+ if not pending and session.get("running") and inflight_now is not None and inflight_now is inflight_at_interrupt:+ session["running"] = False+ _clear_inflight_turn(session)+ _clear_pending(sid)+ with contextlib.suppress(Exception):+ _announce_cancelled_gateway_approvals(session, "interrupt", session_id=sid)+ from tools.approval import resolve_gateway_approval+ resolve_gateway_approval(session["session_key"], "deny", resolve_all=True)++@method("session.interrupt")def _(rid, params: dict) -> dict:_tts_stream_stop() # keypress barge-in also silences streaming TTS (voice is process-global)@@ -55,10 +84,13 @@ def _(rid, params: dict) -> dict:sid = str(params.get("session_id") or "")_note_user_input(session)if _session_uses_compute_host(session):+ with session["history_lock"]:+ inflight_at_interrupt = session.get("inflight_turn")try:_interrupt_session_turn(sid, session, request_id=f"interrupt-{rid}")- except Exception as exc: # health: allow BLE001 -- the bridge raises transport-specific errors unknown here; surfaced verbatim to the client, never swallowed- return _err(rid, 5019, f"compute-host interrupt failed: {exc}")+ except Exception as exc: # health: allow BLE001 -- the bridge raises transport-specific errors unknown here; logged, and Stop recovers the session instead of failing+ logger.warning("session.interrupt: compute-host interrupt failed for %s: %s", sid, exc)+ _recover_unreachable_compute_host_turn(sid, session, inflight_at_interrupt)return _ok(rid, {"status": "interrupted", "turn_isolation": True})# No agent wait: a turn parked on the deferred build already honors _turn_cancel_requested. Waiting here# failed Stop with 5032 once the build failed or outlived 30s (and started a build for a lazy session), so