Skip to main content

reth_trie_parallel/proof_task/
mod.rs

1//! Parallel proof computation using worker pools with dedicated database transactions.
2//!
3//!
4//! # Architecture
5//!
6//! - **Worker Pools**: Pre-spawned workers with dedicated database transactions
7//!   - Storage pool: Handles storage proofs, one account's storage trie per job
8//!   - Account pool: Handles account proofs, calculating storage roots inline
9//! - **Automatic Shutdown**: Workers terminate when the handle is dropped, discarding queued jobs
10//!
11//! # Message Flow
12//!
13//! 1. [`ProofWorkerHandle::dispatch`] splits proof targets into storage and account jobs and queues
14//!    each job for the matching worker pool.
15//! 2. A worker receives a job, runs the proof, and sends one [`ProofWorkerResult`] to the handle's
16//!    result channel.
17//! 3. The owner of the handle receives the results through [`ProofWorkerHandle::results`].
18//!
19//! ```text
20//! ProofWorkerHandle::dispatch -> Storage/Account Worker
21//!                                          |
22//!                                          v
23//! ProofWorkerHandle::results <-- ProofWorkerResult
24//! ```
25
26#[cfg(feature = "metrics")]
27pub mod metrics;
28
29use crate::error::StateRootTaskError;
30use alloy_primitives::B256;
31use reth_concurrency::sync::{
32    atomic::{AtomicBool, AtomicUsize, Ordering},
33    channel::{unbounded, Receiver, Sender},
34    time::FastInstant as Instant,
35};
36use reth_provider::{DatabaseProviderROFactory, ProviderError, ProviderResult, StateProofProvider};
37use reth_tasks::{Runtime, WorkerPool};
38use reth_trie::{DecodedMultiProofV2, MultiProofTargetsV2, ProofV2Target};
39use std::{
40    panic::{catch_unwind, AssertUnwindSafe},
41    sync::Arc,
42    time::Duration,
43};
44use tracing::{debug, debug_span, error, instrument, trace};
45
46#[cfg(feature = "metrics")]
47use self::metrics::ProofWorkerIdleMetrics;
48
49/// Tracks worker availability counts.
50///
51/// It uses cacheline-aligned flags to avoid core-to-core chatter.
52#[derive(Debug)]
53struct AvailabilitySheet {
54    /// One flag per worker, each on its own cacheline. Workers store `true` when idle,
55    /// `false` when busy. Only the owning worker writes; the dispatcher only reads.
56    flags: Vec<crossbeam_utils::CachePadded<AtomicBool>>,
57}
58
59impl AvailabilitySheet {
60    /// Creates a new sheet with `count` workers, all initially marked as busy.
61    fn new(count: usize) -> Self {
62        let flags =
63            (0..count).map(|_| crossbeam_utils::CachePadded::new(AtomicBool::new(false))).collect();
64        Self { flags }
65    }
66
67    /// Returns `true` if more than one worker is currently idle.
68    ///
69    /// Note, that this is somewhat racy since a flag that was just saying `idle` and we counted it
70    /// as such might turn into `busy` right away.
71    fn has_multiple_idle(&self) -> bool {
72        let mut idle = 0u32;
73        for flag in &self.flags {
74            if flag.load(Ordering::Relaxed) {
75                idle += 1;
76                if idle > 1 {
77                    return true;
78                }
79            }
80        }
81        false
82    }
83
84    /// Marks the given worker as idle.
85    fn mark_idle(&self, worker_id: usize) {
86        self.flags[worker_id].store(true, Ordering::Relaxed);
87    }
88
89    /// Marks the given worker as busy.
90    fn mark_busy(&self, worker_id: usize) {
91        self.flags[worker_id].store(false, Ordering::Relaxed);
92    }
93}
94
95/// Owns the storage and account proof worker pools and the channel their results arrive on.
96///
97/// Every job queued by [`Self::dispatch`] sends exactly one [`ProofWorkerResult`] to
98/// [`Self::results`]. A worker that fails to open its provider, at start or after a panicking
99/// job, sends an error that belongs to no job instead, and jobs left queued when every worker of a
100/// pool has failed get no result. Once the handle is dropped, workers finish the jobs they are
101/// running and discard the jobs still queued.
102#[derive(Debug)]
103pub struct ProofWorkerHandle {
104    /// Sender shared with the workers, kept so that [`Self::results`] never disconnects while the
105    /// handle is alive.
106    _result_tx: Sender<ProofWorkerResult>,
107    /// Results sent by both worker pools.
108    result_rx: Receiver<ProofWorkerResult>,
109    /// Direct sender to storage worker pool
110    storage_work_tx: Sender<StorageProofJob>,
111    /// Direct sender to account worker pool
112    account_work_tx: Sender<AccountProofJob>,
113    /// Per-worker availability flags for storage workers. Used to determine whether to chunk
114    /// multiproofs.
115    storage_availability: Arc<AvailabilitySheet>,
116    /// Per-worker availability flags for account workers. Used to determine whether to chunk
117    /// multiproofs.
118    account_availability: Arc<AvailabilitySheet>,
119    /// Total number of storage workers spawned
120    storage_worker_count: usize,
121    /// Total number of account workers spawned
122    account_worker_count: usize,
123    /// Set when the handle is dropped, telling the workers to discard the jobs still queued.
124    handle_dropped: Arc<AtomicBool>,
125}
126
127impl ProofWorkerHandle {
128    /// Spawns storage and account worker pools with dedicated database transactions.
129    ///
130    /// Returns a handle for submitting proof tasks to the worker pools.
131    /// Workers run until the handle is dropped.
132    ///
133    /// # Parameters
134    /// - `runtime`: The centralized runtime used to spawn blocking worker tasks
135    /// - `task_ctx`: Shared context with the factory of providers that serve the proofs. Workers
136    ///   request proofs with exact masks, as needed to produce trie updates from them.
137    /// - `worker_counts`: How many workers of each pool to spawn for this block, with a minimum of
138    ///   one worker of each kind
139    /// - `metrics`: Idle-time metric handles shared across blocks (with the metrics feature).
140    #[instrument(
141        name = "ProofWorkerHandle::new",
142        level = "debug",
143        target = "trie::proof_task",
144        skip_all
145    )]
146    pub fn new<Factory>(
147        runtime: &Runtime,
148        task_ctx: ProofTaskCtx<Factory>,
149        worker_counts: ProofWorkerCounts,
150        #[cfg(feature = "metrics")] metrics: ProofWorkerIdleMetrics,
151    ) -> Self
152    where
153        Factory:
154            DatabaseProviderROFactory<Provider: StateProofProvider> + Clone + Send + Sync + 'static,
155    {
156        let (result_tx, result_rx) = unbounded();
157        let (storage_work_tx, storage_work_rx) = unbounded();
158        let (account_work_tx, account_work_rx) = unbounded();
159
160        let storage_worker_count =
161            worker_counts.storage.max(1).min(runtime.proof_storage_worker_pool().num_threads());
162        let account_worker_count =
163            worker_counts.account.max(1).min(runtime.proof_account_worker_pool().num_threads());
164
165        let storage_availability = Arc::new(AvailabilitySheet::new(storage_worker_count));
166        let account_availability = Arc::new(AvailabilitySheet::new(account_worker_count));
167        let handle_dropped = Arc::new(AtomicBool::new(false));
168
169        debug!(
170            target: "trie::proof_task",
171            storage_worker_count,
172            account_worker_count,
173            "Spawning proof worker pools"
174        );
175
176        spawn_workers(
177            runtime,
178            ProofWorkerKind::Storage,
179            storage_worker_count,
180            ProofWorker {
181                task_ctx: task_ctx.clone(),
182                work_rx: storage_work_rx,
183                result_tx: result_tx.clone(),
184                availability: storage_availability.clone(),
185                handle_dropped: handle_dropped.clone(),
186                #[cfg(feature = "metrics")]
187                metrics: metrics.clone(),
188            },
189            ProofWorker::<_, StorageProofJob>::run,
190        );
191
192        spawn_workers(
193            runtime,
194            ProofWorkerKind::Account,
195            account_worker_count,
196            ProofWorker {
197                task_ctx,
198                work_rx: account_work_rx,
199                result_tx: result_tx.clone(),
200                availability: account_availability.clone(),
201                handle_dropped: handle_dropped.clone(),
202                #[cfg(feature = "metrics")]
203                metrics,
204            },
205            ProofWorker::<_, AccountProofJob>::run,
206        );
207
208        Self {
209            _result_tx: result_tx,
210            result_rx,
211            storage_work_tx,
212            account_work_tx,
213            storage_availability,
214            account_availability,
215            storage_worker_count,
216            account_worker_count,
217            handle_dropped,
218        }
219    }
220
221    /// Returns `true` if more than one storage worker is currently idle.
222    pub fn has_multiple_idle_storage_workers(&self) -> bool {
223        self.storage_availability.has_multiple_idle()
224    }
225
226    /// Returns `true` if more than one account worker is currently idle.
227    pub fn has_multiple_idle_account_workers(&self) -> bool {
228        self.account_availability.has_multiple_idle()
229    }
230
231    /// Returns the total number of storage workers in the pool.
232    pub const fn total_storage_workers(&self) -> usize {
233        self.storage_worker_count
234    }
235
236    /// Returns the total number of account workers in the pool.
237    pub const fn total_account_workers(&self) -> usize {
238        self.account_worker_count
239    }
240
241    /// Returns the receiver of job results.
242    ///
243    /// Results arrive in completion order. The receiver never disconnects while the handle is
244    /// alive.
245    pub const fn results(&self) -> &Receiver<ProofWorkerResult> {
246        &self.result_rx
247    }
248
249    /// Queues the proofs for `targets` and returns the number of jobs queued.
250    ///
251    /// The storage targets of each account become one storage job, and all account targets
252    /// together become one account job. Each job sends exactly one [`ProofWorkerResult`] to
253    /// [`Self::results`]. A storage job without slot targets proves only the account's storage
254    /// root node.
255    ///
256    /// Fails once a worker pool has shut down, which only happens after its workers reported start
257    /// failures on [`Self::results`].
258    pub fn dispatch(&self, targets: MultiProofTargetsV2) -> Result<usize, ProofWorkersUnavailable> {
259        let MultiProofTargetsV2 { account_targets, storage_targets } = targets;
260        let dispatched_at = Instant::now();
261        let mut jobs = 0;
262
263        for (hashed_address, targets) in storage_targets {
264            let job = StorageProofJob { hashed_address, targets, dispatched_at };
265            self.storage_work_tx.send(job).map_err(|_| ProofWorkersUnavailable)?;
266            jobs += 1;
267        }
268
269        if !account_targets.is_empty() {
270            let job = AccountProofJob { targets: account_targets, dispatched_at };
271            self.account_work_tx.send(job).map_err(|_| ProofWorkersUnavailable)?;
272            jobs += 1;
273        }
274
275        Ok(jobs)
276    }
277}
278
279impl Drop for ProofWorkerHandle {
280    fn drop(&mut self) {
281        self.handle_dropped.store(true, Ordering::Relaxed);
282    }
283}
284
285/// A message received from [`ProofWorkerHandle::results`]: the outcome of one queued job, or a
286/// worker's failure to start.
287///
288/// A storage job yields the storage proof of a single account and no account proofs. An account
289/// job yields account proofs and no storage proofs. A failed job does not stop its worker.
290pub type ProofWorkerResult = Result<DecodedMultiProofV2, StateRootTaskError>;
291
292/// Error returned by [`ProofWorkerHandle::dispatch`] when a worker pool has shut down.
293#[derive(Debug, Clone, Copy, thiserror::Error)]
294#[error("proof workers unavailable")]
295pub struct ProofWorkersUnavailable;
296
297/// How many workers [`ProofWorkerHandle::new`] spawns for a block.
298///
299/// Worker instances are recreated for each block on persistent thread pools. Each worker opens a
300/// database transaction and trie cursors, so the caller sizes the counts per block. Counts are
301/// clamped to at least one worker of each kind and capped by that kind's pool capacity.
302#[derive(Clone, Copy, Debug, PartialEq, Eq)]
303pub struct ProofWorkerCounts {
304    /// Number of storage proof workers to spawn.
305    pub storage: usize,
306    /// Number of account proof workers to spawn.
307    pub account: usize,
308}
309
310impl ProofWorkerCounts {
311    /// Creates counts for the given number of storage and account workers.
312    pub const fn new(storage: usize, account: usize) -> Self {
313        Self { storage, account }
314    }
315
316    /// Creates counts that use every thread of both pools.
317    pub fn full(runtime: &Runtime) -> Self {
318        Self::new(
319            runtime.proof_storage_worker_pool().num_threads(),
320            runtime.proof_account_worker_pool().num_threads(),
321        )
322    }
323}
324
325/// Data used for opening proof providers that is shared across all proof worker instances.
326#[derive(Clone, Debug)]
327pub struct ProofTaskCtx<Factory> {
328    /// The factory for creating state providers.
329    factory: Factory,
330    /// Maximum random jitter to apply before each proof computation (trie-debug only).
331    #[cfg(feature = "trie-debug")]
332    proof_jitter: Option<Duration>,
333}
334
335impl<Factory> ProofTaskCtx<Factory> {
336    /// Creates a new [`ProofTaskCtx`] with the given factory.
337    pub const fn new(factory: Factory) -> Self {
338        Self {
339            factory,
340            #[cfg(feature = "trie-debug")]
341            proof_jitter: None,
342        }
343    }
344
345    /// Sets the maximum proof jitter duration (trie-debug only).
346    #[cfg(feature = "trie-debug")]
347    pub const fn with_proof_jitter(mut self, jitter: Option<Duration>) -> Self {
348        self.proof_jitter = jitter;
349        self
350    }
351}
352
353/// The worker pool a proof worker belongs to.
354#[derive(Clone, Copy, Debug)]
355enum ProofWorkerKind {
356    Storage,
357    Account,
358}
359
360impl ProofWorkerKind {
361    /// Returns the runtime pool the workers of this kind run on.
362    fn pool(self, runtime: &Runtime) -> &WorkerPool {
363        match self {
364            Self::Storage => runtime.proof_storage_worker_pool(),
365            Self::Account => runtime.proof_account_worker_pool(),
366        }
367    }
368
369    /// Returns the name of the pool used in diagnostics.
370    const fn name(self) -> &'static str {
371        match self {
372            Self::Storage => "storage",
373            Self::Account => "account",
374        }
375    }
376
377    /// Returns the name of the blocking task that hosts the pool's workers.
378    const fn task_name(self) -> &'static str {
379        match self {
380            Self::Storage => "storage-workers",
381            Self::Account => "account-workers",
382        }
383    }
384
385    /// Returns the span for the worker with the given ID.
386    fn span(self, parent: &tracing::Span, worker_id: usize) -> tracing::Span {
387        match self {
388            Self::Storage => {
389                debug_span!(target: "trie::proof_task", parent: parent, "storage_worker", ?worker_id)
390            }
391            Self::Account => {
392                debug_span!(target: "trie::proof_task", parent: parent, "account_worker", ?worker_id)
393            }
394        }
395    }
396}
397
398/// Runs `run` as `worker_count` workers of the given kind on a blocking task.
399///
400/// A worker that fails to open its provider, at start or after a panicking job, sends a
401/// [`ProofWorkerError`] to the result channel and stops.
402fn spawn_workers<Factory, J>(
403    runtime: &Runtime,
404    kind: ProofWorkerKind,
405    worker_count: usize,
406    worker: ProofWorker<Factory, J>,
407    run: fn(&ProofWorker<Factory, J>, usize) -> ProviderResult<()>,
408) where
409    Factory: Send + Sync + 'static,
410    J: Send + 'static,
411{
412    let rt = runtime.clone();
413    let parent_span = tracing::Span::current();
414    runtime.spawn_blocking_named(kind.task_name(), move || {
415        let next_worker_id = AtomicUsize::new(0);
416        kind.pool(&rt).broadcast(worker_count, |_| {
417            let worker_id = next_worker_id.fetch_add(1, Ordering::Relaxed);
418            let _guard = kind.span(&parent_span, worker_id).entered();
419
420            if let Err(error) = run(&worker, worker_id) {
421                error!(
422                    target: "trie::proof_task",
423                    kind = kind.name(),
424                    worker_id,
425                    ?error,
426                    "Proof worker failed"
427                );
428                let error = StateRootTaskError::Other(Box::new(ProofWorkerError {
429                    kind,
430                    worker_id,
431                    source: error,
432                }));
433                // The send fails only once the handle is dropped, when nobody waits for results.
434                let _ = worker.result_tx.send(Err(error));
435            }
436        });
437    });
438}
439
440/// State shared by the workers of one pool, each holding its own database transaction.
441struct ProofWorker<Factory, J> {
442    /// Shared task context with database factory and prefix sets
443    task_ctx: ProofTaskCtx<Factory>,
444    /// Channel for receiving jobs
445    work_rx: Receiver<J>,
446    /// Sender for job results and worker failures
447    result_tx: Sender<ProofWorkerResult>,
448    /// Per-worker availability flags
449    availability: Arc<AvailabilitySheet>,
450    /// Set when the handle is dropped, after which nobody reads the results of queued jobs.
451    handle_dropped: Arc<AtomicBool>,
452    /// Metrics shared by all workers of the handle.
453    #[cfg(feature = "metrics")]
454    metrics: ProofWorkerIdleMetrics,
455}
456
457impl<Factory: DatabaseProviderROFactory, J> ProofWorker<Factory, J> {
458    /// Runs `process` with `provider` for every job until the handle is dropped and sends each
459    /// job's result, advertising the worker as busy while a job runs. Returns the total time spent
460    /// waiting for jobs.
461    ///
462    /// Jobs received after the handle is dropped are discarded without running, so a cancelled
463    /// block's backlog does not delay the workers of the next block on the same pools.
464    ///
465    /// A job that panics sends [`ProofJobError::Panicked`] instead of its result, so the job's
466    /// receiver fails instead of waiting for a result that never arrives. The worker then replaces
467    /// its provider, whose cached proof state must not be reused after a panic, and moves on to the
468    /// next job. Fails if the new provider cannot be opened.
469    fn process_jobs(
470        &self,
471        worker_id: usize,
472        mut provider: Factory::Provider,
473        mut process: impl FnMut(&Factory::Provider, J) -> ProofWorkerResult,
474    ) -> ProviderResult<Duration> {
475        // Count this worker as available only after successful initialization.
476        self.availability.mark_idle(worker_id);
477
478        let mut total_idle_time = Duration::ZERO;
479        let mut idle_start = Instant::now();
480
481        while let Ok(job) = self.work_rx.recv() {
482            if self.handle_dropped.load(Ordering::Relaxed) {
483                trace!(
484                    target: "trie::proof_task",
485                    worker_id,
486                    queued_jobs = self.work_rx.len() + 1,
487                    "Proof worker handle dropped, discarding queued jobs"
488                );
489                break
490            }
491            total_idle_time += idle_start.elapsed();
492            self.availability.mark_busy(worker_id);
493
494            #[cfg(feature = "trie-debug")]
495            if let Some(max_jitter) = self.task_ctx.proof_jitter {
496                let jitter =
497                    Duration::from_nanos(rand::random_range(0..=max_jitter.as_nanos() as u64));
498                trace!(
499                    target: "trie::proof_task",
500                    worker_id,
501                    jitter_us = jitter.as_micros(),
502                    "Proof worker applying proof jitter"
503                );
504                reth_concurrency::sync::thread::sleep(jitter);
505            }
506
507            match catch_unwind(AssertUnwindSafe(|| process(&provider, job))) {
508                Ok(result) => self.send_result(worker_id, result),
509                Err(panic) => {
510                    let message = panic
511                        .downcast_ref::<&str>()
512                        .copied()
513                        .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
514                        .unwrap_or("unknown panic")
515                        .to_string();
516                    error!(target: "trie::proof_task", worker_id, %message, "Proof job panicked");
517                    self.send_result(worker_id, Err(ProofJobError::Panicked { message }.into()));
518                    provider = self.task_ctx.factory.database_provider_ro()?;
519                }
520            }
521
522            self.availability.mark_idle(worker_id);
523            idle_start = Instant::now();
524        }
525
526        Ok(total_idle_time)
527    }
528
529    /// Sends a job result. The send fails only once the handle is dropped, when the result is no
530    /// longer needed.
531    fn send_result(&self, worker_id: usize, result: ProofWorkerResult) {
532        if self.result_tx.send(result).is_err() {
533            trace!(
534                target: "trie::proof_task",
535                worker_id,
536                "Proof result receiver dropped, discarding result"
537            );
538        }
539    }
540}
541
542impl<Factory> ProofWorker<Factory, StorageProofJob>
543where
544    Factory: DatabaseProviderROFactory<Provider: StateProofProvider>,
545{
546    /// Opens a database transaction and serves storage proof jobs until the handle is dropped.
547    fn run(&self, worker_id: usize) -> ProviderResult<()> {
548        let provider = self.task_ctx.factory.database_provider_ro()?;
549
550        trace!(target: "trie::proof_task", worker_id, "Storage worker started");
551
552        let mut storage_proofs_processed = 0u64;
553        let total_idle_time = self.process_jobs(worker_id, provider, |provider, job| {
554            let StorageProofJob { hashed_address, targets, dispatched_at } = job;
555            let _span = debug_span!(
556                target: "trie::proof_task",
557                "Storage proof calculation",
558                ?hashed_address,
559                targets = targets.len(),
560            )
561            .entered();
562            let proof_start = Instant::now();
563
564            let proof = provider.multiproof_v2(
565                MultiProofTargetsV2 {
566                    account_targets: Vec::new(),
567                    storage_targets: std::iter::once((hashed_address, targets)).collect(),
568                },
569                true,
570            );
571
572            trace!(
573                target: "trie::proof_task",
574                worker_id,
575                ?hashed_address,
576                proof_time_us = proof_start.elapsed().as_micros(),
577                dispatch_to_completion_us = dispatched_at.elapsed().as_micros(),
578                "Storage proof completed"
579            );
580
581            storage_proofs_processed += 1;
582            proof.map_err(|source| ProofJobError::Storage { hashed_address, source }.into())
583        })?;
584
585        trace!(
586            target: "trie::proof_task",
587            worker_id,
588            storage_proofs_processed,
589            total_idle_time_us = total_idle_time.as_micros(),
590            "Storage worker shutting down"
591        );
592
593        #[cfg(feature = "metrics")]
594        self.metrics.record_storage_worker_idle_time(total_idle_time);
595
596        Ok(())
597    }
598}
599
600impl<Factory> ProofWorker<Factory, AccountProofJob>
601where
602    Factory: DatabaseProviderROFactory<Provider: StateProofProvider>,
603{
604    /// Opens a database transaction and serves account proof jobs until the handle is dropped.
605    fn run(&self, worker_id: usize) -> ProviderResult<()> {
606        let provider = self.task_ctx.factory.database_provider_ro()?;
607
608        trace!(target: "trie::proof_task", worker_id, "Account worker started");
609
610        let mut account_proofs_processed = 0u64;
611        let total_idle_time = self.process_jobs(worker_id, provider, |provider, job| {
612            let AccountProofJob { targets, dispatched_at } = job;
613            let _span = debug_span!(
614                target: "trie::proof_task",
615                "Account proof calculation",
616                targets = targets.len(),
617            )
618            .entered();
619            let proof_start = Instant::now();
620
621            let proof = provider.multiproof_v2(
622                MultiProofTargetsV2 {
623                    account_targets: targets,
624                    storage_targets: Default::default(),
625                },
626                true,
627            );
628
629            trace!(
630                target: "trie::proof_task",
631                worker_id,
632                proof_time_us = proof_start.elapsed().as_micros(),
633                dispatch_to_completion_us = dispatched_at.elapsed().as_micros(),
634                "Account proof completed"
635            );
636
637            account_proofs_processed += 1;
638            proof.map_err(|source| ProofJobError::Account { source }.into())
639        })?;
640
641        trace!(
642            target: "trie::proof_task",
643            worker_id,
644            account_proofs_processed,
645            total_idle_time_us = total_idle_time.as_micros(),
646            "Account worker shutting down"
647        );
648
649        #[cfg(feature = "metrics")]
650        self.metrics.record_account_worker_idle_time(total_idle_time);
651
652        Ok(())
653    }
654}
655
656/// A queued storage proof of one account.
657#[derive(Debug)]
658struct StorageProofJob {
659    hashed_address: B256,
660    targets: Vec<ProofV2Target>,
661    dispatched_at: Instant,
662}
663
664/// A queued account proof.
665#[derive(Debug)]
666struct AccountProofJob {
667    targets: Vec<ProofV2Target>,
668    dispatched_at: Instant,
669}
670
671/// Context for a provider failure that stops a proof worker, at start or after a panicking job.
672#[derive(Debug, thiserror::Error)]
673#[error("{} worker {worker_id}: {source}", kind.name())]
674struct ProofWorkerError {
675    kind: ProofWorkerKind,
676    worker_id: usize,
677    #[source]
678    source: ProviderError,
679}
680
681/// A failed proof job, identified by the proof it calculated.
682#[derive(Debug, thiserror::Error)]
683enum ProofJobError {
684    #[error("storage proof of account {hashed_address}: {source}")]
685    Storage {
686        hashed_address: B256,
687        #[source]
688        source: ProviderError,
689    },
690    #[error("account proof: {source}")]
691    Account {
692        #[source]
693        source: ProviderError,
694    },
695    #[error("proof job panicked: {message}")]
696    Panicked { message: String },
697}
698
699impl From<ProofJobError> for StateRootTaskError {
700    fn from(error: ProofJobError) -> Self {
701        Self::Other(Box::new(error))
702    }
703}
704
705#[cfg(test)]
706mod tests {
707    use super::*;
708    use reth_chainspec::ChainSpec;
709    use reth_concurrency::sync::channel::{bounded, RecvTimeoutError};
710    use reth_provider::test_utils::create_test_provider_factory_with_chain_spec;
711    use std::sync::Arc;
712
713    fn test_ctx<Factory>(factory: Factory) -> ProofTaskCtx<Factory> {
714        ProofTaskCtx::new(factory)
715    }
716
717    /// Ensures `ProofWorkerHandle::new` spawns workers correctly.
718    #[reth_concurrency::test]
719    fn spawn_proof_workers_creates_handle() {
720        let chain_spec = Arc::new(ChainSpec::default());
721        let provider_factory = create_test_provider_factory_with_chain_spec(chain_spec);
722        let anchor_hash = reth_db_common::init::init_genesis(&provider_factory).unwrap();
723        let factory = reth_storage_overlay::OverlayStateProviderFactory::new(
724            provider_factory,
725            reth_storage_overlay::OverlayManager::<
726                reth_ethereum_primitives::EthPrimitives,
727            >::default()
728            .overlay_builder(anchor_hash),
729        );
730        let ctx = test_ctx(factory.clone());
731
732        let runtime = reth_tasks::Runtime::test();
733        let proof_worker_handle = ProofWorkerHandle::new(
734            &runtime,
735            ctx,
736            ProofWorkerCounts::full(&runtime),
737            #[cfg(feature = "metrics")]
738            Default::default(),
739        );
740        let proof_result_rx = proof_worker_handle.results().clone();
741
742        // Workers shut down automatically when the handle is dropped.
743        drop(proof_worker_handle);
744
745        // Keep the database alive until both pools release their providers.
746        assert_eq!(
747            proof_result_rx.recv_timeout(Duration::from_secs(30)).unwrap_err(),
748            RecvTimeoutError::Disconnected
749        );
750        drop(factory);
751    }
752
753    /// Ensures a single pool serves quarter, half, and full-capacity worker counts.
754    #[reth_concurrency::test]
755    fn single_pool_serves_fractional_worker_counts() {
756        let provider_factory =
757            create_test_provider_factory_with_chain_spec(Arc::new(ChainSpec::default()));
758        let anchor_hash = reth_db_common::init::init_genesis(&provider_factory).unwrap();
759        let factory = reth_storage_overlay::OverlayStateProviderFactory::new(
760            provider_factory,
761            reth_storage_overlay::OverlayManager::<reth_ethereum_primitives::EthPrimitives>::default()
762                .overlay_builder(anchor_hash),
763        );
764        let ctx = test_ctx(factory);
765
766        let runtime = reth_tasks::RuntimeBuilder::new(
767            reth_tasks::RuntimeConfig::default()
768                .with_rayon(reth_tasks::RayonConfig { cpu_threads: Some(2), ..Default::default() }),
769        )
770        .build()
771        .unwrap();
772        let pool_threads = runtime.proof_storage_worker_pool().num_threads();
773        assert_eq!(pool_threads, 8);
774        assert_eq!(runtime.proof_account_worker_pool().num_threads(), pool_threads);
775
776        for counts in [
777            ProofWorkerCounts::new(0, 0),
778            ProofWorkerCounts::new(pool_threads / 4, pool_threads / 4),
779            ProofWorkerCounts::new(pool_threads / 2, pool_threads / 2),
780            ProofWorkerCounts::full(&runtime),
781            ProofWorkerCounts::new(pool_threads + 1, pool_threads + 2),
782        ] {
783            let proof_worker_handle = ProofWorkerHandle::new(
784                &runtime,
785                ctx.clone(),
786                counts,
787                #[cfg(feature = "metrics")]
788                Default::default(),
789            );
790            assert_eq!(
791                proof_worker_handle.total_storage_workers(),
792                counts.storage.max(1).min(pool_threads)
793            );
794            assert_eq!(
795                proof_worker_handle.total_account_workers(),
796                counts.account.max(1).min(pool_threads)
797            );
798
799            let address = B256::ZERO;
800            let storage_targets = MultiProofTargetsV2 {
801                storage_targets: std::iter::once((address, vec![ProofV2Target::new(B256::ZERO)]))
802                    .collect(),
803                ..Default::default()
804            };
805            assert_eq!(proof_worker_handle.dispatch(storage_targets).unwrap(), 1);
806            let storage_proof = proof_worker_handle
807                .results()
808                .recv_timeout(Duration::from_secs(30))
809                .unwrap()
810                .unwrap();
811            assert!(storage_proof.account_proofs.is_empty());
812            assert!(storage_proof.storage_proofs.contains_key(&address));
813
814            let account_targets = MultiProofTargetsV2 {
815                account_targets: vec![ProofV2Target::new(address)],
816                ..Default::default()
817            };
818            assert_eq!(proof_worker_handle.dispatch(account_targets).unwrap(), 1);
819            let account_proof = proof_worker_handle
820                .results()
821                .recv_timeout(Duration::from_secs(30))
822                .unwrap()
823                .unwrap();
824            assert!(account_proof.storage_proofs.is_empty());
825
826            let results = proof_worker_handle.results().clone();
827            drop(proof_worker_handle);
828            // Every broadcast holds a result sender until all its workers have exited. An
829            // initialization error is a message here, rather than a successful shutdown.
830            assert!(matches!(
831                results.recv_timeout(Duration::from_secs(30)),
832                Err(RecvTimeoutError::Disconnected)
833            ));
834        }
835    }
836
837    /// Ensures jobs still queued when the handle is dropped are discarded, so a cancelled block's
838    /// backlog does not hold the pools that the next block's workers queue behind.
839    #[reth_concurrency::test]
840    fn dropped_handle_discards_queued_jobs() {
841        let provider_factory =
842            create_test_provider_factory_with_chain_spec(Arc::new(ChainSpec::default()));
843        let anchor_hash = reth_db_common::init::init_genesis(&provider_factory).unwrap();
844        let factory = reth_storage_overlay::OverlayStateProviderFactory::new(
845            provider_factory,
846            reth_storage_overlay::OverlayManager::<reth_ethereum_primitives::EthPrimitives>::default()
847                .overlay_builder(anchor_hash),
848        );
849        let runtime = reth_tasks::Runtime::test();
850
851        // Occupy both pools' blocking tasks so the workers start only after the handle is dropped.
852        let (release_tx, release_rx) = bounded::<()>(0);
853        for kind in [ProofWorkerKind::Storage, ProofWorkerKind::Account] {
854            let release_rx = release_rx.clone();
855            runtime.spawn_blocking_named(kind.task_name(), move || {
856                release_rx.recv().unwrap_err();
857            });
858        }
859
860        let proof_worker_handle = ProofWorkerHandle::new(
861            &runtime,
862            test_ctx(factory.clone()),
863            ProofWorkerCounts::new(1, 1),
864            #[cfg(feature = "metrics")]
865            Default::default(),
866        );
867        let targets = MultiProofTargetsV2 {
868            account_targets: vec![ProofV2Target::new(B256::ZERO)],
869            storage_targets: (0..8u8)
870                .map(|byte| (B256::repeat_byte(byte), vec![ProofV2Target::new(B256::ZERO)]))
871                .collect(),
872        };
873        assert_eq!(proof_worker_handle.dispatch(targets).unwrap(), 9);
874
875        let results = proof_worker_handle.results().clone();
876        drop(proof_worker_handle);
877        drop(release_tx);
878
879        assert_eq!(
880            results.recv_timeout(Duration::from_secs(30)).unwrap_err(),
881            RecvTimeoutError::Disconnected
882        );
883        drop(factory);
884    }
885}