Skip to content

Commit 8547347

Browse files
authored
[3.15] gh-162752: Skip stop-the-world when a type slot update changes nothing (gh-162763) (gh-162848)
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. (cherry picked from commit c52b7a8) Co-authored-by: Gregory P. Smith greg@krypto.org
1 parent ea43811 commit 8547347

3 files changed

Lines changed: 217 additions & 12 deletions

File tree

‎Lib/test/test_free_threading/test_type.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,11 @@ def custom_repr(self):
217217
self.assertTrue(all(repr(cls()) == "custom repr"
218218
for cls in subclasses))
219219

220+
# This time the slots are already generic. The fast check must
221+
# release the subclasses it visited before reaching its budget.
222+
Base.__repr__ = lambda self: "replacement"
223+
self.assertTrue(all(repr(cls()) == "replacement" for cls in subclasses))
224+
220225
del Base.__repr__
221226
self.assertTrue(all(repr(cls()) != "custom repr"
222227
for cls in subclasses))
@@ -349,6 +354,87 @@ class C(A, metaclass=Meta):
349354
C.__bases__ = (B,)
350355
self.assertEqual(C.__mro__, (C, B, object))
351356

357+
def test_slot_update_shadowed_branch(self):
358+
class Base:
359+
def __repr__(self):
360+
return "base"
361+
362+
class Target(Base):
363+
pass
364+
365+
class Override(Target):
366+
def __repr__(self):
367+
return "override"
368+
369+
class Native(Base):
370+
__repr__ = object.__repr__
371+
372+
class Inherit(Target, Native):
373+
pass
374+
375+
class Both(Override, Inherit):
376+
pass
377+
378+
# Target's slot is already generic, but Inherit gets its slot from
379+
# Native until Target defines __repr__ in its own dict.
380+
obj = Inherit()
381+
self.assertEqual(repr(obj), object.__repr__(obj))
382+
Target.__repr__ = lambda self: "new"
383+
self.assertEqual(repr(obj), "new")
384+
self.assertEqual(repr(Both()), "override")
385+
386+
def test_slot_update_unchanged_race(self):
387+
# Replacing a Python function with another one does not stop the
388+
# world if no slot changes. That is decided by looking at the slots
389+
# of the subclasses, while other threads change those slots and the
390+
# subclasses. At the end, the slots must agree with the MRO.
391+
N = 100
392+
393+
class Base:
394+
def __repr__(self):
395+
return "base"
396+
397+
class Target(Base):
398+
pass
399+
400+
class Native(Base):
401+
__repr__ = object.__repr__
402+
403+
class Inherit(Target, Native):
404+
pass
405+
406+
def swapper():
407+
# No slot changes.
408+
for _ in range(N):
409+
Base.__repr__ = lambda self: "base"
410+
411+
def toggler():
412+
# Inherit's slot alternates between generic and Native's.
413+
for _ in range(N):
414+
Target.__repr__ = lambda self: "target"
415+
del Target.__repr__
416+
417+
def rebaser():
418+
# Target's only subclass comes and goes.
419+
for _ in range(N):
420+
Inherit.__bases__ = (Native,)
421+
Inherit.__bases__ = (Target, Native)
422+
423+
def reader():
424+
for _ in range(N):
425+
self.assertEqual(repr(Base()), "base")
426+
self.assertIn(repr(Target()), ("base", "target"))
427+
repr(Inherit())
428+
429+
threading_helper.run_concurrently(
430+
[swapper, swapper, toggler, rebaser, reader] + world_stoppers())
431+
432+
obj = Inherit()
433+
self.assertEqual(repr(Target()), "base")
434+
self.assertEqual(repr(obj), object.__repr__(obj))
435+
Target.__repr__ = lambda self: "new"
436+
self.assertEqual(repr(obj), "new")
437+
352438
def test_slot_update_skips_non_str_keys(self):
353439
# Slots are computed (with the world stopped, for an update) without
354440
# comparing the slot name with non-str keys of the type dicts, which
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix a performance regression in the :term:`free-threaded build` when
2+
assigning a special method to a class, such as ``C.__getitem__ = f``, while
3+
other threads are running. Replacing a Python function with another can now
4+
avoid stopping the world when the type slots are already up to date.

‎Objects/typeobject.c‎

Lines changed: 127 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3945,6 +3945,16 @@ static void object_dealloc(PyObject *);
39453945
static PyObject *object_new(PyTypeObject *, PyObject *, PyObject *);
39463946
static int object_init(PyObject *, PyObject *, PyObject *);
39473947
static int update_slot(PyTypeObject *, PyObject *);
3948+
#ifdef Py_GIL_DISABLED
3949+
// Limit the work spent checking subclasses (including repeated visits in a
3950+
// diamond). Keep them alive until after releasing the type and dict locks.
3951+
struct slot_update_refs {
3952+
size_t count;
3953+
PyTypeObject *types[16]; // Small on-stack budget for subclass visits.
3954+
};
3955+
static int slot_update_is_noop(PyTypeObject *, PyObject *, PyObject *,
3956+
struct slot_update_refs *);
3957+
#endif
39483958
static void fixup_slot_dispatchers(PyTypeObject *);
39493959
static int type_ready(PyTypeObject *, int, int);
39503960
static int type_ready_publish(PyTypeObject *, int);
@@ -6839,23 +6849,25 @@ type_update_dict(PyTypeObject *type, PyDictObject *dict, PyObject *name,
68396849
return 0;
68406850
}
68416851

6852+
#ifdef Py_GIL_DISABLED
68426853
static int
6843-
update_slot_after_setattr(PyTypeObject *type, PyObject *name)
6854+
update_slot_after_setattr(PyTypeObject *type, PyObject *name, PyObject *value,
6855+
struct slot_update_refs *refs)
68446856
{
6845-
types_stop_world();
6846-
int res = update_slot(type, name);
6847-
types_start_world();
6848-
#ifdef Py_GIL_DISABLED
6849-
// Invalidate again, after the slots are updated and while TYPE_LOCK is
6850-
// still held. Other threads may have assigned new version tags while
6851-
// the lock was released waiting for the stop-the-world and cached
6852-
// decisions based on the old slots. This is a no-op if the tags are
6853-
// still invalid.
6857+
int res = 0;
6858+
if (!slot_update_is_noop(type, name, value, refs)) {
6859+
types_stop_world();
6860+
res = update_slot(type, name);
6861+
types_start_world();
6862+
}
6863+
// Invalidate again even if no slot changed. Comparing a non-str dict
6864+
// key during the write can cache the old method. Waiting for the world
6865+
// to stop can also let other threads cache decisions based on old slots.
68546866
ASSERT_TYPE_LOCK_HELD();
68556867
type_modified_unlocked(type);
6856-
#endif
68576868
return res;
68586869
}
6870+
#endif
68596871

68606872
static int
68616873
type_setattro(PyObject *self, PyObject *name, PyObject *value)
@@ -6937,16 +6949,29 @@ type_setattro(PyObject *self, PyObject *name, PyObject *value)
69376949
}
69386950
}
69396951

6952+
#ifdef Py_GIL_DISABLED
6953+
struct slot_update_refs refs;
6954+
refs.count = 0;
6955+
#endif
69406956
BEGIN_TYPE_DICT_LOCK(dict);
69416957
res = type_update_dict(type, (PyDictObject *)dict, name, value, &old_value);
69426958
assert(_PyType_CheckConsistency(type));
69436959
if (res == 0) {
69446960
if (is_dunder_name(name) && has_slotdef(name)) {
69456961
// The name corresponds to a type slot.
6946-
res = update_slot_after_setattr(type, name);
6962+
#ifdef Py_GIL_DISABLED
6963+
res = update_slot_after_setattr(type, name, value, &refs);
6964+
#else
6965+
res = update_slot(type, name);
6966+
#endif
69476967
}
69486968
}
69496969
END_TYPE_DICT_LOCK();
6970+
#ifdef Py_GIL_DISABLED
6971+
for (size_t i = 0; i < refs.count; i++) {
6972+
Py_DECREF(refs.types[i]);
6973+
}
6974+
#endif
69506975

69516976
done:
69526977
Py_DECREF(name);
@@ -12314,6 +12339,84 @@ update_slot(PyTypeObject *type, PyObject *name)
1231412339
update_slots_callback, (void *)&callback_data);
1231512340
}
1231612341

12342+
#ifdef Py_GIL_DISABLED
12343+
/* Check the slots in 'type' and the subclasses update_slot() would visit. Note
12344+
* that this must be done without releasing TYPE_LOCK. */
12345+
static int
12346+
slots_are_generic(PyTypeObject *type, PyObject *name, const uint8_t *dups,
12347+
struct slot_update_refs *refs)
12348+
{
12349+
ASSERT_TYPE_LOCK_HELD();
12350+
12351+
for (uint8_t k = 1; k <= dups[0]; k++) {
12352+
pytype_slotdef *p = &slotdefs[dups[k]];
12353+
void **ptr = slotptr(type, p->offset);
12354+
if (ptr != NULL && *ptr != p->function) {
12355+
return 0;
12356+
}
12357+
if (p->function == slot_tp_call &&
12358+
(type->tp_flags & Py_TPFLAGS_HAVE_VECTORCALL)) {
12359+
return 0;
12360+
}
12361+
}
12362+
PyObject *subclasses = lookup_tp_subclasses(type); // borrowed ref
12363+
if (subclasses == NULL) {
12364+
return 1;
12365+
}
12366+
Py_ssize_t i = 0;
12367+
PyObject *ref;
12368+
while (PyDict_Next(subclasses, &i, NULL, &ref)) {
12369+
if (refs->count == Py_ARRAY_LENGTH(refs->types)) {
12370+
// Another visit would exceed the budget for the whole walk
12371+
// (including repeat visits). Fall back to the normal slot update.
12372+
return 0;
12373+
}
12374+
PyTypeObject *subclass = type_from_ref(ref);
12375+
if (subclass == NULL) {
12376+
return 0;
12377+
}
12378+
refs->types[refs->count++] = subclass;
12379+
12380+
// Prune at overrides, as in recurse_down_subclasses(). Don't block
12381+
// on the dict lock: detaching could release TYPE_LOCK mid-walk.
12382+
PyObject *dict = lookup_tp_dict(subclass);
12383+
if (dict == NULL || !PyDict_Check(dict) ||
12384+
!PyMutex_LockFast(&dict->ob_mutex)) {
12385+
return 0;
12386+
}
12387+
int overrides = _PyDict_GetItem_ExactUnicode((PyDictObject *)dict,
12388+
name) != NULL;
12389+
PyMutex_Unlock(&dict->ob_mutex);
12390+
if (!overrides && !slots_are_generic(subclass, name, dups, refs)) {
12391+
return 0;
12392+
}
12393+
// Iterating is only safe if TYPE_LOCK was never released.
12394+
assert(lookup_tp_subclasses(type) == subclasses);
12395+
}
12396+
return 1;
12397+
}
12398+
12399+
/* Return 1 if update_slot() would not change any slot after 'value' was
12400+
assigned to the slot name 'name' of 'type', so the stop-the-world can be
12401+
skipped. Return 0 if slots might change. */
12402+
static int
12403+
slot_update_is_noop(PyTypeObject *type, PyObject *name, PyObject *value,
12404+
struct slot_update_refs *refs)
12405+
{
12406+
ASSERT_TYPE_LOCK_HELD();
12407+
if (value == NULL || !PyFunction_Check(value)) {
12408+
return 0;
12409+
}
12410+
for (pytype_slotdef *p = slotdefs; p->name_strobj; p++) {
12411+
if (p->name_strobj == name) {
12412+
return slots_are_generic(type, name, slotdefs_dups[p - slotdefs],
12413+
refs);
12414+
}
12415+
}
12416+
return 0;
12417+
}
12418+
#endif
12419+
1231712420
/* Store the proper functions in the slot dispatches at class (type)
1231812421
definition time, based upon which operations the class overrides in its
1231912422
dict. The type must not be revealed to other threads yet, so that the
@@ -12357,6 +12460,18 @@ _PyType_InitSlotDefs(PyInterpreterState *interp)
1235712460
return -1;
1235812461
}
1235912462

12463+
#ifndef NDEBUG
12464+
/* The slotdefs of a slot (they are adjacent) share one generic function,
12465+
which dispatches to all of their names. slots_are_generic() compares
12466+
a slot with the function of the slotdef for the assigned name, while
12467+
update_one_slot() stores that of whichever slotdef it handled last.
12468+
If they differed, that comparison could fail for up to date slots. */
12469+
for (pytype_slotdef *p = slotdefs + 1; p->name != NULL; p++) {
12470+
assert(p->offset != (p - 1)->offset
12471+
|| p->function == (p - 1)->function);
12472+
}
12473+
#endif
12474+
1236012475
pytype_slotdef *p;
1236112476
Py_ssize_t idx = 0;
1236212477
for (p = slotdefs; p->name_strobj; p++, idx++) {

0 commit comments

Comments
 (0)