Skip to main content

reth_engine_tree/tree/state_root_strategy/
sparse_trie.rs

1//! Sparse Trie task related functionality.
2
3use std::{
4    any::Any,
5    panic::{self, AssertUnwindSafe},
6    sync::Arc,
7};
8
9use super::{StateRootComputeOutcome, StateRootMessage};
10use alloy_primitives::{
11    map::{hash_map::Entry, B256Map},
12    B256,
13};
14use alloy_rlp::{Decodable, Encodable};
15use metrics::{Gauge, Histogram};
16use reth_concurrency::sync::{
17    channel::{self, mpsc, select_biased, Receiver, Sender},
18    rayon,
19    time::FastInstant as Instant,
20};
21use reth_metrics::Metrics;
22use reth_primitives_traits::Account;
23use reth_tasks::Runtime;
24use reth_trie::{
25    updates::TrieUpdates, DecodedMultiProofV2, HashedPostState, TrieAccount, EMPTY_ROOT_HASH,
26    TRIE_ACCOUNT_RLP_MAX_SIZE,
27};
28use reth_trie_common::{MultiProofTargetsV2, ProofTrieNode, ProofV2Target, ProofV2TargetParent};
29use reth_trie_parallel::{
30    error::StateRootTaskError,
31    proof_task::{ProofWorkerHandle, ProofWorkerResult},
32};
33use reth_trie_sparse::{
34    errors::{
35        SparseStateTrieErrorKind, SparseStateTrieResult, SparseTrieErrorKind, SparseTrieResult,
36    },
37    ArenaParallelSparseTrie, DeferredDrops, LeafUpdate, RevealableSparseTrie, SparseStateTrie,
38    SparseTrie, TrieNodeEpoch,
39};
40use tracing::{debug, debug_span, error, instrument, trace_span};
41
42/// Computes a block's state root by applying streamed updates to an in-memory [`SparseStateTrie`].
43/// Updates that reach a blinded node stay pending while the task fetches the missing proof. The
44/// account trie stays on this task's thread; storage tries can be moved into independent rayon
45/// jobs.
46///
47/// # Message flow
48///
49/// The task coordinates three incoming streams:
50///
51/// 1. **Execution and prewarming:** [`Self::run_hashing_task`] receives [`StateRootMessage`]s,
52///    hashes raw state updates, and forwards [`SparseTrieTaskMessage`]s to [`Self::updates`] in
53///    receive order. `HashedState` supplies changed values; `PrefetchProofs` supplies
54///    [`LeafUpdate::Touched`] hints that must not overwrite changed values. The task buffers these
55///    leaf updates before applying them in batches.
56/// 2. **Proof workers:** blinded paths become [`MultiProofTargetsV2`] chunks, which
57///    [`ProofWorkerHandle::dispatch`] splits into independent account and per-address storage jobs.
58///    The task coalesces the [`ProofWorkerResult`]s returned through
59///    [`ProofWorkerHandle::results`], reveals account proofs locally, and queues storage proofs on
60///    the corresponding address' [`StorageTrieState`].
61/// 3. **Storage jobs:** [`Self::spawn_storage_jobs`] moves each [`StorageTrieWork`] into a rayon
62///    closure. A pass reveals queued proofs, applies unblocked leaves, and hashes the storage trie
63///    once its pending leaves are drained. It sends [`StorageJobMessage::Done`] via
64///    [`Self::storage_done_tx`] to [`Self::storage_done_rx`], returning ownership of the payload
65///    along with newly discovered proof targets, cache counters, and any error. Small or
66///    target-only passes run inline and apply the same output directly.
67///
68/// [`Self::run`] selects between these streams and cancellation. After handling a message,
69/// [`Self::make_progress`] collects queued job returns, applies buffered updates, dispatches proof
70/// requests and storage jobs, and promotes account updates whose storage roots are available.
71/// Proof workers fetch nodes; storage jobs reveal and modify the owned storage trie. Neither
72/// mutates the account trie.
73///
74/// # Storage ownership
75///
76/// On first use, an address' storage trie moves out of [`SparseStateTrie`] into an idle entry.
77/// There is at most one job per address, and no shared mutable access to its trie:
78///
79/// ```text
80///                    dispatch: move StorageTrieWork to rayon
81///   Idle --------------------------------------------------------> InFlight
82///   (task owns trie)                                               (job owns trie)
83///        ^                                                              |
84///        +--------------------------------------------------------------+
85///                    Done: restore payload and merge buffered arrivals
86/// ```
87///
88/// In `Idle`, new proofs and leaf updates make the payload ready for another pass. An inline pass
89/// keeps it in `Idle`. In `InFlight`, the task holds only [`InFlightStorage`] buffers for new
90/// arrivals; the job owns the trie, earlier pending leaves, proofs, and fetched-target cache.
91/// When `Done` arrives, newer changed values and deletions override older pending values, while
92/// touch hints preserve them. Buffered work can then trigger another pass.
93///
94/// `Idle` describes ownership, not completion: a payload can still have leaves blocked on a proof.
95/// Blocked leaves alone do not trigger another pass; new updates or that address' own proof nodes
96/// make it ready again. Account updates wait while their storage trie is in flight or still has
97/// pending leaves, so they cannot use an incomplete storage root.
98///
99/// # Task lifecycle
100///
101/// ```text
102///   Streaming -- FinishedStateUpdates --> Draining -- no pending trie work --> Finalize
103///       |                                    |
104///       +------------- cancellation ---------+--> Canceled
105/// ```
106///
107/// The finish marker publishes the accumulated [`HashedPostState`] through
108/// [`Self::final_hashed_state_tx`] and ends consumption of the update stream. Draining continues
109/// to receive proof results and storage-job returns; late prefetch hints are ignored. Closing
110/// the update channel before the marker is an error, while closing it afterward is harmless.
111///
112/// Finalization waits for all leaf updates, account promotions, and checked-out storage tries.
113/// It restores the storage tries to [`SparseStateTrie`], computes the final root and trie updates,
114/// and returns [`StateRootComputeOutcome`]. The caller publishes that result before consuming
115/// the task with [`Self::into_trie_for_reuse`], which also releases the retained job buffers.
116///
117/// Dropping the consumer's cancel guard makes [`Self::run`] return
118/// [`StateRootTaskError::Canceled`]. Teardown through [`Self::into_cleared_trie`] disconnects the
119/// storage return channel, so late jobs drop their payloads when sending fails. Proof and trie
120/// errors fail the calculation; [`StorageJobMessage::Panicked`] resumes the worker's panic on
121/// this task's thread. During draining, pending updates with no remaining source of progress
122/// produce [`StateRootTaskError::Stalled`].
123pub(super) struct SparseTrieCacheTask<A = ArenaParallelSparseTrie, S = ArenaParallelSparseTrie> {
124    /// Receives updates from execution and prewarming.
125    updates: Receiver<SparseTrieTaskMessage>,
126    /// Fires (by disconnecting) when the consumer drops its cancel guard, meaning nobody is
127    /// waiting for the result anymore. This is the teardown path for a task whose pending
128    /// work never drains, since the updates channel closing is a normal end of stream.
129    cancel_rx: Receiver<()>,
130    /// Sender half for the channel to send final hashed state to.
131    final_hashed_state_tx: Option<mpsc::Sender<Arc<HashedPostState>>>,
132    /// `SparseStateTrie` used for computing the state root.
133    trie: SparseStateTrie<A, S>,
134    /// The parent block's state root.
135    parent_state_root: B256,
136    /// The new epoch assigned to nodes modified by this task.
137    new_epoch: TrieNodeEpoch,
138    /// Handle to the proof worker pools (storage and account).
139    proof_worker_handle: ProofWorkerHandle,
140
141    /// The size of proof targets chunk to spawn in one calculation.
142    /// If None, chunking is disabled and all targets are processed in a single proof.
143    chunk_size: usize,
144    /// If this number is exceeded and chunking is enabled, then this will override whether or not
145    /// there are any active workers and force chunking across workers. This is to prevent tasks
146    /// which are very long from hitting a single worker.
147    max_targets_for_chunking: usize,
148
149    /// Account trie updates.
150    account_updates: B256Map<LeafUpdate>,
151
152    /// Account updates that are buffered but were not yet applied to the trie.
153    new_account_updates: B256Map<LeafUpdate>,
154    /// Storage updates that are buffered but were not yet applied to the trie.
155    new_storage_updates: B256Map<B256Map<LeafUpdate>>,
156    /// Account updates that are blocked by storage root calculation or account reveal.
157    ///
158    /// Those are being moved into `account_updates` once storage roots
159    /// are revealed and/or calculated.
160    ///
161    /// Invariant: for each entry in `pending_account_updates` account must either be already
162    /// revealed in the trie or have an entry in `account_updates`.
163    ///
164    /// Values can be either of:
165    ///   - None: account had a storage update and is awaiting storage root calculation and/or
166    ///     account node reveal to complete.
167    ///   - Some(_): account was changed/destroyed and is awaiting storage root calculation/reveal
168    ///     to complete.
169    pending_account_updates: B256Map<Option<Option<Account>>>,
170    /// Cache of account proof targets that were already fetched/requested from the proof workers.
171    /// Account to the broadest requested parent context (an unknown parent sorts before every
172    /// known parent).
173    fetched_account_targets: B256Map<ProofV2TargetParent>,
174    /// Reusable buffer for RLP encoding of accounts.
175    account_rlp_buf: Vec<u8>,
176    /// Whether the last state update has been received.
177    finished_state_updates: bool,
178    /// Accumulated account leaf update cache hits.
179    account_cache_hits: u64,
180    /// Accumulated account leaf update cache misses.
181    account_cache_misses: u64,
182    /// Accumulated storage leaf update cache hits.
183    storage_cache_hits: u64,
184    /// Accumulated storage leaf update cache misses.
185    storage_cache_misses: u64,
186    /// Pending proof targets queued for dispatch to proof workers.
187    pending_targets: PendingTargets,
188    /// Proof jobs queued on the workers whose results have not been received yet.
189    in_flight_proof_jobs: usize,
190    /// Everything the task knows about a storage trie touched by this block: the trie itself, its
191    /// queued leaf updates, the proof nodes waiting to be revealed into it and its proof target
192    /// cache. See [`StorageTrieState`].
193    ///
194    /// Invariant: an address is either listed here or has its trie in the state trie's storage
195    /// trie map, never both. Everything that reads a storage trie goes through this map until
196    /// [`Self::return_storage_tries`] hands them all back.
197    storage: B256Map<StorageTrieState<S>>,
198    /// Storage job buffers kept alive after returning their tries, until the result is sent.
199    storage_to_drop: B256Map<StorageTrieState<S>>,
200    /// Number of storage tries currently owned by a job running off this thread.
201    storage_in_flight: usize,
202    /// Sender handed to storage jobs. Kept alive by the task so the receiver never disconnects.
203    storage_done_tx: Sender<StorageJobMessage<S>>,
204    /// Receives storage tries coming back from jobs spawned by this task.
205    storage_done_rx: Receiver<StorageJobMessage<S>>,
206    /// Number of pending execution/prewarming updates received but not yet passed to
207    /// `update_leaves`.
208    pending_updates: usize,
209    /// Whether the first buffered leaf batch has been applied.
210    initial_updates_applied: bool,
211    /// Combined final hashed state.
212    ///
213    /// Sparse trie task observes and hashes all state updates, allowing it to cheaply construct a
214    /// final [`HashedPostState`] and share it with main engine thread without requiring any extra
215    /// hashing work.
216    final_hashed_state: HashedPostState,
217
218    /// Metrics for the sparse trie.
219    metrics: SparseTrieTaskMetrics,
220}
221
222impl<A, S> SparseTrieCacheTask<A, S>
223where
224    A: SparseTrie + Default,
225    S: SparseTrie + Default + Clone + 'static,
226{
227    /// Creates a new sparse trie, pre-populating with an existing [`SparseStateTrie`].
228    #[expect(clippy::too_many_arguments)]
229    pub(super) fn new_with_trie(
230        executor: &Runtime,
231        updates: Receiver<StateRootMessage>,
232        cancel_rx: Receiver<()>,
233        final_hashed_state_tx: mpsc::Sender<Arc<HashedPostState>>,
234        proof_worker_handle: ProofWorkerHandle,
235        metrics: SparseTrieTaskMetrics,
236        trie: SparseStateTrie<A, S>,
237        parent_state_root: B256,
238        new_epoch: TrieNodeEpoch,
239        chunk_size: usize,
240    ) -> Self {
241        let (hashed_state_tx, hashed_state_rx) = channel::unbounded();
242        let (storage_done_tx, storage_done_rx) = channel::unbounded();
243
244        let parent_span = tracing::Span::current();
245        let hashing_metrics = metrics.clone();
246        executor.spawn_blocking_named("trie-hashing", move || {
247            let _span = trace_span!(parent: &parent_span, "run_hashing_task").entered();
248            Self::run_hashing_task(updates, hashed_state_tx, hashing_metrics)
249        });
250
251        Self {
252            updates: hashed_state_rx,
253            cancel_rx,
254            proof_worker_handle,
255            final_hashed_state_tx: Some(final_hashed_state_tx),
256            trie,
257            parent_state_root,
258            new_epoch,
259            chunk_size,
260            max_targets_for_chunking: DEFAULT_MAX_TARGETS_FOR_CHUNKING,
261            account_updates: Default::default(),
262            new_account_updates: Default::default(),
263            new_storage_updates: Default::default(),
264            pending_account_updates: Default::default(),
265            fetched_account_targets: Default::default(),
266            account_rlp_buf: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),
267            finished_state_updates: Default::default(),
268            account_cache_hits: 0,
269            account_cache_misses: 0,
270            storage_cache_hits: 0,
271            storage_cache_misses: 0,
272            pending_targets: Default::default(),
273            in_flight_proof_jobs: 0,
274            storage: Default::default(),
275            storage_to_drop: Default::default(),
276            storage_in_flight: 0,
277            storage_done_tx,
278            storage_done_rx,
279            pending_updates: Default::default(),
280            initial_updates_applied: false,
281            final_hashed_state: Default::default(),
282            metrics,
283        }
284    }
285
286    /// Runs the hashing task that drains updates from the channel and converts them to
287    /// `HashedPostState` in parallel, until it forwards the finish marker or the channel closes.
288    fn run_hashing_task(
289        updates: Receiver<StateRootMessage>,
290        hashed_state_tx: Sender<SparseTrieTaskMessage>,
291        metrics: SparseTrieTaskMetrics,
292    ) {
293        let mut total_idle_time = std::time::Duration::ZERO;
294        let mut idle_start = Instant::now();
295
296        while let Ok(message) = updates.recv() {
297            total_idle_time += idle_start.elapsed();
298
299            let finished = matches!(message, StateRootMessage::FinishedStateUpdates);
300            let msg = match message {
301                StateRootMessage::PrefetchProofs(targets) => {
302                    SparseTrieTaskMessage::PrefetchProofs(targets)
303                }
304                StateRootMessage::StateUpdate(state) => {
305                    let _span = trace_span!(target: "engine::tree::payload_processor::sparse_trie", "hashing_state_update").entered();
306                    let hashed = reth_execution_types::state_update_to_hashed_post_state(&state);
307                    SparseTrieTaskMessage::HashedState(hashed)
308                }
309                StateRootMessage::FinishedStateUpdates => {
310                    SparseTrieTaskMessage::FinishedStateUpdates
311                }
312                StateRootMessage::HashedStateUpdate(state) => {
313                    SparseTrieTaskMessage::HashedState(state)
314                }
315            };
316            // Only hints can follow the finish marker, and the task ignores them. Returning here
317            // frees the shared hashing thread for the next block's task while a hint sender, such
318            // as a prewarm task queued behind earlier blocks, is still alive.
319            if hashed_state_tx.send(msg).is_err() || finished {
320                break;
321            }
322
323            idle_start = Instant::now();
324        }
325
326        metrics.hashing_task_idle_time_seconds.record(total_idle_time.as_secs_f64());
327    }
328
329    /// Returns the trie for reuse in the next payload built on top of this one.
330    ///
331    /// Should be called after the state root result has been sent.
332    pub(super) fn into_trie_for_reuse(self) -> (SparseStateTrie<A, S>, DeferredDrops) {
333        debug_assert!(
334            self.storage.is_empty(),
335            "storage tries must be back before the trie is preserved"
336        );
337        let Self { mut trie, .. } = self;
338        let deferred = trie.take_deferred_drops();
339        (trie, deferred)
340    }
341
342    /// Clears the trie, discarding all state.
343    ///
344    /// Use this when the payload was invalid or cancelled - we don't want to preserve
345    /// potentially invalid trie state, but we keep the allocations for reuse.
346    pub(super) fn into_cleared_trie(self) -> (SparseStateTrie<A, S>, DeferredDrops) {
347        let Self { mut trie, storage_done_rx, storage, .. } = self;
348        // Disconnect first so tries still out with a job are dropped by that job instead of here.
349        drop(storage_done_rx);
350        for (address, state) in storage {
351            if let StorageTrieState::Idle(work) = state {
352                trie.insert_storage_trie(address, work.trie);
353            }
354        }
355        trie.clear();
356        let deferred = trie.take_deferred_drops();
357        (trie, deferred)
358    }
359
360    /// Runs the sparse trie task to completion.
361    ///
362    /// This waits for new incoming [`SparseTrieTaskMessage`]s, applies updates
363    /// to the trie and schedules proof fetching when needed.
364    ///
365    /// After the finish marker, drains the remaining proof and storage work until all trie updates
366    /// are applied and all checked-out storage tries have returned. See the [task
367    /// lifecycle](Self#task-lifecycle).
368    #[instrument(
369        name = "SparseTrieCacheTask::run",
370        level = "debug",
371        target = "engine::tree::payload_processor::sparse_trie",
372        skip_all
373    )]
374    pub(super) fn run(&mut self) -> Result<StateRootComputeOutcome, StateRootTaskError> {
375        let now = Instant::now();
376
377        let mut total_idle_time = std::time::Duration::ZERO;
378        let mut idle_start = Instant::now();
379        let mut done = false;
380        let mut finalized_hashed_state = None;
381
382        // Streaming phase: updates are still arriving. Ends when the finish marker is
383        // processed. Only producers hold update senders, so the channel closing before the
384        // marker means they died without finishing the stream.
385        while !self.finished_state_updates {
386            let mut t = Instant::now();
387            select_biased! {
388                recv(self.updates) -> message => {
389                    let wake = Instant::now();
390                    total_idle_time += wake.duration_since(idle_start);
391                    self.metrics
392                        .sparse_trie_channel_wait_duration_histogram
393                        .record(wake.duration_since(t));
394
395                    let update = message.map_err(|_| StateRootTaskError::Other(
396                        "updates channel disconnected before state root calculation".into(),
397                    ))?;
398                    if let Some(hashed_state) = self.on_message(update) {
399                        finalized_hashed_state = Some(hashed_state);
400                    }
401                    self.pending_updates += 1;
402                },
403                recv(self.proof_worker_handle.results()) -> message => {
404                    let wake = Instant::now();
405                    total_idle_time += wake.duration_since(idle_start);
406                    self.metrics
407                        .sparse_trie_channel_wait_duration_histogram
408                        .record(wake.duration_since(t));
409                    t = wake;
410
411                    let Ok(result) = message else {
412                        unreachable!("proof worker results never disconnect while the handle is alive")
413                    };
414                    self.on_proof_worker_result(result, &mut t)?;
415                },
416                recv(self.storage_done_rx) -> message => {
417                    let wake = Instant::now();
418                    total_idle_time += wake.duration_since(idle_start);
419                    self.metrics
420                        .sparse_trie_channel_wait_duration_histogram
421                        .record(wake.duration_since(t));
422
423                    let Ok(returned) = message else {
424                        unreachable!("we own the sender half")
425                    };
426                    self.on_storage_job_message(returned)?;
427                },
428                recv(self.cancel_rx) -> _ => return Err(StateRootTaskError::Canceled),
429            }
430
431            done = self.make_progress()?;
432            idle_start = Instant::now();
433        }
434
435        // Draining phase: the marker is the last message read from the updates channel, so
436        // after it only proof results, storage-job returns, and cancellation can occur. The
437        // update channel closing when producers drop their senders is not observed here, and late
438        // hints are ignored: with all updates known, prefetching has nothing left to help.
439        while !done {
440            let mut t = Instant::now();
441            select_biased! {
442                recv(self.proof_worker_handle.results()) -> message => {
443                    let wake = Instant::now();
444                    total_idle_time += wake.duration_since(idle_start);
445                    self.metrics
446                        .sparse_trie_channel_wait_duration_histogram
447                        .record(wake.duration_since(t));
448                    t = wake;
449
450                    let Ok(result) = message else {
451                        unreachable!("proof worker results never disconnect while the handle is alive")
452                    };
453                    self.on_proof_worker_result(result, &mut t)?;
454                },
455                recv(self.storage_done_rx) -> message => {
456                    let wake = Instant::now();
457                    total_idle_time += wake.duration_since(idle_start);
458                    self.metrics
459                        .sparse_trie_channel_wait_duration_histogram
460                        .record(wake.duration_since(t));
461
462                    let Ok(returned) = message else {
463                        unreachable!("we own the sender half")
464                    };
465                    self.on_storage_job_message(returned)?;
466                },
467                recv(self.cancel_rx) -> _ => return Err(StateRootTaskError::Canceled),
468            }
469
470            done = self.make_progress()?;
471            idle_start = Instant::now();
472        }
473
474        debug_assert_eq!(
475            self.storage_in_flight, 0,
476            "completion must wait for every checked out storage trie"
477        );
478        self.metrics.sparse_trie_idle_time_seconds.record(total_idle_time.as_secs_f64());
479
480        debug!(target: "engine::root", "All proofs processed, ending calculation");
481
482        let start = Instant::now();
483        self.return_storage_tries();
484        let (state_root, trie_updates) = match self.trie.root_with_updates(self.new_epoch) {
485            Ok(result) => result,
486            Err(err)
487                if matches!(
488                    err.kind(),
489                    SparseStateTrieErrorKind::Sparse(SparseTrieErrorKind::Blind)
490                ) =>
491            {
492                // A still-blind account trie means this block never changed state, so preserve
493                // the cached parent root instead of fetching and revealing
494                // the unchanged root node.
495                (self.parent_state_root, TrieUpdates::default())
496            }
497            Err(err) => return Err(StateRootTaskError::Other(err.into())),
498        };
499
500        let end = Instant::now();
501        self.metrics.sparse_trie_final_update_duration_histogram.record(end.duration_since(start));
502        self.metrics.sparse_trie_total_duration_histogram.record(end.duration_since(now));
503
504        self.metrics.sparse_trie_account_cache_hits.record(self.account_cache_hits as f64);
505        self.metrics.sparse_trie_account_cache_misses.record(self.account_cache_misses as f64);
506        self.metrics.sparse_trie_storage_cache_hits.record(self.storage_cache_hits as f64);
507        self.metrics.sparse_trie_storage_cache_misses.record(self.storage_cache_misses as f64);
508        self.account_cache_hits = 0;
509        self.account_cache_misses = 0;
510        self.storage_cache_hits = 0;
511        self.storage_cache_misses = 0;
512
513        Ok(StateRootComputeOutcome {
514            state_root,
515            trie_updates: Arc::new(trie_updates),
516            hashed_state: finalized_hashed_state
517                .expect("finished state updates publish the hashed post state"),
518        })
519    }
520
521    /// Handles a received proof worker result: coalesces everything already queued, reveals the
522    /// proof in the trie, and records timing metrics.
523    fn on_proof_worker_result(
524        &mut self,
525        result: ProofWorkerResult,
526        t: &mut Instant,
527    ) -> Result<(), StateRootTaskError> {
528        let mut proofs = self.complete_proof_job(result)?;
529        while let Ok(next) = self.proof_worker_handle.results().try_recv() {
530            proofs.extend(self.complete_proof_job(next)?);
531        }
532
533        let phase_end = Instant::now();
534        self.metrics
535            .sparse_trie_proof_coalesce_duration_histogram
536            .record(phase_end.duration_since(*t));
537        *t = phase_end;
538
539        self.on_proofs(proofs)?;
540        self.metrics.sparse_trie_reveal_multiproof_duration_histogram.record(t.elapsed());
541        Ok(())
542    }
543
544    /// Applies buffered updates to the trie and dispatches proof targets.
545    ///
546    /// Messages queued after the finish marker are best-effort hints and are not actionable.
547    /// Returns `true` once the finish marker was received and all pending trie work is done.
548    fn make_progress(&mut self) -> Result<bool, StateRootTaskError> {
549        // Absorb a whole burst of returns before the scans below, so one batch of storage jobs
550        // costs one promotion pass rather than one per trie.
551        self.drain_returned_storage_tries()?;
552
553        let updates_queued = !self.finished_state_updates && !self.updates.is_empty();
554
555        if !updates_queued && self.proof_worker_handle.results().is_empty() {
556            // If we don't have any pending messages, we can spend some time on computing
557            // storage roots and promoting account updates.
558            self.dispatch_pending_targets()?;
559            let t = Instant::now();
560            self.process_new_updates()?;
561            self.promote_pending_account_updates()?;
562            self.metrics.sparse_trie_process_updates_duration_histogram.record(t.elapsed());
563
564            if self.finished_state_updates && !self.has_pending_sparse_trie_updates() {
565                return Ok(true);
566            }
567
568            self.dispatch_pending_targets()?;
569            self.ensure_not_stalled(updates_queued)?;
570
571            // If there's still no pending updates spend some time pre-computing the account
572            // trie upper hashes
573            if self.proof_worker_handle.results().is_empty() {
574                self.trie.calculate_subtries(self.new_epoch);
575            }
576        } else if !updates_queued {
577            // If we don't have any pending updates, apply them to the trie,
578            let t = Instant::now();
579            self.process_new_updates()?;
580            self.metrics.sparse_trie_process_updates_duration_histogram.record(t.elapsed());
581            self.dispatch_pending_targets()?;
582        } else if !self.initial_updates_applied && self.pending_updates >= INITIAL_UPDATE_BATCH_SIZE
583        {
584            // Start proof fetching before a continuously arriving state stream drains. Later
585            // batches retain the usual coalescing policy to avoid repeatedly sorting small maps.
586            let t = Instant::now();
587            self.process_new_updates()?;
588            self.metrics.sparse_trie_process_updates_duration_histogram.record(t.elapsed());
589            self.dispatch_pending_targets()?;
590        } else if self.pending_targets.len() > self.chunk_size {
591            // Make sure to dispatch targets if we've accumulated a lot of them.
592            self.dispatch_pending_targets()?;
593        }
594        Ok(false)
595    }
596
597    /// Processes a [`SparseTrieTaskMessage`] from the hashing task.
598    fn on_message(&mut self, message: SparseTrieTaskMessage) -> Option<Arc<HashedPostState>> {
599        match message {
600            SparseTrieTaskMessage::PrefetchProofs(targets) => {
601                self.on_prewarm_targets(targets);
602                None
603            }
604            SparseTrieTaskMessage::HashedState(hashed_state) => {
605                self.on_hashed_state_update(hashed_state);
606                None
607            }
608            SparseTrieTaskMessage::FinishedStateUpdates => {
609                let hashed_state = Arc::new(core::mem::take(&mut self.final_hashed_state));
610                let _ = self.final_hashed_state_tx.take().unwrap().send(Arc::clone(&hashed_state));
611                self.finished_state_updates = true;
612                Some(hashed_state)
613            }
614        }
615    }
616
617    #[instrument(
618        level = "trace",
619        target = "engine::tree::payload_processor::sparse_trie",
620        skip_all
621    )]
622    fn on_prewarm_targets(&mut self, targets: MultiProofTargetsV2) {
623        for target in targets.account_targets {
624            // Only touch accounts that are not yet present in the updates set.
625            self.new_account_updates.entry(target.key()).or_insert(LeafUpdate::Touched);
626        }
627
628        for (address, slots) in targets.storage_targets {
629            if !slots.is_empty() {
630                // Look up outer map once per address instead of once per slot.
631                let new_updates = self.new_storage_updates.entry(address).or_default();
632                for slot in slots {
633                    // Only touch storages that are not yet present in the updates set.
634                    new_updates.entry(slot.key()).or_insert(LeafUpdate::Touched);
635                }
636            }
637
638            // Touch corresponding account leaf to make sure its revealed in accounts trie for
639            // storage root update.
640            self.new_account_updates.entry(address).or_insert(LeafUpdate::Touched);
641        }
642    }
643
644    /// Processes a hashed state update and encodes all state changes as trie updates.
645    #[instrument(
646        level = "trace",
647        target = "engine::tree::payload_processor::sparse_trie",
648        skip_all
649    )]
650    #[allow(clippy::clone_on_copy)]
651    fn on_hashed_state_update(&mut self, hashed_state_update: HashedPostState) {
652        for (&address, storage) in &hashed_state_update.storages {
653            if !storage.storage.is_empty() {
654                // Look up the outer map once per address instead of once per slot.
655                let new_updates = self.new_storage_updates.entry(address).or_default();
656
657                for (&slot, &value) in &storage.storage {
658                    let encoded = if value.is_zero() {
659                        Vec::new()
660                    } else {
661                        alloy_rlp::encode_fixed_size(&value).to_vec()
662                    };
663                    new_updates.insert(slot, LeafUpdate::Changed(encoded));
664                }
665            }
666
667            // Make sure account is tracked in `account_updates` so that it is revealed in accounts
668            // trie for storage root update.
669            self.new_account_updates.entry(address).or_insert(LeafUpdate::Touched);
670
671            // Make sure account is tracked in `pending_account_updates` so that once storage root
672            // is computed, it will be updated in the accounts trie.
673            self.pending_account_updates.entry(address).or_insert(None);
674        }
675
676        for (&address, account) in &hashed_state_update.accounts {
677            // Track account as touched.
678            //
679            // This might overwrite an existing update, which is fine, because storage root from it
680            // is already tracked in the trie and can be easily fetched again.
681            self.new_account_updates.insert(address, LeafUpdate::Touched);
682
683            // Track account in `pending_account_updates` so that once storage root is computed,
684            // it will be updated in the accounts trie.
685            self.pending_account_updates.insert(address, Some(account.clone()));
686        }
687
688        self.final_hashed_state.extend(hashed_state_update);
689    }
690
691    fn on_proofs(&mut self, proofs: DecodedMultiProofV2) -> Result<(), StateRootTaskError> {
692        self.reveal_proof_result(proofs).map_err(|e| StateRootTaskError::Other(e.into()))
693    }
694
695    /// Reveals a proof batch.
696    ///
697    /// The account trie is revealed here because it can never be checked out. Storage proof nodes
698    /// are queued on their address' entry and revealed by the job that runs for it next.
699    fn reveal_proof_result(&mut self, proofs: DecodedMultiProofV2) -> SparseStateTrieResult<()> {
700        let DecodedMultiProofV2 { account_proofs, storage_proofs } = proofs;
701
702        self.queue_storage_proofs(storage_proofs);
703        // Get the workers going before spending this thread on the account trie.
704        self.run_ready_storage_work()?;
705
706        self.trie.reveal_account_proof_nodes(account_proofs)
707    }
708
709    /// Queues storage proof nodes on the entry for the address they belong to.
710    fn queue_storage_proofs(&mut self, storage_proofs: B256Map<Vec<ProofTrieNode>>) {
711        let mut revealed_nodes = 0;
712        for (address, mut nodes) in storage_proofs {
713            if nodes.is_empty() {
714                continue;
715            }
716            revealed_nodes += nodes.len();
717
718            match self.storage_trie_state_mut(address) {
719                StorageTrieState::Idle(work) => work.queue_proofs(&mut nodes),
720                StorageTrieState::InFlight(in_flight) => in_flight.proofs.append(&mut nodes),
721            }
722        }
723        self.trie.record_revealed_storage_nodes(revealed_nodes);
724    }
725
726    /// Returns the storage trie state for `address`, checking its storage trie out of the state
727    /// trie the first time the address is touched by this block.
728    fn storage_trie_state_mut(&mut self, address: B256) -> &mut StorageTrieState<S> {
729        let Self { storage, trie, .. } = self;
730        storage.entry(address).or_insert_with(|| {
731            StorageTrieState::Idle(Box::new(StorageTrieWork::new(
732                trie.take_or_create_storage_trie(&address),
733            )))
734        })
735    }
736
737    /// Accounts for a received proof job result and returns its proofs.
738    fn complete_proof_job(
739        &mut self,
740        result: ProofWorkerResult,
741    ) -> Result<DecodedMultiProofV2, StateRootTaskError> {
742        let proofs = result?;
743        debug_assert!(
744            self.in_flight_proof_jobs > 0,
745            "received proof result without an in-flight proof job"
746        );
747        // Saturates so that a broken invariant in release builds still lets the stall check fire.
748        self.in_flight_proof_jobs = self.in_flight_proof_jobs.saturating_sub(1);
749        Ok(proofs)
750    }
751
752    /// Applies buffered input and runs ready storage work, including work buffered while a job
753    /// was in flight even if no new input messages were received.
754    fn process_new_updates(&mut self) -> SparseTrieResult<()> {
755        self.apply_new_updates()?;
756        self.run_ready_storage_work()
757    }
758
759    /// Applies new account updates and queues new storage updates on their address' entry.
760    fn apply_new_updates(&mut self) -> SparseTrieResult<()> {
761        if self.pending_updates == 0 {
762            return Ok(());
763        }
764
765        let _span = debug_span!("process_new_updates").entered();
766        self.pending_updates = 0;
767        self.initial_updates_applied = true;
768
769        // Queue the new storage updates on their entries; the jobs apply them to the tries.
770        let Self { storage, trie, new_storage_updates, .. } = self;
771        for (address, new) in new_storage_updates.drain() {
772            if new.is_empty() {
773                continue;
774            }
775
776            let state = storage.entry(address).or_insert_with(|| {
777                StorageTrieState::Idle(Box::new(StorageTrieWork::new(
778                    trie.take_or_create_storage_trie(&address),
779                )))
780            });
781            match state {
782                StorageTrieState::Idle(work) => work.queue_updates(new),
783                StorageTrieState::InFlight(in_flight) => {
784                    merge_leaf_updates(&mut in_flight.updates, new)
785                }
786            }
787        }
788
789        // Apply the new account updates to the accounts trie, which is never checked out.
790        self.process_account_leaf_updates(true)?;
791
792        for (address, new) in self.new_account_updates.drain() {
793            match self.account_updates.entry(address) {
794                Entry::Occupied(mut entry) => {
795                    if new.is_changed() {
796                        entry.insert(new);
797                    }
798                }
799                Entry::Vacant(entry) => {
800                    entry.insert(new);
801                }
802            }
803        }
804
805        Ok(())
806    }
807
808    /// Runs a pass over every idle storage trie that has something to do: proof nodes to reveal,
809    /// leaf updates that were not tried against the current state of the trie yet.
810    ///
811    /// Each pass owns its address' payload for its whole duration, so the passes are independent
812    /// of each other and of this thread. Most of them are handed to the rayon pool; the ones that
813    /// would cost more in handoff than in work stay here, see [`StorageTrieWork::is_target_only`]
814    /// and [`INLINE_STORAGE_WORK_UNITS`].
815    #[instrument(
816        level = "trace",
817        target = "engine::tree::payload_processor::sparse_trie",
818        skip_all
819    )]
820    fn run_ready_storage_work(&mut self) -> SparseTrieResult<()> {
821        let mut ready = Vec::new();
822        let mut job_units = 0;
823        for (address, state) in &self.storage {
824            let StorageTrieState::Idle(work) = state else { continue };
825            if !work.has_work() {
826                continue;
827            }
828            if !work.is_target_only() {
829                job_units += work.proofs.len() + work.pending.len();
830            }
831            ready.push(*address);
832        }
833        if ready.is_empty() {
834            return Ok(())
835        }
836
837        let inline_round = job_units <= INLINE_STORAGE_WORK_UNITS;
838        let new_epoch = self.new_epoch;
839        let retain_updates = self.trie.retains_updates();
840        let started = Instant::now();
841        let mut jobs = Vec::new();
842        for address in ready {
843            let state = self.storage.get_mut(&address).expect("entry was just seen");
844            let StorageTrieState::Idle(work) = state else {
845                unreachable!("an idle trie is only checked out from here")
846            };
847
848            if inline_round || work.is_target_only() {
849                let output = work.run(new_epoch, retain_updates);
850                self.apply_storage_output(address, output)?;
851                continue;
852            }
853
854            let StorageTrieState::Idle(work) = core::mem::replace(
855                state,
856                StorageTrieState::InFlight(Box::new(InFlightStorage::new(started))),
857            ) else {
858                unreachable!("just matched")
859            };
860            self.storage_in_flight += 1;
861            jobs.push(StorageTrieJob { address, work });
862        }
863
864        self.spawn_storage_jobs(jobs);
865
866        Ok(())
867    }
868
869    /// Records what a storage pass produced: the proof targets it discovered and its cache
870    /// counters. Returns the error the pass stopped at, if any.
871    fn apply_storage_output(
872        &mut self,
873        address: B256,
874        output: StorageWorkOutput,
875    ) -> SparseTrieResult<()> {
876        let StorageWorkOutput { targets, cache_hits, cache_misses, result } = output;
877
878        self.storage_cache_hits += cache_hits;
879        self.storage_cache_misses += cache_misses;
880        if !targets.is_empty() {
881            self.pending_targets.extend_storage_targets(&address, targets);
882        }
883
884        result
885    }
886
887    /// Invokes `update_leaves` for the accounts trie and collects any new targets.
888    ///
889    /// Returns whether any updates were drained (applied to the trie).
890    #[instrument(
891        level = "trace",
892        target = "engine::tree::payload_processor::sparse_trie",
893        skip_all
894    )]
895    fn process_account_leaf_updates(&mut self, new: bool) -> SparseTrieResult<bool> {
896        let account_updates =
897            if new { &mut self.new_account_updates } else { &mut self.account_updates };
898
899        let updates_len_before = account_updates.len();
900
901        self.trie.trie_mut().update_leaves(account_updates, |target, parent| {
902            match self.fetched_account_targets.entry(target) {
903                Entry::Occupied(mut entry) => {
904                    if parent < *entry.get() {
905                        entry.insert(parent);
906                        self.pending_targets
907                            .push_account_target(ProofV2Target::new(target).with_parent(parent));
908                    }
909                }
910                Entry::Vacant(entry) => {
911                    entry.insert(parent);
912                    self.pending_targets
913                        .push_account_target(ProofV2Target::new(target).with_parent(parent));
914                }
915            }
916        })?;
917
918        let updates_len_after = account_updates.len();
919        self.account_cache_hits += (updates_len_before - updates_len_after) as u64;
920        self.account_cache_misses += updates_len_after as u64;
921
922        Ok(updates_len_after < updates_len_before)
923    }
924
925    /// Hands checked out storage tries to the rayon pool in chunks.
926    ///
927    /// Chunking amortizes the spawn cost over a batch, while each trie is still sent back on its
928    /// own so promotion does not wait for the rest of the chunk.
929    fn spawn_storage_jobs(&self, mut jobs: Vec<StorageTrieJob<S>>) {
930        if jobs.is_empty() {
931            return;
932        }
933
934        let parent_span = debug_span!("spawn_storage_jobs", n = jobs.len());
935        let chunk_len = storage_job_chunk_len(jobs.len());
936        let new_epoch = self.new_epoch;
937        let retain_updates = self.trie.retains_updates();
938        while !jobs.is_empty() {
939            let chunk = jobs.split_off(jobs.len().saturating_sub(chunk_len));
940            let storage_done_tx = self.storage_done_tx.clone();
941            let parent_span = parent_span.clone();
942            rayon::spawn(move || {
943                let _enter = debug_span!(
944                    target: "engine::tree::payload_processor::sparse_trie",
945                    parent: &parent_span,
946                    "storage_jobs",
947                    n = chunk.len(),
948                )
949                .entered();
950                for job in chunk {
951                    let address = job.address;
952                    let message = match panic::catch_unwind(AssertUnwindSafe(|| {
953                        job.run(new_epoch, retain_updates)
954                    })) {
955                        Ok(done) => StorageJobMessage::Done(done),
956                        Err(payload) => StorageJobMessage::Panicked { address, payload },
957                    };
958                    if storage_done_tx.send(message).is_err() {
959                        // Nobody is waiting for the result anymore, drop the rest here.
960                        return;
961                    }
962                }
963            });
964        }
965    }
966
967    /// Handles a message from a storage job: takes a finished payload back, or resumes a panic
968    /// that happened on the job thread here, where it fails this task like an inline panic would.
969    fn on_storage_job_message(&mut self, message: StorageJobMessage<S>) -> SparseTrieResult<()> {
970        match message {
971            StorageJobMessage::Done(done) => self.on_storage_trie_returned(done),
972            StorageJobMessage::Panicked { address, payload } => {
973                if self.storage.remove(&address).is_some() {
974                    self.storage_in_flight -= 1;
975                }
976                panic::resume_unwind(payload)
977            }
978        }
979    }
980
981    /// Puts a payload back into its entry once its job finished, folding in everything that
982    /// arrived for the address while it was gone.
983    fn on_storage_trie_returned(&mut self, done: StorageTrieJobDone<S>) -> SparseTrieResult<()> {
984        let StorageTrieJobDone { address, work, output } = done;
985
986        let Entry::Occupied(mut entry) = self.storage.entry(address) else {
987            unreachable!("a returned payload was checked out of its entry")
988        };
989        let StorageTrieState::InFlight(in_flight) = entry.insert(StorageTrieState::Idle(work))
990        else {
991            unreachable!("a checked out address stays in flight until its job returns")
992        };
993        let started = in_flight.started;
994        let StorageTrieState::Idle(work) = entry.into_mut() else { unreachable!("just inserted") };
995        work.take_buffered(*in_flight);
996        self.storage_in_flight -= 1;
997        self.metrics.sparse_trie_storage_job_duration_histogram.record(started.elapsed());
998
999        self.apply_storage_output(address, output)
1000    }
1001
1002    /// Takes back every payload whose job has already finished, without blocking.
1003    fn drain_returned_storage_tries(&mut self) -> SparseTrieResult<()> {
1004        while let Ok(message) = self.storage_done_rx.try_recv() {
1005            self.on_storage_job_message(message)?;
1006        }
1007
1008        Ok(())
1009    }
1010
1011    /// Puts every storage trie back into the sparse state trie.
1012    ///
1013    /// The final root and everything after it - trie updates, preservation, pruning - reads the
1014    /// storage tries through [`SparseStateTrie`], so no trie may remain in the task's storage map.
1015    fn return_storage_tries(&mut self) {
1016        let mut storage = core::mem::take(&mut self.storage);
1017        for (address, state) in &mut storage {
1018            let StorageTrieState::Idle(work) = state else {
1019                unreachable!("completion must wait for every storage job")
1020            };
1021            self.trie.insert_storage_trie(*address, core::mem::take(&mut work.trie));
1022        }
1023        // Keep the maps and proof buffers until the result has been published.
1024        self.storage_to_drop = storage;
1025    }
1026
1027    /// Promotes the pending account updates whose storage root is already available into proper
1028    /// leaf updates for the accounts trie.
1029    ///
1030    /// Accounts whose trie is still checked out stay pending and are promoted by a later call,
1031    /// once the payload has come back.
1032    #[instrument(
1033        level = "trace",
1034        target = "engine::tree::payload_processor::sparse_trie",
1035        skip_all
1036    )]
1037    fn promote_pending_account_updates(&mut self) -> SparseTrieResult<()> {
1038        self.process_account_leaf_updates(false)?;
1039
1040        if self.pending_account_updates.is_empty() {
1041            return Ok(());
1042        }
1043
1044        let new_epoch = self.new_epoch;
1045        loop {
1046            let span = trace_span!("promote_updates", promoted = tracing::field::Empty).entered();
1047            // Now handle pending account updates that can be upgraded to a proper update.
1048            let account_rlp_buf = &mut self.account_rlp_buf;
1049            let mut num_promoted = 0;
1050            self.pending_account_updates.retain(|addr, account| {
1051                let updated_storage = match self.storage.get_mut(addr) {
1052                    // The payload is out with a job, so the root is not readable yet.
1053                    Some(StorageTrieState::InFlight(_)) => return true,
1054                    Some(StorageTrieState::Idle(work)) if work.updated => Some(work),
1055                    _ => None,
1056                };
1057
1058                if let Some(work) = updated_storage {
1059                    if !work.pending.is_empty() {
1060                        // If account has pending storage updates, it is still pending.
1061                        return true;
1062                    } else if let Some(account) = account.take() {
1063                        let storage_root = work.trie.root(new_epoch).expect("updates are drained, storage trie should be revealed by now");
1064                        let encoded = encode_account_leaf_value(account, storage_root, account_rlp_buf);
1065                        self.account_updates.insert(*addr, LeafUpdate::Changed(encoded));
1066                        num_promoted += 1;
1067                        return false;
1068                    }
1069                }
1070
1071                // Get the current account state either from the trie or from latest account update.
1072                let trie_account = match self.account_updates.get(addr) {
1073                    Some(LeafUpdate::Changed(encoded)) => {
1074                        Some(encoded).filter(|encoded| !encoded.is_empty())
1075                    }
1076                    // Needs to be revealed first
1077                    Some(LeafUpdate::Touched) => return true,
1078                    None => self.trie.get_account_value(addr),
1079                };
1080
1081                let trie_account = trie_account.map(|value| TrieAccount::decode(&mut &value[..]).expect("invalid account RLP"));
1082
1083                let (account, storage_root) = if let Some(account) = account.take() {
1084                    // If account is Some(_) here it means it didn't have any storage updates
1085                    // and we can fetch the storage root directly from the account trie.
1086                    //
1087                    // If it did have storage updates, we would've had processed it above when iterating over storage tries.
1088                    let storage_root = trie_account.map(|account| account.storage_root).unwrap_or(EMPTY_ROOT_HASH);
1089
1090                    (account, storage_root)
1091                } else {
1092                    // An address with no entry was not touched by this block, so its trie, if any,
1093                    // is still in the state trie with the root it was preserved with.
1094                    let storage_root = match self.storage.get_mut(addr) {
1095                        Some(StorageTrieState::Idle(work)) => work.trie.root(new_epoch),
1096                        Some(StorageTrieState::InFlight(_)) => unreachable!("returned above"),
1097                        None => self.trie.storage_root(addr, new_epoch),
1098                    };
1099                    (trie_account.map(Into::into), storage_root.expect("account had storage updates that were applied to its trie, storage root must be revealed by now"))
1100                };
1101
1102                let encoded = encode_account_leaf_value(account, storage_root, account_rlp_buf);
1103                self.account_updates.insert(*addr, LeafUpdate::Changed(encoded));
1104                num_promoted += 1;
1105
1106                false
1107            });
1108            span.record("promoted", num_promoted);
1109            drop(span);
1110
1111            // Only exit when no new updates are processed.
1112            //
1113            // We need to keep iterating if any updates are being drained because that might
1114            // indicate that more pending account updates can be promoted.
1115            if num_promoted == 0 || !self.process_account_leaf_updates(false)? {
1116                break
1117            }
1118        }
1119
1120        Ok(())
1121    }
1122
1123    fn dispatch_pending_targets(&mut self) -> Result<(), StateRootTaskError> {
1124        if self.pending_targets.is_empty() {
1125            return Ok(())
1126        }
1127
1128        let _span = trace_span!("dispatch_pending_targets").entered();
1129        let (targets, chunking_length) = self.pending_targets.take();
1130        let mut dispatch_error = None;
1131        dispatch_with_chunking(
1132            targets,
1133            chunking_length,
1134            self.chunk_size,
1135            self.max_targets_for_chunking,
1136            self.proof_worker_handle.has_multiple_idle_account_workers(),
1137            self.proof_worker_handle.has_multiple_idle_storage_workers(),
1138            MultiProofTargetsV2::chunks,
1139            |proof_targets| {
1140                if dispatch_error.is_some() {
1141                    return;
1142                }
1143
1144                // A chunk becomes several jobs, and an address whose slots span chunks gets one
1145                // storage job per chunk. Every job returns its own result.
1146                match self.proof_worker_handle.dispatch(proof_targets) {
1147                    Ok(jobs) => self.in_flight_proof_jobs += jobs,
1148                    Err(e) => {
1149                        error!("failed to dispatch proofs: {e}");
1150                        dispatch_error = Some(StateRootTaskError::Other(Box::new(e)));
1151                    }
1152                }
1153            },
1154        );
1155
1156        if let Some(error) = dispatch_error {
1157            return Err(error)
1158        }
1159
1160        Ok(())
1161    }
1162
1163    fn has_pending_sparse_trie_updates(&self) -> bool {
1164        !self.account_updates.is_empty() ||
1165            !self.pending_account_updates.is_empty() ||
1166            self.storage.values().any(|state| state.is_pending())
1167    }
1168
1169    /// Returns whether any idle storage trie has a pass to run, which is progress that has not been
1170    /// made yet rather than a stall.
1171    fn has_ready_storage_work(&self) -> bool {
1172        self.storage.values().any(|state| match state {
1173            StorageTrieState::Idle(work) => work.has_work(),
1174            StorageTrieState::InFlight(_) => false,
1175        })
1176    }
1177
1178    /// Errors when pending trie updates remain but nothing can deliver them: no update
1179    /// messages are queued, no proof targets are queued or in flight, no proof results
1180    /// are waiting, and no storage pass is running or waiting to run.
1181    ///
1182    /// `updates_queued` is passed in instead of reading `self.updates` directly, because in
1183    /// the draining phase the updates channel is not read anymore and may hold ignored late
1184    /// hints that must not mask a stall.
1185    fn ensure_not_stalled(&self, updates_queued: bool) -> Result<(), StateRootTaskError> {
1186        if self.finished_state_updates &&
1187            !updates_queued &&
1188            self.pending_updates == 0 &&
1189            self.pending_targets.is_empty() &&
1190            self.in_flight_proof_jobs == 0 &&
1191            self.proof_worker_handle.results().is_empty() &&
1192            self.storage_in_flight == 0 &&
1193            !self.has_ready_storage_work() &&
1194            self.has_pending_sparse_trie_updates()
1195        {
1196            const MAX_STALLED_PROOF_TARGETS_TO_LOG: usize = 5;
1197
1198            let mut account_targets = self
1199                .account_updates
1200                .keys()
1201                .map(|target| (*target, self.fetched_account_targets.get(target).copied()))
1202                .collect::<Vec<_>>();
1203            account_targets.sort_unstable();
1204            let account_targets_truncated =
1205                account_targets.len().saturating_sub(MAX_STALLED_PROOF_TARGETS_TO_LOG);
1206            account_targets.truncate(MAX_STALLED_PROOF_TARGETS_TO_LOG);
1207
1208            let mut storage_targets = self
1209                .storage
1210                .iter()
1211                .filter_map(|(address, state)| match state {
1212                    StorageTrieState::Idle(work) => Some((address, work)),
1213                    StorageTrieState::InFlight(_) => None,
1214                })
1215                .flat_map(|(address, work)| {
1216                    work.pending
1217                        .keys()
1218                        .map(move |target| (*address, *target, work.fetched.get(target).copied()))
1219                })
1220                .collect::<Vec<_>>();
1221            storage_targets.sort_unstable();
1222            let storage_targets_truncated =
1223                storage_targets.len().saturating_sub(MAX_STALLED_PROOF_TARGETS_TO_LOG);
1224            storage_targets.truncate(MAX_STALLED_PROOF_TARGETS_TO_LOG);
1225
1226            error!(
1227                ?account_targets,
1228                account_targets_truncated,
1229                ?storage_targets,
1230                storage_targets_truncated,
1231                "sparse trie task stalled: pending updates remain but no proof targets are queued or in flight"
1232            );
1233
1234            return Err(StateRootTaskError::Stalled)
1235        }
1236
1237        Ok(())
1238    }
1239}
1240
1241/// State of one address' storage trie in the sparse trie task.
1242enum StorageTrieState<S> {
1243    /// Nothing is running for this address, so its payload can be read and handed to a job.
1244    Idle(Box<StorageTrieWork<S>>),
1245    /// A job owns the payload. Everything arriving for the address meanwhile is buffered here
1246    /// and folded back in when the job returns.
1247    InFlight(Box<InFlightStorage>),
1248}
1249
1250impl<S: SparseTrie + Default> StorageTrieState<S> {
1251    /// Returns whether the address still owes the state root some work.
1252    fn is_pending(&self) -> bool {
1253        match self {
1254            Self::InFlight(_) => true,
1255            Self::Idle(work) => !work.pending.is_empty() || work.has_work(),
1256        }
1257    }
1258}
1259
1260/// Everything the sparse trie task knows about one storage trie, moved into a job as a whole and
1261/// handed back by it.
1262struct StorageTrieWork<S> {
1263    /// The storage trie, checked out of the [`SparseStateTrie`] for the whole run.
1264    trie: RevealableSparseTrie<S>,
1265    /// Leaf updates that are not applied to `trie` yet, either because they are new or because
1266    /// they are blocked on a blinded node.
1267    pending: B256Map<LeafUpdate>,
1268    /// Proof nodes to reveal into `trie` before the next leaf pass.
1269    proofs: Vec<ProofTrieNode>,
1270    /// Slots whose proof was already requested, mapped to the broadest requested parent context
1271    /// (an unknown parent sorts before every known parent).
1272    fetched: B256Map<ProofV2TargetParent>,
1273    /// Whether a pass could act on something: proof nodes to reveal, or leaf updates that were
1274    /// not tried against the current state of the trie yet.
1275    ///
1276    /// Blocked updates alone are not enough. Retrying them without a reveal in between cannot
1277    /// apply anything and would only resort the whole set again, and only this trie's own proof
1278    /// nodes can unblock them.
1279    dirty: bool,
1280    /// Whether this address ever had storage leaf updates queued, which is what makes promotion
1281    /// of its account wait for a recomputed storage root.
1282    updated: bool,
1283}
1284
1285impl<S: SparseTrie + Default> StorageTrieWork<S> {
1286    fn new(trie: RevealableSparseTrie<S>) -> Self {
1287        Self {
1288            trie,
1289            pending: Default::default(),
1290            proofs: Vec::new(),
1291            fetched: Default::default(),
1292            dirty: false,
1293            updated: false,
1294        }
1295    }
1296
1297    /// Reveals the queued proof nodes, applies the leaf updates that are not blocked by a blinded
1298    /// node, and recomputes the root once nothing is left to apply.
1299    fn run(&mut self, new_epoch: TrieNodeEpoch, retain_updates: bool) -> StorageWorkOutput {
1300        let Self { trie, pending, proofs, fetched, dirty, .. } = self;
1301        *dirty = false;
1302        let mut output = StorageWorkOutput::default();
1303
1304        if !proofs.is_empty() {
1305            output.result = trie.reveal_v2_proof_nodes(proofs, retain_updates);
1306            proofs.clear();
1307            if output.result.is_err() {
1308                return output
1309            }
1310        }
1311
1312        if !pending.is_empty() {
1313            let updates_len_before = pending.len();
1314            let targets = &mut output.targets;
1315            output.result = trie.update_leaves(pending, |path, parent| match fetched.entry(path) {
1316                Entry::Occupied(mut entry) => {
1317                    if parent < *entry.get() {
1318                        entry.insert(parent);
1319                        targets.push(ProofV2Target::new(path).with_parent(parent));
1320                    }
1321                }
1322                Entry::Vacant(entry) => {
1323                    entry.insert(parent);
1324                    targets.push(ProofV2Target::new(path).with_parent(parent));
1325                }
1326            });
1327            output.cache_hits = (updates_len_before - pending.len()) as u64;
1328            output.cache_misses = pending.len() as u64;
1329            if output.result.is_err() {
1330                return output
1331            }
1332        }
1333
1334        if self.needs_root() {
1335            self.trie.root(new_epoch);
1336        }
1337
1338        output
1339    }
1340
1341    /// Queues leaf updates, letting a newly known value win over one that is still queued.
1342    fn queue_updates(&mut self, updates: B256Map<LeafUpdate>) {
1343        if updates.is_empty() {
1344            return
1345        }
1346
1347        self.updated = true;
1348        self.dirty = true;
1349        merge_leaf_updates(&mut self.pending, updates);
1350    }
1351
1352    /// Queues proof nodes, draining them out of the batch they arrived in.
1353    fn queue_proofs(&mut self, nodes: &mut Vec<ProofTrieNode>) {
1354        if nodes.is_empty() {
1355            return
1356        }
1357
1358        self.dirty = true;
1359        self.proofs.append(nodes);
1360    }
1361
1362    /// Folds what arrived while a job owned this payload back into it.
1363    fn take_buffered(&mut self, buffered: InFlightStorage) {
1364        let InFlightStorage { mut proofs, updates, .. } = buffered;
1365        self.queue_proofs(&mut proofs);
1366        self.queue_updates(updates);
1367    }
1368
1369    /// Returns whether a pass would do anything.
1370    fn has_work(&self) -> bool {
1371        debug_assert!(self.dirty || !self.needs_root(), "a drained pass must hash its trie");
1372        self.dirty
1373    }
1374
1375    /// Returns whether the trie was modified since its root was last computed.
1376    ///
1377    /// Only a trie this block changed is hashed here: for the others the root the account leaf
1378    /// already carries is still correct.
1379    fn needs_root(&self) -> bool {
1380        self.updated &&
1381            self.pending.is_empty() &&
1382            self.trie.is_revealed() &&
1383            !self.trie.is_root_cached()
1384    }
1385
1386    /// Returns whether a pass would only turn pending updates into proof targets.
1387    ///
1388    /// A blind trie has nothing to reveal into and nothing to apply, so running the pass on the
1389    /// task itself keeps the proof request from waiting for a job round trip.
1390    const fn is_target_only(&self) -> bool {
1391        self.proofs.is_empty() && self.trie.is_blind()
1392    }
1393}
1394
1395/// Buffers for one address while a job owns its payload.
1396struct InFlightStorage {
1397    /// When the payload was handed off, for the round trip histogram.
1398    started: Instant,
1399    /// Proof nodes that arrived for this address while the payload was gone.
1400    proofs: Vec<ProofTrieNode>,
1401    /// Leaf updates that were queued for this address while the payload was gone.
1402    updates: B256Map<LeafUpdate>,
1403}
1404
1405impl InFlightStorage {
1406    fn new(started: Instant) -> Self {
1407        Self { started, proofs: Vec::new(), updates: Default::default() }
1408    }
1409}
1410
1411/// A storage payload checked out of its entry and handed to a job.
1412struct StorageTrieJob<S> {
1413    /// Hashed address the payload belongs to.
1414    address: B256,
1415    /// The checked out payload.
1416    work: Box<StorageTrieWork<S>>,
1417}
1418
1419impl<S: SparseTrie + Default> StorageTrieJob<S> {
1420    fn run(mut self, new_epoch: TrieNodeEpoch, retain_updates: bool) -> StorageTrieJobDone<S> {
1421        let output = self.work.run(new_epoch, retain_updates);
1422        StorageTrieJobDone { address: self.address, work: self.work, output }
1423    }
1424}
1425
1426/// What a spawned storage job sends back to the sparse trie task.
1427enum StorageJobMessage<S> {
1428    /// The job finished and hands its payload back.
1429    Done(StorageTrieJobDone<S>),
1430    /// The job panicked and its trie is lost. The global rayon pool has no panic handler, so a
1431    /// panic escaping a spawned job would abort the process; it is caught and resumed on the task
1432    /// thread instead, where it fails the state root calculation like an inline panic.
1433    Panicked {
1434        /// Hashed address of the payload the job owned.
1435        address: B256,
1436        /// The panic payload, resumed on the task thread.
1437        payload: Box<dyn Any + Send>,
1438    },
1439}
1440
1441/// A storage payload coming back to the sparse trie task after its job finished.
1442struct StorageTrieJobDone<S> {
1443    /// Hashed address the payload belongs to.
1444    address: B256,
1445    /// The payload itself, to be put back into its entry.
1446    work: Box<StorageTrieWork<S>>,
1447    /// What the pass produced.
1448    output: StorageWorkOutput,
1449}
1450
1451/// What one storage pass produced for the sparse trie task.
1452struct StorageWorkOutput {
1453    /// Proof targets discovered while applying the leaf updates.
1454    targets: Vec<ProofV2Target>,
1455    /// Leaf updates applied without needing a new proof.
1456    cache_hits: u64,
1457    /// Leaf updates that stayed blocked on a blinded node.
1458    cache_misses: u64,
1459    /// The error the pass stopped at, if any.
1460    result: SparseTrieResult<()>,
1461}
1462
1463impl Default for StorageWorkOutput {
1464    fn default() -> Self {
1465        Self { targets: Vec::new(), cache_hits: 0, cache_misses: 0, result: Ok(()) }
1466    }
1467}
1468
1469/// Merges leaf updates into a queue, letting a newly known value win over a queued one.
1470fn merge_leaf_updates(queued: &mut B256Map<LeafUpdate>, updates: B256Map<LeafUpdate>) {
1471    if queued.is_empty() {
1472        // Take the whole map at once, no per-slot loop.
1473        *queued = updates;
1474        return
1475    }
1476
1477    for (slot, update) in updates {
1478        match queued.entry(slot) {
1479            Entry::Occupied(mut entry) => {
1480                if update.is_changed() {
1481                    entry.insert(update);
1482                }
1483            }
1484            Entry::Vacant(entry) => {
1485                entry.insert(update);
1486            }
1487        }
1488    }
1489}
1490
1491/// Number of storage tries handed to a single spawned job.
1492///
1493/// Chunking keeps a block with thousands of tiny tries from paying a rayon spawn per trie, while
1494/// staying small enough that one slow trie only delays the few behind it in its own chunk. Tries
1495/// are still handed back one at a time, so a chunk does not delay promotion of the ones it
1496/// already finished.
1497fn storage_job_chunk_len(tries: usize) -> usize {
1498    /// Upper bound on how many tries a single slow one can hold up.
1499    const MAX_CHUNK_LEN: usize = 32;
1500
1501    tries.div_ceil(rayon::current_num_threads().max(1) * 4).clamp(1, MAX_CHUNK_LEN)
1502}
1503
1504/// Metrics recorded by sparse trie and hashing tasks.
1505#[derive(Metrics, Clone)]
1506#[metrics(scope = "tree.root")]
1507pub(super) struct SparseTrieTaskMetrics {
1508    /// Histogram of durations spent revealing multiproof results into the sparse trie.
1509    pub(super) sparse_trie_reveal_multiproof_duration_histogram: Histogram,
1510    /// Histogram of durations spent coalescing multiple proof results from the channel.
1511    pub(super) sparse_trie_proof_coalesce_duration_histogram: Histogram,
1512    /// Histogram of durations the event loop spent blocked waiting on channels.
1513    pub(super) sparse_trie_channel_wait_duration_histogram: Histogram,
1514    /// Histogram of durations spent processing trie updates and promoting pending accounts.
1515    pub(super) sparse_trie_process_updates_duration_histogram: Histogram,
1516    /// Histogram of durations storage tries spend checked out for a job on another thread.
1517    pub(super) sparse_trie_storage_job_duration_histogram: Histogram,
1518    /// Histogram of sparse trie final update durations.
1519    pub(super) sparse_trie_final_update_duration_histogram: Histogram,
1520    /// Histogram of sparse trie total durations.
1521    pub(super) sparse_trie_total_duration_histogram: Histogram,
1522    /// Time spent preparing the sparse trie for reuse after state root computation.
1523    pub(super) into_trie_for_reuse_duration_histogram: Histogram,
1524    /// Time spent pruning the sparse trie by node epoch.
1525    pub(super) sparse_trie_prune_duration_histogram: Histogram,
1526    /// Time spent waiting for preserved sparse trie cache to become available.
1527    pub(super) sparse_trie_cache_wait_duration_histogram: Histogram,
1528    /// Histogram for sparse trie task idle time in seconds (waiting for updates or proof
1529    /// results). Excludes the final wait after the channel is closed.
1530    pub(super) sparse_trie_idle_time_seconds: Histogram,
1531    /// Histogram for hashing task idle time in seconds (waiting for messages from execution).
1532    /// Excludes the final wait after the channel is closed.
1533    pub(super) hashing_task_idle_time_seconds: Histogram,
1534
1535    /// Number of account leaf updates applied without needing a new proof (cache hits).
1536    pub(super) sparse_trie_account_cache_hits: Histogram,
1537    /// Number of account leaf updates that required a new proof (cache misses).
1538    pub(super) sparse_trie_account_cache_misses: Histogram,
1539    /// Number of storage leaf updates applied without needing a new proof (cache hits).
1540    pub(super) sparse_trie_storage_cache_hits: Histogram,
1541    /// Number of storage leaf updates that required a new proof (cache misses).
1542    pub(super) sparse_trie_storage_cache_misses: Histogram,
1543
1544    /// Number of storage tries retained in the preserved sparse trie cache.
1545    pub(super) sparse_trie_retained_storage_tries: Gauge,
1546}
1547
1548/// The default max targets, for limiting the number of account and storage proof targets to be
1549/// fetched by a single worker. If exceeded, chunking is forced regardless of worker availability.
1550const DEFAULT_MAX_TARGETS_FOR_CHUNKING: usize = 300;
1551
1552/// Start proof fetching while the first state-update batch is still arriving.
1553const INITIAL_UPDATE_BATCH_SIZE: usize = 64;
1554
1555/// A round of storage passes that would do at most this much work - proof nodes to reveal plus
1556/// leaf updates to apply - runs on the sparse trie task itself, because handing the tries to
1557/// another thread and waiting for them to come back costs more than the work.
1558const INLINE_STORAGE_WORK_UNITS: usize = 16;
1559
1560/// Dispatches work items as a single unit or in chunks based on target size and worker
1561/// availability.
1562#[expect(clippy::too_many_arguments)]
1563fn dispatch_with_chunking<T, I>(
1564    items: T,
1565    chunking_len: usize,
1566    chunk_size: usize,
1567    max_targets_for_chunking: usize,
1568    has_multiple_idle_account_workers: bool,
1569    has_multiple_idle_storage_workers: bool,
1570    chunker: impl FnOnce(T, usize) -> I,
1571    mut dispatch: impl FnMut(T),
1572) where
1573    I: IntoIterator<Item = T>,
1574{
1575    let has_full_chunks = chunking_len >= chunk_size.saturating_mul(2);
1576    let should_chunk = chunking_len > max_targets_for_chunking ||
1577        (has_full_chunks &&
1578            (has_multiple_idle_account_workers || has_multiple_idle_storage_workers));
1579
1580    if should_chunk && chunking_len > chunk_size {
1581        for chunk in chunker(items, chunk_size) {
1582            dispatch(chunk);
1583        }
1584        return;
1585    }
1586
1587    dispatch(items);
1588}
1589
1590/// RLP-encodes the account as a [`TrieAccount`] leaf value, or returns empty for deletions.
1591///
1592/// `Some(Account::default())` with an empty storage root is encoded as a deletion. This is valid
1593/// for post-Merge state because EIP-7523 (<https://eips.ethereum.org/EIPS/eip-7523>) prohibits
1594/// empty accounts. Do not use this encoding rule when replaying historical pre-Merge state, where
1595/// an empty account and a missing account can have different trie representations.
1596fn encode_account_leaf_value(
1597    account: Option<Account>,
1598    storage_root: B256,
1599    account_rlp_buf: &mut Vec<u8>,
1600) -> Vec<u8> {
1601    if account.as_ref().is_none_or(|account| account.is_empty()) && storage_root == EMPTY_ROOT_HASH
1602    {
1603        return Vec::new();
1604    }
1605
1606    account_rlp_buf.clear();
1607    account.unwrap_or_default().into_trie_account(storage_root).encode(account_rlp_buf);
1608    account_rlp_buf.clone()
1609}
1610
1611/// Pending proof targets queued for dispatch to proof workers, along with their count.
1612#[derive(Default)]
1613struct PendingTargets {
1614    /// The proof targets.
1615    targets: MultiProofTargetsV2,
1616    /// Number of account + storage proof targets currently queued.
1617    len: usize,
1618}
1619
1620impl PendingTargets {
1621    /// Returns the number of pending targets.
1622    const fn len(&self) -> usize {
1623        self.len
1624    }
1625
1626    /// Returns `true` if there are no pending targets.
1627    const fn is_empty(&self) -> bool {
1628        self.len == 0
1629    }
1630
1631    /// Takes the pending targets, replacing with empty defaults.
1632    fn take(&mut self) -> (MultiProofTargetsV2, usize) {
1633        (std::mem::take(&mut self.targets), std::mem::take(&mut self.len))
1634    }
1635
1636    /// Adds a target to the account targets.
1637    fn push_account_target(&mut self, target: ProofV2Target) {
1638        self.targets.account_targets.push(target);
1639        self.len += 1;
1640    }
1641
1642    /// Extends storage targets for the given address.
1643    fn extend_storage_targets(&mut self, address: &B256, targets: Vec<ProofV2Target>) {
1644        self.len += targets.len();
1645        self.targets.storage_targets.entry(*address).or_default().extend(targets);
1646    }
1647}
1648
1649/// Message type for the sparse trie task.
1650enum SparseTrieTaskMessage {
1651    /// A hashed state update ready to be processed.
1652    HashedState(HashedPostState),
1653    /// Prefetch proof targets (passed through directly).
1654    PrefetchProofs(MultiProofTargetsV2),
1655    /// Signals that all state updates have been received.
1656    FinishedStateUpdates,
1657}
1658
1659#[cfg(test)]
1660mod tests {
1661    use super::*;
1662    use alloy_primitives::{B256, U256};
1663    use reth_concurrency::sync::thread;
1664    use reth_db_common::init::init_genesis;
1665    use reth_provider::test_utils::create_test_provider_factory;
1666    use reth_storage_overlay::{OverlayManager, OverlayStateProviderFactory};
1667    use reth_trie_common::{
1668        BranchNode, BranchNodeMasks, ExtensionNode, LeafNode, Nibbles, TrieMask, TrieNode,
1669    };
1670    use reth_trie_parallel::proof_task::{ProofTaskCtx, ProofWorkerCounts};
1671    use reth_trie_sparse::ArenaParallelSparseTrie;
1672
1673    fn drain_sparse_trie_tasks(runtime: &Runtime) {
1674        for task_name in ["trie-hashing", "storage-workers", "account-workers"] {
1675            runtime.spawn_blocking_named(task_name, || {}).get();
1676        }
1677    }
1678
1679    fn test_task(
1680        runtime: &Runtime,
1681        trie: SparseStateTrie,
1682    ) -> (SparseTrieCacheTask, Sender<StateRootMessage>, Sender<()>) {
1683        let provider_factory = create_test_provider_factory();
1684        let anchor_hash = init_genesis(&provider_factory).expect("failed to initialize genesis");
1685        let state_provider_factory = OverlayStateProviderFactory::new(
1686            provider_factory,
1687            OverlayManager::<reth_chain_state::EthPrimitives>::default()
1688                .overlay_builder(anchor_hash),
1689        );
1690        let proof_worker_handle = ProofWorkerHandle::new(
1691            runtime,
1692            ProofTaskCtx::new(state_provider_factory),
1693            ProofWorkerCounts::full(runtime),
1694            Default::default(),
1695        );
1696        let (updates_tx, updates_rx) = channel::unbounded();
1697        let (cancel_guard, cancel_rx) = channel::bounded(0);
1698        let task = SparseTrieCacheTask::new_with_trie(
1699            runtime,
1700            updates_rx,
1701            cancel_rx,
1702            mpsc::channel().0,
1703            proof_worker_handle,
1704            SparseTrieTaskMetrics::default(),
1705            trie,
1706            EMPTY_ROOT_HASH,
1707            TrieNodeEpoch::new(1),
1708            1,
1709        );
1710        (task, updates_tx, cancel_guard)
1711    }
1712
1713    fn receive_storage_job(
1714        task: &SparseTrieCacheTask,
1715    ) -> StorageJobMessage<ArenaParallelSparseTrie> {
1716        task.storage_done_rx
1717            .recv_timeout(std::time::Duration::from_secs(5))
1718            .expect("storage job did not return")
1719    }
1720
1721    /// Checks a payload out of its entry the way a spawned job does, without racing one.
1722    fn check_out_storage(
1723        task: &mut SparseTrieCacheTask,
1724        address: B256,
1725    ) -> Box<StorageTrieWork<ArenaParallelSparseTrie>> {
1726        let state = task.storage.get_mut(&address).expect("address must have an entry");
1727        let StorageTrieState::Idle(work) = core::mem::replace(
1728            state,
1729            StorageTrieState::InFlight(Box::new(InFlightStorage::new(Instant::now()))),
1730        ) else {
1731            panic!("trie must be idle")
1732        };
1733        task.storage_in_flight += 1;
1734        work
1735    }
1736
1737    /// Hands a payload checked out by [`check_out_storage`] back, as a finished job would.
1738    fn return_storage(
1739        task: &mut SparseTrieCacheTask,
1740        address: B256,
1741        work: Box<StorageTrieWork<ArenaParallelSparseTrie>>,
1742    ) {
1743        task.on_storage_trie_returned(StorageTrieJobDone {
1744            address,
1745            work,
1746            output: StorageWorkOutput::default(),
1747        })
1748        .unwrap();
1749    }
1750
1751    fn storage_slot_value(
1752        task: &SparseTrieCacheTask,
1753        address: &B256,
1754        slot: &B256,
1755    ) -> Option<Vec<u8>> {
1756        let StorageTrieState::Idle(work) = task.storage.get(address)? else { return None };
1757        work.trie.as_revealed_ref()?.get_leaf_value(&Nibbles::unpack(slot)).cloned()
1758    }
1759
1760    fn storage_root_of(task: &mut SparseTrieCacheTask, address: B256) -> B256 {
1761        let StorageTrieState::Idle(work) = task.storage.get_mut(&address).expect("entry") else {
1762            panic!("payload is out with a job")
1763        };
1764        work.trie.root(TrieNodeEpoch::new(1)).expect("storage trie must be revealed")
1765    }
1766
1767    #[test]
1768    fn test_encode_account_leaf_value_deletion_and_empty_root_is_empty() {
1769        let mut account_rlp_buf = vec![0xAB];
1770        let encoded = encode_account_leaf_value(None, EMPTY_ROOT_HASH, &mut account_rlp_buf);
1771
1772        assert!(encoded.is_empty());
1773        // Early return should not touch the caller's buffer.
1774        assert_eq!(account_rlp_buf, vec![0xAB]);
1775    }
1776
1777    #[test]
1778    fn test_encode_account_leaf_value_empty_account_and_empty_root_is_empty() {
1779        let mut account_rlp_buf = vec![0xAB];
1780        let encoded = encode_account_leaf_value(
1781            Some(Account::default()),
1782            EMPTY_ROOT_HASH,
1783            &mut account_rlp_buf,
1784        );
1785
1786        assert!(encoded.is_empty());
1787        // Early return should not touch the caller's buffer.
1788        assert_eq!(account_rlp_buf, vec![0xAB]);
1789    }
1790
1791    #[test]
1792    #[allow(clippy::needless_update)]
1793    fn test_encode_account_leaf_value_non_empty_account_is_rlp() {
1794        let storage_root = B256::repeat_byte(0x99);
1795        let account = Some(Account {
1796            nonce: 7,
1797            balance: U256::from(42),
1798            bytecode_hash: Some(B256::repeat_byte(0xAA)),
1799            ..Default::default()
1800        });
1801        let mut account_rlp_buf = vec![0x00, 0x01];
1802
1803        let encoded = encode_account_leaf_value(account, storage_root, &mut account_rlp_buf);
1804        let decoded = TrieAccount::decode(&mut &encoded[..]).expect("valid account RLP");
1805
1806        assert_eq!(decoded.nonce, 7);
1807        assert_eq!(decoded.balance, U256::from(42));
1808        assert_eq!(decoded.storage_root, storage_root);
1809        assert_eq!(account_rlp_buf, encoded);
1810    }
1811
1812    #[reth_concurrency::test]
1813    fn hashing_task_returns_after_finish_marker_while_hint_sender_is_alive() {
1814        let runtime = Runtime::test();
1815        let (task, updates_tx, _cancel_guard) = test_task(&runtime, SparseStateTrie::default());
1816        // A hint sender outliving execution, like a prewarm task queued behind earlier blocks.
1817        let _hint_tx = updates_tx.clone();
1818        updates_tx.send(StateRootMessage::FinishedStateUpdates).unwrap();
1819        drop(updates_tx);
1820
1821        // The next block's hashing task runs on the same thread, so it must not wait for the
1822        // hint sender to drop.
1823        let (next_task_tx, next_task_rx) = mpsc::channel();
1824        runtime.spawn_blocking_named("trie-hashing", move || next_task_tx.send(()).unwrap());
1825        next_task_rx
1826            .recv_timeout(std::time::Duration::from_secs(5))
1827            .expect("hashing thread is still held by the finished task");
1828        assert!(matches!(task.updates.try_recv(), Ok(SparseTrieTaskMessage::FinishedStateUpdates)));
1829
1830        drop(task);
1831        drain_sparse_trie_tasks(&runtime);
1832    }
1833
1834    #[reth_concurrency::test]
1835    fn checked_out_storage_trie_holds_back_its_updates_until_it_returns() {
1836        let runtime = Runtime::test();
1837        let trie = SparseStateTrie::default()
1838            .with_accounts_trie(RevealableSparseTrie::<ArenaParallelSparseTrie>::revealed_empty())
1839            .with_default_storage_trie(RevealableSparseTrie::blind_from(
1840                ArenaParallelSparseTrie::default(),
1841            ))
1842            .with_updates(true);
1843        let (mut task, updates_tx, _cancel_guard) = test_task(&runtime, trie);
1844
1845        let address = B256::repeat_byte(0x11);
1846        let revealed_slot = B256::repeat_byte(0x22);
1847        let late_slot = B256::repeat_byte(0x33);
1848        let revealed_value = alloy_rlp::encode_fixed_size(&U256::from(7)).to_vec();
1849        let late_value = alloy_rlp::encode_fixed_size(&U256::from(9)).to_vec();
1850        let later_value = alloy_rlp::encode_fixed_size(&U256::from(11)).to_vec();
1851
1852        let mut state = HashedPostState::default();
1853        state.accounts.insert(address, Some(Account { nonce: 1, ..Default::default() }));
1854        state.storages.entry(address).or_default().storage.insert(revealed_slot, U256::from(7));
1855        task.on_hashed_state_update(state);
1856        task.pending_updates = 1;
1857        task.apply_new_updates().unwrap();
1858
1859        // Check the payload out by hand so the test does not race a spawned job.
1860        let work = check_out_storage(&mut task, address);
1861        task.finished_state_updates = true;
1862
1863        assert!(task.has_pending_sparse_trie_updates());
1864        assert!(
1865            task.ensure_not_stalled(false).is_ok(),
1866            "a checked out payload can still deliver progress"
1867        );
1868
1869        // A proof for a checked out address must be buffered, not revealed into a fresh blind
1870        // trie that the returning job would then overwrite.
1871        let leaf = ProofTrieNode {
1872            path: Nibbles::default(),
1873            node: TrieNode::Leaf(LeafNode::new(
1874                Nibbles::unpack(revealed_slot),
1875                revealed_value.clone(),
1876            )),
1877            masks: None,
1878        };
1879        task.on_proofs(DecodedMultiProofV2 {
1880            storage_proofs: B256Map::from_iter([(address, vec![leaf])]),
1881            ..Default::default()
1882        })
1883        .unwrap();
1884        assert!(!task.trie.storage_tries_mut().contains_key(&address));
1885        let StorageTrieState::InFlight(in_flight) = &task.storage[&address] else {
1886            panic!("payload is out with a job")
1887        };
1888        assert_eq!(in_flight.proofs.len(), 1);
1889
1890        // The same holds for leaf updates arriving while the payload is gone.
1891        let mut state = HashedPostState::default();
1892        state.storages.entry(address).or_default().storage.insert(late_slot, U256::from(9));
1893        task.on_hashed_state_update(state);
1894        task.pending_updates = 1;
1895        task.apply_new_updates().unwrap();
1896        let StorageTrieState::InFlight(in_flight) = &task.storage[&address] else {
1897            panic!("payload is out with a job")
1898        };
1899        assert!(in_flight.updates.contains_key(&late_slot));
1900
1901        return_storage(&mut task, address, work);
1902        assert_eq!(task.storage_in_flight, 0);
1903
1904        // Returned work must run even without new input messages.
1905        assert_eq!(task.pending_updates, 0);
1906        task.process_new_updates().unwrap();
1907        assert_eq!(storage_slot_value(&task, &address, &revealed_slot), Some(revealed_value));
1908        assert_eq!(storage_slot_value(&task, &address, &late_slot), Some(late_value));
1909
1910        let StorageTrieState::Idle(work) = &task.storage[&address] else {
1911            panic!("payload is back")
1912        };
1913        assert!(work.pending.is_empty());
1914        assert!(work.trie.is_root_cached(), "a drained payload hashes its trie");
1915        let root_before = storage_root_of(&mut task, address);
1916
1917        // An update arriving during a job invalidates the root the previous pass computed.
1918        let work = check_out_storage(&mut task, address);
1919        let mut state = HashedPostState::default();
1920        state.storages.entry(address).or_default().storage.insert(late_slot, U256::from(11));
1921        task.on_hashed_state_update(state);
1922        task.pending_updates = 1;
1923        task.apply_new_updates().unwrap();
1924        return_storage(&mut task, address, work);
1925
1926        let StorageTrieState::Idle(work) = &task.storage[&address] else {
1927            panic!("payload is back")
1928        };
1929        assert!(work.has_work(), "a buffered update makes the payload ready again");
1930
1931        task.process_new_updates().unwrap();
1932        assert_eq!(storage_slot_value(&task, &address, &late_slot), Some(later_value));
1933        assert_ne!(storage_root_of(&mut task, address), root_before);
1934
1935        drop(updates_tx);
1936        drop(task);
1937        drain_sparse_trie_tasks(&runtime);
1938    }
1939
1940    #[reth_concurrency::test]
1941    #[allow(clippy::clone_on_copy)]
1942    fn in_flight_storage_updates_keep_latest_values_and_deletions() {
1943        let runtime = Runtime::test();
1944        let trie = SparseStateTrie::default()
1945            .with_accounts_trie(RevealableSparseTrie::revealed_empty())
1946            .with_updates(true);
1947        let (mut task, updates_tx, _cancel_guard) = test_task(&runtime, trie);
1948        let address = B256::repeat_byte(0x11);
1949        let removed_slot = B256::repeat_byte(0x20);
1950        let changed_slot = B256::repeat_byte(0x30);
1951        let new_slot = B256::repeat_byte(0x31);
1952        // A nested branch ensures there are persisted branch updates to compare.
1953        let mut sibling_slot = changed_slot;
1954        sibling_slot[1] = 0x40;
1955        let account = Account { nonce: 1, ..Default::default() };
1956        let parent_leaf = ProofTrieNode {
1957            path: Nibbles::default(),
1958            node: TrieNode::Leaf(LeafNode::new(
1959                Nibbles::unpack(removed_slot),
1960                alloy_rlp::encode(U256::from(7)),
1961            )),
1962            masks: None,
1963        };
1964
1965        let mut state = HashedPostState::default();
1966        state.accounts.insert(address, Some(account.clone()));
1967        state.storages.entry(address).or_default().storage.extend([
1968            (removed_slot, U256::from(8)),
1969            (changed_slot, U256::from(9)),
1970            (new_slot, U256::ONE),
1971            (sibling_slot, U256::from(2)),
1972        ]);
1973        task.on_hashed_state_update(state);
1974        task.pending_updates = 1;
1975        task.apply_new_updates().unwrap();
1976
1977        let mut work = check_out_storage(&mut task, address);
1978        let output = work.run(task.new_epoch, true);
1979        assert_eq!(work.pending.len(), 4, "the blind pass keeps its original updates");
1980        assert_eq!(output.targets.len(), 4);
1981
1982        // New values and a later prewarm hint arrive while the old values are still pending.
1983        let mut state = HashedPostState::default();
1984        state
1985            .storages
1986            .entry(address)
1987            .or_default()
1988            .storage
1989            .extend([(removed_slot, U256::ZERO), (changed_slot, U256::from(11))]);
1990        task.on_hashed_state_update(state);
1991        task.pending_updates = 1;
1992        task.apply_new_updates().unwrap();
1993        task.on_prewarm_targets(MultiProofTargetsV2 {
1994            storage_targets: B256Map::from_iter([(
1995                address,
1996                vec![ProofV2Target::new(removed_slot), ProofV2Target::new(changed_slot)],
1997            )]),
1998            ..Default::default()
1999        });
2000        task.pending_updates = 1;
2001        task.apply_new_updates().unwrap();
2002
2003        task.on_storage_trie_returned(StorageTrieJobDone { address, work, output }).unwrap();
2004        // Deliver the requested parent proof directly so the interleaving is deterministic.
2005        let (targets, _) = task.pending_targets.take();
2006        assert_eq!(targets.storage_targets[&address].len(), 4);
2007        task.on_proofs(DecodedMultiProofV2 {
2008            storage_proofs: B256Map::from_iter([(address, vec![parent_leaf.clone()])]),
2009            ..Default::default()
2010        })
2011        .unwrap();
2012        updates_tx.send(StateRootMessage::FinishedStateUpdates).unwrap();
2013        let outcome = task.run().unwrap();
2014
2015        let expected_root = reth_trie_common::root::storage_root_unsorted([
2016            (changed_slot, U256::from(11)),
2017            (new_slot, U256::ONE),
2018            (sibling_slot, U256::from(2)),
2019        ]);
2020        assert_eq!(
2021            outcome.state_root,
2022            reth_trie_common::root::state_root_unsorted([(
2023                address,
2024                account.into_trie_account(expected_root),
2025            )])
2026        );
2027
2028        let mut serial = RevealableSparseTrie::<ArenaParallelSparseTrie>::blind();
2029        serial.reveal_v2_proof_nodes(&mut [parent_leaf], true).unwrap();
2030        let mut final_updates = B256Map::from_iter([
2031            (removed_slot, LeafUpdate::Changed(Vec::new())),
2032            (changed_slot, LeafUpdate::Changed(alloy_rlp::encode(U256::from(11)))),
2033            (new_slot, LeafUpdate::Changed(alloy_rlp::encode(U256::ONE))),
2034            (sibling_slot, LeafUpdate::Changed(alloy_rlp::encode(U256::from(2)))),
2035        ]);
2036        serial
2037            .update_leaves(&mut final_updates, |_, _| panic!("parent is fully revealed"))
2038            .unwrap();
2039        let (serial_root, serial_updates) = serial.root_with_updates(task.new_epoch).unwrap();
2040        assert_eq!(serial_root, expected_root);
2041        assert!(!serial_updates.updated_nodes.is_empty());
2042        let updates = &outcome.trie_updates.storage_tries[&address];
2043        assert_eq!(updates.storage_nodes, serial_updates.updated_nodes);
2044        assert_eq!(updates.removed_nodes, serial_updates.removed_nodes);
2045
2046        let (mut reused, _) = task.into_trie_for_reuse();
2047        assert_eq!(reused.storage_root(&address, TrieNodeEpoch::new(2)), Some(expected_root));
2048        assert!(reused.take_trie_updates().unwrap().is_empty());
2049        drop(updates_tx);
2050        drain_sparse_trie_tasks(&runtime);
2051    }
2052
2053    #[reth_concurrency::test]
2054    fn unrelated_storage_proofs_do_not_retry_blocked_leaves() {
2055        let runtime = Runtime::test();
2056        let (mut task, updates_tx, _cancel_guard) = test_task(&runtime, SparseStateTrie::default());
2057        let address = B256::repeat_byte(0x11);
2058        let slot = B256::repeat_byte(0x22);
2059        let StorageTrieState::Idle(work) = task.storage_trie_state_mut(address) else {
2060            unreachable!()
2061        };
2062        work.queue_updates(B256Map::from_iter([(slot, LeafUpdate::Changed(vec![1]))]));
2063        task.run_ready_storage_work().unwrap();
2064        assert_eq!(task.storage_cache_misses, 1);
2065
2066        task.on_proofs(DecodedMultiProofV2 {
2067            storage_proofs: B256Map::from_iter([(
2068                B256::repeat_byte(0x33),
2069                vec![ProofTrieNode::empty()],
2070            )]),
2071            ..Default::default()
2072        })
2073        .unwrap();
2074        assert_eq!(task.storage_cache_misses, 1, "unrelated reveals cannot unblock this trie");
2075        assert_eq!(storage_slot_value(&task, &address, &slot), None);
2076
2077        task.on_proofs(DecodedMultiProofV2 {
2078            storage_proofs: B256Map::from_iter([(address, vec![ProofTrieNode::empty()])]),
2079            ..Default::default()
2080        })
2081        .unwrap();
2082        assert_eq!(storage_slot_value(&task, &address, &slot), Some(vec![1]));
2083        assert_eq!(task.storage_cache_hits, 1);
2084        assert!(!task.has_ready_storage_work());
2085
2086        drop(updates_tx);
2087        drop(task);
2088        drain_sparse_trie_tasks(&runtime);
2089    }
2090
2091    #[reth_concurrency::test]
2092    fn canceled_task_disconnects_checked_out_storage_jobs() {
2093        let runtime = Runtime::test();
2094        let trie = SparseStateTrie::default()
2095            .with_default_storage_trie(RevealableSparseTrie::revealed_empty());
2096        let (mut task, updates_tx, cancel_guard) = test_task(&runtime, trie);
2097        let idle_address = B256::repeat_byte(0x11);
2098        let address = B256::repeat_byte(0x22);
2099        task.storage_trie_state_mut(idle_address);
2100        task.storage_trie_state_mut(address);
2101        let work = check_out_storage(&mut task, address);
2102        let done_tx = task.storage_done_tx.clone();
2103        let epoch = task.new_epoch;
2104
2105        drop(cancel_guard);
2106        assert!(matches!(task.run(), Err(StateRootTaskError::Canceled)));
2107        let (trie, _) = task.into_cleared_trie();
2108        assert_eq!(trie.retained_storage_tries_count(), 1, "only the idle trie can be reused");
2109
2110        // Complete the held job after teardown, when its payload must be dropped by the sender.
2111        let done = StorageTrieJob { address, work }.run(epoch, false);
2112        assert!(done_tx.send(StorageJobMessage::Done(done)).is_err());
2113        drop(updates_tx);
2114        drain_sparse_trie_tasks(&runtime);
2115    }
2116
2117    #[reth_concurrency::test]
2118    fn storage_job_panics_are_resumed_on_the_task() {
2119        let runtime = Runtime::test();
2120        let (mut task, updates_tx, _cancel_guard) = test_task(&runtime, SparseStateTrie::default());
2121        let address = B256::repeat_byte(0x11);
2122        let StorageTrieState::Idle(work) = task.storage_trie_state_mut(address) else {
2123            unreachable!()
2124        };
2125        work.queue_proofs(&mut vec![ProofTrieNode {
2126            path: Nibbles::default(),
2127            node: TrieNode::Branch(BranchNode {
2128                state_mask: TrieMask::from(1),
2129                ..Default::default()
2130            }),
2131            masks: None,
2132        }]);
2133        let work = check_out_storage(&mut task, address);
2134        task.spawn_storage_jobs(vec![StorageTrieJob { address, work }]);
2135
2136        let message = receive_storage_job(&task);
2137        assert!(
2138            matches!(&message, StorageJobMessage::Panicked { address: returned, .. } if *returned == address)
2139        );
2140        let panic = panic::catch_unwind(AssertUnwindSafe(|| task.on_storage_job_message(message)));
2141        assert!(panic.is_err());
2142        assert_eq!(task.storage_in_flight, 0);
2143        assert!(!task.storage.contains_key(&address));
2144
2145        drop(updates_tx);
2146        drop(task);
2147        drain_sparse_trie_tasks(&runtime);
2148    }
2149
2150    #[reth_concurrency::test]
2151    fn blind_storage_proof_errors_are_returned_to_the_task() {
2152        let runtime = Runtime::test();
2153        let (mut task, updates_tx, _cancel_guard) = test_task(&runtime, SparseStateTrie::default());
2154        let address = B256::repeat_byte(0x11);
2155        let StorageTrieState::Idle(work) = task.storage_trie_state_mut(address) else {
2156            unreachable!()
2157        };
2158        work.queue_proofs(&mut vec![ProofTrieNode {
2159            path: Nibbles::from_nibbles([1]),
2160            node: TrieNode::Leaf(LeafNode::new(Nibbles::from_nibbles([1]), vec![1])),
2161            masks: None,
2162        }]);
2163        let work = check_out_storage(&mut task, address);
2164        task.spawn_storage_jobs(vec![StorageTrieJob { address, work }]);
2165
2166        let message = receive_storage_job(&task);
2167        assert!(matches!(&message, StorageJobMessage::Done(done) if done.address == address));
2168        let error = task.on_storage_job_message(message).unwrap_err();
2169        assert!(matches!(error.kind(), SparseTrieErrorKind::Blind));
2170        assert_eq!(task.storage_in_flight, 0);
2171        assert!(matches!(task.storage.get(&address), Some(StorageTrieState::Idle(_))));
2172
2173        drop(updates_tx);
2174        drop(task);
2175        drain_sparse_trie_tasks(&runtime);
2176    }
2177
2178    #[reth_concurrency::test]
2179    fn large_storage_batches_run_off_thread() {
2180        let runtime = Runtime::test();
2181        let trie = SparseStateTrie::default()
2182            .with_accounts_trie(RevealableSparseTrie::<ArenaParallelSparseTrie>::revealed_empty())
2183            .with_default_storage_trie(RevealableSparseTrie::blind_from(
2184                ArenaParallelSparseTrie::default(),
2185            ))
2186            .with_updates(true);
2187        let (mut task, updates_tx, _cancel_guard) = test_task(&runtime, trie);
2188
2189        // One leaf per address, enough of them to exceed the inline budget.
2190        let leaves = (0..=INLINE_STORAGE_WORK_UNITS as u8)
2191            .map(|index| {
2192                let address = B256::repeat_byte(0x10 + index);
2193                let slot = B256::repeat_byte(0x80 + index);
2194                let value = alloy_rlp::encode_fixed_size(&U256::from(index + 1)).to_vec();
2195                (address, slot, value)
2196            })
2197            .collect::<Vec<_>>();
2198        let storage_proofs = leaves
2199            .iter()
2200            .map(|(address, slot, value)| {
2201                let leaf = ProofTrieNode {
2202                    path: Nibbles::default(),
2203                    node: TrieNode::Leaf(LeafNode::new(Nibbles::unpack(slot), value.clone())),
2204                    masks: None,
2205                };
2206                (*address, vec![leaf])
2207            })
2208            .collect();
2209
2210        task.on_proofs(DecodedMultiProofV2 { account_proofs: Vec::new(), storage_proofs }).unwrap();
2211
2212        assert_eq!(task.storage_in_flight, leaves.len());
2213        assert!(task.has_pending_sparse_trie_updates(), "completion must wait for the reveals");
2214
2215        while task.storage_in_flight > 0 {
2216            let message = receive_storage_job(&task);
2217            task.on_storage_job_message(message).unwrap();
2218        }
2219        for (address, slot, value) in &leaves {
2220            assert_eq!(storage_slot_value(&task, address, slot).as_ref(), Some(value));
2221        }
2222
2223        drop(updates_tx);
2224        drop(task);
2225        drain_sparse_trie_tasks(&runtime);
2226    }
2227
2228    #[reth_concurrency::test]
2229    #[allow(clippy::clone_on_copy)]
2230    fn run_waits_for_storage_tries_hashed_off_thread() {
2231        let runtime = Runtime::test();
2232        let default_trie = RevealableSparseTrie::<ArenaParallelSparseTrie>::revealed_empty();
2233        let trie = SparseStateTrie::default()
2234            .with_accounts_trie(default_trie.clone())
2235            .with_default_storage_trie(default_trie)
2236            .with_updates(true);
2237        let (mut task, updates_tx, _cancel_guard) = test_task(&runtime, trie);
2238
2239        let accounts = (0..8u8)
2240            .map(|index| {
2241                let address = B256::repeat_byte(0x10 + index);
2242                let account = Account {
2243                    nonce: u64::from(index) + 1,
2244                    balance: U256::from(index),
2245                    ..Default::default()
2246                };
2247                let storage = (0..4u8)
2248                    .map(|slot| {
2249                        (B256::repeat_byte(0x40 + index * 4 + slot), U256::from(slot) + U256::ONE)
2250                    })
2251                    .collect::<Vec<_>>();
2252                (address, account, storage)
2253            })
2254            .collect::<Vec<_>>();
2255
2256        let mut state = HashedPostState::default();
2257        for (address, account, storage) in &accounts {
2258            state.accounts.insert(*address, Some(account.clone()));
2259            state.storages.entry(*address).or_default().storage.extend(storage.iter().copied());
2260        }
2261        updates_tx.send(StateRootMessage::HashedStateUpdate(state)).unwrap();
2262        updates_tx.send(StateRootMessage::FinishedStateUpdates).unwrap();
2263
2264        let outcome = task.run().expect("state root computation should succeed");
2265
2266        let expected = accounts.iter().map(|(address, account, storage)| {
2267            let storage_root =
2268                reth_trie_common::root::storage_root_unsorted(storage.iter().copied());
2269            (*address, account.clone().into_trie_account(storage_root))
2270        });
2271        assert_eq!(outcome.state_root, reth_trie_common::root::state_root_unsorted(expected));
2272        assert_eq!(task.storage_in_flight, 0);
2273        assert!(task.storage.is_empty(), "every storage trie is back in the state trie");
2274
2275        drop(updates_tx);
2276        drop(task);
2277        drain_sparse_trie_tasks(&runtime);
2278    }
2279
2280    #[reth_concurrency::test]
2281    fn first_leaf_batch_starts_proofs_before_input_queue_drains() {
2282        let runtime = reth_tasks::Runtime::test();
2283        let provider_factory = create_test_provider_factory();
2284        let anchor_hash = init_genesis(&provider_factory).expect("failed to initialize genesis");
2285        let state_provider_factory = OverlayStateProviderFactory::new(
2286            provider_factory,
2287            OverlayManager::<reth_chain_state::EthPrimitives>::default()
2288                .overlay_builder(anchor_hash),
2289        );
2290        let proof_worker_handle = ProofWorkerHandle::new(
2291            &runtime,
2292            ProofTaskCtx::new(state_provider_factory),
2293            ProofWorkerCounts::full(&runtime),
2294            Default::default(),
2295        );
2296
2297        let default_trie = RevealableSparseTrie::blind_from(ArenaParallelSparseTrie::default());
2298        let trie = SparseStateTrie::default()
2299            .with_accounts_trie(default_trie.clone())
2300            .with_default_storage_trie(default_trie)
2301            .with_updates(true);
2302
2303        let parent_state_root = B256::repeat_byte(0x55);
2304        let (updates_tx, updates_rx) = channel::unbounded();
2305        let (_cancel_guard, cancel_rx) = channel::bounded::<()>(0);
2306        let mut task = SparseTrieCacheTask::new_with_trie(
2307            &runtime,
2308            updates_rx,
2309            cancel_rx,
2310            mpsc::channel().0,
2311            proof_worker_handle,
2312            SparseTrieTaskMetrics::default(),
2313            trie,
2314            parent_state_root,
2315            TrieNodeEpoch::UNMODIFIED,
2316            1,
2317        );
2318
2319        // Keep an input queued so progress cannot use its normal queue-empty flush.
2320        updates_tx.send(StateRootMessage::PrefetchProofs(Default::default())).unwrap();
2321        let deadline = Instant::now();
2322        while task.updates.is_empty() {
2323            assert!(deadline.elapsed() < std::time::Duration::from_secs(1));
2324            thread::yield_now();
2325        }
2326        for index in 0..INITIAL_UPDATE_BATCH_SIZE {
2327            let mut state = HashedPostState::default();
2328            state.accounts.insert(
2329                B256::repeat_byte(index as u8),
2330                Some(Account { nonce: 1, ..Default::default() }),
2331            );
2332            task.on_hashed_state_update(state);
2333            task.pending_updates += 1;
2334            assert!(!task.make_progress().unwrap());
2335            if index + 1 < INITIAL_UPDATE_BATCH_SIZE {
2336                assert_eq!(task.in_flight_proof_jobs, 0);
2337            }
2338        }
2339        assert!(task.in_flight_proof_jobs > 0, "proof work must start before the queue drains");
2340        assert_eq!(task.pending_updates, 0);
2341
2342        // A second batch remains buffered; the early flush must not become a permanent small
2343        // batch policy that repeatedly scans and sorts pending leaves.
2344        for index in INITIAL_UPDATE_BATCH_SIZE..INITIAL_UPDATE_BATCH_SIZE * 2 {
2345            let mut state = HashedPostState::default();
2346            state.accounts.insert(
2347                B256::repeat_byte(index as u8),
2348                Some(Account { nonce: 1, ..Default::default() }),
2349            );
2350            task.on_hashed_state_update(state);
2351            task.pending_updates += 1;
2352            assert!(!task.make_progress().unwrap());
2353        }
2354        assert_eq!(task.pending_updates, INITIAL_UPDATE_BATCH_SIZE);
2355        assert_eq!(task.new_account_updates.len(), INITIAL_UPDATE_BATCH_SIZE);
2356        drop(updates_tx);
2357        drop(task);
2358        drain_sparse_trie_tasks(&runtime);
2359    }
2360
2361    #[reth_concurrency::test]
2362    fn run_returns_parent_root_without_revealing_blind_trie_when_no_state_updates() {
2363        let runtime = reth_tasks::Runtime::test();
2364        let provider_factory = create_test_provider_factory();
2365        let anchor_hash = init_genesis(&provider_factory).expect("failed to initialize genesis");
2366        let state_provider_factory = OverlayStateProviderFactory::new(
2367            provider_factory,
2368            OverlayManager::<reth_chain_state::EthPrimitives>::default()
2369                .overlay_builder(anchor_hash),
2370        );
2371        let proof_worker_handle = ProofWorkerHandle::new(
2372            &runtime,
2373            ProofTaskCtx::new(state_provider_factory),
2374            ProofWorkerCounts::full(&runtime),
2375            Default::default(),
2376        );
2377
2378        let default_trie = RevealableSparseTrie::blind_from(ArenaParallelSparseTrie::default());
2379        let trie = SparseStateTrie::default()
2380            .with_accounts_trie(default_trie.clone())
2381            .with_default_storage_trie(default_trie)
2382            .with_updates(true);
2383
2384        let parent_state_root = B256::repeat_byte(0x55);
2385        let (updates_tx, updates_rx) = channel::unbounded();
2386        let (_cancel_guard, cancel_rx) = channel::bounded::<()>(0);
2387        let mut task = SparseTrieCacheTask::new_with_trie(
2388            &runtime,
2389            updates_rx,
2390            cancel_rx,
2391            mpsc::channel().0,
2392            proof_worker_handle,
2393            SparseTrieTaskMetrics::default(),
2394            trie,
2395            parent_state_root,
2396            TrieNodeEpoch::UNMODIFIED,
2397            1,
2398        );
2399
2400        updates_tx.send(StateRootMessage::FinishedStateUpdates).unwrap();
2401        drop(updates_tx);
2402
2403        let outcome = task.run().expect("state root computation should succeed");
2404
2405        assert_eq!(outcome.state_root, parent_state_root);
2406        assert!(outcome.trie_updates.is_empty());
2407        assert!(task.trie.state_trie_ref().is_none(), "blind trie should not be revealed");
2408
2409        drop(task);
2410        drain_sparse_trie_tasks(&runtime);
2411    }
2412
2413    #[reth_concurrency::test]
2414    fn stall_check_waits_for_in_flight_proofs_then_reports_pending_updates() {
2415        let runtime = reth_tasks::Runtime::test();
2416        let provider_factory = create_test_provider_factory();
2417        let anchor_hash = init_genesis(&provider_factory).expect("failed to initialize genesis");
2418        let state_provider_factory = OverlayStateProviderFactory::new(
2419            provider_factory,
2420            OverlayManager::<reth_chain_state::EthPrimitives>::default()
2421                .overlay_builder(anchor_hash),
2422        );
2423        let proof_worker_handle = ProofWorkerHandle::new(
2424            &runtime,
2425            ProofTaskCtx::new(state_provider_factory),
2426            ProofWorkerCounts::full(&runtime),
2427            Default::default(),
2428        );
2429
2430        let default_trie = RevealableSparseTrie::blind_from(ArenaParallelSparseTrie::default());
2431        let trie = SparseStateTrie::default()
2432            .with_accounts_trie(default_trie.clone())
2433            .with_default_storage_trie(default_trie)
2434            .with_updates(true);
2435
2436        let (updates_tx, updates_rx) = channel::unbounded();
2437        let (_cancel_guard, cancel_rx) = channel::bounded::<()>(0);
2438        let mut task = SparseTrieCacheTask::new_with_trie(
2439            &runtime,
2440            updates_rx,
2441            cancel_rx,
2442            mpsc::channel().0,
2443            proof_worker_handle,
2444            SparseTrieTaskMetrics::default(),
2445            trie,
2446            B256::repeat_byte(0x55),
2447            TrieNodeEpoch::UNMODIFIED,
2448            1,
2449        );
2450
2451        drop(updates_tx);
2452
2453        let account = B256::repeat_byte(0x11);
2454        let slot = B256::repeat_byte(0x22);
2455        let account_target = B256::repeat_byte(0x33);
2456        let storage_target = B256::repeat_byte(0x44);
2457
2458        task.finished_state_updates = true;
2459        task.account_updates.insert(account, LeafUpdate::Touched);
2460        task.pending_account_updates.insert(account, None);
2461        task.fetched_account_targets.insert(account_target, ProofV2TargetParent::NONE);
2462
2463        // A storage leaf that stayed blocked after its pass ran, so no pass is ready to run.
2464        let StorageTrieState::Idle(work) = task.storage_trie_state_mut(account) else {
2465            panic!("a fresh trie state is idle")
2466        };
2467        work.updated = true;
2468        work.pending.insert(slot, LeafUpdate::Touched);
2469        work.fetched.insert(storage_target, ProofV2TargetParent::new(11));
2470        task.in_flight_proof_jobs = 1;
2471
2472        assert!(task.ensure_not_stalled(false).is_ok());
2473
2474        let result = Ok(DecodedMultiProofV2::default());
2475        task.complete_proof_job(result).expect("proof result should be ok");
2476
2477        assert_eq!(task.in_flight_proof_jobs, 0);
2478        let error = task.ensure_not_stalled(false).expect_err("task should be stalled");
2479        assert!(matches!(error, StateRootTaskError::Stalled));
2480        let error = error.to_string();
2481
2482        assert!(error.contains("sparse trie task stalled"));
2483        assert!(!error.contains("account_targets"));
2484        assert!(!error.contains("storage_targets"));
2485        assert!(!error.contains(&format!("{account:?}")));
2486        assert!(!error.contains(&format!("{account_target:?}")));
2487        assert!(!error.contains(&format!("{storage_target:?}")));
2488        assert!(!error.contains("pending_account_leaves"));
2489        assert!(!error.contains("pending_storage_leaves"));
2490        assert!(!error.contains("pending_account_updates"));
2491        assert!(!error.contains(&format!("{slot:?}")));
2492
2493        drop(task);
2494        drain_sparse_trie_tasks(&runtime);
2495    }
2496
2497    #[reth_concurrency::test]
2498    fn run_completes_when_hints_follow_updates_finish() {
2499        let runtime = reth_tasks::Runtime::test();
2500        let provider_factory = create_test_provider_factory();
2501        let anchor_hash = init_genesis(&provider_factory).expect("failed to initialize genesis");
2502        let state_provider_factory = OverlayStateProviderFactory::new(
2503            provider_factory,
2504            OverlayManager::<reth_chain_state::EthPrimitives>::default()
2505                .overlay_builder(anchor_hash),
2506        );
2507        let proof_worker_handle = ProofWorkerHandle::new(
2508            &runtime,
2509            ProofTaskCtx::new(state_provider_factory),
2510            ProofWorkerCounts::full(&runtime),
2511            Default::default(),
2512        );
2513
2514        let default_trie = RevealableSparseTrie::blind_from(ArenaParallelSparseTrie::default());
2515        let trie = SparseStateTrie::default()
2516            .with_accounts_trie(default_trie.clone())
2517            .with_default_storage_trie(default_trie)
2518            .with_updates(true);
2519
2520        let (updates_tx, updates_rx) = channel::unbounded();
2521        let (cancel_guard, cancel_rx) = channel::bounded::<()>(0);
2522        let mut task = SparseTrieCacheTask::new_with_trie(
2523            &runtime,
2524            updates_rx,
2525            cancel_rx,
2526            mpsc::channel().0,
2527            proof_worker_handle,
2528            SparseTrieTaskMetrics::default(),
2529            trie,
2530            B256::repeat_byte(0x55),
2531            TrieNodeEpoch::UNMODIFIED,
2532            1,
2533        );
2534
2535        updates_tx.send(StateRootMessage::FinishedStateUpdates).unwrap();
2536        // The hashing task returns after the finish marker, so this send fails if it already
2537        // dropped the receiver.
2538        let _ = updates_tx.send(StateRootMessage::PrefetchProofs(Default::default()));
2539
2540        // The hashing task forwards the finish marker and never forwards the hint after it.
2541        let wait_start = Instant::now();
2542        while task.updates.is_empty() {
2543            assert!(
2544                wait_start.elapsed() < std::time::Duration::from_secs(1),
2545                "hashing task did not queue the finish marker"
2546            );
2547            thread::yield_now();
2548        }
2549
2550        let (result_tx, result_rx) = mpsc::channel();
2551        let handle = thread::spawn(move || {
2552            let _ = result_tx.send(task.run());
2553        });
2554
2555        let result = result_rx.recv_timeout(std::time::Duration::from_secs(1));
2556        drop(cancel_guard);
2557        handle.join().unwrap();
2558
2559        assert!(result.expect("state root task stalled on a late hint").is_ok());
2560
2561        drop(updates_tx);
2562        drain_sparse_trie_tasks(&runtime);
2563    }
2564
2565    #[reth_concurrency::test]
2566    fn storage_jobs_reveal_separate_extensions_and_branches() {
2567        let runtime = Runtime::test();
2568        let (mut task, updates_tx, _cancel_guard) = test_task(&runtime, SparseStateTrie::default());
2569        let address = B256::repeat_byte(0x11);
2570        let slot = B256::repeat_byte(0x11);
2571        let sibling = B256::repeat_byte(0x12);
2572        let slot_path = Nibbles::unpack(slot);
2573        let sibling_path = Nibbles::unpack(sibling);
2574        let leaf =
2575            TrieNode::Leaf(LeafNode::new(slot_path.slice(2..), alloy_rlp::encode(U256::ONE)));
2576        let sibling_leaf = TrieNode::Leaf(LeafNode::new(
2577            sibling_path.slice(2..),
2578            alloy_rlp::encode(U256::from(2)),
2579        ));
2580        let state_mask = TrieMask::from(0b110);
2581        let mut buf = Vec::new();
2582        let leaf_rlp = leaf.rlp(&mut buf);
2583        buf.clear();
2584        let sibling_rlp = sibling_leaf.rlp(&mut buf);
2585        let branch = TrieNode::Branch(BranchNode::new(vec![leaf_rlp, sibling_rlp], state_mask));
2586        buf.clear();
2587        let extension =
2588            TrieNode::Extension(ExtensionNode::new(slot_path.slice(..1), branch.rlp(&mut buf)));
2589        let StorageTrieState::Idle(work) = task.storage_trie_state_mut(address) else {
2590            unreachable!()
2591        };
2592        work.queue_updates(B256Map::from_iter([(
2593            slot,
2594            LeafUpdate::Changed(alloy_rlp::encode(U256::from(3))),
2595        )]));
2596        // Proof workers emit children before parents, with masks on the branch, not its extension.
2597        work.queue_proofs(&mut vec![
2598            ProofTrieNode { path: slot_path.slice(..2), node: leaf, masks: None },
2599            ProofTrieNode { path: sibling_path.slice(..2), node: sibling_leaf, masks: None },
2600            ProofTrieNode {
2601                path: slot_path.slice(..1),
2602                node: branch,
2603                masks: Some(BranchNodeMasks {
2604                    hash_mask: state_mask,
2605                    tree_mask: TrieMask::default(),
2606                }),
2607            },
2608            ProofTrieNode { path: Nibbles::default(), node: extension, masks: None },
2609        ]);
2610        let work = check_out_storage(&mut task, address);
2611        task.spawn_storage_jobs(vec![StorageTrieJob { address, work }]);
2612        let message = receive_storage_job(&task);
2613        task.on_storage_job_message(message).unwrap();
2614
2615        assert_eq!(task.storage_in_flight, 0);
2616        assert_eq!(
2617            storage_slot_value(&task, &address, &slot),
2618            Some(alloy_rlp::encode(U256::from(3)))
2619        );
2620        assert_eq!(
2621            storage_slot_value(&task, &address, &sibling),
2622            Some(alloy_rlp::encode(U256::from(2)))
2623        );
2624        assert_eq!(
2625            storage_root_of(&mut task, address),
2626            reth_trie_common::root::storage_root_unsorted([
2627                (slot, U256::from(3)),
2628                (sibling, U256::from(2)),
2629            ])
2630        );
2631
2632        drop(updates_tx);
2633        drop(task);
2634        drain_sparse_trie_tasks(&runtime);
2635    }
2636}