Skip to content

Commit fafb317

Browse files
committed
itertools: claim a tee's position and its buffer as one step
`_tee::next` read `index` and moved it on afterwards, and `_tee_dataobject::get_item` released `running` before the value it fetched from the source was cached. Two callers on one `_tee` then read the same index, hand out the same value twice and advance past a value that was never cached, which leaves `index` past `values.len()` and indexes the buffer out of bounds. Two callers at the same index on separate tees each fetch a value from the source, and one of the two is dropped without reaching a caller. Both claims now cover the read and the update. Assisted-by: Claude
1 parent 59a8029 commit fafb317

3 files changed

Lines changed: 80 additions & 6 deletions

File tree

‎crates/vm/src/stdlib/itertools.rs‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -992,13 +992,15 @@ mod decl {
992992
return Ok(PyIterReturn::Return(values[index].clone()));
993993
}
994994
}
995-
// Prevent concurrent/reentrant calls to iterable.next()
995+
// Prevent concurrent/reentrant calls to iterable.next(). The claim
996+
// covers caching the value as well: released any earlier, a second
997+
// tee at the same index fetches a value of its own and one of the
998+
// two is dropped without ever reaching a caller.
996999
if self.running.swap(true, Ordering::Acquire) {
9971000
return Err(vm.new_runtime_error("cannot re-enter the tee iterator"));
9981001
}
999-
let result = self.iterable.next(vm);
1000-
self.running.store(false, Ordering::Release);
1001-
let obj = raise_if_stop!(result?);
1002+
scopeguard::defer! { self.running.store(false, Ordering::Release) }
1003+
let obj = raise_if_stop!(self.iterable.next(vm)?);
10021004
let Some(mut values) = self.values.try_lock() else {
10031005
return Err(vm.new_runtime_error("cannot re-enter the tee iterator"));
10041006
};
@@ -1016,6 +1018,8 @@ mod decl {
10161018
tee_data: PyRef<PyItertoolsTeeData>,
10171019
#[pytraverse(skip)]
10181020
index: AtomicCell<usize>,
1021+
#[pytraverse(skip)]
1022+
advancing: AtomicBool,
10191023
}
10201024

10211025
impl Constructor for PyItertoolsTee {
@@ -1030,6 +1034,7 @@ mod decl {
10301034
Ok(Self {
10311035
tee_data: PyItertoolsTeeData::new(iterator, vm),
10321036
index: AtomicCell::new(0),
1037+
advancing: AtomicBool::new(false),
10331038
})
10341039
}
10351040
}
@@ -1044,6 +1049,7 @@ mod decl {
10441049
Ok(Self {
10451050
tee_data: PyItertoolsTeeData::new(iterator, vm),
10461051
index: AtomicCell::new(0),
1052+
advancing: AtomicBool::new(false),
10471053
}
10481054
.into_ref_with_type(vm, class.to_owned())?
10491055
.into())
@@ -1054,6 +1060,7 @@ mod decl {
10541060
Self {
10551061
tee_data: self.tee_data.clone(),
10561062
index: AtomicCell::new(self.index.load()),
1063+
advancing: AtomicBool::new(false),
10571064
}
10581065
}
10591066
}
@@ -1086,8 +1093,16 @@ mod decl {
10861093
impl SelfIter for PyItertoolsTee {}
10871094
impl IterNext for PyItertoolsTee {
10881095
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
1089-
let value = raise_if_stop!(zelf.tee_data.get_item(vm, zelf.index.load())?);
1090-
zelf.index.fetch_add(1);
1096+
// Reading the index and moving it on is one step: two callers that
1097+
// read the same index hand out the same value twice and leave the
1098+
// buffer to be filled out of order.
1099+
if zelf.advancing.swap(true, Ordering::Acquire) {
1100+
return Err(vm.new_runtime_error("cannot re-enter the tee iterator"));
1101+
}
1102+
scopeguard::defer! { zelf.advancing.store(false, Ordering::Release) }
1103+
let index = zelf.index.load();
1104+
let value = raise_if_stop!(zelf.tee_data.get_item(vm, index)?);
1105+
zelf.index.store(index + 1);
10911106
Ok(PyIterReturn::Return(value))
10921107
}
10931108
}

‎extra_tests/snippets/stdlib_threading_generator.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ def worker():
4242
pass
4343
except Exception as exc: # noqa: BLE001
4444
errors.append(exc)
45+
# the other workers are waiting at the barrier for this one
46+
start.abort()
4547

4648

4749
threads = [threading.Thread(target=worker) for _ in range(WORKERS)]
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""Advance the iterators of one tee() from several threads at once.
2+
3+
Every tee iterator reads its position, asks the shared buffer for that item and
4+
then moves the position on. Reading and moving it on has to be one step, and
5+
the buffer has to stay claimed until the value it fetched from the source is
6+
cached: otherwise two callers work on the same index, a fetched value is
7+
dropped, and the buffer is left to be filled out of order.
8+
9+
A caller that loses the race gets a RuntimeError, never a value another caller
10+
has already been handed.
11+
"""
12+
13+
import itertools
14+
import threading
15+
16+
ROUNDS = 200
17+
WORKERS = 4
18+
19+
errors = []
20+
21+
22+
def drain(iterator, out):
23+
for _ in range(ROUNDS):
24+
try:
25+
out.append(next(iterator))
26+
except StopIteration:
27+
break
28+
except RuntimeError:
29+
# another thread is advancing this tee
30+
pass
31+
except Exception as exc: # noqa: BLE001
32+
errors.append(exc)
33+
break
34+
35+
36+
for _ in range(10):
37+
first, second = itertools.tee(iter(range(ROUNDS * WORKERS)))
38+
taken = [[] for _ in range(WORKERS)]
39+
threads = [
40+
threading.Thread(target=drain, args=(first if i % 2 else second, taken[i]))
41+
for i in range(WORKERS)
42+
]
43+
for t in threads:
44+
t.start()
45+
for t in threads:
46+
t.join()
47+
48+
assert not errors, errors
49+
for got in taken:
50+
# one iterator hands out ascending values, each of them once
51+
assert got == sorted(set(got)), got
52+
for side in (taken[1], taken[3]), (taken[0], taken[2]):
53+
# the two threads sharing an iterator split its values between them
54+
shared = side[0] + side[1]
55+
assert len(shared) == len(set(shared)), shared
56+
57+
print("ok")

0 commit comments

Comments
 (0)