Skip to main content

reth_engine_tree/tree/payload_processor/
prewarm.rs

1//! Caching and prewarming related functionality.
2//!
3//! Prewarming executes transactions in parallel before the actual block execution
4//! to populate the execution cache with state that will likely be accessed during
5//! block processing.
6//!
7//! ## How Prewarming Works
8//!
9//! 1. Incoming transactions are split into two streams: one for prewarming (executed in parallel)
10//!    and one for actual execution (executed sequentially)
11//! 2. Prewarming tasks execute transactions in parallel using shared caches
12//! 3. When actual block execution happens, it benefits from the warmed cache
13//! 4. Block execution commits prewarm results whose reads are still valid instead of executing the
14//!    transactions again
15
16use super::{
17    bal_prewarm_pool::BalPrewarmPool,
18    reuse::{BalanceTracker, PoolTx, PrewarmResults, RecordingDb, RecordingHandle, SpeculativeTx},
19    StateRootHintStream, StateRootUpdateStream,
20};
21use crate::tree::{
22    CachedStateCacheMetrics, CachedStateMetrics, CachedStateProvider, ExecutionEnv,
23    PayloadExecutionCache, SavedCache,
24};
25use alloy_consensus::transaction::TxHashRef;
26use alloy_eip7928::bal::DecodedBal;
27use alloy_eips::eip4895::Withdrawal;
28use alloy_primitives::keccak256;
29use evm2::evm::Database;
30use metrics::{Counter, Gauge, Histogram};
31use reth_concurrency::sync::{
32    atomic::{AtomicBool, AtomicUsize, Ordering},
33    channel::mpsc::{self, channel, Receiver, Sender},
34    rayon::prelude::*,
35    thread,
36    time::FastInstant as Instant,
37};
38use reth_evm::{
39    database::StateProviderDatabase, precompile_cache::PrecompileCacheMap, ConfigureEvm,
40    Evm as EvmInstance, EvmEnv, EvmEnvFor, EvmFor, EvmTypesFor, ExecutableTxFor, RecoveredTx,
41    SpecFor,
42};
43use reth_metrics::Metrics;
44use reth_primitives_traits::NodePrimitives;
45use reth_provider::{
46    BlockExecutionOutput, BlockNumReader, ChangeSetReader, DatabaseProviderFactory,
47    DatabaseProviderROFactory, EvmStateProvider, EvmStateProviderBox, HistoryReader,
48    PruneCheckpointReader, StageCheckpointReader, StateProvider, StorageChangeSetReader,
49    StorageSettingsCache,
50};
51use reth_storage_overlay::OverlayStateProviderFactory;
52use reth_tasks::{Runtime, WorkerStatefulPool};
53use reth_trie_common::MultiProofTargetsV2;
54use std::{sync::Arc, time::Duration};
55use tokio::sync::oneshot;
56use tracing::{debug, debug_span, instrument, trace, trace_span, warn, Span};
57
58/// Maximum number of consecutive rounds that execute stale prewarm results again.
59const MAX_REFRESH_ROUNDS: usize = 4;
60
61/// Number of transactions ahead of block execution that refreshing checks after block execution
62/// published actual writes.
63const REFRESH_WINDOW: usize = 64;
64
65/// How often refreshing checks whether block execution published actual writes.
66const REFRESH_POLL_INTERVAL: Duration = Duration::from_micros(50);
67
68/// Determines the prewarming mode: transaction-based, BAL-based, or skipped.
69///
70/// Each variant carries the state-root capability its producers use, so the capability dies
71/// with the workers instead of outliving them.
72#[derive(Debug)]
73pub enum PrewarmMode<Tx> {
74    /// Prewarm by executing transactions from a stream, each paired with its block index.
75    Transactions {
76        /// Stream of transactions pending prewarm execution.
77        pending: Receiver<(usize, Tx)>,
78        /// Best-effort access hints emitted by the prewarm workers.
79        hints: Option<StateRootHintStream>,
80    },
81    /// Prewarm by prefetching slots from a Block Access List.
82    BlockAccessList {
83        /// The decoded block access list.
84        bal: Arc<DecodedBal>,
85        /// Authoritative pre-hashed updates derived from the BAL.
86        updates: Option<StateRootUpdateStream>,
87    },
88    /// Transaction prewarming is skipped (e.g. small blocks where the overhead exceeds the
89    /// benefit). No workers are spawned.
90    Skipped,
91}
92
93/// A task that is responsible for caching and prewarming the cache by executing transactions
94/// individually in parallel.
95///
96/// Note: This task runs until cancelled externally.
97#[derive(Debug)]
98pub struct PrewarmCacheTask<N, P, Evm>
99where
100    N: NodePrimitives,
101    Evm: ConfigureEvm<Primitives = N>,
102{
103    /// The executor used to spawn execution tasks.
104    executor: Runtime,
105    /// Shared execution cache.
106    execution_cache: PayloadExecutionCache,
107    /// Context provided to execution tasks
108    ctx: PrewarmContext<N, P, Evm>,
109    /// Receiver for events produced by tx execution
110    actions_rx: Receiver<PrewarmTaskEvent<N::Receipt>>,
111    /// Parent span for tracing
112    parent_span: Span,
113}
114
115impl<N, P, Evm> PrewarmCacheTask<N, P, Evm>
116where
117    N: NodePrimitives,
118    P: DatabaseProviderFactory + Clone + 'static,
119    P::Provider: BlockNumReader
120        + PruneCheckpointReader
121        + StageCheckpointReader
122        + ChangeSetReader
123        + StorageChangeSetReader
124        + StorageSettingsCache
125        + HistoryReader
126        + 'static,
127    Evm: ConfigureEvm<Primitives = N> + 'static,
128{
129    /// Initializes the task with the given transactions pending execution
130    pub fn new(
131        executor: Runtime,
132        execution_cache: PayloadExecutionCache,
133        ctx: PrewarmContext<N, P, Evm>,
134    ) -> (Self, Sender<PrewarmTaskEvent<N::Receipt>>) {
135        let (actions_tx, actions_rx) = channel();
136
137        trace!(
138            target: "engine::tree::payload_processor::prewarm",
139            prewarming_threads = executor.prewarming_pool().current_num_threads(),
140            transaction_count = ctx.env.transaction_count,
141            "Initialized prewarm task"
142        );
143
144        (
145            Self { executor, execution_cache, ctx, actions_rx, parent_span: Span::current() },
146            actions_tx,
147        )
148    }
149
150    /// Streams pending transactions and executes them in parallel on the prewarming pool.
151    ///
152    /// Uses `in_place_scope` to dispatch transactions as they arrive and wait for all spawned
153    /// tasks to complete. The task-local state owner is dropped before signaling completion,
154    /// releasing cache references before cache publication. Each worker initialises its EVM via
155    /// [`get_or_init`](reth_tasks::WorkerStatefulPool::get_or_init).
156    fn spawn_txs_prewarm<Tx>(
157        &self,
158        pending: mpsc::Receiver<(usize, Tx)>,
159        actions_tx: Sender<PrewarmTaskEvent<N::Receipt>>,
160        state_root_hint_stream: Option<StateRootHintStream>,
161    ) where
162        Tx: ExecutableTxFor<Evm> + Clone + Send + Sync + 'static,
163    {
164        let ctx = self.ctx.clone();
165        let pool = Arc::clone(self.executor.prewarming_pool());
166        let span = Span::current();
167
168        self.executor.spawn_blocking_named("prewarm-txs", move || {
169            let _enter = debug_span!(
170                target: "engine::tree::payload_processor::prewarm",
171                parent: &span,
172                "prewarm_txs"
173            )
174            .entered();
175
176            let ctx = &ctx;
177
178            let mut tx_count = 0usize;
179            let state_root_hint_stream = state_root_hint_stream.as_ref();
180            // Transactions to execute again when their results become stale.
181            let mut refresh_txs = Vec::new();
182            {
183                let pool = WorkerStatefulPool::new(pool);
184                let pool = &pool;
185                pool.in_place_scope(|s| {
186                    while let Ok((index, tx)) = pending.recv() {
187                        if ctx.should_stop() {
188                            trace!(
189                                target: "engine::tree::payload_processor::prewarm",
190                                "Termination requested, stopping transaction distribution"
191                            );
192                            break;
193                        }
194
195                        // skip transactions already executed by the main loop
196                        if index < ctx.executed_tx_index.load(Ordering::Relaxed) {
197                            continue;
198                        }
199
200                        tx_count += 1;
201                        if ctx.prewarm_results.is_some() {
202                            refresh_txs.push((index, tx.clone()));
203                        }
204                        // Seed results before queueing, so that they are ready as soon as possible.
205                        let seeded = if let Some(results) = &ctx.prewarm_results &&
206                            let Some(seeds) = &ctx.env.pool_seeds
207                        {
208                            results.seed(index, tx.tx().tx_hash(), seeds)
209                        } else {
210                            None
211                        };
212                        if seeded.is_some() {
213                            ctx.metrics.seeded_transactions.increment(1);
214                        }
215                        let parent_span = Span::current();
216                        s.spawn(move |_| {
217                            let _enter = trace_span!(
218                                target: "engine::tree::payload_processor::prewarm",
219                                parent: parent_span,
220                                "prewarm_tx",
221                                i = index,
222                            )
223                            .entered();
224                            Self::transact_worker(
225                                ctx,
226                                pool,
227                                index,
228                                tx,
229                                seeded,
230                                state_root_hint_stream,
231                            );
232                        });
233                    }
234
235                    // Send withdrawal prefetch targets after all transactions dispatched
236                    if let Some(state_root_hint_stream) = state_root_hint_stream &&
237                        let Some(withdrawals) = &ctx.env.withdrawals &&
238                        !withdrawals.is_empty()
239                    {
240                        let targets = multiproof_targets_from_withdrawals(withdrawals);
241                        state_root_hint_stream.on_access_hint(targets.into());
242                    }
243                });
244
245                if let Some(results) = &ctx.prewarm_results {
246                    Self::refresh_results(ctx, pool, results, &refresh_txs);
247                }
248            }
249
250            let _ = actions_tx
251                .send(PrewarmTaskEvent::FinishedTxExecution { executed_transactions: tx_count });
252        });
253    }
254
255    /// Executes transactions again whose results became stale, because the predicted writes of
256    /// earlier transactions changed after they were executed.
257    ///
258    /// Each round checks the transactions that block execution has not reached yet, in block
259    /// order, on all pool threads. Rounds repeat while they find stale results, then wait for
260    /// block execution to publish actual writes that differ from the predicted ones, until
261    /// prewarming stops.
262    fn refresh_results<Tx>(
263        ctx: &PrewarmContext<N, P, Evm>,
264        pool: &WorkerStatefulPool,
265        results: &PrewarmResults<EvmTypesFor<Evm>>,
266        txs: &[(usize, Tx)],
267    ) where
268        Tx: ExecutableTxFor<Evm> + Clone + Send + Sync,
269    {
270        let mut rounds = 0;
271        // Rounds after block execution published writes only check the transactions it reaches
272        // soon, the others are checked in later rounds.
273        let mut window_len = usize::MAX;
274        while !ctx.should_stop() {
275            let generation = results.predicted().generation();
276            // Skip the transaction block execution is executing and the one it reaches next.
277            let next = ctx.executed_tx_index.load(Ordering::Relaxed) + 1;
278            let start = txs.partition_point(|(index, _)| *index <= next);
279            if start == txs.len() {
280                break
281            }
282            let window = &txs[start..txs.len().min(start.saturating_add(window_len))];
283            // Checking is cheap, so only stale transactions are handed to the pool.
284            let stale = window
285                .iter()
286                .filter(|(index, _)| results.needs_refresh(*index))
287                .collect::<Vec<_>>();
288            let refreshed = !stale.is_empty();
289            if refreshed {
290                let cursor = AtomicUsize::new(0);
291                pool.in_place_scope(|s| {
292                    for _ in 0..pool.current_num_threads().min(stale.len()) {
293                        s.spawn(|_| {
294                            while let Some((index, tx)) =
295                                stale.get(cursor.fetch_add(1, Ordering::Relaxed))
296                            {
297                                if ctx.should_stop() {
298                                    break
299                                }
300                                Self::transact_worker(ctx, pool, *index, tx.clone(), None, None);
301                            }
302                        });
303                    }
304                });
305            }
306
307            rounds += 1;
308            if refreshed && rounds < MAX_REFRESH_ROUNDS {
309                continue
310            }
311            rounds = 0;
312            window_len = REFRESH_WINDOW;
313            while results.predicted().generation() == generation && !ctx.should_stop() {
314                thread::sleep(REFRESH_POLL_INTERVAL);
315            }
316        }
317    }
318
319    /// Executes a single prewarm transaction on the current pool thread's EVM, or only loads the
320    /// reads of its `seeded` pool transaction result.
321    ///
322    /// Lazily initialises per-thread [`PrewarmEvmState`] via
323    /// [`get_or_init`](reth_tasks::WorkerStatefulPool::get_or_init) on first access.
324    fn transact_worker<Tx>(
325        ctx: &PrewarmContext<N, P, Evm>,
326        pool: &WorkerStatefulPool,
327        index: usize,
328        tx: Tx,
329        seeded: Option<Arc<PoolTx<EvmTypesFor<Evm>>>>,
330        state_root_hint_stream: Option<&StateRootHintStream>,
331    ) where
332        Tx: ExecutableTxFor<Evm>,
333    {
334        if ctx.should_stop() || index < ctx.executed_tx_index.load(Ordering::Relaxed) {
335            return;
336        }
337
338        pool.get_or_init(
339            || ctx.evm_for_ctx(),
340            |state| {
341                let Some(evm) = state.evm.as_mut() else { return };
342
343                let start = Instant::now();
344
345                let (tx_env, tx) = tx.into_parts();
346                let send_hints = |state: &evm2::evm::PendingState| {
347                    if index > 0 &&
348                        let Some(state_root_hint_stream) = state_root_hint_stream
349                    {
350                        let (targets, storage_targets) =
351                            MultiProofTargetsV2::from_account_changes(state.account_changes());
352                        ctx.metrics.prefetch_storage_targets.record(storage_targets as f64);
353                        state_root_hint_stream.on_access_hint(targets.into());
354                    }
355                };
356
357                if let Some(seeded) = seeded {
358                    // Block execution loads the reads to validate the result.
359                    if let Err(err) = seeded.load_reads(evm.state_db_mut()) {
360                        trace!(
361                            target: "engine::tree::payload_processor::prewarm",
362                            %err,
363                            tx_hash=%tx.tx().tx_hash(),
364                            "Failed to load reads of seeded pool transaction",
365                        );
366                    }
367                    send_hints(seeded.state());
368                    return;
369                }
370
371                let Some(results) = &ctx.prewarm_results else {
372                    let hint_stream = state_root_hint_stream.filter(|_| index > 0);
373                    let res = evm.transact_and_discard(&tx_env, |executed| {
374                        hint_stream.is_some().then(|| {
375                            MultiProofTargetsV2::from_account_changes(executed.account_changes())
376                        })
377                    });
378                    let hints = match res {
379                        Ok(hints) => hints,
380                        Err(err) => {
381                            trace!(
382                                target: "engine::tree::payload_processor::prewarm",
383                                %err,
384                                tx_hash=%tx.tx().tx_hash(),
385                                sender=%tx.signer(),
386                                "Error when executing prewarm transaction",
387                            );
388                            ctx.metrics.transaction_errors.increment(1);
389                            return;
390                        }
391                    };
392                    ctx.metrics.execution_duration.record(start.elapsed());
393                    if ctx.should_stop() {
394                        return;
395                    }
396                    if let Some(stream) = hint_stream &&
397                        let Some((targets, storage_targets)) = hints
398                    {
399                        ctx.metrics.prefetch_storage_targets.record(storage_targets as f64);
400                        stream.on_access_hint(targets.into());
401                    }
402                    ctx.metrics.total_runtime.record(start.elapsed());
403                    return;
404                };
405
406                // Prewarming disables nonce and balance checks, so a reusable result must also show
407                // that the caller would have passed them.
408                let speculative = SpeculativeTx::new(*tx.signer(), tx.tx());
409                // Clear evm2's read-through overlay so every read reaches the recording database
410                // and sees the latest prediction. The provider retains the shared warm cache.
411                drop(evm.take_state_cache());
412                state.recording.start(Some((Arc::clone(results.predicted()), index)));
413                let res = evm
414                    .transact_with_inspector(&tx_env, BalanceTracker::new(state.recording.clone()));
415                let reads = state.recording.take_reads();
416                let (mut balances, res) = match res {
417                    Ok(res) => res,
418                    Err(err) => {
419                        trace!(
420                            target: "engine::tree::payload_processor::prewarm",
421                            %err,
422                            tx_hash=%tx.tx().tx_hash(),
423                            sender=%tx.signer(),
424                            "Error when executing prewarm transaction",
425                        );
426                        ctx.metrics.transaction_errors.increment(1);
427                        if let Some(reads) = reads {
428                            results.reject(index, reads);
429                        }
430                        return;
431                    }
432                };
433                ctx.metrics.execution_duration.record(start.elapsed());
434
435                if ctx.should_stop() {
436                    return;
437                }
438
439                send_hints(&res.pending_state);
440
441                if let Some(reads) = reads &&
442                    index >= ctx.executed_tx_index.load(Ordering::Relaxed)
443                {
444                    results.store(index, res, reads, &mut balances, speculative);
445                }
446                ctx.metrics.total_runtime.record(start.elapsed());
447            },
448        );
449    }
450
451    /// Saves the warmed cache in `self.execution_cache` after prewarming completes.
452    ///
453    /// This method calls [`PayloadExecutionCache::update_with_guard`], which requires exclusive
454    /// access. It should only be called after ensuring that:
455    /// 1. All prewarming tasks have completed execution
456    /// 2. No other concurrent operations are accessing the cache
457    ///
458    /// This moves the task's `ExecutionCache` into `self.execution_cache` when the block is valid,
459    /// without retaining an extra Arc reference that would prevent reuse after unlocking.
460    /// This method is called from `run()` only after all execution tasks are complete.
461    ///
462    /// State insertion and block validation run under the mutex because the cache being updated
463    /// may also be stored in `self.execution_cache`. Removed `SavedCache` values are dropped after
464    /// unlocking, before the next prewarm task. Their contents are freed only when the last
465    /// `ExecutionCache` clone is dropped, which may happen later on another thread.
466    #[instrument(level = "debug", target = "engine::tree::payload_processor::prewarm", skip_all)]
467    fn save_cache(
468        self,
469        execution_outcome: Arc<BlockExecutionOutput<N::Receipt>>,
470        valid_block_rx: mpsc::Receiver<()>,
471    ) {
472        let start = Instant::now();
473
474        let Self {
475            execution_cache,
476            ctx: PrewarmContext { env, metrics, cache_state_metrics, saved_cache, .. },
477            ..
478        } = self;
479        let hash = env.hash;
480
481        if let Some(saved_cache) = saved_cache {
482            debug!(target: "engine::caching", parent_hash=?hash, "Updating execution cache");
483            let (previous, rejected) = execution_cache.update_with_guard(|cached| {
484                let new_cache = SavedCache::new(hash, saved_cache.into_cache());
485
486                // Update under the mutex so no checkout can observe partially updated state.
487                if new_cache.cache().insert_state(&execution_outcome.state).is_err() {
488                    debug!(target: "engine::caching", "cleared execution cache on update error");
489                    return (cached.take(), Some(new_cache));
490                }
491
492                new_cache.update_metrics(cache_state_metrics.as_ref());
493
494                // `cached` and `new_cache` can point to the same cache.
495                // insert_state has already applied this block's changes to it, so keep the mutex
496                // locked until validation succeeds or we clear `cached` on failure.
497                if valid_block_rx.recv().is_err() {
498                    debug!(target: "engine::caching", "cleared execution cache on invalid block");
499                    return (cached.take(), Some(new_cache));
500                }
501
502                let reused =
503                    cached.as_ref().is_some_and(|previous| previous.shares_cache_with(&new_cache));
504                let previous = cached.replace(new_cache);
505                if reused {
506                    // `cached` and `previous` hold the same cache. Drop the extra Arc reference
507                    // before unlocking so get_cache_for can reuse it.
508                    drop(previous);
509                    (None, None)
510                } else {
511                    // Drop the old cache after unlocking; freeing it may be expensive.
512                    (previous, None)
513                }
514            });
515
516            // Drop these SavedCache values on this worker, without a background drop queue.
517            // This frees their contents only if no other ExecutionCache clones remain.
518            // Otherwise, the thread dropping the last ExecutionCache clone frees them later.
519            // Another payload may access or allocate a cache while these drops run.
520            drop((previous, rejected));
521
522            let elapsed = start.elapsed();
523            debug!(target: "engine::caching", parent_hash=?hash, elapsed=?elapsed, "Updated execution cache");
524
525            metrics.cache_saving_duration.set(elapsed.as_secs_f64());
526        }
527    }
528
529    /// Runs BAL-based prewarming and state-root streaming inline.
530    ///
531    /// Spawns two halves concurrently on separate pools, then waits for both to complete:
532    /// 1. Hashed state streaming on the BAL streaming pool so storage updates can reach the
533    ///    state-root job before account reads finish.
534    /// 2. Storage prefetch on the prewarming pool to populate the execution cache, unless BAL batch
535    ///    I/O is disabled.
536    ///
537    /// Completion uses native Tokio in all builds and does not yield to the fuzz scheduler.
538    #[instrument(level = "debug", target = "engine::tree::payload_processor::prewarm", skip_all)]
539    fn run_bal_prewarm(
540        &self,
541        decoded_bal: Arc<DecodedBal>,
542        actions_tx: Sender<PrewarmTaskEvent<N::Receipt>>,
543        hashed_update_stream: Option<StateRootUpdateStream>,
544    ) {
545        let bal = decoded_bal.as_bal();
546        if bal.is_empty() {
547            if let Some(hashed_update_stream) = hashed_update_stream {
548                hashed_update_stream.finish();
549            }
550            let _ =
551                actions_tx.send(PrewarmTaskEvent::FinishedTxExecution { executed_transactions: 0 });
552            return;
553        }
554
555        trace!(
556            target: "engine::tree::payload_processor::prewarm",
557            accounts = bal.len(),
558            "Starting BAL prewarm"
559        );
560
561        let ctx = self.ctx.clone();
562        let parent_span = Span::current();
563        let stream_parent_span = parent_span;
564        let prefetch_bal = Arc::clone(&decoded_bal);
565        let stream_bal = Arc::clone(&decoded_bal);
566        let (stream_tx, stream_rx) = oneshot::channel();
567
568        if let Some(hashed_update_stream) = hashed_update_stream {
569            let ctx = ctx.clone();
570            let pool = Arc::clone(self.executor.bal_streaming_pool());
571            self.executor.bal_streaming_pool().spawn(move || {
572                let branch_span = debug_span!(
573                    target: "engine::tree::payload_processor::prewarm",
574                    parent: &stream_parent_span,
575                    "bal_hashed_state_stream",
576                    bal_accounts = stream_bal.as_bal().len(),
577                );
578                let parent_span = branch_span.clone();
579                let _span = branch_span.entered();
580
581                {
582                    let pool = WorkerStatefulPool::new(pool);
583                    stream_bal.as_bal().par_iter().for_each(|account_changes| {
584                        pool.get_or_init(
585                            || None,
586                            |provider| {
587                                ctx.send_bal_hashed_state(
588                                    &parent_span,
589                                    provider,
590                                    account_changes,
591                                    &hashed_update_stream,
592                                );
593                            },
594                        );
595                    });
596                }
597                hashed_update_stream.finish();
598                let _ = stream_tx.send(());
599            });
600        } else {
601            let _ = stream_tx.send(());
602        }
603
604        if let Some(saved_cache) = ctx.saved_cache &&
605            !ctx.disable_bal_batch_io &&
606            let Some(pool) = ctx.bal_prewarm_pool.as_ref()
607        {
608            // If
609            //
610            // - BAL path is enabled (and so bal_prewarm_pool is present),
611            // - dispatch_bal_batch_io is false
612            // - execution cache is not disabled
613            //
614            // we launch prewarming of the BAL accounts and declared storages (both storage_reads
615            // and storage_changes). Bytecode is loaded on demand during execution.
616            //
617            // This runs side-by-side with the parallel transaction execution reducing the time it
618            // spends blocking on the data.
619            let caches = saved_cache.cache().clone();
620            let state_provider_factory = ctx.provider.clone();
621            let build = Arc::new(move || {
622                state_provider_factory.database_provider_ro().map(|provider| {
623                    Box::new(provider.into_evm_state_provider()) as EvmStateProviderBox
624                })
625            });
626
627            pool.begin_block(build, caches, ctx.env.txpool_snapshot.clone());
628            let dispatch_start = Instant::now();
629            for account in prefetch_bal.as_bal() {
630                pool.warm_account(account.address, account.storage_slots().map(Into::into));
631            }
632            ctx.metrics.bal_slot_iteration_duration.record(dispatch_start.elapsed());
633            pool.end_block();
634        }
635
636        stream_rx
637            .blocking_recv()
638            .expect("BAL hashed-state streaming task dropped without signaling completion");
639
640        let _ = actions_tx.send(PrewarmTaskEvent::FinishedTxExecution { executed_transactions: 0 });
641    }
642
643    /// Executes the task.
644    ///
645    /// This will execute the transactions until all transactions have been processed or the task
646    /// was cancelled.
647    #[instrument(
648        parent = &self.parent_span,
649        level = "debug",
650        target = "engine::tree::payload_processor::prewarm",
651        name = "prewarm and caching",
652        skip_all
653    )]
654    pub fn run<Tx>(self, mode: PrewarmMode<Tx>, actions_tx: Sender<PrewarmTaskEvent<N::Receipt>>)
655    where
656        Tx: ExecutableTxFor<Evm> + Clone + Send + Sync + 'static,
657    {
658        // Spawn execution tasks based on mode. The state-root capabilities arrive inside the
659        // mode and move into the spawned producers, so they die with the producers instead of
660        // living for the full lifetime of this task.
661        match mode {
662            PrewarmMode::Transactions { pending, hints } => {
663                self.spawn_txs_prewarm(pending, actions_tx, hints);
664            }
665            PrewarmMode::BlockAccessList { bal, updates } => {
666                self.run_bal_prewarm(bal, actions_tx, updates);
667            }
668            PrewarmMode::Skipped => {
669                let _ = actions_tx
670                    .send(PrewarmTaskEvent::FinishedTxExecution { executed_transactions: 0 });
671            }
672        }
673
674        let mut final_execution_outcome = None;
675        let mut finished_execution = false;
676        while let Ok(event) = self.actions_rx.recv() {
677            match event {
678                PrewarmTaskEvent::TerminateTransactionExecution => {
679                    // stop tx processing
680                    debug!(target: "engine::tree::prewarm", "Terminating prewarm execution");
681                    self.ctx.stop();
682                }
683                PrewarmTaskEvent::Terminate { execution_outcome, valid_block_rx } => {
684                    trace!(target: "engine::tree::payload_processor::prewarm", "Received termination signal");
685                    // `Terminate` can arrive without `TerminateTransactionExecution` when the
686                    // handle is dropped on an execution error, so stop workers before waiting.
687                    self.ctx.stop();
688                    final_execution_outcome =
689                        Some(execution_outcome.map(|outcome| (outcome, valid_block_rx)));
690
691                    if finished_execution {
692                        // all tasks are done, we can exit, which will save caches and exit
693                        break
694                    }
695                }
696                PrewarmTaskEvent::FinishedTxExecution { executed_transactions } => {
697                    trace!(target: "engine::tree::payload_processor::prewarm", "Finished prewarm execution signal");
698                    self.ctx.metrics.transactions.set(executed_transactions as f64);
699                    self.ctx.metrics.transactions_histogram.record(executed_transactions as f64);
700
701                    finished_execution = true;
702
703                    if final_execution_outcome.is_some() {
704                        // all tasks are done, we can exit, which will save caches and exit
705                        break
706                    }
707                }
708            }
709        }
710
711        debug!(target: "engine::tree::payload_processor::prewarm", "Completed prewarm execution");
712
713        // save caches and finish using the shared ExecutionOutcome
714        if let Some(Some((execution_outcome, valid_block_rx))) = final_execution_outcome {
715            self.save_cache(execution_outcome, valid_block_rx);
716        }
717    }
718}
719
720/// Context required by tx execution tasks.
721#[derive(Debug, Clone)]
722pub struct PrewarmContext<N, P, Evm>
723where
724    N: NodePrimitives,
725    Evm: ConfigureEvm<Primitives = N>,
726{
727    /// The execution environment.
728    pub env: ExecutionEnv<Evm>,
729    /// The EVM configuration.
730    pub evm_config: Evm,
731    /// The saved cache.
732    pub saved_cache: Option<SavedCache>,
733    /// Provider to obtain the state
734    pub provider: OverlayStateProviderFactory<P, N>,
735    /// Dedicated blocking pool for warming the BAL read-set. `Some` only on the BAL parallel
736    /// execution path; the pool is owned by the [`PayloadProcessor`](super::PayloadProcessor).
737    pub(crate) bal_prewarm_pool: Option<Arc<BalPrewarmPool>>,
738    /// The metrics for the prewarm task.
739    pub metrics: PrewarmMetrics,
740    /// Metrics for the execution cache.
741    /// Metrics for the execution cache. `None` disables metrics recording.
742    pub cache_metrics: Option<CachedStateMetrics>,
743    /// Metrics for shared execution cache state. `None` disables metrics recording.
744    pub cache_state_metrics: Option<CachedStateCacheMetrics>,
745    /// An atomic bool that tells prewarm tasks to not start any more execution.
746    pub terminate_execution: Arc<AtomicBool>,
747    /// Shared counter tracking the next transaction index to be executed by the main execution
748    /// loop. Prewarm workers skip transactions with `index < counter` since those have already
749    /// been executed.
750    pub executed_tx_index: Arc<AtomicUsize>,
751    /// Whether the precompile cache is disabled.
752    pub precompile_cache_disabled: bool,
753    /// The precompile cache map.
754    pub precompile_cache_map: PrecompileCacheMap<SpecFor<Evm>>,
755    /// Whether to disable BAL-driven parallel state root computation.
756    /// Only valid when BAL parallel execution is also disabled.
757    pub disable_bal_parallel_state_root: bool,
758    /// Whether BAL state prefetching during prewarm is disabled.
759    pub disable_bal_batch_io: bool,
760    /// Results of transaction prewarming that block execution may reuse, `None` if disabled.
761    pub(crate) prewarm_results: Option<Arc<PrewarmResults<EvmTypesFor<Evm>>>>,
762}
763
764/// Per-thread EVM state initialised by [`PrewarmContext::evm_for_ctx`] and stored in
765/// workers via [`WorkerStatefulPool::get_or_init`].
766struct PrewarmEvmState<Evm: ConfigureEvm> {
767    /// The EVM, `None` if its state provider could not be created.
768    evm: Option<EvmFor<'static, Evm>>,
769    recording: RecordingHandle,
770}
771
772impl<N, P, Evm> PrewarmContext<N, P, Evm>
773where
774    N: NodePrimitives,
775    P: DatabaseProviderFactory,
776    P::Provider: BlockNumReader
777        + PruneCheckpointReader
778        + StageCheckpointReader
779        + ChangeSetReader
780        + StorageChangeSetReader
781        + StorageSettingsCache
782        + HistoryReader
783        + 'static,
784    Evm: ConfigureEvm<Primitives = N> + 'static,
785{
786    /// Creates a per-thread EVM for prewarming.
787    #[instrument(level = "debug", target = "engine::tree::payload_processor::prewarm", skip_all)]
788    fn evm_for_ctx(&self) -> PrewarmEvmState<Evm> {
789        let mut state_provider = match self.provider.database_provider_ro() {
790            Ok(provider) => Box::new(provider.into_evm_state_provider()) as EvmStateProviderBox,
791            Err(err) => {
792                trace!(
793                    target: "engine::tree::payload_processor::prewarm",
794                    %err,
795                    "Failed to build state provider in prewarm thread"
796                );
797                return PrewarmEvmState { evm: None, recording: RecordingHandle::default() }
798            }
799        };
800
801        // Use the caches to create a new provider with caching
802        if let Some(saved_cache) = &self.saved_cache {
803            let caches = saved_cache.cache().clone();
804            state_provider = Box::new(
805                CachedStateProvider::new_prewarm(state_provider, caches)
806                    .with_txpool_snapshot(self.env.txpool_snapshot.clone()),
807            );
808        }
809
810        let evm_env =
811            self.env.evm_env.clone().with_nonce_check_disabled().with_balance_check_disabled();
812
813        let recording = RecordingHandle::default();
814        let config = if self.prewarm_results.is_some() {
815            self.evm_config.clone().with_jit_support_enabled(false)
816        } else {
817            self.evm_config.clone()
818        };
819        let db = StateProviderDatabase::new(state_provider);
820        let evm = if self.prewarm_results.is_some() {
821            self.create_evm(&config, RecordingDb::new(db, recording.clone()), evm_env)
822        } else {
823            self.create_evm(&config, db, evm_env)
824        };
825        PrewarmEvmState { evm: Some(evm), recording }
826    }
827
828    /// Creates a prewarm EVM, caching precompile results unless the cache is disabled.
829    ///
830    /// Prewarming does not record precompile cache metrics.
831    fn create_evm(
832        &self,
833        config: &Evm,
834        db: impl Database + 'static,
835        evm_env: EvmEnvFor<Evm>,
836    ) -> EvmFor<'static, Evm> {
837        if self.precompile_cache_disabled {
838            config.evm_with_env(db, evm_env)
839        } else {
840            config.evm_with_precompile_cache(db, evm_env, self.precompile_cache_map.clone(), false)
841        }
842    }
843
844    /// Returns `true` if prewarming should stop.
845    #[inline]
846    pub fn should_stop(&self) -> bool {
847        self.terminate_execution.load(Ordering::Relaxed)
848    }
849
850    /// Signals all prewarm tasks to stop execution.
851    #[inline]
852    pub fn stop(&self) {
853        self.terminate_execution.store(true, Ordering::Relaxed);
854    }
855
856    /// Hashes and streams a single BAL account's state to the state-root job's hashed-update
857    /// stream.
858    ///
859    /// For each changed account, storage slots are hashed and sent immediately, then the account
860    /// is sent as a separate update. The parent account is read only when the BAL did not provide
861    /// all account leaf fields needed for state-root computation.
862    ///
863    /// The `provider` is lazily initialized on first call and reused across accounts on the same
864    /// thread.
865    fn send_bal_hashed_state(
866        &self,
867        parent_span: &Span,
868        provider: &mut Option<EvmStateProviderBox>,
869        account_changes: &alloy_eip7928::AccountChanges,
870        hashed_update_stream: &StateRootUpdateStream,
871    ) {
872        if self.disable_bal_parallel_state_root {
873            return;
874        }
875        let address = account_changes.address;
876        let mut hashed_address = None;
877        let account_info = account_changes.account_info();
878
879        if !account_info.changes_state_root(account_changes) {
880            return;
881        }
882
883        // If there are any storage changes we can assume that the resulting account info will be
884        // non-empty, so the account will exist, and therefore we can pre-emptively send out storage
885        // changes to start processing them before potentially hitting the db in the next step.
886        if account_changes.has_storage_changes() {
887            let hashed_address = *hashed_address.get_or_insert_with(|| keccak256(address));
888            let storage_map = reth_trie::HashedStorage::from_iter(
889                account_changes
890                    .storage_post_states()
891                    .map(|(slot, value)| (keccak256(slot.to_be_bytes::<32>()), value)),
892            );
893
894            let mut hashed_state = reth_trie::HashedPostState::default();
895            hashed_state.storages.insert(hashed_address, storage_map);
896            hashed_update_stream.on_hashed_state_update(hashed_state);
897        }
898
899        let existing_account = if account_info.is_complete() {
900            None
901        } else {
902            if provider.is_none() {
903                let _span = debug_span!(
904                    target: "engine::tree::payload_processor::prewarm",
905                    parent: parent_span,
906                    "bal_hashed_state_provider_init",
907                    has_saved_cache = !self.disable_bal_batch_io && self.saved_cache.is_some(),
908                )
909                .entered();
910
911                let inner = match self.provider.database_provider_ro() {
912                    Ok(p) => p.into_evm_state_provider(),
913                    Err(err) => {
914                        warn!(
915                            target: "engine::tree::payload_processor::prewarm",
916                            ?err,
917                            "Failed to build provider for BAL account reads"
918                        );
919                        return;
920                    }
921                };
922                let boxed: EvmStateProviderBox =
923                    match (self.disable_bal_batch_io, &self.saved_cache) {
924                        (false, Some(saved)) => {
925                            let caches = saved.cache().clone();
926                            Box::new(
927                                CachedStateProvider::new_prewarm(inner, caches)
928                                    .with_txpool_snapshot(self.env.txpool_snapshot.clone()),
929                            )
930                        }
931                        _ => Box::new(inner),
932                    };
933                *provider = Some(boxed);
934            }
935            let account_reader = provider.as_ref().expect("provider just initialized");
936            account_reader.basic_account(&address).ok().flatten()
937        };
938
939        let mut account = existing_account.unwrap_or_default();
940        account.apply_bal_info(account_info);
941        let hashed_address = hashed_address.unwrap_or_else(|| keccak256(address));
942
943        // It is possible for the resulting account info to be empty. This can happen when, in the
944        // same block:
945        // * tx1: A new account is funded
946        // * tx2: CREATE2 is called on the new account, SELFDESTRUCT is called within the init code
947        //
948        // In this case the account will have only balance_changes, one for funding and the second
949        // setting balance back to zero. The resulting account is fully empty, we mark it as None
950        // with no storage changes to indicate that it should be deleted if nothing else.
951        //
952        // We assume that if the account info is all zero then it can't have storage, so we don't
953        // have to explicitly check for empty storage.
954        let account = (!account.is_empty()).then_some(account);
955
956        let mut hashed_state = reth_trie::HashedPostState::default();
957        hashed_state.accounts.insert(hashed_address, account);
958        hashed_update_stream.on_hashed_state_update(hashed_state);
959    }
960}
961
962/// Returns [`MultiProofTargetsV2`] for withdrawal addresses.
963///
964/// Withdrawals only modify account balances (no storage), so the targets contain
965/// only account-level entries with empty storage sets.
966fn multiproof_targets_from_withdrawals(withdrawals: &[Withdrawal]) -> MultiProofTargetsV2 {
967    MultiProofTargetsV2 {
968        account_targets: withdrawals.iter().map(|w| keccak256(w.address).into()).collect(),
969        ..Default::default()
970    }
971}
972
973/// The events the pre-warm task can handle.
974///
975/// Generic over `R` (receipt type) to allow sharing `Arc<ExecutionOutcome<R>>` with the main
976/// execution path without cloning the expensive `BundleState`.
977#[derive(Debug)]
978pub enum PrewarmTaskEvent<R> {
979    /// Signals the prewarm workers to stop executing further transactions.
980    ///
981    /// This only sets the termination flag the workers poll; the task keeps running to save the
982    /// cache. Sent once the authoritative execution no longer needs prewarming, so the workers do
983    /// not race ahead on transactions that will never be used.
984    TerminateTransactionExecution,
985    /// Tears the whole task down: stops the workers, optionally saves the warmed cache from the
986    /// final output, and exits.
987    ///
988    /// Sent when execution completed successfully (carrying the output to save) or when the task
989    /// handle is dropped (carrying no output, e.g. after an execution error). Handling this event
990    /// also stops the workers, since a teardown may arrive without a preceding
991    /// [`TerminateTransactionExecution`](Self::TerminateTransactionExecution).
992    Terminate {
993        /// The final execution outcome, or `None` when the task is torn down without one (e.g. a
994        /// dropped handle). Using `Arc` allows sharing with the main execution path without
995        /// cloning the expensive `BundleState`.
996        execution_outcome: Option<Arc<BlockExecutionOutput<R>>>,
997        /// Receiver for the block validation result.
998        ///
999        /// Cache saving is racing the state root validation. We optimistically construct the
1000        /// updated cache but only save it once we know the block is valid.
1001        valid_block_rx: mpsc::Receiver<()>,
1002    },
1003    /// Emitted by the worker-dispatch side once every dispatched transaction has finished or been
1004    /// cancelled, reporting how many were executed.
1005    FinishedTxExecution {
1006        /// Number of transactions executed
1007        executed_transactions: usize,
1008    },
1009}
1010
1011/// Metrics for transactions prewarming.
1012#[derive(Metrics, Clone)]
1013#[metrics(scope = "sync.prewarm")]
1014pub struct PrewarmMetrics {
1015    /// The number of transactions to prewarm
1016    pub(crate) transactions: Gauge,
1017    /// A histogram of the number of transactions to prewarm
1018    pub(crate) transactions_histogram: Histogram,
1019    /// A histogram of duration per transaction prewarming
1020    pub(crate) total_runtime: Histogram,
1021    /// A histogram of EVM execution duration per transaction prewarming
1022    pub(crate) execution_duration: Histogram,
1023    /// A histogram for prefetch targets per transaction prewarming
1024    pub(crate) prefetch_storage_targets: Histogram,
1025    /// Time spent in `save_cache`, including dropping its removed `SavedCache` values.
1026    /// Excludes any later freeing of cache contents by other `ExecutionCache` clones.
1027    pub(crate) cache_saving_duration: Gauge,
1028    /// Counter for transaction execution errors during prewarming
1029    pub(crate) transaction_errors: Counter,
1030    /// Counter for transactions seeded with results of pool transactions instead of being
1031    /// executed.
1032    pub(crate) seeded_transactions: Counter,
1033    /// A histogram of BAL slot iteration duration during prefetching
1034    pub(crate) bal_slot_iteration_duration: Histogram,
1035}
1036
1037#[cfg(test)]
1038mod tests {
1039
1040    use super::*;
1041    use crate::tree::payload_processor::{CacheTaskHandle, PayloadHandle};
1042    use alloy_consensus::{transaction::Recovered, TxLegacy};
1043    use alloy_eips::eip7702::constants::EIP7702_CLEARED_DELEGATION;
1044    use alloy_primitives::{Address, Signature, TxKind, B256, U256};
1045    use evm2::{evm::EmptyDB, BaseEvmTypes};
1046    use reth_chainspec::ChainSpec;
1047    use reth_concurrency::sync::{
1048        channel,
1049        thread::{JoinHandle, ThreadId},
1050    };
1051    use reth_ethereum_primitives::{EthPrimitives, TransactionSigned};
1052    use reth_evm::{execute::WithTxEnv, TxEnvFor};
1053    use reth_evm_ethereum::EthEvmConfig;
1054    use reth_provider::test_utils::MockEthProvider;
1055    use reth_stages_api::{StageCheckpoint, StageId};
1056    use reth_storage_overlay::OverlayManager;
1057    use reth_tasks::WorkerPool;
1058    use reth_trie_common::bundle_state::{AccountStatus, BundleAccount, BundleState};
1059    use std::time::Duration;
1060
1061    #[reth_concurrency::test]
1062    fn terminate_event_stops_transaction_execution() {
1063        let terminate_execution = Arc::new(AtomicBool::new(false));
1064        let ctx = PrewarmContext {
1065            env: ExecutionEnv::test_default(),
1066            evm_config: EthEvmConfig::new(Arc::new(ChainSpec::default())),
1067            saved_cache: None,
1068            provider: OverlayStateProviderFactory::new(
1069                MockEthProvider::default(),
1070                OverlayManager::default().overlay_builder(B256::ZERO),
1071            ),
1072            bal_prewarm_pool: None,
1073            metrics: PrewarmMetrics::default(),
1074            cache_metrics: None,
1075            cache_state_metrics: None,
1076            terminate_execution: Arc::clone(&terminate_execution),
1077            executed_tx_index: Arc::new(AtomicUsize::new(0)),
1078            precompile_cache_disabled: false,
1079            precompile_cache_map: PrecompileCacheMap::default(),
1080            disable_bal_parallel_state_root: false,
1081            disable_bal_batch_io: false,
1082            prewarm_results: None,
1083        };
1084        let (task, actions_tx) =
1085            PrewarmCacheTask::new(Runtime::test(), PayloadExecutionCache::default(), ctx);
1086        actions_tx
1087            .send(PrewarmTaskEvent::Terminate {
1088                execution_outcome: None,
1089                valid_block_rx: mpsc::channel().1,
1090            })
1091            .unwrap();
1092
1093        task.run::<WithTxEnv<TxEnvFor<EthEvmConfig>, Recovered<TransactionSigned>>>(
1094            PrewarmMode::Skipped,
1095            actions_tx,
1096        );
1097
1098        assert!(terminate_execution.load(Ordering::Relaxed));
1099    }
1100
1101    #[reth_concurrency::test]
1102    fn rebuilds_evm_for_each_prewarm_run() {
1103        let caller = Address::repeat_byte(1);
1104        let provider = MockEthProvider::default();
1105        provider.enable_database_provider();
1106        provider.add_header(B256::ZERO, Default::default());
1107        provider.add_stage_checkpoint(StageId::Finish, StageCheckpoint::new(0));
1108        let tx = Recovered::new_unchecked(
1109            TransactionSigned::new_unhashed(
1110                // Free, so that the empty caller can pay for it.
1111                TxLegacy {
1112                    gas_limit: 21_000,
1113                    to: TxKind::Call(Address::repeat_byte(2)),
1114                    ..Default::default()
1115                }
1116                .into(),
1117                Signature::test_signature(),
1118            ),
1119            caller,
1120        );
1121        let pool = Arc::new(WorkerPool::new(1, "prewarm-test"));
1122        // Payloads that claim the same block hash may still use different block environments.
1123        let prewarm = |beneficiary| {
1124            let mut env = ExecutionEnv::<EthEvmConfig>::test_default();
1125            env.evm_env.block.beneficiary = beneficiary;
1126            let results = Arc::new(PrewarmResults::new(1));
1127            let ctx = PrewarmContext {
1128                env,
1129                evm_config: EthEvmConfig::new(Arc::new(ChainSpec::default())),
1130                saved_cache: None,
1131                provider: OverlayStateProviderFactory::new(
1132                    provider.clone(),
1133                    OverlayManager::default().overlay_builder(B256::ZERO),
1134                ),
1135                bal_prewarm_pool: None,
1136                metrics: PrewarmMetrics::default(),
1137                cache_metrics: None,
1138                cache_state_metrics: None,
1139                terminate_execution: Arc::new(AtomicBool::new(false)),
1140                executed_tx_index: Arc::new(AtomicUsize::new(0)),
1141                precompile_cache_disabled: false,
1142                precompile_cache_map: PrecompileCacheMap::default(),
1143                disable_bal_parallel_state_root: false,
1144                disable_bal_batch_io: false,
1145                prewarm_results: Some(Arc::clone(&results)),
1146            };
1147            let tx =
1148                WithTxEnv { tx_env: ctx.evm_config.tx_env(tx.clone()), tx: Arc::new(tx.clone()) };
1149            let stateful_pool = WorkerStatefulPool::new(Arc::clone(&pool));
1150            stateful_pool.install_fn(|| {
1151                PrewarmCacheTask::transact_worker(&ctx, &stateful_pool, 0, tx, None, None)
1152            });
1153            results.take_valid(0, &mut EmptyDB::default()).unwrap().unwrap().pending_state
1154        };
1155
1156        assert!(prewarm(Address::repeat_byte(0xa))
1157            .account_changes()
1158            .any(|a| a.address == Address::repeat_byte(0xa)));
1159        let state = prewarm(Address::repeat_byte(0xb));
1160        assert!(state.account_changes().any(|a| a.address == Address::repeat_byte(0xb)));
1161        assert!(!state.account_changes().any(|a| a.address == Address::repeat_byte(0xa)));
1162    }
1163
1164    #[reth_concurrency::test]
1165    fn transaction_prewarm_releases_worker_cache_before_cache_task_finishes() {
1166        let runtime = Runtime::test();
1167        let saved = SavedCache::new(B256::ZERO, crate::tree::ExecutionCache::new(1_000));
1168        let mut ctx = test_prewarm_context(saved.clone(), Gauge::noop());
1169        let provider = MockEthProvider::default();
1170        provider.enable_database_provider();
1171        provider.add_header(B256::ZERO, Default::default());
1172        provider.add_stage_checkpoint(StageId::Finish, StageCheckpoint::new(0));
1173        ctx.provider = OverlayStateProviderFactory::new(
1174            provider,
1175            OverlayManager::default().overlay_builder(B256::ZERO),
1176        );
1177        assert!(ctx.evm_for_ctx().evm.is_some());
1178        let tx = Recovered::new_unchecked(
1179            TransactionSigned::new_unhashed(
1180                TxLegacy {
1181                    gas_limit: 21_000,
1182                    to: TxKind::Call(Address::repeat_byte(2)),
1183                    ..Default::default()
1184                }
1185                .into(),
1186                Signature::test_signature(),
1187            ),
1188            Address::repeat_byte(1),
1189        );
1190        let tx = WithTxEnv { tx_env: ctx.evm_config.tx_env(tx.clone()), tx: Arc::new(tx) };
1191        let (task, actions_tx) =
1192            PrewarmCacheTask::new(runtime, PayloadExecutionCache::default(), ctx);
1193        let (pending_tx, pending_rx) = mpsc::channel();
1194        pending_tx.send((0, tx)).unwrap();
1195        drop(pending_tx);
1196        task.spawn_txs_prewarm(pending_rx, actions_tx, None);
1197        assert!(matches!(
1198            task.actions_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
1199            PrewarmTaskEvent::FinishedTxExecution { executed_transactions: 1 }
1200        ));
1201
1202        // The dispatcher can still be dropping its context after sending completion. The cache
1203        // task remains alive, but its workers must no longer retain any cache references.
1204        let deadline = Instant::now() + Duration::from_secs(5);
1205        while saved.usage_count() != 2 {
1206            assert!(Instant::now() < deadline, "worker state outlived transaction prewarming");
1207            thread::yield_now();
1208        }
1209        assert!(task.ctx.saved_cache.is_some());
1210    }
1211
1212    fn test_prewarm_context(
1213        saved_cache: SavedCache,
1214        saving_duration: Gauge,
1215    ) -> PrewarmContext<EthPrimitives, MockEthProvider, EthEvmConfig> {
1216        PrewarmContext {
1217            env: ExecutionEnv { hash: B256::repeat_byte(2), ..ExecutionEnv::test_default() },
1218            evm_config: EthEvmConfig::new(Arc::new(ChainSpec::default())),
1219            saved_cache: Some(saved_cache),
1220            provider: OverlayStateProviderFactory::new(
1221                MockEthProvider::default(),
1222                OverlayManager::default().overlay_builder(B256::ZERO),
1223            ),
1224            bal_prewarm_pool: None,
1225            metrics: PrewarmMetrics {
1226                cache_saving_duration: saving_duration,
1227                ..Default::default()
1228            },
1229            cache_metrics: None,
1230            cache_state_metrics: None,
1231            terminate_execution: Arc::new(AtomicBool::new(false)),
1232            executed_tx_index: Arc::new(AtomicUsize::new(0)),
1233            precompile_cache_disabled: false,
1234            precompile_cache_map: PrecompileCacheMap::default(),
1235            disable_bal_parallel_state_root: false,
1236            disable_bal_batch_io: false,
1237            prewarm_results: None,
1238        }
1239    }
1240
1241    fn save_test_cache(
1242        runtime: &Runtime,
1243        execution_cache: &PayloadExecutionCache,
1244        saved_cache: SavedCache,
1245        state: reth_trie_common::bundle_state::BundleState,
1246        valid: bool,
1247        saving_duration: Gauge,
1248    ) {
1249        let ctx = test_prewarm_context(saved_cache, saving_duration);
1250        let (task, _) = PrewarmCacheTask::new(runtime.clone(), execution_cache.clone(), ctx);
1251        let (valid_tx, valid_rx) = mpsc::channel();
1252        if valid {
1253            valid_tx.send(()).unwrap();
1254        }
1255        drop(valid_tx);
1256        task.save_cache(
1257            Arc::new(BlockExecutionOutput { state, result: Default::default() }),
1258            valid_rx,
1259        );
1260    }
1261
1262    // Observe the handoff before save_cache returns and drops its local variables. A check after
1263    // return would miss the window where the saving task still owns an extra reference.
1264    struct CacheSaveObserver {
1265        cache: PayloadExecutionCache,
1266        observed: Arc<AtomicBool>,
1267    }
1268
1269    impl metrics::GaugeFn for CacheSaveObserver {
1270        fn increment(&self, _: f64) {}
1271        fn decrement(&self, _: f64) {}
1272        fn set(&self, _: f64) {
1273            assert!(
1274                self.cache.get_cache_for(B256::repeat_byte(2)).is_some(),
1275                "saved cache must be available before the saving task returns"
1276            );
1277            self.observed.store(true, Ordering::Relaxed);
1278        }
1279    }
1280
1281    #[reth_concurrency::test]
1282    fn save_cache_releases_warm_cache_before_duration_metric() {
1283        let runtime = Runtime::test();
1284        let execution_cache = PayloadExecutionCache::default();
1285        let saved = SavedCache::new(B256::repeat_byte(1), crate::tree::ExecutionCache::new(1_000));
1286        let address = Address::with_last_byte(1);
1287        saved.cache().insert_storage(address, B256::ZERO, Some(U256::from(7)));
1288        execution_cache.update_with_guard(|slot| *slot = Some(saved.clone()));
1289        // Keep the drop worker occupied: a queued SavedCache would delay cache reuse.
1290        let (release_tx, release_rx) = mpsc::channel::<()>();
1291        runtime.spawn_blocking_named("drop", move || {
1292            let _ = release_rx.recv();
1293        });
1294        let observed = Arc::new(AtomicBool::new(false));
1295        let observer = Arc::new(CacheSaveObserver {
1296            cache: execution_cache.clone(),
1297            observed: observed.clone(),
1298        });
1299        save_test_cache(
1300            &runtime,
1301            &execution_cache,
1302            saved,
1303            Default::default(),
1304            true,
1305            Gauge::from_arc(observer),
1306        );
1307        assert!(observed.load(Ordering::Relaxed), "save duration was not recorded");
1308        let saved = execution_cache.get_cache_for(B256::repeat_byte(2)).unwrap();
1309        assert_eq!(
1310            saved.cache().get_or_try_insert_storage_with(address, B256::ZERO, || Err(())),
1311            Ok(reth_execution_cache::CachedStatus::Cached(U256::from(7))),
1312            "handoff must preserve the warmed contents",
1313        );
1314        drop(release_tx);
1315    }
1316
1317    #[reth_concurrency::test]
1318    fn save_cache_blocks_reuse_while_execution_cache_is_cloned() {
1319        let runtime = Runtime::test();
1320        let execution_cache = PayloadExecutionCache::default();
1321        let saved = SavedCache::new(B256::repeat_byte(1), crate::tree::ExecutionCache::new(1_000));
1322        execution_cache.update_with_guard(|slot| *slot = Some(saved.clone()));
1323        let other_cache_clone = saved.cache().clone();
1324
1325        save_test_cache(&runtime, &execution_cache, saved, Default::default(), true, Gauge::noop());
1326
1327        assert!(execution_cache.get_cache_for(B256::repeat_byte(2)).is_none());
1328        drop(other_cache_clone);
1329        assert!(execution_cache.get_cache_for(B256::repeat_byte(2)).is_some());
1330    }
1331
1332    #[derive(Clone, Copy, Debug)]
1333    enum CacheSlot {
1334        Empty,
1335        Shared,
1336        Distinct,
1337    }
1338
1339    // EIP-7702 bytecode preserves its owned buffer, letting us observe actual cache destruction.
1340    struct CacheDropProbe {
1341        started: Sender<ThreadId>,
1342        inspected: Receiver<()>,
1343        result: Sender<bool>,
1344    }
1345
1346    impl AsRef<[u8]> for CacheDropProbe {
1347        fn as_ref(&self) -> &[u8] {
1348            &EIP7702_CLEARED_DELEGATION
1349        }
1350    }
1351
1352    impl Drop for CacheDropProbe {
1353        fn drop(&mut self) {
1354            let _ = self.started.send(thread::current().id());
1355            // A timeout turns destruction under the mutex into a failure instead of a deadlock.
1356            let unlocked = self.inspected.recv_timeout(std::time::Duration::from_secs(5)).is_ok();
1357            let _ = self.result.send(unlocked);
1358        }
1359    }
1360
1361    fn observe_cache_drop(
1362        saved: &SavedCache,
1363        execution_cache: &PayloadExecutionCache,
1364        expect_saved_cache: bool,
1365    ) -> (Receiver<bool>, JoinHandle<ThreadId>) {
1366        let (started_tx, started_rx) = mpsc::channel();
1367        let (inspected_tx, inspected_rx) = mpsc::channel();
1368        let (result_tx, result_rx) = mpsc::channel();
1369        let cache = execution_cache.clone();
1370        let reader = thread::spawn(move || {
1371            let drop_thread = started_rx.recv().unwrap();
1372            // Waiting for the mutex must return while the removed cache is still being dropped.
1373            cache.wait_for_availability();
1374            assert_eq!(cache.get_cache_for(B256::repeat_byte(2)).is_some(), expect_saved_cache);
1375            cache.update_with_guard(|slot| assert_eq!(slot.is_some(), expect_saved_cache));
1376            let _ = inspected_tx.send(());
1377            drop_thread
1378        });
1379        let bytes = alloy_primitives::bytes::Bytes::from_owner(CacheDropProbe {
1380            started: started_tx,
1381            inspected: inspected_rx,
1382            result: result_tx,
1383        });
1384        let code = evm2::bytecode::Bytecode::new_eip7702_raw(bytes.into()).unwrap();
1385        saved
1386            .cache()
1387            .insert_code(B256::repeat_byte(3), Some(reth_primitives_traits::Bytecode(code)));
1388        (result_rx, reader)
1389    }
1390
1391    #[reth_concurrency::test]
1392    fn save_cache_freeing_waits_for_validator_cache_references() {
1393        let runtime = Runtime::test();
1394        let execution_cache = PayloadExecutionCache::default();
1395        let saved = SavedCache::new(B256::repeat_byte(1), crate::tree::ExecutionCache::new(1_000));
1396        execution_cache.update_with_guard(|cached| *cached = Some(saved.clone()));
1397        let (dropped, reader) = observe_cache_drop(&saved, &execution_cache, false);
1398        let ctx = test_prewarm_context(saved, Gauge::noop());
1399        let (task, actions_tx) =
1400            PrewarmCacheTask::new(runtime.clone(), execution_cache.clone(), ctx);
1401        let mut payload = PayloadHandle {
1402            prewarm_handle: CacheTaskHandle::<_, BaseEvmTypes> {
1403                saved_cache: task.ctx.saved_cache.clone(),
1404                to_prewarm_task: Some(actions_tx.clone()),
1405                executed_tx_index: task.ctx.executed_tx_index.clone(),
1406                prewarm_results: None,
1407                cache_metrics: None,
1408            },
1409            transactions: channel::never::<(usize, Result<(), ()>)>(),
1410            _span: Span::none(),
1411        };
1412        // The validator keeps this ExecutionCache clone after calling terminate_caching.
1413        let validator_cache = payload.caches().unwrap();
1414        let valid_block_tx = payload.terminate_caching(Some(Arc::new(BlockExecutionOutput {
1415            state: Default::default(),
1416            result: Default::default(),
1417        })));
1418        drop(valid_block_tx);
1419        let prewarm = runtime.spawn_blocking_named("prewarm", move || {
1420            task.run::<WithTxEnv<TxEnvFor<EthEvmConfig>, Recovered<TransactionSigned>>>(
1421                PrewarmMode::Skipped,
1422                actions_tx,
1423            );
1424            thread::current().id()
1425        });
1426        let prewarm_thread = *prewarm.get();
1427
1428        execution_cache.update_with_guard(|cached| assert!(cached.is_none()));
1429        assert_eq!(payload.prewarm_handle.saved_cache.as_ref().unwrap().usage_count(), 2);
1430        assert!(matches!(dropped.try_recv(), Err(mpsc::TryRecvError::Empty)));
1431        drop(payload);
1432        assert!(matches!(dropped.try_recv(), Err(mpsc::TryRecvError::Empty)));
1433
1434        drop(validator_cache);
1435        assert!(dropped.try_recv().expect("last ExecutionCache drop must free the cache"));
1436        let drop_thread = reader.join().unwrap();
1437        assert_eq!(drop_thread, thread::current().id());
1438        assert_ne!(drop_thread, prewarm_thread);
1439    }
1440
1441    fn assert_save_cache_drops_removed_caches(slot: CacheSlot, valid: bool, insert_error: bool) {
1442        let runtime = Runtime::test();
1443        let execution_cache = PayloadExecutionCache::default();
1444        let cache_to_save =
1445            SavedCache::new(B256::repeat_byte(1), crate::tree::ExecutionCache::new(1_000));
1446        let distinct_previous = matches!(slot, CacheSlot::Distinct).then(|| {
1447            // The same block hash does not imply the same allocation.
1448            SavedCache::new(B256::repeat_byte(2), crate::tree::ExecutionCache::new(1_000))
1449        });
1450        execution_cache.update_with_guard(|cached| {
1451            *cached = match slot {
1452                CacheSlot::Empty => None,
1453                CacheSlot::Shared => Some(cache_to_save.clone()),
1454                CacheSlot::Distinct => distinct_previous.clone(),
1455            };
1456        });
1457        let expect_saved_cache = valid && !insert_error;
1458        let mut drops = Vec::new();
1459        if let Some(previous) = &distinct_previous {
1460            drops.push(observe_cache_drop(previous, &execution_cache, expect_saved_cache));
1461        }
1462        if !expect_saved_cache {
1463            drops.push(observe_cache_drop(&cache_to_save, &execution_cache, expect_saved_cache));
1464        }
1465        // Retaining this SavedCache would prevent save_cache from freeing the old cache.
1466        drop(distinct_previous);
1467
1468        // Cleanup must finish even when the shared background drop worker is occupied.
1469        let (release_tx, release_rx) = mpsc::channel::<()>();
1470        runtime.spawn_blocking_named("drop", move || {
1471            let _ = release_rx.recv();
1472        });
1473
1474        let mut state = BundleState::default();
1475        if insert_error {
1476            // Modified accounts without current info are rejected by insert_state.
1477            state.state.insert(
1478                Address::with_last_byte(1),
1479                BundleAccount::new(None, None, Default::default(), AccountStatus::Changed),
1480            );
1481        }
1482        save_test_cache(&runtime, &execution_cache, cache_to_save, state, valid, Gauge::noop());
1483
1484        for (result, reader) in drops {
1485            assert!(
1486                result.try_recv().expect("removed cache must be destroyed before save returns"),
1487                "cache mutex must be unlocked during destruction"
1488            );
1489            assert_eq!(reader.join().unwrap(), thread::current().id());
1490        }
1491        execution_cache.update_with_guard(|slot| {
1492            if expect_saved_cache {
1493                let saved = slot.as_ref().expect("valid cache saved");
1494                assert_eq!(saved.executed_block_hash(), B256::repeat_byte(2));
1495            } else {
1496                assert!(slot.is_none(), "polluted cache must be removed");
1497            }
1498        });
1499        assert_eq!(
1500            execution_cache.get_cache_for(B256::repeat_byte(2)).is_some(),
1501            expect_saved_cache
1502        );
1503        drop(release_tx);
1504    }
1505
1506    #[reth_concurrency::test]
1507    fn save_cache_drops_replaced_allocation_after_unlock() {
1508        assert_save_cache_drops_removed_caches(CacheSlot::Distinct, true, false);
1509    }
1510
1511    #[reth_concurrency::test]
1512    fn save_cache_drops_invalid_allocations_after_unlock() {
1513        assert_save_cache_drops_removed_caches(CacheSlot::Distinct, false, false);
1514    }
1515
1516    #[reth_concurrency::test]
1517    fn save_cache_drops_allocations_after_unlock_on_insert_error() {
1518        assert_save_cache_drops_removed_caches(CacheSlot::Distinct, true, true);
1519    }
1520
1521    #[reth_concurrency::test]
1522    fn save_cache_drops_shared_allocation_after_unlock_on_invalid_block() {
1523        assert_save_cache_drops_removed_caches(CacheSlot::Shared, false, false);
1524    }
1525
1526    #[reth_concurrency::test]
1527    fn save_cache_drops_shared_allocation_after_unlock_on_insert_error() {
1528        assert_save_cache_drops_removed_caches(CacheSlot::Shared, true, true);
1529    }
1530
1531    #[reth_concurrency::test]
1532    fn save_cache_handles_empty_slot() {
1533        for (valid, insert_error) in [(true, false), (false, false), (true, true)] {
1534            assert_save_cache_drops_removed_caches(CacheSlot::Empty, valid, insert_error);
1535        }
1536    }
1537}