test(agent): close session input fixtures and share shutdown diagnostics

This commit is contained in:
Xubin Ren committed 2026-10-18 18:33:24 +08:00
1 parent 2756c6bb78
commit 90fcb7f903
3 files changed
+29 -27

No files matched your search

+14
View File
@@ -1,6 +1,7 @@
"""Session-worker completion helpers for integration tests.""" """Session-worker completion helpers for integration tests."""
import asyncio import asyncio
import faulthandler
import time import time
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
@@ -38,6 +39,19 @@ async def run_session(loop: AgentLoop, msg: InboundMessage) -> None:
await asyncio.gather(*loop._active_tasks[loop._effective_session_key(msg)]) await asyncio.gather(*loop._active_tasks[loop._effective_session_key(msg)])
async def stop_loop(loop: AgentLoop, worker: asyncio.Task[None], *, timeout: float) -> None:
"""Stop an integration loop, retaining native shutdown stacks on timeout."""
loop.stop()
try:
await asyncio.wait_for(worker, timeout=timeout)
except TimeoutError:
close_task = loop.sessions.state._close_task
if close_task is not None:
close_task.print_stack()
faulthandler.dump_traceback()
raise
def mock_session_manager(*_args, **_kwargs): def mock_session_manager(*_args, **_kwargs):
"""Model the asynchronous state boundary in scheduler-only unit tests.""" """Model the asynchronous state boundary in scheduler-only unit tests."""
from unittest.mock import AsyncMock, MagicMock from unittest.mock import AsyncMock, MagicMock
+2 -13
View File
@@ -1,13 +1,12 @@
"""Independent turns and internal controls retain their session inbox semantics.""" """Independent turns and internal controls retain their session inbox semantics."""
import asyncio import asyncio
import faulthandler
import threading import threading
from unittest.mock import AsyncMock, MagicMock from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
from agent.session_helpers import run_session from agent.session_helpers import run_session, stop_loop
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.tools.context import current_request_context from nanobot.agent.tools.context import current_request_context
@@ -705,14 +704,4 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop
replies.append((reply.chat_id, reply.metadata.get("message_id"))) replies.append((reply.chat_id, reply.metadata.get("message_id")))
assert replies == [("chat-a", "message-a")] assert replies == [("chat-a", "message-a")]
finally: finally:
loop.stop() await stop_loop(loop, worker, timeout=3)
try:
await asyncio.wait_for(worker, timeout=3)
except TimeoutError:
# Native Windows CI has timed out after the routing assertions.
# Preserve the deadline and expose the shielded storage drain.
close_task = loop.sessions.state._close_task
if close_task is not None:
close_task.print_stack()
faulthandler.dump_traceback()
raise
+13 -14
View File
@@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
from agent.session_helpers import stop_loop
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
@@ -13,19 +14,25 @@ from nanobot.runtime_context import public_history_message
from nanobot.session.session_messages import SESSION_MESSAGE_METADATA_KEY from nanobot.session.session_messages import SESSION_MESSAGE_METADATA_KEY
def _loop(tmp_path: Path) -> AgentLoop: @pytest.fixture
async def loop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "state")
provider = MagicMock(aclose=AsyncMock()) provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model" provider.get_default_model.return_value = "test-model"
provider.generation = SimpleNamespace(max_tokens=4096) provider.generation = SimpleNamespace(max_tokens=4096)
provider.chat_stream_with_retry = AsyncMock( provider.chat_stream_with_retry = AsyncMock(
return_value=LLMResponse(content="Reviewed", tool_calls=[], usage=None) return_value=LLMResponse(content="Reviewed", tool_calls=[], usage=None)
) )
return AgentLoop( agent = AgentLoop(
bus=MessageBus(), bus=MessageBus(),
provider=provider, provider=provider,
workspace=tmp_path, workspace=tmp_path,
model="test-model", model="test-model",
) )
try:
yield agent
finally:
await agent.aclose()
def _message(content: str = "Please review") -> InboundMessage: def _message(content: str = "Please review") -> InboundMessage:
@@ -50,11 +57,8 @@ def _message(content: str = "Please review") -> InboundMessage:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_session_message_runs_as_user_input_and_replies_on_target_route( async def test_session_message_runs_as_user_input_and_replies_on_target_route(
tmp_path: Path, loop: AgentLoop,
monkeypatch: pytest.MonkeyPatch,
) -> None: ) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "state")
loop = _loop(tmp_path)
loop.sessions.save(loop.sessions.get_or_create("telegram:target")) loop.sessions.save(loop.sessions.get_or_create("telegram:target"))
msg = _message() msg = _message()
@@ -82,11 +86,8 @@ async def test_session_message_runs_as_user_input_and_replies_on_target_route(
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_session_message_text_is_not_dispatched_as_a_slash_command( async def test_session_message_text_is_not_dispatched_as_a_slash_command(
tmp_path: Path, loop: AgentLoop,
monkeypatch: pytest.MonkeyPatch,
) -> None: ) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "state")
loop = _loop(tmp_path)
loop.sessions.save(loop.sessions.get_or_create("telegram:target")) loop.sessions.save(loop.sessions.get_or_create("telegram:target"))
task = asyncio.create_task(loop.run()) task = asyncio.create_task(loop.run())
try: try:
@@ -96,12 +97,10 @@ async def test_session_message_text_is_not_dispatched_as_a_slash_command(
assert response.content == "Reviewed" assert response.content == "Reviewed"
loop.provider.chat_stream_with_retry.assert_awaited_once() loop.provider.chat_stream_with_retry.assert_awaited_once()
finally: finally:
loop.stop() await stop_loop(loop, task, timeout=2)
await asyncio.wait_for(task, timeout=2)
async def test_path_followup_reaches_running_turn(tmp_path: Path) -> None: async def test_path_followup_reaches_running_turn(loop: AgentLoop) -> None:
loop = _loop(tmp_path)
first_call = asyncio.Event() first_call = asyncio.Event()
release = asyncio.Event() release = asyncio.Event()
calls = [] calls = []