Skip to main content

mito2/read/
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//! Utilities to remove duplicate rows from a sorted batch.
16
17use std::fmt;
18use std::sync::Arc;
19use std::time::{Duration, Instant};
20
21use api::v1::OpType;
22use datatypes::data_type::DataType;
23use datatypes::prelude::ScalarVector;
24use datatypes::value::Value;
25use datatypes::vectors::MutableVector;
26
27use crate::error::Result;
28use crate::read::{Batch, BatchColumn};
29
30/// Trait for reporting dedup metrics.
31pub trait DedupMetricsReport: Send + Sync {
32    /// Reports and resets the metrics.
33    fn report(&self, metrics: &mut DedupMetrics);
34}
35
36/// Strategy to remove duplicate rows from sorted batches.
37pub trait DedupStrategy: Send {
38    /// Pushes a batch to the dedup strategy.
39    /// Returns the deduplicated batch.
40    fn push_batch(&mut self, batch: Batch, metrics: &mut DedupMetrics) -> Result<Option<Batch>>;
41
42    /// Finishes the deduplication and resets the strategy.
43    ///
44    /// Users must ensure that `push_batch` is called for all batches before
45    /// calling this method.
46    fn finish(&mut self, metrics: &mut DedupMetrics) -> Result<Option<Batch>>;
47}
48
49/// Removes deleted rows from the batch and updates metrics.
50fn filter_deleted_from_batch(batch: &mut Batch, metrics: &mut DedupMetrics) -> Result<()> {
51    let num_rows = batch.num_rows();
52    batch.filter_deleted()?;
53    let num_rows_after_filter = batch.num_rows();
54    let num_deleted = num_rows - num_rows_after_filter;
55    metrics.num_deleted_rows += num_deleted;
56    metrics.num_unselected_rows += num_deleted;
57
58    Ok(())
59}
60
61/// Metrics for deduplication.
62#[derive(Default)]
63pub struct DedupMetrics {
64    /// Number of rows removed during deduplication.
65    pub(crate) num_unselected_rows: usize,
66    /// Number of deleted rows.
67    pub(crate) num_deleted_rows: usize,
68    /// Time spent on deduplication.
69    pub(crate) dedup_cost: Duration,
70}
71
72impl fmt::Debug for DedupMetrics {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        // Skip output if dedup_cost is zero
75        if self.dedup_cost.is_zero() {
76            return write!(f, "{{}}");
77        }
78
79        write!(f, r#"{{"dedup_cost":"{:?}""#, self.dedup_cost)?;
80
81        if self.num_unselected_rows > 0 {
82            write!(f, r#", "num_unselected_rows":{}"#, self.num_unselected_rows)?;
83        }
84        if self.num_deleted_rows > 0 {
85            write!(f, r#", "num_deleted_rows":{}"#, self.num_deleted_rows)?;
86        }
87
88        write!(f, "}}")
89    }
90}
91
92impl DedupMetrics {
93    /// Merges metrics from another DedupMetrics instance.
94    pub(crate) fn merge(&mut self, other: &DedupMetrics) {
95        let DedupMetrics {
96            num_unselected_rows,
97            num_deleted_rows,
98            dedup_cost,
99        } = other;
100
101        self.num_unselected_rows += *num_unselected_rows;
102        self.num_deleted_rows += *num_deleted_rows;
103        self.dedup_cost += *dedup_cost;
104    }
105
106    /// Reports the metrics if dedup_cost exceeds 10ms and resets them.
107    pub(crate) fn maybe_report(&mut self, reporter: &Option<Arc<dyn DedupMetricsReport>>) {
108        if self.dedup_cost.as_millis() > 10
109            && let Some(r) = reporter
110        {
111            r.report(self);
112        }
113    }
114}
115
116/// Buffer to store fields in the last row to merge.
117///
118/// Usage:
119/// We should call `maybe_init()` to initialize the builder and then call `push_first_row()`
120/// to push the first row of batches that the timestamp is the same as the row in this builder.
121/// Finally we should call `merge_last_non_null()` to merge the last non-null fields and
122/// return the merged batch.
123struct LastFieldsBuilder {
124    /// Filter deleted rows.
125    filter_deleted: bool,
126    /// Fields builders, lazy initialized.
127    builders: Vec<Box<dyn MutableVector>>,
128    /// Last fields to merge, lazy initialized.
129    /// Only initializes this field when `skip_merge()` is false.
130    last_fields: Vec<Value>,
131    /// Whether the last row (including `last_fields`) has null field.
132    /// Only sets this field when `contains_deletion` is false.
133    contains_null: bool,
134    /// Whether the last row has delete op. If true, skips merging fields.
135    contains_deletion: bool,
136    /// Whether the builder is initialized.
137    initialized: bool,
138}
139
140impl LastFieldsBuilder {
141    /// Returns a new builder with the given `filter_deleted` flag.
142    fn new(filter_deleted: bool) -> Self {
143        Self {
144            filter_deleted,
145            builders: Vec::new(),
146            last_fields: Vec::new(),
147            contains_null: false,
148            contains_deletion: false,
149            initialized: false,
150        }
151    }
152
153    /// Initializes the builders with the last row of the batch.
154    fn maybe_init(&mut self, batch: &Batch) {
155        debug_assert!(!batch.is_empty());
156
157        if self.initialized {
158            // Already initialized or no fields to merge.
159            return;
160        }
161
162        self.initialized = true;
163
164        if batch.fields().is_empty() {
165            // No fields to merge.
166            return;
167        }
168
169        let last_idx = batch.num_rows() - 1;
170        let fields = batch.fields();
171        // Safety: The last_idx is valid.
172        self.contains_deletion =
173            batch.op_types().get_data(last_idx).unwrap() == OpType::Delete as u8;
174        // If the row has been deleted, then we don't need to merge fields.
175        if !self.contains_deletion {
176            self.contains_null = fields.iter().any(|col| col.data.is_null(last_idx));
177        }
178
179        if self.skip_merge() {
180            // No null field or the row has been deleted, no need to merge.
181            return;
182        }
183        if self.builders.is_empty() {
184            self.builders = fields
185                .iter()
186                .map(|col| col.data.data_type().create_mutable_vector(1))
187                .collect();
188        }
189        self.last_fields = fields.iter().map(|col| col.data.get(last_idx)).collect();
190    }
191
192    /// Returns true if the builder don't need to merge the rows.
193    fn skip_merge(&self) -> bool {
194        debug_assert!(self.initialized);
195
196        // No null field or the row has been deleted, no need to merge.
197        self.contains_deletion || !self.contains_null
198    }
199
200    /// Pushes first row of a batch to the builder.
201    fn push_first_row(&mut self, batch: &Batch) {
202        debug_assert!(self.initialized);
203        debug_assert!(!batch.is_empty());
204
205        if self.skip_merge() {
206            // No remaining null field, skips this batch.
207            return;
208        }
209
210        // Both `maybe_init()` and `push_first_row()` can update the builder. If the delete
211        // op is not in the latest row, then we can't set the deletion flag in the `maybe_init()`.
212        // We must check the batch and update the deletion flag here to prevent
213        // the builder from merging non-null fields in rows that insert before the deleted row.
214        self.contains_deletion = batch.op_types().get_data(0).unwrap() == OpType::Delete as u8;
215        if self.contains_deletion {
216            // Deletes this row.
217            return;
218        }
219
220        let fields = batch.fields();
221        for (idx, value) in self.last_fields.iter_mut().enumerate() {
222            if value.is_null() && !fields[idx].data.is_null(0) {
223                // Updates the value.
224                *value = fields[idx].data.get(0);
225            }
226        }
227        // Updates the flag.
228        self.contains_null = self.last_fields.iter().any(Value::is_null);
229    }
230
231    /// Merges last non-null fields, builds a new batch and resets the builder.
232    /// It may overwrites the last row of the `buffer`. The `buffer` is the batch
233    /// that initialized the builder.
234    fn merge_last_non_null(
235        &mut self,
236        buffer: Batch,
237        metrics: &mut DedupMetrics,
238    ) -> Result<Option<Batch>> {
239        debug_assert!(self.initialized);
240
241        let mut output = if self.last_fields.is_empty() {
242            // No need to overwrite the last row.
243            buffer
244        } else {
245            // Builds last fields.
246            for (builder, value) in self.builders.iter_mut().zip(&self.last_fields) {
247                // Safety: Vectors of the batch has the same type.
248                builder.push_value_ref(&value.as_value_ref());
249            }
250            let fields = self
251                .builders
252                .iter_mut()
253                .zip(buffer.fields())
254                .map(|(builder, col)| BatchColumn {
255                    column_id: col.column_id,
256                    data: builder.to_vector(),
257                })
258                .collect();
259
260            if buffer.num_rows() == 1 {
261                // Replaces the buffer directly if it only has one row.
262                buffer.with_fields(fields)?
263            } else {
264                // Replaces the last row of the buffer.
265                let front = buffer.slice(0, buffer.num_rows() - 1);
266                let last = buffer.slice(buffer.num_rows() - 1, 1);
267                let last = last.with_fields(fields)?;
268                Batch::concat(vec![front, last])?
269            }
270        };
271
272        // Resets itself. `self.builders` is already reset in `to_vector()`.
273        self.clear();
274
275        if self.filter_deleted {
276            filter_deleted_from_batch(&mut output, metrics)?;
277        }
278
279        if output.is_empty() {
280            Ok(None)
281        } else {
282            Ok(Some(output))
283        }
284    }
285
286    /// Clears the builder.
287    fn clear(&mut self) {
288        self.last_fields.clear();
289        self.contains_null = false;
290        self.contains_deletion = false;
291        self.initialized = false;
292    }
293}
294
295/// Dedup strategy that keeps the last non-null field for the same key.
296///
297/// It assumes that batches from files and memtables don't contain duplicate rows
298/// and the merge reader never concatenates batches from different source.
299///
300/// We might implement a new strategy if we need to process files with duplicate rows.
301pub(crate) struct LastNonNull {
302    /// Buffered batch that fields in the last row may be updated.
303    buffer: Option<Batch>,
304    /// Fields that overlaps with the last row of the `buffer`.
305    last_fields: LastFieldsBuilder,
306}
307
308impl LastNonNull {
309    /// Creates a new strategy with the given `filter_deleted` flag.
310    pub(crate) fn new(filter_deleted: bool) -> Self {
311        Self {
312            buffer: None,
313            last_fields: LastFieldsBuilder::new(filter_deleted),
314        }
315    }
316}
317
318impl DedupStrategy for LastNonNull {
319    fn push_batch(&mut self, batch: Batch, metrics: &mut DedupMetrics) -> Result<Option<Batch>> {
320        let start = Instant::now();
321
322        if batch.is_empty() {
323            return Ok(None);
324        }
325
326        let Some(buffer) = self.buffer.as_mut() else {
327            // The buffer is empty, store the batch and return. We need to observe the next batch.
328            self.buffer = Some(batch);
329            return Ok(None);
330        };
331
332        // Initializes last fields with the first buffer.
333        self.last_fields.maybe_init(buffer);
334
335        if buffer.primary_key() != batch.primary_key() {
336            // Next key is different.
337            let buffer = std::mem::replace(buffer, batch);
338            let merged = self.last_fields.merge_last_non_null(buffer, metrics)?;
339            metrics.dedup_cost += start.elapsed();
340            return Ok(merged);
341        }
342
343        if buffer.last_timestamp() != batch.first_timestamp() {
344            // The next batch has a different timestamp.
345            let buffer = std::mem::replace(buffer, batch);
346            let merged = self.last_fields.merge_last_non_null(buffer, metrics)?;
347            metrics.dedup_cost += start.elapsed();
348            return Ok(merged);
349        }
350
351        // The next batch has the same key and timestamp.
352
353        if !self.last_fields.filter_deleted
354            && !self.last_fields.contains_deletion
355            && batch.op_types().get_data(0).unwrap() == OpType::Delete as u8
356        {
357            // Keeps the delete as a barrier, so readers don't fill null fields of the
358            // merged row from rows it deleted.
359            let buffer = std::mem::replace(buffer, batch);
360            let merged = self.last_fields.merge_last_non_null(buffer, metrics)?;
361            metrics.dedup_cost += start.elapsed();
362            return Ok(merged);
363        }
364
365        metrics.num_unselected_rows += 1;
366        // We assumes each batch doesn't contain duplicate rows so we only need to check the first row.
367        if batch.num_rows() == 1 {
368            self.last_fields.push_first_row(&batch);
369            metrics.dedup_cost += start.elapsed();
370            return Ok(None);
371        }
372
373        // The next batch has the same key and timestamp but contains multiple rows.
374        // We can merge the first row and buffer the remaining rows.
375        let first = batch.slice(0, 1);
376        self.last_fields.push_first_row(&first);
377        // Moves the remaining rows to the buffer.
378        let batch = batch.slice(1, batch.num_rows() - 1);
379        let buffer = std::mem::replace(buffer, batch);
380        let merged = self.last_fields.merge_last_non_null(buffer, metrics)?;
381
382        metrics.dedup_cost += start.elapsed();
383
384        Ok(merged)
385    }
386
387    fn finish(&mut self, metrics: &mut DedupMetrics) -> Result<Option<Batch>> {
388        let start = Instant::now();
389
390        let Some(buffer) = self.buffer.take() else {
391            return Ok(None);
392        };
393
394        // Initializes last fields with the first buffer.
395        self.last_fields.maybe_init(&buffer);
396
397        let merged = self.last_fields.merge_last_non_null(buffer, metrics)?;
398
399        metrics.dedup_cost += start.elapsed();
400
401        Ok(merged)
402    }
403}
404
405/// An iterator that dedup rows by [LastNonNull] strategy.
406/// The input iterator must returns sorted batches.
407pub(crate) struct LastNonNullIter<I> {
408    /// Inner iterator that returns sorted batches.
409    iter: Option<I>,
410    /// Dedup strategy.
411    strategy: LastNonNull,
412    /// Dedup metrics.
413    metrics: DedupMetrics,
414    /// The current batch returned by the iterator. If it is None, we need to
415    /// fetch a new batch.
416    /// The batch is always not empty.
417    current_batch: Option<Batch>,
418    /// The index of the current row in the current batch.
419    /// more to check issue #5229.
420    current_index: usize,
421}
422
423impl<I> LastNonNullIter<I> {
424    /// Creates a new iterator with the given inner iterator.
425    pub(crate) fn new(iter: I) -> Self {
426        Self {
427            iter: Some(iter),
428            // We only use the iter in memtables. Memtables never filter deleted.
429            strategy: LastNonNull::new(false),
430            metrics: DedupMetrics::default(),
431            current_batch: None,
432            current_index: 0,
433        }
434    }
435}
436
437impl<I: Iterator<Item = Result<Batch>>> LastNonNullIter<I> {
438    /// Fetches the next batch from the inner iterator. It will slice the batch if it
439    /// contains duplicate rows.
440    fn next_batch_for_merge(&mut self) -> Result<Option<Batch>> {
441        if self.current_batch.is_none() {
442            // No current batch. Fetches a new batch from the inner iterator.
443            let Some(iter) = self.iter.as_mut() else {
444                // The iterator is exhausted.
445                return Ok(None);
446            };
447
448            self.current_batch = iter.next().transpose()?;
449            self.current_index = 0;
450            if self.current_batch.is_none() {
451                // The iterator is exhausted.
452                self.iter = None;
453                return Ok(None);
454            }
455        }
456
457        if let Some(batch) = &self.current_batch {
458            let n = batch.num_rows();
459            // Safety: The batch is not empty when accessed.
460            let timestamps = batch.timestamps_native().unwrap();
461            let mut pos = self.current_index;
462            while pos + 1 < n && timestamps[pos] != timestamps[pos + 1] {
463                pos += 1;
464            }
465            let segment = batch.slice(self.current_index, pos - self.current_index + 1);
466            if pos + 1 < n && timestamps[pos] == timestamps[pos + 1] {
467                self.current_index = pos + 1;
468            } else {
469                self.current_batch = None;
470                self.current_index = 0;
471            }
472            return Ok(Some(segment));
473        }
474
475        Ok(None)
476    }
477
478    fn next_batch(&mut self) -> Result<Option<Batch>> {
479        while let Some(batch) = self.next_batch_for_merge()? {
480            if let Some(batch) = self.strategy.push_batch(batch, &mut self.metrics)? {
481                return Ok(Some(batch));
482            }
483        }
484
485        self.strategy.finish(&mut self.metrics)
486    }
487}
488
489impl<I: Iterator<Item = Result<Batch>>> Iterator for LastNonNullIter<I> {
490    type Item = Result<Batch>;
491
492    fn next(&mut self) -> Option<Self::Item> {
493        self.next_batch().transpose()
494    }
495}
496
497#[cfg(test)]
498mod tests {
499    use std::sync::Arc;
500
501    use datatypes::arrow::array::{TimestampMillisecondArray, UInt8Array, UInt64Array};
502
503    use super::*;
504    use crate::read::BatchBuilder;
505
506    /// Returns a new [Batch] whose field has column id 1, 2.
507    fn new_batch_multi_fields(
508        primary_key: &[u8],
509        timestamps: &[i64],
510        sequences: &[u64],
511        op_types: &[OpType],
512        fields: &[(Option<u64>, Option<u64>)],
513    ) -> Batch {
514        let mut builder = BatchBuilder::new(primary_key.to_vec());
515        builder
516            .timestamps_array(Arc::new(TimestampMillisecondArray::from_iter_values(
517                timestamps.iter().copied(),
518            )))
519            .unwrap()
520            .sequences_array(Arc::new(UInt64Array::from_iter_values(
521                sequences.iter().copied(),
522            )))
523            .unwrap()
524            .op_types_array(Arc::new(UInt8Array::from_iter_values(
525                op_types.iter().map(|v| *v as u8),
526            )))
527            .unwrap()
528            .push_field_array(
529                1,
530                Arc::new(UInt64Array::from_iter(fields.iter().map(|field| field.0))),
531            )
532            .unwrap()
533            .push_field_array(
534                2,
535                Arc::new(UInt64Array::from_iter(fields.iter().map(|field| field.1))),
536            )
537            .unwrap();
538        builder.build().unwrap()
539    }
540
541    fn check_dedup_strategy(input: &[Batch], strategy: &mut dyn DedupStrategy, expect: &[Batch]) {
542        let mut actual = Vec::new();
543        let mut metrics = DedupMetrics::default();
544        for batch in input {
545            if let Some(out) = strategy.push_batch(batch.clone(), &mut metrics).unwrap() {
546                actual.push(out);
547            }
548        }
549        if let Some(out) = strategy.finish(&mut metrics).unwrap() {
550            actual.push(out);
551        }
552
553        assert_eq!(expect, actual);
554    }
555
556    #[test]
557    fn test_last_non_null_strategy_delete_last() {
558        let input = [
559            new_batch_multi_fields(b"k1", &[1], &[6], &[OpType::Put], &[(Some(11), None)]),
560            new_batch_multi_fields(
561                b"k1",
562                &[1, 2],
563                &[1, 7],
564                &[OpType::Put, OpType::Put],
565                &[(Some(1), None), (Some(22), Some(222))],
566            ),
567            new_batch_multi_fields(b"k1", &[2], &[4], &[OpType::Put], &[(Some(12), None)]),
568            new_batch_multi_fields(
569                b"k2",
570                &[2, 3],
571                &[2, 5],
572                &[OpType::Put, OpType::Delete],
573                &[(None, None), (Some(13), None)],
574            ),
575            new_batch_multi_fields(b"k2", &[3], &[3], &[OpType::Put], &[(None, Some(3))]),
576        ];
577
578        let mut strategy = LastNonNull::new(true);
579        check_dedup_strategy(
580            &input,
581            &mut strategy,
582            &[
583                new_batch_multi_fields(b"k1", &[1], &[6], &[OpType::Put], &[(Some(11), None)]),
584                new_batch_multi_fields(b"k1", &[2], &[7], &[OpType::Put], &[(Some(22), Some(222))]),
585                new_batch_multi_fields(b"k2", &[2], &[2], &[OpType::Put], &[(None, None)]),
586            ],
587        );
588    }
589
590    #[test]
591    fn test_last_non_null_strategy_delete_one() {
592        let input = [
593            new_batch_multi_fields(b"k1", &[1], &[1], &[OpType::Delete], &[(None, None)]),
594            new_batch_multi_fields(b"k2", &[1], &[6], &[OpType::Put], &[(Some(11), None)]),
595        ];
596
597        let mut strategy = LastNonNull::new(true);
598        check_dedup_strategy(
599            &input,
600            &mut strategy,
601            &[new_batch_multi_fields(
602                b"k2",
603                &[1],
604                &[6],
605                &[OpType::Put],
606                &[(Some(11), None)],
607            )],
608        );
609    }
610
611    #[test]
612    fn test_last_non_null_strategy_delete_all() {
613        let input = [
614            new_batch_multi_fields(b"k1", &[1], &[1], &[OpType::Delete], &[(None, None)]),
615            new_batch_multi_fields(b"k2", &[1], &[6], &[OpType::Delete], &[(Some(11), None)]),
616        ];
617
618        let mut strategy = LastNonNull::new(true);
619        check_dedup_strategy(&input, &mut strategy, &[]);
620    }
621
622    #[test]
623    fn test_last_non_null_strategy_same_batch() {
624        let input = [
625            new_batch_multi_fields(b"k1", &[1], &[6], &[OpType::Put], &[(Some(11), None)]),
626            new_batch_multi_fields(
627                b"k1",
628                &[1, 2],
629                &[1, 7],
630                &[OpType::Put, OpType::Put],
631                &[(Some(1), None), (Some(22), Some(222))],
632            ),
633            new_batch_multi_fields(b"k1", &[2], &[4], &[OpType::Put], &[(Some(12), None)]),
634            new_batch_multi_fields(
635                b"k1",
636                &[2, 3],
637                &[2, 5],
638                &[OpType::Put, OpType::Put],
639                &[(None, None), (Some(13), None)],
640            ),
641            new_batch_multi_fields(b"k1", &[3], &[3], &[OpType::Put], &[(None, Some(3))]),
642        ];
643
644        let mut strategy = LastNonNull::new(true);
645        check_dedup_strategy(
646            &input,
647            &mut strategy,
648            &[
649                new_batch_multi_fields(b"k1", &[1], &[6], &[OpType::Put], &[(Some(11), None)]),
650                new_batch_multi_fields(b"k1", &[2], &[7], &[OpType::Put], &[(Some(22), Some(222))]),
651                new_batch_multi_fields(b"k1", &[3], &[5], &[OpType::Put], &[(Some(13), Some(3))]),
652            ],
653        );
654    }
655
656    #[test]
657    fn test_last_non_null_strategy_delete_middle() {
658        let input = [
659            new_batch_multi_fields(b"k1", &[1], &[7], &[OpType::Put], &[(Some(11), None)]),
660            new_batch_multi_fields(b"k1", &[1], &[4], &[OpType::Delete], &[(None, None)]),
661            new_batch_multi_fields(b"k1", &[1], &[1], &[OpType::Put], &[(Some(12), Some(1))]),
662            new_batch_multi_fields(b"k1", &[2], &[8], &[OpType::Put], &[(Some(21), None)]),
663            new_batch_multi_fields(b"k1", &[2], &[5], &[OpType::Delete], &[(None, None)]),
664            new_batch_multi_fields(b"k1", &[2], &[2], &[OpType::Put], &[(Some(22), Some(2))]),
665            new_batch_multi_fields(b"k1", &[3], &[9], &[OpType::Put], &[(Some(31), None)]),
666            new_batch_multi_fields(b"k1", &[3], &[6], &[OpType::Delete], &[(None, None)]),
667            new_batch_multi_fields(b"k1", &[3], &[3], &[OpType::Put], &[(Some(32), Some(3))]),
668        ];
669
670        let mut strategy = LastNonNull::new(true);
671        check_dedup_strategy(
672            &input,
673            &mut strategy,
674            &[
675                new_batch_multi_fields(b"k1", &[1], &[7], &[OpType::Put], &[(Some(11), None)]),
676                new_batch_multi_fields(b"k1", &[2], &[8], &[OpType::Put], &[(Some(21), None)]),
677                new_batch_multi_fields(b"k1", &[3], &[9], &[OpType::Put], &[(Some(31), None)]),
678            ],
679        );
680    }
681
682    #[test]
683    fn test_last_non_null_iter_on_batch() {
684        let input = [new_batch_multi_fields(
685            b"k1",
686            &[1, 1, 2],
687            &[13, 12, 13],
688            &[OpType::Put, OpType::Put, OpType::Put],
689            &[(None, None), (Some(1), None), (Some(2), Some(22))],
690        )];
691        let iter = input.into_iter().map(Ok);
692        let iter = LastNonNullIter::new(iter);
693        let actual: Vec<_> = iter.map(|batch| batch.unwrap()).collect();
694        let expect = [
695            new_batch_multi_fields(b"k1", &[1], &[13], &[OpType::Put], &[(Some(1), None)]),
696            new_batch_multi_fields(b"k1", &[2], &[13], &[OpType::Put], &[(Some(2), Some(22))]),
697        ];
698        assert_eq!(&expect, &actual[..]);
699    }
700
701    #[test]
702    fn test_last_non_null_iter_same_row() {
703        let input = [
704            new_batch_multi_fields(
705                b"k1",
706                &[1, 1, 1],
707                &[13, 12, 11],
708                &[OpType::Put, OpType::Put, OpType::Put],
709                &[(None, None), (Some(1), None), (Some(11), None)],
710            ),
711            new_batch_multi_fields(
712                b"k1",
713                &[1, 1],
714                &[10, 9],
715                &[OpType::Put, OpType::Put],
716                &[(None, Some(11)), (Some(21), Some(31))],
717            ),
718        ];
719        let iter = input.into_iter().map(Ok);
720        let iter = LastNonNullIter::new(iter);
721        let actual: Vec<_> = iter.map(|batch| batch.unwrap()).collect();
722        let expect = [new_batch_multi_fields(
723            b"k1",
724            &[1],
725            &[13],
726            &[OpType::Put],
727            &[(Some(1), Some(11))],
728        )];
729        assert_eq!(&expect, &actual[..]);
730    }
731
732    #[test]
733    fn test_last_non_null_iter_keep_delete_under_put() {
734        // The delete must stay in the output, otherwise a reader that merges this
735        // memtable with an older SST fills the Put's null fields from the deleted row.
736        let input = [new_batch_multi_fields(
737            b"k1",
738            &[1, 1, 1],
739            &[13, 12, 11],
740            &[OpType::Put, OpType::Delete, OpType::Put],
741            &[(Some(1), None), (None, None), (Some(11), Some(21))],
742        )];
743        let iter = input.into_iter().map(Ok);
744        let iter = LastNonNullIter::new(iter);
745        let actual: Vec<_> = iter.map(|batch| batch.unwrap()).collect();
746        let expect = [
747            new_batch_multi_fields(b"k1", &[1], &[13], &[OpType::Put], &[(Some(1), None)]),
748            new_batch_multi_fields(b"k1", &[1], &[12], &[OpType::Delete], &[(None, None)]),
749        ];
750        assert_eq!(&expect, &actual[..]);
751    }
752
753    #[test]
754    fn test_last_non_null_iter_multi_batch() {
755        let input = [
756            new_batch_multi_fields(
757                b"k1",
758                &[1, 1, 2],
759                &[13, 12, 13],
760                &[OpType::Put, OpType::Put, OpType::Put],
761                &[(None, None), (Some(1), None), (Some(2), Some(22))],
762            ),
763            new_batch_multi_fields(
764                b"k1",
765                &[2, 3],
766                &[12, 13],
767                &[OpType::Put, OpType::Delete],
768                &[(None, Some(12)), (None, None)],
769            ),
770            new_batch_multi_fields(
771                b"k2",
772                &[1, 1, 2],
773                &[13, 12, 13],
774                &[OpType::Put, OpType::Put, OpType::Put],
775                &[(None, None), (Some(1), None), (Some(2), Some(22))],
776            ),
777        ];
778        let iter = input.into_iter().map(Ok);
779        let iter = LastNonNullIter::new(iter);
780        let actual: Vec<_> = iter.map(|batch| batch.unwrap()).collect();
781        let expect = [
782            new_batch_multi_fields(b"k1", &[1], &[13], &[OpType::Put], &[(Some(1), None)]),
783            new_batch_multi_fields(b"k1", &[2], &[13], &[OpType::Put], &[(Some(2), Some(22))]),
784            new_batch_multi_fields(b"k1", &[3], &[13], &[OpType::Delete], &[(None, None)]),
785            new_batch_multi_fields(b"k2", &[1], &[13], &[OpType::Put], &[(Some(1), None)]),
786            new_batch_multi_fields(b"k2", &[2], &[13], &[OpType::Put], &[(Some(2), Some(22))]),
787        ];
788        assert_eq!(&expect, &actual[..]);
789    }
790
791    /// Returns a new [Batch] without fields.
792    fn new_batch_no_fields(
793        primary_key: &[u8],
794        timestamps: &[i64],
795        sequences: &[u64],
796        op_types: &[OpType],
797    ) -> Batch {
798        let mut builder = BatchBuilder::new(primary_key.to_vec());
799        builder
800            .timestamps_array(Arc::new(TimestampMillisecondArray::from_iter_values(
801                timestamps.iter().copied(),
802            )))
803            .unwrap()
804            .sequences_array(Arc::new(UInt64Array::from_iter_values(
805                sequences.iter().copied(),
806            )))
807            .unwrap()
808            .op_types_array(Arc::new(UInt8Array::from_iter_values(
809                op_types.iter().map(|v| *v as u8),
810            )))
811            .unwrap();
812        builder.build().unwrap()
813    }
814
815    #[test]
816    fn test_last_non_null_iter_no_batch() {
817        let input = [
818            new_batch_no_fields(
819                b"k1",
820                &[1, 1, 2],
821                &[13, 12, 13],
822                &[OpType::Put, OpType::Put, OpType::Put],
823            ),
824            new_batch_no_fields(b"k1", &[2, 3], &[12, 13], &[OpType::Put, OpType::Delete]),
825            new_batch_no_fields(
826                b"k2",
827                &[1, 1, 2],
828                &[13, 12, 13],
829                &[OpType::Put, OpType::Put, OpType::Put],
830            ),
831        ];
832        let iter = input.into_iter().map(Ok);
833        let iter = LastNonNullIter::new(iter);
834        let actual: Vec<_> = iter.map(|batch| batch.unwrap()).collect();
835        let expect = [
836            new_batch_no_fields(b"k1", &[1], &[13], &[OpType::Put]),
837            new_batch_no_fields(b"k1", &[2], &[13], &[OpType::Put]),
838            new_batch_no_fields(b"k1", &[3], &[13], &[OpType::Delete]),
839            new_batch_no_fields(b"k2", &[1], &[13], &[OpType::Put]),
840            new_batch_no_fields(b"k2", &[2], &[13], &[OpType::Put]),
841        ];
842        assert_eq!(&expect, &actual[..]);
843    }
844}