Skip to main content

mito2/
read.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//! Common structs and utilities for reading data.
16
17pub mod batch_adapter;
18pub mod compat;
19pub mod dedup;
20pub mod flat_dedup;
21pub mod flat_merge;
22pub mod flat_projection;
23pub mod last_row;
24pub mod projection;
25pub(crate) mod prune;
26pub(crate) mod pruner;
27pub mod range;
28#[cfg(feature = "test")]
29pub mod range_cache;
30#[cfg(not(feature = "test"))]
31pub(crate) mod range_cache;
32pub(crate) mod read_columns;
33pub mod scan_region;
34pub mod scan_util;
35pub(crate) mod seq_scan;
36pub mod series_scan;
37pub mod stream;
38pub(crate) mod unordered_scan;
39
40use std::collections::HashMap;
41use std::sync::Arc;
42use std::time::Duration;
43
44use api::v1::OpType;
45use arrow_schema::SchemaRef;
46use async_trait::async_trait;
47use common_time::Timestamp;
48use datafusion_common::arrow::array::UInt8Array;
49use datatypes::arrow;
50use datatypes::arrow::array::{Array, ArrayRef};
51use datatypes::arrow::compute::SortOptions;
52use datatypes::arrow::record_batch::RecordBatch;
53use datatypes::arrow::row::{RowConverter, SortField};
54use datatypes::prelude::{ConcreteDataType, DataType, ScalarVector};
55use datatypes::scalars::ScalarVectorBuilder;
56use datatypes::types::TimestampType;
57use datatypes::value::{Value, ValueRef};
58use datatypes::vectors::{
59    BooleanVector, Helper, TimestampMicrosecondVector, TimestampMillisecondVector,
60    TimestampMillisecondVectorBuilder, TimestampNanosecondVector, TimestampSecondVector,
61    UInt8Vector, UInt8VectorBuilder, UInt32Vector, UInt64Vector, UInt64VectorBuilder, Vector,
62    VectorRef,
63};
64use futures::TryStreamExt;
65use futures::stream::BoxStream;
66use mito_codec::row_converter::{CompositeValues, PrimaryKeyCodec};
67use snafu::{OptionExt, ResultExt, ensure};
68use store_api::storage::{ColumnId, SequenceNumber, SequenceRange};
69
70use crate::error::{
71    ComputeArrowSnafu, ComputeVectorSnafu, ConvertVectorSnafu, DecodeSnafu, InvalidBatchSnafu,
72    Result,
73};
74use crate::memtable::{BoxedBatchIterator, BoxedRecordBatchIterator};
75
76pub(crate) fn timestamp_array_to_i64_slice(arr: &ArrayRef) -> &[i64] {
77    use datatypes::arrow::array::{
78        TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,
79        TimestampSecondArray,
80    };
81    use datatypes::arrow::datatypes::{DataType, TimeUnit};
82
83    match arr.data_type() {
84        DataType::Timestamp(t, _) => match t {
85            TimeUnit::Second => arr
86                .as_any()
87                .downcast_ref::<TimestampSecondArray>()
88                .unwrap()
89                .values(),
90            TimeUnit::Millisecond => arr
91                .as_any()
92                .downcast_ref::<TimestampMillisecondArray>()
93                .unwrap()
94                .values(),
95            TimeUnit::Microsecond => arr
96                .as_any()
97                .downcast_ref::<TimestampMicrosecondArray>()
98                .unwrap()
99                .values(),
100            TimeUnit::Nanosecond => arr
101                .as_any()
102                .downcast_ref::<TimestampNanosecondArray>()
103                .unwrap()
104                .values(),
105        },
106        _ => unreachable!(),
107    }
108}
109
110/// Storage internal representation of a batch of rows for a primary key (time series).
111///
112/// Rows are sorted by primary key, timestamp, sequence desc, op_type desc. Fields
113/// always keep the same relative order as fields in [RegionMetadata](store_api::metadata::RegionMetadata).
114#[derive(Debug, PartialEq, Clone)]
115pub struct Batch {
116    /// Primary key encoded in a comparable form.
117    primary_key: Vec<u8>,
118    /// Possibly decoded `primary_key` values. Some places would decode it in advance.
119    pk_values: Option<CompositeValues>,
120    /// Timestamps of rows, should be sorted and not null.
121    timestamps: VectorRef,
122    /// Sequences of rows
123    ///
124    /// UInt64 type, not null.
125    sequences: Arc<UInt64Vector>,
126    /// Op types of rows
127    ///
128    /// UInt8 type, not null.
129    op_types: Arc<UInt8Vector>,
130    /// Fields organized in columnar format.
131    fields: Vec<BatchColumn>,
132    /// Cache for field index lookup.
133    fields_idx: Option<HashMap<ColumnId, usize>>,
134}
135
136impl Batch {
137    /// Creates a new batch.
138    pub fn new(
139        primary_key: Vec<u8>,
140        timestamps: VectorRef,
141        sequences: Arc<UInt64Vector>,
142        op_types: Arc<UInt8Vector>,
143        fields: Vec<BatchColumn>,
144    ) -> Result<Batch> {
145        BatchBuilder::with_required_columns(primary_key, timestamps, sequences, op_types)
146            .with_fields(fields)
147            .build()
148    }
149
150    /// Tries to set fields for the batch.
151    pub fn with_fields(self, fields: Vec<BatchColumn>) -> Result<Batch> {
152        Batch::new(
153            self.primary_key,
154            self.timestamps,
155            self.sequences,
156            self.op_types,
157            fields,
158        )
159    }
160
161    /// Returns primary key of the batch.
162    pub fn primary_key(&self) -> &[u8] {
163        &self.primary_key
164    }
165
166    /// Returns possibly decoded primary-key values.
167    pub fn pk_values(&self) -> Option<&CompositeValues> {
168        self.pk_values.as_ref()
169    }
170
171    /// Sets possibly decoded primary-key values.
172    pub fn set_pk_values(&mut self, pk_values: CompositeValues) {
173        self.pk_values = Some(pk_values);
174    }
175
176    /// Removes possibly decoded primary-key values. For testing only.
177    #[cfg(any(test, feature = "test"))]
178    pub fn remove_pk_values(&mut self) {
179        self.pk_values = None;
180    }
181
182    /// Returns fields in the batch.
183    pub fn fields(&self) -> &[BatchColumn] {
184        &self.fields
185    }
186
187    /// Returns timestamps of the batch.
188    pub fn timestamps(&self) -> &VectorRef {
189        &self.timestamps
190    }
191
192    /// Returns sequences of the batch.
193    pub fn sequences(&self) -> &Arc<UInt64Vector> {
194        &self.sequences
195    }
196
197    /// Returns op types of the batch.
198    pub fn op_types(&self) -> &Arc<UInt8Vector> {
199        &self.op_types
200    }
201
202    /// Returns the number of rows in the batch.
203    pub fn num_rows(&self) -> usize {
204        // All vectors have the same length. We use the length of sequences vector
205        // since it has static type.
206        self.sequences.len()
207    }
208
209    /// Create an empty [`Batch`].
210    #[allow(dead_code)]
211    pub(crate) fn empty() -> Self {
212        Self {
213            primary_key: vec![],
214            pk_values: None,
215            timestamps: Arc::new(TimestampMillisecondVectorBuilder::with_capacity(0).finish()),
216            sequences: Arc::new(UInt64VectorBuilder::with_capacity(0).finish()),
217            op_types: Arc::new(UInt8VectorBuilder::with_capacity(0).finish()),
218            fields: vec![],
219            fields_idx: None,
220        }
221    }
222
223    /// Returns true if the number of rows in the batch is 0.
224    pub fn is_empty(&self) -> bool {
225        self.num_rows() == 0
226    }
227
228    /// Returns the first timestamp in the batch or `None` if the batch is empty.
229    pub fn first_timestamp(&self) -> Option<Timestamp> {
230        if self.timestamps.is_empty() {
231            return None;
232        }
233
234        Some(self.get_timestamp(0))
235    }
236
237    /// Returns the last timestamp in the batch or `None` if the batch is empty.
238    pub fn last_timestamp(&self) -> Option<Timestamp> {
239        if self.timestamps.is_empty() {
240            return None;
241        }
242
243        Some(self.get_timestamp(self.timestamps.len() - 1))
244    }
245
246    /// Returns the first sequence in the batch or `None` if the batch is empty.
247    pub fn first_sequence(&self) -> Option<SequenceNumber> {
248        if self.sequences.is_empty() {
249            return None;
250        }
251
252        Some(self.get_sequence(0))
253    }
254
255    /// Returns the last sequence in the batch or `None` if the batch is empty.
256    pub fn last_sequence(&self) -> Option<SequenceNumber> {
257        if self.sequences.is_empty() {
258            return None;
259        }
260
261        Some(self.get_sequence(self.sequences.len() - 1))
262    }
263
264    /// Replaces the primary key of the batch.
265    ///
266    /// Notice that this [Batch] also contains a maybe-exist `pk_values`.
267    /// Be sure to update that field as well.
268    pub fn set_primary_key(&mut self, primary_key: Vec<u8>) {
269        self.primary_key = primary_key;
270    }
271
272    /// Slice the batch, returning a new batch.
273    ///
274    /// # Panics
275    /// Panics if `offset + length > self.num_rows()`.
276    pub fn slice(&self, offset: usize, length: usize) -> Batch {
277        let fields = self
278            .fields
279            .iter()
280            .map(|column| BatchColumn {
281                column_id: column.column_id,
282                data: column.data.slice(offset, length),
283            })
284            .collect();
285        // We skip using the builder to avoid validating the batch again.
286        Batch {
287            // Now we need to clone the primary key. We could try `Bytes` if
288            // this becomes a bottleneck.
289            primary_key: self.primary_key.clone(),
290            pk_values: self.pk_values.clone(),
291            timestamps: self.timestamps.slice(offset, length),
292            sequences: Arc::new(self.sequences.get_slice(offset, length)),
293            op_types: Arc::new(self.op_types.get_slice(offset, length)),
294            fields,
295            fields_idx: self.fields_idx.clone(),
296        }
297    }
298
299    /// Takes `batches` and concat them into one batch.
300    ///
301    /// All `batches` must have the same primary key.
302    pub fn concat(mut batches: Vec<Batch>) -> Result<Batch> {
303        ensure!(
304            !batches.is_empty(),
305            InvalidBatchSnafu {
306                reason: "empty batches",
307            }
308        );
309        if batches.len() == 1 {
310            // Now we own the `batches` so we could pop it directly.
311            return Ok(batches.pop().unwrap());
312        }
313
314        let primary_key = std::mem::take(&mut batches[0].primary_key);
315        let first = &batches[0];
316        // We took the primary key from the first batch so we don't use `first.primary_key()`.
317        ensure!(
318            batches
319                .iter()
320                .skip(1)
321                .all(|b| b.primary_key() == primary_key),
322            InvalidBatchSnafu {
323                reason: "batches have different primary key",
324            }
325        );
326        for b in batches.iter().skip(1) {
327            ensure!(
328                b.fields.len() == first.fields.len(),
329                InvalidBatchSnafu {
330                    reason: "batches have different field num",
331                }
332            );
333            for (l, r) in b.fields.iter().zip(&first.fields) {
334                ensure!(
335                    l.column_id == r.column_id,
336                    InvalidBatchSnafu {
337                        reason: "batches have different fields",
338                    }
339                );
340            }
341        }
342
343        // We take the primary key from the first batch.
344        let mut builder = BatchBuilder::new(primary_key);
345        // Concat timestamps, sequences, op_types, fields.
346        let array = concat_arrays(batches.iter().map(|b| b.timestamps().to_arrow_array()))?;
347        builder.timestamps_array(array)?;
348        let array = concat_arrays(batches.iter().map(|b| b.sequences().to_arrow_array()))?;
349        builder.sequences_array(array)?;
350        let array = concat_arrays(batches.iter().map(|b| b.op_types().to_arrow_array()))?;
351        builder.op_types_array(array)?;
352        for (i, batch_column) in first.fields.iter().enumerate() {
353            let array = concat_arrays(batches.iter().map(|b| b.fields()[i].data.to_arrow_array()))?;
354            builder.push_field_array(batch_column.column_id, array)?;
355        }
356
357        builder.build()
358    }
359
360    /// Removes rows whose op type is delete.
361    pub fn filter_deleted(&mut self) -> Result<()> {
362        // Safety: op type column is not null.
363        let array = self.op_types.as_arrow();
364        // Find rows with non-delete op type.
365        let rhs = UInt8Array::new_scalar(OpType::Delete as u8);
366        let predicate =
367            arrow::compute::kernels::cmp::neq(array, &rhs).context(ComputeArrowSnafu)?;
368        self.filter(&BooleanVector::from(predicate))
369    }
370
371    // Applies the `predicate` to the batch.
372    // Safety: We know the array type so we unwrap on casting.
373    pub fn filter(&mut self, predicate: &BooleanVector) -> Result<()> {
374        self.timestamps = self
375            .timestamps
376            .filter(predicate)
377            .context(ComputeVectorSnafu)?;
378        self.sequences = Arc::new(
379            UInt64Vector::try_from_arrow_array(
380                arrow::compute::filter(self.sequences.as_arrow(), predicate.as_boolean_array())
381                    .context(ComputeArrowSnafu)?,
382            )
383            .unwrap(),
384        );
385        self.op_types = Arc::new(
386            UInt8Vector::try_from_arrow_array(
387                arrow::compute::filter(self.op_types.as_arrow(), predicate.as_boolean_array())
388                    .context(ComputeArrowSnafu)?,
389            )
390            .unwrap(),
391        );
392        for batch_column in &mut self.fields {
393            batch_column.data = batch_column
394                .data
395                .filter(predicate)
396                .context(ComputeVectorSnafu)?;
397        }
398
399        Ok(())
400    }
401
402    /// Filters rows by the given `sequence`. Only preserves rows with sequence less than or equal to `sequence`.
403    pub fn filter_by_sequence(&mut self, sequence: Option<SequenceRange>) -> Result<()> {
404        let seq_range = match sequence {
405            None => return Ok(()),
406            Some(seq_range) => {
407                let (Some(first), Some(last)) = (self.first_sequence(), self.last_sequence())
408                else {
409                    return Ok(());
410                };
411                let is_subset = match seq_range {
412                    SequenceRange::Gt { min } => min < first,
413                    SequenceRange::LtEq { max } => max >= last,
414                    SequenceRange::GtLtEq { min, max } => min < first && max >= last,
415                };
416                if is_subset {
417                    return Ok(());
418                }
419                seq_range
420            }
421        };
422
423        let seqs = self.sequences.as_arrow();
424        let predicate = seq_range.filter(seqs).context(ComputeArrowSnafu)?;
425
426        let predicate = BooleanVector::from(predicate);
427        self.filter(&predicate)?;
428
429        Ok(())
430    }
431
432    /// Sorts rows in the batch. If `dedup` is true, it also removes
433    /// duplicated rows according to primary keys.
434    ///
435    /// It orders rows by timestamp, sequence desc and only keep the latest
436    /// row for the same timestamp. It doesn't consider op type as sequence
437    /// should already provide uniqueness for a row.
438    pub fn sort(&mut self, dedup: bool) -> Result<()> {
439        // If building a converter each time is costly, we may allow passing a
440        // converter.
441        let converter = RowConverter::new(vec![
442            SortField::new(self.timestamps.data_type().as_arrow_type()),
443            SortField::new_with_options(
444                self.sequences.data_type().as_arrow_type(),
445                SortOptions {
446                    descending: true,
447                    ..Default::default()
448                },
449            ),
450        ])
451        .context(ComputeArrowSnafu)?;
452        // Columns to sort.
453        let columns = [
454            self.timestamps.to_arrow_array(),
455            self.sequences.to_arrow_array(),
456        ];
457        let rows = converter.convert_columns(&columns).unwrap();
458        let mut to_sort: Vec<_> = rows.iter().enumerate().collect();
459
460        let was_sorted = to_sort.is_sorted_by_key(|x| x.1);
461        if !was_sorted {
462            to_sort.sort_unstable_by_key(|x| x.1);
463        }
464
465        let num_rows = to_sort.len();
466        if dedup {
467            // Dedup by timestamps.
468            to_sort.dedup_by(|left, right| {
469                debug_assert_eq!(18, left.1.as_ref().len());
470                debug_assert_eq!(18, right.1.as_ref().len());
471                let (left_key, right_key) = (left.1.as_ref(), right.1.as_ref());
472                // We only compare the timestamp part and ignore sequence.
473                left_key[..TIMESTAMP_KEY_LEN] == right_key[..TIMESTAMP_KEY_LEN]
474            });
475        }
476        let no_dedup = to_sort.len() == num_rows;
477
478        if was_sorted && no_dedup {
479            return Ok(());
480        }
481        let indices = UInt32Vector::from_iter_values(to_sort.iter().map(|v| v.0 as u32));
482        self.take_in_place(&indices)
483    }
484
485    /// Merges duplicated timestamps in the batch by keeping the latest non-null field values.
486    ///
487    /// Rows must already be sorted by timestamp (ascending) and sequence (descending).
488    ///
489    /// This method deduplicates rows with the same timestamp (keeping the first row in each
490    /// timestamp range as the base row) and fills null fields from subsequent rows until all
491    /// fields are filled or a delete operation is encountered.
492    pub(crate) fn merge_last_non_null(&mut self) -> Result<()> {
493        let num_rows = self.num_rows();
494        if num_rows < 2 {
495            return Ok(());
496        }
497
498        let Some(timestamps) = self.timestamps_native() else {
499            return Ok(());
500        };
501
502        // Fast path: check if there are any duplicate timestamps.
503        let mut has_dup = false;
504        let mut group_count = 1;
505        for i in 1..num_rows {
506            has_dup |= timestamps[i] == timestamps[i - 1];
507            group_count += (timestamps[i] != timestamps[i - 1]) as usize;
508        }
509        if !has_dup {
510            return Ok(());
511        }
512
513        let num_fields = self.fields.len();
514        let op_types = self.op_types.as_arrow().values();
515
516        let mut base_indices: Vec<u32> = Vec::with_capacity(group_count);
517        let mut field_indices: Vec<Vec<u32>> = (0..num_fields)
518            .map(|_| Vec::with_capacity(group_count))
519            .collect();
520
521        let mut start = 0;
522        while start < num_rows {
523            let ts = timestamps[start];
524            let mut end = start + 1;
525            while end < num_rows && timestamps[end] == ts {
526                end += 1;
527            }
528
529            let group_pos = base_indices.len();
530            base_indices.push(start as u32);
531
532            if num_fields > 0 {
533                // Default: take the base row for all fields.
534                for idx in &mut field_indices {
535                    idx.push(start as u32);
536                }
537
538                let base_deleted = op_types[start] == OpType::Delete as u8;
539                if !base_deleted {
540                    // Track fields that are null in the base row and try to fill them from older
541                    // rows in the same timestamp range.
542                    let mut missing_fields = Vec::new();
543                    for (field_idx, col) in self.fields.iter().enumerate() {
544                        if col.data.is_null(start) {
545                            missing_fields.push(field_idx);
546                        }
547                    }
548
549                    if !missing_fields.is_empty() {
550                        for row_idx in (start + 1)..end {
551                            if op_types[row_idx] == OpType::Delete as u8 {
552                                break;
553                            }
554
555                            missing_fields.retain(|&field_idx| {
556                                if self.fields[field_idx].data.is_null(row_idx) {
557                                    true
558                                } else {
559                                    field_indices[field_idx][group_pos] = row_idx as u32;
560                                    false
561                                }
562                            });
563
564                            if missing_fields.is_empty() {
565                                break;
566                            }
567                        }
568                    }
569                }
570            }
571
572            start = end;
573        }
574
575        let base_indices = UInt32Vector::from_vec(base_indices);
576        self.timestamps = self
577            .timestamps
578            .take(&base_indices)
579            .context(ComputeVectorSnafu)?;
580        let array = arrow::compute::take(self.sequences.as_arrow(), base_indices.as_arrow(), None)
581            .context(ComputeArrowSnafu)?;
582        // Safety: We know the array and vector type.
583        self.sequences = Arc::new(UInt64Vector::try_from_arrow_array(array).unwrap());
584        let array = arrow::compute::take(self.op_types.as_arrow(), base_indices.as_arrow(), None)
585            .context(ComputeArrowSnafu)?;
586        // Safety: We know the array and vector type.
587        self.op_types = Arc::new(UInt8Vector::try_from_arrow_array(array).unwrap());
588
589        for (field_idx, batch_column) in self.fields.iter_mut().enumerate() {
590            let idx = UInt32Vector::from_vec(std::mem::take(&mut field_indices[field_idx]));
591            batch_column.data = batch_column.data.take(&idx).context(ComputeVectorSnafu)?;
592        }
593
594        Ok(())
595    }
596
597    /// Returns the estimated memory size of the batch.
598    pub fn memory_size(&self) -> usize {
599        let mut size = std::mem::size_of::<Self>();
600        size += self.primary_key.len();
601        size += self.timestamps.memory_size();
602        size += self.sequences.memory_size();
603        size += self.op_types.memory_size();
604        for batch_column in &self.fields {
605            size += batch_column.data.memory_size();
606        }
607        size
608    }
609
610    /// Returns timestamps in a native slice or `None` if the batch is empty.
611    pub(crate) fn timestamps_native(&self) -> Option<&[i64]> {
612        if self.timestamps.is_empty() {
613            return None;
614        }
615
616        let values = match self.timestamps.data_type() {
617            ConcreteDataType::Timestamp(TimestampType::Second(_)) => self
618                .timestamps
619                .as_any()
620                .downcast_ref::<TimestampSecondVector>()
621                .unwrap()
622                .as_arrow()
623                .values(),
624            ConcreteDataType::Timestamp(TimestampType::Millisecond(_)) => self
625                .timestamps
626                .as_any()
627                .downcast_ref::<TimestampMillisecondVector>()
628                .unwrap()
629                .as_arrow()
630                .values(),
631            ConcreteDataType::Timestamp(TimestampType::Microsecond(_)) => self
632                .timestamps
633                .as_any()
634                .downcast_ref::<TimestampMicrosecondVector>()
635                .unwrap()
636                .as_arrow()
637                .values(),
638            ConcreteDataType::Timestamp(TimestampType::Nanosecond(_)) => self
639                .timestamps
640                .as_any()
641                .downcast_ref::<TimestampNanosecondVector>()
642                .unwrap()
643                .as_arrow()
644                .values(),
645            other => panic!("timestamps in a Batch has other type {:?}", other),
646        };
647
648        Some(values)
649    }
650
651    /// Takes the batch in place.
652    fn take_in_place(&mut self, indices: &UInt32Vector) -> Result<()> {
653        self.timestamps = self.timestamps.take(indices).context(ComputeVectorSnafu)?;
654        let array = arrow::compute::take(self.sequences.as_arrow(), indices.as_arrow(), None)
655            .context(ComputeArrowSnafu)?;
656        // Safety: we know the array and vector type.
657        self.sequences = Arc::new(UInt64Vector::try_from_arrow_array(array).unwrap());
658        let array = arrow::compute::take(self.op_types.as_arrow(), indices.as_arrow(), None)
659            .context(ComputeArrowSnafu)?;
660        self.op_types = Arc::new(UInt8Vector::try_from_arrow_array(array).unwrap());
661        for batch_column in &mut self.fields {
662            batch_column.data = batch_column
663                .data
664                .take(indices)
665                .context(ComputeVectorSnafu)?;
666        }
667
668        Ok(())
669    }
670
671    /// Gets a timestamp at given `index`.
672    ///
673    /// # Panics
674    /// Panics if `index` is out-of-bound or the timestamp vector returns null.
675    fn get_timestamp(&self, index: usize) -> Timestamp {
676        match self.timestamps.get_ref(index) {
677            ValueRef::Timestamp(timestamp) => timestamp,
678
679            // We have check the data type is timestamp compatible in the [BatchBuilder] so it's safe to panic.
680            value => panic!("{:?} is not a timestamp", value),
681        }
682    }
683
684    /// Gets a sequence at given `index`.
685    ///
686    /// # Panics
687    /// Panics if `index` is out-of-bound or the sequence vector returns null.
688    pub(crate) fn get_sequence(&self, index: usize) -> SequenceNumber {
689        // Safety: sequences is not null so it actually returns Some.
690        self.sequences.get_data(index).unwrap()
691    }
692
693    /// Checks the batch is monotonic by timestamps.
694    #[cfg(debug_assertions)]
695    #[allow(dead_code)]
696    pub(crate) fn check_monotonic(&self) -> Result<(), String> {
697        use std::cmp::Ordering;
698        if self.timestamps_native().is_none() {
699            return Ok(());
700        }
701
702        let timestamps = self.timestamps_native().unwrap();
703        let sequences = self.sequences.as_arrow().values();
704        for (i, window) in timestamps.windows(2).enumerate() {
705            let current = window[0];
706            let next = window[1];
707            let current_sequence = sequences[i];
708            let next_sequence = sequences[i + 1];
709            match current.cmp(&next) {
710                Ordering::Less => {
711                    // The current timestamp is less than the next timestamp.
712                    continue;
713                }
714                Ordering::Equal => {
715                    // The current timestamp is equal to the next timestamp.
716                    if current_sequence < next_sequence {
717                        return Err(format!(
718                            "sequence are not monotonic: ts {} == {} but current sequence {} < {}, index: {}",
719                            current, next, current_sequence, next_sequence, i
720                        ));
721                    }
722                }
723                Ordering::Greater => {
724                    // The current timestamp is greater than the next timestamp.
725                    return Err(format!(
726                        "timestamps are not monotonic: {} > {}, index: {}",
727                        current, next, i
728                    ));
729                }
730            }
731        }
732
733        Ok(())
734    }
735
736    /// Returns Ok if the given batch is behind the current batch.
737    #[cfg(debug_assertions)]
738    #[allow(dead_code)]
739    pub(crate) fn check_next_batch(&self, other: &Batch) -> Result<(), String> {
740        // Checks the primary key
741        if self.primary_key() < other.primary_key() {
742            return Ok(());
743        }
744        if self.primary_key() > other.primary_key() {
745            return Err(format!(
746                "primary key is not monotonic: {:?} > {:?}",
747                self.primary_key(),
748                other.primary_key()
749            ));
750        }
751        // Checks the timestamp.
752        if self.last_timestamp() < other.first_timestamp() {
753            return Ok(());
754        }
755        if self.last_timestamp() > other.first_timestamp() {
756            return Err(format!(
757                "timestamps are not monotonic: {:?} > {:?}",
758                self.last_timestamp(),
759                other.first_timestamp()
760            ));
761        }
762        // Checks the sequence.
763        if self.last_sequence() >= other.first_sequence() {
764            return Ok(());
765        }
766        Err(format!(
767            "sequences are not monotonic: {:?} < {:?}",
768            self.last_sequence(),
769            other.first_sequence()
770        ))
771    }
772
773    /// Returns the value of the column in the primary key.
774    ///
775    /// Lazily decodes the primary key and caches the result.
776    pub fn pk_col_value(
777        &mut self,
778        codec: &dyn PrimaryKeyCodec,
779        col_idx_in_pk: usize,
780        column_id: ColumnId,
781    ) -> Result<Option<&Value>> {
782        if self.pk_values.is_none() {
783            self.pk_values = Some(codec.decode(&self.primary_key).context(DecodeSnafu)?);
784        }
785
786        let pk_values = self.pk_values.as_ref().unwrap();
787        Ok(match pk_values {
788            CompositeValues::Dense(values) => values.get(col_idx_in_pk).map(|(_, v)| v),
789            CompositeValues::Sparse(values) => values.get(&column_id),
790        })
791    }
792
793    /// Returns values of the field in the batch.
794    ///
795    /// Lazily caches the field index.
796    pub fn field_col_value(&mut self, column_id: ColumnId) -> Option<&BatchColumn> {
797        if self.fields_idx.is_none() {
798            self.fields_idx = Some(
799                self.fields
800                    .iter()
801                    .enumerate()
802                    .map(|(i, c)| (c.column_id, i))
803                    .collect(),
804            );
805        }
806
807        self.fields_idx
808            .as_ref()
809            .unwrap()
810            .get(&column_id)
811            .map(|&idx| &self.fields[idx])
812    }
813}
814
815/// A struct to check the batch is monotonic.
816#[cfg(debug_assertions)]
817#[derive(Default)]
818#[allow(dead_code)]
819pub(crate) struct BatchChecker {
820    last_batch: Option<Batch>,
821    start: Option<Timestamp>,
822    end: Option<Timestamp>,
823}
824
825#[cfg(debug_assertions)]
826#[allow(dead_code)]
827impl BatchChecker {
828    /// Attaches the given start timestamp to the checker.
829    pub(crate) fn with_start(mut self, start: Option<Timestamp>) -> Self {
830        self.start = start;
831        self
832    }
833
834    /// Attaches the given end timestamp to the checker.
835    pub(crate) fn with_end(mut self, end: Option<Timestamp>) -> Self {
836        self.end = end;
837        self
838    }
839
840    /// Returns true if the given batch is monotonic and behind
841    /// the last batch.
842    pub(crate) fn check_monotonic(&mut self, batch: &Batch) -> Result<(), String> {
843        batch.check_monotonic()?;
844
845        if let (Some(start), Some(first)) = (self.start, batch.first_timestamp())
846            && start > first
847        {
848            return Err(format!(
849                "batch's first timestamp is before the start timestamp: {:?} > {:?}",
850                start, first
851            ));
852        }
853        if let (Some(end), Some(last)) = (self.end, batch.last_timestamp())
854            && end <= last
855        {
856            return Err(format!(
857                "batch's last timestamp is after the end timestamp: {:?} <= {:?}",
858                end, last
859            ));
860        }
861
862        // Checks the batch is behind the last batch.
863        // Then Updates the last batch.
864        let res = self
865            .last_batch
866            .as_ref()
867            .map(|last| last.check_next_batch(batch))
868            .unwrap_or(Ok(()));
869        self.last_batch = Some(batch.clone());
870        res
871    }
872
873    /// Formats current batch and last batch for debug.
874    pub(crate) fn format_batch(&self, batch: &Batch) -> String {
875        use std::fmt::Write;
876
877        let mut message = String::new();
878        if let Some(last) = &self.last_batch {
879            write!(
880                message,
881                "last_pk: {:?}, last_ts: {:?}, last_seq: {:?}, ",
882                last.primary_key(),
883                last.last_timestamp(),
884                last.last_sequence()
885            )
886            .unwrap();
887        }
888        write!(
889            message,
890            "batch_pk: {:?}, batch_ts: {:?}, batch_seq: {:?}",
891            batch.primary_key(),
892            batch.timestamps(),
893            batch.sequences()
894        )
895        .unwrap();
896
897        message
898    }
899
900    /// Checks batches from the part range are monotonic. Otherwise, panics.
901    pub(crate) fn ensure_part_range_batch(
902        &mut self,
903        scanner: &str,
904        region_id: store_api::storage::RegionId,
905        partition: usize,
906        part_range: store_api::region_engine::PartitionRange,
907        batch: &Batch,
908    ) {
909        if let Err(e) = self.check_monotonic(batch) {
910            let err_msg = format!(
911                "{}: batch is not sorted, {}, region_id: {}, partition: {}, part_range: {:?}",
912                scanner, e, region_id, partition, part_range,
913            );
914            common_telemetry::error!("{err_msg}, {}", self.format_batch(batch));
915            // Only print the number of row in the panic message.
916            panic!("{err_msg}, batch rows: {}", batch.num_rows());
917        }
918    }
919}
920
921/// Len of timestamp in arrow row format.
922const TIMESTAMP_KEY_LEN: usize = 9;
923
924/// Helper function to concat arrays from `iter`.
925fn concat_arrays(iter: impl Iterator<Item = ArrayRef>) -> Result<ArrayRef> {
926    let arrays: Vec<_> = iter.collect();
927    let dyn_arrays: Vec<_> = arrays.iter().map(|array| array.as_ref()).collect();
928    arrow::compute::concat(&dyn_arrays).context(ComputeArrowSnafu)
929}
930
931/// A column in a [Batch].
932#[derive(Debug, PartialEq, Eq, Clone)]
933pub struct BatchColumn {
934    /// Id of the column.
935    pub column_id: ColumnId,
936    /// Data of the column.
937    pub data: VectorRef,
938}
939
940/// Builder to build [Batch].
941pub struct BatchBuilder {
942    primary_key: Vec<u8>,
943    timestamps: Option<VectorRef>,
944    sequences: Option<Arc<UInt64Vector>>,
945    op_types: Option<Arc<UInt8Vector>>,
946    fields: Vec<BatchColumn>,
947}
948
949impl BatchBuilder {
950    /// Creates a new [BatchBuilder] with primary key.
951    pub fn new(primary_key: Vec<u8>) -> BatchBuilder {
952        BatchBuilder {
953            primary_key,
954            timestamps: None,
955            sequences: None,
956            op_types: None,
957            fields: Vec::new(),
958        }
959    }
960
961    /// Creates a new [BatchBuilder] with all required columns.
962    pub fn with_required_columns(
963        primary_key: Vec<u8>,
964        timestamps: VectorRef,
965        sequences: Arc<UInt64Vector>,
966        op_types: Arc<UInt8Vector>,
967    ) -> BatchBuilder {
968        BatchBuilder {
969            primary_key,
970            timestamps: Some(timestamps),
971            sequences: Some(sequences),
972            op_types: Some(op_types),
973            fields: Vec::new(),
974        }
975    }
976
977    /// Set all field columns.
978    pub fn with_fields(mut self, fields: Vec<BatchColumn>) -> Self {
979        self.fields = fields;
980        self
981    }
982
983    /// Push a field column.
984    pub fn push_field(&mut self, column: BatchColumn) -> &mut Self {
985        self.fields.push(column);
986        self
987    }
988
989    /// Push an array as a field.
990    pub fn push_field_array(&mut self, column_id: ColumnId, array: ArrayRef) -> Result<&mut Self> {
991        let vector = Helper::try_into_vector(array).context(ConvertVectorSnafu)?;
992        self.fields.push(BatchColumn {
993            column_id,
994            data: vector,
995        });
996
997        Ok(self)
998    }
999
1000    /// Try to set an array as timestamps.
1001    pub fn timestamps_array(&mut self, array: ArrayRef) -> Result<&mut Self> {
1002        let vector = Helper::try_into_vector(array).context(ConvertVectorSnafu)?;
1003        ensure!(
1004            vector.data_type().is_timestamp(),
1005            InvalidBatchSnafu {
1006                reason: format!("{:?} is not a timestamp type", vector.data_type()),
1007            }
1008        );
1009
1010        self.timestamps = Some(vector);
1011        Ok(self)
1012    }
1013
1014    /// Try to set an array as sequences.
1015    pub fn sequences_array(&mut self, array: ArrayRef) -> Result<&mut Self> {
1016        ensure!(
1017            *array.data_type() == arrow::datatypes::DataType::UInt64,
1018            InvalidBatchSnafu {
1019                reason: "sequence array is not UInt64 type",
1020            }
1021        );
1022        // Safety: The cast must success as we have ensured it is uint64 type.
1023        let vector = Arc::new(UInt64Vector::try_from_arrow_array(array).unwrap());
1024        self.sequences = Some(vector);
1025
1026        Ok(self)
1027    }
1028
1029    /// Try to set an array as op types.
1030    pub fn op_types_array(&mut self, array: ArrayRef) -> Result<&mut Self> {
1031        ensure!(
1032            *array.data_type() == arrow::datatypes::DataType::UInt8,
1033            InvalidBatchSnafu {
1034                reason: "sequence array is not UInt8 type",
1035            }
1036        );
1037        // Safety: The cast must success as we have ensured it is uint64 type.
1038        let vector = Arc::new(UInt8Vector::try_from_arrow_array(array).unwrap());
1039        self.op_types = Some(vector);
1040
1041        Ok(self)
1042    }
1043
1044    /// Builds the [Batch].
1045    pub fn build(self) -> Result<Batch> {
1046        let timestamps = self.timestamps.context(InvalidBatchSnafu {
1047            reason: "missing timestamps",
1048        })?;
1049        let sequences = self.sequences.context(InvalidBatchSnafu {
1050            reason: "missing sequences",
1051        })?;
1052        let op_types = self.op_types.context(InvalidBatchSnafu {
1053            reason: "missing op_types",
1054        })?;
1055        // Our storage format ensure these columns are not nullable so
1056        // we use assert here.
1057        assert_eq!(0, timestamps.null_count());
1058        assert_eq!(0, sequences.null_count());
1059        assert_eq!(0, op_types.null_count());
1060
1061        let ts_len = timestamps.len();
1062        ensure!(
1063            sequences.len() == ts_len,
1064            InvalidBatchSnafu {
1065                reason: format!(
1066                    "sequence have different len {} != {}",
1067                    sequences.len(),
1068                    ts_len
1069                ),
1070            }
1071        );
1072        ensure!(
1073            op_types.len() == ts_len,
1074            InvalidBatchSnafu {
1075                reason: format!(
1076                    "op type have different len {} != {}",
1077                    op_types.len(),
1078                    ts_len
1079                ),
1080            }
1081        );
1082        for column in &self.fields {
1083            ensure!(
1084                column.data.len() == ts_len,
1085                InvalidBatchSnafu {
1086                    reason: format!(
1087                        "column {} has different len {} != {}",
1088                        column.column_id,
1089                        column.data.len(),
1090                        ts_len
1091                    ),
1092                }
1093            );
1094        }
1095
1096        Ok(Batch {
1097            primary_key: self.primary_key,
1098            pk_values: None,
1099            timestamps,
1100            sequences,
1101            op_types,
1102            fields: self.fields,
1103            fields_idx: None,
1104        })
1105    }
1106}
1107
1108impl From<Batch> for BatchBuilder {
1109    fn from(batch: Batch) -> Self {
1110        Self {
1111            primary_key: batch.primary_key,
1112            timestamps: Some(batch.timestamps),
1113            sequences: Some(batch.sequences),
1114            op_types: Some(batch.op_types),
1115            fields: batch.fields,
1116        }
1117    }
1118}
1119
1120/// Async [Batch] reader and iterator wrapper.
1121///
1122/// This is the data source for SST writers or internal readers.
1123pub enum Source {
1124    /// Source from a [BoxedBatchReader].
1125    Reader(BoxedBatchReader),
1126    /// Source from a [BoxedBatchIterator].
1127    Iter(BoxedBatchIterator),
1128    /// Source from a [BoxedBatchStream].
1129    Stream(BoxedBatchStream),
1130}
1131
1132impl Source {
1133    /// Returns next [Batch] from this data source.
1134    pub async fn next_batch(&mut self) -> Result<Option<Batch>> {
1135        match self {
1136            Source::Reader(reader) => reader.next_batch().await,
1137            Source::Iter(iter) => iter.next().transpose(),
1138            Source::Stream(stream) => stream.try_next().await,
1139        }
1140    }
1141}
1142
1143/// Async [RecordBatch] reader and iterator wrapper for flat format.
1144pub struct FlatSource {
1145    schema: SchemaRef,
1146    inner: FlatSourceInner,
1147}
1148
1149impl FlatSource {
1150    /// Create a [FlatSource] from a [BoxedRecordBatchIterator] and its schema.
1151    pub fn new_iter(schema: SchemaRef, iter: BoxedRecordBatchIterator) -> Self {
1152        Self {
1153            schema,
1154            inner: FlatSourceInner::Iter(iter),
1155        }
1156    }
1157
1158    /// Create a [FlatSource] from a [BoxedRecordBatchStream] and its schema.
1159    pub fn new_stream(schema: SchemaRef, stream: BoxedRecordBatchStream) -> Self {
1160        Self {
1161            schema,
1162            inner: FlatSourceInner::Stream(stream),
1163        }
1164    }
1165
1166    pub(crate) fn schema(&self) -> &SchemaRef {
1167        &self.schema
1168    }
1169
1170    pub async fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
1171        self.inner.next_batch().await
1172    }
1173
1174    #[cfg(test)]
1175    pub(crate) fn take_iter(self) -> BoxedRecordBatchIterator {
1176        match self.inner {
1177            FlatSourceInner::Iter(iter) => iter,
1178            FlatSourceInner::Stream(_) => unreachable!(),
1179        }
1180    }
1181}
1182
1183enum FlatSourceInner {
1184    /// Source from a [BoxedRecordBatchIterator].
1185    Iter(BoxedRecordBatchIterator),
1186    /// Source from a [BoxedRecordBatchStream].
1187    Stream(BoxedRecordBatchStream),
1188}
1189
1190impl FlatSourceInner {
1191    /// Returns next [RecordBatch] from this data source.
1192    pub async fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
1193        match self {
1194            Self::Iter(iter) => iter.next().transpose(),
1195            Self::Stream(stream) => stream.try_next().await,
1196        }
1197    }
1198}
1199
1200/// Async batch reader.
1201///
1202/// The reader must guarantee [Batch]es returned by it have the same schema.
1203#[async_trait]
1204pub trait BatchReader: Send {
1205    /// Fetch next [Batch].
1206    ///
1207    /// Returns `Ok(None)` when the reader has reached its end and calling `next_batch()`
1208    /// again won't return batch again.
1209    ///
1210    /// If `Err` is returned, caller should not call this method again, the implementor
1211    /// may or may not panic in such case.
1212    async fn next_batch(&mut self) -> Result<Option<Batch>>;
1213}
1214
1215/// Pointer to [BatchReader].
1216pub type BoxedBatchReader = Box<dyn BatchReader>;
1217
1218/// Pointer to a stream that yields [Batch].
1219pub type BoxedBatchStream = BoxStream<'static, Result<Batch>>;
1220
1221/// Pointer to a stream that yields [RecordBatch].
1222pub type BoxedRecordBatchStream = BoxStream<'static, Result<RecordBatch>>;
1223
1224#[async_trait::async_trait]
1225impl<T: BatchReader + ?Sized> BatchReader for Box<T> {
1226    async fn next_batch(&mut self) -> Result<Option<Batch>> {
1227        (**self).next_batch().await
1228    }
1229}
1230
1231/// Local metrics for scanners.
1232#[derive(Debug, Default)]
1233pub(crate) struct ScannerMetrics {
1234    /// Duration to scan data.
1235    scan_cost: Duration,
1236    /// Duration while waiting for `yield`.
1237    yield_cost: Duration,
1238    /// Number of batches returned.
1239    num_batches: usize,
1240    /// Number of rows returned.
1241    num_rows: usize,
1242}
1243
1244#[cfg(test)]
1245mod tests {
1246    use datatypes::arrow::array::{TimestampMillisecondArray, UInt8Array, UInt64Array};
1247    use mito_codec::row_converter::{self, build_primary_key_codec_with_fields};
1248    use store_api::codec::PrimaryKeyEncoding;
1249    use store_api::storage::consts::ReservedColumnId;
1250
1251    use super::*;
1252    use crate::error::Error;
1253    use crate::test_util::new_batch_builder;
1254
1255    fn new_batch(
1256        timestamps: &[i64],
1257        sequences: &[u64],
1258        op_types: &[OpType],
1259        field: &[u64],
1260    ) -> Batch {
1261        new_batch_builder(b"test", timestamps, sequences, op_types, 1, field)
1262            .build()
1263            .unwrap()
1264    }
1265
1266    fn new_batch_with_u64_fields(
1267        timestamps: &[i64],
1268        sequences: &[u64],
1269        op_types: &[OpType],
1270        fields: &[(ColumnId, &[Option<u64>])],
1271    ) -> Batch {
1272        assert_eq!(timestamps.len(), sequences.len());
1273        assert_eq!(timestamps.len(), op_types.len());
1274        for (_, values) in fields {
1275            assert_eq!(timestamps.len(), values.len());
1276        }
1277
1278        let mut builder = BatchBuilder::new(b"test".to_vec());
1279        builder
1280            .timestamps_array(Arc::new(TimestampMillisecondArray::from_iter_values(
1281                timestamps.iter().copied(),
1282            )))
1283            .unwrap()
1284            .sequences_array(Arc::new(UInt64Array::from_iter_values(
1285                sequences.iter().copied(),
1286            )))
1287            .unwrap()
1288            .op_types_array(Arc::new(UInt8Array::from_iter_values(
1289                op_types.iter().map(|v| *v as u8),
1290            )))
1291            .unwrap();
1292
1293        for (col_id, values) in fields {
1294            builder
1295                .push_field_array(*col_id, Arc::new(UInt64Array::from(values.to_vec())))
1296                .unwrap();
1297        }
1298
1299        builder.build().unwrap()
1300    }
1301
1302    fn new_batch_without_fields(
1303        timestamps: &[i64],
1304        sequences: &[u64],
1305        op_types: &[OpType],
1306    ) -> Batch {
1307        assert_eq!(timestamps.len(), sequences.len());
1308        assert_eq!(timestamps.len(), op_types.len());
1309
1310        let mut builder = BatchBuilder::new(b"test".to_vec());
1311        builder
1312            .timestamps_array(Arc::new(TimestampMillisecondArray::from_iter_values(
1313                timestamps.iter().copied(),
1314            )))
1315            .unwrap()
1316            .sequences_array(Arc::new(UInt64Array::from_iter_values(
1317                sequences.iter().copied(),
1318            )))
1319            .unwrap()
1320            .op_types_array(Arc::new(UInt8Array::from_iter_values(
1321                op_types.iter().map(|v| *v as u8),
1322            )))
1323            .unwrap();
1324
1325        builder.build().unwrap()
1326    }
1327
1328    #[test]
1329    fn test_empty_batch() {
1330        let batch = Batch::empty();
1331        assert!(batch.is_empty());
1332        assert_eq!(None, batch.first_timestamp());
1333        assert_eq!(None, batch.last_timestamp());
1334        assert_eq!(None, batch.first_sequence());
1335        assert_eq!(None, batch.last_sequence());
1336        assert!(batch.timestamps_native().is_none());
1337    }
1338
1339    #[test]
1340    fn test_first_last_one() {
1341        let batch = new_batch(&[1], &[2], &[OpType::Put], &[4]);
1342        assert_eq!(
1343            Timestamp::new_millisecond(1),
1344            batch.first_timestamp().unwrap()
1345        );
1346        assert_eq!(
1347            Timestamp::new_millisecond(1),
1348            batch.last_timestamp().unwrap()
1349        );
1350        assert_eq!(2, batch.first_sequence().unwrap());
1351        assert_eq!(2, batch.last_sequence().unwrap());
1352    }
1353
1354    #[test]
1355    fn test_first_last_multiple() {
1356        let batch = new_batch(
1357            &[1, 2, 3],
1358            &[11, 12, 13],
1359            &[OpType::Put, OpType::Put, OpType::Put],
1360            &[21, 22, 23],
1361        );
1362        assert_eq!(
1363            Timestamp::new_millisecond(1),
1364            batch.first_timestamp().unwrap()
1365        );
1366        assert_eq!(
1367            Timestamp::new_millisecond(3),
1368            batch.last_timestamp().unwrap()
1369        );
1370        assert_eq!(11, batch.first_sequence().unwrap());
1371        assert_eq!(13, batch.last_sequence().unwrap());
1372    }
1373
1374    #[test]
1375    fn test_slice() {
1376        let batch = new_batch(
1377            &[1, 2, 3, 4],
1378            &[11, 12, 13, 14],
1379            &[OpType::Put, OpType::Delete, OpType::Put, OpType::Put],
1380            &[21, 22, 23, 24],
1381        );
1382        let batch = batch.slice(1, 2);
1383        let expect = new_batch(
1384            &[2, 3],
1385            &[12, 13],
1386            &[OpType::Delete, OpType::Put],
1387            &[22, 23],
1388        );
1389        assert_eq!(expect, batch);
1390    }
1391
1392    #[test]
1393    fn test_timestamps_native() {
1394        let batch = new_batch(
1395            &[1, 2, 3, 4],
1396            &[11, 12, 13, 14],
1397            &[OpType::Put, OpType::Delete, OpType::Put, OpType::Put],
1398            &[21, 22, 23, 24],
1399        );
1400        assert_eq!(&[1, 2, 3, 4], batch.timestamps_native().unwrap());
1401    }
1402
1403    #[test]
1404    fn test_concat_empty() {
1405        let err = Batch::concat(vec![]).unwrap_err();
1406        assert!(
1407            matches!(err, Error::InvalidBatch { .. }),
1408            "unexpected err: {err}"
1409        );
1410    }
1411
1412    #[test]
1413    fn test_concat_one() {
1414        let batch = new_batch(&[], &[], &[], &[]);
1415        let actual = Batch::concat(vec![batch.clone()]).unwrap();
1416        assert_eq!(batch, actual);
1417
1418        let batch = new_batch(&[1, 2], &[11, 12], &[OpType::Put, OpType::Put], &[21, 22]);
1419        let actual = Batch::concat(vec![batch.clone()]).unwrap();
1420        assert_eq!(batch, actual);
1421    }
1422
1423    #[test]
1424    fn test_concat_multiple() {
1425        let batches = vec![
1426            new_batch(&[1, 2], &[11, 12], &[OpType::Put, OpType::Put], &[21, 22]),
1427            new_batch(
1428                &[3, 4, 5],
1429                &[13, 14, 15],
1430                &[OpType::Put, OpType::Delete, OpType::Put],
1431                &[23, 24, 25],
1432            ),
1433            new_batch(&[], &[], &[], &[]),
1434            new_batch(&[6], &[16], &[OpType::Put], &[26]),
1435        ];
1436        let batch = Batch::concat(batches).unwrap();
1437        let expect = new_batch(
1438            &[1, 2, 3, 4, 5, 6],
1439            &[11, 12, 13, 14, 15, 16],
1440            &[
1441                OpType::Put,
1442                OpType::Put,
1443                OpType::Put,
1444                OpType::Delete,
1445                OpType::Put,
1446                OpType::Put,
1447            ],
1448            &[21, 22, 23, 24, 25, 26],
1449        );
1450        assert_eq!(expect, batch);
1451    }
1452
1453    #[test]
1454    fn test_concat_different() {
1455        let batch1 = new_batch(&[1], &[1], &[OpType::Put], &[1]);
1456        let mut batch2 = new_batch(&[2], &[2], &[OpType::Put], &[2]);
1457        batch2.primary_key = b"hello".to_vec();
1458        let err = Batch::concat(vec![batch1, batch2]).unwrap_err();
1459        assert!(
1460            matches!(err, Error::InvalidBatch { .. }),
1461            "unexpected err: {err}"
1462        );
1463    }
1464
1465    #[test]
1466    fn test_concat_different_fields() {
1467        let batch1 = new_batch(&[1], &[1], &[OpType::Put], &[1]);
1468        let fields = vec![
1469            batch1.fields()[0].clone(),
1470            BatchColumn {
1471                column_id: 2,
1472                data: Arc::new(UInt64Vector::from_slice([2])),
1473            },
1474        ];
1475        // Batch 2 has more fields.
1476        let batch2 = batch1.clone().with_fields(fields).unwrap();
1477        let err = Batch::concat(vec![batch1.clone(), batch2]).unwrap_err();
1478        assert!(
1479            matches!(err, Error::InvalidBatch { .. }),
1480            "unexpected err: {err}"
1481        );
1482
1483        // Batch 2 has different field.
1484        let fields = vec![BatchColumn {
1485            column_id: 2,
1486            data: Arc::new(UInt64Vector::from_slice([2])),
1487        }];
1488        let batch2 = batch1.clone().with_fields(fields).unwrap();
1489        let err = Batch::concat(vec![batch1, batch2]).unwrap_err();
1490        assert!(
1491            matches!(err, Error::InvalidBatch { .. }),
1492            "unexpected err: {err}"
1493        );
1494    }
1495
1496    #[test]
1497    fn test_filter_deleted_empty() {
1498        let mut batch = new_batch(&[], &[], &[], &[]);
1499        batch.filter_deleted().unwrap();
1500        assert!(batch.is_empty());
1501    }
1502
1503    #[test]
1504    fn test_filter_deleted() {
1505        let mut batch = new_batch(
1506            &[1, 2, 3, 4],
1507            &[11, 12, 13, 14],
1508            &[OpType::Delete, OpType::Put, OpType::Delete, OpType::Put],
1509            &[21, 22, 23, 24],
1510        );
1511        batch.filter_deleted().unwrap();
1512        let expect = new_batch(&[2, 4], &[12, 14], &[OpType::Put, OpType::Put], &[22, 24]);
1513        assert_eq!(expect, batch);
1514
1515        let mut batch = new_batch(
1516            &[1, 2, 3, 4],
1517            &[11, 12, 13, 14],
1518            &[OpType::Put, OpType::Put, OpType::Put, OpType::Put],
1519            &[21, 22, 23, 24],
1520        );
1521        let expect = batch.clone();
1522        batch.filter_deleted().unwrap();
1523        assert_eq!(expect, batch);
1524    }
1525
1526    #[test]
1527    fn test_filter_by_sequence() {
1528        // Filters put only.
1529        let mut batch = new_batch(
1530            &[1, 2, 3, 4],
1531            &[11, 12, 13, 14],
1532            &[OpType::Put, OpType::Put, OpType::Put, OpType::Put],
1533            &[21, 22, 23, 24],
1534        );
1535        batch
1536            .filter_by_sequence(Some(SequenceRange::LtEq { max: 13 }))
1537            .unwrap();
1538        let expect = new_batch(
1539            &[1, 2, 3],
1540            &[11, 12, 13],
1541            &[OpType::Put, OpType::Put, OpType::Put],
1542            &[21, 22, 23],
1543        );
1544        assert_eq!(expect, batch);
1545
1546        // Filters to empty.
1547        let mut batch = new_batch(
1548            &[1, 2, 3, 4],
1549            &[11, 12, 13, 14],
1550            &[OpType::Put, OpType::Delete, OpType::Put, OpType::Put],
1551            &[21, 22, 23, 24],
1552        );
1553
1554        batch
1555            .filter_by_sequence(Some(SequenceRange::LtEq { max: 10 }))
1556            .unwrap();
1557        assert!(batch.is_empty());
1558
1559        // None filter.
1560        let mut batch = new_batch(
1561            &[1, 2, 3, 4],
1562            &[11, 12, 13, 14],
1563            &[OpType::Put, OpType::Delete, OpType::Put, OpType::Put],
1564            &[21, 22, 23, 24],
1565        );
1566        let expect = batch.clone();
1567        batch.filter_by_sequence(None).unwrap();
1568        assert_eq!(expect, batch);
1569
1570        // Filter a empty batch
1571        let mut batch = new_batch(&[], &[], &[], &[]);
1572        batch
1573            .filter_by_sequence(Some(SequenceRange::LtEq { max: 10 }))
1574            .unwrap();
1575        assert!(batch.is_empty());
1576
1577        // Filter a empty batch with None
1578        let mut batch = new_batch(&[], &[], &[], &[]);
1579        batch.filter_by_sequence(None).unwrap();
1580        assert!(batch.is_empty());
1581
1582        // Test From variant - exclusive lower bound
1583        let mut batch = new_batch(
1584            &[1, 2, 3, 4],
1585            &[11, 12, 13, 14],
1586            &[OpType::Put, OpType::Put, OpType::Put, OpType::Put],
1587            &[21, 22, 23, 24],
1588        );
1589        batch
1590            .filter_by_sequence(Some(SequenceRange::Gt { min: 12 }))
1591            .unwrap();
1592        let expect = new_batch(&[3, 4], &[13, 14], &[OpType::Put, OpType::Put], &[23, 24]);
1593        assert_eq!(expect, batch);
1594
1595        // Test From variant with no matches
1596        let mut batch = new_batch(
1597            &[1, 2, 3, 4],
1598            &[11, 12, 13, 14],
1599            &[OpType::Put, OpType::Delete, OpType::Put, OpType::Put],
1600            &[21, 22, 23, 24],
1601        );
1602        batch
1603            .filter_by_sequence(Some(SequenceRange::Gt { min: 20 }))
1604            .unwrap();
1605        assert!(batch.is_empty());
1606
1607        // Test Range variant - exclusive lower bound, inclusive upper bound
1608        let mut batch = new_batch(
1609            &[1, 2, 3, 4, 5],
1610            &[11, 12, 13, 14, 15],
1611            &[
1612                OpType::Put,
1613                OpType::Put,
1614                OpType::Put,
1615                OpType::Put,
1616                OpType::Put,
1617            ],
1618            &[21, 22, 23, 24, 25],
1619        );
1620        batch
1621            .filter_by_sequence(Some(SequenceRange::GtLtEq { min: 12, max: 14 }))
1622            .unwrap();
1623        let expect = new_batch(&[3, 4], &[13, 14], &[OpType::Put, OpType::Put], &[23, 24]);
1624        assert_eq!(expect, batch);
1625
1626        // Test Range variant with mixed operations
1627        let mut batch = new_batch(
1628            &[1, 2, 3, 4, 5],
1629            &[11, 12, 13, 14, 15],
1630            &[
1631                OpType::Put,
1632                OpType::Delete,
1633                OpType::Put,
1634                OpType::Delete,
1635                OpType::Put,
1636            ],
1637            &[21, 22, 23, 24, 25],
1638        );
1639        batch
1640            .filter_by_sequence(Some(SequenceRange::GtLtEq { min: 11, max: 13 }))
1641            .unwrap();
1642        let expect = new_batch(
1643            &[2, 3],
1644            &[12, 13],
1645            &[OpType::Delete, OpType::Put],
1646            &[22, 23],
1647        );
1648        assert_eq!(expect, batch);
1649
1650        // Test Range variant with no matches
1651        let mut batch = new_batch(
1652            &[1, 2, 3, 4],
1653            &[11, 12, 13, 14],
1654            &[OpType::Put, OpType::Put, OpType::Put, OpType::Put],
1655            &[21, 22, 23, 24],
1656        );
1657        batch
1658            .filter_by_sequence(Some(SequenceRange::GtLtEq { min: 20, max: 25 }))
1659            .unwrap();
1660        assert!(batch.is_empty());
1661    }
1662
1663    #[test]
1664    fn test_merge_last_non_null_no_dup() {
1665        let mut batch = new_batch_with_u64_fields(
1666            &[1, 2],
1667            &[2, 1],
1668            &[OpType::Put, OpType::Put],
1669            &[(1, &[Some(10), None]), (2, &[Some(100), Some(200)])],
1670        );
1671        let expect = batch.clone();
1672        batch.merge_last_non_null().unwrap();
1673        assert_eq!(expect, batch);
1674    }
1675
1676    #[test]
1677    fn test_merge_last_non_null_fill_null_fields() {
1678        // Rows are already sorted by timestamp asc and sequence desc.
1679        let mut batch = new_batch_with_u64_fields(
1680            &[1, 1, 1],
1681            &[3, 2, 1],
1682            &[OpType::Put, OpType::Put, OpType::Put],
1683            &[
1684                (1, &[None, Some(10), Some(11)]),
1685                (2, &[Some(100), Some(200), Some(300)]),
1686            ],
1687        );
1688        batch.merge_last_non_null().unwrap();
1689
1690        // Field 1 is filled from the first older row (seq=2). Field 2 keeps the base value.
1691        // Filled fields must not be overwritten by even older duplicates.
1692        let expect = new_batch_with_u64_fields(
1693            &[1],
1694            &[3],
1695            &[OpType::Put],
1696            &[(1, &[Some(10)]), (2, &[Some(100)])],
1697        );
1698        assert_eq!(expect, batch);
1699    }
1700
1701    #[test]
1702    fn test_merge_last_non_null_stop_at_delete_row() {
1703        // A delete row in older duplicates should stop filling to avoid resurrecting values before
1704        // deletion.
1705        let mut batch = new_batch_with_u64_fields(
1706            &[1, 1, 1],
1707            &[3, 2, 1],
1708            &[OpType::Put, OpType::Delete, OpType::Put],
1709            &[
1710                (1, &[None, Some(10), Some(11)]),
1711                (2, &[Some(100), Some(200), Some(300)]),
1712            ],
1713        );
1714        batch.merge_last_non_null().unwrap();
1715
1716        let expect = new_batch_with_u64_fields(
1717            &[1],
1718            &[3],
1719            &[OpType::Put],
1720            &[(1, &[None]), (2, &[Some(100)])],
1721        );
1722        assert_eq!(expect, batch);
1723    }
1724
1725    #[test]
1726    fn test_merge_last_non_null_base_delete_no_merge() {
1727        let mut batch = new_batch_with_u64_fields(
1728            &[1, 1],
1729            &[3, 2],
1730            &[OpType::Delete, OpType::Put],
1731            &[(1, &[None, Some(10)]), (2, &[None, Some(200)])],
1732        );
1733        batch.merge_last_non_null().unwrap();
1734
1735        // Base row is delete, keep it as is and don't merge fields from older rows.
1736        let expect =
1737            new_batch_with_u64_fields(&[1], &[3], &[OpType::Delete], &[(1, &[None]), (2, &[None])]);
1738        assert_eq!(expect, batch);
1739    }
1740
1741    #[test]
1742    fn test_merge_last_non_null_multiple_timestamp_groups() {
1743        let mut batch = new_batch_with_u64_fields(
1744            &[1, 1, 2, 3, 3],
1745            &[5, 4, 3, 2, 1],
1746            &[
1747                OpType::Put,
1748                OpType::Put,
1749                OpType::Put,
1750                OpType::Put,
1751                OpType::Put,
1752            ],
1753            &[
1754                (1, &[None, Some(10), Some(20), None, Some(30)]),
1755                (2, &[Some(100), Some(110), Some(120), None, Some(130)]),
1756            ],
1757        );
1758        batch.merge_last_non_null().unwrap();
1759
1760        let expect = new_batch_with_u64_fields(
1761            &[1, 2, 3],
1762            &[5, 3, 2],
1763            &[OpType::Put, OpType::Put, OpType::Put],
1764            &[
1765                (1, &[Some(10), Some(20), Some(30)]),
1766                (2, &[Some(100), Some(120), Some(130)]),
1767            ],
1768        );
1769        assert_eq!(expect, batch);
1770    }
1771
1772    #[test]
1773    fn test_merge_last_non_null_no_fields() {
1774        let mut batch = new_batch_without_fields(
1775            &[1, 1, 2],
1776            &[3, 2, 1],
1777            &[OpType::Put, OpType::Put, OpType::Put],
1778        );
1779        batch.merge_last_non_null().unwrap();
1780
1781        let expect = new_batch_without_fields(&[1, 2], &[3, 1], &[OpType::Put, OpType::Put]);
1782        assert_eq!(expect, batch);
1783    }
1784
1785    #[test]
1786    fn test_filter() {
1787        // Filters put only.
1788        let mut batch = new_batch(
1789            &[1, 2, 3, 4],
1790            &[11, 12, 13, 14],
1791            &[OpType::Put, OpType::Put, OpType::Put, OpType::Put],
1792            &[21, 22, 23, 24],
1793        );
1794        let predicate = BooleanVector::from_vec(vec![false, false, true, true]);
1795        batch.filter(&predicate).unwrap();
1796        let expect = new_batch(&[3, 4], &[13, 14], &[OpType::Put, OpType::Put], &[23, 24]);
1797        assert_eq!(expect, batch);
1798
1799        // Filters deletion.
1800        let mut batch = new_batch(
1801            &[1, 2, 3, 4],
1802            &[11, 12, 13, 14],
1803            &[OpType::Put, OpType::Delete, OpType::Put, OpType::Put],
1804            &[21, 22, 23, 24],
1805        );
1806        let predicate = BooleanVector::from_vec(vec![false, false, true, true]);
1807        batch.filter(&predicate).unwrap();
1808        let expect = new_batch(&[3, 4], &[13, 14], &[OpType::Put, OpType::Put], &[23, 24]);
1809        assert_eq!(expect, batch);
1810
1811        // Filters to empty.
1812        let predicate = BooleanVector::from_vec(vec![false, false]);
1813        batch.filter(&predicate).unwrap();
1814        assert!(batch.is_empty());
1815    }
1816
1817    #[test]
1818    fn test_sort_and_dedup() {
1819        let original = new_batch(
1820            &[2, 3, 1, 4, 5, 2],
1821            &[1, 2, 3, 4, 5, 6],
1822            &[
1823                OpType::Put,
1824                OpType::Put,
1825                OpType::Put,
1826                OpType::Put,
1827                OpType::Put,
1828                OpType::Put,
1829            ],
1830            &[21, 22, 23, 24, 25, 26],
1831        );
1832
1833        let mut batch = original.clone();
1834        batch.sort(true).unwrap();
1835        // It should only keep one timestamp 2.
1836        assert_eq!(
1837            new_batch(
1838                &[1, 2, 3, 4, 5],
1839                &[3, 6, 2, 4, 5],
1840                &[
1841                    OpType::Put,
1842                    OpType::Put,
1843                    OpType::Put,
1844                    OpType::Put,
1845                    OpType::Put,
1846                ],
1847                &[23, 26, 22, 24, 25],
1848            ),
1849            batch
1850        );
1851
1852        let mut batch = original.clone();
1853        batch.sort(false).unwrap();
1854
1855        // It should only keep one timestamp 2.
1856        assert_eq!(
1857            new_batch(
1858                &[1, 2, 2, 3, 4, 5],
1859                &[3, 6, 1, 2, 4, 5],
1860                &[
1861                    OpType::Put,
1862                    OpType::Put,
1863                    OpType::Put,
1864                    OpType::Put,
1865                    OpType::Put,
1866                    OpType::Put,
1867                ],
1868                &[23, 26, 21, 22, 24, 25],
1869            ),
1870            batch
1871        );
1872
1873        let original = new_batch(
1874            &[2, 2, 1],
1875            &[1, 6, 1],
1876            &[OpType::Delete, OpType::Put, OpType::Put],
1877            &[21, 22, 23],
1878        );
1879
1880        let mut batch = original.clone();
1881        batch.sort(true).unwrap();
1882        let expect = new_batch(&[1, 2], &[1, 6], &[OpType::Put, OpType::Put], &[23, 22]);
1883        assert_eq!(expect, batch);
1884
1885        let mut batch = original.clone();
1886        batch.sort(false).unwrap();
1887        let expect = new_batch(
1888            &[1, 2, 2],
1889            &[1, 6, 1],
1890            &[OpType::Put, OpType::Put, OpType::Delete],
1891            &[23, 22, 21],
1892        );
1893        assert_eq!(expect, batch);
1894    }
1895
1896    #[test]
1897    fn test_get_value() {
1898        let encodings = [PrimaryKeyEncoding::Dense, PrimaryKeyEncoding::Sparse];
1899
1900        for encoding in encodings {
1901            let codec = build_primary_key_codec_with_fields(
1902                encoding,
1903                [
1904                    (
1905                        ReservedColumnId::table_id(),
1906                        row_converter::SortField::new(ConcreteDataType::uint32_datatype()),
1907                    ),
1908                    (
1909                        ReservedColumnId::tsid(),
1910                        row_converter::SortField::new(ConcreteDataType::uint64_datatype()),
1911                    ),
1912                    (
1913                        100,
1914                        row_converter::SortField::new(ConcreteDataType::string_datatype()),
1915                    ),
1916                    (
1917                        200,
1918                        row_converter::SortField::new(ConcreteDataType::string_datatype()),
1919                    ),
1920                ]
1921                .into_iter(),
1922            );
1923
1924            let values = [
1925                Value::UInt32(1000),
1926                Value::UInt64(2000),
1927                Value::String("abcdefgh".into()),
1928                Value::String("zyxwvu".into()),
1929            ];
1930            let mut buf = vec![];
1931            codec
1932                .encode_values(
1933                    &[
1934                        (ReservedColumnId::table_id(), values[0].clone()),
1935                        (ReservedColumnId::tsid(), values[1].clone()),
1936                        (100, values[2].clone()),
1937                        (200, values[3].clone()),
1938                    ],
1939                    &mut buf,
1940                )
1941                .unwrap();
1942
1943            let field_col_id = 2;
1944            let mut batch = new_batch_builder(
1945                &buf,
1946                &[1, 2, 3],
1947                &[1, 1, 1],
1948                &[OpType::Put, OpType::Put, OpType::Put],
1949                field_col_id,
1950                &[42, 43, 44],
1951            )
1952            .build()
1953            .unwrap();
1954
1955            let v = batch
1956                .pk_col_value(&*codec, 0, ReservedColumnId::table_id())
1957                .unwrap()
1958                .unwrap();
1959            assert_eq!(values[0], *v);
1960
1961            let v = batch
1962                .pk_col_value(&*codec, 1, ReservedColumnId::tsid())
1963                .unwrap()
1964                .unwrap();
1965            assert_eq!(values[1], *v);
1966
1967            let v = batch.pk_col_value(&*codec, 2, 100).unwrap().unwrap();
1968            assert_eq!(values[2], *v);
1969
1970            let v = batch.pk_col_value(&*codec, 3, 200).unwrap().unwrap();
1971            assert_eq!(values[3], *v);
1972
1973            let v = batch.field_col_value(field_col_id).unwrap();
1974            assert_eq!(v.data.get(0), Value::UInt64(42));
1975            assert_eq!(v.data.get(1), Value::UInt64(43));
1976            assert_eq!(v.data.get(2), Value::UInt64(44));
1977        }
1978    }
1979}