Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions Lib/test/test_free_threading/test_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,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))
Expand Down Expand Up @@ -273,6 +278,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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
163 changes: 148 additions & 15 deletions Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3860,6 +3860,16 @@ static PyObject *object_new(PyTypeObject *, PyObject *, PyObject *);
static int object_init(PyObject *, PyObject *, PyObject *);
static int update_slot(PyTypeObject *, PyObject *);
static bool has_slotdef(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_new_set_names(PyTypeObject *);
static int type_new_init_subclass(PyTypeObject *, PyObject *);
Expand Down Expand Up @@ -6520,25 +6530,28 @@ type_update_dict(PyTypeObject *type, PyDictObject *dict, PyObject *name,
return -1;
}

if (is_dunder_name(name) && has_slotdef(name)) {
return 0;
}

#ifdef Py_GIL_DISABLED
static int
update_slot_after_setattr(PyTypeObject *type, PyObject *name, PyObject *value,
struct slot_update_refs *refs)
{
int res = 0;
if (!slot_update_is_noop(type, name, value, refs)) {
types_stop_world();
int res = update_slot(type, name);
res = update_slot(type, name);
types_start_world();
#ifdef Py_GIL_DISABLED
// TYPE_LOCK may have been released while waiting for stop-the-world.
// Invalidate any version tags assigned from the old slots.
ASSERT_TYPE_LOCK_HELD();
type_modified_unlocked(type);
#endif
if (res < 0) {
// On the default build, looking up the name in a subclass dict
// can call __eq__ of a str subclass key, which can fail.
return -1;
}
}

return 0;
// 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);
return res;
}
#endif

static int
type_setattro(PyObject *self, PyObject *name, PyObject *value)
Expand Down Expand Up @@ -6619,10 +6632,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.
#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);
Expand All @@ -6638,7 +6670,11 @@ type_dealloc_common(PyTypeObject *type)
PyObject *bases = lookup_tp_bases(type);
if (bases != NULL) {
PyObject *exc = PyErr_GetRaisedException();
// The type lock protects tp_subclasses of the bases from being
// mutated while another thread iterates over it.
BEGIN_TYPE_LOCK();
remove_all_subclasses(type, bases);
END_TYPE_LOCK();
PyErr_SetRaisedException(exc);
}
}
Expand Down Expand Up @@ -11836,6 +11872,103 @@ update_slot(PyTypeObject *type, PyObject *name)
update_slots_callback, (void *)ptrs);
}

#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, pytype_slotdef **defs,
struct slot_update_refs *refs)
{
ASSERT_TYPE_LOCK_HELD();

for (pytype_slotdef **pp = defs; *pp != NULL; pp++) {
pytype_slotdef *p = *pp;
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, defs, 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;
}

#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

/* Collect the slotdefs with this name, as update_slot() does. */
pytype_slotdef *defs[MAX_EQUIV];
pytype_slotdef **pp = defs;
for (pytype_slotdef *p = slotdefs; p->name; p++) {
if (p->name_strobj == name) {
*pp++ = p;
}
}
*pp = NULL;
if (defs[0] == NULL) {
return 0;
}
return slots_are_generic(type, name, defs, refs);
}
#endif

/* Store the proper functions in the slot dispatches at class (type)
definition time, based upon which operations the class overrides in its
dict. */
Expand Down
Loading