Skip to main content

sui_indexer_alt_framework/pipeline/concurrent/
collector.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::collections::BTreeMap;
5use std::sync::Arc;
6use std::sync::atomic::AtomicU64;
7use std::sync::atomic::Ordering;
8
9use sui_futures::service::Service;
10use tokio::sync::SetOnce;
11use tokio::sync::mpsc;
12use tracing::debug;
13use tracing::info;
14
15use crate::metrics::CheckpointLagMetricReporter;
16use crate::metrics::IndexerMetrics;
17use crate::pipeline::CommitterConfig;
18use crate::pipeline::IndexedCheckpoint;
19use crate::pipeline::WatermarkPart;
20use crate::pipeline::batch_floor::BatchFloor;
21use crate::pipeline::concurrent::BatchStatus;
22use crate::pipeline::concurrent::BatchedRows;
23use crate::pipeline::concurrent::Handler;
24
25/// Processed values that are waiting to be written to the database. This is an internal type used
26/// by the concurrent collector to hold data it is waiting to send to the committer.
27struct PendingCheckpoint<H: Handler> {
28    /// Iterator over values to be inserted into the database from this checkpoint
29    values: std::vec::IntoIter<H::Value>,
30    /// The watermark associated with this checkpoint and the part of it that is left to commit
31    watermark: WatermarkPart,
32}
33
34impl<H: Handler> PendingCheckpoint<H> {
35    /// Whether there are values left to commit from this indexed checkpoint.
36    fn is_empty(&self) -> bool {
37        let empty = self.values.len() == 0;
38        debug_assert!(!empty || self.watermark.batch_rows == 0);
39        empty
40    }
41}
42
43impl<H: Handler> From<IndexedCheckpoint<H>> for PendingCheckpoint<H> {
44    fn from(indexed: IndexedCheckpoint<H>) -> Self {
45        let total_rows = indexed.values.len();
46        Self {
47            watermark: WatermarkPart {
48                watermark: indexed.watermark,
49                batch_rows: total_rows,
50                total_rows,
51            },
52            values: indexed.values.into_iter(),
53        }
54    }
55}
56
57/// The collector task is responsible for gathering rows into batches which it then sends to a
58/// committer task to write to the database:
59///
60/// - Whenever rows are pending and the committer has room for another batch (its input channel
61///   has a free slot), the collector cuts the pending rows into a batch and sends it. While the
62///   committer is busy, rows keep accumulating, so batches grow under back-pressure. A batch also
63///   ends when the handler reports it as ready, or when it holds `max_watermark_updates`
64///   checkpoints; whatever is left goes into the next batch.
65///
66/// - If `config.min_batch_rows` is set, rows are only cut into a batch once that many are pending,
67///   or once rows have been pending for `config.max_batch_delay()`.
68///
69/// - When the processor closes its channel, everything still pending is written out.
70///
71/// The `main_reader_lo` tracks the lowest checkpoint that can be committed by this pipeline.
72///
73/// This task will shutdown if any of its channels are closed.
74pub(super) fn collector<H: Handler>(
75    handler: Arc<H>,
76    config: CommitterConfig,
77    mut rx: mpsc::Receiver<IndexedCheckpoint<H>>,
78    tx: mpsc::Sender<BatchedRows<H>>,
79    main_reader_lo: Arc<SetOnce<AtomicU64>>,
80    metrics: Arc<IndexerMetrics>,
81    max_pending_rows: usize,
82    max_watermark_updates: usize,
83) -> Service {
84    Service::new().spawn_aborting(async move {
85        let checkpoint_lag_reporter = CheckpointLagMetricReporter::new_for_pipeline::<H>(
86            &metrics.collected_checkpoint_timestamp_lag,
87            &metrics.latest_collected_checkpoint_timestamp_lag_ms,
88            &metrics.latest_collected_checkpoint,
89        );
90
91        // Data for checkpoints that are ready to be sent but haven't been written yet.
92        let mut pending: BTreeMap<u64, PendingCheckpoint<H>> = BTreeMap::new();
93        let mut pending_rows = 0;
94        let mut floor = BatchFloor::new(&config);
95
96        info!(pipeline = H::NAME, "Starting collector");
97
98        // Wait for main_reader_lo to be initialized before processing any checkpoints.
99        let reader_lo_atomic = main_reader_lo.wait().await;
100
101        loop {
102            let batch_due = floor.is_reached(pending_rows);
103
104            tokio::select! {
105                biased;
106
107                permit = tx.reserve(), if batch_due => {
108                    let Ok(permit) = permit else {
109                        info!(
110                            pipeline = H::NAME,
111                            "Committer closed channel, stopping collector"
112                        );
113                        return Ok(());
114                    };
115
116                    let batched_rows = gather_batch(
117                        &*handler,
118                        &mut pending,
119                        &mut pending_rows,
120                        max_watermark_updates,
121                        &checkpoint_lag_reporter,
122                        &metrics,
123                    );
124                    permit.send(batched_rows);
125                    floor.set_pending(!pending.is_empty());
126                }
127
128                // docs::#collector (see https://docs.sui.io/develop/accessing-data/custom-indexer/custom-indexers)
129                received = rx.recv(), if pending_rows < max_pending_rows => {
130                    // The processor has stopped, so write out everything that is left.
131                    let Some(mut indexed) = received else {
132                        break;
133                    };
134
135                    let reader_lo = reader_lo_atomic.load(Ordering::Relaxed);
136
137                    metrics
138                        .collector_reader_lo
139                        .with_label_values(&[H::NAME])
140                        .set(reader_lo as i64);
141
142                    let mut recv_cps = 0usize;
143                    let mut recv_rows = 0usize;
144                    loop {
145                        if indexed.checkpoint() < reader_lo {
146                            indexed.values.clear();
147                            metrics
148                                .total_collector_skipped_checkpoints
149                                .with_label_values(&[H::NAME])
150                                .inc();
151                        }
152
153                        recv_cps += 1;
154                        recv_rows += indexed.len();
155                        pending_rows += indexed.len();
156                        pending.insert(indexed.checkpoint(), indexed.into());
157
158                        if pending_rows >= max_pending_rows {
159                            break;
160                        }
161
162                        match rx.try_recv() {
163                            Ok(next) => indexed = next,
164                            Err(_) => break,
165                        }
166                    }
167
168                    metrics
169                        .total_collector_rows_received
170                        .with_label_values(&[H::NAME])
171                        .inc_by(recv_rows as u64);
172                    metrics
173                        .total_collector_checkpoints_received
174                        .with_label_values(&[H::NAME])
175                        .inc_by(recv_cps as u64);
176
177                    floor.set_pending(true);
178                }
179                // docs::/#collector
180
181                () = floor.delay_elapsed(), if !batch_due => {}
182            }
183        }
184
185        while !pending.is_empty() {
186            let batched_rows = gather_batch(
187                &*handler,
188                &mut pending,
189                &mut pending_rows,
190                max_watermark_updates,
191                &checkpoint_lag_reporter,
192                &metrics,
193            );
194            if tx.send(batched_rows).await.is_err() {
195                info!(
196                    pipeline = H::NAME,
197                    "Committer closed channel, stopping collector"
198                );
199                return Ok(());
200            }
201        }
202
203        info!(
204            pipeline = H::NAME,
205            "Processor closed channel, pending rows empty, stopping collector",
206        );
207
208        Ok(())
209    })
210}
211
212/// Cut the next batch out of `pending`, taking checkpoints in order until the handler reports the
213/// batch as ready or it holds `max_watermark_updates` watermarks.
214fn gather_batch<H: Handler>(
215    handler: &H,
216    pending: &mut BTreeMap<u64, PendingCheckpoint<H>>,
217    pending_rows: &mut usize,
218    max_watermark_updates: usize,
219    checkpoint_lag_reporter: &CheckpointLagMetricReporter,
220    metrics: &IndexerMetrics,
221) -> BatchedRows<H> {
222    let guard = metrics
223        .collector_gather_latency
224        .with_label_values(&[H::NAME])
225        .start_timer();
226
227    let mut batch = H::Batch::default();
228    let mut watermark = Vec::new();
229    let mut batch_len = 0;
230
231    while let Some(mut entry) = pending.first_entry() {
232        if watermark.len() >= max_watermark_updates {
233            break;
234        }
235
236        let indexed = entry.get_mut();
237        let before = indexed.values.len();
238        let status = handler.batch(&mut batch, &mut indexed.values);
239        let taken = before - indexed.values.len();
240
241        batch_len += taken;
242        watermark.push(indexed.watermark.take(taken));
243        if indexed.is_empty() {
244            checkpoint_lag_reporter.report_lag(
245                indexed.watermark.checkpoint(),
246                indexed.watermark.timestamp_ms(),
247            );
248            entry.remove();
249        }
250
251        if status == BatchStatus::Ready {
252            break;
253        }
254    }
255
256    let elapsed = guard.stop_and_record();
257    debug!(
258        pipeline = H::NAME,
259        elapsed_ms = elapsed * 1000.0,
260        rows = batch_len,
261        "Gathered batch",
262    );
263
264    metrics
265        .total_collector_batches_created
266        .with_label_values(&[H::NAME])
267        .inc();
268
269    metrics
270        .collector_batch_size
271        .with_label_values(&[H::NAME])
272        .observe(batch_len as f64);
273
274    *pending_rows -= batch_len;
275
276    BatchedRows {
277        batch,
278        batch_len,
279        watermark,
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use std::time::Duration;
286
287    use async_trait::async_trait;
288    use tokio::sync::mpsc;
289
290    use crate::metrics::tests::test_metrics;
291    use crate::mocks::store::FallibleMockConnection;
292    use crate::mocks::store::FallibleMockStore;
293    use crate::pipeline::Processor;
294    use crate::pipeline::concurrent::BatchStatus;
295    use crate::types::full_checkpoint_content::Checkpoint;
296
297    use super::*;
298
299    #[derive(Clone)]
300    struct Entry;
301
302    struct TestHandler;
303
304    // Max chunk rows for testing - simulates postgres bind parameter limit
305    const TEST_MAX_CHUNK_ROWS: usize = 1024;
306
307    #[async_trait]
308    impl Processor for TestHandler {
309        type Value = Entry;
310        const NAME: &'static str = "test_handler";
311
312        async fn process(&self, _checkpoint: &Arc<Checkpoint>) -> anyhow::Result<Vec<Self::Value>> {
313            Ok(vec![])
314        }
315    }
316
317    #[async_trait]
318    impl Handler for TestHandler {
319        type Store = FallibleMockStore;
320        type Batch = Vec<Entry>;
321
322        const MAX_PENDING_ROWS: usize = 10000;
323
324        fn batch(
325            &self,
326            batch: &mut Self::Batch,
327            values: &mut std::vec::IntoIter<Self::Value>,
328        ) -> BatchStatus {
329            // Simulate batch size limit
330            let remaining_capacity = TEST_MAX_CHUNK_ROWS.saturating_sub(batch.len());
331            let to_take = remaining_capacity.min(values.len());
332            batch.extend(values.take(to_take));
333
334            if batch.len() >= TEST_MAX_CHUNK_ROWS {
335                BatchStatus::Ready
336            } else {
337                BatchStatus::Pending
338            }
339        }
340
341        async fn commit<'a>(
342            &self,
343            _batch: &Self::Batch,
344            _conn: &mut FallibleMockConnection<'a>,
345        ) -> anyhow::Result<usize> {
346            tokio::time::sleep(Duration::from_millis(1000)).await;
347            Ok(0)
348        }
349    }
350
351    /// Start a collector whose committer channel holds `collector_channel_size` batches.
352    fn spawn_collector(
353        config: CommitterConfig,
354        collector_channel_size: usize,
355    ) -> (
356        mpsc::Sender<IndexedCheckpoint<TestHandler>>,
357        mpsc::Receiver<BatchedRows<TestHandler>>,
358        Service,
359    ) {
360        let (processor_tx, processor_rx) = mpsc::channel(10);
361        let (collector_tx, collector_rx) = mpsc::channel(collector_channel_size);
362        let main_reader_lo = Arc::new(SetOnce::new_with(Some(AtomicU64::new(0))));
363
364        let service = collector::<TestHandler>(
365            Arc::new(TestHandler),
366            config,
367            processor_rx,
368            collector_tx,
369            main_reader_lo,
370            test_metrics(),
371            TestHandler::MAX_PENDING_ROWS,
372            TestHandler::MAX_WATERMARK_UPDATES,
373        );
374
375        (processor_tx, collector_rx, service)
376    }
377
378    /// Configuration that holds rows until `min_batch_rows` are pending, or for at most
379    /// `max_batch_delay_ms`.
380    fn min_batch_config(min_batch_rows: usize, max_batch_delay_ms: u64) -> CommitterConfig {
381        CommitterConfig {
382            min_batch_rows,
383            max_batch_delay_ms,
384            ..CommitterConfig::default()
385        }
386    }
387
388    /// Wait for a timeout on the channel, expecting this operation to timeout.
389    async fn expect_timeout<H: Handler>(
390        rx: &mut mpsc::Receiver<BatchedRows<H>>,
391        duration: Duration,
392    ) {
393        match tokio::time::timeout(duration, rx.recv()).await {
394            Err(_) => (), // Expected timeout - test passes
395            Ok(_) => panic!("Expected timeout but received data instead"),
396        }
397    }
398
399    /// Receive from the channel with a given timeout, panicking if the timeout is reached or the
400    /// channel is closed.
401    async fn recv_with_timeout<H: Handler>(
402        rx: &mut mpsc::Receiver<BatchedRows<H>>,
403        timeout: Duration,
404    ) -> BatchedRows<H> {
405        match tokio::time::timeout(timeout, rx.recv()).await {
406            Ok(Some(batch)) => batch,
407            Ok(None) => panic!("Collector channel was closed unexpectedly"),
408            Err(_) => panic!("Test timed out waiting for batch from collector"),
409        }
410    }
411
412    #[tokio::test]
413    async fn test_collector_batches_data() {
414        let (processor_tx, mut collector_rx, _collector) =
415            spawn_collector(CommitterConfig::default(), 10);
416
417        let part1_length = TEST_MAX_CHUNK_ROWS / 2;
418        let part2_length = TEST_MAX_CHUNK_ROWS - part1_length - 1;
419
420        // Send test data
421        let test_data = vec![
422            IndexedCheckpoint::new(0, 1, 10, 1000, vec![Entry; part1_length]),
423            IndexedCheckpoint::new(0, 2, 20, 2000, vec![Entry; part2_length]),
424            IndexedCheckpoint::new(0, 3, 30, 3000, vec![Entry, Entry]),
425        ];
426
427        for data in test_data {
428            processor_tx.send(data).await.unwrap();
429        }
430
431        let batch1 = recv_with_timeout(&mut collector_rx, Duration::from_secs(1)).await;
432        assert_eq!(batch1.batch_len, TEST_MAX_CHUNK_ROWS);
433
434        let batch2 = recv_with_timeout(&mut collector_rx, Duration::from_secs(1)).await;
435        assert_eq!(batch2.batch_len, 1);
436    }
437
438    #[tokio::test]
439    async fn test_collector_shutdown() {
440        let (processor_tx, mut collector_rx, mut collector) =
441            spawn_collector(CommitterConfig::default(), 10);
442
443        processor_tx
444            .send(IndexedCheckpoint::new(0, 1, 10, 1000, vec![Entry, Entry]))
445            .await
446            .unwrap();
447
448        tokio::time::sleep(Duration::from_millis(200)).await;
449
450        let batch = recv_with_timeout(&mut collector_rx, Duration::from_secs(1)).await;
451        assert_eq!(batch.batch_len, 2);
452
453        // Drop processor sender to simulate shutdown
454        drop(processor_tx);
455
456        // After a short delay, collector should shut down
457        tokio::time::timeout(Duration::from_millis(500), collector.join())
458            .await
459            .expect("collector shutdown timeout")
460            .expect("collector shutdown failed");
461    }
462
463    #[tokio::test]
464    async fn test_collector_respects_max_pending() {
465        let processor_channel_size = 5; // unit is checkpoint
466        let collector_channel_size = 2; // unit is batch, aka rows / MAX_CHUNK_ROWS
467        let (processor_tx, processor_rx) = mpsc::channel(processor_channel_size);
468        let (collector_tx, _collector_rx) = mpsc::channel(collector_channel_size);
469        let main_reader_lo = Arc::new(SetOnce::new_with(Some(AtomicU64::new(0))));
470
471        let metrics = test_metrics();
472
473        let handler = Arc::new(TestHandler);
474        let _collector = collector::<TestHandler>(
475            handler,
476            CommitterConfig::default(),
477            processor_rx,
478            collector_tx,
479            main_reader_lo.clone(),
480            metrics.clone(),
481            TestHandler::MAX_PENDING_ROWS,
482            TestHandler::MAX_WATERMARK_UPDATES,
483        );
484
485        // Send more data than MAX_PENDING_ROWS plus collector channel buffer
486        let data = IndexedCheckpoint::new(
487            0,
488            1,
489            10,
490            1000,
491            vec![
492                Entry;
493                // Decreasing this number by even 1 would make the test fail.
494                TestHandler::MAX_PENDING_ROWS
495                    + TEST_MAX_CHUNK_ROWS * collector_channel_size
496            ],
497        );
498        processor_tx.send(data).await.unwrap();
499
500        tokio::time::sleep(Duration::from_millis(200)).await;
501
502        // Now fill up the processor channel with minimum data to trigger send blocking
503        for _ in 0..processor_channel_size {
504            let more_data = IndexedCheckpoint::new(0, 2, 11, 1000, vec![Entry]);
505            processor_tx.send(more_data).await.unwrap();
506        }
507
508        // Now sending even more data should block because of MAX_PENDING_ROWS limit.
509        let even_more_data = IndexedCheckpoint::new(0, 3, 12, 1000, vec![Entry]);
510
511        let send_result = processor_tx.try_send(even_more_data);
512        assert!(matches!(
513            send_result,
514            Err(mpsc::error::TrySendError::Full(_))
515        ));
516    }
517
518    /// A checkpoint is cut into a batch as soon as the committer has room, and checkpoints that
519    /// arrive while it has none are gathered into the next batch together.
520    #[tokio::test(start_paused = true)]
521    async fn test_collector_writes_as_soon_as_the_committer_has_room() {
522        let (processor_tx, mut collector_rx, _collector) =
523            spawn_collector(CommitterConfig::default(), 1);
524
525        processor_tx
526            .send(IndexedCheckpoint::new(0, 1, 10, 1000, vec![Entry]))
527            .await
528            .unwrap();
529        tokio::time::sleep(Duration::from_millis(10)).await;
530
531        // The first batch now fills the committer's channel, so these have to wait.
532        for cp in 2..=4 {
533            processor_tx
534                .send(IndexedCheckpoint::new(0, cp, 10, 1000, vec![Entry]))
535                .await
536                .unwrap();
537        }
538        tokio::time::sleep(Duration::from_millis(10)).await;
539
540        let batch = recv_with_timeout(&mut collector_rx, Duration::from_secs(1)).await;
541        assert_eq!(batch.batch_len, 1);
542        assert_eq!(batch.watermark.len(), 1);
543
544        let batch = recv_with_timeout(&mut collector_rx, Duration::from_secs(1)).await;
545        assert_eq!(batch.batch_len, 3);
546        assert_eq!(batch.watermark.len(), 3);
547    }
548
549    /// Checkpoints without rows still reach the committer, so the watermark can advance past them.
550    #[tokio::test(start_paused = true)]
551    async fn test_collector_writes_checkpoints_without_rows() {
552        let (processor_tx, mut collector_rx, _collector) =
553            spawn_collector(CommitterConfig::default(), 10);
554
555        processor_tx
556            .send(IndexedCheckpoint::new(0, 1, 10, 1000, vec![]))
557            .await
558            .unwrap();
559
560        let batch = recv_with_timeout(&mut collector_rx, Duration::from_secs(1)).await;
561        assert_eq!(batch.batch_len, 0);
562        assert_eq!(batch.watermark.len(), 1);
563    }
564
565    #[tokio::test(start_paused = true)]
566    async fn test_collector_holds_rows_until_min_batch_rows() {
567        let (processor_tx, mut collector_rx, _collector) =
568            spawn_collector(min_batch_config(10, 60_000), 10);
569
570        processor_tx
571            .send(IndexedCheckpoint::new(0, 1, 10, 1000, vec![Entry; 9]))
572            .await
573            .unwrap();
574        expect_timeout(&mut collector_rx, Duration::from_secs(1)).await;
575
576        processor_tx
577            .send(IndexedCheckpoint::new(0, 2, 20, 2000, vec![Entry]))
578            .await
579            .unwrap();
580
581        let batch = recv_with_timeout(&mut collector_rx, Duration::from_millis(100)).await;
582        assert_eq!(batch.batch_len, 10);
583        assert_eq!(batch.watermark.len(), 2);
584    }
585
586    #[tokio::test(start_paused = true)]
587    async fn test_collector_writes_rows_below_min_batch_rows_after_max_batch_delay() {
588        let (processor_tx, mut collector_rx, _collector) =
589            spawn_collector(min_batch_config(10, 3000), 10);
590
591        processor_tx
592            .send(IndexedCheckpoint::new(0, 1, 10, 1000, vec![Entry; 9]))
593            .await
594            .unwrap();
595        expect_timeout(&mut collector_rx, Duration::from_secs(2)).await;
596
597        let batch = recv_with_timeout(&mut collector_rx, Duration::from_secs(2)).await;
598        assert_eq!(batch.batch_len, 9);
599    }
600
601    #[tokio::test(start_paused = true)]
602    async fn test_collector_writes_rows_below_min_batch_rows_on_shutdown() {
603        let (processor_tx, mut collector_rx, mut collector) =
604            spawn_collector(min_batch_config(100, 60_000), 10);
605
606        processor_tx
607            .send(IndexedCheckpoint::new(0, 1, 10, 1000, vec![Entry; 5]))
608            .await
609            .unwrap();
610        drop(processor_tx);
611
612        let batch = recv_with_timeout(&mut collector_rx, Duration::from_secs(1)).await;
613        assert_eq!(batch.batch_len, 5);
614
615        tokio::time::timeout(Duration::from_secs(1), collector.join())
616            .await
617            .expect("collector shutdown timeout")
618            .expect("collector shutdown failed");
619    }
620
621    /// The collector must wait for `main_reader_lo` to be initialized before attempting to prepare
622    /// checkpoints for commit.
623    #[tokio::test(start_paused = true)]
624    async fn test_collector_waits_for_main_reader_lo_init() {
625        let (processor_tx, processor_rx) = mpsc::channel(10);
626        let (collector_tx, mut collector_rx) = mpsc::channel(10);
627        let main_reader_lo = Arc::new(SetOnce::new());
628
629        let handler = Arc::new(TestHandler);
630        let collector = collector(
631            handler,
632            CommitterConfig::default(),
633            processor_rx,
634            collector_tx,
635            main_reader_lo.clone(),
636            test_metrics(),
637            TestHandler::MAX_PENDING_ROWS,
638            TestHandler::MAX_WATERMARK_UPDATES,
639        );
640
641        let test_data = IndexedCheckpoint::new(0, 1, 10, 1000, vec![Entry; 11]);
642        processor_tx.send(test_data).await.unwrap();
643
644        // Advance time significantly - collector should still be blocked waiting for
645        // main_reader_lo.
646        tokio::time::advance(Duration::from_secs(100)).await;
647
648        assert!(collector_rx.try_recv().is_err());
649
650        // Now initialize the main reader lo to 0, unblocking the collector.
651        main_reader_lo.set(AtomicU64::new(0)).ok();
652
653        tokio::time::advance(Duration::from_secs(1)).await;
654
655        let batch = recv_with_timeout(&mut collector_rx, Duration::from_secs(2)).await;
656
657        assert_eq!(batch.batch_len, 11);
658
659        collector.shutdown().await.unwrap();
660    }
661
662    /// When receiving checkpoints, if they are below the main reader lo, they should be dropped
663    /// immediately.
664    #[tokio::test]
665    async fn test_collector_drops_checkpoints_immediately_if_le_main_reader_lo() {
666        let (processor_tx, processor_rx) = mpsc::channel(10);
667        let (collector_tx, mut collector_rx) = mpsc::channel(10);
668        let main_reader_lo = Arc::new(SetOnce::new_with(Some(AtomicU64::new(5))));
669        let metrics = test_metrics();
670
671        let collector = collector(
672            Arc::new(TestHandler),
673            CommitterConfig::default(),
674            processor_rx,
675            collector_tx,
676            main_reader_lo.clone(),
677            metrics.clone(),
678            TestHandler::MAX_PENDING_ROWS,
679            TestHandler::MAX_WATERMARK_UPDATES,
680        );
681
682        let rows_per_checkpoint = 11;
683
684        let test_data: Vec<_> = [1, 5, 2, 6, 4, 3]
685            .into_iter()
686            .map(|cp| IndexedCheckpoint::new(0, cp, 10, 1000, vec![Entry; rows_per_checkpoint]))
687            .collect();
688        for data in test_data {
689            processor_tx.send(data).await.unwrap();
690        }
691        let batch = recv_with_timeout(&mut collector_rx, Duration::from_secs(2)).await;
692
693        // Make sure that we are advancing watermarks.
694        assert_eq!(batch.watermark.len(), 6);
695        // And reporting the checkpoints as received.
696        assert_eq!(
697            metrics
698                .total_collector_checkpoints_received
699                .with_label_values(&[TestHandler::NAME])
700                .get(),
701            6
702        );
703        // But the collector should filter out four checkpoints: (1, 2, 3, 4)
704        assert_eq!(
705            metrics
706                .total_collector_skipped_checkpoints
707                .with_label_values(&[TestHandler::NAME])
708                .get(),
709            4
710        );
711        // And that we only have values from two checkpoints (5, 6)
712        assert_eq!(batch.batch_len, rows_per_checkpoint * 2);
713
714        collector.shutdown().await.unwrap();
715    }
716
717    /// Because a checkpoint may be partially batched before the main reader lo advances past it,
718    /// the collector must ensure that it fully writes out the checkpoint. Otherwise, this will
719    /// essentially stall the commit_watermark task indefinitely as the latter waits for the
720    /// remaining checkpoint parts.
721    #[tokio::test(start_paused = true)]
722    async fn test_collector_only_filters_whole_checkpoints() {
723        let (processor_tx, processor_rx) = mpsc::channel(10);
724        let (collector_tx, mut collector_rx) = mpsc::channel(10);
725        let main_reader_lo = Arc::new(SetOnce::new_with(Some(AtomicU64::new(0))));
726
727        let metrics = test_metrics();
728
729        let collector = collector(
730            Arc::new(TestHandler),
731            CommitterConfig::default(),
732            processor_rx,
733            collector_tx,
734            main_reader_lo.clone(),
735            metrics.clone(),
736            TestHandler::MAX_PENDING_ROWS,
737            TestHandler::MAX_WATERMARK_UPDATES,
738        );
739
740        let more_than_max_chunk_rows = TEST_MAX_CHUNK_ROWS + 10;
741
742        let test_data =
743            IndexedCheckpoint::new(0, 1, 10, 1000, vec![Entry; more_than_max_chunk_rows]);
744        processor_tx.send(test_data).await.unwrap();
745        tokio::time::advance(Duration::from_secs(1)).await;
746        let batch = recv_with_timeout(&mut collector_rx, Duration::from_secs(2)).await;
747
748        // There are still 10 rows left to be sent in the next batch.
749        assert_eq!(batch.batch_len, TEST_MAX_CHUNK_ROWS);
750
751        // Send indexed checkpoints 2 through 5 inclusive, but also bump the main reader lo to 4.
752        let test_data: Vec<_> = (2..=5)
753            .map(|cp| IndexedCheckpoint::new(0, cp, 10, 1000, vec![Entry; 11]))
754            .collect();
755        for data in test_data {
756            processor_tx.send(data).await.unwrap();
757        }
758        let atomic = main_reader_lo.get().unwrap();
759        atomic.store(4, Ordering::Relaxed);
760        tokio::time::advance(Duration::from_secs(10)).await;
761
762        let batch = recv_with_timeout(&mut collector_rx, Duration::from_secs(2)).await;
763
764        // The next batch should still be the remaining 10 rows from checkpoint 1.
765        assert_eq!(batch.batch_len, 10);
766        assert_eq!(batch.watermark[0].watermark.checkpoint_hi_inclusive, 1);
767
768        recv_with_timeout(&mut collector_rx, Duration::from_secs(2)).await;
769
770        assert_eq!(
771            metrics
772                .total_collector_skipped_checkpoints
773                .with_label_values(&[TestHandler::NAME])
774                .get(),
775            2
776        );
777        assert_eq!(
778            metrics
779                .total_collector_checkpoints_received
780                .with_label_values(&[TestHandler::NAME])
781                .get(),
782            5
783        );
784
785        collector.shutdown().await.unwrap();
786    }
787}