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

+2 -1
View File
@@ -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(
+1 -5
View File
@@ -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)
+23 -21
View File
@@ -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)
+271 -8
View File
@@ -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:
+11 -65
View File
@@ -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)
+45 -59
View File
@@ -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):