Skip to content

gh-159041: Fix asyncio task tracking during thread state clear - #159319

Open
mikegit123git wants to merge 3 commits into
python:mainfrom
mikegit123git:gh-159041-asyncio-task-finalizer
Open

mikegit123git wants to merge 3 commits into
python:mainfrom
mikegit123git:gh-159041-asyncio-task-finalizer

Conversation

@mikegit123git

@mikegit123git mikegit123git commented Oct 13, 2026 •

Copy link
Copy Markdown

Fixes #159041

Summary

PyThreadState_Clear() currently merges the thread state's asyncio task
list before the Py_CLEAR() calls run finalizers. A finalizer can create
an asyncio Task after the merge, leaving the Task linked to a thread state
that is subsequently freed.

Move the task-list merge after all finalizer-capable cleanup operations and
add a regression test for a Task created by a thread-state finalizer.

Tests

  • ./python -m test test_asyncio.test_free_threading -j0 (GIL build)
  • ./python -m test test_asyncio.test_free_threading -j0 (free-threaded build)
  • make patchcheck

@python-cla-bot

python-cla-bot Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@BHUVANSH855 BHUVANSH855 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kindly sign CLA, so that maintainers can begin with review process.

@BHUVANSH855 BHUVANSH855 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from the overview of changes, i just want to ask isn't this duplicate or overlaps with #159073

@mikegit123git

Copy link
Copy Markdown
Author

Thanks for pointing this out!

I took a closer look at #159073, and you're right that both PRs address the same underlying issue.

There are some differences in the implementation and regression tests. This PR focuses on thread-state cleanup and tests task tracking with an event loop running in another thread, while #159073 also handles interpreter shutdown and moves the task-list merge further toward the end of PyThreadState_Clear().

I'm happy to defer to the maintainers on whether to consolidate the changes. Thanks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

asyncio Task created from a finalizer during PyThreadState_Clear() registers into memory that is about to be freed (3.14 regression)

2 participants