From c93df6d34eddd3b074ba626b9d1b5accee8c723c Mon Sep 17 00:00:00 2001 From: wlkr73 <86650480+wlkr73@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:28:40 +0000 Subject: [PATCH 1/3] gh-160573: Drop the set once when a shared iterator is exhausted setiter_iternext() read si->si_set, checked it for NULL, walked the table under the set's critical section and then cleared si->si_set and decrefed the set after Py_END_CRITICAL_SECTION(). Threads that reach the exhausted branch together all pass the NULL check, so every one of them drops the iterator's single reference and the set is over-released. On a free-threaded debug build the damage shows up at finalization as "refcount is too small" in validate_gc_objects(); when the set is still alive it shows up earlier as a negative refcount the next time sys.getrefcount() reads it. Hold the iterator's own critical section across the size check, the walk, the clear and the counter updates, and store NULL with the same atomic store the lock-free fast path uses for its read. The iterator's reference is then dropped exactly once, after the lock has been released. Add a regression test in test_free_threading: eight threads race to exhaust one iterator over a set with a large dummy tail, and the set's refcount must stay unchanged. Without the fix it aborts with _Py_NegativeRefcount. --- Lib/test/test_free_threading/test_set.py | 49 ++++++++++++ ...-10-24-19-40-00.gh-issue-160573.sT9kQe.rst | 4 + Objects/setobject.c | 75 ++++++++++++------- 3 files changed, 102 insertions(+), 26 deletions(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-10-24-19-40-00.gh-issue-160573.sT9kQe.rst diff --git a/Lib/test/test_free_threading/test_set.py b/Lib/test/test_free_threading/test_set.py index 9dd3d68d5dad135..7c9ffa53cfbee07 100644 --- a/Lib/test/test_free_threading/test_set.py +++ b/Lib/test/test_free_threading/test_set.py @@ -1,3 +1,4 @@ +import sys import unittest from threading import Thread, Barrier, Event from test.support import threading_helper @@ -159,5 +160,53 @@ class LargeSetTest(RaceTestBase, unittest.TestCase): SET_SIZE = 20 # larger than PySet_MINSIZE +class TestSetIteratorExhaustion(unittest.TestCase): + """Exhausting one set iterator from several threads at once.""" + + # One live element followed by a long run of dummy entries widens the + # window between reading si_set and clearing it, so threads that arrive + # together all reach the exhausted branch. + SET_SIZE = 300_000 + NUM_THREADS = 8 + ROUNDS = 3 + + @threading_helper.requires_working_threading() + def test_racing_exhaustion_releases_set_once(self): + s = set(range(self.SET_SIZE)) + for i in range(1, self.SET_SIZE): + s.discard(i) + # Extra references keep a wrongly released set alive, so every lost + # reference shows up as a refcount difference instead of a crash. + keep = [s] * 1000 + base = sys.getrefcount(s) + try: + for _ in range(self.ROUNDS): + it = iter(s) + next(it) # leave the iterator on the exhausted branch + barrier = Barrier(self.NUM_THREADS, timeout=10) + errors = [] + + def exhaust(): + barrier.wait() + try: + next(it) + except StopIteration: + pass + except BaseException as exc: + errors.append(exc) + + threads = [Thread(target=exhaust) + for _ in range(self.NUM_THREADS)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + self.assertEqual(errors, []) + self.assertEqual(sys.getrefcount(s), base) + finally: + del keep + + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-24-19-40-00.gh-issue-160573.sT9kQe.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-24-19-40-00.gh-issue-160573.sT9kQe.rst new file mode 100644 index 000000000000000..0c4f49ca1ba5bbe --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-24-19-40-00.gh-issue-160573.sT9kQe.rst @@ -0,0 +1,4 @@ +Fix a crash when a :class:`set` iterator that is shared between threads reaches +its end in a free-threaded build: every thread that walked off the end of the +table released the iterator's reference to the set, so the set was over-released. +The reference is now dropped once, under the iterator's critical section. diff --git a/Objects/setobject.c b/Objects/setobject.c index a762edf5933e185..0ae20f83f112a0f 100644 --- a/Objects/setobject.c +++ b/Objects/setobject.c @@ -1093,42 +1093,65 @@ static PyObject *setiter_iternext(PyObject *self) { setiterobject *si = (setiterobject*)self; PyObject *key = NULL; - Py_ssize_t i, mask; + Py_ssize_t i = 0, mask; setentry *entry; - PySetObject *so = si->si_set; + PySetObject *so; + int released = 0; + int size_changed = 0; - if (so == NULL) + /* The fast path still reads si_set without the lock, so it must be the + atomic load; a plain read races with the clearing thread's store. */ + if (FT_ATOMIC_LOAD_PTR_RELAXED(si->si_set) == NULL) return NULL; - assert (PyAnySet_Check(so)); - Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used); - Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used); - if (si_used != so_used) { + /* si_set is cleared by whichever thread walks off the end of the table + first, so both the read and the clear need the iterator's own lock: an + unlocked read can pick up a pointer to a set that the release has + already deallocated. */ + Py_BEGIN_CRITICAL_SECTION(self); + so = si->si_set; + if (so != NULL) { + assert (PyAnySet_Check(so)); + + Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used); + Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used); + if (si_used != so_used) { + si->si_used = -1; /* Make this state sticky */ + size_changed = 1; + } + else { + Py_BEGIN_CRITICAL_SECTION(so); + i = si->si_pos; + assert(i>=0); + entry = so->table; + mask = so->mask; + while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) { + i++; + } + if (i <= mask) { + key = Py_NewRef(entry[i].key); + } + Py_END_CRITICAL_SECTION(); + si->si_pos = i+1; + if (key == NULL) { + FT_ATOMIC_STORE_PTR_RELAXED(si->si_set, NULL); + released = 1; + } + else { + si->len--; + } + } + } + Py_END_CRITICAL_SECTION(); + + if (size_changed) { PyErr_SetString(PyExc_RuntimeError, "Set changed size during iteration"); - si->si_used = -1; /* Make this state sticky */ return NULL; } - - Py_BEGIN_CRITICAL_SECTION(so); - i = si->si_pos; - assert(i>=0); - entry = so->table; - mask = so->mask; - while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) { - i++; - } - if (i <= mask) { - key = Py_NewRef(entry[i].key); - } - Py_END_CRITICAL_SECTION(); - si->si_pos = i+1; - if (key == NULL) { - si->si_set = NULL; + if (released) { Py_DECREF(so); - return NULL; } - si->len--; return key; } From 909027cc97ca1e41f7bb2b7e00dfce27de841360 Mon Sep 17 00:00:00 2001 From: Kumar Aditya Date: Fri, 20 Nov 2026 18:18:31 +0530 Subject: [PATCH 2/3] Keep the set reference until dealloc in free-threaded set iterators Address review: on the free-threaded build, do not clear si_set when the iterator is exhausted. Mark exhaustion with a sentinel si_pos instead, as done for dict iterators in gh-160312, and drop the iterator's own critical section. si_pos and len are now only written with the set locked. Also read so->used, si_used and len atomically in __length_hint__ (gh-144356). --- Lib/test/test_free_threading/test_set.py | 102 +++++++++------- ...-10-24-19-40-00.gh-issue-160573.sT9kQe.rst | 2 +- Objects/setobject.c | 115 ++++++++++-------- 3 files changed, 125 insertions(+), 94 deletions(-) diff --git a/Lib/test/test_free_threading/test_set.py b/Lib/test/test_free_threading/test_set.py index 7c9ffa53cfbee07..639bc729fa31ac6 100644 --- a/Lib/test/test_free_threading/test_set.py +++ b/Lib/test/test_free_threading/test_set.py @@ -1,4 +1,3 @@ -import sys import unittest from threading import Thread, Barrier, Event from test.support import threading_helper @@ -161,51 +160,70 @@ class LargeSetTest(RaceTestBase, unittest.TestCase): class TestSetIteratorExhaustion(unittest.TestCase): - """Exhausting one set iterator from several threads at once.""" - - # One live element followed by a long run of dummy entries widens the - # window between reading si_set and clearing it, so threads that arrive - # together all reach the exhausted branch. - SET_SIZE = 300_000 - NUM_THREADS = 8 - ROUNDS = 3 - - @threading_helper.requires_working_threading() - def test_racing_exhaustion_releases_set_once(self): - s = set(range(self.SET_SIZE)) - for i in range(1, self.SET_SIZE): - s.discard(i) - # Extra references keep a wrongly released set alive, so every lost - # reference shows up as a refcount difference instead of a crash. - keep = [s] * 1000 - base = sys.getrefcount(s) - try: - for _ in range(self.ROUNDS): - it = iter(s) - next(it) # leave the iterator on the exhausted branch - barrier = Barrier(self.NUM_THREADS, timeout=10) - errors = [] - - def exhaust(): - barrier.wait() + def test_racing_shared_iterator_exhaustion(self): + # gh-160573: exhausting a set iterator shared between threads must + # not release the iterator's reference to the set more than once. + for tp in (set, frozenset): + cell = [iter(tp(range(8)))] + + def worker(): + for _ in range(5000): + it = cell[0] try: next(it) except StopIteration: + cell[0] = iter(tp(range(8))) + + with self.subTest(tp=tp): + threading_helper.run_concurrently(worker, nthreads=4) + + def test_racing_shared_iterator_exhaustion_contended(self): + # Same as above, but the set's lock is contended: other threads + # keep mutating and iterating the set while its iterator is shared. + s = set(range(8)) + cell = [iter(s)] + done = Event() + + def exhaust(): + for _ in range(5000): + it = cell[0] + try: + next(it) + except StopIteration: + cell[0] = iter(s) + except RuntimeError: + # The set changed size during iteration. + cell[0] = iter(s) + + def mutate(): + while not done.is_set(): + s.add(100) + s.discard(100) + + def iterate(): + while not done.is_set(): + try: + for _ in s: pass - except BaseException as exc: - errors.append(exc) - - threads = [Thread(target=exhaust) - for _ in range(self.NUM_THREADS)] - for thread in threads: - thread.start() - for thread in threads: - thread.join() - - self.assertEqual(errors, []) - self.assertEqual(sys.getrefcount(s), base) - finally: - del keep + except RuntimeError: + pass + + def run_exhaust(): + try: + threading_helper.run_concurrently(exhaust, nthreads=4) + finally: + done.set() + + threading_helper.run_concurrently([run_exhaust, mutate, iterate]) + + def test_exhausted_iterator_stays_exhausted(self): + s = {1} + it = iter(s) + self.assertEqual(list(it), [1]) + s.add(2) + self.assertRaises(StopIteration, next, it) + self.assertEqual(it.__length_hint__(), 0) + self.assertEqual(list(it.__reduce__()[1][0]), []) if __name__ == "__main__": diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-24-19-40-00.gh-issue-160573.sT9kQe.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-24-19-40-00.gh-issue-160573.sT9kQe.rst index 0c4f49ca1ba5bbe..7a69a4769204857 100644 --- a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-24-19-40-00.gh-issue-160573.sT9kQe.rst +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-24-19-40-00.gh-issue-160573.sT9kQe.rst @@ -1,4 +1,4 @@ Fix a crash when a :class:`set` iterator that is shared between threads reaches its end in a free-threaded build: every thread that walked off the end of the table released the iterator's reference to the set, so the set was over-released. -The reference is now dropped once, under the iterator's critical section. +The iterator now keeps its reference to the set until it is deallocated. diff --git a/Objects/setobject.c b/Objects/setobject.c index 0ae20f83f112a0f..ebc0b30261ee82a 100644 --- a/Objects/setobject.c +++ b/Objects/setobject.c @@ -1027,7 +1027,10 @@ frozenset_hash(PyObject *self) typedef struct { PyObject_HEAD - PySetObject *si_set; /* Set to NULL when iterator is exhausted */ + /* Set to NULL when the iterator is exhausted, except in the free-threaded + build, where the reference is kept until the iterator is deallocated + (see setiter_set_exhausted()). */ + PySetObject *si_set; Py_ssize_t si_used; Py_ssize_t si_pos; Py_ssize_t len; @@ -1056,8 +1059,13 @@ setiter_len(PyObject *op, PyObject *Py_UNUSED(ignored)) { setiterobject *si = (setiterobject*)op; Py_ssize_t len = 0; - if (si->si_set != NULL && si->si_used == si->si_set->used) - len = si->len; + PySetObject *so = si->si_set; + if (so != NULL + && FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used) + == FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used)) + { + len = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->len); + } return PyLong_FromSsize_t(len); } @@ -1089,69 +1097,74 @@ static PyMethodDef setiter_methods[] = { {NULL, NULL} /* sentinel */ }; +/* Mark the iterator as exhausted. In the free-threaded build an iterator + may be advanced by several threads at once, each holding a borrowed + pointer to si_set, so the iterator keeps its reference to the set until + it is deallocated (as list and tuple iterators do) and records exhaustion + by setting si_pos to SETITER_EXHAUSTED. */ +#define SETITER_EXHAUSTED (-1) + +static void +setiter_set_exhausted(setiterobject *si, PySetObject *so) +{ +#ifdef Py_GIL_DISABLED + _Py_atomic_store_ssize_relaxed(&si->si_pos, SETITER_EXHAUSTED); + _Py_atomic_store_ssize_relaxed(&si->len, 0); +#else + si->si_set = NULL; + Py_DECREF(so); +#endif +} + static PyObject *setiter_iternext(PyObject *self) { setiterobject *si = (setiterobject*)self; PyObject *key = NULL; - Py_ssize_t i = 0, mask; + Py_ssize_t i, mask; setentry *entry; - PySetObject *so; - int released = 0; - int size_changed = 0; + PySetObject *so = si->si_set; - /* The fast path still reads si_set without the lock, so it must be the - atomic load; a plain read races with the clearing thread's store. */ - if (FT_ATOMIC_LOAD_PTR_RELAXED(si->si_set) == NULL) + if (so == NULL) return NULL; + assert (PyAnySet_Check(so)); - /* si_set is cleared by whichever thread walks off the end of the table - first, so both the read and the clear need the iterator's own lock: an - unlocked read can pick up a pointer to a set that the release has - already deallocated. */ - Py_BEGIN_CRITICAL_SECTION(self); - so = si->si_set; - if (so != NULL) { - assert (PyAnySet_Check(so)); - - Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used); - Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used); - if (si_used != so_used) { - si->si_used = -1; /* Make this state sticky */ - size_changed = 1; - } - else { - Py_BEGIN_CRITICAL_SECTION(so); - i = si->si_pos; - assert(i>=0); - entry = so->table; - mask = so->mask; - while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) { - i++; - } - if (i <= mask) { - key = Py_NewRef(entry[i].key); - } - Py_END_CRITICAL_SECTION(); - si->si_pos = i+1; - if (key == NULL) { - FT_ATOMIC_STORE_PTR_RELAXED(si->si_set, NULL); - released = 1; - } - else { - si->len--; - } - } +#ifdef Py_GIL_DISABLED + if (_Py_atomic_load_ssize_relaxed(&si->si_pos) == SETITER_EXHAUSTED) { + return NULL; } - Py_END_CRITICAL_SECTION(); +#endif - if (size_changed) { + Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used); + Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used); + if (si_used != so_used) { PyErr_SetString(PyExc_RuntimeError, "Set changed size during iteration"); + /* Make this state sticky */ + FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_used, -1); return NULL; } - if (released) { - Py_DECREF(so); + + /* si_pos and len are only written with the set locked, so that an + iterator marked as exhausted by another thread stays exhausted. */ + Py_BEGIN_CRITICAL_SECTION(so); + i = si->si_pos; + if (i != SETITER_EXHAUSTED) { + assert(i>=0); + entry = so->table; + mask = so->mask; + while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) { + i++; + } + if (i <= mask) { + key = Py_NewRef(entry[i].key); + FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_pos, i+1); + FT_ATOMIC_STORE_SSIZE_RELAXED(si->len, si->len - 1); + } + else { + setiter_set_exhausted(si, so); + } } + Py_END_CRITICAL_SECTION(); return key; } From db0a1360e1905c7fe0225d81f6e4cf3dd83fbf7b Mon Sep 17 00:00:00 2001 From: Kumar Aditya Date: Fri, 20 Nov 2026 18:20:45 +0530 Subject: [PATCH 3/3] Tidy formatting of the set iterator changes --- Objects/setobject.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/Objects/setobject.c b/Objects/setobject.c index ebc0b30261ee82a..370b727f70a3206 100644 --- a/Objects/setobject.c +++ b/Objects/setobject.c @@ -1060,11 +1060,12 @@ setiter_len(PyObject *op, PyObject *Py_UNUSED(ignored)) setiterobject *si = (setiterobject*)op; Py_ssize_t len = 0; PySetObject *so = si->si_set; - if (so != NULL - && FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used) - == FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used)) - { - len = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->len); + if (so != NULL) { + Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used); + Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used); + if (si_used == so_used) { + len = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->len); + } } return PyLong_FromSsize_t(len); } @@ -1108,8 +1109,8 @@ static void setiter_set_exhausted(setiterobject *si, PySetObject *so) { #ifdef Py_GIL_DISABLED - _Py_atomic_store_ssize_relaxed(&si->si_pos, SETITER_EXHAUSTED); - _Py_atomic_store_ssize_relaxed(&si->len, 0); + FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_pos, SETITER_EXHAUSTED); + FT_ATOMIC_STORE_SSIZE_RELAXED(si->len, 0); #else si->si_set = NULL; Py_DECREF(so); @@ -1129,7 +1130,7 @@ static PyObject *setiter_iternext(PyObject *self) assert (PyAnySet_Check(so)); #ifdef Py_GIL_DISABLED - if (_Py_atomic_load_ssize_relaxed(&si->si_pos) == SETITER_EXHAUSTED) { + if (FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_pos) == SETITER_EXHAUSTED) { return NULL; } #endif @@ -1149,7 +1150,7 @@ static PyObject *setiter_iternext(PyObject *self) Py_BEGIN_CRITICAL_SECTION(so); i = si->si_pos; if (i != SETITER_EXHAUSTED) { - assert(i>=0); + assert(i >= 0); entry = so->table; mask = so->mask; while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) { @@ -1157,7 +1158,7 @@ static PyObject *setiter_iternext(PyObject *self) } if (i <= mask) { key = Py_NewRef(entry[i].key); - FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_pos, i+1); + FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_pos, i + 1); FT_ATOMIC_STORE_SSIZE_RELAXED(si->len, si->len - 1); } else {