Skip to content

Commit 89d78fc

Browse files
gh-154130: Fix double decref of the dict in shared dict iterators (#160312)
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
1 parent 9e5ab7e commit 89d78fc

2 files changed

Lines changed: 90 additions & 12 deletions

File tree

‎Lib/test/test_free_threading/test_dict.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,51 @@ def race(iter_times: int,
565565
CHURN_SIZE = 512
566566
race(ITER_TIMES, CHURN_SIZE, APPENDER_THREADS, REPLACER_THREADS)
567567

568+
def test_racing_shared_iterator_exhaustion(self):
569+
# gh-154130: exhausting a dict iterator shared between threads must
570+
# not release the iterator's reference to the dict more than once.
571+
makers = [
572+
lambda d: iter(d),
573+
lambda d: iter(d.values()),
574+
lambda d: iter(d.items()),
575+
lambda d: reversed(d),
576+
lambda d: reversed(d.items()),
577+
]
578+
for make in makers:
579+
cell = [make({i: i for i in range(8)})]
580+
581+
def worker():
582+
for _ in range(5000):
583+
it = cell[0]
584+
try:
585+
next(it)
586+
except StopIteration:
587+
cell[0] = make({i: i for i in range(8)})
588+
except RuntimeError:
589+
# Concurrent next() calls may observe each other's
590+
# updates as a modification; only crashes are bugs.
591+
pass
592+
593+
with self.subTest(make=make):
594+
threading_helper.run_concurrently(worker, nthreads=4)
595+
596+
def test_exhausted_iterator_stays_exhausted(self):
597+
d = {1: 1}
598+
for it in (iter(d), iter(d.items()), reversed(d)):
599+
self.assertEqual(len(list(it)), 1)
600+
d[2] = 2
601+
self.assertRaises(StopIteration, next, it)
602+
self.assertEqual(it.__length_hint__(), 0)
603+
del d[2]
604+
605+
def test_reversed_empty_dict_iterator_not_exhausted(self):
606+
# A reverse iterator over an empty dict starts at position -1 but is
607+
# not exhausted, so a later size change must still be detected.
608+
d = {}
609+
it = reversed(d)
610+
d[1] = 1
611+
self.assertRaises(RuntimeError, next, it)
612+
568613
def test_racing_update_from_mutating_pair(self):
569614
# gh-159244: dict() must not read the items of a key/value pair
570615
# that another thread empties concurrently.

‎Objects/dictobject.c‎

Lines changed: 45 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5705,7 +5705,10 @@ PyDict_DelItemString(PyObject *v, const char *key)
57055705

57065706
typedef struct {
57075707
PyObject_HEAD
5708-
PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
5708+
/* Set to NULL when the iterator is exhausted, except in the free-threaded
5709+
build, where the reference is kept until the iterator is deallocated
5710+
(see dictiter_set_exhausted()). */
5711+
PyDictObject *di_dict;
57095712
Py_ssize_t di_used;
57105713
Py_ssize_t di_pos;
57115714
PyObject* di_result; /* reusable result tuple for iteritems */
@@ -5800,6 +5803,28 @@ static PyMethodDef dictiter_methods[] = {
58005803
{NULL, NULL} /* sentinel */
58015804
};
58025805

5806+
/* Mark the iterator as exhausted. In the free-threaded build an iterator
5807+
may be advanced by several threads at once, each holding a borrowed
5808+
pointer to di_dict, so the iterator keeps its reference to the dict until
5809+
it is deallocated (as list and tuple iterators do) and records exhaustion
5810+
by setting di_pos to DICTITER_EXHAUSTED. This is distinct from -1, the
5811+
starting position of a reverse iterator over an empty dict. */
5812+
#ifdef Py_GIL_DISABLED
5813+
#define DICTITER_EXHAUSTED PY_SSIZE_T_MIN
5814+
#endif
5815+
5816+
static void
5817+
dictiter_set_exhausted(dictiterobject *di, PyDictObject *d)
5818+
{
5819+
#ifdef Py_GIL_DISABLED
5820+
_Py_atomic_store_ssize_relaxed(&di->di_pos, DICTITER_EXHAUSTED);
5821+
_Py_atomic_store_ssize_relaxed(&di->len, 0);
5822+
#else
5823+
di->di_dict = NULL;
5824+
Py_DECREF(d);
5825+
#endif
5826+
}
5827+
58035828
#ifdef Py_GIL_DISABLED
58045829

58055830
static int
@@ -6065,16 +6090,18 @@ dictiter_iternextitem_lock_held(PyDictObject *d, PyObject *self,
60656090
assert (PyAnyDict_Check(d));
60666091
ASSERT_DICT_LOCKED(d);
60676092

6093+
i = FT_ATOMIC_LOAD_SSIZE_RELAXED(di->di_pos);
6094+
if (i < 0) {
6095+
return -1; /* exhausted */
6096+
}
6097+
60686098
if (di->di_used != d->ma_used) {
60696099
PyErr_SetString(PyExc_RuntimeError,
60706100
"dictionary changed size during iteration");
60716101
di->di_used = -1; /* Make this state sticky */
60726102
return -1;
60736103
}
60746104

6075-
i = FT_ATOMIC_LOAD_SSIZE_RELAXED(di->di_pos);
6076-
6077-
assert(i >= 0);
60786105
if (_PyDict_HasSplitTable(d)) {
60796106
if (i >= d->ma_used)
60806107
goto fail;
@@ -6125,8 +6152,7 @@ dictiter_iternextitem_lock_held(PyDictObject *d, PyObject *self,
61256152
return 0;
61266153

61276154
fail:
6128-
di->di_dict = NULL;
6129-
Py_DECREF(d);
6155+
dictiter_set_exhausted(di, d);
61306156
return -1;
61316157
}
61326158

@@ -6170,6 +6196,11 @@ dictiter_iternext_threadsafe(PyDictObject *d, PyObject *self,
61706196

61716197
assert (PyAnyDict_Check(d));
61726198

6199+
i = _Py_atomic_load_ssize_relaxed(&di->di_pos);
6200+
if (i == DICTITER_EXHAUSTED) {
6201+
return -1;
6202+
}
6203+
61736204
if (di->di_used != _Py_atomic_load_ssize_relaxed(&d->ma_used)) {
61746205
PyErr_SetString(PyExc_RuntimeError,
61756206
"dictionary changed size during iteration");
@@ -6179,9 +6210,7 @@ dictiter_iternext_threadsafe(PyDictObject *d, PyObject *self,
61796210

61806211
ensure_shared_on_read(d);
61816212

6182-
i = _Py_atomic_load_ssize_relaxed(&di->di_pos);
61836213
k = _Py_atomic_load_ptr_acquire(&d->ma_keys);
6184-
assert(i >= 0);
61856214
if (_PyDict_HasSplitTable(d)) {
61866215
PyDictValues *values = _Py_atomic_load_ptr_consume(&d->ma_values);
61876216
if (values == NULL) {
@@ -6260,8 +6289,7 @@ dictiter_iternext_threadsafe(PyDictObject *d, PyObject *self,
62606289
"dictionary keys changed during iteration");
62616290

62626291
fail:
6263-
di->di_dict = NULL;
6264-
Py_DECREF(d);
6292+
dictiter_set_exhausted(di, d);
62656293
return -1;
62666294

62676295
try_locked:
@@ -6363,6 +6391,12 @@ dictreviter_iter_lock_held(PyDictObject *d, PyObject *self)
63636391
assert (PyAnyDict_Check(d));
63646392
ASSERT_DICT_LOCKED(d);
63656393

6394+
#ifdef Py_GIL_DISABLED
6395+
if (di->di_pos == DICTITER_EXHAUSTED) {
6396+
return NULL;
6397+
}
6398+
#endif
6399+
63666400
if (di->di_used != d->ma_used) {
63676401
PyErr_SetString(PyExc_RuntimeError,
63686402
"dictionary changed size during iteration");
@@ -6449,8 +6483,7 @@ dictreviter_iter_lock_held(PyDictObject *d, PyObject *self)
64496483
}
64506484

64516485
fail:
6452-
di->di_dict = NULL;
6453-
Py_DECREF(d);
6486+
dictiter_set_exhausted(di, d);
64546487
return NULL;
64556488
}
64566489

0 commit comments

Comments
 (0)