diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index d1d8ae232..6b54fa601 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -452,6 +452,7 @@ class AgentLoop: ) self._idle_compact_check_interval_s = idle_compact_check_interval_seconds self._next_idle_compact_check_at = time.monotonic() + self._idle_compact_check_running = False if model_preset: self.set_model_preset(model_preset, publish_update=False) self.commands = CommandRouter() @@ -1413,12 +1414,13 @@ class AgentLoop: return result async def _check_expired_sessions_if_due(self) -> None: - if self.bus.admission.paused: + if self.bus.admission.paused or self._idle_compact_check_running: return now = time.monotonic() if now < self._next_idle_compact_check_at: return self._next_idle_compact_check_at = now + self._idle_compact_check_interval_s + self._idle_compact_check_running = True try: with self.bus.admission.activity(): await self.auto_compact.check_expired( @@ -1428,6 +1430,8 @@ class AgentLoop: ) except SessionOperationQueueFullError: logger.debug("Skipping idle archival while session storage is busy") + finally: + self._idle_compact_check_running = False async def run(self) -> None: """Run the agent loop, dispatching messages as tasks to stay responsive to /stop.""" @@ -1442,7 +1446,9 @@ class AgentLoop: async with asyncio.timeout(1.0): msg = await self.bus.consume_inbound() except asyncio.TimeoutError: - await self._check_expired_sessions_if_due() + # Storage may wait behind a turn that /stop needs to cancel. + if not self.bus.admission.paused: + self.schedule_background(self._check_expired_sessions_if_due()) continue except asyncio.CancelledError: # Preserve real task cancellation so shutdown can complete cleanly. @@ -1812,7 +1818,8 @@ class AgentLoop: if self._pending_queues.get(key) is pending: self._pending_queues.pop(key) await self._cancel_pending_messages(key, pending, asyncio.CancelledError()) - if self._background_tasks: + # A scan can schedule archival while shutdown waits for it. + while self._background_tasks: await asyncio.gather(*self._background_tasks, return_exceptions=True) except BaseException as exc: errors.append(exc) diff --git a/tests/agent/test_runtime_maintenance.py b/tests/agent/test_runtime_maintenance.py index 8a4371aa1..546c697b1 100644 --- a/tests/agent/test_runtime_maintenance.py +++ b/tests/agent/test_runtime_maintenance.py @@ -294,6 +294,99 @@ async def test_async_idle_scan_keeps_storage_work_owned(agent, monkeypatch): assert agent.bus.admission.paused +async def test_idle_storage_scan_does_not_delay_stop(agent, monkeypatch): + model_started, scan_started, release_scan = (asyncio.Event() for _ in range(3)) + original_list = agent.sessions.state.list_sessions + + async def chat(**kwargs): + model_started.set() + await asyncio.Future() + + async def list_sessions(): + scan_started.set() + await release_scan.wait() + return await original_list() + + agent.provider.chat_stream_with_retry = chat + monkeypatch.setattr(agent.sessions.state, "list_sessions", list_sessions) + consumer = asyncio.create_task(agent.run()) + try: + await agent.bus.publish_inbound(message()) + async with asyncio.timeout(5): + await model_started.wait() + await scan_started.wait() + await agent.bus.publish_inbound(message("/stop")) + async with asyncio.timeout(3): + while True: + reply = await agent.bus.consume_outbound() + if reply.content == "Stopped 1 task(s).": + break + assert not consumer.done() + assert not release_scan.is_set() + with pytest.raises(RuntimeBusyError): + with agent.maintenance(): + pytest.fail("pending idle scan was mistaken for an idle runtime") + finally: + release_scan.set() + agent.stop() + await asyncio.wait_for(consumer, timeout=5) + + +async def test_idle_tick_during_maintenance_does_not_start_scan(agent, monkeypatch): + async def idle_once(): + agent.stop() + raise asyncio.TimeoutError + + check = AsyncMock() + monkeypatch.setattr(agent.auto_compact, "check_expired", check) + monkeypatch.setattr(agent.bus, "consume_inbound", idle_once) + with agent.maintenance(): + await agent.run() + check.assert_not_awaited() + assert not agent._background_tasks + + +@pytest.mark.parametrize("scan_fails", [False, True]) +async def test_idle_scan_is_single_flight_and_drains_spawned_work(agent, monkeypatch, scan_fails): + entered, release, child_started, release_child = (asyncio.Event() for _ in range(4)) + + async def child(): + child_started.set() + await release_child.wait() + + async def scan(*args, **kwargs): + entered.set() + await release.wait() + agent.schedule_background(child()) + if scan_fails: + raise OSError("idle scan failed after scheduling archival") + + check = AsyncMock(side_effect=scan) + monkeypatch.setattr(agent.auto_compact, "check_expired", check) + agent.schedule_background(agent._check_expired_sessions_if_due()) + closing = None + try: + await asyncio.wait_for(entered.wait(), timeout=3) + agent._next_idle_compact_check_at = 0 + await asyncio.wait_for(agent._check_expired_sessions_if_due(), timeout=3) + check.assert_awaited_once() + closing = asyncio.create_task(agent.aclose()) + await asyncio.sleep(0) + assert not closing.done() + release.set() + await asyncio.wait_for(child_started.wait(), timeout=3) + # Shutdown cannot finish until this explicitly held child is released. + done, _ = await asyncio.wait((closing,), timeout=0.05) + assert not done + assert not agent._idle_compact_check_running + finally: + release.set() + release_child.set() + if closing is not None: + await asyncio.wait_for(closing, timeout=3) + assert not agent._background_tasks + + async def test_cancelled_exec_startup_stays_busy_until_cleanup_finishes(agent, tmp_path, monkeypatch): manager = agent._exec_session_manager entered, cancelling, release = (asyncio.Event() for _ in range(3))