1use 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
52pub const SMALL_BLOCK_TX_THRESHOLD: usize = 5;
55
56type 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#[derive(Debug)]
86pub struct PayloadProcessor<Evm>
87where
88 Evm: ConfigureEvm,
89{
90 executor: Runtime,
92 execution_cache: PayloadExecutionCache,
94 cache_metrics: Option<CachedStateMetrics>,
96 cache_state_metrics: Option<CachedStateCacheMetrics>,
98 cross_block_cache_size: usize,
100 disable_transaction_prewarming: bool,
102 disable_state_cache: bool,
104 evm_config: Evm,
106 precompile_cache_disabled: bool,
108 precompile_cache_map: PrecompileCacheMap<SpecFor<Evm>>,
110 disable_bal_parallel_state_root: bool,
113 disable_bal_batch_io: bool,
115 reuse_prewarm_results: bool,
117 bal_prewarm_pool: OnceLock<Arc<bal_prewarm_pool::BalPrewarmPool>>,
120 bal_prewarm_threads: usize,
122}
123
124impl<Evm> PayloadProcessor<Evm>
125where
126 Evm: ConfigureEvm,
127{
128 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 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 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 #[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 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 const SMALL_BLOCK_TX_THRESHOLD: usize = 30;
241
242 const PARALLEL_PREFETCH_COUNT: usize = 4;
250
251 const FIRST_PARALLEL_TX_WINDOW_SIZE: usize = 64;
253
254 #[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 } else if transaction_count < Self::SMALL_BLOCK_TX_THRESHOLD {
281 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 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 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 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 .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 if disconnected {
333 Err(())
334 } else {
335 Ok(())
336 }
337 });
338 });
339 } else {
340 let prefetch = Self::PARALLEL_PREFETCH_COUNT.min(transaction_count);
344 let mut iter = transactions.into_iter();
345
346 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 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 #[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 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 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 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 #[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 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 let caches = match cached.take() {
564 Some(existing) => existing.cache().clone(),
565 None => ExecutionCache::new(self.cross_block_cache_size),
566 };
567
568 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 *cached = Some(new_cache);
579 debug!(target: "engine::caching", ?block_with_parent, "Updated execution cache for inserted block");
580 });
581 }
582}
583
584fn 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#[derive_where::derive_where(Debug; Tx, Err, R)]
621pub struct PayloadHandle<Tx, Err, R, H: evm2::EvmTypes> {
622 prewarm_handle: CacheTaskHandle<R, H>,
623 transactions: IndexedTxReceiver<Tx, Err>,
625 _span: Span,
627}
628
629impl<Tx, Err, R: Send + Sync + 'static, H: evm2::EvmTypes> PayloadHandle<Tx, Err, R, H> {
630 pub fn caches(&self) -> Option<ExecutionCache> {
632 self.prewarm_handle.saved_cache.as_ref().map(|cache| cache.cache().clone())
633 }
634
635 pub fn cache_metrics(&self) -> Option<CachedStateMetrics> {
637 self.prewarm_handle.cache_metrics.clone()
638 }
639
640 pub const fn executed_tx_index(&self) -> &Arc<AtomicUsize> {
645 &self.prewarm_handle.executed_tx_index
646 }
647
648 pub(crate) fn prewarm_results(&self) -> Option<Arc<PrewarmResults<H>>> {
650 self.prewarm_handle.prewarm_results.clone()
651 }
652
653 pub fn stop_prewarming_execution(&self) {
657 self.prewarm_handle.stop_prewarming_execution()
658 }
659
660 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 pub fn iter_transactions(&mut self) -> impl Iterator<Item = Result<Tx, Err>> + '_ {
676 self.transactions.iter().map(|(_, tx)| tx)
677 }
678
679 pub fn clone_transaction_receiver(&self) -> IndexedTxReceiver<Tx, Err> {
681 self.transactions.clone()
682 }
683}
684
685#[derive_where::derive_where(Debug; R)]
691pub struct CacheTaskHandle<R, H: evm2::EvmTypes> {
692 saved_cache: Option<SavedCache>,
694 to_prewarm_task: Option<mpsc::Sender<PrewarmTaskEvent<R>>>,
696 executed_tx_index: Arc<AtomicUsize>,
699 prewarm_results: Option<Arc<PrewarmResults<H>>>,
701 cache_metrics: Option<CachedStateMetrics>,
703}
704
705impl<R: Send + Sync + 'static, H: evm2::EvmTypes> CacheTaskHandle<R, H> {
706 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 #[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 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 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 }
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 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 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 assert!(payload_processor.execution_cache.get_cache_for(block_hash).is_none());
1037
1038 payload_processor.on_inserted_executed_block(block_with_parent, &bundle_state);
1040
1041 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 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 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 let cached = payload_processor.execution_cache.get_cache_for(block1_hash);
1100 assert!(cached.is_some(), "Original cache should be preserved");
1101
1102 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 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 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 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 #[reth_concurrency::test]
1177 fn fork_prewarm_dropped_without_save_does_not_corrupt_cache() {
1178 let execution_cache = PayloadExecutionCache::default();
1179
1180 let block4_hash = B256::repeat_byte(4u8);
1182 execution_cache.update_with_guard(|slot| *slot = Some(make_saved_cache(block4_hash)));
1183
1184 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 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 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 drop(prewarm_cache);
1207
1208 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 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 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 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}