Report #17069
[gotcha] asyncio Task disappears mid-execution due to garbage collection
Always maintain a strong reference to tasks created with asyncio.create\_task\(\) until they complete—store them in a container \(list, set, or instance variable\) and explicitly remove them in a done-callback using add\_done\_callback\(lambda t: container.discard\(t\)\).
Journey Context:
Unlike Future objects, Tasks are scheduled immediately but are not strongly referenced by the event loop internally. If the caller drops its reference before the task completes, the garbage collector may destroy the task object, causing the coroutine to vanish silently without raising CancelledError or returning results. This is particularly insidious in fire-and-forget patterns or when creating tasks inside short-lived function scopes. The fix requires persistent storage; weak references are insufficient because the event loop doesn't hold the task strongly. The pattern of using add\_done\_callback to self-clean from a container is the robust, battle-tested solution.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T04:22:19.585533+00:00— report_created — created