[mypyc] Fix race in the __weakref__ getter on free-threaded builds (#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.
2 files changed
tree: 10cdbf37e1618c6843ad85f350ac97f9f74745bf
  1. .github/
  2. docs/
  3. misc/
  4. mypy/
  5. mypyc/
  6. skills/
  7. test-data/
  8. .editorconfig
  9. .git-blame-ignore-revs
  10. .gitattributes
  11. .gitignore
  12. .pre-commit-config.yaml
  13. .readthedocs.yaml
  14. action.yml
  15. build-requirements.txt
  16. CHANGELOG.md
  17. conftest.py
  18. CONTRIBUTING.md
  19. CREDITS
  20. dev-requirements.in
  21. dev-requirements.txt
  22. LICENSE
  23. MANIFEST.in
  24. mypy-requirements.txt
  25. mypy_bootstrap.ini
  26. mypy_self_check.ini
  27. pyproject.toml
  28. README.md
  29. runtests.py
  30. setup.py
  31. test-requirements.in
  32. test-requirements.txt
  33. tox.ini
README.md

Mypy: Static Typing for Python

Stable Version Downloads Build Status Documentation Status Chat at https://gitter.im/python/typing Checked with mypy Code style: black Linting: Ruff

Got a question?

We are always happy to answer questions! Here are some good places to ask them:

If you're just getting started, the documentation and type hints cheat sheet can also help answer questions.

If you think you've found a bug:

To report a bug or request an enhancement:

To discuss a new type system feature:

What is mypy?

Mypy is a static type checker for Python.

Type checkers help ensure that you're using variables and functions in your code correctly. With mypy, add type hints (PEP 484) to your Python programs, and mypy will warn you when you use those types incorrectly.

Python is a dynamic language, so usually you'll only see errors in your code when you attempt to run it. Mypy is a static checker, so it finds bugs in your programs without even running them!

Here is a small example to whet your appetite:

number = input("What is your favourite number?")
print("It is", number + 1)  # error: Unsupported operand types for + ("str" and "int")

Adding type hints for mypy does not interfere with the way your program would otherwise run. Think of type hints as similar to comments! You can always use the Python interpreter to run your code, even if mypy reports errors.

Mypy is designed with gradual typing in mind. This means you can add type hints to your code base slowly and that you can always fall back to dynamic typing when static typing is not convenient.

Mypy has a powerful and easy-to-use type system, supporting features such as type inference, generics, callable types, tuple types, union types, structural subtyping and more. Using mypy will make your programs easier to understand, debug, and maintain.

See the documentation for more examples and information.

In particular, see:

Quick start

Mypy can be installed using pip:

python3 -m pip install -U mypy

If you want to run the latest version of the code, you can install from the repo directly:

python3 -m pip install -U git+https://github.com/python/mypy.git

Now you can type-check the statically typed parts of a program like this:

mypy PROGRAM

You can always use the Python interpreter to run your statically typed programs, even if mypy reports type errors:

python3 PROGRAM

If you are working with large code bases, you can run mypy in daemon mode, that will give much faster (often sub-second) incremental updates:

dmypy run -- PROGRAM

You can also try mypy in an online playground (developed by Yusuke Miyazaki).

Integrations

Mypy can be integrated into popular IDEs:

Web site and documentation

Additional information is available at the web site:

https://www.mypy-lang.org/

Jump straight to the documentation:

https://mypy.readthedocs.io/

Follow along our changelog at:

https://mypy-lang.blogspot.com/

Contributing

Help in testing, development, documentation and other tasks is highly appreciated and useful to the project. There are tasks for contributors of all experience levels.

To get started with developing mypy, see CONTRIBUTING.md.

Mypyc and compiled version of mypy

Mypyc uses Python type hints to compile Python modules to faster C extensions. Mypy is itself compiled using mypyc: this makes mypy approximately 4 times faster than if interpreted!

To install an interpreted mypy instead, use:

python3 -m pip install --no-binary mypy -U mypy

To use a compiled version of a development version of mypy, directly install a binary from https://github.com/mypyc/mypy_mypyc-wheels/releases/latest.

To contribute to the mypyc project, check out the issue tracker at https://github.com/mypyc/mypyc