From 5997a714f2f6bb4fd73f789213ebc093e2c04164 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:49:41 +0800 Subject: [PATCH] refactor(agent): centralize session execution ownership (#6699) --- nanobot/agent/automation_turns.py | 32 +- nanobot/agent/cron_turns.py | 18 +- nanobot/agent/loop.py | 129 ++++---- nanobot/agent/session_inbox.py | 106 +++++++ nanobot/command/builtin.py | 9 - nanobot/triggers/local_turns.py | 18 +- tests/agent/test_loop_recovery.py | 3 +- tests/agent/test_loop_session_policy.py | 6 +- tests/agent/test_runner_injections.py | 44 +-- tests/agent/test_session_inbox_controls.py | 279 +++++++++++++++++- tests/command/test_stop_pending_queue.py | 76 +---- tests/tools/test_exec_session_tools.py | 104 +++---- .../async-session-stop/CombinedLifecycle.tla | 77 +++++ verification/async-session-stop/README.md | 17 ++ .../async-session-stop/combined-baseline.cfg | 5 + .../async-session-stop/combined-final.cfg | 5 + 16 files changed, 642 insertions(+), 286 deletions(-) create mode 100644 nanobot/agent/session_inbox.py create mode 100644 verification/async-session-stop/CombinedLifecycle.tla create mode 100644 verification/async-session-stop/README.md create mode 100644 verification/async-session-stop/combined-baseline.cfg create mode 100644 verification/async-session-stop/combined-final.cfg diff --git a/nanobot/agent/automation_turns.py b/nanobot/agent/automation_turns.py index f746e1933..9a17cb0a8 100644 --- a/nanobot/agent/automation_turns.py +++ b/nanobot/agent/automation_turns.py @@ -1,7 +1,6 @@ from __future__ import annotations import asyncio -import dataclasses from collections.abc import Awaitable, Callable, Iterable from nanobot.bus.events import InboundMessage, OutboundMessage @@ -20,10 +19,9 @@ class AutomationTurnCoordinator: enqueue: Callable[[InboundMessage], Awaitable[None]], turn_id: Callable[[InboundMessage], str | None], pending_id: Callable[[InboundMessage], str | None], - should_defer_turn: Callable[[InboundMessage, str, Iterable[str]], bool], + should_defer_turn: Callable[[InboundMessage], bool], missing_id_error: str, duplicate_id_error: Callable[[str], str], - deferred_queues: dict[str, list[InboundMessage]] | None = None, ) -> None: self._enqueue = enqueue self._turn_id = turn_id @@ -31,7 +29,6 @@ class AutomationTurnCoordinator: self._should_defer_turn = should_defer_turn self._missing_id_error = missing_id_error self._duplicate_id_error = duplicate_id_error - self.deferred_queues = deferred_queues if deferred_queues is not None else {} self._waiters: dict[str, asyncio.Future[OutboundMessage | None]] = {} self._pending_messages_by_turn_id: dict[str, InboundMessage] = {} @@ -65,24 +62,9 @@ class AutomationTurnCoordinator: self._waiters.pop(turn_id, None) self._pending_messages_by_turn_id.pop(turn_id, None) - def defer_if_active( - self, - msg: InboundMessage, - *, - session_key: str, - active_session_keys: Iterable[str], - ) -> bool: - """Defer an automation turn when its target session is already active.""" - if not self._should_defer_turn(msg, session_key, active_session_keys): - return False - pending_msg = msg - if session_key != msg.session_key: - pending_msg = dataclasses.replace( - msg, - session_key_override=session_key, - ) - self.deferred_queues.setdefault(session_key, []).append(pending_msg) - return True + def should_defer(self, msg: InboundMessage) -> bool: + """Whether this turn waits for an already-active inbox to become idle.""" + return self._should_defer_turn(msg) def complete( self, @@ -104,10 +86,12 @@ class AutomationTurnCoordinator: else: future.set_result(response) - def pending_ids_for_session(self, session_key: str) -> set[str]: + def pending_ids_for_session( + self, session_key: str, deferred: Iterable[InboundMessage], + ) -> set[str]: """Return automation IDs that are waiting for or running in *session_key*.""" pending_ids: set[str] = set() - for msg in self.deferred_queues.get(session_key, []): + for msg in deferred: pending_id = self._pending_id(msg) if pending_id: pending_ids.add(pending_id) diff --git a/nanobot/agent/cron_turns.py b/nanobot/agent/cron_turns.py index 514e717e8..e74310700 100644 --- a/nanobot/agent/cron_turns.py +++ b/nanobot/agent/cron_turns.py @@ -18,29 +18,21 @@ class CronTurnCoordinator(AutomationTurnCoordinator): self, *, enqueue: Callable[[InboundMessage], Awaitable[None]], - deferred_queues: dict[str, list[InboundMessage]] | None = None, ) -> None: super().__init__( enqueue=enqueue, turn_id=lambda msg: cron_run_id(msg.metadata), pending_id=_cron_job_id, - should_defer_turn=_should_defer_cron_turn, + should_defer_turn=lambda msg: defer_cron_until_session_idle(msg.metadata), missing_id_error="cron turn metadata must include a run_id", duplicate_id_error=lambda run_id: f"cron run {run_id!r} is already pending", - deferred_queues=deferred_queues, ) - def pending_job_ids_for_session(self, session_key: str) -> set[str]: + def pending_job_ids_for_session( + self, session_key: str, deferred: Iterable[InboundMessage], + ) -> set[str]: """Return cron jobs that are waiting for or running in *session_key*.""" - return self.pending_ids_for_session(session_key) - - -def _should_defer_cron_turn( - msg: InboundMessage, - session_key: str, - active_session_keys: Iterable[str], -) -> bool: - return defer_cron_until_session_idle(msg.metadata) and session_key in active_session_keys + return self.pending_ids_for_session(session_key, deferred) def _cron_job_id(msg: InboundMessage) -> str | None: diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 569e3acbe..634cc9ed8 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -28,6 +28,7 @@ from nanobot.agent.memory import Consolidator from nanobot.agent.model_runtime import ModelRuntimeResolver from nanobot.agent.pending_inputs import PendingInputs from nanobot.agent.runner import AgentCheckpoint, AgentRunner, AgentRunResult, AgentRunSpec +from nanobot.agent.session_inbox import SessionExecutionClosedError, SessionInbox, SessionInboxes from nanobot.agent.subagent import SubagentManager from nanobot.agent.tools.context import RequestContext, bind_request_context, reset_request_context from nanobot.agent.tools.exec_session import ExecSessionManager @@ -409,7 +410,6 @@ class AgentLoop: self._running = False self._runtime_context_providers: list[RuntimeContextProvider] = [] self._active_tasks: dict[str, set[asyncio.Task[Any]]] = {} - self._discarding_sessions: set[str] = set() self._background_tasks: set[asyncio.Task[Any]] = set() self._close_lock = asyncio.Lock() self._session_locks: weakref.WeakValueDictionary[str, asyncio.Lock] = ( @@ -418,17 +418,10 @@ class AgentLoop: # A queue is installed before its single session worker is scheduled. # It remains the only admission path until that worker atomically # observes the queue empty and removes it. - self._pending_queues: dict[str, asyncio.Queue[InboundMessage]] = {} + self._pending_queues = SessionInboxes() self._preserve_inflight_turns_on_shutdown = False - self._deferred_automation_turns: dict[str, list[InboundMessage]] = {} - self._cron_turns = CronTurnCoordinator( - enqueue=self._enqueue_session_message, - deferred_queues=self._deferred_automation_turns, - ) - self._local_trigger_turns = LocalTriggerTurnCoordinator( - enqueue=self._enqueue_session_message, - deferred_queues=self._deferred_automation_turns, - ) + self._cron_turns = CronTurnCoordinator(enqueue=self._enqueue_session_message) + self._local_trigger_turns = LocalTriggerTurnCoordinator(enqueue=self._enqueue_session_message) self._automation_turn_coordinators = ( self._cron_turns, self._local_trigger_turns, @@ -690,10 +683,14 @@ class AgentLoop: return await self._local_trigger_turns.submit(msg) def pending_cron_job_ids_for_session(self, session_key: str) -> set[str]: - return self._cron_turns.pending_job_ids_for_session(session_key) + inbox = self._pending_queues.get(session_key) + return self._cron_turns.pending_job_ids_for_session(session_key, inbox.deferred if inbox else ()) def pending_local_trigger_ids_for_session(self, session_key: str) -> set[str]: - return self._local_trigger_turns.pending_trigger_ids_for_session(session_key) + inbox = self._pending_queues.get(session_key) + return self._local_trigger_turns.pending_trigger_ids_for_session( + session_key, inbox.deferred if inbox else (), + ) async def _persist_user_message_early( self, @@ -899,17 +896,25 @@ class AgentLoop: if not tasks and self._active_tasks.get(key) is tasks: self._active_tasks.pop(key, None) + @staticmethod + def _request_worker_cancellation(tasks: Iterable[asyncio.Task[Any]]) -> int: + # A cancelling worker still owns its cleanup. Another controller should + # join it instead of interrupting that cleanup with a second cancel(). + return sum(1 for task in tasks if not task.done() and not task.cancelling() and task.cancel()) + async def _cancel_active_tasks(self, key: str) -> int: + with self._pending_queues.controlling(key): + return await self._cancel_session_work(key) + + async def _cancel_session_work(self, key: str) -> int: pending = self._pending_queues.get(key) current = asyncio.current_task() tracked = self._active_tasks.get(key, set()) # A command running on the session worker must keep its task and inbox # registered until the worker finishes; only other tasks can be stopped. owns_queue = current in tracked - if not owns_queue: - self._active_tasks.pop(key, None) tasks = tuple(task for task in tracked if task is not current) - cancelled = sum(1 for t in tasks if not t.done() and t.cancel()) + cancelled = self._request_worker_cancellation(tasks) journal_session = await self.sessions.state.read(key) journaled_followup_ids = ( tuple( @@ -923,17 +928,13 @@ class AgentLoop: if journal_session is not None else () ) - for t in tasks: - try: - await t - except asyncio.CancelledError: - pass - except Exception: - pass + if tasks: + await asyncio.shield(asyncio.gather(*tasks, return_exceptions=True)) + for task in tasks: + self._active_task_done(key, tracked, task) if tasks and not owns_queue and pending is not None and self._pending_queues.get(key) is pending: # A task cancelled before its first step never enters the worker's # cleanup handler. Only reclaim that worker's original inbox. - self._pending_queues.pop(key, None) await self._cancel_pending_messages(key, pending, asyncio.CancelledError()) if journaled_followup_ids and journal_session is not None: # Explicit session cancellation owns the follow-ups accepted before @@ -946,14 +947,12 @@ class AgentLoop: async def discard_session(self, key: str) -> None: """Stop active work for *key* and forget its cached session.""" - with self.bus.admission.activity(): - self._discarding_sessions.add(key) + with self.bus.admission.activity(), self._pending_queues.controlling(key, discard=True): try: await self.sessions.state.discard(key) - await self._cancel_active_tasks(key) + await self._cancel_session_work(key) finally: self.discard_session_file_state(key) - self._discarding_sessions.discard(key) def discard_session_file_state(self, key: str) -> None: """Forget ephemeral file-read state for a reset or removed session.""" @@ -1345,6 +1344,8 @@ class AgentLoop: with self.bus.admission.activity(): try: await self._dispatch_inbound(msg) + except SessionExecutionClosedError: + break except (SessionOperationQueueFullError, SessionConflictError, ExecutionControlError) as exc: key = msg.session_key logger.warning("Session input rejected for {}: {}", key, exc) @@ -1398,7 +1399,7 @@ class AgentLoop: def _has_pending_work(self) -> bool: return bool( - self.bus.inbound_size or self._pending_queues or self._deferred_automation_turns + self.bus.inbound_size or self._pending_queues or self.bus.has_pending_events or self._active_tasks or self._background_tasks or self._close_lock.locked() or self.subagents.has_pending_work or self._exec_session_manager.has_pending_work @@ -1434,50 +1435,41 @@ class AgentLoop: return pending_msg async def _enqueue_session_message(self, msg: InboundMessage) -> None: + self._pending_queues.check_admission() self.bus.admission.check() session_key = msg.session_key if not self.subagents.accepts_result(msg, session_key): return - for coordinator in self._automation_turn_coordinators: - if coordinator.defer_if_active( - msg, - session_key=session_key, - active_session_keys=self._pending_queues.keys(), - ): - return - - if session_key in self._pending_queues: - msg = await self._journal_pending_message(session_key, msg) pending = self._pending_queues.get(session_key) + if pending is not None: + if any(coordinator.should_defer(msg) for coordinator in self._automation_turn_coordinators): + pending.defer(msg) + return + msg = await self._journal_pending_message(session_key, msg) + self._pending_queues.check_admission() + pending = self._pending_queues.get(session_key) if pending is not None: pending.put_nowait(msg) return - new_pending: asyncio.Queue[InboundMessage] = asyncio.Queue() + new_pending = SessionInbox() new_pending.put_nowait(msg) - self._pending_queues[session_key] = new_pending + self._pending_queues.install(session_key, new_pending) task = asyncio.create_task(self._run_session_queue(session_key, new_pending)) self._track_active_task(session_key, task) async def _run_session_queue( self, session_key: str, - pending: asyncio.Queue[InboundMessage], + pending: SessionInbox, ) -> None: try: + await self._pending_queues.wait_for_controls(session_key) while self._pending_queues.get(session_key) is pending: - try: - item = pending.get_nowait() - except asyncio.QueueEmpty: - # Idle-only automation follows all accepted user input on - # this same worker, including before the bus loop starts. - deferred = self._deferred_automation_turns.get(session_key) - if not deferred: - break - item = deferred.pop(0) - if not deferred: - self._deferred_automation_turns.pop(session_key) + item = pending.next_turn() + if item is None: + break session = self.sessions.state.peek_header(session_key) log_content = session is None or ( session.policy.persist and session.policy.log_content @@ -1497,20 +1489,18 @@ class AgentLoop: await self._cancel_pending_messages(session_key, pending, exc) raise finally: - owns_queue = self._pending_queues.get(session_key) is pending - if owns_queue: - self._pending_queues.pop(session_key, None) + self._pending_queues.detach(session_key, pending) async def _cancel_pending_messages( self, session_key: str, - pending: asyncio.Queue[InboundMessage], + pending: SessionInbox, error: asyncio.CancelledError, ) -> None: - for msg in self._deferred_automation_turns.pop(session_key, []): - pending.put_nowait(msg) - while not pending.empty(): - item = pending.get_nowait() + # End admission before publishing any cancellation notifications. Those + # callbacks can yield to another submitter for the same session key. + self._pending_queues.detach(session_key, pending) + for item in pending.drain(): for coordinator in self._automation_turn_coordinators: coordinator.complete(item, error=error) if item.channel != "system" and self.commands.requires_session_queue(command_text(item)): @@ -1588,7 +1578,7 @@ class AgentLoop: # shutdown keeps the durable checkpoint untouched instead, # allowing RecoveryCoordinator to offer Continue safely. if ( - session_key in self._discarding_sessions + self._pending_queues.is_discarding(session_key) or self._preserve_inflight_turns_on_shutdown ): raise exc @@ -1661,6 +1651,8 @@ class AgentLoop: await self._aclose_unlocked() async def _aclose_unlocked(self) -> None: + self._pending_queues.close_admission() + self._running = False errors: list[BaseException] = [] active_task_groups = getattr(self, "_active_tasks", {}) current_task = asyncio.current_task() @@ -1670,18 +1662,19 @@ class AgentLoop: if key in self._pending_queues and any(task is not current_task for task in tasks) } active_tasks = tuple({task for tasks in active_task_groups.values() for task in tasks}) - active_task_groups.clear() active_tasks = tuple(task for task in active_tasks if task is not current_task) - for task in active_tasks: - if not task.done(): - task.cancel() + self._request_worker_cancellation(active_tasks) try: if active_tasks: - await asyncio.gather(*active_tasks, return_exceptions=True) + await asyncio.shield(asyncio.gather(*active_tasks, return_exceptions=True)) + for key, tasks in tuple(active_task_groups.items()): + for task in tuple(tasks): + if task.done(): + self._active_task_done(key, tasks, task) for key, pending in pending_queues.items(): if self._pending_queues.get(key) is pending: - self._pending_queues.pop(key) await self._cancel_pending_messages(key, pending, asyncio.CancelledError()) + await self._pending_queues.join_controls() # A scan can schedule archival while shutdown waits for it. while self._background_tasks: await asyncio.gather(*self._background_tasks, return_exceptions=True) diff --git a/nanobot/agent/session_inbox.py b/nanobot/agent/session_inbox.py new file mode 100644 index 000000000..76efb9fd7 --- /dev/null +++ b/nanobot/agent/session_inbox.py @@ -0,0 +1,106 @@ +"""Pending input and idle-only turns for one session worker's lifetime.""" + +from __future__ import annotations + +import asyncio +from collections import deque +from collections.abc import Generator, Iterator, Mapping +from contextlib import contextmanager + +from nanobot.bus.events import InboundMessage + + +class SessionInbox(asyncio.Queue[InboundMessage]): + """Runner injection sees only the input FIFO; the worker also drains idle-only turns.""" + + def __init__(self, maxsize: int = 0) -> None: + super().__init__(maxsize) + self._deferred: deque[InboundMessage] = deque() + + @property + def deferred(self) -> tuple[InboundMessage, ...]: + return tuple(self._deferred) + + def defer(self, msg: InboundMessage) -> None: + self._deferred.append(msg) + + def next_turn(self) -> InboundMessage | None: + if not self.empty(): + return self.get_nowait() + return self._deferred.popleft() if self._deferred else None + + def drain(self) -> Iterator[InboundMessage]: + """Only for a detached inbox that can no longer accept work.""" + while (msg := self.next_turn()) is not None: + yield msg + + +class SessionExecutionClosedError(RuntimeError): + """Work cannot enter the session dispatcher once it starts shutting down.""" + + +class SessionInboxes(Mapping[str, SessionInbox]): + """Own inbox admission and the handoff from control cleanup to a new worker.""" + + def __init__(self) -> None: + self._active: dict[str, SessionInbox] = {} + self._controls: dict[str, dict[asyncio.Event, tuple[asyncio.Task[object] | None, bool]]] = {} + self._closed = False + + def __getitem__(self, key: str) -> SessionInbox: + return self._active[key] + + def __iter__(self) -> Iterator[str]: + return iter(self._active) + + def __len__(self) -> int: + return len(self._active) + + def close_admission(self) -> None: + self._closed = True + + def check_admission(self) -> None: + if self._closed: + raise SessionExecutionClosedError("Session execution is closing") + + def install(self, key: str, inbox: SessionInbox) -> None: + self.check_admission() + if key in self: + raise RuntimeError("Cannot replace a live session inbox") + self._active[key] = inbox + + def detach(self, key: str, inbox: SessionInbox) -> None: + if self.get(key) is inbox: + del self._active[key] + + @contextmanager + def controlling(self, key: str, *, discard: bool = False) -> Generator[None]: + """Accept work into a replacement inbox without starting its worker yet.""" + self.check_admission() + finished = asyncio.Event() + controls = self._controls.setdefault(key, {}) + controls[finished] = (asyncio.current_task(), discard) + try: + yield + finally: + del controls[finished] + if not controls: + del self._controls[key] + finished.set() + + def is_discarding(self, key: str) -> bool: + return any(discard for _, discard in self._controls.get(key, {}).values()) + + async def wait_for_controls(self, key: str) -> None: + while controls := self._controls.get(key): + await next(iter(controls)).wait() + + async def join_controls(self) -> None: + """After admission closes, wait for controls still using runtime resources.""" + current = asyncio.current_task() + pending = [ + finished for controls in self._controls.values() + for finished, (owner, _) in controls.items() if owner is not current + ] + if pending: + await asyncio.gather(*(finished.wait() for finished in pending)) diff --git a/nanobot/command/builtin.py b/nanobot/command/builtin.py index fa7cede33..7b6cfd7de 100644 --- a/nanobot/command/builtin.py +++ b/nanobot/command/builtin.py @@ -143,15 +143,6 @@ async def cmd_stop(ctx: CommandContext) -> OutboundMessage: loop = ctx.loop msg = ctx.msg total = await loop._cancel_active_tasks(ctx.key) # pyright: ignore[reportPrivateUsage] - # Also drain pending queue to prevent mid-turn injection deadlock - pending = loop._pending_queues.pop(ctx.key, None) # pyright: ignore[reportPrivateUsage] - if pending is not None: - while not pending.empty(): - try: - pending.get_nowait() - total += 1 - except Exception: - break content = f"Stopped {total} task(s)." if total else "No active task to stop." return OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, content=content, diff --git a/nanobot/triggers/local_turns.py b/nanobot/triggers/local_turns.py index b52df54cd..0c2d7982a 100644 --- a/nanobot/triggers/local_turns.py +++ b/nanobot/triggers/local_turns.py @@ -14,31 +14,23 @@ class LocalTriggerTurnCoordinator(AutomationTurnCoordinator): self, *, enqueue: Callable[[InboundMessage], Awaitable[None]], - deferred_queues: dict[str, list[InboundMessage]] | None = None, ) -> None: super().__init__( enqueue=enqueue, turn_id=lambda msg: local_trigger_delivery_id(msg.metadata), pending_id=_local_trigger_id, - should_defer_turn=_should_defer_local_trigger_turn, + should_defer_turn=lambda msg: local_trigger(msg.metadata) is not None, missing_id_error="local trigger turn metadata must include a delivery_id", duplicate_id_error=lambda delivery_id: ( f"local trigger delivery {delivery_id!r} is already pending" ), - deferred_queues=deferred_queues, ) - def pending_trigger_ids_for_session(self, session_key: str) -> set[str]: + def pending_trigger_ids_for_session( + self, session_key: str, deferred: Iterable[InboundMessage], + ) -> set[str]: """Return local triggers waiting for or running in *session_key*.""" - return self.pending_ids_for_session(session_key) - - -def _should_defer_local_trigger_turn( - msg: InboundMessage, - session_key: str, - active_session_keys: Iterable[str], -) -> bool: - return local_trigger(msg.metadata) is not None and session_key in active_session_keys + return self.pending_ids_for_session(session_key, deferred) def _local_trigger_id(msg: InboundMessage) -> str | None: diff --git a/tests/agent/test_loop_recovery.py b/tests/agent/test_loop_recovery.py index aed3bce91..2e7ebed7d 100644 --- a/tests/agent/test_loop_recovery.py +++ b/tests/agent/test_loop_recovery.py @@ -9,6 +9,7 @@ import pytest from agent.session_helpers import save_completed_subagent from nanobot.agent.loop import AgentLoop +from nanobot.agent.session_inbox import SessionInboxes from nanobot.agent.turn_delivery import TurnDeliveryFactory from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.queue import MessageBus @@ -131,7 +132,7 @@ async def test_recovery_continuation_runs_without_a_sustained_goal( loop._session_locks = {} loop._concurrency_gate = None loop._automation_turn_coordinators = [] - loop._discarding_sessions = set() + loop._pending_queues = SessionInboxes() loop._preserve_inflight_turns_on_shutdown = False loop.turn_delivery_factory = TurnDeliveryFactory(bus) process_message = AsyncMock(return_value=OutboundMessage( diff --git a/tests/agent/test_loop_session_policy.py b/tests/agent/test_loop_session_policy.py index c3a018ff1..21cc902ea 100644 --- a/tests/agent/test_loop_session_policy.py +++ b/tests/agent/test_loop_session_policy.py @@ -334,10 +334,6 @@ async def test_session_discard_control_cancels_active_turn(tmp_path, monkeypatch loop = _loop(tmp_path, []) - async def wait_for_discard(key: str) -> None: - while loop.sessions.get_cached(key) is not None or key in loop._discarding_sessions: - await asyncio.sleep(0) - loop.provider.chat_stream_with_retry = AsyncMock(side_effect=block_provider) monkeypatch.setattr(loop, "aclose", AsyncMock()) terminate_exec_sessions = AsyncMock(return_value=1) @@ -372,7 +368,7 @@ async def test_session_discard_control_cancels_active_turn(tmp_path, monkeypatch with pytest.raises(asyncio.CancelledError): await asyncio.wait_for(active_task, timeout=2) - await asyncio.wait_for(wait_for_discard(key), timeout=2) + await asyncio.wait_for(loop._pending_queues.wait_for_controls(key), timeout=2) assert loop.sessions.get_cached(key) is None assert loop._file_state_store.for_session(key) is not previous_file_state terminate_exec_sessions.assert_awaited_once_with(key) diff --git a/tests/agent/test_runner_injections.py b/tests/agent/test_runner_injections.py index bbfdd53a1..e83b675f9 100644 --- a/tests/agent/test_runner_injections.py +++ b/tests/agent/test_runner_injections.py @@ -9,6 +9,7 @@ import pytest from agent.runner_helpers import make_run_spec from agent.session_helpers import run_session, visible_message from nanobot.agent.context import TranscriptInput +from nanobot.agent.session_inbox import SessionInbox from nanobot.agent.tools.context import RequestContext from nanobot.config.schema import AgentDefaults from nanobot.providers.base import LLMResponse, ToolCallRequest @@ -1084,8 +1085,8 @@ async def test_followup_routed_to_pending_queue(tmp_path): loop = _make_loop(tmp_path) - pending = asyncio.Queue(maxsize=20) - loop._pending_queues["discord:c"] = pending + pending = SessionInbox(maxsize=20) + loop._pending_queues.install("discord:c", pending) run_task = asyncio.create_task(loop.run()) msg = InboundMessage(channel="discord", sender_id="u", chat_id="c", content="follow-up") @@ -1105,30 +1106,31 @@ async def test_followup_routed_to_pending_queue(tmp_path): async def test_websocket_followup_is_admitted_before_recovery_queue(tmp_path): from nanobot.bus.events import InboundMessage + pending = SessionInbox(maxsize=20) + + async def admit(_msg): + assert pending.empty(), "follow-up queued before recovery admission" + return True + admission = MagicMock() - admission.admit = AsyncMock(return_value=True) + admission.admit = AsyncMock(side_effect=admit) loop = _make_loop(tmp_path, recovery_admission=admission) - - session_key = "websocket:chat" - pending = asyncio.Queue(maxsize=20) - loop._pending_queues[session_key] = pending - - run_task = asyncio.create_task(loop.run()) + loop._pending_queues.install("websocket:chat", pending) msg = InboundMessage( channel="websocket", sender_id="u", chat_id="chat", content="new request", ) - await loop.bus.publish_inbound(msg) - queued_msg = await asyncio.wait_for(pending.get(), timeout=2) - admission.admit.assert_awaited_once_with(msg) - assert queued_msg.content == msg.content - assert queued_msg.metadata["_recovery_followup_id"] - - loop.stop() - await asyncio.wait_for(run_task, timeout=2) + try: + await loop._dispatch_inbound(msg) + queued_msg = pending.get_nowait() + admission.admit.assert_awaited_once_with(msg) + assert queued_msg.content == msg.content + assert queued_msg.metadata["_recovery_followup_id"] + finally: + await loop.aclose() @pytest.mark.asyncio @@ -1140,8 +1142,8 @@ async def test_mid_turn_subagent_result_does_not_resolve_a_new_turn_route(tmp_pa loop.turn_delivery_factory.route_policy = route_policy session_key = "websocket:chat-1" - pending = asyncio.Queue(maxsize=20) - loop._pending_queues[session_key] = pending + pending = SessionInbox(maxsize=20) + loop._pending_queues.install(session_key, pending) run_task = asyncio.create_task(loop.run()) msg = InboundMessage( @@ -1568,7 +1570,7 @@ async def test_session_worker_processes_leftovers_without_republishing(tmp_path) loop = _make_loop(tmp_path) session_key = "cli:c" - pending = asyncio.Queue() + pending = SessionInbox() processed: list[str] = [] async def _process_message(msg, **_kwargs): @@ -1583,7 +1585,7 @@ async def test_session_worker_processes_leftovers_without_republishing(tmp_path) chat_id="c", content=content, )) - loop._pending_queues[session_key] = pending + loop._pending_queues.install(session_key, pending) await loop._run_session_queue(session_key, pending) diff --git a/tests/agent/test_session_inbox_controls.py b/tests/agent/test_session_inbox_controls.py index 3b6abade8..ac1ce5344 100644 --- a/tests/agent/test_session_inbox_controls.py +++ b/tests/agent/test_session_inbox_controls.py @@ -7,6 +7,7 @@ import pytest from agent.session_helpers import run_session, stop_loop, visible_message from nanobot.agent.automation_turns import AutomationTurnError from nanobot.agent.loop import AgentLoop +from nanobot.agent.session_inbox import SessionInbox from nanobot.agent.tools.context import current_request_context from nanobot.agent.tools.cron import CronTool from nanobot.bus.events import InboundMessage, OutboundMessage @@ -315,9 +316,8 @@ def _automation_message(kind: str, name: str) -> InboundMessage: @pytest.mark.parametrize("kind", ["cron", "local_trigger"]) async def test_automation_turn_is_deferred_while_session_active(loop, kind): key = "websocket:test" - pending = asyncio.Queue() - loop._pending_queues[key] = pending - coordinator = loop._cron_turns if kind == "cron" else loop._local_trigger_turns + pending = SessionInbox() + loop._pending_queues.install(key, pending) pending_ids = ( loop.pending_cron_job_ids_for_session if kind == "cron" @@ -329,17 +329,17 @@ async def test_automation_turn_is_deferred_while_session_active(loop, kind): try: await loop.bus.publish_inbound(msg) async with asyncio.timeout(3): - while not coordinator.deferred_queues.get(key): + while not pending.deferred: await asyncio.sleep(0) assert pending.empty() assert loop._active_tasks == {} - assert coordinator.deferred_queues[key] == [msg] + assert pending.deferred == (msg,) assert pending_ids(key) == {"deferred"} loop._process_message = AsyncMock(return_value=None) await loop._run_session_queue(key, pending) assert loop._process_message.await_args.args[0] is msg - assert key not in coordinator.deferred_queues + assert not pending.deferred assert pending_ids(key) == set() finally: loop.stop() @@ -466,7 +466,7 @@ async def test_cancelled_session_completes_queued_automation_waiters(loop): )) tasks.extend([cron, trigger]) await asyncio.sleep(0) - assert len(loop._deferred_automation_turns["websocket:test"]) == 2 + assert len(loop._pending_queues["websocket:test"].deferred) == 2 worker.cancel() with pytest.raises(asyncio.CancelledError): await worker @@ -583,6 +583,270 @@ async def test_cancel_preserves_followups_accepted_after_cancellation_started(lo )] == ["new followup"] +@pytest.fixture +def handoff_started(loop, monkeypatch): + """Exercise the real dispatcher and inbox without waiting on turn storage.""" + started = asyncio.Event() + + async def process_message(msg, **_kwargs): + if msg.content == "original turn": + started.set() + await asyncio.Event().wait() + return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, content="automation finished") + + monkeypatch.setattr(loop.sessions.state, "read", AsyncMock(return_value=None)) + monkeypatch.setattr(loop, "_process_message", process_message) + return started + + +@pytest.mark.parametrize("kind", ["cron", "local_trigger"]) +async def test_stop_does_not_strand_automation_submitted_during_cleanup( + loop, monkeypatch, kind, handoff_started, +): + cleaning_exec = asyncio.Event() + submit_turn = loop.submit_cron_turn if kind == "cron" else loop.submit_local_trigger_turn + cancel_launches = loop._exec_session_manager._cancel_launches + + async def observe_launch_cleanup(launches): + # Wake the submitter from the real exec cleanup without adding a + # suspension that could hide the late queue removal this test catches. + cleaning_exec.set() + return await cancel_launches(launches) + + monkeypatch.setattr(loop._exec_session_manager, "_cancel_launches", observe_launch_cleanup) + async with asyncio.timeout(5), asyncio.TaskGroup() as tasks: + await loop._dispatch_inbound(InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="original turn", + )) + await handoff_started.wait() + stop = tasks.create_task(loop._dispatch_inbound(InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="/stop", + ))) + await cleaning_exec.wait() + submitted = tasks.create_task(submit_turn(_automation_message(kind, "new work"))) + await stop + while True: + reply = await loop.bus.consume_outbound() + if reply.event is None and reply.content.startswith("Stopped "): + break + result = await submitted + assert result is not None and result.content == "automation finished" + + +async def test_automation_arriving_during_queue_cancellation_is_not_stranded(loop, handoff_started): + notifying = asyncio.Event() + release_notification = asyncio.Event() + + async def observe_completion(event): + if event.context.metadata.get("message_id") == "queued-compact": + notifying.set() + await release_notification.wait() + + loop.bus.subscribe(observe_completion, TurnCompleted) + async with asyncio.timeout(5), asyncio.TaskGroup() as tasks: + await loop._dispatch_inbound(InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="original turn", + )) + await handoff_started.wait() + await loop._dispatch_inbound(InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="/compact", + metadata={"message_id": "queued-compact"}, + )) + stop = tasks.create_task(loop._dispatch_inbound(InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="/stop", + ))) + try: + await notifying.wait() + msg = _automation_message("cron", "after queue cancellation") + submitted = tasks.create_task(loop.submit_cron_turn(msg)) + while "after queue cancellation" not in loop.pending_cron_job_ids_for_session(msg.session_key): + await asyncio.sleep(0) + finally: + release_notification.set() + await stop + while True: + reply = await loop.bus.consume_outbound() + if reply.event is None and reply.content.startswith("Stopped "): + break + result = await submitted + assert result is not None and result.content == "automation finished" + + +async def test_shutdown_rejects_automation_before_starting_cleanup(loop): + started = asyncio.Event() + cleaning = asyncio.Event() + release = asyncio.Event() + + async def chat(**_kwargs): + if not started.is_set(): + started.set() + try: + await asyncio.Event().wait() + finally: + cleaning.set() + await release.wait() + return LLMResponse(content="too late to start") + + loop.provider.chat_stream_with_retry = chat + await loop._enqueue_session_message(InboundMessage( + channel="websocket", sender_id="user", chat_id="already-active", content="original turn", + )) + await asyncio.wait_for(started.wait(), timeout=3) + close = asyncio.create_task(loop.aclose()) + try: + await asyncio.wait_for(cleaning.wait(), timeout=3) + # The snapshot contains another session; both same-key and cross-session + # submitters must see the closed runtime, not just its active inboxes. + with pytest.raises(RuntimeError, match="Session execution is closing"): + await asyncio.wait_for(loop.submit_local_trigger_turn( + _automation_message("local_trigger", "during shutdown"), + ), timeout=3) + finally: + release.set() + await asyncio.wait_for(close, timeout=3) + + +async def test_shutdown_waits_for_worker_already_cancelling_from_stop(loop, monkeypatch): + started = asyncio.Event() + cancelling = asyncio.Event() + release = asyncio.Event() + closing_resources = asyncio.Event() + close_subagents = loop.subagents.close + + async def chat(**_kwargs): + started.set() + try: + await asyncio.Event().wait() + finally: + cancelling.set() + await release.wait() + + async def observe_close(): + closing_resources.set() + await close_subagents() + + loop.provider.chat_stream_with_retry = chat + monkeypatch.setattr(loop.subagents, "close", observe_close) + dispatcher = asyncio.create_task(loop.run()) + close = None + try: + async with asyncio.timeout(5): + await loop.bus.publish_inbound(InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="original turn", + )) + await started.wait() + await loop.bus.publish_inbound(InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="/stop", + )) + await cancelling.wait() + close = asyncio.create_task(loop.aclose()) + # With no other workers or background tasks, a close that does not + # join this worker goes straight to shared resource teardown. + await asyncio.sleep(0) + assert not closing_resources.is_set() + finally: + release.set() + if close is not None: + await asyncio.wait_for(close, timeout=3) + await stop_loop(loop, dispatcher, timeout=3) + assert closing_resources.is_set() + + +async def test_replacement_waits_for_same_session_resource_cleanup(loop, monkeypatch): + started = asyncio.Event() + cleaning = asyncio.Event() + release = asyncio.Event() + cleanup_at_dispatch = [] + dispatch_one = loop._dispatch_one + cancel_by_session = loop.subagents.cancel_by_session + + async def chat(**_kwargs): + if not started.is_set(): + started.set() + await asyncio.Event().wait() + return LLMResponse(content="automation finished") + + async def observe_dispatch(msg, pending): + if msg.content == "same session": + cleanup_at_dispatch.append(release.is_set()) + await dispatch_one(msg, pending) + + async def blocked_cleanup(key): + cleaning.set() + await release.wait() + return await cancel_by_session(key) + + loop.provider.chat_stream_with_retry = chat + monkeypatch.setattr(loop, "_dispatch_one", observe_dispatch) + monkeypatch.setattr(loop.subagents, "cancel_by_session", blocked_cleanup) + dispatcher = asyncio.create_task(loop.run()) + submitted = None + try: + async with asyncio.timeout(5): + await loop.bus.publish_inbound(InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="original turn", + )) + await started.wait() + await loop.bus.publish_inbound(InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="/stop", + )) + await cleaning.wait() + submitted = asyncio.create_task(loop.submit_cron_turn( + _automation_message("cron", "same session"), + )) + other = _automation_message("cron", "other session") + other.chat_id = "other" + assert (await loop.submit_cron_turn(other)).content == "automation finished" + release.set() + assert (await submitted).content == "automation finished" + assert cleanup_at_dispatch == [True] + finally: + release.set() + if submitted is not None: + submitted.cancel() + await asyncio.gather(submitted, return_exceptions=True) + await stop_loop(loop, dispatcher, timeout=3) + + +async def test_shutdown_joins_control_when_no_worker_remains(loop, monkeypatch): + cleaning = asyncio.Event() + release = asyncio.Event() + closing_resources = asyncio.Event() + seen_released = [] + cancel_by_session = loop.subagents.cancel_by_session + close_subagents = loop.subagents.close + + async def blocked_cleanup(key): + cleaning.set() + await release.wait() + return await cancel_by_session(key) + + async def observe_close(): + seen_released.append(release.is_set()) + closing_resources.set() + await close_subagents() + + monkeypatch.setattr(loop.subagents, "cancel_by_session", blocked_cleanup) + monkeypatch.setattr(loop.subagents, "close", observe_close) + dispatcher = asyncio.create_task(loop.run()) + close = None + try: + async with asyncio.timeout(5): + await loop.bus.publish_inbound(InboundMessage( + channel="websocket", sender_id="user", chat_id="test", content="/stop", + )) + await cleaning.wait() + close = asyncio.create_task(loop.aclose()) + await asyncio.sleep(0) + assert not closing_resources.is_set() + finally: + release.set() + if close is not None: + await asyncio.wait_for(close, timeout=3) + await stop_loop(loop, dispatcher, timeout=3) + assert seen_released and all(seen_released) + + @pytest.mark.parametrize("action", ["stop", "close"]) async def test_cancel_before_worker_runs_completes_automation(loop, action): loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="unused")) @@ -692,7 +956,6 @@ async def test_ingress_sources_share_one_session_worker(loop, bus_running): assert len(set(workers)) == 1 assert loop.bus.inbound_size == 0 assert key not in loop._pending_queues - assert key not in loop._deferred_automation_turns finally: release.set() for task in tasks: diff --git a/tests/command/test_stop_pending_queue.py b/tests/command/test_stop_pending_queue.py index c2da1497e..b1efb6d84 100644 --- a/tests/command/test_stop_pending_queue.py +++ b/tests/command/test_stop_pending_queue.py @@ -1,76 +1,22 @@ -import asyncio from unittest.mock import AsyncMock, MagicMock import pytest -from nanobot.bus.events import OutboundMessage +from nanobot.bus.events import InboundMessage from nanobot.command.builtin import cmd_stop from nanobot.command.router import CommandContext -@pytest.mark.asyncio -async def test_cmd_stop_drains_pending_queue(): - mock_loop = MagicMock() - mock_loop._cancel_active_tasks = AsyncMock(return_value=1) - mock_loop._pending_queues = {} - - pending = asyncio.Queue() - await pending.put("msg1") - await pending.put("msg2") - mock_loop._pending_queues["test-session"] = pending - - ctx = CommandContext( - msg=MagicMock(channel="websocket", chat_id="test-chat", metadata={}), - session=None, - key="test-session", - raw="/stop", - loop=mock_loop, - ) +@pytest.mark.parametrize(("count", "content"), [ + (3, "Stopped 3 task(s)."), + (0, "No active task to stop."), +]) +async def test_cmd_stop_reports_session_cancellation(count, content): + loop = MagicMock(_cancel_active_tasks=AsyncMock(return_value=count)) + msg = InboundMessage(channel="websocket", sender_id="user", chat_id="chat", content="/stop") + ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw=msg.content, loop=loop) result = await cmd_stop(ctx) - assert isinstance(result, OutboundMessage) - assert "Stopped 3 task(s)" in result.content - assert "test-session" not in mock_loop._pending_queues - - -@pytest.mark.asyncio -async def test_cmd_stop_with_empty_pending_queue(): - mock_loop = MagicMock() - mock_loop._cancel_active_tasks = AsyncMock(return_value=2) - mock_loop._pending_queues = {} - - pending = asyncio.Queue() - mock_loop._pending_queues["test-session"] = pending - - ctx = CommandContext( - msg=MagicMock(channel="websocket", chat_id="test-chat", metadata={}), - session=None, - key="test-session", - raw="/stop", - loop=mock_loop, - ) - - result = await cmd_stop(ctx) - - assert "Stopped 2 task(s)" in result.content - assert "test-session" not in mock_loop._pending_queues - - -@pytest.mark.asyncio -async def test_cmd_stop_no_pending_queue(): - mock_loop = MagicMock() - mock_loop._cancel_active_tasks = AsyncMock(return_value=0) - mock_loop._pending_queues = {} - - ctx = CommandContext( - msg=MagicMock(channel="websocket", chat_id="test-chat", metadata={}), - session=None, - key="test-session", - raw="/stop", - loop=mock_loop, - ) - - result = await cmd_stop(ctx) - - assert "No active task to stop" in result.content + loop._cancel_active_tasks.assert_awaited_once_with(msg.session_key) + assert (result.channel, result.chat_id, result.content) == (msg.channel, msg.chat_id, content) diff --git a/tests/tools/test_exec_session_tools.py b/tests/tools/test_exec_session_tools.py index 24a32f4c9..38001efa8 100644 --- a/tests/tools/test_exec_session_tools.py +++ b/tests/tools/test_exec_session_tools.py @@ -8,7 +8,7 @@ import subprocess import sys import time from types import SimpleNamespace -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, MagicMock import pytest from loguru import logger @@ -27,7 +27,9 @@ from nanobot.agent.tools.exec_session import ( ) from nanobot.agent.tools.registry import is_tool_error_result from nanobot.agent.tools.shell import ExecTool +from nanobot.bus.queue import MessageBus from nanobot.execution import processes +from nanobot.providers.base import GenerationSettings def _python_command(code: str) -> str: @@ -985,54 +987,44 @@ def test_exec_session_manager_preserves_single_cleanup_error(): asyncio.run(run()) -def test_agent_loop_shutdown_closes_exec_sessions(tmp_path): - async def run() -> None: - manager = ExecSessionManager() - tool = ExecTool(working_dir=str(tmp_path), timeout=30, session_manager=manager) - initial = await tool.execute( - command=_waiting_shell_command("ready"), - yield_time_ms=100, - ) - sid = _session_id(initial) - process = manager._sessions[sid].process - - loop = object.__new__(AgentLoop) - loop.sessions = SimpleNamespace(state=SimpleNamespace(aclose=AsyncMock())) - loop._background_tasks = set() - loop._exec_session_manager = manager - loop.runtime_resolver = SimpleNamespace(aclose=AsyncMock()) - loop.subagents = SimpleNamespace(close=AsyncMock()) - - await loop.aclose() - await loop.aclose() - - assert process.returncode is not None - assert manager._sessions == {} - assert loop.subagents.close.await_count == 2 - - asyncio.run(run()) +@pytest.fixture +def shutdown_loop(tmp_path) -> AgentLoop: + provider = MagicMock(aclose=AsyncMock(), generation=GenerationSettings()) + return AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model") -def test_agent_loop_shutdown_attempts_all_cleanup_after_errors(): - async def run() -> None: - loop = object.__new__(AgentLoop) - loop.sessions = SimpleNamespace(state=SimpleNamespace(aclose=AsyncMock())) - loop._background_tasks = set() - loop.runtime_resolver = SimpleNamespace(aclose=AsyncMock()) - loop.subagents = SimpleNamespace( - close=AsyncMock(side_effect=RuntimeError("subagent cleanup failed")), - ) - loop._exec_session_manager = SimpleNamespace( - close_all=AsyncMock(side_effect=OSError("exec cleanup failed")), - ) - with pytest.raises(BaseExceptionGroup) as exc_info: - await loop.aclose() +async def test_agent_loop_shutdown_closes_exec_sessions(shutdown_loop, tmp_path, monkeypatch): + manager = shutdown_loop._exec_session_manager + close_subagents = AsyncMock(wraps=shutdown_loop.subagents.close) + monkeypatch.setattr(shutdown_loop.subagents, "close", close_subagents) + tool = ExecTool(working_dir=str(tmp_path), timeout=30, session_manager=manager) + initial = await tool.execute( + command=_waiting_shell_command("ready"), + yield_time_ms=100, + ) + sid = _session_id(initial) + process = manager._sessions[sid].process - assert len(exc_info.value.exceptions) == 2 - loop.subagents.close.assert_awaited_once() - loop._exec_session_manager.close_all.assert_awaited_once() + await shutdown_loop.aclose() + await shutdown_loop.aclose() - asyncio.run(run()) + assert process.returncode is not None + assert manager._sessions == {} + assert close_subagents.await_count == 2 + + +async def test_agent_loop_shutdown_attempts_all_cleanup_after_errors(shutdown_loop, monkeypatch): + close_subagents = AsyncMock(side_effect=RuntimeError("subagent cleanup failed")) + close_exec_sessions = AsyncMock(side_effect=OSError("exec cleanup failed")) + monkeypatch.setattr(shutdown_loop.subagents, "close", close_subagents) + monkeypatch.setattr(shutdown_loop._exec_session_manager, "close_all", close_exec_sessions) + + with pytest.raises(BaseExceptionGroup) as exc_info: + await shutdown_loop.aclose() + + assert len(exc_info.value.exceptions) == 2 + close_subagents.assert_awaited_once() + close_exec_sessions.assert_awaited_once() def test_terminate_by_owner_kills_matching_sessions(tmp_path): @@ -1185,22 +1177,16 @@ def test_terminate_by_owner_skips_sessions_without_owner_key(tmp_path): asyncio.run(run()) -def test_agent_loop_shutdown_preserves_single_cleanup_error(): - async def run() -> None: - loop = object.__new__(AgentLoop) - loop.sessions = SimpleNamespace(state=SimpleNamespace(aclose=AsyncMock())) - loop._background_tasks = set() - loop.runtime_resolver = SimpleNamespace(aclose=AsyncMock()) - loop.subagents = SimpleNamespace( - close=AsyncMock(side_effect=RuntimeError("subagent cleanup failed")), - ) - loop._exec_session_manager = SimpleNamespace(close_all=AsyncMock()) - with pytest.raises(RuntimeError, match="subagent cleanup failed"): - await loop.aclose() +async def test_agent_loop_shutdown_preserves_single_cleanup_error(shutdown_loop, monkeypatch): + close_subagents = AsyncMock(side_effect=RuntimeError("subagent cleanup failed")) + close_exec_sessions = AsyncMock(wraps=shutdown_loop._exec_session_manager.close_all) + monkeypatch.setattr(shutdown_loop.subagents, "close", close_subagents) + monkeypatch.setattr(shutdown_loop._exec_session_manager, "close_all", close_exec_sessions) - loop._exec_session_manager.close_all.assert_awaited_once() + with pytest.raises(RuntimeError, match="subagent cleanup failed"): + await shutdown_loop.aclose() - asyncio.run(run()) + close_exec_sessions.assert_awaited_once() async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch): diff --git a/verification/async-session-stop/CombinedLifecycle.tla b/verification/async-session-stop/CombinedLifecycle.tla new file mode 100644 index 000000000..87d95bfdf --- /dev/null +++ b/verification/async-session-stop/CombinedLifecycle.tla @@ -0,0 +1,77 @@ +--------------------------- MODULE CombinedLifecycle ------------------------- +CONSTANT JoinControls +Keys == {"A", "B"} +VARIABLES phase, workers, controls, controlled, submitted + +vars == <> + +Init == + /\ phase = "open" + /\ workers = [k \in Keys |-> "running"] + /\ controls = {} + /\ controlled = {} + /\ submitted = {} + +BeginControl(k) == + /\ phase = "open" + /\ k \notin controlled + /\ controls' = controls \cup {k} + /\ controlled' = controlled \cup {k} + /\ workers' = [workers EXCEPT ![k] = IF @ = "running" THEN "cancelling" ELSE @] + /\ UNCHANGED <> + +FinishControl(k) == + /\ k \in controls + /\ workers[k] \in {"none", "queued"} + /\ controls' = controls \ {k} + /\ UNCHANGED <> + +SubmitReplacement(k) == + /\ phase = "open" + /\ workers[k] = "none" + /\ k \notin submitted + /\ workers' = [workers EXCEPT ![k] = "queued"] + /\ submitted' = submitted \cup {k} + /\ UNCHANGED <> + +StartReplacement(k) == + /\ workers[k] = "queued" + /\ k \notin controls + /\ workers' = [workers EXCEPT ![k] = "running"] + /\ UNCHANGED <> + +FinishWorker(k) == + /\ workers[k] \in {"running", "cancelling"} + /\ workers' = [workers EXCEPT ![k] = "none"] + /\ UNCHANGED <> + +BeginClose == + /\ phase = "open" + /\ phase' = "closing" + /\ workers' = [k \in Keys |-> IF workers[k] = "none" THEN "none" ELSE "cancelling"] + /\ UNCHANGED <> + +TearDown == + /\ phase = "closing" + /\ \A k \in Keys: workers[k] = "none" + /\ ~JoinControls \/ controls = {} + /\ phase' = "closed" + /\ UNCHANGED <> + +Next == + \/ BeginClose + \/ TearDown + \/ \E k \in Keys: + BeginControl(k) \/ FinishControl(k) \/ SubmitReplacement(k) + \/ StartReplacement(k) \/ FinishWorker(k) + +Spec == + /\ Init + /\ [][Next]_vars + /\ WF_vars(TearDown) + /\ \A k \in Keys: WF_vars(FinishControl(k)) /\ WF_vars(FinishWorker(k)) + +CloseJoinsAllOwners == + phase = "closed" => (controls = {} /\ \A k \in Keys: workers[k] = "none") +CloseEventuallyCompletes == (phase = "closing") ~> (phase = "closed") +============================================================================= diff --git a/verification/async-session-stop/README.md b/verification/async-session-stop/README.md new file mode 100644 index 000000000..1a1f06d45 --- /dev/null +++ b/verification/async-session-stop/README.md @@ -0,0 +1,17 @@ +# Session inbox lifecycle model + +`CombinedLifecycle.tla` models shutdown admission, worker lifetime, and control handoff across two session keys, with at most one control and one replacement per key. It checks that shutdown waits for all workers and controls before closing shared resources, and that shutdown eventually finishes if workers and controls can complete their cleanup. + +## Run the checks + +Use [TLC 2.19 (TLA+ v1.7.4)](https://github.com/tlaplus/tlaplus/releases/tag/v1.7.4). Run these commands from a scratch copy of this directory so TLC output stays out of the source tree. Replace `/path/to/tla2tools.jar` with the path to the downloaded JAR. + +```sh +java -XX:+UseParallelGC -cp "/path/to/tla2tools.jar" tlc2.TLC -config combined-final.cfg CombinedLifecycle.tla +java -XX:+UseParallelGC -cp "/path/to/tla2tools.jar" tlc2.TLC -config combined-baseline.cfg CombinedLifecycle.tla +``` + +- `combined-final.cfg` checks the current model and exhausts 333 distinct states without a violation. +- `combined-baseline.cfg` disables joining in-flight controls. It must violate `CloseJoinsAllOwners`: shutdown can close resources while a control is still running after its worker exits. + +The Python replay is `test_shutdown_joins_control_when_no_worker_remains` in [the inbox regression tests](../../tests/agent/test_session_inbox_controls.py). The same tests cover automation arriving during queue retirement and replacement workers waiting for cleanup. The model does not verify the Python implementation and excludes direct SDK calls, forced shutdown deadlines, subprocess termination, and SQLite recovery. The smaller models used during diagnosis are preserved in [the original PR snapshot](https://github.com/HKUDS/nanobot/tree/f552eccf358cd5bbe5f295e6138921fb0d425475/verification/async-session-stop). diff --git a/verification/async-session-stop/combined-baseline.cfg b/verification/async-session-stop/combined-baseline.cfg new file mode 100644 index 000000000..a8c2d58e9 --- /dev/null +++ b/verification/async-session-stop/combined-baseline.cfg @@ -0,0 +1,5 @@ +CONSTANT JoinControls = FALSE +SPECIFICATION Spec +INVARIANT CloseJoinsAllOwners +PROPERTY CloseEventuallyCompletes +CHECK_DEADLOCK FALSE diff --git a/verification/async-session-stop/combined-final.cfg b/verification/async-session-stop/combined-final.cfg new file mode 100644 index 000000000..713d712b8 --- /dev/null +++ b/verification/async-session-stop/combined-final.cfg @@ -0,0 +1,5 @@ +CONSTANT JoinControls = TRUE +SPECIFICATION Spec +INVARIANT CloseJoinsAllOwners +PROPERTY CloseEventuallyCompletes +CHECK_DEADLOCK FALSE