From bec6f10e2d84917fbe632200853e56b54f0f9ee1 Mon Sep 17 00:00:00 2001 From: pqminh27 <76590223+pqminh27@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:11:27 +0700 Subject: [PATCH] gh-162572: Clear stale class source metadata --- Include/internal/pycore_dict.h | 5 + Lib/test/test_capi/test_watchers.py | 34 ++++ Lib/test/test_descr.py | 158 ++++++++++++++++++ Lib/test/test_inspect/test_inspect.py | 12 ++ ...-11-26-01-49-20.gh-issue-162572.ZDZYUc.rst | 3 + Objects/dictobject.c | 56 +++++++ Objects/typeobject.c | 94 +++++++++-- 7 files changed, 345 insertions(+), 17 deletions(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-11-26-01-49-20.gh-issue-162572.ZDZYUc.rst diff --git a/Include/internal/pycore_dict.h b/Include/internal/pycore_dict.h index a30a79f31e6d968..b9de90b21508d75 100644 --- a/Include/internal/pycore_dict.h +++ b/Include/internal/pycore_dict.h @@ -182,6 +182,11 @@ extern int _PyDict_Pop_KnownHash( Py_hash_t hash, PyObject **result); +extern int _PyDict_Pop_ExactUnicode_LockHeld( + PyDictObject *dict, + PyObject *key, + PyObject **result); + extern void _PyDict_Clear_LockHeld(PyObject *op); #ifdef Py_GIL_DISABLED diff --git a/Lib/test/test_capi/test_watchers.py b/Lib/test/test_capi/test_watchers.py index 490ae7b23e62795..98ed2daf905572a 100644 --- a/Lib/test/test_capi/test_watchers.py +++ b/Lib/test/test_capi/test_watchers.py @@ -310,6 +310,40 @@ class C: pass self.assertEqual(str(cm.unraisable.exc_value), "boom!") self.assert_events([]) + def test_type_watcher_not_called_for_failed_module_update(self): + class Meta(type): + pass + + class Key: + fail = False + + def __hash__(self): + return hash('__firstlineno__') + + def __eq__(self, other): + if self.fail and other == '__firstlineno__': + raise ValueError('cannot clear firstlineno') + return False + + key = Key() + namespace = {key: None, '__module__': 'old_module', + '__firstlineno__': 1} + with self.assertWarns(RuntimeWarning): + C = Meta('C', (), namespace) + key.fail = True + + with self.watcher(kind=self.ERROR) as wid: + self.watch(wid, C) + with catch_unraisable_exception() as cm: + with self.assertRaisesRegex(ValueError, + 'cannot clear firstlineno'): + C.__module__ = 'new_module' + self.assertIsNone(cm.unraisable) + key.fail = False + self.assertEqual(vars(C)['__module__'], 'old_module') + self.assertEqual(vars(C)['__firstlineno__'], 1) + self.assert_events([]) + def test_two_watchers(self): class C1: pass class C2: pass diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index 2f5953ba096d439..d60d4660ecf82a2 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -3783,6 +3783,164 @@ class Some: self.assertIsInstance(repr(Some), str) # should not crash self.assertIsInstance(repr(Some()), str) # should not crash + def test_set_module_clears_firstlineno(self): + class Meta(type): + pass + + class DelegatingMeta(type): + def __setattr__(cls, name, value): + super().__setattr__(name, value) + + for metaclass in (type, Meta, DelegatingMeta): + for module in (__name__, 'new_module'): + with self.subTest(metaclass=metaclass, module=module): + class C(metaclass=metaclass): + pass + + self.assertIsInstance(vars(C)['__firstlineno__'], int) + C.__module__ = module + self.assertEqual(vars(C)['__module__'], module) + self.assertNotIn('__firstlineno__', vars(C)) + C.__module__ = module # Already invalidated. + self.assertNotIn('__firstlineno__', vars(C)) + + class Plain: + pass + + with self.assertRaises(TypeError): + del Plain.__module__ + + class C(metaclass=Meta): + pass + + lineno = vars(C)['__firstlineno__'] + del C.__module__ + self.assertNotIn('__module__', vars(C)) + self.assertEqual(vars(C)['__firstlineno__'], lineno) + + def test_set_module_respects_metaclass_descriptor(self): + calls = [] + + class Meta(type): + @property + def __module__(cls): + return vars(cls)['__module__'] + + @__module__.setter + def __module__(cls, value): + calls.append((cls, value)) + + class C(metaclass=Meta): + pass + + lineno = vars(C)['__firstlineno__'] + C.__module__ = 'new_module' + self.assertEqual(calls, [(C, 'new_module')]) + self.assertEqual(vars(C)['__module__'], __name__) + self.assertEqual(vars(C)['__firstlineno__'], lineno) + + def test_set_module_write_failure_preserves_firstlineno(self): + class Meta(type): + pass + + class Key: + comparisons = 0 + fail_after = None + + def __hash__(self): + return hash('__module__') + + def __eq__(self, other): + if other == '__module__': + self.comparisons += 1 + if (self.fail_after is not None + and self.comparisons > self.fail_after): + raise ValueError('cannot insert module') + return False + + key = Key() + with self.assertWarns(RuntimeWarning): + C = Meta('C', (), {key: None, '__firstlineno__': 1}) + del C.__module__ + # Allow one lookup of the missing key, then fail during insertion. + # The number of comparisons in a lookup depends on the hash seed. + key.comparisons = 0 + self.assertNotIn('__module__', vars(C)) + key.fail_after = key.comparisons + key.comparisons = 0 + keys = list(vars(C)) + with self.assertRaises(AttributeError): + C.__module__ = 'new_module' + self.assertEqual(vars(C)['__firstlineno__'], 1) + self.assertEqual(list(vars(C)), keys) + + def test_set_module_clear_failure_preserves_module(self): + class Meta(type): + pass + + class Key: + fail = False + + def __hash__(self): + return hash('__firstlineno__') + + def __eq__(self, other): + if self.fail and other == '__firstlineno__': + raise ValueError('cannot clear firstlineno') + return False + + key = Key() + namespace = {key: None, '__module__': 'old_module', + '__firstlineno__': 1} + with self.assertWarns(RuntimeWarning): + C = Meta('C', (), namespace) + + key.fail = True + keys = list(vars(C)) + with self.assertRaisesRegex(ValueError, 'cannot clear firstlineno'): + C.__module__ = 'new_module' + key.fail = False + self.assertEqual(vars(C)['__module__'], 'old_module') + self.assertEqual(vars(C)['__firstlineno__'], 1) + self.assertEqual(list(vars(C)), keys) + + def test_set_module_invalidates_cache_after_comparison(self): + class Meta(type): + pass + + holder = {} + cache_reads = [] + + class Key: + in_comparison = False + + def __hash__(self): + return hash('__module__') + + def __eq__(self, other): + if (other == '__module__' and 'C' in holder + and not self.in_comparison): + self.in_comparison = True + try: + cache_reads.append(holder['C'].__module__) + finally: + self.in_comparison = False + return False + + key = Key() + namespace = {key: None, '__module__': 'old_module', + '__firstlineno__': 1} + with self.assertWarns(RuntimeWarning): + C = Meta('C', (), namespace) + holder['C'] = C + + C.__module__ = 'new_module' + + self.assertTrue(cache_reads) + self.assertIn('old_module', cache_reads) + self.assertEqual(vars(C)['__module__'], 'new_module') + self.assertEqual(C.__module__, 'new_module') + def test_keyword_arguments(self): # Testing keyword arguments to __init__, __call__... def f(a): return a diff --git a/Lib/test/test_inspect/test_inspect.py b/Lib/test/test_inspect/test_inspect.py index ef9d2061611f335..efd1dc346befd83 100644 --- a/Lib/test/test_inspect/test_inspect.py +++ b/Lib/test/test_inspect/test_inspect.py @@ -1289,6 +1289,18 @@ def test_findsource_on_class_with_out_of_bounds_lineno(self): with self.assertRaisesRegex(OSError, "lineno is out of bounds"): inspect.findsource(cls) + def test_getsource_after_set_module_with_custom_metaclass(self): + class Meta(type): + pass + + # Keep the original line number within the bounds of inspect.py. + ns = {'__name__': __name__, 'Meta': Meta} + exec('class C(metaclass=Meta): pass', ns) + cls = ns['C'] + cls.__module__ = inspect.__name__ + with self.assertRaisesRegex(OSError, 'source code not available'): + inspect.getsource(cls) + def test_getsource_on_method(self): self.assertSourceEqual(mod2.ClassWithMethod.method, 118, 119) diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-26-01-49-20.gh-issue-162572.ZDZYUc.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-26-01-49-20.gh-issue-162572.ZDZYUc.rst new file mode 100644 index 000000000000000..6205af757ac4300 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-26-01-49-20.gh-issue-162572.ZDZYUc.rst @@ -0,0 +1,3 @@ +Assigning :attr:`~type.__module__` now clears :attr:`~type.__firstlineno__` +when a custom metaclass uses the default attribute setter to update the +class dictionary. diff --git a/Objects/dictobject.c b/Objects/dictobject.c index c9cc5d8c566fc6f..c55e01df9570869 100644 --- a/Objects/dictobject.c +++ b/Objects/dictobject.c @@ -3363,6 +3363,62 @@ PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) } +/* Remove an exact str key without comparing it to non-str keys. The caller + must hold the dict lock. */ +int +_PyDict_Pop_ExactUnicode_LockHeld(PyDictObject *mp, PyObject *key, + PyObject **result) +{ + assert(PyDict_Check(mp)); + assert(can_modify_dict(mp)); + assert(PyUnicode_CheckExact(key)); + + Py_hash_t hash = hash_unicode_key(key); + PyDictKeysObject *dk = mp->ma_keys; + Py_ssize_t ix; + if (dk->dk_kind == DICT_KEYS_GENERAL) { + ix = do_lookup(mp, dk, key, hash, compare_generic_exact_unicode); + } + else { + ix = unicodekeys_lookup_unicode(dk, key, hash); + } + if (ix < 0) { + if (result != NULL) { + *result = NULL; + } + return 0; + } + + PyObject *old_value; + if (dk->dk_kind == DICT_KEYS_SPLIT) { + old_value = mp->ma_values->values[ix]; + } + else if (dk->dk_kind == DICT_KEYS_GENERAL) { + old_value = DK_ENTRIES(dk)[ix].me_value; + } + else { + old_value = DK_UNICODE_ENTRIES(dk)[ix].me_value; + } + if (old_value == NULL) { + if (result != NULL) { + *result = NULL; + } + return 0; + } + + _PyDict_NotifyEvent(PyDict_EVENT_DELETED, mp, key, NULL); + delitem_common(mp, hash, ix, Py_NewRef(old_value)); + + if (result != NULL) { + *result = old_value; + } + else { + Py_DECREF(old_value); + } + return 1; +} + + /* Internal version of dict.pop(). */ int _PyDict_Pop_KnownHash(PyDictObject *mp, PyObject *key, Py_hash_t hash, diff --git a/Objects/typeobject.c b/Objects/typeobject.c index 68908c3f0bae626..6f755eca4c8cc6b 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -1098,6 +1098,45 @@ set_version_unlocked(PyTypeObject *tp, unsigned int version) #endif } +/* Clear valid type versions and lookup caches without notifying watchers. + This is used after re-entrant code has repopulated caches during a type + update that was already reported to watchers. */ +static void +type_invalidate_cache_unlocked(PyTypeObject *type) +{ + ASSERT_NEW_TYPE_OR_LOCKED(type); +#ifdef Py_GIL_DISABLED + assert(!types_world_is_stopped()); +#endif + if (type->tp_version_tag == 0) { + return; + } + assert((type->tp_flags & _Py_TPFLAGS_STATIC_BUILTIN) == 0); + + PyObject *subclasses = lookup_tp_subclasses(type); + if (subclasses != NULL) { + assert(PyDict_CheckExact(subclasses)); + + Py_ssize_t i = 0; + PyObject *ref; + while (PyDict_Next(subclasses, &i, NULL, &ref)) { + PyTypeObject *subclass = type_from_ref(ref); + if (subclass == NULL) { + continue; + } + type_invalidate_cache_unlocked(subclass); + Py_DECREF(subclass); + } + } + + set_version_unlocked(type, 0); + _PyTypeCache_Invalidate(type); + if (PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE)) { + FT_ATOMIC_STORE_PTR_RELAXED( + ((PyHeapTypeObject *)type)->_spec_cache.getitem, NULL); + } +} + void _PyType_Modified_Unlocked(PyTypeObject *type) { @@ -6657,25 +6696,31 @@ _Py_type_getattro_stackref(PyTypeObject *type, PyObject *name, // the type versions. static int type_update_dict(PyTypeObject *type, PyDictObject *dict, PyObject *name, - PyObject *value, PyObject **old_value) -{ - // We don't want any re-entrancy between when we update the dict - // and call _PyType_Modified_Unlocked, including running the destructor - // of the current value as it can observe the cache in an inconsistent - // state. The name is an exact unicode (see type_setattro()) and - // str subclass keys are copied to exact str by type_new_copy_dict() - // and type_setattro(). The type dict can still hold non-str keys - // (type_new_impl() only warns about them) and comparing with one of - // those can run user code that releases the locks. + PyObject *value, PyObject **old_value, PyObject **old_firstlineno) +{ + // Resolve all potentially re-entrant lookups before changing the type + // dict. A non-str key with a colliding hash can run user code during + // lookup, so the firstlineno lookup must not happen after __module__ has + // been updated. if (_PyDict_GetItemRef_Unicode_LockHeld(dict, name, old_value) < 0) { return -1; } - /* Clear the VALID_VERSION flag of 'type' and all its - subclasses. This could possibly be unified with the - update_subclasses() recursion in update_slot(), but carefully: - they each have their own conditions on which to stop - recursing into subclasses. */ + bool clear_firstlineno = value != NULL && name == &_Py_ID(__module__); + if (clear_firstlineno) { + PyObject *firstlineno = &_Py_ID(__firstlineno__); + PyObject *preflight_value = NULL; + if (_PyDict_GetItemRef_Unicode_LockHeld(dict, firstlineno, + &preflight_value) < 0) { + return -1; + } + Py_XDECREF(preflight_value); + } + + /* Clear the VALID_VERSION flag of 'type' and all its subclasses before + the update. A comparison during the write can re-enter Python and + repopulate the type cache, so successful updates clear caches again + after both dict changes are complete. */ _PyType_Modified_Unlocked(type); if (_PyDict_SetItem_LockHeld(dict, name, value) < 0) { @@ -6686,6 +6731,18 @@ type_update_dict(PyTypeObject *type, PyDictObject *dict, PyObject *name, return -1; } + if (clear_firstlineno) { + // The preflight above preserves lookup errors before the module is + // changed. Once the write succeeds, remove only the exact internal + // str key; this cannot run user code or fail, so no rollback is + // needed. + _PyDict_Pop_ExactUnicode_LockHeld(dict, &_Py_ID(__firstlineno__), + old_firstlineno); + } + + if (clear_firstlineno) { + type_invalidate_cache_unlocked(type); + } return 0; } @@ -6761,6 +6818,7 @@ type_setattro(PyObject *self, PyObject *name, PyObject *value) #endif PyObject *old_value = NULL; + PyObject *old_firstlineno = NULL; PyObject *descr = _PyType_LookupRef(metatype, name); if (descr != NULL) { descrsetfunc f = Py_TYPE(descr)->tp_descr_set; @@ -6788,7 +6846,8 @@ type_setattro(PyObject *self, PyObject *name, PyObject *value) } BEGIN_TYPE_DICT_LOCK(dict); - res = type_update_dict(type, (PyDictObject *)dict, name, value, &old_value); + res = type_update_dict(type, (PyDictObject *)dict, name, value, + &old_value, &old_firstlineno); assert(_PyType_CheckConsistency(type)); if (res == 0) { if (is_dunder_name(name) && has_slotdef(name)) { @@ -6801,8 +6860,9 @@ type_setattro(PyObject *self, PyObject *name, PyObject *value) done: Py_DECREF(name); Py_XDECREF(descr); - // delay decref of the old value as lock-free type cache readers may access it + // Delay decrefs as lock-free type cache readers may access the old values. _PyObject_XDecRefDelayed(old_value); + _PyObject_XDecRefDelayed(old_firstlineno); return res; }