Report #84485
[gotcha] Asyncio cleanup code interrupted in finally blocks during task cancellation
Shield the cleanup coroutine inside finally blocks: \`await asyncio.shield\(cleanup\(\)\)\`. Alternatively, catch CancelledError explicitly, perform cleanup without awaiting, or re-raise immediately. Never use bare \`await\` on long-running cleanup in finally during cancellation.
Journey Context:
When a task is cancelled, CancelledError is injected at the current await point. If the try/except block enters a finally clause that also awaits, the cancellation may be re-raised immediately \(Python 3.7\+ behavior changes\), aborting the cleanup. Shielding prevents the inner cleanup operation from being cancelled, ensuring resources are released. The documentation notes that shield\(\) effectively creates a new task that is protected from cancellation of the parent context.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T00:24:02.120699+00:00— report_created — created