Skip to main content

reth_tasks/
runtime.rs

1//! Centralized management of async and parallel execution.
2//!
3//! This module provides [`Runtime`], a cheaply cloneable handle that manages:
4//! - Tokio runtime (either owned or attached)
5//! - Task spawning with shutdown awareness and panic monitoring
6//! - Dedicated rayon thread pools for different workloads (with `rayon` feature)
7//! - [`BlockingTaskGuard`] for rate-limiting expensive operations (with `rayon` feature)
8
9use crate::{
10    metrics::{IncCounterOnDrop, TaskExecutorMetrics},
11    shutdown::{GracefulShutdown, GracefulShutdownGuard, Shutdown},
12    wait_for_shutdown_progress,
13    worker_map::WorkerMap,
14    PanickedTaskError, TaskEvent, TaskManager,
15};
16use futures_util::{
17    future::{select, BoxFuture},
18    Future, FutureExt, TryFutureExt,
19};
20use reth_concurrency::sync::{
21    atomic::{AtomicUsize, Ordering},
22    parking_lot, thread,
23    time::{Duration, Instant},
24    Mutex,
25};
26use std::{num::NonZeroUsize, pin::pin, sync::Arc};
27use tokio::{runtime::Handle, sync::mpsc::UnboundedSender, task::JoinHandle};
28use tracing::{debug, error, Span};
29use tracing_futures::Instrument;
30
31#[cfg(feature = "rayon")]
32use crate::pool::{build_pool_with_panic_handler, BlockingTaskGuard, BlockingTaskPool, WorkerPool};
33#[cfg(feature = "rayon")]
34use reth_concurrency::sync::{
35    rayon::{ThreadPool, ThreadPoolBuildError, ThreadPoolBuilder},
36    thread::available_parallelism,
37};
38
39#[cfg(all(feature = "fuzz", dst))]
40use reth_concurrency::sync::runtime;
41
42use tokio::runtime::Runtime as TokioRuntime;
43
44/// Default thread keep-alive duration for the tokio runtime.
45pub const DEFAULT_THREAD_KEEP_ALIVE: Duration = Duration::from_secs(15);
46
47/// Default reserved CPU cores for OS and other processes.
48pub const DEFAULT_RESERVED_CPU_CORES: usize = 2;
49
50/// Default number of threads for the storage I/O pool.
51pub const DEFAULT_STORAGE_POOL_THREADS: usize = 16;
52
53/// Default number of threads for the state trie overlay worker pool.
54#[cfg(feature = "rayon")]
55pub const DEFAULT_STATE_TRIE_OVERLAY_WORKER_THREADS: usize = 4;
56
57/// Default maximum number of concurrent blocking tasks (for RPC tracing guard).
58pub const DEFAULT_MAX_BLOCKING_TASKS: usize = 512;
59
60/// Configuration for the tokio runtime.
61#[derive(Debug, Clone)]
62pub enum TokioConfig {
63    /// Build and own a new tokio runtime.
64    Owned {
65        /// Number of worker threads. If `None`, uses tokio's default (number of CPU cores).
66        worker_threads: Option<usize>,
67        /// How long to keep worker threads alive when idle.
68        thread_keep_alive: Duration,
69        /// Thread name prefix.
70        thread_name: &'static str,
71    },
72    /// Attach to an existing tokio runtime handle.
73    ExistingHandle(Handle),
74}
75
76impl Default for TokioConfig {
77    fn default() -> Self {
78        Self::Owned {
79            worker_threads: None,
80            thread_keep_alive: DEFAULT_THREAD_KEEP_ALIVE,
81            thread_name: "tokio-rt",
82        }
83    }
84}
85
86impl TokioConfig {
87    /// Create a config that attaches to an existing runtime handle.
88    pub const fn existing_handle(handle: Handle) -> Self {
89        Self::ExistingHandle(handle)
90    }
91
92    /// Create a config for an owned runtime with the specified number of worker threads.
93    pub const fn with_worker_threads(worker_threads: usize) -> Self {
94        Self::Owned {
95            worker_threads: Some(worker_threads),
96            thread_keep_alive: DEFAULT_THREAD_KEEP_ALIVE,
97            thread_name: "tokio-rt",
98        }
99    }
100}
101
102/// Configuration for the rayon thread pools.
103#[derive(Debug, Clone)]
104#[cfg(feature = "rayon")]
105pub struct RayonConfig {
106    /// Number of threads for the general CPU pool.
107    /// If `None`, derived from available parallelism minus reserved cores.
108    pub cpu_threads: Option<usize>,
109    /// Number of CPU cores to reserve for OS and other processes.
110    pub reserved_cpu_cores: usize,
111    /// Number of threads for the RPC blocking pool (trace calls, `eth_getProof`, etc.).
112    /// If `None`, uses the same as `cpu_threads`.
113    pub rpc_threads: Option<usize>,
114    /// Number of threads for the storage I/O pool (static file, `RocksDB` writes in
115    /// `save_blocks`). If `None`, uses [`DEFAULT_STORAGE_POOL_THREADS`].
116    pub storage_threads: Option<usize>,
117    /// Maximum number of concurrent blocking tasks for the RPC guard semaphore.
118    pub max_blocking_tasks: usize,
119    /// Number of threads for the proof storage worker pool (trie storage proof workers).
120    /// If `None` or zero, uses four times the resolved CPU pool thread count.
121    pub proof_storage_worker_threads: Option<usize>,
122    /// Number of threads for the proof account worker pool (trie account proof workers).
123    /// If `None` or zero, uses four times the resolved CPU pool thread count.
124    pub proof_account_worker_threads: Option<usize>,
125    /// Number of threads for the prewarming pool (execution prewarming workers).
126    /// If `None`, derived from available parallelism.
127    pub prewarming_threads: Option<usize>,
128    /// Number of threads for the BAL streaming pool (BAL hashed state streaming).
129    /// If `None`, derived from available parallelism.
130    pub bal_streaming_threads: Option<usize>,
131    /// Number of threads for the state trie overlay worker pool.
132    /// If `None`, uses [`DEFAULT_STATE_TRIE_OVERLAY_WORKER_THREADS`].
133    pub state_trie_overlay_worker_threads: Option<usize>,
134}
135
136#[cfg(feature = "rayon")]
137impl Default for RayonConfig {
138    fn default() -> Self {
139        Self {
140            cpu_threads: None,
141            reserved_cpu_cores: DEFAULT_RESERVED_CPU_CORES,
142            rpc_threads: None,
143            storage_threads: None,
144            max_blocking_tasks: DEFAULT_MAX_BLOCKING_TASKS,
145            proof_storage_worker_threads: None,
146            proof_account_worker_threads: None,
147            prewarming_threads: None,
148            bal_streaming_threads: None,
149            state_trie_overlay_worker_threads: None,
150        }
151    }
152}
153
154#[cfg(feature = "rayon")]
155impl RayonConfig {
156    /// Set the number of reserved CPU cores.
157    pub const fn with_reserved_cpu_cores(mut self, reserved_cpu_cores: usize) -> Self {
158        self.reserved_cpu_cores = reserved_cpu_cores;
159        self
160    }
161
162    /// Set the maximum number of concurrent blocking tasks.
163    pub const fn with_max_blocking_tasks(mut self, max_blocking_tasks: usize) -> Self {
164        self.max_blocking_tasks = max_blocking_tasks;
165        self
166    }
167
168    /// Set the number of threads for the RPC blocking pool.
169    pub const fn with_rpc_threads(mut self, rpc_threads: usize) -> Self {
170        self.rpc_threads = Some(rpc_threads);
171        self
172    }
173
174    /// Set the number of threads for the storage I/O pool.
175    pub const fn with_storage_threads(mut self, storage_threads: usize) -> Self {
176        self.storage_threads = Some(storage_threads);
177        self
178    }
179
180    /// Set the number of threads for the proof storage worker pool.
181    pub const fn with_proof_storage_worker_threads(
182        mut self,
183        proof_storage_worker_threads: usize,
184    ) -> Self {
185        self.proof_storage_worker_threads = Some(proof_storage_worker_threads);
186        self
187    }
188
189    /// Set the number of threads for the proof account worker pool.
190    pub const fn with_proof_account_worker_threads(
191        mut self,
192        proof_account_worker_threads: usize,
193    ) -> Self {
194        self.proof_account_worker_threads = Some(proof_account_worker_threads);
195        self
196    }
197
198    /// Set the number of threads for the prewarming pool.
199    pub const fn with_prewarming_threads(mut self, prewarming_threads: usize) -> Self {
200        self.prewarming_threads = Some(prewarming_threads);
201        self
202    }
203
204    /// Set the number of threads for the BAL streaming pool.
205    pub const fn with_bal_streaming_threads(mut self, bal_streaming_threads: usize) -> Self {
206        self.bal_streaming_threads = Some(bal_streaming_threads);
207        self
208    }
209
210    /// Set the number of threads for the state trie overlay worker pool.
211    pub const fn with_state_trie_overlay_worker_threads(
212        mut self,
213        state_trie_overlay_worker_threads: usize,
214    ) -> Self {
215        self.state_trie_overlay_worker_threads = Some(state_trie_overlay_worker_threads);
216        self
217    }
218
219    /// Compute the default number of threads based on available parallelism.
220    fn default_thread_count(&self) -> usize {
221        // TODO: reserved_cpu_cores is currently ignored because subtracting from thread pool
222        // sizes doesn't actually reserve CPU cores for other processes.
223        let _ = self.reserved_cpu_cores;
224        self.cpu_threads.unwrap_or_else(|| available_parallelism().map_or(1, NonZeroUsize::get))
225    }
226
227    /// Returns the explicitly configured proof storage worker thread count, treating zero as
228    /// unset.
229    fn proof_storage_worker_threads_override(&self) -> Option<usize> {
230        self.proof_storage_worker_threads.filter(|&threads| threads > 0)
231    }
232
233    /// Returns the explicitly configured proof account worker thread count, treating zero as
234    /// unset.
235    fn proof_account_worker_threads_override(&self) -> Option<usize> {
236        self.proof_account_worker_threads.filter(|&threads| threads > 0)
237    }
238}
239
240/// Configuration for building a [`Runtime`].
241#[derive(Debug, Clone, Default)]
242pub struct RuntimeConfig {
243    /// Tokio runtime configuration.
244    pub tokio: TokioConfig,
245    /// Rayon thread pool configuration.
246    #[cfg(feature = "rayon")]
247    pub rayon: RayonConfig,
248}
249
250impl RuntimeConfig {
251    /// Set the tokio configuration.
252    pub fn with_tokio(mut self, tokio: TokioConfig) -> Self {
253        self.tokio = tokio;
254        self
255    }
256
257    /// Set the rayon configuration.
258    #[cfg(feature = "rayon")]
259    pub const fn with_rayon(mut self, rayon: RayonConfig) -> Self {
260        self.rayon = rayon;
261        self
262    }
263
264    /// Override the available CPU count used to size thread pools.
265    ///
266    /// Explicit thread counts and externally supplied Tokio runtimes are preserved.
267    /// Fixed-size pools, such as the storage I/O pool, are not affected.
268    pub fn with_cpu_cores(mut self, cpu_cores: NonZeroUsize) -> Self {
269        let cpu_cores = cpu_cores.get();
270        if let TokioConfig::Owned { worker_threads, .. } = &mut self.tokio {
271            worker_threads.get_or_insert(cpu_cores);
272        }
273        #[cfg(feature = "rayon")]
274        self.rayon.cpu_threads.get_or_insert(cpu_cores);
275        self
276    }
277}
278
279/// Error returned when [`RuntimeBuilder::build`] fails.
280#[derive(Debug, thiserror::Error)]
281pub enum RuntimeBuildError {
282    /// Failed to build the tokio runtime.
283    #[error("Failed to build tokio runtime: {0}")]
284    TokioBuild(#[from] std::io::Error),
285    /// Failed to build a rayon thread pool.
286    #[cfg(feature = "rayon")]
287    #[error("Failed to build rayon thread pool: {0}")]
288    RayonBuild(#[from] ThreadPoolBuildError),
289}
290
291// ── RuntimeInner ──────────────────────────────────────────────────────
292
293struct RuntimeInner {
294    /// Owned tokio runtime, taken during shutdown even while other handles remain alive.
295    tokio_runtime: Mutex<Option<TokioRuntime>>,
296    /// Handle to the tokio runtime.
297    handle: Handle,
298    /// Receiver of the shutdown signal.
299    on_shutdown: Shutdown,
300    /// Sender half for sending task events to the [`TaskManager`].
301    task_events_tx: UnboundedSender<TaskEvent>,
302    /// Task executor metrics.
303    metrics: TaskExecutorMetrics,
304    /// How many [`GracefulShutdown`] tasks are currently active.
305    graceful_tasks: Arc<AtomicUsize>,
306    /// General-purpose rayon CPU pool.
307    #[cfg(feature = "rayon")]
308    cpu_pool: ThreadPool,
309    /// RPC blocking pool.
310    #[cfg(feature = "rayon")]
311    rpc_pool: BlockingTaskPool,
312    /// Storage I/O pool.
313    #[cfg(feature = "rayon")]
314    storage_pool: ThreadPool,
315    /// Rate limiter for expensive RPC operations.
316    #[cfg(feature = "rayon")]
317    blocking_guard: BlockingTaskGuard,
318    /// Proof storage worker pool (trie storage proof computation).
319    #[cfg(feature = "rayon")]
320    proof_storage_worker_pool: WorkerPool,
321    /// Proof account worker pool (trie account proof computation).
322    #[cfg(feature = "rayon")]
323    proof_account_worker_pool: WorkerPool,
324    /// Proof storage worker thread count the operator configured explicitly, if any.
325    #[cfg(feature = "rayon")]
326    proof_storage_worker_threads_override: Option<usize>,
327    /// Proof account worker thread count the operator configured explicitly, if any.
328    #[cfg(feature = "rayon")]
329    proof_account_worker_threads_override: Option<usize>,
330    /// Prewarming pool (execution prewarming workers).
331    #[cfg(feature = "rayon")]
332    prewarming_pool: Arc<WorkerPool>,
333    /// BAL streaming pool (BAL hashed state streaming).
334    #[cfg(feature = "rayon")]
335    bal_streaming_pool: Arc<WorkerPool>,
336    /// State trie overlay worker pool.
337    #[cfg(feature = "rayon")]
338    state_trie_overlay_worker_pool: Arc<WorkerPool>,
339    /// Named single-thread worker map. Each unique name gets a dedicated OS thread
340    /// that is reused across all tasks submitted under that name.
341    worker_map: WorkerMap,
342    /// Handle to the spawned [`TaskManager`] background task.
343    /// The task monitors critical tasks for panics and fires the shutdown signal.
344    /// Can be taken via [`Runtime::take_task_manager_handle`] to poll for panic errors.
345    task_manager_handle: Mutex<Option<JoinHandle<Result<(), PanickedTaskError>>>>,
346}
347
348impl Drop for RuntimeInner {
349    fn drop(&mut self) {
350        // The last handle can belong to an async task, including one running on this runtime.
351        // Without explicit shutdown, let blocking tasks finish in the background in that case.
352        if Handle::try_current().is_ok() &&
353            let Some(runtime) = self.tokio_runtime.get_mut().unwrap().take()
354        {
355            runtime.shutdown_background();
356        }
357    }
358}
359
360// ── Runtime ───────────────────────────────────────────────────────────
361
362/// A cheaply cloneable handle to the runtime resources.
363///
364/// Wraps an `Arc<RuntimeInner>` and provides access to:
365/// - The tokio [`Handle`]
366/// - Task spawning with shutdown awareness and panic monitoring
367/// - Rayon thread pools (with `rayon` feature)
368#[derive(Clone)]
369pub struct Runtime(Arc<RuntimeInner>);
370
371impl std::fmt::Debug for Runtime {
372    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373        f.debug_struct("Runtime").field("handle", &self.0.handle).finish()
374    }
375}
376
377// ── Pool accessors ────────────────────────────────────────────────────
378
379impl Runtime {
380    /// Takes the [`TaskManager`] handle out of this runtime, if one is stored.
381    ///
382    /// The handle resolves with `Err(PanickedTaskError)` if a critical task panicked,
383    /// or `Ok(())` if shutdown was requested. If not taken, the background task still
384    /// runs and logs panics at `debug!` level.
385    pub fn take_task_manager_handle(&self) -> Option<JoinHandle<Result<(), PanickedTaskError>>> {
386        self.0.task_manager_handle.lock().unwrap().take()
387    }
388
389    /// Returns the tokio runtime [`Handle`].
390    pub fn handle(&self) -> &Handle {
391        &self.0.handle
392    }
393
394    /// Get the general-purpose rayon CPU thread pool.
395    #[cfg(feature = "rayon")]
396    pub fn cpu_pool(&self) -> &ThreadPool {
397        &self.0.cpu_pool
398    }
399
400    /// Get the RPC blocking task pool.
401    #[cfg(feature = "rayon")]
402    pub fn rpc_pool(&self) -> &BlockingTaskPool {
403        &self.0.rpc_pool
404    }
405
406    /// Get the storage I/O pool.
407    #[cfg(feature = "rayon")]
408    pub fn storage_pool(&self) -> &ThreadPool {
409        &self.0.storage_pool
410    }
411
412    /// Get a clone of the [`BlockingTaskGuard`].
413    #[cfg(feature = "rayon")]
414    pub fn blocking_guard(&self) -> BlockingTaskGuard {
415        self.0.blocking_guard.clone()
416    }
417
418    /// Get the proof storage worker pool.
419    #[cfg(feature = "rayon")]
420    pub fn proof_storage_worker_pool(&self) -> &WorkerPool {
421        &self.0.proof_storage_worker_pool
422    }
423
424    /// Get the proof account worker pool.
425    #[cfg(feature = "rayon")]
426    pub fn proof_account_worker_pool(&self) -> &WorkerPool {
427        &self.0.proof_account_worker_pool
428    }
429
430    /// Returns the proof storage worker thread count the operator configured explicitly, if any.
431    /// A configured count of zero is treated as unset.
432    ///
433    /// Callers that size the worker count per block must use this verbatim instead of scaling it.
434    #[cfg(feature = "rayon")]
435    pub fn proof_storage_worker_threads_override(&self) -> Option<usize> {
436        self.0.proof_storage_worker_threads_override
437    }
438
439    /// Returns the proof account worker thread count the operator configured explicitly, if any.
440    /// A configured count of zero is treated as unset.
441    ///
442    /// Callers that size the worker count per block must use this verbatim instead of scaling it.
443    #[cfg(feature = "rayon")]
444    pub fn proof_account_worker_threads_override(&self) -> Option<usize> {
445        self.0.proof_account_worker_threads_override
446    }
447
448    /// Get the prewarming pool.
449    #[cfg(feature = "rayon")]
450    pub fn prewarming_pool(&self) -> &Arc<WorkerPool> {
451        &self.0.prewarming_pool
452    }
453
454    /// Get the BAL streaming pool.
455    #[cfg(feature = "rayon")]
456    pub fn bal_streaming_pool(&self) -> &Arc<WorkerPool> {
457        &self.0.bal_streaming_pool
458    }
459
460    /// Get the state trie overlay worker pool.
461    #[cfg(feature = "rayon")]
462    pub fn state_trie_overlay_worker_pool(&self) -> Arc<WorkerPool> {
463        Arc::clone(&self.0.state_trie_overlay_worker_pool)
464    }
465}
466
467// ── Test helpers ──────────────────────────────────────────────────────
468
469impl Runtime {
470    /// Creates a lightweight [`Runtime`] for tests with minimal thread pools.
471    ///
472    /// If called from within a tokio runtime (e.g. `#[tokio::test]`), attaches to the existing
473    /// handle to avoid shutdown panics when the test runtime is dropped.
474    pub fn test() -> Self {
475        let config = match Handle::try_current() {
476            Ok(handle) => Self::test_config().with_tokio(TokioConfig::existing_handle(handle)),
477            Err(_) => Self::test_config(),
478        };
479        RuntimeBuilder::new(config).build().expect("failed to build test Runtime")
480    }
481
482    const fn test_config() -> RuntimeConfig {
483        RuntimeConfig {
484            tokio: TokioConfig::Owned {
485                worker_threads: Some(2),
486                thread_keep_alive: DEFAULT_THREAD_KEEP_ALIVE,
487                thread_name: "tokio-test",
488            },
489            #[cfg(feature = "rayon")]
490            rayon: RayonConfig {
491                cpu_threads: Some(2),
492                reserved_cpu_cores: 0,
493                rpc_threads: Some(2),
494                storage_threads: Some(2),
495                max_blocking_tasks: 16,
496                proof_storage_worker_threads: Some(2),
497                proof_account_worker_threads: Some(2),
498                prewarming_threads: Some(2),
499                bal_streaming_threads: Some(2),
500                state_trie_overlay_worker_threads: Some(2),
501            },
502        }
503    }
504}
505
506// ── Spawn methods ─────────────────────────────────────────────────────
507
508/// Determines how a task is spawned.
509enum TaskKind {
510    /// Spawn the task to the default executor [`Handle::spawn`].
511    Default,
512    /// Spawn the task to the blocking executor [`Handle::spawn_blocking`].
513    Blocking,
514}
515
516impl Runtime {
517    /// Returns the receiver of the shutdown signal.
518    pub fn on_shutdown_signal(&self) -> &Shutdown {
519        &self.0.on_shutdown
520    }
521
522    /// Spawns a future on the tokio runtime depending on the [`TaskKind`].
523    fn spawn_on_rt<F>(&self, fut: F, task_kind: TaskKind) -> JoinHandle<()>
524    where
525        F: Future<Output = ()> + Send + 'static,
526    {
527        match task_kind {
528            TaskKind::Default => spawn_async(&self.0.handle, fut),
529            TaskKind::Blocking => {
530                let handle = self.0.handle.clone();
531                self.0.handle.spawn_blocking(move || handle.block_on(fut))
532            }
533        }
534    }
535
536    /// Spawns a regular task depending on the given [`TaskKind`].
537    fn spawn_task_as(&self, fut: BoxFuture<'static, ()>, task_kind: TaskKind) -> JoinHandle<()> {
538        self.spawn_on_rt(self.regular_task(fut, &task_kind), task_kind)
539    }
540
541    fn regular_task(
542        &self,
543        fut: BoxFuture<'static, ()>,
544        task_kind: &TaskKind,
545    ) -> impl Future<Output = ()> + use<> {
546        match task_kind {
547            TaskKind::Default => self.0.metrics.inc_regular_tasks(),
548            TaskKind::Blocking => self.0.metrics.inc_regular_blocking_tasks(),
549        }
550        let on_shutdown = self.0.on_shutdown.clone();
551
552        let finished_counter = match task_kind {
553            TaskKind::Default => self.0.metrics.finished_regular_tasks_total.clone(),
554            TaskKind::Blocking => self.0.metrics.finished_regular_blocking_tasks_total.clone(),
555        };
556
557        async move {
558            let _inc_counter_on_drop = IncCounterOnDrop::new(finished_counter);
559            let _ = select(on_shutdown, fut).await;
560        }
561        .in_current_span()
562    }
563
564    /// Spawns the task onto the runtime.
565    /// The given future resolves as soon as the [Shutdown] signal is received.
566    ///
567    /// See also [`Handle::spawn`].
568    pub fn spawn_task<F>(&self, fut: F) -> JoinHandle<()>
569    where
570        F: Future<Output = ()> + Send + 'static,
571    {
572        self.spawn_task_as(fut.boxed(), TaskKind::Default)
573    }
574
575    /// Spawns a blocking task onto the runtime.
576    /// The given future resolves as soon as the [Shutdown] signal is received.
577    ///
578    /// See also [`Handle::spawn_blocking`].
579    pub fn spawn_blocking_task<F>(&self, fut: F) -> JoinHandle<()>
580    where
581        F: Future<Output = ()> + Send + 'static,
582    {
583        self.spawn_task_as(fut.boxed(), TaskKind::Blocking)
584    }
585
586    /// Spawns a shutdown-aware blocking task whose result is delivered separately. An async
587    /// simulation polls it on an independent Shuttle task. Otherwise it uses the blocking pool.
588    pub fn spawn_blocking_task_detached(&self, fut: impl Future<Output = ()> + Send + 'static) {
589        #[cfg(all(feature = "fuzz", dst))]
590        if runtime::Runtime::local_services(self.handle()).is_some() {
591            // The blocking pool keeps a worker's panic in its join handle. A Shuttle task that
592            // unwinds fails the execution, so the panic is caught here instead.
593            let task = self.regular_task(fut.boxed(), &TaskKind::Blocking);
594            drop(shuttle::future::spawn(std::panic::AssertUnwindSafe(task).catch_unwind()));
595            return;
596        }
597        self.spawn_blocking_task(fut);
598    }
599
600    /// Spawns a blocking closure directly on the tokio runtime, bypassing shutdown
601    /// awareness. Useful for raw CPU-bound work.
602    pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
603    where
604        F: FnOnce() -> R + Send + 'static,
605        R: Send + 'static,
606    {
607        // Erases the closure type so tokio's blocking task machinery is instantiated once per `R`
608        // instead of once per closure.
609        self.0.handle.spawn_blocking(Box::new(func) as Box<dyn FnOnce() -> R + Send>)
610    }
611
612    /// Spawns a blocking closure onto the runtime.
613    ///
614    /// Unlike [`spawn_blocking_task`](Self::spawn_blocking_task), the closure runs directly on the
615    /// blocking thread instead of being driven as a future, and it also runs if the [Shutdown]
616    /// signal fired before it started. Like [`spawn_blocking_task`](Self::spawn_blocking_task), it
617    /// runs in the caller's span and is counted as a regular blocking task.
618    ///
619    /// See also [`Handle::spawn_blocking`].
620    pub fn spawn_blocking_task_fn<F>(&self, func: F) -> JoinHandle<()>
621    where
622        F: FnOnce() + Send + 'static,
623    {
624        self.spawn_blocking(self.instrument_blocking_task(func))
625    }
626
627    /// Submits a blocking closure whose caller receives its result separately. Dropping
628    /// the request or firing shutdown leaves the closure running. Simulation runs it on
629    /// an independent logical thread in the current execution.
630    pub fn spawn_blocking_task_fn_detached(&self, func: impl FnOnce() + Send + 'static) {
631        #[cfg(not(all(feature = "fuzz", dst)))]
632        self.spawn_blocking_task_fn(func);
633        #[cfg(all(feature = "fuzz", dst))]
634        thread::spawn(self.instrument_blocking_task(func));
635    }
636
637    fn instrument_blocking_task<F: FnOnce()>(&self, func: F) -> impl FnOnce() + use<F> {
638        self.0.metrics.inc_regular_blocking_tasks();
639        let finished_counter = self.0.metrics.finished_regular_blocking_tasks_total.clone();
640        let span = Span::current();
641        move || {
642            let _inc_counter_on_drop = IncCounterOnDrop::new(finished_counter);
643            let _enter = span.enter();
644            func()
645        }
646    }
647
648    /// Moves the given value to a dedicated background thread for deallocation.
649    ///
650    /// This is useful when dropping a value is expensive (e.g. large nested collections)
651    /// and should not block the current task. Uses a persistent named thread (`"drop"`)
652    /// to avoid thread creation overhead on hot paths.
653    pub fn spawn_drop<T: Send + 'static>(&self, value: T) {
654        self.spawn_blocking_named("drop", move || drop(value));
655    }
656
657    /// Spawns a blocking closure on a dedicated, named selected-backend thread.
658    ///
659    /// Unlike [`spawn_blocking`](Self::spawn_blocking) which uses tokio's blocking thread pool,
660    /// this reuses the same worker for all tasks submitted under the same `name`. The worker
661    /// is created lazily on first use and its name is set to `name`. It is an OS thread natively
662    /// and a logical thread under `fuzz` plus `--cfg dst`.
663    ///
664    /// This is useful for tasks that benefit from running on a stable thread, e.g. for
665    /// thread-local state reuse or to avoid thread creation overhead on hot paths.
666    ///
667    /// Returns a [`LazyHandle`](crate::LazyHandle) handle that resolves on first access and caches
668    /// the result.
669    pub fn spawn_blocking_named<F, R>(&self, name: &'static str, func: F) -> crate::LazyHandle<R>
670    where
671        F: FnOnce() -> R + Send + 'static,
672        R: Send + 'static,
673    {
674        crate::LazyHandle::new(self.0.worker_map.spawn_on(name, func))
675    }
676
677    /// Attempts to spawn a blocking closure on a dedicated, named selected-backend thread.
678    ///
679    /// Returns `None` if the named worker already has a task running or queued, allowing the caller
680    /// to fall back to another executor instead of serializing behind the named worker.
681    pub fn try_spawn_blocking_named<F, R>(
682        &self,
683        name: &'static str,
684        func: F,
685    ) -> Option<crate::LazyHandle<R>>
686    where
687        F: FnOnce() -> R + Send + 'static,
688        R: Send + 'static,
689    {
690        self.0.worker_map.try_spawn_on(name, func).map(crate::LazyHandle::new)
691    }
692
693    /// Spawns a blocking closure on a named selected-backend thread if idle, otherwise falls back
694    /// to tokio's unnamed blocking thread pool.
695    ///
696    /// Returns `true` if the closure was spawned on the named thread.
697    pub fn spawn_blocking_named_or_tokio<F>(&self, name: &'static str, func: F) -> bool
698    where
699        F: FnOnce() + Send + 'static,
700    {
701        let func = Arc::new(parking_lot::Mutex::new(Some(func)));
702        let named_func = func.clone();
703
704        if self
705            .try_spawn_blocking_named(name, move || {
706                #[cfg(not(all(feature = "fuzz", dst)))]
707                if let Some(func) = named_func.lock().take() {
708                    func();
709                }
710                #[cfg(all(feature = "fuzz", dst))]
711                {
712                    if shuttle::current::try_get_current_task().is_some() {
713                        reth_concurrency::sync::thread::yield_now();
714                    }
715                    let func = named_func.lock().take();
716                    if let Some(func) = func {
717                        func();
718                    }
719                }
720            })
721            .is_some()
722        {
723            return true
724        }
725
726        #[cfg(not(all(feature = "fuzz", dst)))]
727        if let Some(func) = func.lock().take() {
728            self.spawn_blocking(func);
729        }
730        #[cfg(all(feature = "fuzz", dst))]
731        {
732            if shuttle::current::try_get_current_task().is_some() {
733                reth_concurrency::sync::thread::yield_now();
734            }
735            let func = func.lock().take();
736            if let Some(func) = func {
737                self.spawn_blocking(func);
738            }
739        }
740        false
741    }
742
743    /// Spawns the task onto the runtime.
744    /// The given future resolves as soon as the [Shutdown] signal is received.
745    ///
746    /// See also [`Handle::spawn`].
747    pub fn spawn_with_signal<F>(&self, f: impl FnOnce(Shutdown) -> F) -> JoinHandle<()>
748    where
749        F: Future<Output = ()> + Send + 'static,
750    {
751        let on_shutdown = self.0.on_shutdown.clone();
752        let fut = f(on_shutdown);
753        spawn_async(&self.0.handle, fut.boxed().in_current_span())
754    }
755
756    /// Spawns a critical task depending on the given [`TaskKind`].
757    fn spawn_critical_as(
758        &self,
759        name: &'static str,
760        fut: BoxFuture<'static, ()>,
761        task_kind: TaskKind,
762    ) -> JoinHandle<()> {
763        self.0.metrics.inc_critical_tasks();
764        let panicked_tasks_tx = self.0.task_events_tx.clone();
765        let on_shutdown = self.0.on_shutdown.clone();
766
767        // wrap the task in catch unwind
768        let task = std::panic::AssertUnwindSafe(fut)
769            .catch_unwind()
770            .map_err(move |error| {
771                let task_error = PanickedTaskError::new(name, error);
772                error!("{task_error}");
773                let _ = panicked_tasks_tx.send(TaskEvent::Panic(task_error));
774            })
775            .in_current_span();
776
777        let finished_critical_tasks_total_metrics =
778            self.0.metrics.finished_critical_tasks_total.clone();
779        let task = async move {
780            let _inc_counter_on_drop = IncCounterOnDrop::new(finished_critical_tasks_total_metrics);
781            let task = pin!(task);
782            let _ = select(on_shutdown, task).await;
783        };
784
785        self.spawn_on_rt(task, task_kind)
786    }
787
788    /// This spawns a critical task onto the runtime.
789    /// The given future resolves as soon as the [Shutdown] signal is received.
790    ///
791    /// If this task panics, the [`TaskManager`] is notified.
792    pub fn spawn_critical_task<F>(&self, name: &'static str, fut: F) -> JoinHandle<()>
793    where
794        F: Future<Output = ()> + Send + 'static,
795    {
796        self.spawn_critical_as(name, fut.boxed(), TaskKind::Default)
797    }
798
799    /// This spawns a critical blocking task onto the runtime.
800    /// The given future resolves as soon as the [Shutdown] signal is received.
801    ///
802    /// If this task panics, the [`TaskManager`] is notified.
803    pub fn spawn_critical_blocking_task<F>(&self, name: &'static str, fut: F) -> JoinHandle<()>
804    where
805        F: Future<Output = ()> + Send + 'static,
806    {
807        self.spawn_critical_as(name, fut.boxed(), TaskKind::Blocking)
808    }
809
810    /// Spawns a critical task on a dedicated named selected-backend thread.
811    /// The given future resolves as soon as the [`Shutdown`] signal is received.
812    ///
813    /// If this task panics, the [`TaskManager`] is notified. The thread is native outside DST;
814    /// under `fuzz` plus `--cfg dst`, Tokio futures are not driven by the synchronous scheduler.
815    pub fn spawn_critical_os_thread<F>(
816        &self,
817        thread_name: &'static str,
818        task_name: &'static str,
819        fut: F,
820    ) -> thread::JoinHandle<()>
821    where
822        F: Future<Output = ()> + Send + 'static,
823    {
824        self.spawn_critical_os_thread_boxed(thread_name, task_name, fut.boxed())
825    }
826
827    fn spawn_critical_os_thread_boxed(
828        &self,
829        thread_name: &'static str,
830        task_name: &'static str,
831        fut: BoxFuture<'static, ()>,
832    ) -> thread::JoinHandle<()> {
833        self.0.metrics.inc_critical_tasks();
834        let handle = self.0.handle.clone();
835        let panicked_tasks_tx = self.0.task_events_tx.clone();
836        let on_shutdown = self.0.on_shutdown.clone();
837
838        let task = std::panic::AssertUnwindSafe(fut)
839            .catch_unwind()
840            .map_err(move |error| {
841                let task_error = PanickedTaskError::new(task_name, error);
842                error!("{task_error}");
843                let _ = panicked_tasks_tx.send(TaskEvent::Panic(task_error));
844            })
845            .in_current_span();
846
847        let finished_critical_tasks_total_metrics =
848            self.0.metrics.finished_critical_tasks_total.clone();
849        let task = async move {
850            let _inc_counter_on_drop = IncCounterOnDrop::new(finished_critical_tasks_total_metrics);
851            let task = pin!(task);
852            let _ = select(on_shutdown, task).await;
853        };
854
855        thread::Builder::new()
856            .name(thread_name.to_string())
857            .spawn(move || {
858                let _guard = handle.enter();
859                handle.block_on(task);
860            })
861            .unwrap_or_else(|e| panic!("failed to spawn critical OS thread {thread_name:?}: {e}"))
862    }
863
864    /// This spawns a critical task onto the runtime.
865    ///
866    /// If this task panics, the [`TaskManager`] is notified.
867    /// The [`TaskManager`] will wait until the given future has completed before shutting down.
868    ///
869    /// # Example
870    ///
871    /// ```no_run
872    /// # async fn t(executor: reth_tasks::TaskExecutor) {
873    ///
874    /// executor.spawn_critical_with_graceful_shutdown_signal("grace", async move |shutdown| {
875    ///     // await the shutdown signal
876    ///     let guard = shutdown.await;
877    ///     // do work before exiting the program
878    ///     tokio::time::sleep(std::time::Duration::from_secs(1)).await;
879    ///     // allow graceful shutdown
880    ///     drop(guard);
881    /// });
882    /// # }
883    /// ```
884    pub fn spawn_critical_with_graceful_shutdown_signal<F>(
885        &self,
886        name: &'static str,
887        f: impl FnOnce(GracefulShutdown) -> F,
888    ) -> JoinHandle<()>
889    where
890        F: Future<Output = ()> + Send + 'static,
891    {
892        let on_shutdown = GracefulShutdown::new(
893            self.0.on_shutdown.clone(),
894            GracefulShutdownGuard::new(Arc::clone(&self.0.graceful_tasks)),
895        );
896        self.spawn_critical_graceful_boxed(name, f(on_shutdown).boxed())
897    }
898
899    fn spawn_critical_graceful_boxed(
900        &self,
901        name: &'static str,
902        fut: BoxFuture<'static, ()>,
903    ) -> JoinHandle<()> {
904        let panicked_tasks_tx = self.0.task_events_tx.clone();
905
906        // wrap the task in catch unwind
907        let task = std::panic::AssertUnwindSafe(fut)
908            .catch_unwind()
909            .map_err(move |error| {
910                let task_error = PanickedTaskError::new(name, error);
911                error!("{task_error}");
912                let _ = panicked_tasks_tx.send(TaskEvent::Panic(task_error));
913            })
914            .map(drop)
915            .in_current_span();
916
917        spawn_async(&self.0.handle, task)
918    }
919
920    /// This spawns a regular task onto the runtime.
921    ///
922    /// The [`TaskManager`] will wait until the given future has completed before shutting down.
923    ///
924    /// # Example
925    ///
926    /// ```no_run
927    /// # async fn t(executor: reth_tasks::TaskExecutor) {
928    ///
929    /// executor.spawn_with_graceful_shutdown_signal(async move |shutdown| {
930    ///     // await the shutdown signal
931    ///     let guard = shutdown.await;
932    ///     // do work before exiting the program
933    ///     tokio::time::sleep(std::time::Duration::from_secs(1)).await;
934    ///     // allow graceful shutdown
935    ///     drop(guard);
936    /// });
937    /// # }
938    /// ```
939    pub fn spawn_with_graceful_shutdown_signal<F>(
940        &self,
941        f: impl FnOnce(GracefulShutdown) -> F,
942    ) -> JoinHandle<()>
943    where
944        F: Future<Output = ()> + Send + 'static,
945    {
946        let on_shutdown = GracefulShutdown::new(
947            self.0.on_shutdown.clone(),
948            GracefulShutdownGuard::new(Arc::clone(&self.0.graceful_tasks)),
949        );
950        spawn_async(&self.0.handle, f(on_shutdown).boxed())
951    }
952
953    /// Sends a request to the `TaskManager` to initiate a graceful shutdown.
954    ///
955    /// Caution: This will terminate the entire program.
956    pub fn initiate_graceful_shutdown(
957        &self,
958    ) -> Result<GracefulShutdown, tokio::sync::mpsc::error::SendError<()>> {
959        self.0
960            .task_events_tx
961            .send(TaskEvent::GracefulShutdown)
962            .map_err(|_send_error_with_task_event| tokio::sync::mpsc::error::SendError(()))?;
963
964        Ok(GracefulShutdown::new(
965            self.0.on_shutdown.clone(),
966            GracefulShutdownGuard::new(Arc::clone(&self.0.graceful_tasks)),
967        ))
968    }
969
970    /// Fires the shutdown signal and waits until all graceful tasks complete.
971    pub fn graceful_shutdown(&self) {
972        let _ = self.do_graceful_shutdown(None);
973    }
974
975    /// Fires the shutdown signal and waits until all graceful tasks complete or the timeout
976    /// elapses.
977    ///
978    /// Returns `true` if all tasks completed before the timeout.
979    pub fn graceful_shutdown_with_timeout(&self, timeout: Duration) -> bool {
980        self.do_graceful_shutdown(Some(timeout))
981    }
982
983    /// Shuts down the owned tokio runtime for all clones, waiting at most `timeout` for blocking
984    /// tasks. Externally supplied runtimes are left running.
985    ///
986    /// Panics if called from an async context while an owned runtime remains.
987    pub fn shutdown_timeout(self, timeout: Duration) {
988        let runtime = self.0.tokio_runtime.lock().unwrap().take();
989        if let Some(runtime) = runtime {
990            runtime.shutdown_timeout(timeout);
991        }
992    }
993
994    fn do_graceful_shutdown(&self, timeout: Option<Duration>) -> bool {
995        let _ = self.0.task_events_tx.send(TaskEvent::GracefulShutdown);
996        let deadline = timeout.map(|t| Instant::now() + t);
997        while self.0.graceful_tasks.load(Ordering::SeqCst) > 0 {
998            if deadline.is_some_and(|d| Instant::now() > d) {
999                debug!("graceful shutdown timed out");
1000                return false;
1001            }
1002            wait_for_shutdown_progress();
1003        }
1004        debug!("gracefully shut down");
1005        true
1006    }
1007}
1008
1009// ── RuntimeBuilder ────────────────────────────────────────────────────
1010
1011/// Builder for constructing a [`Runtime`].
1012#[derive(Debug, Clone)]
1013pub struct RuntimeBuilder {
1014    config: RuntimeConfig,
1015}
1016
1017impl RuntimeBuilder {
1018    /// Create a new builder with the given configuration.
1019    pub const fn new(config: RuntimeConfig) -> Self {
1020        Self { config }
1021    }
1022
1023    /// Build the [`Runtime`].
1024    ///
1025    /// The [`TaskManager`] is automatically spawned as a background task that monitors
1026    /// critical tasks for panics. Use [`Runtime::take_task_manager_handle`] to extract
1027    /// the join handle if you need to poll for panic errors.
1028    #[tracing::instrument(name = "RuntimeBuilder::build", level = "debug", skip_all)]
1029    pub fn build(self) -> Result<Runtime, RuntimeBuildError> {
1030        debug!(?self.config, "Building runtime");
1031        let config = self.config;
1032
1033        let (owned_runtime, handle) = match &config.tokio {
1034            TokioConfig::Owned { worker_threads, thread_keep_alive, thread_name } => {
1035                let mut builder = tokio::runtime::Builder::new_multi_thread();
1036                builder
1037                    .enable_all()
1038                    .thread_keep_alive(*thread_keep_alive)
1039                    .thread_name(*thread_name);
1040
1041                if let Some(threads) = worker_threads {
1042                    builder.worker_threads(*threads);
1043                }
1044
1045                let runtime = builder.build()?;
1046                let h = runtime.handle().clone();
1047                (Some(runtime), h)
1048            }
1049            TokioConfig::ExistingHandle(h) => (None, h.clone()),
1050        };
1051
1052        let (task_manager, on_shutdown, task_events_tx, graceful_tasks) =
1053            TaskManager::new_parts(handle.clone());
1054
1055        #[cfg(feature = "rayon")]
1056        let (
1057            cpu_pool,
1058            rpc_pool,
1059            storage_pool,
1060            blocking_guard,
1061            proof_storage_worker_pool,
1062            proof_account_worker_pool,
1063            prewarming_pool,
1064            bal_streaming_pool,
1065            state_trie_overlay_worker_pool,
1066        ) = {
1067            let default_threads = config.rayon.default_thread_count();
1068            let rpc_threads = config.rayon.rpc_threads.unwrap_or(default_threads);
1069
1070            let cpu_pool = build_pool_with_panic_handler(
1071                ThreadPoolBuilder::new()
1072                    .num_threads(default_threads)
1073                    .thread_name(|i| format!("cpu-{i:02}")),
1074            )?;
1075
1076            let rpc_raw = build_pool_with_panic_handler(
1077                ThreadPoolBuilder::new()
1078                    .num_threads(rpc_threads)
1079                    .thread_name(|i| format!("rpc-{i:02}")),
1080            )?;
1081            let rpc_pool = BlockingTaskPool::new(rpc_raw);
1082
1083            let storage_threads =
1084                config.rayon.storage_threads.unwrap_or(DEFAULT_STORAGE_POOL_THREADS);
1085            let storage_pool = build_pool_with_panic_handler(
1086                ThreadPoolBuilder::new()
1087                    .num_threads(storage_threads)
1088                    .thread_name(|i| format!("storage-{i:02}")),
1089            )?;
1090
1091            let blocking_guard = BlockingTaskGuard::new(config.rayon.max_blocking_tasks);
1092
1093            // `cpu_threads` may be zero, which rayon resolves to the automatic count when the
1094            // cpu pool is built; size the proof pools from that resolved count so a zero never
1095            // reaches the per-block worker budget.
1096            let default_proof_worker_threads = cpu_pool.current_num_threads() * 4;
1097
1098            let proof_storage_worker_threads = config
1099                .rayon
1100                .proof_storage_worker_threads_override()
1101                .unwrap_or(default_proof_worker_threads);
1102            let proof_storage_worker_pool =
1103                WorkerPool::new(proof_storage_worker_threads, "proof-strg");
1104
1105            let proof_account_worker_threads = config
1106                .rayon
1107                .proof_account_worker_threads_override()
1108                .unwrap_or(default_proof_worker_threads);
1109            let proof_account_worker_pool =
1110                WorkerPool::new(proof_account_worker_threads, "proof-acct");
1111
1112            let prewarming_threads = config.rayon.prewarming_threads.unwrap_or(default_threads);
1113            let prewarming_pool = Arc::new(WorkerPool::new(prewarming_threads, "prewarm"));
1114
1115            let bal_streaming_threads =
1116                config.rayon.bal_streaming_threads.unwrap_or(default_threads);
1117            let bal_streaming_pool = Arc::new(WorkerPool::new(bal_streaming_threads, "bal-stream"));
1118
1119            let state_trie_overlay_worker_threads = config
1120                .rayon
1121                .state_trie_overlay_worker_threads
1122                .unwrap_or(DEFAULT_STATE_TRIE_OVERLAY_WORKER_THREADS);
1123            let state_trie_overlay_worker_pool =
1124                Arc::new(WorkerPool::new(state_trie_overlay_worker_threads, "state-ovly"));
1125
1126            debug!(
1127                default_threads,
1128                rpc_threads,
1129                storage_threads,
1130                proof_storage_worker_threads,
1131                proof_account_worker_threads,
1132                prewarming_threads,
1133                bal_streaming_threads,
1134                state_trie_overlay_worker_threads,
1135                max_blocking_tasks = config.rayon.max_blocking_tasks,
1136                "Configured lazy rayon worker pools"
1137            );
1138
1139            (
1140                cpu_pool,
1141                rpc_pool,
1142                storage_pool,
1143                blocking_guard,
1144                proof_storage_worker_pool,
1145                proof_account_worker_pool,
1146                prewarming_pool,
1147                bal_streaming_pool,
1148                state_trie_overlay_worker_pool,
1149            )
1150        };
1151
1152        let task_manager_handle = spawn_async(&handle, async move {
1153            let result = task_manager.await;
1154            if let Err(ref err) = result {
1155                debug!("{err}");
1156            }
1157            result
1158        });
1159
1160        let tokio_runtime = Mutex::new(owned_runtime);
1161        let task_manager_handle = Mutex::new(Some(task_manager_handle));
1162        let inner = RuntimeInner {
1163            tokio_runtime,
1164            handle,
1165            on_shutdown,
1166            task_events_tx,
1167            metrics: Default::default(),
1168            graceful_tasks,
1169            #[cfg(feature = "rayon")]
1170            cpu_pool,
1171            #[cfg(feature = "rayon")]
1172            rpc_pool,
1173            #[cfg(feature = "rayon")]
1174            storage_pool,
1175            #[cfg(feature = "rayon")]
1176            blocking_guard,
1177            #[cfg(feature = "rayon")]
1178            proof_storage_worker_pool,
1179            #[cfg(feature = "rayon")]
1180            proof_account_worker_pool,
1181            #[cfg(feature = "rayon")]
1182            proof_storage_worker_threads_override: config
1183                .rayon
1184                .proof_storage_worker_threads_override(),
1185            #[cfg(feature = "rayon")]
1186            proof_account_worker_threads_override: config
1187                .rayon
1188                .proof_account_worker_threads_override(),
1189            #[cfg(feature = "rayon")]
1190            prewarming_pool,
1191            #[cfg(feature = "rayon")]
1192            bal_streaming_pool,
1193            #[cfg(feature = "rayon")]
1194            state_trie_overlay_worker_pool,
1195            worker_map: WorkerMap::new(),
1196            task_manager_handle,
1197        };
1198
1199        Ok(Runtime(Arc::new(inner)))
1200    }
1201}
1202
1203fn spawn_async<F>(handle: &Handle, future: F) -> JoinHandle<F::Output>
1204where
1205    F: Future + Send + 'static,
1206    F::Output: Send + 'static,
1207{
1208    #[cfg(all(feature = "fuzz", dst))]
1209    if let Some(services) = runtime::Runtime::local_services(handle) {
1210        return services.spawn_local(future);
1211    }
1212    handle.spawn(future)
1213}
1214
1215#[cfg(test)]
1216mod tests {
1217    use super::*;
1218    use reth_concurrency::sync::mpsc;
1219    use tokio::sync::oneshot;
1220
1221    #[cfg(not(all(feature = "fuzz", dst)))]
1222    use crate::test_utils;
1223    #[cfg(not(all(feature = "fuzz", dst)))]
1224    use std::future;
1225
1226    #[test]
1227    fn test_runtime_config_default() {
1228        let config = RuntimeConfig::default();
1229        assert!(matches!(config.tokio, TokioConfig::Owned { .. }));
1230    }
1231
1232    #[test]
1233    fn cpu_cores_override_sizes_tokio_workers() {
1234        let config = RuntimeConfig::default().with_cpu_cores(NonZeroUsize::new(8).unwrap());
1235        assert!(matches!(config.tokio, TokioConfig::Owned { worker_threads: Some(8), .. }));
1236    }
1237
1238    #[test]
1239    fn cpu_cores_override_preserves_explicit_tokio_workers() {
1240        let config = RuntimeConfig::default()
1241            .with_tokio(TokioConfig::with_worker_threads(2))
1242            .with_cpu_cores(NonZeroUsize::new(8).unwrap());
1243        assert!(matches!(config.tokio, TokioConfig::Owned { worker_threads: Some(2), .. }));
1244    }
1245
1246    #[test]
1247    fn cpu_cores_override_preserves_existing_tokio_runtime() {
1248        let runtime = TokioRuntime::new().unwrap();
1249        let config = RuntimeConfig::default()
1250            .with_tokio(TokioConfig::existing_handle(runtime.handle().clone()))
1251            .with_cpu_cores(NonZeroUsize::new(8).unwrap());
1252        assert!(matches!(config.tokio, TokioConfig::ExistingHandle(_)));
1253    }
1254
1255    #[cfg(feature = "rayon")]
1256    #[reth_concurrency::test]
1257    fn cpu_cores_override_sizes_cpu_pools() {
1258        let runtime = RuntimeBuilder::new(
1259            RuntimeConfig::default().with_cpu_cores(NonZeroUsize::new(5).unwrap()),
1260        )
1261        .build()
1262        .unwrap();
1263        assert_eq!(runtime.handle().metrics().num_workers(), 5);
1264        assert_eq!(runtime.cpu_pool().current_num_threads(), 5);
1265        assert_eq!(
1266            crate::test_utils::block_on(
1267                runtime.rpc_pool().spawn(reth_concurrency::sync::rayon::current_num_threads)
1268            )
1269            .unwrap(),
1270            5
1271        );
1272        assert_eq!(runtime.prewarming_pool().current_num_threads(), 5);
1273        assert_eq!(runtime.bal_streaming_pool().current_num_threads(), 5);
1274        assert_eq!(runtime.proof_storage_worker_pool().num_threads(), 20);
1275        assert_eq!(runtime.proof_account_worker_pool().num_threads(), 20);
1276        assert_eq!(runtime.storage_pool().current_num_threads(), DEFAULT_STORAGE_POOL_THREADS);
1277        assert_eq!(
1278            runtime.state_trie_overlay_worker_pool().num_threads(),
1279            DEFAULT_STATE_TRIE_OVERLAY_WORKER_THREADS
1280        );
1281    }
1282
1283    #[cfg(feature = "rayon")]
1284    #[test]
1285    fn cpu_cores_override_preserves_explicit_cpu_threads() {
1286        let config = RuntimeConfig::default()
1287            .with_rayon(RayonConfig { cpu_threads: Some(2), ..Default::default() })
1288            .with_cpu_cores(NonZeroUsize::new(8).unwrap());
1289        assert_eq!(config.rayon.default_thread_count(), 2);
1290    }
1291
1292    #[test]
1293    fn test_runtime_config_existing_handle() {
1294        let rt = TokioRuntime::new().unwrap();
1295        let config =
1296            Runtime::test_config().with_tokio(TokioConfig::existing_handle(rt.handle().clone()));
1297        assert!(matches!(config.tokio, TokioConfig::ExistingHandle(_)));
1298    }
1299
1300    #[cfg(feature = "rayon")]
1301    #[test]
1302    fn test_rayon_config_thread_count() {
1303        let config = RayonConfig::default();
1304        let count = config.default_thread_count();
1305        assert!(count >= 1);
1306    }
1307
1308    #[cfg(feature = "rayon")]
1309    #[reth_concurrency::test]
1310    fn zero_cpu_threads_still_size_the_proof_pools() {
1311        let rt = TokioRuntime::new().unwrap();
1312        let mut config =
1313            Runtime::test_config().with_tokio(TokioConfig::existing_handle(rt.handle().clone()));
1314        config.rayon.cpu_threads = Some(0);
1315        config.rayon.proof_storage_worker_threads = None;
1316        config.rayon.proof_account_worker_threads = None;
1317        let runtime = RuntimeBuilder::new(config).build().unwrap();
1318
1319        let resolved = runtime.cpu_pool().current_num_threads();
1320        assert!(resolved >= 1);
1321        assert_eq!(runtime.proof_storage_worker_pool().current_num_threads(), resolved * 4);
1322        assert_eq!(runtime.proof_account_worker_pool().current_num_threads(), resolved * 4);
1323    }
1324
1325    #[cfg(feature = "rayon")]
1326    #[reth_concurrency::test]
1327    fn proof_worker_threads_keep_pinned_counts() {
1328        let rt = TokioRuntime::new().unwrap();
1329        for configured in [1, 8, 16, 17, 64] {
1330            let mut config = Runtime::test_config()
1331                .with_tokio(TokioConfig::existing_handle(rt.handle().clone()));
1332            config.rayon.proof_storage_worker_threads = Some(configured);
1333            config.rayon.proof_account_worker_threads = Some(configured);
1334            let runtime = RuntimeBuilder::new(config).build().unwrap();
1335            assert_eq!(runtime.proof_storage_worker_pool().current_num_threads(), configured);
1336            assert_eq!(runtime.proof_account_worker_pool().current_num_threads(), configured);
1337            assert_eq!(runtime.proof_storage_worker_threads_override(), Some(configured));
1338            assert_eq!(runtime.proof_account_worker_threads_override(), Some(configured));
1339        }
1340    }
1341
1342    #[cfg(feature = "rayon")]
1343    #[reth_concurrency::test]
1344    fn zero_proof_worker_threads_use_the_default() {
1345        let rt = TokioRuntime::new().unwrap();
1346        let mut config =
1347            Runtime::test_config().with_tokio(TokioConfig::existing_handle(rt.handle().clone()));
1348        config.rayon.proof_storage_worker_threads = Some(0);
1349        config.rayon.proof_account_worker_threads = Some(0);
1350        let runtime = RuntimeBuilder::new(config).build().unwrap();
1351
1352        let default = runtime.cpu_pool().current_num_threads() * 4;
1353        assert_eq!(runtime.proof_storage_worker_pool().current_num_threads(), default);
1354        assert_eq!(runtime.proof_account_worker_pool().current_num_threads(), default);
1355        assert_eq!(runtime.proof_storage_worker_threads_override(), None);
1356        assert_eq!(runtime.proof_account_worker_threads_override(), None);
1357    }
1358
1359    #[reth_concurrency::test]
1360    fn test_runtime_builder() {
1361        let rt = TokioRuntime::new().unwrap();
1362        let config =
1363            Runtime::test_config().with_tokio(TokioConfig::existing_handle(rt.handle().clone()));
1364        let runtime = RuntimeBuilder::new(config).build().unwrap();
1365        let _ = runtime.handle();
1366    }
1367
1368    // Exercises native Tokio runtime ownership or OS-thread behavior.
1369    #[cfg(not(all(feature = "fuzz", dst)))]
1370    #[test]
1371    fn last_runtime_clone_can_drop_on_its_worker() {
1372        test_utils::run(|| {
1373            let runtime = RuntimeBuilder::new(Runtime::test_config()).build().unwrap();
1374            let task_runtime = runtime.clone();
1375            let (release, wait) = oneshot::channel();
1376            let task = runtime.handle().spawn(async move {
1377                wait.await.unwrap();
1378                drop(task_runtime);
1379            });
1380
1381            thread::spawn(move || drop(runtime)).join().unwrap();
1382            release.send(()).unwrap();
1383            Handle::current().block_on(task).unwrap();
1384        });
1385    }
1386
1387    // Exercises native Tokio runtime ownership or OS-thread behavior.
1388    #[cfg(not(all(feature = "fuzz", dst)))]
1389    #[test]
1390    fn shutdown_with_live_runtime_clones() {
1391        test_utils::run(|| {
1392            let runtime = RuntimeBuilder::new(Runtime::test_config()).build().unwrap();
1393            let retained = runtime.clone();
1394            let task_runtime = runtime.clone();
1395            let (started, ready) = oneshot::channel();
1396            let task = runtime.handle().spawn(async move {
1397                let _runtime = task_runtime;
1398                started.send(()).unwrap();
1399                future::pending::<()>().await;
1400            });
1401            Handle::current().block_on(ready).unwrap();
1402
1403            thread::spawn(move || runtime.shutdown_timeout(Duration::from_secs(5))).join().unwrap();
1404
1405            assert!(Handle::current().block_on(task).unwrap_err().is_cancelled());
1406            assert!(Handle::current()
1407                .block_on(retained.handle().spawn(async {}))
1408                .unwrap_err()
1409                .is_cancelled());
1410            retained.shutdown_timeout(Duration::from_secs(5));
1411        });
1412    }
1413
1414    // Exercises native Tokio runtime ownership or OS-thread behavior.
1415    #[cfg(not(all(feature = "fuzz", dst)))]
1416    #[test]
1417    fn shutdown_preserves_external_runtime() {
1418        test_utils::run(|| {
1419            let runtime = RuntimeBuilder::new(
1420                Runtime::test_config().with_tokio(TokioConfig::existing_handle(Handle::current())),
1421            )
1422            .build()
1423            .unwrap();
1424            let retained = runtime.clone();
1425
1426            runtime.shutdown_timeout(Duration::from_secs(5));
1427
1428            assert_eq!(
1429                Handle::current().block_on(retained.handle().spawn(async { 42 })).unwrap(),
1430                42
1431            );
1432        });
1433    }
1434
1435    // Exercises native Tokio runtime ownership or OS-thread behavior.
1436    #[cfg(not(all(feature = "fuzz", dst)))]
1437    #[reth_concurrency::test]
1438    fn critical_os_thread_uses_requested_name() {
1439        let runtime = Runtime::test();
1440        let (tx, rx) = mpsc::channel();
1441
1442        let handle = runtime.spawn_critical_os_thread(
1443            "critical-os-test",
1444            "critical os thread test",
1445            async move {
1446                let name = thread::current().name().unwrap().to_string();
1447                tx.send(name).unwrap();
1448            },
1449        );
1450
1451        let name = rx.recv_timeout(Duration::from_secs(5)).unwrap();
1452        assert_eq!(name, "critical-os-test");
1453        handle.join().unwrap();
1454    }
1455
1456    // Exercises native Tokio runtime ownership or OS-thread behavior.
1457    #[cfg(not(all(feature = "fuzz", dst)))]
1458    #[reth_concurrency::test]
1459    fn critical_os_thread_panic_is_reported() {
1460        let runtime = Runtime::test();
1461        let manager_handle = runtime.take_task_manager_handle().unwrap();
1462
1463        let handle = runtime.spawn_critical_os_thread(
1464            "critical-os-panic",
1465            "critical os thread panic test",
1466            async { panic!("critical os thread panic") },
1467        );
1468
1469        let err =
1470            runtime.handle().block_on(async move { manager_handle.await.unwrap().unwrap_err() });
1471        assert_eq!(err.task_name, "critical os thread panic test");
1472        assert_eq!(err.error, Some("critical os thread panic".to_string()));
1473        handle.join().unwrap();
1474    }
1475
1476    #[cfg(feature = "rayon")]
1477    #[reth_concurrency::test]
1478    fn test_worker_pools_are_lazy() {
1479        let runtime = Runtime::test();
1480
1481        // Worker pools are lazy — not initialized until first access.
1482        assert!(!runtime.0.bal_streaming_pool.is_initialized());
1483        assert!(!runtime.0.proof_storage_worker_pool.is_initialized());
1484        assert!(!runtime.0.state_trie_overlay_worker_pool.is_initialized());
1485
1486        // Accessing them triggers initialization and returns the configured thread count.
1487        assert_eq!(runtime.bal_streaming_pool().current_num_threads(), 2);
1488        assert!(runtime.0.bal_streaming_pool.is_initialized());
1489
1490        assert_eq!(runtime.proof_storage_worker_pool().current_num_threads(), 2);
1491        assert_eq!(runtime.proof_account_worker_pool().current_num_threads(), 2);
1492        assert_eq!(runtime.prewarming_pool().current_num_threads(), 2);
1493        assert_eq!(runtime.state_trie_overlay_worker_pool().current_num_threads(), 2);
1494    }
1495
1496    #[reth_concurrency::test]
1497    async fn service_can_release_a_blocking_worker() {
1498        let runtime = Runtime::test();
1499        let (started_tx, started_rx) = oneshot::channel();
1500        let (release_tx, release_rx) = mpsc::channel();
1501        let (done_tx, done_rx) = oneshot::channel();
1502
1503        let service = runtime.spawn_critical_task("release worker", async move {
1504            started_rx.await.unwrap();
1505            release_tx.send(()).unwrap();
1506        });
1507        runtime.spawn_blocking_task_detached(async move {
1508            started_tx.send(()).unwrap();
1509            release_rx.recv_timeout(Duration::from_secs(5)).unwrap();
1510            done_tx.send(()).unwrap();
1511        });
1512
1513        done_rx.await.unwrap();
1514        service.await.unwrap();
1515    }
1516
1517    #[reth_concurrency::test]
1518    async fn signal_tasks_run_in_async_tests() {
1519        let runtime = Runtime::test();
1520        let (signal_tx, signal_rx) = oneshot::channel();
1521        let (graceful_tx, graceful_rx) = oneshot::channel();
1522        let (critical_tx, critical_rx) = oneshot::channel();
1523
1524        runtime.spawn_with_signal(|_| async move { signal_tx.send(()).unwrap() });
1525        runtime
1526            .spawn_with_graceful_shutdown_signal(|_| async move { graceful_tx.send(()).unwrap() });
1527        runtime.spawn_critical_with_graceful_shutdown_signal("critical", |_| async move {
1528            critical_tx.send(()).unwrap()
1529        });
1530
1531        signal_rx.await.unwrap();
1532        graceful_rx.await.unwrap();
1533        critical_rx.await.unwrap();
1534    }
1535}