diff --git a/Lib/test/test_free_threading/test_races.py b/Lib/test/test_free_threading/test_races.py index 23b48c76195408..62e1b0385dc03b 100644 --- a/Lib/test/test_free_threading/test_races.py +++ b/Lib/test/test_free_threading/test_races.py @@ -318,6 +318,34 @@ def emit_warning(): do_race(modify_filters, emit_warning) + def test_brc_queue_sys_intern_race(self): + # 1 million strings will take Thread A significant time to process in map() + # giving Thread B plenty of time to drop references to strings that Thread A + # hasn't interned yet! + strings = ["race_string_massive_" + str(j) for j in range(1000000)] + + # Give Thread B a copy of the list. + # Thread A still holds 'strings' so local refcount > 0. + shared = list(strings) + + def thread_b_func(): + # Thread B simply clears its list, which decrements the shared refcount + # of every string. Since Thread B is not the owner, this calls + # _Py_DecRefShared. Since shared refcount drops to 0, they get queued + # to Thread A! + shared.clear() + + tb = threading.Thread(target=thread_b_func) + tb.start() + + # Thread A enters map() which runs entirely in C! + # While Thread A iterates over the 1,000,000 strings, Thread B is + # concurrently clearing its list and queueing them. + # Any string that Thread B queues BEFORE Thread A reaches it in map() + # will become queued, AND THEN made immortal by sys.intern! + list(map(sys.intern, strings)) + tb.join() + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Library/2026-06-26-13-25-59.gh-issue-152276.LGiipk.rst b/Misc/NEWS.d/next/Library/2026-06-26-13-25-59.gh-issue-152276.LGiipk.rst new file mode 100644 index 00000000000000..05fbb89a535138 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-06-26-13-25-59.gh-issue-152276.LGiipk.rst @@ -0,0 +1 @@ +Fix "assert(!_Py_IsImmortal(op))" failure when BRC merge queue races with objects that were recently made immortal. diff --git a/Python/brc.c b/Python/brc.c index d27687052aec19..a456545b50d2d3 100644 --- a/Python/brc.c +++ b/Python/brc.c @@ -104,6 +104,9 @@ merge_queued_objects(_PyObjectStack *to_merge) { PyObject *ob; while ((ob = _PyObjectStack_Pop(to_merge)) != NULL) { + if (_Py_IsImmortal(ob)) { + continue; + } // Subtract one when merging because the queue had a reference. Py_ssize_t refcount = _Py_ExplicitMergeRefcount(ob, -1); if (refcount == 0) {