Skip to content

Commit 00cefa8

Browse files
naschemegpshead
andauthored
[3.14] gh-162752: Skip stop-the-world when a type slot update changes nothing (gh-162763) (gh-162849)
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. The check walks tp_subclasses with only TYPE_LOCK held, so also hold TYPE_LOCK when type_dealloc() removes a type from the subclasses of its bases. That part of gh-151377 was not backported to 3.14. (cherry picked from commit c52b7a8) Co-authored-by: Gregory P. Smith <greg@krypto.org>
1 parent 1f1ce79 commit 00cefa8

3 files changed

Lines changed: 238 additions & 15 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
@@ -198,6 +198,11 @@ def custom_repr(self):
198198
self.assertTrue(all(repr(cls()) == "custom repr"
199199
for cls in subclasses))
200200

201+
# This time the slots are already generic. The fast check must
202+
# release the subclasses it visited before reaching its budget.
203+
Base.__repr__ = lambda self: "replacement"
204+
self.assertTrue(all(repr(cls()) == "replacement" for cls in subclasses))
205+
201206
del Base.__repr__
202207
self.assertTrue(all(repr(cls()) != "custom repr"
203208
for cls in subclasses))
@@ -273,6 +278,87 @@ class C(A, metaclass=Meta):
273278
C.__bases__ = (B,)
274279
self.assertEqual(C.__mro__, (C, B, object))
275280

281+
def test_slot_update_shadowed_branch(self):
282+
class Base:
283+
def __repr__(self):
284+
return "base"
285+
286+
class Target(Base):
287+
pass
288+
289+
class Override(Target):
290+
def __repr__(self):
291+
return "override"
292+
293+
class Native(Base):
294+
__repr__ = object.__repr__
295+
296+
class Inherit(Target, Native):
297+
pass
298+
299+
class Both(Override, Inherit):
300+
pass
301+
302+
# Target's slot is already generic, but Inherit gets its slot from
303+
# Native until Target defines __repr__ in its own dict.
304+
obj = Inherit()
305+
self.assertEqual(repr(obj), object.__repr__(obj))
306+
Target.__repr__ = lambda self: "new"
307+
self.assertEqual(repr(obj), "new")
308+
self.assertEqual(repr(Both()), "override")
309+
310+
def test_slot_update_unchanged_race(self):
311+
# Replacing a Python function with another one does not stop the
312+
# world if no slot changes. That is decided by looking at the slots
313+
# of the subclasses, while other threads change those slots and the
314+
# subclasses. At the end, the slots must agree with the MRO.
315+
N = 100
316+
317+
class Base:
318+
def __repr__(self):
319+
return "base"
320+
321+
class Target(Base):
322+
pass
323+
324+
class Native(Base):
325+
__repr__ = object.__repr__
326+
327+
class Inherit(Target, Native):
328+
pass
329+
330+
def swapper():
331+
# No slot changes.
332+
for _ in range(N):
333+
Base.__repr__ = lambda self: "base"
334+
335+
def toggler():
336+
# Inherit's slot alternates between generic and Native's.
337+
for _ in range(N):
338+
Target.__repr__ = lambda self: "target"
339+
del Target.__repr__
340+
341+
def rebaser():
342+
# Target's only subclass comes and goes.
343+
for _ in range(N):
344+
Inherit.__bases__ = (Native,)
345+
Inherit.__bases__ = (Target, Native)
346+
347+
def reader():
348+
for _ in range(N):
349+
self.assertEqual(repr(Base()), "base")
350+
self.assertIn(repr(Target()), ("base", "target"))
351+
repr(Inherit())
352+
353+
threading_helper.run_concurrently(
354+
[swapper, swapper, toggler, rebaser, reader] + world_stoppers())
355+
356+
obj = Inherit()
357+
self.assertEqual(repr(Target()), "base")
358+
self.assertEqual(repr(obj), object.__repr__(obj))
359+
Target.__repr__ = lambda self: "new"
360+
self.assertEqual(repr(obj), "new")
361+
276362
def test_slot_update_skips_non_str_keys(self):
277363
# Slots are computed (with the world stopped, for an update) without
278364
# 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: 148 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3860,6 +3860,16 @@ static PyObject *object_new(PyTypeObject *, PyObject *, PyObject *);
38603860
static int object_init(PyObject *, PyObject *, PyObject *);
38613861
static int update_slot(PyTypeObject *, PyObject *);
38623862
static bool has_slotdef(PyObject *);
3863+
#ifdef Py_GIL_DISABLED
3864+
// Limit the work spent checking subclasses (including repeated visits in a
3865+
// diamond). Keep them alive until after releasing the type and dict locks.
3866+
struct slot_update_refs {
3867+
size_t count;
3868+
PyTypeObject *types[16]; // Small on-stack budget for subclass visits.
3869+
};
3870+
static int slot_update_is_noop(PyTypeObject *, PyObject *, PyObject *,
3871+
struct slot_update_refs *);
3872+
#endif
38633873
static void fixup_slot_dispatchers(PyTypeObject *);
38643874
static int type_new_set_names(PyTypeObject *);
38653875
static int type_new_init_subclass(PyTypeObject *, PyObject *);
@@ -6520,25 +6530,28 @@ type_update_dict(PyTypeObject *type, PyDictObject *dict, PyObject *name,
65206530
return -1;
65216531
}
65226532

6523-
if (is_dunder_name(name) && has_slotdef(name)) {
6533+
return 0;
6534+
}
6535+
6536+
#ifdef Py_GIL_DISABLED
6537+
static int
6538+
update_slot_after_setattr(PyTypeObject *type, PyObject *name, PyObject *value,
6539+
struct slot_update_refs *refs)
6540+
{
6541+
int res = 0;
6542+
if (!slot_update_is_noop(type, name, value, refs)) {
65246543
types_stop_world();
6525-
int res = update_slot(type, name);
6544+
res = update_slot(type, name);
65266545
types_start_world();
6527-
#ifdef Py_GIL_DISABLED
6528-
// TYPE_LOCK may have been released while waiting for stop-the-world.
6529-
// Invalidate any version tags assigned from the old slots.
6530-
ASSERT_TYPE_LOCK_HELD();
6531-
type_modified_unlocked(type);
6532-
#endif
6533-
if (res < 0) {
6534-
// On the default build, looking up the name in a subclass dict
6535-
// can call __eq__ of a str subclass key, which can fail.
6536-
return -1;
6537-
}
65386546
}
6539-
6540-
return 0;
6547+
// Invalidate again even if no slot changed. Comparing a non-str dict
6548+
// key during the write can cache the old method. Waiting for the world
6549+
// to stop can also let other threads cache decisions based on old slots.
6550+
ASSERT_TYPE_LOCK_HELD();
6551+
type_modified_unlocked(type);
6552+
return res;
65416553
}
6554+
#endif
65426555

65436556
static int
65446557
type_setattro(PyObject *self, PyObject *name, PyObject *value)
@@ -6619,10 +6632,29 @@ type_setattro(PyObject *self, PyObject *name, PyObject *value)
66196632
}
66206633
}
66216634

6635+
#ifdef Py_GIL_DISABLED
6636+
struct slot_update_refs refs;
6637+
refs.count = 0;
6638+
#endif
66226639
BEGIN_TYPE_DICT_LOCK(dict);
66236640
res = type_update_dict(type, (PyDictObject *)dict, name, value, &old_value);
66246641
assert(_PyType_CheckConsistency(type));
6642+
if (res == 0) {
6643+
if (is_dunder_name(name) && has_slotdef(name)) {
6644+
// The name corresponds to a type slot.
6645+
#ifdef Py_GIL_DISABLED
6646+
res = update_slot_after_setattr(type, name, value, &refs);
6647+
#else
6648+
res = update_slot(type, name);
6649+
#endif
6650+
}
6651+
}
66256652
END_TYPE_DICT_LOCK();
6653+
#ifdef Py_GIL_DISABLED
6654+
for (size_t i = 0; i < refs.count; i++) {
6655+
Py_DECREF(refs.types[i]);
6656+
}
6657+
#endif
66266658

66276659
done:
66286660
Py_DECREF(name);
@@ -6638,7 +6670,11 @@ type_dealloc_common(PyTypeObject *type)
66386670
PyObject *bases = lookup_tp_bases(type);
66396671
if (bases != NULL) {
66406672
PyObject *exc = PyErr_GetRaisedException();
6673+
// The type lock protects tp_subclasses of the bases from being
6674+
// mutated while another thread iterates over it.
6675+
BEGIN_TYPE_LOCK();
66416676
remove_all_subclasses(type, bases);
6677+
END_TYPE_LOCK();
66426678
PyErr_SetRaisedException(exc);
66436679
}
66446680
}
@@ -11836,6 +11872,103 @@ update_slot(PyTypeObject *type, PyObject *name)
1183611872
update_slots_callback, (void *)ptrs);
1183711873
}
1183811874

11875+
#ifdef Py_GIL_DISABLED
11876+
/* Check the slots in 'type' and the subclasses update_slot() would visit. Note
11877+
* that this must be done without releasing TYPE_LOCK. */
11878+
static int
11879+
slots_are_generic(PyTypeObject *type, PyObject *name, pytype_slotdef **defs,
11880+
struct slot_update_refs *refs)
11881+
{
11882+
ASSERT_TYPE_LOCK_HELD();
11883+
11884+
for (pytype_slotdef **pp = defs; *pp != NULL; pp++) {
11885+
pytype_slotdef *p = *pp;
11886+
void **ptr = slotptr(type, p->offset);
11887+
if (ptr != NULL && *ptr != p->function) {
11888+
return 0;
11889+
}
11890+
if (p->function == slot_tp_call &&
11891+
(type->tp_flags & Py_TPFLAGS_HAVE_VECTORCALL)) {
11892+
return 0;
11893+
}
11894+
}
11895+
PyObject *subclasses = lookup_tp_subclasses(type); // borrowed ref
11896+
if (subclasses == NULL) {
11897+
return 1;
11898+
}
11899+
Py_ssize_t i = 0;
11900+
PyObject *ref;
11901+
while (PyDict_Next(subclasses, &i, NULL, &ref)) {
11902+
if (refs->count == Py_ARRAY_LENGTH(refs->types)) {
11903+
// Another visit would exceed the budget for the whole walk
11904+
// (including repeat visits). Fall back to the normal slot update.
11905+
return 0;
11906+
}
11907+
PyTypeObject *subclass = type_from_ref(ref);
11908+
if (subclass == NULL) {
11909+
return 0;
11910+
}
11911+
refs->types[refs->count++] = subclass;
11912+
11913+
// Prune at overrides, as in recurse_down_subclasses(). Don't block
11914+
// on the dict lock: detaching could release TYPE_LOCK mid-walk.
11915+
PyObject *dict = lookup_tp_dict(subclass);
11916+
if (dict == NULL || !PyDict_Check(dict) ||
11917+
!PyMutex_LockFast(&dict->ob_mutex)) {
11918+
return 0;
11919+
}
11920+
int overrides = _PyDict_GetItem_ExactUnicode((PyDictObject *)dict,
11921+
name) != NULL;
11922+
PyMutex_Unlock(&dict->ob_mutex);
11923+
if (!overrides && !slots_are_generic(subclass, name, defs, refs)) {
11924+
return 0;
11925+
}
11926+
// Iterating is only safe if TYPE_LOCK was never released.
11927+
assert(lookup_tp_subclasses(type) == subclasses);
11928+
}
11929+
return 1;
11930+
}
11931+
11932+
/* Return 1 if update_slot() would not change any slot after 'value' was
11933+
assigned to the slot name 'name' of 'type', so the stop-the-world can be
11934+
skipped. Return 0 if slots might change. */
11935+
static int
11936+
slot_update_is_noop(PyTypeObject *type, PyObject *name, PyObject *value,
11937+
struct slot_update_refs *refs)
11938+
{
11939+
ASSERT_TYPE_LOCK_HELD();
11940+
if (value == NULL || !PyFunction_Check(value)) {
11941+
return 0;
11942+
}
11943+
11944+
#ifndef NDEBUG
11945+
/* The slotdefs of a slot (they are adjacent) share one generic function,
11946+
which dispatches to all of their names. slots_are_generic() compares
11947+
a slot with the function of the slotdef for the assigned name, while
11948+
update_one_slot() stores that of whichever slotdef it handled last.
11949+
If they differed, that comparison could fail for up to date slots. */
11950+
for (pytype_slotdef *p = slotdefs + 1; p->name != NULL; p++) {
11951+
assert(p->offset != (p - 1)->offset
11952+
|| p->function == (p - 1)->function);
11953+
}
11954+
#endif
11955+
11956+
/* Collect the slotdefs with this name, as update_slot() does. */
11957+
pytype_slotdef *defs[MAX_EQUIV];
11958+
pytype_slotdef **pp = defs;
11959+
for (pytype_slotdef *p = slotdefs; p->name; p++) {
11960+
if (p->name_strobj == name) {
11961+
*pp++ = p;
11962+
}
11963+
}
11964+
*pp = NULL;
11965+
if (defs[0] == NULL) {
11966+
return 0;
11967+
}
11968+
return slots_are_generic(type, name, defs, refs);
11969+
}
11970+
#endif
11971+
1183911972
/* Store the proper functions in the slot dispatches at class (type)
1184011973
definition time, based upon which operations the class overrides in its
1184111974
dict. */

0 commit comments

Comments
 (0)