Skip to content

[mypyc] Allow native classes to support weak refs - #22387

Merged
JukkaL merged 2 commits into
masterfrom
mypyc-weakref
Nov 9, 2026
Merged

JukkaL merged 2 commits into
masterfrom
mypyc-weakref

Conversation

@JukkaL

@JukkaL JukkaL commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator

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.

Comment thread mypyc/ir/class_ir.py Outdated
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())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@JukkaL
JukkaL merged commit 55c99b7 into master Nov 9, 2026
19 checks passed
@JukkaL
JukkaL deleted the mypyc-weakref branch November 9, 2026 12:43
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Compatibility issues with weakrefs

2 participants