python / python/mypy

Add rule to detect potential bug caused by unheld references to asyncio.create_task

Open
#14,710 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-async
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Feature

Hi there,

I wanted to suggest adding a rule to MyPy to help detect a potential bug that can occur when using asyncio.create_task. If a developer doesn't hold a reference to the task object returned by create_task, the task may disappear without warning when Python runs garbage collection. This can lead to unpredictable failures in the code, which can be extremely difficult to debug.

References:
https://textual.textualize.io/blog/2023/02/11/the-heisenbug-lurking-in-your-async-code/
https://news.ycombinator.com/item?id=34754276

Pitch

I think adding a rule to MyPy that flags code which creates an asyncio task but doesn't hold a reference to it would be very helpful in preventing this bug from occurring. It would alert developers to the fact that they need to make sure they're holding a reference to the task object if they want to avoid this problem.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing mypy’s existing handling of asyncio.create_task and the linked reports describing tasks that are not held. Define which unheld-reference patterns the proposed rule should flag, how diagnostics should appear, and what test cases establish that the rule is complete.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.