Skip to main content

reth_execution_cache/
lib.rs

1//! Cross-block execution cache for payload processing.
2//!
3//! This crate provides the core caching infrastructure used during block execution:
4//! - [`ExecutionCache`]: Fixed-size concurrent caches for accounts, storage, and bytecode
5//! - [`SavedCache`]: An execution cache snapshot associated with a specific block hash
6//! - [`PayloadExecutionCache`]: Thread-safe wrapper for sharing cached state across payload
7//!   processing tasks
8
9#![doc(
10    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
11    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
12    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
13)]
14#![cfg_attr(docsrs, feature(doc_cfg))]
15#![cfg_attr(not(test), warn(unused_crate_dependencies))]
16
17mod cached_state;
18pub use cached_state::*;
19
20mod txpool;
21pub use txpool::*;
22
23use alloy_primitives::B256;
24use metrics::{Counter, Histogram};
25use reth_concurrency::sync::{parking_lot::Mutex, time::FastInstant as Instant};
26use reth_metrics::Metrics;
27use std::{sync::Arc, time::Duration};
28use tracing::{debug, instrument, warn};
29
30/// A guarded, thread-safe cache of execution state that tracks the most recent block's caches.
31///
32/// This is the cross-block cache used to accelerate sequential payload processing.
33/// When a new block arrives, its parent's cached state can be reused to avoid
34/// redundant database lookups.
35///
36/// This process assumes that payloads are received sequentially.
37///
38/// ## Cache Safety
39///
40/// **CRITICAL**: Cache update operations require exclusive access. All concurrent cache users
41/// (such as prewarming tasks) must be terminated before calling
42/// [`PayloadExecutionCache::update_with_guard`], otherwise the cache may be corrupted or cleared.
43#[derive(Clone, Debug, Default)]
44pub struct PayloadExecutionCache {
45    /// Guarded cloneable cache identified by a block hash.
46    inner: Arc<Mutex<Option<SavedCache>>>,
47    /// Metrics for cache operations.
48    metrics: PayloadExecutionCacheMetrics,
49}
50
51impl PayloadExecutionCache {
52    /// Returns the cache for `parent_hash` if it's available for use.
53    ///
54    /// See [`Self::checkout`] for when a cache is available.
55    pub fn get_cache_for(&self, parent_hash: B256) -> Option<SavedCache> {
56        match self.checkout(parent_hash) {
57            CacheCheckout::Available(cache) => Some(cache),
58            CacheCheckout::Empty | CacheCheckout::InUse { .. } => None,
59        }
60    }
61
62    /// Checks out the stored cache for `parent_hash`.
63    ///
64    /// The stored cache is available when no other task holds a reference to it (checked via the
65    /// Arc reference count). If it was saved for another block, it is cleared and re-keyed to
66    /// `parent_hash` before it is returned.
67    #[instrument(level = "debug", target = "engine::tree::payload_processor", skip(self))]
68    pub fn checkout(&self, parent_hash: B256) -> CacheCheckout {
69        let start = Instant::now();
70        let mut cache = self.inner.lock();
71
72        let elapsed = start.elapsed();
73        self.metrics.execution_cache_wait_duration.record(elapsed.as_secs_f64());
74        if elapsed.as_millis() > 5 {
75            warn!(blocked_for=?elapsed, "Blocked waiting for execution cache mutex");
76        }
77
78        if let Some(c) = cache.as_mut() {
79            let cached_hash = c.executed_block_hash();
80            // Check that the cache hash matches the parent hash of the current block. It won't
81            // match in case it's a fork block.
82            let hash_matches = cached_hash == parent_hash;
83            // Check `is_available()` to ensure no other tasks (e.g., prewarming) currently hold
84            // a reference to this cache. We can only reuse it when we have exclusive access.
85            let available = c.is_available();
86            let usage_count = c.usage_count();
87
88            debug!(
89                target: "engine::caching",
90                %cached_hash,
91                %parent_hash,
92                hash_matches,
93                available,
94                usage_count,
95                "Existing cache found"
96            );
97
98            if available {
99                if !hash_matches {
100                    // Fork block: clear and update the hash on the ORIGINAL before cloning.
101                    // This prevents the canonical chain from matching on the stale hash
102                    // and picking up polluted data if the fork block fails.
103                    c.clear_with_hash(parent_hash);
104                }
105                return CacheCheckout::Available(c.clone())
106            }
107            self.metrics.execution_cache_in_use.increment(1);
108            return CacheCheckout::InUse { cached_hash }
109        }
110
111        debug!(target: "engine::caching", %parent_hash, "No cache found");
112        CacheCheckout::Empty
113    }
114
115    /// Waits for the mutex protecting the stored `Option<SavedCache>` to be released.
116    ///
117    /// This does not wait for other users to drop their [`ExecutionCache`] clones or for removed
118    /// caches to finish dropping after unlocking. A subsequent [`Self::get_cache_for`] can still
119    /// return `None`, causing its caller to allocate a new cache while those drops run.
120    ///
121    /// Returns only the time spent waiting for the mutex, excluding post-unlock cleanup.
122    pub fn wait_for_availability(&self) -> Duration {
123        let start = Instant::now();
124        // Acquire lock to wait for any current holders to finish
125        let _guard = self.inner.lock();
126        let elapsed = start.elapsed();
127        if elapsed.as_millis() > 5 {
128            debug!(
129                target: "engine::tree::payload_processor",
130                blocked_for=?elapsed,
131                "Waited for execution cache to become available"
132            );
133        }
134        elapsed
135    }
136
137    /// Runs `update_fn` with mutable access to the stored `Option<SavedCache>` under the mutex.
138    /// Returns the closure's result after releasing the mutex, allowing removed caches to be
139    /// dropped outside the lock.
140    ///
141    /// Drop extra [`SavedCache`] or [`ExecutionCache`] clones of the stored cache before the
142    /// closure returns: [`Self::get_cache_for`] requires that cache's Arc strong reference
143    /// count to be one.
144    ///
145    /// ## CRITICAL SAFETY REQUIREMENT
146    ///
147    /// **Before calling this method, you MUST ensure there are no other active cache users.**
148    /// This includes:
149    /// - No running prewarming task instances that could write to the cache
150    /// - No concurrent transactions that might access the cached state
151    /// - All prewarming operations must be completed or cancelled
152    ///
153    /// Violating this requirement can result in cache corruption, incorrect state data,
154    /// and potential consensus failures.
155    pub fn update_with_guard<F, R>(&self, update_fn: F) -> R
156    where
157        F: FnOnce(&mut Option<SavedCache>) -> R,
158    {
159        let mut guard = self.inner.lock();
160        update_fn(&mut guard)
161    }
162}
163
164/// Outcome of [`PayloadExecutionCache::checkout`].
165#[derive(Debug)]
166pub enum CacheCheckout {
167    /// The stored cache, keyed to the requested parent hash.
168    Available(SavedCache),
169    /// No cache is stored yet.
170    Empty,
171    /// The stored cache is still held by another task, such as a prewarm task that has not saved
172    /// its block yet.
173    InUse {
174        /// Hash of the block whose post-state the stored cache holds.
175        cached_hash: B256,
176    },
177}
178
179/// Metrics for [`PayloadExecutionCache`] operations.
180#[derive(Metrics, Clone)]
181#[metrics(scope = "consensus.engine.beacon")]
182struct PayloadExecutionCacheMetrics {
183    /// Counter for when the execution cache was unavailable because other threads
184    /// (e.g., prewarming) are still using it.
185    execution_cache_in_use: Counter,
186    /// Time spent waiting for execution cache mutex to become available.
187    execution_cache_wait_duration: Histogram,
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[reth_concurrency::test]
195    fn single_checkout_blocks_second() {
196        let cache = PayloadExecutionCache::default();
197        let hash = B256::repeat_byte(1u8);
198
199        cache.update_with_guard(|slot| {
200            *slot = Some(SavedCache::new(hash, ExecutionCache::new(1_000)))
201        });
202
203        let first = cache.get_cache_for(hash);
204        assert!(first.is_some());
205
206        let second = cache.get_cache_for(hash);
207        assert!(second.is_none());
208    }
209
210    #[reth_concurrency::test]
211    fn checkout_available_after_drop() {
212        let cache = PayloadExecutionCache::default();
213        let hash = B256::repeat_byte(2u8);
214
215        cache.update_with_guard(|slot| {
216            *slot = Some(SavedCache::new(hash, ExecutionCache::new(1_000)))
217        });
218
219        let checked_out = cache.get_cache_for(hash);
220        assert!(checked_out.is_some());
221        drop(checked_out);
222
223        let second = cache.get_cache_for(hash);
224        assert!(second.is_some());
225    }
226
227    #[reth_concurrency::test]
228    fn raw_cache_handle_blocks_checkout_until_drop() {
229        let cache = PayloadExecutionCache::default();
230        let hash = B256::repeat_byte(3u8);
231
232        cache.update_with_guard(|slot| {
233            *slot = Some(SavedCache::new(hash, ExecutionCache::new(1_000)))
234        });
235
236        let checked_out = cache.get_cache_for(hash).expect("checkout should succeed");
237        let cache_handle = checked_out.cache().clone();
238        drop(checked_out);
239
240        let blocked = cache.get_cache_for(hash);
241        assert!(blocked.is_none(), "raw ExecutionCache handle should keep slot in use");
242
243        drop(cache_handle);
244
245        let available = cache.get_cache_for(hash);
246        assert!(available.is_some(), "checkout should succeed after raw handle is dropped");
247    }
248
249    #[reth_concurrency::test]
250    fn hash_mismatch_clears_and_retags() {
251        let cache = PayloadExecutionCache::default();
252        let hash_a = B256::repeat_byte(0xAA);
253        let hash_b = B256::repeat_byte(0xBB);
254
255        cache.update_with_guard(|slot| {
256            *slot = Some(SavedCache::new(hash_a, ExecutionCache::new(1_000)))
257        });
258
259        let checked_out = cache.get_cache_for(hash_b);
260        assert!(checked_out.is_some());
261        assert_eq!(checked_out.unwrap().executed_block_hash(), hash_b);
262    }
263
264    #[reth_concurrency::test]
265    fn empty_cache_returns_none() {
266        let cache = PayloadExecutionCache::default();
267        assert!(cache.get_cache_for(B256::ZERO).is_none());
268    }
269
270    #[reth_concurrency::test]
271    fn checkout_distinguishes_empty_from_in_use() {
272        let cache = PayloadExecutionCache::default();
273        let hash = B256::repeat_byte(7u8);
274        assert!(matches!(cache.checkout(hash), CacheCheckout::Empty));
275
276        cache.update_with_guard(|slot| {
277            *slot = Some(SavedCache::new(hash, ExecutionCache::new(1_000)))
278        });
279        let held = cache.get_cache_for(hash).expect("checkout should succeed");
280
281        assert!(matches!(
282            cache.checkout(B256::repeat_byte(8u8)),
283            CacheCheckout::InUse { cached_hash } if cached_hash == hash
284        ));
285        drop(held);
286    }
287}