fix(agent): report background task failures
This commit is contained in:
1 parent
eb3fc07087
commit
aa117e7271
2 files changed
+86
-1
No files matched your search
+12
-1
@@ -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."""
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user