Skip to main content

reth_tasks/
pool.rs

1//! Additional helpers for executing tracing calls
2
3use crate::metrics::WorkerPoolMetrics;
4use reth_concurrency::sync::{
5    atomic::{AtomicUsize, Ordering},
6    rayon, thread,
7    time::Instant,
8    OnceLock,
9};
10use std::{
11    any::Any,
12    cell::RefCell,
13    future::Future,
14    ops::Deref,
15    panic::{catch_unwind, AssertUnwindSafe},
16    pin::Pin,
17    sync::{Arc, Weak},
18    task::{ready, Context, Poll},
19};
20use tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};
21
22#[cfg(all(feature = "fuzz", dst))]
23use reth_concurrency::sync::channel;
24#[cfg(all(feature = "fuzz", dst))]
25use std::mem;
26
27#[cfg(not(all(feature = "fuzz", dst)))]
28use std::sync;
29
30/// RPC Tracing call guard semaphore.
31///
32/// This is used to restrict the number of concurrent RPC requests to tracing methods like
33/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of
34/// memory and CPU.
35///
36/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit
37/// parallel blocking tasks in the pool.
38#[derive(Clone, Debug)]
39pub struct BlockingTaskGuard(Arc<Semaphore>);
40
41impl BlockingTaskGuard {
42    /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in
43    /// parallel.
44    pub fn new(max_blocking_tasks: usize) -> Self {
45        Self(Arc::new(Semaphore::new(max_blocking_tasks)))
46    }
47
48    /// See also [`Semaphore::acquire_owned`]
49    pub async fn acquire_owned(self) -> Result<OwnedSemaphorePermit, AcquireError> {
50        self.0.acquire_owned().await
51    }
52
53    /// See also [`Semaphore::acquire_many_owned`]
54    pub async fn acquire_many_owned(self, n: u32) -> Result<OwnedSemaphorePermit, AcquireError> {
55        self.0.acquire_many_owned(n).await
56    }
57}
58
59/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.
60///
61/// This is a dedicated threadpool for blocking tasks which are CPU bound.
62/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio
63/// runtime's blocking pool, which performs poorly with CPU bound tasks (see
64/// <https://ryhl.io/blog/async-what-is-blocking/>). Once the tokio blocking
65/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the
66/// queue and block other RPC calls.
67///
68/// See also [tokio-docs] for more information.
69///
70/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code
71#[derive(Clone, Debug)]
72pub struct BlockingTaskPool {
73    pool: Arc<rayon::ThreadPool>,
74}
75
76impl BlockingTaskPool {
77    /// Create a new `BlockingTaskPool` with the given threadpool.
78    pub fn new(pool: rayon::ThreadPool) -> Self {
79        Self { pool: Arc::new(pool) }
80    }
81
82    /// Convenience function to start building a new threadpool.
83    pub fn builder() -> rayon::ThreadPoolBuilder {
84        rayon::ThreadPoolBuilder::new()
85    }
86
87    /// Convenience function to build a new threadpool with the default configuration.
88    ///
89    /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.
90    /// If a different stack size or other parameters are needed, they can be configured via
91    /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].
92    pub fn build() -> Result<Self, rayon::ThreadPoolBuildError> {
93        Self::builder().build().map(Self::new)
94    }
95
96    /// Asynchronous wrapper around Rayon's
97    /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).
98    ///
99    /// Runs a function on the configured threadpool, returning a future that resolves with the
100    /// function's return value.
101    ///
102    /// If the function panics, the future will resolve to an error.
103    pub fn spawn<F, R>(&self, func: F) -> BlockingTaskHandle<R>
104    where
105        F: FnOnce() -> R + Send + 'static,
106        R: Send + 'static,
107    {
108        let (tx, rx) = oneshot::channel();
109
110        self.pool.spawn(move || {
111            let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));
112        });
113
114        BlockingTaskHandle { rx }
115    }
116
117    /// Asynchronous wrapper around Rayon's
118    /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).
119    ///
120    /// Runs a function on the configured threadpool, returning a future that resolves with the
121    /// function's return value.
122    ///
123    /// If the function panics, the future will resolve to an error.
124    pub fn spawn_fifo<F, R>(&self, func: F) -> BlockingTaskHandle<R>
125    where
126        F: FnOnce() -> R + Send + 'static,
127        R: Send + 'static,
128    {
129        let (tx, rx) = oneshot::channel();
130
131        self.pool.spawn_fifo(move || {
132            let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));
133        });
134
135        BlockingTaskHandle { rx }
136    }
137}
138
139/// Async handle for a blocking task running in a Rayon thread pool.
140///
141/// ## Panics
142///
143/// If polled from outside a tokio runtime.
144#[derive(Debug)]
145#[must_use = "futures do nothing unless you `.await` or poll them"]
146#[pin_project::pin_project]
147pub struct BlockingTaskHandle<T> {
148    #[pin]
149    pub(crate) rx: oneshot::Receiver<thread::Result<T>>,
150}
151
152impl<T> Future for BlockingTaskHandle<T> {
153    type Output = thread::Result<T>;
154
155    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
156        match ready!(self.project().rx.poll(cx)) {
157            Ok(res) => Poll::Ready(res),
158            Err(_) => Poll::Ready(Err(Box::<TokioBlockingTaskError>::default())),
159        }
160    }
161}
162
163/// An error returned when the Tokio channel is dropped while awaiting a result.
164///
165/// This should only happen
166#[derive(Debug, Default, thiserror::Error)]
167#[error("tokio channel dropped while awaiting result")]
168#[non_exhaustive]
169pub struct TokioBlockingTaskError;
170
171reth_concurrency::sync::thread_local! {
172    static WORKER: RefCell<Worker> = const { RefCell::new(Worker::new()) };
173}
174
175#[cfg(all(feature = "fuzz", dst))]
176std::thread_local! {
177    // Shuttle tasks share one runner thread, but jobs retain their logical pool worker's state.
178    #[allow(
179        clippy::disallowed_types,
180        reason = "Host-local storage retains non-Send worker values; access is serialized by the selected Mutex."
181    )]
182    static WORKERS: RefCell<std::collections::BTreeMap<(usize, usize), std::rc::Rc<WorkerSlot>>> =
183        const { RefCell::new(std::collections::BTreeMap::new()) };
184}
185
186#[cfg(all(feature = "fuzz", dst))]
187#[derive(Default)]
188struct WorkerSlot {
189    state: RefCell<Worker>,
190    access: reth_concurrency::sync::Mutex<()>,
191    owner: std::cell::Cell<Option<thread::ThreadId>>,
192}
193
194fn with_current_worker<R>(f: impl FnOnce(&RefCell<Worker>) -> R) -> R {
195    #[cfg(all(feature = "fuzz", dst))]
196    if let Some(pool) = rayon::current_pool_id() {
197        let index = rayon::current_thread_index().expect("pool context has a worker index");
198        #[allow(
199            clippy::disallowed_methods,
200            reason = "Only finds worker storage in host TLS; the borrow ends before scheduler-managed locking."
201        )]
202        let worker =
203            WORKERS.with(|workers| workers.borrow_mut().entry((pool, index)).or_default().clone());
204        // Reentrant calls keep native RefCell semantics instead of locking this task against
205        // itself.
206        let current = thread::current().id();
207        if worker.owner.get() == Some(current) {
208            return f(&worker.state);
209        }
210        // Distinct simulated jobs can share a logical slot while one is suspended on I/O.
211        let access = worker.access.lock().expect("worker access is not poisoned");
212        worker.owner.set(Some(current));
213        let result = catch_unwind(AssertUnwindSafe(|| f(&worker.state)));
214        worker.owner.set(None);
215        drop(access);
216        return match result {
217            Ok(value) => value,
218            Err(panic) => std::panic::resume_unwind(panic),
219        };
220    }
221    WORKER.with(f)
222}
223
224/// A rayon thread pool with per-thread [`Worker`] state.
225///
226/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via
227/// [`WorkerStatefulPool::init`]. Access state through its owner from jobs executing on the pool,
228/// for example inside [`install_fn`](Self::install_fn).
229///
230/// Worker access is backed by a thread-local [`RefCell`] (logical-worker-local under `fuzz` plus
231/// `--cfg dst`). State is created, accessed, and dropped on its worker, including non-`Send`
232/// values. Under `fuzz` plus `--cfg dst`, different simulated jobs sharing a logical slot serialize
233/// worker access even across blocking executor waits; recursive access retains the native borrow
234/// checks. Keep [`with_worker`](Self::with_worker) and [`with_worker_mut`](Self::with_worker_mut) closures short
235/// and non-yielding: if Rayon runs another job on the same thread while a borrow is active,
236/// re-entrant worker access can panic.
237///
238/// Independent [`WorkerStatefulPool`] owners can reuse the same threads with different state
239/// configurations; each owner clears its state when dropped.
240///
241/// The underlying rayon pool is created lazily on first access.
242#[derive(Debug)]
243pub struct WorkerPool {
244    pool: OnceLock<rayon::ThreadPool>,
245    metrics: OnceLock<WorkerPoolMetrics>,
246    num_threads: usize,
247    thread_name_prefix: &'static str,
248}
249
250impl WorkerPool {
251    /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.
252    ///
253    /// The underlying rayon pool is not created until the first method that requires it is called.
254    /// Thread names follow the pattern `"{prefix}-{index:02}"`.
255    pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {
256        Self { pool: OnceLock::new(), metrics: OnceLock::new(), num_threads, thread_name_prefix }
257    }
258
259    /// Returns a reference to the underlying rayon pool, creating it on first access.
260    fn pool(&self) -> &rayon::ThreadPool {
261        self.pool.get_or_init(|| {
262            let prefix = self.thread_name_prefix;
263            build_pool_with_panic_handler(
264                rayon::ThreadPoolBuilder::new()
265                    .num_threads(self.num_threads)
266                    .thread_name(move |i| format!("{prefix}-{i:02}")),
267            )
268            .unwrap_or_else(|err| panic!("failed to build {prefix} worker pool: {err}"))
269        })
270    }
271
272    /// Returns metrics for this worker pool.
273    fn metrics(&self) -> &WorkerPoolMetrics {
274        self.metrics.get_or_init(|| WorkerPoolMetrics::new(self.thread_name_prefix))
275    }
276
277    /// Returns `true` if the underlying rayon pool has been initialized.
278    pub fn is_initialized(&self) -> bool {
279        self.pool.get().is_some()
280    }
281
282    /// Returns the number of threads the pool is configured with, without creating it.
283    pub const fn num_threads(&self) -> usize {
284        self.num_threads
285    }
286
287    /// Returns the total number of threads in the underlying rayon pool.
288    pub fn current_num_threads(&self) -> usize {
289        self.pool().current_num_threads()
290    }
291
292    /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each
293    /// thread's [`Worker`].
294    ///
295    /// The closure runs with exclusive access to each selected thread's worker.
296    /// Only `num_threads` threads execute the closure; the rest skip it.
297    pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {
298        if num_threads >= self.pool().current_num_threads() {
299            // Fast path: run on every thread, no atomic coordination needed.
300            self.pool().broadcast(|_| {
301                with_current_worker(|worker| f(&mut worker.borrow_mut()));
302            });
303        } else {
304            let remaining = AtomicUsize::new(num_threads);
305            self.pool().broadcast(|_| {
306                // Atomically claim a slot; threads that can't decrement skip the closure.
307                let mut current = remaining.load(Ordering::Relaxed);
308                loop {
309                    if current == 0 {
310                        return;
311                    }
312                    match remaining.compare_exchange_weak(
313                        current,
314                        current - 1,
315                        Ordering::Relaxed,
316                        Ordering::Relaxed,
317                    ) {
318                        Ok(_) => break,
319                        Err(actual) => current = actual,
320                    }
321                }
322                with_current_worker(|worker| f(&mut worker.borrow_mut()));
323            });
324        }
325    }
326
327    /// Runs a closure on the pool with access to the calling thread's [`Worker`].
328    ///
329    /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.
330    /// Each thread can access its own [`Worker`] via the provided reference or through additional
331    /// [`WorkerPool::with_worker`] calls.
332    pub fn install<R: Send>(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {
333        let pool = self.pool();
334        let metrics = self.metrics().clone();
335        let queued_at = Instant::now();
336
337        pool.install(move || {
338            let started_at = Instant::now();
339            metrics.record_job_queue_wait(started_at.saturating_duration_since(queued_at));
340            let _record_job_duration = RecordWorkerPoolJobDurationOnDrop::new(metrics, started_at);
341            Self::with_worker(f)
342        })
343    }
344
345    /// Runs a closure on the pool without worker state access.
346    ///
347    /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]
348    /// state.
349    pub fn install_fn<R: Send>(&self, f: impl FnOnce() -> R + Send) -> R {
350        let pool = self.pool();
351        let metrics = self.metrics().clone();
352        let queued_at = Instant::now();
353
354        pool.install(move || {
355            let started_at = Instant::now();
356            metrics.record_job_queue_wait(started_at.saturating_duration_since(queued_at));
357            let _record_job_duration = RecordWorkerPoolJobDurationOnDrop::new(metrics, started_at);
358            f()
359        })
360    }
361
362    /// Runs a closure on this pool, waiting for its result.
363    ///
364    /// Unlike [`install_fn`](Self::install_fn), this always queues the closure onto this pool
365    /// when called from another rayon pool. This avoids Rayon running the closure on the caller's
366    /// worker through its cross-pool install path.
367    pub fn spawn_and_wait<R: Send + 'static>(&self, f: impl FnOnce() -> R + Send + 'static) -> R {
368        let pool = self.pool();
369        if pool.current_thread_index().is_some() {
370            return f()
371        }
372
373        #[cfg(not(all(feature = "fuzz", dst)))]
374        let (tx, rx) = sync::mpsc::sync_channel(1);
375        #[cfg(all(feature = "fuzz", dst))]
376        let (tx, rx) = channel::bounded(1);
377        self.spawn(move || {
378            let _ = tx.send(catch_unwind(AssertUnwindSafe(f)));
379        });
380
381        match rx.recv().expect("worker pool exited before completing task") {
382            Ok(result) => result,
383            Err(panic) => std::panic::resume_unwind(panic),
384        }
385    }
386
387    /// Spawns a closure on the pool.
388    pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {
389        let pool = self.pool();
390        let metrics = self.metrics().clone();
391        let queued_at = Instant::now();
392
393        pool.spawn(move || {
394            let started_at = Instant::now();
395            metrics.record_job_queue_wait(started_at.saturating_duration_since(queued_at));
396            let _record_job_duration = RecordWorkerPoolJobDurationOnDrop::new(metrics, started_at);
397            f();
398        });
399    }
400
401    /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling
402    /// thread into a worker for the duration — tasks spawned inside the scope run on the pool
403    /// and the call blocks until all of them complete.
404    pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {
405        self.pool().in_place_scope(f)
406    }
407
408    /// Accesses the current thread's [`Worker`] from within a pool closure.
409    ///
410    /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`
411    /// reference from `install` belongs to a different thread.
412    ///
413    /// This borrows the thread-local worker for the entire duration of `f`. Do not yield to Rayon
414    /// from inside `f` if another job could call [`with_worker_mut`](Self::with_worker_mut) on the
415    /// same thread. Yield points include parallel iterators, `rayon::join`, scopes, and waiting in
416    /// `ThreadPool::install` on a different Rayon pool. A cross-pool `install` may run another job
417    /// from the caller's pool on the same thread while it waits.
418    ///
419    /// Prefer copying or cloning the required worker state in `f`, returning from this method to
420    /// release the borrow, and only then performing work that may yield.
421    ///
422    /// # Panics
423    ///
424    /// Panics if the current thread's worker is already mutably borrowed, including by a
425    /// re-entrant [`with_worker_mut`](Self::with_worker_mut) call.
426    pub fn with_worker<R>(f: impl FnOnce(&Worker) -> R) -> R {
427        with_current_worker(|worker| f(&worker.borrow()))
428    }
429
430    /// Mutably accesses the current thread's [`Worker`] from within a pool closure.
431    ///
432    /// This exclusively borrows the thread-local worker for the entire duration of `f`. The borrow
433    /// is not re-entrant: if Rayon runs another job on the same thread before `f` returns, any call
434    /// to [`with_worker`](Self::with_worker) or `with_worker_mut` from that job will panic.
435    ///
436    /// Do not call operations that can yield to Rayon from inside `f` when re-entrant worker access
437    /// is possible. This includes parallel iterators, `rayon::join`, scopes, and waiting in
438    /// `ThreadPool::install` on a different Rayon pool. In particular, a cross-pool `install`
439    /// cooperatively runs jobs from the caller's pool while waiting for the target pool.
440    ///
441    /// Prefer computing updates before entering `with_worker_mut`, then use this closure only to
442    /// apply the update to the worker state.
443    ///
444    /// # Panics
445    ///
446    /// Panics if the current thread's worker is already borrowed, including by a re-entrant
447    /// `with_worker` or `with_worker_mut` call.
448    pub fn with_worker_mut<R>(f: impl FnOnce(&mut Worker) -> R) -> R {
449        with_current_worker(|worker| f(&mut worker.borrow_mut()))
450    }
451}
452
453#[cfg(all(feature = "fuzz", dst))]
454impl Drop for WorkerPool {
455    fn drop(&mut self) {
456        if let Some(pool) = self.pool.get() {
457            let id = pool.id();
458            #[allow(
459                clippy::disallowed_methods,
460                reason = "Removes this pool's non-Send worker storage on its host runner during teardown."
461            )]
462            WORKERS.with(|workers| workers.borrow_mut().retain(|(pool, _), _| *pool != id));
463        }
464    }
465}
466
467/// Records a worker pool job's run time when the job finishes or unwinds.
468struct RecordWorkerPoolJobDurationOnDrop {
469    metrics: WorkerPoolMetrics,
470    started_at: Instant,
471}
472
473impl RecordWorkerPoolJobDurationOnDrop {
474    const fn new(metrics: WorkerPoolMetrics, started_at: Instant) -> Self {
475        Self { metrics, started_at }
476    }
477}
478
479impl Drop for RecordWorkerPoolJobDurationOnDrop {
480    fn drop(&mut self) {
481        self.metrics.record_job_duration(self.started_at.elapsed());
482    }
483}
484
485/// Builds a rayon thread pool with a panic handler that prevents aborting the process.
486///
487/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler
488/// itself is intentionally a no-op.
489pub fn build_pool_with_panic_handler(
490    builder: rayon::ThreadPoolBuilder,
491) -> Result<rayon::ThreadPool, rayon::ThreadPoolBuildError> {
492    builder.panic_handler(|_| {}).build()
493}
494
495/// Per-thread state container for a [`WorkerPool`].
496///
497/// Holds a type-erased `Box<dyn Any>` that can be initialized and accessed with concrete types
498/// through [`WorkerStatefulPool`].
499#[derive(Debug, Default)]
500pub struct Worker {
501    state: Option<(Weak<WorkerStatefulPool>, Box<dyn Any>)>,
502}
503
504impl Worker {
505    /// Creates a new empty `Worker`.
506    const fn new() -> Self {
507        Self { state: None }
508    }
509
510    /// Initializes the worker state.
511    ///
512    /// If state of type `T` already exists for `stateful_pool`, passes `Some(&mut T)` to the
513    /// closure so resources can be reused. Otherwise, drops the previous state and passes
514    /// `None`.
515    fn init<T: 'static>(
516        &mut self,
517        stateful_pool: &Weak<WorkerStatefulPool>,
518        f: impl FnOnce(Option<&mut T>) -> T,
519    ) {
520        let existing = self.state.take().and_then(|(owner, boxed)| {
521            (Weak::ptr_eq(&owner, stateful_pool) && boxed.is::<T>()).then_some(boxed)
522        });
523
524        let new_state = match existing {
525            Some(mut boxed) => {
526                let r = boxed.downcast_mut::<T>().expect("type checked above");
527                *r = f(Some(r));
528                boxed
529            }
530            None => Box::new(f(None)),
531        };
532
533        self.state = Some((stateful_pool.clone(), new_state));
534    }
535
536    /// Returns a reference to the state for `stateful_pool`, downcasted to `T`.
537    ///
538    /// # Panics
539    ///
540    /// Panics if the worker has not been initialized or if the run or type does not match.
541    fn get<T: 'static>(&self, stateful_pool: &Weak<WorkerStatefulPool>) -> &T {
542        let (owner, state) = self.state.as_ref().expect("worker not initialized");
543        assert!(Weak::ptr_eq(owner, stateful_pool), "worker state run mismatch");
544        state.downcast_ref::<T>().expect("worker state type mismatch")
545    }
546
547    /// Returns a mutable reference to the state for `stateful_pool`, downcasted to `T`.
548    ///
549    /// # Panics
550    ///
551    /// Panics if the worker has not been initialized or if the run or type does not match.
552    fn get_mut<T: 'static>(&mut self, stateful_pool: &Weak<WorkerStatefulPool>) -> &mut T {
553        let (owner, state) = self.state.as_mut().expect("worker not initialized");
554        assert!(Weak::ptr_eq(owner, stateful_pool), "worker state run mismatch");
555        state.downcast_mut::<T>().expect("worker state type mismatch")
556    }
557
558    /// Returns mutable state for `stateful_pool`, creating it with `f` if absent.
559    ///
560    /// Reuses existing state without calling `f` when both its run and type match.
561    /// Otherwise, drops the previous state before calling `f` to create its replacement.
562    /// If `f` panics, the worker remains uninitialized.
563    fn get_or_init<T: 'static>(
564        &mut self,
565        stateful_pool: &Weak<WorkerStatefulPool>,
566        f: impl FnOnce() -> T,
567    ) -> &mut T {
568        if !self
569            .state
570            .as_ref()
571            .is_some_and(|(owner, state)| Weak::ptr_eq(owner, stateful_pool) && state.is::<T>())
572        {
573            self.state = None;
574            self.state = Some((stateful_pool.clone(), Box::new(f())));
575        }
576        self.get_mut(stateful_pool)
577    }
578
579    /// Drops the worker state only if it belongs to `stateful_pool`.
580    fn clear(&mut self, stateful_pool: &Weak<WorkerStatefulPool>) {
581        if self.state.as_ref().is_some_and(|(owner, _)| Weak::ptr_eq(owner, stateful_pool)) {
582            self.state = None;
583        }
584    }
585}
586
587/// Owns one run's thread-local state on a shared [`WorkerPool`].
588///
589/// Share this value with jobs through an [`Arc`]. Dropping the last handle clears this run's
590/// state on every pool thread, leaving other runs' state untouched. Worker slots retain only
591/// a weak reference to this owner and do not keep it alive. Dereferences to the underlying
592/// pool for scheduling jobs; each job accessing state must retain an owner handle.
593///
594/// Access closures borrow the current thread's worker and must not yield to Rayon or recursively
595/// access worker state. Use them only in jobs executing on this pool. Cleanup broadcasts to the
596/// pool and blocks until complete; the last handle must be dropped outside worker access closures.
597#[derive(Debug)]
598pub struct WorkerStatefulPool {
599    pool: Arc<WorkerPool>,
600    owner: Weak<Self>,
601}
602
603impl WorkerStatefulPool {
604    /// Creates a shared state owner without initializing the pool or its workers.
605    pub fn new(pool: Arc<WorkerPool>) -> Arc<Self> {
606        Arc::new_cyclic(|owner| Self { pool, owner: owner.clone() })
607    }
608
609    /// Initializes this run's state on every pool thread.
610    ///
611    /// Offers existing state to `f` only when its run and type match. Otherwise, drops the previous
612    /// state before calling `f` with `None`.
613    pub fn init<T: 'static>(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {
614        self.pool.broadcast(self.pool.current_num_threads(), |worker| {
615            worker.init(&self.owner, &f);
616        });
617    }
618
619    /// Reads this run's state on the current worker thread.
620    ///
621    /// # Panics
622    ///
623    /// Panics if the worker is uninitialized, its run or type differs, or it is mutably borrowed.
624    pub fn get<T: 'static, R>(&self, f: impl FnOnce(&T) -> R) -> R {
625        WorkerPool::with_worker(|worker| f(worker.get(&self.owner)))
626    }
627
628    /// Mutably accesses this run's state, initializing it on the current worker if needed.
629    ///
630    /// Reuses state without calling `init` when both its run and type match. Otherwise, drops the
631    /// previous state before calling `init`. If `init` panics, the worker remains uninitialized.
632    ///
633    /// # Panics
634    ///
635    /// Panics if the current worker is already borrowed.
636    pub fn get_or_init<T: 'static, R>(
637        &self,
638        init: impl FnOnce() -> T,
639        f: impl FnOnce(&mut T) -> R,
640    ) -> R {
641        WorkerPool::with_worker_mut(|worker| f(worker.get_or_init(&self.owner, init)))
642    }
643}
644
645impl Deref for WorkerStatefulPool {
646    type Target = WorkerPool;
647
648    fn deref(&self) -> &Self::Target {
649        &self.pool
650    }
651}
652
653impl Drop for WorkerStatefulPool {
654    fn drop(&mut self) {
655        if let Some(pool) = self.pool.pool.get() {
656            #[cfg(all(feature = "fuzz", dst))]
657            let unwinding = thread::panicking();
658            pool.broadcast(|_| {
659                let clear = || {
660                    with_current_worker(|worker| worker.borrow_mut().clear(&self.owner));
661                };
662                #[cfg(not(all(feature = "fuzz", dst)))]
663                clear();
664                #[cfg(all(feature = "fuzz", dst))]
665                if unwinding {
666                    if let Err(panic) = catch_unwind(AssertUnwindSafe(clear)) {
667                        // Dropping an arbitrary secondary panic payload could panic again.
668                        mem::forget(panic);
669                        tracing::error!("worker state destructor panicked during unwinding");
670                    }
671                } else {
672                    clear();
673                }
674            });
675        }
676    }
677}
678
679#[cfg(test)]
680mod tests {
681    use super::*;
682    use crate::test_utils;
683    use reth_concurrency::sync::{channel, rayon::prelude::*};
684    use std::{mem, time::Duration};
685
686    #[test]
687    fn blocking_pool() {
688        test_utils::run(|| {
689            let pool = BlockingTaskPool::build().unwrap();
690            let res = pool.spawn(move || 5);
691            let res = test_utils::block_on(res).unwrap();
692            assert_eq!(res, 5);
693        });
694    }
695
696    #[test]
697    fn blocking_pool_panic() {
698        test_utils::run(|| {
699            let pool = BlockingTaskPool::build().unwrap();
700            let res = pool.spawn(move || -> i32 {
701                panic!("blocking pool panic");
702            });
703            let panic = test_utils::block_on(res).unwrap_err();
704            assert_eq!(panic.downcast_ref::<&str>(), Some(&"blocking pool panic"));
705        });
706    }
707
708    #[reth_concurrency::test]
709    fn worker_pool_init_and_access() {
710        let pool = Arc::new(WorkerPool::new(2, "test"));
711        let state = WorkerStatefulPool::new(Arc::clone(&pool));
712        state.init(|_| vec![1u8, 2, 3]);
713        let sum = pool.install_fn(|| state.get(|v: &Vec<u8>| v.iter().sum::<u8>()));
714        assert_eq!(sum, 6);
715        drop(state);
716        pool.broadcast(2, |worker| assert!(worker.state.is_none()));
717    }
718
719    #[reth_concurrency::test]
720    fn worker_pool_reinit_reuses_resources() {
721        let pool = Arc::new(WorkerPool::new(1, "test"));
722        let state = WorkerStatefulPool::new(Arc::clone(&pool));
723        state.init(|existing: Option<&mut Vec<u8>>| {
724            assert!(existing.is_none());
725            vec![1, 2, 3]
726        });
727        state.init(|existing: Option<&mut Vec<u8>>| {
728            let v = existing.expect("should have existing state");
729            assert_eq!(v, &mut vec![1, 2, 3]);
730            v.push(4);
731            mem::take(v)
732        });
733        let len = pool.install_fn(|| state.get(Vec::<u8>::len));
734        assert_eq!(len, 4);
735    }
736
737    #[reth_concurrency::test]
738    fn worker_pool_clear_and_reinit() {
739        let pool = Arc::new(WorkerPool::new(1, "test"));
740        let state = WorkerStatefulPool::new(Arc::clone(&pool));
741        state.init(|_| 42u64);
742        assert_eq!(pool.install_fn(|| state.get(|v: &u64| *v)), 42);
743        drop(state);
744        let state = WorkerStatefulPool::new(Arc::clone(&pool));
745        state.init(|_| String::from("hello"));
746        assert_eq!(pool.install_fn(|| state.get(String::clone)), "hello");
747    }
748
749    #[reth_concurrency::test]
750    fn worker_pool_par_iter_with_worker() {
751        let pool = Arc::new(WorkerPool::new(2, "test"));
752        let state = WorkerStatefulPool::new(Arc::clone(&pool));
753        state.init(|_| 10u64);
754        let results = pool.install_fn(|| {
755            (0u64..4).into_par_iter().map(|i| state.get(|v: &u64| i + *v)).collect::<Vec<_>>()
756        });
757        assert_eq!(results, vec![10, 11, 12, 13]);
758    }
759
760    #[reth_concurrency::test]
761    fn worker_pool_spawn_and_wait_runs_on_target_pool() {
762        let caller_pool = WorkerPool::new(1, "caller");
763        let target_pool = Arc::new(WorkerPool::new(1, "target"));
764
765        let thread_name = caller_pool.install_fn({
766            let target_pool = Arc::clone(&target_pool);
767            move || {
768                WorkerPool::with_worker_mut(|_| {
769                    target_pool.spawn_and_wait(|| thread::current().name().unwrap().to_owned())
770                })
771            }
772        });
773
774        assert_eq!(thread_name, "target-00");
775    }
776
777    #[reth_concurrency::test]
778    fn worker_get_or_init_reuses_only_matching_run_and_type() {
779        let mut worker = Worker::new();
780        let first = stateful_pool();
781        let second = stateful_pool();
782
783        worker.get_or_init(&first.owner, || vec![1u8]).push(2);
784        assert_eq!(
785            worker.get_or_init::<Vec<u8>>(&first.owner.clone(), || panic!("must reuse")),
786            &[1, 2]
787        );
788        assert_eq!(worker.get_or_init(&second.owner, || vec![3u8]), &[3]);
789        assert_eq!(worker.get_or_init(&second.owner, || String::from("new type")), "new type");
790        assert_eq!(*worker.get_or_init(&first.owner, || 42u64), 42);
791    }
792
793    #[reth_concurrency::test]
794    fn worker_init_reuses_only_matching_run_and_type() {
795        let mut worker = Worker::new();
796        let first = stateful_pool();
797        let second = stateful_pool();
798        worker.init(&first.owner, |_| 1u64);
799        worker.init(&second.owner, |existing: Option<&mut u64>| {
800            assert!(existing.is_none());
801            2
802        });
803        worker.init(&second.owner, |existing: Option<&mut String>| {
804            assert!(existing.is_none());
805            String::from("new type")
806        });
807        assert_eq!(worker.get::<String>(&second.owner), "new type");
808    }
809
810    #[reth_concurrency::test]
811    fn worker_pool_late_cleanup_preserves_other_runs() {
812        let pool = Arc::new(WorkerPool::new(2, "run-cleanup"));
813        let first = WorkerStatefulPool::new(Arc::clone(&pool));
814        let second = WorkerStatefulPool::new(Arc::clone(&pool));
815        first.init(|_| 1u64);
816        pool.broadcast(1, |worker| {
817            assert_eq!(*worker.get_or_init(&second.owner, || 2u64), 2);
818        });
819        drop(first);
820        let retained = AtomicUsize::new(0);
821        pool.broadcast(2, |worker| {
822            if let Some((owner, state)) = &worker.state {
823                assert!(Weak::ptr_eq(owner, &second.owner));
824                assert_eq!(state.downcast_ref::<u64>(), Some(&2));
825                retained.fetch_add(1, Ordering::Relaxed);
826            }
827        });
828        assert_eq!(retained.load(Ordering::Relaxed), 1);
829        drop(second);
830        pool.broadcast(2, |worker| assert!(worker.state.is_none()));
831    }
832
833    #[reth_concurrency::test]
834    #[should_panic(expected = "worker state run mismatch")]
835    fn worker_get_rejects_another_run() {
836        let mut worker = Worker::new();
837        worker.init(&stateful_pool().owner, |_| 1u64);
838        worker.get::<u64>(&stateful_pool().owner);
839    }
840
841    #[reth_concurrency::test]
842    #[should_panic(expected = "worker state run mismatch")]
843    fn worker_get_mut_rejects_another_run() {
844        let mut worker = Worker::new();
845        worker.init(&stateful_pool().owner, |_| 1u64);
846        worker.get_mut::<u64>(&stateful_pool().owner);
847    }
848
849    #[reth_concurrency::test]
850    fn worker_replacement_drops_previous_state_before_initialization() {
851        let mut worker = Worker::new();
852        let previous_run = stateful_pool();
853        let next_run = stateful_pool();
854        let resource = Arc::new(());
855
856        for owner in [&previous_run.owner, &next_run.owner] {
857            worker.init(&previous_run.owner, |_| Arc::clone(&resource));
858            assert_eq!(Arc::strong_count(&resource), 2);
859            assert_eq!(
860                *worker.get_or_init(owner, || {
861                    assert_eq!(Arc::strong_count(&resource), 1);
862                    42u64
863                }),
864                42,
865            );
866        }
867    }
868
869    #[reth_concurrency::test]
870    fn worker_failed_replacement_leaves_state_uninitialized() {
871        let mut worker = Worker::new();
872        let previous_run = stateful_pool();
873        let next_run = stateful_pool();
874        worker.init(&previous_run.owner, |_| 1u64);
875
876        let panic = catch_unwind(AssertUnwindSafe(|| {
877            worker.get_or_init::<u64>(&next_run.owner, || panic!("initialization failed"));
878        }))
879        .unwrap_err();
880        assert_eq!(panic.downcast_ref::<&str>(), Some(&"initialization failed"));
881        assert!(worker.state.is_none());
882        assert_eq!(*worker.get_or_init(&next_run.owner, || 2u64), 2);
883    }
884
885    #[reth_concurrency::test]
886    fn stateful_pool_drop_does_not_initialize_unused_pool() {
887        let pool = Arc::new(WorkerPool::new(1, "unused-state"));
888        drop(WorkerStatefulPool::new(Arc::clone(&pool)));
889        assert!(!pool.is_initialized());
890    }
891
892    #[reth_concurrency::test]
893    fn stateful_pool_last_job_handle_clears_state() {
894        let pool = Arc::new(WorkerPool::new(2, "owned-state"));
895        let state = WorkerStatefulPool::new(Arc::clone(&pool));
896        let owner = Arc::downgrade(&state);
897        let resource = Arc::new(());
898        state.init(|_| Arc::clone(&resource));
899        let (ready_tx, ready_rx) = channel::unbounded();
900        let (release_tx, release_rx) = channel::unbounded();
901        let (done_tx, done_rx) = channel::unbounded();
902        let job_state = Arc::clone(&state);
903        state.spawn(move || {
904            ready_tx.send(()).unwrap();
905            release_rx.recv_timeout(Duration::from_secs(5)).unwrap();
906            job_state.get(|value: &Arc<()>| assert_eq!(Arc::strong_count(value), 3));
907            drop(job_state);
908            done_tx.send(()).unwrap();
909        });
910        ready_rx.recv_timeout(Duration::from_secs(5)).unwrap();
911        drop(state);
912        assert!(owner.upgrade().is_some());
913        assert_eq!(Arc::strong_count(&resource), 3);
914        release_tx.send(()).unwrap();
915        done_rx.recv_timeout(Duration::from_secs(5)).unwrap();
916        assert!(owner.upgrade().is_none());
917        assert_eq!(Arc::strong_count(&resource), 1);
918        pool.broadcast(2, |worker| assert!(worker.state.is_none()));
919    }
920
921    #[reth_concurrency::test]
922    fn stateful_pool_clears_after_job_panics() {
923        let pool = Arc::new(WorkerPool::new(1, "unwind-state"));
924        let state = WorkerStatefulPool::new(Arc::clone(&pool));
925        let resource = Arc::new(());
926        state.init(|_| Arc::clone(&resource));
927        let panic = catch_unwind(AssertUnwindSafe(|| {
928            pool.install_fn(move || {
929                state.get_or_init(|| Arc::new(()), |_| panic!("job failed"));
930            });
931        }))
932        .unwrap_err();
933        assert_eq!(panic.downcast_ref::<&str>(), Some(&"job failed"));
934        assert_eq!(Arc::strong_count(&resource), 1);
935        pool.broadcast(1, |worker| assert!(worker.state.is_none()));
936    }
937
938    #[reth_concurrency::test]
939    fn stateful_pool_clears_after_unwrapping_owner() {
940        let pool = Arc::new(WorkerPool::new(1, "unwrapped-state"));
941        let state = WorkerStatefulPool::new(Arc::clone(&pool));
942        let resource = Arc::new(());
943        state.init(|_| Arc::clone(&resource));
944        let state = Arc::try_unwrap(state).unwrap();
945        assert_eq!(Arc::strong_count(&resource), 2);
946        drop(state);
947        assert_eq!(Arc::strong_count(&resource), 1);
948        pool.broadcast(1, |worker| assert!(worker.state.is_none()));
949    }
950
951    fn stateful_pool() -> Arc<WorkerStatefulPool> {
952        WorkerStatefulPool::new(Arc::new(WorkerPool::new(1, "state-test")))
953    }
954}