Skip to main content

mito2/sst/parquet/
flat_format.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//! Format to store in parquet.
16//!
17//! It can store both encoded primary key and raw key columns.
18//!
19//! We store two additional internal columns at last:
20//! - `__primary_key`, the encoded primary key of the row (tags). Type: dictionary(uint32, binary)
21//! - `__sequence`, the sequence number of a row. Type: uint64
22//! - `__op_type`, the op type of the row. Type: uint8
23//!
24//! The format is
25//! ```text
26//! primary key columns, field columns, time index, encoded primary key, __sequence, __op_type.
27//!
28//! It stores field columns in the same order as [RegionMetadata::field_columns()](store_api::metadata::RegionMetadata::field_columns())
29//! and stores primary key columns in the same order as [RegionMetadata::primary_key].
30
31use std::borrow::Borrow;
32use std::collections::HashMap;
33use std::sync::Arc;
34
35use api::v1::SemanticType;
36use datatypes::arrow::array::{
37    Array, ArrayRef, BinaryArray, DictionaryArray, UInt32Array, UInt64Array,
38};
39use datatypes::arrow::compute::kernels::take::take;
40use datatypes::arrow::datatypes::{DataType as ArrowDataType, Schema, SchemaRef};
41use datatypes::arrow::record_batch::RecordBatch;
42use datatypes::prelude::{ConcreteDataType, DataType};
43use datatypes::value::ValueRef;
44use datatypes::vectors::MutableVector;
45use mito_codec::row_converter::sparse::{
46    RESERVED_COLUMN_ID_TABLE_ID, RESERVED_COLUMN_ID_TSID, SparsePrimaryKeyView,
47};
48use mito_codec::row_converter::{
49    DensePrimaryKeyCodec, PrimaryKeyCodec, SparseOffsetsCache, build_primary_key_codec,
50};
51use parquet::file::metadata::RowGroupMetaData;
52use snafu::{OptionExt, ResultExt, ensure};
53use store_api::codec::PrimaryKeyEncoding;
54use store_api::metadata::{RegionMetadata, RegionMetadataRef};
55use store_api::storage::{ColumnId, SequenceNumber};
56
57use crate::error::{
58    ComputeArrowSnafu, DecodeSnafu, InvalidParquetSnafu, InvalidRecordBatchSnafu,
59    NewRecordBatchSnafu, Result,
60};
61use crate::read::read_columns::{JsonTargetTypes, ReadColumns};
62use crate::sst::parquet::format::{
63    FIXED_POS_COLUMN_NUM, FormatProjection, INTERNAL_COLUMN_NUM, PrimaryKeyArray,
64    PrimaryKeyReadFormat, StatValues, column_null_counts, column_values,
65};
66use crate::sst::parquet::read_columns::ParquetReadColumns;
67use crate::sst::{
68    FlatSchemaOptions, flat_sst_arrow_schema_column_num, tag_maybe_to_dictionary_field,
69    to_flat_sst_arrow_schema, with_field_id,
70};
71
72/// Helper for writing the SST format.
73pub(crate) struct FlatWriteFormat {
74    /// SST file schema.
75    arrow_schema: SchemaRef,
76    override_sequence: Option<SequenceNumber>,
77}
78
79impl FlatWriteFormat {
80    /// Creates a new helper.
81    pub(crate) fn new(metadata: RegionMetadataRef, options: &FlatSchemaOptions) -> FlatWriteFormat {
82        let arrow_schema = to_flat_sst_arrow_schema(&metadata, options);
83        FlatWriteFormat {
84            arrow_schema,
85            override_sequence: None,
86        }
87    }
88
89    /// Set override sequence.
90    pub(crate) fn with_override_sequence(
91        mut self,
92        override_sequence: Option<SequenceNumber>,
93    ) -> Self {
94        self.override_sequence = override_sequence;
95        self
96    }
97
98    /// Gets the arrow schema to store in parquet.
99    #[cfg(test)]
100    pub(crate) fn arrow_schema(&self) -> &SchemaRef {
101        &self.arrow_schema
102    }
103
104    /// Convert `batch` to a arrow record batch to store in parquet.
105    pub(crate) fn convert_batch(&self, batch: &RecordBatch) -> Result<RecordBatch> {
106        debug_assert_eq!(batch.num_columns(), self.arrow_schema.fields().len());
107
108        let Some(override_sequence) = self.override_sequence else {
109            return Ok(batch.clone());
110        };
111
112        let mut columns = batch.columns().to_vec();
113        let sequence_array = Arc::new(UInt64Array::from(vec![override_sequence; batch.num_rows()]));
114        columns[sequence_column_index(batch.num_columns())] = sequence_array;
115
116        RecordBatch::try_new(batch.schema(), columns).context(NewRecordBatchSnafu)
117    }
118}
119
120/// Returns the position of the sequence column.
121pub(crate) fn sequence_column_index(num_columns: usize) -> usize {
122    num_columns - 2
123}
124
125/// Returns the position of the time index column.
126pub(crate) fn time_index_column_index(num_columns: usize) -> usize {
127    num_columns - 4
128}
129
130/// Returns the position of the primary key column.
131pub(crate) fn primary_key_column_index(num_columns: usize) -> usize {
132    num_columns - 3
133}
134
135/// Wraps the `__primary_key` `BinaryArray` back into a `DictionaryArray<UInt32, Binary>` with identity keys.
136pub(crate) fn wrap_pk_binary_to_dict(
137    record_batch: RecordBatch,
138    dict_schema: &SchemaRef,
139) -> Result<RecordBatch> {
140    let pk_idx = primary_key_column_index(record_batch.num_columns());
141    let pk_column = record_batch.column(pk_idx);
142    let binary_array = pk_column
143        .as_any()
144        .downcast_ref::<BinaryArray>()
145        .with_context(|| InvalidRecordBatchSnafu {
146            reason: format!(
147                "expected BinaryArray for __primary_key, got {:?}",
148                pk_column.data_type()
149            ),
150        })?;
151    let n = binary_array.len();
152    let keys = UInt32Array::from_iter_values(0..n as u32);
153    let dict_array: ArrayRef = Arc::new(DictionaryArray::new(keys, pk_column.clone()));
154
155    let mut columns = record_batch.columns().to_vec();
156    columns[pk_idx] = dict_array;
157
158    RecordBatch::try_new(dict_schema.clone(), columns).context(NewRecordBatchSnafu)
159}
160
161/// Returns the position of the op type key column.
162pub(crate) fn op_type_column_index(num_columns: usize) -> usize {
163    num_columns - 1
164}
165
166/// Returns the start index of field columns in a flat batch.
167///
168/// `num_columns` is the total number of columns in the flat batch schema,
169/// including tag columns (if present), field columns, and fixed position columns
170/// (time index, primary key, sequence, op type).
171///
172/// For Dense encoding (raw PK columns included): field_column_start = primary_key.len()
173/// For Sparse encoding (no raw PK columns): field_column_start = 0
174pub(crate) fn field_column_start(metadata: &RegionMetadata, num_columns: usize) -> usize {
175    // Calculates field column start: total columns - fixed columns - field columns
176    // Field column count = total metadata columns - time index column - primary key columns
177    let field_column_count = metadata.column_metadatas.len() - 1 - metadata.primary_key.len();
178    num_columns - FIXED_POS_COLUMN_NUM - field_column_count
179}
180
181// TODO(yingwen): Add an option to skip reading internal columns if the region is
182// append only and doesn't use sparse encoding (We need to check the table id under
183// sparse encoding).
184/// Helper for reading the flat SST format with projection.
185///
186/// Physical Parquet projections describe stored columns and drive pruning and
187/// prefiltering. Converted projections describe batches returned by `convert_batch`.
188/// Sparse compaction can retain encoded-only tags; query reads may expand them.
189/// Neither layout is the final user projection. Compatibility aligns converted
190/// batches before merge; temporary predicate columns never change their layout.
191pub struct FlatReadFormat {
192    /// Sequence number to override the sequence read from the SST.
193    override_sequence: Option<SequenceNumber>,
194    /// Logical columns requested by this read.
195    read_cols: ReadColumns,
196    /// Parquet format adapter.
197    parquet_adapter: ParquetAdapter,
198    /// Output schema to wrap binary `__primary_key` back to a dictionary; `None` disables wrapping.
199    pk_dict_wrap_schema: Option<SchemaRef>,
200}
201
202impl FlatReadFormat {
203    /// Creates a helper with existing `metadata` and `column_ids` to read.
204    ///
205    /// If `skip_auto_convert` is true, skips auto conversion of format when the encoding is sparse encoding.
206    pub fn new(
207        metadata: RegionMetadataRef,
208        read_cols: ReadColumns,
209        file_schema: Option<SchemaRef>,
210        file_path: &str,
211        skip_auto_convert: bool,
212    ) -> Result<FlatReadFormat> {
213        let num_columns = file_schema.as_ref().map(|x| x.fields().len());
214        let is_legacy = match num_columns {
215            Some(num) => Self::is_legacy_format(&metadata, num, file_path)?,
216            None => metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse,
217        };
218
219        let parquet_adapter = if is_legacy {
220            // Safety: is_legacy_format() ensures primary_key is not empty.
221            if metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse {
222                // Only skip auto convert when the primary key encoding is sparse.
223                ParquetAdapter::PrimaryKeyToFlat(ParquetPrimaryKeyToFlat::new(
224                    metadata,
225                    read_cols.clone(),
226                    skip_auto_convert,
227                ))
228            } else {
229                ParquetAdapter::PrimaryKeyToFlat(ParquetPrimaryKeyToFlat::new(
230                    metadata,
231                    read_cols.clone(),
232                    false,
233                ))
234            }
235        } else {
236            let file_schema = file_schema
237                .unwrap_or_else(|| to_flat_sst_arrow_schema(&metadata, &Default::default()));
238            ParquetAdapter::Flat(ParquetFlat::new(metadata, read_cols.clone(), file_schema))
239        };
240
241        Ok(FlatReadFormat {
242            override_sequence: None,
243            read_cols,
244            parquet_adapter,
245            pk_dict_wrap_schema: None,
246        })
247    }
248
249    /// Sets the sequence number to override.
250    pub(crate) fn set_override_sequence(&mut self, sequence: Option<SequenceNumber>) {
251        self.override_sequence = sequence;
252    }
253
254    /// Enables wrapping binary `__primary_key` batches back to a dictionary in [`Self::convert_batch`].
255    pub(crate) fn set_pk_as_binary(&mut self, output_schema: SchemaRef) {
256        self.pk_dict_wrap_schema = Some(output_schema);
257    }
258
259    /// Index in the converted batch, never in a separately projected prefilter batch.
260    pub fn projected_index_by_id(&self, column_id: ColumnId) -> Option<usize> {
261        self.format_projection()
262            .column_id_to_projected_index
263            .get(&column_id)
264            .copied()
265    }
266
267    /// Returns min values of specific column in row groups.
268    pub fn min_values(
269        &self,
270        row_groups: &[impl Borrow<RowGroupMetaData>],
271        column_id: ColumnId,
272    ) -> StatValues {
273        match &self.parquet_adapter {
274            ParquetAdapter::Flat(p) => p.min_values(row_groups, column_id),
275            ParquetAdapter::PrimaryKeyToFlat(p) => p.format.min_values(row_groups, column_id),
276        }
277    }
278
279    /// Returns max values of specific column in row groups.
280    pub fn max_values(
281        &self,
282        row_groups: &[impl Borrow<RowGroupMetaData>],
283        column_id: ColumnId,
284    ) -> StatValues {
285        match &self.parquet_adapter {
286            ParquetAdapter::Flat(p) => p.max_values(row_groups, column_id),
287            ParquetAdapter::PrimaryKeyToFlat(p) => p.format.max_values(row_groups, column_id),
288        }
289    }
290
291    /// Returns null counts of specific column in row groups.
292    pub fn null_counts(
293        &self,
294        row_groups: &[impl Borrow<RowGroupMetaData>],
295        column_id: ColumnId,
296    ) -> StatValues {
297        match &self.parquet_adapter {
298            ParquetAdapter::Flat(p) => p.null_counts(row_groups, column_id),
299            ParquetAdapter::PrimaryKeyToFlat(p) => p.format.null_counts(row_groups, column_id),
300        }
301    }
302
303    /// Gets the arrow schema of the SST file.
304    pub(crate) fn arrow_schema(&self) -> &SchemaRef {
305        match &self.parquet_adapter {
306            ParquetAdapter::Flat(p) => &p.arrow_schema,
307            ParquetAdapter::PrimaryKeyToFlat(p) => p.format.arrow_schema(),
308        }
309    }
310
311    /// Gets the projected output schema expected by the scan.
312    pub(crate) fn output_arrow_schema(&self) -> Result<SchemaRef> {
313        let projection = self.parquet_read_columns().root_indices();
314        let mut schema = self
315            .arrow_schema()
316            .project(projection)
317            .context(ComputeArrowSnafu)?;
318        let mut fields = schema.fields().iter().cloned().collect::<Vec<_>>();
319        for (column_id, target) in self.json_target_types().iter() {
320            let Some(index) = self.parquet_projected_index_by_id(*column_id) else {
321                continue;
322            };
323            let Some(field) = schema.fields().get(index) else {
324                continue;
325            };
326            let mut field = field.as_ref().clone();
327            field.set_data_type(ConcreteDataType::json2(target.clone()).as_arrow_type());
328            fields[index] = Arc::new(field);
329        }
330        schema.fields = fields.into();
331        Ok(Arc::new(schema))
332    }
333
334    /// Index of a column in the projected schema produced directly by parquet
335    /// reading, before any primary-key-to-flat conversion.
336    pub(crate) fn parquet_projected_index_by_id(&self, column_id: ColumnId) -> Option<usize> {
337        match &self.parquet_adapter {
338            ParquetAdapter::Flat(p) => p
339                .format_projection
340                .column_id_to_projected_index
341                .get(&column_id)
342                .copied(),
343            // `format_projection` addresses the post-conversion flat batch here.
344            // This helper needs the raw primary-key projection used by parquet reading.
345            ParquetAdapter::PrimaryKeyToFlat(p) => p
346                .format
347                .field_id_to_projected_index()
348                .get(&column_id)
349                .copied(),
350        }
351    }
352
353    /// Gets the metadata of the SST.
354    pub(crate) fn metadata(&self) -> &RegionMetadataRef {
355        match &self.parquet_adapter {
356            ParquetAdapter::Flat(p) => &p.metadata,
357            ParquetAdapter::PrimaryKeyToFlat(p) => p.format.metadata(),
358        }
359    }
360
361    /// Get the sorted read columns to read from the sst file.
362    pub(crate) fn parquet_read_columns(&self) -> &ParquetReadColumns {
363        match &self.parquet_adapter {
364            ParquetAdapter::Flat(p) => &p.format_projection.parquet_read_cols,
365            ParquetAdapter::PrimaryKeyToFlat(p) => p.format.parquet_read_columns(),
366        }
367    }
368
369    /// Gets JSON2 read targets.
370    pub(crate) fn json_target_types(&self) -> &JsonTargetTypes {
371        self.read_cols.json_target_types()
372    }
373
374    /// Gets the projection in the flat format.
375    ///
376    /// When `skip_auto_convert` is enabled (primary-key format read), this returns the
377    /// primary-key format projection so filter/prune can resolve projected indices.
378    pub(crate) fn format_projection(&self) -> &FormatProjection {
379        match &self.parquet_adapter {
380            ParquetAdapter::Flat(p) => &p.format_projection,
381            ParquetAdapter::PrimaryKeyToFlat(p) => &p.format_projection,
382        }
383    }
384
385    /// Returns `true` if raw batches from parquet use the flat layout and
386    /// stores primary key columns as raw columns.
387    /// Returns `false` for the legacy primary-key-to-flat conversion path.
388    pub(crate) fn batch_has_raw_pk_columns(&self) -> bool {
389        matches!(&self.parquet_adapter, ParquetAdapter::Flat(_))
390    }
391
392    /// Creates a sequence array to override.
393    pub(crate) fn new_override_sequence_array(&self, length: usize) -> Option<ArrayRef> {
394        self.override_sequence
395            .map(|seq| Arc::new(UInt64Array::from_value(seq, length)) as ArrayRef)
396    }
397
398    /// Convert a record batch to apply flat format conversion and override sequence array.
399    ///
400    /// Returns a new RecordBatch with flat format conversion applied first (if enabled),
401    /// then the sequence column replaced by the override sequence array.
402    pub(crate) fn convert_batch(
403        &self,
404        record_batch: RecordBatch,
405        override_sequence_array: Option<&ArrayRef>,
406    ) -> Result<RecordBatch> {
407        let record_batch = if let Some(dict_schema) = &self.pk_dict_wrap_schema {
408            wrap_pk_binary_to_dict(record_batch, dict_schema)?
409        } else {
410            record_batch
411        };
412
413        // First, apply flat format conversion.
414        let mut batch = match &self.parquet_adapter {
415            ParquetAdapter::Flat(_) => record_batch,
416            ParquetAdapter::PrimaryKeyToFlat(p) => p.convert_batch(record_batch)?,
417        };
418
419        // Normalize nested field names and metadata to the SST's region metadata
420        // before schema compatibility and merging with memtables. This removes
421        // Parquet-added field IDs; equals_datatype also permits nested name differences.
422        for index in 0..batch.num_columns() {
423            let array = batch.column(index);
424            if !matches!(array.data_type(), ArrowDataType::Struct(_)) {
425                continue;
426            }
427            let field = batch.schema_ref().field(index);
428            let Some(column) = self.metadata().column_by_name(field.name()) else {
429                continue;
430            };
431            let target = column.column_schema.data_type.as_arrow_type();
432            if array.data_type() != &target && array.data_type().equals_datatype(&target) {
433                let array =
434                    datatypes::arrow::compute::cast(array, &target).context(ComputeArrowSnafu)?;
435                let mut fields = batch.schema().fields().to_vec();
436                fields[index] = Arc::new(field.clone().with_data_type(target));
437                let mut columns = batch.columns().to_vec();
438                columns[index] = array;
439                batch = RecordBatch::try_new(
440                    Arc::new(Schema::new_with_metadata(
441                        fields,
442                        batch.schema().metadata().clone(),
443                    )),
444                    columns,
445                )
446                .context(NewRecordBatchSnafu)?;
447            }
448        }
449
450        // Then apply sequence override if provided
451        let Some(override_array) = override_sequence_array else {
452            return Ok(batch);
453        };
454
455        let mut columns = batch.columns().to_vec();
456        let sequence_column_idx = sequence_column_index(batch.num_columns());
457
458        // Use the provided override sequence array, slicing if necessary to match batch length
459        let sequence_array = if override_array.len() > batch.num_rows() {
460            override_array.slice(0, batch.num_rows())
461        } else {
462            override_array.clone()
463        };
464
465        columns[sequence_column_idx] = sequence_array;
466
467        RecordBatch::try_new(batch.schema(), columns).context(NewRecordBatchSnafu)
468    }
469
470    /// Checks whether the batch from the parquet file needs to be converted to match the flat format.
471    ///
472    /// * `metadata` is the region metadata (always assumes flat format).
473    /// * `num_columns` is the number of columns in the parquet file.
474    /// * `file_path` is the path to the parquet file, for error message.
475    pub(crate) fn is_legacy_format(
476        metadata: &RegionMetadata,
477        num_columns: usize,
478        file_path: &str,
479    ) -> Result<bool> {
480        if metadata.primary_key.is_empty() {
481            return Ok(false);
482        }
483
484        // For flat format, compute expected column number:
485        // all columns + internal columns (pk, sequence, op_type)
486        let expected_columns = metadata.column_metadatas.len() + INTERNAL_COLUMN_NUM;
487
488        if expected_columns == num_columns {
489            // Same number of columns, no conversion needed
490            Ok(false)
491        } else {
492            ensure!(
493                expected_columns >= num_columns,
494                InvalidParquetSnafu {
495                    file: file_path,
496                    reason: format!(
497                        "Expected columns {} should be >= actual columns {}",
498                        expected_columns, num_columns
499                    )
500                }
501            );
502
503            // Different number of columns, check if the difference matches primary key count
504            let column_diff = expected_columns - num_columns;
505
506            ensure!(
507                column_diff == metadata.primary_key.len(),
508                InvalidParquetSnafu {
509                    file: file_path,
510                    reason: format!(
511                        "Column number difference {} does not match primary key count {}",
512                        column_diff,
513                        metadata.primary_key.len()
514                    )
515                }
516            );
517
518            Ok(true)
519        }
520    }
521}
522
523/// Wraps the parquet helper for different formats.
524enum ParquetAdapter {
525    Flat(ParquetFlat),
526    PrimaryKeyToFlat(ParquetPrimaryKeyToFlat),
527}
528
529/// Helper to reads the parquet from primary key format into the flat format.
530struct ParquetPrimaryKeyToFlat {
531    /// The primary key format to read the parquet.
532    format: PrimaryKeyReadFormat,
533    /// Format converter for handling flat format conversion.
534    convert_format: Option<FlatConvertFormat>,
535    /// Projection computed for the flat format.
536    format_projection: FormatProjection,
537}
538
539impl ParquetPrimaryKeyToFlat {
540    /// Creates a helper with existing `metadata` and `column_ids` to read.
541    fn new(
542        metadata: RegionMetadataRef,
543        read_cols: ReadColumns,
544        skip_auto_convert: bool,
545    ) -> ParquetPrimaryKeyToFlat {
546        assert!(if skip_auto_convert {
547            metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse
548        } else {
549            true
550        });
551
552        // Creates a map to lookup index based on the new format.
553        let id_to_index = sst_column_id_indices(&metadata);
554        let sst_column_num =
555            flat_sst_arrow_schema_column_num(&metadata, &FlatSchemaOptions::default());
556
557        let codec = build_primary_key_codec(&metadata);
558        let format = PrimaryKeyReadFormat::new(metadata.clone(), read_cols.clone());
559        let (convert_format, format_projection) = if skip_auto_convert {
560            (
561                None,
562                FormatProjection {
563                    parquet_read_cols: format.parquet_read_columns().clone(),
564                    column_id_to_projected_index: format.field_id_to_projected_index().clone(),
565                },
566            )
567        } else {
568            // Computes the format projection for the new format.
569            let format_projection = FormatProjection::compute_format_projection(
570                &metadata,
571                &id_to_index,
572                sst_column_num,
573                read_cols.clone(),
574            );
575            (
576                FlatConvertFormat::new(Arc::clone(&metadata), &format_projection, codec),
577                format_projection,
578            )
579        };
580
581        Self {
582            format,
583            convert_format,
584            format_projection,
585        }
586    }
587
588    fn convert_batch(&self, record_batch: RecordBatch) -> Result<RecordBatch> {
589        if let Some(convert_format) = &self.convert_format {
590            convert_format.convert(record_batch)
591        } else {
592            Ok(record_batch)
593        }
594    }
595}
596
597/// Helper to reads the parquet in flat format directly.
598struct ParquetFlat {
599    /// The metadata stored in the SST.
600    metadata: RegionMetadataRef,
601    /// SST file schema.
602    arrow_schema: SchemaRef,
603    /// Projection computed for the flat format.
604    format_projection: FormatProjection,
605    /// Column id to top-level SST index. Shared statistics helpers resolve
606    /// physical leaves from each file's actual Parquet schema.
607    column_id_to_sst_index: HashMap<ColumnId, usize>,
608}
609
610impl ParquetFlat {
611    /// Creates a helper with existing `metadata` and `column_ids` to read.
612    fn new(
613        metadata: RegionMetadataRef,
614        read_cols: ReadColumns,
615        arrow_schema: SchemaRef,
616    ) -> ParquetFlat {
617        // Creates a map to lookup index.
618        let id_to_index = sst_column_id_indices(&metadata);
619        let sst_column_num =
620            flat_sst_arrow_schema_column_num(&metadata, &FlatSchemaOptions::default());
621        let format_projection = FormatProjection::compute_format_projection(
622            &metadata,
623            &id_to_index,
624            sst_column_num,
625            read_cols,
626        );
627
628        Self {
629            metadata,
630            arrow_schema,
631            format_projection,
632            column_id_to_sst_index: id_to_index,
633        }
634    }
635
636    /// Returns min values of specific column in row groups.
637    fn min_values(
638        &self,
639        row_groups: &[impl Borrow<RowGroupMetaData>],
640        column_id: ColumnId,
641    ) -> StatValues {
642        self.get_stat_values(row_groups, column_id, true)
643    }
644
645    /// Returns max values of specific column in row groups.
646    fn max_values(
647        &self,
648        row_groups: &[impl Borrow<RowGroupMetaData>],
649        column_id: ColumnId,
650    ) -> StatValues {
651        self.get_stat_values(row_groups, column_id, false)
652    }
653
654    /// Returns null counts of specific column in row groups.
655    fn null_counts(
656        &self,
657        row_groups: &[impl Borrow<RowGroupMetaData>],
658        column_id: ColumnId,
659    ) -> StatValues {
660        let Some(index) = self.column_id_to_sst_index.get(&column_id) else {
661            // No such column in the SST.
662            return StatValues::NoColumn;
663        };
664        let stats = column_null_counts(row_groups, *index);
665        StatValues::from_stats_opt(stats)
666    }
667
668    fn get_stat_values(
669        &self,
670        row_groups: &[impl Borrow<RowGroupMetaData>],
671        column_id: ColumnId,
672        is_min: bool,
673    ) -> StatValues {
674        let Some(column) = self.metadata.column_by_id(column_id) else {
675            // No such column in the SST.
676            return StatValues::NoColumn;
677        };
678        let Some(index) = self.column_id_to_sst_index.get(&column_id) else {
679            return StatValues::NoStats;
680        };
681
682        let stats = column_values(row_groups, column, *index, is_min);
683        StatValues::from_stats_opt(stats)
684    }
685}
686
687/// Returns a map that the key is the column id and the value is the column position
688/// in the SST.
689/// It only supports SSTs with raw primary key columns.
690pub(crate) fn sst_column_id_indices(metadata: &RegionMetadata) -> HashMap<ColumnId, usize> {
691    let mut id_to_index = HashMap::with_capacity(metadata.column_metadatas.len());
692    let mut column_index = 0;
693    // keys
694    for pk_id in &metadata.primary_key {
695        id_to_index.insert(*pk_id, column_index);
696        column_index += 1;
697    }
698    // fields
699    for column in &metadata.column_metadatas {
700        if column.semantic_type == SemanticType::Field {
701            id_to_index.insert(column.column_id, column_index);
702            column_index += 1;
703        }
704    }
705    // time index
706    id_to_index.insert(metadata.time_index_column().column_id, column_index);
707
708    id_to_index
709}
710
711/// Decodes primary keys from a batch and returns decoded primary key information.
712///
713/// The batch must contain a primary key column at the expected index.
714/// Primary keys stay encoded: tag values are extracted lazily per column
715/// in [`DecodedPrimaryKeys::get_tag_column`] without decoding every label.
716/// The codec must describe the source key's field order and types.
717pub fn decode_primary_keys(
718    codec: &dyn PrimaryKeyCodec,
719    batch: &RecordBatch,
720) -> Result<DecodedPrimaryKeys> {
721    let primary_key_index = primary_key_column_index(batch.num_columns());
722    let pk_dict_array = batch
723        .column(primary_key_index)
724        .as_any()
725        .downcast_ref::<PrimaryKeyArray>()
726        .with_context(|| InvalidRecordBatchSnafu {
727            reason: "Primary key column is not a dictionary array".to_string(),
728        })?;
729    let pk_values_array = pk_dict_array
730        .values()
731        .as_any()
732        .downcast_ref::<BinaryArray>()
733        .with_context(|| InvalidRecordBatchSnafu {
734            reason: "Primary key values are not binary array".to_string(),
735        })?;
736
737    let keys = pk_dict_array.keys();
738
739    // Collects consecutive runs of identical dictionary keys, preserving their
740    // row order. Maps original key index -> new decoded value index.
741    // The parquet reader may read the whole dictionary page into the dictionary
742    // values, so we may decode many primary keys not in this batch if we decode
743    // the values array directly.
744    let pk_indices = keys.values();
745    let mut key_to_decoded_index = Vec::with_capacity(keys.len());
746    let mut distinct_keys: Vec<u32> = Vec::new();
747    let mut prev_key: Option<u32> = None;
748    for &current_key in pk_indices.iter().take(keys.len()) {
749        // Check if current key is the same as previous key
750        if let Some(prev) = prev_key
751            && prev == current_key
752        {
753            // Reuse the last decoded index
754            key_to_decoded_index.push((distinct_keys.len() - 1) as u32);
755            continue;
756        }
757
758        distinct_keys.push(current_key);
759        key_to_decoded_index.push((distinct_keys.len() - 1) as u32);
760        prev_key = Some(current_key);
761    }
762
763    let inner = match codec.encoding() {
764        PrimaryKeyEncoding::Sparse => DecodedKeysInner::Sparse {
765            values: pk_values_array.clone(),
766            distinct_keys,
767        },
768        PrimaryKeyEncoding::Dense => DecodedKeysInner::Dense {
769            codec: codec
770                .as_dense()
771                .context(InvalidRecordBatchSnafu {
772                    reason: "expected dense primary key codec",
773                })?
774                .clone(),
775            offsets: Vec::new(),
776            values: pk_values_array.clone(),
777            distinct_keys,
778        },
779    };
780
781    Ok(DecodedPrimaryKeys {
782        inner,
783        keys_array: UInt32Array::from(key_to_decoded_index),
784        pk_offsets: SparseOffsetsCache::new(),
785        value_buf: Vec::new(),
786    })
787}
788
789/// Encoded primary keys and encoding-specific lookup state.
790enum DecodedKeysInner {
791    /// Dense keys share positional offsets across projected tag columns.
792    Dense {
793        codec: DensePrimaryKeyCodec,
794        values: BinaryArray,
795        distinct_keys: Vec<u32>,
796        /// Initialized by positional access; full extraction needs no offsets.
797        offsets: Vec<Vec<usize>>,
798    },
799    /// Sparse primary keys stay encoded; each tag column extracts only its own
800    /// values from the raw keys.
801    Sparse {
802        /// Dictionary values of the primary key array.
803        values: BinaryArray,
804        /// Dictionary key of each distinct consecutive run, in first-appearance order.
805        distinct_keys: Vec<u32>,
806    },
807}
808
809/// Holds decoded primary key values for unique keys and their indices.
810pub struct DecodedPrimaryKeys {
811    inner: DecodedKeysInner,
812    /// Prebuilt keys array for creating dictionary arrays.
813    keys_array: UInt32Array,
814    /// Scratch offsets shared when extracting sparse tag values.
815    pk_offsets: SparseOffsetsCache,
816    /// Reusable buffer for extracting sparse tag values.
817    value_buf: Vec<u8>,
818}
819
820/// Pushes the value of `column_id` in `pk` into `builder`.
821fn push_sparse_tag_value(
822    pk: &[u8],
823    column_id: ColumnId,
824    builder: &mut dyn MutableVector,
825    pk_offsets: &mut SparseOffsetsCache,
826    value_buf: &mut Vec<u8>,
827) -> Result<()> {
828    let mut view = SparsePrimaryKeyView::new(pk, pk_offsets).context(DecodeSnafu)?;
829    push_sparse_tag_value_in_view(&mut view, column_id, builder, value_buf)
830}
831
832/// Pushes the value of `column_id` into `builder` using an existing view, so
833/// multiple columns of the same key share offset discovery.
834fn push_sparse_tag_value_in_view(
835    view: &mut SparsePrimaryKeyView,
836    column_id: ColumnId,
837    builder: &mut dyn MutableVector,
838    value_buf: &mut Vec<u8>,
839) -> Result<()> {
840    match column_id {
841        RESERVED_COLUMN_ID_TABLE_ID => builder.push_value_ref(&ValueRef::UInt32(view.table_id())),
842        RESERVED_COLUMN_ID_TSID => builder.push_value_ref(&ValueRef::UInt64(view.tsid())),
843        _ => {
844            let value = view.label(column_id, value_buf).context(DecodeSnafu)?;
845            match value {
846                None => builder.push_null(),
847                Some(value) => builder.push_value_ref(&ValueRef::String(value)),
848            }
849        }
850    }
851    Ok(())
852}
853
854impl DecodedPrimaryKeys {
855    /// Gets a tag column array by column id and data type.
856    ///
857    /// For sparse encoding, extracts the column lazily from the encoded keys.
858    /// For dense encoding, uses pk_index to decode only the requested field.
859    pub fn get_tag_column(
860        &mut self,
861        column_id: ColumnId,
862        pk_index: Option<usize>,
863        column_type: &ConcreteDataType,
864    ) -> Result<ArrayRef> {
865        let Self {
866            inner,
867            keys_array,
868            pk_offsets,
869            value_buf,
870        } = self;
871
872        // Gets values from the primary key.
873        let values_vector = match inner {
874            DecodedKeysInner::Dense {
875                codec,
876                values,
877                distinct_keys,
878                offsets,
879            } => {
880                let pk_idx = pk_index.context(InvalidRecordBatchSnafu {
881                    reason: "pk_index required for dense encoding",
882                })?;
883                let mut builder = column_type.create_mutable_vector(distinct_keys.len());
884                if offsets.is_empty() {
885                    *offsets = vec![Vec::new(); distinct_keys.len()];
886                }
887                for (&key, offsets) in distinct_keys.iter().zip(offsets) {
888                    if pk_idx < codec.num_fields() {
889                        let value = codec
890                            .decode_value_at(values.value(key as usize), pk_idx, offsets)
891                            .context(DecodeSnafu)?;
892                        builder.push_value_ref(&value.as_value_ref());
893                    } else {
894                        builder.push_null();
895                    }
896                }
897                builder.to_vector()
898            }
899            DecodedKeysInner::Sparse {
900                values,
901                distinct_keys,
902            } => {
903                let mut builder = column_type.create_mutable_vector(distinct_keys.len());
904                for &key in distinct_keys.iter() {
905                    let pk = values.value(key as usize);
906                    push_sparse_tag_value(pk, column_id, &mut *builder, pk_offsets, value_buf)?;
907                }
908                builder.to_vector()
909            }
910        };
911        let values_array = values_vector.to_arrow_array();
912
913        // Only creates dictionary array for string types, otherwise take values by keys
914        if column_type.is_string() {
915            // Creates dictionary array using the same keys for string types
916            // Note that the dictionary values may have nulls.
917            let dict_array = DictionaryArray::new(keys_array.clone(), values_array);
918            Ok(Arc::new(dict_array))
919        } else {
920            // For non-string types, takes values by keys indices to create a regular array
921            let taken_array = take(&values_array, keys_array, None).context(ComputeArrowSnafu)?;
922            Ok(taken_array)
923        }
924    }
925
926    /// Materializes all Dense tags in source-schema order with one sequential
927    /// traversal per key. Values are consumed immediately by their Arrow builders.
928    pub fn get_dense_tag_columns(&self) -> Result<Vec<ArrayRef>> {
929        let DecodedKeysInner::Dense {
930            codec,
931            values,
932            distinct_keys,
933            ..
934        } = &self.inner
935        else {
936            return InvalidRecordBatchSnafu {
937                reason: "expected dense primary key values",
938            }
939            .fail();
940        };
941        let mut builders: Vec<_> = codec
942            .fields()
943            .iter()
944            .map(|(_, field)| field.data_type().create_mutable_vector(distinct_keys.len()))
945            .collect();
946        let mut value_buf = Vec::new();
947        for &key in distinct_keys {
948            codec
949                .decode_dense_with(values.value(key as usize), &mut value_buf, |pos, value| {
950                    builders[pos].push_value_ref(&value);
951                })
952                .context(DecodeSnafu)?;
953        }
954        codec
955            .fields()
956            .iter()
957            .zip(builders)
958            .map(|((_, field), mut builder)| {
959                let values = builder.to_vector().to_arrow_array();
960                if field.data_type().is_string() {
961                    Ok(Arc::new(DictionaryArray::new(self.keys_array.clone(), values)) as ArrayRef)
962                } else {
963                    take(&values, &self.keys_array, None).context(ComputeArrowSnafu)
964                }
965            })
966            .collect()
967    }
968
969    /// Gets multiple sparse tag column arrays in one pass over the distinct keys,
970    /// sharing each key's offset discovery between the columns.
971    ///
972    /// Must only be called for sparse primary keys. Columns hold their values in
973    /// the order of `columns`, whose entries are tag column ids and data types.
974    pub fn get_sparse_tag_columns(
975        &mut self,
976        columns: &[(ColumnId, ConcreteDataType)],
977    ) -> Result<Vec<ArrayRef>> {
978        let Self {
979            inner,
980            keys_array,
981            pk_offsets,
982            value_buf,
983        } = self;
984        let DecodedKeysInner::Sparse {
985            values,
986            distinct_keys,
987        } = inner
988        else {
989            return InvalidRecordBatchSnafu {
990                reason: "expected sparse primary key values",
991            }
992            .fail();
993        };
994
995        let mut builders: Vec<_> = columns
996            .iter()
997            .map(|(_, column_type)| column_type.create_mutable_vector(distinct_keys.len()))
998            .collect();
999        for &key in distinct_keys.iter() {
1000            let pk = values.value(key as usize);
1001            let mut view = SparsePrimaryKeyView::new(pk, pk_offsets).context(DecodeSnafu)?;
1002            // Visit all columns before moving to the next key so offset
1003            // discovery is shared between columns.
1004            for ((column_id, _), builder) in columns.iter().zip(&mut builders) {
1005                push_sparse_tag_value_in_view(&mut view, *column_id, &mut **builder, value_buf)?;
1006            }
1007        }
1008
1009        columns
1010            .iter()
1011            .zip(builders)
1012            .map(|((_, column_type), mut builder)| {
1013                let values_array = builder.to_vector().to_arrow_array();
1014                if column_type.is_string() {
1015                    // Note that the dictionary values may have nulls.
1016                    Ok(
1017                        Arc::new(DictionaryArray::new(keys_array.clone(), values_array))
1018                            as ArrayRef,
1019                    )
1020                } else {
1021                    take(&values_array, keys_array, None)
1022                        .context(ComputeArrowSnafu)
1023                        .map(|array| array as ArrayRef)
1024                }
1025            })
1026            .collect()
1027    }
1028}
1029
1030/// Converts a batch that doesn't have decoded primary key columns into a batch that has decoded
1031/// primary key columns in flat format.
1032pub(crate) struct FlatConvertFormat {
1033    /// Metadata of the region.
1034    metadata: RegionMetadataRef,
1035    /// Primary key codec to decode primary keys.
1036    codec: Arc<dyn PrimaryKeyCodec>,
1037    /// Projected primary key column information: (column_id, pk_index, column_index in metadata).
1038    projected_primary_keys: Vec<(ColumnId, usize, usize)>,
1039}
1040
1041impl FlatConvertFormat {
1042    /// Creates a new `FlatConvertFormat`.
1043    ///
1044    /// The `format_projection` is the projection computed in the [FlatReadFormat] with the `metadata`.
1045    /// The `codec` is the primary key codec of the `metadata`.
1046    ///
1047    /// Returns `None` if there is no primary key.
1048    pub(crate) fn new(
1049        metadata: RegionMetadataRef,
1050        format_projection: &FormatProjection,
1051        codec: Arc<dyn PrimaryKeyCodec>,
1052    ) -> Option<Self> {
1053        if metadata.primary_key.is_empty() {
1054            return None;
1055        }
1056
1057        // Builds projected primary keys list maintaining the order of RegionMetadata::primary_key
1058        let mut projected_primary_keys = Vec::new();
1059        for (pk_index, &column_id) in metadata.primary_key.iter().enumerate() {
1060            if format_projection
1061                .column_id_to_projected_index
1062                .contains_key(&column_id)
1063            {
1064                // We expect the format_projection is built from the metadata.
1065                let column_index = metadata.column_index_by_id(column_id).unwrap();
1066                projected_primary_keys.push((column_id, pk_index, column_index));
1067            }
1068        }
1069
1070        Some(Self {
1071            metadata,
1072            codec,
1073            projected_primary_keys,
1074        })
1075    }
1076
1077    /// Converts a batch to have decoded primary key columns in flat format.
1078    ///
1079    /// The primary key array in the batch is a dictionary array.
1080    pub(crate) fn convert(&self, batch: RecordBatch) -> Result<RecordBatch> {
1081        if self.projected_primary_keys.is_empty() {
1082            return Ok(batch);
1083        }
1084
1085        let mut decoded_pks = decode_primary_keys(self.codec.as_ref(), &batch)?;
1086
1087        // Builds decoded tag column arrays.
1088        let mut decoded_columns = Vec::new();
1089        if self.codec.encoding() == PrimaryKeyEncoding::Sparse {
1090            // Extract all projected tag columns in one pass over the distinct
1091            // keys, sharing offset discovery between the columns.
1092            let columns: Vec<_> = self
1093                .projected_primary_keys
1094                .iter()
1095                .map(|(column_id, _, column_index)| {
1096                    let column_metadata = &self.metadata.column_metadatas[*column_index];
1097                    (*column_id, column_metadata.column_schema.data_type.clone())
1098                })
1099                .collect();
1100            decoded_columns.extend(decoded_pks.get_sparse_tag_columns(&columns)?);
1101        } else if self.projected_primary_keys.len() == self.metadata.primary_key.len() {
1102            decoded_columns.extend(decoded_pks.get_dense_tag_columns()?);
1103        } else {
1104            for (column_id, pk_index, column_index) in &self.projected_primary_keys {
1105                let column_metadata = &self.metadata.column_metadatas[*column_index];
1106                let tag_column = decoded_pks.get_tag_column(
1107                    *column_id,
1108                    Some(*pk_index),
1109                    &column_metadata.column_schema.data_type,
1110                )?;
1111                decoded_columns.push(tag_column);
1112            }
1113        }
1114
1115        // Builds new columns: decoded tag columns first, then original columns
1116        let mut new_columns = Vec::with_capacity(batch.num_columns() + decoded_columns.len());
1117        new_columns.extend(decoded_columns);
1118        new_columns.extend_from_slice(batch.columns());
1119
1120        // Builds new schema
1121        let mut new_fields =
1122            Vec::with_capacity(batch.schema().fields().len() + self.projected_primary_keys.len());
1123        for (column_id, _, column_index) in &self.projected_primary_keys {
1124            let column_metadata = &self.metadata.column_metadatas[*column_index];
1125            let old_field = &self.metadata.schema.arrow_schema().fields()[*column_index];
1126            let field =
1127                tag_maybe_to_dictionary_field(&column_metadata.column_schema.data_type, old_field);
1128            new_fields.push(Arc::new(with_field_id((*field).clone(), *column_id)));
1129        }
1130        new_fields.extend(batch.schema().fields().iter().cloned());
1131
1132        let new_schema = Arc::new(Schema::new(new_fields));
1133        RecordBatch::try_new(new_schema, new_columns).context(NewRecordBatchSnafu)
1134    }
1135}
1136
1137#[cfg(test)]
1138impl FlatReadFormat {
1139    /// Creates a helper with existing `metadata` and all columns.
1140    pub fn new_with_all_columns(metadata: RegionMetadataRef) -> FlatReadFormat {
1141        Self::new(
1142            Arc::clone(&metadata),
1143            ReadColumns::new(metadata.column_metadatas.iter().map(|c| c.column_id)),
1144            None,
1145            "test",
1146            false,
1147        )
1148        .unwrap()
1149    }
1150}
1151
1152#[cfg(test)]
1153mod tests {
1154    use std::sync::Arc;
1155
1156    use api::v1::SemanticType;
1157    use datatypes::arrow::array::{
1158        ArrayRef, BinaryArray, Int64Array, TimestampMillisecondArray, UInt8Array, UInt32Array,
1159        UInt64Array,
1160    };
1161    use datatypes::arrow::datatypes::{DataType as ArrowDataType, Field, TimeUnit};
1162    use datatypes::arrow::record_batch::RecordBatch;
1163    use datatypes::prelude::ConcreteDataType;
1164    use datatypes::schema::ColumnSchema;
1165    use datatypes::types::json_type::{JsonNativeType, JsonObjectType};
1166    use parquet::arrow::ArrowSchemaConverter;
1167    use parquet::basic::{Repetition, Type as PhysicalType};
1168    use parquet::file::metadata::{ColumnChunkMetaData, RowGroupMetaData};
1169    use parquet::file::statistics::Statistics;
1170    use parquet::schema::types::{SchemaDescriptor, Type};
1171    use store_api::codec::PrimaryKeyEncoding;
1172    use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataBuilder};
1173    use store_api::storage::RegionId;
1174    use store_api::storage::consts::{
1175        OP_TYPE_COLUMN_NAME, PRIMARY_KEY_COLUMN_NAME, SEQUENCE_COLUMN_NAME,
1176    };
1177
1178    use super::*;
1179    use crate::read::read_columns::ReadColumns;
1180    use crate::sst::{
1181        FlatSchemaOptions, PARQUET_FIELD_ID_KEY, PRIMARY_KEY_PARQUET_FIELD_ID,
1182        flat_sst_arrow_schema_column_num, override_pk_field_to_binary, to_flat_sst_arrow_schema,
1183    };
1184
1185    #[test]
1186    fn dense_tag_columns_match_eager_decoding() {
1187        use datatypes::arrow::datatypes::UInt32Type;
1188        use datatypes::value::Value;
1189        use datatypes::vectors::Helper;
1190        use mito_codec::row_converter::{DensePrimaryKeyCodec, PrimaryKeyCodecExt, SortField};
1191
1192        let columns = [
1193            (17, ConcreteDataType::string_datatype()),
1194            (9, ConcreteDataType::int64_datatype()),
1195            (2, ConcreteDataType::binary_datatype()),
1196        ];
1197        let codec = DensePrimaryKeyCodec::with_fields(
1198            columns
1199                .iter()
1200                .map(|(id, ty)| (*id, SortField::new(ty.clone())))
1201                .collect(),
1202        );
1203        let rows = [
1204            vec![
1205                Value::from("中文\0abcdefgh"),
1206                Value::Int64(-42),
1207                Value::Binary(vec![0, 1, 255].into()),
1208            ],
1209            vec![Value::from(""), Value::Null, Value::Binary(vec![].into())],
1210            vec![Value::Null, Value::Int64(i64::MAX), Value::Null],
1211        ];
1212        let mut encoded: Vec<_> = rows
1213            .iter()
1214            .map(|row| codec.encode(row.iter().map(Value::as_value_ref)).unwrap())
1215            .collect();
1216        // Unreferenced dictionary entries must not be inspected.
1217        encoded.push(vec![255]);
1218        let row_keys = [2, 2, 0, 1, 0, 0];
1219        let pk = DictionaryArray::<UInt32Type>::new(
1220            UInt32Array::from(row_keys.to_vec()),
1221            Arc::new(BinaryArray::from_iter_values(&encoded)),
1222        );
1223        let batch = RecordBatch::try_from_iter([
1224            (
1225                "ts",
1226                Arc::new(TimestampMillisecondArray::from_iter_values(0..6)) as ArrayRef,
1227            ),
1228            ("__primary_key", Arc::new(pk) as ArrayRef),
1229            (
1230                "__sequence",
1231                Arc::new(UInt64Array::from(vec![1; 6])) as ArrayRef,
1232            ),
1233            (
1234                "__op_type",
1235                Arc::new(UInt8Array::from(vec![1; 6])) as ArrayRef,
1236            ),
1237        ])
1238        .unwrap();
1239        let mut metadata = RegionMetadataBuilder::new(RegionId::new(1, 1));
1240        for (id, ty) in columns.iter().rev() {
1241            metadata.push_column_metadata(ColumnMetadata {
1242                column_id: *id,
1243                column_schema: ColumnSchema::new(format!("tag_{id}"), ty.clone(), true),
1244                semantic_type: SemanticType::Tag,
1245            });
1246        }
1247        metadata
1248            .push_column_metadata(ColumnMetadata {
1249                column_id: 23,
1250                column_schema: ColumnSchema::new(
1251                    "ts",
1252                    ConcreteDataType::timestamp_millisecond_datatype(),
1253                    false,
1254                ),
1255                semantic_type: SemanticType::Timestamp,
1256            })
1257            .primary_key(vec![17, 9, 2]);
1258        let metadata = Arc::new(metadata.build().unwrap());
1259        let format = FlatReadFormat::new(
1260            metadata.clone(),
1261            ReadColumns::new([17, 9, 2, 23]),
1262            Some(batch.schema()),
1263            "test",
1264            false,
1265        )
1266        .unwrap();
1267        for (offset, len) in [(0, 6), (1, 4), (3, 0)] {
1268            let mut decoded = decode_primary_keys(&codec, &batch.slice(offset, len)).unwrap();
1269            let all = decoded.get_dense_tag_columns().unwrap();
1270            let converted = format
1271                .convert_batch(batch.slice(offset, len), None)
1272                .unwrap();
1273            // Out-of-order and repeated projections share the same key offsets.
1274            for pos in [2, 0, 1, 0] {
1275                let array = decoded
1276                    .get_tag_column(columns[pos].0, Some(pos), &columns[pos].1)
1277                    .unwrap();
1278                assert_eq!(array.to_data(), all[pos].to_data());
1279                assert_eq!(converted.column(pos).to_data(), all[pos].to_data());
1280                let actual = Helper::try_into_vector(array).unwrap();
1281                for (row, &key) in row_keys[offset..offset + len].iter().enumerate() {
1282                    let eager = codec
1283                        .decode_dense_without_column_id(&encoded[key as usize])
1284                        .unwrap();
1285                    assert_eq!(actual.get(row), eager[pos]);
1286                }
1287            }
1288            // A position beyond the source schema remains NULL, never decoded
1289            // with a newer schema's field order or type.
1290            let missing = decoded
1291                .get_tag_column(99, Some(3), &ConcreteDataType::int64_datatype())
1292                .unwrap();
1293            assert_eq!(missing.null_count(), len);
1294            assert!(decoded.get_tag_column(17, None, &columns[0].1).is_err());
1295        }
1296        let mut malformed_columns = batch.columns().to_vec();
1297        malformed_columns[1] = Arc::new(DictionaryArray::<UInt32Type>::new(
1298            UInt32Array::from(vec![0; 6]),
1299            Arc::new(BinaryArray::from(vec![&[0, 1][..]])),
1300        ));
1301        let malformed = RecordBatch::try_new(batch.schema(), malformed_columns).unwrap();
1302        assert!(format.convert_batch(malformed.clone(), None).is_err());
1303        // A partial projection must still avoid decoding an unneeded broken suffix.
1304        let partial = FlatReadFormat::new(
1305            metadata,
1306            ReadColumns::new([17, 23]),
1307            Some(batch.schema()),
1308            "test",
1309            false,
1310        )
1311        .unwrap();
1312        let partial = partial.convert_batch(malformed, None).unwrap();
1313        let tag = Helper::try_into_vector(partial.column(0).clone()).unwrap();
1314        assert!((0..6).all(|row| tag.get(row).is_null()));
1315    }
1316
1317    /// Builds a `RegionMetadata` with the given number of tags and fields.
1318    fn build_metadata(
1319        num_tags: usize,
1320        num_fields: usize,
1321        encoding: PrimaryKeyEncoding,
1322    ) -> RegionMetadata {
1323        let mut builder = RegionMetadataBuilder::new(RegionId::new(0, 0));
1324        let mut col_id = 0u32;
1325
1326        for i in 0..num_tags {
1327            builder.push_column_metadata(ColumnMetadata {
1328                column_schema: ColumnSchema::new(
1329                    format!("tag_{i}"),
1330                    ConcreteDataType::string_datatype(),
1331                    true,
1332                ),
1333                semantic_type: SemanticType::Tag,
1334                column_id: col_id,
1335            });
1336            col_id += 1;
1337        }
1338
1339        for i in 0..num_fields {
1340            builder.push_column_metadata(ColumnMetadata {
1341                column_schema: ColumnSchema::new(
1342                    format!("field_{i}"),
1343                    ConcreteDataType::uint64_datatype(),
1344                    true,
1345                ),
1346                semantic_type: SemanticType::Field,
1347                column_id: col_id,
1348            });
1349            col_id += 1;
1350        }
1351
1352        builder.push_column_metadata(ColumnMetadata {
1353            column_schema: ColumnSchema::new(
1354                "ts".to_string(),
1355                ConcreteDataType::timestamp_millisecond_datatype(),
1356                false,
1357            ),
1358            semantic_type: SemanticType::Timestamp,
1359            column_id: col_id,
1360        });
1361
1362        let mut primary_key: Vec<u32> = (0..num_tags as u32).collect();
1363        if encoding == PrimaryKeyEncoding::Sparse {
1364            let reserved = crate::test_util::sst_util::sst_region_metadata_with_encoding(encoding);
1365            primary_key.splice(0..0, reserved.primary_key.into_iter().take(2));
1366            for column in reserved.column_metadatas.into_iter().take(2) {
1367                builder.push_column_metadata(column);
1368            }
1369        }
1370        builder.primary_key(primary_key);
1371        builder.primary_key_encoding(encoding);
1372        builder.build().unwrap()
1373    }
1374
1375    /// Builds the metadata of a table with a JSON2 struct field column:
1376    /// `[tag_0, field_0, payload, nullable_after_payload, ts]` with primary key `tag_0`.
1377    fn metadata_with_struct_field() -> RegionMetadata {
1378        let mut builder = RegionMetadataBuilder::new(RegionId::new(0, 0));
1379        builder
1380            .push_column_metadata(ColumnMetadata {
1381                column_schema: ColumnSchema::new(
1382                    "tag_0".to_string(),
1383                    ConcreteDataType::string_datatype(),
1384                    true,
1385                ),
1386                semantic_type: SemanticType::Tag,
1387                column_id: 0,
1388            })
1389            .push_column_metadata(ColumnMetadata {
1390                column_schema: ColumnSchema::new(
1391                    "field_0".to_string(),
1392                    ConcreteDataType::int64_datatype(),
1393                    true,
1394                ),
1395                semantic_type: SemanticType::Field,
1396                column_id: 1,
1397            })
1398            .push_column_metadata(ColumnMetadata {
1399                column_schema: ColumnSchema::new(
1400                    "payload".to_string(),
1401                    ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new())),
1402                    false,
1403                ),
1404                semantic_type: SemanticType::Field,
1405                column_id: 2,
1406            })
1407            .push_column_metadata(ColumnMetadata {
1408                column_schema: ColumnSchema::new(
1409                    "nullable_after_payload".to_string(),
1410                    ConcreteDataType::int64_datatype(),
1411                    true,
1412                ),
1413                semantic_type: SemanticType::Field,
1414                column_id: 4,
1415            })
1416            .push_column_metadata(ColumnMetadata {
1417                column_schema: ColumnSchema::new(
1418                    "ts".to_string(),
1419                    ConcreteDataType::timestamp_nanosecond_datatype(),
1420                    false,
1421                ),
1422                semantic_type: SemanticType::Timestamp,
1423                column_id: 3,
1424            });
1425        builder.primary_key(vec![0]);
1426        builder.primary_key_encoding(PrimaryKeyEncoding::Dense);
1427        builder.build().unwrap()
1428    }
1429
1430    /// Builds a file schema and a row group in which the `payload` struct
1431    /// column expands to three leaf columns. The `ns_edge` leaf carries small
1432    /// Int64 statistics that must not be mistaken for the statistics of `ts`.
1433    fn struct_column_file_and_row_group(raw_pk_columns: bool) -> (SchemaRef, RowGroupMetaData) {
1434        let mut arrow_fields = vec![
1435            Field::new("tag_0", ArrowDataType::Utf8, true),
1436            Field::new("field_0", ArrowDataType::Int64, true),
1437            Field::new(
1438                "payload",
1439                ArrowDataType::Struct(
1440                    vec![
1441                        Field::new("metadata", ArrowDataType::Binary, false),
1442                        Field::new("value", ArrowDataType::Binary, false),
1443                        Field::new("ns_edge", ArrowDataType::Int64, true),
1444                    ]
1445                    .into(),
1446                ),
1447                false,
1448            ),
1449            Field::new("nullable_after_payload", ArrowDataType::Int64, true),
1450            Field::new(
1451                "ts",
1452                ArrowDataType::Timestamp(TimeUnit::Nanosecond, None),
1453                false,
1454            ),
1455            Field::new(PRIMARY_KEY_COLUMN_NAME, ArrowDataType::Binary, false),
1456            Field::new(SEQUENCE_COLUMN_NAME, ArrowDataType::UInt64, false),
1457            Field::new(OP_TYPE_COLUMN_NAME, ArrowDataType::UInt8, false),
1458        ];
1459        if !raw_pk_columns {
1460            arrow_fields.remove(0);
1461        }
1462        let file_schema = Arc::new(Schema::new(arrow_fields));
1463
1464        let leaf = |name: &str, physical: PhysicalType| {
1465            Arc::new(
1466                Type::primitive_type_builder(name, physical)
1467                    .with_repetition(Repetition::OPTIONAL)
1468                    .build()
1469                    .unwrap(),
1470            )
1471        };
1472        let payload = Arc::new(
1473            Type::group_type_builder("payload")
1474                .with_repetition(Repetition::OPTIONAL)
1475                .with_fields(vec![
1476                    leaf("metadata", PhysicalType::BYTE_ARRAY),
1477                    leaf("value", PhysicalType::BYTE_ARRAY),
1478                    leaf("ns_edge", PhysicalType::INT64),
1479                ])
1480                .build()
1481                .unwrap(),
1482        );
1483        let mut parquet_fields = vec![
1484            leaf("tag_0", PhysicalType::BYTE_ARRAY),
1485            leaf("field_0", PhysicalType::INT64),
1486            payload,
1487            leaf("nullable_after_payload", PhysicalType::INT64),
1488            leaf("ts", PhysicalType::INT64),
1489            leaf(PRIMARY_KEY_COLUMN_NAME, PhysicalType::BYTE_ARRAY),
1490            leaf(SEQUENCE_COLUMN_NAME, PhysicalType::INT64),
1491            leaf(OP_TYPE_COLUMN_NAME, PhysicalType::INT32),
1492        ];
1493        if !raw_pk_columns {
1494            parquet_fields.remove(0);
1495        }
1496        let schema_descr = Arc::new(SchemaDescriptor::new(Arc::new(
1497            Type::group_type_builder("schema")
1498                .with_fields(parquet_fields)
1499                .build()
1500                .unwrap(),
1501        )));
1502
1503        // Omitted raw tags shift all subsequent leaves in primary-key SSTs.
1504        let ns_edge_leaf = if raw_pk_columns { 4 } else { 3 };
1505        let nullable_leaf = ns_edge_leaf + 1;
1506        let ts_leaf = nullable_leaf + 1;
1507        let chunks: Vec<_> = (0..schema_descr.num_columns())
1508            .map(|i| {
1509                let mut builder = ColumnChunkMetaData::builder(schema_descr.column(i));
1510                if i == ns_edge_leaf {
1511                    // Small values from the JSON payload, not timestamps.
1512                    builder = builder.set_statistics(Statistics::int64(
1513                        Some(0),
1514                        Some(86_400_000_000_000),
1515                        None,
1516                        Some(65),
1517                        true,
1518                    ));
1519                } else if i == nullable_leaf {
1520                    builder = builder.set_statistics(Statistics::int64(
1521                        Some(100),
1522                        Some(200),
1523                        None,
1524                        Some(7),
1525                        true,
1526                    ));
1527                } else if i == ts_leaf {
1528                    builder = builder.set_statistics(Statistics::int64(
1529                        Some(1_788_998_400_000_000_000),
1530                        Some(1_789_084_800_000_000_000),
1531                        None,
1532                        Some(0),
1533                        true,
1534                    ));
1535                }
1536                builder.build().unwrap()
1537            })
1538            .collect();
1539        let row_group = RowGroupMetaData::builder(schema_descr)
1540            .set_num_rows(69)
1541            .set_total_byte_size(0)
1542            .set_column_metadata(chunks)
1543            .build()
1544            .unwrap();
1545
1546        (file_schema, row_group)
1547    }
1548
1549    /// Regression test: row group statistics must be looked up by parquet leaf
1550    /// column index. A struct field column (e.g. JSON2) expands to multiple
1551    /// leaf columns, so statistics of columns after it must not be read from
1552    /// the struct's leaves. Otherwise min-max pruning can drop a whole row
1553    /// group by mistake (e.g. pruning `ts` with the small `ns_edge` stats),
1554    /// which caused data loss during SWCS compaction.
1555    #[test]
1556    fn test_stats_with_struct_field_column() {
1557        for (encoding, raw_pk_columns) in [
1558            (PrimaryKeyEncoding::Dense, true),
1559            (PrimaryKeyEncoding::Dense, false),
1560            (PrimaryKeyEncoding::Sparse, false),
1561        ] {
1562            let mut metadata = metadata_with_struct_field();
1563            metadata.primary_key_encoding = encoding;
1564            let metadata = Arc::new(metadata);
1565            let (file_schema, row_group) = struct_column_file_and_row_group(raw_pk_columns);
1566            let read_format = FlatReadFormat::new(
1567                metadata,
1568                ReadColumns::new([0, 1, 2, 3, 4]),
1569                Some(file_schema),
1570                "test",
1571                false,
1572            )
1573            .unwrap();
1574            let row_groups = [&row_group];
1575
1576            // Statistics of `ts` come from the `ts` leaf column, not the leaves of
1577            // the payload struct.
1578            let StatValues::Values(min) = read_format.min_values(&row_groups, 3) else {
1579                panic!("expected ts min values")
1580            };
1581            let min = min.as_any().downcast_ref::<Int64Array>().unwrap();
1582            assert_eq!(1_788_998_400_000_000_000, min.value(0));
1583            let StatValues::Values(max) = read_format.max_values(&row_groups, 3) else {
1584                panic!("expected ts max values")
1585            };
1586            let max = max.as_any().downcast_ref::<Int64Array>().unwrap();
1587            assert_eq!(1_789_084_800_000_000_000, max.value(0));
1588
1589            let stats = crate::sst::parquet::stats::RowGroupPruningStats::new(
1590                &row_groups,
1591                &read_format,
1592                None,
1593                false,
1594            );
1595            for (start, end, keep) in [
1596                (1_788_998_400_000_000_000, 1_789_084_800_000_000_000, true),
1597                (1_789_084_800_000_000_001, 1_789_171_200_000_000_000, false),
1598            ] {
1599                let predicate = table::predicate::Predicate::new(vec![
1600                    datafusion_expr::col("ts").gt_eq(datafusion_expr::lit(
1601                        datafusion_common::ScalarValue::TimestampNanosecond(Some(start), None),
1602                    )),
1603                    datafusion_expr::col("ts").lt(datafusion_expr::lit(
1604                        datafusion_common::ScalarValue::TimestampNanosecond(Some(end), None),
1605                    )),
1606                ]);
1607                assert_eq!(
1608                    vec![keep],
1609                    predicate
1610                        .prune_with_stats(&stats, read_format.metadata().schema.arrow_schema(),)
1611                );
1612            }
1613
1614            // Null counts of `ts` also read the correct leaf column.
1615            let StatValues::Values(nulls) = read_format.null_counts(&row_groups, 3) else {
1616                panic!("expected ts null counts")
1617            };
1618            let nulls = nulls.as_any().downcast_ref::<UInt64Array>().unwrap();
1619            assert!(nulls.is_valid(0));
1620            assert_eq!(0, nulls.value(0));
1621
1622            // A null slot may contain an underlying zero. Check validity and
1623            // a nonzero count to distinguish unknown or wrong-leaf statistics.
1624            let StatValues::Values(nulls) = read_format.null_counts(&row_groups, 4) else {
1625                panic!("expected nullable field null counts")
1626            };
1627            let nulls = nulls.as_any().downcast_ref::<UInt64Array>().unwrap();
1628            assert!(nulls.is_valid(0));
1629            assert_eq!(7, nulls.value(0));
1630
1631            // A column that expands to multiple leaf columns has no single column
1632            // statistics.
1633            assert!(matches!(
1634                read_format.min_values(&row_groups, 2),
1635                StatValues::NoStats
1636            ));
1637            assert!(matches!(
1638                read_format.max_values(&row_groups, 2),
1639                StatValues::NoStats
1640            ));
1641            assert!(matches!(
1642                read_format.null_counts(&row_groups, 2),
1643                StatValues::NoStats
1644            ));
1645        }
1646    }
1647
1648    /// Even one leaf cannot supply the null count of a nested parent:
1649    /// {"a": null} and [null] are non-null parents with null children.
1650    #[test]
1651    fn test_single_leaf_nested_columns_have_no_root_stats() {
1652        let child = Arc::new(Field::new("a", ArrowDataType::Int64, true));
1653        for nested_type in [
1654            ArrowDataType::Struct(vec![child.clone()].into()),
1655            ArrowDataType::List(child.clone()),
1656            ArrowDataType::LargeList(child.clone()),
1657            ArrowDataType::FixedSizeList(child, 1),
1658        ] {
1659            let metadata = Arc::new(metadata_with_struct_field());
1660            let (schema, _) = struct_column_file_and_row_group(true);
1661            let mut fields = schema.fields().to_vec();
1662            fields[2] = Arc::new(Field::new("payload", nested_type.clone(), true));
1663            let schema = Arc::new(Schema::new(fields));
1664            let descriptor = Arc::new(ArrowSchemaConverter::new().convert(&schema).unwrap());
1665            let chunks = descriptor
1666                .columns()
1667                .iter()
1668                .map(|column| {
1669                    ColumnChunkMetaData::builder(column.clone())
1670                        .build()
1671                        .unwrap()
1672                })
1673                .collect();
1674            let row_group = RowGroupMetaData::builder(descriptor)
1675                .set_num_rows(1)
1676                .set_total_byte_size(0)
1677                .set_column_metadata(chunks)
1678                .build()
1679                .unwrap();
1680            let format = ParquetFlat::new(metadata, ReadColumns::new([0, 1, 2, 3]), schema);
1681
1682            // The nested root has no usable statistics, independently of the
1683            // values stored in any row group. Its leaf still occupies a slot.
1684            let groups = &[row_group];
1685            assert!(
1686                matches!(format.min_values(groups, 2), StatValues::NoStats),
1687                "{nested_type:?}"
1688            );
1689            assert!(
1690                matches!(format.max_values(groups, 2), StatValues::NoStats),
1691                "{nested_type:?}"
1692            );
1693            assert!(
1694                matches!(format.null_counts(groups, 2), StatValues::NoStats),
1695                "{nested_type:?}"
1696            );
1697        }
1698    }
1699
1700    #[test]
1701    fn test_field_column_start() {
1702        // (num_tags, num_fields, encoding, expected)
1703        let cases = [
1704            (1, 1, PrimaryKeyEncoding::Dense, 1),
1705            (2, 2, PrimaryKeyEncoding::Dense, 2),
1706            (0, 2, PrimaryKeyEncoding::Dense, 0),
1707            (2, 2, PrimaryKeyEncoding::Sparse, 0),
1708        ];
1709
1710        for (num_tags, num_fields, encoding, expected) in cases {
1711            let metadata = build_metadata(num_tags, num_fields, encoding);
1712            let options = FlatSchemaOptions::from_encoding(encoding);
1713            let num_columns = flat_sst_arrow_schema_column_num(&metadata, &options);
1714            let result = field_column_start(&metadata, num_columns);
1715            assert_eq!(
1716                result, expected,
1717                "num_tags={num_tags}, num_fields={num_fields}, encoding={encoding:?}"
1718            );
1719        }
1720    }
1721
1722    #[test]
1723    fn test_convert_batch_wraps_binary_pk_to_dict() {
1724        use datatypes::arrow::array::{Array, DictionaryArray, StringArray};
1725        use datatypes::arrow::datatypes::UInt32Type;
1726
1727        // build_metadata(1, 1, Dense) projects to:
1728        // [tag_0: Dict<UInt32, Utf8>, field_0: UInt64, ts: Timestamp(ms),
1729        //  __primary_key: Dict<UInt32, Binary>, __sequence: UInt64, __op_type: UInt8]
1730        let metadata = Arc::new(build_metadata(1, 1, PrimaryKeyEncoding::Dense));
1731        let column_ids: Vec<u32> = metadata
1732            .column_metadatas
1733            .iter()
1734            .map(|c| c.column_id)
1735            .collect();
1736        let mut read_format = FlatReadFormat::new(
1737            metadata.clone(),
1738            ReadColumns::new(column_ids),
1739            None,
1740            "test",
1741            false,
1742        )
1743        .unwrap();
1744        let output_schema = read_format.output_arrow_schema().unwrap();
1745        read_format.set_pk_as_binary(output_schema.clone());
1746        let binary_schema = override_pk_field_to_binary(&output_schema);
1747
1748        // The __primary_key field must preserve its field_id metadata after
1749        // being converted from dictionary to plain binary.
1750        let pk_field = binary_schema
1751            .field_with_name(PRIMARY_KEY_COLUMN_NAME)
1752            .unwrap();
1753        assert_eq!(
1754            pk_field.metadata().get(PARQUET_FIELD_ID_KEY),
1755            Some(&PRIMARY_KEY_PARQUET_FIELD_ID.to_string()),
1756            "__primary_key field must retain its PARQUET:field_id after override_pk_field_to_binary"
1757        );
1758
1759        // Repeat the second pk to verify identity keys (no dedup).
1760        let tag_keys = UInt32Array::from(vec![0u32, 1, 1]);
1761        let tag_values = Arc::new(StringArray::from(vec!["t0", "t1"]));
1762        let tag_array: ArrayRef =
1763            Arc::new(DictionaryArray::<UInt32Type>::new(tag_keys, tag_values));
1764        let field_array: ArrayRef = Arc::new(UInt64Array::from(vec![10u64, 11, 12]));
1765        let ts_array: ArrayRef = Arc::new(TimestampMillisecondArray::from(vec![1i64, 2, 3]));
1766        let pk_array: ArrayRef = Arc::new(BinaryArray::from_iter_values(
1767            [b"alpha".as_ref(), b"beta", b"beta"].iter().copied(),
1768        ));
1769        let seq_array: ArrayRef = Arc::new(UInt64Array::from(vec![100u64, 101, 102]));
1770        let op_array: ArrayRef = Arc::new(UInt8Array::from(vec![1u8, 1, 1]));
1771
1772        let batch = RecordBatch::try_new(
1773            binary_schema,
1774            vec![
1775                tag_array,
1776                field_array,
1777                ts_array,
1778                pk_array,
1779                seq_array,
1780                op_array,
1781            ],
1782        )
1783        .unwrap();
1784
1785        let wrapped = read_format.convert_batch(batch, None).unwrap();
1786        assert_eq!(wrapped.schema(), output_schema);
1787
1788        let pk_idx = primary_key_column_index(wrapped.num_columns());
1789        let pk_col = wrapped.column(pk_idx);
1790        assert_eq!(
1791            pk_col.data_type(),
1792            &ArrowDataType::Dictionary(
1793                Box::new(ArrowDataType::UInt32),
1794                Box::new(ArrowDataType::Binary)
1795            )
1796        );
1797        let dict = pk_col
1798            .as_any()
1799            .downcast_ref::<DictionaryArray<UInt32Type>>()
1800            .unwrap();
1801        assert_eq!(dict.keys().values(), &[0, 1, 2]);
1802        let values = dict
1803            .values()
1804            .as_any()
1805            .downcast_ref::<BinaryArray>()
1806            .unwrap();
1807        assert_eq!(values.value(0), b"alpha");
1808        assert_eq!(values.value(1), b"beta");
1809        assert_eq!(values.value(2), b"beta");
1810    }
1811
1812    #[test]
1813    fn test_output_arrow_schema_uses_projection() {
1814        let metadata = Arc::new(build_metadata(1, 2, PrimaryKeyEncoding::Dense));
1815        let read_format = FlatReadFormat::new(
1816            metadata.clone(),
1817            ReadColumns::new([0_u32, 2_u32]),
1818            None,
1819            "test",
1820            false,
1821        )
1822        .unwrap();
1823
1824        let output_schema = read_format.output_arrow_schema().unwrap();
1825        let projection = read_format.parquet_read_columns().root_indices();
1826        let expected = Arc::new(
1827            to_flat_sst_arrow_schema(&metadata, &FlatSchemaOptions::default())
1828                .project(projection)
1829                .unwrap(),
1830        );
1831
1832        assert_eq!(expected, output_schema);
1833    }
1834}