1use 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#[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 FromWatermark {
27 replay_after_commit_index: CommitIndex,
30 consumer_last_processed_commit_index: CommitIndex,
32 },
33 FullEpochPaced,
37}
38
39impl CommitConsumerArgs {
40 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct CommitProgress {
116 pub highest_committed_index: CommitIndex,
120 pub highest_committed_round: Round,
123}
124
125#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
132pub struct PeerProgress {
133 pub quorum_accepted_round: Round,
136 pub quorum_commit_index: CommitIndex,
138 pub responsive_stake: Stake,
141 pub probed_at_ms: u64,
144}
145
146pub 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 pub fn progress(&self) -> CommitProgress {
179 *self.committed.borrow()
180 }
181
182 pub fn subscribe_progress(&self) -> watch::Receiver<CommitProgress> {
186 self.committed.subscribe()
187 }
188
189 pub fn replay_target(&self) -> Option<CommitIndex> {
194 self.replay_target.get().copied()
195 }
196
197 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 pub fn subscribe_handled_commit(&self) -> watch::Receiver<CommitIndex> {
225 self.handled.subscribe()
226 }
227
228 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 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 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 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 assert!(!committed.has_changed().unwrap());
461 assert!(!handled.has_changed().unwrap());
462 }
463}