diff --git a/Lib/test/test_free_threading/test_type.py b/Lib/test/test_free_threading/test_type.py index a62f766e8df133c..34979c4294f0afb 100644 --- a/Lib/test/test_free_threading/test_type.py +++ b/Lib/test/test_free_threading/test_type.py @@ -217,6 +217,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)) @@ -349,6 +354,87 @@ 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_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 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..fb7622cec0e83f4 --- /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. 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 fd7699471438ff8..83e00daa72f8a2c 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -3945,6 +3945,16 @@ 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 *); +#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); @@ -6839,23 +6849,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) { - types_stop_world(); - int res = update_slot(type, name); - 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. + int res = 0; + if (!slot_update_is_noop(type, name, value, refs)) { + types_stop_world(); + res = update_slot(type, name); + types_start_world(); + } + // 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(); type_modified_unlocked(type); -#endif return res; } +#endif static int type_setattro(PyObject *self, PyObject *name, PyObject *value) @@ -6937,16 +6949,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); @@ -12314,6 +12339,84 @@ update_slot(PyTypeObject *type, PyObject *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; + } + // Iterating is only safe if TYPE_LOCK was never released. + assert(lookup_tp_subclasses(type) == subclasses); + } + 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; + } + for (pytype_slotdef *p = slotdefs; p->name_strobj; p++) { + if (p->name_strobj == name) { + return slots_are_generic(type, name, slotdefs_dups[p - slotdefs], + refs); + } + } + return 0; +} +#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 @@ -12357,6 +12460,18 @@ _PyType_InitSlotDefs(PyInterpreterState *interp) return -1; } +#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 + pytype_slotdef *p; Py_ssize_t idx = 0; for (p = slotdefs; p->name_strobj; p++, idx++) {