1use 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
21const FIXED_CACHE_ALIGNMENT: usize = 128;
26
27const FIXED_CACHE_ENTRY_OVERHEAD: usize = size_of::<usize>();
29
30const fn fixed_cache_entry_size<K, V>() -> usize {
35 fixed_cache_key_size_with_value::<K>(size_of::<V>())
36}
37
38const fn fixed_cache_key_size_with_value<K>(value: usize) -> usize {
43 let raw_size = FIXED_CACHE_ENTRY_OVERHEAD + size_of::<K>() + value;
44 raw_size.div_ceil(FIXED_CACHE_ALIGNMENT) * FIXED_CACHE_ALIGNMENT
46}
47
48const ESTIMATED_AVG_CODE_SIZE: usize = 8 * 1024;
55
56const CODE_CACHE_ENTRY_SIZE: usize =
58 fixed_cache_key_size_with_value::<Address>(ESTIMATED_AVG_CODE_SIZE);
59
60const STORAGE_CACHE_ENTRY_SIZE: usize =
62 fixed_cache_entry_size::<(Address, StorageKey), StorageValue>();
63
64const ACCOUNT_CACHE_ENTRY_SIZE: usize = fixed_cache_entry_size::<Address, Option<Account>>();
66
67struct EpochCacheConfig;
69impl CacheConfig for EpochCacheConfig {
70 const EPOCHS: bool = true;
71}
72
73type FixedCache<K, V, H = DefaultHashBuilder> = fixed_cache::Cache<K, V, H, EpochCacheConfig>;
75
76#[derive(Debug)]
88pub struct CachedStateProvider<S> {
89 state_provider: S,
91
92 caches: ExecutionCache,
94
95 txpool_snapshot: Option<TxPoolPrewarmCacheSnapshot>,
97
98 metrics: Option<CachedStateMetrics>,
100
101 execution_metric_counts: CacheMetricCounts,
103
104 txpool_metric_counts: CacheMetricCounts,
106
107 fill_mode: CacheFillMode,
109
110 cache_stats: Option<Arc<CacheStats>>,
113}
114
115impl<S> CachedStateProvider<S> {
116 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub enum CacheFillMode {
285 LookupOnly,
287 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#[derive(Debug, Clone, PartialEq, Eq)]
371pub enum CachedStatus<T> {
372 NotCached(T),
374 Cached(T),
376}
377
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380pub enum CachedStateMetricsSource {
381 Engine,
383 Builder,
385 #[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#[derive(Metrics, Clone)]
403#[metrics(scope = "sync.caching")]
404pub struct CachedStateMetrics {
405 execution_cache_created_total: Counter,
407
408 execution_cache_creation_duration_seconds: Histogram,
410
411 code_cache_hits: Gauge,
413
414 code_cache_misses: Gauge,
416
417 storage_cache_hits: Gauge,
419
420 storage_cache_misses: Gauge,
422
423 account_cache_hits: Gauge,
425
426 account_cache_misses: Gauge,
428
429 txpool_snapshot_code_hits: Gauge,
431
432 txpool_snapshot_code_misses: Gauge,
434
435 txpool_snapshot_storage_hits: Gauge,
437
438 txpool_snapshot_storage_misses: Gauge,
440
441 txpool_snapshot_account_hits: Gauge,
443
444 txpool_snapshot_account_misses: Gauge,
446}
447
448#[derive(Metrics, Clone)]
450#[metrics(scope = "sync.caching")]
451pub struct CachedStateCacheMetrics {
452 code_cache_size: Gauge,
454
455 code_cache_capacity: Gauge,
457
458 code_cache_collisions: Gauge,
460
461 storage_cache_size: Gauge,
463
464 storage_cache_capacity: Gauge,
466
467 storage_cache_collisions: Gauge,
469
470 account_cache_size: Gauge,
472
473 account_cache_capacity: Gauge,
475
476 account_cache_collisions: Gauge,
478}
479
480impl CachedStateMetrics {
481 pub fn reset(&self) {
483 self.code_cache_hits.set(0);
485 self.code_cache_misses.set(0);
486
487 self.storage_cache_hits.set(0);
489 self.storage_cache_misses.set(0);
490
491 self.account_cache_hits.set(0);
493 self.account_cache_misses.set(0);
494
495 self.txpool_snapshot_code_hits.set(0);
497 self.txpool_snapshot_code_misses.set(0);
498
499 self.txpool_snapshot_storage_hits.set(0);
501 self.txpool_snapshot_storage_misses.set(0);
502
503 self.txpool_snapshot_account_hits.set(0);
505 self.txpool_snapshot_account_misses.set(0);
506 }
507
508 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 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#[derive(Debug, Default)]
597pub struct CacheStats {
598 account_hits: AtomicUsize,
600 account_misses: AtomicUsize,
602 storage_hits: AtomicUsize,
604 storage_misses: AtomicUsize,
606 code_hits: AtomicUsize,
608 code_misses: AtomicUsize,
610 txpool_snapshot_account_hits: AtomicUsize,
612 txpool_snapshot_account_misses: AtomicUsize,
614 txpool_snapshot_storage_hits: AtomicUsize,
616 txpool_snapshot_storage_misses: AtomicUsize,
618 txpool_snapshot_code_hits: AtomicUsize,
620 txpool_snapshot_code_misses: AtomicUsize,
622}
623
624impl CacheStats {
625 pub fn record_account_hit(&self) {
627 self.account_hits.fetch_add(1, Ordering::Relaxed);
628 }
629
630 pub fn record_account_miss(&self) {
632 self.account_misses.fetch_add(1, Ordering::Relaxed);
633 }
634
635 pub fn account_hits(&self) -> usize {
637 self.account_hits.load(Ordering::Relaxed)
638 }
639
640 pub fn account_misses(&self) -> usize {
642 self.account_misses.load(Ordering::Relaxed)
643 }
644
645 pub fn record_storage_hit(&self) {
647 self.storage_hits.fetch_add(1, Ordering::Relaxed);
648 }
649
650 pub fn record_storage_miss(&self) {
652 self.storage_misses.fetch_add(1, Ordering::Relaxed);
653 }
654
655 pub fn storage_hits(&self) -> usize {
657 self.storage_hits.load(Ordering::Relaxed)
658 }
659
660 pub fn storage_misses(&self) -> usize {
662 self.storage_misses.load(Ordering::Relaxed)
663 }
664
665 pub fn record_code_hit(&self) {
667 self.code_hits.fetch_add(1, Ordering::Relaxed);
668 }
669
670 pub fn record_code_miss(&self) {
672 self.code_misses.fetch_add(1, Ordering::Relaxed);
673 }
674
675 pub fn code_hits(&self) -> usize {
677 self.code_hits.load(Ordering::Relaxed)
678 }
679
680 pub fn code_misses(&self) -> usize {
682 self.code_misses.load(Ordering::Relaxed)
683 }
684
685 pub fn record_txpool_snapshot_account_hit(&self) {
687 self.txpool_snapshot_account_hits.fetch_add(1, Ordering::Relaxed);
688 }
689
690 pub fn record_txpool_snapshot_account_miss(&self) {
692 self.txpool_snapshot_account_misses.fetch_add(1, Ordering::Relaxed);
693 }
694
695 pub fn txpool_snapshot_account_hits(&self) -> usize {
697 self.txpool_snapshot_account_hits.load(Ordering::Relaxed)
698 }
699
700 pub fn txpool_snapshot_account_misses(&self) -> usize {
702 self.txpool_snapshot_account_misses.load(Ordering::Relaxed)
703 }
704
705 pub fn record_txpool_snapshot_storage_hit(&self) {
707 self.txpool_snapshot_storage_hits.fetch_add(1, Ordering::Relaxed);
708 }
709
710 pub fn record_txpool_snapshot_storage_miss(&self) {
712 self.txpool_snapshot_storage_misses.fetch_add(1, Ordering::Relaxed);
713 }
714
715 pub fn txpool_snapshot_storage_hits(&self) -> usize {
717 self.txpool_snapshot_storage_hits.load(Ordering::Relaxed)
718 }
719
720 pub fn txpool_snapshot_storage_misses(&self) -> usize {
722 self.txpool_snapshot_storage_misses.load(Ordering::Relaxed)
723 }
724
725 pub fn record_txpool_snapshot_code_hit(&self) {
727 self.txpool_snapshot_code_hits.fetch_add(1, Ordering::Relaxed);
728 }
729
730 pub fn record_txpool_snapshot_code_miss(&self) {
732 self.txpool_snapshot_code_misses.fetch_add(1, Ordering::Relaxed);
733 }
734
735 pub fn txpool_snapshot_code_hits(&self) -> usize {
737 self.txpool_snapshot_code_hits.load(Ordering::Relaxed)
738 }
739
740 pub fn txpool_snapshot_code_misses(&self) -> usize {
742 self.txpool_snapshot_code_misses.load(Ordering::Relaxed)
743 }
744}
745
746#[derive(Debug)]
761pub struct CacheStatsHandler {
762 collisions: AtomicU64,
763 size: AtomicUsize,
764 capacity: usize,
765}
766
767impl CacheStatsHandler {
768 pub const fn new(capacity: usize) -> Self {
770 Self { collisions: AtomicU64::new(0), size: AtomicUsize::new(0), capacity }
771 }
772
773 pub fn collisions(&self) -> u64 {
775 self.collisions.load(Ordering::Relaxed)
776 }
777
778 pub fn size(&self) -> usize {
780 self.size.load(Ordering::Relaxed)
781 }
782
783 pub const fn capacity(&self) -> usize {
785 self.capacity
786 }
787
788 pub fn increment_size(&self) {
790 let _ = self.size.fetch_add(1, Ordering::Relaxed);
791 }
792
793 pub fn decrement_size(&self) {
795 let _ = self.size.fetch_sub(1, Ordering::Relaxed);
796 }
797
798 pub fn reset_size(&self) {
800 self.size.store(0, Ordering::Relaxed);
801 }
802
803 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 self.increment_size();
819 }
820 Some((evicted_key, _)) if evicted_key != key => {
821 self.collisions.fetch_add(1, Ordering::Relaxed);
823 }
824 Some(_) => {
825 }
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#[derive(Debug, Clone)]
954pub struct ExecutionCache(Arc<ExecutionCacheInner>);
955
956#[derive(Debug)]
958struct ExecutionCacheInner {
959 code_cache: FixedCache<B256, Option<Bytecode>, FbBuildHasher<32>>,
961
962 storage_cache: FixedCache<(Address, StorageKey), StorageValue>,
964
965 account_cache: FixedCache<Address, Option<Account>, FbBuildHasher<20>>,
967
968 code_stats: Arc<CacheStatsHandler>,
970
971 storage_stats: Arc<CacheStatsHandler>,
973
974 account_stats: Arc<CacheStatsHandler>,
976
977 selfdestruct_encountered: Once,
979}
980
981impl ExecutionCache {
982 const MIN_CACHE_SIZE_WITH_EPOCHS: usize = 1 << 12; pub const fn bytes_to_entries(size_bytes: usize, entry_size: usize) -> usize {
991 let entries = size_bytes / entry_size;
992 let rounded = if entries == 0 { 1 } else { (entries + 1).next_power_of_two() >> 1 };
994 if rounded < Self::MIN_CACHE_SIZE_WITH_EPOCHS {
996 Self::MIN_CACHE_SIZE_WITH_EPOCHS
997 } else {
998 rounded
999 }
1000 }
1001
1002 pub fn new(total_cache_size: usize) -> Self {
1004 let code_cache_size = (total_cache_size * 556) / 10000; let storage_cache_size = (total_cache_size * 8888) / 10000; let account_cache_size = (total_cache_size * 556) / 10000; 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 fn usage_count(&self) -> usize {
1032 Arc::strong_count(&self.0)
1033 }
1034
1035 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 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 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 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 pub fn insert_code(&self, hash: B256, code: Option<Bytecode>) {
1100 self.0.code_cache.insert(hash, code);
1101 }
1102
1103 pub fn insert_account(&self, address: Address, account: Option<Account>) {
1105 self.0.account_cache.insert(address, account);
1106 }
1107
1108 #[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 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 account.status.is_not_modified() {
1150 continue
1151 }
1152
1153 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 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 for (key, slot) in &account.storage {
1193 self.insert_storage(*addr, (*key).into(), Some(slot.present_value));
1194 }
1195
1196 self.insert_account(*addr, Some(Account::from(account_info)));
1199 }
1200
1201 Ok(())
1202 }
1203
1204 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 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#[derive(Debug, Clone)]
1239pub struct SavedCache {
1240 hash: B256,
1242
1243 caches: ExecutionCache,
1245}
1246
1247impl SavedCache {
1248 pub const fn new(hash: B256, caches: ExecutionCache) -> Self {
1250 Self { hash, caches }
1251 }
1252
1253 pub const fn executed_block_hash(&self) -> B256 {
1255 self.hash
1256 }
1257
1258 pub fn is_available(&self) -> bool {
1260 self.caches.usage_count() == 1
1261 }
1262
1263 pub fn usage_count(&self) -> usize {
1265 self.caches.usage_count()
1266 }
1267
1268 pub const fn cache(&self) -> &ExecutionCache {
1270 &self.caches
1271 }
1272
1273 pub fn into_cache(self) -> ExecutionCache {
1275 self.caches
1276 }
1277
1278 pub fn shares_cache_with(&self, other: &Self) -> bool {
1281 Arc::ptr_eq(&self.caches.0, &other.caches.0)
1282 }
1283
1284 pub fn update_metrics(&self, metrics: Option<&CachedStateCacheMetrics>) {
1286 if let Some(metrics) = metrics {
1287 self.caches.update_metrics(metrics);
1288 }
1289 }
1290
1291 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 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 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 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 state: HashMap::from_iter([(
1440 Address::random(),
1441 BundleAccount::new(
1442 Some(AccountInfo {
1443 nonce: 1,
1444 code_hash: B256::random(), code: None,
1446 ..Default::default()
1447 }),
1448 None, 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 let result = caches.insert_state(&bundle);
1461 assert!(result.is_ok());
1462
1463 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 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 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, code: None,
1491 ..Default::default()
1492 }),
1493 None, 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 assert!(caches.insert_state(&bundle).is_ok());
1506
1507 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 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 state: HashMap::from_iter([(
1571 addr1,
1572 BundleAccount::new(
1573 None, None, 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 assert!(caches.insert_state(&bundle).is_ok());
1587
1588 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, None, 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 let total_cache_size = 4 * 1024 * 1024 * 1024; let code_budget = (total_cache_size * 556) / 10000; let capacity = ExecutionCache::bytes_to_entries(code_budget, CODE_CACHE_ENTRY_SIZE);
1627
1628 assert_eq!(
1631 capacity, 16384,
1632 "code cache should have 16384 entries with default 4 GB budget"
1633 );
1634 }
1635}