Skip to content

Free-threading: stop-the-world from a callback under TYPE_LOCK can deadlock #158195

Closed

Description

@scasella

Bug description:

On free-threaded builds, the interpreter can deadlock when Python code running under an unpinned TYPE_LOCK stops the world, directly or through an automatic GC, while another thread holds TYPE_LOCK pinned and waits to stop the world. The callbacks are a metaclass mro() (from type_ready()) and a str-subclass class-dict key's __eq__ (from type_setattro()).

Observed on fresh free-threaded builds of main a000129 (which includes PR #152826), main 8c056c3 and 3.15 13b1659 (macOS arm64, Clang, 2026-09-25), and earlier on main 6757482, 3.15 2dafe2a and 3.14 1d8c9f8. The default build is not affected.

This is the same lock-order family as gh-158194 (PyType_Freeze()), gh-156910 and gh-155400, but a distinct bug. Those were fixed by pinning at C call sites, which cannot cover arbitrary Python code or the GC. The broader approach below might also cover gh-158194; gh-158194's pin does not fix this.

Reproducer (main, 3.15 and 3.14.4+)

Trimmed from the attached repro.py (mro bug):

import faulthandler, sys, threading, time
print("sys._is_gil_enabled() =", sys._is_gil_enabled())
if sys._is_gil_enabled() is not False:
    sys.exit("needs a free-threaded build with the GIL disabled")
faulthandler.dump_traceback_later(20, exit=True)   # dump stacks and exit if hung

def f(): pass

class Meta(type):
    def mro(cls):             # called by type_ready() with TYPE_LOCK held, not pinned
        f.__qualname__ = "f"  # stops the world (func_set_qualname)
        return type.mro(cls)

stop, errors = threading.Event(), []

def guarded(fn):
    def run():
        try: fn()
        except BaseException as e: errors.append(e); raise
    return run

def setter():
    while not stop.is_set():
        Meta("K", (), {})

def pinner():                 # type_set_bases(): pinned TYPE_LOCK, then stop-the-world
    class A: pass
    class B: pass
    class X(A): pass
    while not stop.is_set():
        X.__bases__ = (B,); X.__bases__ = (A,)

def contender():              # plain stop-the-world; keeps stw->mutex contended
    def g(): pass
    while not stop.is_set():
        g.__qualname__ = "g"

ts = [threading.Thread(target=guarded(fn)) for fn in (setter, pinner, contender) for _ in range(2)]
for t in ts: t.start()
time.sleep(5); stop.set()
for t in ts: t.join()
if errors: sys.exit(f"FAIL: {errors[0]!r}")
print("done")
  • Actual: the process hangs. faulthandler dumps the stacks after 20 s and exits with status 1.
  • Expected: done after about 5 s.

repro_realistic.py (ABC subclasses + functools.wraps + GC) and repro_dunder_pinner.py hang on main and 3.15 only: 3.14 (from 3.14.4, which backported type_lock_prevent_release()) pins only the __bases__/MRO path.

Native stacks of a hang

Stock main 8c056c3 (free-threaded debug, no patch), repro.py mro bug, captured with macOS sample (trimmed):

setter   type_ready_publish typeobject.c:9513 -> mro_internal typeobject.c:3641 -> [Python mro()]
         -> func_set_qualname funcobject.c:755 -> stop_the_world pystate.c:2475 -> _PyMutex_LockTimed
         -> _PyThreadState_Attach pystate.c:2305 -> _PyCriticalSection_Resume critical_section.c:152
         -> _PyMutex_LockTimed
pinner   type_set_bases typeobject.c:2002 -> stop_the_world pystate.c:2475 -> _PyMutex_LockTimed

These stacks are consistent with the lock-cycle diagnosis below; lock ownership is inferred from the code paths, not read from the samples.

Mechanism

  1. T1's callback under unpinned TYPE_LOCK stops the world and parks on a busy stw->mutex. Parking detaches T1, which releases TYPE_LOCK.
  2. T2 takes TYPE_LOCK pinned (e.g. __bases__ assignment) and parks on stw->mutex.
  3. stw->mutex is handed to T1, whose re-attach (_PyCriticalSection_Resume()) waits for TYPE_LOCK: ABBA.

A proposed approach, for specialist review

fix-{main,3.15,3.14}.diff change Python/pystate.c so that stop_the_world() never waits for a critical-section mutex while owning the stop-the-world locks: if the critical section cannot be resumed without blocking, it drops stw->mutex and the rwmutex, waits, and retries. Regression-tested candidate fix. Broader attachment, finalization, progress, and interaction concerns remain for specialist review:

  • Re-attaching with tstate->critical_section temporarily set to 0 around _PyThreadState_Attach(): every attachment outcome, including shutdown/finalization and free-threaded builds running with the GIL enabled.
  • Nested and two-mutex critical sections; pinned sections. Only the topmost critical section is restored, which matches what _PyCriticalSection_Resume() already does.
  • Global vs per-interpreter stop-the-world; progress under contention.
  • PR gh-151518: Avoid STW starvation of attaching threads #152826 (Free-threaded CPython can starve a thread reattaching during repeated stop-the-world GC #151518), merged on 2026-09-25, changes attach and the stop-the-world state machine. The bug still reproduces on main a000129, which includes it: repro.py mro bug hung 5/5 there with the same stack shape (stop_the_world now at pystate.c:2523). fix-main.diff applies cleanly to a000129 and completed 5/5, but the two changes still need review together; applying cleanly does not establish that they are compatible.
  • Maintainability: the try-resume could move into the critical-section implementation instead of duplicating its private representation in pystate.c.

Performance impact has not been measured. No failure was observed on the patched build tested (main 8c056c3 debug, exactly fix-main.diff): each configuration that hung on stock main debug ran 0/5 or 0/3 hung, and both regression tests passed 3/3.

Validation on fresh builds and environment

Fresh out-of-tree free-threaded builds of main 8c056c3 (stock, and with exactly the attached fix-main.diff, sha256 844eee86…) and 3.15 13b1659 (stock), run one at a time on 2026-09-25. A run counts as hung only when the process stopped using CPU and a native sample showed stacks consistent with the lock cycle above.

main debug stock patched
repro.py mro bug / strkey bug 5/5 / 5/5 hung 0/5 / 0/5 hung
repro.py mro gc, repro_realistic.py gc, repro_dunder_pinner.py mro bug 3/3 hung each 0/3 hung each
ctl modes 0/4 0/4
regression tests 3/3 hung (standalone) 3/3 pass (in-tree)

mro bug also hung on stock main release (5/5) and stock 3.15 debug (3/3). On main a000129 (after PR #152826, debug), repro.py mro bug hung 5/5 stock and completed 5/5 with fix-main.diff; a native sample of one stock hang had the same shape as above. test_free_threading, test_types and test_descr pass when patched. Not built: patched main release, patched 3.15 and 3.14 (fix-3.15.diff, fix-3.14.diff).

python -VV of the fresh stock builds:

Python 3.16.0a0 free-threading build (heads/val/main-base-dirty:8c056c3, Sep 25 2026, 08:58:37) [Clang 21.0.0 (clang-2100.3.34.2)]
Python 3.15.0rc2+dev free-threading build (heads/val/315-base-dirty:13b1659, Sep 25 2026, 09:07:27) [Clang 21.0.0 (clang-2100.3.34.2)]

Earlier stock builds (used for the older results below):

Python 3.16.0a0 free-threading build (heads/main-dirty:6757482, Sep 22 2026, 20:29:11) [Clang 21.0.0 (clang-2100.3.34.2)]
Python 3.15.0rc2+dev free-threading build (heads/3.15-dirty:2dafe2a, Sep 22 2026, 21:35:07) [Clang 21.0.0 (clang-2100.3.34.2)]
Python 3.14.7+ free-threading build (heads/3.14-dirty:1d8c9f8, Sep 22 2026, 20:25:42) [Clang 21.0.0 (clang-2100.3.34.2)]

The -dirty suffix comes from CPython's Makefile running git describe --dirty from the out-of-tree build directory, where git sees every tracked file as missing. All of these builds were made out-of-tree, and their source trees show no tracked changes; the fresh trees were verified clean after each build.

Older results, code locations, patch details and open questions

Attached files. Each reproducer prints sys._is_gil_enabled() and exits with status 2 unless it is False. A worker exception exits with status 3.

  • repro.py [mro|strkey] [bug|gc|ctl] [secs]: bug stops the world directly inside the callback, gc only allocates cycles (the automatic GC stops the world), and ctl is the control (no stop-the-world, GC disabled).
  • repro_dunder_pinner.py: the same, with X.__repr__ assignment as the pinned partner (main and 3.15).
  • repro_realistic.py [gc|bug]: ABC subclass creation plus functools.wraps plus GC (main and 3.15).
  • test_type_stw_deadlock.py: a standalone copy of the two regression tests in the diffs.

Older stock-build results. These are stock builds (no patch) of main @ 6757482, 3.15 @ 2dafe2a and 3.14 @ 1d8c9f8, run on 2026-09-25 with the reproducers as they were before the GIL check and the exception propagation were added (the stress logic is the same). CPU-time inactivity was used only to screen for a hang. A native sample was taken of the first hang in each cell; those samples had the same shape as the stacks above (with stop_the_world at pystate.c:2454 on 6757482).

Build repro.py mro bug repro.py strkey bug repro_realistic.py gc
main FT debug 2/2 hung 2/2 hung 1/1 hung
main FT release 2/2 hung 2/2 hung 2/2 hung
3.15 FT debug 2/2 hung 2/2 hung 2/2 hung
3.14 FT debug 2/2 hung 2/2 hung 0/2 (expected: not pinned on 3.14)

Control: repro.py mro ctl completed on main release. The standalone regression tests hung on stock main release. In the earlier investigation (2026-09-23, same stock commits), the gc modes of repro.py hung on all three branches, and repro_dunder_pinner.py hung on main and 3.15.

Earlier investigation (2026-09-23; stock main 6757482 / 3.15 2dafe2a / 3.14 1d8c9f8; earlier revision of the patch). Most of these patched builds were made before the attached diffs were finalized, so the exact source they were built from may differ.

  • All reproducer configurations that hang on stock builds completed on patched main debug and release, 3.15 debug and 3.14 debug.
  • The two new tests passed in 2.4–5.6 s.
  • test_free_threading, test_threading, test_gc, test_descr, test_capi and related suites passed on the patched debug builds.
  • After the diffs were finalized, patched main release was re-run: 2/2 repro.py mro bug and 3/3 regression-test runs completed.

Code locations.

Step main @ 6757482 3.15 @ 2dafe2a 3.14 @ 1d8c9f8
mro_invoke() calls Python mro() under unpinned TYPE_LOCK typeobject.c:3578 :3643 :3502
type_setattro() calls a str-subclass __eq__ under TYPE_LOCK :6715 :6872 :6317
stop_the_world() blocks on stw->mutex pystate.c:2454 :2423 :2387
Attach resumes the critical section pystate.c:2305 → critical_section.c:152 :2274 :2242
Pinned TYPE_LOCK then stop-the-world typeobject.c 672, 1712, 1908, 1974, 3903, 6401 686, 1782, 1978, 2044, 3968, 6558 set_tp_mro 647 only

The unpinned sites are unchanged at the current tips (checked 2026-09-25). stop_the_world() was reworked by PR #152826, but the hang remains on main after it. On 3.14, v3.14.3 has no type_lock_prevent_release() and v3.14.4 does (the backport of gh-145685). This is the same hand-off-after-detach hazard described in gh-144513.

How the patch works. A new stw_lock() replaces the direct PyMutex_Lock(&stw->mutex). If the thread has a resumable critical section and the fast path fails, it:

  1. detaches, which suspends its critical sections;
  2. takes stw->mutex without detaching;
  3. re-attaches without resuming;
  4. tries to resume the critical section with PyMutex_LockFast;
  5. on failure, releases stw->mutex and the rwmutex, blocks in _PyCriticalSection_Resume() while owning nothing, and retries.

A mutex pinned by type_lock_prevent_release() is not stored in the critical section, so pinned holders take the unchanged path. The rwmutex is released too, because holding it while waiting for TYPE_LOCK could still deadlock against a pending global stop-the-world such as os.fork().

Alternatives considered:

  • Call mro() outside TYPE_LOCK. This is incomplete: the str-key path and GC inside such code remain.
  • Never run Python code under TYPE_LOCK. This would be a large restructuring.
  • Disable hand-off for stw->mutex. This is not enough, because a consumed wake-up can still hang.
  • Pin at the callback sites. This is not possible across arbitrary Python code.

As noted above, the try-resume helpers could instead live in critical_section.c, for example as _PyCriticalSection_TryResume(), so that pystate.c does not depend on the critical section's private representation.

Open questions and gaps.

  • Starvation on the retry path is not ruled out.
  • Linux, Windows, subinterpreters and a real os.fork() racing this path were not tested.
  • How often real programs combine a Python-level mro() or a str-subclass class-dict key with a concurrent pinned type update is unknown.
  • 3.15.0 final is expected on 2026-10-01 (PEP 790). Deadlock caused by type_lock_prevent_release() #155400, from the same family, was marked release blocker. I leave any priority decision to the release manager.

How it was found

An audit of stop_the_world() callers for locks that are held across the wait.

CPython versions tested on:

3.14, 3.15, CPython main branch

Operating systems tested on:

macOS

Attachments

repro.py.txt
repro_dunder_pinner.py.txt
repro_realistic.py.txt
test_type_stw_deadlock.py.txt
fix-main.diff.txt
fix-3.15.diff.txt
fix-3.14.diff.txt

Linked PRs

Activity

  1. added
    type-bug
    interpreter-core
    on Sep 26, 2026
  2. picnixz commented on Sep 26, 2026

    @picnixz
    Member

    I personally don't find the reproducers actually realistic.

    Performance impact has not been measured

    Unfortunately, we need this.

    cc @ZeroIntensity

  3. scasella commented on Sep 26, 2026

    @scasella
    Author

    Thanks, both fair points. I've followed up on each. All runs below are on free-threaded builds of main @ 8c056c3, 3.15 @ 13b1659 and 3.14 @ 1d8c9f8, on macOS arm64.

    Realism. I agree the str-subclass key path is contrived: setattr normalizes the name to an exact str, so it's only reachable through the class namespace. Two other routes need less:

    1. No metaclass at all, through the class's dict mutex. repr(K.__dict__) holds the dict's critical section while calling the values' __repr__. If one of those triggers an automatic GC while another thread uses unittest.mock.patch.object(K, "__lt__", ...), the setter's apply_type_slot_updates() pins TYPE_LOCK and the dict mutex and waits for the stop-the-world, which closes the same cycle.

      • repro_dict_repr.py, run with no arguments, hangs 3/3 on main debug, 2/2 on main release and 2/2 on 3.15 debug.
      • 3.14 isn't affected (2/2 pass), since it doesn't pin on dunder assignment.
      • The attached patch fixes it (3/3 pass).
      • The native stacks show dict_repr → … → gc_collect_main → stop_the_world → _PyCriticalSection_Resume in one thread and type_setattro → update_slot_after_setattr → stop_the_world in another.

      The unpinned side here is dict_repr, not code in typeobject.c. Pinning more call sites can't close this: any critical section on a type's __dict__ that ends up running Python can play that role. That's why the patch handles it in stop_the_world().

    2. A Python mro() that does nothing unusual. Python-level mro() overrides do ship: PyGObject's GObjectMeta defines one (gi/types.py), so it runs for every GObject class, and pydantic's ModelMetaclass had one in 2.10.0–2.10.4.

      • repro_c3_mro.py uses a metaclass whose mro() only computes the C3 linearization in Python, with no stop-the-world of its own. Alongside it run one thread creating ordinary cyclic garbage and one defining ABC subclasses.
      • In its default 30 s run it hung 3/4 on main debug and 2/4 on main release, with an automatic GC inside mro_internal() in the stack.
      • It passed 3/3 with the patch, though at that base rate three passes don't show much.
      • I haven't tested PyGObject itself.

    Both are still stress tests, and I don't have evidence of this hitting a real application.

    Performance. I ran pyperf microbenchmarks of the stop-the-world paths the patch touches: gc.collect(), __qualname__ and __bases__ assignment, ABC subclass creation, and a stop-the-world inside mro(). They ran on release builds of main @ 8c056c3 with and without the patch, same flags, on an untuned M4 Pro.

    • Uncontended, two interleaved runs: the patched build's geometric mean was 1.02–1.04x slower. The same binary measured against itself varied by up to 1.03x (up to 9% per benchmark), so I can't detect a difference above noise.
      • Single-threaded, stop_the_world() still takes the rwmutex and stw->mutex before it finds no other threads. The __qualname__ row (29 ns stock vs 30 ns patched) therefore times exactly the lock path the patch changes.
      • The only extra work there is reading tstate->critical_section, plus a PyMutex_LockFast inside a critical section in place of the lock PyMutex_Lock would have taken.
    • With 2 or 6 contending threads, lock scheduling dominates. The sign flips between runs (1.21x slower, then 1.28x faster, at 2 threads), so I can't claim anything either way.

    pyperformance is running on both builds. I'll post the comparison, and note any benchmarks that don't run on 3.16t, when it finishes. The raw pyperf JSON is available if useful.

    Attachments:

    repro_dict_repr.py.txt
    repro_c3_mro.py.txt

  4. ZeroIntensity commented on Sep 27, 2026

    @ZeroIntensity
    Member

    Looking at fix-main.diff.txt, the proposed fix seems very invasive. We should fix the lock ordering issues in typeobject.c, not try to retrofit the critical section API to work with it.

    I think @colesbury or @nascheme should take a look at this.

  5. scasella commented on Sep 27, 2026

    @scasella
    Author

    One observation that may help: in every hang I've captured, the pinned side is in typeobject.c (type_set_bases, type_set_abstractmethods, apply_type_slot_updates), waiting for the stop-the-world while holding TYPE_LOCK pinned (plus the type's dict mutex for slot updates). The unpinned side can be outside it (dict_repr in repro_dict_repr.py). So a fix on the pinned side, not waiting for the stop-the-world while holding pinned mutexes, should cover both repros, whereas pinning more of the unpinned sites wouldn't.

    Happy to run the repros against any candidate patch on main and 3.15.

    For completeness, pyperformance for the current diff (92 of 97 benchmarks; dask, genshi, fastapi and both sqlalchemy benchmarks don't run on 3.16t): geometric mean 1.03x faster with the patch. I read that as run-to-run drift rather than an effect of the diff, since the speedups cluster early in the run order and the slowdowns late. There's no sign of a regression; the largest slowdown is tornado_http at 1.06x (±3 ms).

  6. nascheme commented on Oct 3, 2026

    @nascheme
    Member

    I came up with an alternative fix, less invasive and it seems safe to me.

    We should fix the lock ordering issues in typeobject.c, not try to retrofit the critical section API to work with it.

    I considered options along those lines but did not find a feasible one. Type structures are read very often and modified rarely, so reads need to be cheap, and the cost of synchronization should fall on writers. A mutex on the read side is not an option; it scales too badly.

    Atomics could work in principle. Relaxed loads are essentially free on x86-64 and ARM64, so the issue is not load cost but the extent of the changes. Every place that reads type members with a plain load (e.g. Py_TYPE(op)->tp_flags or a slot pointer) would need to use an atomic load instead. That affects the C API: inline header functions like PyType_HasFeature() and direct tp_* access in extensions and generated code (Cython). Already-compiled extensions would keep their plain loads, which would then formally race with the writers. Atomics also give no consistency across fields: a slot update currently changes several slots across a type and its subclasses as one step, and readers could then see a partial update.

  7. Gil-AdB commented on Nov 21, 2026

    @Gil-AdB

    AI disclosure. I used AI tools to read the CPython source, to write the two scripts below, and to run the experiments. I reviewed the scripts and the results.

    This comment adds a forced reproducer for the deadlock: a gdb script that opens the window in every run, with no sleep and no stress loop. It also gives two controls and results on 3.14.10, on the 3.14 branch with and without the backport (PR #161586), and on main. I hope it is useful as a check of the 3.14 backport.

    The window

    The deadlock needs this order of events (line numbers are 3.14.10):

    1. The contender C stops the world. It owns stw->mutex (pystate.c:2435) and waits for the other threads in the PyEvent_WaitTimed loop (pystate.c:2469).
    2. The setter S runs Meta.mro() from type_ready(), with TYPE_LOCK held and not pinned. It sets f.__defaults__, so func_set_defaults() stops the world, and S parks on stw->mutex. The park detaches S (parking_lot.c:354), and the detach suspends its critical section: TYPE_LOCK is free.
    3. The partner P runs X.__bases__ = (B,). type_set_bases() takes TYPE_LOCK, set_tp_mro() pins it (typeobject.c:647) and stops the world. P parks on stw->mutex, and TYPE_LOCK stays locked.
    4. P's park lets the world stop. C's start_the_world() unlocks stw->mutex. S waited more than 1 ms, so mutex_unpark() hands stw->mutex to S (lock.c:149).
    5. S re-attaches inside its park and calls _PyCriticalSection_Resume() (pystate.c:2269), which waits for TYPE_LOCK. P owns TYPE_LOCK and waits for stw->mutex, which S owns.

    Without help, the window is narrow. S must come to stw->mutex after C locks it, but before C's stop request suspends S at an eval-breaker check. P must be inside type_set_bases() (C code, no eval-breaker check) when the request comes, and C's stop-the-world must last until P parks.

    I first tried to force the order in Python, with events in the callbacks. That forces the outer order (C and P start only after S is in Meta.mro()), but not steps 1 to 3. Each Python-level wait detaches the thread, and a pending stop request suspends a detached thread until start_the_world(). A thread that runs bytecode suspends at its next eval-breaker check. Thus Python code cannot keep C's stop-the-world open until a named event in another thread.

    The reproducer

    Two files: the program gh158195_w1.py and the gdb script gh158195_gdb.py (below). The program names its threads setter, partner and contender, and gdb finds each thread by that name. You need a free-threaded build with debug symbols and gdb with Python support:

    ./configure --disable-gil OPT="-g -O2" && make -j
    gdb -q -nx -x gh158195_gdb.py --args ./python -X gil=0 gh158195_w1.py pinned
    

    gdb runs in non-stop mode. It stops one thread at a breakpoint and continues it when a named event occurs in another thread. The other threads keep running. No hold has a time limit:

    • h1: C at func_set_defaults, until P is held at h2. Otherwise C's stop request suspends P in Python code before type_set_bases().
    • h2: P at type_set_bases (before TYPE_LOCK), until two events occur. S is parked on stw->mutex (in _PySemaphore_Wait, after the detach), and C's stop loop has called PyEvent_WaitTimed 3 times after that park. Each of those calls comes after a 1 ms timeout of the previous one. Thus S's wait is more than 1 ms by CPython's own clock events, and the unlock hands stw->mutex to S.
    • h3: S at func_set_defaults (in Meta.mro(), with TYPE_LOCK held), until C is in its stop loop (PyEvent_WaitTimed).

    The script decides the result from the state, not from a time. When S parks on TYPE_LOCK, gdb stops all threads and reads the wait-for graph. Then it prints the two stacks, the mutex bits, the handed_off field of S's mutex_entry for stw->mutex, and whether P's critical section is pinned. If each thread waits for a mutex that only the other can unlock, the script prints VERDICT deadlock and leaves the threads stopped for inspection (thread apply all bt).

    Controls, with the same script:

    # the opposite order: P starts after C's stop-the-world has ended
    GH158195_ORDER=control gdb -q -nx -x gh158195_gdb.py --args ./python -X gil=0 gh158195_w1.py pinned-late
    # the same order, but P's stop-the-world does not pin TYPE_LOCK (Y has the metaclass Meta)
    gdb -q -nx -x gh158195_gdb.py --args ./python -X gil=0 gh158195_w1.py unpinned
    

    Both controls print done B. For a run without a terminal, GH158195_BATCH=1 makes gdb exit with status 86 on the deadlock and 0 when the program exits normally. gdb needs an open stdin in that mode, for example mkfifo in; exec 3<>in; GH158195_BATCH=1 gdb ... <&3.

    Note: on the 3.14 branch after 3.14.10 and on main, func_set_qualname() no longer stops the world. Thus the f.__qualname__ trigger of repro.py does not stop the world there. func_set_defaults() still stops the world on all of them, so the scripts use f.__defaults__.

    Results

    Free-threaded static builds (--disable-gil, OPT="-g -O2", GCC 12.2 on Debian 12), 10 runs per arm.

    Build aarch64 forced aarch64 controls (order / unpinned) x86_64 forced x86_64 controls (order / unpinned)
    3.14.10 (release tarball) 10/10 deadlock 10/10 done / 10/10 done 10/10 deadlock 10/10 done / 10/10 done
    3.14 branch f3eb3cc (base of PR #161586) 10/10 deadlock 10/10 done / 10/10 done 10/10 deadlock 10/10 done / 10/10 done
    PR #161586 head f31699d 10/10 done 10/10 done / 10/10 done 10/10 done 10/10 done / 10/10 done
    main 1822ff5 10/10 done 10/10 done / 10/10 done 10/10 done 10/10 done / 10/10 done
    • aarch64: Debian 12 container on an Apple silicon Mac, gdb 13.1. x86_64: Debian 13 VM (QEMU), gdb 16.3.
    • In each deadlock run, the script found the same cycle. The setter's mutex_entry for stw->mutex had handed_off=1, stw->mutex and TYPE_LOCK were both locked, and the partner's critical section was pinned. In all 40 deadlock runs, the contender also blocked on TYPE_LOCK after its stop-the-world (_Py_Specialize_ToBool -> _PyType_Validate).
    • In each forced run on the PR [3.14] gh-158195: Do not hold the type lock during stop-the-world (gh-160987) #161586 head and on main, the window opened in the same order. The setter parked on stw->mutex, h2 ended, and the partner parked on stw->mutex. Then the setter resumed its critical section without a wait for TYPE_LOCK.
    • Without gdb, the program completed in 20 of 20 runs on 3.14.10 on each machine.

    On main and with the backport, the forced order completes, because type_set_bases() no longer pins TYPE_LOCK. The partner's park releases TYPE_LOCK, so the setter can resume its critical section. The scripts did not find a new problem on main. They show that the backport removes this cycle under the forced order, while its base on the 3.14 branch still deadlocks.

    gh158195_w1.py
    """gh-158195: stop-the-world under an unpinned TYPE_LOCK against a pinned TYPE_LOCK holder.
    
    Free-threaded build only. Run alone, the program almost always ends with "done B": the window
    is a few microseconds wide. Run under gh158195_gdb.py, gdb holds each thread at a named point
    until a named event in another thread, and the window opens in every run.
    
        python3.14t -X gil=0 gh158195_w1.py [pinned|pinned-late|unpinned]
    
    Threads (the names are also the OS thread names, which gdb shows):
      setter     Meta("K", (), {}): type_ready() calls Meta.mro() with TYPE_LOCK held in a critical
                 section that is not pinned. Meta.mro() sets `go`, then sets f.__defaults__:
                 func_set_defaults() stops the world.
      partner    waits for `go`, then:
                   pinned:   X.__bases__ = (B,). type_set_bases() takes TYPE_LOCK, and set_tp_mro()
                             pins it (type_lock_prevent_release) and stops the world.
                   unpinned: Y.__bases__ = (B,). Y has the metaclass Meta, so type_set_bases()
                             calls Meta.mro(), which stops the world with TYPE_LOCK not pinned.
                             This is the control of the pin.
                   pinned-late: as pinned, but the partner first waits for `contender_done`,
                             which the contender sets after its stop-the-world. This is the
                             control of the order.
      contender  waits for `go`, then g.__defaults__ = None: a plain stop-the-world that holds
                 stw->mutex while the setter comes to it.
      main       after the contender has ended, h.__defaults__ = None: one more stop-the-world.
    
    func_set_defaults() stops the world in 3.14.10, on the 3.14 branch and on main. (On the 3.14
    branch and on main, func_set_qualname() no longer stops the world.)
    
    The deadlock (gh158195_gdb.py forces this order):
      1. The contender owns stw->mutex and waits for the world to stop.
      2. The setter parks on stw->mutex. The park detaches the thread, which suspends its critical
         section: TYPE_LOCK is free.
      3. The partner takes TYPE_LOCK, pins it, and parks on stw->mutex behind the setter.
      4. The contender's start_the_world() unlocks stw->mutex. The setter waited more than 1 ms, so
         the unlock hands stw->mutex to the setter (TIME_TO_BE_FAIR_NS, Python/lock.c).
      5. The setter's re-attach (_PyCriticalSection_Resume) waits for TYPE_LOCK. The partner keeps
         TYPE_LOCK pinned while it waits for stw->mutex, which the setter owns.
    
    gc is off, so no automatic collection stops the world at another point.
    """
    
    import gc
    import sys
    import threading
    
    if sys._is_gil_enabled():
        sys.exit("needs a free-threaded build with the GIL disabled (-X gil=0)")
    gc.disable()
    
    
    def f():
        pass
    
    
    def f2():
        pass
    
    
    def g():
        pass
    
    
    def h():
        pass
    
    
    go = threading.Event()
    contender_done = threading.Event()
    
    
    class Meta(type):
        def mro(cls):
            # type_ready() and type_set_bases() call this with TYPE_LOCK held (not pinned).
            if cls.__name__ == "K":
                go.set()  # release the contender and the partner
                f.__defaults__ = None  # stops the world
            else:
                f2.__defaults__ = None  # stops the world
            return type.mro(cls)
    
    
    class A:
        pass
    
    
    class B:
        pass
    
    
    class X(A):
        pass
    
    
    class Y(A, metaclass=Meta):
        pass
    
    
    mode = sys.argv[1] if len(sys.argv) > 1 else "pinned"
    if mode not in ("pinned", "pinned-late", "unpinned"):
        sys.exit("mode: pinned, pinned-late or unpinned")
    
    
    def contender():
        go.wait()
        g.__defaults__ = None
        contender_done.set()
    
    
    def partner():
        go.wait()
        if mode == "pinned-late":
            contender_done.wait()
        if mode == "unpinned":
            Y.__bases__ = (B,)
        else:
            X.__bases__ = (B,)
    
    
    def setter():
        Meta("K", (), {})
    
    
    # Warm-up, one thread at a time. A type-cache miss takes TYPE_LOCK (find_name_in_mro), and the
    # setter holds TYPE_LOCK inside the window, so a miss in another thread would make it wait for
    # TYPE_LOCK before its own step. Start one thread first, so that the thread-start code is warm.
    g.__defaults__ = None
    X.__bases__
    A.__name__
    Meta("K0", (), {})
    X.__bases__ = (A,)
    Y.__bases__ = (A,)
    warm = threading.Thread(target=lambda: None, name="warm")
    warm.start()
    warm.join()
    
    tc = threading.Thread(target=contender, name="contender")
    tp = threading.Thread(target=partner, name="partner")
    ts = threading.Thread(target=setter, name="setter")
    tc.start()
    tp.start()
    ts.start()
    tc.join()
    h.__defaults__ = None  # main's stop-the-world
    ts.join()
    tp.join()
    cls = Y if mode == "unpinned" else X
    print("done", cls.__bases__[0].__name__)
    gh158195_gdb.py
    # gh-158195: force the deadlock window with gdb in non-stop mode, on an unmodified free-threaded
    # build with debug symbols (configure --disable-gil, OPT="-g -O2" or a debug build).
    #
    #   gdb -q -nx -x gh158195_gdb.py --args ./python -X gil=0 gh158195_w1.py pinned
    #
    # Arms (the order comes from GH158195_ORDER, the program mode from the last argument):
    #   forced           GH158195_ORDER=forced (default)  program mode pinned       deadlock
    #   control-order    GH158195_ORDER=control           program mode pinned-late  "done B"
    #   control-unpinned GH158195_ORDER=forced            program mode unpinned     "done B"
    #
    # Every hold ends at a named event in another thread. No hold has a time limit. gdb stops one
    # thread at a breakpoint (non-stop mode: the other threads keep running) and continues it when
    # the event comes. If the event came first, the thread does not stop.
    #
    # Forced order (the bounding events of the window):
    #   h1  contender at func_set_defaults (before its stop-the-world)
    #         until the partner is held at h2. Otherwise the stop request would suspend the partner
    #         in Python code before type_set_bases().
    #   h2  partner at type_set_bases (before TYPE_LOCK)
    #         until the setter is parked on stw->mutex (in _PySemaphore_Wait, after the detach that
    #         released TYPE_LOCK) AND the contender's stop-the-world loop has called
    #         PyEvent_WaitTimed 3 more times after that park. Each of those calls follows a 1 ms
    #         timeout of the previous one, so the setter's wait is > 1 ms by CPython's own clock
    #         events, and the unlock hands stw->mutex to the setter (TIME_TO_BE_FAIR_NS).
    #   h3  setter at func_set_defaults (in Meta.mro(), TYPE_LOCK held, not pinned)
    #         until the contender is in its stop-the-world loop (PyEvent_WaitTimed after h1), so
    #         that stw->mutex is owned when the setter comes to it.
    # The partner is held attached at h2, so the contender's stop-the-world cannot end before the
    # partner parks: the partner takes TYPE_LOCK and parks on stw->mutex while the setter is parked.
    #
    # Control order (program mode pinned-late): h1 until the setter is held at h3; h3 as above;
    # h2 until the setter owns stw->mutex again (its own PyEvent_WaitTimed or
    # _PyEval_StartTheWorld after h3). The partner takes TYPE_LOCK after the setter has resumed it.
    #
    # Verdict, by state, not by time: when the setter parks on TYPE_LOCK (in _PySemaphore_Wait),
    # gdb stops all threads and reads the wait-for graph:
    #   - setter: parked on TYPE_LOCK inside _PyCriticalSection_Resume, under its park on
    #     stw->mutex whose mutex_entry has handed_off == 1 (the setter owns stw->mutex);
    #   - partner: parked on stw->mutex under stop_the_world and type_set_bases, with its
    #     TYPE_LOCK critical section pinned (_cs_mutex == NULL) and TYPE_LOCK locked.
    # Each waits for a mutex that only the other can unlock: a deadlock. If the graph has no
    # cycle (for example a wake without hand-off), gdb continues all threads.
    # With GH158195_BATCH=1, gdb kills the program after the verdict and exits: 86 deadlock,
    # 0 program exited with status 0, 1 anything else. Without it, gdb leaves the threads stopped
    # for inspection (thread apply all bt).
    import os
    
    import gdb
    
    ORDER = os.environ.get("GH158195_ORDER", "forced")
    BATCH = os.environ.get("GH158195_BATCH") == "1"
    POLLS = 3  # contender stop-loop calls after the setter's park (each follows a 1 ms timeout)
    ROLES = {"setter": "S", "partner": "P", "contender": "C"}
    
    for cmd in ("set non-stop on", "set pagination off", "set confirm off",
                "set print thread-events off", "set breakpoint pending off"):
        gdb.execute(cmd)
    
    st = {
        "seq": 0,
        "ev": [],         # (seq, role, event)
        "held": {},       # hold name -> thread number
        "done": set(),    # hold names that have ended (or never stopped)
        "last_park": {},  # role -> address of its last _PyParkingLot_Park
        "s_parked_stw_seq": None,
        "c_polls_after": 0,
        "verdict": None,
        "checking": False,
    }
    addr = {}
    
    
    def log(msg):
        print("gh158195: " + msg, flush=True)
    
    
    def role():
        t = gdb.selected_thread()
        return ROLES.get(t.name or "")
    
    
    def ev(r, name):
        st["seq"] += 1
        st["ev"].append((st["seq"], r, name))
        return st["seq"]
    
    
    def seen(r, name, after=0):
        return any(s > after and rr == r and n == name for s, rr, n in st["ev"])
    
    
    def first_seq(r, name):
        for s, rr, n in st["ev"]:
            if rr == r and n == name:
                return s
        return None
    
    
    def resolve_addresses():
        if addr:
            return
        interp = "_PyRuntime.interpreters.main"
        addr["stw"] = int(gdb.parse_and_eval("(unsigned long)&%s->stoptheworld.mutex" % interp))
        addr["type"] = int(gdb.parse_and_eval("(unsigned long)&%s->types.mutex" % interp))
    
    
    # Hold conditions: name -> (role, breakpoint, until()).
    def until_h1():
        if ORDER == "control":
            return seen("S", "hold:h3")
        return seen("P", "hold:h2")
    
    
    def until_h2():
        if ORDER == "control":
            rel = first_seq("S", "release:h3")
            return rel is not None and (seen("S", "PyEvent_WaitTimed", rel)
                                        or seen("S", "_PyEval_StartTheWorld", rel))
        return st["s_parked_stw_seq"] is not None and st["c_polls_after"] >= POLLS
    
    
    def until_h3():
        rel = first_seq("C", "release:h1")
        return rel is not None and seen("C", "PyEvent_WaitTimed", rel)
    
    
    HOLDS = {
        "h1": ("C", "func_set_defaults", until_h1),
        "h2": ("P", "type_set_bases", until_h2),
        "h3": ("S", "func_set_defaults", until_h3),
    }
    
    
    def release_ready():
        for name, num in list(st["held"].items()):
            if HOLDS[name][2]():
                del st["held"][name]
                st["done"].add(name)
                r = HOLDS[name][0]
                ev(r, "release:" + name)
                log("release %s (%s, thread %d)" % (name, r, num))
                gdb.post_event(lambda n=num: resume(n))
    
    
    def resume(num):
        for t in gdb.selected_inferior().threads():
            if t.num == num and t.is_valid() and t.is_stopped():
                t.switch()
                gdb.execute("continue &")
    
    
    class Bp(gdb.Breakpoint):
        def __init__(self, spec):
            super().__init__(spec, internal=True)
            self.spec = spec
    
        def stop(self):
            r = role()
            if r is None or st["verdict"]:
                return False
            resolve_addresses()
            stop = self.on_hit(r)
            release_ready()
            return stop
    
        def on_hit(self, r):
            ev(r, self.spec)
            for name, (hr, spec, until) in HOLDS.items():
                if hr == r and spec == self.spec and name not in st["done"] \
                        and name not in st["held"]:
                    if until():
                        st["done"].add(name)
                        ev(r, "release:" + name)  # the event came first: no stop
                        log("pass %s (%s at %s): its event came first" % (name, r, spec))
                        return False
                    st["held"][name] = gdb.selected_thread().num
                    ev(r, "hold:" + name)
                    log("hold %s (%s at %s)" % (name, r, spec))
                    return True
            return False
    
    
    class WaitBp(Bp):
        def on_hit(self, r):
            ev(r, self.spec)
            if r == "C" and st["s_parked_stw_seq"] is not None:
                st["c_polls_after"] += 1
            return False
    
    
    class ParkBp(Bp):
        def on_hit(self, r):
            a = int(gdb.parse_and_eval("(unsigned long)addr"))
            st["last_park"][r] = a
            which = {addr["stw"]: "stw", addr["type"]: "TYPE_LOCK"}.get(a, hex(a))
            ev(r, "park:" + which)
            return False
    
    
    class SemaBp(Bp):
        def on_hit(self, r):
            older = gdb.selected_frame().older()
            if older is None or older.name() != "_PyParkingLot_Park":
                return False
            a = st["last_park"].get(r)
            if a == addr["stw"]:
                s = ev(r, "parked:stw")
                if r == "S" and seen("S", "release:h3") and st["s_parked_stw_seq"] is None:
                    st["s_parked_stw_seq"] = s
                    log("setter parked on stw->mutex")
                elif r == "P":
                    log("partner parked on stw->mutex")
            elif a == addr["type"]:
                ev(r, "parked:TYPE_LOCK")
                if r == "S" and seen("S", "release:h3") and not st["checking"]:
                    st["checking"] = True
                    log("setter parked on TYPE_LOCK: stop all threads and read the wait-for graph")
                    gdb.post_event(lambda: gdb.execute("interrupt -a"))
                    return True
            return False
    
    
    Bp("func_set_defaults")
    Bp("type_set_bases")
    Bp("_PyEval_StartTheWorld")
    WaitBp("PyEvent_WaitTimed")
    ParkBp("_PyParkingLot_Park")
    SemaBp("_PySemaphore_Wait")
    
    
    def frames_of(thread):
        thread.switch()
        out = []
        f = gdb.newest_frame()
        while f is not None:
            out.append(f)
            f = f.older()
        return out
    
    
    def var(frame, name):
        try:
            v = frame.read_var(name)
            if v.is_optimized_out:
                return None
            return v
        except (ValueError, gdb.error):
            return None
    
    
    def park_info(frame):
        """(address, park_arg) of a _PyParkingLot_Park frame, from its stack struct `wait`."""
        w = var(frame, "wait")
        if w is not None:
            return int(w["addr"]), int(w["park_arg"])
        a = var(frame, "addr")
        p = var(frame, "park_arg")
        return (int(a) if a is not None else None), (int(p) if p is not None else None)
    
    
    def analyse():
        threads = {ROLES.get(t.name or ""): t for t in gdb.selected_inferior().threads()}
        S, P = threads.get("S"), threads.get("P")
        bits = lambda a: int(gdb.parse_and_eval("*(unsigned char *)%d" % a))
        stw_bits, type_bits = bits(addr["stw"]), bits(addr["type"])
        log("stw->mutex _bits=%d, TYPE_LOCK _bits=%d (1 = locked, 2 = has parked)"
            % (stw_bits, type_bits))
        facts = {}
        if S is not None:
            fs = frames_of(S)
            names = [f.name() for f in fs]
            parks = [park_info(f) for f in fs if f.name() == "_PyParkingLot_Park"]
            facts["S_parked_type"] = bool(parks) and parks[0][0] == addr["type"]
            facts["S_in_resume"] = "_PyCriticalSection_Resume" in names
            outer = [p for p in parks[1:] if p[0] == addr["stw"]]
            handed = None
            if outer and outer[0][1]:
                handed = int(gdb.parse_and_eval(
                    "*(int *)(%d + sizeof(PyTime_t))" % outer[0][1]))
            facts["S_handed_off_stw"] = handed == 1
            log("setter stack: " + " <- ".join(n or "?" for n in names[:14]))
            log("setter: parks %s, stw->mutex mutex_entry.handed_off=%s"
                % ([(hex(a) if a else a) for a, _ in parks], handed))
        if P is not None:
            fp = frames_of(P)
            names = [f.name() for f in fp]
            parks = [park_info(f) for f in fp if f.name() == "_PyParkingLot_Park"]
            facts["P_parked_stw"] = bool(parks) and parks[0][0] == addr["stw"]
            facts["P_in_stw_from_set_bases"] = "stop_the_world" in names and \
                "type_set_bases" in names
            pinned = None
            for f in fp:
                if f.name() == "type_set_bases":
                    cs = var(f, "_py_cs")
                    if cs is not None:
                        pinned = int(cs["_cs_mutex"]) == 0
            facts["P_pinned"] = pinned is True
            log("partner stack: " + " <- ".join(n or "?" for n in names[:14]))
            log("partner: parks %s, TYPE_LOCK critical section pinned=%s"
                % ([(hex(a) if a else a) for a, _ in parks], pinned))
        for r, t in sorted(threads.items(), key=lambda kv: kv[1].num):
            if r not in ("S", "P"):
                names = [f.name() for f in frames_of(t)]
                log("%s stack (information only): " % (t.name or r)
                    + " <- ".join(n or "?" for n in names[6:16]))
        facts["TYPE_LOCK_locked"] = bool(type_bits & 1)
        facts["stw_locked"] = bool(stw_bits & 1)
        log("facts: " + ", ".join("%s=%s" % kv for kv in sorted(facts.items())))
        if facts and all(facts.values()):
            st["verdict"] = "deadlock"
            log("VERDICT deadlock: the setter owns stw->mutex (hand-off) and waits for TYPE_LOCK; "
                "the partner owns TYPE_LOCK (pinned) and waits for stw->mutex")
            if BATCH:
                gdb.execute("kill")
                os._exit(86)
            log("all threads are stopped; inspect with: thread apply all bt")
        else:
            log("no wait-for cycle: continue all threads")
            gdb.execute("continue -a &")
    
    
    def on_stop(event):
        if not st["checking"] or st["verdict"] or st.get("analysed"):
            return
        if all(t.is_stopped() for t in gdb.selected_inferior().threads()):
            st["analysed"] = True
            gdb.post_event(analyse)
    
    
    def on_exit(event):
        code = getattr(event, "exit_code", None)
        if st["verdict"] == "deadlock":
            os._exit(86)  # the kill after the verdict
        st["verdict"] = "exited"
        log("program exited, status %s; open holds: %s" % (code, sorted(st["held"])))
        if BATCH:
            os._exit(0 if code == 0 else 1)
    
    
    gdb.events.stop.connect(on_stop)
    gdb.events.exited.connect(on_exit)
    log("order=%s; holds h1 h2 h3; breakpoints set" % ORDER)
    gdb.execute("run &")
  8. added 2 commits that reference this issue on Nov 22, 2026
  9. nascheme commented on Nov 23, 2026

    @nascheme
    Member

    I've merged the backport to 3.14, this issue should be fixed on all branches now.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretopic-free-threadingtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions