refactor(agent): centralize session execution ownership (#6699)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-18 13:49:41 +08:00
1 parent 53a556585e
commit 5997a714f2
16 files changed
+642 -286

No files matched your search

+8 -24
View File
@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import dataclasses
from collections.abc import Awaitable, Callable, Iterable from collections.abc import Awaitable, Callable, Iterable
from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.events import InboundMessage, OutboundMessage
@@ -20,10 +19,9 @@ class AutomationTurnCoordinator:
enqueue: Callable[[InboundMessage], Awaitable[None]], enqueue: Callable[[InboundMessage], Awaitable[None]],
turn_id: Callable[[InboundMessage], str | None], turn_id: Callable[[InboundMessage], str | None],
pending_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, missing_id_error: str,
duplicate_id_error: Callable[[str], str], duplicate_id_error: Callable[[str], str],
deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None: ) -> None:
self._enqueue = enqueue self._enqueue = enqueue
self._turn_id = turn_id self._turn_id = turn_id
@@ -31,7 +29,6 @@ class AutomationTurnCoordinator:
self._should_defer_turn = should_defer_turn self._should_defer_turn = should_defer_turn
self._missing_id_error = missing_id_error self._missing_id_error = missing_id_error
self._duplicate_id_error = duplicate_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._waiters: dict[str, asyncio.Future[OutboundMessage | None]] = {}
self._pending_messages_by_turn_id: dict[str, InboundMessage] = {} self._pending_messages_by_turn_id: dict[str, InboundMessage] = {}
@@ -65,24 +62,9 @@ class AutomationTurnCoordinator:
self._waiters.pop(turn_id, None) self._waiters.pop(turn_id, None)
self._pending_messages_by_turn_id.pop(turn_id, None) self._pending_messages_by_turn_id.pop(turn_id, None)
def defer_if_active( def should_defer(self, msg: InboundMessage) -> bool:
self, """Whether this turn waits for an already-active inbox to become idle."""
msg: InboundMessage, return self._should_defer_turn(msg)
*,
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 complete( def complete(
self, self,
@@ -104,10 +86,12 @@ class AutomationTurnCoordinator:
else: else:
future.set_result(response) 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*.""" """Return automation IDs that are waiting for or running in *session_key*."""
pending_ids: set[str] = set() pending_ids: set[str] = set()
for msg in self.deferred_queues.get(session_key, []): for msg in deferred:
pending_id = self._pending_id(msg) pending_id = self._pending_id(msg)
if pending_id: if pending_id:
pending_ids.add(pending_id) pending_ids.add(pending_id)
+5 -13
View File
@@ -18,29 +18,21 @@ class CronTurnCoordinator(AutomationTurnCoordinator):
self, self,
*, *,
enqueue: Callable[[InboundMessage], Awaitable[None]], enqueue: Callable[[InboundMessage], Awaitable[None]],
deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None: ) -> None:
super().__init__( super().__init__(
enqueue=enqueue, enqueue=enqueue,
turn_id=lambda msg: cron_run_id(msg.metadata), turn_id=lambda msg: cron_run_id(msg.metadata),
pending_id=_cron_job_id, 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", 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", 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 cron jobs that are waiting for or running in *session_key*."""
return self.pending_ids_for_session(session_key) return self.pending_ids_for_session(session_key, deferred)
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
def _cron_job_id(msg: InboundMessage) -> str | None: def _cron_job_id(msg: InboundMessage) -> str | None:
+61 -68
View File
@@ -28,6 +28,7 @@ from nanobot.agent.memory import Consolidator
from nanobot.agent.model_runtime import ModelRuntimeResolver from nanobot.agent.model_runtime import ModelRuntimeResolver
from nanobot.agent.pending_inputs import PendingInputs from nanobot.agent.pending_inputs import PendingInputs
from nanobot.agent.runner import AgentCheckpoint, AgentRunner, AgentRunResult, AgentRunSpec 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.subagent import SubagentManager
from nanobot.agent.tools.context import RequestContext, bind_request_context, reset_request_context from nanobot.agent.tools.context import RequestContext, bind_request_context, reset_request_context
from nanobot.agent.tools.exec_session import ExecSessionManager from nanobot.agent.tools.exec_session import ExecSessionManager
@@ -409,7 +410,6 @@ class AgentLoop:
self._running = False self._running = False
self._runtime_context_providers: list[RuntimeContextProvider] = [] self._runtime_context_providers: list[RuntimeContextProvider] = []
self._active_tasks: dict[str, set[asyncio.Task[Any]]] = {} self._active_tasks: dict[str, set[asyncio.Task[Any]]] = {}
self._discarding_sessions: set[str] = set()
self._background_tasks: set[asyncio.Task[Any]] = set() self._background_tasks: set[asyncio.Task[Any]] = set()
self._close_lock = asyncio.Lock() self._close_lock = asyncio.Lock()
self._session_locks: weakref.WeakValueDictionary[str, 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. # A queue is installed before its single session worker is scheduled.
# It remains the only admission path until that worker atomically # It remains the only admission path until that worker atomically
# observes the queue empty and removes it. # 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._preserve_inflight_turns_on_shutdown = False
self._deferred_automation_turns: dict[str, list[InboundMessage]] = {} self._cron_turns = CronTurnCoordinator(enqueue=self._enqueue_session_message)
self._cron_turns = CronTurnCoordinator( self._local_trigger_turns = LocalTriggerTurnCoordinator(enqueue=self._enqueue_session_message)
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._automation_turn_coordinators = ( self._automation_turn_coordinators = (
self._cron_turns, self._cron_turns,
self._local_trigger_turns, self._local_trigger_turns,
@@ -690,10 +683,14 @@ class AgentLoop:
return await self._local_trigger_turns.submit(msg) return await self._local_trigger_turns.submit(msg)
def pending_cron_job_ids_for_session(self, session_key: str) -> set[str]: 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]: 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( async def _persist_user_message_early(
self, self,
@@ -899,17 +896,25 @@ class AgentLoop:
if not tasks and self._active_tasks.get(key) is tasks: if not tasks and self._active_tasks.get(key) is tasks:
self._active_tasks.pop(key, None) 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: 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) pending = self._pending_queues.get(key)
current = asyncio.current_task() current = asyncio.current_task()
tracked = self._active_tasks.get(key, set()) tracked = self._active_tasks.get(key, set())
# A command running on the session worker must keep its task and inbox # A command running on the session worker must keep its task and inbox
# registered until the worker finishes; only other tasks can be stopped. # registered until the worker finishes; only other tasks can be stopped.
owns_queue = current in tracked 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) 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) journal_session = await self.sessions.state.read(key)
journaled_followup_ids = ( journaled_followup_ids = (
tuple( tuple(
@@ -923,17 +928,13 @@ class AgentLoop:
if journal_session is not None if journal_session is not None
else () else ()
) )
for t in tasks: if tasks:
try: await asyncio.shield(asyncio.gather(*tasks, return_exceptions=True))
await t for task in tasks:
except asyncio.CancelledError: self._active_task_done(key, tracked, task)
pass
except Exception:
pass
if tasks and not owns_queue and pending is not None and self._pending_queues.get(key) is pending: 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 # A task cancelled before its first step never enters the worker's
# cleanup handler. Only reclaim that worker's original inbox. # cleanup handler. Only reclaim that worker's original inbox.
self._pending_queues.pop(key, None)
await self._cancel_pending_messages(key, pending, asyncio.CancelledError()) await self._cancel_pending_messages(key, pending, asyncio.CancelledError())
if journaled_followup_ids and journal_session is not None: if journaled_followup_ids and journal_session is not None:
# Explicit session cancellation owns the follow-ups accepted before # Explicit session cancellation owns the follow-ups accepted before
@@ -946,14 +947,12 @@ class AgentLoop:
async def discard_session(self, key: str) -> None: async def discard_session(self, key: str) -> None:
"""Stop active work for *key* and forget its cached session.""" """Stop active work for *key* and forget its cached session."""
with self.bus.admission.activity(): with self.bus.admission.activity(), self._pending_queues.controlling(key, discard=True):
self._discarding_sessions.add(key)
try: try:
await self.sessions.state.discard(key) await self.sessions.state.discard(key)
await self._cancel_active_tasks(key) await self._cancel_session_work(key)
finally: finally:
self.discard_session_file_state(key) self.discard_session_file_state(key)
self._discarding_sessions.discard(key)
def discard_session_file_state(self, key: str) -> None: def discard_session_file_state(self, key: str) -> None:
"""Forget ephemeral file-read state for a reset or removed session.""" """Forget ephemeral file-read state for a reset or removed session."""
@@ -1345,6 +1344,8 @@ class AgentLoop:
with self.bus.admission.activity(): with self.bus.admission.activity():
try: try:
await self._dispatch_inbound(msg) await self._dispatch_inbound(msg)
except SessionExecutionClosedError:
break
except (SessionOperationQueueFullError, SessionConflictError, ExecutionControlError) as exc: except (SessionOperationQueueFullError, SessionConflictError, ExecutionControlError) as exc:
key = msg.session_key key = msg.session_key
logger.warning("Session input rejected for {}: {}", key, exc) logger.warning("Session input rejected for {}: {}", key, exc)
@@ -1398,7 +1399,7 @@ class AgentLoop:
def _has_pending_work(self) -> bool: def _has_pending_work(self) -> bool:
return 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.bus.has_pending_events or self._active_tasks or self._background_tasks
or self._close_lock.locked() or self._close_lock.locked()
or self.subagents.has_pending_work or self._exec_session_manager.has_pending_work or self.subagents.has_pending_work or self._exec_session_manager.has_pending_work
@@ -1434,50 +1435,41 @@ class AgentLoop:
return pending_msg return pending_msg
async def _enqueue_session_message(self, msg: InboundMessage) -> None: async def _enqueue_session_message(self, msg: InboundMessage) -> None:
self._pending_queues.check_admission()
self.bus.admission.check() self.bus.admission.check()
session_key = msg.session_key session_key = msg.session_key
if not self.subagents.accepts_result(msg, session_key): if not self.subagents.accepts_result(msg, session_key):
return 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) 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: if pending is not None:
pending.put_nowait(msg) pending.put_nowait(msg)
return return
new_pending: asyncio.Queue[InboundMessage] = asyncio.Queue() new_pending = SessionInbox()
new_pending.put_nowait(msg) 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)) task = asyncio.create_task(self._run_session_queue(session_key, new_pending))
self._track_active_task(session_key, task) self._track_active_task(session_key, task)
async def _run_session_queue( async def _run_session_queue(
self, self,
session_key: str, session_key: str,
pending: asyncio.Queue[InboundMessage], pending: SessionInbox,
) -> None: ) -> None:
try: try:
await self._pending_queues.wait_for_controls(session_key)
while self._pending_queues.get(session_key) is pending: while self._pending_queues.get(session_key) is pending:
try: item = pending.next_turn()
item = pending.get_nowait() if item is None:
except asyncio.QueueEmpty: break
# 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)
session = self.sessions.state.peek_header(session_key) session = self.sessions.state.peek_header(session_key)
log_content = session is None or ( log_content = session is None or (
session.policy.persist and session.policy.log_content session.policy.persist and session.policy.log_content
@@ -1497,20 +1489,18 @@ class AgentLoop:
await self._cancel_pending_messages(session_key, pending, exc) await self._cancel_pending_messages(session_key, pending, exc)
raise raise
finally: finally:
owns_queue = self._pending_queues.get(session_key) is pending self._pending_queues.detach(session_key, pending)
if owns_queue:
self._pending_queues.pop(session_key, None)
async def _cancel_pending_messages( async def _cancel_pending_messages(
self, self,
session_key: str, session_key: str,
pending: asyncio.Queue[InboundMessage], pending: SessionInbox,
error: asyncio.CancelledError, error: asyncio.CancelledError,
) -> None: ) -> None:
for msg in self._deferred_automation_turns.pop(session_key, []): # End admission before publishing any cancellation notifications. Those
pending.put_nowait(msg) # callbacks can yield to another submitter for the same session key.
while not pending.empty(): self._pending_queues.detach(session_key, pending)
item = pending.get_nowait() for item in pending.drain():
for coordinator in self._automation_turn_coordinators: for coordinator in self._automation_turn_coordinators:
coordinator.complete(item, error=error) coordinator.complete(item, error=error)
if item.channel != "system" and self.commands.requires_session_queue(command_text(item)): 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, # shutdown keeps the durable checkpoint untouched instead,
# allowing RecoveryCoordinator to offer Continue safely. # allowing RecoveryCoordinator to offer Continue safely.
if ( if (
session_key in self._discarding_sessions self._pending_queues.is_discarding(session_key)
or self._preserve_inflight_turns_on_shutdown or self._preserve_inflight_turns_on_shutdown
): ):
raise exc raise exc
@@ -1661,6 +1651,8 @@ class AgentLoop:
await self._aclose_unlocked() await self._aclose_unlocked()
async def _aclose_unlocked(self) -> None: async def _aclose_unlocked(self) -> None:
self._pending_queues.close_admission()
self._running = False
errors: list[BaseException] = [] errors: list[BaseException] = []
active_task_groups = getattr(self, "_active_tasks", {}) active_task_groups = getattr(self, "_active_tasks", {})
current_task = asyncio.current_task() 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) 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_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) active_tasks = tuple(task for task in active_tasks if task is not current_task)
for task in active_tasks: self._request_worker_cancellation(active_tasks)
if not task.done():
task.cancel()
try: try:
if active_tasks: 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(): for key, pending in pending_queues.items():
if self._pending_queues.get(key) is pending: if self._pending_queues.get(key) is pending:
self._pending_queues.pop(key)
await self._cancel_pending_messages(key, pending, asyncio.CancelledError()) 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. # A scan can schedule archival while shutdown waits for it.
while self._background_tasks: while self._background_tasks:
await asyncio.gather(*self._background_tasks, return_exceptions=True) await asyncio.gather(*self._background_tasks, return_exceptions=True)
+106
View File
@@ -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))
-9
View File
@@ -143,15 +143,6 @@ async def cmd_stop(ctx: CommandContext) -> OutboundMessage:
loop = ctx.loop loop = ctx.loop
msg = ctx.msg msg = ctx.msg
total = await loop._cancel_active_tasks(ctx.key) # pyright: ignore[reportPrivateUsage] 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." content = f"Stopped {total} task(s)." if total else "No active task to stop."
return OutboundMessage( return OutboundMessage(
channel=msg.channel, chat_id=msg.chat_id, content=content, channel=msg.channel, chat_id=msg.chat_id, content=content,
+5 -13
View File
@@ -14,31 +14,23 @@ class LocalTriggerTurnCoordinator(AutomationTurnCoordinator):
self, self,
*, *,
enqueue: Callable[[InboundMessage], Awaitable[None]], enqueue: Callable[[InboundMessage], Awaitable[None]],
deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None: ) -> None:
super().__init__( super().__init__(
enqueue=enqueue, enqueue=enqueue,
turn_id=lambda msg: local_trigger_delivery_id(msg.metadata), turn_id=lambda msg: local_trigger_delivery_id(msg.metadata),
pending_id=_local_trigger_id, 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", missing_id_error="local trigger turn metadata must include a delivery_id",
duplicate_id_error=lambda delivery_id: ( duplicate_id_error=lambda delivery_id: (
f"local trigger delivery {delivery_id!r} is already pending" 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 local triggers waiting for or running in *session_key*."""
return self.pending_ids_for_session(session_key) return self.pending_ids_for_session(session_key, deferred)
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
def _local_trigger_id(msg: InboundMessage) -> str | None: def _local_trigger_id(msg: InboundMessage) -> str | None:
+2 -1
View File
@@ -9,6 +9,7 @@ import pytest
from agent.session_helpers import save_completed_subagent from agent.session_helpers import save_completed_subagent
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.agent.session_inbox import SessionInboxes
from nanobot.agent.turn_delivery import TurnDeliveryFactory from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
@@ -131,7 +132,7 @@ async def test_recovery_continuation_runs_without_a_sustained_goal(
loop._session_locks = {} loop._session_locks = {}
loop._concurrency_gate = None loop._concurrency_gate = None
loop._automation_turn_coordinators = [] loop._automation_turn_coordinators = []
loop._discarding_sessions = set() loop._pending_queues = SessionInboxes()
loop._preserve_inflight_turns_on_shutdown = False loop._preserve_inflight_turns_on_shutdown = False
loop.turn_delivery_factory = TurnDeliveryFactory(bus) loop.turn_delivery_factory = TurnDeliveryFactory(bus)
process_message = AsyncMock(return_value=OutboundMessage( process_message = AsyncMock(return_value=OutboundMessage(
+1 -5
View File
@@ -334,10 +334,6 @@ async def test_session_discard_control_cancels_active_turn(tmp_path, monkeypatch
loop = _loop(tmp_path, []) 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) loop.provider.chat_stream_with_retry = AsyncMock(side_effect=block_provider)
monkeypatch.setattr(loop, "aclose", AsyncMock()) monkeypatch.setattr(loop, "aclose", AsyncMock())
terminate_exec_sessions = AsyncMock(return_value=1) 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): with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(active_task, timeout=2) 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.sessions.get_cached(key) is None
assert loop._file_state_store.for_session(key) is not previous_file_state assert loop._file_state_store.for_session(key) is not previous_file_state
terminate_exec_sessions.assert_awaited_once_with(key) terminate_exec_sessions.assert_awaited_once_with(key)
+23 -21
View File
@@ -9,6 +9,7 @@ import pytest
from agent.runner_helpers import make_run_spec from agent.runner_helpers import make_run_spec
from agent.session_helpers import run_session, visible_message from agent.session_helpers import run_session, visible_message
from nanobot.agent.context import TranscriptInput from nanobot.agent.context import TranscriptInput
from nanobot.agent.session_inbox import SessionInbox
from nanobot.agent.tools.context import RequestContext from nanobot.agent.tools.context import RequestContext
from nanobot.config.schema import AgentDefaults from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import LLMResponse, ToolCallRequest 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) loop = _make_loop(tmp_path)
pending = asyncio.Queue(maxsize=20) pending = SessionInbox(maxsize=20)
loop._pending_queues["discord:c"] = pending loop._pending_queues.install("discord:c", pending)
run_task = asyncio.create_task(loop.run()) run_task = asyncio.create_task(loop.run())
msg = InboundMessage(channel="discord", sender_id="u", chat_id="c", content="follow-up") 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): async def test_websocket_followup_is_admitted_before_recovery_queue(tmp_path):
from nanobot.bus.events import InboundMessage 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 = MagicMock()
admission.admit = AsyncMock(return_value=True) admission.admit = AsyncMock(side_effect=admit)
loop = _make_loop(tmp_path, recovery_admission=admission) loop = _make_loop(tmp_path, recovery_admission=admission)
loop._pending_queues.install("websocket:chat", pending)
session_key = "websocket:chat"
pending = asyncio.Queue(maxsize=20)
loop._pending_queues[session_key] = pending
run_task = asyncio.create_task(loop.run())
msg = InboundMessage( msg = InboundMessage(
channel="websocket", channel="websocket",
sender_id="u", sender_id="u",
chat_id="chat", chat_id="chat",
content="new request", content="new request",
) )
await loop.bus.publish_inbound(msg)
queued_msg = await asyncio.wait_for(pending.get(), timeout=2) try:
admission.admit.assert_awaited_once_with(msg) await loop._dispatch_inbound(msg)
assert queued_msg.content == msg.content queued_msg = pending.get_nowait()
assert queued_msg.metadata["_recovery_followup_id"] admission.admit.assert_awaited_once_with(msg)
assert queued_msg.content == msg.content
loop.stop() assert queued_msg.metadata["_recovery_followup_id"]
await asyncio.wait_for(run_task, timeout=2) finally:
await loop.aclose()
@pytest.mark.asyncio @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 loop.turn_delivery_factory.route_policy = route_policy
session_key = "websocket:chat-1" session_key = "websocket:chat-1"
pending = asyncio.Queue(maxsize=20) pending = SessionInbox(maxsize=20)
loop._pending_queues[session_key] = pending loop._pending_queues.install(session_key, pending)
run_task = asyncio.create_task(loop.run()) run_task = asyncio.create_task(loop.run())
msg = InboundMessage( msg = InboundMessage(
@@ -1568,7 +1570,7 @@ async def test_session_worker_processes_leftovers_without_republishing(tmp_path)
loop = _make_loop(tmp_path) loop = _make_loop(tmp_path)
session_key = "cli:c" session_key = "cli:c"
pending = asyncio.Queue() pending = SessionInbox()
processed: list[str] = [] processed: list[str] = []
async def _process_message(msg, **_kwargs): async def _process_message(msg, **_kwargs):
@@ -1583,7 +1585,7 @@ async def test_session_worker_processes_leftovers_without_republishing(tmp_path)
chat_id="c", chat_id="c",
content=content, content=content,
)) ))
loop._pending_queues[session_key] = pending loop._pending_queues.install(session_key, pending)
await loop._run_session_queue(session_key, pending) await loop._run_session_queue(session_key, pending)
+271 -8
View File
@@ -7,6 +7,7 @@ import pytest
from agent.session_helpers import run_session, stop_loop, visible_message from agent.session_helpers import run_session, stop_loop, visible_message
from nanobot.agent.automation_turns import AutomationTurnError from nanobot.agent.automation_turns import AutomationTurnError
from nanobot.agent.loop import AgentLoop 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.context import current_request_context
from nanobot.agent.tools.cron import CronTool from nanobot.agent.tools.cron import CronTool
from nanobot.bus.events import InboundMessage, OutboundMessage 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"]) @pytest.mark.parametrize("kind", ["cron", "local_trigger"])
async def test_automation_turn_is_deferred_while_session_active(loop, kind): async def test_automation_turn_is_deferred_while_session_active(loop, kind):
key = "websocket:test" key = "websocket:test"
pending = asyncio.Queue() pending = SessionInbox()
loop._pending_queues[key] = pending loop._pending_queues.install(key, pending)
coordinator = loop._cron_turns if kind == "cron" else loop._local_trigger_turns
pending_ids = ( pending_ids = (
loop.pending_cron_job_ids_for_session loop.pending_cron_job_ids_for_session
if kind == "cron" if kind == "cron"
@@ -329,17 +329,17 @@ async def test_automation_turn_is_deferred_while_session_active(loop, kind):
try: try:
await loop.bus.publish_inbound(msg) await loop.bus.publish_inbound(msg)
async with asyncio.timeout(3): async with asyncio.timeout(3):
while not coordinator.deferred_queues.get(key): while not pending.deferred:
await asyncio.sleep(0) await asyncio.sleep(0)
assert pending.empty() assert pending.empty()
assert loop._active_tasks == {} assert loop._active_tasks == {}
assert coordinator.deferred_queues[key] == [msg] assert pending.deferred == (msg,)
assert pending_ids(key) == {"deferred"} assert pending_ids(key) == {"deferred"}
loop._process_message = AsyncMock(return_value=None) loop._process_message = AsyncMock(return_value=None)
await loop._run_session_queue(key, pending) await loop._run_session_queue(key, pending)
assert loop._process_message.await_args.args[0] is msg 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() assert pending_ids(key) == set()
finally: finally:
loop.stop() loop.stop()
@@ -466,7 +466,7 @@ async def test_cancelled_session_completes_queued_automation_waiters(loop):
)) ))
tasks.extend([cron, trigger]) tasks.extend([cron, trigger])
await asyncio.sleep(0) await asyncio.sleep(0)
assert len(loop._deferred_automation_turns["websocket:test"]) == 2 assert len(loop._pending_queues["websocket:test"].deferred) == 2
worker.cancel() worker.cancel()
with pytest.raises(asyncio.CancelledError): with pytest.raises(asyncio.CancelledError):
await worker await worker
@@ -583,6 +583,270 @@ async def test_cancel_preserves_followups_accepted_after_cancellation_started(lo
)] == ["new followup"] )] == ["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"]) @pytest.mark.parametrize("action", ["stop", "close"])
async def test_cancel_before_worker_runs_completes_automation(loop, action): async def test_cancel_before_worker_runs_completes_automation(loop, action):
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="unused")) 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 len(set(workers)) == 1
assert loop.bus.inbound_size == 0 assert loop.bus.inbound_size == 0
assert key not in loop._pending_queues assert key not in loop._pending_queues
assert key not in loop._deferred_automation_turns
finally: finally:
release.set() release.set()
for task in tasks: for task in tasks:
+11 -65
View File
@@ -1,76 +1,22 @@
import asyncio
from unittest.mock import AsyncMock, MagicMock from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
from nanobot.bus.events import OutboundMessage from nanobot.bus.events import InboundMessage
from nanobot.command.builtin import cmd_stop from nanobot.command.builtin import cmd_stop
from nanobot.command.router import CommandContext from nanobot.command.router import CommandContext
@pytest.mark.asyncio @pytest.mark.parametrize(("count", "content"), [
async def test_cmd_stop_drains_pending_queue(): (3, "Stopped 3 task(s)."),
mock_loop = MagicMock() (0, "No active task to stop."),
mock_loop._cancel_active_tasks = AsyncMock(return_value=1) ])
mock_loop._pending_queues = {} async def test_cmd_stop_reports_session_cancellation(count, content):
loop = MagicMock(_cancel_active_tasks=AsyncMock(return_value=count))
pending = asyncio.Queue() msg = InboundMessage(channel="websocket", sender_id="user", chat_id="chat", content="/stop")
await pending.put("msg1") ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw=msg.content, loop=loop)
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,
)
result = await cmd_stop(ctx) result = await cmd_stop(ctx)
assert isinstance(result, OutboundMessage) loop._cancel_active_tasks.assert_awaited_once_with(msg.session_key)
assert "Stopped 3 task(s)" in result.content assert (result.channel, result.chat_id, result.content) == (msg.channel, msg.chat_id, 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
+45 -59
View File
@@ -8,7 +8,7 @@ import subprocess
import sys import sys
import time import time
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import AsyncMock from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
from loguru import logger 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.registry import is_tool_error_result
from nanobot.agent.tools.shell import ExecTool from nanobot.agent.tools.shell import ExecTool
from nanobot.bus.queue import MessageBus
from nanobot.execution import processes from nanobot.execution import processes
from nanobot.providers.base import GenerationSettings
def _python_command(code: str) -> str: def _python_command(code: str) -> str:
@@ -985,54 +987,44 @@ def test_exec_session_manager_preserves_single_cleanup_error():
asyncio.run(run()) asyncio.run(run())
def test_agent_loop_shutdown_closes_exec_sessions(tmp_path): @pytest.fixture
async def run() -> None: def shutdown_loop(tmp_path) -> AgentLoop:
manager = ExecSessionManager() provider = MagicMock(aclose=AsyncMock(), generation=GenerationSettings())
tool = ExecTool(working_dir=str(tmp_path), timeout=30, session_manager=manager) return AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
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())
def test_agent_loop_shutdown_attempts_all_cleanup_after_errors(): async def test_agent_loop_shutdown_closes_exec_sessions(shutdown_loop, tmp_path, monkeypatch):
async def run() -> None: manager = shutdown_loop._exec_session_manager
loop = object.__new__(AgentLoop) close_subagents = AsyncMock(wraps=shutdown_loop.subagents.close)
loop.sessions = SimpleNamespace(state=SimpleNamespace(aclose=AsyncMock())) monkeypatch.setattr(shutdown_loop.subagents, "close", close_subagents)
loop._background_tasks = set() tool = ExecTool(working_dir=str(tmp_path), timeout=30, session_manager=manager)
loop.runtime_resolver = SimpleNamespace(aclose=AsyncMock()) initial = await tool.execute(
loop.subagents = SimpleNamespace( command=_waiting_shell_command("ready"),
close=AsyncMock(side_effect=RuntimeError("subagent cleanup failed")), yield_time_ms=100,
) )
loop._exec_session_manager = SimpleNamespace( sid = _session_id(initial)
close_all=AsyncMock(side_effect=OSError("exec cleanup failed")), process = manager._sessions[sid].process
)
with pytest.raises(BaseExceptionGroup) as exc_info:
await loop.aclose()
assert len(exc_info.value.exceptions) == 2 await shutdown_loop.aclose()
loop.subagents.close.assert_awaited_once() await shutdown_loop.aclose()
loop._exec_session_manager.close_all.assert_awaited_once()
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): 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()) asyncio.run(run())
def test_agent_loop_shutdown_preserves_single_cleanup_error(): async def test_agent_loop_shutdown_preserves_single_cleanup_error(shutdown_loop, monkeypatch):
async def run() -> None: close_subagents = AsyncMock(side_effect=RuntimeError("subagent cleanup failed"))
loop = object.__new__(AgentLoop) close_exec_sessions = AsyncMock(wraps=shutdown_loop._exec_session_manager.close_all)
loop.sessions = SimpleNamespace(state=SimpleNamespace(aclose=AsyncMock())) monkeypatch.setattr(shutdown_loop.subagents, "close", close_subagents)
loop._background_tasks = set() monkeypatch.setattr(shutdown_loop._exec_session_manager, "close_all", close_exec_sessions)
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()
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): async def test_exec_session_shared_kill_survives_cancelled_caller(monkeypatch):
@@ -0,0 +1,77 @@
--------------------------- MODULE CombinedLifecycle -------------------------
CONSTANT JoinControls
Keys == {"A", "B"}
VARIABLES phase, workers, controls, controlled, submitted
vars == <<phase, workers, controls, controlled, submitted>>
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 <<phase, submitted>>
FinishControl(k) ==
/\ k \in controls
/\ workers[k] \in {"none", "queued"}
/\ controls' = controls \ {k}
/\ UNCHANGED <<phase, workers, controlled, submitted>>
SubmitReplacement(k) ==
/\ phase = "open"
/\ workers[k] = "none"
/\ k \notin submitted
/\ workers' = [workers EXCEPT ![k] = "queued"]
/\ submitted' = submitted \cup {k}
/\ UNCHANGED <<phase, controls, controlled>>
StartReplacement(k) ==
/\ workers[k] = "queued"
/\ k \notin controls
/\ workers' = [workers EXCEPT ![k] = "running"]
/\ UNCHANGED <<phase, controls, controlled, submitted>>
FinishWorker(k) ==
/\ workers[k] \in {"running", "cancelling"}
/\ workers' = [workers EXCEPT ![k] = "none"]
/\ UNCHANGED <<phase, controls, controlled, submitted>>
BeginClose ==
/\ phase = "open"
/\ phase' = "closing"
/\ workers' = [k \in Keys |-> IF workers[k] = "none" THEN "none" ELSE "cancelling"]
/\ UNCHANGED <<controls, controlled, submitted>>
TearDown ==
/\ phase = "closing"
/\ \A k \in Keys: workers[k] = "none"
/\ ~JoinControls \/ controls = {}
/\ phase' = "closed"
/\ UNCHANGED <<workers, controls, controlled, submitted>>
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")
=============================================================================
+17
View File
@@ -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).
@@ -0,0 +1,5 @@
CONSTANT JoinControls = FALSE
SPECIFICATION Spec
INVARIANT CloseJoinsAllOwners
PROPERTY CloseEventuallyCompletes
CHECK_DEADLOCK FALSE
@@ -0,0 +1,5 @@
CONSTANT JoinControls = TRUE
SPECIFICATION Spec
INVARIANT CloseJoinsAllOwners
PROPERTY CloseEventuallyCompletes
CHECK_DEADLOCK FALSE