1use super::job::BackfillJobResult;
2use crate::{BackfillJob, SingleBlockBackfillJob};
3use alloy_primitives::BlockNumber;
4use futures::{
5 future::{BoxFuture, Either},
6 stream::{FuturesOrdered, Stream},
7 StreamExt,
8};
9use reth_evm::{
10 execute::{BlockExecutionError, BlockExecutionOutput},
11 ConfigureEvm,
12};
13use reth_node_api::NodePrimitives;
14use reth_primitives_traits::RecoveredBlock;
15use reth_provider::{BlockReader, Chain, ProviderError, StateProviderFactory};
16use reth_prune_types::PruneModes;
17use reth_stages_api::ExecutionStageThresholds;
18use std::{
19 ops::RangeInclusive,
20 pin::Pin,
21 task::{ready, Context, Poll},
22 time::Duration,
23};
24use tokio::task::{JoinError, JoinHandle};
25use tracing::debug;
26
27pub(crate) const DEFAULT_PARALLELISM: usize = 4;
29const DEFAULT_BATCH_SIZE: usize = 100;
31const BACKFILL_RETRY_DELAY: Duration = Duration::from_secs(1);
33const MAX_BACKFILL_RETRIES: u16 = 300;
35
36type BackfillTaskIterator<T> =
38 Box<dyn Iterator<Item = BackfillJobResult<T>> + Send + Sync + 'static>;
39
40struct BackfillTaskOutput<T> {
42 job: BackfillTaskIterator<T>,
43 result: Option<BackfillJobResult<T>>,
44}
45
46type BackfillTask<T> = Either<
48 JoinHandle<BackfillTaskOutput<T>>,
49 BoxFuture<'static, Result<BackfillTaskOutput<T>, JoinError>>,
50>;
51
52pub(super) type SingleBlockStreamItem<N> = (
53 RecoveredBlock<<N as NodePrimitives>::Block>,
54 BlockExecutionOutput<<N as NodePrimitives>::Receipt>,
55);
56type BatchBlockStreamItem<N> = Chain<N>;
57
58#[derive(Debug)]
65pub struct StreamBackfillJob<E, P, T> {
66 evm_config: E,
67 provider: P,
68 prune_modes: PruneModes,
69 range: RangeInclusive<BlockNumber>,
70 tasks: FuturesOrdered<BackfillTask<T>>,
71 retries: u16,
72 parallelism: usize,
73 batch_size: usize,
74 thresholds: ExecutionStageThresholds,
75}
76
77impl<E, P, T> StreamBackfillJob<E, P, T>
78where
79 T: Send + Sync + 'static,
80{
81 pub const fn with_parallelism(mut self, parallelism: usize) -> Self {
83 self.parallelism = parallelism;
84 self
85 }
86
87 pub const fn with_batch_size(mut self, batch_size: usize) -> Self {
89 self.batch_size = batch_size;
90 self
91 }
92
93 fn backfill_task(mut job: BackfillTaskIterator<T>, retry: bool) -> BackfillTask<T> {
94 let next = move || BackfillTaskOutput { result: job.next(), job };
95 if retry {
96 Either::Right(Box::pin(async move {
97 tokio::time::sleep(BACKFILL_RETRY_DELAY).await;
98 tokio::task::spawn_blocking(next).await
99 }))
100 } else {
101 Either::Left(tokio::task::spawn_blocking(next))
102 }
103 }
104
105 fn poll_next_task(
107 &mut self,
108 cx: &mut Context<'_>,
109 max_retries: u16,
110 ) -> Poll<Option<BackfillJobResult<T>>> {
111 while let Some(res) = ready!(self.tasks.poll_next_unpin(cx)) {
112 let task_result = res.map_err(BlockExecutionError::other)?;
113
114 if let BackfillTaskOutput { result: Some(job_result), job } = task_result {
115 let retry = max_retries != 0 &&
117 matches!(
118 job_result
119 .as_ref()
120 .err()
121 .and_then(BlockExecutionError::as_internal)
122 .and_then(|error| error.downcast_other::<ProviderError>()),
123 Some(ProviderError::StateUnavailableDuringSync)
124 );
125 self.tasks.push_front(Self::backfill_task(job, retry));
127
128 if retry && self.retries < max_retries {
129 self.retries += 1;
130 } else {
131 self.retries = 0;
132 return Poll::Ready(Some(job_result))
133 }
134 };
135 }
136
137 Poll::Ready(None)
138 }
139}
140
141impl<E, P> Stream for StreamBackfillJob<E, P, SingleBlockStreamItem<E::Primitives>>
142where
143 E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
144 P: BlockReader + StateProviderFactory + Clone + Unpin + 'static,
145{
146 type Item = BackfillJobResult<SingleBlockStreamItem<E::Primitives>>;
147
148 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
149 let this = self.get_mut();
150
151 while this.tasks.len() < this.parallelism {
153 let Some(block_number) = this.range.next() else {
155 debug!(target: "exex::backfill", tasks = %this.tasks.len(), range = ?this.range, "No more single blocks to backfill");
156 break;
157 };
158
159 debug!(target: "exex::backfill", tasks = %this.tasks.len(), ?block_number, "Spawning new single block backfill task");
161 let job = Box::new(SingleBlockBackfillJob {
162 evm_config: this.evm_config.clone(),
163 provider: this.provider.clone(),
164 range: block_number..=block_number,
165 stream_parallelism: this.parallelism,
166 }) as BackfillTaskIterator<_>;
167 this.tasks.push_back(Self::backfill_task(job, false));
168 }
169
170 this.poll_next_task(cx, 0)
171 }
172}
173
174impl<E, P> Stream for StreamBackfillJob<E, P, BatchBlockStreamItem<E::Primitives>>
175where
176 E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
177 P: BlockReader + StateProviderFactory + Clone + Unpin + 'static,
178{
179 type Item = BackfillJobResult<BatchBlockStreamItem<E::Primitives>>;
180
181 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
182 let this = self.get_mut();
183
184 loop {
185 while this.tasks.len() < this.parallelism {
187 let mut range = this.range.by_ref().take(this.batch_size);
189 let start = range.next();
190 let range_bounds = start.zip(range.last().or(start));
191
192 let Some(range) = range_bounds.map(|(first, last)| first..=last) else {
194 debug!(target: "exex::backfill", tasks = %this.tasks.len(), range = ?this.range, "No more block batches to backfill");
195 break;
196 };
197
198 debug!(target: "exex::backfill", tasks = %this.tasks.len(), ?range, "Spawning new block batch backfill task");
200 let job = Box::new(BackfillJob {
201 evm_config: this.evm_config.clone(),
202 provider: this.provider.clone(),
203 prune_modes: this.prune_modes.clone(),
204 thresholds: this.thresholds.clone(),
205 range,
206 stream_parallelism: this.parallelism,
207 }) as BackfillTaskIterator<_>;
208 this.tasks.push_back(Self::backfill_task(job, false));
209 }
210
211 let res = ready!(this.poll_next_task(cx, MAX_BACKFILL_RETRIES));
212
213 if res.is_some() {
214 return Poll::Ready(res);
215 }
216
217 if this.range.is_empty() {
218 return Poll::Ready(None);
220 }
221 }
222 }
223}
224
225impl<E, P> From<SingleBlockBackfillJob<E, P>>
226 for StreamBackfillJob<E, P, SingleBlockStreamItem<E::Primitives>>
227where
228 E: ConfigureEvm,
229{
230 fn from(job: SingleBlockBackfillJob<E, P>) -> Self {
231 Self {
232 evm_config: job.evm_config,
233 provider: job.provider,
234 prune_modes: PruneModes::default(),
235 range: job.range,
236 tasks: FuturesOrdered::new(),
237 retries: 0,
238 parallelism: job.stream_parallelism,
239 batch_size: 1,
240 thresholds: ExecutionStageThresholds { max_blocks: Some(1), ..Default::default() },
241 }
242 }
243}
244
245impl<E, P> From<BackfillJob<E, P>> for StreamBackfillJob<E, P, BatchBlockStreamItem<E::Primitives>>
246where
247 E: ConfigureEvm,
248{
249 fn from(job: BackfillJob<E, P>) -> Self {
250 let batch_size = job.thresholds.max_blocks.map_or(DEFAULT_BATCH_SIZE, |max| max as usize);
251 Self {
252 evm_config: job.evm_config,
253 provider: job.provider,
254 prune_modes: job.prune_modes,
255 range: job.range,
256 tasks: FuturesOrdered::new(),
257 retries: 0,
258 parallelism: job.stream_parallelism,
259 batch_size,
260 thresholds: ExecutionStageThresholds {
261 max_blocks: Some(batch_size as u64),
262 ..job.thresholds
263 },
264 }
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271 use crate::{
272 backfill::test_utils::{
273 blocks_and_execution_outcome, blocks_and_execution_outputs, chain_spec,
274 execute_block_and_commit_to_database,
275 },
276 BackfillJobFactory,
277 };
278 use alloy_consensus::{constants::ETH_TO_WEI, Header, TxEip2930};
279 use alloy_primitives::{b256, Address, TxKind, U256};
280 use eyre::Result;
281 use futures::StreamExt;
282 use reth_chainspec::{ChainSpec, EthereumHardfork, MIN_TRANSACTION_GAS};
283 use reth_db_common::init::init_genesis;
284 use reth_ethereum_primitives::{Block, BlockBody, Transaction};
285 use reth_evm_ethereum::EthEvmConfig;
286 use reth_primitives_traits::{Block as _, NodePrimitives};
287 use reth_provider::{
288 providers::{BlockchainProvider, ProviderNodeTypes},
289 test_utils::create_test_provider_factory_with_chain_spec,
290 ProviderFactory,
291 };
292 use reth_stages_api::ExecutionStageThresholds;
293 use reth_testing_utils::{generators, generators::sign_tx_with_key_pair};
294 use secp256k1::Keypair;
295 use std::{future, iter, sync::Arc};
296
297 #[tokio::test]
298 async fn test_single_blocks() -> eyre::Result<()> {
299 reth_tracing::init_test_tracing();
300
301 let key_pair = generators::generate_key(&mut generators::rng());
303 let address =
304 Address::from_raw_public_key(&key_pair.public_key().serialize_uncompressed()[1..]);
305
306 let chain_spec = chain_spec(address);
307
308 let executor = EthEvmConfig::ethereum(chain_spec.clone());
309 let provider_factory = create_test_provider_factory_with_chain_spec(chain_spec.clone());
310 init_genesis(&provider_factory)?;
311 let blockchain_db = BlockchainProvider::new(provider_factory.clone())?;
312
313 let blocks_and_execution_outcomes =
315 blocks_and_execution_outputs(provider_factory, chain_spec, key_pair)?;
316
317 let factory = BackfillJobFactory::new(executor.clone(), blockchain_db.clone());
319 let mut backfill_stream = factory.backfill(1..=1).into_single_blocks().into_stream();
320
321 let (block, execution_output) = backfill_stream.next().await.unwrap().unwrap();
323 let expected_block = blocks_and_execution_outcomes[0].0.clone();
324 let expected_output = &blocks_and_execution_outcomes[0].1;
325 assert_eq!(block, expected_block);
326 assert_eq!(&execution_output, expected_output);
327
328 assert!(backfill_stream.next().await.is_none());
330
331 Ok(())
332 }
333
334 #[tokio::test]
335 async fn test_batch() -> eyre::Result<()> {
336 reth_tracing::init_test_tracing();
337
338 let key_pair = generators::generate_key(&mut generators::rng());
340 let address =
341 Address::from_raw_public_key(&key_pair.public_key().serialize_uncompressed()[1..]);
342
343 let chain_spec = chain_spec(address);
344
345 let executor = EthEvmConfig::ethereum(chain_spec.clone());
346 let provider_factory = create_test_provider_factory_with_chain_spec(chain_spec.clone());
347 init_genesis(&provider_factory)?;
348 let blockchain_db = BlockchainProvider::new(provider_factory.clone())?;
349
350 let (blocks, execution_outcome) =
352 blocks_and_execution_outcome(provider_factory, chain_spec, key_pair)?;
353
354 let factory = BackfillJobFactory::new(executor.clone(), blockchain_db.clone())
356 .with_thresholds(ExecutionStageThresholds { max_blocks: Some(2), ..Default::default() })
357 .with_stream_parallelism(1);
358 let mut backfill_stream = factory.backfill(1..=2).into_stream();
359 let chain = backfill_stream.next().await.unwrap().unwrap();
360
361 assert!(chain.blocks_iter().map(|block| block.as_ref()).eq(&blocks));
362 assert_eq!(chain.execution_outcome(), &execution_outcome);
363
364 assert!(backfill_stream.next().await.is_none());
366
367 Ok(())
368 }
369
370 #[tokio::test(start_paused = true)]
371 async fn backfill_retries_temporary_state_errors_in_order() -> eyre::Result<()> {
372 let mut backfill = StreamBackfillJob::<(), (), u64> {
373 evm_config: (),
374 provider: (),
375 prune_modes: PruneModes::default(),
376 range: 1..=2,
377 tasks: FuturesOrdered::new(),
378 retries: 0,
379 parallelism: 2,
380 batch_size: 1,
381 thresholds: ExecutionStageThresholds::default(),
382 };
383 let temporary_error =
384 || Err(BlockExecutionError::other(ProviderError::StateUnavailableDuringSync));
385 backfill.tasks.push_back(Either::Right(Box::pin(future::ready(Ok(BackfillTaskOutput {
386 result: Some(temporary_error()),
387 job: Box::new(iter::once(Ok(1))),
388 })))));
389 backfill.tasks.push_back(Either::Right(Box::pin(future::ready(Ok(BackfillTaskOutput {
390 result: Some(Ok(2)),
391 job: Box::new(
392 iter::once(Err(BlockExecutionError::other(ProviderError::HeaderNotFound(
393 3.into(),
394 ))))
395 .chain(iter::repeat_with(temporary_error).take(2)),
396 ),
397 })))));
398
399 let mut stream = futures::stream::poll_fn(|cx| backfill.poll_next_task(cx, 1));
400 assert!(futures::poll!(stream.next()).is_pending());
401 tokio::time::advance(BACKFILL_RETRY_DELAY).await;
402 assert_eq!(stream.next().await.transpose()?, Some(1));
403 assert_eq!(stream.next().await.transpose()?, Some(2));
404
405 let error = stream.next().await.unwrap().unwrap_err();
406 assert!(matches!(
407 error.as_internal().and_then(|error| error.downcast_other::<ProviderError>()),
408 Some(ProviderError::HeaderNotFound(block)) if *block == 3.into()
409 ));
410 let retry_start = tokio::time::Instant::now();
411 let error = stream.next().await.unwrap().unwrap_err();
412 assert!(matches!(
413 error.as_internal().and_then(|error| error.downcast_other::<ProviderError>()),
414 Some(ProviderError::StateUnavailableDuringSync)
415 ));
416 assert!(retry_start.elapsed() >= BACKFILL_RETRY_DELAY);
417
418 Ok(())
419 }
420
421 fn create_blocks(
422 chain_spec: &Arc<ChainSpec>,
423 key_pair: Keypair,
424 n: u64,
425 ) -> Result<Vec<RecoveredBlock<reth_ethereum_primitives::Block>>> {
426 let mut blocks = Vec::with_capacity(n as usize);
427 let mut parent_hash = chain_spec.genesis_hash();
428
429 for (i, nonce) in (1..=n).zip(0..n) {
430 let block = Block {
431 header: Header {
432 parent_hash,
433 receipts_root: b256!(
435 "0xd3a6acf9a244d78b33831df95d472c4128ea85bf079a1d41e32ed0b7d2244c9e"
436 ),
437 difficulty: chain_spec.fork(EthereumHardfork::Paris).ttd().expect("Paris TTD"),
438 number: i,
439 gas_limit: MIN_TRANSACTION_GAS,
440 gas_used: MIN_TRANSACTION_GAS,
441 ..Default::default()
442 },
443 body: BlockBody {
444 transactions: vec![sign_tx_with_key_pair(
445 key_pair,
446 Transaction::Eip2930(TxEip2930 {
447 chain_id: chain_spec.chain.id(),
448 nonce,
449 gas_limit: MIN_TRANSACTION_GAS,
450 gas_price: 1_500_000_000,
451 to: TxKind::Call(Address::ZERO),
452 value: U256::from(0.1 * ETH_TO_WEI as f64),
453 ..Default::default()
454 }),
455 )],
456 ..Default::default()
457 },
458 }
459 .try_into_recovered()?;
460
461 parent_hash = block.hash();
462 blocks.push(block);
463 }
464
465 Ok(blocks)
466 }
467
468 fn execute_and_commit_blocks<N>(
469 provider_factory: &ProviderFactory<N>,
470 chain_spec: &Arc<ChainSpec>,
471 blocks: &[RecoveredBlock<reth_ethereum_primitives::Block>],
472 ) -> Result<()>
473 where
474 N: ProviderNodeTypes<
475 Primitives: NodePrimitives<
476 Block = reth_ethereum_primitives::Block,
477 BlockBody = reth_ethereum_primitives::BlockBody,
478 Receipt = reth_ethereum_primitives::Receipt,
479 >,
480 >,
481 {
482 for block in blocks {
483 execute_block_and_commit_to_database(provider_factory, chain_spec.clone(), block)?;
484 }
485 Ok(())
486 }
487
488 #[tokio::test]
489 async fn test_batch_parallel_range_advance() -> Result<()> {
490 reth_tracing::init_test_tracing();
491
492 let key_pair = generators::generate_key(&mut generators::rng());
494 let address =
495 Address::from_raw_public_key(&key_pair.public_key().serialize_uncompressed()[1..]);
496
497 let chain_spec = chain_spec(address);
498
499 let executor = EthEvmConfig::ethereum(chain_spec.clone());
500 let provider_factory = create_test_provider_factory_with_chain_spec(chain_spec.clone());
501 init_genesis(&provider_factory)?;
502 let blockchain_db = BlockchainProvider::new(provider_factory.clone())?;
503
504 let blocks = create_blocks(&chain_spec, key_pair, 4)?;
506 execute_and_commit_blocks(&provider_factory, &chain_spec, &blocks)?;
507
508 let factory = BackfillJobFactory::new(executor.clone(), blockchain_db.clone())
510 .with_thresholds(ExecutionStageThresholds { max_blocks: Some(2), ..Default::default() })
511 .with_stream_parallelism(2);
512
513 let mut backfill_stream = factory.backfill(1..=4).into_stream();
515
516 let chain1 = backfill_stream.next().await.unwrap()?;
518 let chain2 = backfill_stream.next().await.unwrap()?;
519 assert!(backfill_stream.next().await.is_none());
520
521 let factory_seq =
523 BackfillJobFactory::new(executor.clone(), blockchain_db.clone()).with_thresholds(
524 ExecutionStageThresholds { max_blocks: Some(2), ..Default::default() },
525 );
526
527 let expected_chain1 =
528 factory_seq.backfill(1..=2).collect::<Result<Vec<_>, _>>()?.into_iter().next().unwrap();
529 let expected_chain2 =
530 factory_seq.backfill(3..=4).collect::<Result<Vec<_>, _>>()?.into_iter().next().unwrap();
531
532 assert_eq!(chain1.blocks(), expected_chain1.blocks());
534 assert_eq!(chain1.execution_outcome(), expected_chain1.execution_outcome());
535 assert_eq!(chain2.blocks(), expected_chain2.blocks());
536 assert_eq!(chain2.execution_outcome(), expected_chain2.execution_outcome());
537
538 Ok(())
539 }
540}