You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
_Py_SetImmortal must be run on allocating thread (no-gil) #113956
The code in _Py_SetImmortal must be run on the thread that originally allocated the object. If this is not the case, then a race between Py_INCREF can cause the _Py_SetImmortal to be ignored.
I think something like this should occur inside _Py_SetImmortal.
It looks like _Py_SetImmortal is not exposed outside the runtime. However, PEP 683, says:
Then setting any object’s refcount to _Py_IMMORTAL_REFCNT makes it immortal.
This implies there is an intent to expose it, and with the changes to nogil. It seems that this should be exposed as an explicit operation, rather than by setting the ref count directly.
Yes, if the owning thread calls Py_INCREF() concurrently with another thread trying to immortalize the object, that will result in a race condition
_Py_SetImmortal() is not public and I don't think we should make it public (at least not in 3.13)
The check that the caller is the owning thread is conservative. It's also safe to immortalize objects in certain other cases, such as during a stop-the-world event.
I would be hesitant to add an assertion to _Py_SetImmortal() because we call it from a number of places where we already know we are in a bad state, like none_dealloc.
The only call I've seen that concerns me is in _PyUnicode_InternInPlace(). In the free-threaded builds, we should probably only immortalize the string if it is owned by the current thread.
Adding a concrete reproducer for this race. The scenario @mjp41 described and @colesbury confirmed above is reachable from pure-Python code via concurrent setattr() on shared objects with fresh string keys — exactly the _PyUnicode_InternInPlace caller Sam flagged as the concerning one.
Reproducer (pure stdlib, no extensions)
importosimportsignalimportsysimportthreadingimporttimeN_THREADS=8N_ITERS=500N_KEYS_PER_ITER=5SCENARIO_TIMEOUT=120classTarget:
passdefscenario():
foriinrange(N_ITERS):
target=Target()
# Fresh strings via concatenation — NOT bytecode literals, so they# aren't already interned-immortal when the threads start.keys= [
"tsan_intern_race_probe_"+str(i) +"_"+str(j)
forjinrange(N_KEYS_PER_ITER)
]
values=list(range(N_KEYS_PER_ITER))
barrier=threading.Barrier(N_THREADS)
defworker():
barrier.wait()
fork, vinzip(keys, values):
try:
setattr(target, k, v)
exceptException:
passthreads= [threading.Thread(target=worker) for_inrange(N_THREADS)]
fortinthreads:
t.start()
fortinthreads:
t.join()
# Run in a forked subprocess so a crash doesn't take down the parent.pid=os.fork()
ifpid==0:
try:
scenario()
os._exit(0)
exceptException:
os._exit(1)
deadline=time.monotonic() +SCENARIO_TIMEOUTstatus=Nonewhiletime.monotonic() <deadline:
r, s=os.waitpid(pid, os.WNOHANG)
ifr!=0:
status=sbreaktime.sleep(0.1)
ifstatusisNone:
os.kill(pid, signal.SIGKILL)
os.waitpid(pid, 0)
print("TIMEOUT")
elifos.WIFSIGNALED(status):
print(f"CRASH ({signal.Signals(os.WTERMSIG(status)).name})")
elifos.WIFEXITED(status) andos.WEXITSTATUS(status) !=0:
print(f"FAIL (exit {os.WEXITSTATUS(status)})")
else:
print("OK")
Observed results
Reproduced on two independent free-threaded debug builds, in every run tried (4 runs total, 2 per build):
Build
Commit
TSan
Result
3.14 debug FT + TSan
heads/3.14-dirty:ea9ecc8955a, Apr 6 2026
yes
11 TSan data races + SIGABRT at Objects/unicodeobject.c:778
3.15 debug FT + ASAN (no TSan)
heads/main:4d0e8ee649c, Mar 29 2026
no
SIGABRT at Objects/unicodeobject.c:691 (same check; file reorganized)
Both builds: Clang 21.1.2, Linux x86_64, --disable-gil --with-pydebug. The 3.14 build additionally has --with-thread-sanitizer; the 3.15 build has -fsanitize=address.
The SIGABRT in both cases is the debug consistency check at _PyUnicode_CheckConsistency:
The object's ob_ref_local has been set to _Py_IMMORTAL_REFCNT_LOCAL (3221225472 = 0xC0000000) by one thread, while another thread is observing it in the SSTATE_INTERNED_MORTAL state — the invariant the consistency check enforces.
TSan on the 3.14 build flags the underlying race directly. Writer (Thread T8, inside intern_common after LOCK_INTERNED):
WARNING: ThreadSanitizer: data race
Write of size 4 at 0x7fffb4d1ab1c by thread T8:
#0 _Py_SetImmortalUntracked Objects/object.c:2687:22
#1 _Py_SetImmortal Objects/object.c:2704:5
#2 immortalize_interned Objects/unicodeobject.c:15957:5
#3 intern_common Objects/unicodeobject.c:16106:9
#4 _PyUnicode_InternMortal Objects/unicodeobject.c:16123:10
#5 PyObject_SetAttr Objects/object.c:1452:5
#6 builtin_setattr_impl Python/bltinmodule.c:1731:9
...
Reader (Thread T1, still in PyObject_SetAttr before entering intern_common):
Previous atomic read of size 4 at 0x7fffb4d1ab1c by thread T1:
#0 _Py_atomic_load_uint32_relaxed Include/cpython/pyatomic_gcc.h:367:10
#1 _Py_IsImmortal Include/refcount.h:128:13
#2 Py_INCREF Include/refcount.h:299:10
#3 PyObject_SetAttr Objects/object.c:1449:5
#4 builtin_setattr_impl Python/bltinmodule.c:1731:9
...
Same address (ob_ref_local of the interned string), same step sequence @mjp41 described in the original post: one thread is mid-_Py_SetImmortal, another thread's Py_INCREF is concurrently reading the field.
Notes
Not reproducible (user-visibly) on a release FT build — the consistency check is compiled out. The underlying data race still exists and TSan still flags it.
Not reproducible on a GIL build (serialized access to the interning path).
The 3.15 reproduction is with ASAN, no TSan — so the SIGABRT is not a TSan instrumentation artifact. It's a natural consequence of the program flow violating the SSTATE_INTERNED_MORTAL → !immortal invariant.
Both test builds include the reordering from gh-146041: Avoid lock in sys.intern() for already interned strings #146072 (merged 2026-03-24), which moved _Py_SetImmortal(s) to execute before the atomic publication of SSTATE_INTERNED_IMMORTAL. The comment added in that PR explicitly documents the ordering as the synchronization point for intern_common's lock-free fast path — which makes the race window visible in the source. I don't think gh-146041: Avoid lock in sys.intern() for already interned strings #146072introduced the race (the Py_INCREF at PyObject_SetAttr:1449 has always been concurrent with immortalize_interned under the lock), but the new layout makes it easier to reason about.
The comment in _PyUnicode_CheckConsistency (Objects/unicodeobject.c:760-763 on 3.14, :675-676 on 3.15) calls the "object observed in INTERNED_MORTAL state turns out to be immortal" case "extremely unlikely (worth a potential failed assertion in a debug build)." The reproducer above suggests "extremely unlikely" is too strong — 8 threads and a fresh key per iteration is enough to hit it on first try.
No fix proposed — I'm not familiar enough with the FT internals to judge between making the writes atomic, relaxing the debug assertion, or requiring the owning-thread discipline Matthew originally suggested. Happy to provide full TSan output or test any candidate fix.
Found while investigating TSan results from a C extension (wrapt) using labeille and ft-review-toolkit; isolated to pure stdlib after ruling out the extension's own races.
Root cause analysis, reproducer creation and comment draft done with assistance from Claude Code, reviewed by a human.
@colesbury it seems a test in the CFFI thread sanitizer CI is able to reliably trigger a race related to this, see python-cffi/cffi#242. I'm not able to reproduce this race on 3.15. It also seems to have started happening relatively recently. Maybe something was included in a 3.14 backport that makes triggering this easier?
Since it's fixed in 3.15 and appears to be harmless for CFFI, my plan right now for CFFI is to just add a suppression for this.
Activity
colesbury commentedon Jan 11, 2024
A few thoughts:
Py_INCREF()concurrently with another thread trying to immortalize the object, that will result in a race condition_Py_SetImmortal()is not public and I don't think we should make it public (at least not in 3.13)colesbury commentedon Jan 11, 2024
I would be hesitant to add an assertion to
_Py_SetImmortal()because we call it from a number of places where we already know we are in a bad state, likenone_dealloc.The only call I've seen that concerns me is in
_PyUnicode_InternInPlace(). In the free-threaded builds, we should probably only immortalize the string if it is owned by the current thread.mjp41 commentedon Jan 12, 2024
@colesbury thanks for the reply. This makes sense. I had thought this is more externally reachable.
I think you could make it concurrency safe by borrowing a third bit from
ob_ref_sharedto represent Immortal.colesbury commentedon Jan 12, 2024
Yeah, that would address concurrency safety, but using
ob_ref_localserves two other purposes:ob_ref_local32-bits without having to worry about overflow, because the immortal value isUINT32_MAX.Py_INCREFandPy_DECREFfaster because we only need to accessob_tidandob_ref_local.devdanzin commentedon Apr 10, 2026
Adding a concrete reproducer for this race. The scenario @mjp41 described and @colesbury confirmed above is reachable from pure-Python code via concurrent
setattr()on shared objects with fresh string keys — exactly the_PyUnicode_InternInPlacecaller Sam flagged as the concerning one.Reproducer (pure stdlib, no extensions)
Observed results
Reproduced on two independent free-threaded debug builds, in every run tried (4 runs total, 2 per build):
heads/3.14-dirty:ea9ecc8955a, Apr 6 2026Objects/unicodeobject.c:778heads/main:4d0e8ee649c, Mar 29 2026Objects/unicodeobject.c:691(same check; file reorganized)Both builds: Clang 21.1.2, Linux x86_64,
--disable-gil --with-pydebug. The 3.14 build additionally has--with-thread-sanitizer; the 3.15 build has-fsanitize=address.The SIGABRT in both cases is the debug consistency check at
_PyUnicode_CheckConsistency:The object's
ob_ref_localhas been set to_Py_IMMORTAL_REFCNT_LOCAL(3221225472=0xC0000000) by one thread, while another thread is observing it in theSSTATE_INTERNED_MORTALstate — the invariant the consistency check enforces.TSan on the 3.14 build flags the underlying race directly. Writer (Thread T8, inside
intern_commonafterLOCK_INTERNED):Reader (Thread T1, still in
PyObject_SetAttrbefore enteringintern_common):Same address (
ob_ref_localof the interned string), same step sequence @mjp41 described in the original post: one thread is mid-_Py_SetImmortal, another thread'sPy_INCREFis concurrently reading the field.Notes
SSTATE_INTERNED_MORTAL→!immortalinvariant._Py_SetImmortal(s)to execute before the atomic publication ofSSTATE_INTERNED_IMMORTAL. The comment added in that PR explicitly documents the ordering as the synchronization point forintern_common's lock-free fast path — which makes the race window visible in the source. I don't think gh-146041: Avoid lock in sys.intern() for already interned strings #146072 introduced the race (thePy_INCREFatPyObject_SetAttr:1449has always been concurrent withimmortalize_internedunder the lock), but the new layout makes it easier to reason about._PyUnicode_CheckConsistency(Objects/unicodeobject.c:760-763on 3.14,:675-676on 3.15) calls the "object observed in INTERNED_MORTAL state turns out to be immortal" case "extremely unlikely (worth a potential failed assertion in a debug build)." The reproducer above suggests "extremely unlikely" is too strong — 8 threads and a fresh key per iteration is enough to hit it on first try.No fix proposed — I'm not familiar enough with the FT internals to judge between making the writes atomic, relaxing the debug assertion, or requiring the owning-thread discipline Matthew originally suggested. Happy to provide full TSan output or test any candidate fix.
Found while investigating TSan results from a C extension (
wrapt) using labeille and ft-review-toolkit; isolated to pure stdlib after ruling out the extension's own races.Root cause analysis, reproducer creation and comment draft done with assistance from Claude Code, reviewed by a human.
ngoldbaum commentedon Apr 21, 2026
@colesbury it seems a test in the CFFI thread sanitizer CI is able to reliably trigger a race related to this, see python-cffi/cffi#242. I'm not able to reproduce this race on 3.15. It also seems to have started happening relatively recently. Maybe something was included in a 3.14 backport that makes triggering this easier?
Since it's fixed in 3.15 and appears to be harmless for CFFI, my plan right now for CFFI is to just add a suppression for this.
colesbury commentedon Apr 21, 2026
It's not fully fixed in 3.15 either
gh-113956: Make intern_common thread-safe in free-threaded build (gh-…
[3.14] gh-113956: Make intern_common thread-safe in free-threaded bui…
colesbury commentedon Apr 23, 2026
I'm closing the issue now that:
sys.intern, etc. are now thread-safe in the way that they use_Py_SetImmortalPyUnstable_SetImmortalis limited to_PyObject_IsUniquelyReferenced()pythongh-113956: Make intern_common thread-safe in free-threaded build (