Skip to content

[mypyc] Fix memory safety bugs in list.count, match sequence patterns and dict.setdefault - #22415

Merged
JukkaL merged 3 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-container-error-refs
Nov 10, 2026
Merged

JukkaL merged 3 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-container-error-refs

Conversation

@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor

This fixes three crashes in mypyc container primitives, and an incorrect result for dict.setdefault on dict subclasses.

  1. Match sequence patterns. PySequence_GetItem was declared as never failing, so a __getitem__ that raises crashed compiled code:

    class S(collections.abc.Sequence):
        def __len__(self): return 2
        def __getitem__(self, i): raise RuntimeError
    def f(x: object) -> object:
        match x:
            case [a, b]: return a
        return None
    f(S())  # segfault, now raises RuntimeError

    It is now declared with ERR_MAGIC.

  2. list.count. On GIL builds, it passed a borrowed item to PyObject_RichCompareBool. If __eq__ removes the item from the list (e.g. lst.clear(); return NotImplemented), the reflected comparison receives a freed object. It now holds a reference during the comparison, as CPython does.

  3. dict.setdefault(k, v) on free-threaded builds. It used PyDict_SetDefault, which returns a borrowed reference, and only increfed the result after the dict lock was released. A stress test segfaults reliably on 3.14t. It now uses PyDict_SetDefaultRef.

  4. d.setdefault(k, [] / {} / set()). This did a separate get and set:

    • On free-threaded builds that is not atomic, and concurrent appends were lost.
    • For dict subclasses it used __getitem__, so __missing__ ran and a setdefault override was ignored. For example, Counter().setdefault("x", []) returned 0 and inserted nothing.

    It now keeps the lookup fast path for exact dicts. Otherwise it creates the empty collection and calls setdefault.

Added regression tests to run-match.test, run-lists.test and run-dicts.test. The free-threading races can't be tested deterministically, so I checked them manually with stress scripts on 3.14t: before the fix they segfaulted or lost updates, after it they ran clean.

The sequence_get_item primitive (PySequence_GetItem) used by sequence
patterns in match statements was declared with ERR_NEVER, so if the
subject's __getitem__ raised an exception the NULL result was used as
a valid object, causing a crash. Use ERR_MAGIC so the error propagates.
On builds with the GIL, list_count passed the borrowed list item
directly to PyObject_RichCompareBool. If the item's __eq__ removed it
from the list (e.g. by clearing the list), the item could be freed
while still in use, for example by the reflected comparison. Hold a
reference to the item during the comparison, like CPython does.
CPyDict_SetDefault used PyDict_SetDefault, which returns a borrowed
reference, and only increfed it after the call. On free-threaded builds
another thread can remove the value from the dict in between, so the
result could be freed before we took a reference. Use
PyDict_SetDefaultRef instead.

CPyDict_SetDefaultWithEmptyDatatype (used for d.setdefault(k, []),
d.setdefault(k, {}) and d.setdefault(k, set())) did a separate get and
set. This was not atomic on free-threaded builds, so concurrent calls
could each insert a fresh collection and lose updates. For dict
subclasses it also used __getitem__, so __missing__ was triggered
(e.g. Counter returned 0 and inserted nothing) and an overridden
setdefault was ignored. Now we only do a lookup as a fast path for
exact dicts, and otherwise create the empty collection and call
setdefault (PyDict_SetDefaultRef for exact dicts, the setdefault method
for subclasses).

@JukkaL JukkaL left a comment

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.

Thanks, great finds!

@JukkaL
JukkaL merged commit 533e32e into python:master Nov 10, 2026
18 checks passed
@Jahongir-Qurbonov
Jahongir-Qurbonov deleted the mypyc-container-error-refs branch November 14, 2026 22:05
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.

2 participants