Skip to main content

consensus_core/
commit_consumer.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::sync::Arc;
5
6use consensus_config::Stake;
7use consensus_types::block::Round;
8use mysten_metrics::monitored_mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
9use parking_lot::Mutex;
10use tokio::sync::{SetOnce, watch};
11use tracing::debug;
12
13use crate::{CommitIndex, CommittedSubDag};
14
15/// Arguments from commit consumer to this consensus instance.
16#[derive(Clone)]
17pub struct CommitConsumerArgs {
18    pub(crate) replay_mode: ReplayMode,
19    pub(crate) commit_sender: UnboundedSender<CommittedSubDag>,
20    monitor: Arc<ConsumerMonitor>,
21}
22
23#[derive(Clone, Copy, Debug)]
24pub(crate) enum ReplayMode {
25    /// Replay from a consumer-supplied watermark without acknowledgement pacing.
26    FromWatermark {
27        /// Commit indices start at one. Replay starts at this index plus one;
28        /// zero requests the entire epoch.
29        replay_after_commit_index: CommitIndex,
30        /// Consumer-supplied target for startup readiness.
31        consumer_last_processed_commit_index: CommitIndex,
32    },
33    /// Replay the entire epoch, discovering the target from consensus storage.
34    /// Only the finalized prefix is paced by application acknowledgements;
35    /// the unfinalized tail and live consensus keep their existing flow control.
36    FullEpochPaced,
37}
38
39impl CommitConsumerArgs {
40    /// Requests replay after `replay_after_commit_index`, using the consumer's
41    /// last processed index as the recovery target. This mode does not wait for
42    /// application acknowledgements during startup.
43    /// Commit indices start at one; use zero to replay from the first commit.
44    pub fn new(
45        replay_after_commit_index: CommitIndex,
46        consumer_last_processed_commit_index: CommitIndex,
47    ) -> (Self, UnboundedReceiver<CommittedSubDag>) {
48        Self::new_with_replay_mode(ReplayMode::FromWatermark {
49            replay_after_commit_index,
50            consumer_last_processed_commit_index,
51        })
52    }
53
54    /// Replays the epoch from its first commit into a consumer with no durable
55    /// execution watermark. Consensus owns storage and delivers historical and
56    /// live commits over the returned stream.
57    ///
58    /// This is an integration API for external consensus consumers that rebuild
59    /// application state on restart. DO NOT REMOVE this entry point solely because it
60    /// has no production callers in this workspace. Changes to this contract
61    /// must account for downstream consumers.
62    ///
63    /// Consensus discovers the startup target from its store: the last stored
64    /// commit when transaction voting is disabled, or the last finalized commit
65    /// when voting is enabled. It waits for application acknowledgements between
66    /// recovery batches. An unfinalized tail goes through normal finalization
67    /// without waiting for application at startup, since it may need live consensus.
68    /// Consequently, pacing bounds only the finalized prefix: if voting is enabled
69    /// and no commits are finalized, the entire history is queued without pacing.
70    ///
71    /// The consumer must run before awaiting [`crate::ConsensusAuthority::start`]
72    /// and call [`ConsumerMonitor::set_highest_handled_commit`] only after
73    /// applying each commit. Waiting for startup before consuming would deadlock
74    /// recovery. Use [`Self::monitor`] to observe readiness and committed-head
75    /// progress without accessing storage.
76    /// Startup panics if the consumer closes while recovery is waiting for an
77    /// application acknowledgement.
78    pub fn new_with_full_replay() -> (Self, UnboundedReceiver<CommittedSubDag>) {
79        Self::new_with_replay_mode(ReplayMode::FullEpochPaced)
80    }
81
82    fn new_with_replay_mode(replay_mode: ReplayMode) -> (Self, UnboundedReceiver<CommittedSubDag>) {
83        let (replay_after_commit_index, replay_target) = match replay_mode {
84            ReplayMode::FromWatermark {
85                replay_after_commit_index,
86                consumer_last_processed_commit_index,
87            } => (
88                replay_after_commit_index,
89                Some(consumer_last_processed_commit_index),
90            ),
91            ReplayMode::FullEpochPaced => (0, None),
92        };
93        let (commit_sender, commit_receiver) = unbounded_channel("consensus_commit_output");
94        let monitor = Arc::new(ConsumerMonitor::new(
95            replay_after_commit_index,
96            replay_target,
97        ));
98        (
99            Self {
100                replay_mode,
101                commit_sender,
102                monitor,
103            },
104            commit_receiver,
105        )
106    }
107
108    pub fn monitor(&self) -> Arc<ConsumerMonitor> {
109        self.monitor.clone()
110    }
111}
112
113/// Process-local committed head reported by consensus, independently of application progress.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct CommitProgress {
116    /// Latest committed index reported by consensus, independently of consumer progress.
117    /// Recovery reports the stored head before replay, rather than each historical
118    /// commit as it is delivered. Live commits advance this value afterwards.
119    pub highest_committed_index: CommitIndex,
120    /// Leader round associated with [`Self::highest_committed_index`], including
121    /// the stored head during replay rather than the consumer's replay position.
122    pub highest_committed_round: Round,
123}
124
125/// This node's view of committee progress. The round prober sets the round, stake and probe
126/// time after every complete probe, and the commit syncer sets the quorum commit index. The
127/// values are read-only and are not inputs to consensus.
128///
129/// The round prober runs only on validator nodes. On other nodes only `quorum_commit_index`
130/// updates.
131#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
132pub struct PeerProgress {
133    /// Highest round over all authorities at which an authority's block was accepted by a
134    /// quorum of stake, from the last complete probe.
135    pub quorum_accepted_round: Round,
136    /// Quorum commit index from the last commit syncer scheduling pass.
137    pub quorum_commit_index: CommitIndex,
138    /// Total stake of peers whose request succeeded in the last complete probe. It excludes
139    /// this node.
140    pub responsive_stake: Stake,
141    /// Consensus clock time in milliseconds when the last complete probe finished. It is zero
142    /// when no probe has completed.
143    pub probed_at_ms: u64,
144}
145
146/// Tracks application progress, startup readiness, the consensus head, and peer progress.
147///
148/// External consumers observe the committed head, handled commits, and replay
149/// target separately to monitor catch-up without reading consensus storage. Liveness
150/// watchdogs use [`PeerProgress`] to interpret a pause in local commits.
151/// DO NOT REMOVE these observation APIs solely because they have no callers in
152/// this workspace. They support the external integration described by
153/// [`CommitConsumerArgs::new_with_full_replay`].
154pub struct ConsumerMonitor {
155    replay_target: SetOnce<CommitIndex>,
156    committed: watch::Sender<CommitProgress>,
157    handled: watch::Sender<CommitIndex>,
158    peer_progress: Mutex<PeerProgress>,
159}
160
161impl ConsumerMonitor {
162    pub(crate) fn new(
163        replay_after_commit_index: CommitIndex,
164        replay_target: Option<CommitIndex>,
165    ) -> Self {
166        Self {
167            replay_target: SetOnce::new_with(replay_target),
168            committed: watch::Sender::new(CommitProgress {
169                highest_committed_index: 0,
170                highest_committed_round: 0,
171            }),
172            handled: watch::Sender::new(replay_after_commit_index),
173            peer_progress: Mutex::new(PeerProgress::default()),
174        }
175    }
176
177    /// Returns the consensus head, independently of consumer acknowledgements.
178    pub fn progress(&self) -> CommitProgress {
179        *self.committed.borrow()
180    }
181
182    /// Subscribes to consensus head changes only. To observe application progress
183    /// and target discovery, also use [`Self::subscribe_handled_commit`] and
184    /// [`Self::wait_for_replay_target`].
185    pub fn subscribe_progress(&self) -> watch::Receiver<CommitProgress> {
186        self.committed.subscribe()
187    }
188
189    /// Returns the fixed startup target. With [`CommitConsumerArgs::new_with_full_replay`],
190    /// `None` means storage has not been inspected and `Some(0)` means there is no
191    /// finalized startup work. With [`CommitConsumerArgs::new`], the consumer-supplied
192    /// last processed index is available immediately.
193    pub fn replay_target(&self) -> Option<CommitIndex> {
194        self.replay_target.get().copied()
195    }
196
197    /// Waits for target discovery, without waiting for the consumer to apply it.
198    pub async fn wait_for_replay_target(&self) -> CommitIndex {
199        *self.replay_target.wait().await
200    }
201
202    pub(crate) fn set_replay_target(&self, target: CommitIndex) {
203        self.replay_target
204            .set(target)
205            .expect("startup replay target must be set only once");
206    }
207
208    pub(crate) fn report_committed(&self, index: CommitIndex, round: Round) {
209        self.committed.send_if_modified(|progress| {
210            if index <= progress.highest_committed_index {
211                return false;
212            }
213            progress.highest_committed_index = index;
214            progress.highest_committed_round = round;
215            true
216        });
217    }
218
219    pub fn highest_handled_commit(&self) -> CommitIndex {
220        *self.handled.borrow()
221    }
222
223    /// Subscribes to consumer acknowledgements, independently of consensus progress.
224    pub fn subscribe_handled_commit(&self) -> watch::Receiver<CommitIndex> {
225        self.handled.subscribe()
226    }
227
228    /// Acknowledge application, after the consumer has finished processing the commit.
229    pub fn set_highest_handled_commit(&self, highest_handled_commit: CommitIndex) {
230        debug!("Highest handled commit set to {}", highest_handled_commit);
231        self.handled.send_replace(highest_handled_commit);
232    }
233
234    /// Returns this node's latest view of committee progress. See [`PeerProgress`].
235    pub fn peer_progress(&self) -> PeerProgress {
236        *self.peer_progress.lock()
237    }
238
239    pub(crate) fn report_probe(
240        &self,
241        quorum_accepted_round: Round,
242        responsive_stake: Stake,
243        probed_at_ms: u64,
244    ) {
245        let mut progress = self.peer_progress.lock();
246        progress.quorum_accepted_round = quorum_accepted_round;
247        progress.responsive_stake = responsive_stake;
248        progress.probed_at_ms = probed_at_ms;
249    }
250
251    pub(crate) fn report_quorum_commit_index(&self, quorum_commit_index: CommitIndex) {
252        self.peer_progress.lock().quorum_commit_index = quorum_commit_index;
253    }
254
255    pub(crate) async fn wait_for_handled(&self, target: CommitIndex) {
256        let mut handled = self.subscribe_handled_commit();
257        loop {
258            if *handled.borrow_and_update() >= target {
259                return;
260            }
261            handled.changed().await.unwrap();
262        }
263    }
264
265    /// Waits until the consumer has applied the startup replay target, including
266    /// target discovery for full replay. An undiscovered target is not an empty
267    /// database.
268    pub async fn replay_to_consumer_last_processed_commit_complete(&self) {
269        let target = self.wait_for_replay_target().await;
270        self.wait_for_handled(target).await;
271    }
272}
273
274#[cfg(test)]
275mod test {
276    use std::time::Duration;
277
278    use rstest::rstest;
279    use tokio::time::timeout;
280
281    use super::*;
282
283    #[tokio::test]
284    async fn test_consumer_monitor() {
285        let monitor = ConsumerMonitor::new(0, Some(10));
286        assert_eq!(monitor.highest_handled_commit(), 0);
287        monitor.set_highest_handled_commit(100);
288        assert_eq!(monitor.highest_handled_commit(), 100);
289        monitor
290            .replay_to_consumer_last_processed_commit_complete()
291            .await;
292    }
293
294    #[tokio::test]
295    async fn full_replay_waits_for_storage_and_for_the_consumer() {
296        let (args, _receiver) = CommitConsumerArgs::new_with_full_replay();
297        let monitor = args.monitor();
298        assert!(
299            timeout(
300                Duration::from_millis(20),
301                monitor.replay_to_consumer_last_processed_commit_complete()
302            )
303            .await
304            .is_err()
305        );
306        monitor.set_replay_target(5);
307        monitor.set_highest_handled_commit(4);
308        assert!(
309            timeout(
310                Duration::from_millis(20),
311                monitor.replay_to_consumer_last_processed_commit_complete()
312            )
313            .await
314            .is_err()
315        );
316        monitor.set_highest_handled_commit(5);
317        timeout(
318            Duration::from_secs(1),
319            monitor.replay_to_consumer_last_processed_commit_complete(),
320        )
321        .await
322        .unwrap();
323    }
324
325    #[rstest]
326    #[case(0)]
327    #[case(5)]
328    #[tokio::test]
329    async fn acknowledged_full_replay_waits_for_target_discovery(#[case] target: CommitIndex) {
330        let (args, _receiver) = CommitConsumerArgs::new_with_full_replay();
331        let monitor = args.monitor();
332        assert_eq!(monitor.replay_target(), None);
333        let ready = monitor.replay_to_consumer_last_processed_commit_complete();
334        tokio::pin!(ready);
335        assert!(futures::poll!(&mut ready).is_pending());
336
337        monitor.set_highest_handled_commit(target);
338        assert!(futures::poll!(&mut ready).is_pending());
339        monitor.set_replay_target(target);
340        timeout(Duration::from_secs(1), ready).await.unwrap();
341    }
342
343    #[rstest]
344    #[case::discovered_empty(true, 0)]
345    #[case::discovered_nonempty(true, 5)]
346    #[case::supplied_empty(false, 0)]
347    #[case::supplied_nonempty(false, 5)]
348    #[tokio::test]
349    #[should_panic(expected = "startup replay target must be set only once")]
350    async fn replay_target_cannot_be_set_twice(
351        #[case] full_replay: bool,
352        #[case] target: CommitIndex,
353    ) {
354        let (args, _receiver) = if full_replay {
355            CommitConsumerArgs::new_with_full_replay()
356        } else {
357            CommitConsumerArgs::new(0, target)
358        };
359        let monitor = args.monitor();
360        if full_replay {
361            monitor.set_replay_target(target);
362        }
363        assert_eq!(monitor.replay_target(), Some(target));
364        assert_eq!(monitor.wait_for_replay_target().await, target);
365        monitor.set_replay_target(target);
366    }
367
368    #[tokio::test]
369    async fn committed_handled_and_target_notifications_are_independent() {
370        let (args, _receiver) = CommitConsumerArgs::new_with_full_replay();
371        let monitor = args.monitor();
372        let mut committed = monitor.subscribe_progress();
373        let mut handled = monitor.subscribe_handled_commit();
374        let target = monitor.wait_for_replay_target();
375        tokio::pin!(target);
376        assert!(futures::poll!(&mut target).is_pending());
377
378        monitor.report_committed(20, 50);
379        timeout(Duration::from_secs(1), committed.changed())
380            .await
381            .unwrap()
382            .unwrap();
383        assert_eq!(
384            *committed.borrow_and_update(),
385            CommitProgress {
386                highest_committed_index: 20,
387                highest_committed_round: 50,
388            }
389        );
390        assert!(!handled.has_changed().unwrap());
391        assert!(futures::poll!(&mut target).is_pending());
392
393        monitor.set_highest_handled_commit(2);
394        timeout(Duration::from_secs(1), handled.changed())
395            .await
396            .unwrap()
397            .unwrap();
398        assert_eq!(*handled.borrow_and_update(), 2);
399        assert!(!committed.has_changed().unwrap());
400        assert!(futures::poll!(&mut target).is_pending());
401
402        monitor.set_replay_target(5);
403        assert_eq!(timeout(Duration::from_secs(1), target).await.unwrap(), 5);
404        assert!(!committed.has_changed().unwrap());
405        assert!(!handled.has_changed().unwrap());
406        assert_eq!(monitor.replay_target(), Some(5));
407        assert_eq!(monitor.highest_handled_commit(), 2);
408
409        monitor.report_committed(19, 49);
410        monitor.report_committed(20, 50);
411        assert!(!committed.has_changed().unwrap());
412        assert_eq!(monitor.progress(), *committed.borrow());
413    }
414
415    #[tokio::test]
416    async fn committed_head_advances_independently_of_a_stalled_consumer() {
417        let monitor = ConsumerMonitor::new(0, Some(0));
418        monitor.report_committed(20, 50);
419        monitor.set_highest_handled_commit(2);
420        monitor.report_committed(21, 52);
421        monitor.report_committed(19, 49);
422        assert_eq!(monitor.highest_handled_commit(), 2);
423        assert_eq!(monitor.progress().highest_committed_index, 21);
424        assert_eq!(monitor.progress().highest_committed_round, 52);
425    }
426
427    #[tokio::test]
428    async fn peer_progress_stores_latest_samples() {
429        let monitor = ConsumerMonitor::new(0, Some(0));
430        assert_eq!(monitor.peer_progress(), PeerProgress::default());
431        let committed = monitor.subscribe_progress();
432        let handled = monitor.subscribe_handled_commit();
433
434        monitor.report_probe(30, 7_500, 1_000);
435        monitor.report_quorum_commit_index(12);
436        assert_eq!(
437            monitor.peer_progress(),
438            PeerProgress {
439                quorum_accepted_round: 30,
440                quorum_commit_index: 12,
441                responsive_stake: 7_500,
442                probed_at_ms: 1_000,
443            }
444        );
445
446        // Lower values replace higher ones.
447        monitor.report_probe(20, 0, 2_000);
448        monitor.report_quorum_commit_index(3);
449        assert_eq!(
450            monitor.peer_progress(),
451            PeerProgress {
452                quorum_accepted_round: 20,
453                quorum_commit_index: 3,
454                responsive_stake: 0,
455                probed_at_ms: 2_000,
456            }
457        );
458
459        // Peer progress does not notify the committed head or handled commit subscribers.
460        assert!(!committed.has_changed().unwrap());
461        assert!(!handled.has_changed().unwrap());
462    }
463}