GeezerVison is showing github.com — gh-144763: Don't detach the GIL in tracemalloc by vstinner · Pull Request #144779 · python/cpython
Conversation
vstinner
commented
Feb 13, 2026
•
edited by bedevere-app
Bot
Loading
Uh oh!
There was an error while loading. Please reload this page.
tracemalloc no longer detachs the GIL to acquire its internal lock.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
tracemalloc no longer detachs the GIL to acquire its internal lock.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Don't call PyRefTracer_SetTracer() while holding TABLES_LOCK().
This change basically reverts commit 01157e0 (PR #139449) which fixed another deadlock on tracemalloc.stop() :-) See issue #139116.
I pushed a change to avoid the deadlock on tracemalloc.stop(): don't call PyRefTracer_SetTracer() while holding TABLES_LOCK().
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
|
int lineno = -1;
|
|
|
PyCodeObject *code = _PyFrame_GetCode(pyframe);
|
|
|
// PyUnstable_InterpreterFrame_GetLine() cannot but used, since it uses
|
|
|
// a critical section which can trigger a deadlock.
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think the problem is that critical sections requires an active thread state and this code can be called with detached thread state iirc.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
tracemalloc_get_frame() is called with an attached thread state, see the caller traceback_get_frames() which has the code:
PyThreadState *tstate = _PyThreadState_GET();
assert(tstate != NULL);
Example of deadlock when running #144763 (comment) reproducer on a free-threaded build:
- Thread A:
_PyCode_GetTLBC() => ... => tracemalloc_alloc(): TABLES_LOCK()
- Thread B:
_PyTraceMalloc_TraceRef() => ... => tracemalloc_get_frame() => PyUnstable_InterpreterFrame_GetLine() => PyCode_Addr2Line(): Py_BEGIN_CRITICAL_SECTION(co)
Locks:
- Thread A is in a
Py_BEGIN_CRITICAL_SECTION(co) critical section (_PyCode_GetTLBC()) and waits for TABLES_LOCK().
- Thread B has
TABLES_LOCK() lock and waits for Py_BEGIN_CRITICAL_SECTION(co) critical section.
Thread A and thread B want to use Py_BEGIN_CRITICAL_SECTION(co) on the same code object (0x20000844810).
=> deadlock :-(
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There are probably some thread-safety issues here if the code object is being concurrently instrumented or deinstrumented. I don't see a better way of handling it, so let's leave a TODO or note.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is it necessary to keep the attached thread state in TABLES_LOCK? It seems the bulk of the fix is just calling PyRefTracer_SetTracer without holding the lock.
Alternatively, we could just use Py_BEGIN_CRITICAL_SECTION_MUTEX instead of PyMutex_Lock.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
vstinner
commented
Feb 16, 2026
•
edited
Loading
Uh oh!
There was an error while loading. Please reload this page.
Is it necessary to keep the attached thread state in TABLES_LOCK? It seems the bulk of the fix is just calling PyRefTracer_SetTracer without holding the lock.
There are two problems:
Yes, I think that it's necessary to keep the attached thread state in TABLES_LOCK (not detach the thread state).
Alternatively, we could just use Py_BEGIN_CRITICAL_SECTION_MUTEX instead of PyMutex_Lock.
What would be the benefits?
|
ZeroIntensity reacted with thumbs up emoji
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Using _Py_LOCK_DONT_DETACH in TABLES_LOCK() definitely seems like the right approach for the allocator calls (i.e., tracemalloc_alloc/tracemalloc_free). We don't want to detach the thread state there.
I'm not really sure about _PyTraceMalloc_Stop() and _PyTraceMalloc_Start(). Should these be safe to call concurrently? The implementation isn't thread-safe for concurrent calls to tracemalloc.start() or tracemalloc.stop(). Maybe that's fine?
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
I'm not really sure about _PyTraceMalloc_Stop() and _PyTraceMalloc_Start(). Should these be safe to call concurrently? The implementation isn't thread-safe for concurrent calls to tracemalloc.start() or tracemalloc.stop(). Maybe that's fine?
I'm only aware of #128679 : concurrent calls to PyTraceMalloc_Track() and tracemalloc.stop() (case tested by test_tracemalloc.test_tracemalloc_track_race()).
I don't think that two threads should be able to call tracemalloc.stop() and tracemalloc.start() in parallel. I expect that only a single thread (the main thread?) would call these two methods.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Could we use _Py_LOCK_DONT_DETACH in TABLES_LOCK, but use a normal (detaching) call in start/stop? That should avoid the reftracer deadlock without needing to move the call to PyRefTracer_SetTracer.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Nevermind, that would lead to a lock-ordering deadlock:
- Thread A releases the GIL and acquires
TABLES_LOCK.
- Thread B acquires the GIL and begins waiting on
TABLES_LOCK.
- Thread A is waiting on the GIL, which thread B holds.
- Deadlock!
If I remember correctly, tracemalloc still needs more work to avoid crashes when running concurrently (particularly in subinterpreters), so I think it would be fine to leave start/stop as is in this PR and address it later.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this makes sense.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
vstinner
added a commit
to vstinner/cpython
that referenced
this pull request
Feb 18, 2026
tracemalloc no longer detaches the GIL to acquire its internal lock.
Co-authored-by: Kumar Aditya <[email protected]>
(cherry picked from commit 83f4fff)
vstinner
added a commit
to vstinner/cpython
that referenced
this pull request
Feb 18, 2026
Avoid PyUnstable_InterpreterFrame_GetLine() since it uses a critical
section which can lead to a deadlock.
_PyTraceMalloc_Stop() now also calls PyRefTracer_SetTracer() without
holding TABLES_LOCK() to prevent another deadlock.
Co-authored-by: Kumar Aditya <[email protected]>
(cherry picked from commit 83f4fff)
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Backport of the fix to 3.14: #144965. The backport is different since the 3.14 code already avoided to detach the thread safe.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
vstinner
added a commit
that referenced
this pull request
Feb 18, 2026
gh-144763: Fix race conditions in tracemalloc (#144779)
Avoid PyUnstable_InterpreterFrame_GetLine() since it uses a critical
section which can lead to a deadlock.
_PyTraceMalloc_Stop() now also calls PyRefTracer_SetTracer() without
holding TABLES_LOCK() to prevent another deadlock.
(cherry picked from commit 83f4fff)
Co-authored-by: Kumar Aditya <[email protected]>
⚠️⚠️⚠️ Buildbot failure ⚠️⚠️⚠️
Hi! The buildbot AMD64 FreeBSD Refleaks 3.14 (tier-3) has failed when building commit f67cf83.
What do you need to do:
- Don't panic.
- Check the buildbot page in the devguide if you don't know what the buildbots are or how they work.
- Go to the page of the buildbot that failed (https://buildbot.python.org/#/builders/1800/builds/1004) and take a look at the build logs.
- Check if the failure is related to this commit (f67cf83) or if it is a false positive.
- If the failure is related to this commit, please, reflect that on the issue and make a new Pull Request with a fix.
You can take a look at the buildbot page here:
https://buildbot.python.org/#/builders/1800/builds/1004
Test leaking resources:
- test_events: references
- test_events: memory blocks
Summary of the results of the build (if available):
==
Click to see traceback logs
Traceback (most recent call last):
File "/buildbot/buildarea/3.14.ware-freebsd.refleak/build/Lib/test/support/__init__.py", line 859, in gc_collect
gc.collect()
ResourceWarning: unclosed <socket.socket fd=9, family=2, type=1, proto=6, laddr=('127.0.0.1', 15216), raddr=('127.0.0.1', 15217)>
Task was destroyed but it is pending!
task: <Task pending name='Task-4077' coro=<BaseSelectorEventLoop._accept_connection2() done, defined at /buildbot/buildarea/3.14.ware-freebsd.refleak/build/Lib/asyncio/selector_events.py:217> wait_for=<Future finished exception=ConnectionResetError()>>
Future exception was never retrieved
future: <Future finished exception=ConnectionResetError()>
Traceback (most recent call last):
File "/buildbot/buildarea/3.14.ware-freebsd.refleak/build/Lib/asyncio/sslproto.py", line 581, in _on_handshake_complete
raise handshake_exc
ConnectionResetError
Warning -- Unraisable exception
Exception ignored while calling deallocator <function _SelectorTransport.__del__ at 0x847dcc4d0>:
Traceback (most recent call last):
File "/buildbot/buildarea/3.14.ware-freebsd.refleak/build/Lib/asyncio/selector_events.py", line 873, in __del__
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
ResourceWarning: unclosed transport <_SelectorSocketTransport closing fd=9>
k
Traceback (most recent call last):
File "/buildbot/buildarea/3.14.ware-freebsd.refleak/build/Lib/test/support/__init__.py", line 859, in gc_collect
gc.collect()
ResourceWarning: unclosed <socket.socket fd=8, family=2, type=1, proto=6, laddr=('127.0.0.1', 11443), raddr=('127.0.0.1', 11444)>
Task was destroyed but it is pending!
task: <Task pending name='Task-4078' coro=<BaseSelectorEventLoop._accept_connection2() done, defined at /buildbot/buildarea/3.14.ware-freebsd.refleak/build/Lib/asyncio/selector_events.py:217> wait_for=<Future pending cb=[Task.task_wakeup()]>>
Warning -- Unraisable exception
Exception ignored while calling deallocator <function _SelectorTransport.__del__ at 0x844ba84d0>:
Traceback (most recent call last):
File "/buildbot/buildarea/3.14.ware-freebsd.refleak/build/Lib/asyncio/selector_events.py", line 873, in __del__
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
ResourceWarning: unclosed transport <_SelectorSocketTransport closing fd=8>
k
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
brijkapadia
pushed a commit
to brijkapadia/cpython
that referenced
this pull request
Feb 28, 2026
tracemalloc no longer detaches the GIL to acquire its internal lock.
Co-authored-by: Kumar Aditya <[email protected]>
ljfp
pushed a commit
to ljfp/cpython
that referenced
this pull request
Apr 25, 2026
tracemalloc no longer detaches the GIL to acquire its internal lock.
Co-authored-by: Kumar Aditya <[email protected]>
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|