Skip to main content

reth_exex/
manager.rs

1use crate::{
2    wal::Wal, ExExEvent, ExExNotification, ExExNotifications, FinishedExExHeight, WalHandle,
3};
4use alloy_consensus::BlockHeader;
5use alloy_eips::BlockNumHash;
6use futures::StreamExt;
7use itertools::Itertools;
8use metrics::Gauge;
9use reth_chain_state::ForkChoiceStream;
10use reth_ethereum_primitives::EthPrimitives;
11use reth_evm::ConfigureEvm;
12use reth_metrics::{metrics::Counter, Metrics};
13use reth_node_api::NodePrimitives;
14use reth_primitives_traits::SealedHeader;
15use reth_provider::{Chain, HeaderProvider};
16use std::{
17    collections::VecDeque,
18    fmt::Debug,
19    future::{poll_fn, Future},
20    ops::Not,
21    pin::Pin,
22    sync::{
23        atomic::{AtomicUsize, Ordering},
24        Arc,
25    },
26    task::{ready, Context, Poll},
27};
28use tokio::sync::{
29    mpsc::{self, error::SendError, UnboundedReceiver, UnboundedSender},
30    watch,
31};
32use tokio_util::sync::{PollSendError, PollSender, ReusableBoxFuture};
33use tracing::{debug, warn};
34
35/// Default max size of the internal state notifications buffer.
36///
37/// 1024 notifications in the buffer is 3.5 hours of mainnet blocks,
38/// or 17 minutes of 1-second blocks.
39pub const DEFAULT_EXEX_MANAGER_CAPACITY: usize = 1024;
40
41/// Default maximum number of blocks allowed in the WAL before emitting a warning.
42///
43/// This constant defines the default threshold for the Write-Ahead Log (WAL) size. If the number
44/// of blocks in the WAL exceeds this limit, a warning is logged to indicate potential issues.
45///
46/// This value is appropriate for Ethereum mainnet with ~12 second block times. For L2 chains with
47/// faster block times, this value should be increased proportionally to avoid excessive warnings.
48pub const DEFAULT_WAL_BLOCKS_WARNING: usize = 128;
49
50/// The source of the notification.
51///
52/// This distinguishment is needed to not commit any pipeline notificatations to [WAL](`Wal`),
53/// because they are already finalized.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum ExExNotificationSource {
56    /// The notification was sent from the pipeline.
57    Pipeline,
58    /// The notification was sent from the blockchain tree.
59    BlockchainTree,
60}
61
62/// Metrics for an `ExEx`.
63#[derive(Metrics)]
64#[metrics(scope = "exex")]
65struct ExExMetrics {
66    /// The total number of notifications sent to an `ExEx`.
67    notifications_sent_total: Counter,
68    /// The total number of events an `ExEx` has sent to the manager.
69    events_sent_total: Counter,
70}
71
72/// A handle to an `ExEx` used by the [`ExExManager`] to communicate with `ExEx`'s.
73///
74/// A handle should be created for each `ExEx` with a unique ID. The channels returned by
75/// [`ExExHandle::new`] should be given to the `ExEx`, while the handle itself should be given to
76/// the manager in [`ExExManager::new`].
77#[derive(Debug)]
78pub struct ExExHandle<N: NodePrimitives = EthPrimitives> {
79    /// The execution extension's ID.
80    id: String,
81    /// Metrics for an `ExEx`.
82    metrics: ExExMetrics,
83    /// Channel to send [`ExExNotification`]s to the `ExEx`.
84    sender: PollSender<ExExNotification<N>>,
85    /// Channel to receive [`ExExEvent`]s from the `ExEx`.
86    receiver: UnboundedReceiver<ExExEvent>,
87    /// The ID of the next notification to send to this `ExEx`.
88    next_notification_id: usize,
89    /// The finished block of the `ExEx`.
90    ///
91    /// If this is `None`, the `ExEx` has not emitted a `FinishedHeight` event.
92    finished_height: Option<BlockNumHash>,
93    /// The number of sent notifications that revert blocks and that the `ExEx`'s notification
94    /// stream has not acknowledged with [`ExExEvent::RevertReceived`] yet.
95    ///
96    /// While it's not zero, [`ExExEvent::FinishedHeight`] events are stale: the `ExEx` sent them
97    /// before receiving a revert, so they may name a reverted block.
98    unacknowledged_reverts: usize,
99}
100
101impl<N: NodePrimitives> ExExHandle<N> {
102    /// Create a new handle for the given `ExEx`.
103    ///
104    /// Returns the handle, as well as a [`UnboundedSender`] for [`ExExEvent`]s and a
105    /// [`mpsc::Receiver`] for [`ExExNotification`]s that should be given to the `ExEx`.
106    pub fn new<P, E: ConfigureEvm<Primitives = N>>(
107        id: String,
108        node_head: BlockNumHash,
109        provider: P,
110        evm_config: E,
111        wal_handle: WalHandle<N>,
112    ) -> (Self, UnboundedSender<ExExEvent>, ExExNotifications<P, E>) {
113        let (notification_tx, notification_rx) = mpsc::channel(1);
114        let (event_tx, event_rx) = mpsc::unbounded_channel();
115        let notifications =
116            ExExNotifications::new(node_head, provider, evm_config, notification_rx, wal_handle)
117                .with_revert_receipts(event_tx.clone());
118
119        (
120            Self {
121                id: id.clone(),
122                metrics: ExExMetrics::new_with_labels(&[("exex", id)]),
123                sender: PollSender::new(notification_tx),
124                receiver: event_rx,
125                next_notification_id: 0,
126                finished_height: None,
127                unacknowledged_reverts: 0,
128            },
129            event_tx,
130            notifications,
131        )
132    }
133
134    /// Reserves a slot in the `PollSender` channel and sends the notification if the slot was
135    /// successfully reserved.
136    ///
137    /// When the notification is sent, it is considered delivered.
138    fn send(
139        &mut self,
140        cx: &mut Context<'_>,
141        (notification_id, notification): &(usize, ExExNotification<N>),
142    ) -> Poll<Result<(), PollSendError<ExExNotification<N>>>> {
143        // Skip the chain commit notification if the finished height of the ExEx is higher than
144        // or equal to the tip of the new notification. I.e., the ExEx has already processed the
145        // notification. Always send [ExExNotification::ChainReorged] and
146        // [ExExNotification::ChainReverted], because the ExEx should be aware of the reorgs and
147        // reverts lower than its finished height.
148        if let Some(finished_height) = self.finished_height &&
149            let ExExNotification::ChainCommitted { new } = notification &&
150            finished_height.number >= new.tip().number()
151        {
152            debug!(
153                target: "exex::manager",
154                exex_id = %self.id,
155                %notification_id,
156                ?finished_height,
157                new_tip = %new.tip().number(),
158                "Skipping notification"
159            );
160
161            self.next_notification_id = notification_id + 1;
162            return Poll::Ready(Ok(()))
163        }
164
165        // Rewind on every attempt, so the pruner doesn't treat blocks of the new branch as
166        // processed while the revert waits for a slot, and so a height the ExEx reports in the
167        // meantime is rewound too before the revert is sent.
168        let reverted = notification.reverted_chain();
169        if let Some(reverted) = &reverted &&
170            let Some(finished_height) = &mut self.finished_height
171        {
172            rewind_to_fork_block(finished_height, reverted);
173        }
174
175        debug!(
176            target: "exex::manager",
177            exex_id = %self.id,
178            %notification_id,
179            "Reserving slot for notification"
180        );
181        match self.sender.poll_reserve(cx) {
182            Poll::Ready(Ok(())) => (),
183            other => return other,
184        }
185
186        debug!(
187            target: "exex::manager",
188            exex_id = %self.id,
189            %notification_id,
190            "Sending notification"
191        );
192        match self.sender.send_item(notification.clone()) {
193            Ok(()) => {
194                self.next_notification_id = notification_id + 1;
195                self.metrics.notifications_sent_total.increment(1);
196                if reverted.is_some() {
197                    self.unacknowledged_reverts += 1;
198                }
199                Poll::Ready(Ok(()))
200            }
201            Err(err) => Poll::Ready(Err(err)),
202        }
203    }
204}
205
206/// Metrics for the `ExEx` manager.
207#[derive(Metrics)]
208#[metrics(scope = "exex.manager")]
209pub struct ExExManagerMetrics {
210    /// Max size of the internal state notifications buffer.
211    max_capacity: Gauge,
212    /// Current capacity of the internal state notifications buffer.
213    current_capacity: Gauge,
214    /// Current size of the internal state notifications buffer.
215    ///
216    /// Note that this might be slightly bigger than the maximum capacity in some cases.
217    buffer_size: Gauge,
218    /// Current number of `ExEx`'s on the node.
219    num_exexs: Gauge,
220    /// Number of notifications waiting for space in the internal buffer.
221    queued_notifications: Gauge,
222}
223
224/// The execution extension manager.
225///
226/// The manager is responsible for:
227///
228/// - Receiving relevant events from the rest of the node, and sending these to the execution
229///   extensions
230/// - Backpressure
231/// - Error handling
232/// - Monitoring
233#[derive(Debug)]
234pub struct ExExManager<P, N: NodePrimitives> {
235    /// Provider for querying headers.
236    provider: P,
237
238    /// Handles to communicate with the `ExEx`'s.
239    exex_handles: Vec<ExExHandle<N>>,
240
241    /// [`ExExNotification`] channel from the [`ExExManagerHandle`]s.
242    handle_rx: UnboundedReceiver<(ExExNotificationSource, ExExNotification<N>)>,
243
244    /// Notifications waiting for space in the internal buffer, in arrival order.
245    queued_notifications: VecDeque<QueuedNotification<N>>,
246
247    /// The minimum notification ID currently present in the buffer.
248    min_id: usize,
249    /// Monotonically increasing ID for [`ExExNotification`]s.
250    next_id: usize,
251    /// Internal buffer of [`ExExNotification`]s.
252    ///
253    /// The first element of the tuple is a monotonically increasing ID unique to the notification
254    /// (the second element of the tuple).
255    buffer: VecDeque<(usize, ExExNotification<N>)>,
256    /// Max size of the internal state notifications buffer.
257    max_capacity: usize,
258    /// Current state notifications buffer capacity.
259    ///
260    /// Used to inform the execution stage of possible batch sizes.
261    current_capacity: Arc<AtomicUsize>,
262
263    /// Whether the manager is ready to receive new notifications.
264    is_ready: watch::Sender<bool>,
265
266    /// The finished height of all `ExEx`'s.
267    finished_height: watch::Sender<FinishedExExHeight>,
268
269    /// Write-Ahead Log for the [`ExExNotification`]s.
270    wal: Wal<N>,
271    /// A stream of finalized headers.
272    finalized_header_stream: ForkChoiceStream<SealedHeader<N::BlockHeader>>,
273    /// The threshold for the number of blocks in the WAL before emitting a warning.
274    wal_blocks_warning: usize,
275
276    /// A handle to the `ExEx` manager.
277    handle: ExExManagerHandle<N>,
278    /// Metrics for the `ExEx` manager.
279    metrics: ExExManagerMetrics,
280}
281
282impl<P, N> ExExManager<P, N>
283where
284    N: NodePrimitives,
285{
286    /// Create a new [`ExExManager`].
287    ///
288    /// You must provide an [`ExExHandle`] for each `ExEx` and the maximum capacity of the
289    /// notification buffer in the manager.
290    ///
291    /// When the capacity is exceeded (which can happen if an `ExEx` is slow) no one can send
292    /// notifications over [`ExExManagerHandle`]s until there is capacity again.
293    pub fn new(
294        provider: P,
295        handles: Vec<ExExHandle<N>>,
296        max_capacity: usize,
297        wal: Wal<N>,
298        finalized_header_stream: ForkChoiceStream<SealedHeader<N::BlockHeader>>,
299    ) -> Self {
300        let num_exexs = handles.len();
301
302        let (handle_tx, handle_rx) = mpsc::unbounded_channel();
303        let (is_ready_tx, is_ready_rx) = watch::channel(true);
304        let (finished_height_tx, finished_height_rx) = watch::channel(if num_exexs == 0 {
305            FinishedExExHeight::NoExExs
306        } else {
307            FinishedExExHeight::NotReady
308        });
309
310        let current_capacity = Arc::new(AtomicUsize::new(max_capacity));
311
312        let metrics = ExExManagerMetrics::default();
313        metrics.max_capacity.set(max_capacity as f64);
314        metrics.num_exexs.set(num_exexs as f64);
315
316        Self {
317            provider,
318
319            exex_handles: handles,
320
321            handle_rx,
322
323            queued_notifications: VecDeque::new(),
324
325            min_id: 0,
326            next_id: 0,
327            buffer: VecDeque::with_capacity(max_capacity),
328            max_capacity,
329            current_capacity: Arc::clone(&current_capacity),
330
331            is_ready: is_ready_tx,
332            finished_height: finished_height_tx,
333
334            wal,
335            finalized_header_stream,
336            wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,
337
338            handle: ExExManagerHandle {
339                exex_tx: handle_tx,
340                num_exexs,
341                is_ready_receiver: is_ready_rx.clone(),
342                is_ready: ReusableBoxFuture::new(make_wait_future(is_ready_rx)),
343                current_capacity,
344                finished_height: finished_height_rx,
345            },
346            metrics,
347        }
348    }
349
350    /// Returns the handle to the manager.
351    pub fn handle(&self) -> ExExManagerHandle<N> {
352        self.handle.clone()
353    }
354
355    /// Sets the threshold for the number of blocks in the WAL before emitting a warning.
356    ///
357    /// For L2 chains with faster block times, this value should be increased proportionally
358    /// to avoid excessive warnings. For example, a chain with 2-second block times might use
359    /// a value 6x higher than the default.
360    pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {
361        self.wal_blocks_warning = threshold;
362        self
363    }
364
365    /// Updates the current buffer capacity and notifies all `is_ready` watchers of the manager's
366    /// readiness to receive notifications.
367    fn update_capacity(&self) {
368        let capacity = self
369            .max_capacity
370            .saturating_sub(self.buffer.len().saturating_add(self.queued_notifications.len()));
371        self.current_capacity.store(capacity, Ordering::Relaxed);
372        self.metrics.current_capacity.set(capacity as f64);
373        self.metrics.buffer_size.set(self.buffer.len() as f64);
374
375        // we can safely ignore if the channel is closed, since the manager always holds it open
376        // internally
377        let _ = self.is_ready.send(capacity > 0);
378    }
379
380    /// Pushes a new notification into the managers internal buffer, assigning the notification a
381    /// unique ID.
382    fn push_notification(&mut self, notification: ExExNotification<N>) {
383        let next_id = self.next_id;
384        self.buffer.push_back((next_id, notification));
385        self.next_id += 1;
386    }
387
388    /// Returns `true` if a new notification can enter the buffer without overtaking queued ones.
389    fn can_push_notification(&self) -> bool {
390        self.queued_notifications.is_empty() && self.buffer.len() < self.max_capacity
391    }
392}
393
394impl<P, N> ExExManager<P, N>
395where
396    P: HeaderProvider,
397    N: NodePrimitives,
398{
399    /// Finalizes the WAL according to the passed finalized header.
400    ///
401    /// This function checks if all ExExes are on the canonical chain and finalizes the WAL if
402    /// necessary.
403    fn finalize_wal(&self, finalized_header: SealedHeader<N::BlockHeader>) -> eyre::Result<()> {
404        debug!(target: "exex::manager", header = ?finalized_header.num_hash(), "Received finalized header");
405
406        // Check if all ExExes are on the canonical chain
407        let exex_finished_heights = self
408            .exex_handles
409            .iter()
410            // Get ID and finished height for each ExEx
411            .map(|exex_handle| (&exex_handle.id, exex_handle.finished_height))
412            // Deduplicate all hashes
413            .unique_by(|(_, num_hash)| num_hash.map(|num_hash| num_hash.hash))
414            // Check if hashes are canonical
415            .map(|(exex_id, num_hash)| {
416                num_hash.map_or(Ok((exex_id, num_hash, false)), |num_hash| {
417                    self.provider
418                        .is_known(num_hash.hash)
419                        // Save the ExEx ID, finished height, and whether the hash is canonical
420                        .map(|is_canonical| (exex_id, Some(num_hash), is_canonical))
421                })
422            })
423            // We collect here to be able to log the unfinalized ExExes below
424            .collect::<Result<Vec<_>, _>>()?;
425        if exex_finished_heights.iter().all(|(_, _, is_canonical)| *is_canonical) {
426            // If there is a finalized header and all ExExs are on the canonical chain, finalize
427            // the WAL with either the lowest finished height among all ExExes, or finalized header
428            // – whichever is lower.
429            let lowest_finished_height = exex_finished_heights
430                .iter()
431                .copied()
432                .filter_map(|(_, num_hash, _)| num_hash)
433                .chain([(finalized_header.num_hash())])
434                .min_by_key(|num_hash| num_hash.number)
435                .unwrap();
436
437            // Queued canonical notifications are read back from the WAL, so their files are kept
438            // even below an ExEx's finished height. File IDs grow in commit order, so the first
439            // queued one is the lowest.
440            let retain_from = self.queued_notifications.iter().find_map(|queued| match queued {
441                QueuedNotification::Wal(file_id) => Some(*file_id),
442                QueuedNotification::Handle(_) => None,
443            });
444            self.wal.finalize_retaining(lowest_finished_height, retain_from)?;
445            if self.wal.num_blocks() > self.wal_blocks_warning {
446                warn!(
447                    target: "exex::manager",
448                    blocks = ?self.wal.num_blocks(),
449                    threshold = self.wal_blocks_warning,
450                    queued_notifications = self.queued_notifications.len(),
451                    "WAL contains too many blocks and is not getting cleared. That will lead to increased disk space usage. Check that you emit the FinishedHeight event from your ExExes."
452                );
453            }
454        } else {
455            let unfinalized_exexes = exex_finished_heights
456                .into_iter()
457                .filter_map(|(exex_id, num_hash, is_canonical)| {
458                    is_canonical.not().then_some((exex_id, num_hash))
459                })
460                .format_with(", ", |(exex_id, num_hash), f| {
461                    f(&format_args!("{exex_id} = {num_hash:?}"))
462                })
463                // We need this because `debug!` uses the argument twice when formatting the final
464                // log message, but the result of `format_with` can only be used once
465                .to_string();
466            debug!(
467                target: "exex::manager",
468                %unfinalized_exexes,
469                "Not all ExExes are on the canonical chain, can't finalize the WAL"
470            );
471        }
472
473        Ok(())
474    }
475}
476
477impl<P, N> Future for ExExManager<P, N>
478where
479    P: HeaderProvider + Unpin + 'static,
480    N: NodePrimitives,
481{
482    type Output = eyre::Result<()>;
483
484    /// Main loop of the [`ExExManager`]. The order of operations is as follows:
485    /// 1. Handle incoming ExEx events. We do it before finalizing the WAL, because it depends on
486    ///    the latest state of [`ExExEvent::FinishedHeight`] events.
487    /// 2. Receive [`ExExManagerHandle`] notifications and push them to the internal buffer, or
488    ///    queue them if it's full. Blockchain tree notifications are always committed to the WAL,
489    ///    and queued only by file ID.
490    /// 3. Finalize the WAL with the finalized header, if necessary.
491    /// 4. Move queued notifications to the internal buffer in arrival order.
492    /// 5. Send notifications from the internal buffer to those ExExes that are ready to receive new
493    ///    notifications.
494    /// 6. Remove notifications from the internal buffer that have been sent to **all** ExExes and
495    ///    update the internal buffer capacity.
496    /// 7. Update the channel with the lowest [`FinishedExExHeight`] among all ExExes.
497    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
498        let this = self.get_mut();
499
500        // Handle incoming ExEx events
501        for exex in &mut this.exex_handles {
502            while let Poll::Ready(Some(event)) = exex.receiver.poll_recv(cx) {
503                debug!(target: "exex::manager", exex_id = %exex.id, ?event, "Received event from ExEx");
504                // Revert receipts come from the notification stream, not from the ExEx.
505                if !matches!(event, ExExEvent::RevertReceived(_)) {
506                    exex.metrics.events_sent_total.increment(1);
507                }
508                match event {
509                    ExExEvent::FinishedHeight(height) if exex.unacknowledged_reverts == 0 => {
510                        exex.finished_height = Some(height)
511                    }
512                    ExExEvent::FinishedHeight(height) => {
513                        debug!(
514                            target: "exex::manager",
515                            exex_id = %exex.id,
516                            ?height,
517                            unacknowledged_reverts = exex.unacknowledged_reverts,
518                            "Ignoring finished height sent before the ExEx received a revert"
519                        );
520                    }
521                    ExExEvent::RevertReceived(_) => {
522                        // Only the stream of this ExEx sends receipts, once per revert it
523                        // receives from the manager.
524                        debug_assert!(exex.unacknowledged_reverts > 0, "unexpected revert receipt");
525                        exex.unacknowledged_reverts = exex.unacknowledged_reverts.saturating_sub(1);
526                    }
527                }
528            }
529        }
530
531        // Drain handle notifications, even when the buffer is full.
532        while let Poll::Ready(Some((source, notification))) = this.handle_rx.poll_recv(cx) {
533            let committed_tip = notification.committed_chain().map(|chain| chain.tip().number());
534            let reverted_tip = notification.reverted_chain().map(|chain| chain.tip().number());
535            debug!(target: "exex::manager", ?committed_tip, ?reverted_tip, "Received new notification");
536
537            // Commit to WAL only notifications from blockchain tree. Pipeline notifications
538            // always contain only finalized blocks.
539            let file_id = match source {
540                ExExNotificationSource::BlockchainTree => {
541                    debug!(target: "exex::manager", ?committed_tip, ?reverted_tip, "Committing notification to WAL");
542                    Some(this.wal.commit(&notification)?)
543                }
544                ExExNotificationSource::Pipeline => {
545                    debug!(target: "exex::manager", ?committed_tip, ?reverted_tip, "Notification was sent from pipeline, skipping WAL commit");
546                    None
547                }
548            };
549
550            if this.can_push_notification() {
551                this.push_notification(notification);
552            } else if let Some(file_id) = file_id {
553                // Keep only the file ID, so a slow ExEx grows the WAL instead of memory.
554                this.queued_notifications.push_back(QueuedNotification::Wal(file_id));
555            } else {
556                this.queued_notifications.push_back(QueuedNotification::Handle(notification));
557            }
558        }
559
560        // Drain the finalized header stream and finalize the WAL with the last header
561        let mut last_finalized_header = None;
562        while let Poll::Ready(finalized_header) = this.finalized_header_stream.poll_next_unpin(cx) {
563            last_finalized_header = finalized_header;
564        }
565        if let Some(header) = last_finalized_header {
566            this.finalize_wal(header)?;
567        }
568
569        // Move queued notifications to the buffer
570        while this.buffer.len() < this.max_capacity &&
571            let Some(queued) = this.queued_notifications.pop_front()
572        {
573            let notification = match queued {
574                QueuedNotification::Wal(file_id) => this.wal.read_notification(file_id)?,
575                QueuedNotification::Handle(notification) => notification,
576            };
577            this.push_notification(notification);
578        }
579        this.metrics.queued_notifications.set(this.queued_notifications.len() as f64);
580        let buffer_full = this.buffer.len() >= this.max_capacity;
581
582        // Advance all poll senders
583        let mut min_id = usize::MAX;
584        for idx in (0..this.exex_handles.len()).rev() {
585            let mut exex = this.exex_handles.swap_remove(idx);
586
587            // It is a logic error for this to ever underflow since the manager manages the
588            // notification IDs
589            let notification_index = exex
590                .next_notification_id
591                .checked_sub(this.min_id)
592                .expect("exex expected notification ID outside the manager's range");
593            if let Some(notification) = this.buffer.get(notification_index) &&
594                let Poll::Ready(Err(err)) = exex.send(cx, notification)
595            {
596                // The channel was closed, which is irrecoverable for the manager
597                return Poll::Ready(Err(err.into()))
598            }
599            min_id = min_id.min(exex.next_notification_id);
600            this.exex_handles.push(exex);
601        }
602
603        // Remove processed buffered notifications
604        debug!(target: "exex::manager", %min_id, "Updating lowest notification id in buffer");
605        this.buffer.retain(|&(id, _)| id >= min_id);
606        this.min_id = min_id;
607
608        // Update capacity
609        this.update_capacity();
610
611        // If the buffer was full and we made space, we need to wake up to accept new notifications
612        if buffer_full && this.buffer.len() < this.max_capacity {
613            debug!(target: "exex::manager", "Buffer has space again, waking up senders");
614            cx.waker().wake_by_ref();
615        }
616
617        // Update watch channel block number
618        let finished_height = this.exex_handles.iter_mut().try_fold(u64::MAX, |curr, exex| {
619            exex.finished_height.map_or(Err(()), |height| Ok(height.number.min(curr)))
620        });
621        if let Ok(finished_height) = finished_height {
622            let _ = this.finished_height.send(FinishedExExHeight::Height(finished_height));
623        }
624
625        Poll::Pending
626    }
627}
628
629/// A handle to communicate with the [`ExExManager`].
630#[derive(Debug)]
631pub struct ExExManagerHandle<N: NodePrimitives = EthPrimitives> {
632    /// Channel to send notifications to the `ExEx` manager.
633    exex_tx: UnboundedSender<(ExExNotificationSource, ExExNotification<N>)>,
634    /// The number of `ExEx`'s running on the node.
635    num_exexs: usize,
636    /// A watch channel denoting whether the manager is ready for new notifications or not.
637    ///
638    /// This is stored internally alongside a `ReusableBoxFuture` representation of the same value.
639    /// This field is only used to create a new `ReusableBoxFuture` when the handle is cloned,
640    /// but is otherwise unused.
641    is_ready_receiver: watch::Receiver<bool>,
642    /// A reusable future that resolves when the manager is ready for new
643    /// notifications.
644    is_ready: ReusableBoxFuture<'static, watch::Receiver<bool>>,
645    /// The current capacity of the manager's internal notification buffer.
646    current_capacity: Arc<AtomicUsize>,
647    /// The finished height of all `ExEx`'s.
648    finished_height: watch::Receiver<FinishedExExHeight>,
649}
650
651impl<N: NodePrimitives> ExExManagerHandle<N> {
652    /// Creates an empty manager handle.
653    ///
654    /// Use this if there is no manager present.
655    ///
656    /// The handle will always be ready, and have a capacity of 0.
657    pub fn empty() -> Self {
658        let (exex_tx, _) = mpsc::unbounded_channel();
659        let (_, is_ready_rx) = watch::channel(true);
660        let (_, finished_height_rx) = watch::channel(FinishedExExHeight::NoExExs);
661
662        Self {
663            exex_tx,
664            num_exexs: 0,
665            is_ready_receiver: is_ready_rx.clone(),
666            is_ready: ReusableBoxFuture::new(make_wait_future(is_ready_rx)),
667            current_capacity: Arc::new(AtomicUsize::new(0)),
668            finished_height: finished_height_rx,
669        }
670    }
671
672    /// Synchronously send a notification over the channel to all execution extensions.
673    ///
674    /// Senders should call [`Self::has_capacity`] first.
675    pub fn send(
676        &self,
677        source: ExExNotificationSource,
678        notification: ExExNotification<N>,
679    ) -> Result<(), SendError<(ExExNotificationSource, ExExNotification<N>)>> {
680        self.exex_tx.send((source, notification))
681    }
682
683    /// Asynchronously send a notification over the channel to all execution extensions.
684    ///
685    /// The returned future resolves when the notification has been delivered. If there is no
686    /// capacity in the channel, the future will wait.
687    pub async fn send_async(
688        &mut self,
689        source: ExExNotificationSource,
690        notification: ExExNotification<N>,
691    ) -> Result<(), SendError<(ExExNotificationSource, ExExNotification<N>)>> {
692        self.ready().await;
693        self.exex_tx.send((source, notification))
694    }
695
696    /// Get the current capacity of the `ExEx` manager's internal notification buffer.
697    pub fn capacity(&self) -> usize {
698        self.current_capacity.load(Ordering::Relaxed)
699    }
700
701    /// Whether there is capacity in the `ExEx` manager's internal notification buffer.
702    ///
703    /// If this returns `false`, the owner of the handle should **NOT** send new notifications over
704    /// the channel until the manager is ready again, as this can lead to unbounded memory growth.
705    pub fn has_capacity(&self) -> bool {
706        self.capacity() > 0
707    }
708
709    /// Returns `true` if there are `ExEx`'s installed in the node.
710    pub const fn has_exexs(&self) -> bool {
711        self.num_exexs > 0
712    }
713
714    /// The finished height of all `ExEx`'s.
715    pub fn finished_height(&self) -> watch::Receiver<FinishedExExHeight> {
716        self.finished_height.clone()
717    }
718
719    /// Wait until the manager is ready for new notifications.
720    pub async fn ready(&mut self) {
721        poll_fn(|cx| self.poll_ready(cx)).await
722    }
723
724    /// Wait until the manager is ready for new notifications.
725    pub fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<()> {
726        let rx = ready!(self.is_ready.poll(cx));
727        self.is_ready.set(make_wait_future(rx));
728        Poll::Ready(())
729    }
730}
731
732/// Moves `block` to the fork block of `reverted` if `reverted` contains it.
733///
734/// A reverted block no longer proves that the ExEx processed the blocks at its height, so it is
735/// replaced by the fork block, which is on both branches. Otherwise, commits of the new branch at
736/// or below the old block would be skipped. The notification stream tracks the ExEx head with a
737/// broader rule, because it also has to decide which reverts the ExEx needs.
738fn rewind_to_fork_block<N: NodePrimitives>(block: &mut BlockNumHash, reverted: &Chain<N>) {
739    if reverted.block_number(block.hash) == Some(block.number) {
740        *block = reverted.fork_block();
741    }
742}
743
744/// Creates a future that resolves once the given watch channel receiver is true.
745async fn make_wait_future(mut rx: watch::Receiver<bool>) -> watch::Receiver<bool> {
746    // NOTE(onbjerg): We can ignore the error here, because if the channel is closed, the node
747    // is shutting down.
748    let _ = rx.wait_for(|ready| *ready).await;
749    rx
750}
751
752impl<N: NodePrimitives> Clone for ExExManagerHandle<N> {
753    fn clone(&self) -> Self {
754        Self {
755            exex_tx: self.exex_tx.clone(),
756            num_exexs: self.num_exexs,
757            is_ready_receiver: self.is_ready_receiver.clone(),
758            is_ready: ReusableBoxFuture::new(make_wait_future(self.is_ready_receiver.clone())),
759            current_capacity: self.current_capacity.clone(),
760            finished_height: self.finished_height.clone(),
761        }
762    }
763}
764
765/// A notification waiting for space in the [`ExExManager`]'s internal buffer.
766#[derive(Debug)]
767enum QueuedNotification<N: NodePrimitives> {
768    /// A blockchain tree notification stored in the WAL file with this ID.
769    Wal(u32),
770    /// A notification received from an [`ExExManagerHandle`].
771    Handle(ExExNotification<N>),
772}
773
774#[cfg(test)]
775mod tests {
776    use super::*;
777    use crate::wal::{WalError, WalResult};
778    use alloy_primitives::B256;
779    use futures::{FutureExt, StreamExt, TryStreamExt};
780    use rand::Rng;
781    use reth_chain_state::CanonStateNotification;
782    use reth_db_common::init::init_genesis;
783    use reth_evm_ethereum::EthEvmConfig;
784    use reth_primitives_traits::RecoveredBlock;
785    use reth_provider::{
786        providers::BlockchainProvider,
787        test_utils::{create_test_provider_factory, MockEthProvider},
788        BlockReader, BlockWriter, Chain, DBProvider, DatabaseProviderFactory, TransactionVariant,
789    };
790    use reth_testing_utils::generators::{
791        self, random_block, random_block_range, BlockParams, BlockRangeParams,
792    };
793    use std::time::Duration;
794
795    fn empty_finalized_header_stream() -> ForkChoiceStream<SealedHeader> {
796        let (tx, rx) = watch::channel(None);
797        // Do not drop the sender, otherwise the receiver will always return an error
798        std::mem::forget(tx);
799        ForkChoiceStream::new(rx)
800    }
801
802    #[tokio::test]
803    async fn test_delivers_events() {
804        let temp_dir = tempfile::tempdir().unwrap();
805        let wal = Wal::new(temp_dir.path()).unwrap();
806
807        let (mut exex_handle, event_tx, mut _notification_rx) = ExExHandle::new(
808            "test_exex".to_string(),
809            Default::default(),
810            (),
811            EthEvmConfig::mainnet(),
812            wal.handle(),
813        );
814
815        // Send an event and check that it's delivered correctly
816        let event = ExExEvent::FinishedHeight(BlockNumHash::new(42, B256::random()));
817        event_tx.send(event).unwrap();
818        let received_event = exex_handle.receiver.recv().await.unwrap();
819        assert_eq!(received_event, event);
820    }
821
822    #[tokio::test]
823    async fn test_has_exexs() {
824        let temp_dir = tempfile::tempdir().unwrap();
825        let wal = Wal::new(temp_dir.path()).unwrap();
826
827        let (exex_handle_1, _, _) = ExExHandle::new(
828            "test_exex_1".to_string(),
829            Default::default(),
830            (),
831            EthEvmConfig::mainnet(),
832            wal.handle(),
833        );
834
835        assert!(!ExExManager::new((), vec![], 0, wal.clone(), empty_finalized_header_stream())
836            .handle
837            .has_exexs());
838
839        assert!(ExExManager::new((), vec![exex_handle_1], 0, wal, empty_finalized_header_stream())
840            .handle
841            .has_exexs());
842    }
843
844    #[tokio::test]
845    async fn test_has_capacity() {
846        let temp_dir = tempfile::tempdir().unwrap();
847        let wal = Wal::new(temp_dir.path()).unwrap();
848
849        let (exex_handle_1, _, _) = ExExHandle::new(
850            "test_exex_1".to_string(),
851            Default::default(),
852            (),
853            EthEvmConfig::mainnet(),
854            wal.handle(),
855        );
856
857        assert!(!ExExManager::new((), vec![], 0, wal.clone(), empty_finalized_header_stream())
858            .handle
859            .has_capacity());
860
861        assert!(ExExManager::new(
862            (),
863            vec![exex_handle_1],
864            10,
865            wal,
866            empty_finalized_header_stream()
867        )
868        .handle
869        .has_capacity());
870    }
871
872    #[test]
873    fn test_push_notification() {
874        let temp_dir = tempfile::tempdir().unwrap();
875        let wal = Wal::new(temp_dir.path()).unwrap();
876
877        let (exex_handle, _, _) = ExExHandle::new(
878            "test_exex".to_string(),
879            Default::default(),
880            (),
881            EthEvmConfig::mainnet(),
882            wal.handle(),
883        );
884
885        // Create a mock ExExManager and add the exex_handle to it
886        let mut exex_manager =
887            ExExManager::new((), vec![exex_handle], 10, wal, empty_finalized_header_stream());
888
889        // Define the notification for testing
890        let mut block1: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
891        block1.set_hash(B256::repeat_byte(0x01));
892        block1.set_block_number(10);
893
894        let notification1 = ExExNotification::ChainCommitted {
895            new: Arc::new(Chain::new(vec![block1.clone()], Default::default(), Default::default())),
896        };
897
898        // Push the first notification
899        exex_manager.push_notification(notification1.clone());
900
901        // Verify the buffer contains the notification with the correct ID
902        assert_eq!(exex_manager.buffer.len(), 1);
903        assert_eq!(exex_manager.buffer.front().unwrap().0, 0);
904        assert_eq!(exex_manager.buffer.front().unwrap().1, notification1);
905        assert_eq!(exex_manager.next_id, 1);
906
907        // Push another notification
908        let mut block2: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
909        block2.set_hash(B256::repeat_byte(0x02));
910        block2.set_block_number(20);
911
912        let notification2 = ExExNotification::ChainCommitted {
913            new: Arc::new(Chain::new(vec![block2.clone()], Default::default(), Default::default())),
914        };
915
916        exex_manager.push_notification(notification2.clone());
917
918        // Verify the buffer contains both notifications with correct IDs
919        assert_eq!(exex_manager.buffer.len(), 2);
920        assert_eq!(exex_manager.buffer.front().unwrap().0, 0);
921        assert_eq!(exex_manager.buffer.front().unwrap().1, notification1);
922        assert_eq!(exex_manager.buffer.get(1).unwrap().0, 1);
923        assert_eq!(exex_manager.buffer.get(1).unwrap().1, notification2);
924        assert_eq!(exex_manager.next_id, 2);
925    }
926
927    #[test]
928    fn test_update_capacity() {
929        let temp_dir = tempfile::tempdir().unwrap();
930        let wal = Wal::new(temp_dir.path()).unwrap();
931
932        let (exex_handle, _, _) = ExExHandle::new(
933            "test_exex".to_string(),
934            Default::default(),
935            (),
936            EthEvmConfig::mainnet(),
937            wal.handle(),
938        );
939
940        // Create a mock ExExManager and add the exex_handle to it
941        let max_capacity = 5;
942        let mut exex_manager = ExExManager::new(
943            (),
944            vec![exex_handle],
945            max_capacity,
946            wal,
947            empty_finalized_header_stream(),
948        );
949
950        // Push some notifications to fill part of the buffer
951        let mut block1: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
952        block1.set_hash(B256::repeat_byte(0x01));
953        block1.set_block_number(10);
954
955        let notification1 = ExExNotification::ChainCommitted {
956            new: Arc::new(Chain::new(vec![block1.clone()], Default::default(), Default::default())),
957        };
958
959        exex_manager.push_notification(notification1.clone());
960        exex_manager.push_notification(notification1);
961
962        // Update capacity
963        exex_manager.update_capacity();
964
965        // Verify current capacity and metrics
966        assert_eq!(exex_manager.current_capacity.load(Ordering::Relaxed), max_capacity - 2);
967
968        // Clear the buffer and update capacity
969        exex_manager.buffer.clear();
970        exex_manager.update_capacity();
971
972        // Verify current capacity
973        assert_eq!(exex_manager.current_capacity.load(Ordering::Relaxed), max_capacity);
974    }
975
976    #[tokio::test]
977    async fn test_updates_block_height() {
978        let temp_dir = tempfile::tempdir().unwrap();
979        let wal = Wal::new(temp_dir.path()).unwrap();
980
981        let provider_factory = create_test_provider_factory();
982
983        let (exex_handle, event_tx, mut _notification_rx) = ExExHandle::new(
984            "test_exex".to_string(),
985            Default::default(),
986            (),
987            EthEvmConfig::mainnet(),
988            wal.handle(),
989        );
990
991        // Check initial block height
992        assert!(exex_handle.finished_height.is_none());
993
994        // Update the block height via an event
995        let block = BlockNumHash::new(42, B256::random());
996        event_tx.send(ExExEvent::FinishedHeight(block)).unwrap();
997
998        // Create a mock ExExManager and add the exex_handle to it
999        let exex_manager = ExExManager::new(
1000            provider_factory,
1001            vec![exex_handle],
1002            10,
1003            Wal::new(temp_dir.path()).unwrap(),
1004            empty_finalized_header_stream(),
1005        );
1006
1007        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1008
1009        // Pin the ExExManager to call the poll method
1010        let mut pinned_manager = std::pin::pin!(exex_manager);
1011        let _ = pinned_manager.as_mut().poll(&mut cx);
1012
1013        // Check that the block height was updated
1014        let updated_exex_handle = &pinned_manager.exex_handles[0];
1015        assert_eq!(updated_exex_handle.finished_height, Some(block));
1016
1017        // Get the receiver for the finished height
1018        let mut receiver = pinned_manager.handle.finished_height();
1019
1020        // Wait for a new value to be sent
1021        receiver.changed().await.unwrap();
1022
1023        // Get the latest value
1024        let finished_height = *receiver.borrow();
1025
1026        // The finished height should be updated to the lower block height
1027        assert_eq!(finished_height, FinishedExExHeight::Height(42));
1028    }
1029
1030    #[tokio::test]
1031    async fn test_updates_block_height_lower() {
1032        let temp_dir = tempfile::tempdir().unwrap();
1033        let wal = Wal::new(temp_dir.path()).unwrap();
1034
1035        let provider_factory = create_test_provider_factory();
1036
1037        // Create two `ExExHandle` instances
1038        let (exex_handle1, event_tx1, _) = ExExHandle::new(
1039            "test_exex1".to_string(),
1040            Default::default(),
1041            (),
1042            EthEvmConfig::mainnet(),
1043            wal.handle(),
1044        );
1045        let (exex_handle2, event_tx2, _) = ExExHandle::new(
1046            "test_exex2".to_string(),
1047            Default::default(),
1048            (),
1049            EthEvmConfig::mainnet(),
1050            wal.handle(),
1051        );
1052
1053        let block1 = BlockNumHash::new(42, B256::random());
1054        let block2 = BlockNumHash::new(10, B256::random());
1055
1056        // Send events to update the block heights of the two handles, with the second being lower
1057        event_tx1.send(ExExEvent::FinishedHeight(block1)).unwrap();
1058        event_tx2.send(ExExEvent::FinishedHeight(block2)).unwrap();
1059
1060        let exex_manager = ExExManager::new(
1061            provider_factory,
1062            vec![exex_handle1, exex_handle2],
1063            10,
1064            Wal::new(temp_dir.path()).unwrap(),
1065            empty_finalized_header_stream(),
1066        );
1067
1068        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1069
1070        let mut pinned_manager = std::pin::pin!(exex_manager);
1071
1072        let _ = pinned_manager.as_mut().poll(&mut cx);
1073
1074        // Get the receiver for the finished height
1075        let mut receiver = pinned_manager.handle.finished_height();
1076
1077        // Wait for a new value to be sent
1078        receiver.changed().await.unwrap();
1079
1080        // Get the latest value
1081        let finished_height = *receiver.borrow();
1082
1083        // The finished height should be updated to the lower block height
1084        assert_eq!(finished_height, FinishedExExHeight::Height(10));
1085    }
1086
1087    #[tokio::test]
1088    async fn test_updates_block_height_greater() {
1089        let temp_dir = tempfile::tempdir().unwrap();
1090        let wal = Wal::new(temp_dir.path()).unwrap();
1091
1092        let provider_factory = create_test_provider_factory();
1093
1094        // Create two `ExExHandle` instances
1095        let (exex_handle1, event_tx1, _) = ExExHandle::new(
1096            "test_exex1".to_string(),
1097            Default::default(),
1098            (),
1099            EthEvmConfig::mainnet(),
1100            wal.handle(),
1101        );
1102        let (exex_handle2, event_tx2, _) = ExExHandle::new(
1103            "test_exex2".to_string(),
1104            Default::default(),
1105            (),
1106            EthEvmConfig::mainnet(),
1107            wal.handle(),
1108        );
1109
1110        // Assert that the initial block height is `None` for the first `ExExHandle`.
1111        assert!(exex_handle1.finished_height.is_none());
1112
1113        let block1 = BlockNumHash::new(42, B256::random());
1114        let block2 = BlockNumHash::new(100, B256::random());
1115
1116        // Send events to update the block heights of the two handles, with the second being higher.
1117        event_tx1.send(ExExEvent::FinishedHeight(block1)).unwrap();
1118        event_tx2.send(ExExEvent::FinishedHeight(block2)).unwrap();
1119
1120        let exex_manager = ExExManager::new(
1121            provider_factory,
1122            vec![exex_handle1, exex_handle2],
1123            10,
1124            Wal::new(temp_dir.path()).unwrap(),
1125            empty_finalized_header_stream(),
1126        );
1127
1128        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1129
1130        let mut pinned_manager = std::pin::pin!(exex_manager);
1131
1132        let _ = pinned_manager.as_mut().poll(&mut cx);
1133
1134        // Get the receiver for the finished height
1135        let mut receiver = pinned_manager.handle.finished_height();
1136
1137        // Wait for a new value to be sent
1138        receiver.changed().await.unwrap();
1139
1140        // Get the latest value
1141        let finished_height = *receiver.borrow();
1142
1143        // The finished height should be updated to the lower block height
1144        assert_eq!(finished_height, FinishedExExHeight::Height(42));
1145
1146        // // The lower block height should be retained
1147        // let updated_exex_handle = &pinned_manager.exex_handles[0];
1148        // assert_eq!(updated_exex_handle.finished_height, Some(42));
1149    }
1150
1151    #[tokio::test]
1152    async fn test_exex_manager_capacity() {
1153        let temp_dir = tempfile::tempdir().unwrap();
1154        let wal = Wal::new(temp_dir.path()).unwrap();
1155
1156        let provider_factory = create_test_provider_factory();
1157
1158        let (exex_handle_1, _, _) = ExExHandle::new(
1159            "test_exex_1".to_string(),
1160            Default::default(),
1161            (),
1162            EthEvmConfig::mainnet(),
1163            wal.handle(),
1164        );
1165
1166        // Create an ExExManager with a small max capacity
1167        let max_capacity = 2;
1168        let exex_manager = ExExManager::new(
1169            provider_factory,
1170            vec![exex_handle_1],
1171            max_capacity,
1172            Wal::new(temp_dir.path()).unwrap(),
1173            empty_finalized_header_stream(),
1174        );
1175
1176        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1177
1178        // Setup a notification
1179        let notification = ExExNotification::ChainCommitted {
1180            new: Arc::new(Chain::new(
1181                vec![RecoveredBlock::default()],
1182                Default::default(),
1183                Default::default(),
1184            )),
1185        };
1186
1187        // Send notifications to go over the max capacity
1188        exex_manager
1189            .handle
1190            .exex_tx
1191            .send((ExExNotificationSource::BlockchainTree, notification.clone()))
1192            .unwrap();
1193        exex_manager
1194            .handle
1195            .exex_tx
1196            .send((ExExNotificationSource::BlockchainTree, notification.clone()))
1197            .unwrap();
1198        exex_manager
1199            .handle
1200            .exex_tx
1201            .send((ExExNotificationSource::BlockchainTree, notification))
1202            .unwrap();
1203
1204        // Pin the ExExManager to call the poll method
1205        let mut pinned_manager = std::pin::pin!(exex_manager);
1206
1207        // Before polling, the next notification ID should be 0 and the buffer should be empty
1208        assert_eq!(pinned_manager.next_id, 0);
1209        assert_eq!(pinned_manager.buffer.len(), 0);
1210
1211        let _ = pinned_manager.as_mut().poll(&mut cx);
1212
1213        // After polling, the next notification ID and buffer size should be updated
1214        assert_eq!(pinned_manager.next_id, 2);
1215        assert_eq!(pinned_manager.buffer.len(), 2);
1216    }
1217
1218    #[tokio::test]
1219    async fn exex_handle_new() {
1220        let provider_factory = create_test_provider_factory();
1221        init_genesis(&provider_factory).unwrap();
1222        let provider = BlockchainProvider::new(provider_factory).unwrap();
1223
1224        let temp_dir = tempfile::tempdir().unwrap();
1225        let wal = Wal::new(temp_dir.path()).unwrap();
1226
1227        let (mut exex_handle, _, mut notifications) = ExExHandle::new(
1228            "test_exex".to_string(),
1229            Default::default(),
1230            provider,
1231            EthEvmConfig::mainnet(),
1232            wal.handle(),
1233        );
1234
1235        // Check initial state
1236        assert_eq!(exex_handle.id, "test_exex");
1237        assert_eq!(exex_handle.next_notification_id, 0);
1238
1239        // Setup two blocks for the chain commit notification
1240        let mut block1: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
1241        block1.set_hash(B256::repeat_byte(0x01));
1242        block1.set_block_number(10);
1243
1244        let mut block2: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
1245        block2.set_hash(B256::repeat_byte(0x02));
1246        block2.set_block_number(11);
1247
1248        // Setup a notification
1249        let notification = ExExNotification::ChainCommitted {
1250            new: Arc::new(Chain::new(
1251                vec![RecoveredBlock::default()],
1252                Default::default(),
1253                Default::default(),
1254            )),
1255        };
1256
1257        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1258
1259        // Send a notification and ensure it's received correctly
1260        match exex_handle.send(&mut cx, &(22, notification.clone())) {
1261            Poll::Ready(Ok(())) => {
1262                let received_notification = notifications.next().await.unwrap().unwrap();
1263                assert_eq!(received_notification, notification);
1264            }
1265            Poll::Pending => panic!("Notification send is pending"),
1266            Poll::Ready(Err(e)) => panic!("Failed to send notification: {e:?}"),
1267        }
1268
1269        // Ensure the notification ID was incremented
1270        assert_eq!(exex_handle.next_notification_id, 23);
1271    }
1272
1273    #[tokio::test]
1274    async fn test_notification_if_finished_height_gt_chain_tip() {
1275        let provider_factory = create_test_provider_factory();
1276        init_genesis(&provider_factory).unwrap();
1277        let provider = BlockchainProvider::new(provider_factory).unwrap();
1278
1279        let temp_dir = tempfile::tempdir().unwrap();
1280        let wal = Wal::new(temp_dir.path()).unwrap();
1281
1282        let (mut exex_handle, _, mut notifications) = ExExHandle::new(
1283            "test_exex".to_string(),
1284            Default::default(),
1285            provider,
1286            EthEvmConfig::mainnet(),
1287            wal.handle(),
1288        );
1289
1290        // Set finished_height to a value higher than the block tip
1291        exex_handle.finished_height = Some(BlockNumHash::new(15, B256::random()));
1292
1293        let mut block1: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
1294        block1.set_hash(B256::repeat_byte(0x01));
1295        block1.set_block_number(10);
1296
1297        let notification = ExExNotification::ChainCommitted {
1298            new: Arc::new(Chain::new(vec![block1.clone()], Default::default(), Default::default())),
1299        };
1300
1301        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1302
1303        // Send the notification
1304        match exex_handle.send(&mut cx, &(22, notification)) {
1305            Poll::Ready(Ok(())) => {
1306                poll_fn(|cx| {
1307                    // The notification should be skipped, so nothing should be sent.
1308                    // Check that the receiver channel is indeed empty
1309                    assert!(notifications.poll_next_unpin(cx).is_pending());
1310                    Poll::Ready(())
1311                })
1312                .await;
1313            }
1314            Poll::Pending | Poll::Ready(Err(_)) => {
1315                panic!("Notification should not be pending or fail");
1316            }
1317        }
1318
1319        // Ensure the notification ID was still incremented
1320        assert_eq!(exex_handle.next_notification_id, 23);
1321    }
1322
1323    #[tokio::test]
1324    async fn test_sends_commit_on_other_branch_below_finished_height() {
1325        let provider_factory = create_test_provider_factory();
1326        init_genesis(&provider_factory).unwrap();
1327        let provider = BlockchainProvider::new(provider_factory).unwrap();
1328
1329        let temp_dir = tempfile::tempdir().unwrap();
1330        let wal = Wal::new(temp_dir.path()).unwrap();
1331
1332        let (mut exex_handle, _, mut notifications) = ExExHandle::new(
1333            "test_exex".to_string(),
1334            Default::default(),
1335            provider,
1336            EthEvmConfig::mainnet(),
1337            wal.handle(),
1338        );
1339
1340        let block = |number, hash, parent_hash| {
1341            let mut block = RecoveredBlock::<reth_ethereum_primitives::Block>::default();
1342            block.set_block_number(number);
1343            block.set_hash(hash);
1344            block.set_parent_hash(parent_hash);
1345            block
1346        };
1347        let a2 = BlockNumHash::new(2, B256::repeat_byte(0xa2));
1348        let a5 = BlockNumHash::new(5, B256::repeat_byte(0xa5));
1349        let a3_to_a5 = vec![
1350            block(3, B256::repeat_byte(0xa3), a2.hash),
1351            block(4, B256::repeat_byte(0xa4), B256::repeat_byte(0xa3)),
1352            block(5, a5.hash, B256::repeat_byte(0xa4)),
1353        ];
1354        let b3 = block(3, B256::repeat_byte(0xb3), a2.hash);
1355        let b4 = block(4, B256::repeat_byte(0xb4), b3.hash());
1356
1357        // The ExEx finished A5, then A3..A5 are reorged to B3.
1358        exex_handle.finished_height = Some(a5);
1359        let reorg = ExExNotification::ChainReorged {
1360            old: Arc::new(Chain::new(a3_to_a5, Default::default(), Default::default())),
1361            new: Arc::new(Chain::new(vec![b3], Default::default(), Default::default())),
1362        };
1363        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1364        assert!(exex_handle.send(&mut cx, &(0, reorg.clone())).is_ready());
1365        assert_eq!(notifications.next().await.unwrap().unwrap(), reorg);
1366        assert_eq!(exex_handle.finished_height, Some(a2));
1367
1368        // B4 is not on the branch of A5, so it must be delivered.
1369        let commit = ExExNotification::ChainCommitted {
1370            new: Arc::new(Chain::new(vec![b4], Default::default(), Default::default())),
1371        };
1372        assert!(exex_handle.send(&mut cx, &(1, commit.clone())).is_ready());
1373        let received = notifications.next().now_or_never().expect("B4 must be delivered");
1374        assert_eq!(received.unwrap().unwrap(), commit);
1375    }
1376
1377    /// A `FinishedHeight` the ExEx sent before receiving a reorg names a reverted block, so the
1378    /// manager must rewind or ignore it rather than skip the next commit of the new branch.
1379    #[tokio::test]
1380    async fn test_ignores_finished_height_sent_before_revert_received() -> eyre::Result<()> {
1381        // The ExEx reports A4 either while the reorg waits for a slot or after it's sent.
1382        for report_while_reorg_waits in [true, false] {
1383            let provider_factory = create_test_provider_factory();
1384            init_genesis(&provider_factory)?;
1385            let provider = BlockchainProvider::new(provider_factory)?;
1386
1387            let temp_dir = tempfile::tempdir()?;
1388            let wal = Wal::new(temp_dir.path())?;
1389
1390            let (exex_handle, events_tx, mut notifications) = ExExHandle::new(
1391                "test_exex".to_string(),
1392                Default::default(),
1393                provider.clone(),
1394                EthEvmConfig::mainnet(),
1395                wal.handle(),
1396            );
1397            let mut exex_manager = std::pin::pin!(ExExManager::new(
1398                provider,
1399                vec![exex_handle],
1400                10,
1401                wal,
1402                empty_finalized_header_stream()
1403            ));
1404            let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1405
1406            let block = |number, hash, parent_hash| {
1407                let mut block = RecoveredBlock::<reth_ethereum_primitives::Block>::default();
1408                block.set_block_number(number);
1409                block.set_hash(hash);
1410                block.set_parent_hash(parent_hash);
1411                block
1412            };
1413            let chain =
1414                |blocks| Arc::new(Chain::new(blocks, Default::default(), Default::default()));
1415            let a2 = B256::repeat_byte(0xa2);
1416            let a3 = block(3, B256::repeat_byte(0xa3), a2);
1417            let a4 = block(4, B256::repeat_byte(0xa4), a3.hash());
1418            let b3 = block(3, B256::repeat_byte(0xb3), a2);
1419            let b4 = block(4, B256::repeat_byte(0xb4), b3.hash());
1420            let b3_num_hash = b3.num_hash();
1421            let fork_block = BlockNumHash::new(2, a2);
1422
1423            // The ExEx processes A3 and reports it.
1424            let commit_a3 = ExExNotification::ChainCommitted { new: chain(vec![a3.clone()]) };
1425            exex_manager.handle().send(ExExNotificationSource::Pipeline, commit_a3.clone())?;
1426            assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1427            assert_eq!(notifications.try_poll_next_unpin(&mut cx)?, Poll::Ready(Some(commit_a3)));
1428            events_tx.send(ExExEvent::FinishedHeight(a3.num_hash()))?;
1429
1430            // A4 fills the channel, so the reorg of A3..A4 to B3 waits for a slot. The finished
1431            // height is rewound already, so the pruner keeps B3.
1432            let commit_a4 = ExExNotification::ChainCommitted { new: chain(vec![a4.clone()]) };
1433            let reorg = ExExNotification::ChainReorged {
1434                old: chain(vec![a3, a4.clone()]),
1435                new: chain(vec![b3]),
1436            };
1437            exex_manager.handle().send(ExExNotificationSource::Pipeline, commit_a4.clone())?;
1438            exex_manager.handle().send(ExExNotificationSource::Pipeline, reorg.clone())?;
1439            assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1440            assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1441            assert_eq!(exex_manager.exex_handles[0].finished_height, Some(fork_block));
1442
1443            // The ExEx takes A4, which frees the slot for the reorg, and reports A4 before taking
1444            // the reorg.
1445            assert_eq!(notifications.try_poll_next_unpin(&mut cx)?, Poll::Ready(Some(commit_a4)));
1446            if report_while_reorg_waits {
1447                events_tx.send(ExExEvent::FinishedHeight(a4.num_hash()))?;
1448            }
1449            assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1450            if !report_while_reorg_waits {
1451                events_tx.send(ExExEvent::FinishedHeight(a4.num_hash()))?;
1452            }
1453            let commit_b4 = ExExNotification::ChainCommitted { new: chain(vec![b4]) };
1454            exex_manager.handle().send(ExExNotificationSource::Pipeline, commit_b4.clone())?;
1455            assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1456            assert_eq!(exex_manager.exex_handles[0].finished_height, Some(fork_block));
1457
1458            // B4 is at the height of the stale A4, so keeping A4 would skip it.
1459            assert_eq!(notifications.try_poll_next_unpin(&mut cx)?, Poll::Ready(Some(reorg)));
1460            assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1461            assert_eq!(notifications.try_poll_next_unpin(&mut cx)?, Poll::Ready(Some(commit_b4)));
1462
1463            // Once the ExEx has taken the reorg, its finished heights count again.
1464            events_tx.send(ExExEvent::FinishedHeight(b3_num_hash))?;
1465            assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1466            assert_eq!(exex_manager.exex_handles[0].finished_height, Some(b3_num_hash));
1467        }
1468
1469        Ok(())
1470    }
1471
1472    #[tokio::test]
1473    async fn test_sends_chain_reorged_notification() {
1474        let provider_factory = create_test_provider_factory();
1475        init_genesis(&provider_factory).unwrap();
1476        let provider = BlockchainProvider::new(provider_factory).unwrap();
1477
1478        let temp_dir = tempfile::tempdir().unwrap();
1479        let wal = Wal::new(temp_dir.path()).unwrap();
1480
1481        let (mut exex_handle, _, mut notifications) = ExExHandle::new(
1482            "test_exex".to_string(),
1483            Default::default(),
1484            provider,
1485            EthEvmConfig::mainnet(),
1486            wal.handle(),
1487        );
1488
1489        let notification = ExExNotification::ChainReorged {
1490            old: Arc::new(Chain::default()),
1491            new: Arc::new(Chain::default()),
1492        };
1493
1494        // Even if the finished height is higher than the tip of the new chain, the reorg
1495        // notification should be received
1496        exex_handle.finished_height = Some(BlockNumHash::new(u64::MAX, B256::random()));
1497
1498        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1499
1500        // Send the notification
1501        match exex_handle.send(&mut cx, &(22, notification.clone())) {
1502            Poll::Ready(Ok(())) => {
1503                let received_notification = notifications.next().await.unwrap().unwrap();
1504                assert_eq!(received_notification, notification);
1505            }
1506            Poll::Pending | Poll::Ready(Err(_)) => {
1507                panic!("Notification should not be pending or fail")
1508            }
1509        }
1510
1511        // Ensure the notification ID was incremented
1512        assert_eq!(exex_handle.next_notification_id, 23);
1513    }
1514
1515    #[tokio::test]
1516    async fn test_sends_chain_reverted_notification() {
1517        let provider_factory = create_test_provider_factory();
1518        init_genesis(&provider_factory).unwrap();
1519        let provider = BlockchainProvider::new(provider_factory).unwrap();
1520
1521        let temp_dir = tempfile::tempdir().unwrap();
1522        let wal = Wal::new(temp_dir.path()).unwrap();
1523
1524        let (mut exex_handle, _, mut notifications) = ExExHandle::new(
1525            "test_exex".to_string(),
1526            Default::default(),
1527            provider,
1528            EthEvmConfig::mainnet(),
1529            wal.handle(),
1530        );
1531
1532        let notification = ExExNotification::ChainReverted { old: Arc::new(Chain::default()) };
1533
1534        // Even if the finished height is higher than the tip of the new chain, the reorg
1535        // notification should be received
1536        exex_handle.finished_height = Some(BlockNumHash::new(u64::MAX, B256::random()));
1537
1538        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1539
1540        // Send the notification
1541        match exex_handle.send(&mut cx, &(22, notification.clone())) {
1542            Poll::Ready(Ok(())) => {
1543                let received_notification = notifications.next().await.unwrap().unwrap();
1544                assert_eq!(received_notification, notification);
1545            }
1546            Poll::Pending | Poll::Ready(Err(_)) => {
1547                panic!("Notification should not be pending or fail")
1548            }
1549        }
1550
1551        // Ensure the notification ID was incremented
1552        assert_eq!(exex_handle.next_notification_id, 23);
1553    }
1554
1555    #[tokio::test]
1556    async fn test_exex_wal() -> eyre::Result<()> {
1557        reth_tracing::init_test_tracing();
1558
1559        let mut rng = generators::rng();
1560
1561        let provider_factory = create_test_provider_factory();
1562        let genesis_hash = init_genesis(&provider_factory).unwrap();
1563        let genesis_block = provider_factory
1564            .sealed_block_with_senders(genesis_hash.into(), TransactionVariant::NoHash)
1565            .unwrap()
1566            .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
1567
1568        let block = random_block(
1569            &mut rng,
1570            genesis_block.number + 1,
1571            BlockParams { parent: Some(genesis_hash), ..Default::default() },
1572        )
1573        .try_recover()
1574        .unwrap();
1575        let provider_rw = provider_factory.database_provider_rw().unwrap();
1576        provider_rw.insert_block(&block).unwrap();
1577        provider_rw.commit().unwrap();
1578
1579        let provider = BlockchainProvider::new(provider_factory).unwrap();
1580
1581        let temp_dir = tempfile::tempdir().unwrap();
1582        let wal = Wal::new(temp_dir.path()).unwrap();
1583
1584        let (exex_handle, events_tx, mut notifications) = ExExHandle::new(
1585            "test_exex".to_string(),
1586            Default::default(),
1587            provider.clone(),
1588            EthEvmConfig::mainnet(),
1589            wal.handle(),
1590        );
1591
1592        let genesis_notification = ExExNotification::ChainCommitted {
1593            new: Arc::new(Chain::new(
1594                vec![genesis_block.clone()],
1595                Default::default(),
1596                Default::default(),
1597            )),
1598        };
1599        let notification = ExExNotification::ChainCommitted {
1600            new: Arc::new(Chain::new(vec![block.clone()], Default::default(), Default::default())),
1601        };
1602
1603        let (finalized_headers_tx, rx) = watch::channel(None);
1604        finalized_headers_tx.send(Some(genesis_block.clone_sealed_header()))?;
1605        let finalized_header_stream = ForkChoiceStream::new(rx);
1606
1607        let mut exex_manager = std::pin::pin!(ExExManager::new(
1608            provider,
1609            vec![exex_handle],
1610            2,
1611            wal,
1612            finalized_header_stream
1613        ));
1614
1615        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1616
1617        exex_manager
1618            .handle()
1619            .send(ExExNotificationSource::Pipeline, genesis_notification.clone())?;
1620        exex_manager.handle().send(ExExNotificationSource::BlockchainTree, notification.clone())?;
1621
1622        assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1623        assert_eq!(
1624            notifications.try_poll_next_unpin(&mut cx)?,
1625            Poll::Ready(Some(genesis_notification))
1626        );
1627        assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1628        assert_eq!(
1629            notifications.try_poll_next_unpin(&mut cx)?,
1630            Poll::Ready(Some(notification.clone()))
1631        );
1632        // WAL shouldn't contain the genesis notification, because it's finalized
1633        assert_eq!(
1634            exex_manager.wal.iter_notifications()?.collect::<WalResult<Vec<_>>>()?,
1635            std::slice::from_ref(&notification)
1636        );
1637
1638        finalized_headers_tx.send(Some(block.clone_sealed_header()))?;
1639        assert!(exex_manager.as_mut().poll(&mut cx).is_pending());
1640        // WAL isn't finalized because the ExEx didn't emit the `FinishedHeight` event
1641        assert_eq!(
1642            exex_manager.wal.iter_notifications()?.collect::<WalResult<Vec<_>>>()?,
1643            std::slice::from_ref(&notification)
1644        );
1645
1646        // Send a `FinishedHeight` event with a non-canonical block
1647        events_tx
1648            .send(ExExEvent::FinishedHeight((rng.random::<u64>(), rng.random::<B256>()).into()))
1649            .unwrap();
1650
1651        finalized_headers_tx.send(Some(block.clone_sealed_header()))?;
1652        assert!(exex_manager.as_mut().poll(&mut cx).is_pending());
1653        // WAL isn't finalized because the ExEx emitted a `FinishedHeight` event with a
1654        // non-canonical block
1655        assert_eq!(
1656            exex_manager.wal.iter_notifications()?.collect::<WalResult<Vec<_>>>()?,
1657            std::slice::from_ref(&notification)
1658        );
1659
1660        // Send a `FinishedHeight` event with a canonical block
1661        events_tx.send(ExExEvent::FinishedHeight(block.num_hash())).unwrap();
1662
1663        finalized_headers_tx.send(Some(block.clone_sealed_header()))?;
1664        assert!(exex_manager.as_mut().poll(&mut cx).is_pending());
1665        // WAL is finalized
1666        assert_eq!(exex_manager.wal.iter_notifications()?.next().transpose()?, None);
1667
1668        Ok(())
1669    }
1670
1671    #[tokio::test]
1672    async fn test_deadlock_manager_wakes_after_buffer_clears() {
1673        // This test simulates the scenario where the buffer fills up, ingestion pauses,
1674        // and then space clears. We verify the manager wakes up to process pending items.
1675
1676        let temp_dir = tempfile::tempdir().unwrap();
1677        let wal = Wal::new(temp_dir.path()).unwrap();
1678        let provider_factory = create_test_provider_factory();
1679        init_genesis(&provider_factory).unwrap();
1680        let provider = BlockchainProvider::new(provider_factory.clone()).unwrap();
1681
1682        // 1. Setup Manager with Capacity = 1
1683        let (exex_handle, _, mut notifications) = ExExHandle::new(
1684            "test_exex".to_string(),
1685            Default::default(),
1686            provider,
1687            EthEvmConfig::mainnet(),
1688            wal.handle(),
1689        );
1690
1691        let max_capacity = 2;
1692        let exex_manager = ExExManager::new(
1693            provider_factory,
1694            vec![exex_handle],
1695            max_capacity,
1696            wal,
1697            empty_finalized_header_stream(),
1698        );
1699
1700        let manager_handle = exex_manager.handle();
1701
1702        // Spawn manager in background so it runs continuously
1703        tokio::spawn(async move {
1704            exex_manager.await.ok();
1705        });
1706
1707        // Helper to create notifications
1708        let mut rng = generators::rng();
1709        let mut make_notif = |id: u64| {
1710            let block = random_block(&mut rng, id, BlockParams::default()).try_recover().unwrap();
1711            ExExNotification::ChainCommitted {
1712                new: Arc::new(Chain::new(vec![block], Default::default(), Default::default())),
1713            }
1714        };
1715
1716        manager_handle.send(ExExNotificationSource::Pipeline, make_notif(1)).unwrap();
1717
1718        // Send the "Stuck" Item (Notification #100).
1719        // At this point, the buffer is full (buffer_full=true), so this item waits in the
1720        // manager's queue.
1721        manager_handle.send(ExExNotificationSource::Pipeline, make_notif(100)).unwrap();
1722
1723        // 3. Relieve Pressure
1724        // We consume items from the ExEx.
1725        // As we pull items out, the ExEx frees space -> Manager sends buffered item -> Manager
1726        // frees space. Once Manager frees space, the FIX (wake_by_ref) should trigger,
1727        // causing it to read Notif #100.
1728
1729        // Consume the jam
1730        let _ = notifications.next().await.unwrap();
1731
1732        // 4. Assert No Deadlock
1733        // We expect Notification #100 next.
1734        // If the wake_by_ref fix is missing, this will Time Out because the manager is sleeping
1735        // despite having empty buffer.
1736        let result =
1737            tokio::time::timeout(std::time::Duration::from_secs(1), notifications.next()).await;
1738
1739        assert!(
1740            result.is_ok(),
1741            "Deadlock detected! Manager failed to wake up and process Pending Item #100."
1742        );
1743    }
1744
1745    fn canonical_notifications(count: u64) -> Vec<CanonStateNotification> {
1746        random_block_range(
1747            &mut generators::rng(),
1748            1..=count,
1749            BlockRangeParams { tx_count: 0..1, ..Default::default() },
1750        )
1751        .into_iter()
1752        .map(|block| CanonStateNotification::Commit {
1753            new: Arc::new(Chain::new(
1754                vec![block.try_recover().unwrap()],
1755                Default::default(),
1756                Default::default(),
1757            )),
1758        })
1759        .collect()
1760    }
1761
1762    fn canonical_manager(wal: Wal) -> ExExManager<MockEthProvider, EthPrimitives> {
1763        ExExManager::new(
1764            MockEthProvider::default(),
1765            vec![],
1766            1,
1767            wal,
1768            empty_finalized_header_stream(),
1769        )
1770    }
1771
1772    #[tokio::test]
1773    async fn test_canonical_notifications_survive_backpressure() -> eyre::Result<()> {
1774        let temp_dir = tempfile::tempdir()?;
1775        let wal = Wal::new(temp_dir.path())?;
1776        let provider = MockEthProvider::<EthPrimitives>::default();
1777        let (first, first_events, mut first_notifications) = ExExHandle::new(
1778            "first".to_string(),
1779            Default::default(),
1780            provider.clone(),
1781            EthEvmConfig::mainnet(),
1782            wal.handle(),
1783        );
1784        let (second, second_events, mut second_notifications) = ExExHandle::new(
1785            "second".to_string(),
1786            Default::default(),
1787            provider.clone(),
1788            EthEvmConfig::mainnet(),
1789            wal.handle(),
1790        );
1791        let mut manager = ExExManager::new(
1792            provider,
1793            vec![first, second],
1794            2,
1795            wal,
1796            empty_finalized_header_stream(),
1797        );
1798        let canonical = manager.handle();
1799        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1800        let mut updates = canonical_notifications(16);
1801
1802        let old = updates.last().unwrap().committed();
1803        let mut rng = generators::rng();
1804        let replacement = random_block(
1805            &mut rng,
1806            old.first().number(),
1807            BlockParams { parent: Some(old.first().parent_hash()), ..Default::default() },
1808        )
1809        .try_recover()?;
1810        let new = Arc::new(Chain::new(vec![replacement], Default::default(), Default::default()));
1811        updates.push(CanonStateNotification::Reorg { old: old.clone(), new: new.clone() });
1812        updates.push(CanonStateNotification::Reorg { old: new, new: old });
1813        let live_parent = updates.last().unwrap().tip().num_hash();
1814
1815        // Neither consumer is polled between manager polls, so the manager must keep receiving
1816        // tree notifications with its two-entry buffer full.
1817        for chunk in updates.chunks(4) {
1818            for update in chunk {
1819                canonical.send(ExExNotificationSource::BlockchainTree, update.clone().into())?;
1820            }
1821            assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1822            assert!(manager.buffer.len() <= manager.max_capacity);
1823            tokio::task::yield_now().await;
1824        }
1825        assert!(!manager.queued_notifications.is_empty());
1826        let expected = updates.into_iter().map(ExExNotification::from).collect::<Vec<_>>();
1827        assert_eq!(manager.wal.iter_notifications()?.collect::<WalResult<Vec<_>>>()?, expected);
1828
1829        // The faster consumer can advance, but the slower one still holds the shared buffer.
1830        assert_eq!(
1831            first_notifications.try_poll_next_unpin(&mut cx)?,
1832            Poll::Ready(Some(expected[0].clone()))
1833        );
1834        assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1835        assert!(!manager.queued_notifications.is_empty());
1836
1837        // No further canonical update is needed to drain the entire queue.
1838        let mut finished_height = manager.handle().finished_height();
1839        tokio::spawn(manager);
1840        tokio::time::timeout(Duration::from_secs(10), async {
1841            for (index, notification) in expected.iter().enumerate() {
1842                if index > 0 {
1843                    assert_eq!(first_notifications.try_next().await?, Some(notification.clone()));
1844                }
1845                assert_eq!(second_notifications.try_next().await?, Some(notification.clone()));
1846            }
1847            eyre::Ok(())
1848        })
1849        .await??;
1850
1851        let block = random_block(
1852            &mut rng,
1853            live_parent.number + 1,
1854            BlockParams { parent: Some(live_parent.hash), ..Default::default() },
1855        )
1856        .try_recover()?;
1857        let live = CanonStateNotification::<EthPrimitives>::Commit {
1858            new: Arc::new(Chain::new(vec![block], Default::default(), Default::default())),
1859        };
1860        let live_head = live.tip().num_hash();
1861        canonical.send(ExExNotificationSource::BlockchainTree, live.clone().into())?;
1862        let live = ExExNotification::from(live);
1863        tokio::time::timeout(Duration::from_secs(10), async {
1864            assert_eq!(first_notifications.try_next().await?, Some(live.clone()));
1865            assert_eq!(second_notifications.try_next().await?, Some(live));
1866            eyre::Ok(())
1867        })
1868        .await??;
1869        assert_eq!(first_notifications.try_poll_next_unpin(&mut cx)?, Poll::Pending);
1870        assert_eq!(second_notifications.try_poll_next_unpin(&mut cx)?, Poll::Pending);
1871
1872        // Persisting and delivering notifications never acknowledges work for the consumers.
1873        assert_eq!(*finished_height.borrow(), FinishedExExHeight::NotReady);
1874        first_events.send(ExExEvent::FinishedHeight(live_head))?;
1875        second_events.send(ExExEvent::FinishedHeight(live_head))?;
1876        tokio::time::timeout(
1877            Duration::from_secs(10),
1878            finished_height
1879                .wait_for(|height| *height == FinishedExExHeight::Height(live_head.number)),
1880        )
1881        .await??;
1882        Ok(())
1883    }
1884
1885    #[tokio::test]
1886    async fn test_canonical_notifications_follow_queued_handle_notifications() -> eyre::Result<()> {
1887        let temp_dir = tempfile::tempdir()?;
1888        let wal = Wal::new(temp_dir.path())?;
1889        let provider = MockEthProvider::<EthPrimitives>::default();
1890        let (exex, _, mut notifications) = ExExHandle::new(
1891            "exex".to_string(),
1892            Default::default(),
1893            provider.clone(),
1894            EthEvmConfig::mainnet(),
1895            wal.handle(),
1896        );
1897        let mut manager =
1898            ExExManager::new(provider, vec![exex], 1, wal, empty_finalized_header_stream());
1899        let canonical = manager.handle();
1900        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1901        let updates = canonical_notifications(3);
1902        let expected = updates.iter().cloned().map(ExExNotification::from).collect::<Vec<_>>();
1903
1904        // The second pipeline notification is queued because the buffer is full, and the tree
1905        // notification arrives after it.
1906        for notification in &expected[..2] {
1907            manager.handle.send(ExExNotificationSource::Pipeline, notification.clone())?;
1908        }
1909        assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1910        canonical.send(ExExNotificationSource::BlockchainTree, updates[2].clone().into())?;
1911        assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1912
1913        tokio::spawn(manager);
1914        tokio::time::timeout(Duration::from_secs(10), async {
1915            for notification in expected {
1916                assert_eq!(notifications.try_next().await?, Some(notification));
1917            }
1918            eyre::Ok(())
1919        })
1920        .await??;
1921        Ok(())
1922    }
1923
1924    #[tokio::test]
1925    async fn test_canonical_wal_finalization_keeps_queued_notifications() -> eyre::Result<()> {
1926        let temp_dir = tempfile::tempdir()?;
1927        let wal = Wal::<EthPrimitives>::new(temp_dir.path())?;
1928        let (finalized, finalized_receiver) = watch::channel(None);
1929        let mut manager = ExExManager::new(
1930            MockEthProvider::<EthPrimitives>::default(),
1931            vec![],
1932            1,
1933            wal,
1934            ForkChoiceStream::new(finalized_receiver),
1935        );
1936        let canonical = manager.handle();
1937        let updates = canonical_notifications(3);
1938        let header = updates.last().unwrap().tip().clone_sealed_header();
1939        let expected = updates.iter().cloned().map(ExExNotification::from).collect::<Vec<_>>();
1940        for update in updates {
1941            canonical.send(ExExNotificationSource::BlockchainTree, update.into())?;
1942        }
1943        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1944        assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1945        assert!(matches!(
1946            manager.queued_notifications.make_contiguous(),
1947            [QueuedNotification::Wal(1), QueuedNotification::Wal(2)]
1948        ));
1949
1950        // Only the notification that already left the queue is finalized.
1951        finalized.send(Some(header))?;
1952        assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1953        assert_eq!(
1954            manager.wal.iter_notifications()?.collect::<WalResult<Vec<_>>>()?,
1955            expected[1..]
1956        );
1957        assert!(matches!(
1958            manager.queued_notifications.make_contiguous(),
1959            [QueuedNotification::Wal(2)]
1960        ));
1961        Ok(())
1962    }
1963
1964    #[tokio::test]
1965    async fn test_canonical_wal_commit_error() -> eyre::Result<()> {
1966        let temp_dir = tempfile::tempdir()?;
1967        let directory = temp_dir.path().join("wal");
1968        let mut manager = canonical_manager(Wal::new(&directory)?);
1969        let canonical = manager.handle();
1970        canonical.send(
1971            ExExNotificationSource::BlockchainTree,
1972            canonical_notifications(1).remove(0).into(),
1973        )?;
1974        reth_fs_util::remove_dir_all(&directory)?;
1975
1976        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1977        let Poll::Ready(Err(error)) = Pin::new(&mut manager).poll(&mut cx) else {
1978            panic!("expected WAL commit failure")
1979        };
1980        assert!(matches!(error.downcast_ref::<WalError>(), Some(WalError::FsPathError(_))));
1981        Ok(())
1982    }
1983
1984    #[tokio::test]
1985    async fn test_canonical_wal_missing_entry() -> eyre::Result<()> {
1986        let temp_dir = tempfile::tempdir()?;
1987        let mut manager = canonical_manager(Wal::new(temp_dir.path())?);
1988        let canonical = manager.handle();
1989        for update in canonical_notifications(2) {
1990            canonical.send(ExExNotificationSource::BlockchainTree, update.into())?;
1991        }
1992        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1993        assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1994        reth_fs_util::remove_file(temp_dir.path().join("1.wal"))?;
1995
1996        let Poll::Ready(Err(error)) = Pin::new(&mut manager).poll(&mut cx) else {
1997            panic!("expected missing WAL entry")
1998        };
1999        assert!(matches!(error.downcast_ref::<WalError>(), Some(WalError::FileNotFound(1))));
2000        Ok(())
2001    }
2002
2003    #[tokio::test]
2004    async fn test_capacity_accounts_for_queued_notifications() -> eyre::Result<()> {
2005        let temp_dir = tempfile::tempdir()?;
2006        let wal = Wal::new(temp_dir.path())?;
2007        let provider = MockEthProvider::<EthPrimitives>::default();
2008        let (exex, _, mut notifications) = ExExHandle::new(
2009            "exex".to_string(),
2010            Default::default(),
2011            provider.clone(),
2012            EthEvmConfig::mainnet(),
2013            wal.handle(),
2014        );
2015        let mut manager =
2016            ExExManager::new(provider, vec![exex], 2, wal, empty_finalized_header_stream());
2017        let mut handle = manager.handle();
2018        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
2019        let updates = canonical_notifications(4);
2020        let expected = updates.iter().cloned().map(ExExNotification::from).collect::<Vec<_>>();
2021
2022        for update in updates {
2023            handle.send(ExExNotificationSource::BlockchainTree, update.into())?;
2024        }
2025
2026        // Two notifications enter the buffer and two are queued. Delivering the first shrinks the
2027        // buffer below max_capacity, but capacity must remain zero while notifications are queued.
2028        assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
2029        assert_eq!(manager.buffer.len(), 1);
2030        assert_eq!(manager.queued_notifications.len(), 2);
2031        assert_eq!(handle.capacity(), 0);
2032        assert!(!handle.has_capacity());
2033        assert!(handle.poll_ready(&mut cx).is_pending());
2034
2035        // Draining one notification refills the buffer from the queue and delivers the second,
2036        // leaving one buffered and one queued (still at max_capacity).
2037        assert_eq!(
2038            notifications.try_poll_next_unpin(&mut cx)?,
2039            Poll::Ready(Some(expected[0].clone()))
2040        );
2041        assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
2042        assert_eq!(manager.buffer.len(), 1);
2043        assert_eq!(manager.queued_notifications.len(), 1);
2044        assert_eq!(handle.capacity(), 0);
2045        assert!(!handle.has_capacity());
2046        assert!(handle.poll_ready(&mut cx).is_pending());
2047
2048        // Draining another empties the queue and leaves one slot free in the buffer.
2049        assert_eq!(
2050            notifications.try_poll_next_unpin(&mut cx)?,
2051            Poll::Ready(Some(expected[1].clone()))
2052        );
2053        assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
2054        assert_eq!(manager.buffer.len(), 1);
2055        assert!(manager.queued_notifications.is_empty());
2056        assert_eq!(handle.capacity(), 1);
2057        assert!(handle.has_capacity());
2058        assert!(handle.poll_ready(&mut cx).is_ready());
2059
2060        assert_eq!(
2061            notifications.try_poll_next_unpin(&mut cx)?,
2062            Poll::Ready(Some(expected[2].clone()))
2063        );
2064        assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
2065        assert_eq!(handle.capacity(), 2);
2066        assert_eq!(
2067            notifications.try_poll_next_unpin(&mut cx)?,
2068            Poll::Ready(Some(expected[3].clone()))
2069        );
2070        Ok(())
2071    }
2072}