Skip to main content

reth_trie_sparse/arena/
mod.rs

1mod branch_child_idx;
2mod cursor;
3mod nodes;
4
5use branch_child_idx::{BranchChildIdx, BranchChildIter};
6use cursor::{ArenaCursor, NextResult, SeekResult};
7use nodes::{
8    ArenaSparseNode, ArenaSparseNodeBranch, ArenaSparseNodeBranchChild, ArenaSparseNodeState,
9};
10
11use crate::{
12    LeafLookup, LeafLookupError, LeafUpdate, SparseTrie, SparseTrieUpdates, TrieNodeEpoch,
13};
14use alloc::{boxed::Box, collections::VecDeque, vec::Vec};
15use alloy_primitives::{keccak256, map::B256Map, B256};
16use alloy_trie::TrieMask;
17use core::{cmp::Reverse, mem};
18use reth_execution_errors::SparseTrieResult;
19use reth_trie_common::{
20    BranchNodeMasks, BranchNodeRef, ExtensionNodeRef, LeafNodeRef, Nibbles, ProofTrieNodeV2,
21    ProofV2TargetParent, RlpNode, TrieNodeV2, EMPTY_ROOT_HASH,
22};
23use slotmap::{DefaultKey, SlotMap};
24use smallvec::SmallVec;
25use tracing::{instrument, trace};
26
27/// Alias for the slotmap key type used as node references throughout the arena trie.
28type Index = DefaultKey;
29/// Alias for the slotmap used as the node arena throughout the arena trie.
30type NodeArena = SlotMap<Index, ArenaSparseNode>;
31
32const TRACE_TARGET: &str = "trie::arena";
33
34/// The maximum path length (in nibbles) for nodes that live in the upper trie. Nodes at this
35/// depth or deeper belong to lower subtries.
36const UPPER_TRIE_MAX_DEPTH: usize = 2;
37
38/// Compacts an arena by BFS-copying all reachable nodes into a fresh `SlotMap`, dropping
39/// unreachable (pruned) slots. Parents are stored before children for cache-friendly top-down
40/// traversal.
41fn compact_arena(arena: &mut NodeArena, root: &mut Index) {
42    let mut new_arena = SlotMap::with_capacity(arena.len());
43    let mut queue = VecDeque::new();
44
45    let root_node = arena.remove(*root).expect("root exists");
46    let new_root = new_arena.insert(root_node);
47    queue.push_back(new_root);
48
49    while let Some(new_idx) = queue.pop_front() {
50        // Invariant: any node popped from `queue` has been moved into `new_arena` but
51        // its Branch.children have not been rewritten yet — every Revealed(idx) here is
52        // still an old-arena index, and the child is still present in `arena` because
53        // only this parent's iteration can remove it (each child has exactly one parent).
54        let old_children: SmallVec<[(usize, Index); 16]> = match &new_arena[new_idx] {
55            ArenaSparseNode::Branch(b) => b
56                .children
57                .iter()
58                .enumerate()
59                .filter_map(|(i, c)| match c {
60                    ArenaSparseNodeBranchChild::Revealed(old_idx) => Some((i, *old_idx)),
61                    _ => None,
62                })
63                .collect(),
64            _ => continue,
65        };
66
67        for (child_pos, old_child_idx) in old_children {
68            let child_node = arena.remove(old_child_idx).expect("child exists");
69            let new_child_idx = new_arena.insert(child_node);
70            let ArenaSparseNode::Branch(b) = &mut new_arena[new_idx] else { unreachable!() };
71            b.children[child_pos] = ArenaSparseNodeBranchChild::Revealed(new_child_idx);
72            queue.push_back(new_child_idx);
73        }
74    }
75
76    debug_assert!(
77        arena.is_empty(),
78        "compact_arena: {} orphaned nodes remaining after BFS drain",
79        arena.len(),
80    );
81
82    *arena = new_arena;
83    *root = new_root;
84}
85
86/// Reusable traversal state and optional accumulators shared by
87/// [`ArenaSparseSubtrie`] and [`ArenaParallelSparseTrie`].
88#[derive(Debug, Default, Clone)]
89struct ArenaTrieBuffers {
90    /// Reusable cursor for trie traversals.
91    cursor: ArenaCursor,
92    /// Trie updates built up directly during hashing and structural changes. `Some` when
93    /// tracking updates, `None` otherwise. Initialized alongside `updates` in `set_updates`.
94    updates: Option<SparseTrieUpdates>,
95    /// Reusable buffer for RLP encoding.
96    rlp_buf: Vec<u8>,
97    /// Reusable buffer for child `RlpNode`s during hashing.
98    rlp_node_buf: Vec<RlpNode>,
99}
100
101impl ArenaTrieBuffers {
102    fn clear(&mut self) {
103        if let Some(updates) = self.updates.as_mut() {
104            updates.clear();
105        }
106        self.rlp_buf.clear();
107        self.rlp_node_buf.clear();
108    }
109}
110
111/// A subtrie within the arena-based parallel sparse trie.
112///
113/// Each subtrie owns its own arena, allowing parallel mutations across subtries.
114#[derive(Debug, Clone)]
115struct ArenaSparseSubtrie {
116    /// The arena allocating nodes within this subtrie.
117    arena: NodeArena,
118    /// The root node of this subtrie.
119    root: Index,
120    /// The absolute path of this subtrie's root in the full trie.
121    path: Nibbles,
122    /// Reusable buffers for traversal, RLP encoding, and update actions.
123    buffers: ArenaTrieBuffers,
124    /// Reusable buffer for collecting required proofs during leaf updates.
125    /// Each entry is `(index, proof)` where `index` is the position of the target in the
126    /// `sorted_updates` slice passed to [`Self::update_leaves`].
127    required_proofs: Vec<(usize, ArenaRequiredProof)>,
128    /// Total number of revealed leaves in this subtrie.
129    num_leaves: u64,
130    /// Number of dirty (modified since last hash) leaves in this subtrie.
131    num_dirty_leaves: u64,
132}
133
134impl ArenaSparseSubtrie {
135    /// Creates a new subtrie with a pre-allocated root slot containing
136    /// [`ArenaSparseNode::EmptyRoot`]. The caller must overwrite `subtrie.arena[subtrie.root]`
137    /// before use.
138    fn new(record_updates: bool) -> Box<Self> {
139        let mut arena = SlotMap::new();
140        let root =
141            arena.insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Revealed });
142        let buffers = ArenaTrieBuffers {
143            updates: record_updates.then(SparseTrieUpdates::default),
144            ..Default::default()
145        };
146        Box::new(Self {
147            arena,
148            root,
149            path: Nibbles::default(),
150            buffers,
151            required_proofs: Vec::new(),
152            num_leaves: 0,
153            num_dirty_leaves: 0,
154        })
155    }
156
157    /// Asserts that `num_leaves` and `num_dirty_leaves` match the actual counts in the arena.
158    #[cfg(debug_assertions)]
159    fn debug_assert_counters(&self) {
160        let (actual_leaves, actual_dirty) =
161            ArenaParallelSparseTrie::count_leaves_and_dirty(&self.arena, self.root);
162        debug_assert_eq!(
163            self.num_leaves, actual_leaves,
164            "subtrie {:?} num_leaves mismatch: stored {} vs actual {}",
165            self.path, self.num_leaves, actual_leaves,
166        );
167        debug_assert_eq!(
168            self.num_dirty_leaves, actual_dirty,
169            "subtrie {:?} num_dirty_leaves mismatch: stored {} vs actual {}",
170            self.path, self.num_dirty_leaves, actual_dirty,
171        );
172    }
173
174    /// Collapses nodes last modified before `prune_before` into hash stubs while copying retained
175    /// nodes into a compacted arena.
176    ///
177    /// Expects that all nodes have computed hashes (i.e. `prune` is called after hashing).
178    fn prune(&mut self, prune_before: TrieNodeEpoch) -> usize {
179        // Only branches can have pruneable children.
180        if !matches!(&self.arena[self.root], ArenaSparseNode::Branch(_)) {
181            return 0;
182        }
183
184        debug_assert_eq!(self.num_dirty_leaves, 0, "prune must run after hashing");
185
186        if prune_before == TrieNodeEpoch::UNMODIFIED {
187            return 0;
188        }
189
190        let old_count = self.arena.len();
191        // Do not reserve the old arena's size: discarded nodes should release their capacity.
192        let mut new_arena = SlotMap::new();
193        let mut new_num_leaves = 0u64;
194
195        // The subtrie root is retained by the owning upper trie.
196        let root_node = self.arena.remove(self.root).expect("root exists");
197        let new_root = new_arena.insert(root_node);
198        let mut stack = Vec::new();
199        if let Some(frame) =
200            prepare_retained_node(&new_arena, new_root, self.path, &mut new_num_leaves)
201        {
202            stack.push(frame);
203        }
204
205        while let Some(frame) = stack.last_mut() {
206            let Some((child_pos, nibble, old_child_idx)) = frame.next_revealed_child(&new_arena)
207            else {
208                stack.pop();
209                continue;
210            };
211
212            let parent_new_idx = frame.new_idx;
213            let mut child_path = frame.branch_logical_path;
214            child_path.push(nibble);
215
216            let child_epoch = self.arena[old_child_idx]
217                .state_ref()
218                .and_then(ArenaSparseNodeState::cached_epoch)
219                .expect("prune must run after hashing");
220
221            if child_epoch.should_prune(prune_before) {
222                let node = &self.arena[old_child_idx];
223                let rlp_node = node
224                    .state_ref()
225                    .and_then(ArenaSparseNodeState::cached_rlp_node)
226                    .cloned()
227                    .expect("prune must run after hashing");
228                trace!(
229                    target: TRACE_TARGET,
230                    path = ?child_path,
231                    variant = %AsRef::<str>::as_ref(node),
232                    cached_rlp_node = ?rlp_node,
233                    "pruning node",
234                );
235                let ArenaSparseNode::Branch(b) = &mut new_arena[parent_new_idx] else {
236                    unreachable!()
237                };
238                b.children[child_pos] = ArenaSparseNodeBranchChild::Blinded(rlp_node);
239            } else {
240                let child_node = self.arena.remove(old_child_idx).expect("child exists");
241                let new_child_idx = new_arena.insert(child_node);
242                if let Some(frame) = prepare_retained_node(
243                    &new_arena,
244                    new_child_idx,
245                    child_path,
246                    &mut new_num_leaves,
247                ) {
248                    stack.push(frame);
249                }
250                let ArenaSparseNode::Branch(b) = &mut new_arena[parent_new_idx] else {
251                    unreachable!()
252                };
253                b.children[child_pos] = ArenaSparseNodeBranchChild::Revealed(new_child_idx);
254            }
255        }
256
257        let pruned = old_count - new_arena.len();
258        self.num_leaves = new_num_leaves;
259        self.num_dirty_leaves = 0;
260        self.arena = new_arena;
261        self.root = new_root;
262
263        #[cfg(debug_assertions)]
264        self.debug_assert_counters();
265        return pruned;
266
267        struct CopyFrame {
268            new_idx: Index,
269            branch_logical_path: Nibbles,
270            state_mask: TrieMask,
271            remaining_child_mask: TrieMask,
272        }
273
274        impl CopyFrame {
275            fn next_revealed_child(&mut self, new_arena: &NodeArena) -> Option<(usize, u8, Index)> {
276                let ArenaSparseNode::Branch(b) = &new_arena[self.new_idx] else { unreachable!() };
277
278                loop {
279                    let nibble = self.remaining_child_mask.first_set_bit_index()?;
280                    self.remaining_child_mask.unset_bit(nibble);
281                    let child_idx = BranchChildIdx::new(self.state_mask, nibble)
282                        .expect("remaining_child_mask must be a subset of state_mask");
283
284                    if let ArenaSparseNodeBranchChild::Revealed(old_idx) = b.children[child_idx] {
285                        return Some((child_idx.get(), nibble, old_idx))
286                    }
287                }
288            }
289        }
290
291        /// Prepares a retained node for copying, returning a stack frame when the node has children
292        /// to walk.
293        fn prepare_retained_node(
294            new_arena: &NodeArena,
295            new_idx: Index,
296            node_path: Nibbles,
297            new_num_leaves: &mut u64,
298        ) -> Option<CopyFrame> {
299            let ArenaSparseNode::Branch(b) = &new_arena[new_idx] else {
300                if matches!(&new_arena[new_idx], ArenaSparseNode::Leaf { .. }) {
301                    *new_num_leaves += 1;
302                }
303                return None;
304            };
305
306            let mut branch_logical_path = node_path;
307            branch_logical_path.extend(&b.short_key);
308
309            Some(CopyFrame {
310                new_idx,
311                branch_logical_path,
312                state_mask: b.state_mask,
313                remaining_child_mask: b.state_mask,
314            })
315        }
316    }
317
318    /// Applies leaf updates within this subtrie. Uses the same walk-down-with-cursor pattern as
319    /// [`Self::reveal_nodes`], but checks accessibility for [`LeafUpdate::Touched`] entries.
320    ///
321    /// `sorted_updates` must be sorted lexicographically by their nibbles path (index 1).
322    ///
323    /// Any required proofs are appended to `self.required_proofs` and should be drained by the
324    /// caller after this method returns.
325    #[instrument(
326        level = "trace",
327        target = TRACE_TARGET,
328        skip_all,
329        fields(
330            subtrie = ?self.path,
331            num_updates = sorted_updates.len(),
332        ),
333    )]
334    fn update_leaves(&mut self, sorted_updates: &[(B256, Nibbles, LeafUpdate)]) {
335        if sorted_updates.is_empty() {
336            return;
337        }
338        trace!(target: TRACE_TARGET, "Subtrie update_leaves");
339
340        debug_assert!(
341            !matches!(self.arena[self.root], ArenaSparseNode::EmptyRoot { .. }),
342            "subtrie root must not be EmptyRoot at start of update_leaves"
343        );
344
345        self.buffers.cursor.reset(&self.arena, self.root, self.path);
346
347        for (idx, &(key, ref full_path, ref update)) in sorted_updates.iter().enumerate() {
348            let find_result = self.buffers.cursor.seek(&mut self.arena, full_path);
349
350            // If the path hits a blinded node, request a proof regardless of update type.
351            if matches!(find_result, SeekResult::Blinded) {
352                let logical_len = self.buffers.cursor.head_logical_branch_path_len(&self.arena);
353                self.required_proofs.push((
354                    idx,
355                    ArenaRequiredProof { key, parent: ProofV2TargetParent::new(logical_len) },
356                ));
357                continue;
358            }
359
360            match update {
361                LeafUpdate::Changed(value) if !value.is_empty() => {
362                    // Upsert: insert or update a leaf with the given value.
363                    let (_result, deltas) = ArenaParallelSparseTrie::upsert_leaf(
364                        &mut self.arena,
365                        &mut self.buffers.cursor,
366                        &mut self.root,
367                        full_path,
368                        value,
369                        find_result,
370                    );
371                    self.num_leaves = (self.num_leaves as i64 + deltas.num_leaves_delta) as u64;
372                    self.num_dirty_leaves =
373                        (self.num_dirty_leaves as i64 + deltas.num_dirty_leaves_delta) as u64;
374                }
375                LeafUpdate::Changed(_) => {
376                    let (result, deltas) = ArenaParallelSparseTrie::remove_leaf(
377                        &mut self.arena,
378                        &mut self.buffers.cursor,
379                        &mut self.root,
380                        key,
381                        full_path,
382                        find_result,
383                        &mut self.buffers.updates,
384                    );
385                    self.num_leaves = (self.num_leaves as i64 + deltas.num_leaves_delta) as u64;
386                    self.num_dirty_leaves =
387                        (self.num_dirty_leaves as i64 + deltas.num_dirty_leaves_delta) as u64;
388
389                    if let RemoveLeafResult::NeedsProof { key, proof_key, parent } = result {
390                        self.required_proofs
391                            .push((idx, ArenaRequiredProof { key: proof_key, parent }));
392                        self.required_proofs.push((idx, ArenaRequiredProof { key, parent }));
393                    }
394                }
395                LeafUpdate::Touched => {}
396            }
397        }
398
399        // Drain remaining cursor entries, propagating dirty state.
400        self.buffers.cursor.drain(&mut self.arena);
401
402        #[cfg(debug_assertions)]
403        self.debug_assert_counters();
404    }
405
406    /// Reveals nodes inside this subtrie. Uses [`ArenaCursor::seek`] to locate the ancestor
407    /// node, then replaces blinded children with the proof nodes.
408    fn reveal_nodes(&mut self, nodes: &mut [ProofTrieNodeV2]) -> SparseTrieResult<()> {
409        if nodes.is_empty() {
410            return Ok(());
411        }
412        trace!(target: TRACE_TARGET, path = ?self.path, num_nodes = nodes.len(), "Subtrie reveal_nodes");
413
414        debug_assert!(
415            !matches!(self.arena[self.root], ArenaSparseNode::EmptyRoot { .. }),
416            "subtrie root must not be EmptyRoot in reveal_nodes"
417        );
418
419        self.buffers.cursor.reset(&self.arena, self.root, self.path);
420
421        for node in nodes.iter_mut() {
422            let find_result = self.buffers.cursor.seek(&mut self.arena, &node.path);
423            if ArenaParallelSparseTrie::reveal_node(
424                &mut self.arena,
425                &self.buffers.cursor,
426                node,
427                find_result,
428            )
429            .is_some_and(|child_idx| matches!(self.arena[child_idx], ArenaSparseNode::Leaf { .. }))
430            {
431                self.num_leaves += 1;
432            }
433        }
434
435        // Drain remaining cursor entries, propagating dirty state.
436        self.buffers.cursor.drain(&mut self.arena);
437
438        #[cfg(debug_assertions)]
439        self.debug_assert_counters();
440
441        Ok(())
442    }
443
444    /// Computes and caches `RlpNode` for all dirty nodes via iterative post-order DFS.
445    /// After this call every node reachable from `self.root` will be in `Cached` state.
446    ///
447    /// Trie updates are written directly to `self.buffers.updates` (if `Some`).
448    fn update_cached_rlp(&mut self, new_epoch: TrieNodeEpoch) {
449        ArenaParallelSparseTrie::update_cached_rlp(
450            &mut self.arena,
451            self.root,
452            self.path,
453            &mut self.buffers,
454            new_epoch,
455        );
456        self.num_dirty_leaves = 0;
457        #[cfg(debug_assertions)]
458        self.debug_assert_counters();
459    }
460}
461
462/// Tracks the net change in leaf counters caused by a trie mutation (upsert or removal).
463/// Returned alongside [`UpsertLeafResult`] / [`RemoveLeafResult`] so the caller can maintain
464/// aggregate counters on [`ArenaSparseSubtrie`] without scanning the arena.
465#[derive(Debug, Default)]
466struct SubtrieCounterDeltas {
467    num_leaves_delta: i64,
468    num_dirty_leaves_delta: i64,
469}
470
471/// Result of `upsert_leaf` indicating whether a new child was created that the caller
472/// may need to wrap as a subtrie (in the upper trie).
473#[derive(Debug)]
474enum UpsertLeafResult {
475    /// A leaf was updated in place (no structural change).
476    Updated,
477    /// A new leaf was created (e.g. EmptyRoot→Leaf, or root-level split).
478    NewLeaf,
479    /// A new child (branch or leaf) was created or inserted. The child is the cursor head
480    /// and its parent is the cursor's parent.
481    NewChild,
482}
483
484/// Result of `remove_leaf` indicating whether a proof is needed to complete a branch
485/// collapse.
486#[derive(Debug)]
487enum RemoveLeafResult {
488    /// No proof needed — the removal (and any collapse) completed fully.
489    Removed,
490    /// No leaf was found at the given path (no-op).
491    NotFound,
492    /// The branch collapse requires revealing a blinded sibling. The caller must request a
493    /// proof for the given key below the revealed logical parent branch.
494    NeedsProof { key: B256, proof_key: B256, parent: ProofV2TargetParent },
495}
496
497/// A proof request generated during leaf updates when a blinded node is encountered.
498#[derive(Debug, Clone)]
499struct ArenaRequiredProof {
500    /// The key requiring a proof.
501    key: B256,
502    /// The revealed logical parent branch.
503    parent: ProofV2TargetParent,
504}
505
506/// An arena-based parallel sparse trie.
507///
508/// Configuration for controlling when parallelism is enabled in [`ArenaParallelSparseTrie`]
509/// operations.
510#[derive(Debug, Clone, Copy, PartialEq, Eq)]
511pub struct ArenaParallelismThresholds {
512    /// Minimum number of dirty leaves in a subtrie before it is eligible for parallel hash
513    /// computation. Subtries with fewer dirty leaves than this are hashed serially during
514    /// [`ArenaParallelSparseTrie::update_subtrie_hashes`].
515    pub min_dirty_leaves: u64,
516    /// Minimum number of nodes to reveal in a subtrie before it is eligible for parallel
517    /// reveal. Subtries with fewer nodes to reveal than this are revealed inline during the
518    /// upper trie walk.
519    pub min_revealed_nodes: usize,
520    /// Minimum number of leaf updates targeting a subtrie before it is eligible for parallel
521    /// update. Subtries with fewer updates than this are updated inline during the upper trie
522    /// walk.
523    pub min_updates: usize,
524    /// Minimum number of revealed leaves in a subtrie before it is eligible for parallel
525    /// pruning. Subtries with fewer leaves than this are pruned inline during the upper trie
526    /// walk.
527    pub min_leaves_for_prune: u64,
528}
529
530impl Default for ArenaParallelismThresholds {
531    fn default() -> Self {
532        Self {
533            min_dirty_leaves: 64,
534            min_revealed_nodes: 16,
535            min_updates: 128,
536            min_leaves_for_prune: 128,
537        }
538    }
539}
540
541/// An arena-based sparse trie whose subtries can be mutated in parallel.
542///
543/// ## Structure
544///
545/// Uses arena allocation ([`slotmap::SlotMap`]) for node storage with direct index-based child
546/// pointers, avoiding the per-node hashing overhead of a `HashMap`-based trie. The trie is split
547/// into two tiers:
548///
549/// - **Upper trie** (`upper_arena`): Contains nodes whose path is shorter than
550///   `UPPER_TRIE_MAX_DEPTH` nibbles. These are the root and its immediate children.
551/// - **Lower subtries** (`ArenaSparseSubtrie`): Each child of an upper-trie branch at the depth
552///   boundary becomes the root of its own subtrie, stored as an `ArenaSparseNode::Subtrie` child in
553///   the upper arena. Each subtrie owns its own arena, enabling lock-free parallel mutation.
554///
555/// Node placement is determined by path length (not counting a branch's short key):
556///
557/// - Paths with **< `UPPER_TRIE_MAX_DEPTH`** nibbles live in `upper_arena`.
558/// - Paths with **≥ `UPPER_TRIE_MAX_DEPTH`** nibbles live in a subtrie.
559///
560/// ## Node Revealing
561///
562/// Nodes are lazily revealed from proof data via [`SparseTrie::reveal_nodes`]. Each node is
563/// placed into the upper arena or delegated to its subtrie based on path depth. Unrevealed
564/// children are stored as `ArenaSparseNodeBranchChild::Blinded` with their RLP encoding.
565/// When multiple subtries have pending reveals, they are processed in parallel using rayon
566/// (controlled by [`ArenaParallelismThresholds::min_revealed_nodes`]).
567///
568/// ## Leaf Operations
569///
570/// Leaf updates and removals are applied via [`SparseTrie::update_leaves`]. The method walks
571/// the upper trie to route each update to the correct subtrie, then processes subtries in
572/// parallel when the update count exceeds [`ArenaParallelismThresholds::min_updates`].
573///
574/// After updates, structural changes (branch collapse, subtrie unwrapping) are handled by
575/// propagating dirty state back up through the upper trie.
576///
577/// ## Root Hash Calculation
578///
579/// Root hash computation follows a bottom-up approach:
580///
581/// 1. **[`SparseTrie::update_subtrie_hashes`]**: Takes dirty subtries from the upper arena and
582///    hashes them in parallel (when dirty leaf count meets
583///    [`ArenaParallelismThresholds::min_dirty_leaves`]), then walks the upper trie to restore
584///    hashed subtries and inline-hash any remaining dirty nodes.
585/// 2. **[`SparseTrie::root`]**: Calls `update_subtrie_hashes`, then RLP-encodes the full upper trie
586///    depth-first to produce the root hash.
587///
588/// Each node tracks its state via `ArenaSparseNodeState` (`Revealed`, `Cached`, or `Dirty`)
589/// so only modified subtrees are recomputed.
590///
591/// ## Pruning
592///
593/// [`SparseTrie::prune`] replaces nodes older than its epoch cutoff with
594/// `ArenaSparseNodeBranchChild::Blinded` entries using their cached RLP, then compacts the
595/// arenas. Subtries are pruned in parallel when their leaf count exceeds
596/// [`ArenaParallelismThresholds::min_leaves_for_prune`].
597#[derive(Debug, Clone)]
598pub struct ArenaParallelSparseTrie {
599    /// The arena allocating nodes in the upper trie.
600    upper_arena: NodeArena,
601    /// The root node of the upper trie.
602    root: Index,
603    /// Reusable buffers for traversal, RLP encoding, and update actions.
604    buffers: ArenaTrieBuffers,
605    /// Thresholds controlling when parallelism is enabled for different operations.
606    parallelism_thresholds: ArenaParallelismThresholds,
607}
608
609impl ArenaParallelSparseTrie {
610    /// Sets the thresholds that control when parallelism is used during operations.
611    pub const fn with_parallelism_thresholds(
612        mut self,
613        thresholds: ArenaParallelismThresholds,
614    ) -> Self {
615        self.parallelism_thresholds = thresholds;
616        self
617    }
618
619    /// Returns `true` if a node at the given path length should be placed in a subtrie rather
620    /// than the upper arena.
621    const fn should_be_subtrie(path_len: usize) -> bool {
622        path_len == UPPER_TRIE_MAX_DEPTH
623    }
624
625    /// If the child at the cursor head should be a subtrie based on its depth, wraps it
626    /// in [`ArenaSparseNode::Subtrie`].
627    ///
628    /// The child must be the cursor head and its parent the cursor's parent.
629    fn maybe_wrap_in_subtrie(&mut self, child_idx: Index, child_path: &Nibbles) {
630        if !Self::should_be_subtrie(child_path.len()) {
631            return;
632        }
633
634        // Only branch and leaf nodes can become subtrie roots.
635        if !matches!(
636            self.upper_arena[child_idx],
637            ArenaSparseNode::Branch(_) | ArenaSparseNode::Leaf { .. }
638        ) {
639            return;
640        }
641
642        trace!(target: TRACE_TARGET, ?child_path, "Wrapping child into subtrie");
643        let mut subtrie = ArenaSparseSubtrie::new(self.buffers.updates.is_some());
644        subtrie.path = *child_path;
645        let mut root_node =
646            mem::replace(&mut self.upper_arena[child_idx], ArenaSparseNode::TakenSubtrie);
647
648        // Migrate any revealed children from the upper arena into the subtrie arena.
649        if let ArenaSparseNode::Branch(b) = &mut root_node {
650            for child in &mut b.children {
651                if let ArenaSparseNodeBranchChild::Revealed(idx) = child {
652                    *idx =
653                        Self::migrate_nodes(&mut subtrie.arena, &mut self.upper_arena, *idx, None);
654                }
655            }
656        }
657
658        subtrie.arena[subtrie.root] = root_node;
659        let (leaves, dirty) = Self::count_leaves_and_dirty(&subtrie.arena, subtrie.root);
660        subtrie.num_leaves = leaves;
661        subtrie.num_dirty_leaves = dirty;
662        #[cfg(debug_assertions)]
663        subtrie.debug_assert_counters();
664        self.upper_arena[child_idx] = ArenaSparseNode::Subtrie(subtrie);
665    }
666
667    /// If the cursor head is a branch, wraps any revealed children that sit at
668    /// the subtrie boundary depth (`UPPER_TRIE_MAX_DEPTH`). This is needed after
669    /// structural changes like root-level splits or subtrie unwraps that can place
670    /// non-subtrie nodes at the boundary depth.
671    fn maybe_wrap_branch_children(&mut self, cursor: &ArenaCursor) {
672        let head = cursor.head().expect("cursor is non-empty");
673        let head_idx = head.index;
674        let head_path = head.path;
675
676        let ArenaSparseNode::Branch(b) = &self.upper_arena[head_idx] else { return };
677        let short_key = b.short_key;
678        let children: SmallVec<[_; 4]> = b
679            .child_iter()
680            .filter_map(|(nibble, child)| match child {
681                ArenaSparseNodeBranchChild::Revealed(idx) => Some((nibble, *idx)),
682                ArenaSparseNodeBranchChild::Blinded(_) => None,
683            })
684            .collect();
685
686        for (nibble, child_idx) in children {
687            let mut child_path = head_path;
688            child_path.extend(&short_key);
689            child_path.push_unchecked(nibble);
690            self.maybe_wrap_in_subtrie(child_idx, &child_path);
691        }
692    }
693
694    /// Checks whether the subtrie at the cursor head has become empty after updates.
695    /// If the subtrie's root is [`ArenaSparseNode::EmptyRoot`] (all leaves were removed), the
696    /// child slot is removed from the parent branch entirely, the subtrie is recycled, and
697    /// if the parent is left with a single revealed child, it is collapsed via
698    /// `collapse_branch`.
699    ///
700    /// The subtrie must be the cursor head and its parent the cursor's parent.
701    /// Pops the subtrie entry (propagating leaf count deltas) before returning.
702    #[instrument(
703        level = "trace",
704        target = TRACE_TARGET,
705        skip_all,
706        fields(subtrie_path = ?cursor.head().expect("cursor is non-empty").path),
707    )]
708    fn maybe_unwrap_subtrie(&mut self, cursor: &mut ArenaCursor) {
709        let subtrie_idx = cursor.head().expect("cursor is non-empty").index;
710
711        let ArenaSparseNode::Subtrie(subtrie) = &self.upper_arena[subtrie_idx] else {
712            return;
713        };
714
715        if !matches!(subtrie.arena[subtrie.root], ArenaSparseNode::EmptyRoot { .. }) {
716            return;
717        }
718
719        let child_nibble = cursor
720            .head()
721            .expect("cursor is non-empty")
722            .path
723            .last()
724            .expect("subtrie path must have at least one nibble");
725        let parent_idx = cursor.parent().expect("cursor has parent").index;
726
727        // Pop the subtrie entry before mutating, so collapse_branch sees the parent as
728        // the cursor head.
729        cursor.pop(&mut self.upper_arena);
730
731        self.recycle_subtrie_from_idx(subtrie_idx);
732
733        trace!(target: TRACE_TARGET, "Unwrapping empty subtrie, removing child slot");
734        let parent_branch = self.upper_arena[parent_idx].branch_mut();
735        let child_idx = BranchChildIdx::new(parent_branch.state_mask, child_nibble)
736            .expect("child nibble not found in parent state_mask");
737
738        parent_branch.children.remove(child_idx.get());
739        parent_branch.unset_child_bit(child_nibble);
740        // The branch structure changed (child removed), so any cached RLP is stale.
741        parent_branch.state = parent_branch.state.to_dirty();
742
743        self.maybe_collapse_or_remove_branch(cursor);
744    }
745
746    /// Merges buffered updates from a [`ArenaSparseNode::Subtrie`] and drops it.
747    ///
748    /// # Panics
749    ///
750    /// Panics if `node` is not a `Subtrie`.
751    fn recycle_subtrie(&mut self, node: ArenaSparseNode) {
752        let ArenaSparseNode::Subtrie(mut subtrie) = node else {
753            unreachable!("recycle_subtrie called on non-Subtrie node")
754        };
755        Self::merge_subtrie_updates(&mut self.buffers.updates, &mut subtrie.buffers.updates);
756    }
757
758    /// Removes a [`ArenaSparseNode::Subtrie`] from the upper arena at `idx` and recycles it.
759    fn recycle_subtrie_from_idx(&mut self, idx: Index) {
760        let node = self.upper_arena.remove(idx).expect("subtrie exists in arena");
761        self.recycle_subtrie(node);
762    }
763
764    /// Handles cascading structural changes on the branch at the cursor head after a child
765    /// has been removed.
766    ///
767    /// Depending on the remaining child count:
768    /// - **0 children**: the branch becomes `EmptyRoot` (if root) or is removed from its parent,
769    ///   cascading upward.
770    /// - **1 child**: collapses the branch into its sole child, unless that child is a
771    ///   `TakenSubtrie` (deferred) or blinded. If the remaining child is an empty subtrie, it is
772    ///   also removed, reducing to the 0-children case.
773    /// - **2+ children**: nothing to do.
774    fn maybe_collapse_or_remove_branch(&mut self, cursor: &mut ArenaCursor) {
775        loop {
776            let branch_entry = cursor.head().expect("cursor is non-empty");
777            let branch_idx = branch_entry.index;
778            let branch_path = branch_entry.path;
779
780            // Read-only phase: extract the count and remaining-child info we need before
781            // mutating. All values here are Copy so the borrow is released.
782            let count = {
783                let ArenaSparseNode::Branch(b) = &self.upper_arena[branch_idx] else {
784                    return;
785                };
786                b.state_mask.count_bits()
787            };
788
789            if count >= 2 {
790                return;
791            }
792
793            if count == 0 {
794                if branch_idx == self.root {
795                    self.upper_arena[branch_idx] =
796                        ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Dirty };
797                    return;
798                }
799                // Remove the empty branch from its parent.
800                let branch_nibble = branch_path.last().expect("non-root branch");
801                cursor.pop(&mut self.upper_arena);
802                self.upper_arena.remove(branch_idx);
803                let parent_idx = cursor.head().expect("cursor is non-empty").index;
804                let parent_branch = self.upper_arena[parent_idx].branch_mut();
805                let child_idx = BranchChildIdx::new(parent_branch.state_mask, branch_nibble)
806                    .expect("child nibble not found in parent state_mask");
807                parent_branch.children.remove(child_idx.get());
808                parent_branch.unset_child_bit(branch_nibble);
809                parent_branch.state = parent_branch.state.to_dirty();
810                continue; // re-check the parent
811            }
812
813            // count == 1 — determine what kind of child remains.
814            let (remaining_nibble, remaining_child_idx) = {
815                let b = self.upper_arena[branch_idx].branch_ref();
816                let nibble = b.state_mask.iter().next().expect("branch has at least one child");
817                let child_idx = match &b.children[0] {
818                    ArenaSparseNodeBranchChild::Revealed(idx) => Some(*idx),
819                    ArenaSparseNodeBranchChild::Blinded(_) => None,
820                };
821                (nibble, child_idx)
822            };
823
824            let Some(child_idx) = remaining_child_idx else {
825                debug_assert!(false, "single remaining child is blinded — should have been caught by check_subtrie_collapse_needs_proof");
826                return;
827            };
828
829            if matches!(self.upper_arena[child_idx], ArenaSparseNode::TakenSubtrie) {
830                // Subtrie hasn't been restored yet; collapse is deferred to the
831                // post-restore phase.
832                return;
833            }
834
835            // Check if the remaining child is an empty subtrie that should also be removed.
836            let is_empty_subtrie = matches!(
837                &self.upper_arena[child_idx],
838                ArenaSparseNode::Subtrie(s) if matches!(s.arena[s.root], ArenaSparseNode::EmptyRoot { .. })
839            );
840
841            if is_empty_subtrie {
842                self.recycle_subtrie_from_idx(child_idx);
843                let branch = self.upper_arena[branch_idx].branch_mut();
844                branch.children.remove(0);
845                branch.unset_child_bit(remaining_nibble);
846                branch.state = branch.state.to_dirty();
847                continue; // now count == 0, will be handled next iteration
848            }
849
850            // Normal collapse: the remaining child is a Leaf, Branch, or non-empty Subtrie.
851            Self::collapse_branch(
852                &mut self.upper_arena,
853                cursor,
854                &mut self.root,
855                &mut self.buffers.updates,
856            );
857
858            // After collapse, the remaining child (now at cursor head) may be a
859            // Subtrie whose path was shortened by the collapsed branch's prefix. Since
860            // should_be_subtrie requires path_len == UPPER_TRIE_MAX_DEPTH and the collapse
861            // made the path shorter, the subtrie is no longer eligible — unwrap it.
862            let child_idx = cursor.head().expect("cursor is non-empty").index;
863            if let ArenaSparseNode::Subtrie(_) = &self.upper_arena[child_idx] {
864                let ArenaSparseNode::Subtrie(mut subtrie) =
865                    mem::replace(&mut self.upper_arena[child_idx], ArenaSparseNode::TakenSubtrie)
866                else {
867                    unreachable!()
868                };
869                Self::migrate_nodes(
870                    &mut self.upper_arena,
871                    &mut subtrie.arena,
872                    subtrie.root,
873                    Some(child_idx),
874                );
875                Self::merge_subtrie_updates(
876                    &mut self.buffers.updates,
877                    &mut subtrie.buffers.updates,
878                );
879
880                // The migrated subtrie root may be a branch whose children now live in
881                // the upper arena at or beyond the subtrie boundary depth. Re-wrap any
882                // such children as subtries.
883                self.maybe_wrap_branch_children(cursor);
884            }
885            return;
886        }
887    }
888
889    /// Appends a subtrie's updates after the parent's earlier updates. Paths shared with
890    /// earlier hashing passes are resolved when updates are taken.
891    fn merge_subtrie_updates(
892        dst: &mut Option<SparseTrieUpdates>,
893        src: &mut Option<SparseTrieUpdates>,
894    ) {
895        if let Some(dst) = dst.as_mut() {
896            dst.append(src.as_mut().expect("updates are enabled"));
897        }
898    }
899
900    /// Right-pads a nibble path with zeros and packs it into a [`B256`].
901    fn nibbles_to_padded_b256(path: &Nibbles) -> B256 {
902        let mut bytes = [0u8; 32];
903        path.pack_to(&mut bytes);
904        B256::from(bytes)
905    }
906
907    /// Returns the [`BranchNodeMasks`] for a branch based on the status of its children.
908    fn get_branch_masks(arena: &NodeArena, branch: &ArenaSparseNodeBranch) -> BranchNodeMasks {
909        let mut masks = BranchNodeMasks::default();
910
911        for (nibble, child) in branch.child_iter() {
912            let (hash_bit, tree_bit) = match child {
913                ArenaSparseNodeBranchChild::Blinded(_) => (
914                    branch.branch_masks.hash_mask.is_bit_set(nibble),
915                    branch.branch_masks.tree_mask.is_bit_set(nibble),
916                ),
917                ArenaSparseNodeBranchChild::Revealed(child_idx) => {
918                    let child = &arena[*child_idx];
919                    (child.hash_mask_bit(), child.tree_mask_bit())
920                }
921            };
922
923            masks.set_child_bits(nibble, hash_bit, tree_bit);
924        }
925
926        masks
927    }
928
929    /// Computes and caches `RlpNode` for all dirty nodes reachable from `root` in `arena`.
930    ///
931    /// Uses the cursor's stack to walk dirty branches depth-first. For each branch,
932    /// children are iterated left-to-right:
933    /// - Blinded, cached, leaf, and `EmptyRoot` children have their `RlpNode` pushed directly onto
934    ///   `rlp_node_buf`.
935    /// - Dirty branch children are pushed onto `stack` and processed recursively first.
936    ///
937    /// When a dirty branch child finishes and is popped, the parent resumes iteration after
938    /// the child's nibble. Once all children of a branch are processed, the branch is encoded
939    /// via `BranchNodeRef` using the last N entries on `rlp_node_buf`, then replaced with a
940    /// single result `RlpNode`.
941    #[instrument(level = "trace", target = TRACE_TARGET, skip_all, fields(base_path = ?base_path), ret)]
942    fn update_cached_rlp(
943        arena: &mut NodeArena,
944        root: Index,
945        base_path: Nibbles,
946        buffers: &mut ArenaTrieBuffers,
947        new_epoch: TrieNodeEpoch,
948    ) -> RlpNode {
949        let cursor = &mut buffers.cursor;
950        let rlp_buf = &mut buffers.rlp_buf;
951        let rlp_node_buf = &mut buffers.rlp_node_buf;
952        let updates = &mut buffers.updates;
953
954        rlp_node_buf.clear();
955
956        // Step 1: Handle trivial roots that don't need the stack-based walk.
957        // Empty roots and leaves are encoded in place. Already-cached branches need no work.
958        // Only dirty branches enter the main loop below.
959        match &arena[root] {
960            ArenaSparseNode::EmptyRoot { state } => {
961                let node_epoch = match state {
962                    ArenaSparseNodeState::Cached { epoch, .. } => *epoch,
963                    ArenaSparseNodeState::Revealed => TrieNodeEpoch::UNMODIFIED,
964                    ArenaSparseNodeState::Dirty => new_epoch,
965                };
966                let rlp_node = RlpNode::word_rlp(&EMPTY_ROOT_HASH);
967                *arena[root].state_mut() =
968                    ArenaSparseNodeState::Cached { rlp_node: rlp_node.clone(), epoch: node_epoch };
969                return rlp_node
970            }
971            ArenaSparseNode::Leaf { .. } => {
972                Self::encode_leaf(arena, root, rlp_buf, rlp_node_buf, new_epoch);
973                return rlp_node_buf.pop().expect("encode_leaf must push an RlpNode");
974            }
975            ArenaSparseNode::Branch(b) => {
976                if let ArenaSparseNodeState::Cached { rlp_node, .. } = &b.state {
977                    let rlp_node = rlp_node.clone();
978                    return rlp_node;
979                }
980            }
981            ArenaSparseNode::Subtrie(_) | ArenaSparseNode::TakenSubtrie => {
982                unreachable!("Subtrie/TakenSubtrie should not appear inside a subtrie's own arena");
983            }
984        }
985
986        cursor.reset(arena, root, base_path);
987
988        // Step 2: Walk dirty branches depth-first using `cursor.next`. Only dirty branches
989        // are descended into; all other children (leaves, cached branches, blinded, subtries)
990        // are encoded when their parent branch is popped.
991        loop {
992            let result = cursor.next(&mut *arena, |_, node| {
993                matches!(
994                    node,
995                    ArenaSparseNode::Branch(b) if matches!(b.state, ArenaSparseNodeState::Dirty)
996                )
997            });
998
999            match result {
1000                NextResult::Done => break,
1001                NextResult::NonBranch => {
1002                    unreachable!("should_descend only returns true for dirty branches")
1003                }
1004                NextResult::Branch => {}
1005            };
1006
1007            let head = cursor.head().expect("cursor is non-empty");
1008            let head_idx = head.index;
1009            let head_path = head.path;
1010
1011            // The branch at `head_idx` is exhausted. All its dirty child branches
1012            // have already been encoded and cached. Collect all children's RLP nodes
1013            // and encode the branch.
1014            trace!(
1015                target: TRACE_TARGET,
1016                branch_path = ?head_path,
1017                branch_short_key = ?arena[head_idx].short_key().expect("head is a branch"),
1018                state_mask = ?arena[head_idx].branch_ref().state_mask,
1019                "Calculating branch RlpNode",
1020            );
1021
1022            rlp_node_buf.clear();
1023            let mut node_epoch = TrieNodeEpoch::UNMODIFIED;
1024            let state_mask = arena[head_idx].branch_ref().state_mask;
1025            for (child_idx, _nibble) in BranchChildIter::new(state_mask) {
1026                match &arena[head_idx].branch_ref().children[child_idx] {
1027                    ArenaSparseNodeBranchChild::Blinded(rlp_node) => {
1028                        rlp_node_buf.push(rlp_node.clone());
1029                    }
1030                    ArenaSparseNodeBranchChild::Revealed(child_idx) => {
1031                        let child_idx = *child_idx;
1032                        match &arena[child_idx] {
1033                            ArenaSparseNode::Leaf { .. } => {
1034                                Self::encode_leaf(
1035                                    arena,
1036                                    child_idx,
1037                                    rlp_buf,
1038                                    rlp_node_buf,
1039                                    new_epoch,
1040                                );
1041                            }
1042                            ArenaSparseNode::Branch(child_b) => {
1043                                let ArenaSparseNodeState::Cached { rlp_node, .. } = &child_b.state
1044                                else {
1045                                    panic!("child branch must be cached after DFS");
1046                                };
1047                                let rlp_node = rlp_node.clone();
1048                                rlp_node_buf.push(rlp_node);
1049                            }
1050                            ArenaSparseNode::Subtrie(subtrie) => {
1051                                let subtrie_root = &subtrie.arena[subtrie.root];
1052                                match subtrie_root {
1053                                    ArenaSparseNode::Branch(ArenaSparseNodeBranch {
1054                                        state: ArenaSparseNodeState::Cached { rlp_node, .. },
1055                                        ..
1056                                    }) |
1057                                    ArenaSparseNode::Leaf {
1058                                        state: ArenaSparseNodeState::Cached { rlp_node, .. },
1059                                        ..
1060                                    } => {
1061                                        rlp_node_buf.push(rlp_node.clone());
1062                                    }
1063                                    _ => panic!("subtrie root must be a cached Branch or Leaf"),
1064                                }
1065                            }
1066                            ArenaSparseNode::TakenSubtrie | ArenaSparseNode::EmptyRoot { .. } => {
1067                                unreachable!("Unexpected child {:?}", arena[child_idx]);
1068                            }
1069                        }
1070                        let Some(ArenaSparseNodeState::Cached { epoch: child_epoch, .. }) =
1071                            arena[child_idx].state_ref()
1072                        else {
1073                            panic!("revealed child must be cached after encoding");
1074                        };
1075                        node_epoch = node_epoch.max(*child_epoch);
1076                    }
1077                }
1078            }
1079
1080            // Encode the branch, optionally wrapping in an extension if it has a short_key.
1081            let b = arena[head_idx].branch_ref();
1082            let short_key = b.short_key;
1083            let state_mask = b.state_mask;
1084            let prev_branch_masks = b.branch_masks;
1085            let new_branch_masks = Self::get_branch_masks(arena, b);
1086            let was_dirty = matches!(b.state, ArenaSparseNodeState::Dirty);
1087            if was_dirty {
1088                node_epoch = node_epoch.max(new_epoch);
1089            }
1090
1091            rlp_buf.clear();
1092            let rlp_node = BranchNodeRef::new(rlp_node_buf, state_mask).rlp(rlp_buf);
1093
1094            let rlp_node = if short_key.is_empty() {
1095                rlp_node
1096            } else {
1097                rlp_buf.clear();
1098                ExtensionNodeRef::new(&short_key, &rlp_node).rlp(rlp_buf)
1099            };
1100
1101            trace!(
1102                target: TRACE_TARGET,
1103                path = ?head_path,
1104                short_key = ?arena[head_idx].short_key(),
1105                children = ?state_mask.iter().zip(rlp_node_buf.iter()).collect::<Vec<_>>(),
1106                rlp_node = ?rlp_node,
1107                "Calculated branch RlpNode",
1108            );
1109
1110            let branch = arena[head_idx].branch_mut();
1111            branch.state = ArenaSparseNodeState::Cached { rlp_node, epoch: node_epoch };
1112            branch.branch_masks = new_branch_masks;
1113
1114            // Record trie updates for dirty branches only.
1115            // Skip the root node (empty logical path) as PST does.
1116            if let Some(trie_updates) = updates.as_mut().filter(|_| was_dirty) {
1117                let mut logical_path = head_path;
1118                logical_path.extend(&short_key);
1119
1120                if !logical_path.is_empty() {
1121                    if !prev_branch_masks.is_empty() && new_branch_masks.is_empty() {
1122                        trie_updates.push((logical_path, None));
1123                    } else if !new_branch_masks.is_empty() {
1124                        let compact = arena[head_idx].branch_ref().branch_node_compact(arena);
1125                        trie_updates.push((logical_path, Some(compact)));
1126                    }
1127                }
1128            }
1129        }
1130
1131        let ArenaSparseNodeState::Cached { rlp_node, .. } = &arena[root].branch_ref().state else {
1132            panic!("root must be cached after update_cached_rlp");
1133        };
1134        rlp_node.clone()
1135    }
1136
1137    /// Immutable traversal to find a leaf value at `full_path` starting from `root` in `arena`.
1138    /// `path_offset` is the number of nibbles already consumed from `full_path`.
1139    fn get_leaf_value_in_arena<'a>(
1140        arena: &'a NodeArena,
1141        mut current: Index,
1142        full_path: &Nibbles,
1143        mut path_offset: usize,
1144    ) -> Option<&'a Vec<u8>> {
1145        loop {
1146            match &arena[current] {
1147                ArenaSparseNode::EmptyRoot { .. } | ArenaSparseNode::TakenSubtrie => return None,
1148                ArenaSparseNode::Leaf { key, value, .. } => {
1149                    let remaining = full_path.slice(path_offset..);
1150                    return (remaining == *key).then_some(value);
1151                }
1152                ArenaSparseNode::Branch(b) => {
1153                    let short_key = &b.short_key;
1154                    let logical_end = path_offset + short_key.len();
1155                    if full_path.len() <= logical_end ||
1156                        full_path.slice(path_offset..logical_end) != *short_key
1157                    {
1158                        return None;
1159                    }
1160
1161                    let child_nibble = full_path.get_unchecked(logical_end);
1162                    let child_idx = BranchChildIdx::new(b.state_mask, child_nibble)?;
1163                    match &b.children[child_idx] {
1164                        ArenaSparseNodeBranchChild::Blinded(_) => return None,
1165                        ArenaSparseNodeBranchChild::Revealed(child_idx) => {
1166                            current = *child_idx;
1167                            path_offset = logical_end + 1;
1168                        }
1169                    }
1170                }
1171                ArenaSparseNode::Subtrie(subtrie) => {
1172                    return Self::get_leaf_value_in_arena(
1173                        &subtrie.arena,
1174                        subtrie.root,
1175                        full_path,
1176                        path_offset,
1177                    );
1178                }
1179            }
1180        }
1181    }
1182
1183    /// Immutable traversal from the given root in `arena`, following `full_path` to find a leaf.
1184    /// Returns whether the leaf exists or not, or an error if a blinded node is encountered or
1185    /// the value doesn't match.
1186    fn find_leaf_in_arena(
1187        arena: &NodeArena,
1188        mut current: Index,
1189        full_path: &Nibbles,
1190        mut path_offset: usize,
1191        expected_value: Option<&Vec<u8>>,
1192    ) -> Result<LeafLookup, LeafLookupError> {
1193        loop {
1194            match &arena[current] {
1195                ArenaSparseNode::EmptyRoot { .. } | ArenaSparseNode::TakenSubtrie => {
1196                    return Ok(LeafLookup::NonExistent);
1197                }
1198                ArenaSparseNode::Leaf { key, value, .. } => {
1199                    let remaining = full_path.slice(path_offset..);
1200                    if remaining != *key {
1201                        return Ok(LeafLookup::NonExistent);
1202                    }
1203                    if let Some(expected) = expected_value &&
1204                        *expected != *value
1205                    {
1206                        return Err(LeafLookupError::ValueMismatch {
1207                            path: *full_path,
1208                            expected: Some(expected.clone()),
1209                            actual: value.clone(),
1210                        });
1211                    }
1212                    return Ok(LeafLookup::Exists);
1213                }
1214                ArenaSparseNode::Branch(b) => {
1215                    let short_key = &b.short_key;
1216                    let logical_end = path_offset + short_key.len();
1217
1218                    if full_path.len() <= logical_end {
1219                        return Ok(LeafLookup::NonExistent);
1220                    }
1221
1222                    if full_path.slice(path_offset..logical_end) != *short_key {
1223                        return Ok(LeafLookup::NonExistent);
1224                    }
1225
1226                    let child_nibble = full_path.get_unchecked(logical_end);
1227                    let Some(child_idx) = BranchChildIdx::new(b.state_mask, child_nibble) else {
1228                        return Ok(LeafLookup::NonExistent);
1229                    };
1230
1231                    match &b.children[child_idx] {
1232                        ArenaSparseNodeBranchChild::Blinded(rlp_node) => {
1233                            let hash = rlp_node
1234                                .as_hash()
1235                                .unwrap_or_else(|| keccak256(rlp_node.as_slice()));
1236                            let mut blinded_path = full_path.slice(..logical_end);
1237                            blinded_path.push_unchecked(child_nibble);
1238                            return Err(LeafLookupError::BlindedNode { path: blinded_path, hash });
1239                        }
1240                        ArenaSparseNodeBranchChild::Revealed(child_idx) => {
1241                            current = *child_idx;
1242                            path_offset = logical_end + 1;
1243                        }
1244                    }
1245                }
1246                ArenaSparseNode::Subtrie(subtrie) => {
1247                    return Self::find_leaf_in_arena(
1248                        &subtrie.arena,
1249                        subtrie.root,
1250                        full_path,
1251                        path_offset,
1252                        expected_value,
1253                    );
1254                }
1255            }
1256        }
1257    }
1258
1259    /// Encodes a leaf node's RLP and pushes it onto `rlp_node_buf`.
1260    ///
1261    /// If the leaf is already cached, its existing `RlpNode` is reused.
1262    fn encode_leaf(
1263        arena: &mut NodeArena,
1264        idx: Index,
1265        rlp_buf: &mut Vec<u8>,
1266        rlp_node_buf: &mut Vec<RlpNode>,
1267        new_epoch: TrieNodeEpoch,
1268    ) {
1269        let (key, value, state) = match &arena[idx] {
1270            ArenaSparseNode::Leaf { key, value, state } => (key, value, state),
1271            _ => unreachable!("encode_leaf called on non-Leaf node"),
1272        };
1273
1274        let epoch = match state {
1275            ArenaSparseNodeState::Cached { rlp_node, .. } => {
1276                rlp_node_buf.push(rlp_node.clone());
1277                return;
1278            }
1279            ArenaSparseNodeState::Revealed => TrieNodeEpoch::UNMODIFIED,
1280            ArenaSparseNodeState::Dirty => new_epoch,
1281        };
1282
1283        rlp_buf.clear();
1284        let rlp_node = LeafNodeRef { key, value }.rlp(rlp_buf);
1285
1286        *arena[idx].state_mut() =
1287            ArenaSparseNodeState::Cached { rlp_node: rlp_node.clone(), epoch };
1288        rlp_node_buf.push(rlp_node);
1289    }
1290
1291    /// Creates a new leaf and a new branch that splits an existing child from the new leaf at
1292    /// a divergence point. Returns the index of the new branch.
1293    ///
1294    /// `new_leaf_path` is the full remaining path for the new leaf (relative to the split
1295    /// point's parent).
1296    ///
1297    /// The old child's key (leaf) or `short_key` (branch) is truncated to the suffix after the
1298    /// divergence nibble and its state is set to dirty.
1299    ///
1300    /// The top of `stack` must be the leaf or branch being split. The top of stack will be the
1301    /// newly created branch once this returns.
1302    /// Returns `true` if the existing node was not already dirty (i.e., the split newly dirtied
1303    /// it).
1304    fn split_and_insert_leaf(
1305        arena: &mut NodeArena,
1306        cursor: &mut ArenaCursor,
1307        root: &mut Index,
1308        new_leaf_path: Nibbles,
1309        value: &[u8],
1310    ) -> bool {
1311        let old_child_entry = cursor.head().expect("cursor must have head");
1312        let old_child_idx = old_child_entry.index;
1313        let old_child_short_key = arena[old_child_idx].short_key().expect("top of stack is a leaf");
1314        let diverge_len = new_leaf_path.common_prefix_length(old_child_short_key);
1315
1316        trace!(
1317            target: TRACE_TARGET,
1318            path = ?old_child_entry.path,
1319            ?new_leaf_path,
1320            ?old_child_short_key,
1321            diverge_len,
1322            "Splitting node and inserting new leaf",
1323        );
1324
1325        let old_child_nibble = old_child_short_key.get_unchecked(diverge_len);
1326        let old_child_suffix = old_child_short_key.slice(diverge_len + 1..);
1327
1328        // Truncate the old child's key/short_key and mark it dirty.
1329        // Track whether the existing node was not already dirty (a leaf that becomes newly dirty).
1330        let newly_dirtied_existing = match &mut arena[old_child_idx] {
1331            ArenaSparseNode::Leaf { key, state, .. } => {
1332                *key = old_child_suffix;
1333                let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
1334                *state = ArenaSparseNodeState::Dirty;
1335                was_clean
1336            }
1337            ArenaSparseNode::Branch(b) => {
1338                b.short_key = old_child_suffix;
1339                b.state = b.state.to_dirty();
1340                // Branches don't contribute to num_dirty_leaves.
1341                false
1342            }
1343            _ => unreachable!("split_and_insert_leaf called on non-Leaf/Branch node"),
1344        };
1345
1346        let short_key = new_leaf_path.slice(..diverge_len);
1347        let new_leaf_nibble = new_leaf_path.get_unchecked(diverge_len);
1348        debug_assert_ne!(old_child_nibble, new_leaf_nibble);
1349
1350        let new_leaf_idx = arena.insert(ArenaSparseNode::Leaf {
1351            state: ArenaSparseNodeState::Dirty,
1352            key: new_leaf_path.slice(diverge_len + 1..),
1353            value: value.to_vec(),
1354        });
1355
1356        let (first_nibble, first_child, second_nibble, second_child) =
1357            if old_child_nibble < new_leaf_nibble {
1358                (old_child_nibble, old_child_idx, new_leaf_nibble, new_leaf_idx)
1359            } else {
1360                (new_leaf_nibble, new_leaf_idx, old_child_nibble, old_child_idx)
1361            };
1362
1363        let state_mask = TrieMask::from_nibble(first_nibble) | TrieMask::from_nibble(second_nibble);
1364        let mut children = SmallVec::with_capacity(2);
1365        children.push(ArenaSparseNodeBranchChild::Revealed(first_child));
1366        children.push(ArenaSparseNodeBranchChild::Revealed(second_child));
1367
1368        let new_branch_idx = arena.insert(ArenaSparseNode::Branch(ArenaSparseNodeBranch {
1369            state: ArenaSparseNodeState::Dirty,
1370            children,
1371            state_mask,
1372            short_key,
1373            branch_masks: BranchNodeMasks::default(),
1374        }));
1375
1376        cursor.replace_head_index(arena, root, new_branch_idx);
1377        newly_dirtied_existing
1378    }
1379
1380    /// Performs a leaf upsert using a pre-computed [`SeekResult`] from
1381    /// [`ArenaCursor::seek`].
1382    ///
1383    /// Handles three cases based on `find_result`:
1384    /// 1. `RevealedLeaf` — the cursor head is a leaf; update in place or split into a branch.
1385    /// 2. Diverged — the path diverges within the branch's `short_key`, split it.
1386    /// 3. `NoChild` — the target nibble has no child, insert a new leaf.
1387    ///
1388    /// The caller must handle [`SeekResult::Blinded`] and
1389    /// [`SeekResult::RevealedSubtrie`] before calling this function.
1390    /// The cursor must be non-empty when called.
1391    ///
1392    /// Returns an [`UpsertLeafResult`] and [`SubtrieCounterDeltas`] so the caller can maintain
1393    /// aggregate counters and decide whether to wrap the result as a subtrie.
1394    #[instrument(level = "trace", target = TRACE_TARGET, skip_all, fields(full_path = ?full_path))]
1395    fn upsert_leaf(
1396        arena: &mut NodeArena,
1397        cursor: &mut ArenaCursor,
1398        root: &mut Index,
1399        full_path: &Nibbles,
1400        value: &[u8],
1401        find_result: SeekResult,
1402    ) -> (UpsertLeafResult, SubtrieCounterDeltas) {
1403        trace!(target: TRACE_TARGET, ?find_result, "Upserting leaf");
1404        let head = cursor.head().expect("cursor is non-empty");
1405
1406        match find_result {
1407            SeekResult::Blinded => {
1408                unreachable!("Blinded case must be handled by caller")
1409            }
1410            SeekResult::EmptyRoot => {
1411                let head_idx = head.index;
1412                let head_path = head.path;
1413                arena[head_idx] = ArenaSparseNode::Leaf {
1414                    state: ArenaSparseNodeState::Dirty,
1415                    key: full_path.slice(head_path.len()..),
1416                    value: value.to_vec(),
1417                };
1418                (
1419                    UpsertLeafResult::NewLeaf,
1420                    SubtrieCounterDeltas { num_leaves_delta: 1, num_dirty_leaves_delta: 1 },
1421                )
1422            }
1423            SeekResult::RevealedLeaf => {
1424                // RevealedLeaf guarantees the leaf's full path matches the target exactly.
1425                let head_idx = head.index;
1426                let was_clean =
1427                    if let ArenaSparseNode::Leaf { value: v, state, .. } = &mut arena[head_idx] {
1428                        v.clear();
1429                        v.extend_from_slice(value);
1430                        let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
1431                        *state = ArenaSparseNodeState::Dirty;
1432                        was_clean
1433                    } else {
1434                        unreachable!("RevealedLeaf but cursor head is not a leaf")
1435                    };
1436                (
1437                    UpsertLeafResult::Updated,
1438                    SubtrieCounterDeltas {
1439                        num_leaves_delta: 0,
1440                        num_dirty_leaves_delta: was_clean as i64,
1441                    },
1442                )
1443            }
1444            SeekResult::Diverged => {
1445                let head_path = head.path;
1446                let full_path_from_head = full_path.slice(head_path.len()..);
1447
1448                let split_dirtied_existing =
1449                    Self::split_and_insert_leaf(arena, cursor, root, full_path_from_head, value);
1450
1451                let result = if cursor.depth() >= 1 {
1452                    UpsertLeafResult::NewChild
1453                } else {
1454                    UpsertLeafResult::NewLeaf
1455                };
1456                (
1457                    result,
1458                    SubtrieCounterDeltas {
1459                        num_leaves_delta: 1,
1460                        num_dirty_leaves_delta: 1 + split_dirtied_existing as i64,
1461                    },
1462                )
1463            }
1464            SeekResult::NoChild { child_nibble } => {
1465                let head_idx = head.index;
1466
1467                let head_branch_logical_path = cursor.head_logical_branch_path(arena);
1468                let leaf_key = full_path.slice(head_branch_logical_path.len() + 1..);
1469                let new_leaf = arena.insert(ArenaSparseNode::Leaf {
1470                    state: ArenaSparseNodeState::Dirty,
1471                    key: leaf_key,
1472                    value: value.to_vec(),
1473                });
1474
1475                let branch = arena[head_idx].branch_mut();
1476                branch.set_child(child_nibble, ArenaSparseNodeBranchChild::Revealed(new_leaf));
1477
1478                // Re-seek to position the cursor on the newly inserted leaf.
1479                cursor.seek(arena, full_path);
1480
1481                (
1482                    UpsertLeafResult::NewChild,
1483                    SubtrieCounterDeltas { num_leaves_delta: 1, num_dirty_leaves_delta: 1 },
1484                )
1485            }
1486            SeekResult::RevealedSubtrie => {
1487                unreachable!("RevealedSubtrie must be handled by caller")
1488            }
1489        }
1490    }
1491
1492    /// Removes a leaf node from the trie using a pre-computed [`SeekResult`] from
1493    /// [`ArenaCursor::seek`].
1494    ///
1495    /// Only the `RevealedLeaf` case performs a removal — the leaf must exist and its full path
1496    /// must match `full_path`. All other cases (`Diverged`, `NoChild`) are no-ops since the leaf
1497    /// doesn't exist at that path.
1498    ///
1499    /// When removing a leaf from a branch, if the branch is left with only one remaining child,
1500    /// the branch is collapsed: the remaining child absorbs the branch's `short_key` + the child's
1501    /// nibble as a prefix to its own key/`short_key`, and replaces the branch in the parent.
1502    /// If the remaining child is blinded, the collapse cannot proceed and a
1503    /// [`RemoveLeafResult::NeedsProof`] is returned so the caller can request a proof.
1504    ///
1505    /// The caller must handle [`SeekResult::Blinded`] and
1506    /// [`SeekResult::RevealedSubtrie`] before calling this function.
1507    fn remove_leaf(
1508        arena: &mut NodeArena,
1509        cursor: &mut ArenaCursor,
1510        root: &mut Index,
1511        key: B256,
1512        full_path: &Nibbles,
1513        find_result: SeekResult,
1514        updates: &mut Option<SparseTrieUpdates>,
1515    ) -> (RemoveLeafResult, SubtrieCounterDeltas) {
1516        match find_result {
1517            SeekResult::Blinded | SeekResult::RevealedSubtrie => {
1518                unreachable!("Blinded/RevealedSubtrie must be handled by caller")
1519            }
1520            SeekResult::EmptyRoot | SeekResult::Diverged | SeekResult::NoChild { .. } => {
1521                (RemoveLeafResult::NotFound, SubtrieCounterDeltas::default())
1522            }
1523            SeekResult::RevealedLeaf => {
1524                // RevealedLeaf guarantees the leaf's full path matches the target exactly.
1525                let head = cursor.head().expect("cursor is non-empty");
1526                let head_idx = head.index;
1527                let head_path = head.path;
1528
1529                trace!(
1530                    target: TRACE_TARGET,
1531                    path = ?head_path,
1532                    ?full_path,
1533                    "Removing leaf",
1534                );
1535
1536                // Before mutating, check if removing this leaf would leave the parent
1537                // branch with a single blinded sibling (requiring a proof to collapse).
1538                if let Some(parent_entry) = cursor.parent() {
1539                    let parent_idx = parent_entry.index;
1540                    let child_nibble = head_path.last().expect("non-root leaf");
1541                    let parent_branch = arena[parent_idx].branch_ref();
1542
1543                    if parent_branch.state_mask.count_bits() == 2 &&
1544                        parent_branch.sibling_child(child_nibble).is_blinded()
1545                    {
1546                        let sibling_nibble = parent_branch
1547                            .state_mask
1548                            .iter()
1549                            .find(|&n| n != child_nibble)
1550                            .expect("branch has two children");
1551                        let mut sibling_path = cursor.parent_logical_branch_path(arena);
1552                        sibling_path.push_unchecked(sibling_nibble);
1553                        trace!(target: TRACE_TARGET, ?full_path, ?sibling_path, "Removal would collapse branch onto blinded sibling, requesting proof");
1554                        return (
1555                            RemoveLeafResult::NeedsProof {
1556                                key,
1557                                proof_key: Self::nibbles_to_padded_b256(&sibling_path),
1558                                parent: ProofV2TargetParent::new(
1559                                    sibling_path
1560                                        .len()
1561                                        .checked_sub(1)
1562                                        .expect("sibling path has a child nibble"),
1563                                ),
1564                            },
1565                            SubtrieCounterDeltas::default(),
1566                        );
1567                    }
1568                }
1569
1570                // Check if the removed leaf was dirty before removing it.
1571                let removed_was_dirty =
1572                    matches!(arena[head_idx].state_ref(), Some(ArenaSparseNodeState::Dirty));
1573
1574                if cursor.depth() == 0 {
1575                    // The leaf is the root — replace with EmptyRoot and reset the cursor
1576                    // so subsequent iterations can call seek normally.
1577                    arena.remove(head_idx);
1578                    *root = arena
1579                        .insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Dirty });
1580                    cursor.reset(arena, *root, head_path);
1581                    return (
1582                        RemoveLeafResult::Removed,
1583                        SubtrieCounterDeltas {
1584                            num_leaves_delta: -1,
1585                            num_dirty_leaves_delta: -(removed_was_dirty as i64),
1586                        },
1587                    );
1588                }
1589
1590                // Pop the leaf entry, propagating dirty state to the parent.
1591                cursor.pop(arena);
1592
1593                // The parent must be a branch. Remove the leaf from it.
1594                let parent_entry = cursor.head().expect("cursor is non-empty");
1595                let parent_idx = parent_entry.index;
1596                let child_nibble = head_path.last().expect("non-root leaf");
1597
1598                // Remove the leaf from the arena and from the parent's children.
1599                arena.remove(head_idx);
1600                let parent_branch = arena[parent_idx].branch_mut();
1601                parent_branch.remove_child(child_nibble);
1602
1603                // If the branch now has only one child, collapse it. The blinded sibling
1604                // case was already handled above before any mutations.
1605                let collapse_dirtied_leaf = if parent_branch.state_mask.count_bits() == 1 {
1606                    Self::collapse_branch(arena, cursor, root, updates)
1607                } else {
1608                    false
1609                };
1610                (
1611                    RemoveLeafResult::Removed,
1612                    SubtrieCounterDeltas {
1613                        num_leaves_delta: -1,
1614                        num_dirty_leaves_delta: (collapse_dirtied_leaf as i64) -
1615                            (removed_was_dirty as i64),
1616                    },
1617                )
1618            }
1619        }
1620    }
1621
1622    /// Checks whether a subtrie receiving only removals would cause its parent branch to collapse
1623    /// onto a single blinded sibling. If so, returns the proof needed to reveal that blinded
1624    /// sibling so the caller can request it and skip the subtrie's updates.
1625    ///
1626    /// Returns `Some(proof)` for the blinded sibling when the edge-case applies, `None` otherwise.
1627    fn check_subtrie_collapse_needs_proof(
1628        arena: &NodeArena,
1629        cursor: &ArenaCursor,
1630        subtrie_updates: &[(B256, Nibbles, LeafUpdate)],
1631    ) -> Option<ArenaRequiredProof> {
1632        let num_removals = subtrie_updates
1633            .iter()
1634            .filter(|(_, _, u)| matches!(u, LeafUpdate::Changed(v) if v.is_empty()))
1635            .count() as u64;
1636
1637        // Touched is a no-op that doesn't alter trie structure, so it must be
1638        // excluded when deciding whether "all updates are removals". This mirrors
1639        // the `all_removals` / `might_empty_subtrie` filter in `update_leaves`.
1640        // Without this, a batch of removals + Touched entries
1641        // would fail the `num_removals != num_changed` check, skip the proof
1642        // request for the blinded sibling, and later panic in
1643        // `maybe_collapse_or_remove_branch` when the subtrie empties inline.
1644        let num_changed =
1645            subtrie_updates.iter().filter(|(_, _, u)| matches!(u, LeafUpdate::Changed(_))).count()
1646                as u64;
1647
1648        if num_removals == 0 || num_removals != num_changed {
1649            return None;
1650        }
1651
1652        // The subtrie is the cursor head; its parent is the cursor's parent.
1653        let subtrie_entry = cursor.head()?;
1654        let subtrie_num_leaves = match &arena[subtrie_entry.index] {
1655            ArenaSparseNode::Subtrie(s) => s.num_leaves,
1656            _ => return None,
1657        };
1658        if num_removals < subtrie_num_leaves {
1659            return None;
1660        }
1661
1662        let child_nibble =
1663            subtrie_entry.path.last().expect("subtrie path must have at least one nibble");
1664
1665        let parent_entry = cursor.parent()?;
1666        let parent_branch = arena[parent_entry.index].branch_ref();
1667        if parent_branch.state_mask.count_bits() != 2 {
1668            return None;
1669        }
1670
1671        if !parent_branch.sibling_child(child_nibble).is_blinded() {
1672            return None;
1673        }
1674
1675        let sibling_nibble = parent_branch
1676            .state_mask
1677            .iter()
1678            .find(|&n| n != child_nibble)
1679            .expect("branch has two children");
1680        let mut sibling_path = cursor.parent_logical_branch_path(arena);
1681        sibling_path.push_unchecked(sibling_nibble);
1682
1683        Some(ArenaRequiredProof {
1684            key: Self::nibbles_to_padded_b256(&sibling_path),
1685            parent: ProofV2TargetParent::new(
1686                sibling_path.len().checked_sub(1).expect("sibling path has a child nibble"),
1687            ),
1688        })
1689    }
1690
1691    /// Collapses a branch node that has exactly one remaining revealed child. The branch's
1692    /// `short_key`, the remaining child's nibble, and the child's own key/`short_key` are
1693    /// concatenated to form the child's new key/`short_key`. The child then replaces the branch
1694    /// in the grandparent (or becomes the new root).
1695    ///
1696    /// The caller must verify that the remaining child is not blinded before calling this function.
1697    ///
1698    /// The branch being collapsed must be the current cursor head. The cursor head will be
1699    /// replaced with the remaining child which has taken its place.
1700    /// Returns `true` if the collapse dirtied a surviving leaf that was not already dirty.
1701    fn collapse_branch(
1702        arena: &mut NodeArena,
1703        cursor: &mut ArenaCursor,
1704        root: &mut Index,
1705        updates: &mut Option<SparseTrieUpdates>,
1706    ) -> bool {
1707        let branch_entry = cursor.head().expect("cursor is non-empty");
1708        let branch_idx = branch_entry.index;
1709        let branch = arena[branch_idx].branch_ref();
1710        let remaining_nibble =
1711            branch.state_mask.iter().next().expect("branch has at least one child");
1712        let branch_short_key = branch.short_key;
1713
1714        debug_assert_eq!(
1715            branch.state_mask.count_bits(),
1716            1,
1717            "collapse_branch requires exactly 1 child"
1718        );
1719        debug_assert!(
1720            !branch.children[0].is_blinded(),
1721            "collapse_branch called with a blinded remaining child"
1722        );
1723
1724        trace!(
1725            target: TRACE_TARGET,
1726            path = ?branch_entry.path,
1727            short_key = ?branch_short_key,
1728            branch_masks = ?branch.branch_masks,
1729            ?remaining_nibble,
1730            "Collapsing single-child branch",
1731        );
1732
1733        // Record the collapsed branch's logical path for trie update tracking if it
1734        // was previously persisted in the DB trie.
1735        if let Some(trie_updates) = updates.as_mut() &&
1736            !branch.branch_masks.is_empty()
1737        {
1738            let logical_path = cursor.head_logical_branch_path(arena);
1739            if !logical_path.is_empty() {
1740                trie_updates.push((logical_path, None));
1741            }
1742        }
1743
1744        // Build the prefix: branch's short_key + remaining child's nibble.
1745        let mut prefix = branch_short_key;
1746        prefix.push_unchecked(remaining_nibble);
1747
1748        let ArenaSparseNodeBranchChild::Revealed(child_idx) = branch.children[0] else {
1749            unreachable!()
1750        };
1751
1752        // Prepend the prefix to the child's key/short_key and mark dirty.
1753        // Track whether a leaf was newly dirtied by this collapse.
1754        let newly_dirtied_leaf = match &mut arena[child_idx] {
1755            ArenaSparseNode::Leaf { key, state, .. } => {
1756                let mut new_key = prefix;
1757                new_key.extend(key);
1758                *key = new_key;
1759                let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
1760                *state = ArenaSparseNodeState::Dirty;
1761                was_clean
1762            }
1763            ArenaSparseNode::Branch(b) => {
1764                let mut new_short_key = prefix;
1765                new_short_key.extend(&b.short_key);
1766                b.short_key = new_short_key;
1767                b.state = b.state.to_dirty();
1768                false
1769            }
1770            ArenaSparseNode::Subtrie(subtrie) => {
1771                subtrie.path = branch_entry.path;
1772                match &mut subtrie.arena[subtrie.root] {
1773                    ArenaSparseNode::Branch(b) => {
1774                        let mut new_short_key = prefix;
1775                        new_short_key.extend(&b.short_key);
1776                        b.short_key = new_short_key;
1777                        b.state = b.state.to_dirty();
1778                    }
1779                    ArenaSparseNode::Leaf { key, state, .. } => {
1780                        let mut new_key = prefix;
1781                        new_key.extend(key);
1782                        *key = new_key;
1783                        let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
1784                        *state = ArenaSparseNodeState::Dirty;
1785                        if was_clean {
1786                            subtrie.num_dirty_leaves += 1;
1787                        }
1788                    }
1789                    _ => {
1790                        unreachable!("subtrie root must be a Branch or Leaf during collapse_branch")
1791                    }
1792                }
1793                false
1794            }
1795            _ => unreachable!("remaining child must be Leaf, Branch, or Subtrie"),
1796        };
1797
1798        // Replace the branch with the remaining child in the grandparent (or root).
1799        cursor.replace_head_index(arena, root, child_idx);
1800
1801        // Free the collapsed branch.
1802        arena.remove(branch_idx);
1803        newly_dirtied_leaf
1804    }
1805
1806    /// Counts the total leaves and dirty leaves in a subtree rooted at `idx`.
1807    fn count_leaves_and_dirty(arena: &NodeArena, idx: Index) -> (u64, u64) {
1808        match &arena[idx] {
1809            ArenaSparseNode::Leaf { state, .. } => {
1810                let dirty = matches!(state, ArenaSparseNodeState::Dirty) as u64;
1811                (1, dirty)
1812            }
1813            ArenaSparseNode::Branch(b) => {
1814                let mut leaves = 0u64;
1815                let mut dirty = 0u64;
1816                for c in &b.children {
1817                    if let ArenaSparseNodeBranchChild::Revealed(child_idx) = c {
1818                        let (l, d) = Self::count_leaves_and_dirty(arena, *child_idx);
1819                        leaves += l;
1820                        dirty += d;
1821                    }
1822                }
1823                (leaves, dirty)
1824            }
1825            _ => (0, 0),
1826        }
1827    }
1828
1829    /// Asserts that every node in the upper arena satisfies the subtrie structure invariant:
1830    /// - Nodes at `UPPER_TRIE_MAX_DEPTH` path length must be `Subtrie` (or `TakenSubtrie`).
1831    /// - Nodes at other depths must NOT be `Subtrie`.
1832    ///
1833    /// Uses the cursor to DFS the upper arena, checking each visited node's path length.
1834    #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
1835    #[cfg(debug_assertions)]
1836    fn debug_assert_subtrie_structure(&mut self) {
1837        let mut cursor = mem::take(&mut self.buffers.cursor);
1838        cursor.reset(&self.upper_arena, self.root, Nibbles::default());
1839
1840        loop {
1841            let result = cursor.next(&mut self.upper_arena, |_, _| true);
1842            match result {
1843                NextResult::Done => break,
1844                NextResult::NonBranch | NextResult::Branch => {
1845                    let head = cursor.head().expect("cursor is non-empty");
1846                    let path_len = head.path.len();
1847                    let node = &self.upper_arena[head.index];
1848
1849                    if Self::should_be_subtrie(path_len) {
1850                        debug_assert!(
1851                            matches!(
1852                                node,
1853                                ArenaSparseNode::Subtrie(_) | ArenaSparseNode::TakenSubtrie
1854                            ),
1855                            "node at path_len={path_len} should be a Subtrie but is {node:?}",
1856                        );
1857                    } else {
1858                        debug_assert!(
1859                            !matches!(node, ArenaSparseNode::Subtrie(_)),
1860                            "node at path_len={path_len} should NOT be a Subtrie but is",
1861                        );
1862                    }
1863                }
1864            }
1865        }
1866
1867        self.buffers.cursor = cursor;
1868    }
1869
1870    /// Recursively migrates all nodes from `src` into `dst`, starting at `src_idx`.
1871    /// Branch children's `Revealed` indices are remapped to the new `dst` indices during
1872    /// the migration.
1873    ///
1874    /// If `dst_slot` is `Some(idx)`, the node at `src_idx` is placed into `dst[idx]`
1875    /// (overwriting); otherwise a new slot is allocated. Returns the `dst` index of the
1876    /// migrated node.
1877    fn migrate_nodes(
1878        dst: &mut NodeArena,
1879        src: &mut NodeArena,
1880        src_idx: Index,
1881        dst_slot: Option<Index>,
1882    ) -> Index {
1883        let mut node = src.remove(src_idx).expect("node exists in source arena");
1884
1885        // Recursively migrate children first so their new indices are known.
1886        if let ArenaSparseNode::Branch(b) = &mut node {
1887            for child in &mut b.children {
1888                if let ArenaSparseNodeBranchChild::Revealed(child_idx) = child {
1889                    *child_idx = Self::migrate_nodes(dst, src, *child_idx, None);
1890                }
1891            }
1892        }
1893
1894        if let Some(slot) = dst_slot {
1895            dst[slot] = node;
1896            slot
1897        } else {
1898            dst.insert(node)
1899        }
1900    }
1901
1902    /// Removes a pruned node from the arena and blinds the parent's child slot with the node's
1903    /// cached RLP.
1904    fn remove_pruned_node(
1905        arena: &mut NodeArena,
1906        cursor: &ArenaCursor,
1907        idx: Index,
1908        nibble: Option<u8>,
1909    ) -> ArenaSparseNode {
1910        let path = cursor.head().expect("cursor is non-empty").path;
1911        let node = arena.remove(idx).expect("node must exist to be pruned");
1912        let rlp_node = node
1913            .state_ref()
1914            .and_then(ArenaSparseNodeState::cached_rlp_node)
1915            .cloned()
1916            .expect("prune must run after hashing");
1917        trace!(
1918            target: TRACE_TARGET,
1919            ?path,
1920            variant = %AsRef::<str>::as_ref(&node),
1921            cached_rlp_node = ?rlp_node,
1922            "pruning node",
1923        );
1924
1925        let parent_idx = cursor.parent().expect("pruned child has parent").index;
1926        let child_nibble = nibble.expect("non-root child");
1927        let parent_branch = arena[parent_idx].branch_mut();
1928        let child_idx = BranchChildIdx::new(parent_branch.state_mask, child_nibble)
1929            .expect("child nibble not found in parent state_mask");
1930        parent_branch.children[child_idx] = ArenaSparseNodeBranchChild::Blinded(rlp_node);
1931
1932        node
1933    }
1934
1935    /// Reveals a single proof node using a pre-computed [`SeekResult`] from
1936    /// [`ArenaCursor::seek`].
1937    ///
1938    /// If the result is `Blinded`, the blinded child is replaced with the proof node (converted to
1939    /// an arena node with `Cached` state). All other cases (already revealed, no child, diverged,
1940    /// leaf head) are no-ops — the proof node is skipped.
1941    ///
1942    /// Returns the `Index` of the revealed node in the arena, if any was revealed.
1943    #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
1944    fn reveal_node(
1945        arena: &mut NodeArena,
1946        cursor: &ArenaCursor,
1947        node: &mut ProofTrieNodeV2,
1948        find_result: SeekResult,
1949    ) -> Option<Index> {
1950        let SeekResult::Blinded = find_result else {
1951            // Already revealed, no child slot, or diverged — skip this proof node.
1952            return None;
1953        };
1954
1955        let head = cursor.head().expect("cursor is non-empty");
1956        let head_idx = head.index;
1957        let head_branch_logical_path = cursor.head_logical_branch_path(arena);
1958
1959        debug_assert_eq!(
1960            node.path.len(),
1961            head_branch_logical_path.len() + 1,
1962            "proof node path {:?} is not a direct child of branch at {:?} (expected depth {})",
1963            node.path,
1964            head_branch_logical_path,
1965            head_branch_logical_path.len() + 1,
1966        );
1967
1968        let child_nibble = node.path.get_unchecked(head_branch_logical_path.len());
1969        let head_branch = arena[head_idx].branch_ref();
1970        let dense_child_idx = BranchChildIdx::new(head_branch.state_mask, child_nibble)
1971            .expect("Blinded result but child nibble not in state_mask");
1972
1973        let cached_rlp = match &head_branch.children[dense_child_idx] {
1974            ArenaSparseNodeBranchChild::Blinded(rlp) => rlp.clone(),
1975            ArenaSparseNodeBranchChild::Revealed(_) => return None,
1976        };
1977
1978        trace!(
1979            target: TRACE_TARGET,
1980            path = ?node.path,
1981            rlp_node = ?cached_rlp,
1982            "Revealing node",
1983        );
1984
1985        let proof_node = mem::replace(node, ProofTrieNodeV2::empty());
1986        let mut arena_node = ArenaSparseNode::from_proof_node(proof_node);
1987
1988        let state = arena_node.state_mut();
1989        *state =
1990            ArenaSparseNodeState::Cached { rlp_node: cached_rlp, epoch: TrieNodeEpoch::UNMODIFIED };
1991
1992        let child_idx = arena.insert(arena_node);
1993        arena[head_idx].branch_mut().children[dense_child_idx] =
1994            ArenaSparseNodeBranchChild::Revealed(child_idx);
1995
1996        Some(child_idx)
1997    }
1998
1999    #[cfg(debug_assertions)]
2000    fn collect_reachable_nodes(
2001        arena: &NodeArena,
2002        idx: Index,
2003        reachable: &mut alloy_primitives::map::HashSet<Index>,
2004    ) {
2005        if !reachable.insert(idx) {
2006            return;
2007        }
2008        if let ArenaSparseNode::Branch(b) = &arena[idx] {
2009            for child in &b.children {
2010                if let ArenaSparseNodeBranchChild::Revealed(child_idx) = child {
2011                    Self::collect_reachable_nodes(arena, *child_idx, reachable);
2012                }
2013            }
2014        }
2015    }
2016
2017    #[cfg(debug_assertions)]
2018    fn assert_no_orphaned_nodes(arena: &NodeArena, root: Index, label: &str) {
2019        let mut reachable = alloy_primitives::map::HashSet::default();
2020        Self::collect_reachable_nodes(arena, root, &mut reachable);
2021        let all_indices: alloy_primitives::map::HashSet<Index> =
2022            arena.iter().map(|(idx, _)| idx).collect();
2023        let orphaned: Vec<_> = all_indices.difference(&reachable).collect();
2024        debug_assert!(
2025            orphaned.is_empty(),
2026            "{label} has {} orphaned node(s): {orphaned:?}",
2027            orphaned.len(),
2028        );
2029    }
2030}
2031
2032#[cfg(debug_assertions)]
2033impl Drop for ArenaParallelSparseTrie {
2034    fn drop(&mut self) {
2035        Self::assert_no_orphaned_nodes(&self.upper_arena, self.root, "upper arena");
2036
2037        for (_, node) in &self.upper_arena {
2038            if let Some(subtrie) = node.as_subtrie() {
2039                Self::assert_no_orphaned_nodes(
2040                    &subtrie.arena,
2041                    subtrie.root,
2042                    &alloc::format!("subtrie {:?}", subtrie.path),
2043                );
2044            }
2045        }
2046    }
2047}
2048
2049impl Default for ArenaParallelSparseTrie {
2050    fn default() -> Self {
2051        let mut upper_arena = SlotMap::new();
2052        let root = upper_arena
2053            .insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Revealed });
2054        Self {
2055            upper_arena,
2056            root,
2057            buffers: ArenaTrieBuffers::default(),
2058            parallelism_thresholds: ArenaParallelismThresholds::default(),
2059        }
2060    }
2061}
2062
2063impl ArenaParallelSparseTrie {
2064    /// Hashes a subtrie at `head_idx` and collects its update actions.
2065    fn update_upper_subtrie(&mut self, head_idx: Index, new_epoch: TrieNodeEpoch) {
2066        let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[head_idx] else {
2067            unreachable!()
2068        };
2069
2070        if !subtrie.arena[subtrie.root].is_cached() {
2071            subtrie.update_cached_rlp(new_epoch);
2072        }
2073
2074        Self::merge_subtrie_updates(&mut self.buffers.updates, &mut subtrie.buffers.updates);
2075    }
2076}
2077
2078impl SparseTrie for ArenaParallelSparseTrie {
2079    #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
2080    fn set_root(
2081        &mut self,
2082        root: TrieNodeV2,
2083        masks: Option<BranchNodeMasks>,
2084        retain_updates: bool,
2085    ) -> SparseTrieResult<()> {
2086        debug_assert!(
2087            matches!(self.upper_arena[self.root], ArenaSparseNode::EmptyRoot { .. }),
2088            "set_root called on a trie that already has revealed nodes"
2089        );
2090
2091        self.set_updates(retain_updates);
2092
2093        match root {
2094            TrieNodeV2::EmptyRoot => {
2095                trace!(target: TRACE_TARGET, "Setting empty root");
2096                self.upper_arena[self.root] =
2097                    ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Revealed };
2098            }
2099            TrieNodeV2::Leaf(leaf) => {
2100                trace!(target: TRACE_TARGET, key = ?leaf.key, "Setting leaf root");
2101                self.upper_arena[self.root] = ArenaSparseNode::Leaf {
2102                    state: ArenaSparseNodeState::Revealed,
2103                    key: leaf.key,
2104                    value: leaf.value,
2105                };
2106            }
2107            TrieNodeV2::Branch(branch) => {
2108                trace!(target: TRACE_TARGET, state_mask = ?branch.state_mask, num_children = branch.state_mask.count_bits(), "Setting branch root");
2109                let mut children = SmallVec::with_capacity(branch.state_mask.count_bits() as usize);
2110                for (stack_ptr, _nibble) in branch.state_mask.iter().enumerate() {
2111                    children
2112                        .push(ArenaSparseNodeBranchChild::Blinded(branch.stack[stack_ptr].clone()));
2113                }
2114
2115                self.upper_arena[self.root] = ArenaSparseNode::Branch(ArenaSparseNodeBranch {
2116                    state: ArenaSparseNodeState::Revealed,
2117                    children,
2118                    state_mask: branch.state_mask,
2119                    short_key: branch.key,
2120                    branch_masks: masks.unwrap_or_default(),
2121                });
2122            }
2123            TrieNodeV2::Extension(_) => {
2124                panic!("set_root does not support Extension nodes; extensions are represented as branches with a short_key")
2125            }
2126        }
2127
2128        Ok(())
2129    }
2130
2131    fn set_updates(&mut self, retain_updates: bool) {
2132        if retain_updates {
2133            self.buffers.updates.get_or_insert_with(SparseTrieUpdates::default).clear();
2134        } else {
2135            self.buffers.updates = None;
2136        }
2137    }
2138
2139    #[instrument(level = "trace", target = TRACE_TARGET, skip_all, fields(num_nodes = nodes.len()))]
2140    fn reveal_nodes(&mut self, nodes: &mut [ProofTrieNodeV2]) -> SparseTrieResult<()> {
2141        if nodes.is_empty() {
2142            return Ok(());
2143        }
2144
2145        if matches!(self.upper_arena[self.root], ArenaSparseNode::EmptyRoot { .. }) {
2146            trace!(target: TRACE_TARGET, "Skipping reveal_nodes on empty root");
2147            return Ok(());
2148        }
2149
2150        // Sort nodes lexicographically by path.
2151        nodes.sort_unstable_by_key(|n| n.path);
2152
2153        let threshold = self.parallelism_thresholds.min_revealed_nodes;
2154
2155        // Take the cursor out to avoid borrow conflicts with `self`.
2156        let mut cursor = mem::take(&mut self.buffers.cursor);
2157        cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2158
2159        // Skip root node if present (set_root handles the root).
2160        let mut node_idx = if nodes[0].path.is_empty() { 1 } else { 0 };
2161
2162        // Walk the upper trie, revealing upper nodes inline and collecting subtrie work.
2163        // Subtries with enough nodes to reveal are taken for parallel processing; the rest
2164        // are revealed inline.
2165        let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>, Vec<ProofTrieNodeV2>)> = Vec::new();
2166
2167        while node_idx < nodes.len() {
2168            let find_result = cursor.seek(&mut self.upper_arena, &nodes[node_idx].path);
2169
2170            match find_result {
2171                SeekResult::RevealedLeaf => {
2172                    trace!(target: TRACE_TARGET, path = ?nodes[node_idx].path, "Skipping reveal: leaf head");
2173                    node_idx += 1;
2174                }
2175                SeekResult::Blinded => {
2176                    // Save the proof node's path before reveal_node consumes it.
2177                    let child_path = nodes[node_idx].path;
2178                    let child_idx = Self::reveal_node(
2179                        &mut self.upper_arena,
2180                        &cursor,
2181                        &mut nodes[node_idx],
2182                        SeekResult::Blinded,
2183                    );
2184                    node_idx += 1;
2185
2186                    if let Some(child_idx) = child_idx {
2187                        self.maybe_wrap_in_subtrie(child_idx, &child_path);
2188                    }
2189                }
2190                SeekResult::RevealedSubtrie => {
2191                    let subtrie_entry = cursor.head().expect("cursor is non-empty");
2192                    let child_idx = subtrie_entry.index;
2193                    let prefix = subtrie_entry.path;
2194
2195                    let subtrie_start = node_idx;
2196                    while node_idx < nodes.len() && nodes[node_idx].path.starts_with(&prefix) {
2197                        node_idx += 1;
2198                    }
2199                    let num_subtrie_nodes = node_idx - subtrie_start;
2200
2201                    if num_subtrie_nodes >= threshold {
2202                        // Take subtrie for parallel reveal.
2203                        trace!(target: TRACE_TARGET, ?prefix, num_subtrie_nodes, "Taking subtrie for parallel reveal");
2204                        let ArenaSparseNode::Subtrie(subtrie) = mem::replace(
2205                            &mut self.upper_arena[child_idx],
2206                            ArenaSparseNode::TakenSubtrie,
2207                        ) else {
2208                            unreachable!("RevealedSubtrie must point to a Subtrie node")
2209                        };
2210                        let node_vec: Vec<ProofTrieNodeV2> = (subtrie_start..node_idx)
2211                            .map(|i| mem::replace(&mut nodes[i], ProofTrieNodeV2::empty()))
2212                            .collect();
2213                        taken.push((child_idx, subtrie, node_vec));
2214                    } else {
2215                        // Reveal inline.
2216                        trace!(target: TRACE_TARGET, ?prefix, num_subtrie_nodes, "Revealing subtrie inline");
2217                        let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[child_idx]
2218                        else {
2219                            unreachable!("RevealedSubtrie must point to a Subtrie node")
2220                        };
2221                        let mut subtrie_nodes: Vec<ProofTrieNodeV2> = (subtrie_start..node_idx)
2222                            .map(|i| mem::replace(&mut nodes[i], ProofTrieNodeV2::empty()))
2223                            .collect();
2224                        subtrie.reveal_nodes(&mut subtrie_nodes)?;
2225                    }
2226                }
2227                _ => {
2228                    trace!(target: TRACE_TARGET, path = ?nodes[node_idx].path, ?find_result, "Skipping reveal: no blinded child");
2229                    node_idx += 1;
2230                }
2231            }
2232        }
2233
2234        // Drain remaining cursor entries from the upper-trie walk.
2235        cursor.drain(&mut self.upper_arena);
2236        self.buffers.cursor = cursor;
2237
2238        if taken.is_empty() {
2239            return Ok(());
2240        }
2241
2242        // Reveal taken subtries, in parallel if more than one.
2243        if taken.len() == 1 {
2244            let (_, subtrie, node_vec) = &mut taken[0];
2245            subtrie.reveal_nodes(node_vec)?;
2246        } else {
2247            use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator};
2248
2249            let parent_span = tracing::Span::current();
2250            let results: Vec<SparseTrieResult<()>> = taken
2251                .par_iter_mut()
2252                .map(|(_, subtrie, node_vec)| {
2253                    let _guard = parent_span.enter();
2254                    subtrie.reveal_nodes(node_vec)
2255                })
2256                .collect();
2257
2258            if let Some(err) = results.into_iter().find(|r| r.is_err()) {
2259                // Restore before returning so we don't leave TakenSubtrie holes.
2260                for (idx, subtrie, _) in taken {
2261                    self.upper_arena[idx] = ArenaSparseNode::Subtrie(subtrie);
2262                }
2263                return err;
2264            }
2265        }
2266
2267        // Restore taken subtries into the upper arena.
2268        for (idx, subtrie, _) in taken {
2269            self.upper_arena[idx] = ArenaSparseNode::Subtrie(subtrie);
2270        }
2271
2272        #[cfg(debug_assertions)]
2273        self.debug_assert_subtrie_structure();
2274
2275        Ok(())
2276    }
2277
2278    #[instrument(level = "trace", target = TRACE_TARGET, skip_all, ret)]
2279    fn root(&mut self, new_epoch: TrieNodeEpoch) -> B256 {
2280        self.update_subtrie_hashes(new_epoch);
2281
2282        let rlp_node = Self::update_cached_rlp(
2283            &mut self.upper_arena,
2284            self.root,
2285            Nibbles::default(),
2286            &mut self.buffers,
2287            new_epoch,
2288        );
2289
2290        rlp_node.as_hash().expect("root RlpNode must be a hash")
2291    }
2292
2293    fn is_root_cached(&self) -> bool {
2294        self.upper_arena[self.root].is_cached()
2295    }
2296
2297    fn root_epoch(&self) -> Option<TrieNodeEpoch> {
2298        match self.upper_arena[self.root].state_ref()? {
2299            ArenaSparseNodeState::Revealed => Some(TrieNodeEpoch::UNMODIFIED),
2300            ArenaSparseNodeState::Cached { epoch, .. } => Some(*epoch),
2301            ArenaSparseNodeState::Dirty => None,
2302        }
2303    }
2304
2305    #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
2306    fn update_subtrie_hashes(&mut self, new_epoch: TrieNodeEpoch) {
2307        trace!(target: TRACE_TARGET, "Updating subtrie hashes");
2308
2309        // Only descend if the root is a branch; otherwise there are no subtries.
2310        if !matches!(&self.upper_arena[self.root], ArenaSparseNode::Branch(_)) {
2311            return;
2312        }
2313
2314        // Count total dirty leaves across all subtries to make one global parallelism decision.
2315        let mut total_dirty_leaves: u64 = 0;
2316        let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>)> = Vec::new();
2317        for (idx, node) in &mut self.upper_arena {
2318            let ArenaSparseNode::Subtrie(s) = node else { continue };
2319            if s.num_dirty_leaves == 0 {
2320                continue;
2321            }
2322            total_dirty_leaves += s.num_dirty_leaves;
2323            let ArenaSparseNode::Subtrie(subtrie) =
2324                mem::replace(node, ArenaSparseNode::TakenSubtrie)
2325            else {
2326                unreachable!()
2327            };
2328            taken.push((idx, subtrie));
2329        }
2330
2331        // Hash taken subtries in parallel if total dirty leaves meet the threshold.
2332        if !taken.is_empty() {
2333            if taken.len() == 1 || total_dirty_leaves < self.parallelism_thresholds.min_dirty_leaves
2334            {
2335                for (_, subtrie) in &mut taken {
2336                    subtrie.update_cached_rlp(new_epoch);
2337                }
2338            } else {
2339                use rayon::iter::{IntoParallelIterator, ParallelIterator};
2340
2341                let parent_span = tracing::Span::current();
2342                taken = taken
2343                    .into_par_iter()
2344                    .map(|(idx, mut subtrie)| {
2345                        let _guard = parent_span.enter();
2346                        subtrie.update_cached_rlp(new_epoch);
2347                        (idx, subtrie)
2348                    })
2349                    .collect();
2350            }
2351        }
2352
2353        // If the root branch is already cached and nothing was taken for parallel
2354        // hashing, there are no dirty subtries to process.
2355        if taken.is_empty() && self.upper_arena[self.root].is_cached() {
2356            return;
2357        }
2358
2359        // Walk the upper trie depth-first, restoring hashed subtries and inline-hashing
2360        // any remaining dirty subtries. Only descend into dirty branches; clean subtrees
2361        // cannot contain dirty subtries since dirty state propagates upward.
2362        taken.sort_unstable_by_key(|(_, b)| Reverse(b.path));
2363
2364        self.buffers.cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2365
2366        loop {
2367            let result = self.buffers.cursor.next(&mut self.upper_arena, |_, child| match child {
2368                ArenaSparseNode::Branch(_) | ArenaSparseNode::Subtrie(_) => !child.is_cached(),
2369                ArenaSparseNode::TakenSubtrie => true,
2370                _ => false,
2371            });
2372
2373            match result {
2374                NextResult::Done => break,
2375                NextResult::Branch => continue,
2376                NextResult::NonBranch => {}
2377            }
2378
2379            // Head is a subtrie or taken-subtrie — process it.
2380            let head_idx = self.buffers.cursor.head().expect("cursor is non-empty").index;
2381
2382            if matches!(&self.upper_arena[head_idx], ArenaSparseNode::TakenSubtrie) {
2383                let (_, subtrie) = taken.pop().expect("taken subtries must not be exhausted");
2384                debug_assert_eq!(
2385                    subtrie.path,
2386                    self.buffers.cursor.head().expect("cursor is non-empty").path,
2387                    "taken subtrie path mismatch",
2388                );
2389                self.upper_arena[head_idx] = ArenaSparseNode::Subtrie(subtrie);
2390            }
2391
2392            self.update_upper_subtrie(head_idx, new_epoch);
2393        }
2394    }
2395
2396    fn get_leaf_value(&self, full_path: &Nibbles) -> Option<&Vec<u8>> {
2397        Self::get_leaf_value_in_arena(&self.upper_arena, self.root, full_path, 0)
2398    }
2399
2400    fn find_leaf(
2401        &self,
2402        full_path: &Nibbles,
2403        expected_value: Option<&Vec<u8>>,
2404    ) -> Result<LeafLookup, LeafLookupError> {
2405        Self::find_leaf_in_arena(&self.upper_arena, self.root, full_path, 0, expected_value)
2406    }
2407
2408    fn take_updates(&mut self) -> SparseTrieUpdates {
2409        let Some(updates) = self.buffers.updates.as_mut() else { return Vec::new() };
2410
2411        // Stable sorting preserves append order for each path. Keep the last update,
2412        // including deletions, when collapsing each group of equal paths.
2413        updates.sort_by_key(|(path, _)| *path);
2414        updates.dedup_by(|later, earlier| {
2415            if later.0 == earlier.0 {
2416                mem::swap(earlier, later);
2417                true
2418            } else {
2419                false
2420            }
2421        });
2422        let capacity = updates.len();
2423        mem::replace(updates, Vec::with_capacity(capacity))
2424    }
2425
2426    #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
2427    fn clear(&mut self) {
2428        self.upper_arena = SlotMap::new();
2429        self.root = self
2430            .upper_arena
2431            .insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Revealed });
2432        self.buffers.clear();
2433    }
2434
2435    #[instrument(
2436        level = "trace",
2437        target = TRACE_TARGET,
2438        skip_all,
2439        fields(prune_before = prune_before.get()),
2440    )]
2441    fn prune(&mut self, prune_before: TrieNodeEpoch) -> usize {
2442        assert!(self.root_epoch().is_some(), "prune cannot run on a dirty trie");
2443
2444        // Only descend if the root is a branch; otherwise there are no subtries.
2445        if !matches!(&self.upper_arena[self.root], ArenaSparseNode::Branch(_)) {
2446            return 0;
2447        }
2448
2449        let threshold = self.parallelism_thresholds.min_leaves_for_prune;
2450
2451        let mut cursor = mem::take(&mut self.buffers.cursor);
2452        cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2453
2454        // Subtries taken for parallel pruning.
2455        let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>)> = Vec::new();
2456
2457        let mut pruned = 0;
2458
2459        loop {
2460            let result = cursor.next(&mut self.upper_arena, |_, child| {
2461                matches!(
2462                    child,
2463                    ArenaSparseNode::Branch(_) |
2464                        ArenaSparseNode::Subtrie(_) |
2465                        ArenaSparseNode::Leaf { .. }
2466                )
2467            });
2468
2469            if matches!(result, NextResult::Done) {
2470                break
2471            }
2472
2473            let head = cursor.head().expect("cursor is non-empty");
2474            let head_idx = head.index;
2475            let head_path = head.path;
2476
2477            match &self.upper_arena[head_idx] {
2478                ArenaSparseNode::Branch(_) | ArenaSparseNode::Leaf { .. } => {
2479                    // Don't prune the root.
2480                    if cursor.depth() == 0 {
2481                        continue;
2482                    }
2483
2484                    let node_epoch = self.upper_arena[head_idx]
2485                        .state_ref()
2486                        .and_then(ArenaSparseNodeState::cached_epoch)
2487                        .expect("prune must run after hashing");
2488                    if !node_epoch.should_prune(prune_before) {
2489                        continue;
2490                    }
2491
2492                    Self::remove_pruned_node(
2493                        &mut self.upper_arena,
2494                        &cursor,
2495                        head_idx,
2496                        head_path.last(),
2497                    );
2498                    pruned += 1;
2499                }
2500                ArenaSparseNode::Subtrie(_) => {
2501                    let root_epoch = self.upper_arena[head_idx]
2502                        .state_ref()
2503                        .and_then(ArenaSparseNodeState::cached_epoch)
2504                        .expect("prune must run after hashing");
2505                    if root_epoch.should_prune(prune_before) {
2506                        let removed = Self::remove_pruned_node(
2507                            &mut self.upper_arena,
2508                            &cursor,
2509                            head_idx,
2510                            head_path.last(),
2511                        );
2512                        let ArenaSparseNode::Subtrie(s) = &removed else { unreachable!() };
2513                        pruned += s.arena.len();
2514                        self.recycle_subtrie(removed);
2515                        continue;
2516                    }
2517
2518                    let ArenaSparseNode::Subtrie(subtrie) = &self.upper_arena[head_idx] else {
2519                        unreachable!()
2520                    };
2521                    if subtrie.num_leaves >= threshold {
2522                        let ArenaSparseNode::Subtrie(subtrie) = mem::replace(
2523                            &mut self.upper_arena[head_idx],
2524                            ArenaSparseNode::TakenSubtrie,
2525                        ) else {
2526                            unreachable!()
2527                        };
2528                        taken.push((head_idx, subtrie));
2529                    } else {
2530                        let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[head_idx]
2531                        else {
2532                            unreachable!()
2533                        };
2534                        pruned += subtrie.prune(prune_before);
2535                    }
2536                }
2537                _ => unreachable!("NonBranch in prune walk must be Subtrie, Leaf, or Branch"),
2538            }
2539        }
2540
2541        self.buffers.cursor = cursor;
2542
2543        if !taken.is_empty() {
2544            // Prune taken subtries, in parallel if more than one.
2545            if taken.len() == 1 {
2546                let (_, ref mut subtrie) = taken[0];
2547                pruned += subtrie.prune(prune_before);
2548            } else {
2549                use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator};
2550
2551                let parent_span = tracing::Span::current();
2552                pruned += taken
2553                    .par_iter_mut()
2554                    .map(|(_, subtrie)| {
2555                        let _guard = parent_span.enter();
2556                        let _span = tracing::trace_span!(
2557                            target: TRACE_TARGET,
2558                            "subtrie_prune",
2559                            subtrie = ?subtrie.path,
2560                        )
2561                        .entered();
2562
2563                        subtrie.prune(prune_before)
2564                    })
2565                    .sum::<usize>();
2566            }
2567
2568            // Restore taken subtries into the upper arena.
2569            for (child_idx, subtrie) in taken {
2570                self.upper_arena[child_idx] = ArenaSparseNode::Subtrie(subtrie);
2571            }
2572        }
2573
2574        if pruned > 0 {
2575            compact_arena(&mut self.upper_arena, &mut self.root);
2576        }
2577
2578        pruned
2579    }
2580
2581    #[instrument(
2582        level = "trace",
2583        target = TRACE_TARGET,
2584        skip_all,
2585        fields(num_updates = updates.len()),
2586    )]
2587    fn update_leaves(
2588        &mut self,
2589        updates: &mut B256Map<LeafUpdate>,
2590        mut proof_required_fn: impl FnMut(B256, ProofV2TargetParent),
2591    ) -> SparseTrieResult<()> {
2592        if updates.is_empty() {
2593            return Ok(());
2594        }
2595
2596        // Drain and sort updates lexicographically by nibbles path.
2597        let mut sorted: Vec<_> =
2598            updates.drain().map(|(key, update)| (key, Nibbles::unpack(key), update)).collect();
2599        sorted.sort_unstable_by_key(|entry| entry.1);
2600
2601        let threshold = self.parallelism_thresholds.min_updates;
2602        let parallelize_distributed_updates = sorted.len() >= threshold.saturating_mul(4);
2603
2604        let mut cursor = mem::take(&mut self.buffers.cursor);
2605        cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2606
2607        // Subtries taken for parallel processing: (arena_index, subtrie, update_range).
2608        let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>, core::ops::Range<usize>)> = Vec::new();
2609
2610        let mut update_idx = 0;
2611        while update_idx < sorted.len() {
2612            let (key, ref full_path, ref update) = sorted[update_idx];
2613
2614            let find_result = cursor.seek(&mut self.upper_arena, full_path);
2615
2616            match find_result {
2617                // Blinded — request a proof regardless of update type.
2618                SeekResult::Blinded => {
2619                    let logical_len = cursor.head_logical_branch_path_len(&self.upper_arena);
2620                    let parent = ProofV2TargetParent::new(logical_len);
2621                    trace!(target: TRACE_TARGET, ?key, ?parent, "Update hit blinded node, requesting proof");
2622                    proof_required_fn(key, parent);
2623                    updates.insert(key, update.clone());
2624                }
2625                // Subtrie — forward all consecutive updates under this subtrie's prefix.
2626                SeekResult::RevealedSubtrie => {
2627                    let subtrie_entry = cursor.head().expect("cursor is non-empty");
2628                    let child_idx = subtrie_entry.index;
2629                    let subtrie_root_path = subtrie_entry.path;
2630
2631                    let subtrie_start = update_idx;
2632                    while update_idx < sorted.len() &&
2633                        sorted[update_idx].1.starts_with(&subtrie_root_path)
2634                    {
2635                        update_idx += 1;
2636                    }
2637
2638                    let subtrie_updates = &sorted[subtrie_start..update_idx];
2639
2640                    // Edge-case: if all updates are removals that could empty the
2641                    // subtrie and collapse the parent onto a blinded sibling, request
2642                    // a proof for the sibling and skip the subtrie's updates.
2643                    if let Some(proof) = Self::check_subtrie_collapse_needs_proof(
2644                        &self.upper_arena,
2645                        &cursor,
2646                        subtrie_updates,
2647                    ) {
2648                        trace!(target: TRACE_TARGET, proof_key = ?proof.key, proof_parent = ?proof.parent, "Subtrie collapse would need blinded sibling, requesting proof");
2649                        proof_required_fn(proof.key, proof.parent);
2650                        for &(key, _, ref update) in subtrie_updates {
2651                            updates.insert(key, update.clone());
2652                        }
2653                        // Pop the subtrie entry before continuing.
2654                        continue;
2655                    }
2656
2657                    let num_subtrie_updates = update_idx - subtrie_start;
2658
2659                    // If all updates are removals and could empty the subtrie,
2660                    // force inline processing so the upper-arena collapse logic
2661                    // can detect blinded siblings and request proofs.
2662                    let all_removals = subtrie_updates
2663                        .iter()
2664                        // Filter out Touched, as they don't affect the structure of the trie. So an
2665                        // update set with 2 removals and one Touched could still result in an empty
2666                        // sub trie.
2667                        .filter(|(_, _, u)| matches!(u, LeafUpdate::Changed(_)))
2668                        .all(|(_, _, u)| matches!(u, LeafUpdate::Changed(v) if v.is_empty()));
2669                    let subtrie_num_leaves = match &self.upper_arena[child_idx] {
2670                        ArenaSparseNode::Subtrie(s) => s.num_leaves,
2671                        _ => 0,
2672                    };
2673                    let might_empty_subtrie =
2674                        all_removals && num_subtrie_updates as u64 >= subtrie_num_leaves;
2675
2676                    if (num_subtrie_updates >= threshold || parallelize_distributed_updates) &&
2677                        !might_empty_subtrie
2678                    {
2679                        // Take subtrie for parallel update.
2680                        trace!(target: TRACE_TARGET, ?subtrie_root_path, num_subtrie_updates, "Taking subtrie for parallel update");
2681                        let ArenaSparseNode::Subtrie(subtrie) = mem::replace(
2682                            &mut self.upper_arena[child_idx],
2683                            ArenaSparseNode::TakenSubtrie,
2684                        ) else {
2685                            unreachable!()
2686                        };
2687                        taken.push((child_idx, subtrie, subtrie_start..update_idx));
2688                    } else {
2689                        // Update inline.
2690                        trace!(target: TRACE_TARGET, ?subtrie_root_path, num_subtrie_updates, "Updating subtrie inline");
2691                        let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[child_idx]
2692                        else {
2693                            unreachable!()
2694                        };
2695
2696                        subtrie.update_leaves(subtrie_updates);
2697
2698                        for (target_idx, proof) in subtrie.required_proofs.drain(..) {
2699                            proof_required_fn(proof.key, proof.parent);
2700                            let (key, _, ref update) = subtrie_updates[target_idx];
2701                            updates.insert(key, update.clone());
2702                        }
2703
2704                        // Check if the subtrie's root became empty after updates.
2705                        self.maybe_unwrap_subtrie(&mut cursor);
2706                    }
2707
2708                    // Don't increment update_idx — already advanced past subtrie updates.
2709                    continue;
2710                }
2711                // EmptyRoot, leaf, diverged branch, or empty child slot — upsert directly.
2712                find_result @ (SeekResult::EmptyRoot |
2713                SeekResult::RevealedLeaf |
2714                SeekResult::Diverged |
2715                SeekResult::NoChild { .. }) => match update {
2716                    LeafUpdate::Changed(v) if !v.is_empty() => {
2717                        let (result, _deltas) = Self::upsert_leaf(
2718                            &mut self.upper_arena,
2719                            &mut cursor,
2720                            &mut self.root,
2721                            full_path,
2722                            v,
2723                            find_result,
2724                        );
2725                        match result {
2726                            UpsertLeafResult::NewChild => {
2727                                let head = cursor.head().expect("cursor is non-empty");
2728                                if Self::should_be_subtrie(head.path.len()) {
2729                                    // The new child itself sits at the subtrie
2730                                    // boundary — wrap it directly.
2731                                    self.maybe_wrap_in_subtrie(head.index, &head.path);
2732                                } else {
2733                                    // The new child is above the boundary (e.g. a
2734                                    // split at depth 1 creates children at depth 2).
2735                                    // Wrap any of its children that land there.
2736                                    self.maybe_wrap_branch_children(&cursor);
2737                                }
2738                            }
2739                            UpsertLeafResult::NewLeaf => {
2740                                // A root-level split may create children at the
2741                                // subtrie boundary depth. Wrap them.
2742                                self.maybe_wrap_branch_children(&cursor);
2743                            }
2744                            UpsertLeafResult::Updated => {}
2745                        }
2746                    }
2747                    LeafUpdate::Changed(_) => {
2748                        let (result, _deltas) = Self::remove_leaf(
2749                            &mut self.upper_arena,
2750                            &mut cursor,
2751                            &mut self.root,
2752                            key,
2753                            full_path,
2754                            find_result,
2755                            &mut self.buffers.updates,
2756                        );
2757                        match result {
2758                            RemoveLeafResult::NeedsProof { key, proof_key, parent } => {
2759                                proof_required_fn(proof_key, parent);
2760                                let update =
2761                                    mem::replace(&mut sorted[update_idx].2, LeafUpdate::Touched);
2762                                updates.insert(key, update);
2763                            }
2764                            RemoveLeafResult::Removed => {
2765                                // remove_leaf may have called collapse_branch, which
2766                                // can leave structural invariants violated:
2767                                // 1. A branch with 0-1 children that needs further collapse or
2768                                //    removal.
2769                                // 2. A Subtrie at a depth shallower than UPPER_TRIE_MAX_DEPTH that
2770                                //    needs unwrapping.
2771                                // 3. A non-Subtrie node at UPPER_TRIE_MAX_DEPTH that needs
2772                                //    wrapping.
2773                                self.maybe_collapse_or_remove_branch(&mut cursor);
2774                                let head =
2775                                    cursor.head().expect("cursor always has root after collapse");
2776                                self.maybe_wrap_in_subtrie(head.index, &head.path);
2777                            }
2778                            RemoveLeafResult::NotFound => {}
2779                        }
2780                    }
2781                    LeafUpdate::Touched => {}
2782                },
2783            }
2784
2785            update_idx += 1;
2786        }
2787
2788        // Drain remaining cursor entries from the upper-trie walk.
2789        cursor.drain(&mut self.upper_arena);
2790        self.buffers.cursor = cursor;
2791
2792        if taken.is_empty() {
2793            #[cfg(debug_assertions)]
2794            self.debug_assert_subtrie_structure();
2795
2796            return Ok(());
2797        }
2798
2799        // Apply updates to taken subtries, in parallel if more than one.
2800        if taken.len() == 1 {
2801            let (_, ref mut subtrie, ref range) = taken[0];
2802            subtrie.update_leaves(&sorted[range.clone()]);
2803        } else {
2804            use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator};
2805
2806            let parent_span = tracing::Span::current();
2807            taken.par_iter_mut().for_each(|(_, subtrie, range)| {
2808                let _guard = parent_span.enter();
2809                subtrie.update_leaves(&sorted[range.clone()]);
2810            });
2811        }
2812
2813        // Collect subtrie paths before consuming `taken`, then restore subtries and
2814        // process required proofs.
2815        let taken_paths: Vec<Nibbles> = taken.iter().map(|(_, s, _)| s.path).collect();
2816        for (child_idx, mut subtrie, range) in taken {
2817            let subtrie_updates = &sorted[range];
2818            for (target_idx, proof) in subtrie.required_proofs.drain(..) {
2819                proof_required_fn(proof.key, proof.parent);
2820                let (key, _, ref update) = subtrie_updates[target_idx];
2821                updates.insert(key, update.clone());
2822            }
2823
2824            // Restore the subtrie into the upper arena.
2825            self.upper_arena[child_idx] = ArenaSparseNode::Subtrie(subtrie);
2826        }
2827
2828        // Navigate to each taken subtrie via seek to propagate dirty state
2829        // through intermediate branches. Taken subtries are guaranteed not to
2830        // become EmptyRoot (the would-empty-subtrie check above forces those
2831        // inline), so we only need to handle sibling collapses that may have
2832        // occurred during inline processing while this subtrie was taken.
2833        {
2834            let mut cursor = mem::take(&mut self.buffers.cursor);
2835            cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2836
2837            for path in &taken_paths {
2838                let find_result = cursor.seek(&mut self.upper_arena, path);
2839                match find_result {
2840                    SeekResult::RevealedSubtrie => {
2841                        debug_assert!(
2842                            {
2843                                let head_idx = cursor.head().expect("cursor is non-empty").index;
2844                                !matches!(
2845                                    &self.upper_arena[head_idx],
2846                                    ArenaSparseNode::Subtrie(s) if matches!(s.arena[s.root], ArenaSparseNode::EmptyRoot { .. })
2847                                )
2848                            },
2849                            "taken subtrie became EmptyRoot — should have been forced inline"
2850                        );
2851
2852                        cursor.pop(&mut self.upper_arena);
2853
2854                        // The parent branch (now at cursor top) may have had a sibling
2855                        // removed during inline processing while this subtrie was taken.
2856                        // Handle any necessary collapse or removal.
2857                        self.maybe_collapse_or_remove_branch(&mut cursor);
2858                    }
2859                    _ => {
2860                        // Subtrie was already unwrapped by a prior collapse; dirty state
2861                        // was propagated during that collapse. Nothing to do.
2862                    }
2863                }
2864            }
2865
2866            cursor.drain(&mut self.upper_arena);
2867            self.buffers.cursor = cursor;
2868        }
2869
2870        #[cfg(debug_assertions)]
2871        self.debug_assert_subtrie_structure();
2872
2873        Ok(())
2874    }
2875}
2876
2877#[cfg(test)]
2878mod tests {
2879    use super::TRACE_TARGET;
2880    use crate::{
2881        ArenaParallelSparseTrie, ArenaParallelismThresholds, LeafUpdate, SparseTrie, TrieNodeEpoch,
2882    };
2883    use alloy_primitives::{map::B256Map, B256, U256};
2884    use rand::{seq::SliceRandom, Rng, SeedableRng};
2885    use reth_trie::test_utils::TrieTestHarness;
2886    use reth_trie_common::ProofV2Target;
2887    use std::collections::BTreeMap;
2888    use tracing::{info, trace};
2889
2890    const fn epoch(value: u64) -> TrieNodeEpoch {
2891        TrieNodeEpoch::new(value)
2892    }
2893
2894    /// Test harness for proptest-based arena sparse trie testing.
2895    ///
2896    /// Wraps [`TrieTestHarness`] and adds `ArenaParallelSparseTrie`-specific helpers for
2897    /// the reveal-update loop and asserting that sparse trie updates match `StorageRoot`.
2898    struct ArenaTrieTestHarness {
2899        /// The inner general-purpose harness.
2900        inner: TrieTestHarness,
2901    }
2902
2903    impl std::ops::Deref for ArenaTrieTestHarness {
2904        type Target = TrieTestHarness;
2905        fn deref(&self) -> &Self::Target {
2906            &self.inner
2907        }
2908    }
2909
2910    impl std::ops::DerefMut for ArenaTrieTestHarness {
2911        fn deref_mut(&mut self) -> &mut Self::Target {
2912            &mut self.inner
2913        }
2914    }
2915
2916    impl ArenaTrieTestHarness {
2917        /// Creates a new test harness from a map of hashed storage slots to values.
2918        fn new(storage: BTreeMap<B256, U256>) -> Self {
2919            Self { inner: TrieTestHarness::new(storage) }
2920        }
2921
2922        /// Computes the new storage root and trie updates after applying the given changes
2923        /// using both `StorageRoot` and the provided `ArenaParallelSparseTrie`, then asserts
2924        /// they match.
2925        fn assert_changes(
2926            &self,
2927            apst: &mut ArenaParallelSparseTrie,
2928            changes: BTreeMap<B256, U256>,
2929        ) {
2930            // Compute expected root and trie updates via StorageRoot.
2931            let (expected_root, mut expected_trie_updates) = if changes.is_empty() {
2932                (self.original_root(), Default::default())
2933            } else {
2934                self.get_root_with_updates(&changes)
2935            };
2936
2937            self.minimize_trie_updates(&mut expected_trie_updates);
2938
2939            // Build leaf updates for the APST: non-zero values are upserts (RLP-encoded),
2940            // zero values are deletions (empty vec).
2941            let mut leaf_updates: B256Map<LeafUpdate> = changes
2942                .iter()
2943                .map(|(&slot, &value)| {
2944                    let rlp_value = if value == U256::ZERO {
2945                        Vec::new()
2946                    } else {
2947                        alloy_rlp::encode_fixed_size(&value).to_vec()
2948                    };
2949                    (slot, LeafUpdate::Changed(rlp_value))
2950                })
2951                .collect();
2952
2953            // Reveal-update loop: call update_leaves, collect required proofs, fetch them,
2954            // reveal, and repeat until no more proofs are needed.
2955            loop {
2956                let mut targets: Vec<ProofV2Target> = Vec::new();
2957                apst.update_leaves(&mut leaf_updates, |key, parent| {
2958                    targets.push(ProofV2Target::new(key).with_parent(parent));
2959                })
2960                .expect("update_leaves should succeed");
2961
2962                if targets.is_empty() {
2963                    break;
2964                }
2965
2966                let (mut proof_nodes, _) = self.proof_v2(&mut targets);
2967                apst.reveal_nodes(&mut proof_nodes).expect("reveal_nodes should succeed");
2968            }
2969
2970            // Compute root and take updates from the APST.
2971            let actual_root = apst.root(epoch(0));
2972            let mut actual_updates = apst.take_updates();
2973
2974            actual_updates.retain(|(path, node)| match node {
2975                Some(node) => self.storage_trie_updates().storage_nodes.get(path) != Some(node),
2976                None => self.storage_trie_updates().storage_nodes.contains_key(path),
2977            });
2978            pretty_assertions::assert_eq!(
2979                expected_trie_updates.into_sorted().storage_nodes,
2980                actual_updates,
2981                "trie updates mismatch"
2982            );
2983            assert_eq!(expected_root, actual_root, "storage root mismatch");
2984        }
2985    }
2986
2987    use proptest::prelude::*;
2988    use proptest_arbitrary_interop::arb;
2989
2990    /// Builds a changeset by mixing `new_keys` (fresh insertions) with a fraction of
2991    /// existing keys from `base` (updates/deletions).
2992    ///
2993    /// `overlap_pct` controls how many existing keys are included, and `delete_pct`
2994    /// controls how many of those become deletions (zero values). The remaining
2995    /// overlap keys get random non-zero values.
2996    fn build_changeset(
2997        base: &BTreeMap<B256, U256>,
2998        new_keys: BTreeMap<B256, U256>,
2999        overlap_pct: f64,
3000        delete_pct: f64,
3001        rng: &mut rand::rngs::StdRng,
3002    ) -> BTreeMap<B256, U256> {
3003        let num_overlap = (base.len() as f64 * overlap_pct) as usize;
3004        let num_delete = (num_overlap as f64 * delete_pct) as usize;
3005
3006        let mut all_keys: Vec<B256> = base.keys().copied().collect();
3007        all_keys.shuffle(rng);
3008        let overlap_keys = &all_keys[..num_overlap];
3009
3010        let mut changeset = new_keys;
3011        for (i, &key) in overlap_keys.iter().enumerate() {
3012            let value =
3013                if i < num_delete { U256::ZERO } else { U256::from(rng.random::<u64>() | 1) };
3014            changeset.entry(key).or_insert(value);
3015        }
3016        changeset
3017    }
3018
3019    proptest! {
3020        #![proptest_config(ProptestConfig::with_cases(1000))]
3021        #[test]
3022        fn arena_trie_proptest(
3023            initial in proptest::collection::btree_map(arb::<B256>(), arb::<U256>(), 0..=100usize),
3024            changeset1_new_keys in proptest::collection::btree_map(arb::<B256>(), arb::<U256>(), 0..=30usize),
3025            changeset2_new_keys in proptest::collection::btree_map(arb::<B256>(), arb::<U256>(), 0..=30usize),
3026            overlap_pct in 0.0..=0.5f64,
3027            delete_pct in 0.0..=0.33f64, // percent of overlapping changeset which are deletes
3028            shuffle_seed in arb::<u64>(),
3029        ) {
3030            reth_tracing::init_test_tracing();
3031            info!(target: TRACE_TARGET, ?shuffle_seed, "PROPTEST START");
3032
3033            // Filter out zero-valued entries from the initial dataset (zeros mean "absent").
3034            let initial: BTreeMap<B256, U256> = initial.into_iter()
3035                .filter(|(_, v)| *v != U256::ZERO)
3036                .collect();
3037
3038            let mut rng = rand::rngs::StdRng::seed_from_u64(shuffle_seed);
3039
3040            let changeset1 = build_changeset(&initial, changeset1_new_keys, overlap_pct, delete_pct, &mut rng);
3041            for (i, (k, v)) in changeset1.iter().enumerate() {
3042                trace!(target: TRACE_TARGET, ?i, ?k, ?v, "Changeset 1 entry");
3043            }
3044
3045            let mut harness = ArenaTrieTestHarness::new(initial);
3046
3047            // Initialize the APST from the harness root node.
3048            let root_node = harness.root_node();
3049            let mut apst = ArenaParallelSparseTrie::default().with_parallelism_thresholds(
3050                ArenaParallelismThresholds {
3051                    min_dirty_leaves: 3,
3052                    min_revealed_nodes: 3,
3053                    min_updates: 3,
3054                    min_leaves_for_prune: 3,
3055                },
3056            );
3057            apst.set_root(root_node.node, root_node.masks, true).expect("set_root should succeed");
3058
3059            harness.assert_changes(&mut apst, changeset1.clone());
3060
3061            // Update the harness base dataset to reflect the first changeset.
3062            harness.apply_changeset(changeset1);
3063
3064            // All nodes were cached at epoch 0, so this maximally prunes the trie before the
3065            // second update round.
3066            apst.prune(epoch(1));
3067
3068            let changeset2 = build_changeset(harness.storage(), changeset2_new_keys, overlap_pct, delete_pct, &mut rng);
3069            for (i, (k, v)) in changeset2.iter().enumerate() {
3070                trace!(target: TRACE_TARGET, ?i, ?k, ?v, "Changeset 2 entry");
3071            }
3072
3073            harness.assert_changes(&mut apst, changeset2);
3074        }
3075    }
3076}