Skip to main content

reth_trie/verify/
pipeline.rs

1//! Ordered storage scheduling, root delivery, shared findings, and background task lifetime.
2
3use super::{Output, StorageJob, StorageWorker};
4use crate::{hashed_cursor::HashedStorageCursor, trie_cursor::TrieStorageCursor};
5use alloy_primitives::{B256, U256};
6use reth_concurrency::sync::{
7    channel::{self, Receiver, Sender},
8    thread::{self, JoinHandle},
9};
10use reth_execution_errors::StateRootError;
11use reth_storage_errors::db::DatabaseError;
12use std::{
13    panic::{catch_unwind, AssertUnwindSafe},
14    sync::Arc,
15};
16
17/// Owns storage scheduling and one pending root announcement for the account producer.
18#[derive(Debug)]
19pub(super) struct StoragePipeline {
20    context: WorkerContext,
21    background: Option<JoinHandle<()>>,
22    announcements: Receiver<(B256, Receiver<B256>)>,
23    next: Option<(B256, Receiver<B256>)>,
24}
25
26impl StoragePipeline {
27    /// Spawns the background thread which walks `addresses` and verifies their storage on one
28    /// thread per worker.
29    ///
30    /// # Panics
31    ///
32    /// Panics if `workers` is empty or `storage_lookahead` is zero.
33    pub(super) fn spawn<L, T, H, TX>(
34        addresses: L,
35        workers: Vec<StorageWorker<T, H, TX>>,
36        context: WorkerContext,
37        storage_lookahead: usize,
38    ) -> Result<Self, DatabaseError>
39    where
40        L: Iterator<Item = Result<StorageJob, DatabaseError>> + Send + 'static,
41        T: TrieStorageCursor + Send + 'static,
42        H: HashedStorageCursor<Value = U256> + Send + 'static,
43        TX: Send + 'static,
44    {
45        assert!(!workers.is_empty(), "verification requires storage workers");
46        assert!(storage_lookahead > 0, "storage lookahead must be positive");
47        // The account producer retains one announcement outside the queue. Reserving its
48        // slot here bounds all dispatched roots, including that lookahead, by the limit.
49        let (announcements_tx, announcements) = channel::bounded(storage_lookahead - 1);
50        let scheduler = StorageScheduler { addresses, workers, context: context.clone() };
51        let span = tracing::Span::current();
52        let background = thread::Builder::new()
53            .name("trie-lookahead".into())
54            .spawn(move || {
55                let _entered = span.enter();
56                scheduler.run(announcements_tx);
57            })
58            .map_err(|error| DatabaseError::Custom(Arc::new(error)))?;
59        Ok(Self { context, background: Some(background), announcements, next: None })
60    }
61
62    /// Returns the next root in address order up to and including `up_to`, or all remaining
63    /// roots if `up_to` is `None`. Returns `None` when the bound is reached, scanning completes
64    /// without another root, or verification is cancelled. Findings are consumed independently.
65    /// A missing worker result waits for cancellation by the findings consumer after it receives
66    /// the worker error, rather than replacing the original error with a channel error.
67    pub(super) fn next_root(&mut self, up_to: Option<B256>) -> Option<(B256, B256)> {
68        if self.context.is_cancelled() {
69            return None;
70        }
71        if self.next.is_none() {
72            self.next = channel::select! {
73                recv(self.announcements) -> announcement => announcement.ok(),
74                recv(self.context.cancel) -> _ => return None,
75            };
76        }
77        let Some((address, root)) = &self.next else { return None };
78        if up_to.is_some_and(|bound| *address > bound) {
79            return None;
80        }
81        let root = channel::select! {
82            recv(root) -> root => root,
83            recv(self.context.cancel) -> _ => return None,
84        };
85        match root {
86            Ok(root) => {
87                let address = *address;
88                self.next = None;
89                Some((address, root))
90            }
91            Err(_) => {
92                // A failing worker drops its root sender before WorkerContext::run reports the
93                // original error. The findings consumer cancels us after receiving that error;
94                // do not race it with a synthetic channel error or skip the missing root.
95                match self.context.cancel.recv() {
96                    Ok(()) | Err(_) => None,
97                }
98            }
99        }
100    }
101
102    /// Joins storage producers while the caller's iterator continues consuming findings.
103    pub(super) fn finish(&mut self) {
104        self.join();
105    }
106
107    fn join(&mut self) {
108        // Re-raising while already unwinding would abort the process.
109        if let Some(background) = self.background.take() &&
110            let Err(panic) = background.join() &&
111            !thread::panicking()
112        {
113            std::panic::resume_unwind(panic);
114        }
115    }
116}
117
118impl Drop for StoragePipeline {
119    fn drop(&mut self) {
120        self.join();
121    }
122}
123
124/// Body of the background thread: walks storage addresses and keeps the workers supplied with
125/// jobs.
126struct StorageScheduler<L, T, H, TX> {
127    addresses: L,
128    workers: Vec<StorageWorker<T, H, TX>>,
129    context: WorkerContext,
130}
131
132impl<L, T, H, TX> StorageScheduler<L, T, H, TX>
133where
134    L: Iterator<Item = Result<StorageJob, DatabaseError>>,
135    T: TrieStorageCursor + Send,
136    H: HashedStorageCursor<Value = U256> + Send,
137    TX: Send,
138{
139    fn run(mut self, announcements: Sender<(B256, Receiver<B256>)>) {
140        let context = self.context.clone();
141        // Retain the sender across setup failures until their error has been reported.
142        let mut announcements = Some(announcements);
143        context.run(|| {
144            let worker_count = self.workers.len();
145            let pool = reth_tasks::WorkerPool::new(worker_count, "trie-verify");
146            // Reserve backlog space before dispatch so a slow early root can always finish
147            // without competing with later results for space.
148            let (jobs_tx, jobs_rx) = channel::bounded(worker_count * 2);
149            pool.in_place_scope(|scope| {
150                for worker in self.workers.drain(..) {
151                    let jobs = jobs_rx.clone();
152                    let context = self.context.clone();
153                    let span = tracing::Span::current();
154                    scope.spawn(move |_| {
155                        let _entered = span.enter();
156                        context.run(|| worker.run(jobs, &context));
157                    });
158                }
159                drop(jobs_rx);
160                // Close announcements before joining workers: account EOF must not depend on
161                // workers finishing their findings sends.
162                // Keep scan failure ordered before EOF, including when `produce` panics.
163                if let Some(sender) = &announcements {
164                    context.run(|| self.produce(jobs_tx, sender));
165                }
166                drop(announcements.take());
167            });
168            Ok(())
169        });
170    }
171
172    fn produce(
173        &mut self,
174        jobs: Sender<(B256, Option<Sender<B256>>)>,
175        announcements: &Sender<(B256, Receiver<B256>)>,
176    ) -> Result<(), StateRootError> {
177        for job in self.addresses.by_ref() {
178            let job = job?;
179            let root = if job.root_required {
180                let (sender, receiver) = channel::bounded(1);
181                // Announce in scan order before dispatch, regardless of completion order.
182                if !self.context.send(announcements, (job.address, receiver)) {
183                    return Ok(());
184                }
185                Some(sender)
186            } else {
187                None
188            };
189            if !self.context.send(&jobs, (job.address, root)) {
190                return Ok(());
191            }
192        }
193        Ok(())
194    }
195}
196
197/// Shared cancellation and reporting policy for background threads.
198///
199/// Verification is cancelled once the `cancel` sender is dropped; nothing is ever sent on it.
200#[derive(Clone, Debug)]
201pub(super) struct WorkerContext {
202    events: Sender<Result<Output, StateRootError>>,
203    cancel: Receiver<()>,
204}
205
206impl WorkerContext {
207    pub(super) const fn new(
208        events: Sender<Result<Output, StateRootError>>,
209        cancel: Receiver<()>,
210    ) -> Self {
211        Self { events, cancel }
212    }
213
214    /// Sends `value`, returning `false` if it was not sent because verification was cancelled or
215    /// `sender` disconnected.
216    pub(super) fn send<T>(&self, sender: &Sender<T>, value: T) -> bool {
217        channel::send_or_cancel(sender, value, &self.cancel).is_ok()
218    }
219
220    /// Receives the next job. Returns `None` once `jobs` is exhausted, and may return `None` early
221    /// if verification was cancelled.
222    pub(super) fn receive<T>(&self, jobs: &Receiver<T>) -> Option<T> {
223        channel::select! {
224            recv(jobs) -> job => job.ok(),
225            recv(self.cancel) -> _ => None,
226        }
227    }
228
229    /// Returns whether verification was cancelled.
230    pub(super) fn is_cancelled(&self) -> bool {
231        self.cancel.try_recv() == Err(channel::TryRecvError::Disconnected)
232    }
233
234    /// Reports one finding, applying backpressure until it is consumed or verification stops.
235    pub(super) fn report_one(&self, output: Output) -> bool {
236        self.send(&self.events, Ok(output))
237    }
238
239    /// Runs `work`, reporting its error or panic as a verification error.
240    pub(super) fn run(&self, work: impl FnOnce() -> Result<(), StateRootError>) {
241        let result = catch_unwind(AssertUnwindSafe(work)).unwrap_or_else(|panic| {
242            let message = panic
243                .downcast_ref::<&str>()
244                .copied()
245                .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
246                .unwrap_or("unknown panic");
247            Err(DatabaseError::Other(format!("trie verification thread panicked: {message}"))
248                .into())
249        });
250        // The error is only lost if verification was already cancelled, in which case the
251        // verifier has stopped reading results.
252        if let Err(error) = result {
253            self.send(&self.events, Err(error));
254        }
255    }
256}