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