Skip to main content

reth_concurrency/sync/
runtime.rs

1//! Explicit entry point for a blocking workload.
2
3#[cfg(all(feature = "fuzz", dst))]
4use super::deterministic;
5
6#[cfg(all(feature = "async-test", feature = "fuzz", dst))]
7use std::rc::Rc;
8#[cfg(all(feature = "async-test", feature = "fuzz", dst))]
9use tokio::{runtime::Handle, task::LocalSet};
10
11#[cfg(all(feature = "async-test", feature = "fuzz", dst))]
12tokio::task_local! {
13    // Scoped around the whole simulation workload so logical workers can enqueue service tasks.
14    static SERVICES: (tokio::runtime::Id, Rc<LocalSet>);
15}
16
17/// Runs a workload using the backend selected by the `fuzz` feature and `dst` cfg.
18///
19/// Runtime construction exposes no scheduler configuration. Simulation runs one
20/// fixed round-robin execution; every spawned task must finish before returning.
21#[derive(Clone, Copy, Debug, Default)]
22pub struct Runtime;
23
24impl Runtime {
25    /// Creates an execution entry point.
26    pub const fn new() -> Self {
27        Self
28    }
29
30    /// Runs `work` and returns its result. Callers must join or finish spawned work.
31    ///
32    /// Generate Arbitrary and property-test inputs before calling `run`, then move
33    /// owned inputs into `work`. Derived Arbitrary implementations can use native
34    /// recursion-count thread-local state, which is not simulated.
35    ///
36    /// Simulated primitives must be created inside `work`, not captured from a
37    /// previous execution or returned from it. Runs may not be nested. Panics
38    /// propagate to the caller. Simulation rejects a workload that returns with
39    /// pending timers, or whose unfinished tasks later attempt a timed operation;
40    /// finish or join spawned work before `work` returns.
41    ///
42    /// Simulation has no step limit and Shuttle retains every scheduling step. Run workloads
43    /// in a worker process with external time and memory limits. Virtual time advances only
44    /// when no workload task is runnable; yielding while polling for a timer can run forever.
45    /// After a failed execution, Shuttle may abandon suspended task stacks without running
46    /// destructors, retaining resources owned by those stacks. Restart the worker instead of
47    /// repeatedly catching execution failures and continuing in the same process.
48    pub fn run<F, T>(&self, work: F) -> T
49    where
50        F: FnOnce() -> T + Send + 'static,
51        T: Send + 'static,
52    {
53        #[cfg(not(all(feature = "fuzz", dst)))]
54        {
55            work()
56        }
57        #[cfg(all(feature = "fuzz", dst))]
58        {
59            deterministic::run(work)
60        }
61    }
62
63    /// Runs an in-process async test. Construct the fixture in `work` so its resources live
64    /// within one execution. The future itself may be non-`Send`.
65    ///
66    /// Native tests use a current-thread Tokio runtime. In simulation, Shuttle drives the
67    /// request and the Tokio local set used by Reth's service spawner. Blocking workers run
68    /// as separate logical tasks. The local set cancels unfinished services when the test
69    /// returns. Tokio time stays paused and the test must complete using in-process wakeups.
70    #[cfg(feature = "async-test")]
71    pub fn run_async<F, T>(&self, work: impl FnOnce() -> F + Send + 'static) -> T
72    where
73        F: Future<Output = T>,
74        T: Send + 'static,
75    {
76        self.run(move || {
77            let mut builder = tokio::runtime::Builder::new_current_thread();
78            #[cfg(all(feature = "fuzz", dst))]
79            builder.start_paused(true);
80            let runtime = builder.enable_all().build().unwrap();
81            #[cfg(not(all(feature = "fuzz", dst)))]
82            {
83                runtime.block_on(async move { work().await })
84            }
85            #[cfg(all(feature = "fuzz", dst))]
86            {
87                let _entered = runtime.enter();
88                let services = Rc::new(LocalSet::new());
89                SERVICES.sync_scope((runtime.handle().id(), services.clone()), || {
90                    shuttle::future::block_on(services.run_until(work()))
91                })
92            }
93        })
94    }
95
96    /// Returns the service executor for `handle` inside its active async simulation.
97    /// Other Tokio runtimes and callers outside that simulation use their own executors.
98    #[cfg(all(feature = "async-test", feature = "fuzz", dst))]
99    pub fn local_services(handle: &Handle) -> Option<Rc<LocalSet>> {
100        SERVICES
101            .try_with(|(id, services)| (*id == handle.id()).then(|| Rc::clone(services)))
102            .ok()
103            .flatten()
104    }
105}
106
107#[cfg(all(test, feature = "async-test", feature = "fuzz", dst))]
108mod tests {
109    use super::*;
110    use std::future::pending;
111
112    #[test]
113    fn local_services_are_scoped_to_the_test_runtime() {
114        let other = tokio::runtime::Builder::new_current_thread().build().unwrap();
115        let other_handle = other.handle().clone();
116        let (handle, service) = Runtime::new().run_async(move || async move {
117            assert!(Runtime::local_services(&other_handle).is_none());
118            let handle = Handle::current();
119            let service = Runtime::local_services(&handle).unwrap().spawn_local(pending::<()>());
120            (handle, service)
121        });
122
123        assert!(Runtime::local_services(&handle).is_none());
124        assert!(other.block_on(service).unwrap_err().is_cancelled());
125    }
126}