Report #95674
[gotcha] asyncio.shield coroutine still gets cancelled during event loop shutdown or task cancellation
Shield prevents parent cancellation but not inner task cancellation; wrap critical cleanup in try/except CancelledError inside the shielded coroutine
Journey Context:
asyncio.shield creates a new Task that is protected from cancellation of the parent task, but this protection is not absolute. If the event loop is shutting down, or if the shielded task itself receives a cancel\(\) \(e.g., via wait\_for timeout or explicit cancellation\), it still raises CancelledError. Additionally, exceptions in shielded tasks must be explicitly awaited or they become unhandled task exceptions. The correct pattern for critical cleanup \(like database transactions\) is to use shield PLUS an inner try/except CancelledError to handle the case where the shielded task itself is cancelled, ensuring commit/rollback completes before re-raising.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T19:10:19.260607+00:00— report_created — created