Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork33.7k
Description
In#88831@vincentbernat pointed out that CPython only keeps weak references in_all_tasks, so a reference to aTask returned byloop.create_task has to be kept to be sure the task will not be killed with a "Task was destroyed but it is pending!" at some random point in time.
When shielding a task from cancellation withawait shield(something()),something continues to run when the containing coroutine is cancelled. As soon as that happens,something() is free-flying, i.e. there's no reference from user code anymore.shield itself has a bunch of circular strong references, but these shouldn't keep CPython from garbage-collecting the task. Hence, here the same problem occurs and the task might be killed unpredictably. Additionally, when running coroutines in parallel withgather andreturn_exceptions=False, an exception in one of the coroutines will leave remaining tasks free-flying. Also in this case, the remaining tasks might be killed unpredictably.
Hence, a warning in the documentation forcreate_task unfortunately does not suffice to solve the problem. Additionally, it has been brought up in#88831 that an API for fire-and-forget tasks (i.e. when the user doesn't want to keep a reference) would be nice.
As solution, I suggest to either
(1) introduce a further_pending_tasks set to keep strong references to all pending tasks. This would be the simplest solution also with respect to the API. In fact, a lot of dicussions on Stack Overflow (e.g.,here,here,here) already rely on this behavior (throwing away the reference returned bycreate_task), although it's wrong currently. Since the behaviour for free-flying tasks is unpredictable currently, it should not introduce any compatibility issues when making it predictable by preventing them from being garbage-collected.
(2) make sure there's always a chain of strong references from the most basic futures to the running tasks awaiting something. A quickgrep resulted in potential problems, e.g.,here andhere. This does not seem like a very robust approach, though.
(3) introduce the concept ofbackground tasks, i.e., tasks the user does not want to hold references to. The interface could look like suggested in#88831 (comment) . Tasks fromshield andgather could be automatically converted to such background tasks. Clearly, it would add complexity to the API, but the distinction between normal tasks and background tasks might potentially be beneficial also for other purposes. E.g., one might add an API call that waits for all background tasks to be completed.
My preferred solution would be (1).
Linked PRs
Metadata
Metadata
Assignees
Projects
Status