Repository navigation
[mypyc] Allow native classes to support weak refs - #22387
Merged
Merged
Conversation
p-sawicki
approved these changes
Nov 6, 2026
| or not self.is_generated | ||
| or self.has_dict | ||
| # For the __weakref__ getset | ||
| or (self.is_ext_class and not self.is_trait and self.supports_weakrefs()) |
Collaborator
There was a problem hiding this comment.
same condition as has_weakrefs in emitclass.py - could move it to a helper method.
Fixes mypyc/mypyc#1102. Native classes support weak references if they opt in using `@mypyc_attr(weakrefs=True)`, which adds a weak reference list field to the object struct. The base class of a hierarchy must opt in, since the offset of the field must be the same in all subclasses. Native subclasses of non-native classes (other than dict/Exception subclasses) always support weak references, like interpreted subclasses. They already have `__dict__` storage, and the weak reference list goes next to it at no additional memory cost: in the managed pre-header on 3.12+ (Py_TPFLAGS_MANAGED_WEAKREF), and in a trailing slot after `__dict__` on older versions. This works the same way whether or not the base class supports weak references, so mypyc doesn't need to know anything about the base class. Previously some of these classes were weak-referenceable (on 3.11 and earlier, or if the base class supported them), but tp_dealloc never cleared the weak references, so they resurrected freed memory. Now tp_dealloc clears weak references for all classes that support them. On 3.11 and earlier, callable classes (used for nested functions, lambdas and singledispatch functions) and native dict/Exception subclasses used to accept weak references, but the result crashed or corrupted memory once the object died. They now reject weak references, as on 3.12+, and their instances are one pointer smaller.
This was referenced Nov 14, 2026
JukkaL
pushed a commit
that referenced
this pull request
Nov 17, 2026
…asses (#22468) Weak reference support for native classes was added in #22387. Along with it, mypyc reports a compile error when the target of `weakref.ref()` or `weakref.proxy()` has the type of a native class without weak reference support. This gave a false positive for classes that allow interpreted subclasses: ```python import weakref from mypy_extensions import mypyc_attr @mypyc_attr(allow_interpreted_subclasses=True) class A: pass def f(a: A) -> object: return weakref.ref(a) ``` mypyc reported `Cannot create weak reference to instance of native class "A"` for `f`. But `a` may be an instance of an interpreted subclass of `A`, and interpreted subclasses always support weak references (this is also what the docs say). Now the error is not reported if the class allows interpreted subclasses. Calling `f` with an instance of `A` itself still raises `TypeError` at runtime, like it does when the static type is `object`. All base classes of a class that allows interpreted subclasses must allow them as well, so it's enough to check the class itself. I also removed a TODO comment in the generated `tp_dealloc` that said weak references created inside `__del__` are not cleared. The weak reference list is cleared after `PyObject_CallFinalizerFromDealloc()` returns, so these are cleared too. (CPython's second clearing pass in `subtype_dealloc` is for the legacy `tp_del` slot, which mypyc doesn't use.) Tests: I added a class that allows interpreted subclasses to the irbuild error test case. In `run-weakref.test`, an interpreted subclass instance passed to a compiled `weakref.ref()` call now works, and an instance of the native class still raises `TypeError`. The existing `__del__` test now also creates a weak reference inside `__del__` and checks that it's dead after the object is freed.
p-sawicki
pushed a commit
that referenced
this pull request
Nov 19, 2026
…22486) The `__weakref__` getter of native classes (`CPy_GetWeakrefs`, added in #22387) reads the head of the object's weak reference list and increfs it without any synchronization. On a free-threaded build another thread can drop the last reference to that weak reference object between the two steps. `weakref_dealloc` then unlinks it from the list and frees it, and the getter increfs freed memory. CPython had the same race in `subtype_getweakref` (the getter that classes defined in Python use). It was fixed in python/cpython#150247 (for python/cpython#149816; backported to 3.14 and 3.15, not to 3.13): the getter now holds the interpreter's weak reference list lock and uses `_Py_TryIncref`. Both are internal APIs, and the lock is a striped mutex in the interpreter state, so an extension can't take the same lock. `PyUnstable_TryIncRef` alone isn't enough, because it relies on the caller holding a lock that the deallocator also takes. ### Reproducer ```python import threading, weakref from mypy_extensions import mypyc_attr @mypyc_attr(weakrefs=True) class C: pass def churn(o: C, n: int) -> None: for _ in range(n): weakref.ref(o, None) weakref.ref(o, lambda r: None) def read(o: object, n: int) -> None: for _ in range(n): getattr(o, "__weakref__") ``` Running two `churn` threads and two `read` threads on one instance with `n = 100_000`, compiled for 3.14t: on master 8 of 10 runs failed (5 segfaults, 3 hangs). With this PR all 10 passed, and the same script with a non-native class passes on both. ### Fix On free-threaded builds, `CPy_GetWeakrefs` now calls CPython's own getter. It gets the `__weakref__` descriptor of a small class created with `type()` on first use and calls its `PyGetSetDef.get` function directly. `subtype_getweakref` only looks at `Py_TYPE(obj)->tp_weaklistoffset`, so it works for native classes too. That way the getter takes the right lock, and native classes behave the same as classes defined in Python on every version: they are safe wherever CPython is, and on versions where CPython's own getter is still racy (3.13t, 3.14t before 3.14.9) they are no worse than interpreted classes. The descriptor is cached with a compare-and-swap rather than a mutex, since creating the class can run arbitrary code through the GC, which could reenter the getter. GIL builds are unchanged. ### Tests I added `testConcurrentWeakrefGetter` to `run-threading.test`, with the same pattern as the other concurrency tests there. On 3.14t it segfaulted in 3 of 3 runs without the fix and passed in 3 of 3 runs with it. It also passes on regular builds, where it's only a smoke test. The weakref and threading run tests pass on 3.14t, and the full `test_run.py` passes on 3.13.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes mypyc/mypyc#1102.
Native classes support weak references if they opt in using
@mypyc_attr(weakrefs=True), which adds a weak reference list field to the object struct. The base class of a hierarchy must opt in, since the offset of the field must be the same in all subclasses.Native subclasses of non-native classes (other than dict/Exception subclasses) always support weak references, like interpreted subclasses.
Previously some of these classes were weak-referenceable (on 3.11 and earlier, or if the base class supported them), but tp_dealloc never cleared the weak references, so they resurrected freed memory. Now tp_dealloc clears weak references for all classes that support them.
On 3.11 and earlier, callable classes (used for nested functions, lambdas and singledispatch functions) and native dict/Exception subclasses used to accept weak references, but the result crashed or corrupted memory once the object died. They now reject weak references, as on 3.12+, and their instances are one pointer smaller.