Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Background tasks can disappear mid-execution #339

Closed
jakubsvehla opened this issue May 11, 2024 · 1 comment
Closed

Background tasks can disappear mid-execution #339

jakubsvehla opened this issue May 11, 2024 · 1 comment

Comments

@jakubsvehla
Copy link

jakubsvehla commented May 11, 2024

According to the asyncio documentation, it is necessary to keep a strong reference to a task to avoid it disappearing mid-execution because the event loop only keeps weak references to tasks. However, Quart uses a WeakSet to store the tasks which means that they can potentially be garbage collected before they finish. And users cannot keep their own strong references because the task is not returned.

The solution would be to use normal set instead of the WeakSet to keep the tasks in the background_tasks app instance variable and add task.add_done_callback(self.background_tasks.discard) to the add_background_task method after the task is created.

I tried to reproduce the bug but wasn't able to. I found several discussions where others are also not able to reproduce this behavior but nevertheless it's still recommended (both in the official docs and in the discussions) to keep the strong references (and use a callback to remove it) because it can happen in some cases that the task disappears before finishing.

Here are some discussions related to that:

I can also create a merge request for it but I won't be able to create a failing test for it since I wasn't able to reproduce it.

Environment:

  • Python version: 3.12
  • Quart version: 0.19.5
@pgjones
Copy link
Member

pgjones commented May 19, 2024

Thanks, fixed in 425f685 and released in 0.19.6

@pgjones pgjones closed this as completed May 19, 2024
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jun 3, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants