Skip to content

Commit c52b7a8

Browse files
naschemegpshead
andauthored
gh-162752: Skip stop-the-world when a type slot update changes nothing (gh-162763)
Fix a performance regression in the 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. Co-authored-by: Gregory P. Smith <greg@krypto.org>
1 parent 0423fc6 commit c52b7a8

3 files changed

Lines changed: 215 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
@@ -358,6 +358,11 @@ def custom_repr(self):
358358
self.assertTrue(all(repr(cls()) == "custom repr"
359359
for cls in subclasses))
360360

361+
# This time the slots are already generic. The fast check must
362+
# release the subclasses it visited before reaching its budget.
363+
Base.__repr__ = lambda self: "replacement"
364+
self.assertTrue(all(repr(cls()) == "replacement" for cls in subclasses))
365+
361366
del Base.__repr__
362367
self.assertTrue(all(repr(cls()) != "custom repr"
363368
for cls in subclasses))
@@ -500,6 +505,87 @@ class C(A, metaclass=Meta):
500505
C.__bases__ = (B,)
501506
self.assertEqual(C.__mro__, (C, B, object))
502507

508+
def test_slot_update_shadowed_branch(self):
509+
class Base:
510+
def __repr__(self):
511+
return "base"
512+
513+
class Target(Base):
514+
pass
515+
516+
class Override(Target):
517+
def __repr__(self):
518+
return "override"
519+
520+
class Native(Base):
521+
__repr__ = object.__repr__
522+
523+
class Inherit(Target, Native):
524+
pass
525+
526+
class Both(Override, Inherit):
527+
pass
528+
529+
# Target's slot is already generic, but Inherit gets its slot from
530+
# Native until Target defines __repr__ in its own dict.
531+
obj = Inherit()
532+
self.assertEqual(repr(obj), object.__repr__(obj))
533+
Target.__repr__ = lambda self: "new"
534+
self.assertEqual(repr(obj), "new")
535+
self.assertEqual(repr(Both()), "override")
536+
537+
def test_slot_update_unchanged_race(self):
538+
# Replacing a Python function with another one does not stop the
539+
# world if no slot changes. That is decided by looking at the slots
540+
# of the subclasses, while other threads change those slots and the
541+
# subclasses. At the end, the slots must agree with the MRO.
542+
N = 100
543+
544+
class Base:
545+
def __repr__(self):
546+
return "base"
547+
548+
class Target(Base):
549+
pass
550+
551+
class Native(Base):
552+
__repr__ = object.__repr__
553+
554+
class Inherit(Target, Native):
555+
pass
556+
557+
def swapper():
558+
# No slot changes.
559+
for _ in range(N):
560+
Base.__repr__ = lambda self: "base"
561+
562+
def toggler():
563+
# Inherit's slot alternates between generic and Native's.
564+
for _ in range(N):
565+
Target.__repr__ = lambda self: "target"
566+
del Target.__repr__
567+
568+
def rebaser():
569+
# Target's only subclass comes and goes.
570+
for _ in range(N):
571+
Inherit.__bases__ = (Native,)
572+
Inherit.__bases__ = (Target, Native)
573+
574+
def reader():
575+
for _ in range(N):
576+
self.assertEqual(repr(Base()), "base")
577+
self.assertIn(repr(Target()), ("base", "target"))
578+
repr(Inherit())
579+
580+
threading_helper.run_concurrently(
581+
[swapper, swapper, toggler, rebaser, reader] + world_stoppers())
582+
583+
obj = Inherit()
584+
self.assertEqual(repr(Target()), "base")
585+
self.assertEqual(repr(obj), object.__repr__(obj))
586+
Target.__repr__ = lambda self: "new"
587+
self.assertEqual(repr(obj), "new")
588+
503589
def test_slot_update_skips_non_str_keys(self):
504590
# Slots are computed (with the world stopped, for an update) without
505591
# 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: 125 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3894,6 +3894,16 @@ static void object_dealloc(PyObject *);
38943894
static PyObject *object_new(PyTypeObject *, PyObject *, PyObject *);
38953895
static int object_init(PyObject *, PyObject *, PyObject *);
38963896
static int update_slot(PyTypeObject *, PyObject *);
3897+
#ifdef Py_GIL_DISABLED
3898+
// Limit the work spent checking subclasses (including repeated visits in a
3899+
// diamond). Keep them alive until after releasing the type and dict locks.
3900+
struct slot_update_refs {
3901+
size_t count;
3902+
PyTypeObject *types[16]; // Small on-stack budget for subclass visits.
3903+
};
3904+
static int slot_update_is_noop(PyTypeObject *, PyObject *, PyObject *,
3905+
struct slot_update_refs *);
3906+
#endif
38973907
static void fixup_slot_dispatchers(PyTypeObject *);
38983908
static int type_ready(PyTypeObject *, int, int);
38993909
static int type_ready_publish(PyTypeObject *, int);
@@ -6717,23 +6727,25 @@ type_update_dict(PyTypeObject *type, PyDictObject *dict, PyObject *name,
67176727
return 0;
67186728
}
67196729

6730+
#ifdef Py_GIL_DISABLED
67206731
static int
6721-
update_slot_after_setattr(PyTypeObject *type, PyObject *name)
6732+
update_slot_after_setattr(PyTypeObject *type, PyObject *name, PyObject *value,
6733+
struct slot_update_refs *refs)
67226734
{
6723-
types_stop_world();
6724-
int res = update_slot(type, name);
6725-
types_start_world();
6726-
#ifdef Py_GIL_DISABLED
6727-
// Invalidate again, after the slots are updated and while TYPE_LOCK is
6728-
// still held. Other threads may have assigned new version tags while
6729-
// the lock was released waiting for the stop-the-world and cached
6730-
// decisions based on the old slots. This is a no-op if the tags are
6731-
// still invalid.
6735+
int res = 0;
6736+
if (!slot_update_is_noop(type, name, value, refs)) {
6737+
types_stop_world();
6738+
res = update_slot(type, name);
6739+
types_start_world();
6740+
}
6741+
// Invalidate again even if no slot changed. Comparing a non-str dict
6742+
// key during the write can cache the old method. Waiting for the world
6743+
// to stop can also let other threads cache decisions based on old slots.
67326744
ASSERT_TYPE_LOCK_HELD();
67336745
_PyType_Modified_Unlocked(type);
6734-
#endif
67356746
return res;
67366747
}
6748+
#endif
67376749

67386750
static int
67396751
type_setattro(PyObject *self, PyObject *name, PyObject *value)
@@ -6815,16 +6827,29 @@ type_setattro(PyObject *self, PyObject *name, PyObject *value)
68156827
}
68166828
}
68176829

6830+
#ifdef Py_GIL_DISABLED
6831+
struct slot_update_refs refs;
6832+
refs.count = 0;
6833+
#endif
68186834
BEGIN_TYPE_DICT_LOCK(dict);
68196835
res = type_update_dict(type, (PyDictObject *)dict, name, value, &old_value);
68206836
assert(_PyType_CheckConsistency(type));
68216837
if (res == 0) {
68226838
if (is_dunder_name(name) && has_slotdef(name)) {
68236839
// The name corresponds to a type slot.
6824-
res = update_slot_after_setattr(type, name);
6840+
#ifdef Py_GIL_DISABLED
6841+
res = update_slot_after_setattr(type, name, value, &refs);
6842+
#else
6843+
res = update_slot(type, name);
6844+
#endif
68256845
}
68266846
}
68276847
END_TYPE_DICT_LOCK();
6848+
#ifdef Py_GIL_DISABLED
6849+
for (size_t i = 0; i < refs.count; i++) {
6850+
Py_DECREF(refs.types[i]);
6851+
}
6852+
#endif
68286853

68296854
done:
68306855
Py_DECREF(name);
@@ -12336,6 +12361,82 @@ update_slot(PyTypeObject *type, PyObject *name)
1233612361
update_slots_callback, (void *)&callback_data);
1233712362
}
1233812363

12364+
#ifdef Py_GIL_DISABLED
12365+
/* Check the slots in 'type' and the subclasses update_slot() would visit. Note
12366+
* that this must be done without releasing TYPE_LOCK. */
12367+
static int
12368+
slots_are_generic(PyTypeObject *type, PyObject *name, const uint8_t *dups,
12369+
struct slot_update_refs *refs)
12370+
{
12371+
ASSERT_TYPE_LOCK_HELD();
12372+
12373+
for (uint8_t k = 1; k <= dups[0]; k++) {
12374+
pytype_slotdef *p = &slotdefs[dups[k]];
12375+
void **ptr = slotptr(type, p->offset);
12376+
if (ptr != NULL && *ptr != p->function) {
12377+
return 0;
12378+
}
12379+
if (p->function == slot_tp_call &&
12380+
(type->tp_flags & Py_TPFLAGS_HAVE_VECTORCALL)) {
12381+
return 0;
12382+
}
12383+
}
12384+
PyObject *subclasses = lookup_tp_subclasses(type); // borrowed ref
12385+
if (subclasses == NULL) {
12386+
return 1;
12387+
}
12388+
Py_ssize_t i = 0;
12389+
PyObject *ref;
12390+
while (PyDict_Next(subclasses, &i, NULL, &ref)) {
12391+
if (refs->count == Py_ARRAY_LENGTH(refs->types)) {
12392+
// Another visit would exceed the budget for the whole walk
12393+
// (including repeat visits). Fall back to the normal slot update.
12394+
return 0;
12395+
}
12396+
PyTypeObject *subclass = type_from_ref(ref);
12397+
if (subclass == NULL) {
12398+
return 0;
12399+
}
12400+
refs->types[refs->count++] = subclass;
12401+
12402+
// Prune at overrides, as in recurse_down_subclasses(). Don't block
12403+
// on the dict lock: detaching could release TYPE_LOCK mid-walk.
12404+
PyObject *dict = lookup_tp_dict(subclass);
12405+
if (dict == NULL || !PyDict_Check(dict) ||
12406+
!PyMutex_LockFast(&dict->ob_mutex)) {
12407+
return 0;
12408+
}
12409+
int overrides = _PyDict_GetItem_ExactUnicode((PyDictObject *)dict,
12410+
name) != NULL;
12411+
PyMutex_Unlock(&dict->ob_mutex);
12412+
if (!overrides && !slots_are_generic(subclass, name, dups, refs)) {
12413+
return 0;
12414+
}
12415+
// Iterating is only safe if TYPE_LOCK was never released.
12416+
assert(lookup_tp_subclasses(type) == subclasses);
12417+
}
12418+
return 1;
12419+
}
12420+
12421+
/* Return 1 if update_slot() would not change any slot after 'value' was
12422+
assigned to the slot name 'name' of 'type', so the stop-the-world can be
12423+
skipped. Return 0 if slots might change. */
12424+
static int
12425+
slot_update_is_noop(PyTypeObject *type, PyObject *name, PyObject *value,
12426+
struct slot_update_refs *refs)
12427+
{
12428+
ASSERT_TYPE_LOCK_HELD();
12429+
if (value == NULL || !PyFunction_Check(value)) {
12430+
return 0;
12431+
}
12432+
Py_ssize_t idx = slotname_lookup(name, _PyObject_HashDictKey(name));
12433+
if (idx < 0) {
12434+
return 0;
12435+
}
12436+
return slots_are_generic(type, name, slotdefs_dups[idx], refs);
12437+
}
12438+
#endif
12439+
1233912440
/* Store the proper functions in the slot dispatches at class (type)
1234012441
definition time, based upon which operations the class overrides in its
1234112442
dict. The type must not be revealed to other threads yet, so that the
@@ -12383,6 +12484,18 @@ _PyType_InitSlotDefs(PyInterpreterState *interp)
1238312484
}
1238412485
init_slotname_table();
1238512486

12487+
#ifndef NDEBUG
12488+
/* The slotdefs of a slot (they are adjacent) share one generic function,
12489+
which dispatches to all of their names. slots_are_generic() compares
12490+
a slot with the function of the slotdef for the assigned name, while
12491+
update_one_slot() stores that of whichever slotdef it handled last.
12492+
If they differed, that comparison could fail for up to date slots. */
12493+
for (pytype_slotdef *p = slotdefs + 1; p->name != NULL; p++) {
12494+
assert(p->offset != (p - 1)->offset
12495+
|| p->function == (p - 1)->function);
12496+
}
12497+
#endif
12498+
1238612499
/* Group the slotdefs by name: slotdefs_dups[i] lists the indices of
1238712500
all slotdefs with the same name as slotdefs[i], in slotdefs order. */
1238812501
memset(slotdefs_dups, 0, sizeof(slotdefs_dups));

0 commit comments

Comments
 (0)