Skip to main content

reth_exex/backfill/
job.rs

1use crate::StreamBackfillJob;
2use reth_evm::ConfigureEvm;
3use std::{
4    collections::BTreeMap,
5    ops::RangeInclusive,
6    time::{Duration, Instant},
7};
8
9use alloy_consensus::BlockHeader;
10use alloy_primitives::BlockNumber;
11use reth_ethereum_primitives::Receipt;
12use reth_evm::execute::{BlockExecutionError, BlockExecutionOutput, Executor};
13use reth_node_api::{Block as _, BlockBody as _, NodePrimitives};
14use reth_primitives_traits::{format_gas_throughput, RecoveredBlock, SignedTransaction};
15use reth_provider::{
16    BlockReader, Chain, ExecutionOutcome, ProviderError, StateProvider, StateProviderFactory,
17    TransactionVariant,
18};
19use reth_prune_types::PruneModes;
20use reth_revm::database::StateProviderDatabase;
21use reth_stages_api::ExecutionStageThresholds;
22use reth_tracing::tracing::{debug, trace};
23
24pub(super) type BackfillJobResult<T> = Result<T, BlockExecutionError>;
25
26/// Backfill job started for a specific range.
27///
28/// It implements [`Iterator`] that executes blocks in batches according to the provided thresholds
29/// and yields [`Chain`]. In other words, this iterator can yield multiple items for the given range
30/// depending on the configured thresholds.
31#[derive(Debug)]
32pub struct BackfillJob<E, P> {
33    pub(crate) evm_config: E,
34    pub(crate) provider: P,
35    pub(crate) prune_modes: PruneModes,
36    pub(crate) thresholds: ExecutionStageThresholds,
37    pub(crate) range: RangeInclusive<BlockNumber>,
38    pub(crate) stream_parallelism: usize,
39}
40
41impl<E, P> Iterator for BackfillJob<E, P>
42where
43    E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
44    P: BlockReader<Transaction: SignedTransaction> + StateProviderFactory,
45{
46    type Item = BackfillJobResult<Chain<E::Primitives>>;
47
48    fn next(&mut self) -> Option<Self::Item> {
49        if self.range.is_empty() {
50            return None
51        }
52
53        Some(self.execute_range())
54    }
55}
56
57impl<E, P> BackfillJob<E, P>
58where
59    E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
60    P: BlockReader<Transaction: SignedTransaction> + StateProviderFactory,
61{
62    /// Converts the backfill job into a single block backfill job.
63    pub fn into_single_blocks(self) -> SingleBlockBackfillJob<E, P> {
64        self.into()
65    }
66
67    /// Converts the backfill job into a stream.
68    pub fn into_stream(self) -> StreamBackfillJob<E, P, Chain<E::Primitives>> {
69        self.into()
70    }
71
72    fn execute_range(&mut self) -> BackfillJobResult<Chain<E::Primitives>> {
73        debug!(
74            target: "exex::backfill",
75            range = ?self.range,
76            "Executing block range"
77        );
78
79        let mut executor = self.evm_config.batch_executor(StateProviderDatabase::new(
80            self.provider
81                .history_by_block_number(self.range.start().saturating_sub(1))
82                .map_err(BlockExecutionError::other)?
83                .into_evm_state_provider(),
84        ));
85
86        let mut fetch_block_duration = Duration::default();
87        let mut execution_duration = Duration::default();
88        let mut cumulative_gas = 0;
89        let batch_start = Instant::now();
90
91        let mut blocks = Vec::new();
92        let mut results = Vec::new();
93        for block_number in self.range.clone() {
94            // Fetch the block
95            let fetch_block_start = Instant::now();
96
97            // we need the block's transactions along with their hashes
98            let block = self
99                .provider
100                .sealed_block_with_senders(block_number.into(), TransactionVariant::WithHash)
101                .map_err(BlockExecutionError::other)?
102                .ok_or_else(|| ProviderError::HeaderNotFound(block_number.into()))
103                .map_err(BlockExecutionError::other)?;
104
105            fetch_block_duration += fetch_block_start.elapsed();
106
107            cumulative_gas += block.gas_used();
108
109            // Configure the executor to use the current state.
110            trace!(target: "exex::backfill", number = block_number, txs = block.body().transactions().len(), "Executing block");
111
112            // Execute the block
113            let execute_start = Instant::now();
114
115            // Unseal the block for execution
116            let (block, senders) = block.split_sealed();
117            let (header, body) = block.split_sealed_header_body();
118            let block = P::Block::new_sealed(header, body).with_senders(senders);
119
120            results.push(executor.execute_one(&block)?);
121            execution_duration += execute_start.elapsed();
122
123            // Seal the block back and save it
124            blocks.push(block);
125            // Check if we should commit now
126            if self.thresholds.is_end_of_batch(
127                block_number - *self.range.start() + 1,
128                executor.size_hint() as u64,
129                cumulative_gas,
130                batch_start.elapsed(),
131            ) {
132                break
133            }
134        }
135
136        let first_block_number = blocks.first().expect("blocks should not be empty").number();
137        let last_block_number = blocks.last().expect("blocks should not be empty").number();
138        debug!(
139            target: "exex::backfill",
140            range = ?*self.range.start()..=last_block_number,
141            block_fetch = ?fetch_block_duration,
142            execution = ?execution_duration,
143            throughput = format_gas_throughput(cumulative_gas, execution_duration),
144            "Finished executing block range"
145        );
146        self.range = last_block_number + 1..=*self.range.end();
147
148        let outcome = ExecutionOutcome::from_blocks(
149            first_block_number,
150            executor.into_state().take_bundle(),
151            results,
152        );
153        let chain = Chain::new(blocks, outcome, BTreeMap::new());
154        Ok(chain)
155    }
156}
157
158/// Single block Backfill job started for a specific range.
159///
160/// It implements [`Iterator`] which executes a block each time the
161/// iterator is advanced and yields ([`RecoveredBlock`], [`BlockExecutionOutput`])
162#[derive(Debug, Clone)]
163pub struct SingleBlockBackfillJob<E, P> {
164    pub(crate) evm_config: E,
165    pub(crate) provider: P,
166    pub(crate) range: RangeInclusive<BlockNumber>,
167    pub(crate) stream_parallelism: usize,
168}
169
170impl<E, P> Iterator for SingleBlockBackfillJob<E, P>
171where
172    E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
173    P: BlockReader + StateProviderFactory,
174{
175    type Item = BackfillJobResult<(
176        RecoveredBlock<P::Block>,
177        BlockExecutionOutput<<E::Primitives as NodePrimitives>::Receipt>,
178    )>;
179
180    fn next(&mut self) -> Option<Self::Item> {
181        self.range.next().map(|block_number| self.execute_block(block_number))
182    }
183}
184
185impl<E, P> SingleBlockBackfillJob<E, P>
186where
187    E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
188    P: BlockReader + StateProviderFactory,
189{
190    /// Converts the single block backfill job into a stream.
191    pub fn into_stream(
192        self,
193    ) -> StreamBackfillJob<
194        E,
195        P,
196        (RecoveredBlock<reth_ethereum_primitives::Block>, BlockExecutionOutput<Receipt>),
197    > {
198        self.into()
199    }
200
201    #[expect(clippy::type_complexity)]
202    pub(crate) fn execute_block(
203        &self,
204        block_number: u64,
205    ) -> BackfillJobResult<(
206        RecoveredBlock<P::Block>,
207        BlockExecutionOutput<<E::Primitives as NodePrimitives>::Receipt>,
208    )> {
209        // Fetch the block with senders for execution.
210        let block_with_senders = self
211            .provider
212            .recovered_block(block_number.into(), TransactionVariant::WithHash)
213            .map_err(BlockExecutionError::other)?
214            .ok_or_else(|| ProviderError::HeaderNotFound(block_number.into()))
215            .map_err(BlockExecutionError::other)?;
216
217        // Configure the executor to use the previous block's state.
218        let executor = self.evm_config.batch_executor(StateProviderDatabase::new(
219            self.provider
220                .history_by_block_number(block_number.saturating_sub(1))
221                .map_err(BlockExecutionError::other)?
222                .into_evm_state_provider(),
223        ));
224
225        trace!(target: "exex::backfill", number = block_number, txs = block_with_senders.body().transaction_count(), "Executing block");
226
227        let block_execution_output = executor.execute(&block_with_senders)?;
228
229        Ok((block_with_senders, block_execution_output))
230    }
231}
232
233impl<E, P> From<BackfillJob<E, P>> for SingleBlockBackfillJob<E, P> {
234    fn from(job: BackfillJob<E, P>) -> Self {
235        Self {
236            evm_config: job.evm_config,
237            provider: job.provider,
238            range: job.range,
239            stream_parallelism: job.stream_parallelism,
240        }
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use crate::{
247        backfill::{
248            job::ExecutionStageThresholds,
249            test_utils::{blocks_and_execution_outputs, chain_spec, to_execution_outcome},
250        },
251        BackfillJobFactory,
252    };
253    use alloy_consensus::BlockHeader;
254    use reth_db_common::init::init_genesis;
255    use reth_evm_ethereum::EthEvmConfig;
256    use reth_primitives_traits::crypto::secp256k1::public_key_to_address;
257    use reth_provider::{
258        providers::BlockchainProvider, test_utils::create_test_provider_factory_with_chain_spec,
259    };
260    use reth_testing_utils::generators;
261
262    #[test]
263    fn test_backfill() -> eyre::Result<()> {
264        reth_tracing::init_test_tracing();
265
266        // Create a key pair for the sender
267        let key_pair = generators::generate_key(&mut generators::rng());
268        let address = public_key_to_address(key_pair.public_key());
269
270        let chain_spec = chain_spec(address);
271
272        let executor = EthEvmConfig::ethereum(chain_spec.clone());
273        let provider_factory = create_test_provider_factory_with_chain_spec(chain_spec.clone());
274        init_genesis(&provider_factory)?;
275        let blockchain_db = BlockchainProvider::new(provider_factory.clone())?;
276
277        let blocks_and_execution_outputs =
278            blocks_and_execution_outputs(provider_factory, chain_spec, key_pair)?;
279        let (block, block_execution_output) = blocks_and_execution_outputs.first().unwrap();
280        let execution_outcome = to_execution_outcome(block.number, block_execution_output);
281
282        // Backfill the first block
283        let factory = BackfillJobFactory::new(executor, blockchain_db);
284        let job = factory.backfill(1..=1);
285        let chains = job.collect::<Result<Vec<_>, _>>()?;
286
287        // Assert that the backfill job produced the same chain as we got before when we were
288        // executing only the first block
289        assert_eq!(chains.len(), 1);
290        let mut chain = chains.into_iter().next().unwrap();
291        chain.execution_outcome_mut().bundle.reverts.sort();
292        assert_eq!(chain.blocks().len(), 1);
293        assert_eq!(chain.blocks().get(&1).map(|block| block.as_ref()), Some(block));
294        assert_eq!(chain.execution_outcome(), &execution_outcome);
295
296        Ok(())
297    }
298
299    #[test]
300    fn test_single_block_backfill() -> eyre::Result<()> {
301        reth_tracing::init_test_tracing();
302
303        // Create a key pair for the sender
304        let key_pair = generators::generate_key(&mut generators::rng());
305        let address = public_key_to_address(key_pair.public_key());
306
307        let chain_spec = chain_spec(address);
308
309        let executor = EthEvmConfig::ethereum(chain_spec.clone());
310        let provider_factory = create_test_provider_factory_with_chain_spec(chain_spec.clone());
311        init_genesis(&provider_factory)?;
312        let blockchain_db = BlockchainProvider::new(provider_factory.clone())?;
313
314        let blocks_and_execution_outcomes =
315            blocks_and_execution_outputs(provider_factory, chain_spec, key_pair)?;
316
317        // Backfill the first block
318        let factory = BackfillJobFactory::new(executor, blockchain_db);
319        let job = factory.backfill(1..=1);
320        let single_job = job.into_single_blocks();
321        let block_execution_it = single_job.into_iter();
322
323        // Assert that the backfill job only produces a single block
324        let blocks_and_outcomes = block_execution_it.collect::<Vec<_>>();
325        assert_eq!(blocks_and_outcomes.len(), 1);
326
327        // Assert that the backfill job single block iterator produces the expected output for each
328        // block
329        for (i, res) in blocks_and_outcomes.into_iter().enumerate() {
330            let (block, mut execution_output) = res?;
331            execution_output.state.reverts.sort();
332
333            let expected_block = blocks_and_execution_outcomes[i].0.clone();
334            let expected_output = &blocks_and_execution_outcomes[i].1;
335
336            assert_eq!(block, expected_block);
337            assert_eq!(&execution_output, expected_output);
338        }
339
340        Ok(())
341    }
342
343    /// Verify that ExEx backfill (using `history_by_block_number`) produces identical execution
344    /// results to the pipeline path (using `LatestStateProvider`).
345    ///
346    /// This is a regression test for an issue reported on mainnet where backfill fails around
347    /// blocks 1.7M-3.8M with "transaction gas limit X is more than blocks available gas Y",
348    /// suggesting the state provider used during backfill may return different state than what the
349    /// pipeline used during initial sync.
350    #[test]
351    fn test_backfill_state_provider_parity() -> eyre::Result<()> {
352        reth_tracing::init_test_tracing();
353
354        let key_pair = generators::generate_key(&mut generators::rng());
355        let address = public_key_to_address(key_pair.public_key());
356
357        let chain_spec = chain_spec(address);
358
359        let executor = EthEvmConfig::ethereum(chain_spec.clone());
360        let provider_factory = create_test_provider_factory_with_chain_spec(chain_spec.clone());
361        init_genesis(&provider_factory)?;
362        let blockchain_db = BlockchainProvider::new(provider_factory.clone())?;
363
364        // Execute blocks via LatestStateProvider (pipeline-style) and commit to DB.
365        // This mirrors what the pipeline's ExecutionStage does.
366        let pipeline_results =
367            blocks_and_execution_outputs(provider_factory, chain_spec, key_pair)?;
368
369        // Now re-execute via SingleBlockBackfillJob which uses history_by_block_number.
370        let factory = BackfillJobFactory::new(executor, blockchain_db);
371        let job = factory.backfill(1..=2);
372        let single_job = job.into_single_blocks();
373        let backfill_results: Vec<_> = single_job.into_iter().collect::<Result<Vec<_>, _>>()?;
374
375        assert_eq!(
376            pipeline_results.len(),
377            backfill_results.len(),
378            "should produce same number of block results"
379        );
380
381        for (i, ((pipeline_block, pipeline_output), (backfill_block, mut backfill_output))) in
382            pipeline_results.iter().zip(backfill_results).enumerate()
383        {
384            backfill_output.state.reverts.sort();
385
386            assert_eq!(
387                backfill_block, *pipeline_block,
388                "block {i} mismatch between pipeline and backfill"
389            );
390
391            assert_eq!(
392                backfill_output.receipts, pipeline_output.receipts,
393                "block {i}: receipts differ — gas accounting divergence between \
394                 LatestStateProvider and history_by_block_number"
395            );
396
397            assert_eq!(
398                backfill_output.gas_used, pipeline_output.gas_used,
399                "block {i}: gas_used differs"
400            );
401
402            assert_eq!(
403                &backfill_output, pipeline_output,
404                "block {i}: full execution output differs between pipeline and backfill"
405            );
406        }
407
408        Ok(())
409    }
410
411    /// Same as above but for the batch `BackfillJob` path (`execute_range`), which also uses
412    /// `history_by_block_number`. Verifies the batch execution outcome matches what the pipeline
413    /// produced block-by-block.
414    #[test]
415    fn test_backfill_batch_state_provider_parity() -> eyre::Result<()> {
416        reth_tracing::init_test_tracing();
417
418        let key_pair = generators::generate_key(&mut generators::rng());
419        let address = public_key_to_address(key_pair.public_key());
420
421        let chain_spec = chain_spec(address);
422
423        let executor = EthEvmConfig::ethereum(chain_spec.clone());
424        let provider_factory = create_test_provider_factory_with_chain_spec(chain_spec.clone());
425        init_genesis(&provider_factory)?;
426        let blockchain_db = BlockchainProvider::new(provider_factory.clone())?;
427
428        let pipeline_results =
429            blocks_and_execution_outputs(provider_factory, chain_spec, key_pair)?;
430
431        // Re-execute via batch BackfillJob (execute_range) using history_by_block_number
432        let factory = BackfillJobFactory::new(executor, blockchain_db);
433        let job = factory.backfill(1..=2);
434        let chains = job.collect::<Result<Vec<_>, _>>()?;
435
436        assert_eq!(chains.len(), 1, "two blocks without threshold should yield one chain");
437        let chain = chains.into_iter().next().unwrap();
438
439        // Compare each block's receipts from the chain against the pipeline outputs
440        for (i, (pipeline_block, pipeline_output)) in pipeline_results.iter().enumerate() {
441            let block_number = pipeline_block.number();
442            let chain_block = chain.blocks().get(&block_number).expect("block should be in chain");
443            assert_eq!(
444                chain_block.as_ref(),
445                pipeline_block,
446                "block {i}: block mismatch in batch backfill"
447            );
448
449            let chain_receipts = &chain.execution_outcome().receipts[i];
450            assert_eq!(
451                chain_receipts, &pipeline_output.receipts,
452                "block {i}: receipts differ in batch backfill — potential gas accounting \
453                 divergence between LatestStateProvider and history_by_block_number"
454            );
455        }
456
457        Ok(())
458    }
459
460    #[test]
461    fn test_backfill_with_batch_threshold() -> eyre::Result<()> {
462        reth_tracing::init_test_tracing();
463
464        // Create a key pair for the sender
465        let key_pair = generators::generate_key(&mut generators::rng());
466        let address = public_key_to_address(key_pair.public_key());
467
468        let chain_spec = chain_spec(address);
469
470        let executor = EthEvmConfig::ethereum(chain_spec.clone());
471        let provider_factory = create_test_provider_factory_with_chain_spec(chain_spec.clone());
472        init_genesis(&provider_factory)?;
473        let blockchain_db = BlockchainProvider::new(provider_factory.clone())?;
474
475        let blocks_and_execution_outputs =
476            blocks_and_execution_outputs(provider_factory, chain_spec, key_pair)?;
477        let (block1, output1) = blocks_and_execution_outputs[0].clone();
478        let (block2, output2) = blocks_and_execution_outputs[1].clone();
479
480        // Backfill with max_blocks=1, expect two separate chains
481        let factory = BackfillJobFactory::new(executor, blockchain_db).with_thresholds(
482            ExecutionStageThresholds { max_blocks: Some(1), ..Default::default() },
483        );
484        let job = factory.backfill(1..=2);
485        let chains = job.collect::<Result<Vec<_>, _>>()?;
486
487        // Assert two chains, each with one block
488        assert_eq!(chains.len(), 2);
489
490        let mut chain1 = chains[0].clone();
491        chain1.execution_outcome_mut().bundle.reverts.sort();
492        assert_eq!(chain1.blocks().len(), 1);
493        assert_eq!(chain1.blocks().get(&1).map(|block| block.as_ref()), Some(&block1));
494        assert_eq!(chain1.execution_outcome(), &to_execution_outcome(1, &output1));
495
496        let mut chain2 = chains[1].clone();
497        chain2.execution_outcome_mut().bundle.reverts.sort();
498        assert_eq!(chain2.blocks().len(), 1);
499        assert_eq!(chain2.blocks().get(&2).map(|block| block.as_ref()), Some(&block2));
500        assert_eq!(chain2.execution_outcome(), &to_execution_outcome(2, &output2));
501
502        Ok(())
503    }
504}