Skip to main content

vortex_io/runtime/
current.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::future::Future;
5use std::sync::Arc;
6
7use async_channel::TryRecvError;
8use futures::Stream;
9use futures::StreamExt;
10use futures::stream::BoxStream;
11use parking_lot::Mutex;
12use smol::block_on;
13use vortex_utils::parallelism::get_available_parallelism;
14
15use crate::runtime::BlockingRuntime;
16use crate::runtime::Executor;
17use crate::runtime::Handle;
18pub use crate::runtime::pool::CurrentThreadWorkerPool;
19use crate::runtime::smol::SmolExecutor;
20
21/// A current thread runtime allows callers to much more explicitly drive Vortex futures than with
22/// a Tokio runtime.
23///
24/// The current thread runtime will do no work unless `block_on` is called. In other words, the
25/// default behavior is single-threaded with code running on the thread that called `block_on`.
26///
27/// It's also possible to clone the runtime onto other threads, each of which can call `block_on`
28/// to drive work on that thread. Each thread shares the same underlying executor with the same
29/// set of tasks, allowing work to be driven in parallel.
30///
31/// For automatic driving of work, a [`CurrentThreadWorkerPool`] can be created from the runtime
32/// by calling [`new_pool`](CurrentThreadRuntime::new_pool). The returned pool can be configured
33/// with the desired number of worker threads that will drive work on behalf of the runtime.
34#[derive(Clone, Default)]
35pub struct CurrentThreadRuntime {
36    executor: Arc<SmolExecutor>,
37}
38
39impl CurrentThreadRuntime {
40    /// Create a new current thread runtime.
41    pub fn new() -> Self {
42        Self::default()
43    }
44
45    /// Create a new worker pool for driving the runtime in the background.
46    ///
47    /// This pool can be used to offload work from the current thread to a set of worker threads
48    /// that will drive the runtime's executor.
49    ///
50    /// By default, the pool has no worker threads; the caller must set the desired number of
51    /// worker threads using the `set_workers` method on the returned pool.
52    pub fn new_pool(&self) -> CurrentThreadWorkerPool {
53        CurrentThreadWorkerPool::new(Arc::clone(&self.executor))
54    }
55
56    /// Returns an iterator wrapper around a stream, blocking the current thread for each item.
57    ///
58    /// ## Multi-threaded Usage
59    ///
60    /// To drive the iterator from multiple threads, simply clone it and call `next()` on each
61    /// clone. Results on each thread are ordered with respect to the stream, but there is no
62    /// ordering guarantee between threads.
63    pub fn block_on_stream_thread_safe<F, S, R>(&self, f: F) -> ThreadSafeIterator<R>
64    where
65        F: FnOnce(Handle) -> S,
66        S: Stream<Item = R> + Send + 'static,
67        R: Send + 'static,
68    {
69        let stream = f(self.handle());
70
71        // We create an MPMC result channel and spawn a task to drive the stream and send results.
72        // This allows multiple worker threads to drive the execution while all waiting for results
73        // on the channel. Channel buffers up to one item per core so calling threads can get a
74        // ready item without every one of them having to become an executor.
75        let capacity = get_available_parallelism().unwrap_or(1).max(1);
76        let (result_tx, result_rx) = async_channel::bounded(capacity);
77        let driver = self.executor.async_executor().spawn(async move {
78            futures::pin_mut!(stream);
79            while let Some(item) = stream.next().await {
80                // If all receivers are dropped, we stop driving the stream.
81                if let Err(e) = result_tx.send(item).await {
82                    tracing::trace!("all receivers dropped, stopping stream: {}", e);
83                    break;
84                }
85            }
86        });
87
88        ThreadSafeIterator {
89            executor: Arc::clone(&self.executor),
90            results: result_rx,
91            driver: Arc::new(Mutex::new(Some(driver))),
92        }
93    }
94}
95
96impl BlockingRuntime for CurrentThreadRuntime {
97    type BlockingIterator<'a, R: 'a> = CurrentThreadIterator<'a, R>;
98
99    fn handle(&self) -> Handle {
100        let executor: Arc<dyn Executor> = Arc::clone(&self.executor) as Arc<dyn Executor>;
101        Handle::new(Arc::downgrade(&executor))
102    }
103
104    fn block_on<Fut, R>(&self, fut: Fut) -> R
105    where
106        Fut: Future<Output = R>,
107    {
108        block_on(self.executor.run(fut))
109    }
110
111    fn block_on_stream<'a, S, R>(&self, stream: S) -> Self::BlockingIterator<'a, R>
112    where
113        S: Stream<Item = R> + Send + 'a,
114        R: Send + 'a,
115    {
116        CurrentThreadIterator {
117            executor: Arc::clone(&self.executor),
118            stream: stream.boxed(),
119        }
120    }
121}
122
123/// An iterator that wraps up a stream to drive it using the current thread execution.
124pub struct CurrentThreadIterator<'a, T> {
125    executor: Arc<SmolExecutor>,
126    stream: BoxStream<'a, T>,
127}
128
129impl<T> Iterator for CurrentThreadIterator<'_, T> {
130    type Item = T;
131
132    fn next(&mut self) -> Option<Self::Item> {
133        block_on(self.executor.run(self.stream.next()))
134    }
135}
136
137/// An iterator that drives a stream from multiple threads.
138pub struct ThreadSafeIterator<T> {
139    executor: Arc<SmolExecutor>,
140    results: async_channel::Receiver<T>,
141    /// Handle to the task driving the stream. Once the stream ends, the first consumer to
142    /// observe it joins the task so a panic raised while driving the stream is re-raised rather
143    /// than silently ending the iterator.
144    driver: Arc<Mutex<Option<smol::Task<()>>>>,
145}
146
147// Manual clone implementation since `T` does not need to be `Clone`.
148impl<T> Clone for ThreadSafeIterator<T> {
149    fn clone(&self) -> Self {
150        Self {
151            executor: Arc::clone(&self.executor),
152            results: self.results.clone(),
153            driver: Arc::clone(&self.driver),
154        }
155    }
156}
157
158impl<T> Iterator for ThreadSafeIterator<T> {
159    type Item = T;
160
161    fn next(&mut self) -> Option<Self::Item> {
162        // If driver already has an item, take it without driving the executor
163        match self.results.try_recv() {
164            Ok(item) => return Some(item),
165            Err(TryRecvError::Empty) => {}
166            Err(TryRecvError::Closed) => return self.get_task_error(),
167        }
168
169        match block_on(self.executor.run(self.results.recv())) {
170            Ok(item) => Some(item),
171            Err(_) => self.get_task_error(),
172        }
173    }
174}
175
176impl<T> ThreadSafeIterator<T> {
177    // Join current task so panics are re-raised
178    fn get_task_error(&self) -> Option<T> {
179        let task = self.driver.lock().take();
180        if let Some(task) = task {
181            block_on(self.executor.run(task));
182        }
183        None
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use std::any::Any;
190    use std::panic::AssertUnwindSafe;
191    use std::sync::Arc;
192    use std::sync::Barrier;
193    use std::sync::atomic::AtomicUsize;
194    use std::sync::atomic::Ordering;
195    use std::task::Poll;
196    use std::thread;
197    use std::time::Duration;
198
199    use futures::StreamExt;
200    use futures::stream;
201    use parking_lot::Mutex;
202
203    use super::*;
204
205    #[test]
206    fn test_worker_thread() {
207        let runtime = CurrentThreadRuntime::new();
208
209        // We spawn a future that sets a value on a separate thread.
210        let value = Arc::new(AtomicUsize::new(0));
211        let value2 = Arc::clone(&value);
212        runtime
213            .handle()
214            .spawn(async move {
215                value2.store(42, Ordering::SeqCst);
216            })
217            .detach();
218
219        // By default, nothing has driven the executor, so the value should still be 0.
220        assert_eq!(value.load(Ordering::SeqCst), 0);
221
222        // An empty pool still does nothing.
223        let pool = runtime.new_pool();
224        assert_eq!(value.load(Ordering::SeqCst), 0);
225
226        // Adding a worker thread should drive the executor.
227        pool.set_workers(1);
228        for _ in 0..10 {
229            if value.load(Ordering::SeqCst) == 42 {
230                break;
231            }
232            thread::sleep(Duration::from_millis(10));
233        }
234        assert_eq!(value.load(Ordering::SeqCst), 42);
235    }
236
237    #[test]
238    fn test_block_on_stream_single_thread() {
239        let mut iter =
240            CurrentThreadRuntime::new().block_on_stream(stream::iter(vec![1, 2, 3, 4, 5]).boxed());
241
242        assert_eq!(iter.next(), Some(1));
243        assert_eq!(iter.next(), Some(2));
244        assert_eq!(iter.next(), Some(3));
245        assert_eq!(iter.next(), Some(4));
246        assert_eq!(iter.next(), Some(5));
247        assert_eq!(iter.next(), None);
248    }
249
250    #[test]
251    fn test_block_on_stream_multiple_threads() {
252        let counter = Arc::new(AtomicUsize::new(0));
253        let num_threads = 4;
254        let items_per_thread = 25;
255        let total_items = 100;
256
257        let iter = CurrentThreadRuntime::new()
258            .block_on_stream_thread_safe(|_h| stream::iter(0..total_items).boxed());
259
260        let barrier = Arc::new(Barrier::new(num_threads));
261        let results = Arc::new(Mutex::new(Vec::new()));
262
263        let threads: Vec<_> = (0..num_threads)
264            .map(|_| {
265                let mut iter = iter.clone();
266                let counter = Arc::clone(&counter);
267                let barrier = Arc::clone(&barrier);
268                let results = Arc::clone(&results);
269
270                thread::spawn(move || {
271                    barrier.wait();
272                    let mut local_results = Vec::new();
273
274                    for _ in 0..items_per_thread {
275                        if let Some(item) = iter.next() {
276                            counter.fetch_add(1, Ordering::SeqCst);
277                            local_results.push(item);
278                        }
279                    }
280
281                    results.lock().push(local_results);
282                })
283            })
284            .collect();
285
286        for thread in threads {
287            thread.join().unwrap();
288        }
289
290        assert_eq!(counter.load(Ordering::SeqCst), total_items);
291
292        let all_results = results.lock();
293        let mut collected: Vec<_> = all_results.iter().flatten().copied().collect();
294        collected.sort();
295        assert_eq!(collected, (0..total_items).collect::<Vec<_>>());
296    }
297
298    #[test]
299    fn test_block_on_stream_thread_safe_propagates_driver_panic() {
300        let runtime = CurrentThreadRuntime::new();
301        let mut iter = runtime.block_on_stream_thread_safe(|_h| {
302            stream::poll_fn(|_| -> Poll<Option<usize>> {
303                panic!("stream driver panic");
304            })
305            .boxed()
306        });
307
308        let panic = std::panic::catch_unwind(AssertUnwindSafe(|| iter.next()))
309            .expect_err("stream panic must propagate through iterator");
310        let message = panic
311            .downcast_ref::<&'static str>()
312            .copied()
313            .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
314            .unwrap_or("<unknown panic>");
315        assert!(message.contains("stream driver panic"));
316    }
317
318    fn panic_message(panic: &(dyn Any + Send)) -> &str {
319        panic
320            .downcast_ref::<&'static str>()
321            .copied()
322            .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
323            .unwrap_or("<unknown panic>")
324    }
325
326    // A driver panic must propagate on *every* run, regardless of executor scheduling. Running
327    // the scenario many times guards against a return to timing-dependent propagation.
328    #[test]
329    fn test_block_on_stream_thread_safe_panic_propagation_is_deterministic() {
330        for i in 0..2000 {
331            let mut iter = CurrentThreadRuntime::new().block_on_stream_thread_safe(|_h| {
332                stream::poll_fn(|_| -> Poll<Option<usize>> {
333                    panic!("deterministic driver panic");
334                })
335                .boxed()
336            });
337
338            let outcome = std::panic::catch_unwind(AssertUnwindSafe(|| iter.next()));
339            assert!(
340                outcome.is_err(),
341                "driver panic was swallowed on iteration {i}: next() returned {:?}",
342                outcome.ok().flatten(),
343            );
344        }
345    }
346
347    // A panic after some items were already produced must still surface, not be seen as a clean
348    // end of stream.
349    #[test]
350    fn test_block_on_stream_thread_safe_panic_after_items() {
351        let mut emitted = 0usize;
352        let iter = CurrentThreadRuntime::new().block_on_stream_thread_safe(move |_h| {
353            stream::poll_fn(move |_| -> Poll<Option<usize>> {
354                if emitted < 3 {
355                    emitted += 1;
356                    Poll::Ready(Some(emitted))
357                } else {
358                    panic!("driver panic after items");
359                }
360            })
361            .boxed()
362        });
363
364        // Drain the iterator. The terminal event must be a propagated panic, never a clean
365        // `None`. This avoids depending on exactly how many buffered items survive channel close.
366        let outcome = std::panic::catch_unwind(AssertUnwindSafe(move || iter.collect::<Vec<_>>()));
367        match outcome {
368            Ok(items) => panic!("driver panic was swallowed; stream ended cleanly with {items:?}"),
369            Err(panic) => assert!(panic_message(&*panic).contains("driver panic after items")),
370        }
371    }
372
373    // With multiple consumers, a driver panic must reach *every* consumer that observes the end
374    // of the stream; it must never be swallowed by all of them. Exactly one consumer joins the
375    // driver and observes the panic; the rest see the stream end.
376    #[test]
377    fn test_block_on_stream_thread_safe_multi_consumer_panic_surfaced() {
378        let iter = CurrentThreadRuntime::new().block_on_stream_thread_safe(|_h| {
379            stream::poll_fn(|_| -> Poll<Option<usize>> {
380                panic!("multi consumer driver panic");
381            })
382            .boxed()
383        });
384
385        let num_threads = 4;
386        let barrier = Arc::new(Barrier::new(num_threads));
387        let panics = Arc::new(AtomicUsize::new(0));
388
389        let handles: Vec<_> = (0..num_threads)
390            .map(|_| {
391                let mut iter = iter.clone();
392                let barrier = Arc::clone(&barrier);
393                let panics = Arc::clone(&panics);
394                thread::spawn(move || {
395                    barrier.wait();
396                    match std::panic::catch_unwind(AssertUnwindSafe(|| iter.next())) {
397                        // The driver panicked before producing anything, so a clean end is the
398                        // only non-panic outcome a consumer may observe.
399                        Ok(None) => {}
400                        Ok(Some(_)) => panic!("no item was produced before the driver panicked"),
401                        Err(panic) => {
402                            assert!(panic_message(&*panic).contains("multi consumer driver panic"));
403                            panics.fetch_add(1, Ordering::SeqCst);
404                        }
405                    }
406                })
407            })
408            .collect();
409
410        for handle in handles {
411            handle.join().expect("consumer thread panicked uncaught");
412        }
413
414        // The panic surfaces to exactly one consumer and is never swallowed by all of them.
415        assert_eq!(panics.load(Ordering::SeqCst), 1);
416    }
417
418    // Clean completion must return `None` with no spurious panic.
419    #[test]
420    fn test_block_on_stream_thread_safe_clean_completion_returns_none() {
421        let mut iter = CurrentThreadRuntime::new()
422            .block_on_stream_thread_safe(|_h| stream::iter(vec![1usize, 2, 3]).boxed());
423
424        assert_eq!(iter.next(), Some(1));
425        assert_eq!(iter.next(), Some(2));
426        assert_eq!(iter.next(), Some(3));
427        assert_eq!(iter.next(), None);
428        assert_eq!(iter.next(), None);
429    }
430
431    #[test]
432    fn test_block_on_stream_concurrent_clone_and_drive() {
433        let num_items = 50;
434        let num_threads = 3;
435
436        let iter = CurrentThreadRuntime::new().block_on_stream_thread_safe(|h| {
437            stream::unfold(0, move |state| {
438                let h = h.clone();
439                async move {
440                    if state < num_items {
441                        h.spawn_cpu(move || {
442                            thread::sleep(Duration::from_micros(10));
443                            state
444                        })
445                        .await;
446                        Some((state, state + 1))
447                    } else {
448                        None
449                    }
450                }
451            })
452        });
453
454        let collected = Arc::new(Mutex::new(Vec::new()));
455        let barrier = Arc::new(Barrier::new(num_threads));
456
457        let threads: Vec<_> = (0..num_threads)
458            .map(|thread_id| {
459                let iter = iter.clone();
460                let collected = Arc::clone(&collected);
461                let barrier = Arc::clone(&barrier);
462
463                thread::spawn(move || {
464                    barrier.wait();
465                    let mut local_items = Vec::new();
466
467                    for item in iter {
468                        local_items.push((thread_id, item));
469                        if local_items.len() >= 5 {
470                            break;
471                        }
472                    }
473
474                    collected.lock().extend(local_items);
475                })
476            })
477            .collect();
478
479        for thread in threads {
480            thread.join().unwrap();
481        }
482
483        let results = collected.lock();
484        let mut values: Vec<_> = results.iter().map(|(_, v)| *v).collect();
485        values.sort();
486        assert_eq!(values, (0..num_threads * 5).collect::<Vec<_>>());
487    }
488
489    #[test]
490    fn test_block_on_stream_async_work() {
491        let runtime = CurrentThreadRuntime::new();
492        let handle = runtime.handle();
493        let iter = runtime.block_on_stream({
494            stream::unfold((handle, 0), |(h, state)| async move {
495                if state < 10 {
496                    let value = h
497                        .spawn(async move { futures::future::ready(state * 2).await })
498                        .await;
499                    Some((value, (h, state + 1)))
500                } else {
501                    None
502                }
503            })
504        });
505
506        let results: Vec<_> = iter.collect();
507        assert_eq!(results, vec![0, 2, 4, 6, 8, 10, 12, 14, 16, 18]);
508    }
509
510    #[test]
511    fn test_block_on_stream_drop_receivers_early() {
512        let counter = Arc::new(AtomicUsize::new(0));
513        let c = Arc::clone(&counter);
514
515        let mut iter = CurrentThreadRuntime::new().block_on_stream({
516            stream::unfold(0, move |state| {
517                let c = Arc::clone(&c);
518                async move {
519                    (state < 100).then(|| {
520                        c.fetch_add(1, Ordering::SeqCst);
521                        (state, state + 1)
522                    })
523                }
524            })
525            .boxed()
526        });
527
528        assert_eq!(iter.next(), Some(0));
529        assert_eq!(iter.next(), Some(1));
530        assert_eq!(iter.next(), Some(2));
531
532        drop(iter);
533
534        let final_count = counter.load(Ordering::SeqCst);
535        assert!(
536            final_count < 100,
537            "Stream should stop when all receivers are dropped"
538        );
539    }
540
541    #[test]
542    fn test_block_on_stream_interleaved_access() {
543        let barrier = Arc::new(Barrier::new(2));
544        let iter = CurrentThreadRuntime::new()
545            .block_on_stream_thread_safe(|_h| stream::iter(0..20).boxed());
546
547        let iter1 = iter.clone();
548        let iter2 = iter;
549        let barrier1 = Arc::clone(&barrier);
550        let barrier2 = barrier;
551
552        let thread1 = thread::spawn(move || {
553            let mut iter = iter1;
554            let mut results = Vec::new();
555            barrier1.wait();
556
557            for _ in 0..5 {
558                if let Some(val) = iter.next() {
559                    results.push(val);
560                    thread::sleep(Duration::from_micros(50));
561                }
562            }
563            results
564        });
565
566        let thread2 = thread::spawn(move || {
567            let mut iter = iter2;
568            let mut results = Vec::new();
569            barrier2.wait();
570
571            for _ in 0..5 {
572                if let Some(val) = iter.next() {
573                    results.push(val);
574                    thread::sleep(Duration::from_micros(50));
575                }
576            }
577            results
578        });
579
580        let results1 = thread1.join().unwrap();
581        let results2 = thread2.join().unwrap();
582
583        let mut all_results = results1;
584        all_results.extend(results2);
585        all_results.sort();
586
587        assert_eq!(all_results, (0..10).collect::<Vec<_>>());
588
589        for i in 0..10 {
590            assert_eq!(all_results.iter().filter(|&&x| x == i).count(), 1);
591        }
592    }
593
594    #[test]
595    fn test_block_on_stream_stress_test() {
596        let num_threads = 10;
597        let num_items = 1000;
598
599        let iter = CurrentThreadRuntime::new()
600            .block_on_stream_thread_safe(|_h| stream::iter(0..num_items).boxed());
601
602        let received = Arc::new(Mutex::new(Vec::new()));
603        let barrier = Arc::new(Barrier::new(num_threads));
604
605        let threads: Vec<_> = (0..num_threads)
606            .map(|_| {
607                let iter = iter.clone();
608                let received = Arc::clone(&received);
609                let barrier = Arc::clone(&barrier);
610
611                thread::spawn(move || {
612                    barrier.wait();
613                    for val in iter {
614                        received.lock().push(val);
615                    }
616                })
617            })
618            .collect();
619
620        for thread in threads {
621            thread.join().unwrap();
622        }
623
624        let mut results = received.lock().clone();
625        results.sort();
626
627        assert_eq!(results.len(), num_items);
628        assert_eq!(results, (0..num_items).collect::<Vec<_>>());
629    }
630}