The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): cancel background review when session ends or is stopped
joaomarcosb797ed9779b0
diff --git a/agent/background_review.py b/agent/background_review.pyindex 4045e33a502..3b34116af21 100644--- a/agent/background_review.py+++ b/agent/background_review.py@@ -99,18 +99,26 @@ def finish_background_review_run(agent: Any, run: Optional[_BackgroundReviewRun]run.request_done.set()-def _interrupt_background_review(review_agent: Any) -> None:+def _interrupt_background_review(+ review_agent: Any,+ *,+ message: str = "superseded by a new live turn",+ tool_reason: str = "background review superseded",+) -> None:"""Request abort off-thread so a wedged abort hook cannot stall the live turn (the bounded- ``request_done`` wait in the canceller relies on this returning fast)."""+ ``request_done`` wait in the canceller relies on this returning fast).++ ``message``/``tool_reason`` default to the original live-turn-preemption wording; callers+ cancelling for a different reason (e.g. the owning session itself is ending, #102895) should+ pass their own so logs/diagnostics describe what actually happened.+ """def _interrupt() -> None:try:from agent.interrupt_compat import request_hard_interrupt- request_hard_interrupt(- review_agent, "superseded by a new live turn", tool_reason="background review superseded"- )+ request_hard_interrupt(review_agent, message, tool_reason=tool_reason)except Exception:- logger.debug("Failed to cancel in-flight background review for a new turn", exc_info=True)+ logger.debug("Failed to cancel in-flight background review (%s)", message, exc_info=True)try:threading.Thread(target=_interrupt, daemon=True, name="bg-review-cancel").start()@@ -118,13 +126,27 @@ def _interrupt_background_review(review_agent: Any) -> None:logger.debug("Failed to start background-review cancellation thread", exc_info=True)-def cancel_background_review_for_live_turn(agent: Any) -> None:+def cancel_background_review_for_live_turn(+ agent: Any,+ *,+ message: str = "superseded by a new live turn",+ tool_reason: str = "background review superseded",+) -> None:"""Cancel the current review and await its request-phase acknowledgement. Foreground priority:past the bounded deadline, warn and let the live turn proceed — self-improvement work mustnever block a user-facing turn.Foreground priority is preserved: if the review does not acknowledge within the bounded deadline, awarning is logged and the live turn proceeds anyway. See #84423.++ Despite the name, this is also the session-teardown/interrupt cancellation path+ (``tui_gateway.session_lifecycle._finalize_session`` and ``_interrupt_session_turn``, #102895): a+ session ending or being explicitly stopped while its background review is still running must+ cancel that review the same way a new live turn preempts one — the review fork is invisible to+ every other interrupt/teardown mechanism (not tracked on ``session["running"]``, not joined by+ the run-thread wait), so this is the only thing that ever sets its ``_interrupt_requested``. Pass+ a reason-appropriate ``message``/``tool_reason`` when the caller isn't the live-turn-preemption+ path so diagnostics describe the real cause."""with _optional_lock(agent, "_background_review_lock"):run = getattr(agent, "_background_review_run", None)@@ -134,14 +156,14 @@ def cancel_background_review_for_live_turn(agent: Any) -> None:# survive teardown. Placed in this finally so a fork that consumed tokens and THEN raised is still# attributed (issue #87250). Best-effort: the recorder never raises into the review thread.if review_agent is not None:- _interrupt_background_review(review_agent)+ _interrupt_background_review(review_agent, message=message, tool_reason=tool_reason)if run is None:returnif not run.request_done.wait(timeout=_BACKGROUND_REVIEW_CANCEL_TIMEOUT_SECONDS):logger.warning(- "Background review did not acknowledge cancellation within %.1fs; "- "proceeding with foreground live turn",+ "Background review did not acknowledge cancellation within %.1fs; proceeding (%s)",_BACKGROUND_REVIEW_CANCEL_TIMEOUT_SECONDS,+ message,)diff --git a/tests/tui_gateway/test_finalize_session_cancels_background_review.py b/tests/tui_gateway/test_finalize_session_cancels_background_review.pynew file mode 100644index 00000000000..42dd4248e28--- /dev/null+++ b/tests/tui_gateway/test_finalize_session_cancels_background_review.py@@ -0,0 +1,161 @@+"""Regression for #102895: deleting/closing a session must stop its+in-flight background memory/skill review fork.++The reported symptom: a desktop session's post-turn skill-review fork+degraded into a failed-tool-call retry loop (malformed tool arguments from+a fallback local model). The user deleted the session in the UI, but the+review fork kept calling the model for 70+ minutes — only a full app+restart stopped it.++Root cause: the review fork is a SEPARATE ``AIAgent`` instance tracked only+on the parent's ``_background_review_agent`` / ``_active_children``+(``agent/background_review.py``). It is never registered on+``session["running"]`` or ``session["_run_thread"]``, so it was invisible+to both:+ - ``_teardown_popped_session``'s run-thread join, and+ - ``session.interrupt``'s ``_interrupt_session_turn`` (gated on+ ``session.get("running")``).++Every session-teardown path (explicit close, idle-timeout reap, ws-orphan+reap, shutdown) funnels through ``_finalize_session`` — the single+``_finalized``-guarded chokepoint (see its own docstring) — so that is+where the missing cancellation belongs. The fix calls the existing+``agent.background_review.cancel_background_review_for_live_turn`` helper+(previously only invoked when a NEW live turn preempts a running review)+from ``_finalize_session`` as well, so "this session is ending" cancels an+in-flight review exactly like "a new turn arrived" already did.+"""++from __future__ import annotations++import threading+from unittest.mock import MagicMock++from tui_gateway.server import _finalize_session+++def _make_session(agent, session_key="test_key_bg_review"):+ return {+ "agent": agent,+ "history": [],+ "history_lock": threading.Lock(),+ "session_key": session_key,+ "_finalized": False,+ }+++def _agent_with_live_review_fork():+ """A parent agent with a background-review fork that is still running.++ Mirrors the real shape installed by ``agent/agent_init.py`` and+ populated by ``agent/background_review.py``'s+ ``_run_review_in_thread`` while a review is in flight.+ """+ agent = MagicMock()+ agent._persist_session = MagicMock()+ agent.commit_memory_session = MagicMock()+ agent.session_id = "parent-session"+ agent.model = "test-model"+ agent.platform = "desktop"+ agent._session_messages = None++ review_fork = MagicMock()+ # hard_interrupt is looked up via inspect.getattr_static in+ # agent.interrupt_compat.request_hard_interrupt — a real callable+ # attribute (not an auto-speccing MagicMock surprise) is required.+ review_fork.hard_interrupt = MagicMock()++ lock = threading.Lock()+ agent._background_review_lock = lock+ agent._background_review_agent = review_fork+ agent._background_review_run = None # legacy-pointer path+ agent._active_children = [review_fork]+ agent._active_children_lock = threading.Lock()++ return agent, review_fork+++class TestFinalizeSessionCancelsBackgroundReview:+ def test_finalize_interrupts_live_review_fork(self):+ """_finalize_session must hard-interrupt a running review fork."""+ agent, review_fork = _agent_with_live_review_fork()+ session = _make_session(agent)++ _finalize_session(session, end_reason="tui_close")++ # cancel_background_review_for_live_turn dispatches the actual+ # interrupt() call on a short-lived daemon thread (#84423) so a+ # wedged abort hook cannot stall the caller — wait for it instead+ # of asserting synchronously.+ for _ in range(50):+ if review_fork.hard_interrupt.called:+ break+ threading.Event().wait(0.05)++ assert review_fork.hard_interrupt.called, (+ "session finalize must interrupt the in-flight background "+ "review fork (#102895): the failed-tool retry loop would "+ "otherwise keep calling the model after the session is gone"+ )+ _, kwargs = review_fork.hard_interrupt.call_args+ # tool_reason must describe session teardown, not the unrelated+ # (and here false) "superseded by a new live turn" default wording.+ assert kwargs.get("tool_reason") == "session ended"++ def test_finalize_reports_the_real_end_reason(self):+ """The interrupt message names the actual end_reason, not the+ generic live-turn-preemption wording, so logs/diagnostics are+ truthful about why the review stopped."""+ agent, review_fork = _agent_with_live_review_fork()+ session = _make_session(agent)++ _finalize_session(session, end_reason="idle_timeout")++ for _ in range(50):+ if review_fork.hard_interrupt.called:+ break+ threading.Event().wait(0.05)++ assert review_fork.hard_interrupt.called+ args, _kwargs = review_fork.hard_interrupt.call_args+ assert args and "idle_timeout" in args[0]++ def test_finalize_without_a_review_fork_is_a_no_op(self):+ """No live review → cancellation path must not raise or interfere+ with the ordinary finalize flow (most sessions have no review+ running at teardown time)."""+ agent = MagicMock()+ agent._persist_session = MagicMock()+ agent.commit_memory_session = MagicMock()+ agent.session_id = "parent-session-2"+ agent.model = "test-model"+ agent.platform = "desktop"+ agent._session_messages = None+ agent._background_review_lock = threading.Lock()+ agent._background_review_agent = None+ agent._background_review_run = None+ agent._active_children = []+ agent._active_children_lock = threading.Lock()++ session = _make_session(agent, session_key="no-review-session")++ # Must not raise.+ _finalize_session(session, end_reason="tui_close")++ agent.commit_memory_session.assert_not_called() # empty history++ def test_finalize_tolerates_agent_missing_review_attributes(self):+ """A minimal/legacy agent object with no background-review+ attributes at all must not break finalize (defensive getattr)."""++ class BareAgent:+ session_id = "bare-agent-session"+ model = "test-model"+ platform = "tui"+ _session_messages = None++ session = _make_session(BareAgent(), session_key="bare-agent")++ # Must not raise despite BareAgent having no+ # _background_review_agent/_background_review_lock attributes.+ _finalize_session(session, end_reason="tui_close")diff --git a/tests/tui_gateway/test_session_interrupt_cancels_background_review.py b/tests/tui_gateway/test_session_interrupt_cancels_background_review.pynew file mode 100644index 00000000000..563a1baba43--- /dev/null+++ b/tests/tui_gateway/test_session_interrupt_cancels_background_review.py@@ -0,0 +1,134 @@+"""Regression for #102895 (sibling path): an explicit /stop must also+cancel a running background memory/skill review, not only the foreground+turn.++``_interrupt_session_turn`` (backing the ``session.interrupt`` RPC and the+WS-orphan reaper's interrupt-at-grace) gates its+``request_hard_interrupt(session.get("agent"))`` call on+``should_interrupt = bool(session.get("running"))``. The background-review+fork is a SEPARATE ``AIAgent`` (tracked only on the parent's+``_background_review_agent`` / ``_active_children`` —+``agent/background_review.py``) that is never reflected in+``session["running"]``. The common real-world shape is: the foreground turn+already finished (``running`` is ``False``), the post-turn review is still+running, and the user hits Stop expecting everything to stop — but the+`running`-gated branch never fires, so nothing ever interrupts the review.++See ``tests/tui_gateway/test_finalize_session_cancels_background_review.py``+for the session-teardown (delete/close/reap) counterpart of this same root+cause.+"""++from __future__ import annotations++import threading+from unittest.mock import MagicMock++import pytest+++def server():+ from unittest.mock import patch+ import importlib++ with patch.dict(+ "sys.modules",+ {+ "hermes_constants": MagicMock(get_hermes_home=MagicMock(return_value="/tmp/hermes_test")),+ "hermes_cli.env_loader": MagicMock(),+ "hermes_cli.banner": MagicMock(),+ "hermes_state": MagicMock(),+ },+ ):+ mod = importlib.import_module("tui_gateway.server")+ yield mod+++def _session_with_finished_turn_and_live_review(review_fork):+ """A session whose foreground turn already ended but whose background+ review is still running — the exact shape from the #102895 log+ (finish_reason=stop at 20:03:09, review starts same timestamp)."""+ agent = MagicMock()+ agent._background_review_lock = threading.Lock()+ agent._background_review_agent = review_fork+ agent._background_review_run = None+ agent._active_children = [review_fork]+ agent._active_children_lock = threading.Lock()++ return {+ "agent": agent,+ "history_lock": threading.Lock(),+ "running": False, # foreground turn already finished+ "queued_prompt": None,+ "session_key": "session-key-review-only",+ "_run_thread": None,+ }+++def test_stop_interrupts_a_review_running_after_the_turn_finished(server, monkeypatch):+ """/stop with running=False must still reach a live background review."""+ review_fork = MagicMock()+ review_fork.hard_interrupt = MagicMock()+ session = _session_with_finished_turn_and_live_review(review_fork)++ monkeypatch.setattr(server, "_tts_stream_stop", lambda: None)+ monkeypatch.setattr(server, "_sess_nowait", lambda _params, _rid: (session, None))+ monkeypatch.setattr(server, "_sess", lambda _params, _rid: (session, None))+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda _session: False)+ monkeypatch.setattr(server, "_clear_pending", lambda _sid: None)++ response = server._methods["session.interrupt"](+ "stop", {"session_id": "ui-session"}+ )++ assert response["result"]["status"] == "interrupted"++ for _ in range(50):+ if review_fork.hard_interrupt.called:+ break+ threading.Event().wait(0.05)++ assert review_fork.hard_interrupt.called, (+ "session.interrupt with running=False must still cancel a live "+ "background review fork (#102895 sibling path) — otherwise a "+ "user who hits Stop believing everything stopped is left with a "+ "review silently retrying against the model forever"+ )+ _, kwargs = review_fork.hard_interrupt.call_args+ assert kwargs.get("tool_reason") == "session interrupted"+++def test_stop_without_a_review_is_unaffected(server, monkeypatch):+ """No live review → the new cancellation path is a no-op; the ordinary+ interrupt contract (status, hard_interrupt on the foreground agent)+ must be unchanged."""+ agent = MagicMock()+ agent._background_review_lock = threading.Lock()+ agent._background_review_agent = None+ agent._background_review_run = None+ agent._active_children = []+ agent._active_children_lock = threading.Lock()+ agent.hard_interrupt = MagicMock()++ session = {+ "agent": agent,+ "history_lock": threading.Lock(),+ "running": True,+ "queued_prompt": None,+ "session_key": "session-key-normal-stop",+ "_run_thread": None,+ }++ monkeypatch.setattr(server, "_tts_stream_stop", lambda: None)+ monkeypatch.setattr(server, "_sess_nowait", lambda _params, _rid: (session, None))+ monkeypatch.setattr(server, "_sess", lambda _params, _rid: (session, None))+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda _session: False)+ monkeypatch.setattr(server, "_clear_pending", lambda _sid: None)++ response = server._methods["session.interrupt"](+ "stop", {"session_id": "ui-session"}+ )++ assert response["result"]["status"] == "interrupted"+ assert agent.hard_interrupt.calleddiff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.pyindex 473a3b62303..d124ed258a6 100644--- a/tui_gateway/session_lifecycle.py+++ b/tui_gateway/session_lifecycle.py@@ -441,6 +441,20 @@ def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> Nowith contextlib.suppress(Exception):from tools.approval import clear_sessionclear_session(str(session_key))+ # A session's in-flight background memory/skill review ends WITH the session too (#102895): the+ # review fork is a SEPARATE AIAgent instance tracked only on the parent's+ # _background_review_agent/_active_children (agent/background_review.py) — never on+ # session["running"] or session["_run_thread"] — so it is invisible both to the run_thread join+ # in _teardown_popped_session and to session.interrupt's running-gated request_hard_interrupt in+ # _interrupt_session_turn. Every finalize path (explicit close, idle-timeout reap, ws-orphan+ # reap, shutdown) funnels through here, so cancelling here closes the gap for all of them at+ # once. Without it, a review whose provider degraded into a failed-tool retry loop keeps calling+ # the model forever after the session is gone: nothing ever sets its _interrupt_requested.+ if agent is not None:+ with contextlib.suppress(Exception):+ from agent.background_review import cancel_background_review_for_live_turn+ cancel_background_review_for_live_turn(+ agent, message=f"session ended ({end_reason})", tool_reason="session ended")# Close the slash-worker in this single ``_finalized``-guarded chokepoint (a direct caller can't leak it); idempotent.with contextlib.suppress(Exception):if worker := session.get("slash_worker"):@@ -726,6 +740,18 @@ def _interrupt_session_turn(if session.get("running"):session["running"] = False_clear_inflight_turn(session)+ # Sibling of the #102895 finalize-path fix above: an explicit /stop (or the WS-orphan reaper's+ # interrupt-at-grace) must also reach a background memory/skill review, not just the foreground+ # turn. The review fork is invisible to `should_interrupt`/`run_thread_alive` above (both gated+ # on the FOREGROUND turn's session["running"]/_run_thread) — a user hitting Stop while only the+ # post-turn review is still running (the common case: the main turn already finished) would see+ # "stopped" while the review keeps calling the model. Fires unconditionally (both compute-host+ # and in-process turns) since the review is always local to this process.+ if (agent_for_review := session.get("agent")) is not None:+ with contextlib.suppress(Exception):+ from agent.background_review import cancel_background_review_for_live_turn+ cancel_background_review_for_live_turn(+ agent_for_review, message="session interrupted", tool_reason="session interrupted")_clear_pending(sid)with contextlib.suppress(Exception):# Deny-resolve every pending approval so no agent thread blocks on the queue. The