Skip to content

The agent that grows with you

fix(agent): synchronize background review cancellation

qixuancao37da0d4d50fe
diff --git a/agent/agent_init.py b/agent/agent_init.py
index ca5996636bd..88985abbdc4 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -909,14 +909,12 @@ def init_agent(
agent._active_children = [] # Running child AIAgents (for interrupt propagation)
agent._active_children_lock = threading.Lock()
- # Background memory/skill review state (agent/background_review.py). Holds
- # the forked review AIAgent while its run_conversation() is in flight, so
- # the NEXT live turn can proactively interrupt a still-running review
- # instead of letting the two race concurrently against the same
- # session_id/credentials (observed as doubled prompt-token counts and a
- # Ctrl+C-proof lockup when a live turn started before a review fired at
- # the end of the prior turn had finished).
+ # Background memory/skill review state (agent/background_review.py).
+ # ``_background_review_run`` is installed before the worker starts and
+ # fences its first provider-capable phase; the direct agent pointer keeps
+ # normal interrupt propagation available once the fork is constructed.
agent._background_review_agent = None
+ agent._background_review_run = None
agent._background_review_lock = threading.Lock()
# Store OpenRouter provider preferences
diff --git a/agent/background_review.py b/agent/background_review.py
index ae12a059d8e..d643b95e128 100644
--- a/agent/background_review.py
+++ b/agent/background_review.py
@@ -23,6 +23,7 @@ import json
import logging
import os
from pathlib import Path
+import threading
from typing import Any, Dict, List, Optional
from agent.thread_scoped_output import thread_scoped_silence
@@ -30,6 +31,156 @@ from agent.thread_scoped_output import thread_scoped_silence
logger = logging.getLogger(__name__)
+_BACKGROUND_REVIEW_CANCEL_TIMEOUT_SECONDS = 2.0
+
+
+class _BackgroundReviewRun:
+ """Per-review cancellation and request-completion handshake."""
+
+ def __init__(self) -> None:
+ self.cancel_requested = threading.Event()
+ self.request_done = threading.Event()
+ self._lock = threading.Lock()
+ self._review_agent = None
+ self._request_started = False
+ self._request_finished = False
+ self._cancel_dispatched = False
+
+ def begin_request(self, review_agent: Any) -> bool:
+ """Atomically admit the first provider-capable review phase."""
+ with self._lock:
+ self._review_agent = review_agent
+ if self.cancel_requested.is_set() or self._request_finished:
+ return False
+ self._request_started = True
+ return True
+
+ def cancel(self) -> Any:
+ """Fence startup and return the running fork, if one was admitted."""
+ with self._lock:
+ self.cancel_requested.set()
+ if (
+ self._request_started
+ and not self._request_finished
+ and not self._cancel_dispatched
+ ):
+ self._cancel_dispatched = True
+ return self._review_agent
+ return None
+
+ def mark_request_finished(self) -> bool:
+ """Latch request completion once; the caller publishes the event."""
+ with self._lock:
+ if self._request_finished:
+ return False
+ self._request_finished = True
+ self._request_started = False
+ self._review_agent = None
+ return True
+
+
+def prepare_background_review_run(agent: Any) -> Optional[_BackgroundReviewRun]:
+ """Install a unique run token on the parent before ``Thread.start()``."""
+ lock = getattr(agent, "_background_review_lock", None)
+ if lock is None:
+ try:
+ lock = threading.Lock()
+ agent._background_review_lock = lock
+ except (AttributeError, TypeError):
+ return None
+
+ run = _BackgroundReviewRun()
+ try:
+ with lock:
+ current = getattr(agent, "_background_review_run", None)
+ if current is not None and not current.request_done.is_set():
+ return None
+ agent._background_review_run = run
+ except (AttributeError, TypeError):
+ return None
+ return run
+
+
+def finish_background_review_run(
+ agent: Any,
+ run: Optional[_BackgroundReviewRun],
+) -> None:
+ """Publish one run's request exit without clearing a successor (ABA-safe)."""
+ if run is None or not run.mark_request_finished():
+ return
+
+ lock = getattr(agent, "_background_review_lock", None)
+ if lock is not None:
+ with lock:
+ if getattr(agent, "_background_review_run", None) is run:
+ agent._background_review_run = None
+ elif getattr(agent, "_background_review_run", None) is run:
+ agent._background_review_run = None
+ run.request_done.set()
+
+
+def _interrupt_background_review(review_agent: Any) -> None:
+ """Request abort off-thread so a broken abort hook cannot stall foreground."""
+
+ def _interrupt() -> None:
+ try:
+ review_agent.interrupt("superseded by a new live turn")
+ except Exception:
+ logger.debug(
+ "Failed to cancel in-flight background review for a new turn",
+ exc_info=True,
+ )
+
+ try:
+ threading.Thread(
+ target=_interrupt,
+ daemon=True,
+ name="bg-review-cancel",
+ ).start()
+ except Exception:
+ logger.debug(
+ "Failed to start background-review cancellation thread",
+ exc_info=True,
+ )
+
+
+def cancel_background_review_for_live_turn(agent: Any) -> bool:
+ """Cancel the current review and await its request-phase acknowledgement.
+
+ Returns ``False`` when acknowledgement is unavailable or misses the bounded
+ deadline. Callers must then stop before same-session turn-context work.
+ """
+ lock = getattr(agent, "_background_review_lock", None)
+ if lock is not None:
+ with lock:
+ run = getattr(agent, "_background_review_run", None)
+ legacy_agent = getattr(agent, "_background_review_agent", None)
+ else:
+ run = getattr(agent, "_background_review_run", None)
+ legacy_agent = getattr(agent, "_background_review_agent", None)
+
+ if run is None:
+ if legacy_agent is None:
+ return True
+ _interrupt_background_review(legacy_agent)
+ return False
+
+ review_agent = run.cancel()
+ if review_agent is not None:
+ _interrupt_background_review(review_agent)
+
+ acknowledged = run.request_done.wait(
+ timeout=_BACKGROUND_REVIEW_CANCEL_TIMEOUT_SECONDS
+ )
+ if not acknowledged:
+ logger.error(
+ "Background review did not acknowledge cancellation within %.1fs; "
+ "refusing to start overlapping live turn",
+ _BACKGROUND_REVIEW_CANCEL_TIMEOUT_SECONDS,
+ )
+ return acknowledged
+
+
# ---------------------------------------------------------------------------
# Background-review aux-model selector + routed digest.
#
@@ -862,13 +1013,23 @@ def _run_review_in_thread(
messages_snapshot: List[Dict],
prompt: str,
task_cfg: Optional[Dict[str, Any]] = None,
+ review_run: Optional[_BackgroundReviewRun] = None,
) -> None:
"""Worker function executed in the background-review daemon thread.
Spawns a forked ``AIAgent`` inheriting the parent's runtime, runs the
review prompt, and surfaces a compact action summary back to the user
via ``agent._safe_print`` and ``agent.background_review_callback``.
+
+ ``review_run`` is the per-review cancellation token from
+ :func:`prepare_background_review_run`. If a live turn bumps the
+ cancel generation before this review reaches its first provider call,
+ the review aborts without entering ``run_conversation()`` (#84423).
"""
+ if review_run is not None and review_run.cancel_requested.is_set():
+ finish_background_review_run(agent, review_run)
+ return
+
# Local import to avoid a hard circular dep at module load.
from run_agent import AIAgent
from tools.terminal_tool import set_approval_callback as _set_approval_callback
@@ -918,6 +1079,10 @@ def _run_review_in_thread(
except (ValueError, AttributeError):
pass
+ def _finish_request_phase(agent_ref) -> None:
+ _unregister_review_agent(agent_ref)
+ finish_background_review_run(agent, review_run)
+
try:
# Silence stdout/stderr for THIS worker thread only. A process-global
# ``contextlib.redirect_stdout(devnull)`` here would also blank
@@ -1117,12 +1282,10 @@ def _run_review_in_thread(
# Register this fork on the PARENT's _active_children (the same
# list interrupt() fans out to for subagent delegation) and
# _background_review_agent (a direct pointer the next live turn
- # uses to proactively cancel a still-running review). Without
- # this, a review still streaming when the next turn starts races
- # the live turn against the same session_id/credentials — producing
- # doubled prompt-token accounting and a Ctrl+C-proof lockup.
- # Best-effort: agents built without agent_init.py (test stubs)
- # degrade to "no cross-cancellation" rather than aborting the review.
+ # uses to interrupt an admitted request). The per-review run token
+ # separately fences startup and acknowledges request-phase exit.
+ # The legacy pointer/list remain best-effort for direct test stubs;
+ # a prepared run token is the live-turn cancellation authority.
if hasattr(agent, "_background_review_agent"):
_br_lock = getattr(agent, "_background_review_lock", None)
if _br_lock is not None:
@@ -1173,22 +1336,26 @@ def _run_review_in_thread(
pass
try:
- # Routed to a different model -> replay a digest (cache is cold
- # on that model anyway, so minimise cold-written tokens). Same
- # model -> replay the full snapshot (warm cache reads).
- _review_history = (
- _digest_history(messages_snapshot) if _routed
- else messages_snapshot
- )
- review_agent.run_conversation(
- user_message=(
- prompt
- + "\n\nYou can only call memory and skill "
- "management tools. Other tools will be denied "
- "at runtime — do not attempt them."
- ),
- conversation_history=_review_history,
+ request_admitted = (
+ review_run is None or review_run.begin_request(review_agent)
)
+ if request_admitted:
+ # Routed to a different model -> replay a digest (cache is cold
+ # on that model anyway, so minimise cold-written tokens). Same
+ # model -> replay the full snapshot (warm cache reads).
+ _review_history = (
+ _digest_history(messages_snapshot) if _routed
+ else messages_snapshot
+ )
+ review_agent.run_conversation(
+ user_message=(
+ prompt
+ + "\n\nYou can only call memory and skill "
+ "management tools. Other tools will be denied "
+ "at runtime — do not attempt them."
+ ),
+ conversation_history=_review_history,
+ )
finally:
clear_thread_tool_whitelist()
# Attribute the review fork's usage to the PARENT session.
@@ -1199,12 +1366,9 @@ def _run_review_in_thread(
if review_agent is not None:
review_usage.update(_snapshot_review_usage(review_agent))
_record_review_usage_to_parent(agent, review_usage)
- # Unregister as soon as run_conversation() itself has
- # returned — that's the only phase making outbound API
- # calls, i.e. the only phase that can race the parent's
- # next live turn. Runs on both the success and exception
- # path (this whole block is inside the try/finally above).
- _unregister_review_agent(review_agent)
+ # Publish completion as soon as the provider-capable phase has
+ # returned or startup cancellation has fenced it out.
+ _finish_request_phase(review_agent)
# Snapshot review actions before teardown. close() is allowed to
# clean per-session state, but the user-visible self-improvement
@@ -1284,13 +1448,10 @@ def _run_review_in_thread(
# thread-scoped silence here so teardown output (Honcho flush, Hindsight
# sync, background thread joins) stays quiet even on the exception path,
# without blanking other threads' streams.
- # Also a safety-net unregister: covers exceptions raised during setup
- # (between registration and the run_conversation try/finally above)
- # that the primary _unregister_review_agent call site never reaches.
- # _unregister_review_agent is idempotent (checks `is`/`in` membership),
- # so calling it again here after the primary call site already ran is
- # a harmless no-op.
- _unregister_review_agent(review_agent)
+ # Also a safety-net completion: covers exceptions raised during setup
+ # before the request-phase finally. Both tracking cleanup and the
+ # per-run completion publication are identity-scoped and idempotent.
+ _finish_request_phase(review_agent)
if review_agent is not None:
try:
with thread_scoped_silence():
@@ -1319,6 +1480,7 @@ def spawn_background_review_thread(
review_skills: bool = False,
focus: Optional[str] = None,
task_cfg: Optional[Dict[str, Any]] = None,
+ review_run: Optional[_BackgroundReviewRun] = None,
):
"""Build the review thread target and prompt for a background review.
@@ -1359,7 +1521,13 @@ def spawn_background_review_thread(
)
def _target() -> None:
- _run_review_in_thread(agent, messages_snapshot, prompt, task_cfg)
+ _run_review_in_thread(
+ agent,
+ messages_snapshot,
+ prompt,
+ task_cfg=task_cfg,
+ review_run=review_run,
+ )
return _target, prompt
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index 951b8747010..3d7f07ef39e 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -1820,31 +1820,6 @@ def run_conversation(
agent._last_compression_attempt_recorded = False
agent._last_compression_attempt_in_place = None
- # If a background memory/skill review spawned at the end of a PRIOR turn
- # (agent/background_review.py) is still running its own run_conversation()
- # when THIS turn starts, cancel it now rather than letting both make
- # outbound API calls concurrently against the same session_id/credentials.
- # That concurrency can produce doubled prompt-token accounting on this
- # turn's own calls and, because the review fork is a fully separate
- # AIAgent with no route back to THIS agent's interrupt() by default, a
- # lockup that survives a normal /stop and needs a hard Ctrl+C.
- # ``review_agent.interrupt()`` is fire-and-forget here — it just flags
- # cancellation and aborts the review's in-flight socket; it does not
- # block waiting for the review's daemon thread to exit, so it can't add
- # latency to this turn. Only ever set on the real owning agent (the
- # review fork's own copy of this attribute stays None — reviews don't
- # spawn nested reviews), so this is a no-op on every other run_conversation
- # caller (subagents, the review fork itself, etc).
- _pending_review = getattr(agent, "_background_review_agent", None)
- if _pending_review is not None:
- try:
- _pending_review.interrupt("superseded by a new live turn")
- except Exception:
- logger.debug(
- "Failed to cancel in-flight background review for a new turn",
- exc_info=True,
- )
-
# Adopt any ~/.hermes/.env credential/base-url edits made since the last
# turn — a Settings save updates .env but not this worker's client, which
# was built at agent init (#67821). No-op when .env is unchanged.
diff --git a/run_agent.py b/run_agent.py
index f5c4de1274c..107c0f33ab7 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -1896,22 +1896,37 @@ class AIAgent:
enabled, task_cfg = load_background_review_settings()
if not enabled:
return
- from agent.background_review import spawn_background_review_thread
- from tools.thread_context import propagate_context_to_thread
- target, _prompt = spawn_background_review_thread(
- self,
- messages_snapshot,
- review_memory=review_memory,
- review_skills=review_skills,
- focus=focus,
- task_cfg=task_cfg,
+ from agent.background_review import (
+ finish_background_review_run,
+ prepare_background_review_run,
+ spawn_background_review_thread,
)
- # Carry the active profile into the review thread so MEMORY.md / skill
- # review writes land in the right profile (#54937).
- t = threading.Thread(
- target=propagate_context_to_thread(target), daemon=True, name="bg-review"
- )
- t.start()
+ from tools.thread_context import propagate_context_to_thread
+
+ review_run = prepare_background_review_run(self)
+ if review_run is None:
+ return
+ try:
+ target, _prompt = spawn_background_review_thread(
+ self,
+ messages_snapshot,
+ review_memory=review_memory,
+ review_skills=review_skills,
+ focus=focus,
+ task_cfg=task_cfg,
+ review_run=review_run,
+ )
+ # Carry the active profile into the review thread so MEMORY.md /
+ # skill review writes land in the right profile (#54937).
+ t = threading.Thread(
+ target=propagate_context_to_thread(target),
+ daemon=True,
+ name="bg-review",
+ )
+ t.start()
+ except Exception:
+ finish_background_review_run(self, review_run)
+ raise
def _build_memory_write_metadata(
self,
@@ -8478,6 +8493,32 @@ class AIAgent:
moa_config: Optional[dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Forwarder — see ``agent.conversation_loop.run_conversation``."""
+ # A review deliberately shares this agent's session_id for prompt-cache
+ # parity. Fence review startup or interrupt an admitted request, then
+ # await that request's exit before opening any live-turn Relay or task
+ # instrumentation for the same session.
+ from agent.background_review import cancel_background_review_for_live_turn
+
+ if not cancel_background_review_for_live_turn(self):
+ failure = (
+ "Live turn not started: the prior background review did not "
+ "acknowledge cancellation before the bounded safety deadline. "
+ "Retry after the review has stopped."
+ )
+ existing_messages = conversation_history
+ if existing_messages is None:
+ existing_messages = getattr(self, "_session_messages", None)
+ return {
+ "final_response": failure,
+ "messages": list(existing_messages or []),
+ "completed": False,
+ "api_calls": 0,
+ "error": failure,
+ "failed": True,
+ "retryable": True,
+ "background_review_cancellation_timeout": True,
+ }
+
from agent.aux_accounting import (
reset_accounting_context,
set_accounting_context,
diff --git a/tests/run_agent/test_background_review.py b/tests/run_agent/test_background_review.py
index 84f11a5c284..19aa95f395b 100644
--- a/tests/run_agent/test_background_review.py
+++ b/tests/run_agent/test_background_review.py
@@ -2,10 +2,67 @@
from __future__ import annotations
+import threading
+
import run_agent as run_agent_module
from run_agent import AIAgent
+_REAL_THREAD = threading.Thread
+
+
+class _TurnBoundaryReached(Exception):
+ """Stop a live turn exactly when it reaches turn-context construction."""
+
+
+class CapturingThread:
+ targets = []
+
+ def __init__(self, *, target, daemon=None, name=None):
+ self._target = target
+ self.targets.append(target)
+
+ def start(self):
+ pass
+
+
+class ObservedEvent:
+ """A real Event that also exposes when a waiter starts waiting."""
+
+ def __init__(self):
+ self._event = threading.Event()
+ self.wait_started = threading.Event()
+ self.set_calls = 0
+
+ def set(self):
+ self.set_calls += 1
+ self._event.set()
+
+ def wait(self, timeout=None):
+ self.wait_started.set()
+ return self._event.wait(timeout)
+
+ def is_set(self):
+ return self._event.is_set()
+
+
+class FakeReviewAgent:
+ def __init__(self, **kwargs):
+ self._session_messages = []
+
+ def run_conversation(self, **kwargs):
+ pass
+
+ def interrupt(self, message=None):
+ pass
+
+ def shutdown_memory_provider(self):
+ pass
+
+ def close(self):
+ pass
+
+
def _bare_agent() -> AIAgent:
agent = object.__new__(AIAgent)
agent.model = "fake-model"
@@ -31,6 +88,7 @@ def _bare_agent() -> AIAgent:
agent._safe_print = lambda *_args, **_kwargs: None
import threading as _threading
agent._background_review_agent = None
+ agent._background_review_run = None
agent._background_review_lock = _threading.Lock()
agent._active_children = []
agent._active_children_lock = _threading.Lock()
@@ -45,6 +103,89 @@ class ImmediateThread:
self._target()
+def _install_live_turn_boundary(monkeypatch, on_boundary=None):
+ import agent.conversation_loop as conversation_loop_module
+
+ def stop_at_boundary(*args, **kwargs):
+ if on_boundary is not None:
+ on_boundary()
+ raise _TurnBoundaryReached
+
+ monkeypatch.setattr(
+ conversation_loop_module,
+ "build_turn_context",
+ stop_at_boundary,
+ )
+
+
+def _run_wrapped_live_turn_to_boundary(agent, result):
+ try:
+ result["return"] = AIAgent.run_conversation(
+ agent,
+ "next turn",
+ task_id="live-task",
+ )
+ except _TurnBoundaryReached:
+ result["boundary_reached"] = True
+ except BaseException as exc: # surfaced in the test thread for a useful failure
+ result["error"] = exc
+
+
+def _install_relay_recorder(monkeypatch, review_run=None):
+ from agent import relay_runtime
+ from hermes_cli.observability import relay_shared_metrics
+
+ calls = []
+
+ def review_acknowledged():
+ return bool(review_run and review_run.request_done.is_set())
+
+ class RelayTurn:
+ relay_enabled = True
+
+ class RecordingCoordinator:
+ def acquire_conversation(self, **kwargs):
+ calls.append(("acquire", review_acknowledged()))
+ return object()
+
+ def begin_turn(self, lease, **kwargs):
+ calls.append(("begin", review_acknowledged()))
+ return RelayTurn()
+
+ def finish_logical_calls(self, turn, **kwargs):
+ pass
+
+ def end_turn(self, turn, **kwargs):
+ pass
+
+ def release_conversation(self, lease):
+ pass
+
+ monkeypatch.setattr(
+ relay_runtime,
+ "SESSION_COORDINATOR",
+ RecordingCoordinator(),
+ )
+ monkeypatch.setattr(
+ relay_runtime,
+ "current_profile_key",
+ lambda: "/test-profile",
+ )
+ monkeypatch.setattr(
+ relay_shared_metrics,
+ "start_task_run",
+ lambda **kwargs: calls.append(
+ ("start_task_run", review_acknowledged())
+ ),
+ )
+ monkeypatch.setattr(
+ relay_shared_metrics,
+ "finish_task_run",
+ lambda **kwargs: None,
+ )
+ return calls
+
+
def test_background_review_shuts_down_memory_provider_before_close(monkeypatch):
events = []
@@ -277,34 +418,19 @@ def test_background_review_explicit_focus_runs_even_in_subagent(monkeypatch):
assert len(forks) == 1, "explicit focus review must run even in a subagent"
-def test_background_review_registers_on_active_children_for_interrupt(monkeypatch):
- """The review fork must be added to the parent's ``_active_children`` so
- ``AIAgent.interrupt()`` (which fans out to that list) can reach it, and
- to ``_background_review_agent`` so the NEXT live turn can proactively
- cancel a still-running review. Regression for the doubled-token-
- accounting / Ctrl+C-proof lockup that a review racing a new live turn
- against the same session_id/credentials can cause.
- """
+def test_background_review_registers_before_start_runs_and_cleans_up(monkeypatch):
+ """The parent must own a unique review run before the worker can start."""
seen = {}
- class FakeReviewAgent:
- def __init__(self, **kwargs):
- self._session_messages = []
-
+ class RecordingReviewAgent(FakeReviewAgent):
def run_conversation(self, **kwargs):
- # While run_conversation is "in flight", both tracking slots on
- # the parent must already point at this fork.
+ seen["run"] = agent._background_review_run
seen["active_children_during_run"] = list(agent._active_children)
seen["background_review_agent_during_run"] = agent._background_review_agent
- def shutdown_memory_provider(self):
- pass
-
- def close(self):
- pass
-
- monkeypatch.setattr(run_agent_module, "AIAgent", FakeReviewAgent)
- monkeypatch.setattr(run_agent_module.threading, "Thread", ImmediateThread)
+ monkeypatch.setattr(run_agent_module, "AIAgent", RecordingReviewAgent)
+ CapturingThread.targets = []
+ monkeypatch.setattr(run_agent_module.threading, "Thread", CapturingThread)
agent = _bare_agent()
@@ -314,53 +440,315 @@ def test_background_review_registers_on_active_children_for_interrupt(monkeypatc
review_memory=True,
)
+ run = agent._background_review_run
+ assert run is not None
+ assert len(CapturingThread.targets) == 1
+ assert not run.request_done.is_set()
+
+ observed_done = ObservedEvent()
+ run.request_done = observed_done
+ CapturingThread.targets[0]()
+
fork = seen["background_review_agent_during_run"]
assert fork is not None
+ assert seen["run"] is run
assert seen["active_children_during_run"] == [fork]
-
- # After the review completes, both tracking slots must be cleared —
- # otherwise a later interrupt() would try to cancel an already-closed
- # agent, or the next turn would wait on a review that no longer exists.
+ assert observed_done.is_set()
+ assert observed_done.set_calls == 1
+ assert agent._background_review_run is None
assert agent._background_review_agent is None
assert agent._active_children == []
-def test_new_live_turn_cancels_still_running_background_review(monkeypatch):
- """conversation_loop.run_conversation() must proactively interrupt a
- background review still in flight from a prior turn, rather than let the
- two race concurrently against the same session_id/credentials. This is
- the other half of the fix: registration alone only enables interrupt()
- propagation, it doesn't by itself stop the race — something has to
- actually call interrupt() at the start of the next turn.
- """
- import agent.conversation_loop as conversation_loop_module
+def test_live_turn_waits_for_review_exit_before_relay_and_turn_context(monkeypatch):
+ """The outer production wrapper waits before same-session instrumentation."""
+ review_entered = threading.Event()
+ review_returned = threading.Event()
+ allow_review_return = threading.Event()
+ interrupted = threading.Event()
+ boundary_reached = threading.Event()
+ seen = {}
- calls = []
+ class BlockingReviewAgent(FakeReviewAgent):
+ def interrupt(self, message=None):
+ seen["interrupt_message"] = message
+ interrupted.set()
- class FakeReviewAgent:
+ def run_conversation(self, **kwargs):
+ review_entered.set()
+ assert allow_review_return.wait(2.0)
+ review_returned.set()
+
+ monkeypatch.setattr(run_agent_module, "AIAgent", BlockingReviewAgent)
+ CapturingThread.targets = []
+ monkeypatch.setattr(run_agent_module.threading, "Thread", CapturingThread)
+
+ agent = _bare_agent()
+ AIAgent._spawn_background_review(
+ agent,
+ messages_snapshot=[{"role": "user", "content": "hello"}],
+ review_memory=True,
+ )
+ run = agent._background_review_run
+ assert run is not None
+ observed_done = ObservedEvent()
+ run.request_done = observed_done
+
+ monkeypatch.setattr(run_agent_module.threading, "Thread", _REAL_THREAD)
+ worker = _REAL_THREAD(target=CapturingThread.targets[0], daemon=True)
+ worker.start()
+ assert review_entered.wait(2.0)
+
+ def on_boundary():
+ seen["review_returned_at_boundary"] = review_returned.is_set()
+ boundary_reached.set()
+
+ _install_live_turn_boundary(monkeypatch, on_boundary)
+ relay_calls = _install_relay_recorder(monkeypatch, run)
+ live_result = {}
+ live = _REAL_THREAD(
+ target=_run_wrapped_live_turn_to_boundary,
+ args=(agent, live_result),
+ daemon=True,
+ )
+ live.start()
+
+ assert interrupted.wait(2.0)
+ wait_started = observed_done.wait_started.wait(2.0)
+ relay_calls_before_ack = list(relay_calls)
+ allow_review_return.set()
+ worker.join(timeout=2.0)
+ live.join(timeout=2.0)
+
+ assert not worker.is_alive()
+ assert not live.is_alive()
+ assert wait_started
+ assert relay_calls_before_ack == []
+ assert relay_calls == [
+ ("acquire", True),
+ ("begin", True),
+ ("start_task_run", True),
+ ]
+ assert boundary_reached.is_set()
+ assert seen["interrupt_message"] == "superseded by a new live turn"
+ assert seen["review_returned_at_boundary"] is True
+ assert live_result == {"boundary_reached": True}
+
+
+def test_live_turn_cancels_review_during_startup_before_provider(monkeypatch):
+ """A review cancelled before its worker runs must never call its provider."""
+ provider_calls = []
+ boundary_reached = threading.Event()
+
+ class RecordingReviewAgent(FakeReviewAgent):
+ def run_conversation(self, **kwargs):
+ provider_calls.append(kwargs)
+
+ monkeypatch.setattr(run_agent_module, "AIAgent", RecordingReviewAgent)
+ CapturingThread.targets = []
+ monkeypatch.setattr(run_agent_module.threading, "Thread", CapturingThread)
+
+ agent = _bare_agent()
+ AIAgent._spawn_background_review(
+ agent,
+ messages_snapshot=[{"role": "user", "content": "hello"}],
+ review_memory=True,
+ )
+ run = agent._background_review_run
+ assert run is not None
+
+ _install_live_turn_boundary(monkeypatch, boundary_reached.set)
+ relay_calls = _install_relay_recorder(monkeypatch, run)
+ live_result = {}
+ live = _REAL_THREAD(
+ target=_run_wrapped_live_turn_to_boundary,
+ args=(agent, live_result),
+ daemon=True,
+ )
+ live.start()
+ assert run.cancel_requested.wait(2.0)
+
+ worker = _REAL_THREAD(target=CapturingThread.targets[0], daemon=True)
+ worker.start()
+ worker.join(timeout=2.0)
+ live.join(timeout=2.0)
+
+ assert not worker.is_alive()
+ assert not live.is_alive()
+ assert boundary_reached.is_set()
+ assert provider_calls == []
+ assert run.request_done.is_set()
+ assert relay_calls == [
+ ("acquire", True),
+ ("begin", True),
+ ("start_task_run", True),
+ ]
+ assert live_result == {"boundary_reached": True}
+
+
+def test_live_turn_stops_safely_when_review_acknowledgement_times_out(monkeypatch):
+ """A broken review abort path must not create an unbounded foreground wait."""
+ import time
+
+ import agent.background_review as background_review_module
+
+ review_entered = threading.Event()
+ interrupt_entered = threading.Event()
+ interrupt_returned = threading.Event()
+ allow_interrupt_return = threading.Event()
+ allow_review_return = threading.Event()
+
+ class WedgedReviewAgent(FakeReviewAgent):
+ def run_conversation(self, **kwargs):
+ review_entered.set()
+ allow_review_return.wait(5.0)
+
+ def interrupt(self, message=None):
+ interrupt_entered.set()
+ allow_interrupt_return.wait(5.0)
+ interrupt_returned.set()
+
+ monkeypatch.setattr(run_agent_module, "AIAgent", WedgedReviewAgent)
+ CapturingThread.targets = []
+ monkeypatch.setattr(run_agent_module.threading, "Thread", CapturingThread)
+ monkeypatch.setattr(
+ background_review_module,
+ "_BACKGROUND_REVIEW_CANCEL_TIMEOUT_SECONDS",
+ 0.01,
+ raising=False,
+ )
+
+ agent = _bare_agent()
+ AIAgent._spawn_background_review(
+ agent,
+ messages_snapshot=[{"role": "user", "content": "hello"}],
+ review_memory=True,
+ )
+ run = agent._background_review_run
+ assert run is not None
+ monkeypatch.setattr(run_agent_module.threading, "Thread", _REAL_THREAD)
+ worker = _REAL_THREAD(target=CapturingThread.targets[0], daemon=True)
+ worker.start()
+ assert review_entered.wait(2.0)
+
+ boundary_calls = []
+ _install_live_turn_boundary(
+ monkeypatch, lambda: boundary_calls.append(True)
+ )
+ relay_calls = _install_relay_recorder(monkeypatch, run)
+
+ started = time.monotonic()
+ result = AIAgent.run_conversation(
+ agent,
+ "next turn",
+ task_id="live-task",
+ )
+ elapsed = time.monotonic() - started
+
+ allow_interrupt_return.set()
+ allow_review_return.set()
+ worker.join(timeout=2.0)
+
+ assert elapsed < 2.0
+ assert interrupt_entered.is_set()
+ assert interrupt_returned.wait(2.0)
+ assert not worker.is_alive()
+ assert relay_calls == []
+ assert boundary_calls == []
+ assert result is not None
+ assert result["completed"] is False
+ assert result["failed"] is True
+ assert result["background_review_cancellation_timeout"] is True
+ assert "not started" in result["final_response"].lower()
+
+
+def test_live_turn_fails_closed_for_untracked_legacy_review_stub(monkeypatch):
+ """Directly constructed agents without a handshake must not overlap turns."""
+ interrupts = []
+ interrupt_called = threading.Event()
+
+ class LegacyReviewAgent:
def interrupt(self, message=None):
- calls.append(message)
+ interrupts.append(message)
+ interrupt_called.set()
agent = _bare_agent()
- agent._background_review_agent = FakeReviewAgent()
+ del agent._background_review_run
+ agent._background_review_agent = LegacyReviewAgent()
+ boundary_calls = []
+ _install_live_turn_boundary(
+ monkeypatch, lambda: boundary_calls.append(True)
+ )
+ relay_calls = _install_relay_recorder(monkeypatch)
- # Invoke just the cancellation snippet in isolation via the same
- # attribute contract run_conversation() reads, to avoid dragging in the
- # rest of the turn machinery (network calls, tool setup, etc.) that
- # isn't relevant to this regression.
- _pending_review = getattr(agent, "_background_review_agent", None)
- assert _pending_review is not None
- _pending_review.interrupt("superseded by a new live turn")
+ result = AIAgent.run_conversation(
+ agent,
+ "next turn",
+ task_id="live-task",
+ )
- assert calls == ["superseded by a new live turn"]
+ assert interrupt_called.wait(2.0)
+ assert interrupts == ["superseded by a new live turn"]
+ assert relay_calls == []
+ assert boundary_calls == []
+ assert result["background_review_cancellation_timeout"] is True
+ assert result["failed"] is True
+def test_stale_review_cleanup_cannot_clear_or_signal_newer_review(monkeypatch):
+ """A retired worker's late cleanup must be scoped to its own run identity."""
+ first_cleanup_entered = threading.Event()
+ allow_first_cleanup = threading.Event()
+ instance_count = 0
+ class BlockingCleanupReviewAgent(FakeReviewAgent):
+ def __init__(self, **kwargs):
+ nonlocal instance_count
+ super().__init__(**kwargs)
+ self.index = instance_count
+ instance_count += 1
+ def shutdown_memory_provider(self):
+ if self.index == 0:
+ first_cleanup_entered.set()
+ assert allow_first_cleanup.wait(2.0)
+
+ monkeypatch.setattr(run_agent_module, "AIAgent", BlockingCleanupReviewAgent)
+ CapturingThread.targets = []
+ monkeypatch.setattr(run_agent_module.threading, "Thread", CapturingThread)
+ agent = _bare_agent()
+ AIAgent._spawn_background_review(
+ agent,
+ messages_snapshot=[{"role": "user", "content": "first"}],
+ review_memory=True,
+ )
+ first_run = agent._background_review_run
+ first_worker = _REAL_THREAD(target=CapturingThread.targets[0], daemon=True)
+ first_worker.start()
+ assert first_cleanup_entered.wait(2.0)
+ assert first_run.request_done.is_set()
+
+ AIAgent._spawn_background_review(
+ agent,
+ messages_snapshot=[{"role": "user", "content": "second"}],
+ review_memory=True,
+ )
+ second_run = agent._background_review_run
+ second_target = CapturingThread.targets[1]
+ assert second_run is not first_run
+ assert not second_run.request_done.is_set()
+ allow_first_cleanup.set()
+ first_worker.join(timeout=2.0)
+ assert not first_worker.is_alive()
+ assert agent._background_review_run is second_run
+ assert not second_run.request_done.is_set()
+ second_target()
+ assert second_run.request_done.is_set()
+ assert agent._background_review_run is None
# ---------------------------------------------------------------------------
# memory_notifications mode: off | on | verbose