Skip to content
Sarj Code Standards

no-unobserved-task-exception

Observe the outcome of every stored asyncio task.

Why

A failed task that nothing awaits, gathers or inspects reports its exception only as "Task exception was never retrieved" when it is garbage-collected: late, without the logging context of the code that started it, and never while a reference keeps it alive.

Fix

Give the task one owner that observes its outcome: await it, or gather it with return_exceptions=True where the owner stops; create it with TaskGroup.create_task inside the scope that waits for it; or add a done callback that checks task.cancelled() and logs task.exception() with the starting code's context. Returning the task or passing it to the component that joins it also observes it.

Examples

Before — flagged A stored task is only cancelled, so its failure is never retrieved
app/recorder.py
import asyncio
class Recorder:
def start(self) -> None:
self._upload = asyncio.create_task(self._send())
def stop(self) -> None:
self._upload.cancel()
async def _send(self) -> None:
await asyncio.sleep(1)
After — preferred The owner gathers the task when it stops
app/recorder.py
import asyncio
class Recorder:
def start(self) -> None:
self._upload = asyncio.create_task(self._send())
async def stop(self) -> None:
self._upload.cancel()
await asyncio.gather(self._upload, return_exceptions=True)
async def _send(self) -> None:
await asyncio.sleep(1)