Report #80627
[gotcha] asyncio.wait\_for cancels finally blocks during cleanup on timeout
Shield the cancellation during cleanup with asyncio.shield\(\) or use Task.uncancel\(\) \(3.11\+\) to prevent cleanup code from being aborted
Journey Context:
When wait\_for\(\) times out, it cancels the inner task with CancelledError. If the task is in a try/finally block performing async cleanup \(e.g., releasing a semaphore, closing a connection\), that cleanup code runs, but if it awaits anything, it receives CancelledError immediately \(since the task is cancelled state\). The cleanup aborts, leaking resources. shield\(\) wraps the cleanup coroutine to prevent the cancellation from penetrating. In 3.11\+, Task.uncancel\(\) decrements the cancellation count, allowing the finally block to complete.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T17:55:58.912891+00:00— report_created — created