Skip to content

Commit 1782f62

Browse files
gh-160573: Drop the set once when a shared iterator is exhausted (#160619)
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
1 parent 4d342eb commit 1782f62

3 files changed

Lines changed: 127 additions & 19 deletions

File tree

‎Lib/test/test_free_threading/test_set.py‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,5 +159,72 @@ class LargeSetTest(RaceTestBase, unittest.TestCase):
159159
SET_SIZE = 20 # larger than PySet_MINSIZE
160160

161161

162+
class TestSetIteratorExhaustion(unittest.TestCase):
163+
def test_racing_shared_iterator_exhaustion(self):
164+
# gh-160573: exhausting a set iterator shared between threads must
165+
# not release the iterator's reference to the set more than once.
166+
for tp in (set, frozenset):
167+
cell = [iter(tp(range(8)))]
168+
169+
def worker():
170+
for _ in range(5000):
171+
it = cell[0]
172+
try:
173+
next(it)
174+
except StopIteration:
175+
cell[0] = iter(tp(range(8)))
176+
177+
with self.subTest(tp=tp):
178+
threading_helper.run_concurrently(worker, nthreads=4)
179+
180+
def test_racing_shared_iterator_exhaustion_contended(self):
181+
# Same as above, but the set's lock is contended: other threads
182+
# keep mutating and iterating the set while its iterator is shared.
183+
s = set(range(8))
184+
cell = [iter(s)]
185+
done = Event()
186+
187+
def exhaust():
188+
for _ in range(5000):
189+
it = cell[0]
190+
try:
191+
next(it)
192+
except StopIteration:
193+
cell[0] = iter(s)
194+
except RuntimeError:
195+
# The set changed size during iteration.
196+
cell[0] = iter(s)
197+
198+
def mutate():
199+
while not done.is_set():
200+
s.add(100)
201+
s.discard(100)
202+
203+
def iterate():
204+
while not done.is_set():
205+
try:
206+
for _ in s:
207+
pass
208+
except RuntimeError:
209+
pass
210+
211+
def run_exhaust():
212+
try:
213+
threading_helper.run_concurrently(exhaust, nthreads=4)
214+
finally:
215+
done.set()
216+
217+
threading_helper.run_concurrently([run_exhaust, mutate, iterate])
218+
219+
def test_exhausted_iterator_stays_exhausted(self):
220+
s = {1}
221+
it = iter(s)
222+
self.assertEqual(list(it), [1])
223+
s.add(2)
224+
self.assertRaises(StopIteration, next, it)
225+
self.assertEqual(it.__length_hint__(), 0)
226+
self.assertEqual(list(it.__reduce__()[1][0]), [])
227+
228+
162229
if __name__ == "__main__":
163230
unittest.main()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix a crash when a :class:`set` iterator that is shared between threads reaches
2+
its end in a free-threaded build: every thread that walked off the end of the
3+
table released the iterator's reference to the set, so the set was over-released.
4+
The iterator now keeps its reference to the set until it is deallocated.

‎Objects/setobject.c‎

Lines changed: 56 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1027,7 +1027,10 @@ frozenset_hash(PyObject *self)
10271027

10281028
typedef struct {
10291029
PyObject_HEAD
1030-
PySetObject *si_set; /* Set to NULL when iterator is exhausted */
1030+
/* Set to NULL when the iterator is exhausted, except in the free-threaded
1031+
build, where the reference is kept until the iterator is deallocated
1032+
(see setiter_set_exhausted()). */
1033+
PySetObject *si_set;
10311034
Py_ssize_t si_used;
10321035
Py_ssize_t si_pos;
10331036
Py_ssize_t len;
@@ -1056,8 +1059,14 @@ setiter_len(PyObject *op, PyObject *Py_UNUSED(ignored))
10561059
{
10571060
setiterobject *si = (setiterobject*)op;
10581061
Py_ssize_t len = 0;
1059-
if (si->si_set != NULL && si->si_used == si->si_set->used)
1060-
len = si->len;
1062+
PySetObject *so = si->si_set;
1063+
if (so != NULL) {
1064+
Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used);
1065+
Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used);
1066+
if (si_used == so_used) {
1067+
len = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->len);
1068+
}
1069+
}
10611070
return PyLong_FromSsize_t(len);
10621071
}
10631072

@@ -1089,6 +1098,25 @@ static PyMethodDef setiter_methods[] = {
10891098
{NULL, NULL} /* sentinel */
10901099
};
10911100

1101+
/* Mark the iterator as exhausted. In the free-threaded build an iterator
1102+
may be advanced by several threads at once, each holding a borrowed
1103+
pointer to si_set, so the iterator keeps its reference to the set until
1104+
it is deallocated (as list and tuple iterators do) and records exhaustion
1105+
by setting si_pos to SETITER_EXHAUSTED. */
1106+
#define SETITER_EXHAUSTED (-1)
1107+
1108+
static void
1109+
setiter_set_exhausted(setiterobject *si, PySetObject *so)
1110+
{
1111+
#ifdef Py_GIL_DISABLED
1112+
FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_pos, SETITER_EXHAUSTED);
1113+
FT_ATOMIC_STORE_SSIZE_RELAXED(si->len, 0);
1114+
#else
1115+
si->si_set = NULL;
1116+
Py_DECREF(so);
1117+
#endif
1118+
}
1119+
10921120
static PyObject *setiter_iternext(PyObject *self)
10931121
{
10941122
setiterobject *si = (setiterobject*)self;
@@ -1101,34 +1129,43 @@ static PyObject *setiter_iternext(PyObject *self)
11011129
return NULL;
11021130
assert (PyAnySet_Check(so));
11031131

1132+
#ifdef Py_GIL_DISABLED
1133+
if (FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_pos) == SETITER_EXHAUSTED) {
1134+
return NULL;
1135+
}
1136+
#endif
1137+
11041138
Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used);
11051139
Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used);
11061140
if (si_used != so_used) {
11071141
PyErr_SetString(PyExc_RuntimeError,
11081142
"Set changed size during iteration");
1109-
si->si_used = -1; /* Make this state sticky */
1143+
/* Make this state sticky */
1144+
FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_used, -1);
11101145
return NULL;
11111146
}
11121147

1148+
/* si_pos and len are only written with the set locked, so that an
1149+
iterator marked as exhausted by another thread stays exhausted. */
11131150
Py_BEGIN_CRITICAL_SECTION(so);
11141151
i = si->si_pos;
1115-
assert(i>=0);
1116-
entry = so->table;
1117-
mask = so->mask;
1118-
while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) {
1119-
i++;
1120-
}
1121-
if (i <= mask) {
1122-
key = Py_NewRef(entry[i].key);
1152+
if (i != SETITER_EXHAUSTED) {
1153+
assert(i >= 0);
1154+
entry = so->table;
1155+
mask = so->mask;
1156+
while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) {
1157+
i++;
1158+
}
1159+
if (i <= mask) {
1160+
key = Py_NewRef(entry[i].key);
1161+
FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_pos, i + 1);
1162+
FT_ATOMIC_STORE_SSIZE_RELAXED(si->len, si->len - 1);
1163+
}
1164+
else {
1165+
setiter_set_exhausted(si, so);
1166+
}
11231167
}
11241168
Py_END_CRITICAL_SECTION();
1125-
si->si_pos = i+1;
1126-
if (key == NULL) {
1127-
si->si_set = NULL;
1128-
Py_DECREF(so);
1129-
return NULL;
1130-
}
1131-
si->len--;
11321169
return key;
11331170
}
11341171

0 commit comments

Comments
 (0)