reth_execution_cache/
lib.rs1#![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#[derive(Clone, Debug, Default)]
44pub struct PayloadExecutionCache {
45 inner: Arc<Mutex<Option<SavedCache>>>,
47 metrics: PayloadExecutionCacheMetrics,
49}
50
51impl PayloadExecutionCache {
52 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 #[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 let hash_matches = cached_hash == parent_hash;
83 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 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 pub fn wait_for_availability(&self) -> Duration {
123 let start = Instant::now();
124 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 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#[derive(Debug)]
166pub enum CacheCheckout {
167 Available(SavedCache),
169 Empty,
171 InUse {
174 cached_hash: B256,
176 },
177}
178
179#[derive(Metrics, Clone)]
181#[metrics(scope = "consensus.engine.beacon")]
182struct PayloadExecutionCacheMetrics {
183 execution_cache_in_use: Counter,
186 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}