Skip to content

Commit 9e5ab7e

Browse files
gh-152276: Fix assertion failure when an object becomes immortal while queued for BRC merging (#162316)
1 parent 8dbf4cf commit 9e5ab7e

3 files changed

Lines changed: 24 additions & 1 deletion

File tree

‎Lib/test/test_free_threading/test_races.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,22 @@ def set_recursion_limit():
288288

289289
do_race(something_recursive, set_recursion_limit)
290290

291+
def test_racing_intern_queued_for_merge(self):
292+
# gh-152276: an object may become immortal while it is queued for
293+
# its owning thread to merge its reference count.
294+
# The same strings are used on every run, so that reruns do not
295+
# create new immortal strings.
296+
for i in range(10):
297+
strings = [f"test_racing_intern_queued_for_merge_{i}_{j}"
298+
for j in range(1000)]
299+
shared = list(strings)
300+
# Dropping the references from another thread queues the strings
301+
# to be merged by this thread, which is busy interning them.
302+
thread = threading.Thread(target=shared.clear)
303+
thread.start()
304+
list(map(sys.intern, strings))
305+
thread.join()
306+
291307

292308
@threading_helper.requires_working_threading()
293309
class TestWarningsRaces(TestBase):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
For the :term:`free-threaded build`, avoid an assertion failure when an object
2+
becomes immortal while queued for biased reference counting (BRC) merging.

‎Objects/object.c‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,12 @@ _Py_MergeZeroLocalRefcount(PyObject *op)
468468
Py_ssize_t
469469
_Py_ExplicitMergeRefcount(PyObject *op, Py_ssize_t extra)
470470
{
471-
assert(!_Py_IsImmortal(op));
471+
if (_Py_IsImmortal(op)) {
472+
// The object may have become immortal after it was queued to be
473+
// merged (for example, by sys.intern()). There is nothing to merge
474+
// and the reference total no longer includes the object.
475+
return _Py_IMMORTAL_INITIAL_REFCNT;
476+
}
472477

473478
#ifdef Py_REF_DEBUG
474479
_Py_AddRefTotal(_PyThreadState_GET(), extra);

0 commit comments

Comments
 (0)