From fa599a892ed1cf4131250ae2fb0980c1f3b1f5df Mon Sep 17 00:00:00 2001 From: Piotr Sawicki Date: Mon, 2 Nov 2026 12:38:12 +0100 Subject: [PATCH] [mypyc] Fix reference leak in statics initialization --- mypyc/lib-rt/misc_ops.c | 2 +- mypyc/test-data/run-sets.test | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/mypyc/lib-rt/misc_ops.c b/mypyc/lib-rt/misc_ops.c index 2099176214dbc..51b66984bec37 100644 --- a/mypyc/lib-rt/misc_ops.c +++ b/mypyc/lib-rt/misc_ops.c @@ -781,8 +781,8 @@ int CPyStatics_Initialize(PyObject **statics, } for (int i = 0; i < num_items; i++) { PyObject *item = statics[*frozensets++]; - Py_INCREF(item); if (PySet_Add(obj, item) == -1) { + Py_DECREF(obj); return -1; } } diff --git a/mypyc/test-data/run-sets.test b/mypyc/test-data/run-sets.test index 2668d63bcdaca..fdab0f5e88976 100644 --- a/mypyc/test-data/run-sets.test +++ b/mypyc/test-data/run-sets.test @@ -117,6 +117,7 @@ update(s, [5, 4, 3]) assert s == {1, 2, 3, 4, 5} [case testFrozenSets] +import sys from typing import FrozenSet, List, Any, cast from testutil import assertRaises @@ -183,6 +184,13 @@ def test_frozen_sets() -> None: with assertRaises(TypeError, "frozenset object expected; got set"): castFrozenSetError() + value = b'frozenset member' + assert value in {b'frozenset member', b'other member'} + # References from the statics array, the precomputed frozenset, and the + # getrefcount argument. The compiled local borrows its reference. + getrefcount: Any = getattr(sys, "getrefcount") + assert getrefcount(value) == 3, getrefcount(value) + [case testFrozenSetsFromIterables] from typing import FrozenSet