Skip to content

Commit 9c7def0

Browse files
committed
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.
1 parent b6a5ee6 commit 9c7def0

3 files changed

Lines changed: 158 additions & 69 deletions

File tree

‎Lib/test/test_free_threading/test_type.py‎

Lines changed: 34 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,35 @@ 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+
503537
def test_slot_update_skips_non_str_keys(self):
504538
# Slots are computed (with the world stopped, for an update) without
505539
# comparing the slot name with non-str keys of the type dicts, which
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
Fix a performance regression in the :term:`free-threaded build` when
22
assigning a special method to a class, such as ``C.__getitem__ = f``, while
3-
other threads are running. The world is no longer stopped if no type slot
4-
would change.
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: 122 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -3888,14 +3888,22 @@ solid_base(PyTypeObject *type)
38883888
/// data passed to update_slots_callback()
38893889
typedef struct {
38903890
pytype_slotdef **defs;
3891-
// If not NULL, only check if any slot would change, setting *changed.
3892-
bool *changed;
38933891
} update_callback_data_t;
38943892

38953893
static void object_dealloc(PyObject *);
38963894
static PyObject *object_new(PyTypeObject *, PyObject *, PyObject *);
38973895
static int object_init(PyObject *, PyObject *, PyObject *);
3898-
static int update_slot(PyTypeObject *, PyObject *, bool *);
3896+
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
38993907
static void fixup_slot_dispatchers(PyTypeObject *);
39003908
static int type_ready(PyTypeObject *, int, int);
39013909
static int type_ready_publish(PyTypeObject *, int);
@@ -6719,37 +6727,25 @@ type_update_dict(PyTypeObject *type, PyDictObject *dict, PyObject *name,
67196727
return 0;
67206728
}
67216729

6730+
#ifdef Py_GIL_DISABLED
67226731
static int
6723-
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)
67246734
{
6725-
#ifdef Py_GIL_DISABLED
6726-
// Check if we actually need to update the slot. If not, we can skip the
6727-
// STW, which can be expensive. This is pretty common since assigning a new
6728-
// function to an existing slot name, like "C.__getitem__ = f", usually
6729-
// changes no slot.
6730-
ASSERT_TYPE_LOCK_HELD();
6731-
bool changed = false;
6732-
if (update_slot(type, name, &changed) < 0) {
6733-
return -1;
6734-
}
6735-
if (!changed) {
6736-
return 0;
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();
67376740
}
6738-
#endif
6739-
types_stop_world();
6740-
int res = update_slot(type, name, NULL);
6741-
types_start_world();
6742-
#ifdef Py_GIL_DISABLED
6743-
// Invalidate again, after the slots are updated and while TYPE_LOCK is
6744-
// still held. Other threads may have assigned new version tags while
6745-
// the lock was released waiting for the stop-the-world and cached
6746-
// decisions based on the old slots. This is a no-op if the tags are
6747-
// still invalid.
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.
67486744
ASSERT_TYPE_LOCK_HELD();
67496745
_PyType_Modified_Unlocked(type);
6750-
#endif
67516746
return res;
67526747
}
6748+
#endif
67536749

67546750
static int
67556751
type_setattro(PyObject *self, PyObject *name, PyObject *value)
@@ -6831,16 +6827,29 @@ type_setattro(PyObject *self, PyObject *name, PyObject *value)
68316827
}
68326828
}
68336829

6830+
#ifdef Py_GIL_DISABLED
6831+
struct slot_update_refs refs;
6832+
refs.count = 0;
6833+
#endif
68346834
BEGIN_TYPE_DICT_LOCK(dict);
68356835
res = type_update_dict(type, (PyDictObject *)dict, name, value, &old_value);
68366836
assert(_PyType_CheckConsistency(type));
68376837
if (res == 0) {
68386838
if (is_dunder_name(name) && has_slotdef(name)) {
68396839
// The name corresponds to a type slot.
6840-
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
68416845
}
68426846
}
68436847
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
68446853

68456854
done:
68466855
Py_DECREF(name);
@@ -12138,14 +12147,11 @@ collect_slot_descrs(PyTypeObject *type, PyObject **descrs)
1213812147
* If descrs is not NULL, it holds the descriptors found by
1213912148
* collect_slot_descrs() and no lookups are done.
1214012149
*
12141-
* If changed is not NULL, the type is not modified. Instead, *changed is
12142-
* set to true if the slot (or tp_flags) would be changed.
12143-
*
1214412150
* Exceptions that occur internally are ignored, such as when looking up
1214512151
* descriptors. */
1214612152
static void
1214712153
update_one_slot(PyTypeObject *type, pytype_slotdef *p, pytype_slotdef **next_p,
12148-
PyObject **descrs, bool *changed)
12154+
PyObject **descrs)
1214912155
{
1215012156
ASSERT_NEW_TYPE_OR_LOCKED(type);
1215112157

@@ -12283,14 +12289,7 @@ update_one_slot(PyTypeObject *type, pytype_slotdef *p, pytype_slotdef **next_p,
1228312289
}
1228412290
if (p->function == slot_tp_call) {
1228512291
/* A generic __call__ is incompatible with vectorcall */
12286-
if (changed != NULL) {
12287-
if (type->tp_flags & Py_TPFLAGS_HAVE_VECTORCALL) {
12288-
*changed = true;
12289-
}
12290-
}
12291-
else {
12292-
type_clear_flags(type, Py_TPFLAGS_HAVE_VECTORCALL);
12293-
}
12292+
type_clear_flags(type, Py_TPFLAGS_HAVE_VECTORCALL);
1229412293
}
1229512294
}
1229612295
PyStackRef_CLOSE(descr_ref);
@@ -12303,15 +12302,8 @@ update_one_slot(PyTypeObject *type, pytype_slotdef *p, pytype_slotdef **next_p,
1230312302
slot_value = generic;
1230412303
}
1230512304

12306-
if (changed != NULL) {
12307-
if (*ptr != slot_value) {
12308-
*changed = true;
12309-
}
12310-
}
12311-
else {
12312-
ASSERT_WORLD_STOPPED_OR_NEW_TYPE(type);
12313-
*ptr = slot_value;
12314-
}
12305+
ASSERT_WORLD_STOPPED_OR_NEW_TYPE(type);
12306+
*ptr = slot_value;
1231512307

1231612308
if (next_p != NULL) {
1231712309
*next_p = p;
@@ -12326,23 +12318,17 @@ update_slots_callback(PyTypeObject *type, void *data)
1232612318
ASSERT_NEW_TYPE_OR_LOCKED(type);
1232712319

1232812320
update_callback_data_t *update_data = (update_callback_data_t *)data;
12329-
bool *changed = update_data->changed;
1233012321
pytype_slotdef **pp = update_data->defs;
1233112322
for (; *pp; pp++) {
12332-
if (changed != NULL && *changed) {
12333-
break; // already known that an update is needed
12334-
}
12335-
update_one_slot(type, *pp, NULL, NULL, changed);
12323+
update_one_slot(type, *pp, NULL, NULL);
1233612324
}
1233712325
return 0;
1233812326
}
1233912327

1234012328
/* Update the slots after assignment to a class (type) attribute. In the
12341-
free-threaded build, this is called with the world stopped. If changed is
12342-
not NULL, nothing is updated and *changed is set to true if any slot of the
12343-
type or its subclasses would change. */
12329+
free-threaded build, this is called with the world stopped. */
1234412330
static int
12345-
update_slot(PyTypeObject *type, PyObject *name, bool *changed)
12331+
update_slot(PyTypeObject *type, PyObject *name)
1234612332
{
1234712333
pytype_slotdef *ptrs[MAX_EQUIV];
1234812334
pytype_slotdef *p;
@@ -12371,11 +12357,84 @@ update_slot(PyTypeObject *type, PyObject *name, bool *changed)
1237112357

1237212358
update_callback_data_t callback_data;
1237312359
callback_data.defs = ptrs;
12374-
callback_data.changed = changed;
1237512360
return update_subclasses(type, name,
1237612361
update_slots_callback, (void *)&callback_data);
1237712362
}
1237812363

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+
}
12416+
return 1;
12417+
}
12418+
12419+
/* Return 1 if update_slot() would not change any slot after 'value' was
12420+
assigned to the slot name 'name' of 'type', so the stop-the-world can be
12421+
skipped. Return 0 if slots might change. */
12422+
static int
12423+
slot_update_is_noop(PyTypeObject *type, PyObject *name, PyObject *value,
12424+
struct slot_update_refs *refs)
12425+
{
12426+
ASSERT_TYPE_LOCK_HELD();
12427+
if (value == NULL || !PyFunction_Check(value)) {
12428+
return 0;
12429+
}
12430+
Py_ssize_t idx = slotname_lookup(name, _PyObject_HashDictKey(name));
12431+
if (idx < 0) {
12432+
return 0;
12433+
}
12434+
return slots_are_generic(type, name, slotdefs_dups[idx], refs);
12435+
}
12436+
#endif
12437+
1237912438
/* Store the proper functions in the slot dispatches at class (type)
1238012439
definition time, based upon which operations the class overrides in its
1238112440
dict. The type must not be revealed to other threads yet, so that the
@@ -12392,7 +12451,7 @@ fixup_slot_dispatchers(PyTypeObject *type)
1239212451
descrs = NULL;
1239312452
}
1239412453
for (pytype_slotdef *p = slotdefs; p->name; ) {
12395-
update_one_slot(type, p, &p, descrs, NULL);
12454+
update_one_slot(type, p, &p, descrs);
1239612455
}
1239712456
if (descrs != NULL) {
1239812457
clear_slot_descrs(descrs);
@@ -12407,7 +12466,7 @@ update_all_slots(PyTypeObject* type)
1240712466
types_stop_world();
1240812467
for (pytype_slotdef *p = slotdefs; p->name; p++) {
1240912468
/* update_slot returns int but can't actually fail in this case*/
12410-
update_slot(type, p->name_strobj, NULL);
12469+
update_slot(type, p->name_strobj);
1241112470
}
1241212471
types_start_world();
1241312472
// Invalidate the version tags after the slots are updated, while
@@ -12575,12 +12634,8 @@ recurse_down_subclasses(PyTypeObject *type, PyObject *attr_name,
1257512634
// With the world stopped, use borrowed references to the subclasses,
1257612635
// so that dropping a reference cannot run type_dealloc(). Look up
1257712636
// attr_name without calling __eq__ of non-str keys, consistent with
12578-
// find_slot_name_in_mro(). This is also done with only TYPE_LOCK held
12579-
// when checking for slot changes (see update_slot()). That is safe
12580-
// too: type_dealloc() removes the type from tp_subclasses, which
12581-
// requires TYPE_LOCK, before it tears down the type, and the type
12582-
// dicts are only modified with TYPE_LOCK held.
12583-
ASSERT_TYPE_LOCK_HELD();
12637+
// find_slot_name_in_mro().
12638+
assert(types_world_is_stopped());
1258412639
if (_PyWeakref_IS_DEAD(ref)) {
1258512640
continue;
1258612641
}

0 commit comments

Comments
 (0)