From b6a5ee63d2e546feaaa22689f83824b1998d59f3 Mon Sep 17 00:00:00 2001 From: Neil Schemenauer Date: Fri, 27 Nov 2026 13:23:47 -0700 Subject: [PATCH 1/5] gh-162752: Skip stop-the-world when a type slot update changes nothing Assigning a special method to a class stopped the world on every assignment, even when no slot changed (e.g. replacing one Python __getitem__ function with another). With other threads contending, each pause could cost about 1 ms. Before stopping the world, compute the new slot values with TYPE_LOCK held and skip the pause if none would change. --- ...-11-27-13-23-47.gh-issue-162752.POPDrA.rst | 4 ++ Objects/typeobject.c | 70 +++++++++++++++---- 2 files changed, 61 insertions(+), 13 deletions(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-11-27-13-23-47.gh-issue-162752.POPDrA.rst diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-27-13-23-47.gh-issue-162752.POPDrA.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-27-13-23-47.gh-issue-162752.POPDrA.rst new file mode 100644 index 000000000000000..96dc325e9ea8905 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-27-13-23-47.gh-issue-162752.POPDrA.rst @@ -0,0 +1,4 @@ +Fix a performance regression in the :term:`free-threaded build` when +assigning a special method to a class, such as ``C.__getitem__ = f``, while +other threads are running. The world is no longer stopped if no type slot +would change. diff --git a/Objects/typeobject.c b/Objects/typeobject.c index a2690e8e6aa5bac..a1b4f527981c720 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -3888,12 +3888,14 @@ solid_base(PyTypeObject *type) /// data passed to update_slots_callback() typedef struct { pytype_slotdef **defs; + // If not NULL, only check if any slot would change, setting *changed. + bool *changed; } update_callback_data_t; static void object_dealloc(PyObject *); static PyObject *object_new(PyTypeObject *, PyObject *, PyObject *); static int object_init(PyObject *, PyObject *, PyObject *); -static int update_slot(PyTypeObject *, PyObject *); +static int update_slot(PyTypeObject *, PyObject *, bool *); static void fixup_slot_dispatchers(PyTypeObject *); static int type_ready(PyTypeObject *, int, int); static int type_ready_publish(PyTypeObject *, int); @@ -6720,8 +6722,22 @@ type_update_dict(PyTypeObject *type, PyDictObject *dict, PyObject *name, static int update_slot_after_setattr(PyTypeObject *type, PyObject *name) { +#ifdef Py_GIL_DISABLED + // Check if we actually need to update the slot. If not, we can skip the + // STW, which can be expensive. This is pretty common since assigning a new + // function to an existing slot name, like "C.__getitem__ = f", usually + // changes no slot. + ASSERT_TYPE_LOCK_HELD(); + bool changed = false; + if (update_slot(type, name, &changed) < 0) { + return -1; + } + if (!changed) { + return 0; + } +#endif types_stop_world(); - int res = update_slot(type, name); + int res = update_slot(type, name, NULL); types_start_world(); #ifdef Py_GIL_DISABLED // Invalidate again, after the slots are updated and while TYPE_LOCK is @@ -12122,11 +12138,14 @@ collect_slot_descrs(PyTypeObject *type, PyObject **descrs) * If descrs is not NULL, it holds the descriptors found by * collect_slot_descrs() and no lookups are done. * + * If changed is not NULL, the type is not modified. Instead, *changed is + * set to true if the slot (or tp_flags) would be changed. + * * Exceptions that occur internally are ignored, such as when looking up * descriptors. */ static void update_one_slot(PyTypeObject *type, pytype_slotdef *p, pytype_slotdef **next_p, - PyObject **descrs) + PyObject **descrs, bool *changed) { ASSERT_NEW_TYPE_OR_LOCKED(type); @@ -12264,7 +12283,14 @@ update_one_slot(PyTypeObject *type, pytype_slotdef *p, pytype_slotdef **next_p, } if (p->function == slot_tp_call) { /* A generic __call__ is incompatible with vectorcall */ - type_clear_flags(type, Py_TPFLAGS_HAVE_VECTORCALL); + if (changed != NULL) { + if (type->tp_flags & Py_TPFLAGS_HAVE_VECTORCALL) { + *changed = true; + } + } + else { + type_clear_flags(type, Py_TPFLAGS_HAVE_VECTORCALL); + } } } PyStackRef_CLOSE(descr_ref); @@ -12277,8 +12303,15 @@ update_one_slot(PyTypeObject *type, pytype_slotdef *p, pytype_slotdef **next_p, slot_value = generic; } - ASSERT_WORLD_STOPPED_OR_NEW_TYPE(type); - *ptr = slot_value; + if (changed != NULL) { + if (*ptr != slot_value) { + *changed = true; + } + } + else { + ASSERT_WORLD_STOPPED_OR_NEW_TYPE(type); + *ptr = slot_value; + } if (next_p != NULL) { *next_p = p; @@ -12293,17 +12326,23 @@ update_slots_callback(PyTypeObject *type, void *data) ASSERT_NEW_TYPE_OR_LOCKED(type); update_callback_data_t *update_data = (update_callback_data_t *)data; + bool *changed = update_data->changed; pytype_slotdef **pp = update_data->defs; for (; *pp; pp++) { - update_one_slot(type, *pp, NULL, NULL); + if (changed != NULL && *changed) { + break; // already known that an update is needed + } + update_one_slot(type, *pp, NULL, NULL, changed); } return 0; } /* Update the slots after assignment to a class (type) attribute. In the - free-threaded build, this is called with the world stopped. */ + free-threaded build, this is called with the world stopped. If changed is + not NULL, nothing is updated and *changed is set to true if any slot of the + type or its subclasses would change. */ static int -update_slot(PyTypeObject *type, PyObject *name) +update_slot(PyTypeObject *type, PyObject *name, bool *changed) { pytype_slotdef *ptrs[MAX_EQUIV]; pytype_slotdef *p; @@ -12332,6 +12371,7 @@ update_slot(PyTypeObject *type, PyObject *name) update_callback_data_t callback_data; callback_data.defs = ptrs; + callback_data.changed = changed; return update_subclasses(type, name, update_slots_callback, (void *)&callback_data); } @@ -12352,7 +12392,7 @@ fixup_slot_dispatchers(PyTypeObject *type) descrs = NULL; } for (pytype_slotdef *p = slotdefs; p->name; ) { - update_one_slot(type, p, &p, descrs); + update_one_slot(type, p, &p, descrs, NULL); } if (descrs != NULL) { clear_slot_descrs(descrs); @@ -12367,7 +12407,7 @@ update_all_slots(PyTypeObject* type) types_stop_world(); for (pytype_slotdef *p = slotdefs; p->name; p++) { /* update_slot returns int but can't actually fail in this case*/ - update_slot(type, p->name_strobj); + update_slot(type, p->name_strobj, NULL); } types_start_world(); // Invalidate the version tags after the slots are updated, while @@ -12535,8 +12575,12 @@ recurse_down_subclasses(PyTypeObject *type, PyObject *attr_name, // With the world stopped, use borrowed references to the subclasses, // so that dropping a reference cannot run type_dealloc(). Look up // attr_name without calling __eq__ of non-str keys, consistent with - // find_slot_name_in_mro(). - assert(types_world_is_stopped()); + // find_slot_name_in_mro(). This is also done with only TYPE_LOCK held + // when checking for slot changes (see update_slot()). That is safe + // too: type_dealloc() removes the type from tp_subclasses, which + // requires TYPE_LOCK, before it tears down the type, and the type + // dicts are only modified with TYPE_LOCK held. + ASSERT_TYPE_LOCK_HELD(); if (_PyWeakref_IS_DEAD(ref)) { continue; } From 9c7def0f7277d77f15755529005c9da458b9a674 Mon Sep 17 00:00:00 2001 From: Neil Schemenauer Date: Fri, 27 Nov 2026 16:34:28 -0700 Subject: [PATCH 2/5] Rework the "slot not changed" check. Avoid looking at the type dict, since it can release TYPE_LOCK. Add slot_update_is_noop() helper and use that. --- Lib/test/test_free_threading/test_type.py | 34 ++++ ...-11-27-13-23-47.gh-issue-162752.POPDrA.rst | 4 +- Objects/typeobject.c | 189 +++++++++++------- 3 files changed, 158 insertions(+), 69 deletions(-) diff --git a/Lib/test/test_free_threading/test_type.py b/Lib/test/test_free_threading/test_type.py index f7e4adf2e02ce8a..f08a4b4b1e63e67 100644 --- a/Lib/test/test_free_threading/test_type.py +++ b/Lib/test/test_free_threading/test_type.py @@ -358,6 +358,11 @@ def custom_repr(self): self.assertTrue(all(repr(cls()) == "custom repr" for cls in subclasses)) + # This time the slots are already generic. The fast check must + # release the subclasses it visited before reaching its budget. + Base.__repr__ = lambda self: "replacement" + self.assertTrue(all(repr(cls()) == "replacement" for cls in subclasses)) + del Base.__repr__ self.assertTrue(all(repr(cls()) != "custom repr" for cls in subclasses)) @@ -500,6 +505,35 @@ class C(A, metaclass=Meta): C.__bases__ = (B,) self.assertEqual(C.__mro__, (C, B, object)) + def test_slot_update_shadowed_branch(self): + class Base: + def __repr__(self): + return "base" + + class Target(Base): + pass + + class Override(Target): + def __repr__(self): + return "override" + + class Native(Base): + __repr__ = object.__repr__ + + class Inherit(Target, Native): + pass + + class Both(Override, Inherit): + pass + + # Target's slot is already generic, but Inherit gets its slot from + # Native until Target defines __repr__ in its own dict. + obj = Inherit() + self.assertEqual(repr(obj), object.__repr__(obj)) + Target.__repr__ = lambda self: "new" + self.assertEqual(repr(obj), "new") + self.assertEqual(repr(Both()), "override") + def test_slot_update_skips_non_str_keys(self): # Slots are computed (with the world stopped, for an update) without # comparing the slot name with non-str keys of the type dicts, which diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-27-13-23-47.gh-issue-162752.POPDrA.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-27-13-23-47.gh-issue-162752.POPDrA.rst index 96dc325e9ea8905..fb7622cec0e83f4 100644 --- a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-27-13-23-47.gh-issue-162752.POPDrA.rst +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-27-13-23-47.gh-issue-162752.POPDrA.rst @@ -1,4 +1,4 @@ Fix a performance regression in the :term:`free-threaded build` when assigning a special method to a class, such as ``C.__getitem__ = f``, while -other threads are running. The world is no longer stopped if no type slot -would change. +other threads are running. Replacing a Python function with another can now +avoid stopping the world when the type slots are already up to date. diff --git a/Objects/typeobject.c b/Objects/typeobject.c index a1b4f527981c720..cc10139b9a1042b 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -3888,14 +3888,22 @@ solid_base(PyTypeObject *type) /// data passed to update_slots_callback() typedef struct { pytype_slotdef **defs; - // If not NULL, only check if any slot would change, setting *changed. - bool *changed; } update_callback_data_t; static void object_dealloc(PyObject *); static PyObject *object_new(PyTypeObject *, PyObject *, PyObject *); static int object_init(PyObject *, PyObject *, PyObject *); -static int update_slot(PyTypeObject *, PyObject *, bool *); +static int update_slot(PyTypeObject *, PyObject *); +#ifdef Py_GIL_DISABLED +// Limit the work spent checking subclasses (including repeated visits in a +// diamond). Keep them alive until after releasing the type and dict locks. +struct slot_update_refs { + size_t count; + PyTypeObject *types[16]; // Small on-stack budget for subclass visits. +}; +static int slot_update_is_noop(PyTypeObject *, PyObject *, PyObject *, + struct slot_update_refs *); +#endif static void fixup_slot_dispatchers(PyTypeObject *); static int type_ready(PyTypeObject *, int, int); static int type_ready_publish(PyTypeObject *, int); @@ -6719,37 +6727,25 @@ type_update_dict(PyTypeObject *type, PyDictObject *dict, PyObject *name, return 0; } +#ifdef Py_GIL_DISABLED static int -update_slot_after_setattr(PyTypeObject *type, PyObject *name) +update_slot_after_setattr(PyTypeObject *type, PyObject *name, PyObject *value, + struct slot_update_refs *refs) { -#ifdef Py_GIL_DISABLED - // Check if we actually need to update the slot. If not, we can skip the - // STW, which can be expensive. This is pretty common since assigning a new - // function to an existing slot name, like "C.__getitem__ = f", usually - // changes no slot. - ASSERT_TYPE_LOCK_HELD(); - bool changed = false; - if (update_slot(type, name, &changed) < 0) { - return -1; - } - if (!changed) { - return 0; + int res = 0; + if (!slot_update_is_noop(type, name, value, refs)) { + types_stop_world(); + res = update_slot(type, name); + types_start_world(); } -#endif - types_stop_world(); - int res = update_slot(type, name, NULL); - types_start_world(); -#ifdef Py_GIL_DISABLED - // Invalidate again, after the slots are updated and while TYPE_LOCK is - // still held. Other threads may have assigned new version tags while - // the lock was released waiting for the stop-the-world and cached - // decisions based on the old slots. This is a no-op if the tags are - // still invalid. + // Invalidate again even if no slot changed. Comparing a non-str dict + // key during the write can cache the old method. Waiting for the world + // to stop can also let other threads cache decisions based on old slots. ASSERT_TYPE_LOCK_HELD(); _PyType_Modified_Unlocked(type); -#endif return res; } +#endif static int type_setattro(PyObject *self, PyObject *name, PyObject *value) @@ -6831,16 +6827,29 @@ type_setattro(PyObject *self, PyObject *name, PyObject *value) } } +#ifdef Py_GIL_DISABLED + struct slot_update_refs refs; + refs.count = 0; +#endif BEGIN_TYPE_DICT_LOCK(dict); res = type_update_dict(type, (PyDictObject *)dict, name, value, &old_value); assert(_PyType_CheckConsistency(type)); if (res == 0) { if (is_dunder_name(name) && has_slotdef(name)) { // The name corresponds to a type slot. - res = update_slot_after_setattr(type, name); +#ifdef Py_GIL_DISABLED + res = update_slot_after_setattr(type, name, value, &refs); +#else + res = update_slot(type, name); +#endif } } END_TYPE_DICT_LOCK(); +#ifdef Py_GIL_DISABLED + for (size_t i = 0; i < refs.count; i++) { + Py_DECREF(refs.types[i]); + } +#endif done: Py_DECREF(name); @@ -12138,14 +12147,11 @@ collect_slot_descrs(PyTypeObject *type, PyObject **descrs) * If descrs is not NULL, it holds the descriptors found by * collect_slot_descrs() and no lookups are done. * - * If changed is not NULL, the type is not modified. Instead, *changed is - * set to true if the slot (or tp_flags) would be changed. - * * Exceptions that occur internally are ignored, such as when looking up * descriptors. */ static void update_one_slot(PyTypeObject *type, pytype_slotdef *p, pytype_slotdef **next_p, - PyObject **descrs, bool *changed) + PyObject **descrs) { ASSERT_NEW_TYPE_OR_LOCKED(type); @@ -12283,14 +12289,7 @@ update_one_slot(PyTypeObject *type, pytype_slotdef *p, pytype_slotdef **next_p, } if (p->function == slot_tp_call) { /* A generic __call__ is incompatible with vectorcall */ - if (changed != NULL) { - if (type->tp_flags & Py_TPFLAGS_HAVE_VECTORCALL) { - *changed = true; - } - } - else { - type_clear_flags(type, Py_TPFLAGS_HAVE_VECTORCALL); - } + type_clear_flags(type, Py_TPFLAGS_HAVE_VECTORCALL); } } PyStackRef_CLOSE(descr_ref); @@ -12303,15 +12302,8 @@ update_one_slot(PyTypeObject *type, pytype_slotdef *p, pytype_slotdef **next_p, slot_value = generic; } - if (changed != NULL) { - if (*ptr != slot_value) { - *changed = true; - } - } - else { - ASSERT_WORLD_STOPPED_OR_NEW_TYPE(type); - *ptr = slot_value; - } + ASSERT_WORLD_STOPPED_OR_NEW_TYPE(type); + *ptr = slot_value; if (next_p != NULL) { *next_p = p; @@ -12326,23 +12318,17 @@ update_slots_callback(PyTypeObject *type, void *data) ASSERT_NEW_TYPE_OR_LOCKED(type); update_callback_data_t *update_data = (update_callback_data_t *)data; - bool *changed = update_data->changed; pytype_slotdef **pp = update_data->defs; for (; *pp; pp++) { - if (changed != NULL && *changed) { - break; // already known that an update is needed - } - update_one_slot(type, *pp, NULL, NULL, changed); + update_one_slot(type, *pp, NULL, NULL); } return 0; } /* Update the slots after assignment to a class (type) attribute. In the - free-threaded build, this is called with the world stopped. If changed is - not NULL, nothing is updated and *changed is set to true if any slot of the - type or its subclasses would change. */ + free-threaded build, this is called with the world stopped. */ static int -update_slot(PyTypeObject *type, PyObject *name, bool *changed) +update_slot(PyTypeObject *type, PyObject *name) { pytype_slotdef *ptrs[MAX_EQUIV]; pytype_slotdef *p; @@ -12371,11 +12357,84 @@ update_slot(PyTypeObject *type, PyObject *name, bool *changed) update_callback_data_t callback_data; callback_data.defs = ptrs; - callback_data.changed = changed; return update_subclasses(type, name, update_slots_callback, (void *)&callback_data); } +#ifdef Py_GIL_DISABLED +/* Check the slots in 'type' and the subclasses update_slot() would visit. Note + * that this must be done without releasing TYPE_LOCK. */ +static int +slots_are_generic(PyTypeObject *type, PyObject *name, const uint8_t *dups, + struct slot_update_refs *refs) +{ + ASSERT_TYPE_LOCK_HELD(); + + for (uint8_t k = 1; k <= dups[0]; k++) { + pytype_slotdef *p = &slotdefs[dups[k]]; + void **ptr = slotptr(type, p->offset); + if (ptr != NULL && *ptr != p->function) { + return 0; + } + if (p->function == slot_tp_call && + (type->tp_flags & Py_TPFLAGS_HAVE_VECTORCALL)) { + return 0; + } + } + PyObject *subclasses = lookup_tp_subclasses(type); // borrowed ref + if (subclasses == NULL) { + return 1; + } + Py_ssize_t i = 0; + PyObject *ref; + while (PyDict_Next(subclasses, &i, NULL, &ref)) { + if (refs->count == Py_ARRAY_LENGTH(refs->types)) { + // Another visit would exceed the budget for the whole walk + // (including repeat visits). Fall back to the normal slot update. + return 0; + } + PyTypeObject *subclass = type_from_ref(ref); + if (subclass == NULL) { + return 0; + } + refs->types[refs->count++] = subclass; + + // Prune at overrides, as in recurse_down_subclasses(). Don't block + // on the dict lock: detaching could release TYPE_LOCK mid-walk. + PyObject *dict = lookup_tp_dict(subclass); + if (dict == NULL || !PyDict_Check(dict) || + !PyMutex_LockFast(&dict->ob_mutex)) { + return 0; + } + int overrides = _PyDict_GetItem_ExactUnicode((PyDictObject *)dict, + name) != NULL; + PyMutex_Unlock(&dict->ob_mutex); + if (!overrides && !slots_are_generic(subclass, name, dups, refs)) { + return 0; + } + } + return 1; +} + +/* Return 1 if update_slot() would not change any slot after 'value' was + assigned to the slot name 'name' of 'type', so the stop-the-world can be + skipped. Return 0 if slots might change. */ +static int +slot_update_is_noop(PyTypeObject *type, PyObject *name, PyObject *value, + struct slot_update_refs *refs) +{ + ASSERT_TYPE_LOCK_HELD(); + if (value == NULL || !PyFunction_Check(value)) { + return 0; + } + Py_ssize_t idx = slotname_lookup(name, _PyObject_HashDictKey(name)); + if (idx < 0) { + return 0; + } + return slots_are_generic(type, name, slotdefs_dups[idx], refs); +} +#endif + /* Store the proper functions in the slot dispatches at class (type) definition time, based upon which operations the class overrides in its dict. The type must not be revealed to other threads yet, so that the @@ -12392,7 +12451,7 @@ fixup_slot_dispatchers(PyTypeObject *type) descrs = NULL; } for (pytype_slotdef *p = slotdefs; p->name; ) { - update_one_slot(type, p, &p, descrs, NULL); + update_one_slot(type, p, &p, descrs); } if (descrs != NULL) { clear_slot_descrs(descrs); @@ -12407,7 +12466,7 @@ update_all_slots(PyTypeObject* type) types_stop_world(); for (pytype_slotdef *p = slotdefs; p->name; p++) { /* update_slot returns int but can't actually fail in this case*/ - update_slot(type, p->name_strobj, NULL); + update_slot(type, p->name_strobj); } types_start_world(); // Invalidate the version tags after the slots are updated, while @@ -12575,12 +12634,8 @@ recurse_down_subclasses(PyTypeObject *type, PyObject *attr_name, // With the world stopped, use borrowed references to the subclasses, // so that dropping a reference cannot run type_dealloc(). Look up // attr_name without calling __eq__ of non-str keys, consistent with - // find_slot_name_in_mro(). This is also done with only TYPE_LOCK held - // when checking for slot changes (see update_slot()). That is safe - // too: type_dealloc() removes the type from tp_subclasses, which - // requires TYPE_LOCK, before it tears down the type, and the type - // dicts are only modified with TYPE_LOCK held. - ASSERT_TYPE_LOCK_HELD(); + // find_slot_name_in_mro(). + assert(types_world_is_stopped()); if (_PyWeakref_IS_DEAD(ref)) { continue; } From 24499ffeee93cf07dfe991a347a2b5f26c4bb816 Mon Sep 17 00:00:00 2001 From: "Gregory P. Smith" Date: Sun, 29 Nov 2026 13:33:56 -0800 Subject: [PATCH 3/5] gh-162752: Assert that the slotdefs of a slot share a function The slotdefs that fill the same slot all name the same generic function, since that function has to dispatch to every one of their special methods. The check that lets a special method assignment skip the stop-the-world depends on it: it compares a slot with the function of the slotdef for the assigned name, while update_one_slot() stores that of whichever slotdef it handled last. If they ever differed, slots that are up to date could fail the comparison and stop the world on every assignment. Assert it when the slotdefs are initialized. Co-authored with Claude Fable 5.2 --- Objects/typeobject.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Objects/typeobject.c b/Objects/typeobject.c index cc10139b9a1042b..a9f8039baac48ef 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -12482,6 +12482,18 @@ _PyType_InitSlotDefs(PyInterpreterState *interp) } init_slotname_table(); +#ifndef NDEBUG + /* The slotdefs of a slot (they are adjacent) share one generic function, + which dispatches to all of their names. slots_are_generic() compares + a slot with the function of the slotdef for the assigned name, while + update_one_slot() stores that of whichever slotdef it handled last. + If they differed, that comparison could fail for up to date slots. */ + for (pytype_slotdef *p = slotdefs + 1; p->name != NULL; p++) { + assert(p->offset != (p - 1)->offset + || p->function == (p - 1)->function); + } +#endif + /* Group the slotdefs by name: slotdefs_dups[i] lists the indices of all slotdefs with the same name as slotdefs[i], in slotdefs order. */ memset(slotdefs_dups, 0, sizeof(slotdefs_dups)); From 5d1926d05b3e415f42937262cb836fdbba65effc Mon Sep 17 00:00:00 2001 From: "Gregory P. Smith" Date: Sun, 29 Nov 2026 13:33:56 -0800 Subject: [PATCH 4/5] gh-162752: Test racing unchanged slot updates with real ones Assigning a Python function over another one now decides without stopping the world whether any slot changes, by walking the subclasses with the type lock held. Race that walk against assignments that do change the slots of a subclass and against __bases__ assignments that remove the subclass and free its base's tp_subclasses, then check that the slots still agree with the MRO. Co-authored with Claude Fable 5.2 --- Lib/test/test_free_threading/test_type.py | 52 +++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/Lib/test/test_free_threading/test_type.py b/Lib/test/test_free_threading/test_type.py index f08a4b4b1e63e67..cde0533130bd976 100644 --- a/Lib/test/test_free_threading/test_type.py +++ b/Lib/test/test_free_threading/test_type.py @@ -534,6 +534,58 @@ class Both(Override, Inherit): self.assertEqual(repr(obj), "new") self.assertEqual(repr(Both()), "override") + def test_slot_update_unchanged_race(self): + # Replacing a Python function with another one does not stop the + # world if no slot changes. That is decided by looking at the slots + # of the subclasses, while other threads change those slots and the + # subclasses. At the end, the slots must agree with the MRO. + N = 100 + + class Base: + def __repr__(self): + return "base" + + class Target(Base): + pass + + class Native(Base): + __repr__ = object.__repr__ + + class Inherit(Target, Native): + pass + + def swapper(): + # No slot changes. + for _ in range(N): + Base.__repr__ = lambda self: "base" + + def toggler(): + # Inherit's slot alternates between generic and Native's. + for _ in range(N): + Target.__repr__ = lambda self: "target" + del Target.__repr__ + + def rebaser(): + # Target's only subclass comes and goes. + for _ in range(N): + Inherit.__bases__ = (Native,) + Inherit.__bases__ = (Target, Native) + + def reader(): + for _ in range(N): + self.assertEqual(repr(Base()), "base") + self.assertIn(repr(Target()), ("base", "target")) + repr(Inherit()) + + threading_helper.run_concurrently( + [swapper, swapper, toggler, rebaser, reader] + world_stoppers()) + + obj = Inherit() + self.assertEqual(repr(Target()), "base") + self.assertEqual(repr(obj), object.__repr__(obj)) + Target.__repr__ = lambda self: "new" + self.assertEqual(repr(obj), "new") + def test_slot_update_skips_non_str_keys(self): # Slots are computed (with the world stopped, for an update) without # comparing the slot name with non-str keys of the type dicts, which From 0044e19b526d75e0f371a36fffd2736b57b58b48 Mon Sep 17 00:00:00 2001 From: "Gregory P. Smith" Date: Sun, 29 Nov 2026 13:33:56 -0800 Subject: [PATCH 5/5] gh-162752: Assert the type lock is kept while checking subclass slots slots_are_generic() iterates tp_subclasses with a borrowed reference, which is only safe while TYPE_LOCK is held: a __bases__ assignment in another thread can empty and free that dict. Nothing fails visibly if the lock is dropped during the walk (the freed dict is usually reused), so assert that the dict is still the one being iterated. With this, test_slot_update_unchanged_race fails if the walk blocks. Co-authored with Claude Fable 5.2 --- Objects/typeobject.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Objects/typeobject.c b/Objects/typeobject.c index a9f8039baac48ef..e16e12b06731a66 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -12412,6 +12412,8 @@ slots_are_generic(PyTypeObject *type, PyObject *name, const uint8_t *dups, if (!overrides && !slots_are_generic(subclass, name, dups, refs)) { return 0; } + // Iterating is only safe if TYPE_LOCK was never released. + assert(lookup_tp_subclasses(type) == subclasses); } return 1; }