reth_engine_tree/tree/payload_processor/bal_prewarm_pool.rs
1//! BAL read-set prewarming pool.
2
3use alloy_primitives::{Address, StorageKey};
4use reth_concurrency::sync::{
5 atomic::{AtomicUsize, Ordering},
6 channel,
7 channel::{Receiver, Sender},
8 thread::{self, Builder, JoinHandle},
9};
10use reth_execution_cache::{CachedStateProvider, ExecutionCache, TxPoolPrewarmCacheSnapshot};
11use reth_provider::{EvmStateProvider, EvmStateProviderBox, ProviderResult};
12use std::sync::Arc;
13use tokio::sync::oneshot;
14use tracing::{error, trace};
15
16/// Builds a fresh EVM provider over the block's parent state. Type-erased so the pool is not
17/// generic over the provider factory; each worker builds its own per block.
18pub type BuildProviderFn = dyn Fn() -> ProviderResult<EvmStateProviderBox> + Send + Sync;
19
20/// A single warm request: an account and a batch of its storage slots, or a batch of storage slots
21/// on their own.
22enum PrewarmTarget {
23 Account(Address, Box<[StorageKey]>),
24 Storage(Address, Box<[StorageKey]>),
25}
26
27/// A message in a worker's queue. The per-block lifecycle is explicit and ordered (the queue is
28/// FIFO): one `BeginBlock`, then the worker's share of `Warm`s, then one `EndBlock`.
29enum PrewarmMsg {
30 /// Open a read txn for the new block: build a provider over the parent state and hold it.
31 BeginBlock {
32 build: Arc<BuildProviderFn>,
33 caches: ExecutionCache,
34 txpool_snapshot: Option<TxPoolPrewarmCacheSnapshot>,
35 },
36 /// Warm one target into the held provider's cache. Ignored if no provider is held.
37 Warm(PrewarmTarget),
38 /// Drop the held provider (and its read txn).
39 EndBlock(Arc<SendOnDrop>),
40}
41
42/// Long-lived pool of blocking threads that warm the BAL read-set into the shared execution cache.
43#[derive(Debug)]
44pub struct BalPrewarmPool {
45 /// One queue per worker. `BeginBlock`/`EndBlock` are broadcast to all; `Warm`s round-robin.
46 workers: Vec<Sender<PrewarmMsg>>,
47 /// Round-robin cursor for distributing warm requests across workers.
48 next: AtomicUsize,
49 handles: Vec<JoinHandle<()>>,
50}
51
52impl BalPrewarmPool {
53 /// Spawns `num_threads` long-lived blocking worker threads. Owned by the
54 /// [`PayloadProcessor`](super::PayloadProcessor); dropping the pool stops and joins the
55 /// threads.
56 pub fn new(num_threads: usize) -> Arc<Self> {
57 let mut workers = Vec::with_capacity(num_threads);
58 let mut handles = Vec::with_capacity(num_threads);
59 for i in 0..num_threads {
60 let (tx, rx) = channel::unbounded::<PrewarmMsg>();
61 workers.push(tx);
62 handles.push(
63 Builder::new()
64 .name(format!("bal-prewarm-{i:03}"))
65 .spawn(move || prewarm_loop(rx))
66 .expect("spawn bal-prewarm thread"),
67 );
68 }
69 trace!(target: "engine::tree::bal_prewarm_pool", num_threads, "BalPrewarmPool spawned");
70 Arc::new(Self { workers, next: AtomicUsize::new(0), handles })
71 }
72
73 /// Begins a block: hands every worker the provider builder and shared cache so each opens its
74 /// own read txn over the parent state. Pair with [`end_block`](Self::end_block).
75 pub fn begin_block(
76 &self,
77 build: Arc<BuildProviderFn>,
78 caches: ExecutionCache,
79 txpool_snapshot: Option<TxPoolPrewarmCacheSnapshot>,
80 ) {
81 for worker in &self.workers {
82 let _ = worker.send(PrewarmMsg::BeginBlock {
83 build: build.clone(),
84 caches: caches.clone(),
85 txpool_snapshot: txpool_snapshot.clone(),
86 });
87 }
88 }
89
90 /// Fire-and-forget: warm an account and its storage slots.
91 ///
92 /// The slots are dispatched in `WARM_BATCH_SIZE` chunks that are distributed independently,
93 /// so a single account with a large read-set does not serialize onto one worker;
94 /// [`end_block`](Self::end_block) waits for the slowest queue.
95 pub fn warm_account(&self, addr: Address, slots: impl IntoIterator<Item = StorageKey>) {
96 let mut slots = slots.into_iter();
97 let mut batch: Box<[StorageKey]> = slots.by_ref().take(WARM_BATCH_SIZE).collect();
98 self.send_warm(PrewarmTarget::Account(addr, batch));
99
100 loop {
101 batch = slots.by_ref().take(WARM_BATCH_SIZE).collect();
102 if batch.is_empty() {
103 break
104 }
105 self.send_warm(PrewarmTarget::Storage(addr, batch));
106 }
107 }
108
109 /// Ends the block: every worker drops its provider (and read txn) once it has drained the warm
110 /// requests queued ahead of this message.
111 ///
112 /// Blocks until all workers processed the end block message. Completion uses native Tokio in
113 /// all builds, so this wait does not yield to the fuzz scheduler.
114 pub fn end_block(&self) {
115 let (tx, rx) = oneshot::channel();
116 let tx = Arc::new(SendOnDrop { sender: Some(tx) });
117
118 for worker in &self.workers {
119 let _ = worker.send(PrewarmMsg::EndBlock(tx.clone()));
120 }
121
122 drop(tx);
123 rx.blocking_recv().expect("BAL prewarm pool dropped without signaling completion");
124 }
125
126 fn send_warm(&self, target: PrewarmTarget) {
127 let i = self.next.fetch_add(1, Ordering::Relaxed) % self.workers.len();
128 let _ = self.workers[i].send(PrewarmMsg::Warm(target));
129 }
130}
131
132impl Drop for BalPrewarmPool {
133 /// Disconnects every worker's queue and joins the workers. Detaching them instead, by dropping
134 /// their handles, races with their exit in glibc before 2.43 and can crash the process.
135 ///
136 /// A worker drains the requests queued ahead of the disconnect before it exits, so the join is
137 /// only as long as the queues are: [`end_block`](Self::end_block) empties them before the last
138 /// handle to the pool goes away. A handle for the current thread is skipped because joining it
139 /// would deadlock.
140 fn drop(&mut self) {
141 self.workers.clear();
142 let current = thread::current().id();
143 for handle in self.handles.drain(..) {
144 if handle.thread().id() != current &&
145 let Err(err) = handle.join()
146 {
147 error!(target: "engine::tree::bal_prewarm_pool", ?err, "BAL prewarm worker panicked");
148 }
149 }
150 }
151}
152
153/// Number of warming threads.
154///
155/// The work performed on those threads boils down mostly to MDBX reads. An MDBX read consists of
156/// a tree traversal and major page faults causing I/O.
157///
158/// In order to utilize the parallelism of `NVMe` we have to give it enough work, or equally,
159/// maintain a high queue depth. Modern `NVMe` devices require in between 64-128 requests in-flight
160/// to achieve its peak performance. Ideally we don't grow past that but it's OK to do so, it just
161/// means that a request is going to wait in the `NVMe` queue rather than in memory.
162///
163/// MDBX piggy-backs on the OS page cache for its buffers. Oftentimes, the hit rate reaches 90-99%
164/// hit rate. At that point, the workload can be classified as CPU-bound. In that case, having
165/// a high number of threads is counterproductive due to the effects of context switching, core
166/// migration, contention, etc.
167///
168/// However, that overhead is considered negligible compared to the benefits of fully utilizing
169/// `NVMe` resources. For example, with request latency of 100µs, 100k IO requests the expected
170/// time to finish is 312.5ms at QD=32 and 156.26ms at QD=64.
171///
172/// This should explain why this particular value is picked.
173pub const DEFAULT_BAL_PREWARM_THREADS: usize = 128;
174
175/// Number of storage slots carried by one warm message.
176///
177/// Batching amortizes the send over many slots and hands the worker a run of slots that live
178/// close together in the storage table, while the cap keeps enough messages in flight to saturate
179/// the workers on blocks whose read-set is concentrated in a few accounts.
180const WARM_BATCH_SIZE: usize = 8;
181
182fn prewarm_loop(rx: Receiver<PrewarmMsg>) {
183 // The provider (and its MDBX read txn) held for the current block, between `BeginBlock` and
184 // `EndBlock`. `None` while idle, so no read txn is pinned across the inter-block gap.
185 let mut provider: Option<CachedStateProvider<EvmStateProviderBox>> = None;
186
187 // Blocks when idle; the channel disconnects (and the loop ends) when the pool is dropped.
188 while let Ok(msg) = rx.recv() {
189 match msg {
190 PrewarmMsg::BeginBlock { build, caches, txpool_snapshot } => {
191 provider = match (build)() {
192 Ok(inner) => Some(
193 CachedStateProvider::new_prewarm(inner, caches)
194 .with_txpool_snapshot(txpool_snapshot),
195 ),
196 Err(err) => {
197 trace!(target: "engine::tree::bal_prewarm_pool", %err, "failed to build provider");
198 None
199 }
200 };
201 }
202 PrewarmMsg::Warm(target) => {
203 let Some(provider) = provider.as_ref() else { continue };
204 match target {
205 PrewarmTarget::Account(addr, slots) => {
206 let _ = provider.basic_account(&addr);
207 for &slot in &slots {
208 let _ = provider.storage(addr, slot);
209 }
210 }
211 PrewarmTarget::Storage(addr, slots) => {
212 for &slot in &slots {
213 let _ = provider.storage(addr, slot);
214 }
215 }
216 }
217 }
218 PrewarmMsg::EndBlock(end_tx) => {
219 provider = None;
220 drop(end_tx);
221 }
222 }
223 }
224}
225
226struct SendOnDrop {
227 sender: Option<oneshot::Sender<()>>,
228}
229
230impl Drop for SendOnDrop {
231 fn drop(&mut self) {
232 if let Some(sender) = self.sender.take() {
233 let _ = sender.send(());
234 }
235 }
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241 use reth_provider::ProviderError;
242 use std::time::{Duration, Instant};
243
244 #[reth_concurrency::test]
245 fn drop_waits_for_the_workers_to_exit() {
246 let num_threads = 4;
247 let started = Arc::new(AtomicUsize::new(0));
248 let finished = Arc::new(AtomicUsize::new(0));
249 let pool = BalPrewarmPool::new(num_threads);
250 let build: Arc<BuildProviderFn> = {
251 let (started, finished) = (started.clone(), finished.clone());
252 Arc::new(move || {
253 started.fetch_add(1, Ordering::SeqCst);
254 thread::sleep(Duration::from_millis(50));
255 finished.fetch_add(1, Ordering::SeqCst);
256 Err(ProviderError::UnsupportedProvider)
257 })
258 };
259 pool.begin_block(build, ExecutionCache::new(1_000), None);
260 let deadline = Instant::now() + Duration::from_secs(5);
261 while started.load(Ordering::SeqCst) < num_threads {
262 assert!(Instant::now() < deadline, "BAL prewarm workers did not start");
263 thread::yield_now();
264 }
265
266 drop(pool);
267 assert_eq!(finished.load(Ordering::SeqCst), num_threads);
268 }
269}