Skip to content

gh-158195: Defer critical section restoration after STW - #158678

Open
nascheme wants to merge 1 commit into
python:mainfrom
nascheme:gh-158195-defer-cs-acquire-after-stw
Open

nascheme wants to merge 1 commit into
python:mainfrom
nascheme:gh-158195-defer-cs-acquire-after-stw

Conversation

@nascheme

@nascheme nascheme commented Oct 3, 2026 •

Copy link
Copy Markdown
Member

In the free-threaded build, a thread that holds a critical section and requests a stop-the-world (STW) pause can deadlock against a thread that waits for STW while holding a lock that is not released on detach.

An example of a deadlock:

  • T1 holds TYPE_LOCK and requests STW (atomic GC, etc).
  • The STW mutex is held by someone else, T1 parks and detaches, which releases TYPE_LOCK.
  • T2 acquires TYPE_LOCK, pins it and requests STW. It parks behind T1.
  • T1 acquires the STW mutex, when STW is finished, _PyThreadState_Attach() resumes T1's critical section and blocks on TYPE_LOCK
  • T1 is waiting on TYPE_LOCK, T2 is waiting on the STW mutex. Deadlock.

This PR fixes the deadlock by resuming the critical section after the STW mutex is released. With this change, T1 will block reacquiring TYPE_LOCK, letting T2 complete its STW work first.

This is a change in behavior of the STW APIs. On the contended path, stop_the_world() already released the requester's critical sections (parking detaches). After this PR, they are released until start_the_world() returns rather than being re-acquired when stop_the_world() returns. This is observable to code that takes a critical section itself, calls STW directly, and relies on continuous ownership after the restart.

Note: this PR was created with the assistance of AI agents (Claude and GPT models).

Restore critical sections *after* releasing the stop-the-world mutex,
rather than before.  This prevents deadlocks if there is a pinned mutex,
e.g. as done by type_lock_prevent_release().
@nascheme

nascheme commented Oct 3, 2026

Copy link
Copy Markdown
Member Author

CC @colesbury this could use your expert review. I explored a few different fixes for this deadlock and this seems like the best approach.

@nascheme
nascheme requested a review from colesbury October 3, 2026 19:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs backport to 3.14 bugs and security fixes needs backport to 3.15 pre-release feature fixes, bugs and security fixes topic-free-threading type-bug An unexpected behavior, bug, or error

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant