Skip to content

Commit 59a8029

Browse files
committed
generator: read the frame state under the running claim
send(), send_none(), throw() and close() read `closed` and `frame.lasti()` before `running` was compare_exchanged, so the frame they went on to resume could be one another thread had already advanced. A resume that decided from `lasti() == 0` that the generator had not started pushes no value onto the value stack, and the code after the yield pops one, which underflows the stack. The compare_exchange now hands back a guard, taken before those reads and released after maybe_close(), so the generator is retired while it is still claimed. Assisted-by: Claude
1 parent 81f0690 commit 59a8029

2 files changed

Lines changed: 163 additions & 41 deletions

File tree

‎crates/vm/src/coroutine.rs‎

Lines changed: 70 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,21 @@ unsafe impl Traverse for Coro {
5151
}
5252
}
5353

54+
/// An exclusive claim on a generator's frame, released when dropped.
55+
///
56+
/// Only the holder may look at the frame or resume it. Resuming decides from
57+
/// the frame state whether the sent value goes on the value stack, so a state
58+
/// read taken before the claim can be answered by a frame that another thread
59+
/// then advances: resuming it leaves the stack short of what the code after
60+
/// the yield pops.
61+
struct RunningGuard<'a>(&'a Coro);
62+
63+
impl Drop for RunningGuard<'_> {
64+
fn drop(&mut self) {
65+
self.0.running.store(false);
66+
}
67+
}
68+
5469
fn gen_name(jen: &PyObject, vm: &VirtualMachine) -> &'static str {
5570
let typ = jen.class();
5671
if typ.is(vm.ctx.types.coroutine_type) {
@@ -88,10 +103,10 @@ impl Coro {
88103
}
89104
}
90105

91-
fn maybe_close(&self, res: &PyResult<ExecutionResult>, entered_frame: bool) {
92-
if !entered_frame {
93-
return;
94-
}
106+
/// Retire the generator if the frame it just ran came to an end. The claim
107+
/// is still held, so a thread waiting for it cannot resume a frame that has
108+
/// already finished.
109+
fn maybe_close(&self, res: &PyResult<ExecutionResult>, _claim: &RunningGuard<'_>) {
95110
match res {
96111
Ok(ExecutionResult::Return(_)) | Err(_) => {
97112
self.closed.store(true);
@@ -109,45 +124,44 @@ impl Coro {
109124
}
110125
}
111126

112-
fn run_with_context<F>(
127+
/// Take the frame for this thread, or report that another thread holds it.
128+
///
129+
/// What the resume depends on -- whether the generator is closed, and
130+
/// whether it has started -- has to be read from here onwards.
131+
fn claim(&self, jen: &PyObject, vm: &VirtualMachine) -> PyResult<RunningGuard<'_>> {
132+
if self.running.compare_exchange(false, true).is_err() {
133+
return Err(vm.new_value_error(format!("{} already executing", gen_name(jen, vm))));
134+
}
135+
Ok(RunningGuard(self))
136+
}
137+
138+
fn run_claimed<F>(
113139
&self,
114-
jen: &PyObject,
140+
_claim: &RunningGuard<'_>,
115141
vm: &VirtualMachine,
116142
func: F,
117-
) -> (PyResult<ExecutionResult>, bool)
143+
) -> PyResult<ExecutionResult>
118144
where
119145
F: FnOnce(&Py<FrameObject>) -> PyResult<ExecutionResult>,
120146
{
121-
if self.running.compare_exchange(false, true).is_err() {
122-
return (
123-
Err(vm.new_value_error(format!("{} already executing", gen_name(jen, vm)))),
124-
false,
125-
);
126-
}
127-
128-
// SAFETY: running.compare_exchange guarantees exclusive access
147+
// SAFETY: the claim guarantees exclusive access
129148
let gen_exc = unsafe { self.exception.swap(None) };
130149
let exception_ptr = &self.exception as *const PyAtomicRef<Option<PyBaseException>>;
131150

132-
let result = vm.resume_gen_frame(&self.frame, gen_exc, |f| {
151+
vm.resume_gen_frame(&self.frame, gen_exc, |f| {
133152
let result = func(f);
134-
// SAFETY: exclusive access guaranteed by running flag
153+
// SAFETY: exclusive access guaranteed by the claim
135154
let _old = unsafe { (*exception_ptr).swap(vm.current_exception()) };
136155
result
137-
});
138-
139-
self.running.store(false);
140-
(result, true)
156+
})
141157
}
142158

143159
fn finalize_send_result(
144160
&self,
145161
result: PyResult<ExecutionResult>,
146-
entered_frame: bool,
147162
jen: &PyObject,
148163
vm: &VirtualMachine,
149164
) -> PyResult<PyIterReturn> {
150-
self.maybe_close(&result, entered_frame);
151165
match result {
152166
Ok(exec_res) => Ok(exec_res.into_iter_return(vm)),
153167
Err(e) => {
@@ -177,16 +191,20 @@ impl Coro {
177191
if self.closed.load() {
178192
return Ok(PyIterReturn::StopIteration(None));
179193
}
180-
if self.running.load() {
181-
return Err(vm.new_value_error(format!("{} already executing", gen_name(jen, vm))));
194+
let claim = self.claim(jen, vm)?;
195+
// The generator can have run to its end in the meantime.
196+
if self.closed.load() {
197+
return Ok(PyIterReturn::StopIteration(None));
182198
}
183199
let value = if self.frame.lasti() > 0 {
184200
Some(vm.ctx.none())
185201
} else {
186202
None
187203
};
188-
let (result, entered_frame) = self.run_with_context(jen, vm, |f| f.resume(value, vm));
189-
self.finalize_send_result(result, entered_frame, jen, vm)
204+
let result = self.run_claimed(&claim, vm, |f| f.resume(value, vm));
205+
self.maybe_close(&result, &claim);
206+
drop(claim);
207+
self.finalize_send_result(result, jen, vm)
190208
}
191209

192210
pub fn send(
@@ -198,8 +216,10 @@ impl Coro {
198216
if self.closed.load() {
199217
return Ok(PyIterReturn::StopIteration(None));
200218
}
201-
if self.running.load() {
202-
return Err(vm.new_value_error(format!("{} already executing", gen_name(jen, vm))));
219+
let claim = self.claim(jen, vm)?;
220+
// The generator can have run to its end in the meantime.
221+
if self.closed.load() {
222+
return Ok(PyIterReturn::StopIteration(None));
203223
}
204224
let value = if self.frame.lasti() > 0 {
205225
Some(value)
@@ -211,8 +231,10 @@ impl Coro {
211231
} else {
212232
None
213233
};
214-
let (result, entered_frame) = self.run_with_context(jen, vm, |f| f.resume(value, vm));
215-
self.finalize_send_result(result, entered_frame, jen, vm)
234+
let result = self.run_claimed(&claim, vm, |f| f.resume(value, vm));
235+
self.maybe_close(&result, &claim);
236+
drop(claim);
237+
self.finalize_send_result(result, jen, vm)
216238
}
217239

218240
pub fn throw(
@@ -237,13 +259,25 @@ impl Coro {
237259
// Validate exception type before entering generator context.
238260
// Invalid types propagate to caller without closing the generator.
239261
crate::exceptions::ExceptionCtor::try_from_object(vm, exc_type.clone())?;
240-
let (result, entered_frame) =
241-
self.run_with_context(jen, vm, |f| f.gen_throw(vm, exc_type, exc_val, exc_tb));
242-
self.maybe_close(&result, entered_frame);
262+
let claim = self.claim(jen, vm)?;
263+
// The generator can have run to its end in the meantime. Normalizing
264+
// runs the exception's constructor, so let the claim go first.
265+
if self.closed.load() {
266+
drop(claim);
267+
return Err(vm.normalize_exception(exc_type, exc_val, exc_tb)?);
268+
}
269+
let result = self.run_claimed(&claim, vm, |f| f.gen_throw(vm, exc_type, exc_val, exc_tb));
270+
self.maybe_close(&result, &claim);
271+
drop(claim);
243272
Ok(result?.into_iter_return(vm))
244273
}
245274

246275
pub fn close(&self, jen: &PyObject, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
276+
if self.closed.load() {
277+
return Ok(vm.ctx.none());
278+
}
279+
let claim = self.claim(jen, vm)?;
280+
// The generator can have run to its end in the meantime.
247281
if self.closed.load() {
248282
return Ok(vm.ctx.none());
249283
}
@@ -252,24 +286,19 @@ impl Coro {
252286
self.closed.store(true);
253287
return Ok(vm.ctx.none());
254288
}
255-
let (result, entered_frame) = self.run_with_context(jen, vm, |f| {
289+
let result = self.run_claimed(&claim, vm, |f| {
256290
f.gen_throw(
257291
vm,
258292
vm.ctx.exceptions.generator_exit.to_owned().into(),
259293
vm.ctx.none(),
260294
vm.ctx.none(),
261295
)
262296
});
263-
if !entered_frame {
264-
return match result {
265-
Err(err) => Err(err),
266-
Ok(_) => unreachable!("run_with_context preflight returned without an error"),
267-
};
268-
}
269297
self.closed.store(true);
270298
// Release frame locals and stack to free references held by the
271299
// closed generator, matching gen_send_ex2 with close_on_completion.
272300
self.clear_frame_locals_on_close();
301+
drop(claim);
273302
match result {
274303
Ok(ExecutionResult::Yield(_)) => {
275304
Err(vm.new_runtime_error(format!("{} ignored GeneratorExit", gen_name(jen, vm))))
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
"""Resume one generator from several threads at once.
2+
3+
A generator is resumed by one thread at a time, and whether the sent value is
4+
pushed onto the frame's value stack depends on whether the generator has
5+
already started. Deciding that before the generator is claimed reads a frame
6+
another thread can advance in the meantime, and resuming it then leaves the
7+
stack short of what the code after the yield expects.
8+
9+
Every yielded value still has to reach exactly one caller: threads that lose
10+
the race get a ValueError instead of a value.
11+
"""
12+
13+
import threading
14+
15+
WORKERS = 4
16+
ROUNDS = 400
17+
18+
19+
def counter():
20+
yield 1
21+
yield 2
22+
yield 3
23+
24+
25+
gens = [counter() for _ in range(ROUNDS)]
26+
received = [[] for _ in range(ROUNDS)]
27+
start = threading.Barrier(WORKERS)
28+
errors = []
29+
30+
31+
def worker():
32+
try:
33+
for index, gen in enumerate(gens):
34+
start.wait()
35+
for _ in range(3):
36+
try:
37+
received[index].append(next(gen))
38+
except StopIteration:
39+
break
40+
except ValueError:
41+
# another thread is running this generator
42+
pass
43+
except Exception as exc: # noqa: BLE001
44+
errors.append(exc)
45+
46+
47+
threads = [threading.Thread(target=worker) for _ in range(WORKERS)]
48+
for t in threads:
49+
t.start()
50+
for t in threads:
51+
t.join()
52+
53+
assert not errors, errors
54+
for got in received:
55+
# no value handed out twice, and none skipped
56+
assert sorted(got) == list(range(1, len(got) + 1)), got
57+
58+
59+
# a generator that is closed while it is being resumed stays consistent
60+
def loop():
61+
while True:
62+
yield 1
63+
64+
65+
shared = loop()
66+
closed = threading.Barrier(2)
67+
68+
69+
def resumer():
70+
closed.wait()
71+
for _ in range(ROUNDS):
72+
try:
73+
next(shared)
74+
except (StopIteration, ValueError):
75+
pass
76+
77+
78+
def closer():
79+
closed.wait()
80+
try:
81+
shared.close()
82+
except ValueError:
83+
# the generator was running
84+
pass
85+
86+
87+
pair = [threading.Thread(target=resumer), threading.Thread(target=closer)]
88+
for t in pair:
89+
t.start()
90+
for t in pair:
91+
t.join()
92+
93+
print("ok")

0 commit comments

Comments
 (0)