Skip to main content

reth_execution_cache/
cached_state.rs

1//! Execution cache implementation for block processing.
2use crate::TxPoolPrewarmCacheSnapshot;
3use alloy_primitives::{
4    map::{DefaultHashBuilder, FbBuildHasher},
5    Address, StorageKey, StorageValue, B256,
6};
7use fixed_cache::{AnyRef, CacheConfig, Stats, StatsHandler};
8use metrics::{Counter, Gauge, Histogram};
9use reth_concurrency::sync::{
10    atomic::{AtomicU64, AtomicUsize, Ordering},
11    parking_lot::Once,
12};
13use reth_errors::ProviderResult;
14use reth_metrics::Metrics;
15use reth_primitives_traits::{Account, Bytecode};
16use reth_storage_api::EvmStateProvider;
17use reth_trie_common::bundle_state::BundleState;
18use std::{cell::Cell, fmt, sync::Arc, time::Duration};
19use tracing::{debug_span, instrument, trace, warn};
20
21/// Alignment in bytes for entries in the fixed-cache.
22///
23/// Each bucket in `fixed-cache` is aligned to 128 bytes (cache line) due to
24/// `#[repr(C, align(128))]` on the internal `Bucket` struct.
25const FIXED_CACHE_ALIGNMENT: usize = 128;
26
27/// Overhead per entry in the fixed-cache (the `AtomicUsize` tag field).
28const FIXED_CACHE_ENTRY_OVERHEAD: usize = size_of::<usize>();
29
30/// Calculates the actual size of a fixed-cache entry for a given key-value pair.
31///
32/// The entry size is `overhead + size_of::<K>() + size_of::<V>()`, rounded up to the
33/// next multiple of [`FIXED_CACHE_ALIGNMENT`] (128 bytes).
34const fn fixed_cache_entry_size<K, V>() -> usize {
35    fixed_cache_key_size_with_value::<K>(size_of::<V>())
36}
37
38/// Calculates the actual size of a fixed-cache entry for a given key-value pair.
39///
40/// The entry size is `overhead + size_of::<K>() + size_of::<V>()`, rounded up to the
41/// next multiple of [`FIXED_CACHE_ALIGNMENT`] (128 bytes).
42const fn fixed_cache_key_size_with_value<K>(value: usize) -> usize {
43    let raw_size = FIXED_CACHE_ENTRY_OVERHEAD + size_of::<K>() + value;
44    // Round up to next multiple of alignment
45    raw_size.div_ceil(FIXED_CACHE_ALIGNMENT) * FIXED_CACHE_ALIGNMENT
46}
47
48/// Estimated average bytecode size for cache budget calculation.
49///
50/// The fixed-cache stores `Option<Bytecode>` inline (pointer-sized), but each cached contract
51/// also holds bytecode on the heap. For budget estimation we use 8 KiB, which is close to the
52/// observed mainnet average (~7 KiB). Using `MAX_CODE_SIZE` (48 KiB) overestimates by ~7x,
53/// yielding only 4096 entries for a 228 MB code-cache budget when 16384 fit comfortably.
54const ESTIMATED_AVG_CODE_SIZE: usize = 8 * 1024;
55
56/// Size in bytes of a single code cache entry (inline metadata + estimated heap).
57const CODE_CACHE_ENTRY_SIZE: usize =
58    fixed_cache_key_size_with_value::<Address>(ESTIMATED_AVG_CODE_SIZE);
59
60/// Size in bytes of a single storage cache entry.
61const STORAGE_CACHE_ENTRY_SIZE: usize =
62    fixed_cache_entry_size::<(Address, StorageKey), StorageValue>();
63
64/// Size in bytes of a single account cache entry.
65const ACCOUNT_CACHE_ENTRY_SIZE: usize = fixed_cache_entry_size::<Address, Option<Account>>();
66
67/// Cache configuration with epoch tracking enabled for O(1) cache invalidation.
68struct EpochCacheConfig;
69impl CacheConfig for EpochCacheConfig {
70    const EPOCHS: bool = true;
71}
72
73/// Type alias for the fixed-cache used for accounts and storage.
74type FixedCache<K, V, H = DefaultHashBuilder> = fixed_cache::Cache<K, V, H, EpochCacheConfig>;
75
76/// A wrapper of a state provider and a shared cache.
77///
78/// [`CacheFillMode`] controls whether misses populate the shared cache. This is used by background
79/// prewarmers and speculative execution workers that intentionally seed the cache for other
80/// readers. Canonical execution usually leaves this disabled because the EVM database `State`
81/// already caches reads during the block, and the shared cache is updated after the block from the
82/// final [`BundleState`]. See also [`ExecutionCache::insert_state`].
83///
84/// Execution-cache and txpool-snapshot hit/miss metrics are recorded separately when
85/// [`CachedStateMetrics`] is provided. Slow-block [`CacheStats`] are controlled separately by
86/// [`Self::new_with_mode`].
87#[derive(Debug)]
88pub struct CachedStateProvider<S> {
89    /// The state provider
90    state_provider: S,
91
92    /// The caches used for the provider
93    caches: ExecutionCache,
94
95    /// Optional immutable txpool-prewarm snapshot consulted before the regular execution cache.
96    txpool_snapshot: Option<TxPoolPrewarmCacheSnapshot>,
97
98    /// Metrics for the cached state provider.
99    metrics: Option<CachedStateMetrics>,
100
101    /// Provider-local execution-cache hit/miss counters flushed when the provider is dropped.
102    execution_metric_counts: CacheMetricCounts,
103
104    /// Provider-local txpool-cache hit/miss counters flushed when the provider is dropped.
105    txpool_metric_counts: CacheMetricCounts,
106
107    /// Whether cache misses should populate the shared execution cache.
108    fill_mode: CacheFillMode,
109
110    /// Optional cache statistics for detailed block logging. Only tracked when slow block
111    /// threshold is configured.
112    cache_stats: Option<Arc<CacheStats>>,
113}
114
115impl<S> CachedStateProvider<S> {
116    /// Creates a new [`CachedStateProvider`] from an [`ExecutionCache`], state provider, and
117    /// optional [`CachedStateMetrics`].
118    pub const fn new(
119        state_provider: S,
120        caches: ExecutionCache,
121        metrics: Option<CachedStateMetrics>,
122    ) -> Self {
123        Self::new_with_mode(state_provider, caches, CacheFillMode::LookupOnly, metrics, None)
124    }
125
126    /// Creates a cache-filling [`CachedStateProvider`].
127    ///
128    /// Doesn't accept metrics because prewarming path does not need to report hit/misses.
129    pub const fn new_prewarm(state_provider: S, caches: ExecutionCache) -> Self {
130        Self::new_with_mode(state_provider, caches, CacheFillMode::FillOnMiss, None, None)
131    }
132
133    /// Creates a [`CachedStateProvider`] with explicit cache fill behavior and optional
134    /// block-local cache stats.
135    pub const fn new_with_mode(
136        state_provider: S,
137        caches: ExecutionCache,
138        fill_mode: CacheFillMode,
139        metrics: Option<CachedStateMetrics>,
140        cache_stats: Option<Arc<CacheStats>>,
141    ) -> Self {
142        Self {
143            state_provider,
144            caches,
145            txpool_snapshot: None,
146            metrics,
147            execution_metric_counts: CacheMetricCounts::new(),
148            txpool_metric_counts: CacheMetricCounts::new(),
149            fill_mode,
150            cache_stats,
151        }
152    }
153
154    /// Adds an immutable txpool-prewarm snapshot as the first cache lookup tier.
155    pub fn with_txpool_snapshot(mut self, snapshot: Option<TxPoolPrewarmCacheSnapshot>) -> Self {
156        self.txpool_snapshot = snapshot;
157        self
158    }
159
160    fn record_account_hit(&self) {
161        self.record_metric(CacheMetricKind::AccountHit);
162        if let Some(stats) = &self.cache_stats {
163            stats.record_account_hit();
164        }
165    }
166
167    fn record_account_miss(&self) {
168        self.record_metric(CacheMetricKind::AccountMiss);
169        if let Some(stats) = &self.cache_stats {
170            stats.record_account_miss();
171        }
172    }
173
174    fn record_storage_hit(&self) {
175        self.record_metric(CacheMetricKind::StorageHit);
176        if let Some(stats) = &self.cache_stats {
177            stats.record_storage_hit();
178        }
179    }
180
181    fn record_storage_miss(&self) {
182        self.record_metric(CacheMetricKind::StorageMiss);
183        if let Some(stats) = &self.cache_stats {
184            stats.record_storage_miss();
185        }
186    }
187
188    fn record_code_hit(&self) {
189        self.record_metric(CacheMetricKind::CodeHit);
190        if let Some(stats) = &self.cache_stats {
191            stats.record_code_hit();
192        }
193    }
194
195    fn record_code_miss(&self) {
196        self.record_metric(CacheMetricKind::CodeMiss);
197        if let Some(stats) = &self.cache_stats {
198            stats.record_code_miss();
199        }
200    }
201
202    fn record_txpool_account_hit(&self) {
203        self.record_txpool_metric(CacheMetricKind::AccountHit);
204        if let Some(stats) = &self.cache_stats {
205            stats.record_txpool_snapshot_account_hit();
206        }
207    }
208
209    fn record_txpool_account_miss(&self) {
210        self.record_txpool_metric(CacheMetricKind::AccountMiss);
211        if let Some(stats) = &self.cache_stats {
212            stats.record_txpool_snapshot_account_miss();
213        }
214    }
215
216    fn record_txpool_storage_hit(&self) {
217        self.record_txpool_metric(CacheMetricKind::StorageHit);
218        if let Some(stats) = &self.cache_stats {
219            stats.record_txpool_snapshot_storage_hit();
220        }
221    }
222
223    fn record_txpool_storage_miss(&self) {
224        self.record_txpool_metric(CacheMetricKind::StorageMiss);
225        if let Some(stats) = &self.cache_stats {
226            stats.record_txpool_snapshot_storage_miss();
227        }
228    }
229
230    fn record_txpool_code_hit(&self) {
231        self.record_txpool_metric(CacheMetricKind::CodeHit);
232        if let Some(stats) = &self.cache_stats {
233            stats.record_txpool_snapshot_code_hit();
234        }
235    }
236
237    fn record_txpool_code_miss(&self) {
238        self.record_txpool_metric(CacheMetricKind::CodeMiss);
239        if let Some(stats) = &self.cache_stats {
240            stats.record_txpool_snapshot_code_miss();
241        }
242    }
243
244    #[inline]
245    fn record_metric(&self, kind: CacheMetricKind) {
246        if self.metrics.is_some() {
247            self.execution_metric_counts.record(kind);
248        }
249    }
250
251    #[inline]
252    fn record_txpool_metric(&self, kind: CacheMetricKind) {
253        if self.metrics.is_some() {
254            self.txpool_metric_counts.record(kind);
255        }
256    }
257
258    fn flush_buffered_metrics(&self) {
259        let execution_counts = self.execution_metric_counts.take();
260        let txpool_counts = self.txpool_metric_counts.take();
261        if execution_counts.is_empty() && txpool_counts.is_empty() {
262            return;
263        }
264
265        if let Some(metrics) = &self.metrics {
266            metrics.record_access_counts(execution_counts);
267            metrics.record_txpool_access_counts(txpool_counts);
268        }
269    }
270
271    const fn should_fill_on_miss(&self) -> bool {
272        matches!(self.fill_mode, CacheFillMode::FillOnMiss)
273    }
274}
275
276impl<S> Drop for CachedStateProvider<S> {
277    fn drop(&mut self) {
278        self.flush_buffered_metrics();
279    }
280}
281
282/// Whether cache misses should populate the shared execution cache.
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub enum CacheFillMode {
285    /// Only read existing cache entries.
286    LookupOnly,
287    /// Insert values loaded from the underlying provider.
288    FillOnMiss,
289}
290
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292enum CacheMetricKind {
293    AccountHit,
294    AccountMiss,
295    StorageHit,
296    StorageMiss,
297    CodeHit,
298    CodeMiss,
299}
300
301#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
302struct CacheMetricSnapshot {
303    account_hits: u64,
304    account_misses: u64,
305    storage_hits: u64,
306    storage_misses: u64,
307    code_hits: u64,
308    code_misses: u64,
309}
310
311impl CacheMetricSnapshot {
312    const fn is_empty(&self) -> bool {
313        self.account_hits == 0 &&
314            self.account_misses == 0 &&
315            self.storage_hits == 0 &&
316            self.storage_misses == 0 &&
317            self.code_hits == 0 &&
318            self.code_misses == 0
319    }
320}
321
322#[derive(Debug, Default)]
323struct CacheMetricCounts {
324    account_hits: Cell<u64>,
325    account_misses: Cell<u64>,
326    storage_hits: Cell<u64>,
327    storage_misses: Cell<u64>,
328    code_hits: Cell<u64>,
329    code_misses: Cell<u64>,
330}
331
332impl CacheMetricCounts {
333    const fn new() -> Self {
334        Self {
335            account_hits: Cell::new(0),
336            account_misses: Cell::new(0),
337            storage_hits: Cell::new(0),
338            storage_misses: Cell::new(0),
339            code_hits: Cell::new(0),
340            code_misses: Cell::new(0),
341        }
342    }
343
344    #[inline]
345    fn record(&self, kind: CacheMetricKind) {
346        let counter = match kind {
347            CacheMetricKind::AccountHit => &self.account_hits,
348            CacheMetricKind::AccountMiss => &self.account_misses,
349            CacheMetricKind::StorageHit => &self.storage_hits,
350            CacheMetricKind::StorageMiss => &self.storage_misses,
351            CacheMetricKind::CodeHit => &self.code_hits,
352            CacheMetricKind::CodeMiss => &self.code_misses,
353        };
354        counter.set(counter.get() + 1);
355    }
356
357    const fn take(&self) -> CacheMetricSnapshot {
358        CacheMetricSnapshot {
359            account_hits: self.account_hits.replace(0),
360            account_misses: self.account_misses.replace(0),
361            storage_hits: self.storage_hits.replace(0),
362            storage_misses: self.storage_misses.replace(0),
363            code_hits: self.code_hits.replace(0),
364            code_misses: self.code_misses.replace(0),
365        }
366    }
367}
368
369/// Represents the status of a key in the cache.
370#[derive(Debug, Clone, PartialEq, Eq)]
371pub enum CachedStatus<T> {
372    /// The key is not in the cache (or was invalidated). The value was recalculated.
373    NotCached(T),
374    /// The key exists in cache and has a specific value.
375    Cached(T),
376}
377
378/// The source that is using the execution cache.
379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380pub enum CachedStateMetricsSource {
381    /// Engine (validation).
382    Engine,
383    /// Payload builder.
384    Builder,
385    /// Tests.
386    #[cfg(any(test, feature = "test-utils"))]
387    Test,
388}
389
390impl fmt::Display for CachedStateMetricsSource {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        match self {
393            Self::Engine => f.write_str("engine"),
394            Self::Builder => f.write_str("builder"),
395            #[cfg(any(test, feature = "test-utils"))]
396            Self::Test => f.write_str("test"),
397        }
398    }
399}
400
401/// Metrics for the cached state provider, showing hits and misses for each cache tier.
402#[derive(Metrics, Clone)]
403#[metrics(scope = "sync.caching")]
404pub struct CachedStateMetrics {
405    /// Number of times a new execution cache was created
406    execution_cache_created_total: Counter,
407
408    /// Duration of execution cache creation in seconds
409    execution_cache_creation_duration_seconds: Histogram,
410
411    /// Execution-cache code hits
412    code_cache_hits: Gauge,
413
414    /// Execution-cache code misses
415    code_cache_misses: Gauge,
416
417    /// Execution-cache storage hits
418    storage_cache_hits: Gauge,
419
420    /// Execution-cache storage misses
421    storage_cache_misses: Gauge,
422
423    /// Execution-cache account hits
424    account_cache_hits: Gauge,
425
426    /// Execution-cache account misses
427    account_cache_misses: Gauge,
428
429    /// Txpool-prewarm snapshot code hits
430    txpool_snapshot_code_hits: Gauge,
431
432    /// Txpool-prewarm snapshot code misses
433    txpool_snapshot_code_misses: Gauge,
434
435    /// Txpool-prewarm snapshot storage hits
436    txpool_snapshot_storage_hits: Gauge,
437
438    /// Txpool-prewarm snapshot storage misses
439    txpool_snapshot_storage_misses: Gauge,
440
441    /// Txpool-prewarm snapshot account hits
442    txpool_snapshot_account_hits: Gauge,
443
444    /// Txpool-prewarm snapshot account misses
445    txpool_snapshot_account_misses: Gauge,
446}
447
448/// Metrics for shared execution cache state.
449#[derive(Metrics, Clone)]
450#[metrics(scope = "sync.caching")]
451pub struct CachedStateCacheMetrics {
452    /// Code cache size (number of entries)
453    code_cache_size: Gauge,
454
455    /// Code cache capacity (maximum entries)
456    code_cache_capacity: Gauge,
457
458    /// Code cache collisions (hash collisions causing eviction)
459    code_cache_collisions: Gauge,
460
461    /// Storage cache size (number of entries)
462    storage_cache_size: Gauge,
463
464    /// Storage cache capacity (maximum entries)
465    storage_cache_capacity: Gauge,
466
467    /// Storage cache collisions (hash collisions causing eviction)
468    storage_cache_collisions: Gauge,
469
470    /// Account cache size (number of entries)
471    account_cache_size: Gauge,
472
473    /// Account cache capacity (maximum entries)
474    account_cache_capacity: Gauge,
475
476    /// Account cache collisions (hash collisions causing eviction)
477    account_cache_collisions: Gauge,
478}
479
480impl CachedStateMetrics {
481    /// Sets all values to zero, indicating that a new block is being executed.
482    pub fn reset(&self) {
483        // code cache
484        self.code_cache_hits.set(0);
485        self.code_cache_misses.set(0);
486
487        // storage cache
488        self.storage_cache_hits.set(0);
489        self.storage_cache_misses.set(0);
490
491        // account cache
492        self.account_cache_hits.set(0);
493        self.account_cache_misses.set(0);
494
495        // txpool-prewarm code cache
496        self.txpool_snapshot_code_hits.set(0);
497        self.txpool_snapshot_code_misses.set(0);
498
499        // txpool-prewarm storage cache
500        self.txpool_snapshot_storage_hits.set(0);
501        self.txpool_snapshot_storage_misses.set(0);
502
503        // txpool-prewarm account cache
504        self.txpool_snapshot_account_hits.set(0);
505        self.txpool_snapshot_account_misses.set(0);
506    }
507
508    /// Returns a new zeroed-out instance of [`CachedStateMetrics`] with a `source` label
509    /// to distinguish between different callers (e.g., engine vs builder).
510    pub fn zeroed(source: CachedStateMetricsSource) -> Self {
511        let zeroed = Self::new_with_labels(&[("source", source.to_string())]);
512        zeroed.reset();
513        zeroed
514    }
515
516    fn record_access(&self, kind: CacheMetricKind, count: u64) {
517        match kind {
518            CacheMetricKind::AccountHit => self.account_cache_hits.increment(count as f64),
519            CacheMetricKind::AccountMiss => self.account_cache_misses.increment(count as f64),
520            CacheMetricKind::StorageHit => self.storage_cache_hits.increment(count as f64),
521            CacheMetricKind::StorageMiss => self.storage_cache_misses.increment(count as f64),
522            CacheMetricKind::CodeHit => self.code_cache_hits.increment(count as f64),
523            CacheMetricKind::CodeMiss => self.code_cache_misses.increment(count as f64),
524        }
525    }
526
527    fn record_access_counts(&self, counts: CacheMetricSnapshot) {
528        if counts.account_hits != 0 {
529            self.record_access(CacheMetricKind::AccountHit, counts.account_hits);
530        }
531        if counts.account_misses != 0 {
532            self.record_access(CacheMetricKind::AccountMiss, counts.account_misses);
533        }
534        if counts.storage_hits != 0 {
535            self.record_access(CacheMetricKind::StorageHit, counts.storage_hits);
536        }
537        if counts.storage_misses != 0 {
538            self.record_access(CacheMetricKind::StorageMiss, counts.storage_misses);
539        }
540        if counts.code_hits != 0 {
541            self.record_access(CacheMetricKind::CodeHit, counts.code_hits);
542        }
543        if counts.code_misses != 0 {
544            self.record_access(CacheMetricKind::CodeMiss, counts.code_misses);
545        }
546    }
547
548    fn record_txpool_access(&self, kind: CacheMetricKind, count: u64) {
549        match kind {
550            CacheMetricKind::AccountHit => {
551                self.txpool_snapshot_account_hits.increment(count as f64)
552            }
553            CacheMetricKind::AccountMiss => {
554                self.txpool_snapshot_account_misses.increment(count as f64)
555            }
556            CacheMetricKind::StorageHit => {
557                self.txpool_snapshot_storage_hits.increment(count as f64)
558            }
559            CacheMetricKind::StorageMiss => {
560                self.txpool_snapshot_storage_misses.increment(count as f64)
561            }
562            CacheMetricKind::CodeHit => self.txpool_snapshot_code_hits.increment(count as f64),
563            CacheMetricKind::CodeMiss => self.txpool_snapshot_code_misses.increment(count as f64),
564        }
565    }
566
567    fn record_txpool_access_counts(&self, counts: CacheMetricSnapshot) {
568        if counts.account_hits != 0 {
569            self.record_txpool_access(CacheMetricKind::AccountHit, counts.account_hits);
570        }
571        if counts.account_misses != 0 {
572            self.record_txpool_access(CacheMetricKind::AccountMiss, counts.account_misses);
573        }
574        if counts.storage_hits != 0 {
575            self.record_txpool_access(CacheMetricKind::StorageHit, counts.storage_hits);
576        }
577        if counts.storage_misses != 0 {
578            self.record_txpool_access(CacheMetricKind::StorageMiss, counts.storage_misses);
579        }
580        if counts.code_hits != 0 {
581            self.record_txpool_access(CacheMetricKind::CodeHit, counts.code_hits);
582        }
583        if counts.code_misses != 0 {
584            self.record_txpool_access(CacheMetricKind::CodeMiss, counts.code_misses);
585        }
586    }
587
588    /// Records a new execution cache creation with its duration.
589    pub fn record_cache_creation(&self, duration: Duration) {
590        self.execution_cache_created_total.increment(1);
591        self.execution_cache_creation_duration_seconds.record(duration.as_secs_f64());
592    }
593}
594
595/// Cache hit/miss statistics for detailed block logging.
596#[derive(Debug, Default)]
597pub struct CacheStats {
598    /// Execution-cache account hits
599    account_hits: AtomicUsize,
600    /// Execution-cache account misses
601    account_misses: AtomicUsize,
602    /// Execution-cache storage hits
603    storage_hits: AtomicUsize,
604    /// Execution-cache storage misses
605    storage_misses: AtomicUsize,
606    /// Execution-cache code hits
607    code_hits: AtomicUsize,
608    /// Execution-cache code misses
609    code_misses: AtomicUsize,
610    /// Txpool-prewarm snapshot account hits
611    txpool_snapshot_account_hits: AtomicUsize,
612    /// Txpool-prewarm snapshot account misses
613    txpool_snapshot_account_misses: AtomicUsize,
614    /// Txpool-prewarm snapshot storage hits
615    txpool_snapshot_storage_hits: AtomicUsize,
616    /// Txpool-prewarm snapshot storage misses
617    txpool_snapshot_storage_misses: AtomicUsize,
618    /// Txpool-prewarm snapshot code hits
619    txpool_snapshot_code_hits: AtomicUsize,
620    /// Txpool-prewarm snapshot code misses
621    txpool_snapshot_code_misses: AtomicUsize,
622}
623
624impl CacheStats {
625    /// Records an account cache hit.
626    pub fn record_account_hit(&self) {
627        self.account_hits.fetch_add(1, Ordering::Relaxed);
628    }
629
630    /// Records an account cache miss.
631    pub fn record_account_miss(&self) {
632        self.account_misses.fetch_add(1, Ordering::Relaxed);
633    }
634
635    /// Returns the number of account cache hits.
636    pub fn account_hits(&self) -> usize {
637        self.account_hits.load(Ordering::Relaxed)
638    }
639
640    /// Returns the number of account cache misses.
641    pub fn account_misses(&self) -> usize {
642        self.account_misses.load(Ordering::Relaxed)
643    }
644
645    /// Records a storage cache hit.
646    pub fn record_storage_hit(&self) {
647        self.storage_hits.fetch_add(1, Ordering::Relaxed);
648    }
649
650    /// Records a storage cache miss.
651    pub fn record_storage_miss(&self) {
652        self.storage_misses.fetch_add(1, Ordering::Relaxed);
653    }
654
655    /// Returns the number of storage cache hits.
656    pub fn storage_hits(&self) -> usize {
657        self.storage_hits.load(Ordering::Relaxed)
658    }
659
660    /// Returns the number of storage cache misses.
661    pub fn storage_misses(&self) -> usize {
662        self.storage_misses.load(Ordering::Relaxed)
663    }
664
665    /// Records a code cache hit.
666    pub fn record_code_hit(&self) {
667        self.code_hits.fetch_add(1, Ordering::Relaxed);
668    }
669
670    /// Records a code cache miss.
671    pub fn record_code_miss(&self) {
672        self.code_misses.fetch_add(1, Ordering::Relaxed);
673    }
674
675    /// Returns the number of code cache hits.
676    pub fn code_hits(&self) -> usize {
677        self.code_hits.load(Ordering::Relaxed)
678    }
679
680    /// Returns the number of code cache misses.
681    pub fn code_misses(&self) -> usize {
682        self.code_misses.load(Ordering::Relaxed)
683    }
684
685    /// Records a txpool-prewarm snapshot account hit.
686    pub fn record_txpool_snapshot_account_hit(&self) {
687        self.txpool_snapshot_account_hits.fetch_add(1, Ordering::Relaxed);
688    }
689
690    /// Records a txpool-prewarm snapshot account miss.
691    pub fn record_txpool_snapshot_account_miss(&self) {
692        self.txpool_snapshot_account_misses.fetch_add(1, Ordering::Relaxed);
693    }
694
695    /// Returns the number of txpool-prewarm snapshot account hits.
696    pub fn txpool_snapshot_account_hits(&self) -> usize {
697        self.txpool_snapshot_account_hits.load(Ordering::Relaxed)
698    }
699
700    /// Returns the number of txpool-prewarm snapshot account misses.
701    pub fn txpool_snapshot_account_misses(&self) -> usize {
702        self.txpool_snapshot_account_misses.load(Ordering::Relaxed)
703    }
704
705    /// Records a txpool-prewarm snapshot storage hit.
706    pub fn record_txpool_snapshot_storage_hit(&self) {
707        self.txpool_snapshot_storage_hits.fetch_add(1, Ordering::Relaxed);
708    }
709
710    /// Records a txpool-prewarm snapshot storage miss.
711    pub fn record_txpool_snapshot_storage_miss(&self) {
712        self.txpool_snapshot_storage_misses.fetch_add(1, Ordering::Relaxed);
713    }
714
715    /// Returns the number of txpool-prewarm snapshot storage hits.
716    pub fn txpool_snapshot_storage_hits(&self) -> usize {
717        self.txpool_snapshot_storage_hits.load(Ordering::Relaxed)
718    }
719
720    /// Returns the number of txpool-prewarm snapshot storage misses.
721    pub fn txpool_snapshot_storage_misses(&self) -> usize {
722        self.txpool_snapshot_storage_misses.load(Ordering::Relaxed)
723    }
724
725    /// Records a txpool-prewarm snapshot code hit.
726    pub fn record_txpool_snapshot_code_hit(&self) {
727        self.txpool_snapshot_code_hits.fetch_add(1, Ordering::Relaxed);
728    }
729
730    /// Records a txpool-prewarm snapshot code miss.
731    pub fn record_txpool_snapshot_code_miss(&self) {
732        self.txpool_snapshot_code_misses.fetch_add(1, Ordering::Relaxed);
733    }
734
735    /// Returns the number of txpool-prewarm snapshot code hits.
736    pub fn txpool_snapshot_code_hits(&self) -> usize {
737        self.txpool_snapshot_code_hits.load(Ordering::Relaxed)
738    }
739
740    /// Returns the number of txpool-prewarm snapshot code misses.
741    pub fn txpool_snapshot_code_misses(&self) -> usize {
742        self.txpool_snapshot_code_misses.load(Ordering::Relaxed)
743    }
744}
745
746/// A stats handler for fixed-cache that tracks collisions and size.
747///
748/// Note: Hits and misses are tracked directly by the [`CachedStateProvider`] via
749/// [`CachedStateMetrics`], not here. The stats handler is used for:
750/// - Collision detection (hash collisions causing eviction of a different key)
751/// - Size tracking
752///
753/// ## Size Tracking
754///
755/// Size is tracked via `on_insert` and `on_remove` callbacks:
756/// - `on_insert`: increment size only when inserting into an empty bucket (no eviction)
757/// - `on_remove`: always decrement size
758///
759/// Collisions (evicting a different key) don't change size since they replace an existing entry.
760#[derive(Debug)]
761pub struct CacheStatsHandler {
762    collisions: AtomicU64,
763    size: AtomicUsize,
764    capacity: usize,
765}
766
767impl CacheStatsHandler {
768    /// Creates a new stats handler with all counters initialized to zero.
769    pub const fn new(capacity: usize) -> Self {
770        Self { collisions: AtomicU64::new(0), size: AtomicUsize::new(0), capacity }
771    }
772
773    /// Returns the number of cache collisions.
774    pub fn collisions(&self) -> u64 {
775        self.collisions.load(Ordering::Relaxed)
776    }
777
778    /// Returns the current size (number of entries).
779    pub fn size(&self) -> usize {
780        self.size.load(Ordering::Relaxed)
781    }
782
783    /// Returns the capacity (maximum number of entries).
784    pub const fn capacity(&self) -> usize {
785        self.capacity
786    }
787
788    /// Increments the size counter. Called on cache insert.
789    pub fn increment_size(&self) {
790        let _ = self.size.fetch_add(1, Ordering::Relaxed);
791    }
792
793    /// Decrements the size counter. Called on cache remove.
794    pub fn decrement_size(&self) {
795        let _ = self.size.fetch_sub(1, Ordering::Relaxed);
796    }
797
798    /// Resets size to zero. Called on cache clear.
799    pub fn reset_size(&self) {
800        self.size.store(0, Ordering::Relaxed);
801    }
802
803    /// Resets collision counter to zero (but not size).
804    pub fn reset_stats(&self) {
805        self.collisions.store(0, Ordering::Relaxed);
806    }
807}
808
809impl<K: PartialEq, V> StatsHandler<K, V> for CacheStatsHandler {
810    fn on_hit(&self, _key: &K, _value: &V) {}
811
812    fn on_miss(&self, _key: AnyRef<'_>) {}
813
814    fn on_insert(&self, key: &K, _value: &V, evicted: Option<(&K, &V)>) {
815        match evicted {
816            None => {
817                // Inserting into an empty bucket
818                self.increment_size();
819            }
820            Some((evicted_key, _)) if evicted_key != key => {
821                // Collision: evicting a different key
822                self.collisions.fetch_add(1, Ordering::Relaxed);
823            }
824            Some(_) => {
825                // Updating the same key, size unchanged
826            }
827        }
828    }
829
830    fn on_remove(&self, _key: &K, _value: &V) {
831        self.decrement_size();
832    }
833}
834
835#[inline]
836fn nonzero_storage_value(value: StorageValue) -> Option<StorageValue> {
837    (!value.is_zero()).then_some(value)
838}
839
840impl<S: EvmStateProvider> EvmStateProvider for CachedStateProvider<S> {
841    fn basic_account(&self, address: &Address) -> ProviderResult<Option<Account>> {
842        if let Some(snapshot) = &self.txpool_snapshot {
843            if let Some(account) = snapshot.account(address) {
844                self.record_txpool_account_hit();
845                return Ok(account)
846            }
847            self.record_txpool_account_miss();
848        }
849
850        if self.should_fill_on_miss() {
851            match self.caches.get_or_try_insert_account_with(*address, || {
852                self.state_provider.basic_account(address)
853            })? {
854                CachedStatus::NotCached(value) => {
855                    self.record_account_miss();
856                    Ok(value)
857                }
858                CachedStatus::Cached(value) => {
859                    self.record_account_hit();
860                    Ok(value)
861                }
862            }
863        } else if let Some(account) = self.caches.0.account_cache.get(address) {
864            self.record_account_hit();
865            Ok(account)
866        } else {
867            self.record_account_miss();
868            self.state_provider.basic_account(address)
869        }
870    }
871
872    fn storage(
873        &self,
874        account: Address,
875        storage_key: StorageKey,
876    ) -> ProviderResult<Option<StorageValue>> {
877        if let Some(snapshot) = &self.txpool_snapshot {
878            if let Some(value) = snapshot.storage(account, storage_key) {
879                self.record_txpool_storage_hit();
880                return Ok(nonzero_storage_value(value))
881            }
882            self.record_txpool_storage_miss();
883        }
884
885        if self.should_fill_on_miss() {
886            match self.caches.get_or_try_insert_storage_with(account, storage_key, || {
887                self.state_provider.storage(account, storage_key).map(Option::unwrap_or_default)
888            })? {
889                CachedStatus::NotCached(value) => {
890                    self.record_storage_miss();
891                    Ok(nonzero_storage_value(value))
892                }
893                CachedStatus::Cached(value) => {
894                    self.record_storage_hit();
895                    Ok(nonzero_storage_value(value))
896                }
897            }
898        } else if let Some(value) = self.caches.0.storage_cache.get(&(account, storage_key)) {
899            self.record_storage_hit();
900            Ok(nonzero_storage_value(value))
901        } else {
902            self.record_storage_miss();
903            self.state_provider.storage(account, storage_key)
904        }
905    }
906
907    fn bytecode_by_hash(&self, code_hash: &B256) -> ProviderResult<Option<Bytecode>> {
908        if let Some(snapshot) = &self.txpool_snapshot {
909            if let Some(code) = snapshot.bytecode(code_hash) {
910                self.record_txpool_code_hit();
911                return Ok(code)
912            }
913            self.record_txpool_code_miss();
914        }
915
916        if self.should_fill_on_miss() {
917            match self.caches.get_or_try_insert_code_with(*code_hash, || {
918                self.state_provider.bytecode_by_hash(code_hash)
919            })? {
920                CachedStatus::NotCached(code) => {
921                    self.record_code_miss();
922                    Ok(code)
923                }
924                CachedStatus::Cached(code) => {
925                    self.record_code_hit();
926                    Ok(code)
927                }
928            }
929        } else if let Some(code) = self.caches.0.code_cache.get(code_hash) {
930            self.record_code_hit();
931            Ok(code)
932        } else {
933            self.record_code_miss();
934            self.state_provider.bytecode_by_hash(code_hash)
935        }
936    }
937
938    fn block_hash(&self, number: alloy_primitives::BlockNumber) -> ProviderResult<Option<B256>> {
939        self.state_provider.block_hash(number)
940    }
941}
942
943/// Execution cache used during block processing.
944///
945/// Optimizes state access by maintaining in-memory copies of frequently accessed
946/// accounts, storage slots, and bytecode. Works in conjunction with prewarming
947/// to reduce database I/O during block execution.
948///
949/// ## Storage Invalidation
950///
951/// Since EIP-6780, SELFDESTRUCT only works within the same transaction where the
952/// contract was created, so we don't need to handle clearing the storage.
953#[derive(Debug, Clone)]
954pub struct ExecutionCache(Arc<ExecutionCacheInner>);
955
956/// Inner state of the [`ExecutionCache`], wrapped in a single [`Arc`].
957#[derive(Debug)]
958struct ExecutionCacheInner {
959    /// Cache for contract bytecode, keyed by code hash.
960    code_cache: FixedCache<B256, Option<Bytecode>, FbBuildHasher<32>>,
961
962    /// Flat storage cache: maps `(Address, StorageKey)` to storage value.
963    storage_cache: FixedCache<(Address, StorageKey), StorageValue>,
964
965    /// Cache for basic account information (nonce, balance, code hash).
966    account_cache: FixedCache<Address, Option<Account>, FbBuildHasher<20>>,
967
968    /// Stats handler for the code cache (shared with the cache via [`Stats`]).
969    code_stats: Arc<CacheStatsHandler>,
970
971    /// Stats handler for the storage cache (shared with the cache via [`Stats`]).
972    storage_stats: Arc<CacheStatsHandler>,
973
974    /// Stats handler for the account cache (shared with the cache via [`Stats`]).
975    account_stats: Arc<CacheStatsHandler>,
976
977    /// One-time notification when SELFDESTRUCT is encountered
978    selfdestruct_encountered: Once,
979}
980
981impl ExecutionCache {
982    /// Minimum cache size required when epochs are enabled.
983    /// With EPOCHS=true, fixed-cache requires 12 bottom bits to be zero (2 needed + 10 epoch).
984    const MIN_CACHE_SIZE_WITH_EPOCHS: usize = 1 << 12; // 4096
985
986    /// Converts a byte size to number of cache entries, rounding down to a power of two.
987    ///
988    /// Fixed-cache requires power-of-two sizes for efficient indexing.
989    /// With epochs enabled, the minimum size is 4096 entries.
990    pub const fn bytes_to_entries(size_bytes: usize, entry_size: usize) -> usize {
991        let entries = size_bytes / entry_size;
992        // Round down to nearest power of two
993        let rounded = if entries == 0 { 1 } else { (entries + 1).next_power_of_two() >> 1 };
994        // Ensure minimum size for epoch tracking
995        if rounded < Self::MIN_CACHE_SIZE_WITH_EPOCHS {
996            Self::MIN_CACHE_SIZE_WITH_EPOCHS
997        } else {
998            rounded
999        }
1000    }
1001
1002    /// Build an [`ExecutionCache`] struct, so that execution caches can be easily cloned.
1003    pub fn new(total_cache_size: usize) -> Self {
1004        let code_cache_size = (total_cache_size * 556) / 10000; // 5.56% of total
1005        let storage_cache_size = (total_cache_size * 8888) / 10000; // 88.88% of total
1006        let account_cache_size = (total_cache_size * 556) / 10000; // 5.56% of total
1007
1008        let code_capacity = Self::bytes_to_entries(code_cache_size, CODE_CACHE_ENTRY_SIZE);
1009        let storage_capacity = Self::bytes_to_entries(storage_cache_size, STORAGE_CACHE_ENTRY_SIZE);
1010        let account_capacity = Self::bytes_to_entries(account_cache_size, ACCOUNT_CACHE_ENTRY_SIZE);
1011
1012        let code_stats = Arc::new(CacheStatsHandler::new(code_capacity));
1013        let storage_stats = Arc::new(CacheStatsHandler::new(storage_capacity));
1014        let account_stats = Arc::new(CacheStatsHandler::new(account_capacity));
1015
1016        Self(Arc::new(ExecutionCacheInner {
1017            code_cache: FixedCache::new(code_capacity, FbBuildHasher::<32>::default())
1018                .with_stats(Some(Stats::new(code_stats.clone()))),
1019            storage_cache: FixedCache::new(storage_capacity, DefaultHashBuilder::default())
1020                .with_stats(Some(Stats::new(storage_stats.clone()))),
1021            account_cache: FixedCache::new(account_capacity, FbBuildHasher::<20>::default())
1022                .with_stats(Some(Stats::new(account_stats.clone()))),
1023            code_stats,
1024            storage_stats,
1025            account_stats,
1026            selfdestruct_encountered: Once::new(),
1027        }))
1028    }
1029
1030    /// Returns the number of active handles to the shared cache.
1031    fn usage_count(&self) -> usize {
1032        Arc::strong_count(&self.0)
1033    }
1034
1035    /// Gets code from cache, or inserts using the provided function.
1036    pub fn get_or_try_insert_code_with<E>(
1037        &self,
1038        hash: B256,
1039        f: impl FnOnce() -> Result<Option<Bytecode>, E>,
1040    ) -> Result<CachedStatus<Option<Bytecode>>, E> {
1041        let mut miss = false;
1042        let result = self.0.code_cache.get_or_try_insert_with(hash, |_| {
1043            miss = true;
1044            f()
1045        })?;
1046
1047        if miss {
1048            Ok(CachedStatus::NotCached(result))
1049        } else {
1050            Ok(CachedStatus::Cached(result))
1051        }
1052    }
1053
1054    /// Gets storage from cache, or inserts using the provided function.
1055    pub fn get_or_try_insert_storage_with<E>(
1056        &self,
1057        address: Address,
1058        key: StorageKey,
1059        f: impl FnOnce() -> Result<StorageValue, E>,
1060    ) -> Result<CachedStatus<StorageValue>, E> {
1061        let mut miss = false;
1062        let result = self.0.storage_cache.get_or_try_insert_with((address, key), |_| {
1063            miss = true;
1064            f()
1065        })?;
1066
1067        if miss {
1068            Ok(CachedStatus::NotCached(result))
1069        } else {
1070            Ok(CachedStatus::Cached(result))
1071        }
1072    }
1073
1074    /// Gets account from cache, or inserts using the provided function.
1075    pub fn get_or_try_insert_account_with<E>(
1076        &self,
1077        address: Address,
1078        f: impl FnOnce() -> Result<Option<Account>, E>,
1079    ) -> Result<CachedStatus<Option<Account>>, E> {
1080        let mut miss = false;
1081        let result = self.0.account_cache.get_or_try_insert_with(address, |_| {
1082            miss = true;
1083            f()
1084        })?;
1085
1086        if miss {
1087            Ok(CachedStatus::NotCached(result))
1088        } else {
1089            Ok(CachedStatus::Cached(result))
1090        }
1091    }
1092
1093    /// Insert storage value into cache.
1094    pub fn insert_storage(&self, address: Address, key: StorageKey, value: Option<StorageValue>) {
1095        self.0.storage_cache.insert((address, key), value.unwrap_or_default());
1096    }
1097
1098    /// Insert code into cache.
1099    pub fn insert_code(&self, hash: B256, code: Option<Bytecode>) {
1100        self.0.code_cache.insert(hash, code);
1101    }
1102
1103    /// Insert account into cache.
1104    pub fn insert_account(&self, address: Address, account: Option<Account>) {
1105        self.0.account_cache.insert(address, account);
1106    }
1107
1108    /// Inserts the post-execution state changes into the cache.
1109    ///
1110    /// This method is called after transaction execution to update the cache with
1111    /// the touched and modified state. The insertion order is critical:
1112    ///
1113    /// 1. Bytecodes: Insert contract code first
1114    /// 2. Storage slots: Update storage values for each account
1115    /// 3. Accounts: Update account info (nonce, balance, code hash)
1116    ///
1117    /// ## Why This Order Matters
1118    ///
1119    /// Account information references bytecode via code hash. If we update accounts
1120    /// before bytecode, we might create cache entries pointing to non-existent code.
1121    /// The current order ensures cache consistency.
1122    ///
1123    /// ## Error Handling
1124    ///
1125    /// Returns an error if the state updates are inconsistent and should be discarded.
1126    #[instrument(level = "debug", target = "engine::caching", skip_all)]
1127    #[expect(clippy::result_unit_err)]
1128    pub fn insert_state(&self, state_updates: &BundleState) -> Result<(), ()> {
1129        let _enter =
1130            debug_span!(target: "engine::tree", "contracts", len = state_updates.contracts.len())
1131                .entered();
1132        // Insert bytecodes
1133        for (code_hash, bytecode) in &state_updates.contracts {
1134            self.insert_code(*code_hash, Some(Bytecode(bytecode.clone())));
1135        }
1136        drop(_enter);
1137
1138        let _enter = debug_span!(
1139            target: "engine::tree",
1140            "accounts",
1141            accounts = state_updates.state.len(),
1142            storages =
1143                state_updates.state.values().map(|account| account.storage.len()).sum::<usize>()
1144        )
1145        .entered();
1146        for (addr, account) in &state_updates.state {
1147            // If the account was not modified, as in not changed and not destroyed, then we have
1148            // nothing to do w.r.t. this particular account and can move on
1149            if account.status.is_not_modified() {
1150                continue
1151            }
1152
1153            // If the original account had code (was a contract), we must clear the entire cache
1154            // because we can't efficiently invalidate all storage slots for a single address.
1155            // This should only happen on pre-Dencun networks.
1156            //
1157            // If the original account had no code (was an EOA or a not yet deployed contract), a
1158            // destroyed account can be removed from the cache. A re-created account still has
1159            // post-block storage and info that must be written below.
1160            if account.was_destroyed() {
1161                let had_code =
1162                    account.original_info.as_ref().is_some_and(|info| !info.is_empty_code_hash());
1163                if had_code {
1164                    self.0.selfdestruct_encountered.call_once(|| {
1165                        warn!(
1166                            target: "engine::caching",
1167                            address = ?addr,
1168                            info = ?account.info,
1169                            original_info = ?account.original_info,
1170                            "Encountered an inter-transaction SELFDESTRUCT that reset the storage cache. Are you running a pre-Dencun network?"
1171                        );
1172                    });
1173                    self.clear();
1174                    return Ok(())
1175                }
1176
1177                if account.info.is_none() {
1178                    self.0.account_cache.remove(addr);
1179                    continue;
1180                }
1181            }
1182
1183            // If we have an account that was modified, but it has a `None` account info, some wild
1184            // error has occurred because this state should be unrepresentable. An account with
1185            // `None` current info, should be destroyed.
1186            let Some(ref account_info) = account.info else {
1187                trace!(target: "engine::caching", ?account, "Account with None account info found in state updates");
1188                return Err(())
1189            };
1190
1191            // Now we iterate over all storage and make updates to the cached storage values
1192            for (key, slot) in &account.storage {
1193                self.insert_storage(*addr, (*key).into(), Some(slot.present_value));
1194            }
1195
1196            // Insert will update if present, so we just use the new account info as the new value
1197            // for the account cache
1198            self.insert_account(*addr, Some(Account::from(account_info)));
1199        }
1200
1201        Ok(())
1202    }
1203
1204    /// Clears storage and account caches, resetting them to empty state.
1205    ///
1206    /// We do not clear the bytecodes cache, because its mapping can never change, as it's
1207    /// `keccak256(bytecode) => bytecode`.
1208    pub fn clear(&self) {
1209        self.0.storage_cache.clear();
1210        self.0.account_cache.clear();
1211
1212        self.0.storage_stats.reset_size();
1213        self.0.account_stats.reset_size();
1214    }
1215
1216    /// Updates the provided metrics with the current stats from the cache's stats handlers,
1217    /// and resets the hit/miss/collision counters.
1218    pub fn update_metrics(&self, metrics: &CachedStateCacheMetrics) {
1219        metrics.code_cache_size.set(self.0.code_stats.size() as f64);
1220        metrics.code_cache_capacity.set(self.0.code_stats.capacity() as f64);
1221        metrics.code_cache_collisions.set(self.0.code_stats.collisions() as f64);
1222        self.0.code_stats.reset_stats();
1223
1224        metrics.storage_cache_size.set(self.0.storage_stats.size() as f64);
1225        metrics.storage_cache_capacity.set(self.0.storage_stats.capacity() as f64);
1226        metrics.storage_cache_collisions.set(self.0.storage_stats.collisions() as f64);
1227        self.0.storage_stats.reset_stats();
1228
1229        metrics.account_cache_size.set(self.0.account_stats.size() as f64);
1230        metrics.account_cache_capacity.set(self.0.account_stats.capacity() as f64);
1231        metrics.account_cache_collisions.set(self.0.account_stats.collisions() as f64);
1232        self.0.account_stats.reset_stats();
1233    }
1234}
1235
1236/// A saved cache that has been used for executing a specific block, which has been updated for its
1237/// execution.
1238#[derive(Debug, Clone)]
1239pub struct SavedCache {
1240    /// The hash of the block these caches were used to execute.
1241    hash: B256,
1242
1243    /// The caches used for the provider.
1244    caches: ExecutionCache,
1245}
1246
1247impl SavedCache {
1248    /// Creates a new instance with the internals
1249    pub const fn new(hash: B256, caches: ExecutionCache) -> Self {
1250        Self { hash, caches }
1251    }
1252
1253    /// Returns the hash for this cache
1254    pub const fn executed_block_hash(&self) -> B256 {
1255        self.hash
1256    }
1257
1258    /// Returns true if the cache is available for use (no other tasks are currently using it).
1259    pub fn is_available(&self) -> bool {
1260        self.caches.usage_count() == 1
1261    }
1262
1263    /// Returns the current number of active handles to the shared cache.
1264    pub fn usage_count(&self) -> usize {
1265        self.caches.usage_count()
1266    }
1267
1268    /// Returns the [`ExecutionCache`] belonging to the tracked hash.
1269    pub const fn cache(&self) -> &ExecutionCache {
1270        &self.caches
1271    }
1272
1273    /// Consumes the saved cache and returns its [`ExecutionCache`].
1274    pub fn into_cache(self) -> ExecutionCache {
1275        self.caches
1276    }
1277
1278    /// Returns whether `self` and `other` refer to the same [`ExecutionCache`] data,
1279    /// regardless of their block hashes.
1280    pub fn shares_cache_with(&self, other: &Self) -> bool {
1281        Arc::ptr_eq(&self.caches.0, &other.caches.0)
1282    }
1283
1284    /// Updates the cache metrics (size/capacity/collisions) from the stats handlers.
1285    pub fn update_metrics(&self, metrics: Option<&CachedStateCacheMetrics>) {
1286        if let Some(metrics) = metrics {
1287            self.caches.update_metrics(metrics);
1288        }
1289    }
1290
1291    /// Clears all caches, resetting them to empty state,
1292    /// and updates the hash of the block this cache belongs to.
1293    pub fn clear_with_hash(&mut self, hash: B256) {
1294        self.hash = hash;
1295        self.caches.clear();
1296    }
1297}
1298
1299#[cfg(any(test, feature = "test-utils"))]
1300impl SavedCache {
1301    /// Clones the cache handle that acts as the availability guard.
1302    pub fn clone_guard_for_test(&self) -> ExecutionCache {
1303        self.caches.clone()
1304    }
1305}
1306
1307#[cfg(test)]
1308mod tests {
1309    use super::*;
1310    use alloy_primitives::{map::HashMap, U256};
1311    use evm2::evm::AccountInfo;
1312    use reth_provider::test_utils::{ExtendedAccount, MockEthProvider};
1313    use reth_storage_api::StateProvider;
1314    use reth_trie_common::bundle_state::{AccountStatus, BundleAccount, StorageSlot};
1315
1316    #[test]
1317    fn test_empty_storage_cached_state_provider() {
1318        let address = Address::random();
1319        let storage_key = StorageKey::random();
1320        let account = ExtendedAccount::new(0, U256::ZERO);
1321
1322        let provider = MockEthProvider::default();
1323        provider.extend_accounts(vec![(address, account)]);
1324
1325        let caches = ExecutionCache::new(1000);
1326        let state_provider = CachedStateProvider::new(
1327            provider.into_evm_state_provider(),
1328            caches,
1329            Some(CachedStateMetrics::zeroed(CachedStateMetricsSource::Test)),
1330        );
1331
1332        let res = state_provider.storage(address, storage_key);
1333        assert!(res.is_ok());
1334        assert_eq!(res.unwrap(), None);
1335    }
1336
1337    #[test]
1338    fn test_uncached_storage_cached_state_provider() {
1339        let address = Address::random();
1340        let storage_key = StorageKey::random();
1341        let storage_value = U256::ONE;
1342        let account =
1343            ExtendedAccount::new(0, U256::ZERO).extend_storage(vec![(storage_key, storage_value)]);
1344
1345        let provider = MockEthProvider::default();
1346        provider.extend_accounts(vec![(address, account)]);
1347
1348        let caches = ExecutionCache::new(1000);
1349        let state_provider = CachedStateProvider::new(
1350            provider.into_evm_state_provider(),
1351            caches,
1352            Some(CachedStateMetrics::zeroed(CachedStateMetricsSource::Test)),
1353        );
1354
1355        let res = state_provider.storage(address, storage_key);
1356        assert!(res.is_ok());
1357        assert_eq!(res.unwrap(), Some(storage_value));
1358    }
1359
1360    #[test]
1361    fn test_get_storage_populated() {
1362        let address = Address::random();
1363        let storage_key = StorageKey::random();
1364        let storage_value = U256::ONE;
1365
1366        let caches = ExecutionCache::new(1000);
1367        caches.insert_storage(address, storage_key, Some(storage_value));
1368
1369        let result = caches
1370            .get_or_try_insert_storage_with(address, storage_key, || Ok::<_, ()>(U256::from(999)));
1371        assert_eq!(result.unwrap(), CachedStatus::Cached(storage_value));
1372    }
1373
1374    #[test]
1375    fn test_get_storage_empty() {
1376        let address = Address::random();
1377        let storage_key = StorageKey::random();
1378
1379        let caches = ExecutionCache::new(1000);
1380        caches.insert_storage(address, storage_key, None);
1381
1382        let result = caches
1383            .get_or_try_insert_storage_with(address, storage_key, || Ok::<_, ()>(U256::from(999)));
1384        assert_eq!(result.unwrap(), CachedStatus::Cached(U256::ZERO));
1385    }
1386
1387    #[test]
1388    fn test_saved_cache_is_available() {
1389        let execution_cache = ExecutionCache::new(1000);
1390        let cache = SavedCache::new(B256::ZERO, execution_cache);
1391
1392        assert!(cache.is_available(), "Cache should be available initially");
1393
1394        let _cache = cache.clone_guard_for_test();
1395
1396        assert!(!cache.is_available(), "Cache should not be available with active handle");
1397    }
1398
1399    #[test]
1400    fn test_saved_cache_multiple_references() {
1401        let execution_cache = ExecutionCache::new(1000);
1402        let cache = SavedCache::new(B256::repeat_byte(2u8), execution_cache);
1403
1404        let cache1 = cache.clone_guard_for_test();
1405        let cache2 = cache.clone_guard_for_test();
1406        let cache3 = cache1.clone();
1407
1408        assert!(!cache.is_available());
1409
1410        drop(cache1);
1411        assert!(!cache.is_available());
1412
1413        drop(cache2);
1414        assert!(!cache.is_available());
1415
1416        drop(cache3);
1417        assert!(cache.is_available());
1418    }
1419
1420    #[test]
1421    fn test_insert_state_destroyed_account_with_code_clears_cache() {
1422        let caches = ExecutionCache::new(1000);
1423
1424        // Pre-populate caches with some data
1425        let addr1 = Address::random();
1426        let addr2 = Address::random();
1427        let storage_key = StorageKey::random();
1428        caches.insert_account(addr1, Some(Account::default()));
1429        caches.insert_account(addr2, Some(Account::default()));
1430        caches.insert_storage(addr1, storage_key, Some(U256::from(42)));
1431
1432        // Verify caches are populated
1433        assert!(caches.0.account_cache.get(&addr1).is_some());
1434        assert!(caches.0.account_cache.get(&addr2).is_some());
1435        assert!(caches.0.storage_cache.get(&(addr1, storage_key)).is_some());
1436
1437        let bundle = BundleState {
1438            // BundleState with a destroyed contract (had code)
1439            state: HashMap::from_iter([(
1440                Address::random(),
1441                BundleAccount::new(
1442                    Some(AccountInfo {
1443                        nonce: 1,
1444                        code_hash: B256::random(), // Non-empty code hash
1445                        code: None,
1446                        ..Default::default()
1447                    }),
1448                    None, // Destroyed, so no current info
1449                    Default::default(),
1450                    AccountStatus::Destroyed,
1451                ),
1452            )]),
1453            contracts: Default::default(),
1454            reverts: Default::default(),
1455            state_size: 0,
1456            reverts_size: 0,
1457        };
1458
1459        // Insert state should clear all caches because a contract was destroyed
1460        let result = caches.insert_state(&bundle);
1461        assert!(result.is_ok());
1462
1463        // Verify all caches were cleared
1464        assert!(caches.0.account_cache.get(&addr1).is_none());
1465        assert!(caches.0.account_cache.get(&addr2).is_none());
1466        assert!(caches.0.storage_cache.get(&(addr1, storage_key)).is_none());
1467    }
1468
1469    #[test]
1470    fn test_insert_state_destroyed_account_without_code_removes_only_account() {
1471        let caches = ExecutionCache::new(1000);
1472
1473        // Pre-populate caches with some data
1474        let addr1 = Address::random();
1475        let addr2 = Address::random();
1476        let storage_key = StorageKey::random();
1477        caches.insert_account(addr1, Some(Account::default()));
1478        caches.insert_account(addr2, Some(Account::default()));
1479        caches.insert_storage(addr1, storage_key, Some(U256::from(42)));
1480
1481        let bundle = BundleState {
1482            // BundleState with a destroyed EOA (no code)
1483            state: HashMap::from_iter([(
1484                addr1,
1485                BundleAccount::new(
1486                    Some(AccountInfo {
1487                        balance: U256::from(100),
1488                        nonce: 1,
1489                        code_hash: alloy_primitives::KECCAK256_EMPTY, // Empty code hash = EOA
1490                        code: None,
1491                        ..Default::default()
1492                    }),
1493                    None, // Destroyed
1494                    Default::default(),
1495                    AccountStatus::Destroyed,
1496                ),
1497            )]),
1498            contracts: Default::default(),
1499            reverts: Default::default(),
1500            state_size: 0,
1501            reverts_size: 0,
1502        };
1503
1504        // Insert state should only remove the destroyed account
1505        assert!(caches.insert_state(&bundle).is_ok());
1506
1507        // Verify only addr1 was removed, other data is still present
1508        assert!(caches.0.account_cache.get(&addr1).is_none());
1509        assert!(caches.0.account_cache.get(&addr2).is_some());
1510        assert!(caches.0.storage_cache.get(&(addr1, storage_key)).is_some());
1511    }
1512
1513    #[test]
1514    fn test_insert_state_recreated_account_updates_cached_storage() {
1515        let caches = ExecutionCache::new(1000);
1516        let addr = Address::random();
1517        let other_addr = Address::random();
1518        let key = StorageKey::from(U256::from(1));
1519        let other_key = StorageKey::from(U256::from(2));
1520        let provider = MockEthProvider::default();
1521        provider.extend_accounts(vec![(addr, ExtendedAccount::new(0, U256::from(100)))]);
1522        let state_provider =
1523            CachedStateProvider::new_prewarm(provider.into_evm_state_provider(), caches.clone());
1524        assert_eq!(state_provider.storage(addr, key).unwrap(), None);
1525        assert_eq!(caches.0.storage_cache.get(&(addr, key)), Some(U256::ZERO));
1526        drop(state_provider);
1527        caches.insert_storage(other_addr, other_key, Some(U256::from(42)));
1528
1529        let current_info =
1530            AccountInfo { nonce: 1, code_hash: B256::random(), ..Default::default() };
1531        let bundle = BundleState {
1532            state: HashMap::from_iter([(
1533                addr,
1534                BundleAccount::new(
1535                    Some(AccountInfo {
1536                        balance: U256::from(100),
1537                        code_hash: alloy_primitives::KECCAK256_EMPTY,
1538                        ..Default::default()
1539                    }),
1540                    Some(current_info.clone()),
1541                    HashMap::from_iter([(
1542                        U256::from(1),
1543                        StorageSlot::new_changed(U256::ZERO, U256::from(7)),
1544                    )]),
1545                    AccountStatus::DestroyedChanged,
1546                ),
1547            )]),
1548            ..Default::default()
1549        };
1550
1551        assert!(caches.insert_state(&bundle).is_ok());
1552        assert_eq!(caches.0.storage_cache.get(&(addr, key)), Some(U256::from(7)));
1553        let cached_account = caches.0.account_cache.get(&addr).flatten().unwrap();
1554        assert_eq!(cached_account.bytecode_hash, Some(current_info.code_hash));
1555        assert_eq!(caches.0.storage_cache.get(&(other_addr, other_key)), Some(U256::from(42)));
1556    }
1557
1558    #[test]
1559    fn test_insert_state_destroyed_account_no_original_info_removes_only_account() {
1560        let caches = ExecutionCache::new(1000);
1561
1562        // Pre-populate caches
1563        let addr1 = Address::random();
1564        let addr2 = Address::random();
1565        caches.insert_account(addr1, Some(Account::default()));
1566        caches.insert_account(addr2, Some(Account::default()));
1567
1568        let bundle = BundleState {
1569            // BundleState with a destroyed account (has no original info)
1570            state: HashMap::from_iter([(
1571                addr1,
1572                BundleAccount::new(
1573                    None, // No original info
1574                    None, // Destroyed
1575                    Default::default(),
1576                    AccountStatus::Destroyed,
1577                ),
1578            )]),
1579            contracts: Default::default(),
1580            reverts: Default::default(),
1581            state_size: 0,
1582            reverts_size: 0,
1583        };
1584
1585        // Insert state should only remove the destroyed account (no code = no full clear)
1586        assert!(caches.insert_state(&bundle).is_ok());
1587
1588        // Verify only addr1 was removed
1589        assert!(caches.0.account_cache.get(&addr1).is_none());
1590        assert!(caches.0.account_cache.get(&addr2).is_some());
1591    }
1592
1593    #[test]
1594    fn test_insert_state_destroyed_uncached_account_keeps_size_zero() {
1595        let caches = ExecutionCache::new(1000);
1596        assert_eq!(caches.0.account_stats.size(), 0);
1597
1598        let addr = Address::random();
1599        let bundle = BundleState {
1600            state: HashMap::from_iter([(
1601                addr,
1602                BundleAccount::new(
1603                    None, // No original info
1604                    None, // Destroyed
1605                    Default::default(),
1606                    AccountStatus::Destroyed,
1607                ),
1608            )]),
1609            contracts: Default::default(),
1610            reverts: Default::default(),
1611            state_size: 0,
1612            reverts_size: 0,
1613        };
1614
1615        assert!(caches.insert_state(&bundle).is_ok());
1616        assert_eq!(caches.0.account_stats.size(), 0);
1617        assert!(caches.0.account_cache.get(&addr).is_none());
1618    }
1619
1620    #[test]
1621    fn test_code_cache_capacity_with_default_budget() {
1622        // Default cross-block cache is 4 GB; code gets 5.56% = ~228 MB.
1623        let total_cache_size = 4 * 1024 * 1024 * 1024; // 4 GB
1624        let code_budget = (total_cache_size * 556) / 10000; // 228 MB
1625
1626        let capacity = ExecutionCache::bytes_to_entries(code_budget, CODE_CACHE_ENTRY_SIZE);
1627
1628        // With ESTIMATED_AVG_CODE_SIZE (8 KiB) we expect 16384 entries.
1629        // If someone accidentally reverts to MAX_CODE_SIZE (48 KiB), this would drop to 4096.
1630        assert_eq!(
1631            capacity, 16384,
1632            "code cache should have 16384 entries with default 4 GB budget"
1633        );
1634    }
1635}