From a25a6ddc145ccbb8ff3aee68c5a5ab6423c2c53d Mon Sep 17 00:00:00 2001 From: Kumar Aditya Date: Fri, 20 Nov 2026 17:48:42 +0530 Subject: [PATCH] gh-152276: Fix assertion failure when an object becomes immortal while queued for BRC merging (GH-162316) (cherry picked from commit 9e5ab7e13f4fe9924055b624fec04de15c4561aa) Co-authored-by: Kumar Aditya --- Lib/test/test_free_threading/test_races.py | 16 ++++++++++++++++ ...026-11-20-12-00-00.gh-issue-152276.bRcImm.rst | 2 ++ Objects/object.c | 7 ++++++- 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-11-20-12-00-00.gh-issue-152276.bRcImm.rst diff --git a/Lib/test/test_free_threading/test_races.py b/Lib/test/test_free_threading/test_races.py index f08de7496eb526..dc1617512f8795 100644 --- a/Lib/test/test_free_threading/test_races.py +++ b/Lib/test/test_free_threading/test_races.py @@ -288,6 +288,22 @@ def set_recursion_limit(): do_race(something_recursive, set_recursion_limit) + def test_racing_intern_queued_for_merge(self): + # gh-152276: an object may become immortal while it is queued for + # its owning thread to merge its reference count. + # The same strings are used on every run, so that reruns do not + # create new immortal strings. + for i in range(10): + strings = [f"test_racing_intern_queued_for_merge_{i}_{j}" + for j in range(1000)] + shared = list(strings) + # Dropping the references from another thread queues the strings + # to be merged by this thread, which is busy interning them. + thread = threading.Thread(target=shared.clear) + thread.start() + list(map(sys.intern, strings)) + thread.join() + @threading_helper.requires_working_threading() class TestWarningsRaces(TestBase): diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-20-12-00-00.gh-issue-152276.bRcImm.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-20-12-00-00.gh-issue-152276.bRcImm.rst new file mode 100644 index 00000000000000..9cc5d98dae0d0f --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-20-12-00-00.gh-issue-152276.bRcImm.rst @@ -0,0 +1,2 @@ +For the :term:`free-threaded build`, avoid an assertion failure when an object +becomes immortal while queued for biased reference counting (BRC) merging. diff --git a/Objects/object.c b/Objects/object.c index 4e15d4c6679596..9e43748451a199 100644 --- a/Objects/object.c +++ b/Objects/object.c @@ -468,7 +468,12 @@ _Py_MergeZeroLocalRefcount(PyObject *op) Py_ssize_t _Py_ExplicitMergeRefcount(PyObject *op, Py_ssize_t extra) { - assert(!_Py_IsImmortal(op)); + if (_Py_IsImmortal(op)) { + // The object may have become immortal after it was queued to be + // merged (for example, by sys.intern()). There is nothing to merge + // and the reference total no longer includes the object. + return _Py_IMMORTAL_INITIAL_REFCNT; + } #ifdef Py_REF_DEBUG _Py_AddRefTotal(_PyThreadState_GET(), extra);