Skip to main content

reth_exex/
notifications.rs

1use crate::{
2    BackfillJobFactory, ExExEvent, ExExNotification, RevertReceipt, StreamBackfillJob, WalHandle,
3};
4use alloy_consensus::BlockHeader;
5use alloy_eips::BlockNumHash;
6use futures::{Stream, StreamExt};
7use reth_ethereum_primitives::EthPrimitives;
8use reth_evm::ConfigureEvm;
9use reth_exex_types::ExExHead;
10use reth_node_api::NodePrimitives;
11use reth_provider::{BlockNumReader, BlockReader, Chain, ProviderResult, StateProviderFactory};
12use reth_stages_api::ExecutionStageThresholds;
13use std::{
14    collections::VecDeque,
15    fmt::Debug,
16    pin::Pin,
17    sync::Arc,
18    task::{ready, Context, Poll},
19};
20use tokio::sync::mpsc::{Receiver, UnboundedSender};
21use tracing::debug;
22
23/// A stream of [`ExExNotification`]s. The stream will emit notifications for all blocks. If the
24/// stream is configured with a head via [`ExExNotifications::set_with_head`] or
25/// [`ExExNotifications::with_head`], it will run backfill jobs to catch up to the node head.
26#[derive(Debug)]
27pub struct ExExNotifications<P, E>
28where
29    E: ConfigureEvm,
30{
31    inner: ExExNotificationsInner<P, E>,
32}
33
34/// A trait, that represents a stream of [`ExExNotification`]s. The stream will emit notifications
35/// for all blocks. If the stream is configured with a head via [`ExExNotifications::set_with_head`]
36/// or [`ExExNotifications::with_head`], it will run backfill jobs to catch up to the node head.
37pub trait ExExNotificationsStream<N: NodePrimitives = EthPrimitives>:
38    Stream<Item = eyre::Result<ExExNotification<N>>> + Unpin
39{
40    /// Sets [`ExExNotificationsStream`] to a stream of [`ExExNotification`]s without a head.
41    ///
42    /// It's a no-op if the stream has already been configured without a head.
43    ///
44    /// See the documentation of [`ExExNotificationsWithoutHead`] for more details.
45    fn set_without_head(&mut self);
46
47    /// Sets [`ExExNotificationsStream`] to a stream of [`ExExNotification`]s with the provided
48    /// head.
49    ///
50    /// It's a no-op if the stream has already been configured with a head.
51    ///
52    /// See the documentation of [`ExExNotificationsWithHead`] for more details.
53    fn set_with_head(&mut self, exex_head: ExExHead);
54
55    /// Returns a new [`ExExNotificationsStream`] without a head.
56    ///
57    /// See the documentation of [`ExExNotificationsWithoutHead`] for more details.
58    fn without_head(self) -> Self
59    where
60        Self: Sized;
61
62    /// Returns a new [`ExExNotificationsStream`] with the provided head.
63    ///
64    /// See the documentation of [`ExExNotificationsWithHead`] for more details.
65    fn with_head(self, exex_head: ExExHead) -> Self
66    where
67        Self: Sized;
68
69    /// Sets custom thresholds for the backfill job.
70    ///
71    /// These thresholds control how many blocks are included in each backfill notification.
72    /// Only takes effect when the stream is configured with a head.
73    ///
74    /// By default, the backfill job uses [`BackfillJobFactory`] defaults (up to 500,000 blocks
75    /// per batch, bounded by 30s execution time).
76    fn set_backfill_thresholds(&mut self, _thresholds: ExecutionStageThresholds) {}
77}
78
79#[derive(Debug)]
80enum ExExNotificationsInner<P, E>
81where
82    E: ConfigureEvm,
83{
84    /// A stream of [`ExExNotification`]s. The stream will emit notifications for all blocks.
85    WithoutHead(ExExNotificationsWithoutHead<P, E>),
86    /// A stream of [`ExExNotification`]s. The stream will only emit notifications for blocks that
87    /// are committed or reverted after the given head.
88    WithHead(Box<ExExNotificationsWithHead<P, E>>),
89    /// Internal state used when transitioning between [`ExExNotificationsInner::WithoutHead`] and
90    /// [`ExExNotificationsInner::WithHead`].
91    Invalid,
92}
93
94impl<P, E> ExExNotificationsInner<P, E>
95where
96    E: ConfigureEvm,
97{
98    /// Returns the provider of the underlying stream.
99    fn provider(&self) -> &P {
100        match self {
101            Self::WithoutHead(n) => &n.provider,
102            Self::WithHead(n) => &n.provider,
103            Self::Invalid => unreachable!(),
104        }
105    }
106}
107
108impl<P, E> ExExNotifications<P, E>
109where
110    E: ConfigureEvm,
111{
112    /// Creates a new stream of [`ExExNotifications`] without a head.
113    pub const fn new(
114        node_head: BlockNumHash,
115        provider: P,
116        evm_config: E,
117        notifications: Receiver<ExExNotification<E::Primitives>>,
118        wal_handle: WalHandle<E::Primitives>,
119    ) -> Self {
120        Self {
121            inner: ExExNotificationsInner::WithoutHead(ExExNotificationsWithoutHead::new(
122                node_head,
123                provider,
124                evm_config,
125                notifications,
126                wal_handle,
127            )),
128        }
129    }
130
131    /// Makes the stream send [`ExExEvent::RevertReceived`] to the manager over `events`, the
132    /// channel the `ExEx` sends its [`ExExEvent`]s on.
133    pub(crate) fn with_revert_receipts(mut self, events: UnboundedSender<ExExEvent>) -> Self {
134        if let ExExNotificationsInner::WithoutHead(notifications) = &mut self.inner {
135            notifications.notifications.revert_receipts = Some(events);
136        }
137        self
138    }
139
140    /// As [`set_with_head`](ExExNotificationsStream::set_with_head), but backfills up to the
141    /// node's current canonical head rather than the head captured at construction.
142    pub fn catch_up_with_head(&mut self, exex_head: ExExHead) -> eyre::Result<()>
143    where
144        P: BlockNumReader,
145    {
146        // Resolve the current canonical head before tearing down the stream state, so a failed
147        // lookup leaves the stream untouched.
148        let local_head: BlockNumHash = self.inner.provider().chain_info()?.into();
149
150        let current = std::mem::replace(&mut self.inner, ExExNotificationsInner::Invalid);
151        let (provider, evm_config, notifications, wal_handle, backfill_thresholds) = match current {
152            ExExNotificationsInner::WithoutHead(n) => {
153                (n.provider, n.evm_config, n.notifications, n.wal_handle, None)
154            }
155            ExExNotificationsInner::WithHead(mut n) => {
156                n.drop_pending_notifications();
157                (n.provider, n.evm_config, n.notifications, n.wal_handle, n.backfill_thresholds)
158            }
159            ExExNotificationsInner::Invalid => unreachable!(),
160        };
161        let mut with_head = ExExNotificationsWithHead::new(
162            local_head,
163            provider,
164            evm_config,
165            notifications,
166            wal_handle,
167            exex_head,
168        );
169        // Preserve any custom backfill thresholds so the catch-up backfill respects the limits
170        // the ExEx already configured.
171        with_head.backfill_thresholds = backfill_thresholds;
172        self.inner = ExExNotificationsInner::WithHead(Box::new(with_head));
173        Ok(())
174    }
175}
176
177impl<P, E> ExExNotificationsStream<E::Primitives> for ExExNotifications<P, E>
178where
179    P: BlockReader + StateProviderFactory + Clone + Unpin + 'static,
180    E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
181{
182    fn set_without_head(&mut self) {
183        let current = std::mem::replace(&mut self.inner, ExExNotificationsInner::Invalid);
184        self.inner = ExExNotificationsInner::WithoutHead(match current {
185            ExExNotificationsInner::WithoutHead(notifications) => notifications,
186            ExExNotificationsInner::WithHead(mut notifications) => {
187                notifications.drop_pending_notifications();
188                ExExNotificationsWithoutHead {
189                    node_head: notifications.initial_local_head,
190                    provider: notifications.provider,
191                    evm_config: notifications.evm_config,
192                    notifications: notifications.notifications,
193                    wal_handle: notifications.wal_handle,
194                }
195            }
196            ExExNotificationsInner::Invalid => unreachable!(),
197        });
198    }
199
200    fn set_with_head(&mut self, exex_head: ExExHead) {
201        let current = std::mem::replace(&mut self.inner, ExExNotificationsInner::Invalid);
202        self.inner = ExExNotificationsInner::WithHead(match current {
203            ExExNotificationsInner::WithoutHead(notifications) => {
204                Box::new(notifications.with_head(exex_head))
205            }
206            ExExNotificationsInner::WithHead(mut notifications) => {
207                notifications.drop_pending_notifications();
208                Box::new(ExExNotificationsWithHead::new(
209                    notifications.initial_local_head,
210                    notifications.provider,
211                    notifications.evm_config,
212                    notifications.notifications,
213                    notifications.wal_handle,
214                    exex_head,
215                ))
216            }
217            ExExNotificationsInner::Invalid => unreachable!(),
218        });
219    }
220
221    fn without_head(mut self) -> Self {
222        self.set_without_head();
223        self
224    }
225
226    fn with_head(mut self, exex_head: ExExHead) -> Self {
227        self.set_with_head(exex_head);
228        self
229    }
230
231    fn set_backfill_thresholds(&mut self, thresholds: ExecutionStageThresholds) {
232        if let ExExNotificationsInner::WithHead(notifications) = &mut self.inner {
233            notifications.backfill_thresholds = Some(thresholds);
234        }
235    }
236}
237
238impl<P, E> Stream for ExExNotifications<P, E>
239where
240    P: BlockReader + StateProviderFactory + Clone + Unpin + 'static,
241    E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
242{
243    type Item = eyre::Result<ExExNotification<E::Primitives>>;
244
245    fn poll_next(
246        self: std::pin::Pin<&mut Self>,
247        cx: &mut std::task::Context<'_>,
248    ) -> std::task::Poll<Option<Self::Item>> {
249        match &mut self.get_mut().inner {
250            ExExNotificationsInner::WithoutHead(notifications) => {
251                notifications.poll_next_unpin(cx).map(|result| result.map(Ok))
252            }
253            ExExNotificationsInner::WithHead(notifications) => notifications.poll_next_unpin(cx),
254            ExExNotificationsInner::Invalid => unreachable!(),
255        }
256    }
257}
258
259/// A stream of [`ExExNotification`]s. The stream will emit notifications for all blocks.
260pub struct ExExNotificationsWithoutHead<P, E>
261where
262    E: ConfigureEvm,
263{
264    node_head: BlockNumHash,
265    provider: P,
266    evm_config: E,
267    notifications: ManagerNotifications<E::Primitives>,
268    wal_handle: WalHandle<E::Primitives>,
269}
270
271impl<P: Debug, E> Debug for ExExNotificationsWithoutHead<P, E>
272where
273    E: ConfigureEvm,
274{
275    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276        f.debug_struct("ExExNotifications")
277            .field("provider", &self.provider)
278            .field("evm_config", &self.evm_config)
279            .field("notifications", &self.notifications)
280            .finish()
281    }
282}
283
284impl<P, E> ExExNotificationsWithoutHead<P, E>
285where
286    E: ConfigureEvm,
287{
288    /// Creates a new instance of [`ExExNotificationsWithoutHead`].
289    const fn new(
290        node_head: BlockNumHash,
291        provider: P,
292        evm_config: E,
293        notifications: Receiver<ExExNotification<E::Primitives>>,
294        wal_handle: WalHandle<E::Primitives>,
295    ) -> Self {
296        Self {
297            node_head,
298            provider,
299            evm_config,
300            notifications: ManagerNotifications { receiver: notifications, revert_receipts: None },
301            wal_handle,
302        }
303    }
304
305    /// Subscribe to notifications with the given head.
306    fn with_head(self, head: ExExHead) -> ExExNotificationsWithHead<P, E> {
307        ExExNotificationsWithHead::new(
308            self.node_head,
309            self.provider,
310            self.evm_config,
311            self.notifications,
312            self.wal_handle,
313            head,
314        )
315    }
316}
317
318impl<P: Unpin, E> Stream for ExExNotificationsWithoutHead<P, E>
319where
320    E: ConfigureEvm,
321{
322    type Item = ExExNotification<E::Primitives>;
323
324    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
325        let notifications = &mut self.get_mut().notifications;
326        let notification = ready!(notifications.poll_recv(cx));
327        if let Some(notification) = &notification {
328            notifications.acknowledge(notification);
329        }
330        Poll::Ready(notification)
331    }
332}
333
334/// A stream of [`ExExNotification`]s. The stream will only emit notifications for blocks that are
335/// committed or reverted after the given head. The head is the ExEx's latest view of the host
336/// chain. It moves with every notification the stream emits, and the stream also skips a
337/// notification that reverts blocks if the head has none of them and already reflects the chain
338/// the notification leaves.
339///
340/// Notifications will be sent starting from the head, not inclusive. For example, if
341/// `exex_head.number == 10`, then the first notification will be with `block.number == 11`. An
342/// `exex_head.number` of 10 indicates that the ExEx has processed up to block 10, and is ready to
343/// process block 11.
344#[derive(Debug)]
345pub struct ExExNotificationsWithHead<P, E>
346where
347    E: ConfigureEvm,
348{
349    /// The node's local head at launch.
350    initial_local_head: BlockNumHash,
351    provider: P,
352    evm_config: E,
353    notifications: ManagerNotifications<E::Primitives>,
354    wal_handle: WalHandle<E::Primitives>,
355    /// The ExEx head: the head it was launched with, moved by every notification the stream
356    /// yields to the ExEx.
357    exex_head: ExExHead,
358
359    /// If true, then we need to check if the ExEx head is on the canonical chain and if not,
360    /// revert its head.
361    pending_check_canonical: bool,
362    /// If true, then we need to check if the ExEx head is behind the node head and if so, backfill
363    /// the missing blocks.
364    pending_check_backfill: bool,
365    /// The backfill job to run before consuming any notifications.
366    backfill_job: Option<StreamBackfillJob<E, P, Chain<E::Primitives>>>,
367    /// Custom thresholds for the backfill job, if set.
368    backfill_thresholds: Option<ExecutionStageThresholds>,
369    /// Notifications that arrived during backfill and need to be delivered after it completes:
370    /// everything from the first notification that the backfill range doesn't cover.
371    pending_notifications: VecDeque<ExExNotification<E::Primitives>>,
372}
373
374impl<P, E> ExExNotificationsWithHead<P, E>
375where
376    E: ConfigureEvm,
377{
378    /// Creates a new [`ExExNotificationsWithHead`].
379    const fn new(
380        node_head: BlockNumHash,
381        provider: P,
382        evm_config: E,
383        notifications: ManagerNotifications<E::Primitives>,
384        wal_handle: WalHandle<E::Primitives>,
385        exex_head: ExExHead,
386    ) -> Self {
387        Self {
388            initial_local_head: node_head,
389            provider,
390            evm_config,
391            notifications,
392            wal_handle,
393            exex_head,
394            pending_check_canonical: true,
395            pending_check_backfill: true,
396            backfill_job: None,
397            backfill_thresholds: None,
398            pending_notifications: VecDeque::new(),
399        }
400    }
401
402    /// Sets custom thresholds for the backfill job.
403    ///
404    /// These thresholds control how many blocks are included in each backfill notification.
405    /// By default, the backfill job uses [`BackfillJobFactory`] defaults (up to 500,000 blocks
406    /// per batch, bounded by 30s execution time).
407    ///
408    /// If your ExEx is memory-constrained, consider setting a lower `max_blocks` value to
409    /// reduce the size of each backfill notification.
410    pub const fn with_backfill_thresholds(mut self, thresholds: ExecutionStageThresholds) -> Self {
411        self.backfill_thresholds = Some(thresholds);
412        self
413    }
414
415    /// Drops the notifications buffered during backfill, acknowledging them to the manager.
416    ///
417    /// Called when the stream is reconfigured, which discards its state.
418    fn drop_pending_notifications(&mut self) {
419        for notification in self.pending_notifications.drain(..) {
420            self.notifications.acknowledge(&notification);
421        }
422    }
423}
424
425impl<P, E> ExExNotificationsWithHead<P, E>
426where
427    P: BlockReader + StateProviderFactory + Clone + Unpin + 'static,
428    E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
429{
430    /// Checks if the ExEx head is on the canonical chain.
431    ///
432    /// If the head block is not found in the database or it's ahead of the node head, it means
433    /// we're not on the canonical chain and we need to revert the notification with the ExEx
434    /// head block.
435    fn check_canonical(&mut self) -> eyre::Result<Option<ExExNotification<E::Primitives>>> {
436        if self.provider.is_known(self.exex_head.block.hash)? &&
437            self.exex_head.block.number <= self.initial_local_head.number
438        {
439            // we have the targeted block and that block is below the current head
440            debug!(target: "exex::notifications", "ExEx head is on the canonical chain");
441            return Ok(None)
442        }
443
444        // If the head block is not found in the database, it means we're not on the canonical
445        // chain.
446
447        // Get the committed notification for the head block from the WAL.
448        let Some(notification) =
449            self.wal_handle.get_committed_notification_by_block_hash(&self.exex_head.block.hash)?
450        else {
451            // it's possible that the exex head is further ahead
452            if self.exex_head.block.number > self.initial_local_head.number {
453                debug!(target: "exex::notifications", "ExEx head is ahead of the canonical chain");
454                return Ok(None);
455            }
456
457            return Err(eyre::eyre!(
458                "Could not find notification for block hash {:?} in the WAL",
459                self.exex_head.block.hash
460            ))
461        };
462
463        // Update the head block hash to the parent hash of the first committed block.
464        let committed_chain = notification.committed_chain().unwrap();
465        let new_exex_head =
466            (committed_chain.first().parent_hash(), committed_chain.first().number() - 1).into();
467        debug!(target: "exex::notifications", old_exex_head = ?self.exex_head.block, new_exex_head = ?new_exex_head, "ExEx head updated");
468        self.exex_head.block = new_exex_head;
469
470        // Return an inverted notification. See the documentation for
471        // `ExExNotification::into_inverted`.
472        Ok(Some(notification.into_inverted()))
473    }
474
475    /// Compares the node head against the ExEx head, and backfills if needed.
476    ///
477    /// CAUTION: This method assumes that the ExEx head is <= the node head, and that it's on the
478    /// canonical chain.
479    ///
480    /// Possible situations are:
481    /// - ExEx is behind the node head (`exex_head.number < node_head.number`). Backfill from the
482    ///   node database.
483    /// - ExEx is at the same block number as the node head (`exex_head.number ==
484    ///   node_head.number`). Nothing to do.
485    fn check_backfill(&mut self) -> eyre::Result<()> {
486        let mut backfill_job_factory =
487            BackfillJobFactory::new(self.evm_config.clone(), self.provider.clone());
488        if let Some(thresholds) = self.backfill_thresholds.clone() {
489            backfill_job_factory = backfill_job_factory.with_thresholds(thresholds);
490        }
491        match self.exex_head.block.number.cmp(&self.initial_local_head.number) {
492            std::cmp::Ordering::Less => {
493                // ExEx is behind the node head, start backfill
494                debug!(target: "exex::notifications", "ExEx is behind the node head and on the canonical chain, starting backfill");
495                let backfill = backfill_job_factory
496                    .backfill(self.exex_head.block.number + 1..=self.initial_local_head.number)
497                    .into_stream();
498                self.backfill_job = Some(backfill);
499            }
500            std::cmp::Ordering::Equal => {
501                debug!(target: "exex::notifications", "ExEx is at the node head");
502            }
503            std::cmp::Ordering::Greater => {
504                debug!(target: "exex::notifications", "ExEx is ahead of the node head");
505            }
506        };
507
508        Ok(())
509    }
510
511    /// Returns whether the ExEx needs `notification`, and if so, moves the ExEx head to where the
512    /// notification leaves it, because the stream yields it.
513    ///
514    /// The ExEx doesn't need a commit that ends at or below its head. It doesn't need a
515    /// notification that reverts blocks if it has none of the reverted blocks and the chain the
516    /// notification leaves ends at or below its head, as when an ExEx restores a checkpoint past
517    /// a queued reorg. Unless the notification's own chain proves that, the canonical chain has
518    /// to; otherwise the ExEx gets the notification. All provider reads happen before the head
519    /// moves, so an error leaves it unchanged.
520    fn advance_exex_head(
521        &mut self,
522        notification: &ExExNotification<E::Primitives>,
523    ) -> ProviderResult<bool> {
524        let head = self.exex_head.block;
525        let committed = notification.committed_chain();
526        let Some(reverted) = notification.reverted_chain() else {
527            let Some(committed) = committed else { return Ok(false) };
528            // Inclusive check because we should start with `exex.head + 1`.
529            if head.number >= committed.tip().number() {
530                return Ok(false)
531            }
532            self.exex_head.block = committed.tip().num_hash();
533            return Ok(true)
534        };
535        let tip = committed.as_ref().map_or_else(|| reverted.fork_block(), |c| c.tip().num_hash());
536
537        // The ExEx is on the new branch, which forks off below every reverted block.
538        if let Some(committed) = &committed &&
539            committed.block_number(head.hash).is_some()
540        {
541            if head == tip {
542                return Ok(false)
543            }
544            self.exex_head.block = tip;
545            return Ok(true)
546        }
547
548        let is_canonical = |block: BlockNumHash| -> ProviderResult<bool> {
549            Ok(self.provider.block_hash(block.number)? == Some(block.hash))
550        };
551        // The reverted blocks form one chain, so the ExEx has none of them if it can't have the
552        // first: it is above the head, or the head is canonical and the first is not.
553        let first_reverted = reverted.first().num_hash();
554        let has_reverted_blocks = first_reverted.number <= head.number &&
555            !(is_canonical(head)? && !is_canonical(first_reverted)?);
556        // A canonical tip at or below the head is on the head's chain whenever the head is
557        // canonical. Otherwise the reverted blocks are above the head, which the ExEx can't have.
558        if !has_reverted_blocks && tip.number <= head.number && is_canonical(tip)? {
559            return Ok(false)
560        }
561
562        if committed.is_some() || has_reverted_blocks {
563            self.exex_head.block = tip;
564        }
565        Ok(true)
566    }
567}
568
569/// Receives the notifications that the [`ExExManager`](crate::ExExManager) sends to one `ExEx`.
570#[derive(Debug)]
571struct ManagerNotifications<N: NodePrimitives> {
572    receiver: Receiver<ExExNotification<N>>,
573    /// The `ExEx`'s event channel to the manager, if the manager tracks revert receipts.
574    revert_receipts: Option<UnboundedSender<ExExEvent>>,
575}
576
577impl<N: NodePrimitives> ManagerNotifications<N> {
578    fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<ExExNotification<N>>> {
579        self.receiver.poll_recv(cx)
580    }
581
582    /// Sends [`ExExEvent::RevertReceived`] if `notification` reverts blocks.
583    ///
584    /// Must be called once for every received notification, when the stream yields it to the
585    /// `ExEx`, skips it or drops it, so that the receipt precedes the `ExEx`'s next events.
586    fn acknowledge(&self, notification: &ExExNotification<N>) {
587        if let Some(events) = &self.revert_receipts &&
588            notification.reverted_chain().is_some() &&
589            events.send(ExExEvent::RevertReceived(RevertReceipt(()))).is_err()
590        {
591            debug!(target: "exex::notifications", "ExEx manager is gone, revert receipt not sent");
592        }
593    }
594}
595
596impl<P, E> Stream for ExExNotificationsWithHead<P, E>
597where
598    P: BlockReader + StateProviderFactory + Clone + Unpin + 'static,
599    E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
600{
601    type Item = eyre::Result<ExExNotification<E::Primitives>>;
602
603    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
604        let this = self.get_mut();
605
606        // 1. Check once whether we need to retrieve a notification gap from the WAL.
607        if this.pending_check_canonical {
608            if let Some(canonical_notification) = this.check_canonical()? {
609                return Poll::Ready(Some(Ok(canonical_notification)))
610            }
611
612            // ExEx head is on the canonical chain, we no longer need to check it
613            this.pending_check_canonical = false;
614        }
615
616        // 2. Check once whether we need to trigger backfill sync
617        if this.pending_check_backfill {
618            this.check_backfill()?;
619            this.pending_check_backfill = false;
620        }
621
622        // 3. If backfill is in progress yield new notifications
623        if let Some(backfill_job) = &mut this.backfill_job {
624            debug!(target: "exex::notifications", "Polling backfill job");
625
626            // Drain the notification channel to prevent backpressure from stalling the
627            // ExExManager. During backfill, the ExEx is not consuming from the channel,
628            // so the capacity-1 channel fills up, which blocks the manager's PollSender,
629            // which fills the manager's 1024-entry buffer, which blocks all upstream
630            // senders. Notifications for blocks covered by the backfill range are
631            // discarded (they'll be re-delivered by the backfill job), while
632            // notifications beyond the backfill range are buffered for delivery after the
633            // backfill completes.
634            while let Poll::Ready(Some(notification)) = this.notifications.poll_recv(cx) {
635                // Always buffer revert-containing notifications (ChainReverted,
636                // ChainReorged) because the backfill job only re-delivers
637                // ChainCommitted from the database. Discarding a reorg here would
638                // leave the ExEx unaware of the fork switch.
639                if notification.reverted_chain().is_some() {
640                    this.pending_notifications.push_back(notification);
641                    continue;
642                }
643                // Covered by backfill range, safe to discard, but only until the first buffered
644                // notification: commits after a buffered revert are on the new branch, which the
645                // backfill doesn't cover.
646                if this.pending_notifications.is_empty() &&
647                    let Some(committed) = notification.committed_chain() &&
648                    committed.tip().number() <= this.initial_local_head.number
649                {
650                    continue;
651                }
652                // Beyond the backfill range — buffer for delivery after backfill
653                this.pending_notifications.push_back(notification);
654            }
655
656            if let Some(chain) = ready!(backfill_job.poll_next_unpin(cx)).transpose()? {
657                debug!(target: "exex::notifications", range = ?chain.range(), "Backfill job returned a chain");
658                this.exex_head.block = chain.tip().num_hash();
659                return Poll::Ready(Some(Ok(ExExNotification::ChainCommitted {
660                    new: Arc::new(chain),
661                })))
662            }
663
664            // Backfill job is done, remove it
665            this.backfill_job = None;
666        }
667
668        // 4. Deliver the notifications buffered during backfill, then the regular event stream,
669        //    skipping the ones the ExEx already has.
670        loop {
671            let notification = match this.pending_notifications.pop_front() {
672                Some(notification) => notification,
673                None => match ready!(this.notifications.poll_recv(cx)) {
674                    Some(notification) => notification,
675                    None => return Poll::Ready(None),
676                },
677            };
678
679            let needed = match this.advance_exex_head(&notification) {
680                Ok(needed) => needed,
681                Err(err) => {
682                    // Keep the notification, so that the next poll retries it.
683                    this.pending_notifications.push_front(notification);
684                    return Poll::Ready(Some(Err(err.into())))
685                }
686            };
687            this.notifications.acknowledge(&notification);
688            if needed {
689                return Poll::Ready(Some(Ok(notification)))
690            }
691        }
692    }
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698    use crate::Wal;
699    use alloy_consensus::Header;
700    use alloy_eips::BlockNumHash;
701    use alloy_primitives::B256;
702    use eyre::OptionExt;
703    use futures::{StreamExt, TryStreamExt};
704    use rand::Rng;
705    use reth_chain_state::CanonicalInMemoryStateWriter;
706    use reth_chainspec::MAINNET;
707    use reth_db_common::init::init_genesis;
708    use reth_ethereum_primitives::Block;
709    use reth_evm_ethereum::EthEvmConfig;
710    use reth_primitives_traits::{Block as _, RecoveredBlock};
711    use reth_provider::{
712        providers::BlockchainProvider,
713        test_utils::{
714            create_test_provider_factory, create_test_provider_factory_with_in_memory_state_writer,
715            MockNodeTypesWithDB,
716        },
717        BlockWriter, Chain, DBProvider, DatabaseProviderFactory,
718    };
719    use reth_testing_utils::generators::{self, random_block, BlockParams};
720    use std::collections::BTreeMap;
721    use tokio::sync::mpsc;
722
723    #[tokio::test]
724    async fn exex_notifications_behind_head_canonical() -> eyre::Result<()> {
725        let mut rng = generators::rng();
726
727        let temp_dir = tempfile::tempdir().unwrap();
728        let wal = Wal::new(temp_dir.path()).unwrap();
729
730        let provider_factory = create_test_provider_factory();
731        let genesis_hash = init_genesis(&provider_factory)?;
732        let genesis_block = provider_factory
733            .block(genesis_hash.into())?
734            .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
735
736        let provider = BlockchainProvider::new(provider_factory.clone())?;
737
738        let node_head_block = random_block(
739            &mut rng,
740            genesis_block.number + 1,
741            BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
742        )
743        .try_recover()?;
744        let node_head = node_head_block.num_hash();
745        let provider_rw = provider_factory.provider_rw()?;
746        provider_rw.insert_block(&node_head_block)?;
747        provider_rw.commit()?;
748        let exex_head =
749            ExExHead { block: BlockNumHash { number: genesis_block.number, hash: genesis_hash } };
750
751        let notification = ExExNotification::ChainCommitted {
752            new: Arc::new(Chain::new(
753                vec![random_block(
754                    &mut rng,
755                    node_head.number + 1,
756                    BlockParams { parent: Some(node_head.hash), ..Default::default() },
757                )
758                .try_recover()?],
759                Default::default(),
760                BTreeMap::new(),
761            )),
762        };
763
764        let (notifications_tx, notifications_rx) = mpsc::channel(1);
765
766        notifications_tx.send(notification.clone()).await?;
767
768        let mut notifications = ExExNotificationsWithoutHead::new(
769            node_head,
770            provider,
771            EthEvmConfig::mainnet(),
772            notifications_rx,
773            wal.handle(),
774        )
775        .with_head(exex_head);
776
777        // First notification is the backfill of missing blocks from the canonical chain
778        assert_eq!(
779            notifications.next().await.transpose()?,
780            Some(ExExNotification::ChainCommitted {
781                new: Arc::new(
782                    BackfillJobFactory::new(
783                        notifications.evm_config.clone(),
784                        notifications.provider.clone()
785                    )
786                    .backfill(1..=1)
787                    .next()
788                    .ok_or_eyre("failed to backfill")??
789                )
790            })
791        );
792
793        // Second notification is the actual notification that we sent before
794        assert_eq!(notifications.next().await.transpose()?, Some(notification));
795
796        Ok(())
797    }
798
799    #[tokio::test]
800    async fn catch_up_with_head_after_pause_backfills_missed_blocks() -> eyre::Result<()> {
801        let mut rng = generators::rng();
802
803        let temp_dir = tempfile::tempdir().unwrap();
804        let wal = Wal::new(temp_dir.path()).unwrap();
805
806        let (provider_factory, in_memory_state_writer) =
807            create_test_provider_factory_with_in_memory_state_writer(MAINNET.clone());
808        let genesis_hash = init_genesis(&provider_factory)?;
809        let genesis_block = provider_factory
810            .block(genesis_hash.into())?
811            .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
812        let mut canonical_in_memory_state_writer = CanonicalInMemoryStateWriter::new(
813            provider_factory.chain_info_headers()?,
814            in_memory_state_writer,
815        );
816        let provider = BlockchainProvider::with_canonical_in_memory_state(
817            provider_factory.clone(),
818            canonical_in_memory_state_writer.canonical_in_memory_state().clone(),
819        );
820
821        let exex_head =
822            ExExHead { block: BlockNumHash { number: genesis_block.number, hash: genesis_hash } };
823        let (notifications_tx, notifications_rx) = mpsc::channel(1);
824
825        let evm_config = EthEvmConfig::mainnet();
826        let mut notifications = ExExNotifications::new(
827            BlockNumHash { number: genesis_block.number, hash: genesis_hash },
828            provider.clone(),
829            evm_config.clone(),
830            notifications_rx,
831            wal.handle(),
832        );
833        // The ExEx configures its head at launch, as usual.
834        notifications.set_with_head(exex_head);
835
836        // Block 1 is delivered live and consumed, but the ExEx fails to durably process it.
837        let node_head_block = random_block(
838            &mut rng,
839            genesis_block.number + 1,
840            BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
841        )
842        .try_recover()?;
843        let node_head = node_head_block.num_hash();
844        let block_1_notification = ExExNotification::ChainCommitted {
845            new: Arc::new(Chain::new(
846                vec![node_head_block.clone()],
847                Default::default(),
848                BTreeMap::new(),
849            )),
850        };
851        notifications_tx.send(block_1_notification.clone()).await?;
852        assert_eq!(notifications.next().await.transpose()?, Some(block_1_notification));
853
854        // Meanwhile the node commits block 1 and advances its canonical head past the
855        // launch-time head.
856        let provider_rw = provider_factory.provider_rw()?;
857        provider_rw.insert_block(&node_head_block)?;
858        provider_rw.commit()?;
859        canonical_in_memory_state_writer.set_canonical_head(node_head_block.clone_sealed_header());
860
861        // The ExEx recovers still at genesis and catches up, it needs block 1 again, but that
862        // notification is long gone from the channel.
863        notifications.catch_up_with_head(exex_head)?;
864
865        let block_2_notification = ExExNotification::ChainCommitted {
866            new: Arc::new(Chain::new(
867                vec![random_block(
868                    &mut rng,
869                    node_head.number + 1,
870                    BlockParams { parent: Some(node_head.hash), ..Default::default() },
871                )
872                .try_recover()?],
873                Default::default(),
874                BTreeMap::new(),
875            )),
876        };
877        notifications_tx.send(block_2_notification.clone()).await?;
878
879        // Backfill re-delivers block 1 up to the node's current head
880        assert_eq!(
881            notifications.next().await.transpose()?,
882            Some(ExExNotification::ChainCommitted {
883                new: Arc::new(
884                    BackfillJobFactory::new(evm_config, provider)
885                        .backfill(1..=1)
886                        .next()
887                        .ok_or_eyre("failed to backfill")??
888                )
889            })
890        );
891        // followed by the live notification for block 2.
892        assert_eq!(notifications.next().await.transpose()?, Some(block_2_notification));
893
894        Ok(())
895    }
896
897    #[tokio::test]
898    async fn exex_notifications_same_head_canonical() -> eyre::Result<()> {
899        let temp_dir = tempfile::tempdir().unwrap();
900        let wal = Wal::new(temp_dir.path()).unwrap();
901
902        let provider_factory = create_test_provider_factory();
903        let genesis_hash = init_genesis(&provider_factory)?;
904        let genesis_block = provider_factory
905            .block(genesis_hash.into())?
906            .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
907
908        let provider = BlockchainProvider::new(provider_factory)?;
909
910        let node_head = BlockNumHash { number: genesis_block.number, hash: genesis_hash };
911        let exex_head = ExExHead { block: node_head };
912
913        let notification = ExExNotification::ChainCommitted {
914            new: Arc::new(Chain::new(
915                vec![Block {
916                    header: Header {
917                        parent_hash: node_head.hash,
918                        number: node_head.number + 1,
919                        ..Default::default()
920                    },
921                    ..Default::default()
922                }
923                .seal_slow()
924                .try_recover()?],
925                Default::default(),
926                BTreeMap::new(),
927            )),
928        };
929
930        let (notifications_tx, notifications_rx) = mpsc::channel(1);
931
932        notifications_tx.send(notification.clone()).await?;
933
934        let mut notifications = ExExNotificationsWithoutHead::new(
935            node_head,
936            provider,
937            EthEvmConfig::mainnet(),
938            notifications_rx,
939            wal.handle(),
940        )
941        .with_head(exex_head);
942
943        let new_notification = notifications.next().await.transpose()?;
944        assert_eq!(new_notification, Some(notification));
945
946        Ok(())
947    }
948
949    /// A reorg replacing the ExEx head block at the same height must be delivered, even though
950    /// its new tip is not above the ExEx head.
951    #[tokio::test]
952    async fn exex_notifications_same_head_reorg_at_head() -> eyre::Result<()> {
953        let temp_dir = tempfile::tempdir().unwrap();
954        let wal = Wal::new(temp_dir.path()).unwrap();
955        let (provider, node_head_block, new_block) = same_head_setup()?;
956        let node_head = node_head_block.num_hash();
957        let exex_head = ExExHead { block: node_head };
958
959        let notification = ExExNotification::ChainReorged {
960            old: Arc::new(Chain::new(vec![node_head_block], Default::default(), BTreeMap::new())),
961            new: Arc::new(Chain::new(vec![new_block], Default::default(), BTreeMap::new())),
962        };
963
964        let (notifications_tx, notifications_rx) = mpsc::channel(1);
965
966        notifications_tx.send(notification.clone()).await?;
967        drop(notifications_tx);
968
969        let mut notifications = ExExNotificationsWithoutHead::new(
970            node_head,
971            provider,
972            EthEvmConfig::mainnet(),
973            notifications_rx,
974            wal.handle(),
975        )
976        .with_head(exex_head);
977
978        assert_eq!(notifications.next().await.transpose()?, Some(notification));
979
980        Ok(())
981    }
982
983    /// A revert of the ExEx head buffered during backfill must move the ExEx head, so that a later
984    /// commit of the new branch at the height of the old head is delivered.
985    #[tokio::test]
986    async fn exex_notifications_commit_after_revert_buffered_during_backfill() -> eyre::Result<()> {
987        let temp_dir = tempfile::tempdir().unwrap();
988        let wal = Wal::new(temp_dir.path()).unwrap();
989        let (provider, a1, b1) = same_head_setup()?;
990        let a2 = random_block(
991            &mut generators::rng(),
992            2,
993            BlockParams { parent: Some(a1.hash()), tx_count: Some(0), ..Default::default() },
994        )
995        .try_recover()?;
996        let provider_rw = provider.database_provider_rw()?;
997        provider_rw.insert_block(&a2)?;
998        provider_rw.commit()?;
999
1000        let revert = ExExNotification::ChainReverted {
1001            old: Arc::new(Chain::new(
1002                vec![a1.clone(), a2.clone()],
1003                Default::default(),
1004                BTreeMap::new(),
1005            )),
1006        };
1007        let commit = ExExNotification::ChainCommitted {
1008            new: Arc::new(Chain::new(vec![b1], Default::default(), BTreeMap::new())),
1009        };
1010        let (notifications_tx, notifications_rx) = mpsc::channel(1);
1011        notifications_tx.send(revert.clone()).await?;
1012
1013        let (events_tx, mut events_rx) = mpsc::unbounded_channel();
1014        let mut notifications = ExExNotificationsWithoutHead::new(
1015            a2.num_hash(),
1016            provider,
1017            EthEvmConfig::mainnet(),
1018            notifications_rx,
1019            wal.handle(),
1020        );
1021        notifications.notifications.revert_receipts = Some(events_tx);
1022        let mut notifications = notifications.with_head(ExExHead { block: a1.num_hash() });
1023
1024        // The backfill of A2 comes first, and the revert is buffered meanwhile.
1025        let Some(ExExNotification::ChainCommitted { new }) =
1026            notifications.next().await.transpose()?
1027        else {
1028            panic!("expected the backfill of A2")
1029        };
1030        assert_eq!(new.tip().num_hash(), a2.num_hash());
1031        assert!(events_rx.try_recv().is_err());
1032        // The revert is acknowledged once it is yielded from the buffer.
1033        assert_eq!(notifications.next().await.transpose()?, Some(revert));
1034        assert_eq!(events_rx.try_recv()?, ExExEvent::RevertReceived(RevertReceipt(())));
1035
1036        notifications_tx.send(commit.clone()).await?;
1037        drop(notifications_tx);
1038        assert_eq!(notifications.next().await.transpose()?, Some(commit));
1039        assert_eq!(notifications.next().await.transpose()?, None);
1040
1041        Ok(())
1042    }
1043
1044    /// Reconfiguring the stream drops the notifications buffered during backfill, so it must
1045    /// acknowledge their reverts, or the manager would ignore the ExEx's finished heights forever.
1046    #[tokio::test]
1047    async fn exex_notifications_acknowledge_reverts_dropped_on_reconfiguration() -> eyre::Result<()>
1048    {
1049        for reconfiguration in ["catch_up_with_head", "set_with_head", "set_without_head"] {
1050            let temp_dir = tempfile::tempdir()?;
1051            let wal = Wal::new(temp_dir.path())?;
1052            let (provider, a1, _) = same_head_setup()?;
1053            let a2 = block(&mut generators::rng(), 2, a1.hash())?;
1054            insert(&provider, &[&a2])?;
1055
1056            let (notifications_tx, notifications_rx) = mpsc::channel(1);
1057            notifications_tx
1058                .send(ExExNotification::ChainReverted { old: chain(vec![a2.clone()]) })
1059                .await?;
1060            let (events_tx, mut events_rx) = mpsc::unbounded_channel();
1061            let mut notifications = ExExNotifications::new(
1062                a2.num_hash(),
1063                provider,
1064                EthEvmConfig::mainnet(),
1065                notifications_rx,
1066                wal.handle(),
1067            )
1068            .with_revert_receipts(events_tx);
1069            let head = ExExHead { block: a1.num_hash() };
1070            notifications.set_with_head(head);
1071
1072            // The backfill of A2 comes first, and the revert is buffered meanwhile.
1073            assert!(matches!(
1074                notifications.next().await.transpose()?,
1075                Some(ExExNotification::ChainCommitted { .. })
1076            ));
1077            assert!(events_rx.try_recv().is_err());
1078
1079            match reconfiguration {
1080                "catch_up_with_head" => notifications.catch_up_with_head(head)?,
1081                "set_with_head" => notifications.set_with_head(head),
1082                _ => notifications.set_without_head(),
1083            }
1084            assert_eq!(
1085                events_rx.try_recv(),
1086                Ok(ExExEvent::RevertReceived(RevertReceipt(()))),
1087                "{reconfiguration}"
1088            );
1089        }
1090
1091        Ok(())
1092    }
1093
1094    /// Inserts a block at height 1 as the node and ExEx head, and returns the head block with a
1095    /// sibling block at the same height.
1096    fn same_head_setup() -> eyre::Result<(
1097        BlockchainProvider<MockNodeTypesWithDB>,
1098        RecoveredBlock<Block>,
1099        RecoveredBlock<Block>,
1100    )> {
1101        let mut rng = generators::rng();
1102        let provider_factory = create_test_provider_factory();
1103        let genesis_hash = init_genesis(&provider_factory)?;
1104        let provider = BlockchainProvider::new(provider_factory)?;
1105
1106        let mut block = || {
1107            let block_params =
1108                BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() };
1109            random_block(&mut rng, 1, block_params).try_recover()
1110        };
1111        let head_block = block()?;
1112        let sibling_block = block()?;
1113        let provider_rw = provider.database_provider_rw()?;
1114        provider_rw.insert_block(&head_block)?;
1115        provider_rw.commit()?;
1116
1117        Ok((provider, head_block, sibling_block))
1118    }
1119
1120    /// Returns a random empty block at `number` on top of `parent`.
1121    fn block(rng: &mut impl Rng, number: u64, parent: B256) -> eyre::Result<RecoveredBlock<Block>> {
1122        let block_params =
1123            BlockParams { parent: Some(parent), tx_count: Some(0), ..Default::default() };
1124        Ok(random_block(rng, number, block_params).try_recover()?)
1125    }
1126
1127    /// Returns a chain of `blocks` without state.
1128    fn chain(blocks: Vec<RecoveredBlock<Block>>) -> Arc<Chain> {
1129        Arc::new(Chain::new(blocks, Default::default(), BTreeMap::new()))
1130    }
1131
1132    /// Writes `blocks` to the database of `provider`, which makes them canonical.
1133    fn insert(
1134        provider: &BlockchainProvider<MockNodeTypesWithDB>,
1135        blocks: &[&RecoveredBlock<Block>],
1136    ) -> eyre::Result<()> {
1137        let provider_rw = provider.database_provider_rw()?;
1138        for block in blocks {
1139            provider_rw.insert_block(block)?;
1140        }
1141        provider_rw.commit()?;
1142        Ok(())
1143    }
1144
1145    /// Runs a stream with `exex_head` over `notifications` until they run out, and returns what
1146    /// it yields and the number of revert receipts it sends.
1147    async fn run_with_head(
1148        provider: BlockchainProvider<MockNodeTypesWithDB>,
1149        node_head: BlockNumHash,
1150        exex_head: BlockNumHash,
1151        notifications: Vec<ExExNotification>,
1152    ) -> eyre::Result<(Vec<ExExNotification>, usize)> {
1153        let temp_dir = tempfile::tempdir()?;
1154        let wal = Wal::new(temp_dir.path())?;
1155        let (notifications_tx, notifications_rx) = mpsc::channel(notifications.len());
1156        for notification in notifications {
1157            notifications_tx.send(notification).await?;
1158        }
1159        drop(notifications_tx);
1160
1161        let (events_tx, mut events_rx) = mpsc::unbounded_channel();
1162        let mut stream = ExExNotificationsWithoutHead::new(
1163            node_head,
1164            provider,
1165            EthEvmConfig::mainnet(),
1166            notifications_rx,
1167            wal.handle(),
1168        );
1169        stream.notifications.revert_receipts = Some(events_tx);
1170        let yielded = stream.with_head(ExExHead { block: exex_head }).try_collect().await?;
1171
1172        let mut receipts = 0;
1173        while events_rx.try_recv().is_ok() {
1174            receipts += 1;
1175        }
1176        Ok((yielded, receipts))
1177    }
1178
1179    /// A queued reorg whose new chain ends at the ExEx head was already applied by the ExEx, so it
1180    /// is skipped, but still acknowledged.
1181    #[tokio::test]
1182    async fn exex_notifications_same_head_skips_reorg_to_head() -> eyre::Result<()> {
1183        let (provider, head_block, sibling_block) = same_head_setup()?;
1184        let head = head_block.num_hash();
1185
1186        let sequence = vec![ExExNotification::ChainReorged {
1187            old: chain(vec![sibling_block]),
1188            new: chain(vec![head_block]),
1189        }];
1190        let (yielded, receipts) = run_with_head(provider, head, head, sequence).await?;
1191        assert_eq!(yielded, vec![]);
1192        // The skipped reorg is still acknowledged, so the manager accepts later finished heights.
1193        assert_eq!(receipts, 1);
1194
1195        Ok(())
1196    }
1197
1198    /// An ExEx that restored a checkpoint past a queued reorg and revert has their resulting chains
1199    /// and none of their reverted blocks, so they must not be replayed, but still acknowledged.
1200    #[tokio::test]
1201    async fn exex_notifications_skip_reverts_behind_restored_head() -> eyre::Result<()> {
1202        let (provider, a1, b1) = same_head_setup()?;
1203        let mut rng = generators::rng();
1204        let a2 = block(&mut rng, 2, a1.hash())?;
1205        let c2 = block(&mut rng, 2, a1.hash())?;
1206        let a3 = block(&mut rng, 3, a2.hash())?;
1207        insert(&provider, &[&a2])?;
1208
1209        // The node reorged B1 to A1, reverted C2 and committed A2, and the ExEx restored A2.
1210        let commit_a3 = ExExNotification::ChainCommitted { new: chain(vec![a3]) };
1211        let sequence = vec![
1212            ExExNotification::ChainReorged { old: chain(vec![b1]), new: chain(vec![a1]) },
1213            ExExNotification::ChainReverted { old: chain(vec![c2]) },
1214            ExExNotification::ChainCommitted { new: chain(vec![a2.clone()]) },
1215            commit_a3.clone(),
1216        ];
1217        let (yielded, receipts) =
1218            run_with_head(provider, a2.num_hash(), a2.num_hash(), sequence).await?;
1219        assert_eq!(yielded, vec![commit_a3]);
1220        assert_eq!(receipts, 2);
1221
1222        Ok(())
1223    }
1224
1225    /// A queued revert of blocks below the ExEx head must be delivered, because the ExEx has them,
1226    /// even though a later notification commits them again.
1227    #[tokio::test]
1228    async fn exex_notifications_deliver_revert_of_head_ancestors() -> eyre::Result<()> {
1229        let (provider, a1, _) = same_head_setup()?;
1230        let a2 = block(&mut generators::rng(), 2, a1.hash())?;
1231        insert(&provider, &[&a2])?;
1232
1233        let sequence = vec![
1234            ExExNotification::ChainReverted { old: chain(vec![a1.clone()]) },
1235            ExExNotification::ChainCommitted { new: chain(vec![a1, a2.clone()]) },
1236        ];
1237        let (yielded, _) =
1238            run_with_head(provider, a2.num_hash(), a2.num_hash(), sequence.clone()).await?;
1239        assert_eq!(yielded, sequence);
1240
1241        Ok(())
1242    }
1243
1244    /// A reorg to a chain that is no longer canonical must be delivered, because the canonical
1245    /// chain can't prove that the ExEx head is on it.
1246    #[tokio::test]
1247    async fn exex_notifications_deliver_reorg_to_non_canonical_chain() -> eyre::Result<()> {
1248        let (provider, a1, b1) = same_head_setup()?;
1249        let mut rng = generators::rng();
1250        let c1 = block(&mut rng, 1, a1.parent_hash())?;
1251        let a2 = block(&mut rng, 2, a1.hash())?;
1252        insert(&provider, &[&a2])?;
1253
1254        let sequence =
1255            vec![ExExNotification::ChainReorged { old: chain(vec![c1]), new: chain(vec![b1]) }];
1256        let (yielded, _) =
1257            run_with_head(provider, a2.num_hash(), a2.num_hash(), sequence.clone()).await?;
1258        assert_eq!(yielded, sequence);
1259
1260        Ok(())
1261    }
1262
1263    /// The backlog a paused ExEx catches up on can hold a reorg that happened before the node
1264    /// head was captured. The backfill already delivers its new branch, so neither the reorg nor
1265    /// the commits after it may be delivered again.
1266    #[tokio::test]
1267    async fn exex_notifications_skip_backlog_applied_by_backfill() -> eyre::Result<()> {
1268        let (provider, b1, a1) = same_head_setup()?;
1269        let genesis = BlockNumHash::new(0, b1.parent_hash());
1270        let b2 = block(&mut generators::rng(), 2, b1.hash())?;
1271        insert(&provider, &[&b2])?;
1272
1273        let sequence = vec![
1274            ExExNotification::ChainReorged { old: chain(vec![a1]), new: chain(vec![b1]) },
1275            ExExNotification::ChainCommitted { new: chain(vec![b2.clone()]) },
1276        ];
1277        let (yielded, _) = run_with_head(provider, b2.num_hash(), genesis, sequence).await?;
1278        // Only the backfill of B1..B2.
1279        assert_eq!(yielded.len(), 1);
1280        assert_eq!(yielded[0].committed_chain().map(|c| c.tip().num_hash()), Some(b2.num_hash()));
1281
1282        Ok(())
1283    }
1284
1285    /// Every delivered notification moves the ExEx head, so a later revert of the blocks it
1286    /// delivered is delivered too, even though the canonical chain doesn't have them.
1287    #[tokio::test]
1288    async fn exex_notifications_deliver_reverts_of_delivered_blocks() -> eyre::Result<()> {
1289        let (provider, a1, b1) = same_head_setup()?;
1290        let c1 = block(&mut generators::rng(), 1, a1.parent_hash())?;
1291
1292        let sequence = vec![
1293            ExExNotification::ChainReorged {
1294                old: chain(vec![a1.clone()]),
1295                new: chain(vec![b1.clone()]),
1296            },
1297            ExExNotification::ChainReverted { old: chain(vec![b1]) },
1298            ExExNotification::ChainCommitted { new: chain(vec![c1.clone()]) },
1299            ExExNotification::ChainReverted { old: chain(vec![c1]) },
1300        ];
1301        let (yielded, _) =
1302            run_with_head(provider, a1.num_hash(), a1.num_hash(), sequence.clone()).await?;
1303        assert_eq!(yielded, sequence);
1304
1305        Ok(())
1306    }
1307
1308    /// A reorg whose canonical new chain ends above the ExEx head must be delivered, even though
1309    /// the ExEx has none of the reverted blocks.
1310    #[tokio::test]
1311    async fn exex_notifications_deliver_reorg_past_head() -> eyre::Result<()> {
1312        let (provider, a1, _) = same_head_setup()?;
1313        let mut rng = generators::rng();
1314        let a2 = block(&mut rng, 2, a1.hash())?;
1315        let a3 = block(&mut rng, 3, a2.hash())?;
1316        let b2 = block(&mut rng, 2, a1.hash())?;
1317        insert(&provider, &[&a2, &a3])?;
1318
1319        let sequence =
1320            vec![ExExNotification::ChainReorged { old: chain(vec![b2]), new: chain(vec![a2, a3]) }];
1321        let (yielded, _) =
1322            run_with_head(provider, a1.num_hash(), a1.num_hash(), sequence.clone()).await?;
1323        assert_eq!(yielded, sequence);
1324
1325        Ok(())
1326    }
1327
1328    /// A commit that follows a revert buffered during backfill is on the new branch, which the
1329    /// backfill doesn't cover, so it must be delivered although it is below the node head.
1330    #[tokio::test]
1331    async fn exex_notifications_commit_buffered_after_revert_during_backfill() -> eyre::Result<()> {
1332        let (provider, a1, b1) = same_head_setup()?;
1333        let a2 = block(&mut generators::rng(), 2, a1.hash())?;
1334        insert(&provider, &[&a2])?;
1335
1336        let sequence = vec![
1337            ExExNotification::ChainReverted { old: chain(vec![a1.clone(), a2.clone()]) },
1338            ExExNotification::ChainCommitted { new: chain(vec![b1]) },
1339        ];
1340        let (yielded, _) =
1341            run_with_head(provider, a2.num_hash(), a1.num_hash(), sequence.clone()).await?;
1342        // The backfill of A2 comes first, and the revert and B1 are buffered meanwhile.
1343        assert_eq!(yielded[0].committed_chain().map(|c| c.tip().num_hash()), Some(a2.num_hash()));
1344        assert_eq!(yielded[1..], sequence);
1345
1346        Ok(())
1347    }
1348
1349    /// The canonical chain can't show which blocks a non-canonical ExEx head descends from, so a
1350    /// revert of non-canonical blocks below it must be delivered.
1351    #[tokio::test]
1352    async fn exex_notifications_deliver_revert_below_non_canonical_head() -> eyre::Result<()> {
1353        let (provider, a1, c1) = same_head_setup()?;
1354        let c2 = block(&mut generators::rng(), 2, c1.hash())?;
1355
1356        // The ExEx restored C2, which is ahead of the node and on a branch it no longer has.
1357        let sequence = vec![ExExNotification::ChainReverted { old: chain(vec![c1]) }];
1358        let (yielded, _) =
1359            run_with_head(provider, a1.num_hash(), c2.num_hash(), sequence.clone()).await?;
1360        assert_eq!(yielded, sequence);
1361
1362        Ok(())
1363    }
1364
1365    /// A reorg whose new chain extends past the ExEx head must be delivered, because the ExEx
1366    /// does not have the blocks above its head.
1367    #[tokio::test]
1368    async fn exex_notifications_same_head_reorg_above_head() -> eyre::Result<()> {
1369        let temp_dir = tempfile::tempdir().unwrap();
1370        let wal = Wal::new(temp_dir.path()).unwrap();
1371        let (provider, head_block, sibling_block) = same_head_setup()?;
1372        let head = head_block.num_hash();
1373
1374        let child_block = random_block(
1375            &mut generators::rng(),
1376            2,
1377            BlockParams { parent: Some(head.hash), tx_count: Some(0), ..Default::default() },
1378        )
1379        .try_recover()?;
1380        let reorg = ExExNotification::ChainReorged {
1381            old: Arc::new(Chain::new(vec![sibling_block], Default::default(), BTreeMap::new())),
1382            new: Arc::new(Chain::new(
1383                vec![head_block, child_block],
1384                Default::default(),
1385                BTreeMap::new(),
1386            )),
1387        };
1388        let (notifications_tx, notifications_rx) = mpsc::channel(1);
1389        notifications_tx.send(reorg.clone()).await?;
1390        drop(notifications_tx);
1391
1392        let mut notifications = ExExNotificationsWithoutHead::new(
1393            head,
1394            provider,
1395            EthEvmConfig::mainnet(),
1396            notifications_rx,
1397            wal.handle(),
1398        )
1399        .with_head(ExExHead { block: head });
1400
1401        assert_eq!(notifications.next().await.transpose()?, Some(reorg));
1402
1403        Ok(())
1404    }
1405
1406    /// After a revert of the ExEx head is forwarded, a commit of the new branch at the height of
1407    /// the ExEx head must be delivered.
1408    #[tokio::test]
1409    async fn exex_notifications_same_head_commit_after_revert() -> eyre::Result<()> {
1410        let temp_dir = tempfile::tempdir().unwrap();
1411        let wal = Wal::new(temp_dir.path()).unwrap();
1412        let (provider, head_block, sibling_block) = same_head_setup()?;
1413        let head = head_block.num_hash();
1414
1415        let revert = ExExNotification::ChainReverted {
1416            old: Arc::new(Chain::new(vec![head_block], Default::default(), BTreeMap::new())),
1417        };
1418        let commit = ExExNotification::ChainCommitted {
1419            new: Arc::new(Chain::new(vec![sibling_block], Default::default(), BTreeMap::new())),
1420        };
1421        let (notifications_tx, notifications_rx) = mpsc::channel(2);
1422        notifications_tx.send(revert.clone()).await?;
1423        notifications_tx.send(commit.clone()).await?;
1424        drop(notifications_tx);
1425
1426        let mut notifications = ExExNotificationsWithoutHead::new(
1427            head,
1428            provider,
1429            EthEvmConfig::mainnet(),
1430            notifications_rx,
1431            wal.handle(),
1432        )
1433        .with_head(ExExHead { block: head });
1434
1435        assert_eq!(notifications.next().await.transpose()?, Some(revert));
1436        assert_eq!(notifications.next().await.transpose()?, Some(commit));
1437        assert_eq!(notifications.next().await.transpose()?, None);
1438
1439        Ok(())
1440    }
1441
1442    #[tokio::test]
1443    async fn exex_notifications_same_head_non_canonical() -> eyre::Result<()> {
1444        let mut rng = generators::rng();
1445
1446        let temp_dir = tempfile::tempdir().unwrap();
1447        let wal = Wal::new(temp_dir.path()).unwrap();
1448
1449        let provider_factory = create_test_provider_factory();
1450        let genesis_hash = init_genesis(&provider_factory)?;
1451        let genesis_block = provider_factory
1452            .block(genesis_hash.into())?
1453            .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
1454
1455        let provider = BlockchainProvider::new(provider_factory)?;
1456
1457        let node_head_block = random_block(
1458            &mut rng,
1459            genesis_block.number + 1,
1460            BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
1461        )
1462        .try_recover()?;
1463        let node_head = node_head_block.num_hash();
1464        let provider_rw = provider.database_provider_rw()?;
1465        provider_rw.insert_block(&node_head_block)?;
1466        provider_rw.commit()?;
1467        let node_head_notification = ExExNotification::ChainCommitted {
1468            new: Arc::new(
1469                BackfillJobFactory::new(EthEvmConfig::mainnet(), provider.clone())
1470                    .backfill(node_head.number..=node_head.number)
1471                    .next()
1472                    .ok_or_else(|| eyre::eyre!("failed to backfill"))??,
1473            ),
1474        };
1475
1476        let exex_head_block = random_block(
1477            &mut rng,
1478            genesis_block.number + 1,
1479            BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
1480        );
1481        let exex_head = ExExHead { block: exex_head_block.num_hash() };
1482        let exex_head_notification = ExExNotification::ChainCommitted {
1483            new: Arc::new(Chain::new(
1484                vec![exex_head_block.clone().try_recover()?],
1485                Default::default(),
1486                BTreeMap::new(),
1487            )),
1488        };
1489        wal.commit(&exex_head_notification)?;
1490
1491        let new_notification = ExExNotification::ChainCommitted {
1492            new: Arc::new(Chain::new(
1493                vec![random_block(
1494                    &mut rng,
1495                    node_head.number + 1,
1496                    BlockParams { parent: Some(node_head.hash), ..Default::default() },
1497                )
1498                .try_recover()?],
1499                Default::default(),
1500                BTreeMap::new(),
1501            )),
1502        };
1503
1504        let (notifications_tx, notifications_rx) = mpsc::channel(1);
1505
1506        notifications_tx.send(new_notification.clone()).await?;
1507
1508        let mut notifications = ExExNotificationsWithoutHead::new(
1509            node_head,
1510            provider,
1511            EthEvmConfig::mainnet(),
1512            notifications_rx,
1513            wal.handle(),
1514        )
1515        .with_head(exex_head);
1516
1517        // First notification is the revert of the ExEx head block to get back to the canonical
1518        // chain
1519        assert_eq!(
1520            notifications.next().await.transpose()?,
1521            Some(exex_head_notification.into_inverted())
1522        );
1523        // Second notification is the backfilled block from the canonical chain to get back to the
1524        // canonical tip
1525        assert_eq!(notifications.next().await.transpose()?, Some(node_head_notification));
1526        // Third notification is the actual notification that we sent before
1527        assert_eq!(notifications.next().await.transpose()?, Some(new_notification));
1528
1529        Ok(())
1530    }
1531
1532    #[tokio::test]
1533    async fn test_notifications_ahead_of_head() -> eyre::Result<()> {
1534        reth_tracing::init_test_tracing();
1535        let mut rng = generators::rng();
1536
1537        let temp_dir = tempfile::tempdir().unwrap();
1538        let wal = Wal::new(temp_dir.path()).unwrap();
1539
1540        let provider_factory = create_test_provider_factory();
1541        let genesis_hash = init_genesis(&provider_factory)?;
1542        let genesis_block = provider_factory
1543            .block(genesis_hash.into())?
1544            .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
1545
1546        let provider = BlockchainProvider::new(provider_factory)?;
1547
1548        let exex_head_block = random_block(
1549            &mut rng,
1550            genesis_block.number + 1,
1551            BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
1552        );
1553        let exex_head_notification = ExExNotification::ChainCommitted {
1554            new: Arc::new(Chain::new(
1555                vec![exex_head_block.clone().try_recover()?],
1556                Default::default(),
1557                BTreeMap::new(),
1558            )),
1559        };
1560        wal.commit(&exex_head_notification)?;
1561
1562        let node_head = BlockNumHash { number: genesis_block.number, hash: genesis_hash };
1563        let exex_head = ExExHead {
1564            block: BlockNumHash { number: exex_head_block.number, hash: exex_head_block.hash() },
1565        };
1566
1567        let new_notification = ExExNotification::ChainCommitted {
1568            new: Arc::new(Chain::new(
1569                vec![random_block(
1570                    &mut rng,
1571                    genesis_block.number + 1,
1572                    BlockParams { parent: Some(genesis_hash), ..Default::default() },
1573                )
1574                .try_recover()?],
1575                Default::default(),
1576                BTreeMap::new(),
1577            )),
1578        };
1579
1580        let (notifications_tx, notifications_rx) = mpsc::channel(1);
1581
1582        notifications_tx.send(new_notification.clone()).await?;
1583
1584        let mut notifications = ExExNotificationsWithoutHead::new(
1585            node_head,
1586            provider,
1587            EthEvmConfig::mainnet(),
1588            notifications_rx,
1589            wal.handle(),
1590        )
1591        .with_head(exex_head);
1592
1593        // First notification is the revert of the ExEx head block to get back to the canonical
1594        // chain
1595        assert_eq!(
1596            notifications.next().await.transpose()?,
1597            Some(exex_head_notification.into_inverted())
1598        );
1599
1600        // Second notification is the actual notification that we sent before
1601        assert_eq!(notifications.next().await.transpose()?, Some(new_notification));
1602
1603        Ok(())
1604    }
1605
1606    /// Regression test for <https://github.com/paradigmxyz/reth/issues/19665>.
1607    ///
1608    /// During backfill, `poll_next` must drain the notification channel so that
1609    /// the upstream `ExExManager` is never blocked by a full channel. Without
1610    /// the drain loop the capacity-1 channel stays full for the entire backfill
1611    /// duration, which stalls the manager's `PollSender` and eventually blocks
1612    /// all upstream senders once the 1024-entry buffer fills up.
1613    ///
1614    /// The key assertion is the `try_send` after the first `poll_next`: it
1615    /// proves the channel was drained during the backfill poll. Without the
1616    /// fix this `try_send` fails because the notification is still sitting in
1617    /// the channel.
1618    #[tokio::test]
1619    async fn exex_notifications_backfill_drains_channel() -> eyre::Result<()> {
1620        let mut rng = generators::rng();
1621
1622        let temp_dir = tempfile::tempdir().unwrap();
1623        let wal = Wal::new(temp_dir.path()).unwrap();
1624
1625        let provider_factory = create_test_provider_factory();
1626        let genesis_hash = init_genesis(&provider_factory)?;
1627        let genesis_block = provider_factory
1628            .block(genesis_hash.into())?
1629            .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
1630
1631        let provider = BlockchainProvider::new(provider_factory.clone())?;
1632
1633        // Insert block 1 into the DB so there's something to backfill
1634        let node_head_block = random_block(
1635            &mut rng,
1636            genesis_block.number + 1,
1637            BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
1638        )
1639        .try_recover()?;
1640        let node_head = node_head_block.num_hash();
1641        let provider_rw = provider_factory.provider_rw()?;
1642        provider_rw.insert_block(&node_head_block)?;
1643        provider_rw.commit()?;
1644
1645        // ExEx head is at genesis — backfill will run for block 1
1646        let exex_head =
1647            ExExHead { block: BlockNumHash { number: genesis_block.number, hash: genesis_hash } };
1648
1649        // Notification for a block AFTER the backfill range (block 2).
1650        let post_backfill_notification = ExExNotification::ChainCommitted {
1651            new: Arc::new(Chain::new(
1652                vec![random_block(
1653                    &mut rng,
1654                    node_head.number + 1,
1655                    BlockParams { parent: Some(node_head.hash), ..Default::default() },
1656                )
1657                .try_recover()?],
1658                Default::default(),
1659                BTreeMap::new(),
1660            )),
1661        };
1662
1663        // Another notification (block 3) used to probe channel capacity.
1664        let probe_notification = ExExNotification::ChainCommitted {
1665            new: Arc::new(Chain::new(
1666                vec![random_block(
1667                    &mut rng,
1668                    node_head.number + 2,
1669                    BlockParams { parent: None, ..Default::default() },
1670                )
1671                .try_recover()?],
1672                Default::default(),
1673                BTreeMap::new(),
1674            )),
1675        };
1676
1677        let (notifications_tx, notifications_rx) = mpsc::channel(1);
1678
1679        // Fill the capacity-1 channel.
1680        notifications_tx.send(post_backfill_notification.clone()).await?;
1681
1682        // Confirm the channel is full — this is the precondition that causes the
1683        // stall in production: the ExExManager's PollSender would block here.
1684        assert!(
1685            notifications_tx.try_send(probe_notification.clone()).is_err(),
1686            "channel should be full before backfill poll"
1687        );
1688
1689        let mut notifications = ExExNotificationsWithoutHead::new(
1690            node_head,
1691            provider,
1692            EthEvmConfig::mainnet(),
1693            notifications_rx,
1694            wal.handle(),
1695        )
1696        .with_head(exex_head);
1697
1698        // Poll once — this returns the backfill result for block 1. Crucially,
1699        // the drain loop in poll_next runs in this same call, consuming the
1700        // notification from the channel and buffering it.
1701        let backfill_result = notifications.next().await.transpose()?;
1702        assert_eq!(
1703            backfill_result,
1704            Some(ExExNotification::ChainCommitted {
1705                new: Arc::new(
1706                    BackfillJobFactory::new(
1707                        notifications.evm_config.clone(),
1708                        notifications.provider.clone()
1709                    )
1710                    .backfill(1..=1)
1711                    .next()
1712                    .ok_or_eyre("failed to backfill")??
1713                )
1714            })
1715        );
1716
1717        // KEY ASSERTION: the channel was drained during the backfill poll above.
1718        // Without the drain loop this try_send fails because the original
1719        // notification is still occupying the capacity-1 channel.
1720        assert!(
1721            notifications_tx.try_send(probe_notification.clone()).is_ok(),
1722            "channel should have been drained during backfill poll"
1723        );
1724
1725        // The first buffered notification (block 2) was drained from the channel
1726        // during backfill and is delivered now.
1727        let buffered = notifications.next().await.transpose()?;
1728        assert_eq!(buffered, Some(post_backfill_notification));
1729
1730        // The probe notification (block 3) that we just sent is delivered next.
1731        let probe = notifications.next().await.transpose()?;
1732        assert_eq!(probe, Some(probe_notification));
1733
1734        Ok(())
1735    }
1736}