Skip to content

Your lightweight open-source personal agent.

fix(agent): report background task failures

yu-xin-caa117e7271e0
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py
index 7d8cec93c..e8cc7e3b5 100644
--- a/nanobot/agent/loop.py
+++ b/nanobot/agent/loop.py
@@ -1681,11 +1681,22 @@ class AgentLoop:
if errors:
raise BaseExceptionGroup("failed to close agent resources", errors)
+ def _background_task_done(self, task: asyncio.Task[Any]) -> None:
+ self._background_tasks.discard(task)
+ if task.cancelled():
+ return
+ exception = task.exception()
+ if exception is not None:
+ logger.opt(exception=exception).error(
+ "Background task '{}' failed",
+ task.get_name(),
+ )
+
def schedule_background(self, coro: Coroutine[Any, Any, Any]) -> None:
"""Schedule a coroutine as a tracked background task (drained on shutdown)."""
task = asyncio.create_task(coro)
self._background_tasks.add(task)
- task.add_done_callback(self._background_tasks.discard)
+ task.add_done_callback(self._background_task_done)
def stop(self) -> None:
"""Stop the agent loop."""
diff --git a/tests/agent/test_task_cancel.py b/tests/agent/test_task_cancel.py
index 6e94ae657..252ec8b36 100644
--- a/tests/agent/test_task_cancel.py
+++ b/tests/agent/test_task_cancel.py
@@ -103,6 +103,80 @@ class TestActiveTaskTracking:
assert "test:c1" not in loop._active_tasks
+async def _wait_for_background_callbacks(loop) -> None:
+ for _ in range(10):
+ if not loop._background_tasks:
+ return
+ await asyncio.sleep(0)
+ raise AssertionError("background task callback did not run")
+
+
+class TestBackgroundTaskTracking:
+ @pytest.mark.asyncio
+ async def test_successful_background_task_is_removed(self, monkeypatch):
+ loop, _bus = _make_loop()
+ mock_logger = MagicMock()
+ monkeypatch.setattr("nanobot.agent.loop.logger", mock_logger)
+
+ loop.schedule_background(asyncio.sleep(0))
+ await _wait_for_background_callbacks(loop)
+
+ assert not loop._background_tasks
+ mock_logger.opt.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_failed_background_task_is_retrieved_and_logged(self, monkeypatch):
+ loop, _bus = _make_loop()
+ mock_logger = MagicMock()
+ monkeypatch.setattr("nanobot.agent.loop.logger", mock_logger)
+ failure = RuntimeError("background failure")
+ loop_errors: list[dict[str, object]] = []
+ event_loop = asyncio.get_running_loop()
+ previous_handler = event_loop.get_exception_handler()
+ event_loop.set_exception_handler(lambda _loop, context: loop_errors.append(context))
+
+ async def fail():
+ raise failure
+
+ try:
+ loop.schedule_background(fail())
+ task_name = next(iter(loop._background_tasks)).get_name()
+ await _wait_for_background_callbacks(loop)
+ finally:
+ event_loop.set_exception_handler(previous_handler)
+
+ assert not loop._background_tasks
+ assert not loop_errors
+ mock_logger.opt.assert_called_once_with(exception=failure)
+ mock_logger.opt.return_value.error.assert_called_once_with(
+ "Background task '{}' failed",
+ task_name,
+ )
+
+ @pytest.mark.asyncio
+ async def test_cancelled_background_task_is_removed_without_error(self, monkeypatch):
+ loop, _bus = _make_loop()
+ mock_logger = MagicMock()
+ monkeypatch.setattr("nanobot.agent.loop.logger", mock_logger)
+ started = asyncio.Event()
+ release = asyncio.Event()
+
+ async def wait_forever():
+ started.set()
+ await release.wait()
+
+ loop.schedule_background(wait_forever())
+ await started.wait()
+ task = next(iter(loop._background_tasks))
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ await _wait_for_background_callbacks(loop)
+
+ assert not loop._background_tasks
+ mock_logger.opt.assert_not_called()
+
+
class TestHandleStop:
@pytest.mark.asyncio
async def test_stop_no_active_task(self):