Skip to main content

reth_engine_tree/tree/payload_processor/
mod.rs

1//! Entrypoint for payload processing.
2
3use crate::tree::{
4    payload_processor::{
5        prewarm::{PrewarmCacheTask, PrewarmContext, PrewarmMode, PrewarmTaskEvent},
6        reuse::{cfg_reuses_prewarm_results, PrewarmResults},
7    },
8    CacheCheckout, CachedStateCacheMetrics, CachedStateMetrics, CachedStateMetricsSource,
9    ExecutionCache, ExecutionEnv, PayloadExecutionCache, SavedCache, TreeConfig,
10};
11use alloy_eips::eip1898::BlockWithParent;
12use alloy_primitives::B256;
13use prewarm::PrewarmMetrics;
14use reth_concurrency::sync::{
15    atomic::{AtomicBool, AtomicUsize},
16    channel,
17    channel::{mpsc, Receiver, Sender},
18    rayon::prelude::*,
19    time::FastInstant as Instant,
20    OnceLock,
21};
22use reth_evm::{
23    precompile_cache::PrecompileCacheMap, ConfigureEvm, ConvertTx, EvmEnv, EvmTypesFor,
24    ExecutableTxFor, ExecutableTxIterator, ExecutableTxParts, ExecutableTxTuple, SpecFor, TxEnvFor,
25    WithTxEnv,
26};
27use reth_primitives_traits::NodePrimitives;
28use reth_provider::{
29    BlockExecutionOutput, BlockNumReader, ChangeSetReader, DatabaseProviderFactory, HistoryReader,
30    PruneCheckpointReader, StageCheckpointReader, StorageChangeSetReader, StorageSettingsCache,
31};
32use reth_storage_overlay::OverlayStateProviderFactory;
33use reth_tasks::Runtime;
34use reth_trie_common::bundle_state::BundleState;
35pub use reth_trie_parallel::{
36    error::StateRootTaskError,
37    state_root_task::{
38        PayloadStateRootHandle, StateAccessHint, StateRootComputeOutcome, StateRootHandle,
39        StateRootHintStream, StateRootMessage, StateRootTaskCancelGuard, StateRootUpdateHook,
40        StateRootUpdateStream,
41    },
42};
43use std::{num::NonZeroUsize, ops::Not, sync::Arc};
44use tracing::{debug, debug_span, instrument, trace, trace_span, warn, Span};
45
46pub mod bal;
47pub mod bal_prewarm_pool;
48pub mod prewarm;
49pub mod receipt_root_task;
50pub(crate) mod reuse;
51
52/// Blocks with fewer transactions than this skip prewarming, since the fixed overhead of spawning
53/// prewarm workers exceeds the execution time saved.
54pub const SMALL_BLOCK_TX_THRESHOLD: usize = 5;
55
56/// Type alias for [`PayloadHandle`] returned by payload processor spawn methods.
57type IteratorTx<Evm, I> = RecoveredTx<TxEnvFor<Evm>, <I as ExecutableTxIterator<Evm>>::Recovered>;
58
59type IteratorPayloadHandle<Evm, I> = PayloadHandle<
60    IteratorTx<Evm, I>,
61    <I as ExecutableTxTuple>::Error,
62    <<Evm as ConfigureEvm>::Primitives as NodePrimitives>::Receipt,
63    EvmTypesFor<Evm>,
64>;
65
66type IteratorPrewarmTxReceiver<Evm, I> =
67    PrewarmTxReceiver<TxEnvFor<Evm>, <I as ExecutableTxIterator<Evm>>::Recovered>;
68
69type IteratorExecuteTxReceiver<Evm, I> = ExecuteTxReceiver<
70    TxEnvFor<Evm>,
71    <I as ExecutableTxIterator<Evm>>::Recovered,
72    <I as ExecutableTxTuple>::Error,
73>;
74
75type RecoveredTx<TxEnv, Recovered> = WithTxEnv<TxEnv, Recovered>;
76type IndexedTxResult<Tx, Err> = (usize, Result<Tx, Err>);
77type IndexedTxReceiver<Tx, Err> = Receiver<IndexedTxResult<Tx, Err>>;
78type IndexedTxSender<Tx, Err> = Sender<IndexedTxResult<Tx, Err>>;
79type PrewarmTxReceiver<TxEnv, Recovered> = mpsc::Receiver<(usize, RecoveredTx<TxEnv, Recovered>)>;
80type ExecuteTxReceiver<TxEnv, Recovered, Err> =
81    IndexedTxReceiver<RecoveredTx<TxEnv, Recovered>, Err>;
82type ExecuteTxSender<TxEnv, Recovered, Err> = IndexedTxSender<RecoveredTx<TxEnv, Recovered>, Err>;
83
84/// Entrypoint for executing the payload.
85#[derive(Debug)]
86pub struct PayloadProcessor<Evm>
87where
88    Evm: ConfigureEvm,
89{
90    /// The executor used by to spawn tasks.
91    executor: Runtime,
92    /// The most recent cache used for execution.
93    execution_cache: PayloadExecutionCache,
94    /// Metrics for the execution cache.
95    cache_metrics: Option<CachedStateMetrics>,
96    /// Metrics for shared execution cache state.
97    cache_state_metrics: Option<CachedStateCacheMetrics>,
98    /// Cross-block cache size in bytes.
99    cross_block_cache_size: usize,
100    /// Whether transactions should not be executed on prewarming task.
101    disable_transaction_prewarming: bool,
102    /// Whether state cache should be disable
103    disable_state_cache: bool,
104    /// Determines how to configure the evm for execution.
105    evm_config: Evm,
106    /// Whether precompile cache should be disabled.
107    precompile_cache_disabled: bool,
108    /// Precompile cache map.
109    precompile_cache_map: PrecompileCacheMap<SpecFor<Evm>>,
110    /// Whether to disable BAL-driven parallel state root computation.
111    /// Only valid when BAL parallel execution is also disabled.
112    disable_bal_parallel_state_root: bool,
113    /// Whether BAL state prefetching during prewarm is disabled.
114    disable_bal_batch_io: bool,
115    /// Whether block execution may reuse transaction prewarming results.
116    reuse_prewarm_results: bool,
117    /// Dedicated blocking pool for warming the BAL read-set, created lazily on the first BAL block
118    /// (see [`Self::bal_prewarm_pool`]). Its threads exit when the processor is dropped.
119    bal_prewarm_pool: OnceLock<Arc<bal_prewarm_pool::BalPrewarmPool>>,
120    /// Number of BAL read-set prewarm workers for this engine.
121    bal_prewarm_threads: usize,
122}
123
124impl<Evm> PayloadProcessor<Evm>
125where
126    Evm: ConfigureEvm,
127{
128    /// Creates a new payload processor.
129    pub fn new(
130        executor: Runtime,
131        evm_config: Evm,
132        config: &TreeConfig,
133        precompile_cache_map: PrecompileCacheMap<SpecFor<Evm>>,
134    ) -> Self {
135        Self {
136            executor,
137            execution_cache: Default::default(),
138            cross_block_cache_size: config.cross_block_cache_size(),
139            disable_transaction_prewarming: config.disable_prewarming(),
140            evm_config,
141            disable_state_cache: config.disable_state_cache(),
142            precompile_cache_disabled: config.precompile_cache_disabled(),
143            precompile_cache_map,
144            cache_metrics: (!config.disable_cache_metrics())
145                .then(|| CachedStateMetrics::zeroed(CachedStateMetricsSource::Engine)),
146            cache_state_metrics: (!config.disable_cache_metrics())
147                .then(CachedStateCacheMetrics::default),
148            disable_bal_parallel_state_root: config.disable_bal_parallel_state_root(),
149            disable_bal_batch_io: config.disable_bal_batch_io(),
150            reuse_prewarm_results: config.prewarm_reuse(),
151            bal_prewarm_pool: OnceLock::new(),
152            bal_prewarm_threads: config
153                .bal_prewarm_threads()
154                .map_or(bal_prewarm_pool::DEFAULT_BAL_PREWARM_THREADS, NonZeroUsize::get),
155        }
156    }
157
158    /// Returns the dedicated BAL read-set prewarm pool, spawning its blocking worker threads on
159    /// first use (only the BAL parallel execution path calls this).
160    fn bal_prewarm_pool(&self) -> Arc<bal_prewarm_pool::BalPrewarmPool> {
161        self.bal_prewarm_pool
162            .get_or_init(|| bal_prewarm_pool::BalPrewarmPool::new(self.bal_prewarm_threads))
163            .clone()
164    }
165
166    /// Returns the shared execution cache handle used for engine backpressure.
167    pub(crate) fn execution_cache(&self) -> PayloadExecutionCache {
168        self.execution_cache.clone()
169    }
170}
171
172impl<Evm> PayloadProcessor<Evm>
173where
174    Evm: ConfigureEvm + 'static,
175{
176    /// Spawns transaction conversion and cache prewarming, optionally wiring prewarm output into
177    /// an externally-owned state-root task.
178    #[instrument(level = "debug", target = "engine::tree::payload_processor", skip_all)]
179    pub fn spawn_with_state_root_streams<P, I: ExecutableTxIterator<Evm>>(
180        &self,
181        env: ExecutionEnv<Evm>,
182        transactions: I,
183        state_provider_factory: OverlayStateProviderFactory<P, Evm::Primitives>,
184        hint_stream: Option<StateRootHintStream>,
185        hashed_update_stream: Option<StateRootUpdateStream>,
186        parallel_bal_execution: bool,
187    ) -> IteratorPayloadHandle<Evm, I>
188    where
189        P: DatabaseProviderFactory + Clone + 'static,
190        P::Provider: BlockNumReader
191            + PruneCheckpointReader
192            + StageCheckpointReader
193            + ChangeSetReader
194            + StorageChangeSetReader
195            + StorageSettingsCache
196            + HistoryReader
197            + 'static,
198    {
199        let prewarm_transactions =
200            self.prewarms_transactions(env.transaction_count, parallel_bal_execution);
201        let (prewarm_rx, execution_rx) = self.spawn_tx_iterator(
202            transactions,
203            env.transaction_count,
204            parallel_bal_execution,
205            prewarm_transactions,
206        );
207        let prewarm_handle = self.spawn_caching_with(
208            env,
209            prewarm_rx,
210            state_provider_factory,
211            hint_stream,
212            hashed_update_stream,
213            parallel_bal_execution,
214        );
215        PayloadHandle { prewarm_handle, transactions: execution_rx, _span: Span::current() }
216    }
217
218    /// Whether the prewarm task will consume converted transactions, i.e. whether
219    /// [`Self::spawn_caching_with`] ends up in [`PrewarmMode::Transactions`].
220    ///
221    /// This is the only place the decision is made: the tx iterator uses it to skip creating the
222    /// prewarm channel and cloning every transaction into it, and the resulting `Option` receiver
223    /// then selects the mode, so the two cannot disagree.
224    const fn prewarms_transactions(
225        &self,
226        transaction_count: usize,
227        parallel_bal_execution: bool,
228    ) -> bool {
229        !parallel_bal_execution &&
230            !self.disable_transaction_prewarming &&
231            transaction_count >= SMALL_BLOCK_TX_THRESHOLD
232    }
233
234    /// Transaction count threshold below which sequential conversion is used.
235    ///
236    /// For blocks with fewer than this many transactions, the rayon parallel iterator overhead
237    /// (work-stealing setup, channel-based reorder) exceeds the cost of sequential conversion.
238    /// Inspired by Nethermind's `RecoverSignature` which uses sequential `foreach` for small
239    /// blocks.
240    const SMALL_BLOCK_TX_THRESHOLD: usize = 30;
241
242    /// Number of leading transactions to convert sequentially before entering the rayon
243    /// parallel path.
244    ///
245    /// Rayon's work-stealing does not guarantee that index 0 is processed first, so the
246    /// ordered consumer can block for up to ~1ms waiting for the first slot. By converting
247    /// a small head sequentially and sending it immediately, execution can start without
248    /// waiting for rayon scheduling.
249    const PARALLEL_PREFETCH_COUNT: usize = 4;
250
251    /// Size of the first parallel tx batch in non-BAL path.
252    const FIRST_PARALLEL_TX_WINDOW_SIZE: usize = 64;
253
254    /// Spawns a task advancing transaction env iterator and streaming updates through a channel.
255    ///
256    /// For blocks with fewer than [`Self::SMALL_BLOCK_TX_THRESHOLD`] transactions, uses
257    /// sequential iteration to avoid rayon overhead. For larger blocks, uses rayon parallel
258    /// iteration to convert transactions in parallel while streaming results to execution.
259    ///
260    /// When `parallel_bal_execution` is disabled, preserves the original transaction order.
261    /// Otherwise, streams results as they become available.
262    ///
263    /// The prewarm channel is only created when `prewarm_transactions` is set, see
264    /// [`Self::prewarms_transactions`]; otherwise no transaction is cloned into it.
265    #[instrument(level = "debug", target = "engine::tree::payload_processor", skip_all)]
266    fn spawn_tx_iterator<I: ExecutableTxIterator<Evm>>(
267        &self,
268        transactions: I,
269        transaction_count: usize,
270        parallel_bal_execution: bool,
271        prewarm_transactions: bool,
272    ) -> (Option<IteratorPrewarmTxReceiver<Evm, I>>, IteratorExecuteTxReceiver<Evm, I>) {
273        let (prewarm_tx, prewarm_rx) =
274            prewarm_transactions.then(|| mpsc::sync_channel(transaction_count)).unzip();
275        let (execute_tx, execute_rx) = channel::bounded(transaction_count);
276        let parent_span = Span::current();
277
278        if transaction_count == 0 {
279            // Empty block — nothing to do.
280        } else if transaction_count < Self::SMALL_BLOCK_TX_THRESHOLD {
281            // Sequential path for small blocks — avoids rayon work-stealing setup and
282            // channel-based reorder overhead when it costs more than sequential conversion.
283            debug!(
284                target: "engine::tree::payload_processor",
285                transaction_count,
286                "using sequential sig recovery for small block"
287            );
288            self.executor.spawn_blocking_named("tx-iterator", move || {
289                // Restore the parent even when the worker span is filtered out.
290                let _parent = parent_span.enter();
291                let _span = debug_span!(target: "engine::tree::payload_processor", "tx_iterator", transaction_count).entered();
292                let (transactions, convert) = transactions.into_parts();
293                convert_serial(
294                    transactions.into_iter(),
295                    &convert,
296                    prewarm_tx.as_ref(),
297                    &execute_tx,
298                );
299            });
300        } else {
301            // Parallel path — recover signatures in parallel on rayon, stream results
302            // to prewarming and execution.
303            let executor = self.executor.clone();
304            self.executor.spawn_blocking_named("tx-iterator", move || {
305                let _parent = parent_span.enter();
306                let _span = debug_span!(target: "engine::tree::payload_processor", "tx_iterator", transaction_count).entered();
307                let (transactions, convert) = transactions.into_parts();
308                if parallel_bal_execution {
309                    // With BALs, we don't care about the order of transactions in execution and
310                    // prewarming, so we don't have to use `for_each_ordered_in`.
311                    let parent_span = Span::current();
312                    executor.cpu_pool().install(|| {
313                        let _parent = parent_span.enter();
314                        let span = debug_span!(target: "engine::tree::payload_processor", "convert_transactions").or_current();
315                        let _entered = span.enter();
316                        let _ = transactions
317                            .into_par_iter()
318                            .enumerate()
319                            // Feed the ordered commit loop before recovering distant transactions.
320                            .by_exponential_blocks()
321                            .try_for_each(|(idx, tx)| {
322                                let _parent = span.enter();
323                                let _span = trace_span!(target: "engine::tree::payload_processor", "convert_transaction", idx).entered();
324                                let tx = convert.convert(tx).map(WithTxEnv::new);
325                                if let (Some(prewarm_tx), Ok(tx)) = (&prewarm_tx, &tx) {
326                                    let _ = prewarm_tx.send((idx, tx.clone()));
327                                }
328                                let disconnected = execute_tx.send((idx, tx)).is_err();
329                                trace!(target: "engine::tree::payload_processor", idx, "yielded transaction");
330                                // Recovery failures are adjudicated in transaction order by
331                                // the BAL commit loop. Earlier slots may still be unconverted.
332                                if disconnected {
333                                    Err(())
334                                } else {
335                                    Ok(())
336                                }
337                            });
338                    });
339                } else {
340                    // To avoid a ~1ms stall waiting for rayon to schedule index 0, the first
341                    // few transactions are recovered sequentially and sent immediately before
342                    // entering the parallel iterator for the remainder.
343                    let prefetch = Self::PARALLEL_PREFETCH_COUNT.min(transaction_count);
344                    let mut iter = transactions.into_iter();
345
346                    // Convert the first few transactions sequentially so execution can
347                    // start immediately without waiting for rayon work-stealing.
348                    if !convert_serial(
349                        iter.by_ref().take(prefetch),
350                        &convert,
351                        prewarm_tx.as_ref(),
352                        &execute_tx,
353                    ) {
354                        return
355                    }
356
357                    let mut iter = iter.enumerate();
358
359                    let mut batch_size = Self::FIRST_PARALLEL_TX_WINDOW_SIZE;
360
361                    // Without BALs, we need to preserve the initial order of transactions.
362                    // Process exponentially increasing windows to make sure that first transactions are prioritized.
363                    let parent_span = Span::current();
364                    executor.cpu_pool().install(move || {
365                        let _parent = parent_span.enter();
366                        let span = debug_span!(target: "engine::tree::payload_processor", "convert_transactions").or_current();
367                        let _entered = span.enter();
368                        loop {
369                            let chunk = iter
370                                .by_ref()
371                                .take(batch_size)
372                                .collect::<Vec<_>>();
373                            if chunk.is_empty() {
374                                break;
375                            }
376
377                            batch_size = batch_size.saturating_mul(2);
378
379                            let chunk = chunk
380                                .into_par_iter()
381                                .map(|(i, tx)| {
382                                    let idx = i + prefetch;
383                                    let _parent = span.enter();
384                                    let _span = trace_span!(target: "engine::tree::payload_processor", "convert_transaction", idx).entered();
385                                    let tx = convert.convert(tx).map(WithTxEnv::new);
386                                    (idx, tx)
387                                })
388                                .collect::<Vec<_>>();
389
390                            for (idx, tx) in chunk {
391                                let failed = tx.is_err();
392                                if let (Some(prewarm_tx), Ok(tx)) = (&prewarm_tx, &tx) {
393                                    let _ = prewarm_tx.send((idx, tx.clone()));
394                                }
395                                if execute_tx.send((idx, tx)).is_err() || failed {
396                                    return
397                                }
398                                trace!(target: "engine::tree::payload_processor", idx, "yielded transaction");
399                            }
400                        }
401                    });
402                }
403            });
404        }
405
406        (prewarm_rx, execute_rx)
407    }
408
409    /// Spawn prewarming optionally wired to the sparse trie task for target updates.
410    ///
411    /// `parallel_bal_execution` is true when the BAL execute path will execute this block. In
412    /// that case prewarm runs in BAL mode: it streams BAL-derived sparse-trie updates and,
413    /// unless `disable_bal_batch_io` is set, prefetches BAL-declared state into the shared cache.
414    #[instrument(level = "debug", target = "engine::tree::payload_processor", skip_all)]
415    fn spawn_caching_with<P>(
416        &self,
417        env: ExecutionEnv<Evm>,
418        transactions: Option<
419            mpsc::Receiver<(usize, impl ExecutableTxFor<Evm> + Clone + Send + Sync + 'static)>,
420        >,
421        state_provider_factory: OverlayStateProviderFactory<P, Evm::Primitives>,
422        hint_stream: Option<StateRootHintStream>,
423        hashed_update_stream: Option<StateRootUpdateStream>,
424        parallel_bal_execution: bool,
425    ) -> CacheTaskHandle<<Evm::Primitives as NodePrimitives>::Receipt, EvmTypesFor<Evm>>
426    where
427        P: DatabaseProviderFactory + Clone + 'static,
428        P::Provider: BlockNumReader
429            + PruneCheckpointReader
430            + StageCheckpointReader
431            + ChangeSetReader
432            + StorageChangeSetReader
433            + StorageSettingsCache
434            + HistoryReader
435            + 'static,
436    {
437        // Each mode carries the capability its producers use; the rest is dropped here, so
438        // unused capabilities do not keep the state-root task's update channel open.
439        let mode = if parallel_bal_execution {
440            PrewarmMode::BlockAccessList {
441                bal: env.decoded_bal.clone().expect("BAL dispatch implies decoded BAL"),
442                updates: hashed_update_stream,
443            }
444        } else if let Some(pending) = transactions {
445            PrewarmMode::Transactions { pending, hints: hint_stream }
446        } else {
447            PrewarmMode::Skipped
448        };
449        let saved_cache =
450            self.disable_state_cache.not().then(|| self.cache_for(env.parent_hash)).flatten();
451
452        // Reused results replace whole transaction executions, which is only equivalent for
453        // configurations that opt in, without block access lists and EIP-8037 multidimensional
454        // block gas.
455        let prewarm_results = (self.reuse_prewarm_results &&
456            matches!(mode, PrewarmMode::Transactions { .. }) &&
457            env.decoded_bal.is_none() &&
458            cfg_reuses_prewarm_results(env.evm_env.version()) &&
459            self.evm_config.reuses_prewarm_results())
460        .then(|| Arc::new(PrewarmResults::new(env.transaction_count)));
461
462        let executed_tx_index = Arc::new(AtomicUsize::new(0));
463        // configure prewarming
464        let prewarm_ctx = PrewarmContext {
465            env,
466            evm_config: self.evm_config.clone(),
467            saved_cache: saved_cache.clone(),
468            provider: state_provider_factory,
469            bal_prewarm_pool: parallel_bal_execution.then(|| self.bal_prewarm_pool()),
470            metrics: PrewarmMetrics::default(),
471            cache_metrics: self.cache_metrics.clone(),
472            cache_state_metrics: self.cache_state_metrics.clone(),
473            terminate_execution: Arc::new(AtomicBool::new(false)),
474            executed_tx_index: Arc::clone(&executed_tx_index),
475            precompile_cache_disabled: self.precompile_cache_disabled,
476            precompile_cache_map: self.precompile_cache_map.clone(),
477            disable_bal_parallel_state_root: self.disable_bal_parallel_state_root,
478            disable_bal_batch_io: self.disable_bal_batch_io,
479            prewarm_results: prewarm_results.clone(),
480        };
481
482        let (prewarm_task, to_prewarm_task) =
483            PrewarmCacheTask::new(self.executor.clone(), self.execution_cache.clone(), prewarm_ctx);
484        {
485            let to_prewarm_task = to_prewarm_task.clone();
486            self.executor.spawn_blocking_named("prewarm", move || {
487                prewarm_task.run(mode, to_prewarm_task);
488            });
489        }
490
491        CacheTaskHandle {
492            saved_cache,
493            to_prewarm_task: Some(to_prewarm_task),
494            executed_tx_index,
495            prewarm_results,
496            cache_metrics: self.cache_metrics.clone(),
497        }
498    }
499
500    /// Returns the cache for the given parent hash, creating one if none is stored yet.
501    ///
502    /// Returns `None` while the stored cache is still held by another task, such as a prewarm
503    /// task queued behind earlier blocks. A new cache is not created then: saving it would free
504    /// the stored cache on the prewarm thread, which slows saves enough that a prewarm backlog
505    /// keeps growing while payloads arrive back to back.
506    #[instrument(level = "debug", target = "engine::caching", skip(self))]
507    pub fn cache_for(&self, parent_hash: B256) -> Option<SavedCache> {
508        match self.execution_cache.checkout(parent_hash) {
509            CacheCheckout::Available(cache) => {
510                debug!("reusing execution cache");
511                Some(cache)
512            }
513            CacheCheckout::InUse { cached_hash } => {
514                warn!(%cached_hash, "Execution cache still in use, executing without it");
515                None
516            }
517            CacheCheckout::Empty => {
518                debug!("creating new execution cache");
519                let start = Instant::now();
520                let cache = ExecutionCache::new(self.cross_block_cache_size);
521                if let Some(metrics) = &self.cache_metrics {
522                    metrics.record_cache_creation(start.elapsed());
523                }
524                Some(SavedCache::new(parent_hash, cache))
525            }
526        }
527    }
528
529    /// Updates the execution cache with the post-execution state from an inserted block.
530    ///
531    /// This is used when blocks are inserted directly (e.g., locally built blocks by sequencers)
532    /// to ensure the cache remains warm for subsequent block execution.
533    ///
534    /// The cache enables subsequent blocks to reuse account, storage, and bytecode data without
535    /// hitting the database, maintaining performance consistency.
536    pub fn on_inserted_executed_block(
537        &self,
538        block_with_parent: BlockWithParent,
539        bundle_state: &BundleState,
540    ) {
541        let cache_state_metrics = self.cache_state_metrics.clone();
542        self.execution_cache.update_with_guard(|cached| {
543            if cached.as_ref().is_some_and(|c| c.executed_block_hash() != block_with_parent.parent) {
544                debug!(
545                    target: "engine::caching",
546                    parent_hash = %block_with_parent.parent,
547                    "Cannot find cache for parent hash, skip updating cache with new state for inserted executed block",
548                );
549                return
550            }
551
552            if let Some(cache) = cached.as_ref().filter(|cache| !cache.is_available()) {
553                debug!(
554                    target: "engine::caching",
555                    parent_hash = %block_with_parent.parent,
556                    usage_count = cache.usage_count(),
557                    "Execution cache is in use, skip updating cache with new state for inserted executed block",
558                );
559                return
560            }
561
562            // Take existing cache (if any) or create fresh caches
563            let caches = match cached.take() {
564                Some(existing) => existing.cache().clone(),
565                None => ExecutionCache::new(self.cross_block_cache_size),
566            };
567
568            // Insert the block's bundle state into cache
569            let new_cache = SavedCache::new(block_with_parent.block.hash, caches);
570            if new_cache.cache().insert_state(bundle_state).is_err() {
571                *cached = None;
572                debug!(target: "engine::caching", "cleared execution cache on update error");
573                return
574            }
575            new_cache.update_metrics(cache_state_metrics.as_ref());
576
577            // Replace with the updated cache
578            *cached = Some(new_cache);
579            debug!(target: "engine::caching", ?block_with_parent, "Updated execution cache for inserted block");
580        });
581    }
582}
583
584/// Converts transactions sequentially and sends them to the execute channel, and to the prewarm
585/// channel if there is one. Returns false on conversion failure or disconnection.
586fn convert_serial<RawTx, Tx, TxEnv, InnerTx, Recovered, Err, C>(
587    iter: impl Iterator<Item = RawTx>,
588    convert: &C,
589    prewarm_tx: Option<&mpsc::SyncSender<(usize, WithTxEnv<TxEnv, Recovered>)>>,
590    execute_tx: &ExecuteTxSender<TxEnv, Recovered, Err>,
591) -> bool
592where
593    Tx: ExecutableTxParts<TxEnv, InnerTx, Recovered = Recovered>,
594    TxEnv: Clone,
595    C: ConvertTx<RawTx, Tx = Tx, Error = Err>,
596{
597    for (idx, raw_tx) in iter.enumerate() {
598        let _span =
599            trace_span!(target: "engine::tree::payload_processor", "convert_transaction", idx)
600                .entered();
601        let tx = convert.convert(raw_tx);
602        let failed = tx.is_err();
603        let tx = tx.map(WithTxEnv::new);
604        if let (Some(prewarm_tx), Ok(tx)) = (prewarm_tx, &tx) {
605            let _ = prewarm_tx.send((idx, tx.clone()));
606        }
607        if execute_tx.send((idx, tx)).is_err() || failed {
608            return false
609        }
610        trace!(target: "engine::tree::payload_processor", idx, "yielded transaction");
611    }
612    true
613}
614
615/// Handle to all the spawned tasks.
616///
617/// Generic over `R` (receipt type) to allow sharing `Arc<ExecutionOutcome<R>>` with the
618/// caching task without cloning the expensive `BundleState`, and over `H` (EVM type family) of the
619/// prewarm results that execution may reuse.
620#[derive_where::derive_where(Debug; Tx, Err, R)]
621pub struct PayloadHandle<Tx, Err, R, H: evm2::EvmTypes> {
622    prewarm_handle: CacheTaskHandle<R, H>,
623    /// Stream of block transactions and their indices in the block.
624    transactions: IndexedTxReceiver<Tx, Err>,
625    /// Span for tracing
626    _span: Span,
627}
628
629impl<Tx, Err, R: Send + Sync + 'static, H: evm2::EvmTypes> PayloadHandle<Tx, Err, R, H> {
630    /// Returns a clone of the caches used by prewarming
631    pub fn caches(&self) -> Option<ExecutionCache> {
632        self.prewarm_handle.saved_cache.as_ref().map(|cache| cache.cache().clone())
633    }
634
635    /// Returns engine cache metrics if a cache exists for prewarming.
636    pub fn cache_metrics(&self) -> Option<CachedStateMetrics> {
637        self.prewarm_handle.cache_metrics.clone()
638    }
639
640    /// Returns a reference to the shared executed transaction index counter.
641    ///
642    /// The main execution loop should store `index + 1` after executing each transaction so that
643    /// prewarm workers can skip transactions that have already been processed.
644    pub const fn executed_tx_index(&self) -> &Arc<AtomicUsize> {
645        &self.prewarm_handle.executed_tx_index
646    }
647
648    /// Returns the transaction prewarming results that execution may reuse, if enabled.
649    pub(crate) fn prewarm_results(&self) -> Option<Arc<PrewarmResults<H>>> {
650        self.prewarm_handle.prewarm_results.clone()
651    }
652
653    /// Terminates the pre-warming transaction processing.
654    ///
655    /// Note: This does not terminate the task yet.
656    pub fn stop_prewarming_execution(&self) {
657        self.prewarm_handle.stop_prewarming_execution()
658    }
659
660    /// Terminates the entire caching task.
661    ///
662    /// If the [`BlockExecutionOutput`] is provided it will update the shared cache using its
663    /// bundle state. Using `Arc<ExecutionOutcome>` allows sharing with the main execution
664    /// path without cloning the expensive `BundleState`.
665    ///
666    /// Returns a sender for the channel that should be notified on block validation success.
667    pub fn terminate_caching(
668        &mut self,
669        execution_outcome: Option<Arc<BlockExecutionOutput<R>>>,
670    ) -> Option<mpsc::Sender<()>> {
671        self.prewarm_handle.terminate_caching(execution_outcome)
672    }
673
674    /// Returns iterator yielding transactions from the stream.
675    pub fn iter_transactions(&mut self) -> impl Iterator<Item = Result<Tx, Err>> + '_ {
676        self.transactions.iter().map(|(_, tx)| tx)
677    }
678
679    /// Returns a clone of the indexed transaction receiver.
680    pub fn clone_transaction_receiver(&self) -> IndexedTxReceiver<Tx, Err> {
681        self.transactions.clone()
682    }
683}
684
685/// Access to the spawned [`PrewarmCacheTask`].
686///
687/// Generic over `R` (receipt type) to allow sharing `Arc<ExecutionOutcome<R>>` with the
688/// prewarm task without cloning the expensive `BundleState`, and over `H` (EVM type family) of the
689/// prewarm results that execution may reuse.
690#[derive_where::derive_where(Debug; R)]
691pub struct CacheTaskHandle<R, H: evm2::EvmTypes> {
692    /// The shared cache the task operates with.
693    saved_cache: Option<SavedCache>,
694    /// Channel to the spawned prewarm task if any
695    to_prewarm_task: Option<mpsc::Sender<PrewarmTaskEvent<R>>>,
696    /// Shared counter tracking the next transaction index to be executed by the main execution
697    /// loop. Prewarm workers skip transactions below this index.
698    executed_tx_index: Arc<AtomicUsize>,
699    /// Transaction prewarming results that execution may reuse.
700    prewarm_results: Option<Arc<PrewarmResults<H>>>,
701    /// Metrics for the execution cache.
702    cache_metrics: Option<CachedStateMetrics>,
703}
704
705impl<R: Send + Sync + 'static, H: evm2::EvmTypes> CacheTaskHandle<R, H> {
706    /// Terminates the pre-warming transaction processing.
707    ///
708    /// Note: This does not terminate the task yet.
709    pub fn stop_prewarming_execution(&self) {
710        self.to_prewarm_task
711            .as_ref()
712            .map(|tx| tx.send(PrewarmTaskEvent::TerminateTransactionExecution).ok());
713    }
714
715    /// Terminates the entire pre-warming task.
716    ///
717    /// If the [`BlockExecutionOutput`] is provided it will update the shared cache using its
718    /// bundle state. Using `Arc<ExecutionOutcome>` avoids cloning the expensive `BundleState`.
719    #[must_use = "sender must be used and notified on block validation success"]
720    pub fn terminate_caching(
721        &mut self,
722        execution_outcome: Option<Arc<BlockExecutionOutput<R>>>,
723    ) -> Option<mpsc::Sender<()>> {
724        self.to_prewarm_task.take().map(|tx| {
725            let (valid_block_tx, valid_block_rx) = mpsc::channel();
726            let event = PrewarmTaskEvent::Terminate { execution_outcome, valid_block_rx };
727            let _ = tx.send(event);
728
729            valid_block_tx
730        })
731    }
732}
733
734impl<R, H: evm2::EvmTypes> Drop for CacheTaskHandle<R, H> {
735    fn drop(&mut self) {
736        // Ensure we always terminate on drop - send None without needing Send + Sync bounds
737        if let Some(tx) = self.to_prewarm_task.take() {
738            let _ = tx.send(PrewarmTaskEvent::Terminate {
739                execution_outcome: None,
740                valid_block_rx: mpsc::channel().1,
741            });
742        }
743    }
744}
745
746#[cfg(test)]
747mod tests {
748    use super::*;
749    use crate::tree::{
750        payload_processor::PayloadProcessor, ExecutionCache, PayloadExecutionCache, SavedCache,
751        TreeConfig,
752    };
753    use alloy_consensus::constants::KECCAK_EMPTY;
754    use alloy_eips::eip1898::{BlockNumHash, BlockWithParent};
755    use alloy_primitives::{Address, B256, U256};
756    use evm2::evm::AccountInfo;
757    use proptest::{
758        prelude::any,
759        test_runner::{Config, TestRunner},
760    };
761    use reth_chainspec::ChainSpec;
762    use reth_concurrency::sync::{channel::RecvTimeoutError, Mutex};
763    use reth_evm_ethereum::EthEvmConfig;
764    use reth_execution_cache::CachedStatus;
765    use reth_trie_common::bundle_state::BundleState;
766    use std::{
767        collections::HashSet,
768        process::Command,
769        sync::{atomic::Ordering, Arc},
770    };
771    use tracing_subscriber::{
772        filter::LevelFilter, layer::SubscriberExt, registry::LookupSpan, Registry,
773    };
774
775    type TestTx = reth_evm::execute::WithTxEnv<
776        reth_evm::TxEnvFor<EthEvmConfig>,
777        reth_primitives_traits::Recovered<reth_ethereum_primitives::TransactionSigned>,
778    >;
779
780    fn converted_tx() -> TestTx {
781        TestTx::new(reth_primitives_traits::Recovered::new_unchecked(
782            reth_ethereum_primitives::TransactionSigned::Legacy(
783                alloy_consensus::Signed::new_unchecked(
784                    alloy_consensus::TxLegacy::default(),
785                    alloy_primitives::Signature::test_signature(),
786                    B256::ZERO,
787                ),
788            ),
789            Address::ZERO,
790        ))
791    }
792
793    fn test_processor() -> PayloadProcessor<EthEvmConfig> {
794        PayloadProcessor::new(
795            reth_tasks::Runtime::test(),
796            EthEvmConfig::new(Arc::new(ChainSpec::default())),
797            &TreeConfig::default(),
798            PrecompileCacheMap::default(),
799        )
800    }
801
802    #[reth_concurrency::test]
803    fn transaction_conversion_preserves_results() {
804        for (count, bal) in [(10, false), (200, false), (200, true)] {
805            let processor = test_processor();
806            let (prewarm, receiver) = processor.spawn_tx_iterator(
807                ((0..count).collect::<Vec<_>>(), |_| Ok::<_, std::io::Error>(converted_tx())),
808                count,
809                bal,
810                true,
811            );
812            let mut indices = Vec::new();
813            for _ in 0..count {
814                let (idx, tx) = receiver.recv_timeout(std::time::Duration::from_secs(10)).unwrap();
815                assert!(tx.is_ok());
816                indices.push(idx);
817            }
818            if bal {
819                indices.sort_unstable();
820            }
821            assert_eq!(indices, (0..count).collect::<Vec<_>>());
822            assert_eq!(prewarm.unwrap().iter().count(), count);
823        }
824    }
825
826    #[reth_concurrency::test]
827    fn transaction_conversion_stops_on_error() {
828        for (count, bal, fail_at) in
829            [(10, false, 0), (10, true, 0), (200, false, 0), (200, false, 4), (200, false, 20)]
830        {
831            let processor = test_processor();
832            let (_, receiver) = processor.spawn_tx_iterator(
833                ((0..count).collect::<Vec<_>>(), move |idx| {
834                    if idx >= fail_at {
835                        Err(std::io::Error::other("invalid transaction"))
836                    } else {
837                        Ok(converted_tx())
838                    }
839                }),
840                count,
841                bal,
842                false,
843            );
844            let mut results = Vec::new();
845            loop {
846                match receiver.recv_timeout(std::time::Duration::from_secs(10)) {
847                    Ok(tx) => results.push(tx),
848                    Err(RecvTimeoutError::Disconnected) => break,
849                    Err(err) => panic!("conversion did not terminate: {err}"),
850                }
851            }
852            assert!(results.iter().any(|(_, tx)| tx.is_err()));
853            assert!(results.len() < count);
854            if !bal {
855                assert_eq!(results.len(), fail_at + 1);
856                assert!(results.last().unwrap().1.is_err());
857            }
858        }
859    }
860
861    #[reth_concurrency::test]
862    fn bal_transaction_conversion_preserves_all_error_slots() {
863        let count = 200;
864        let processor = test_processor();
865        let (_, receiver) = processor.spawn_tx_iterator(
866            ((0..count).collect::<Vec<_>>(), |idx| {
867                if idx % 3 == 0 {
868                    Err(std::io::Error::other("invalid transaction"))
869                } else {
870                    Ok(converted_tx())
871                }
872            }),
873            count,
874            true,
875            false,
876        );
877        let mut indices = Vec::new();
878        for _ in 0..count {
879            let (idx, tx) = receiver.recv_timeout(std::time::Duration::from_secs(10)).unwrap();
880            assert_eq!(tx.is_err(), idx % 3 == 0);
881            indices.push(idx);
882        }
883        indices.sort_unstable();
884        assert_eq!(indices, (0..count).collect::<Vec<_>>());
885    }
886
887    #[reth_concurrency::test]
888    fn dropping_payload_handle_stops_transaction_conversion() {
889        for (count, bal, pause_at) in
890            [(10, false, 0), (1000, false, 0), (1000, false, 4), (1000, true, 0)]
891        {
892            let processor = test_processor();
893            let calls = Arc::new(super::AtomicUsize::new(0));
894            let converted = calls.clone();
895            let (started_tx, started_rx) = channel::unbounded();
896            let (release_tx, release_rx) = channel::bounded::<()>(0);
897            let (_, receiver) = processor.spawn_tx_iterator(
898                ((0..count).collect::<Vec<_>>(), move |idx| {
899                    converted.fetch_add(1, Ordering::Relaxed);
900                    if idx >= pause_at {
901                        started_tx.send(()).unwrap();
902                        let _ = release_rx.recv_timeout(std::time::Duration::from_secs(10));
903                    }
904                    Ok::<_, std::io::Error>(converted_tx())
905                }),
906                count,
907                bal,
908                false,
909            );
910            let handle = super::PayloadHandle {
911                prewarm_handle: super::CacheTaskHandle::<(), evm2::BaseEvmTypes> {
912                    saved_cache: None,
913                    to_prewarm_task: None,
914                    executed_tx_index: Default::default(),
915                    prewarm_results: None,
916                    cache_metrics: None,
917                },
918                transactions: receiver,
919                _span: tracing::Span::none(),
920            };
921            started_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap();
922            drop(handle);
923            drop(release_tx);
924
925            // The converter owns the last sender, so disconnection confirms recovery exited.
926            loop {
927                match started_rx.recv_timeout(std::time::Duration::from_secs(10)) {
928                    Ok(()) => {}
929                    Err(RecvTimeoutError::Disconnected) => break,
930                    Err(err) => panic!("conversion did not terminate: {err}"),
931                }
932            }
933            assert!(calls.load(Ordering::Relaxed) < count);
934        }
935    }
936
937    fn make_saved_cache(hash: B256) -> SavedCache {
938        let execution_cache = ExecutionCache::new(1_000);
939        SavedCache::new(hash, execution_cache)
940    }
941
942    #[reth_concurrency::test]
943    fn execution_cache_allows_single_checkout() {
944        let execution_cache = PayloadExecutionCache::default();
945        let hash = B256::repeat_byte(1u8);
946
947        execution_cache.update_with_guard(|slot| *slot = Some(make_saved_cache(hash)));
948
949        let first = execution_cache.get_cache_for(hash);
950        assert!(first.is_some(), "expected initial checkout to succeed");
951
952        let second = execution_cache.get_cache_for(hash);
953        assert!(second.is_none(), "second checkout should be blocked while guard is active");
954
955        drop(first);
956
957        let third = execution_cache.get_cache_for(hash);
958        assert!(third.is_some(), "third checkout should succeed after guard is dropped");
959    }
960
961    #[reth_concurrency::test]
962    fn execution_cache_checkout_releases_on_drop() {
963        let execution_cache = PayloadExecutionCache::default();
964        let hash = B256::repeat_byte(2u8);
965
966        execution_cache.update_with_guard(|slot| *slot = Some(make_saved_cache(hash)));
967
968        {
969            let guard = execution_cache.get_cache_for(hash);
970            assert!(guard.is_some(), "expected checkout to succeed");
971            // Guard dropped at end of scope
972        }
973
974        let retry = execution_cache.get_cache_for(hash);
975        assert!(retry.is_some(), "checkout should succeed after guard drop");
976    }
977
978    #[reth_concurrency::test]
979    fn execution_cache_mismatch_parent_clears_and_returns() {
980        let execution_cache = PayloadExecutionCache::default();
981        let hash = B256::repeat_byte(3u8);
982
983        execution_cache.update_with_guard(|slot| *slot = Some(make_saved_cache(hash)));
984
985        // When the parent hash doesn't match (fork block), the cache is cleared,
986        // hash updated on the original, and clone returned for reuse
987        let different_hash = B256::repeat_byte(4u8);
988        let cache = execution_cache.get_cache_for(different_hash);
989        assert!(cache.is_some(), "cache should be returned for reuse after clearing");
990
991        drop(cache);
992
993        // The stored cache now has the fork block's parent hash.
994        // Canonical chain looking for original hash sees a mismatch → clears and reuses.
995        let original = execution_cache.get_cache_for(hash);
996        assert!(original.is_some(), "canonical chain gets cache back via mismatch+clear");
997    }
998
999    #[reth_concurrency::test]
1000    fn execution_cache_update_after_release_succeeds() {
1001        let execution_cache = PayloadExecutionCache::default();
1002        let initial = B256::repeat_byte(5u8);
1003
1004        execution_cache.update_with_guard(|slot| *slot = Some(make_saved_cache(initial)));
1005
1006        let guard =
1007            execution_cache.get_cache_for(initial).expect("expected initial checkout to succeed");
1008
1009        drop(guard);
1010
1011        let updated = B256::repeat_byte(6u8);
1012        execution_cache.update_with_guard(|slot| *slot = Some(make_saved_cache(updated)));
1013
1014        let new_checkout = execution_cache.get_cache_for(updated);
1015        assert!(new_checkout.is_some(), "new checkout should succeed after release and update");
1016    }
1017
1018    #[reth_concurrency::test]
1019    fn on_inserted_executed_block_populates_cache() {
1020        let payload_processor = PayloadProcessor::new(
1021            reth_tasks::Runtime::test(),
1022            EthEvmConfig::new(Arc::new(ChainSpec::default())),
1023            &TreeConfig::default(),
1024            PrecompileCacheMap::default(),
1025        );
1026
1027        let parent_hash = B256::repeat_byte(1u8);
1028        let block_hash = B256::repeat_byte(10u8);
1029        let block_with_parent = BlockWithParent {
1030            block: BlockNumHash { hash: block_hash, number: 1 },
1031            parent: parent_hash,
1032        };
1033        let bundle_state = BundleState::default();
1034
1035        // Cache should be empty initially
1036        assert!(payload_processor.execution_cache.get_cache_for(block_hash).is_none());
1037
1038        // Update cache with inserted block
1039        payload_processor.on_inserted_executed_block(block_with_parent, &bundle_state);
1040
1041        // Cache should now exist for the block hash
1042        let cached = payload_processor.execution_cache.get_cache_for(block_hash);
1043        assert!(cached.is_some());
1044        assert_eq!(cached.unwrap().executed_block_hash(), block_hash);
1045    }
1046
1047    #[reth_concurrency::test]
1048    fn cache_for_executes_without_cache_while_stored_cache_is_in_use() {
1049        let payload_processor = PayloadProcessor::new(
1050            reth_tasks::Runtime::test(),
1051            EthEvmConfig::new(Arc::new(ChainSpec::default())),
1052            &TreeConfig::default(),
1053            PrecompileCacheMap::default(),
1054        );
1055        let hash = B256::repeat_byte(1u8);
1056        let next = B256::repeat_byte(2u8);
1057        assert!(payload_processor.cache_for(hash).is_some(), "empty slot creates a cache");
1058
1059        payload_processor
1060            .execution_cache
1061            .update_with_guard(|slot| *slot = Some(make_saved_cache(hash)));
1062        let held = payload_processor.cache_for(hash).expect("stored cache is available");
1063        assert!(payload_processor.cache_for(next).is_none(), "held cache is not replaced");
1064
1065        drop(held);
1066        assert_eq!(
1067            payload_processor.cache_for(next).map(|cache| cache.executed_block_hash()),
1068            Some(next)
1069        );
1070    }
1071
1072    #[reth_concurrency::test]
1073    fn on_inserted_executed_block_skips_on_parent_mismatch() {
1074        let payload_processor = PayloadProcessor::new(
1075            reth_tasks::Runtime::test(),
1076            EthEvmConfig::new(Arc::new(ChainSpec::default())),
1077            &TreeConfig::default(),
1078            PrecompileCacheMap::default(),
1079        );
1080
1081        // Setup: populate cache with block 1
1082        let block1_hash = B256::repeat_byte(1u8);
1083        payload_processor
1084            .execution_cache
1085            .update_with_guard(|slot| *slot = Some(make_saved_cache(block1_hash)));
1086
1087        // Try to insert block 3 with wrong parent (should skip and keep block 1's cache)
1088        let wrong_parent = B256::repeat_byte(99u8);
1089        let block3_hash = B256::repeat_byte(3u8);
1090        let block_with_parent = BlockWithParent {
1091            block: BlockNumHash { hash: block3_hash, number: 3 },
1092            parent: wrong_parent,
1093        };
1094        let bundle_state = BundleState::default();
1095
1096        payload_processor.on_inserted_executed_block(block_with_parent, &bundle_state);
1097
1098        // Cache should still be for block 1 (unchanged)
1099        let cached = payload_processor.execution_cache.get_cache_for(block1_hash);
1100        assert!(cached.is_some(), "Original cache should be preserved");
1101
1102        // Cache for block 3 should not exist
1103        let cached3 = payload_processor.execution_cache.get_cache_for(block3_hash);
1104        assert!(cached3.is_none(), "New block cache should not be created on mismatch");
1105    }
1106
1107    #[reth_concurrency::test]
1108    fn on_inserted_executed_block_does_not_mutate_checked_out_parent_cache() {
1109        let payload_processor = PayloadProcessor::new(
1110            reth_tasks::Runtime::test(),
1111            EthEvmConfig::new(Arc::new(ChainSpec::default())),
1112            &TreeConfig::default(),
1113            PrecompileCacheMap::default(),
1114        );
1115
1116        let parent_hash = B256::repeat_byte(1u8);
1117        payload_processor
1118            .execution_cache
1119            .update_with_guard(|slot| *slot = Some(make_saved_cache(parent_hash)));
1120
1121        // Checking out the cache bumps its `ExecutionCache` refcount, marking the slot as in-use.
1122        // The returned SavedCache shares the same underlying ExecutionCache Arc as the slot,
1123        // so any writes through the slot are observable here
1124        let checked_out = payload_processor
1125            .execution_cache
1126            .get_cache_for(parent_hash)
1127            .expect("expected parent cache checkout to succeed");
1128
1129        let polluted_address = Address::random();
1130        let bundle_state = BundleState::builder(2..=2)
1131            .state_present_account_info(
1132                polluted_address,
1133                AccountInfo {
1134                    balance: U256::from(1337),
1135                    nonce: 7,
1136                    code_hash: KECCAK_EMPTY,
1137                    code: None,
1138                    ..Default::default()
1139                },
1140            )
1141            .build();
1142
1143        // Make parent match the cached slot so we bypass the parent-mismatch guard and exercise
1144        // the in-use guard specifically.
1145        let block_with_parent = BlockWithParent {
1146            block: BlockNumHash { hash: B256::repeat_byte(2u8), number: 2 },
1147            parent: parent_hash,
1148        };
1149
1150        payload_processor.on_inserted_executed_block(block_with_parent, &bundle_state);
1151
1152        // The closure runs only on a cache miss, so NotCached(None) means polluted_address was
1153        // absent and Cached(Some(_)) means it was written by on_inserted_executed_block.
1154        let account = checked_out
1155            .cache()
1156            .get_or_try_insert_account_with(polluted_address, || Ok::<_, ()>(None))
1157            .expect("cache read should succeed");
1158
1159        assert_eq!(
1160            account,
1161            CachedStatus::NotCached(None),
1162            "checked-out parent cache should not observe state from inserted local block"
1163        );
1164    }
1165
1166    /// Tests the full prewarm lifecycle for a fork block:
1167    ///
1168    /// 1. Cache is at canonical block 4.
1169    /// 2. Fork block (parent = block 2) checks out the cache via `get_cache_for`, simulating what
1170    ///    `PrewarmCacheTask` does when it receives a `SavedCache`.
1171    /// 3. Prewarm populates the shared cache with fork-specific state.
1172    /// 4. While the prewarm clone is alive, the cache is unavailable (`usage_count` > 1).
1173    /// 5. Prewarm drops without calling `save_cache` (fork block was invalid).
1174    /// 6. Canonical block 5 (parent = block 4) must get a cache with correct hash and no stale fork
1175    ///    data.
1176    #[reth_concurrency::test]
1177    fn fork_prewarm_dropped_without_save_does_not_corrupt_cache() {
1178        let execution_cache = PayloadExecutionCache::default();
1179
1180        // Canonical chain at block 4.
1181        let block4_hash = B256::repeat_byte(4u8);
1182        execution_cache.update_with_guard(|slot| *slot = Some(make_saved_cache(block4_hash)));
1183
1184        // Fork block arrives with parent = block 2. Prewarm task checks out the cache.
1185        // This simulates PrewarmCacheTask receiving a SavedCache clone from get_cache_for.
1186        let fork_parent = B256::repeat_byte(2u8);
1187        let prewarm_cache = execution_cache.get_cache_for(fork_parent);
1188        assert!(prewarm_cache.is_some(), "prewarm should obtain cache for fork block");
1189        let prewarm_cache = prewarm_cache.unwrap();
1190        assert_eq!(prewarm_cache.executed_block_hash(), fork_parent);
1191
1192        // Prewarm populates cache with fork-specific state (ancestor data for block 2).
1193        // Since ExecutionCache uses Arc<Inner>, this data is shared with the stored original.
1194        let fork_addr = Address::repeat_byte(0xBB);
1195        let fork_key = B256::repeat_byte(0xCC);
1196        prewarm_cache.cache().insert_storage(fork_addr, fork_key, Some(U256::from(999)));
1197
1198        // While prewarm holds the clone, the cache handle count > 1 so the cache is in use.
1199        let during_prewarm = execution_cache.get_cache_for(block4_hash);
1200        assert!(
1201            during_prewarm.is_none(),
1202            "cache must be unavailable while prewarm holds a reference"
1203        );
1204
1205        // Fork block fails — prewarm task drops without calling save_cache/update_with_guard.
1206        drop(prewarm_cache);
1207
1208        // Canonical block 5 arrives (parent = block 4).
1209        // Stored hash = fork_parent (our fix), so get_cache_for sees a mismatch,
1210        // clears the stale fork data, and returns a cache with hash = block4_hash.
1211        let block5_cache = execution_cache.get_cache_for(block4_hash);
1212        assert!(
1213            block5_cache.is_some(),
1214            "canonical chain must get cache after fork prewarm is dropped"
1215        );
1216        assert_eq!(
1217            block5_cache.as_ref().unwrap().executed_block_hash(),
1218            block4_hash,
1219            "cache must carry the canonical parent hash, not the fork parent"
1220        );
1221    }
1222
1223    #[test]
1224    fn transaction_conversion_has_child_spans() {
1225        // Worker threads use the global subscriber. Isolate it from other tests and run each
1226        // filter level in a fresh process so filtered child spans also exercise context fallback.
1227        const LEVEL_ENV: &str = "RETH_TEST_CONVERSION_SPAN_LEVEL";
1228        let Ok(level) = std::env::var(LEVEL_ENV) else {
1229            for level in ["trace", "debug", "info"] {
1230                let output = Command::new(std::env::current_exe().unwrap())
1231                    .args([
1232                        "--exact",
1233                        "tree::payload_processor::tests::transaction_conversion_has_child_spans",
1234                        "--nocapture",
1235                    ])
1236                    .env(LEVEL_ENV, level)
1237                    .output()
1238                    .unwrap();
1239                assert!(
1240                    output.status.success(),
1241                    "{level}: {}\n{}",
1242                    String::from_utf8_lossy(&output.stdout),
1243                    String::from_utf8_lossy(&output.stderr),
1244                );
1245            }
1246            return;
1247        };
1248        let level = level.parse::<LevelFilter>().unwrap();
1249        tracing::subscriber::set_global_default(tracing_subscriber::registry().with(level))
1250            .unwrap();
1251        reth_concurrency::sync::Runtime::new().run(move || {
1252            let processor = test_processor();
1253
1254            // Exercise both sides of the sequential cutoff and the first parallel window, as well
1255            // as randomly sized blocks. BAL execution bypasses the sequential prefetch/windowing.
1256            for count in [0, 1, 29, 30, 68, 69] {
1257                for bal in [false, true] {
1258                    assert_conversion_spans(&processor, count, bal, level);
1259                }
1260            }
1261        });
1262        TestRunner::new(Config::with_cases(32))
1263            .run(&(0..200usize, any::<bool>()), |(count, bal)| {
1264                reth_concurrency::sync::Runtime::new().run(move || {
1265                    let processor = test_processor();
1266                    assert_conversion_spans(&processor, count, bal, level);
1267                });
1268                Ok(())
1269            })
1270            .unwrap();
1271    }
1272
1273    fn assert_conversion_spans(
1274        processor: &PayloadProcessor<EthEvmConfig>,
1275        count: usize,
1276        bal: bool,
1277        level: LevelFilter,
1278    ) {
1279        let request = tracing::info_span!(parent: None, "request");
1280        let _entered = request.enter();
1281        // Retain the spans so registry IDs cannot be recycled between conversions.
1282        let observed = Arc::new(Mutex::new(Vec::new()));
1283        let converted = observed.clone();
1284        let (_, receiver) = processor.spawn_tx_iterator(
1285            ((0..count).collect::<Vec<_>>(), move |idx| {
1286                converted.lock().unwrap().push((idx, Span::current()));
1287                Ok::<_, std::io::Error>(converted_tx())
1288            }),
1289            count,
1290            bal,
1291            false,
1292        );
1293        let mut indices = Vec::new();
1294        loop {
1295            match receiver.recv_timeout(std::time::Duration::from_secs(10)) {
1296                Ok((idx, tx)) => {
1297                    assert!(tx.is_ok());
1298                    indices.push(idx);
1299                }
1300                Err(RecvTimeoutError::Disconnected) => break,
1301                Err(err) => panic!("conversion did not terminate: {err}"),
1302            }
1303        }
1304        if bal {
1305            indices.sort_unstable();
1306        }
1307        assert_eq!(indices, (0..count).collect::<Vec<_>>());
1308        let observed = observed.lock().unwrap();
1309        assert_eq!(observed.len(), count);
1310        let mut transaction_ids = HashSet::new();
1311        for (idx, span) in observed.iter() {
1312            let scope = span
1313                .with_subscriber(|(id, dispatch)| {
1314                    dispatch
1315                        .downcast_ref::<Registry>()
1316                        .unwrap()
1317                        .span(id)
1318                        .unwrap()
1319                        .scope()
1320                        .from_root()
1321                        .map(|span| (span.id(), span.name()))
1322                        .collect::<Vec<_>>()
1323                })
1324                .expect("conversion lost its request context");
1325            assert_eq!(Some(scope[0].0.clone()), request.id());
1326            let mut expected = vec!["request"];
1327            if level >= LevelFilter::DEBUG {
1328                expected.push("spawn_tx_iterator");
1329                expected.push("tx_iterator");
1330                if count >= 30 && (bal || *idx >= 4) {
1331                    expected.push("convert_transactions");
1332                }
1333            }
1334            if level == LevelFilter::TRACE {
1335                expected.push("convert_transaction");
1336                assert!(transaction_ids.insert(span.id().unwrap()), "reused a transaction span");
1337            }
1338            assert_eq!(scope.iter().map(|(_, name)| *name).collect::<Vec<_>>(), expected);
1339        }
1340    }
1341}