Skip to main content

reth_engine_tree/tree/
persist.rs

1//! Persistence scheduling and bookkeeping of the engine API tree handler.
2
3use crate::{
4    persistence::PersistenceResult,
5    tree::{
6        error::AdvancePersistenceError, payload_validator::EngineValidator, EngineApiTreeHandler,
7        WaitForCaches, CHANGESET_CACHE_RETENTION_BLOCKS,
8    },
9};
10use alloy_consensus::BlockHeader;
11use alloy_eips::{BlockNumHash, NumHash};
12use alloy_primitives::B256;
13use reth_concurrency::sync::{
14    channel::{self, TryRecvError},
15    time::FastInstant as Instant,
16};
17use reth_engine_primitives::{ConsensusEngineEvent, SlowBlockInfo};
18use reth_errors::ProviderResult;
19use reth_evm::ConfigureEvm;
20use reth_payload_primitives::{BuiltPayload, PayloadTypes};
21use reth_primitives_traits::NodePrimitives;
22use reth_provider::{
23    BalProvider, BlockReader, ChangeSetReader, DatabaseProviderFactory, ProviderError,
24    PruneCheckpointReader, SaveBlocksInput, StageCheckpointReader, StateProviderFactory,
25    StateReader, StorageChangeSetReader, StorageSettingsCache,
26};
27use std::time::Duration;
28use tracing::debug;
29
30impl<N, P, T, V, C> EngineApiTreeHandler<N, P, T, V, C>
31where
32    N: NodePrimitives,
33    P: DatabaseProviderFactory
34        + BlockReader<Block = N::Block, Header = N::BlockHeader>
35        + StateProviderFactory
36        + StateReader<Receipt = N::Receipt>
37        + BalProvider
38        + Clone
39        + 'static,
40    P::Provider: BlockReader<Block = N::Block, Header = N::BlockHeader>
41        + PruneCheckpointReader
42        + StageCheckpointReader
43        + ChangeSetReader
44        + StorageChangeSetReader
45        + StorageSettingsCache
46        + 'static,
47    C: ConfigureEvm<Primitives = N> + 'static,
48    T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>,
49    V: EngineValidator<T> + WaitForCaches,
50{
51    /// How many canonical blocks are retained in memory. A large count means persistence is
52    /// falling behind execution.
53    fn persistence_gap(&self) -> u64 {
54        self.canonical_in_memory_state().canonical_chain().count() as u64
55    }
56
57    /// How many blocks beyond the configured in-memory buffer are awaiting persistence.
58    fn persistence_backpressure_gap(&self) -> u64 {
59        self.persistence_gap().saturating_sub(self.config.memory_block_buffer_target())
60    }
61
62    /// Returns `true` when the main loop should stop draining the tree input channel.
63    ///
64    /// This is the case when persistence is already running and the number of blocks beyond the
65    /// configured in-memory buffer has reached the configured threshold.
66    pub(super) fn should_backpressure(&self) -> bool {
67        self.persistence_state.in_progress() &&
68            self.persistence_backpressure_gap() >=
69                self.config.persistence_backpressure_threshold()
70    }
71
72    /// Helper method to remove blocks and set the persistence state. This ensures we keep track of
73    /// the current persistence action while we're removing blocks.
74    pub(super) fn remove_blocks(&mut self, new_tip_num: u64) {
75        debug!(target: "engine::tree", ?new_tip_num, last_persisted_block_number=?self.persistence_state.last_persisted_block.number, "Removing blocks using persistence task");
76        if new_tip_num < self.persistence_state.last_persisted_block.number {
77            debug!(target: "engine::tree", ?new_tip_num, "Starting remove blocks job");
78            self.state.set_pending_sparse_trie_prune(false);
79            let (tx, rx) = channel::bounded(1);
80            let _ = self.persistence.remove_blocks_above(new_tip_num, tx);
81            self.persistence_state.start_remove(new_tip_num, rx);
82        }
83    }
84
85    /// Helper method to save blocks and set the persistence state. This ensures we keep track of
86    /// the current persistence action while we're saving blocks.
87    fn persist_blocks(&mut self, input: SaveBlocksInput<N>) {
88        let highest_num_hash = input.last_block();
89        debug!(target: "engine::tree", count=input.persist_rest_blocks().len(), blocks = ?input.persist_rest_blocks().iter().map(|block| block.recovered_block().num_hash()).collect::<Vec<_>>(), "Persisting blocks");
90
91        let (tx, rx) = channel::bounded(1);
92        let _ = self.persistence.save_blocks(input, tx);
93
94        self.persistence_state.start_save(highest_num_hash, rx);
95    }
96
97    /// Triggers new persistence actions if no persistence task is currently in progress.
98    ///
99    /// This checks if we need to remove blocks (disk reorg) or save new blocks to disk.
100    /// Persistence completion is handled separately via the `wait_for_event` method.
101    pub(super) fn advance_persistence(&mut self) -> Result<(), AdvancePersistenceError> {
102        if !self.persistence_state.in_progress() {
103            let payload_build_active = self.payload_builds.is_active();
104            if let Some(new_tip_num) = self.find_disk_reorg()? {
105                self.remove_blocks(new_tip_num)
106            } else if self.backfill_sync_state.is_pending_revalidation() &&
107                !payload_build_active &&
108                self.persistence_state.last_state_trie_persisted_block !=
109                    self.persistence_state.last_persisted_block
110            {
111                let Some(input) = self.get_save_blocks_input(PersistTarget::Persisted) else {
112                    return Err(AdvancePersistenceError::StateTrieCatchupUnavailable)
113                };
114                self.persist_blocks(input);
115            } else if self.backfill_sync_state.is_pending_revalidation() && !payload_build_active {
116                self.revalidate_pending_backfill()?;
117            } else if let Some(input) = self.get_save_blocks_input(PersistTarget::Threshold) {
118                self.persist_blocks(input);
119            }
120        }
121
122        Ok(())
123    }
124
125    /// Persists all remaining blocks until none are left.
126    pub(super) fn persist_until_complete(&mut self) -> Result<(), AdvancePersistenceError> {
127        loop {
128            // Wait for any in-progress persistence to complete (blocking)
129            if let Some((rx, start_time, action)) = self.persistence_state.rx.take() {
130                debug!(target: "engine::tree", ?action, "waiting for in-flight persistence");
131                let result = rx.recv().map_err(|_| AdvancePersistenceError::ChannelClosed)?;
132                self.on_persistence_complete(result, start_time)?;
133                continue
134            }
135
136            // Persistence can finish against a branch that the in-memory canonical chain has
137            // reorged away from. Unwind that stale disk branch before building a head-targeted
138            // save.
139            if let Some(new_tip_num) = self.find_disk_reorg()? {
140                self.remove_blocks(new_tip_num);
141                continue
142            }
143
144            let Some(input) = self.get_save_blocks_input(PersistTarget::Head) else {
145                debug!(target: "engine::tree", "persistence complete, signaling termination");
146                return Ok(())
147            };
148
149            debug!(target: "engine::tree", count = input.persist_rest_blocks().len(), "persisting remaining blocks before shutdown");
150            self.persist_blocks(input);
151        }
152    }
153
154    /// Tries to poll for a completed persistence task (non-blocking).
155    ///
156    /// Returns `true` if a persistence task was completed, `false` otherwise.
157    pub(super) fn try_poll_persistence(&mut self) -> Result<bool, AdvancePersistenceError> {
158        let Some((rx, start_time, action)) = self.persistence_state.rx.take() else {
159            return Ok(false);
160        };
161
162        match rx.try_recv() {
163            Ok(result) => {
164                self.on_persistence_complete(result, start_time)?;
165                Ok(true)
166            }
167            Err(TryRecvError::Empty) => {
168                // Not ready yet, put it back
169                self.persistence_state.rx = Some((rx, start_time, action));
170                Ok(false)
171            }
172            Err(TryRecvError::Disconnected) => Err(AdvancePersistenceError::ChannelClosed),
173        }
174    }
175
176    /// Handles a completed persistence task.
177    pub(super) fn on_persistence_complete(
178        &mut self,
179        result: PersistenceResult,
180        start_time: Instant,
181    ) -> Result<(), AdvancePersistenceError> {
182        self.metrics.engine.persistence_duration.record(start_time.elapsed());
183
184        let PersistenceResult { last_block, last_state_trie_block, commit_duration } = result;
185        debug_assert!(
186            last_state_trie_block.number <= last_block.number,
187            "state/trie frontier cannot exceed the last persisted block"
188        );
189
190        debug!(target: "engine::tree", ?last_block, ?last_state_trie_block, elapsed=?start_time.elapsed(), "Finished persisting, calling finish");
191        self.persistence_state.finish(last_block, last_state_trie_block);
192
193        let last_block_number = last_block.number;
194
195        // Evict cached changesets for blocks below the eviction threshold.
196        // Keep at least CHANGESET_CACHE_RETENTION_BLOCKS from the persisted tip, and also respect
197        // the finalized block if set.
198        let min_threshold = last_block_number.saturating_sub(CHANGESET_CACHE_RETENTION_BLOCKS);
199        let eviction_threshold =
200            if let Some(finalized) = self.canonical_in_memory_state().get_finalized_num_hash() {
201                // Use the minimum of finalized block and retention threshold to be conservative
202                finalized.number.min(min_threshold)
203            } else {
204                // When finalized is not set (e.g., on L2s), use the retention threshold
205                min_threshold
206            };
207        debug!(
208            target: "engine::tree",
209            last_persisted = last_block_number,
210            finalized_number = ?self.canonical_in_memory_state().get_finalized_num_hash().map(|f| f.number),
211            eviction_threshold,
212            "Evicting changesets below threshold"
213        );
214        self.state.tree_state.overlay_manager.evict_cached_changesets(eviction_threshold);
215
216        self.on_new_persisted_block()?;
217
218        self.purge_timing_stats(last_block_number, commit_duration);
219
220        Ok(())
221    }
222
223    /// Removes timing stats for blocks at or below `below_number`.
224    ///
225    /// No-op when detailed block logging is disabled (no stats are recorded in that case).
226    /// When `commit_duration` is provided and a slow block threshold is configured, checks
227    /// each removed block against the threshold and emits a [`ConsensusEngineEvent::SlowBlock`]
228    /// event for blocks that exceed it.
229    pub(super) fn purge_timing_stats(
230        &mut self,
231        below_number: u64,
232        commit_duration: Option<Duration>,
233    ) {
234        let threshold = self.config.slow_block_threshold();
235        let check_slow = commit_duration.is_some() && threshold.is_some();
236
237        // Two-pass: collect keys first because emit_event borrows &mut self.
238        let keys_to_remove: Vec<B256> = self
239            .execution_timing_stats
240            .iter()
241            .filter(|(_, stats)| stats.block_number <= below_number)
242            .map(|(k, _)| *k)
243            .collect();
244
245        for key in keys_to_remove {
246            let stats = self.execution_timing_stats.remove(&key).expect("key just found");
247            if check_slow {
248                let commit_dur = commit_duration.expect("checked above");
249                // state_read_duration is already included in execution_duration
250                let total_duration =
251                    stats.execution_duration + stats.state_hash_duration + commit_dur;
252
253                if total_duration > threshold.expect("checked above") {
254                    self.emit_event(ConsensusEngineEvent::SlowBlock(SlowBlockInfo {
255                        stats,
256                        commit_duration: Some(commit_dur),
257                        total_duration,
258                    }));
259                }
260            }
261        }
262    }
263
264    /// Returns the blocks and frontiers for the next persistence cycle, if one should start.
265    ///
266    /// Threshold persistence honors the normal scheduling gates and retains the configured
267    /// in-memory block buffer. Persisted-target persistence catches the state/trie frontier up to
268    /// the existing database tip. Head persistence bypasses those gates during shutdown and
269    /// returns `None` once both persistence frontiers have reached the canonical head.
270    pub(super) fn get_save_blocks_input(
271        &self,
272        target: PersistTarget,
273    ) -> Option<SaveBlocksInput<N>> {
274        // We will calculate the state root using the database, so we need to be sure there are no
275        // changes
276        debug_assert!(!self.persistence_state.in_progress());
277
278        let prev_partial_state_trie = self.persistence_state.last_state_trie_persisted_block.number;
279        let prev_db_tip = self.persistence_state.last_persisted_block.number;
280        let canonical_head_number = self.state.tree_state.canonical_block_number();
281
282        let (new_db_tip, new_partial_state_trie) = match target {
283            PersistTarget::Head => (canonical_head_number, canonical_head_number),
284            PersistTarget::Persisted => {
285                // Catch-up persistence is the transition into pipeline sync, so it deliberately
286                // runs while backfill is pending and bypasses the normal threshold gates.
287                debug_assert!(self.backfill_sync_state.is_pending_revalidation());
288                debug_assert!(!self.payload_builds.is_active());
289                (prev_db_tip, prev_db_tip)
290            }
291            PersistTarget::Threshold => {
292                if (self.config.suppress_persistence_during_build() &&
293                    self.payload_builds.is_active()) ||
294                    !self.backfill_sync_state.is_idle()
295                {
296                    return None
297                }
298
299                let persistence_threshold =
300                    usize::try_from(self.config.persistence_threshold()).unwrap_or(usize::MAX);
301                if self.canonical_in_memory_state().canonical_chain().count() <=
302                    persistence_threshold
303                {
304                    return None
305                }
306
307                let new_db_tip =
308                    canonical_head_number.saturating_sub(self.config.memory_block_buffer_target());
309                if new_db_tip <= prev_db_tip {
310                    return None
311                }
312
313                let new_partial_state_trie = new_db_tip
314                    .saturating_sub(self.config.num_state_masking_blocks())
315                    .max(prev_partial_state_trie);
316                (new_db_tip, new_partial_state_trie)
317            }
318        };
319
320        debug_assert!(
321            new_db_tip >= prev_db_tip,
322            "disk reorg must be resolved before saving blocks"
323        );
324        debug_assert!(
325            new_partial_state_trie >= prev_partial_state_trie,
326            "disk reorg must be resolved before saving state/trie"
327        );
328
329        if new_db_tip == prev_db_tip && new_partial_state_trie == prev_partial_state_trie {
330            return None
331        }
332
333        let mut blocks = Vec::new();
334        let mut current_hash = self.state.tree_state.canonical_block_hash();
335
336        debug!(
337            target: "engine::tree",
338            ?current_hash,
339            ?prev_partial_state_trie,
340            ?prev_db_tip,
341            ?canonical_head_number,
342            ?new_partial_state_trie,
343            ?new_db_tip,
344            target = ?target,
345            "Returning save input"
346        );
347        while let Some(block) = self.state.tree_state.executed_block_by_hash(current_hash) {
348            if block.recovered_block().number() <= prev_partial_state_trie {
349                break;
350            }
351
352            current_hash = block.recovered_block().parent_hash();
353
354            if block.recovered_block().number() <= new_db_tip {
355                blocks.push(block);
356            }
357        }
358
359        // Reverse the order so that the oldest block comes first
360        blocks.reverse();
361
362        Some(SaveBlocksInput::new(
363            blocks,
364            prev_db_tip,
365            prev_partial_state_trie,
366            new_db_tip,
367            new_partial_state_trie,
368        ))
369    }
370
371    /// This removes the blocks that have been persisted to the database from the in-memory state,
372    /// together with the blocks that conflict with the finalized block, and updates it to reflect
373    /// the newest persisted block height.
374    ///
375    /// Assumes that `finish` has been called on the `persistence_state` at least once
376    pub(super) fn on_new_persisted_block(&mut self) -> ProviderResult<()> {
377        let in_memory_persisted_block = self.persistence_state.last_state_trie_persisted_block;
378
379        // If we have an on-disk reorg, we need to handle it first before touching the in-memory
380        // state.
381        if let Some(remove_above) = self.find_disk_reorg()? {
382            self.remove_blocks(remove_above);
383            return Ok(())
384        }
385
386        // First fetch the finalized block number.
387        let finalized = self
388            .state
389            .forkchoice_state_tracker
390            .last_valid_finalized()
391            .map(|hash| {
392                self.provider
393                    .block_number(hash)
394                    .map(|number| number.map(|number| BlockNumHash { number, hash }))
395            })
396            .transpose()
397            .map(Option::flatten);
398        debug!(target: "engine::tree", upper_bound=?in_memory_persisted_block, ?finalized, "Removing blocks from the in-memory state");
399        // Trims the canonical chain to the state/trie frontier and prunes the blocks that are not
400        // canonical and conflict with the finalized block. If the finalized block number could not
401        // be fetched, the canonical chain is still trimmed and the error is returned afterwards.
402        self.canonical_in_memory_state_writer.on_blocks_persisted(
403            self.persistence_state.last_persisted_block,
404            in_memory_persisted_block,
405            finalized.as_ref().copied().unwrap_or_default(),
406        );
407        self.metrics.engine.executed_blocks.set(self.state.tree_state.block_count() as f64);
408        finalized?;
409        // Persistence changes the overlay anchor. Prepare the remaining canonical range before
410        // the next payload needs to read execution state against the new durable frontier.
411        self.state.tree_state.overlay_manager.precompute_execution_overlay(
412            self.state.tree_state.canonical_block_hash(),
413            in_memory_persisted_block.hash,
414        );
415        self.state.set_pending_sparse_trie_prune(self.should_prune_sparse_trie());
416        Ok(())
417    }
418
419    /// Returns whether sparse trie pruning should be attempted by the next sparse trie task.
420    const fn should_prune_sparse_trie(&self) -> bool {
421        self.config.use_state_root_task()
422    }
423
424    /// This method tries to detect whether on-disk and in-memory states have diverged. It might
425    /// happen if a reorg is happening while we are persisting a block.
426    fn find_disk_reorg(&self) -> ProviderResult<Option<u64>> {
427        let mut canonical = self.state.tree_state.current_canonical_head;
428        let mut persisted = self.persistence_state.last_persisted_block;
429
430        let parent_num_hash = |num_hash: NumHash| -> ProviderResult<NumHash> {
431            Ok(self
432                .sealed_header_by_hash(num_hash.hash)?
433                .ok_or(ProviderError::BlockHashNotFound(num_hash.hash))?
434                .parent_num_hash())
435        };
436
437        // Happy path, canonical chain is ahead or equal to persisted chain.
438        // Walk canonical chain back to make sure that it connects to persisted chain.
439        while canonical.number > persisted.number {
440            canonical = parent_num_hash(canonical)?;
441        }
442
443        // If we've reached persisted tip by walking the canonical chain back, everything is fine.
444        if canonical == persisted {
445            return Ok(None);
446        }
447
448        // At this point, we know that `persisted` block can't be reached by walking the canonical
449        // chain back. In this case we need to truncate it to the first canonical block it connects
450        // to.
451
452        // Firstly, walk back until we reach the same height as `canonical`.
453        while persisted.number > canonical.number {
454            persisted = parent_num_hash(persisted)?;
455        }
456
457        debug_assert_eq!(persisted.number, canonical.number);
458
459        // Now walk both chains back until we find a common ancestor.
460        while persisted.hash != canonical.hash {
461            canonical = parent_num_hash(canonical)?;
462            persisted = parent_num_hash(persisted)?;
463        }
464
465        debug!(target: "engine::tree", remove_above=persisted.number, "on-disk reorg detected");
466
467        Ok(Some(persisted.number))
468    }
469}
470
471/// Target for block persistence.
472#[derive(Debug, Clone, Copy)]
473pub(super) enum PersistTarget {
474    /// Persist up to `canonical_head - memory_block_buffer_target`.
475    Threshold,
476    /// Persist all blocks up to and including the canonical head.
477    Head,
478    /// Persist state/trie updates through the persisted block frontier.
479    Persisted,
480}