Skip to main content

reth_engine_tree/tree/
mod.rs

1use crate::{
2    backfill::{BackfillAction, BackfillSyncState},
3    chain::FromOrchestrator,
4    engine::{DownloadRequest, EngineApiEvent, EngineApiKind, EngineApiRequest, FromEngine},
5    persistence::PersistenceHandle,
6};
7use alloy_consensus::BlockHeader;
8use alloy_eips::BlockNumHash;
9use alloy_primitives::{map::B256Map, B256};
10use alloy_rpc_types_engine::{ForkchoiceState, PayloadStatus, PayloadStatusEnum};
11use error::InsertBlockFatalError;
12use payload_build::PayloadBuildTracker;
13use reth_chain_state::{
14    CanonicalInMemoryState, CanonicalInMemoryStateWriter, ExecutedBlock, ExecutionTimingStats,
15};
16use reth_concurrency::sync::{
17    channel,
18    channel::{mpsc, select_biased, Receiver, Sender},
19    time::FastInstant as Instant,
20};
21use reth_consensus::FullConsensus;
22use reth_engine_primitives::{
23    BeaconEngineMessage, ConsensusEngineEvent, ExecutionPayload, ForkchoiceStateTracker,
24    NewPayloadTimings, OnForkChoiceUpdated,
25};
26use reth_errors::ProviderResult;
27use reth_evm::ConfigureEvm;
28use reth_payload_builder::PayloadBuilderHandle;
29use reth_payload_primitives::{BuiltPayload, PayloadTypes};
30use reth_primitives_traits::NodePrimitives;
31use reth_provider::{
32    BalProvider, BlockReader, ChangeSetReader, DatabaseProviderFactory, PruneCheckpointReader,
33    StageCheckpointReader, StateProviderFactory, StateReader, StorageChangeSetReader,
34    StorageSettingsCache,
35};
36use reth_storage_overlay::OverlayManager;
37use reth_tasks::{spawn_thread, utils::increase_thread_priority};
38use state::TreeState;
39use std::{fmt::Debug, ops, sync::Arc, time::Duration};
40
41use tokio::sync::{
42    mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender},
43    oneshot,
44};
45use tracing::*;
46
47mod block_buffer;
48mod canonical;
49pub mod error;
50mod forkchoice;
51mod insert;
52pub mod instrumented_state;
53mod invalid;
54mod invalid_headers;
55mod metrics;
56mod payload_build;
57pub mod payload_processor;
58pub mod payload_validator;
59mod persist;
60mod persistence_state;
61pub mod state_root_strategy;
62mod sync;
63#[cfg(test)]
64mod tests;
65mod txpool_prewarm;
66pub mod types;
67
68use crate::persistence::PersistenceResult;
69pub use block_buffer::BlockBuffer;
70pub use invalid_headers::InvalidHeaderCache;
71pub use metrics::EngineApiMetrics;
72pub use payload_processor::*;
73pub use payload_validator::{BasicEngineValidator, EngineValidator};
74pub use persistence_state::PersistenceState;
75pub use reth_engine_primitives::TreeConfig;
76pub use reth_execution_cache::{
77    CacheCheckout, CachedStateCacheMetrics, CachedStateMetrics, CachedStateMetricsSource,
78    CachedStateProvider, ExecutionCache, PayloadExecutionCache, SavedCache,
79    TxPoolPrewarmCacheSnapshot,
80};
81pub use txpool_prewarm::{
82    Source as TxPoolPrewarmSource, Transaction as TxPoolPrewarmTransaction,
83    Transactions as TxPoolPrewarmTransactions,
84};
85pub use types::{ExecutionEnv, ValidationOutcome, ValidationOutput};
86
87pub mod state;
88
89/// The minimum number of blocks to retain in the changeset cache after eviction.
90///
91/// This ensures that recent changesets are kept in memory for potential reorgs,
92/// even when the finalized block is not set (e.g., on L2s like Optimism).
93pub const CHANGESET_CACHE_RETENTION_BLOCKS: u64 = 64;
94
95/// Tracks the state of the engine api internals.
96///
97/// This type is not shareable.
98#[derive(Debug)]
99pub struct EngineApiTreeState<N: NodePrimitives> {
100    /// Tracks the state of the blockchain tree.
101    tree_state: TreeState<N>,
102    /// Whether the next sparse trie task should attempt cache pruning during trie preservation.
103    pending_sparse_trie_prune: bool,
104    /// Tracks the forkchoice state updates received by the CL.
105    forkchoice_state_tracker: ForkchoiceStateTracker,
106    /// Buffer of detached blocks.
107    buffer: BlockBuffer<N::Block>,
108    /// Tracks the header of invalid payloads that were rejected by the engine because they're
109    /// invalid.
110    invalid_headers: InvalidHeaderCache,
111}
112
113impl<N: NodePrimitives> EngineApiTreeState<N> {
114    fn new(
115        block_buffer_limit: u32,
116        max_invalid_header_cache_length: u32,
117        invalid_header_hit_eviction_threshold: u8,
118        canonical_block: BlockNumHash,
119        overlay_manager: OverlayManager<N>,
120    ) -> Self {
121        Self {
122            invalid_headers: InvalidHeaderCache::new(
123                max_invalid_header_cache_length,
124                invalid_header_hit_eviction_threshold,
125            ),
126            buffer: BlockBuffer::new(block_buffer_limit),
127            tree_state: TreeState::new(canonical_block, overlay_manager),
128            pending_sparse_trie_prune: false,
129            forkchoice_state_tracker: ForkchoiceStateTracker::default(),
130        }
131    }
132
133    /// Returns a reference to the tree state.
134    pub const fn tree_state(&self) -> &TreeState<N> {
135        &self.tree_state
136    }
137
138    /// Returns whether sparse trie pruning is pending.
139    pub const fn pending_sparse_trie_prune(&self) -> bool {
140        self.pending_sparse_trie_prune
141    }
142
143    /// Sets whether sparse trie pruning is pending for the next sparse trie task.
144    pub const fn set_pending_sparse_trie_prune(&mut self, pending: bool) {
145        self.pending_sparse_trie_prune = pending;
146    }
147
148    /// Takes a pending sparse trie prune request, if any, and snapshots the in-memory parent chain
149    /// ending at `parent_hash`.
150    ///
151    /// `None` means no prune request is pending. `Some(Vec::new())` means a prune was requested,
152    /// but no in-memory parent-chain blocks were found for the parent hash; the sparse trie task
153    /// should still prune nodes cached before the current block's epoch.
154    pub fn take_sparse_trie_prune_blocks(
155        &mut self,
156        parent_hash: B256,
157    ) -> Option<Vec<ExecutedBlock<N>>> {
158        if !self.pending_sparse_trie_prune {
159            return None
160        }
161
162        self.pending_sparse_trie_prune = false;
163        Some(
164            self.tree_state
165                .blocks_by_hash(parent_hash)
166                .map(|(_, blocks)| blocks)
167                .unwrap_or_default(),
168        )
169    }
170
171    /// Returns true if the block has been marked as invalid.
172    pub fn has_invalid_header(&mut self, hash: &B256) -> bool {
173        self.invalid_headers.get(hash).is_some()
174    }
175}
176
177/// The outcome of a tree operation.
178#[derive(Debug)]
179pub struct TreeOutcome<T> {
180    /// The outcome of the operation.
181    pub outcome: T,
182    /// An optional event to tell the caller to do something.
183    pub event: Option<TreeEvent>,
184    /// Whether the block was already seen, meaning no real execution happened during this
185    /// `newPayload` call.
186    pub already_seen: bool,
187}
188
189impl<T> TreeOutcome<T> {
190    /// Create new tree outcome.
191    pub const fn new(outcome: T) -> Self {
192        Self { outcome, event: None, already_seen: false }
193    }
194
195    /// Set event on the outcome.
196    pub fn with_event(mut self, event: TreeEvent) -> Self {
197        self.event = Some(event);
198        self
199    }
200
201    /// Set the `already_seen` flag on the outcome.
202    pub const fn with_already_seen(mut self, value: bool) -> Self {
203        self.already_seen = value;
204        self
205    }
206}
207
208/// Result of trying to insert a new payload in [`EngineApiTreeHandler`].
209#[derive(Debug)]
210pub struct TryInsertPayloadResult {
211    /// - `Valid`: Payload successfully validated and inserted
212    /// - `Syncing`: Parent missing, payload buffered for later
213    /// - Error status: Payload is invalid
214    pub status: PayloadStatus,
215    /// Whether the block was already seen
216    pub already_seen: bool,
217}
218
219impl TryInsertPayloadResult {
220    /// Convert the result into a [`TreeOutcome`].
221    #[inline]
222    pub fn into_outcome(self) -> TreeOutcome<PayloadStatus> {
223        TreeOutcome::new(self.status).with_already_seen(self.already_seen)
224    }
225}
226
227/// Events that are triggered by Tree Chain
228#[derive(Debug)]
229pub enum TreeEvent {
230    /// Tree action is needed.
231    TreeAction(TreeAction),
232    /// Backfill action is needed.
233    BackfillAction(BackfillAction),
234    /// Block download is needed.
235    Download(DownloadRequest),
236}
237
238impl TreeEvent {
239    /// Returns true if the event is a backfill action.
240    const fn is_backfill_action(&self) -> bool {
241        matches!(self, Self::BackfillAction(_))
242    }
243}
244
245/// The actions that can be performed on the tree.
246#[derive(Debug)]
247pub enum TreeAction {
248    /// Make target canonical.
249    MakeCanonical {
250        /// The sync target head hash
251        sync_target_head: B256,
252    },
253}
254
255/// The engine API tree handler implementation.
256///
257/// This type is responsible for processing engine API requests, maintaining the canonical state and
258/// emitting events.
259pub struct EngineApiTreeHandler<N, P, T, V, C>
260where
261    N: NodePrimitives,
262    T: PayloadTypes,
263    C: ConfigureEvm<Primitives = N> + 'static,
264{
265    provider: P,
266    consensus: Arc<dyn FullConsensus<N>>,
267    payload_validator: V,
268    /// Keeps track of internals such as executed and buffered blocks.
269    state: EngineApiTreeState<N>,
270    /// The half for sending messages to the engine.
271    ///
272    /// This is kept so that we can queue in messages to ourself that we can process later, for
273    /// example distributing workload across multiple messages that would otherwise take too long
274    /// to process. E.g. we might receive a range of downloaded blocks and we want to process
275    /// them one by one so that we can handle incoming engine API in between and don't become
276    /// unresponsive. This can happen during live sync transition where we're trying to close the
277    /// gap (up to 3 epochs of blocks in the worst case).
278    incoming_tx: Sender<FromEngine<EngineApiRequest<T, N>, N::Block>>,
279    /// Incoming engine API requests.
280    incoming: Receiver<FromEngine<EngineApiRequest<T, N>, N::Block>>,
281    /// Outgoing events that are emitted to the handler.
282    outgoing: UnboundedSender<EngineApiEvent<N>>,
283    /// Channels to the persistence layer.
284    persistence: PersistenceHandle<N>,
285    /// Tracks the state changes of the persistence task.
286    persistence_state: PersistenceState,
287    /// Flag indicating the state of the node's backfill synchronization process.
288    backfill_sync_state: BackfillSyncState,
289    /// Changes the state of the canonical chain that isn't persisted yet: its executed blocks,
290    /// its chain info, and the notifications it sends.
291    ///
292    /// The engine reads that state through [`Self::canonical_in_memory_state`]. Its clones are
293    /// intended to be accessed from external sources, such as rpc.
294    canonical_in_memory_state_writer: CanonicalInMemoryStateWriter<N>,
295    /// Handle to the payload builder that will receive payload attributes for valid forkchoice
296    /// updates
297    payload_builder: PayloadBuilderHandle<T>,
298    /// Configuration settings.
299    config: TreeConfig,
300    /// Metrics for the engine api.
301    metrics: EngineApiMetrics,
302    /// The engine API variant of this handler
303    engine_kind: EngineApiKind,
304    /// The EVM configuration.
305    evm_config: C,
306    /// Timing statistics for executed blocks, keyed by block hash.
307    /// Stored here (not in `ExecutedBlock`) to avoid leaking observability concerns into the block
308    /// type. Entries are removed when blocks are persisted or invalidated.
309    execution_timing_stats: B256Map<Box<ExecutionTimingStats>>,
310    /// Tracks payload jobs that may still access in-memory overlay state.
311    payload_builds: PayloadBuildTracker,
312    /// Notifies the engine when the final active payload job finishes.
313    payload_build_finished: Receiver<()>,
314    /// Task runtime for spawning blocking work on named, reusable threads.
315    runtime: reth_tasks::Runtime,
316}
317
318impl<N, P: Debug, T: PayloadTypes, V: Debug, C> std::fmt::Debug
319    for EngineApiTreeHandler<N, P, T, V, C>
320where
321    N: NodePrimitives,
322    C: ConfigureEvm<Primitives = N>,
323{
324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325        f.debug_struct("EngineApiTreeHandler")
326            .field("provider", &self.provider)
327            .field("consensus", &self.consensus)
328            .field("payload_validator", &self.payload_validator)
329            .field("state", &self.state)
330            .field("incoming_tx", &self.incoming_tx)
331            .field("persistence", &self.persistence)
332            .field("persistence_state", &self.persistence_state)
333            .field("backfill_sync_state", &self.backfill_sync_state)
334            .field("canonical_in_memory_state_writer", &self.canonical_in_memory_state_writer)
335            .field("payload_builder", &self.payload_builder)
336            .field("config", &self.config)
337            .field("metrics", &self.metrics)
338            .field("engine_kind", &self.engine_kind)
339            .field("evm_config", &self.evm_config)
340            .field("execution_timing_stats", &self.execution_timing_stats.len())
341            .field("payload_builds_active", &self.payload_builds.is_active())
342            .field("runtime", &self.runtime)
343            .finish()
344    }
345}
346
347impl<N, P, T, V, C> EngineApiTreeHandler<N, P, T, V, C>
348where
349    N: NodePrimitives,
350    P: DatabaseProviderFactory
351        + BlockReader<Block = N::Block, Header = N::BlockHeader>
352        + StateProviderFactory
353        + StateReader<Receipt = N::Receipt>
354        + BalProvider
355        + Clone
356        + 'static,
357    P::Provider: BlockReader<Block = N::Block, Header = N::BlockHeader>
358        + PruneCheckpointReader
359        + StageCheckpointReader
360        + ChangeSetReader
361        + StorageChangeSetReader
362        + StorageSettingsCache
363        + 'static,
364    C: ConfigureEvm<Primitives = N> + 'static,
365    T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>,
366    V: EngineValidator<T> + WaitForCaches,
367{
368    /// Creates a new [`EngineApiTreeHandler`].
369    #[expect(clippy::too_many_arguments)]
370    pub fn new(
371        provider: P,
372        consensus: Arc<dyn FullConsensus<N>>,
373        payload_validator: V,
374        outgoing: UnboundedSender<EngineApiEvent<N>>,
375        state: EngineApiTreeState<N>,
376        canonical_in_memory_state_writer: CanonicalInMemoryStateWriter<N>,
377        persistence: PersistenceHandle<N>,
378        persistence_state: PersistenceState,
379        payload_builder: PayloadBuilderHandle<T>,
380        config: TreeConfig,
381        engine_kind: EngineApiKind,
382        evm_config: C,
383        runtime: reth_tasks::Runtime,
384    ) -> Self {
385        let (incoming_tx, incoming) = channel::unbounded();
386
387        let (payload_builds, payload_build_finished) = PayloadBuildTracker::new();
388
389        Self {
390            provider,
391            consensus,
392            payload_validator,
393            incoming,
394            outgoing,
395            persistence,
396            persistence_state,
397            backfill_sync_state: BackfillSyncState::Idle,
398            state,
399            canonical_in_memory_state_writer,
400            payload_builder,
401            config,
402            metrics: Default::default(),
403            incoming_tx,
404            engine_kind,
405            evm_config,
406            execution_timing_stats: B256Map::default(),
407            payload_builds,
408            payload_build_finished,
409            runtime,
410        }
411    }
412
413    /// Creates a new [`EngineApiTreeHandler`] instance and spawns it in its
414    /// own thread.
415    ///
416    /// Returns the sender through which incoming requests can be sent to the task and the receiver
417    /// end of a [`EngineApiEvent`] unbounded channel to receive events from the engine.
418    #[expect(clippy::complexity)]
419    pub fn spawn_new(
420        provider: P,
421        consensus: Arc<dyn FullConsensus<N>>,
422        payload_validator: V,
423        persistence: PersistenceHandle<N>,
424        payload_builder: PayloadBuilderHandle<T>,
425        canonical_in_memory_state_writer: CanonicalInMemoryStateWriter<N>,
426        overlay_manager: OverlayManager<N>,
427        config: TreeConfig,
428        kind: EngineApiKind,
429        evm_config: C,
430        runtime: reth_tasks::Runtime,
431    ) -> (Sender<FromEngine<EngineApiRequest<T, N>, N::Block>>, UnboundedReceiver<EngineApiEvent<N>>)
432    {
433        let best_block_number = provider.best_block_number().unwrap_or(0);
434        let header = provider.sealed_header(best_block_number).ok().flatten().unwrap_or_default();
435
436        let persistence_state = PersistenceState {
437            last_persisted_block: BlockNumHash::new(best_block_number, header.hash()),
438            last_state_trie_persisted_block: BlockNumHash::new(best_block_number, header.hash()),
439            rx: None,
440        };
441
442        let (tx, outgoing) = unbounded_channel();
443        let state = EngineApiTreeState::new(
444            config.block_buffer_limit(),
445            config.max_invalid_header_cache_length(),
446            config.invalid_header_hit_eviction_threshold(),
447            header.num_hash(),
448            overlay_manager,
449        );
450
451        let task = Self::new(
452            provider,
453            consensus,
454            payload_validator,
455            tx,
456            state,
457            canonical_in_memory_state_writer,
458            persistence,
459            persistence_state,
460            payload_builder,
461            config,
462            kind,
463            evm_config,
464            runtime,
465        );
466        let incoming = task.incoming_tx.clone();
467        spawn_thread("engine", || {
468            increase_thread_priority();
469            task.run()
470        });
471        (incoming, outgoing)
472    }
473
474    /// Returns a [`TreeOutcome`] indicating the forkchoice head is valid and canonical.
475    fn valid_outcome(state: ForkchoiceState) -> TreeOutcome<OnForkChoiceUpdated> {
476        TreeOutcome::new(OnForkChoiceUpdated::valid(PayloadStatus::new(
477            PayloadStatusEnum::Valid,
478            Some(state.head_block_hash),
479        )))
480    }
481
482    /// Returns a new [`Sender`] to send messages to this type.
483    pub fn sender(&self) -> Sender<FromEngine<EngineApiRequest<T, N>, N::Block>> {
484        self.incoming_tx.clone()
485    }
486
487    /// Run the engine API handler.
488    ///
489    /// This will block the current thread and process incoming messages.
490    pub fn run(mut self) {
491        let terminated = self.run_until_exit();
492        drop(self);
493        if let Some(tx) = terminated {
494            let _ = tx.send(());
495        }
496    }
497
498    fn run_until_exit(&mut self) -> Option<oneshot::Sender<()>> {
499        loop {
500            // Each iteration has three phases:
501            //
502            // 1. Non-blocking poll for persistence completion. If the background flush already
503            //    landed, absorb the result now so the gap calculation below is fresh.
504            // 2. Decide how to wait for the next event. When the canonical-to-persisted gap beyond
505            //    the in-memory buffer reaches the backpressure threshold we only block on the
506            //    persistence receiver, leaving new engine requests sitting in the unbounded
507            //    upstream channel.
508            // 3. Handle the event (engine message or persistence completion) and kick off a new
509            //    persistence cycle if the threshold is met again.
510            //
511            // The net effect: when the unbuffered persistence gap reaches the threshold, we stop
512            // processing incoming messages and let them queue in the channel. This is only a soft
513            // form of backpressure: it delays replies and, more importantly, prevents executing
514            // further blocks that would pile up in the persistence queue - where each block
515            // carries heavier state (eg. trie updates) than the raw payload sitting in the engine
516            // channel.
517            //
518            // Standard Ethereum CLs won't truly back off - the engine API has no
519            // backpressure semantics, and CLs typically timeout after ≈8s and resend - so
520            // this cannot prevent the incoming channel from growing under sustained load.
521            // But it shifts the bottleneck to the lighter-weight incoming queue rather than
522            // the costlier persistence pipeline. Other clients that respect reply latency
523            // can treat the delayed responses as a signal to chill out.
524            match self.try_poll_persistence() {
525                Ok(true) => {
526                    if let Err(err) = self.advance_persistence() {
527                        error!(target: "engine::tree", %err, "Advancing persistence failed");
528                        return None
529                    }
530                    continue;
531                }
532                Ok(false) => {}
533                Err(err) => {
534                    error!(target: "engine::tree", %err, "Polling persistence failed");
535                    return None
536                }
537            }
538
539            let event = if self.should_backpressure() {
540                self.metrics.engine.backpressure_active.set(1.0);
541                let stall_start = Instant::now();
542                let event = self.wait_for_persistence_event();
543                self.metrics.engine.backpressure_stall_duration.record(stall_start.elapsed());
544                event
545            } else {
546                self.metrics.engine.backpressure_active.set(0.0);
547                self.wait_for_event()
548            };
549
550            match event {
551                LoopEvent::EngineMessage(msg) => {
552                    debug!(target: "engine::tree", %msg, "received new engine message");
553                    match self.on_engine_message(msg) {
554                        Ok(ops::ControlFlow::Break(tx)) => return Some(tx),
555                        Ok(ops::ControlFlow::Continue(())) => {}
556                        Err(fatal) => {
557                            error!(target: "engine::tree", %fatal, "insert block fatal error");
558                            return None
559                        }
560                    }
561                }
562                LoopEvent::PersistenceComplete { result, start_time } => {
563                    if let Err(err) = self.on_persistence_complete(result, start_time) {
564                        error!(target: "engine::tree", %err, "Persistence complete handling failed");
565                        return None
566                    }
567                }
568                LoopEvent::PayloadBuildFinished => {}
569                LoopEvent::Disconnected => {
570                    error!(target: "engine::tree", "Channel disconnected");
571                    return None
572                }
573            }
574
575            // Always check if we need to trigger new persistence after any event:
576            // - After engine messages: new blocks may have been inserted that exceed the
577            //   persistence threshold
578            // - After persistence completion: we can now persist more blocks if needed
579            if let Err(err) = self.advance_persistence() {
580                error!(target: "engine::tree", %err, "Advancing persistence failed");
581                return None
582            }
583        }
584    }
585
586    /// Blocks until the in-flight persistence task completes, used when we are under
587    /// backpressure.
588    ///
589    /// Unlike `wait_for_event`, this deliberately does not read from the tree input channel. Any
590    /// requests sent to the tree remain queued upstream until persistence catches up.
591    fn wait_for_persistence_event(&mut self) -> LoopEvent<T, N> {
592        let maybe_persistence = self.persistence_state.rx.take();
593
594        if let Some((persistence_rx, start_time, _action)) = maybe_persistence {
595            match persistence_rx.recv() {
596                Ok(result) => LoopEvent::PersistenceComplete { result, start_time },
597                Err(_) => LoopEvent::Disconnected,
598            }
599        } else {
600            self.wait_for_event()
601        }
602    }
603
604    /// Blocks until the next event is ready.
605    ///
606    /// Uses biased selection to prioritize persistence completion so in-memory state is updated and
607    /// further writes are unblocked.
608    fn wait_for_event(&mut self) -> LoopEvent<T, N> {
609        // Take ownership of persistence rx if present
610        let maybe_persistence = self.persistence_state.rx.take();
611
612        if let Some((persistence_rx, start_time, action)) = maybe_persistence {
613            // Biased select prioritizes persistence completion to update in memory state and
614            // unblock further writes
615            select_biased! {
616                recv(persistence_rx) -> result => {
617                    // Don't put it back - consumed (oneshot-like behavior)
618                    match result {
619                        Ok(result) => LoopEvent::PersistenceComplete {
620                            result,
621                            start_time,
622                        },
623                        Err(_) => LoopEvent::Disconnected,
624                    }
625                },
626                recv(self.payload_build_finished) -> result => {
627                    // Put the persistence rx back - we didn't consume it.
628                    self.persistence_state.rx = Some((persistence_rx, start_time, action));
629                    match result {
630                        Ok(()) => LoopEvent::PayloadBuildFinished,
631                        Err(_) => LoopEvent::Disconnected,
632                    }
633                },
634                recv(self.incoming) -> msg => {
635                    // Put the persistence rx back - we didn't consume it
636                    self.persistence_state.rx = Some((persistence_rx, start_time, action));
637                    match msg {
638                        Ok(m) => LoopEvent::EngineMessage(m),
639                        Err(_) => LoopEvent::Disconnected,
640                    }
641                },
642            }
643        } else {
644            // No persistence in progress - wait on an incoming message or payload job completion.
645            select_biased! {
646                recv(self.payload_build_finished) -> result => match result {
647                    Ok(()) => LoopEvent::PayloadBuildFinished,
648                    Err(_) => LoopEvent::Disconnected,
649                },
650                recv(self.incoming) -> msg => match msg {
651                    Ok(m) => LoopEvent::EngineMessage(m),
652                    Err(_) => LoopEvent::Disconnected,
653                },
654            }
655        }
656    }
657
658    /// Handles a message from the engine.
659    ///
660    /// Returns `ControlFlow::Break` with the sender of the termination request if the engine
661    /// should terminate.
662    fn on_engine_message(
663        &mut self,
664        msg: FromEngine<EngineApiRequest<T, N>, N::Block>,
665    ) -> Result<ops::ControlFlow<oneshot::Sender<()>>, InsertBlockFatalError> {
666        match msg {
667            FromEngine::Event(event) => match event {
668                FromOrchestrator::BackfillSyncStarted => {
669                    debug!(target: "engine::tree", "received backfill sync started event");
670                    self.backfill_sync_state = BackfillSyncState::Active;
671                }
672                FromOrchestrator::BackfillSyncFinished(ctrl) => {
673                    self.on_backfill_sync_finished(ctrl)?;
674                }
675                FromOrchestrator::Terminate { tx } => {
676                    debug!(target: "engine::tree", "received terminate request");
677                    trace!(target: "engine::tree", "finishing termination, persisting remaining blocks");
678                    if let Err(err) = self.persist_until_complete() {
679                        error!(target: "engine::tree", %err, "Termination failed");
680                    }
681                    return Ok(ops::ControlFlow::Break(tx))
682                }
683            },
684            FromEngine::Request(request) => {
685                match request {
686                    EngineApiRequest::InsertExecutedBlock(payload) => {
687                        let block_num_hash = payload.recovered_block.num_hash();
688                        if block_num_hash.number <= self.state.tree_state.canonical_block_number() {
689                            // outdated block that can be skipped
690                            return Ok(ops::ControlFlow::Continue(()))
691                        }
692
693                        if self.state.tree_state.contains_hash(&block_num_hash.hash) {
694                            // block already known to the tree (e.g. delivered via newPayload first)
695                            return Ok(ops::ControlFlow::Continue(()))
696                        }
697
698                        debug!(target: "engine::tree", block=?block_num_hash, "inserting already executed block");
699                        let now = Instant::now();
700
701                        let block = match self.payload_validator.on_inserted_executed_block(payload)
702                        {
703                            Ok(block) => block,
704                            Err(err) => {
705                                warn!(target: "engine::tree", %err, block=?block_num_hash, "Failed to insert already executed block");
706                                return Ok(ops::ControlFlow::Continue(()))
707                            }
708                        };
709
710                        let is_pending = self.state.tree_state.canonical_block_hash() ==
711                            block.recovered_block().parent_hash();
712
713                        if is_pending {
714                            debug!(target: "engine::tree", pending=?block_num_hash, "updating pending block");
715                            self.canonical_in_memory_state_writer.set_pending_block(block.clone());
716                        } else {
717                            self.canonical_in_memory_state_writer.insert_executed(block.clone());
718                        }
719                        self.state
720                            .tree_state
721                            .overlay_manager
722                            .precompute_child_execution_overlays(block_num_hash.hash);
723                        self.metrics
724                            .engine
725                            .executed_blocks
726                            .set(self.state.tree_state.block_count() as f64);
727
728                        self.metrics.engine.inserted_already_executed_blocks.increment(1);
729                        self.emit_event(EngineApiEvent::BeaconConsensus(
730                            ConsensusEngineEvent::CanonicalBlockAdded(block, now.elapsed()),
731                        ));
732                    }
733                    EngineApiRequest::Beacon(request) => {
734                        match request {
735                            BeaconEngineMessage::ForkchoiceUpdated {
736                                cause,
737                                state,
738                                payload_attrs,
739                                tx,
740                            } => {
741                                let _cause = cause.enter();
742                                let has_attrs = payload_attrs.is_some();
743
744                                let start = Instant::now();
745                                let mut output = self.on_forkchoice_updated(state, payload_attrs);
746
747                                if let Ok(res) = &mut output {
748                                    // track last received forkchoice state
749                                    self.state
750                                        .forkchoice_state_tracker
751                                        .set_latest(state, res.outcome.forkchoice_status());
752
753                                    // emit an event about the handled FCU
754                                    self.emit_event(ConsensusEngineEvent::ForkchoiceUpdated(
755                                        state,
756                                        res.outcome.forkchoice_status(),
757                                    ));
758
759                                    // handle the event if any
760                                    self.on_maybe_tree_event(res.event.take())?;
761                                }
762
763                                if let Err(ref err) = output {
764                                    error!(target: "engine::tree", %err, ?state, "Error processing forkchoice update");
765                                }
766
767                                self.metrics.engine.forkchoice_updated.update_response_metrics(
768                                    start,
769                                    &mut self.metrics.engine.new_payload.latest_finish_at,
770                                    has_attrs,
771                                    &output,
772                                );
773
774                                if let Err(err) =
775                                    tx.send(output.map(|o| o.outcome).map_err(Into::into))
776                                {
777                                    self.metrics
778                                        .engine
779                                        .failed_forkchoice_updated_response_deliveries
780                                        .increment(1);
781                                    warn!(target: "engine::tree", ?state, elapsed=?start.elapsed(), "Failed to deliver forkchoiceUpdated response, receiver dropped (request cancelled): {err:?}");
782                                }
783                            }
784                            BeaconEngineMessage::NewPayload { cause, payload, tx } => {
785                                let _cause = cause.enter();
786                                let start = Instant::now();
787                                let gas_used = payload.gas_used();
788                                let num_hash = payload.num_hash();
789                                let mut output = self.on_new_payload(payload);
790                                self.metrics.engine.new_payload.update_response_metrics(
791                                    start,
792                                    &mut self.metrics.engine.forkchoice_updated.latest_finish_at,
793                                    &output,
794                                    gas_used,
795                                );
796
797                                let maybe_event =
798                                    output.as_mut().ok().and_then(|out| out.event.take());
799
800                                // emit response
801                                if let Err(err) =
802                                    tx.send(output.map(|o| o.outcome).map_err(Into::into))
803                                {
804                                    warn!(target: "engine::tree", payload=?num_hash, elapsed=?start.elapsed(), "Failed to deliver newPayload response, receiver dropped (request cancelled): {err:?}");
805                                    self.metrics
806                                        .engine
807                                        .failed_new_payload_response_deliveries
808                                        .increment(1);
809                                }
810
811                                // handle the event if any
812                                self.on_maybe_tree_event(maybe_event)?;
813                            }
814                            BeaconEngineMessage::RethNewPayload {
815                                cause,
816                                payload,
817                                wait_for_persistence,
818                                wait_for_caches,
819                                tx,
820                                enqueued_at,
821                            } => {
822                                let _cause = cause.enter();
823                                debug!(
824                                    target: "engine::tree",
825                                    wait_for_persistence,
826                                    wait_for_caches,
827                                    "Processing reth_newPayload"
828                                );
829
830                                let backpressure_wait = enqueued_at.elapsed();
831
832                                let explicit_persistence_wait = if wait_for_persistence {
833                                    let pending_persistence = self.persistence_state.rx.take();
834                                    if let Some((rx, start_time, _action)) = pending_persistence {
835                                        let (persistence_tx, persistence_rx) = mpsc::channel();
836                                        self.runtime.spawn_blocking_named(
837                                            "wait-persist",
838                                            move || {
839                                                let start = Instant::now();
840                                                let result = rx
841                                                    .recv()
842                                                    .expect("persistence state channel closed");
843                                                let _ = persistence_tx.send((
844                                                    result,
845                                                    start_time,
846                                                    start.elapsed(),
847                                                ));
848                                            },
849                                        );
850                                        let (result, start_time, wait_duration) = persistence_rx
851                                            .recv()
852                                            .expect("persistence result channel closed");
853                                        let _ = self.on_persistence_complete(result, start_time);
854                                        wait_duration
855                                    } else {
856                                        Duration::ZERO
857                                    }
858                                } else {
859                                    Duration::ZERO
860                                };
861
862                                let cache_wait = wait_for_caches
863                                    .then(|| self.payload_validator.wait_for_caches());
864
865                                let start = Instant::now();
866                                let gas_used = payload.gas_used();
867                                let num_hash = payload.num_hash();
868                                let mut output = self.on_new_payload(payload);
869                                let latency = start.elapsed();
870                                self.metrics.engine.new_payload.update_response_metrics(
871                                    start,
872                                    &mut self.metrics.engine.forkchoice_updated.latest_finish_at,
873                                    &output,
874                                    gas_used,
875                                );
876
877                                let maybe_event =
878                                    output.as_mut().ok().and_then(|out| out.event.take());
879
880                                let timings = NewPayloadTimings {
881                                    latency,
882                                    persistence_wait: backpressure_wait + explicit_persistence_wait,
883                                    execution_cache_wait: cache_wait
884                                        .map(|wait| wait.execution_cache),
885                                    sparse_trie_wait: cache_wait.map(|wait| wait.sparse_trie),
886                                };
887                                if let Err(err) = tx
888                                    .send(output.map(|o| (o.outcome, timings)).map_err(Into::into))
889                                {
890                                    error!(
891                                        target: "engine::tree",
892                                        payload=?num_hash,
893                                        elapsed=?latency,
894                                        "Failed to send event: {err:?}"
895                                    );
896                                    self.metrics
897                                        .engine
898                                        .failed_new_payload_response_deliveries
899                                        .increment(1);
900                                }
901
902                                self.on_maybe_tree_event(maybe_event)?;
903                            }
904                        }
905                    }
906                }
907            }
908            FromEngine::DownloadedBlocks(blocks) => {
909                if let Some(event) = self.on_downloaded(blocks)? {
910                    self.on_tree_event(event)?;
911                }
912            }
913            FromEngine::StartNumberMismatch(mismatch) => {
914                self.on_start_number_mismatch(mismatch.header)
915            }
916        }
917        Ok(ops::ControlFlow::Continue(()))
918    }
919
920    /// Convenience function to handle an optional tree event.
921    fn on_maybe_tree_event(&mut self, event: Option<TreeEvent>) -> ProviderResult<()> {
922        if let Some(event) = event {
923            self.on_tree_event(event)?;
924        }
925
926        Ok(())
927    }
928
929    /// Handles a tree event.
930    ///
931    /// Returns an error if a [`TreeAction::MakeCanonical`] results in a fatal error.
932    fn on_tree_event(&mut self, event: TreeEvent) -> ProviderResult<()> {
933        match event {
934            TreeEvent::TreeAction(action) => match action {
935                TreeAction::MakeCanonical { sync_target_head } => {
936                    self.make_canonical(sync_target_head)?;
937                }
938            },
939            TreeEvent::BackfillAction(action) => {
940                self.emit_event(EngineApiEvent::BackfillAction(action));
941            }
942            TreeEvent::Download(action) => {
943                self.emit_event(EngineApiEvent::Download(action));
944            }
945        }
946
947        Ok(())
948    }
949
950    /// Emits an outgoing event to the engine.
951    fn emit_event(&mut self, event: impl Into<EngineApiEvent<N>>) {
952        let event = event.into();
953
954        if let EngineApiEvent::BackfillAction(action) = event {
955            debug_assert_eq!(
956                self.backfill_sync_state,
957                BackfillSyncState::Idle,
958                "backfill action should only be emitted when backfill is idle"
959            );
960
961            let persistence_in_progress = self.persistence_state.in_progress();
962            let state_trie_needs_catchup = self.persistence_state.last_state_trie_persisted_block !=
963                self.persistence_state.last_persisted_block;
964            if self.payload_builds.is_active() ||
965                persistence_in_progress ||
966                state_trie_needs_catchup
967            {
968                // Backfill can remove the same in-memory blocks as an active payload job or a
969                // persistence task. Enter pending mode to prevent new payload jobs and
970                // re-evaluate the current sync target after all readers and writes drain.
971                debug!(
972                    target: "engine::tree",
973                    last_persisted_block = self.persistence_state.last_persisted_block.number,
974                    last_state_trie_persisted_block = self
975                        .persistence_state
976                        .last_state_trie_persisted_block
977                        .number,
978                    "deferring backfill until persistence and payload jobs drain"
979                );
980                self.backfill_sync_state = BackfillSyncState::PendingRevalidation;
981                return
982            }
983
984            self.dispatch_backfill_action(action);
985            return
986        }
987
988        self.send_event(event);
989    }
990
991    /// Sends an event to the orchestrator.
992    fn send_event(&self, event: EngineApiEvent<N>) {
993        let _ = self.outgoing.send(event).inspect_err(
994            |err| error!(target: "engine::tree", "Failed to send internal event: {err:?}"),
995        );
996    }
997
998    /// Returns the state of the canonical chain that isn't persisted yet, which the engine
999    /// changes through its writer.
1000    const fn canonical_in_memory_state(&self) -> &CanonicalInMemoryState<N> {
1001        self.canonical_in_memory_state_writer.canonical_in_memory_state()
1002    }
1003}
1004
1005/// Events received in the main engine loop.
1006#[derive(Debug)]
1007enum LoopEvent<T, N>
1008where
1009    N: NodePrimitives,
1010    T: PayloadTypes,
1011{
1012    /// An engine API message was received.
1013    EngineMessage(FromEngine<EngineApiRequest<T, N>, N::Block>),
1014    /// A persistence task completed.
1015    PersistenceComplete {
1016        /// The unified result of the persistence operation.
1017        result: PersistenceResult,
1018        /// When the persistence operation started.
1019        start_time: Instant,
1020    },
1021    /// The last active payload job has finished, so suppressed persistence may resume.
1022    PayloadBuildFinished,
1023    /// A channel was disconnected.
1024    Disconnected,
1025}
1026
1027/// Block inclusion can be valid, accepted, or invalid. Invalid blocks are returned as an error
1028/// variant.
1029///
1030/// If we don't know the block's parent, we return `Disconnected`, as we can't claim that the block
1031/// is valid or not.
1032#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1033pub enum BlockStatus {
1034    /// The block is valid: its parent state was available, so it was executed and inserted into
1035    /// the tree.
1036    ///
1037    /// Note: this does not imply the block extends the canonical chain. Blocks on a fork are
1038    /// executed and inserted the same way and report this status as well.
1039    Valid,
1040    /// The block may be valid and has an unknown missing ancestor.
1041    Disconnected {
1042        /// Current canonical head.
1043        head: BlockNumHash,
1044        /// The lowest ancestor block that is not connected to the canonical chain.
1045        missing_ancestor: BlockNumHash,
1046    },
1047}
1048
1049/// How a payload was inserted if it was valid.
1050///
1051/// If the payload was valid, but has already been seen, [`InsertPayloadOk::AlreadySeen`] is
1052/// returned, otherwise [`InsertPayloadOk::Inserted`] is returned.
1053#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1054pub enum InsertPayloadOk {
1055    /// The payload was valid, but we have already seen it.
1056    AlreadySeen(BlockStatus),
1057    /// The payload was valid and inserted into the tree.
1058    Inserted(BlockStatus),
1059}
1060
1061/// Result of waiting for caches to become available.
1062#[derive(Debug, Clone, Copy, Default)]
1063pub struct CacheWaitDurations {
1064    /// Time spent waiting for the execution cache lock, excluding post-unlock cache destruction.
1065    pub execution_cache: Duration,
1066    /// Time spent waiting for the sparse trie lock.
1067    pub sparse_trie: Duration,
1068}
1069
1070/// Trait for types that can wait for caches to become available.
1071///
1072/// Used by `reth_newPayload` to wait for cache updates before starting payload processing.
1073/// Removed execution-cache allocations may still be destroyed concurrently after unlocking.
1074pub trait WaitForCaches {
1075    /// Waits for cache updates to complete.
1076    ///
1077    /// Returns the time spent waiting for each cache separately.
1078    fn wait_for_caches(&self) -> CacheWaitDurations;
1079}