Skip to main content

mito2/read/
flat_dedup.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Dedup implementation for flat format.
16
17use std::ops::Range;
18use std::sync::Arc;
19use std::time::Instant;
20
21use api::v1::OpType;
22use async_stream::try_stream;
23use common_telemetry::debug;
24use datatypes::arrow::array::{
25    Array, ArrayRef, BinaryArray, BooleanArray, BooleanBufferBuilder, UInt8Array, UInt64Array,
26    make_comparator,
27};
28use datatypes::arrow::buffer::BooleanBuffer;
29use datatypes::arrow::compute::kernels::cmp::distinct;
30use datatypes::arrow::compute::kernels::partition::{Partitions, partition};
31use datatypes::arrow::compute::kernels::take::take;
32use datatypes::arrow::compute::{
33    SortOptions, TakeOptions, concat_batches, filter_record_batch, take_record_batch,
34};
35use datatypes::arrow::error::ArrowError;
36use datatypes::arrow::record_batch::RecordBatch;
37use futures::{Stream, TryStreamExt};
38use snafu::ResultExt;
39
40use crate::error::{ComputeArrowSnafu, NewRecordBatchSnafu, Result};
41use crate::metrics::MERGE_FILTER_ROWS_TOTAL;
42use crate::read::dedup::{DedupMetrics, DedupMetricsReport};
43use crate::read::timestamp_array_to_i64_slice;
44use crate::sst::parquet::flat_format::{
45    op_type_column_index, primary_key_column_index, time_index_column_index,
46};
47use crate::sst::parquet::format::{FIXED_POS_COLUMN_NUM, PrimaryKeyArray};
48
49/// An iterator to dedup sorted batches from an iterator based on the dedup strategy.
50pub struct FlatDedupIterator<I, S> {
51    iter: I,
52    strategy: S,
53    metrics: DedupMetrics,
54}
55
56impl<I, S> FlatDedupIterator<I, S> {
57    /// Creates a new dedup iterator.
58    pub fn new(iter: I, strategy: S) -> Self {
59        Self {
60            iter,
61            strategy,
62            metrics: DedupMetrics::default(),
63        }
64    }
65}
66
67impl<I: Iterator<Item = Result<RecordBatch>>, S: RecordBatchDedupStrategy> FlatDedupIterator<I, S> {
68    /// Returns the next deduplicated batch.
69    fn fetch_next_batch(&mut self) -> Result<Option<RecordBatch>> {
70        while let Some(batch) = self.iter.next().transpose()? {
71            if let Some(batch) = self.strategy.push_batch(batch, &mut self.metrics)? {
72                return Ok(Some(batch));
73            }
74        }
75
76        self.strategy.finish(&mut self.metrics)
77    }
78}
79
80impl<I: Iterator<Item = Result<RecordBatch>>, S: RecordBatchDedupStrategy> Iterator
81    for FlatDedupIterator<I, S>
82{
83    type Item = Result<RecordBatch>;
84
85    fn next(&mut self) -> Option<Self::Item> {
86        self.fetch_next_batch().transpose()
87    }
88}
89
90/// An async reader to dedup sorted record batches from a stream based on the dedup strategy.
91pub struct FlatDedupReader<I, S> {
92    stream: I,
93    strategy: S,
94    metrics: DedupMetrics,
95    /// Optional metrics reporter.
96    metrics_reporter: Option<Arc<dyn DedupMetricsReport>>,
97}
98
99impl<I, S> FlatDedupReader<I, S> {
100    /// Creates a new dedup reader.
101    pub fn new(
102        stream: I,
103        strategy: S,
104        metrics_reporter: Option<Arc<dyn DedupMetricsReport>>,
105    ) -> Self {
106        Self {
107            stream,
108            strategy,
109            metrics: DedupMetrics::default(),
110            metrics_reporter,
111        }
112    }
113}
114
115impl<I: Stream<Item = Result<RecordBatch>> + Unpin, S: RecordBatchDedupStrategy>
116    FlatDedupReader<I, S>
117{
118    /// Returns the next deduplicated batch.
119    async fn fetch_next_batch(&mut self) -> Result<Option<RecordBatch>> {
120        while let Some(batch) = self.stream.try_next().await? {
121            if let Some(batch) = self.strategy.push_batch(batch, &mut self.metrics)? {
122                self.metrics.maybe_report(&self.metrics_reporter);
123                return Ok(Some(batch));
124            }
125        }
126
127        let result = self.strategy.finish(&mut self.metrics)?;
128        self.metrics.maybe_report(&self.metrics_reporter);
129        Ok(result)
130    }
131
132    /// Converts the reader into a stream.
133    pub fn into_stream(mut self) -> impl Stream<Item = Result<RecordBatch>> {
134        try_stream! {
135            while let Some(batch) = self.fetch_next_batch().await? {
136                yield batch;
137            }
138        }
139    }
140}
141
142impl<I, S> Drop for FlatDedupReader<I, S> {
143    fn drop(&mut self) {
144        debug!("Flat dedup reader finished, metrics: {:?}", self.metrics);
145
146        MERGE_FILTER_ROWS_TOTAL
147            .with_label_values(&["dedup"])
148            .inc_by(self.metrics.num_unselected_rows as u64);
149        MERGE_FILTER_ROWS_TOTAL
150            .with_label_values(&["delete"])
151            .inc_by(self.metrics.num_deleted_rows as u64);
152
153        // Report any remaining metrics.
154        if let Some(reporter) = &self.metrics_reporter {
155            reporter.report(&mut self.metrics);
156        }
157    }
158}
159
160/// Strategy to remove duplicate rows from sorted record batches.
161pub trait RecordBatchDedupStrategy: Send {
162    /// Pushes a batch to the dedup strategy.
163    /// Returns rows that no longer need to be updated by subsequent input.
164    /// A strategy for partial merges may retain duplicates separated by Deletes.
165    fn push_batch(
166        &mut self,
167        batch: RecordBatch,
168        metrics: &mut DedupMetrics,
169    ) -> Result<Option<RecordBatch>>;
170
171    /// Finishes the deduplication process and returns any remaining batch.
172    ///
173    /// Users must ensure that `push_batch` is called for all batches before
174    /// calling this method.
175    fn finish(&mut self, metrics: &mut DedupMetrics) -> Result<Option<RecordBatch>>;
176}
177
178/// Dedup strategy that keeps the row with latest sequence of each key.
179pub struct FlatLastRow {
180    /// Meta of the last row in the previous batch that has the same key
181    /// as the batch to push.
182    prev_batch: Option<BatchLastRow>,
183    /// Filter deleted rows.
184    filter_deleted: bool,
185}
186
187impl FlatLastRow {
188    /// Creates a new strategy with the given `filter_deleted` flag.
189    pub fn new(filter_deleted: bool) -> Self {
190        Self {
191            prev_batch: None,
192            filter_deleted,
193        }
194    }
195
196    /// Remove duplications from the batch without considering previous rows.
197    fn dedup_one_batch(batch: RecordBatch) -> Result<RecordBatch> {
198        let num_rows = batch.num_rows();
199        if num_rows < 2 {
200            return Ok(batch);
201        }
202
203        let num_columns = batch.num_columns();
204        let timestamps = batch.column(time_index_column_index(num_columns));
205        // Checks duplications based on the timestamp.
206        let mask = find_boundaries(timestamps).context(ComputeArrowSnafu)?;
207        if mask.count_set_bits() == num_rows - 1 {
208            // Fast path: No duplication.
209            return Ok(batch);
210        }
211
212        // The batch has duplicated timestamps, but it doesn't mean it must
213        // has duplicated rows.
214        // Partitions the batch by the primary key and time index.
215        let columns: Vec<_> = [
216            primary_key_column_index(num_columns),
217            time_index_column_index(num_columns),
218        ]
219        .iter()
220        .map(|index| batch.column(*index).clone())
221        .collect();
222        let partitions = partition(&columns).context(ComputeArrowSnafu)?;
223
224        Self::dedup_by_partitions(batch, &partitions)
225    }
226
227    /// Remove duplications for each partition.
228    fn dedup_by_partitions(batch: RecordBatch, partitions: &Partitions) -> Result<RecordBatch> {
229        let ranges = partitions.ranges();
230        // Each range at least has 1 row.
231        let num_duplications: usize = ranges.iter().map(|r| r.end - r.start - 1).sum();
232        if num_duplications == 0 {
233            // Fast path, no duplications.
234            return Ok(batch);
235        }
236
237        // Always takes the first row in each range.
238        let take_indices: UInt64Array = ranges.iter().map(|r| Some(r.start as u64)).collect();
239        take_record_batch(&batch, &take_indices).context(ComputeArrowSnafu)
240    }
241}
242
243impl RecordBatchDedupStrategy for FlatLastRow {
244    fn push_batch(
245        &mut self,
246        batch: RecordBatch,
247        metrics: &mut DedupMetrics,
248    ) -> Result<Option<RecordBatch>> {
249        let start = Instant::now();
250
251        if batch.num_rows() == 0 {
252            return Ok(None);
253        }
254
255        // Dedup current batch to ensure no duplication before we checking the previous row.
256        let row_before_dedup = batch.num_rows();
257        let mut batch = Self::dedup_one_batch(batch)?;
258
259        if let Some(prev_batch) = &self.prev_batch {
260            // If we have previous batch.
261            if prev_batch.is_last_row_duplicated(&batch) {
262                // Duplicated with the last batch, skip the first row.
263                batch = batch.slice(1, batch.num_rows() - 1);
264            }
265        }
266        metrics.num_unselected_rows += row_before_dedup - batch.num_rows();
267
268        let Some(batch_last_row) = BatchLastRow::try_new(batch.clone()) else {
269            // The batch after dedup is empty.
270            // We don't need to update `prev_batch` because they have the same
271            // key and timestamp.
272            metrics.dedup_cost += start.elapsed();
273            return Ok(None);
274        };
275
276        // Store current batch to `prev_batch` so we could compare the next batch
277        // with this batch. We store batch before filtering it as rows with `OpType::Delete`
278        // would be removed from the batch after filter, then we may store an incorrect `last row`
279        // of previous batch.
280        // Safety: We checked the batch is not empty before.
281        self.prev_batch = Some(batch_last_row);
282
283        // Filters deleted rows at last.
284        let result = maybe_filter_deleted(batch, self.filter_deleted, metrics);
285
286        metrics.dedup_cost += start.elapsed();
287
288        result
289    }
290
291    fn finish(&mut self, _metrics: &mut DedupMetrics) -> Result<Option<RecordBatch>> {
292        Ok(None)
293    }
294}
295
296/// Dedup strategy that keeps the last non-null field for the same key.
297pub struct FlatLastNonNull {
298    /// The start index of field columns:
299    field_column_start: usize,
300    /// Filter deleted rows; otherwise preserve every delete barrier.
301    filter_deleted: bool,
302    /// Buffered batch to check whether the next batch have duplicated rows with this batch.
303    /// Fields in the last row of this batch may be updated by the next batch.
304    /// In preserve mode, duplicate keys may be separated by delete markers.
305    buffer: Option<BatchLastRow>,
306    /// Whether the last row range contains a delete operation, either in its own rows
307    /// or in earlier batches of the same key. If so, we don't need to update null fields.
308    contains_delete: bool,
309}
310
311impl RecordBatchDedupStrategy for FlatLastNonNull {
312    fn push_batch(
313        &mut self,
314        batch: RecordBatch,
315        metrics: &mut DedupMetrics,
316    ) -> Result<Option<RecordBatch>> {
317        let start = Instant::now();
318
319        if batch.num_rows() == 0 {
320            return Ok(None);
321        }
322
323        let row_before_dedup = batch.num_rows();
324
325        let Some(buffer) = self.buffer.take() else {
326            // If the buffer is None, dedup the batch, put the batch into the buffer and return.
327            // There is no previous batch with the same key, we can pass contains_delete as false.
328            let (record_batch, contains_delete) =
329                Self::dedup_one_batch(batch, self.field_column_start, false, self.filter_deleted)?;
330            metrics.num_unselected_rows += row_before_dedup - record_batch.num_rows();
331            self.buffer = BatchLastRow::try_new(record_batch);
332            self.contains_delete = contains_delete;
333
334            metrics.dedup_cost += start.elapsed();
335            return Ok(None);
336        };
337
338        if !buffer.is_last_row_duplicated(&batch) {
339            // The first row of batch has different key from the buffer.
340            // We can replace the buffer with the new batch.
341            // Dedup the batch.
342            // There is no previous batch with the same key, we can pass contains_delete as false.
343            let (record_batch, contains_delete) =
344                Self::dedup_one_batch(batch, self.field_column_start, false, self.filter_deleted)?;
345            metrics.num_unselected_rows += row_before_dedup - record_batch.num_rows();
346            debug_assert!(record_batch.num_rows() > 0);
347            self.buffer = BatchLastRow::try_new(record_batch);
348            self.contains_delete = contains_delete;
349
350            let result = maybe_filter_deleted(buffer.last_batch, self.filter_deleted, metrics);
351            metrics.dedup_cost += start.elapsed();
352            return result;
353        }
354
355        // The next batch has duplicated rows.
356        // We can return rows except the last row in the buffer.
357        let output = if buffer.last_batch.num_rows() > 1 {
358            let dedup_batch = buffer.last_batch.slice(0, buffer.last_batch.num_rows() - 1);
359            debug_assert_eq!(buffer.last_batch.num_rows() - 1, dedup_batch.num_rows());
360
361            maybe_filter_deleted(dedup_batch, self.filter_deleted, metrics)?
362        } else {
363            None
364        };
365        let last_row = buffer.last_batch.slice(buffer.last_batch.num_rows() - 1, 1);
366
367        // We concat the last row with the next batch.
368        let schema = batch.schema();
369        let merged = concat_batches(&schema, &[last_row, batch]).context(ComputeArrowSnafu)?;
370        let merged_row_count = merged.num_rows();
371        // Dedup the merged batch and update the buffer.
372        let (record_batch, contains_delete) = Self::dedup_one_batch(
373            merged,
374            self.field_column_start,
375            self.contains_delete,
376            self.filter_deleted,
377        )?;
378        metrics.num_unselected_rows += merged_row_count - record_batch.num_rows();
379        debug_assert!(record_batch.num_rows() > 0);
380        self.buffer = BatchLastRow::try_new(record_batch);
381        self.contains_delete = contains_delete;
382
383        metrics.dedup_cost += start.elapsed();
384
385        Ok(output)
386    }
387
388    fn finish(&mut self, metrics: &mut DedupMetrics) -> Result<Option<RecordBatch>> {
389        let Some(buffer) = self.buffer.take() else {
390            return Ok(None);
391        };
392
393        let start = Instant::now();
394
395        let result = maybe_filter_deleted(buffer.last_batch, self.filter_deleted, metrics);
396
397        metrics.dedup_cost += start.elapsed();
398
399        result
400    }
401}
402
403impl FlatLastNonNull {
404    /// Creates a strategy with the given `filter_deleted` flag. When false,
405    /// every delete barrier is preserved and Puts are folded only between
406    /// barriers so later reads cannot fill fields from a deleted row.
407    /// Inputs for partial merges must form a sequence-contiguous group to avoid
408    /// folding fields across an intermediate version left outside the merge.
409    pub fn new(field_column_start: usize, filter_deleted: bool) -> Self {
410        Self {
411            field_column_start,
412            filter_deleted,
413            buffer: None,
414            contains_delete: false,
415        }
416    }
417
418    /// Remove duplications from the batch without considering the previous and next rows.
419    /// Returns a tuple containing the deduplicated batch and a boolean indicating whether the last range contains deleted rows,
420    /// including a delete inherited from the previous batch.
421    fn dedup_one_batch(
422        batch: RecordBatch,
423        field_column_start: usize,
424        prev_batch_contains_delete: bool,
425        filter_deleted: bool,
426    ) -> Result<(RecordBatch, bool)> {
427        // Get op type array for checking delete operations
428        let op_type_column = batch
429            .column(op_type_column_index(batch.num_columns()))
430            .clone();
431        let op_types = op_type_column
432            .as_any()
433            .downcast_ref::<UInt8Array>()
434            .unwrap();
435        let num_rows = batch.num_rows();
436        if num_rows < 2 {
437            let contains_delete = if num_rows > 0 {
438                op_types.value(0) == OpType::Delete as u8
439            } else {
440                false
441            };
442            return Ok((batch, contains_delete));
443        }
444
445        let num_columns = batch.num_columns();
446        let timestamps = batch.column(time_index_column_index(num_columns));
447        // Checks duplications based on the timestamp.
448        let mask = find_boundaries(timestamps).context(ComputeArrowSnafu)?;
449        if mask.count_set_bits() == num_rows - 1 {
450            let contains_delete = op_types.value(num_rows - 1) == OpType::Delete as u8;
451            // Fast path: No duplication.
452            return Ok((batch, contains_delete));
453        }
454
455        // The batch has duplicated timestamps, but it doesn't mean it must
456        // has duplicated rows.
457        // Partitions the batch by the primary key and time index.
458        let columns: Vec<_> = [
459            primary_key_column_index(num_columns),
460            time_index_column_index(num_columns),
461        ]
462        .iter()
463        .map(|index| batch.column(*index).clone())
464        .collect();
465        let partitions = partition(&columns).context(ComputeArrowSnafu)?;
466
467        Self::dedup_by_partitions(
468            batch,
469            &partitions,
470            field_column_start,
471            op_types,
472            prev_batch_contains_delete,
473            filter_deleted,
474        )
475    }
476
477    /// Remove depulications for each partition.
478    /// Returns a tuple containing the deduplicated batch and a boolean indicating whether the last range contains deleted rows,
479    /// including a delete inherited from the previous batch.
480    fn dedup_by_partitions(
481        batch: RecordBatch,
482        partitions: &Partitions,
483        field_column_start: usize,
484        op_types: &UInt8Array,
485        first_range_contains_delete: bool,
486        filter_deleted: bool,
487    ) -> Result<(RecordBatch, bool)> {
488        let mut ranges = partitions.ranges();
489        // With one range, the last range is the first range, so it keeps the previous batch's delete.
490        let contains_delete = filter_deleted
491            && (Self::last_range_has_delete(&ranges, op_types)
492                || (ranges.len() == 1 && first_range_contains_delete));
493        if !filter_deleted && op_types.values().contains(&(OpType::Delete as u8)) {
494            let mut segments = Vec::with_capacity(ranges.len());
495            for range in ranges {
496                let mut start = range.start;
497                for i in range.clone() {
498                    if op_types.value(i) == OpType::Delete as u8 {
499                        if start < i {
500                            segments.push(start..i);
501                        }
502                        segments.push(i..i + 1);
503                        start = i + 1;
504                    }
505                }
506                if start < range.end {
507                    segments.push(start..range.end);
508                }
509            }
510            ranges = segments;
511        }
512
513        // Each range at least has 1 row.
514        let num_duplications: usize = ranges.iter().map(|r| r.end - r.start - 1).sum();
515        if num_duplications == 0 {
516            // Fast path, no duplication.
517            return Ok((batch, contains_delete));
518        }
519
520        let field_column_end = batch.num_columns() - FIXED_POS_COLUMN_NUM;
521        let take_options = Some(TakeOptions {
522            check_bounds: false,
523        });
524        // Always takes the first value for non-field columns in each range.
525        let non_field_indices: UInt64Array = ranges.iter().map(|r| Some(r.start as u64)).collect();
526        let new_columns = batch
527            .columns()
528            .iter()
529            .enumerate()
530            .map(|(col_idx, column)| {
531                if col_idx >= field_column_start && col_idx < field_column_end {
532                    let field_indices = Self::compute_field_indices(
533                        &ranges,
534                        column,
535                        op_types,
536                        first_range_contains_delete && filter_deleted,
537                    );
538                    take(column, &field_indices, take_options.clone()).context(ComputeArrowSnafu)
539                } else {
540                    take(column, &non_field_indices, take_options.clone())
541                        .context(ComputeArrowSnafu)
542                }
543            })
544            .collect::<Result<Vec<ArrayRef>>>()?;
545
546        let record_batch =
547            RecordBatch::try_new(batch.schema(), new_columns).context(NewRecordBatchSnafu)?;
548        Ok((record_batch, contains_delete))
549    }
550
551    /// Returns an array of indices of the latest non null value for
552    /// each input range.
553    /// If all values in a range are null, the returned index is unspecific.
554    /// Stops when encountering a delete operation and ignores all subsequent rows.
555    fn compute_field_indices(
556        ranges: &[Range<usize>],
557        field_array: &ArrayRef,
558        op_types: &UInt8Array,
559        first_range_contains_delete: bool,
560    ) -> UInt64Array {
561        ranges
562            .iter()
563            .enumerate()
564            .map(|(range_idx, r)| {
565                let mut value_index = r.start as u64;
566                if range_idx == 0 && first_range_contains_delete {
567                    return Some(value_index);
568                }
569
570                // Iterate through the range to find the first valid non-null value
571                // but stop if we encounter a delete operation.
572                for i in r.clone() {
573                    if op_types.value(i) == OpType::Delete as u8 {
574                        break;
575                    }
576                    if field_array.is_valid(i) {
577                        value_index = i as u64;
578                        break;
579                    }
580                }
581
582                Some(value_index)
583            })
584            .collect()
585    }
586
587    /// Checks whether the last range contains a delete operation.
588    fn last_range_has_delete(ranges: &[Range<usize>], op_types: &UInt8Array) -> bool {
589        if let Some(last_range) = ranges.last() {
590            last_range
591                .clone()
592                .any(|i| op_types.value(i) == OpType::Delete as u8)
593        } else {
594            false
595        }
596    }
597}
598
599/// State of the batch with the last row for dedup.
600struct BatchLastRow {
601    /// The record batch that contains the last row.
602    /// It must has at least one row.
603    last_batch: RecordBatch,
604    /// Primary keys of the last batch.
605    primary_key: PrimaryKeyArray,
606    /// Last timestamp value.
607    timestamp: i64,
608}
609
610impl BatchLastRow {
611    /// Returns a new [BatchLastRow] if the record batch is not empty.
612    fn try_new(record_batch: RecordBatch) -> Option<Self> {
613        if record_batch.num_rows() > 0 {
614            let num_columns = record_batch.num_columns();
615            let primary_key = record_batch
616                .column(primary_key_column_index(num_columns))
617                .as_any()
618                .downcast_ref::<PrimaryKeyArray>()
619                .unwrap()
620                .clone();
621            let timestamp_array = record_batch.column(time_index_column_index(num_columns));
622            let timestamp = timestamp_value(timestamp_array, timestamp_array.len() - 1);
623
624            Some(Self {
625                last_batch: record_batch,
626                primary_key,
627                timestamp,
628            })
629        } else {
630            None
631        }
632    }
633
634    /// Returns true if the first row of the input `batch` is duplicated with the last row.
635    fn is_last_row_duplicated(&self, batch: &RecordBatch) -> bool {
636        if batch.num_rows() == 0 {
637            return false;
638        }
639
640        // The first timestamp in the batch.
641        let batch_timestamp = timestamp_value(
642            batch.column(time_index_column_index(batch.num_columns())),
643            0,
644        );
645        if batch_timestamp != self.timestamp {
646            return false;
647        }
648
649        let last_key = primary_key_at(&self.primary_key, self.last_batch.num_rows() - 1);
650        let primary_key = batch
651            .column(primary_key_column_index(batch.num_columns()))
652            .as_any()
653            .downcast_ref::<PrimaryKeyArray>()
654            .unwrap();
655        // Primary key of the first row in the batch.
656        let batch_key = primary_key_at(primary_key, 0);
657
658        last_key == batch_key
659    }
660}
661
662// TODO(yingwen): We only compares timestamp arrays, we can modify this function
663// to simplify the comparator.
664// Port from https://github.com/apache/arrow-rs/blob/55.0.0/arrow-ord/src/partition.rs#L155-L168
665/// Returns a mask with bits set whenever the value or nullability changes
666fn find_boundaries(v: &dyn Array) -> Result<BooleanBuffer, ArrowError> {
667    let slice_len = v.len() - 1;
668    let v1 = v.slice(0, slice_len);
669    let v2 = v.slice(1, slice_len);
670
671    if !v.data_type().is_nested() {
672        return Ok(distinct(&v1, &v2)?.values().clone());
673    }
674    // Given that we're only comparing values, null ordering in the input or
675    // sort options do not matter.
676    let cmp = make_comparator(&v1, &v2, SortOptions::default())?;
677    Ok((0..slice_len).map(|i| !cmp(i, i).is_eq()).collect())
678}
679
680/// Filters deleted rows from the record batch if `filter_deleted` is true.
681fn maybe_filter_deleted(
682    record_batch: RecordBatch,
683    filter_deleted: bool,
684    metrics: &mut DedupMetrics,
685) -> Result<Option<RecordBatch>> {
686    if !filter_deleted {
687        return Ok(Some(record_batch));
688    }
689    let batch = filter_deleted_from_batch(record_batch, metrics)?;
690    // Skips empty batches.
691    if batch.num_rows() == 0 {
692        return Ok(None);
693    }
694    Ok(Some(batch))
695}
696
697/// Removes deleted rows from the batch and updates metrics.
698fn filter_deleted_from_batch(
699    batch: RecordBatch,
700    metrics: &mut DedupMetrics,
701) -> Result<RecordBatch> {
702    let num_rows = batch.num_rows();
703    let op_type_column = batch.column(op_type_column_index(batch.num_columns()));
704    // Safety: The column should be op type.
705    let op_types = op_type_column
706        .as_any()
707        .downcast_ref::<UInt8Array>()
708        .unwrap();
709    let has_delete = op_types
710        .values()
711        .iter()
712        .any(|op_type| *op_type != OpType::Put as u8);
713    if !has_delete {
714        return Ok(batch);
715    }
716
717    let mut builder = BooleanBufferBuilder::new(op_types.len());
718    for op_type in op_types.values() {
719        if *op_type == OpType::Delete as u8 {
720            builder.append(false);
721        } else {
722            builder.append(true);
723        }
724    }
725    let predicate = BooleanArray::new(builder.into(), None);
726    let new_batch = filter_record_batch(&batch, &predicate).context(ComputeArrowSnafu)?;
727    let num_deleted = num_rows - new_batch.num_rows();
728    metrics.num_deleted_rows += num_deleted;
729    metrics.num_unselected_rows += num_deleted;
730
731    Ok(new_batch)
732}
733
734/// Gets the primary key at `index`.
735fn primary_key_at(primary_key: &PrimaryKeyArray, index: usize) -> &[u8] {
736    let key = primary_key.keys().value(index);
737    let binary_values = primary_key
738        .values()
739        .as_any()
740        .downcast_ref::<BinaryArray>()
741        .unwrap();
742    binary_values.value(key as usize)
743}
744
745/// Gets the timestamp value from the timestamp array.
746///
747/// # Panics
748/// Panics if the array is not a timestamp array or
749/// the index is out of bound.
750pub(crate) fn timestamp_value(array: &ArrayRef, idx: usize) -> i64 {
751    timestamp_array_to_i64_slice(array)[idx]
752}
753
754#[cfg(test)]
755mod tests {
756    use std::sync::Arc;
757
758    use api::v1::OpType;
759    use datatypes::arrow::array::{
760        ArrayRef, BinaryDictionaryBuilder, Int64Array, StringDictionaryBuilder,
761        TimestampMillisecondArray, UInt8Array, UInt64Array,
762    };
763    use datatypes::arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit, UInt32Type};
764    use datatypes::arrow::record_batch::RecordBatch;
765
766    use super::*;
767
768    /// Creates a test RecordBatch in flat format with given parameters.
769    fn new_record_batch(
770        primary_keys: &[&[u8]],
771        timestamps: &[i64],
772        sequences: &[u64],
773        op_types: &[OpType],
774        fields: &[u64],
775    ) -> RecordBatch {
776        let num_rows = timestamps.len();
777        debug_assert_eq!(sequences.len(), num_rows);
778        debug_assert_eq!(op_types.len(), num_rows);
779        debug_assert_eq!(fields.len(), num_rows);
780        debug_assert_eq!(primary_keys.len(), num_rows);
781
782        let columns: Vec<ArrayRef> = vec![
783            // k0 column (primary key as string dictionary)
784            build_test_pk_string_dict_array(primary_keys),
785            // field0 column
786            Arc::new(Int64Array::from_iter(
787                fields.iter().map(|v| Some(*v as i64)),
788            )),
789            // ts column (time index)
790            Arc::new(TimestampMillisecondArray::from_iter_values(
791                timestamps.iter().copied(),
792            )),
793            // __primary_key column
794            build_test_pk_array(primary_keys),
795            // __sequence column
796            Arc::new(UInt64Array::from_iter_values(sequences.iter().copied())),
797            // __op_type column
798            Arc::new(UInt8Array::from_iter_values(
799                op_types.iter().map(|v| *v as u8),
800            )),
801        ];
802
803        RecordBatch::try_new(build_test_flat_schema(), columns).unwrap()
804    }
805
806    /// Creates a test RecordBatch in flat format with multiple fields for testing FlatLastNonNull.
807    fn new_record_batch_multi_fields(
808        primary_keys: &[&[u8]],
809        timestamps: &[i64],
810        sequences: &[u64],
811        op_types: &[OpType],
812        fields: &[(Option<u64>, Option<u64>)],
813    ) -> RecordBatch {
814        let num_rows = timestamps.len();
815        debug_assert_eq!(sequences.len(), num_rows);
816        debug_assert_eq!(op_types.len(), num_rows);
817        debug_assert_eq!(fields.len(), num_rows);
818        debug_assert_eq!(primary_keys.len(), num_rows);
819
820        let columns: Vec<ArrayRef> = vec![
821            // k0 column (primary key as string dictionary)
822            build_test_pk_string_dict_array(primary_keys),
823            // field0 column
824            Arc::new(Int64Array::from_iter(
825                fields.iter().map(|field| field.0.map(|v| v as i64)),
826            )),
827            // field1 column
828            Arc::new(Int64Array::from_iter(
829                fields.iter().map(|field| field.1.map(|v| v as i64)),
830            )),
831            // ts column (time index)
832            Arc::new(TimestampMillisecondArray::from_iter_values(
833                timestamps.iter().copied(),
834            )),
835            // __primary_key column
836            build_test_pk_array(primary_keys),
837            // __sequence column
838            Arc::new(UInt64Array::from_iter_values(sequences.iter().copied())),
839            // __op_type column
840            Arc::new(UInt8Array::from_iter_values(
841                op_types.iter().map(|v| *v as u8),
842            )),
843        ];
844
845        RecordBatch::try_new(build_test_multi_field_schema(), columns).unwrap()
846    }
847
848    /// Creates a test string dictionary primary key array for given primary keys.
849    fn build_test_pk_string_dict_array(primary_keys: &[&[u8]]) -> ArrayRef {
850        let mut builder = StringDictionaryBuilder::<UInt32Type>::new();
851        for &pk in primary_keys {
852            let pk_str = std::str::from_utf8(pk).unwrap();
853            builder.append(pk_str).unwrap();
854        }
855        Arc::new(builder.finish())
856    }
857
858    /// Creates a test primary key array for given primary keys.
859    fn build_test_pk_array(primary_keys: &[&[u8]]) -> ArrayRef {
860        let mut builder = BinaryDictionaryBuilder::<UInt32Type>::new();
861        for &pk in primary_keys {
862            builder.append(pk).unwrap();
863        }
864        Arc::new(builder.finish())
865    }
866
867    /// Builds the arrow schema for test flat format.
868    fn build_test_flat_schema() -> SchemaRef {
869        let fields = vec![
870            Field::new(
871                "k0",
872                DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
873                false,
874            ),
875            Field::new("field0", DataType::Int64, true),
876            Field::new(
877                "ts",
878                DataType::Timestamp(TimeUnit::Millisecond, None),
879                false,
880            ),
881            Field::new(
882                "__primary_key",
883                DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Binary)),
884                false,
885            ),
886            Field::new("__sequence", DataType::UInt64, false),
887            Field::new("__op_type", DataType::UInt8, false),
888        ];
889        Arc::new(Schema::new(fields))
890    }
891
892    /// Builds the arrow schema for test flat format with multiple fields.
893    fn build_test_multi_field_schema() -> SchemaRef {
894        let fields = vec![
895            Field::new(
896                "k0",
897                DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
898                false,
899            ),
900            Field::new("field0", DataType::Int64, true),
901            Field::new("field1", DataType::Int64, true),
902            Field::new(
903                "ts",
904                DataType::Timestamp(TimeUnit::Millisecond, None),
905                false,
906            ),
907            Field::new(
908                "__primary_key",
909                DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Binary)),
910                false,
911            ),
912            Field::new("__sequence", DataType::UInt64, false),
913            Field::new("__op_type", DataType::UInt8, false),
914        ];
915        Arc::new(Schema::new(fields))
916    }
917
918    /// Asserts that two RecordBatch vectors are equal.
919    fn check_record_batches_equal(expected: &[RecordBatch], actual: &[RecordBatch]) {
920        for (i, (exp, act)) in expected.iter().zip(actual.iter()).enumerate() {
921            assert_eq!(exp, act, "RecordBatch {} differs", i);
922        }
923        assert_eq!(
924            expected.len(),
925            actual.len(),
926            "Number of batches don't match"
927        );
928    }
929
930    /// Helper function to collect iterator results.
931    fn collect_iterator_results<I>(iter: I) -> Vec<RecordBatch>
932    where
933        I: Iterator<Item = Result<RecordBatch>>,
934    {
935        iter.map(|result| result.unwrap()).collect()
936    }
937
938    #[test]
939    fn test_flat_last_row_no_duplications() {
940        let input = vec![
941            new_record_batch(
942                &[b"k1", b"k1"],
943                &[1, 2],
944                &[11, 12],
945                &[OpType::Put, OpType::Put],
946                &[21, 22],
947            ),
948            new_record_batch(&[b"k1"], &[3], &[13], &[OpType::Put], &[23]),
949            new_record_batch(
950                &[b"k2", b"k2"],
951                &[1, 2],
952                &[111, 112],
953                &[OpType::Put, OpType::Put],
954                &[31, 32],
955            ),
956        ];
957
958        // Test with filter_deleted = true
959        let iter = input.clone().into_iter().map(Ok);
960        let mut dedup_iter = FlatDedupIterator::new(iter, FlatLastRow::new(true));
961        let result = collect_iterator_results(&mut dedup_iter);
962        check_record_batches_equal(&input, &result);
963        assert_eq!(0, dedup_iter.metrics.num_unselected_rows);
964        assert_eq!(0, dedup_iter.metrics.num_deleted_rows);
965
966        // Test with filter_deleted = false
967        let iter = input.clone().into_iter().map(Ok);
968        let mut dedup_iter = FlatDedupIterator::new(iter, FlatLastRow::new(false));
969        let result = collect_iterator_results(&mut dedup_iter);
970        check_record_batches_equal(&input, &result);
971        assert_eq!(0, dedup_iter.metrics.num_unselected_rows);
972        assert_eq!(0, dedup_iter.metrics.num_deleted_rows);
973    }
974
975    #[test]
976    fn test_flat_last_row_duplications() {
977        let input = vec![
978            new_record_batch(
979                &[b"k1", b"k1"],
980                &[1, 2],
981                &[13, 11],
982                &[OpType::Put, OpType::Put],
983                &[11, 12],
984            ),
985            // empty batch.
986            new_record_batch(&[], &[], &[], &[], &[]),
987            // Duplicate with the previous batch.
988            new_record_batch(
989                &[b"k1", b"k1", b"k1"],
990                &[2, 3, 4],
991                &[10, 13, 13],
992                &[OpType::Put, OpType::Put, OpType::Delete],
993                &[2, 13, 14],
994            ),
995            new_record_batch(
996                &[b"k2", b"k2"],
997                &[1, 2],
998                &[20, 20],
999                &[OpType::Put, OpType::Delete],
1000                &[101, 0],
1001            ),
1002            new_record_batch(&[b"k2"], &[2], &[19], &[OpType::Put], &[102]),
1003            new_record_batch(&[b"k3"], &[2], &[20], &[OpType::Put], &[202]),
1004            // This batch won't increase the deleted rows count as it
1005            // is filtered out by the previous batch.
1006            new_record_batch(&[b"k3"], &[2], &[19], &[OpType::Delete], &[0]),
1007        ];
1008
1009        // Test with filter_deleted = true
1010        let expected_filter_deleted = vec![
1011            new_record_batch(
1012                &[b"k1", b"k1"],
1013                &[1, 2],
1014                &[13, 11],
1015                &[OpType::Put, OpType::Put],
1016                &[11, 12],
1017            ),
1018            new_record_batch(&[b"k1"], &[3], &[13], &[OpType::Put], &[13]),
1019            new_record_batch(&[b"k2"], &[1], &[20], &[OpType::Put], &[101]),
1020            new_record_batch(&[b"k3"], &[2], &[20], &[OpType::Put], &[202]),
1021        ];
1022
1023        let iter = input.clone().into_iter().map(Ok);
1024        let mut dedup_iter = FlatDedupIterator::new(iter, FlatLastRow::new(true));
1025        let result = collect_iterator_results(&mut dedup_iter);
1026        check_record_batches_equal(&expected_filter_deleted, &result);
1027        assert_eq!(5, dedup_iter.metrics.num_unselected_rows);
1028        assert_eq!(2, dedup_iter.metrics.num_deleted_rows);
1029
1030        // Test with filter_deleted = false
1031        let expected_no_filter = vec![
1032            new_record_batch(
1033                &[b"k1", b"k1"],
1034                &[1, 2],
1035                &[13, 11],
1036                &[OpType::Put, OpType::Put],
1037                &[11, 12],
1038            ),
1039            new_record_batch(
1040                &[b"k1", b"k1"],
1041                &[3, 4],
1042                &[13, 13],
1043                &[OpType::Put, OpType::Delete],
1044                &[13, 14],
1045            ),
1046            new_record_batch(
1047                &[b"k2", b"k2"],
1048                &[1, 2],
1049                &[20, 20],
1050                &[OpType::Put, OpType::Delete],
1051                &[101, 0],
1052            ),
1053            new_record_batch(&[b"k3"], &[2], &[20], &[OpType::Put], &[202]),
1054        ];
1055
1056        let iter = input.clone().into_iter().map(Ok);
1057        let mut dedup_iter = FlatDedupIterator::new(iter, FlatLastRow::new(false));
1058        let result = collect_iterator_results(&mut dedup_iter);
1059        check_record_batches_equal(&expected_no_filter, &result);
1060        assert_eq!(3, dedup_iter.metrics.num_unselected_rows);
1061        assert_eq!(0, dedup_iter.metrics.num_deleted_rows);
1062    }
1063
1064    #[test]
1065    fn exact_sequence_filter_component_composition_covers_tombstones_and_last_non_null() {
1066        use store_api::storage::SequenceRange;
1067
1068        use crate::read::scan_util::filter_flat_batch_by_sequence;
1069
1070        let filter = |batch| {
1071            filter_flat_batch_by_sequence(
1072                batch,
1073                Some(SequenceRange::GtLtEq { min: 1, max: 3 }),
1074                true,
1075            )
1076            .unwrap()
1077            .unwrap()
1078        };
1079
1080        // The shared merge presents duplicate rows newest-first: the in-range
1081        // tombstone (seq 3) reaches shared dedup and suppresses the eligible
1082        // put (seq 2) across batches.
1083        let output = FlatDedupIterator::new(
1084            vec![
1085                Ok(filter(new_record_batch_multi_fields(
1086                    &[b"series"],
1087                    &[1000],
1088                    &[3],
1089                    &[OpType::Delete],
1090                    &[(None, None)],
1091                ))),
1092                Ok(filter(new_record_batch_multi_fields(
1093                    &[b"series"],
1094                    &[1000],
1095                    &[2],
1096                    &[OpType::Put],
1097                    &[(Some(10), None)],
1098                ))),
1099            ]
1100            .into_iter(),
1101            FlatLastNonNull::new(1, true),
1102        )
1103        .collect::<Result<Vec<_>>>()
1104        .unwrap();
1105        assert!(output.is_empty());
1106
1107        // A newest outside-range tombstone is removed before shared dedup and
1108        // cannot suppress the eligible put.
1109        let output = FlatDedupIterator::new(
1110            vec![Ok(filter(new_record_batch_multi_fields(
1111                &[b"series", b"series"],
1112                &[1000, 1000],
1113                &[4, 2],
1114                &[OpType::Delete, OpType::Put],
1115                &[(None, None), (Some(10), None)],
1116            )))]
1117            .into_iter(),
1118            FlatLastNonNull::new(1, true),
1119        )
1120        .collect::<Result<Vec<_>>>()
1121        .unwrap();
1122        assert_eq!(1, output[0].num_rows());
1123
1124        // A newest outside-range non-null value is removed before
1125        // LastNonNull, so it cannot fill the eligible row's null field.
1126        let output = FlatDedupIterator::new(
1127            vec![Ok(filter(new_record_batch_multi_fields(
1128                &[b"series", b"series"],
1129                &[1000, 1000],
1130                &[4, 2],
1131                &[OpType::Put, OpType::Put],
1132                &[(None, Some(40)), (Some(10), None)],
1133            )))]
1134            .into_iter(),
1135            FlatLastNonNull::new(1, true),
1136        )
1137        .collect::<Result<Vec<_>>>()
1138        .unwrap();
1139        assert_eq!(1, output[0].num_rows());
1140        assert!(output[0].column(2).is_null(0));
1141    }
1142
1143    #[test]
1144    fn test_flat_last_non_null_no_duplications() {
1145        let input = vec![
1146            new_record_batch(
1147                &[b"k1", b"k1"],
1148                &[1, 2],
1149                &[11, 12],
1150                &[OpType::Put, OpType::Put],
1151                &[21, 22],
1152            ),
1153            new_record_batch(&[b"k1"], &[3], &[13], &[OpType::Put], &[23]),
1154            new_record_batch(
1155                &[b"k2", b"k2"],
1156                &[1, 2],
1157                &[111, 112],
1158                &[OpType::Put, OpType::Put],
1159                &[31, 32],
1160            ),
1161        ];
1162
1163        // Test with filter_deleted = true
1164        let iter = input.clone().into_iter().map(Ok);
1165        let mut dedup_iter = FlatDedupIterator::new(iter, FlatLastNonNull::new(1, true));
1166        let result = collect_iterator_results(&mut dedup_iter);
1167        check_record_batches_equal(&input, &result);
1168        assert_eq!(0, dedup_iter.metrics.num_unselected_rows);
1169        assert_eq!(0, dedup_iter.metrics.num_deleted_rows);
1170
1171        // Test with filter_deleted = false
1172        let iter = input.clone().into_iter().map(Ok);
1173        let mut dedup_iter = FlatDedupIterator::new(iter, FlatLastNonNull::new(1, false));
1174        let result = collect_iterator_results(&mut dedup_iter);
1175        check_record_batches_equal(&input, &result);
1176        assert_eq!(0, dedup_iter.metrics.num_unselected_rows);
1177        assert_eq!(0, dedup_iter.metrics.num_deleted_rows);
1178    }
1179
1180    #[test]
1181    fn test_flat_last_non_null_field_merging() {
1182        let input = vec![
1183            new_record_batch_multi_fields(
1184                &[b"k1", b"k1"],
1185                &[1, 2],
1186                &[13, 11],
1187                &[OpType::Put, OpType::Put],
1188                &[(Some(11), Some(11)), (None, None)],
1189            ),
1190            // empty batch
1191            new_record_batch_multi_fields(&[], &[], &[], &[], &[]),
1192            // Duplicate with the previous batch - should merge fields
1193            new_record_batch_multi_fields(
1194                &[b"k1"],
1195                &[2],
1196                &[10],
1197                &[OpType::Put],
1198                &[(Some(12), None)],
1199            ),
1200            new_record_batch_multi_fields(
1201                &[b"k1", b"k1", b"k1"],
1202                &[2, 3, 4],
1203                &[10, 13, 13],
1204                &[OpType::Put, OpType::Put, OpType::Delete],
1205                &[(Some(2), Some(22)), (Some(13), None), (None, Some(14))],
1206            ),
1207            new_record_batch_multi_fields(
1208                &[b"k2", b"k2"],
1209                &[1, 2],
1210                &[20, 20],
1211                &[OpType::Put, OpType::Delete],
1212                &[(Some(101), Some(101)), (None, None)],
1213            ),
1214            new_record_batch_multi_fields(
1215                &[b"k2"],
1216                &[2],
1217                &[19],
1218                &[OpType::Put],
1219                &[(Some(102), Some(102))],
1220            ),
1221            new_record_batch_multi_fields(
1222                &[b"k3"],
1223                &[2],
1224                &[20],
1225                &[OpType::Put],
1226                &[(Some(202), Some(202))],
1227            ),
1228            // This batch won't increase the deleted rows count as it
1229            // is filtered out by the previous batch. (All fields are null).
1230            new_record_batch_multi_fields(
1231                &[b"k3"],
1232                &[2],
1233                &[19],
1234                &[OpType::Delete],
1235                &[(None, None)],
1236            ),
1237        ];
1238
1239        // Test with filter_deleted = true
1240        let expected_filter_deleted = vec![
1241            new_record_batch_multi_fields(
1242                &[b"k1"],
1243                &[1],
1244                &[13],
1245                &[OpType::Put],
1246                &[(Some(11), Some(11))],
1247            ),
1248            new_record_batch_multi_fields(
1249                &[b"k1", b"k1"],
1250                &[2, 3],
1251                &[11, 13],
1252                &[OpType::Put, OpType::Put],
1253                &[(Some(12), Some(22)), (Some(13), None)],
1254            ),
1255            new_record_batch_multi_fields(
1256                &[b"k2"],
1257                &[1],
1258                &[20],
1259                &[OpType::Put],
1260                &[(Some(101), Some(101))],
1261            ),
1262            new_record_batch_multi_fields(
1263                &[b"k3"],
1264                &[2],
1265                &[20],
1266                &[OpType::Put],
1267                &[(Some(202), Some(202))],
1268            ),
1269        ];
1270
1271        let iter = input.clone().into_iter().map(Ok);
1272        let mut dedup_iter = FlatDedupIterator::new(iter, FlatLastNonNull::new(1, true));
1273        let result = collect_iterator_results(&mut dedup_iter);
1274        check_record_batches_equal(&expected_filter_deleted, &result);
1275        assert_eq!(6, dedup_iter.metrics.num_unselected_rows);
1276        assert_eq!(2, dedup_iter.metrics.num_deleted_rows);
1277    }
1278
1279    #[test]
1280    fn test_flat_last_non_null_skip_merge_no_null() {
1281        let input = vec![
1282            new_record_batch_multi_fields(
1283                &[b"k1", b"k1"],
1284                &[1, 2],
1285                &[13, 11],
1286                &[OpType::Put, OpType::Put],
1287                &[(Some(11), Some(11)), (Some(12), Some(12))],
1288            ),
1289            new_record_batch_multi_fields(
1290                &[b"k1"],
1291                &[2],
1292                &[10],
1293                &[OpType::Put],
1294                &[(None, Some(22))],
1295            ),
1296            new_record_batch_multi_fields(
1297                &[b"k1", b"k1"],
1298                &[2, 3],
1299                &[9, 13],
1300                &[OpType::Put, OpType::Put],
1301                &[(Some(32), None), (Some(13), Some(13))],
1302            ),
1303        ];
1304
1305        let expected = vec![
1306            new_record_batch_multi_fields(
1307                &[b"k1"],
1308                &[1],
1309                &[13],
1310                &[OpType::Put],
1311                &[(Some(11), Some(11))],
1312            ),
1313            new_record_batch_multi_fields(
1314                &[b"k1", b"k1"],
1315                &[2, 3],
1316                &[11, 13],
1317                &[OpType::Put, OpType::Put],
1318                &[(Some(12), Some(12)), (Some(13), Some(13))],
1319            ),
1320        ];
1321
1322        let iter = input.into_iter().map(Ok);
1323        let mut dedup_iter = FlatDedupIterator::new(iter, FlatLastNonNull::new(1, true));
1324        let result = collect_iterator_results(&mut dedup_iter);
1325        check_record_batches_equal(&expected, &result);
1326        assert_eq!(2, dedup_iter.metrics.num_unselected_rows);
1327        assert_eq!(0, dedup_iter.metrics.num_deleted_rows);
1328    }
1329
1330    #[test]
1331    fn test_flat_last_non_null_merge_null() {
1332        let input = vec![
1333            new_record_batch_multi_fields(
1334                &[b"k1", b"k1"],
1335                &[1, 2],
1336                &[13, 11],
1337                &[OpType::Put, OpType::Put],
1338                &[(Some(11), Some(11)), (None, None)],
1339            ),
1340            new_record_batch_multi_fields(
1341                &[b"k1"],
1342                &[2],
1343                &[10],
1344                &[OpType::Put],
1345                &[(None, Some(22))],
1346            ),
1347            new_record_batch_multi_fields(
1348                &[b"k1"],
1349                &[3],
1350                &[13],
1351                &[OpType::Put],
1352                &[(Some(33), None)],
1353            ),
1354        ];
1355
1356        let expected = vec![
1357            new_record_batch_multi_fields(
1358                &[b"k1"],
1359                &[1],
1360                &[13],
1361                &[OpType::Put],
1362                &[(Some(11), Some(11))],
1363            ),
1364            new_record_batch_multi_fields(
1365                &[b"k1"],
1366                &[2],
1367                &[11],
1368                &[OpType::Put],
1369                &[(None, Some(22))],
1370            ),
1371            new_record_batch_multi_fields(
1372                &[b"k1"],
1373                &[3],
1374                &[13],
1375                &[OpType::Put],
1376                &[(Some(33), None)],
1377            ),
1378        ];
1379
1380        let iter = input.into_iter().map(Ok);
1381        let mut dedup_iter = FlatDedupIterator::new(iter, FlatLastNonNull::new(1, true));
1382        let result = collect_iterator_results(&mut dedup_iter);
1383        check_record_batches_equal(&expected, &result);
1384        assert_eq!(1, dedup_iter.metrics.num_unselected_rows);
1385        assert_eq!(0, dedup_iter.metrics.num_deleted_rows);
1386    }
1387
1388    /// Helper function to check dedup strategy behavior directly.
1389    fn check_flat_dedup_strategy(
1390        input: &[RecordBatch],
1391        strategy: &mut dyn RecordBatchDedupStrategy,
1392        expect: &[RecordBatch],
1393    ) {
1394        let mut actual = Vec::new();
1395        let mut metrics = DedupMetrics::default();
1396        for batch in input {
1397            if let Some(out) = strategy.push_batch(batch.clone(), &mut metrics).unwrap() {
1398                actual.push(out);
1399            }
1400        }
1401        if let Some(out) = strategy.finish(&mut metrics).unwrap() {
1402            actual.push(out);
1403        }
1404
1405        check_record_batches_equal(expect, &actual);
1406    }
1407
1408    #[test]
1409    fn test_flat_last_non_null_strategy_delete_last() {
1410        let input = vec![
1411            new_record_batch_multi_fields(
1412                &[b"k1"],
1413                &[1],
1414                &[6],
1415                &[OpType::Put],
1416                &[(Some(11), None)],
1417            ),
1418            new_record_batch_multi_fields(
1419                &[b"k1", b"k1"],
1420                &[1, 2],
1421                &[1, 7],
1422                &[OpType::Put, OpType::Put],
1423                &[(Some(1), None), (Some(22), Some(222))],
1424            ),
1425            new_record_batch_multi_fields(
1426                &[b"k1"],
1427                &[2],
1428                &[4],
1429                &[OpType::Put],
1430                &[(Some(12), None)],
1431            ),
1432            new_record_batch_multi_fields(
1433                &[b"k2", b"k2"],
1434                &[2, 3],
1435                &[2, 5],
1436                &[OpType::Put, OpType::Delete],
1437                &[(None, None), (Some(13), None)],
1438            ),
1439            new_record_batch_multi_fields(&[b"k2"], &[3], &[3], &[OpType::Put], &[(None, Some(3))]),
1440        ];
1441
1442        let mut strategy = FlatLastNonNull::new(1, true);
1443        check_flat_dedup_strategy(
1444            &input,
1445            &mut strategy,
1446            &[
1447                new_record_batch_multi_fields(
1448                    &[b"k1"],
1449                    &[1],
1450                    &[6],
1451                    &[OpType::Put],
1452                    &[(Some(11), None)],
1453                ),
1454                new_record_batch_multi_fields(
1455                    &[b"k1"],
1456                    &[2],
1457                    &[7],
1458                    &[OpType::Put],
1459                    &[(Some(22), Some(222))],
1460                ),
1461                new_record_batch_multi_fields(
1462                    &[b"k2"],
1463                    &[2],
1464                    &[2],
1465                    &[OpType::Put],
1466                    &[(None, None)],
1467                ),
1468            ],
1469        );
1470    }
1471
1472    #[test]
1473    fn test_flat_last_non_null_strategy_delete_one() {
1474        let input = vec![
1475            new_record_batch_multi_fields(&[b"k1"], &[1], &[1], &[OpType::Delete], &[(None, None)]),
1476            new_record_batch_multi_fields(
1477                &[b"k2"],
1478                &[1],
1479                &[6],
1480                &[OpType::Put],
1481                &[(Some(11), None)],
1482            ),
1483        ];
1484
1485        let mut strategy = FlatLastNonNull::new(1, true);
1486        check_flat_dedup_strategy(
1487            &input,
1488            &mut strategy,
1489            &[new_record_batch_multi_fields(
1490                &[b"k2"],
1491                &[1],
1492                &[6],
1493                &[OpType::Put],
1494                &[(Some(11), None)],
1495            )],
1496        );
1497    }
1498
1499    #[test]
1500    fn test_flat_last_non_null_strategy_delete_all() {
1501        let input = vec![
1502            new_record_batch_multi_fields(&[b"k1"], &[1], &[1], &[OpType::Delete], &[(None, None)]),
1503            new_record_batch_multi_fields(
1504                &[b"k2"],
1505                &[1],
1506                &[6],
1507                &[OpType::Delete],
1508                &[(Some(11), None)],
1509            ),
1510        ];
1511
1512        let mut strategy = FlatLastNonNull::new(1, true);
1513        check_flat_dedup_strategy(&input, &mut strategy, &[]);
1514    }
1515
1516    #[test]
1517    fn test_flat_last_non_null_strategy_same_batch() {
1518        let input = vec![
1519            new_record_batch_multi_fields(
1520                &[b"k1"],
1521                &[1],
1522                &[6],
1523                &[OpType::Put],
1524                &[(Some(11), None)],
1525            ),
1526            new_record_batch_multi_fields(
1527                &[b"k1", b"k1"],
1528                &[1, 2],
1529                &[1, 7],
1530                &[OpType::Put, OpType::Put],
1531                &[(Some(1), None), (Some(22), Some(222))],
1532            ),
1533            new_record_batch_multi_fields(
1534                &[b"k1"],
1535                &[2],
1536                &[4],
1537                &[OpType::Put],
1538                &[(Some(12), None)],
1539            ),
1540            new_record_batch_multi_fields(
1541                &[b"k1", b"k1"],
1542                &[2, 3],
1543                &[2, 5],
1544                &[OpType::Put, OpType::Put],
1545                &[(None, None), (Some(13), None)],
1546            ),
1547            new_record_batch_multi_fields(&[b"k1"], &[3], &[3], &[OpType::Put], &[(None, Some(3))]),
1548        ];
1549
1550        let mut strategy = FlatLastNonNull::new(1, true);
1551        check_flat_dedup_strategy(
1552            &input,
1553            &mut strategy,
1554            &[
1555                new_record_batch_multi_fields(
1556                    &[b"k1"],
1557                    &[1],
1558                    &[6],
1559                    &[OpType::Put],
1560                    &[(Some(11), None)],
1561                ),
1562                new_record_batch_multi_fields(
1563                    &[b"k1"],
1564                    &[2],
1565                    &[7],
1566                    &[OpType::Put],
1567                    &[(Some(22), Some(222))],
1568                ),
1569                new_record_batch_multi_fields(
1570                    &[b"k1"],
1571                    &[3],
1572                    &[5],
1573                    &[OpType::Put],
1574                    &[(Some(13), Some(3))],
1575                ),
1576            ],
1577        );
1578    }
1579
1580    #[test]
1581    fn test_last_non_null_preserves_delete_barriers() {
1582        let input = new_record_batch_multi_fields(
1583            &[b"k1".as_slice(); 9],
1584            &[1; 9],
1585            &[9, 8, 7, 6, 5, 4, 3, 2, 1],
1586            &[
1587                OpType::Put,
1588                OpType::Put,
1589                OpType::Delete,
1590                OpType::Delete,
1591                OpType::Put,
1592                OpType::Put,
1593                OpType::Delete,
1594                OpType::Put,
1595                OpType::Put,
1596            ],
1597            &[
1598                (None, Some(9)),
1599                (Some(8), None),
1600                (None, None),
1601                (None, None),
1602                (None, Some(5)),
1603                (Some(4), None),
1604                (None, None),
1605                (None, None),
1606                (Some(1), Some(1)),
1607            ],
1608        );
1609        let expected = new_record_batch_multi_fields(
1610            &[b"k1".as_slice(); 6],
1611            &[1; 6],
1612            &[9, 7, 6, 5, 3, 2],
1613            &[
1614                OpType::Put,
1615                OpType::Delete,
1616                OpType::Delete,
1617                OpType::Put,
1618                OpType::Delete,
1619                OpType::Put,
1620            ],
1621            &[
1622                (Some(8), Some(9)),
1623                (None, None),
1624                (None, None),
1625                (Some(4), Some(5)),
1626                (None, None),
1627                (Some(1), Some(1)),
1628            ],
1629        );
1630        // Check both intra-batch partitioning and barriers split across batches.
1631        for batch_size in [1, input.num_rows()] {
1632            let batches = (0..input.num_rows())
1633                .step_by(batch_size)
1634                .map(|start| Ok(input.slice(start, batch_size.min(input.num_rows() - start))));
1635            let output = FlatDedupIterator::new(batches, FlatLastNonNull::new(1, false))
1636                .collect::<Result<Vec<_>>>()
1637                .unwrap();
1638            let actual = concat_batches(&input.schema(), &output).unwrap();
1639            assert_eq!(expected, actual);
1640        }
1641    }
1642
1643    #[test]
1644    fn test_flat_last_non_null_strategy_delete_middle() {
1645        let input = vec![
1646            new_record_batch_multi_fields(
1647                &[b"k1"],
1648                &[1],
1649                &[7],
1650                &[OpType::Put],
1651                &[(Some(11), None)],
1652            ),
1653            new_record_batch_multi_fields(&[b"k1"], &[1], &[4], &[OpType::Delete], &[(None, None)]),
1654            new_record_batch_multi_fields(
1655                &[b"k1"],
1656                &[1],
1657                &[1],
1658                &[OpType::Put],
1659                &[(Some(12), Some(1))],
1660            ),
1661            new_record_batch_multi_fields(
1662                &[b"k1"],
1663                &[2],
1664                &[8],
1665                &[OpType::Put],
1666                &[(Some(21), None)],
1667            ),
1668            new_record_batch_multi_fields(&[b"k1"], &[2], &[5], &[OpType::Delete], &[(None, None)]),
1669            new_record_batch_multi_fields(
1670                &[b"k1"],
1671                &[2],
1672                &[2],
1673                &[OpType::Put],
1674                &[(Some(22), Some(2))],
1675            ),
1676            new_record_batch_multi_fields(
1677                &[b"k1"],
1678                &[3],
1679                &[9],
1680                &[OpType::Put],
1681                &[(Some(31), None)],
1682            ),
1683            new_record_batch_multi_fields(&[b"k1"], &[3], &[6], &[OpType::Delete], &[(None, None)]),
1684            new_record_batch_multi_fields(
1685                &[b"k1"],
1686                &[3],
1687                &[3],
1688                &[OpType::Put],
1689                &[(Some(32), Some(3))],
1690            ),
1691            new_record_batch_multi_fields(
1692                &[b"k1"],
1693                &[3],
1694                &[0],
1695                &[OpType::Put],
1696                &[(Some(33), Some(33))],
1697            ),
1698        ];
1699
1700        let mut strategy = FlatLastNonNull::new(1, true);
1701        check_flat_dedup_strategy(
1702            &input,
1703            &mut strategy,
1704            &[
1705                new_record_batch_multi_fields(
1706                    &[b"k1"],
1707                    &[1],
1708                    &[7],
1709                    &[OpType::Put],
1710                    &[(Some(11), None)],
1711                ),
1712                new_record_batch_multi_fields(
1713                    &[b"k1"],
1714                    &[2],
1715                    &[8],
1716                    &[OpType::Put],
1717                    &[(Some(21), None)],
1718                ),
1719                new_record_batch_multi_fields(
1720                    &[b"k1"],
1721                    &[3],
1722                    &[9],
1723                    &[OpType::Put],
1724                    &[(Some(31), None)],
1725                ),
1726            ],
1727        );
1728    }
1729}