Skip to main content

reth_tasks/
for_each_ordered.rs

1use reth_concurrency::sync::rayon;
2
3use crossbeam_utils::CachePadded;
4use rayon::iter::{IndexedParallelIterator, ParallelIterator};
5#[cfg(all(feature = "fuzz", dst))]
6use reth_concurrency::sync::channel;
7use std::panic::{catch_unwind, AssertUnwindSafe};
8
9#[cfg(not(all(feature = "fuzz", dst)))]
10use reth_concurrency::sync::parking_lot;
11
12/// Extension trait for [`IndexedParallelIterator`]
13/// that streams results to a sequential consumer in index order.
14pub trait ForEachOrdered: IndexedParallelIterator {
15    /// Executes the parallel iterator, calling `f` on each result **sequentially in index
16    /// order**.
17    ///
18    /// Items are computed in parallel, but `f` is invoked as `f(item_0)`, `f(item_1)`, …,
19    /// `f(item_{n-1})` on the calling thread. The calling thread receives each item as soon
20    /// as it (and all preceding items) are ready.
21    ///
22    /// `f` does **not** need to be [`Send`] — it runs exclusively on the calling thread.
23    ///
24    /// # Blocking
25    ///
26    /// The calling thread blocks (via a condvar, or a scheduled channel under `fuzz` plus `--cfg
27    /// dst`) while waiting for the next item to become ready. It does **not** participate in
28    /// rayon's work-stealing while blocked. With the native backend, invoke this from a dedicated
29    /// blocking thread (e.g. via [`tokio::task::spawn_blocking`]) rather than the rayon thread
30    /// pool. With `fuzz` plus `--cfg dst`, invoke this inside
31    /// [`reth_concurrency::sync::Runtime::run`] or one of its selected threads, not directly from a
32    /// Tokio blocking worker.
33    fn for_each_ordered<F>(self, f: F)
34    where
35        Self::Item: Send,
36        F: FnMut(Self::Item);
37
38    /// Like [`for_each_ordered`](Self::for_each_ordered), but runs the parallel work on the
39    /// given `pool` instead of the global rayon thread pool.
40    fn for_each_ordered_in<F>(self, pool: &rayon::ThreadPool, f: F)
41    where
42        Self::Item: Send,
43        F: FnMut(Self::Item);
44}
45
46impl<I: IndexedParallelIterator> ForEachOrdered for I {
47    fn for_each_ordered<F>(self, f: F)
48    where
49        Self::Item: Send,
50        F: FnMut(Self::Item),
51    {
52        ordered_impl(self, None, f);
53    }
54
55    fn for_each_ordered_in<F>(self, pool: &rayon::ThreadPool, f: F)
56    where
57        Self::Item: Send,
58        F: FnMut(Self::Item),
59    {
60        ordered_impl(self, Some(pool), f);
61    }
62}
63
64/// A slot with a native condvar or scheduler-aware channel for notification.
65struct Slot<T> {
66    #[cfg(not(all(feature = "fuzz", dst)))]
67    value: parking_lot::Mutex<Option<T>>,
68    #[cfg(not(all(feature = "fuzz", dst)))]
69    notify: parking_lot::Condvar,
70    #[cfg(all(feature = "fuzz", dst))]
71    tx: channel::Sender<Result<T, ()>>,
72    #[cfg(all(feature = "fuzz", dst))]
73    rx: channel::Receiver<Result<T, ()>>,
74}
75
76impl<T> Slot<T> {
77    #[cfg(not(all(feature = "fuzz", dst)))]
78    const fn new() -> Self {
79        Self { value: parking_lot::Mutex::new(None), notify: parking_lot::Condvar::new() }
80    }
81
82    #[cfg(all(feature = "fuzz", dst))]
83    fn new() -> Self {
84        let (tx, rx) = channel::unbounded();
85        Self { tx, rx }
86    }
87}
88
89struct Shared<T> {
90    slots: Box<[CachePadded<Slot<T>>]>,
91    #[cfg(not(all(feature = "fuzz", dst)))]
92    panicked: std::sync::atomic::AtomicBool,
93}
94
95impl<T> Shared<T> {
96    fn new(n: usize) -> Self {
97        let slots =
98            (0..n).map(|_| CachePadded::new(Slot::new())).collect::<Vec<_>>().into_boxed_slice();
99        Self {
100            slots,
101            #[cfg(not(all(feature = "fuzz", dst)))]
102            panicked: std::sync::atomic::AtomicBool::new(false),
103        }
104    }
105
106    /// Writes a value into slot `i`. Must only be called once per index.
107    #[inline]
108    fn write(&self, i: usize, val: T) {
109        let slot = &self.slots[i];
110        #[cfg(not(all(feature = "fuzz", dst)))]
111        {
112            *slot.value.lock() = Some(val);
113            slot.notify.notify_one();
114        }
115        #[cfg(all(feature = "fuzz", dst))]
116        slot.tx.send(Ok(val)).unwrap_or_else(|_| unreachable!("slot retains its receiver"));
117    }
118
119    /// Blocks until slot `i` is ready and takes the value.
120    /// Returns `None` if the producer panicked.
121    fn take(&self, i: usize) -> Option<T> {
122        let slot = &self.slots[i];
123        #[cfg(all(feature = "fuzz", dst))]
124        {
125            slot.rx.recv().expect("slot retains its sender").ok()
126        }
127        #[cfg(not(all(feature = "fuzz", dst)))]
128        {
129            let mut guard = slot.value.lock();
130            loop {
131                if let Some(val) = guard.take() {
132                    return Some(val);
133                }
134                if self.panicked.load(std::sync::atomic::Ordering::Acquire) {
135                    return None;
136                }
137                slot.notify.wait(&mut guard);
138            }
139        }
140    }
141}
142
143/// Executes a parallel iterator and delivers results to a sequential callback in index order.
144///
145/// Each slot has its own notification, so the consumer blocks on the slot it needs.
146fn ordered_impl<I, F>(iter: I, pool: Option<&rayon::ThreadPool>, mut f: F)
147where
148    I: IndexedParallelIterator,
149    I::Item: Send,
150    F: FnMut(I::Item),
151{
152    let n = iter.len();
153    if n == 0 {
154        return;
155    }
156
157    let shared = Shared::<I::Item>::new(n);
158
159    in_place_scope_in(pool, |s| {
160        // Producer: compute items in parallel and write them into their slots.
161        s.spawn(|_| {
162            let res = catch_unwind(AssertUnwindSafe(|| {
163                iter.enumerate().for_each(|(i, item)| {
164                    shared.write(i, item);
165                });
166            }));
167            if let Err(payload) = res {
168                #[cfg(not(all(feature = "fuzz", dst)))]
169                shared.panicked.store(true, std::sync::atomic::Ordering::Release);
170                // Wake all slots so the consumer doesn't hang. Lock each slot's mutex
171                // first to serialize with the consumer's panicked check → wait sequence.
172                for slot in &*shared.slots {
173                    #[cfg(not(all(feature = "fuzz", dst)))]
174                    {
175                        let _guard = slot.value.lock();
176                        slot.notify.notify_one();
177                    }
178                    #[cfg(all(feature = "fuzz", dst))]
179                    slot.tx
180                        .send(Err(()))
181                        .unwrap_or_else(|_| unreachable!("slot retains its receiver"));
182                }
183                std::panic::resume_unwind(payload);
184            }
185        });
186
187        // Consumer: sequential, ordered, on the calling thread.
188        for i in 0..n {
189            let Some(value) = shared.take(i) else {
190                return;
191            };
192            f(value);
193        }
194    });
195}
196
197fn in_place_scope_in<'scope, F, R>(pool: Option<&rayon::ThreadPool>, f: F)
198where
199    F: FnOnce(&rayon::Scope<'scope>) -> R,
200{
201    if let Some(pool) = pool {
202        pool.in_place_scope(f);
203    } else {
204        rayon::in_place_scope(f);
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211    use reth_concurrency::sync::{
212        atomic::{AtomicUsize, Ordering},
213        rayon::prelude::*,
214        thread,
215    };
216    use std::{cell::Cell, rc::Rc};
217
218    #[cfg(not(all(feature = "fuzz", dst)))]
219    use std::sync::Barrier;
220
221    #[reth_concurrency::test]
222    fn preserves_order() {
223        let input: Vec<u64> = (0..1000).collect();
224        let mut output = Vec::with_capacity(input.len());
225        input.par_iter().map(|x| x * 2).for_each_ordered(|x| output.push(x));
226        let expected: Vec<u64> = (0..1000).map(|x| x * 2).collect();
227        assert_eq!(output, expected);
228    }
229
230    #[reth_concurrency::test]
231    fn empty_iterator() {
232        let input: Vec<u64> = vec![];
233        let mut output = Vec::new();
234        input.par_iter().map(|x| *x).for_each_ordered(|x| output.push(x));
235        assert!(output.is_empty());
236    }
237
238    #[reth_concurrency::test]
239    fn single_element() {
240        let mut output = Vec::new();
241        vec![42u64].par_iter().map(|x| *x).for_each_ordered(|x| output.push(x));
242        assert_eq!(output, vec![42]);
243    }
244
245    // The fuzz iterator shim computes serially; two iterator items cannot rendezvous.
246    #[cfg(not(all(feature = "fuzz", dst)))]
247    #[reth_concurrency::test]
248    fn slow_early_items_still_delivered_in_order() {
249        let barrier = Barrier::new(2);
250        let n = 64usize;
251        let input: Vec<usize> = (0..n).collect();
252        let mut output = Vec::with_capacity(n);
253
254        input
255            .par_iter()
256            .map(|&i| {
257                if i == 0 || i == n - 1 {
258                    barrier.wait();
259                }
260                i
261            })
262            .for_each_ordered(|x| output.push(x));
263
264        assert_eq!(output, input);
265    }
266
267    #[reth_concurrency::test]
268    fn drops_unconsumed_slots_on_panic() {
269        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
270
271        #[derive(Clone)]
272        struct Tracked(#[allow(dead_code)] u64);
273        impl Drop for Tracked {
274            fn drop(&mut self) {
275                DROP_COUNT.fetch_add(1, Ordering::Relaxed);
276            }
277        }
278
279        DROP_COUNT.store(0, Ordering::Relaxed);
280
281        let input: Vec<u64> = (0..100).collect();
282        let result = catch_unwind(|| {
283            input
284                .par_iter()
285                .map(|&i| {
286                    assert!(i != 50, "intentional");
287                    Tracked(i)
288                })
289                .for_each_ordered(|_item| {});
290        });
291
292        assert_eq!(result.unwrap_err().downcast_ref::<&str>(), Some(&"intentional"));
293        let drops = DROP_COUNT.load(Ordering::Relaxed);
294        assert!(drops > 0, "some items should have been dropped");
295    }
296
297    #[reth_concurrency::test]
298    fn no_double_drop() {
299        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
300
301        struct Counted(#[allow(dead_code)] u64);
302        impl Drop for Counted {
303            fn drop(&mut self) {
304                DROP_COUNT.fetch_add(1, Ordering::Relaxed);
305            }
306        }
307
308        DROP_COUNT.store(0, Ordering::Relaxed);
309        let n = 200u64;
310        let input: Vec<u64> = (0..n).collect();
311        input.par_iter().map(|&i| Counted(i)).for_each_ordered(|_item| {});
312
313        assert_eq!(DROP_COUNT.load(Ordering::Relaxed), n as usize);
314    }
315
316    #[reth_concurrency::test]
317    fn callback_is_not_send() {
318        let counter = Rc::new(Cell::new(0u64));
319        let input: Vec<u64> = (0..100).collect();
320        input.par_iter().map(|&x| x).for_each_ordered(|x| {
321            counter.set(counter.get() + x);
322        });
323        assert_eq!(counter.get(), (0..100u64).sum::<u64>());
324    }
325
326    #[reth_concurrency::test]
327    fn panic_does_not_deadlock_consumer() {
328        // Regression test: producer panics while consumer is waiting on a condvar.
329        // Without the lock-before-notify fix, the consumer could miss the wakeup
330        // and deadlock.
331        for _ in 0..100 {
332            let result = catch_unwind(|| {
333                let input: Vec<usize> = (0..256).collect();
334                input
335                    .par_iter()
336                    .map(|&i| {
337                        if i == 128 {
338                            // Yield to increase the chance of the consumer being
339                            // between the panicked check and condvar wait.
340                            thread::yield_now();
341                            panic!("intentional");
342                        }
343                        i
344                    })
345                    .for_each_ordered(|_| {});
346            });
347            assert_eq!(result.unwrap_err().downcast_ref::<&str>(), Some(&"intentional"));
348        }
349    }
350
351    #[reth_concurrency::test]
352    fn early_panic_at_item_zero() {
353        let result = catch_unwind(|| {
354            let input: Vec<u64> = (0..10).collect();
355            input
356                .par_iter()
357                .map(|&i| {
358                    assert!(i != 0, "boom at zero");
359                    i
360                })
361                .for_each_ordered(|_| {});
362        });
363        assert_eq!(result.unwrap_err().downcast_ref::<&str>(), Some(&"boom at zero"));
364    }
365
366    #[reth_concurrency::test]
367    fn late_panic_at_last_item() {
368        let n = 100usize;
369        let result = catch_unwind(|| {
370            let input: Vec<usize> = (0..n).collect();
371            input
372                .par_iter()
373                .map(|&i| {
374                    assert!(i != n - 1, "boom at last");
375                    i
376                })
377                .for_each_ordered(|_| {});
378        });
379        assert_eq!(result.unwrap_err().downcast_ref::<&str>(), Some(&"boom at last"));
380    }
381
382    #[reth_concurrency::test]
383    fn large_items() {
384        let n = 500usize;
385        let input: Vec<usize> = (0..n).collect();
386        let mut output = Vec::with_capacity(n);
387        input
388            .par_iter()
389            .map(|&i| {
390                // Return a heap-allocated value to stress drop semantics.
391                vec![i; 64]
392            })
393            .for_each_ordered(|v| output.push(v[0]));
394        assert_eq!(output, input);
395    }
396
397    #[reth_concurrency::test]
398    fn consumer_slower_than_producer() {
399        // Producer is fast, consumer is slow. All items should still arrive in order.
400        let n = 64usize;
401        let input: Vec<usize> = (0..n).collect();
402        let mut output = Vec::with_capacity(n);
403        input.par_iter().map(|&i| i).for_each_ordered(|x| {
404            if x % 8 == 0 {
405                thread::yield_now();
406            }
407            output.push(x);
408        });
409        assert_eq!(output, input);
410    }
411
412    // The fuzz iterator shim computes serially; two iterator items cannot rendezvous.
413    #[cfg(not(all(feature = "fuzz", dst)))]
414    #[reth_concurrency::test]
415    fn concurrent_panic_and_drop_no_leak() {
416        // Ensure items produced before a panic are all dropped.
417        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
418        static PRODUCED: AtomicUsize = AtomicUsize::new(0);
419
420        struct Tracked;
421        impl Drop for Tracked {
422            fn drop(&mut self) {
423                DROP_COUNT.fetch_add(1, Ordering::Relaxed);
424            }
425        }
426
427        DROP_COUNT.store(0, Ordering::Relaxed);
428        PRODUCED.store(0, Ordering::Relaxed);
429
430        let barrier = Barrier::new(2);
431        let result = catch_unwind(|| {
432            let input: Vec<usize> = (0..64).collect();
433            input
434                .par_iter()
435                .map(|&i| {
436                    if i == 32 {
437                        barrier.wait();
438                        panic!("intentional");
439                    }
440                    if i == 0 {
441                        barrier.wait();
442                    }
443                    PRODUCED.fetch_add(1, Ordering::Relaxed);
444                    Tracked
445                })
446                .for_each_ordered(|_| {});
447        });
448
449        assert_eq!(result.unwrap_err().downcast_ref::<&str>(), Some(&"intentional"));
450        let produced = PRODUCED.load(Ordering::Relaxed);
451        let dropped = DROP_COUNT.load(Ordering::Relaxed);
452        assert_eq!(dropped, produced, "all produced items must be dropped");
453    }
454}