Skip to main content

mito2/memtable/bulk/
part.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//! Bulk part encoder/decoder.
16
17use std::collections::{HashMap, HashSet};
18use std::ops::RangeInclusive;
19use std::sync::Arc;
20use std::time::{Duration, Instant};
21
22use api::helper::{ColumnDataTypeWrapper, to_grpc_value};
23use api::v1::bulk_wal_entry::Body;
24use api::v1::{ArrowIpc, BulkWalEntry, Mutation, OpType, SemanticType};
25use bytes::Bytes;
26use common_grpc::flight::{FlightDecoder, FlightEncoder, FlightMessage};
27use common_recordbatch::DfRecordBatch as RecordBatch;
28use common_time::Timestamp;
29use datafusion_common::Column;
30use datafusion_common::pruning::PruningStatistics;
31use datafusion_expr::utils::expr_to_columns;
32use datatypes::arrow;
33use datatypes::arrow::array::{
34    Array, ArrayRef, BinaryArray, BooleanArray, DictionaryArray, StringDictionaryBuilder,
35    TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,
36    TimestampSecondArray, UInt8Array, UInt32Array, UInt64Array,
37};
38use datatypes::arrow::compute::{SortColumn, SortOptions, concat_batches};
39use datatypes::arrow::datatypes::{
40    DataType as ArrowDataType, Field, Schema, SchemaRef, TimeUnit, UInt32Type,
41};
42use datatypes::data_type::DataType;
43use datatypes::extension::json::align_schema_with_json_array;
44use datatypes::prelude::{MutableVector, Vector};
45use datatypes::value::ValueRef;
46use datatypes::vectors::Helper;
47use mito_codec::key_values::{KeyValue, KeyValues};
48use mito_codec::row_converter::sparse::SparsePrimaryKeyValidator;
49use mito_codec::row_converter::{PrimaryKeyCodec, SortField, build_primary_key_codec_with_fields};
50use parquet::arrow::ArrowWriter;
51use parquet::basic::{Compression, ZstdLevel};
52use parquet::file::metadata::ParquetMetaData;
53use parquet::file::properties::WriterProperties;
54use smallvec::SmallVec;
55use snafu::{OptionExt, ResultExt, ensure};
56use store_api::codec::PrimaryKeyEncoding;
57use store_api::metadata::{RegionMetadata, RegionMetadataRef};
58use store_api::mito_engine_options::FloatFieldEncoding;
59use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME;
60use store_api::storage::{ColumnId, FileId, SequenceNumber, SequenceRange};
61
62use crate::compaction::{collect_json2_rewrite_plans, rewrite_json2_batch, rewrite_json2_schema};
63use crate::error::{
64    self, ColumnNotFoundSnafu, ComputeArrowSnafu, CreateDefaultSnafu, DataTypeMismatchSnafu,
65    EncodeMemtableSnafu, EncodeSnafu, InvalidMetadataSnafu, InvalidRequestSnafu,
66    NewRecordBatchSnafu, Result,
67};
68use crate::memtable::bulk::context::{BulkIterContext, BulkIterContextRef};
69use crate::memtable::bulk::part_reader::ParquetBulkPartIter;
70use crate::memtable::time_series::{ValueBuilder, Values};
71use crate::memtable::{BoxedRecordBatchIterator, MemScanMetrics, MemtableStats};
72use crate::sst::SeriesEstimator;
73use crate::sst::index::IndexOutput;
74use crate::sst::parquet::flat_format::primary_key_column_index;
75use crate::sst::parquet::format::{PrimaryKeyArray, PrimaryKeyArrayBuilder};
76use crate::sst::parquet::{
77    COLUMN_INDEX_TRUNCATE_LENGTH, PARQUET_METADATA_KEY, RowGroupValueBytes, SstInfo,
78    apply_column_compression, apply_float_field_encoding, apply_internal_column_encoding,
79    large_value_fields, max_row_group_decoded_size, max_row_group_uncompressed_size,
80    skip_statistics, var_len_value_bytes,
81};
82
83const INIT_DICT_VALUE_CAPACITY: usize = 8;
84
85/// A raw bulk part in the memtable.
86#[derive(Clone)]
87pub struct BulkPart {
88    pub batch: RecordBatch,
89    pub max_timestamp: i64,
90    pub min_timestamp: i64,
91    /// Uniform sequence for external bulk writes, or the maximum row sequence
92    /// for parts produced by [`BulkPartConverter`]. Rows need not share it.
93    pub sequence: u64,
94    /// Lower bound of row sequences. Slices may inherit a lower bound from
95    /// their parent part rather than recomputing an exact minimum.
96    pub min_sequence: SequenceNumber,
97    pub timestamp_index: usize,
98    pub raw_data: Option<ArrowIpc>,
99}
100
101impl TryFrom<BulkWalEntry> for BulkPart {
102    type Error = error::Error;
103
104    fn try_from(value: BulkWalEntry) -> std::result::Result<Self, Self::Error> {
105        match value.body.expect("Entry payload should be present") {
106            Body::ArrowIpc(ipc) => {
107                let mut decoder = FlightDecoder::try_from_schema_bytes(&ipc.schema)
108                    .context(error::ConvertBulkWalEntrySnafu)?;
109                let batch = decoder
110                    .try_decode_record_batch(&ipc.data_header, &ipc.payload)
111                    .context(error::ConvertBulkWalEntrySnafu)?;
112                Ok(Self {
113                    batch,
114                    max_timestamp: value.max_ts,
115                    min_timestamp: value.min_ts,
116                    sequence: value.sequence,
117                    // Bulk WAL entries represent uniform-sequence external writes.
118                    // Row mutations reconstruct their bounds through BulkPartConverter.
119                    min_sequence: value.sequence,
120                    timestamp_index: value.timestamp_index as usize,
121                    raw_data: Some(ipc),
122                })
123            }
124        }
125    }
126}
127
128impl TryFrom<&BulkPart> for BulkWalEntry {
129    type Error = error::Error;
130
131    fn try_from(value: &BulkPart) -> Result<Self> {
132        if let Some(ipc) = &value.raw_data {
133            Ok(BulkWalEntry {
134                sequence: value.sequence,
135                max_ts: value.max_timestamp,
136                min_ts: value.min_timestamp,
137                timestamp_index: value.timestamp_index as u32,
138                body: Some(Body::ArrowIpc(ipc.clone())),
139            })
140        } else {
141            let mut encoder = FlightEncoder::default();
142            let schema_bytes = encoder
143                .encode_schema(value.batch.schema().as_ref())
144                .data_header;
145            let [rb_data] = encoder
146                .encode(FlightMessage::RecordBatch(value.batch.clone()))
147                .try_into()
148                .map_err(|_| {
149                    error::UnsupportedOperationSnafu {
150                        err_msg: "create BulkWalEntry from RecordBatch with dictionary arrays",
151                    }
152                    .build()
153                })?;
154            Ok(BulkWalEntry {
155                sequence: value.sequence,
156                max_ts: value.max_timestamp,
157                min_ts: value.min_timestamp,
158                timestamp_index: value.timestamp_index as u32,
159                body: Some(Body::ArrowIpc(ArrowIpc {
160                    schema: schema_bytes,
161                    data_header: rb_data.data_header,
162                    payload: rb_data.data_body,
163                })),
164            })
165        }
166    }
167}
168
169impl BulkPart {
170    pub(crate) fn schema(&self) -> SchemaRef {
171        self.batch.schema()
172    }
173
174    pub(crate) fn estimated_size(&self) -> usize {
175        record_batch_estimated_size(&self.batch)
176    }
177
178    /// Returns the estimated series count in this BulkPart.
179    /// This is calculated from the dictionary values count of the PrimaryKeyArray.
180    pub fn estimated_series_count(&self) -> usize {
181        let pk_column_idx = primary_key_column_index(self.batch.num_columns());
182        let pk_column = self.batch.column(pk_column_idx);
183        if let Some(dict_array) = pk_column.as_any().downcast_ref::<PrimaryKeyArray>() {
184            dict_array.values().len()
185        } else {
186            0
187        }
188    }
189
190    /// Creates MemtableStats from this BulkPart.
191    pub fn to_memtable_stats(&self, region_metadata: &RegionMetadataRef) -> MemtableStats {
192        let ts_type = region_metadata.time_index_type();
193        let min_ts = ts_type.create_timestamp(self.min_timestamp);
194        let max_ts = ts_type.create_timestamp(self.max_timestamp);
195
196        MemtableStats {
197            estimated_bytes: self.estimated_size(),
198            decoded_bytes: None,
199            time_range: Some((min_ts, max_ts)),
200            num_rows: self.num_rows(),
201            num_ranges: 1,
202            max_sequence: self.sequence,
203            min_sequence: self.min_sequence,
204            series_count: self.estimated_series_count(),
205        }
206    }
207
208    /// Fills missing columns in the BulkPart batch with default values.
209    ///
210    /// This function checks if the batch schema matches the region metadata schema,
211    /// and if there are missing columns, it fills them with default values (or null
212    /// for nullable columns).
213    ///
214    /// # Arguments
215    ///
216    /// * `region_metadata` - The region metadata containing the expected schema
217    pub fn fill_missing_columns(&mut self, region_metadata: &RegionMetadata) -> Result<()> {
218        // Builds a map of existing columns in the batch
219        let batch_schema = self.batch.schema();
220        let batch_columns: HashSet<_> = batch_schema
221            .fields()
222            .iter()
223            .map(|f| f.name().as_str())
224            .collect();
225
226        // Finds columns that need to be filled
227        let mut columns_to_fill = Vec::new();
228        for column_meta in &region_metadata.column_metadatas {
229            // Sparse bulk batches already carry tags in the encoded primary key.
230            if batch_columns.contains(PRIMARY_KEY_COLUMN_NAME)
231                && column_meta.semantic_type == SemanticType::Tag
232            {
233                continue;
234            }
235            // TODO(yingwen): Returns error if it is impure default after we support filling
236            // bulk insert request in the frontend
237            if !batch_columns.contains(column_meta.column_schema.name.as_str()) {
238                columns_to_fill.push(column_meta);
239            }
240        }
241
242        if columns_to_fill.is_empty() {
243            return Ok(());
244        }
245
246        let num_rows = self.batch.num_rows();
247
248        let mut new_columns = Vec::new();
249        let mut new_fields = Vec::new();
250
251        // First, adds all existing columns
252        new_fields.extend(batch_schema.fields().iter().cloned());
253        new_columns.extend_from_slice(self.batch.columns());
254
255        let region_id = region_metadata.region_id;
256        // Then adds the missing columns with default values
257        for column_meta in columns_to_fill {
258            let default_vector = column_meta
259                .column_schema
260                .create_default_vector(num_rows)
261                .context(CreateDefaultSnafu {
262                    region_id,
263                    column: &column_meta.column_schema.name,
264                })?
265                .with_context(|| InvalidRequestSnafu {
266                    region_id,
267                    reason: format!(
268                        "column {} does not have default value",
269                        column_meta.column_schema.name
270                    ),
271                })?;
272            let arrow_array = default_vector.to_arrow_array();
273            new_fields.push(Arc::new(
274                Field::new(
275                    column_meta.column_schema.name.clone(),
276                    arrow_array.data_type().clone(),
277                    column_meta.column_schema.is_nullable(),
278                )
279                .with_metadata(column_meta.column_schema.metadata().clone()),
280            ));
281            new_columns.push(arrow_array);
282        }
283
284        // Create a new schema and batch with the filled columns
285        let new_schema = Arc::new(Schema::new(new_fields));
286        let new_batch =
287            RecordBatch::try_new(new_schema, new_columns).context(NewRecordBatchSnafu)?;
288
289        // Update the batch
290        self.batch = new_batch;
291
292        // The raw data no longer matches the batch after filling missing
293        // columns. Clears it so the WAL entry is re-encoded from the filled
294        // batch, otherwise replaying the entry restores a batch without the
295        // filled columns and the memtable rejects it.
296        self.raw_data = None;
297
298        Ok(())
299    }
300
301    /// Converts [BulkPart] to [Mutation] for fallback `write_bulk` implementation.
302    pub(crate) fn to_mutation(&self, region_metadata: &RegionMetadataRef) -> Result<Mutation> {
303        let vectors = region_metadata
304            .schema
305            .column_schemas()
306            .iter()
307            .map(|col| match self.batch.column_by_name(&col.name) {
308                None => Ok(None),
309                Some(col) => Helper::try_into_vector(col).map(Some),
310            })
311            .collect::<datatypes::error::Result<Vec<_>>>()
312            .context(error::ComputeVectorSnafu)?;
313
314        let rows = (0..self.num_rows())
315            .map(|row_idx| {
316                let values = (0..self.batch.num_columns())
317                    .map(|col_idx| {
318                        if let Some(v) = &vectors[col_idx] {
319                            to_grpc_value(v.get(row_idx))
320                        } else {
321                            api::v1::Value { value_data: None }
322                        }
323                    })
324                    .collect::<Vec<_>>();
325                api::v1::Row { values }
326            })
327            .collect::<Vec<_>>();
328
329        let schema = region_metadata
330            .column_metadatas
331            .iter()
332            .map(|c| {
333                let data_type_wrapper =
334                    ColumnDataTypeWrapper::try_from(c.column_schema.data_type.clone())?;
335                Ok(api::v1::ColumnSchema {
336                    column_name: c.column_schema.name.clone(),
337                    datatype: data_type_wrapper.datatype() as i32,
338                    semantic_type: c.semantic_type as i32,
339                    ..Default::default()
340                })
341            })
342            .collect::<api::error::Result<Vec<_>>>()
343            .context(error::ConvertColumnDataTypeSnafu {
344                reason: "failed to convert region metadata to column schema",
345            })?;
346
347        let rows = api::v1::Rows { schema, rows };
348
349        Ok(Mutation {
350            op_type: OpType::Put as i32,
351            sequence: self.sequence,
352            rows: Some(rows),
353            write_hint: None,
354        })
355    }
356
357    pub fn timestamps(&self) -> &ArrayRef {
358        self.batch.column(self.timestamp_index)
359    }
360
361    pub fn num_rows(&self) -> usize {
362        self.batch.num_rows()
363    }
364}
365
366/// A collection of small unordered bulk parts.
367/// Used to batch small parts together before merging them into a sorted part.
368pub struct UnorderedPart {
369    /// Small bulk parts that haven't been sorted yet.
370    parts: Vec<BulkPart>,
371    /// Total number of rows across all parts.
372    total_rows: usize,
373    /// Total estimated uncompressed bytes across all parts.
374    total_bytes: usize,
375    /// Minimum timestamp across all parts.
376    min_timestamp: i64,
377    /// Maximum timestamp across all parts.
378    max_timestamp: i64,
379    /// Maximum sequence number across all parts.
380    max_sequence: u64,
381    /// Minimum sequence lower bound across all parts.
382    min_sequence: SequenceNumber,
383    /// Row count threshold for accepting parts (default: 1024).
384    threshold: usize,
385    /// Row count threshold for compacting (default: 4096).
386    compact_threshold: usize,
387}
388
389impl Default for UnorderedPart {
390    fn default() -> Self {
391        Self::new()
392    }
393}
394
395impl UnorderedPart {
396    /// Creates a new empty UnorderedPart.
397    pub fn new() -> Self {
398        Self {
399            parts: Vec::new(),
400            total_rows: 0,
401            total_bytes: 0,
402            min_timestamp: i64::MAX,
403            max_timestamp: i64::MIN,
404            max_sequence: 0,
405            min_sequence: SequenceNumber::MAX,
406            threshold: 1024,
407            compact_threshold: 4096,
408        }
409    }
410
411    /// Sets the threshold for accepting parts into unordered_part.
412    pub fn set_threshold(&mut self, threshold: usize) {
413        self.threshold = threshold;
414    }
415
416    /// Sets the threshold for compacting unordered_part.
417    pub fn set_compact_threshold(&mut self, compact_threshold: usize) {
418        self.compact_threshold = compact_threshold;
419    }
420
421    /// Returns the threshold for accepting parts.
422    pub fn threshold(&self) -> usize {
423        self.threshold
424    }
425
426    /// Returns the compact threshold.
427    pub fn compact_threshold(&self) -> usize {
428        self.compact_threshold
429    }
430
431    /// Returns true if this part should accept the given row count.
432    pub fn should_accept(&self, num_rows: usize) -> bool {
433        num_rows < self.threshold
434    }
435
436    /// Returns true if this part should be compacted by row count.
437    pub fn should_compact(&self) -> bool {
438        self.total_rows >= self.compact_threshold
439    }
440
441    /// Returns the total estimated uncompressed bytes across all parts.
442    pub(crate) fn estimated_bytes(&self) -> usize {
443        self.total_bytes
444    }
445
446    /// Returns the sequence interval occupied by pending small writes.
447    pub(crate) fn sequence_bounds(&self) -> Option<(SequenceNumber, SequenceNumber)> {
448        (!self.is_empty()).then_some((self.min_sequence, self.max_sequence))
449    }
450
451    /// Adds a BulkPart to this unordered collection.
452    pub fn push(&mut self, part: BulkPart) {
453        self.total_rows += part.num_rows();
454        self.total_bytes = self.total_bytes.saturating_add(part.estimated_size());
455        self.min_timestamp = self.min_timestamp.min(part.min_timestamp);
456        self.max_timestamp = self.max_timestamp.max(part.max_timestamp);
457        self.max_sequence = self.max_sequence.max(part.sequence);
458        self.min_sequence = self.min_sequence.min(part.min_sequence);
459        self.parts.push(part);
460    }
461
462    /// Returns the total number of rows across all parts.
463    pub fn num_rows(&self) -> usize {
464        self.total_rows
465    }
466
467    /// Returns true if there are no parts.
468    pub fn is_empty(&self) -> bool {
469        self.parts.is_empty()
470    }
471
472    /// Returns the number of parts in this collection.
473    pub fn num_parts(&self) -> usize {
474        self.parts.len()
475    }
476
477    /// Concatenates and sorts all parts into a single RecordBatch.
478    /// Returns None if the collection is empty.
479    pub fn concat_and_sort(&self, metadata: &RegionMetadataRef) -> Result<Option<RecordBatch>> {
480        if self.parts.is_empty() {
481            return Ok(None);
482        }
483
484        if self.parts.len() == 1 {
485            // If there's only one part, return its batch directly
486            return Ok(Some(self.parts[0].batch.clone()));
487        }
488
489        let schemas = self
490            .parts
491            .iter()
492            .map(|x| (x.batch.schema(), x.num_rows() as u64))
493            .collect::<Vec<_>>();
494        let plans = collect_json2_rewrite_plans(metadata, &schemas)?;
495
496        debug_assert!(self.parts.windows(2).all(|w| rewrite_json2_schema(
497            &w[0].batch.schema(),
498            &plans
499        ) == rewrite_json2_schema(
500            &w[1].batch.schema(),
501            &plans
502        )));
503        let schema = rewrite_json2_schema(&self.parts[0].batch.schema(), &plans);
504
505        let batches = self
506            .parts
507            .iter()
508            .map(|x| rewrite_json2_batch(x.batch.clone(), &plans))
509            .collect::<Result<Vec<_>>>()?;
510        let concatenated = concat_batches(&schema, &batches).context(ComputeArrowSnafu)?;
511
512        // Sort the concatenated batch
513        let sorted_batch = sort_primary_key_record_batch(&concatenated)?;
514
515        Ok(Some(sorted_batch))
516    }
517
518    /// Converts all parts into a single sorted BulkPart.
519    /// Returns None if the collection is empty.
520    pub fn to_bulk_part(&self, metadata: &RegionMetadataRef) -> Result<Option<BulkPart>> {
521        let Some(sorted_batch) = self.concat_and_sort(metadata)? else {
522            return Ok(None);
523        };
524
525        let timestamp_index = self.parts[0].timestamp_index;
526
527        Ok(Some(BulkPart {
528            batch: sorted_batch,
529            max_timestamp: self.max_timestamp,
530            min_timestamp: self.min_timestamp,
531            sequence: self.max_sequence,
532            min_sequence: self.min_sequence,
533            timestamp_index,
534            raw_data: None,
535        }))
536    }
537
538    /// Clears all parts from this collection.
539    pub fn clear(&mut self) {
540        self.parts.clear();
541        self.total_rows = 0;
542        self.total_bytes = 0;
543        self.min_timestamp = i64::MAX;
544        self.max_timestamp = i64::MIN;
545        self.max_sequence = 0;
546        self.min_sequence = SequenceNumber::MAX;
547    }
548}
549
550/// More accurate estimation of the size of a record batch.
551pub fn record_batch_estimated_size(batch: &RecordBatch) -> usize {
552    batch
553        .columns()
554        .iter()
555        // If can not get slice memory size, assume 0 here.
556        .map(|c| c.to_data().get_slice_memory_size().unwrap_or(0))
557        .sum()
558}
559
560/// Primary key column builder for handling strings specially.
561enum PrimaryKeyColumnBuilder {
562    /// String dictionary builder for string types.
563    StringDict(StringDictionaryBuilder<UInt32Type>),
564    /// Generic mutable vector for other types.
565    Vector(Box<dyn MutableVector>),
566}
567
568impl PrimaryKeyColumnBuilder {
569    /// Appends a value to the builder.
570    fn push_value_ref(&mut self, value: ValueRef) -> Result<()> {
571        match self {
572            PrimaryKeyColumnBuilder::StringDict(builder) => {
573                if let Some(s) = value.try_into_string().context(DataTypeMismatchSnafu)? {
574                    // We know the value is a string.
575                    builder.append_value(s);
576                } else {
577                    builder.append_null();
578                }
579            }
580            PrimaryKeyColumnBuilder::Vector(builder) => {
581                builder.push_value_ref(&value);
582            }
583        }
584        Ok(())
585    }
586
587    /// Converts the builder to an ArrayRef.
588    fn into_arrow_array(self) -> ArrayRef {
589        match self {
590            PrimaryKeyColumnBuilder::StringDict(mut builder) => Arc::new(builder.finish()),
591            PrimaryKeyColumnBuilder::Vector(mut builder) => builder.to_vector().to_arrow_array(),
592        }
593    }
594}
595
596/// Converter that converts structs into [BulkPart].
597pub struct BulkPartConverter {
598    /// Schema of the converted batch.
599    schema: SchemaRef,
600    /// Primary key codec for encoding keys
601    primary_key_codec: Arc<dyn PrimaryKeyCodec>,
602    /// Buffer for encoding primary key.
603    key_buf: Vec<u8>,
604    /// Primary key array builder.
605    key_array_builder: PrimaryKeyArrayBuilder,
606    /// Whether any input key was supplied pre-encoded and still needs validation.
607    has_pre_encoded_keys: bool,
608    /// Builders for non-primary key columns.
609    value_builder: ValueBuilder,
610    /// Builders for individual primary key columns.
611    /// The order of builders is the same as the order of primary key columns in the region metadata.
612    primary_key_column_builders: Vec<PrimaryKeyColumnBuilder>,
613
614    /// Max timestamp value.
615    max_ts: i64,
616    /// Min timestamp value.
617    min_ts: i64,
618    /// Max sequence number.
619    max_sequence: SequenceNumber,
620    /// Min sequence number.
621    min_sequence: SequenceNumber,
622}
623
624impl BulkPartConverter {
625    /// Creates a new converter.
626    ///
627    /// If `store_primary_key_columns` is true and the encoding is not sparse encoding, it
628    /// stores primary key columns in arrays additionally.
629    pub fn new(
630        region_metadata: &RegionMetadataRef,
631        schema: SchemaRef,
632        capacity: usize,
633        primary_key_codec: Arc<dyn PrimaryKeyCodec>,
634        store_primary_key_columns: bool,
635    ) -> Self {
636        debug_assert_eq!(
637            region_metadata.primary_key_encoding,
638            primary_key_codec.encoding()
639        );
640
641        let primary_key_column_builders = if store_primary_key_columns
642            && region_metadata.primary_key_encoding != PrimaryKeyEncoding::Sparse
643        {
644            new_primary_key_column_builders(region_metadata, capacity)
645        } else {
646            Vec::new()
647        };
648
649        Self {
650            schema,
651            primary_key_codec,
652            key_buf: Vec::new(),
653            key_array_builder: PrimaryKeyArrayBuilder::new(),
654            has_pre_encoded_keys: false,
655            value_builder: ValueBuilder::new(region_metadata, capacity),
656            primary_key_column_builders,
657            min_ts: i64::MAX,
658            max_ts: i64::MIN,
659            max_sequence: SequenceNumber::MIN,
660            min_sequence: SequenceNumber::MAX,
661        }
662    }
663
664    /// Appends a [KeyValues] into the converter.
665    pub fn append_key_values(&mut self, key_values: &KeyValues) -> Result<()> {
666        for kv in key_values.iter() {
667            self.append_key_value(&kv)?;
668        }
669
670        Ok(())
671    }
672
673    /// Appends a [KeyValue] to builders.
674    ///
675    /// Metric-sparse hints carry encoded keys; raw tags use the destination codec.
676    fn append_key_value(&mut self, kv: &KeyValue) -> Result<()> {
677        // Handles primary key based on encoding type
678        if kv.primary_key_encoding() == PrimaryKeyEncoding::Sparse {
679            ensure!(
680                self.primary_key_codec.encoding() == PrimaryKeyEncoding::Sparse,
681                error::InvalidRecordBatchSnafu {
682                    reason: "pre-encoded primary keys require a sparse destination layout",
683                }
684            );
685            // For sparse encoding, the primary key is already encoded in the KeyValue
686            // Gets the first (and only) primary key value which contains the encoded key
687            let mut primary_keys = kv.primary_keys();
688            if let Some(encoded) = primary_keys
689                .next()
690                .context(ColumnNotFoundSnafu {
691                    column: PRIMARY_KEY_COLUMN_NAME,
692                })?
693                .try_into_binary()
694                .context(DataTypeMismatchSnafu)?
695            {
696                self.key_array_builder
697                    .append(encoded)
698                    .context(ComputeArrowSnafu)?;
699                self.has_pre_encoded_keys = true;
700            } else {
701                return error::InvalidRecordBatchSnafu {
702                    reason: "encoded metric primary key must not be null",
703                }
704                .fail();
705            }
706        } else {
707            // Encode raw primary key columns with the destination codec.
708            self.key_buf.clear();
709            self.primary_key_codec
710                .encode_key_value(kv, &mut self.key_buf)
711                .context(EncodeSnafu)?;
712            self.key_array_builder
713                .append(&self.key_buf)
714                .context(ComputeArrowSnafu)?;
715        };
716
717        // If storing primary key columns, append values to individual builders
718        if !self.primary_key_column_builders.is_empty() {
719            for (builder, pk_value) in self
720                .primary_key_column_builders
721                .iter_mut()
722                .zip(kv.primary_keys())
723            {
724                builder.push_value_ref(pk_value)?;
725            }
726        }
727
728        // Pushes other columns.
729        self.value_builder.push(
730            kv.timestamp(),
731            kv.sequence(),
732            kv.op_type() as u8,
733            kv.fields(),
734        );
735
736        // Updates statistics
737        // Safety: timestamp of kv must be both present and a valid timestamp value.
738        let ts = kv
739            .timestamp()
740            .try_into_timestamp()
741            .unwrap()
742            .unwrap()
743            .value();
744        self.min_ts = self.min_ts.min(ts);
745        self.max_ts = self.max_ts.max(ts);
746        self.max_sequence = self.max_sequence.max(kv.sequence());
747        self.min_sequence = self.min_sequence.min(kv.sequence());
748
749        Ok(())
750    }
751
752    /// Converts buffered content into a [BulkPart].
753    ///
754    /// It sorts the record batch by (primary key, timestamp, sequence desc).
755    pub fn convert(mut self) -> Result<BulkPart> {
756        let values = Values::from(self.value_builder);
757        let mut columns =
758            Vec::with_capacity(4 + values.fields.len() + self.primary_key_column_builders.len());
759
760        // Build primary key column arrays if enabled.
761        for builder in self.primary_key_column_builders {
762            columns.push(builder.into_arrow_array());
763        }
764        // Then fields columns.
765        columns.extend(values.fields.iter().map(|field| field.to_arrow_array()));
766        // Time index.
767        let timestamp_index = columns.len();
768        columns.push(values.timestamp.to_arrow_array());
769        // Primary key.
770        let pk_array = self.key_array_builder.finish();
771        if self.has_pre_encoded_keys {
772            validate_sparse_dictionary(&pk_array)?;
773        }
774        columns.push(Arc::new(pk_array));
775        // Sequence and op type.
776        columns.push(values.sequence.to_arrow_array());
777        columns.push(values.op_type.to_arrow_array());
778
779        // The actual datatype of JSON array is data oriented, not to be derived from the Region
780        // metadata, which is static. So here we have to align the schema.
781        let schema = align_schema_with_json_array(self.schema, &columns);
782        let batch = RecordBatch::try_new(schema, columns).context(NewRecordBatchSnafu)?;
783        // Sorts the record batch.
784        let batch = sort_primary_key_record_batch(&batch)?;
785
786        Ok(BulkPart {
787            batch,
788            max_timestamp: self.max_ts,
789            min_timestamp: self.min_ts,
790            sequence: self.max_sequence,
791            min_sequence: self.min_sequence,
792            timestamp_index,
793            raw_data: None,
794        })
795    }
796}
797
798/// Validates each referenced key once; sliced dictionaries may retain unused invalid values.
799fn validate_sparse_dictionary(keys: &PrimaryKeyArray) -> Result<()> {
800    let values = keys
801        .values()
802        .as_any()
803        .downcast_ref::<BinaryArray>()
804        .context(error::InvalidRecordBatchSnafu {
805            reason: "encoded primary keys must be binary",
806        })?;
807    ensure!(
808        keys.logical_null_count() == 0,
809        error::InvalidRecordBatchSnafu {
810            reason: "encoded primary key must not be null",
811        }
812    );
813    let mut validated = vec![false; values.len()];
814    let mut validator = SparsePrimaryKeyValidator::default();
815    for &index in keys.keys().values() {
816        let index = index as usize;
817        if !validated[index] {
818            validator
819                .validate(values.value(index))
820                .context(EncodeSnafu)?;
821            validated[index] = true;
822        }
823    }
824    Ok(())
825}
826
827fn new_primary_key_column_builders(
828    metadata: &RegionMetadata,
829    capacity: usize,
830) -> Vec<PrimaryKeyColumnBuilder> {
831    metadata
832        .primary_key_columns()
833        .map(|col| {
834            if col.column_schema.data_type.is_string() {
835                PrimaryKeyColumnBuilder::StringDict(StringDictionaryBuilder::with_capacity(
836                    capacity,
837                    INIT_DICT_VALUE_CAPACITY,
838                    capacity,
839                ))
840            } else {
841                PrimaryKeyColumnBuilder::Vector(
842                    col.column_schema.data_type.create_mutable_vector(capacity),
843                )
844            }
845        })
846        .collect()
847}
848
849/// Sorts the record batch with primary key format.
850pub fn sort_primary_key_record_batch(batch: &RecordBatch) -> Result<RecordBatch> {
851    let indices = if let Some(indices) = try_sort_primary_key_indices(batch)? {
852        indices
853    } else {
854        lexsort_primary_key_indices(batch)?
855    };
856
857    datatypes::arrow::compute::take_record_batch(batch, &indices).context(ComputeArrowSnafu)
858}
859
860/// Sorts the known, non-null primary-key layout without comparing encoded keys for every row.
861///
862/// Returns `None` if the batch does not have the exact layout supported by this fast path.
863fn try_sort_primary_key_indices(batch: &RecordBatch) -> Result<Option<UInt32Array>> {
864    let total_columns = batch.num_columns();
865    let timestamp = batch.column(total_columns - 4);
866    let primary_key = batch.column(total_columns - 3);
867    let sequence = batch.column(total_columns - 2);
868
869    let Some(primary_key) = primary_key
870        .as_any()
871        .downcast_ref::<DictionaryArray<UInt32Type>>()
872    else {
873        return Ok(None);
874    };
875    let Some(sequence) = sequence.as_any().downcast_ref::<UInt64Array>() else {
876        return Ok(None);
877    };
878
879    if batch.num_rows() > u32::MAX as usize
880        || primary_key.null_count() != 0
881        || primary_key.values().data_type() != &ArrowDataType::Binary
882        || primary_key.values().null_count() != 0
883        || primary_key.values().len() > batch.num_rows()
884        || timestamp.null_count() != 0
885        || sequence.null_count() != 0
886    {
887        return Ok(None);
888    }
889
890    let indices = match timestamp.data_type() {
891        ArrowDataType::Timestamp(TimeUnit::Second, _) => timestamp
892            .as_any()
893            .downcast_ref::<TimestampSecondArray>()
894            .map(|timestamp| sort_primary_key_indices(primary_key, timestamp.values(), sequence)),
895        ArrowDataType::Timestamp(TimeUnit::Millisecond, _) => timestamp
896            .as_any()
897            .downcast_ref::<TimestampMillisecondArray>()
898            .map(|timestamp| sort_primary_key_indices(primary_key, timestamp.values(), sequence)),
899        ArrowDataType::Timestamp(TimeUnit::Microsecond, _) => timestamp
900            .as_any()
901            .downcast_ref::<TimestampMicrosecondArray>()
902            .map(|timestamp| sort_primary_key_indices(primary_key, timestamp.values(), sequence)),
903        ArrowDataType::Timestamp(TimeUnit::Nanosecond, _) => timestamp
904            .as_any()
905            .downcast_ref::<TimestampNanosecondArray>()
906            .map(|timestamp| sort_primary_key_indices(primary_key, timestamp.values(), sequence)),
907        _ => None,
908    };
909
910    indices.transpose()
911}
912
913/// Computes sorted row indices by ranking dictionary values, scattering rows into primary-key
914/// buckets, and sorting only buckets that are not already ordered by time and sequence.
915fn sort_primary_key_indices(
916    primary_key: &PrimaryKeyArray,
917    timestamps: &[i64],
918    sequences: &UInt64Array,
919) -> Result<UInt32Array> {
920    debug_assert_eq!(primary_key.len(), timestamps.len());
921    debug_assert_eq!(primary_key.len(), sequences.len());
922    debug_assert_eq!(primary_key.null_count(), 0);
923    debug_assert_eq!(primary_key.values().null_count(), 0);
924    debug_assert_eq!(sequences.null_count(), 0);
925
926    // Ranks compare in the same order as the dictionary values. Equal dictionary values receive
927    // the same rank, which is required because Arrow dictionary concatenation only deduplicates
928    // values on a best-effort basis.
929    let value_ranks = datatypes::arrow::compute::rank(
930        primary_key.values().as_ref(),
931        Some(SortOptions {
932            descending: false,
933            nulls_first: true,
934        }),
935    )
936    .context(ComputeArrowSnafu)?;
937
938    // A rank is at most the number of dictionary values. It is not necessarily dense when the
939    // dictionary contains duplicate values, so keep one extra slot and allow empty buckets.
940    let mut counts = vec![0usize; value_ranks.len() + 1];
941    for &key in primary_key.keys().values() {
942        counts[value_ranks[key as usize] as usize] += 1;
943    }
944
945    let mut bucket_offsets = vec![0usize; counts.len()];
946    let mut offset = 0;
947    for (bucket_offset, &count) in bucket_offsets.iter_mut().zip(&counts) {
948        *bucket_offset = offset;
949        offset += count;
950    }
951
952    // Scatter in input order. This preserves already sorted runs within each primary key.
953    let mut next_offsets = bucket_offsets.clone();
954    let mut indices = vec![0u32; primary_key.len()];
955    for (row, &key) in primary_key.keys().values().iter().enumerate() {
956        let rank = value_ranks[key as usize] as usize;
957        indices[next_offsets[rank]] = row as u32;
958        next_offsets[rank] += 1;
959    }
960
961    let sequences = sequences.values();
962    for (&start, count) in bucket_offsets.iter().zip(counts) {
963        let end = start + count;
964        let bucket = &mut indices[start..end];
965        if !bucket.is_sorted_by(|left, right| {
966            compare_time_sequence(timestamps, sequences, *left, *right).is_le()
967        }) {
968            bucket.sort_unstable_by(|left, right| {
969                compare_time_sequence(timestamps, sequences, *left, *right)
970            });
971        }
972    }
973
974    Ok(UInt32Array::from(indices))
975}
976
977#[inline]
978fn compare_time_sequence(
979    timestamps: &[i64],
980    sequences: &[u64],
981    left: u32,
982    right: u32,
983) -> std::cmp::Ordering {
984    let left = left as usize;
985    let right = right as usize;
986    timestamps[left]
987        .cmp(&timestamps[right])
988        .then_with(|| sequences[right].cmp(&sequences[left]))
989}
990
991fn lexsort_primary_key_indices(batch: &RecordBatch) -> Result<UInt32Array> {
992    let total_columns = batch.num_columns();
993    let sort_columns = vec![
994        // Primary key column (ascending)
995        SortColumn {
996            values: batch.column(total_columns - 3).clone(),
997            options: Some(SortOptions {
998                descending: false,
999                nulls_first: true,
1000            }),
1001        },
1002        // Time index column (ascending)
1003        SortColumn {
1004            values: batch.column(total_columns - 4).clone(),
1005            options: Some(SortOptions {
1006                descending: false,
1007                nulls_first: true,
1008            }),
1009        },
1010        // Sequence column (descending)
1011        SortColumn {
1012            values: batch.column(total_columns - 2).clone(),
1013            options: Some(SortOptions {
1014                descending: true,
1015                nulls_first: true,
1016            }),
1017        },
1018    ];
1019
1020    datatypes::arrow::compute::lexsort_to_indices(&sort_columns, None).context(ComputeArrowSnafu)
1021}
1022
1023/// Converts an unordered `BulkPart` with raw tags or encoded primary keys into a `BulkPart`
1024/// with the same format as produced by [BulkPartConverter].
1025///
1026/// This function takes a `BulkPart` where:
1027/// - Raw primary key columns are stored individually and encoded with the destination codec
1028/// - Sparse destinations also accept encoded keys in a `__primary_key` column
1029/// - The batch may not be sorted
1030///
1031/// And produces a `BulkPart` where:
1032/// - Primary key columns are optionally stored (depending on `store_primary_key_columns` and encoding)
1033/// - An encoded `__primary_key` dictionary column is present
1034/// - The batch is sorted by (primary_key, timestamp, sequence desc)
1035///
1036/// # Arguments
1037///
1038/// * `part` - The input `BulkPart` to convert
1039/// * `region_metadata` - Region metadata containing schema information
1040/// * `primary_key_codec` - Codec for encoding primary keys
1041/// * `schema` - Target schema for the output batch
1042/// * `store_primary_key_columns` - If true and encoding is not sparse, stores individual primary key columns
1043///
1044/// # Returns
1045///
1046/// Returns `None` if the input part has no rows, otherwise returns a new `BulkPart` with
1047/// encoded primary keys and sorted data.
1048pub fn convert_bulk_part(
1049    part: BulkPart,
1050    region_metadata: &RegionMetadataRef,
1051    primary_key_codec: Arc<dyn PrimaryKeyCodec>,
1052    schema: SchemaRef,
1053    store_primary_key_columns: bool,
1054) -> Result<Option<BulkPart>> {
1055    if part.num_rows() == 0 {
1056        return Ok(None);
1057    }
1058
1059    let num_rows = part.num_rows();
1060    let is_sparse = region_metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse;
1061
1062    // Builds a column name-to-index map for efficient lookups
1063    let input_schema = part.batch.schema();
1064    let column_indices: HashMap<&str, usize> = input_schema
1065        .fields()
1066        .iter()
1067        .enumerate()
1068        .map(|(idx, field)| (field.name().as_str(), idx))
1069        .collect();
1070
1071    // Determines the structure of the input batch by looking up columns by name
1072    let mut output_columns = Vec::new();
1073
1074    // Encoded input is explicit; otherwise encode raw tags with the destination codec.
1075    let pk_dictionary: ArrayRef = if column_indices.contains_key(PRIMARY_KEY_COLUMN_NAME) {
1076        ensure!(
1077            is_sparse,
1078            error::InvalidRecordBatchSnafu {
1079                reason: "pre-encoded bulk keys require a sparse destination layout"
1080            }
1081        );
1082        let column = part.batch.column(column_indices[PRIMARY_KEY_COLUMN_NAME]);
1083        ensure!(
1084            column.data_type() == &ArrowDataType::Binary
1085                || matches!(column.data_type(), ArrowDataType::Dictionary(_, value) if value.as_ref() == &ArrowDataType::Binary),
1086            error::InvalidRecordBatchSnafu {
1087                reason: "encoded primary keys must be binary"
1088            }
1089        );
1090        let target_type = ArrowDataType::Dictionary(
1091            Box::new(ArrowDataType::UInt32),
1092            Box::new(ArrowDataType::Binary),
1093        );
1094        let column = arrow::compute::cast(column, &target_type).context(ComputeArrowSnafu)?;
1095        let keys = column.as_any().downcast_ref::<PrimaryKeyArray>().context(
1096            error::InvalidRecordBatchSnafu {
1097                reason: "encoded primary keys must be a UInt32 binary dictionary",
1098            },
1099        )?;
1100        validate_sparse_dictionary(keys)?;
1101        column
1102    } else {
1103        // Extract and encode primary key columns by name.
1104        let pk_vectors: Result<Vec<_>> = region_metadata
1105            .primary_key_columns()
1106            .map(|col_meta| {
1107                let col_idx = column_indices
1108                    .get(col_meta.column_schema.name.as_str())
1109                    .context(ColumnNotFoundSnafu {
1110                        column: &col_meta.column_schema.name,
1111                    })?;
1112                let col = part.batch.column(*col_idx);
1113                Helper::try_into_vector(col).context(error::ComputeVectorSnafu)
1114            })
1115            .collect();
1116        let pk_vectors = pk_vectors?;
1117
1118        let mut key_array_builder = PrimaryKeyArrayBuilder::new();
1119        let mut encode_buf = Vec::new();
1120
1121        for row_idx in 0..num_rows {
1122            encode_buf.clear();
1123
1124            // Collects primary key values with column IDs for this row
1125            let pk_values_with_ids: Vec<_> = region_metadata
1126                .primary_key
1127                .iter()
1128                .zip(pk_vectors.iter())
1129                .map(|(col_id, vector)| (*col_id, vector.get_ref(row_idx)))
1130                .collect();
1131
1132            // Encodes the primary key
1133            primary_key_codec
1134                .encode_value_refs(&pk_values_with_ids, &mut encode_buf)
1135                .context(EncodeSnafu)?;
1136
1137            key_array_builder
1138                .append(&encode_buf)
1139                .context(ComputeArrowSnafu)?;
1140        }
1141
1142        Arc::new(key_array_builder.finish())
1143    };
1144
1145    // Adds primary key columns if storing them (only for dense encoding)
1146    if store_primary_key_columns && !is_sparse {
1147        for col_meta in region_metadata.primary_key_columns() {
1148            let col_idx = column_indices
1149                .get(col_meta.column_schema.name.as_str())
1150                .context(ColumnNotFoundSnafu {
1151                    column: &col_meta.column_schema.name,
1152                })?;
1153            let col = part.batch.column(*col_idx);
1154
1155            // Converts to dictionary if needed for string types
1156            let col = if col_meta.column_schema.data_type.is_string() {
1157                let target_type = ArrowDataType::Dictionary(
1158                    Box::new(ArrowDataType::UInt32),
1159                    Box::new(ArrowDataType::Utf8),
1160                );
1161                arrow::compute::cast(col, &target_type).context(ComputeArrowSnafu)?
1162            } else {
1163                col.clone()
1164            };
1165            output_columns.push(col);
1166        }
1167    }
1168
1169    // Adds field columns
1170    for col_meta in region_metadata.field_columns() {
1171        let col_idx = column_indices
1172            .get(col_meta.column_schema.name.as_str())
1173            .context(ColumnNotFoundSnafu {
1174                column: &col_meta.column_schema.name,
1175            })?;
1176        output_columns.push(part.batch.column(*col_idx).clone());
1177    }
1178
1179    // Adds timestamp column
1180    let new_timestamp_index = output_columns.len();
1181    let ts_col_idx = column_indices
1182        .get(
1183            region_metadata
1184                .time_index_column()
1185                .column_schema
1186                .name
1187                .as_str(),
1188        )
1189        .context(ColumnNotFoundSnafu {
1190            column: &region_metadata.time_index_column().column_schema.name,
1191        })?;
1192    output_columns.push(part.batch.column(*ts_col_idx).clone());
1193
1194    // Adds encoded primary key dictionary column
1195    output_columns.push(pk_dictionary);
1196
1197    let sequence_array = UInt64Array::from(vec![part.sequence; num_rows]);
1198    output_columns.push(Arc::new(sequence_array) as ArrayRef);
1199
1200    let op_type_array = UInt8Array::from(vec![OpType::Put as u8; num_rows]);
1201    output_columns.push(Arc::new(op_type_array) as ArrayRef);
1202
1203    // JSON2 arrays carry a data-dependent shape and their own physical layout version.
1204    // Keep that layout metadata while retaining the destination's column IDs.
1205    let schema = if region_metadata
1206        .field_columns()
1207        .any(|c| c.column_schema.data_type.is_json2())
1208    {
1209        let fields = schema
1210            .fields()
1211            .iter()
1212            .map(|field| {
1213                if !datatypes::extension::json::is_json2_extension_type(field) {
1214                    return field.clone();
1215                }
1216                let source = input_schema.field(column_indices[field.name().as_str()]);
1217                let mut metadata = field.metadata().clone();
1218                if datatypes::extension::json::is_json2_extension_type(source) {
1219                    for key in [
1220                        arrow_schema::extension::EXTENSION_TYPE_NAME_KEY,
1221                        arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY,
1222                    ] {
1223                        if let Some(value) = source.metadata().get(key) {
1224                            metadata.insert(key.to_string(), value.clone());
1225                        } else {
1226                            metadata.remove(key);
1227                        }
1228                    }
1229                }
1230                Arc::new(
1231                    field
1232                        .as_ref()
1233                        .clone()
1234                        .with_data_type(source.data_type().clone())
1235                        .with_metadata(metadata),
1236                )
1237            })
1238            .collect::<Vec<_>>();
1239        Arc::new(Schema::new_with_metadata(fields, schema.metadata().clone()))
1240    } else {
1241        schema
1242    };
1243    let batch = RecordBatch::try_new(schema, output_columns).context(NewRecordBatchSnafu)?;
1244
1245    // Sorts the batch by (primary_key, timestamp, sequence desc)
1246    let sorted_batch = sort_primary_key_record_batch(&batch)?;
1247
1248    Ok(Some(BulkPart {
1249        batch: sorted_batch,
1250        max_timestamp: part.max_timestamp,
1251        min_timestamp: part.min_timestamp,
1252        sequence: part.sequence,
1253        min_sequence: part.sequence,
1254        timestamp_index: new_timestamp_index,
1255        raw_data: None,
1256    }))
1257}
1258
1259#[derive(Debug, Clone)]
1260pub struct EncodedBulkPart {
1261    payload: EncodedBulkPayload,
1262    metadata: BulkPartMeta,
1263    /// Cached Arrow schema to avoid rebuilding it from parquet metadata.
1264    schema: SchemaRef,
1265}
1266
1267#[derive(Debug, Clone)]
1268enum EncodedBulkPayload {
1269    Parquet(ParquetBulkPart),
1270    Narthex(crate::series_index::samples::bulk::NarthexBulkPart),
1271}
1272
1273/// Encoded Parquet bytes and their corresponding file metadata.
1274#[derive(Debug, Clone)]
1275pub struct ParquetBulkPart {
1276    pub(crate) data: Bytes,
1277    pub(crate) metadata: Arc<ParquetMetaData>,
1278}
1279
1280impl EncodedBulkPart {
1281    /// Returns the Parquet payload, if this part uses Parquet encoding.
1282    pub fn parquet_part(&self) -> Option<&ParquetBulkPart> {
1283        match &self.payload {
1284            EncodedBulkPayload::Parquet(part) => Some(part),
1285            EncodedBulkPayload::Narthex(_) => None,
1286        }
1287    }
1288
1289    pub fn parquet_metadata(&self) -> Option<&Arc<ParquetMetaData>> {
1290        match &self.payload {
1291            EncodedBulkPayload::Parquet(part) => Some(&part.metadata),
1292            EncodedBulkPayload::Narthex(_) => None,
1293        }
1294    }
1295
1296    pub fn metadata(&self) -> &BulkPartMeta {
1297        &self.metadata
1298    }
1299
1300    pub(crate) fn schema(&self) -> SchemaRef {
1301        self.schema.clone()
1302    }
1303
1304    /// Returns the estimated decoded size of all rows: the uncompressed column chunks, or the
1305    /// variable-length values when dictionary encoding hides them from that size.
1306    pub(crate) fn decoded_size(&self) -> u64 {
1307        let encoded: u64 = self
1308            .parquet_metadata()
1309            .map_or(self.size_bytes() as u64, |metadata| {
1310                metadata
1311                    .row_groups()
1312                    .iter()
1313                    .flat_map(|row_group| row_group.columns())
1314                    .map(|column| column.uncompressed_size() as u64)
1315                    .sum()
1316            });
1317        encoded.max(self.metadata.var_len_bytes)
1318    }
1319
1320    /// Returns the size of the encoded data in bytes
1321    pub(crate) fn size_bytes(&self) -> usize {
1322        match &self.payload {
1323            EncodedBulkPayload::Parquet(part) => part.data.len(),
1324            EncodedBulkPayload::Narthex(part) => part.size_bytes(),
1325        }
1326    }
1327
1328    /// Only Parquet parts can use the existing direct-upload shortcut.
1329    pub fn data(&self) -> Option<&Bytes> {
1330        match &self.payload {
1331            EncodedBulkPayload::Parquet(part) => Some(&part.data),
1332            EncodedBulkPayload::Narthex(_) => None,
1333        }
1334    }
1335
1336    /// Creates MemtableStats from this EncodedBulkPart.
1337    pub fn to_memtable_stats(&self) -> MemtableStats {
1338        let meta = &self.metadata;
1339        let ts_type = meta.region_metadata.time_index_type();
1340        let min_ts = ts_type.create_timestamp(meta.min_timestamp);
1341        let max_ts = ts_type.create_timestamp(meta.max_timestamp);
1342
1343        MemtableStats {
1344            estimated_bytes: self.size_bytes(),
1345            decoded_bytes: Some(self.decoded_size() as usize),
1346            time_range: Some((min_ts, max_ts)),
1347            num_rows: meta.num_rows,
1348            num_ranges: 1,
1349            max_sequence: meta.max_sequence,
1350            min_sequence: meta.min_sequence,
1351            series_count: meta.num_series as usize,
1352        }
1353    }
1354
1355    /// Returns SST metadata for an encoded Parquet part that can be uploaded directly.
1356    /// Narthex parts return `None`: they contain in-memory sample blocks rather than
1357    /// a complete persisted artifact and currently require decoding and re-encoding on flush.
1358    ///
1359    /// # Arguments
1360    /// * `file_id` - The SST file ID to assign to this part
1361    pub(crate) fn to_sst_info(&self, file_id: FileId) -> Option<SstInfo> {
1362        // TODO(yingwen): Support direct flush of encoded Narthex parts by assembling
1363        // the persisted manifest/parts inventory and SST metadata without decoding
1364        // and re-encoding their sample columns.
1365        let parquet_metadata = self.parquet_metadata()?;
1366        let unit = self.metadata.region_metadata.time_index_type().unit();
1367        let max_row_group_uncompressed_size = max_row_group_uncompressed_size(parquet_metadata);
1368        let max_row_group_decoded_size = max_row_group_decoded_size(parquet_metadata);
1369        Some(SstInfo {
1370            file_id,
1371            time_range: (
1372                Timestamp::new(self.metadata.min_timestamp, unit),
1373                Timestamp::new(self.metadata.max_timestamp, unit),
1374            ),
1375            file_size: self.size_bytes() as u64,
1376            max_row_group_uncompressed_size,
1377            max_row_group_decoded_size,
1378            num_rows: self.metadata.num_rows,
1379            num_row_groups: parquet_metadata.num_row_groups() as u64,
1380            file_metadata: Some(parquet_metadata.clone()),
1381            index_metadata: IndexOutput::default(),
1382            num_series: self.metadata.num_series,
1383            format: Default::default(),
1384        })
1385    }
1386
1387    pub(crate) fn primary_keys(&self) -> Option<crate::memtable::BoxedPrimaryKeyIterator> {
1388        match &self.payload {
1389            EncodedBulkPayload::Narthex(part) => Some(part.primary_keys()),
1390            EncodedBulkPayload::Parquet(_) => None,
1391        }
1392    }
1393
1394    pub(crate) fn read(
1395        &self,
1396        context: BulkIterContextRef,
1397        sequence: Option<SequenceRange>,
1398        mem_scan_metrics: Option<MemScanMetrics>,
1399    ) -> Result<Option<BoxedRecordBatchIterator>> {
1400        let parquet_part = match &self.payload {
1401            EncodedBulkPayload::Parquet(part) => part,
1402            EncodedBulkPayload::Narthex(part) => {
1403                let iter = part.read(self.schema.clone()).flat_map(
1404                    move |batch| -> BoxedRecordBatchIterator {
1405                        match batch {
1406                            Ok(batch) => {
1407                                Box::new(super::part_reader::BulkPartBatchIter::from_single(
1408                                    batch,
1409                                    context.clone(),
1410                                    sequence,
1411                                    1,
1412                                    mem_scan_metrics.clone(),
1413                                ))
1414                            }
1415                            Err(error) => Box::new(std::iter::once(Err(error))),
1416                        }
1417                    },
1418                );
1419                return Ok(Some(Box::new(iter)));
1420            }
1421        };
1422        let parquet_metadata = &parquet_part.metadata;
1423        // Compute skip_fields for row group pruning from the configured pre-filter mode.
1424        let skip_fields_for_pruning = context.pre_filter_mode().skip_fields();
1425
1426        // use predicate to find row groups to read.
1427        let row_groups_to_read =
1428            context.row_groups_to_read(parquet_metadata, skip_fields_for_pruning);
1429
1430        if row_groups_to_read.is_empty() {
1431            // All row groups are filtered.
1432            return Ok(None);
1433        }
1434
1435        let iter = ParquetBulkPartIter::try_new(
1436            parquet_part,
1437            self.metadata.num_series as usize,
1438            context,
1439            row_groups_to_read,
1440            sequence,
1441            mem_scan_metrics,
1442        )?;
1443        Ok(Some(Box::new(iter) as BoxedRecordBatchIterator))
1444    }
1445}
1446
1447// TODO(yingwen): max_sequence
1448#[derive(Debug, Clone)]
1449pub struct BulkPartMeta {
1450    /// Total rows in part.
1451    pub num_rows: usize,
1452    /// Max timestamp in part.
1453    pub max_timestamp: i64,
1454    /// Min timestamp in part.
1455    pub min_timestamp: i64,
1456    /// Part region schema.
1457    pub region_metadata: RegionMetadataRef,
1458    /// Number of series.
1459    pub num_series: u64,
1460    /// Lower bound of input sequences, including rows removed by deduplication.
1461    pub min_sequence: SequenceNumber,
1462    /// Maximum sequence number in part.
1463    pub max_sequence: u64,
1464    /// Decoded bytes of string and binary values.
1465    pub var_len_bytes: u64,
1466}
1467
1468/// Metrics for encoding a part.
1469#[derive(Default, Debug)]
1470pub struct BulkPartEncodeMetrics {
1471    /// Cost of iterating over the data.
1472    pub iter_cost: Duration,
1473    /// Cost of writing the data.
1474    pub write_cost: Duration,
1475    /// Size of data before encoding.
1476    pub raw_size: usize,
1477    /// Size of data after encoding.
1478    pub encoded_size: usize,
1479    /// Number of rows in part.
1480    pub num_rows: usize,
1481}
1482
1483pub struct BulkPartEncoder {
1484    metadata: RegionMetadataRef,
1485    writer_props: Option<WriterProperties>,
1486    narthex_format: bool,
1487}
1488
1489impl BulkPartEncoder {
1490    pub fn new(metadata: RegionMetadataRef, row_group_size: usize) -> Result<BulkPartEncoder> {
1491        Self::new_with_float_field_encoding(metadata, row_group_size, FloatFieldEncoding::default())
1492    }
1493
1494    pub(crate) fn new_with_float_field_encoding(
1495        metadata: RegionMetadataRef,
1496        row_group_size: usize,
1497        float_field_encoding: FloatFieldEncoding,
1498    ) -> Result<BulkPartEncoder> {
1499        // TODO(yingwen): Skip arrow schema if needed.
1500        let json = metadata.to_json().context(InvalidMetadataSnafu)?;
1501        let key_value_meta =
1502            parquet::file::metadata::KeyValue::new(PARQUET_METADATA_KEY.to_string(), json);
1503
1504        let mut props = WriterProperties::builder()
1505            .set_key_value_metadata(Some(vec![key_value_meta]))
1506            .set_write_batch_size(row_group_size)
1507            .set_max_row_group_row_count(Some(row_group_size))
1508            .set_compression(Compression::ZSTD(ZstdLevel::default()))
1509            .set_column_index_truncate_length(COLUMN_INDEX_TRUNCATE_LENGTH)
1510            .set_statistics_truncate_length(None);
1511        props = apply_internal_column_encoding(props, &metadata);
1512        props = apply_float_field_encoding(props, &metadata, float_field_encoding);
1513        props = apply_column_compression(props, &metadata)?;
1514        let writer_props = Some(props.build());
1515
1516        Ok(Self {
1517            metadata,
1518            writer_props,
1519            narthex_format: false,
1520        })
1521    }
1522}
1523
1524impl BulkPartEncoder {
1525    pub(crate) fn with_narthex_format(mut self, narthex_format: bool) -> Self {
1526        self.narthex_format = narthex_format;
1527        self
1528    }
1529
1530    /// Returns a tracker cutting row groups like a writer using `props`.
1531    fn row_group_value_bytes(props: &Option<WriterProperties>) -> RowGroupValueBytes {
1532        RowGroupValueBytes::new(
1533            props
1534                .as_ref()
1535                .and_then(WriterProperties::max_row_group_row_count)
1536                .unwrap_or(usize::MAX),
1537        )
1538    }
1539
1540    /// Returns writer properties for a part whose first batch is `batch`.
1541    fn writer_props_for(&self, batch: &RecordBatch) -> Option<WriterProperties> {
1542        let large_value_columns = large_value_fields(&self.metadata, batch);
1543        if large_value_columns.is_empty() {
1544            return self.writer_props.clone();
1545        }
1546        self.writer_props
1547            .clone()
1548            .map(|props| skip_statistics(props.into_builder(), &large_value_columns).build())
1549    }
1550
1551    /// Encodes [BoxedRecordBatchIterator] into [EncodedBulkPart] with min/max timestamps.
1552    pub fn encode_record_batch_iter(
1553        &self,
1554        mut iter: BoxedRecordBatchIterator,
1555        arrow_schema: SchemaRef,
1556        min_timestamp: i64,
1557        max_timestamp: i64,
1558        sequence_bounds: RangeInclusive<SequenceNumber>,
1559        metrics: &mut BulkPartEncodeMetrics,
1560    ) -> Result<Option<EncodedBulkPart>> {
1561        if self.narthex_format {
1562            let mut part = crate::series_index::samples::bulk::NarthexBulkPart::default();
1563            let mut total_rows = 0;
1564            let mut var_len_bytes = 0;
1565            let mut series_estimator = SeriesEstimator::default();
1566            for batch in iter {
1567                let batch = batch?;
1568                if batch.num_rows() == 0 {
1569                    continue;
1570                }
1571                metrics.raw_size += record_batch_estimated_size(&batch);
1572                var_len_bytes += var_len_value_bytes(&batch);
1573                series_estimator.update_flat(&batch);
1574                total_rows += batch.num_rows();
1575                let start = Instant::now();
1576                part.push(&batch)?;
1577                metrics.write_cost += start.elapsed();
1578            }
1579            if total_rows == 0 {
1580                return Ok(None);
1581            }
1582            metrics.encoded_size += part.size_bytes();
1583            metrics.num_rows += total_rows;
1584            return Ok(Some(EncodedBulkPart {
1585                payload: EncodedBulkPayload::Narthex(part),
1586                metadata: BulkPartMeta {
1587                    num_rows: total_rows,
1588                    var_len_bytes,
1589                    min_timestamp,
1590                    max_timestamp,
1591                    region_metadata: self.metadata.clone(),
1592                    num_series: series_estimator.finish(),
1593                    min_sequence: *sequence_bounds.start(),
1594                    max_sequence: *sequence_bounds.end(),
1595                },
1596                schema: arrow_schema,
1597            }));
1598        }
1599        let mut iter_start = Instant::now();
1600        // The first non-empty batch decides which columns skip statistics.
1601        let first = loop {
1602            match iter.next() {
1603                None => return Ok(None),
1604                Some(batch) => {
1605                    let batch = batch?;
1606                    if batch.num_rows() > 0 {
1607                        break batch;
1608                    }
1609                }
1610            }
1611        };
1612        let mut buf = Vec::with_capacity(4096);
1613        let props = self.writer_props_for(&first);
1614        let mut row_group_value_bytes = Self::row_group_value_bytes(&props);
1615        let mut writer = ArrowWriter::try_new(&mut buf, arrow_schema.clone(), props)
1616            .context(EncodeMemtableSnafu)?;
1617        let mut total_rows = 0;
1618        let mut var_len_bytes = 0;
1619        let mut series_estimator = SeriesEstimator::default();
1620
1621        for batch_result in std::iter::once(Ok(first)).chain(iter) {
1622            metrics.iter_cost += iter_start.elapsed();
1623            let batch = batch_result?;
1624            if batch.num_rows() == 0 {
1625                continue;
1626            }
1627
1628            series_estimator.update_flat(&batch);
1629            var_len_bytes += var_len_value_bytes(&batch);
1630            row_group_value_bytes.update(&batch);
1631            metrics.raw_size += record_batch_estimated_size(&batch);
1632            let write_start = Instant::now();
1633            writer.write(&batch).context(EncodeMemtableSnafu)?;
1634            metrics.write_cost += write_start.elapsed();
1635            total_rows += batch.num_rows();
1636            iter_start = Instant::now();
1637        }
1638        metrics.iter_cost += iter_start.elapsed();
1639
1640        let close_start = Instant::now();
1641        for kv in row_group_value_bytes.into_key_values() {
1642            writer.append_key_value_metadata(kv);
1643        }
1644        let file_metadata = writer.close().context(EncodeMemtableSnafu)?;
1645        metrics.write_cost += close_start.elapsed();
1646        metrics.encoded_size += buf.len();
1647        metrics.num_rows += total_rows;
1648
1649        let buf = Bytes::from(buf);
1650        let parquet_metadata = Arc::new(file_metadata);
1651        let num_series = series_estimator.finish();
1652
1653        Ok(Some(EncodedBulkPart {
1654            payload: EncodedBulkPayload::Parquet(ParquetBulkPart {
1655                data: buf,
1656                metadata: parquet_metadata,
1657            }),
1658            metadata: BulkPartMeta {
1659                num_rows: total_rows,
1660                max_timestamp,
1661                min_timestamp,
1662                region_metadata: self.metadata.clone(),
1663                num_series,
1664                min_sequence: *sequence_bounds.start(),
1665                max_sequence: *sequence_bounds.end(),
1666                var_len_bytes,
1667            },
1668            schema: arrow_schema,
1669        }))
1670    }
1671
1672    /// Encodes bulk part to a [EncodedBulkPart], returns the encoded data.
1673    pub fn encode_part(&self, part: &BulkPart) -> Result<Option<EncodedBulkPart>> {
1674        if part.batch.num_rows() == 0 {
1675            return Ok(None);
1676        }
1677
1678        if self.narthex_format {
1679            return self.encode_record_batch_iter(
1680                Box::new(std::iter::once(Ok(part.batch.clone()))),
1681                part.batch.schema(),
1682                part.min_timestamp,
1683                part.max_timestamp,
1684                part.min_sequence..=part.sequence,
1685                &mut BulkPartEncodeMetrics::default(),
1686            );
1687        }
1688        let mut buf = Vec::with_capacity(4096);
1689        let arrow_schema = part.batch.schema();
1690
1691        let file_metadata = {
1692            let props = self.writer_props_for(&part.batch);
1693            let mut row_group_value_bytes = Self::row_group_value_bytes(&props);
1694            let mut writer = ArrowWriter::try_new(&mut buf, arrow_schema.clone(), props)
1695                .context(EncodeMemtableSnafu)?;
1696            writer.write(&part.batch).context(EncodeMemtableSnafu)?;
1697            row_group_value_bytes.update(&part.batch);
1698            for kv in row_group_value_bytes.into_key_values() {
1699                writer.append_key_value_metadata(kv);
1700            }
1701            writer.finish().context(EncodeMemtableSnafu)?
1702        };
1703
1704        let buf = Bytes::from(buf);
1705        let parquet_metadata = Arc::new(file_metadata);
1706
1707        Ok(Some(EncodedBulkPart {
1708            payload: EncodedBulkPayload::Parquet(ParquetBulkPart {
1709                data: buf,
1710                metadata: parquet_metadata,
1711            }),
1712            metadata: BulkPartMeta {
1713                num_rows: part.batch.num_rows(),
1714                max_timestamp: part.max_timestamp,
1715                min_timestamp: part.min_timestamp,
1716                region_metadata: self.metadata.clone(),
1717                num_series: part.estimated_series_count() as u64,
1718                max_sequence: part.sequence,
1719                min_sequence: part.min_sequence,
1720                var_len_bytes: var_len_value_bytes(&part.batch),
1721            },
1722            schema: arrow_schema,
1723        }))
1724    }
1725}
1726
1727/// Per-batch min/max statistics for the first tag column in a `MultiBulkPart`.
1728///
1729/// Since batches are sorted by primary key, we can extract the min/max of the first tag
1730/// from the first/last row's encoded primary key in each batch. These statistics enable
1731/// batch-level pruning using predicates, analogous to row-group pruning in parquet.
1732#[derive(Debug, Clone)]
1733struct BatchStats {
1734    /// Number of batches.
1735    num_batches: usize,
1736    /// Column id of the first tag.
1737    first_tag_id: ColumnId,
1738    /// Min values of the first tag, one element per batch.
1739    min_values: ArrayRef,
1740    /// Max values of the first tag, one element per batch.
1741    max_values: ArrayRef,
1742}
1743
1744impl BatchStats {
1745    /// Computes batch statistics from a slice of record batches.
1746    ///
1747    /// Returns `None` if there is no primary key (no first tag to collect stats for)
1748    /// or if extracting statistics fails.
1749    fn compute(batches: &[RecordBatch], metadata: &RegionMetadata) -> Option<Self> {
1750        // `primary_key.first()` is correct for both dense and sparse encodings.
1751        // For dense, values follow the order of `metadata.primary_key`.
1752        // For sparse, `decode_leftmost` decodes the first value which also
1753        // corresponds to `primary_key.first()`. See `SparsePrimaryKeyCodec` for format details.
1754        let first_tag_id = *metadata.primary_key.first()?;
1755        let first_tag_column = metadata.column_by_id(first_tag_id)?;
1756        let data_type = &first_tag_column.column_schema.data_type;
1757
1758        let converter = build_primary_key_codec_with_fields(
1759            metadata.primary_key_encoding,
1760            [(first_tag_id, SortField::new(data_type.clone()))].into_iter(),
1761        );
1762        let pk_index = primary_key_column_index(batches.first()?.num_columns());
1763
1764        let mut min_builder = data_type.create_mutable_vector(batches.len());
1765        let mut max_builder = data_type.create_mutable_vector(batches.len());
1766
1767        for batch in batches {
1768            match Self::extract_first_tag_bounds(batch, pk_index, &*converter) {
1769                Some((min_val, max_val)) => {
1770                    min_builder.push_value_ref(&min_val.as_value_ref());
1771                    max_builder.push_value_ref(&max_val.as_value_ref());
1772                }
1773                None => {
1774                    min_builder.push_null();
1775                    max_builder.push_null();
1776                }
1777            }
1778        }
1779
1780        Some(Self {
1781            num_batches: batches.len(),
1782            first_tag_id,
1783            min_values: min_builder.to_vector().to_arrow_array(),
1784            max_values: max_builder.to_vector().to_arrow_array(),
1785        })
1786    }
1787
1788    /// Extracts the first tag value from the first and last rows of a batch.
1789    fn extract_first_tag_bounds(
1790        batch: &RecordBatch,
1791        pk_index: usize,
1792        converter: &dyn PrimaryKeyCodec,
1793    ) -> Option<(datatypes::value::Value, datatypes::value::Value)> {
1794        if batch.num_rows() == 0 {
1795            return None;
1796        }
1797
1798        let pk_dict = batch
1799            .column(pk_index)
1800            .as_any()
1801            .downcast_ref::<PrimaryKeyArray>()?;
1802        let pk_values = pk_dict.values().as_any().downcast_ref::<BinaryArray>()?;
1803
1804        let keys = pk_dict.keys();
1805        let min_key = keys.value(0);
1806        let max_key = keys.value(batch.num_rows() - 1);
1807        let min_bytes = pk_values.value(min_key as usize);
1808        let max_bytes = pk_values.value(max_key as usize);
1809
1810        Some((
1811            converter.decode_leftmost(min_bytes).ok()??,
1812            converter.decode_leftmost(max_bytes).ok()??,
1813        ))
1814    }
1815}
1816
1817/// Adapter implementing `PruningStatistics` for `BatchStats`.
1818///
1819/// Used with `Predicate::prune_with_stats()` to skip batches whose first-tag
1820/// min/max range does not match the query predicate.
1821struct BatchPruningStats<'a> {
1822    stats: &'a BatchStats,
1823    metadata: &'a RegionMetadataRef,
1824}
1825
1826impl PruningStatistics for BatchPruningStats<'_> {
1827    fn min_values(&self, column: &Column) -> Option<ArrayRef> {
1828        let col = self.metadata.column_by_name(&column.name)?;
1829        if col.column_id == self.stats.first_tag_id {
1830            Some(self.stats.min_values.clone())
1831        } else {
1832            None
1833        }
1834    }
1835
1836    fn max_values(&self, column: &Column) -> Option<ArrayRef> {
1837        let col = self.metadata.column_by_name(&column.name)?;
1838        if col.column_id == self.stats.first_tag_id {
1839            Some(self.stats.max_values.clone())
1840        } else {
1841            None
1842        }
1843    }
1844
1845    fn num_containers(&self) -> usize {
1846        self.stats.num_batches
1847    }
1848
1849    fn null_counts(&self, _column: &Column) -> Option<ArrayRef> {
1850        None
1851    }
1852
1853    fn row_counts(&self) -> Option<ArrayRef> {
1854        None
1855    }
1856
1857    fn contained(
1858        &self,
1859        _column: &Column,
1860        _values: &std::collections::HashSet<datafusion_common::ScalarValue>,
1861    ) -> Option<BooleanArray> {
1862        None
1863    }
1864}
1865
1866/// Returns true if the predicate references the given column name.
1867fn predicate_references_column(predicate: &table::predicate::Predicate, column_name: &str) -> bool {
1868    let mut columns = HashSet::new();
1869    for expr in predicate.exprs() {
1870        let _ = expr_to_columns(expr, &mut columns);
1871    }
1872    columns.iter().any(|col| col.name == column_name)
1873}
1874
1875/// Returns true if the batch should be pruned (skipped) based on the first-tag min/max
1876/// statistics and the predicate in the context. Returns false if no pruning is possible
1877/// (no primary key, no predicate, or the batch matches the predicate).
1878pub(crate) fn should_prune_bulk_part(
1879    batch: &RecordBatch,
1880    context: &BulkIterContext,
1881    metadata: &RegionMetadata,
1882) -> bool {
1883    let predicate = match &context.predicate {
1884        Some(p) => p,
1885        None => return false,
1886    };
1887    // Check if the predicate references the first tag column to avoid computing
1888    // expensive batch statistics when they won't help with pruning.
1889    let first_tag_id = match metadata.primary_key.first() {
1890        Some(id) => *id,
1891        None => return false,
1892    };
1893    // Safety: `first_tag_id` comes from `metadata.primary_key` so the column always exists.
1894    let first_tag_name = &metadata
1895        .column_by_id(first_tag_id)
1896        .unwrap()
1897        .column_schema
1898        .name;
1899    if !predicate_references_column(predicate, first_tag_name) {
1900        return false;
1901    }
1902    let stats = match BatchStats::compute(std::slice::from_ref(batch), metadata) {
1903        Some(s) => s,
1904        None => return false,
1905    };
1906    let region_meta = context.read_format().metadata();
1907    let pruning_stats = BatchPruningStats {
1908        stats: &stats,
1909        metadata: region_meta,
1910    };
1911    let mask = predicate.prune_with_stats(&pruning_stats, region_meta.schema.arrow_schema());
1912    !mask.first().copied().unwrap_or(true)
1913}
1914
1915/// A collection of ordered RecordBatches representing a bulk part without parquet encoding.
1916///
1917/// Similar to `EncodedBulkPart` but stores raw RecordBatches instead of encoded parquet data.
1918/// The RecordBatches must be ordered by (primary key, timestamp, sequence desc).
1919/// Uses SmallVec to optimize for the common case of few batches while avoiding heap allocation.
1920#[derive(Debug, Clone)]
1921pub struct MultiBulkPart {
1922    /// Ordered record batches. SmallVec optimized for up to 4 batches inline.
1923    batches: SmallVec<[RecordBatch; 4]>,
1924    /// Total rows across all batches.
1925    total_rows: usize,
1926    /// Max timestamp in part.
1927    max_timestamp: i64,
1928    /// Min timestamp in part.
1929    min_timestamp: i64,
1930    /// Lower bound of input sequences, including rows removed by deduplication.
1931    min_sequence: SequenceNumber,
1932    /// Max sequence number in part.
1933    max_sequence: SequenceNumber,
1934    /// Number of series.
1935    series_count: usize,
1936    /// Pre-computed per-batch statistics for the first tag column.
1937    /// `None` if there is no primary key.
1938    batch_stats: Option<BatchStats>,
1939}
1940
1941impl MultiBulkPart {
1942    pub(crate) fn primary_keys(&self) -> Option<crate::memtable::BoxedPrimaryKeyIterator> {
1943        let iterators = self
1944            .batches
1945            .iter()
1946            .map(bulk_primary_keys)
1947            .collect::<Option<Vec<_>>>()?;
1948        Some(Box::new(iterators.into_iter().flatten()))
1949    }
1950
1951    /// Creates a new MultiBulkPart from a single BulkPart.
1952    pub fn from_bulk_part(part: BulkPart, metadata: &RegionMetadata) -> Self {
1953        let num_rows = part.num_rows();
1954        let series_count = part.estimated_series_count();
1955        let batch_stats = BatchStats::compute(std::slice::from_ref(&part.batch), metadata);
1956        let mut batches = SmallVec::new();
1957        batches.push(part.batch);
1958
1959        Self {
1960            batches,
1961            total_rows: num_rows,
1962            max_timestamp: part.max_timestamp,
1963            min_timestamp: part.min_timestamp,
1964            min_sequence: part.min_sequence,
1965            max_sequence: part.sequence,
1966            series_count,
1967            batch_stats,
1968        }
1969    }
1970
1971    /// Creates a new MultiBulkPart from multiple ordered RecordBatches.
1972    ///
1973    /// # Arguments
1974    /// * `batches` - Ordered record batches
1975    /// * `min_timestamp` - Minimum timestamp across all batches
1976    /// * `max_timestamp` - Maximum timestamp across all batches
1977    /// * `min_sequence` - Lower bound of input sequences
1978    /// * `max_sequence` - Maximum sequence number across all batches
1979    /// * `series_count` - Number of series in the batches
1980    /// * `metadata` - Region metadata for computing batch statistics
1981    ///
1982    /// # Panics
1983    /// Panics if batches is empty.
1984    pub fn new(
1985        batches: Vec<RecordBatch>,
1986        min_timestamp: i64,
1987        max_timestamp: i64,
1988        min_sequence: SequenceNumber,
1989        max_sequence: SequenceNumber,
1990        series_count: usize,
1991        metadata: &RegionMetadata,
1992    ) -> Self {
1993        assert!(!batches.is_empty(), "batches must not be empty");
1994
1995        let total_rows = batches.iter().map(|b| b.num_rows()).sum();
1996        let batch_stats = BatchStats::compute(&batches, metadata);
1997
1998        Self {
1999            batches: SmallVec::from_vec(batches),
2000            total_rows,
2001            max_timestamp,
2002            min_timestamp,
2003            min_sequence,
2004            max_sequence,
2005            series_count,
2006            batch_stats,
2007        }
2008    }
2009
2010    /// Returns the total number of rows across all batches.
2011    pub fn num_rows(&self) -> usize {
2012        self.total_rows
2013    }
2014
2015    pub(crate) fn schemas(&self) -> impl Iterator<Item = SchemaRef> + '_ {
2016        self.batches.iter().map(|batch| batch.schema())
2017    }
2018
2019    /// Returns the minimum timestamp.
2020    pub fn min_timestamp(&self) -> i64 {
2021        self.min_timestamp
2022    }
2023
2024    /// Returns the maximum timestamp.
2025    pub fn max_timestamp(&self) -> i64 {
2026        self.max_timestamp
2027    }
2028
2029    /// Returns the lower bound of input sequences.
2030    pub fn min_sequence(&self) -> SequenceNumber {
2031        self.min_sequence
2032    }
2033
2034    /// Returns the maximum sequence number.
2035    pub fn max_sequence(&self) -> SequenceNumber {
2036        self.max_sequence
2037    }
2038
2039    /// Returns the number of series.
2040    pub fn series_count(&self) -> usize {
2041        self.series_count
2042    }
2043
2044    /// Returns the number of record batches in this part.
2045    pub fn num_batches(&self) -> usize {
2046        self.batches.len()
2047    }
2048
2049    /// Returns the estimated memory size of all batches.
2050    pub(crate) fn estimated_size(&self) -> usize {
2051        self.batches.iter().map(record_batch_estimated_size).sum()
2052    }
2053
2054    /// Reads data from this part with the given context and filters.
2055    ///
2056    /// If batch-level statistics are available and a predicate is set, prunes
2057    /// batches whose first-tag min/max range doesn't match the predicate before
2058    /// creating the iterator.
2059    pub(crate) fn read(
2060        &self,
2061        context: BulkIterContextRef,
2062        sequence: Option<SequenceRange>,
2063        mem_scan_metrics: Option<MemScanMetrics>,
2064    ) -> Result<Option<BoxedRecordBatchIterator>> {
2065        if self.batches.is_empty() {
2066            return Ok(None);
2067        }
2068
2069        let batches_to_read = self.prune_batches(&context);
2070
2071        if batches_to_read.is_empty() {
2072            return Ok(None);
2073        }
2074
2075        let iter = crate::memtable::bulk::part_reader::BulkPartBatchIter::new(
2076            batches_to_read,
2077            context,
2078            sequence,
2079            self.series_count,
2080            mem_scan_metrics,
2081        );
2082        Ok(Some(Box::new(iter) as BoxedRecordBatchIterator))
2083    }
2084
2085    /// Prunes batches using the first-tag min/max statistics and the predicate.
2086    /// Returns all batches if no stats or no predicate is available.
2087    fn prune_batches(&self, context: &BulkIterContextRef) -> Vec<RecordBatch> {
2088        if let Some(stats) = &self.batch_stats
2089            && let Some(predicate) = &context.predicate
2090        {
2091            let region_meta = context.read_format().metadata();
2092            let pruning_stats = BatchPruningStats {
2093                stats,
2094                metadata: region_meta,
2095            };
2096            let mask =
2097                predicate.prune_with_stats(&pruning_stats, region_meta.schema.arrow_schema());
2098            self.batches
2099                .iter()
2100                .zip(mask.iter())
2101                .filter_map(
2102                    |(batch, &selected)| {
2103                        if selected { Some(batch.clone()) } else { None }
2104                    },
2105                )
2106                .collect()
2107        } else {
2108            self.batches.iter().cloned().collect()
2109        }
2110    }
2111
2112    /// Converts this `MultiBulkPart` to `MemtableStats`.
2113    pub fn to_memtable_stats(&self, region_metadata: &RegionMetadataRef) -> MemtableStats {
2114        let ts_type = region_metadata.time_index_type();
2115        let min_ts = ts_type.create_timestamp(self.min_timestamp);
2116        let max_ts = ts_type.create_timestamp(self.max_timestamp);
2117
2118        MemtableStats {
2119            estimated_bytes: self.estimated_size(),
2120            decoded_bytes: None,
2121            time_range: Some((min_ts, max_ts)),
2122            num_rows: self.num_rows(),
2123            num_ranges: 1,
2124            max_sequence: self.max_sequence,
2125            min_sequence: self.min_sequence,
2126            series_count: self.series_count,
2127        }
2128    }
2129}
2130
2131/// Reads only the primary-key array of an already materialized bulk batch.
2132pub(crate) fn bulk_primary_keys(
2133    batch: &RecordBatch,
2134) -> Option<crate::memtable::BoxedPrimaryKeyIterator> {
2135    use datatypes::arrow::array::BinaryArray;
2136    let column = batch.column_by_name(store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME)?;
2137    let (values, indices) =
2138        if let Some(dictionary) = column.as_any().downcast_ref::<PrimaryKeyArray>() {
2139            (
2140                dictionary
2141                    .values()
2142                    .as_any()
2143                    .downcast_ref::<BinaryArray>()?
2144                    .clone(),
2145                Some(dictionary.keys().clone()),
2146            )
2147        } else {
2148            (column.as_any().downcast_ref::<BinaryArray>()?.clone(), None)
2149        };
2150    let rows = batch.num_rows();
2151    let mut row = 0;
2152    Some(Box::new(std::iter::from_fn(move || {
2153        if row == rows {
2154            return None;
2155        }
2156        let value = |row| {
2157            values.value(
2158                indices
2159                    .as_ref()
2160                    .map_or(row, |keys| keys.value(row) as usize),
2161            )
2162        };
2163        let bytes = value(row);
2164        row += 1;
2165        while row < rows && value(row) == bytes {
2166            row += 1;
2167        }
2168        Some(bytes::Bytes::copy_from_slice(bytes))
2169    })))
2170}
2171
2172#[cfg(test)]
2173mod tests {
2174    use api::v1::{Row, WriteHint};
2175    use datafusion_common::ScalarValue;
2176    use datatypes::arrow::array::{
2177        BinaryArray, DictionaryArray, Float64Array, TimestampMillisecondArray,
2178    };
2179    use datatypes::arrow::datatypes::UInt32Type;
2180    use datatypes::prelude::{ConcreteDataType, Value};
2181    use mito_codec::row_converter::build_primary_key_codec;
2182    use rand::rngs::StdRng;
2183    use rand::{Rng, SeedableRng};
2184    use store_api::metadata::RegionMetadataBuilder;
2185    use store_api::storage::consts::ReservedColumnId;
2186    use table::predicate::Predicate;
2187
2188    use super::*;
2189    use crate::memtable::bulk::context::BulkIterContext;
2190    use crate::sst::{FlatSchemaOptions, to_flat_sst_arrow_schema};
2191    use crate::test_util::memtable_util::{build_key_values_with_ts_seq_values, metadata_for_test};
2192
2193    struct MutationInput<'a> {
2194        k0: &'a str,
2195        k1: u32,
2196        timestamps: &'a [i64],
2197        v1: &'a [Option<f64>],
2198        sequence: u64,
2199    }
2200
2201    #[test]
2202    fn test_sort_primary_key_record_batch_with_duplicate_dictionary_values() {
2203        // Dictionary keys 1 and 2 both represent "series_a". This can happen after Arrow
2204        // concatenates dictionaries because dictionary deduplication is best-effort.
2205        let primary_key = DictionaryArray::try_new(
2206            UInt32Array::from(vec![0, 1, 0, 2, 2]),
2207            Arc::new(BinaryArray::from_vec(vec![
2208                b"series_b".as_slice(),
2209                b"series_a".as_slice(),
2210                b"series_a".as_slice(),
2211            ])),
2212        )
2213        .unwrap();
2214        let timestamps = TimestampMillisecondArray::from(vec![20, 30, 10, 30, 10]);
2215        let sequences = UInt64Array::from(vec![5, 6, 4, 8, 9]);
2216        let row_ids = UInt32Array::from_iter_values(0..5);
2217        let op_types = UInt8Array::from_value(OpType::Put as u8, 5);
2218        let schema = Arc::new(Schema::new(vec![
2219            Field::new("row_id", ArrowDataType::UInt32, false),
2220            Field::new(
2221                "ts",
2222                ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
2223                false,
2224            ),
2225            Field::new(
2226                PRIMARY_KEY_COLUMN_NAME,
2227                ArrowDataType::Dictionary(
2228                    Box::new(ArrowDataType::UInt32),
2229                    Box::new(ArrowDataType::Binary),
2230                ),
2231                false,
2232            ),
2233            Field::new("__sequence", ArrowDataType::UInt64, false),
2234            Field::new("__op_type", ArrowDataType::UInt8, false),
2235        ]));
2236        let batch = RecordBatch::try_new(
2237            schema,
2238            vec![
2239                Arc::new(row_ids),
2240                Arc::new(timestamps),
2241                Arc::new(primary_key),
2242                Arc::new(sequences),
2243                Arc::new(op_types),
2244            ],
2245        )
2246        .unwrap();
2247
2248        let expected_indices = lexsort_primary_key_indices(&batch).unwrap();
2249        let expected =
2250            datatypes::arrow::compute::take_record_batch(&batch, &expected_indices).unwrap();
2251        let actual = sort_primary_key_record_batch(&batch).unwrap();
2252
2253        let expected_row_ids = expected
2254            .column(0)
2255            .as_any()
2256            .downcast_ref::<UInt32Array>()
2257            .unwrap();
2258        let actual_row_ids = actual
2259            .column(0)
2260            .as_any()
2261            .downcast_ref::<UInt32Array>()
2262            .unwrap();
2263        assert_eq!(expected_row_ids, actual_row_ids);
2264        assert_eq!(actual_row_ids.values(), &[4, 3, 1, 2, 0]);
2265    }
2266
2267    #[test]
2268    fn test_sort_primary_key_record_batch_against_lexsort() {
2269        let mut rng = StdRng::seed_from_u64(0x5eed);
2270        for _ in 0..100 {
2271            let num_rows = rng.random_range(0..128);
2272            let keys = UInt32Array::from_iter_values((0..num_rows).map(|_| rng.random_range(0..8)));
2273            let primary_key = DictionaryArray::try_new(
2274                keys,
2275                Arc::new(BinaryArray::from_vec(vec![
2276                    b"d".as_slice(),
2277                    b"a".as_slice(),
2278                    b"c".as_slice(),
2279                    b"b".as_slice(),
2280                    b"a".as_slice(),
2281                    b"d".as_slice(),
2282                    b"b".as_slice(),
2283                    b"c".as_slice(),
2284                ])),
2285            )
2286            .unwrap();
2287            let timestamps = TimestampMillisecondArray::from_iter_values(
2288                (0..num_rows).map(|_| rng.random_range(-1000..1000)),
2289            );
2290            // Unique sequences ensure that the oracle and fast path have no fully equal sort keys.
2291            let sequences = UInt64Array::from_iter_values(0..num_rows as u64);
2292            let row_ids = UInt32Array::from_iter_values(0..num_rows as u32);
2293            let op_types = UInt8Array::from_value(OpType::Put as u8, num_rows);
2294            let schema = Arc::new(Schema::new(vec![
2295                Field::new("row_id", ArrowDataType::UInt32, false),
2296                Field::new(
2297                    "ts",
2298                    ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
2299                    false,
2300                ),
2301                Field::new(
2302                    PRIMARY_KEY_COLUMN_NAME,
2303                    ArrowDataType::Dictionary(
2304                        Box::new(ArrowDataType::UInt32),
2305                        Box::new(ArrowDataType::Binary),
2306                    ),
2307                    false,
2308                ),
2309                Field::new("__sequence", ArrowDataType::UInt64, false),
2310                Field::new("__op_type", ArrowDataType::UInt8, false),
2311            ]));
2312            let batch = RecordBatch::try_new(
2313                schema,
2314                vec![
2315                    Arc::new(row_ids),
2316                    Arc::new(timestamps),
2317                    Arc::new(primary_key),
2318                    Arc::new(sequences),
2319                    Arc::new(op_types),
2320                ],
2321            )
2322            .unwrap();
2323
2324            let expected_indices = lexsort_primary_key_indices(&batch).unwrap();
2325            let expected =
2326                datatypes::arrow::compute::take_record_batch(&batch, &expected_indices).unwrap();
2327            let actual = sort_primary_key_record_batch(&batch).unwrap();
2328            assert_eq!(expected.column(0), actual.column(0));
2329        }
2330    }
2331
2332    #[test]
2333    fn test_unordered_part_tracks_estimated_bytes() {
2334        let mut part = UnorderedPart::new();
2335        let bulk_part = BulkPart {
2336            batch: RecordBatch::new_empty(Arc::new(arrow::datatypes::Schema::empty())),
2337            max_timestamp: 0,
2338            min_timestamp: 0,
2339            sequence: 0,
2340            min_sequence: 0,
2341            timestamp_index: 0,
2342            raw_data: None,
2343        };
2344        let estimated_size = bulk_part.estimated_size();
2345
2346        part.push(bulk_part);
2347        assert_eq!(estimated_size, part.estimated_bytes());
2348        part.clear();
2349        assert_eq!(0, part.estimated_bytes());
2350        assert!(part.is_empty());
2351    }
2352
2353    #[test]
2354    fn test_unordered_part_should_accept() {
2355        let mut part = UnorderedPart::new();
2356        part.set_threshold(10);
2357        assert!(part.should_accept(9));
2358        assert!(!part.should_accept(10));
2359    }
2360
2361    fn encode(input: &[MutationInput]) -> EncodedBulkPart {
2362        let metadata = metadata_for_test();
2363        let kvs = input
2364            .iter()
2365            .map(|m| {
2366                build_key_values_with_ts_seq_values(
2367                    &metadata,
2368                    m.k0.to_string(),
2369                    m.k1,
2370                    m.timestamps.iter().copied(),
2371                    m.v1.iter().copied(),
2372                    m.sequence,
2373                )
2374            })
2375            .collect::<Vec<_>>();
2376        let schema = to_flat_sst_arrow_schema(&metadata, &FlatSchemaOptions::default());
2377        let primary_key_codec = build_primary_key_codec(&metadata);
2378        let mut converter = BulkPartConverter::new(&metadata, schema, 64, primary_key_codec, true);
2379        for kv in kvs {
2380            converter.append_key_values(&kv).unwrap();
2381        }
2382        let part = converter.convert().unwrap();
2383        let encoder = BulkPartEncoder::new(metadata, 1024).unwrap();
2384        encoder.encode_part(&part).unwrap().unwrap()
2385    }
2386
2387    #[test]
2388    fn test_write_and_read_part_projection() {
2389        let part = encode(&[
2390            MutationInput {
2391                k0: "a",
2392                k1: 0,
2393                timestamps: &[1],
2394                v1: &[Some(0.1)],
2395                sequence: 0,
2396            },
2397            MutationInput {
2398                k0: "b",
2399                k1: 0,
2400                timestamps: &[1],
2401                v1: &[Some(0.0)],
2402                sequence: 0,
2403            },
2404            MutationInput {
2405                k0: "a",
2406                k1: 0,
2407                timestamps: &[2],
2408                v1: &[Some(0.2)],
2409                sequence: 1,
2410            },
2411        ]);
2412
2413        let projection = &[4u32];
2414        let reader = part
2415            .read(
2416                Arc::new(
2417                    BulkIterContext::new(
2418                        part.metadata.region_metadata.clone(),
2419                        Some(projection.as_slice()),
2420                        None,
2421                        false,
2422                        crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
2423                    )
2424                    .unwrap(),
2425                ),
2426                None,
2427                None,
2428            )
2429            .unwrap()
2430            .expect("expect at least one row group");
2431
2432        let mut total_rows_read = 0;
2433        let mut field: Vec<f64> = vec![];
2434        for res in reader {
2435            let batch = res.unwrap();
2436            assert_eq!(5, batch.num_columns());
2437            field.extend_from_slice(
2438                batch
2439                    .column(0)
2440                    .as_any()
2441                    .downcast_ref::<Float64Array>()
2442                    .unwrap()
2443                    .values(),
2444            );
2445            total_rows_read += batch.num_rows();
2446        }
2447        assert_eq!(3, total_rows_read);
2448        assert_eq!(vec![0.1, 0.2, 0.0], field);
2449    }
2450
2451    fn prepare(key_values: Vec<(&str, u32, (i64, i64), u64)>) -> EncodedBulkPart {
2452        let metadata = metadata_for_test();
2453        let kvs = key_values
2454            .into_iter()
2455            .map(|(k0, k1, (start, end), sequence)| {
2456                let ts = start..end;
2457                let v1 = (start..end).map(|_| None);
2458                build_key_values_with_ts_seq_values(&metadata, k0.to_string(), k1, ts, v1, sequence)
2459            })
2460            .collect::<Vec<_>>();
2461        let schema = to_flat_sst_arrow_schema(&metadata, &FlatSchemaOptions::default());
2462        let primary_key_codec = build_primary_key_codec(&metadata);
2463        let mut converter = BulkPartConverter::new(&metadata, schema, 64, primary_key_codec, true);
2464        for kv in kvs {
2465            converter.append_key_values(&kv).unwrap();
2466        }
2467        let part = converter.convert().unwrap();
2468        let encoder = BulkPartEncoder::new(metadata, 1024).unwrap();
2469        encoder.encode_part(&part).unwrap().unwrap()
2470    }
2471
2472    fn check_prune_row_group(
2473        part: &EncodedBulkPart,
2474        predicate: Option<Predicate>,
2475        expected_rows: usize,
2476    ) {
2477        let context = Arc::new(
2478            BulkIterContext::new(
2479                part.metadata.region_metadata.clone(),
2480                None,
2481                predicate,
2482                false,
2483                crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
2484            )
2485            .unwrap(),
2486        );
2487        let reader = part
2488            .read(context, None, None)
2489            .unwrap()
2490            .expect("expect at least one row group");
2491        let mut total_rows_read = 0;
2492        for res in reader {
2493            let batch = res.unwrap();
2494            total_rows_read += batch.num_rows();
2495        }
2496        // Should only read row group 1.
2497        assert_eq!(expected_rows, total_rows_read);
2498    }
2499
2500    #[test]
2501    fn test_prune_row_groups() {
2502        let part = prepare(vec![
2503            ("a", 0, (0, 40), 1),
2504            ("a", 1, (0, 60), 1),
2505            ("b", 0, (0, 100), 2),
2506            ("b", 1, (100, 180), 3),
2507            ("b", 1, (180, 210), 4),
2508        ]);
2509
2510        let context = Arc::new(
2511            BulkIterContext::new(
2512                part.metadata.region_metadata.clone(),
2513                None,
2514                Some(Predicate::new(vec![datafusion_expr::col("ts").eq(
2515                    datafusion_expr::lit(ScalarValue::TimestampMillisecond(Some(300), None)),
2516                )])),
2517                false,
2518                crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
2519            )
2520            .unwrap(),
2521        );
2522        assert!(part.read(context, None, None).unwrap().is_none());
2523
2524        check_prune_row_group(&part, None, 310);
2525
2526        check_prune_row_group(
2527            &part,
2528            Some(Predicate::new(vec![
2529                datafusion_expr::col("k0").eq(datafusion_expr::lit("a")),
2530                datafusion_expr::col("k1").eq(datafusion_expr::lit(0u32)),
2531            ])),
2532            40,
2533        );
2534
2535        check_prune_row_group(
2536            &part,
2537            Some(Predicate::new(vec![
2538                datafusion_expr::col("k0").eq(datafusion_expr::lit("a")),
2539                datafusion_expr::col("k1").eq(datafusion_expr::lit(1u32)),
2540            ])),
2541            60,
2542        );
2543
2544        check_prune_row_group(
2545            &part,
2546            Some(Predicate::new(vec![
2547                datafusion_expr::col("k0").eq(datafusion_expr::lit("a")),
2548            ])),
2549            100,
2550        );
2551
2552        check_prune_row_group(
2553            &part,
2554            Some(Predicate::new(vec![
2555                datafusion_expr::col("k0").eq(datafusion_expr::lit("b")),
2556                datafusion_expr::col("k1").eq(datafusion_expr::lit(0u32)),
2557            ])),
2558            100,
2559        );
2560
2561        // Predicates over field column can do precise filtering.
2562        check_prune_row_group(
2563            &part,
2564            Some(Predicate::new(vec![
2565                datafusion_expr::col("v0").eq(datafusion_expr::lit(150i64)),
2566            ])),
2567            1,
2568        );
2569    }
2570
2571    #[test]
2572    fn test_bulk_part_converter_append_and_convert() {
2573        let metadata = metadata_for_test();
2574        let capacity = 100;
2575        let primary_key_codec = build_primary_key_codec(&metadata);
2576        let schema = to_flat_sst_arrow_schema(
2577            &metadata,
2578            &FlatSchemaOptions::from_encoding(metadata.primary_key_encoding),
2579        );
2580
2581        let mut converter =
2582            BulkPartConverter::new(&metadata, schema, capacity, primary_key_codec, true);
2583
2584        let key_values1 = build_key_values_with_ts_seq_values(
2585            &metadata,
2586            "key1".to_string(),
2587            1u32,
2588            vec![1000, 2000].into_iter(),
2589            vec![Some(1.0), Some(2.0)].into_iter(),
2590            1,
2591        );
2592
2593        let key_values2 = build_key_values_with_ts_seq_values(
2594            &metadata,
2595            "key2".to_string(),
2596            2u32,
2597            vec![1500].into_iter(),
2598            vec![Some(3.0)].into_iter(),
2599            2,
2600        );
2601
2602        converter.append_key_values(&key_values1).unwrap();
2603        converter.append_key_values(&key_values2).unwrap();
2604
2605        let bulk_part = converter.convert().unwrap();
2606
2607        assert_eq!(bulk_part.num_rows(), 3);
2608        assert_eq!(bulk_part.min_timestamp, 1000);
2609        assert_eq!(bulk_part.max_timestamp, 2000);
2610        assert_eq!(bulk_part.sequence, 2);
2611        assert_eq!(bulk_part.timestamp_index, bulk_part.batch.num_columns() - 4);
2612
2613        // Validate primary key columns are stored
2614        // Schema should include primary key columns k0 and k1 at the beginning
2615        let schema = bulk_part.batch.schema();
2616        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
2617        assert_eq!(
2618            field_names,
2619            vec![
2620                "k0",
2621                "k1",
2622                "v0",
2623                "v1",
2624                "ts",
2625                "__primary_key",
2626                "__sequence",
2627                "__op_type"
2628            ]
2629        );
2630    }
2631
2632    #[test]
2633    fn test_bulk_part_converter_sorting() {
2634        let metadata = metadata_for_test();
2635        let capacity = 100;
2636        let primary_key_codec = build_primary_key_codec(&metadata);
2637        let schema = to_flat_sst_arrow_schema(
2638            &metadata,
2639            &FlatSchemaOptions::from_encoding(metadata.primary_key_encoding),
2640        );
2641
2642        let mut converter =
2643            BulkPartConverter::new(&metadata, schema, capacity, primary_key_codec, true);
2644
2645        let key_values1 = build_key_values_with_ts_seq_values(
2646            &metadata,
2647            "z_key".to_string(),
2648            3u32,
2649            vec![3000].into_iter(),
2650            vec![Some(3.0)].into_iter(),
2651            3,
2652        );
2653
2654        let key_values2 = build_key_values_with_ts_seq_values(
2655            &metadata,
2656            "a_key".to_string(),
2657            1u32,
2658            vec![1000].into_iter(),
2659            vec![Some(1.0)].into_iter(),
2660            1,
2661        );
2662
2663        let key_values3 = build_key_values_with_ts_seq_values(
2664            &metadata,
2665            "m_key".to_string(),
2666            2u32,
2667            vec![2000].into_iter(),
2668            vec![Some(2.0)].into_iter(),
2669            2,
2670        );
2671
2672        converter.append_key_values(&key_values1).unwrap();
2673        converter.append_key_values(&key_values2).unwrap();
2674        converter.append_key_values(&key_values3).unwrap();
2675
2676        let bulk_part = converter.convert().unwrap();
2677
2678        assert_eq!(bulk_part.num_rows(), 3);
2679
2680        let ts_column = bulk_part.batch.column(bulk_part.timestamp_index);
2681        let seq_column = bulk_part.batch.column(bulk_part.batch.num_columns() - 2);
2682
2683        let ts_array = ts_column
2684            .as_any()
2685            .downcast_ref::<TimestampMillisecondArray>()
2686            .unwrap();
2687        let seq_array = seq_column.as_any().downcast_ref::<UInt64Array>().unwrap();
2688
2689        assert_eq!(ts_array.values(), &[1000, 2000, 3000]);
2690        assert_eq!(seq_array.values(), &[1, 2, 3]);
2691
2692        // Validate primary key columns are stored
2693        let schema = bulk_part.batch.schema();
2694        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
2695        assert_eq!(
2696            field_names,
2697            vec![
2698                "k0",
2699                "k1",
2700                "v0",
2701                "v1",
2702                "ts",
2703                "__primary_key",
2704                "__sequence",
2705                "__op_type"
2706            ]
2707        );
2708    }
2709
2710    #[test]
2711    fn test_bulk_part_converter_empty() {
2712        let metadata = metadata_for_test();
2713        let capacity = 10;
2714        let primary_key_codec = build_primary_key_codec(&metadata);
2715        let schema = to_flat_sst_arrow_schema(
2716            &metadata,
2717            &FlatSchemaOptions::from_encoding(metadata.primary_key_encoding),
2718        );
2719
2720        let converter =
2721            BulkPartConverter::new(&metadata, schema, capacity, primary_key_codec, true);
2722
2723        let bulk_part = converter.convert().unwrap();
2724
2725        assert_eq!(bulk_part.num_rows(), 0);
2726        assert_eq!(bulk_part.min_timestamp, i64::MAX);
2727        assert_eq!(bulk_part.max_timestamp, i64::MIN);
2728        assert_eq!(bulk_part.sequence, SequenceNumber::MIN);
2729
2730        // Validate primary key columns are present in schema even for empty batch
2731        let schema = bulk_part.batch.schema();
2732        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
2733        assert_eq!(
2734            field_names,
2735            vec![
2736                "k0",
2737                "k1",
2738                "v0",
2739                "v1",
2740                "ts",
2741                "__primary_key",
2742                "__sequence",
2743                "__op_type"
2744            ]
2745        );
2746    }
2747
2748    #[test]
2749    fn test_bulk_part_converter_without_primary_key_columns() {
2750        let metadata = metadata_for_test();
2751        let primary_key_codec = build_primary_key_codec(&metadata);
2752        let schema = to_flat_sst_arrow_schema(
2753            &metadata,
2754            &FlatSchemaOptions {
2755                raw_pk_columns: false,
2756                string_pk_use_dict: true,
2757                ..Default::default()
2758            },
2759        );
2760
2761        let capacity = 100;
2762        let mut converter =
2763            BulkPartConverter::new(&metadata, schema, capacity, primary_key_codec, false);
2764
2765        let key_values1 = build_key_values_with_ts_seq_values(
2766            &metadata,
2767            "key1".to_string(),
2768            1u32,
2769            vec![1000, 2000].into_iter(),
2770            vec![Some(1.0), Some(2.0)].into_iter(),
2771            1,
2772        );
2773
2774        let key_values2 = build_key_values_with_ts_seq_values(
2775            &metadata,
2776            "key2".to_string(),
2777            2u32,
2778            vec![1500].into_iter(),
2779            vec![Some(3.0)].into_iter(),
2780            2,
2781        );
2782
2783        converter.append_key_values(&key_values1).unwrap();
2784        converter.append_key_values(&key_values2).unwrap();
2785
2786        let bulk_part = converter.convert().unwrap();
2787
2788        assert_eq!(bulk_part.num_rows(), 3);
2789        assert_eq!(bulk_part.min_timestamp, 1000);
2790        assert_eq!(bulk_part.max_timestamp, 2000);
2791        assert_eq!(bulk_part.sequence, 2);
2792        assert_eq!(bulk_part.timestamp_index, bulk_part.batch.num_columns() - 4);
2793
2794        // Validate primary key columns are NOT stored individually
2795        let schema = bulk_part.batch.schema();
2796        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
2797        assert_eq!(
2798            field_names,
2799            vec!["v0", "v1", "ts", "__primary_key", "__sequence", "__op_type"]
2800        );
2801    }
2802
2803    #[allow(clippy::too_many_arguments)]
2804    fn build_key_values_with_sparse_encoding(
2805        metadata: &RegionMetadataRef,
2806        table_id: u32,
2807        tsid: u64,
2808        k0: String,
2809        k1: String,
2810        timestamps: impl Iterator<Item = i64>,
2811        values: impl Iterator<Item = Option<f64>>,
2812        sequence: SequenceNumber,
2813    ) -> KeyValues {
2814        // Encode the primary key (__table_id, __tsid, k0, k1) into binary format using the sparse codec
2815        let pk_values = vec![
2816            (ReservedColumnId::table_id(), Value::UInt32(table_id)),
2817            (ReservedColumnId::tsid(), Value::UInt64(tsid)),
2818            (0, Value::String(k0.clone().into())),
2819            (1, Value::String(k1.clone().into())),
2820        ];
2821        let mut encoded_key = Vec::new();
2822        mito_codec::row_converter::SparsePrimaryKeyCodec::schemaless()
2823            .encode_values(&pk_values, &mut encoded_key)
2824            .unwrap();
2825        assert!(!encoded_key.is_empty());
2826
2827        // Create schema for sparse encoding: __primary_key, ts, v0, v1
2828        let column_schema = vec![
2829            api::v1::ColumnSchema {
2830                column_name: PRIMARY_KEY_COLUMN_NAME.to_string(),
2831                datatype: api::helper::ColumnDataTypeWrapper::try_from(
2832                    ConcreteDataType::binary_datatype(),
2833                )
2834                .unwrap()
2835                .datatype() as i32,
2836                semantic_type: api::v1::SemanticType::Tag as i32,
2837                ..Default::default()
2838            },
2839            api::v1::ColumnSchema {
2840                column_name: "ts".to_string(),
2841                datatype: api::helper::ColumnDataTypeWrapper::try_from(
2842                    ConcreteDataType::timestamp_millisecond_datatype(),
2843                )
2844                .unwrap()
2845                .datatype() as i32,
2846                semantic_type: api::v1::SemanticType::Timestamp as i32,
2847                ..Default::default()
2848            },
2849            api::v1::ColumnSchema {
2850                column_name: "v0".to_string(),
2851                datatype: api::helper::ColumnDataTypeWrapper::try_from(
2852                    ConcreteDataType::int64_datatype(),
2853                )
2854                .unwrap()
2855                .datatype() as i32,
2856                semantic_type: api::v1::SemanticType::Field as i32,
2857                ..Default::default()
2858            },
2859            api::v1::ColumnSchema {
2860                column_name: "v1".to_string(),
2861                datatype: api::helper::ColumnDataTypeWrapper::try_from(
2862                    ConcreteDataType::float64_datatype(),
2863                )
2864                .unwrap()
2865                .datatype() as i32,
2866                semantic_type: api::v1::SemanticType::Field as i32,
2867                ..Default::default()
2868            },
2869        ];
2870
2871        let rows = timestamps
2872            .zip(values)
2873            .map(|(ts, v)| Row {
2874                values: vec![
2875                    api::v1::Value {
2876                        value_data: Some(api::v1::value::ValueData::BinaryValue(
2877                            encoded_key.clone(),
2878                        )),
2879                    },
2880                    api::v1::Value {
2881                        value_data: Some(api::v1::value::ValueData::TimestampMillisecondValue(ts)),
2882                    },
2883                    api::v1::Value {
2884                        value_data: Some(api::v1::value::ValueData::I64Value(ts)),
2885                    },
2886                    api::v1::Value {
2887                        value_data: v.map(api::v1::value::ValueData::F64Value),
2888                    },
2889                ],
2890            })
2891            .collect();
2892
2893        let mutation = api::v1::Mutation {
2894            op_type: 1,
2895            sequence,
2896            rows: Some(api::v1::Rows {
2897                schema: column_schema,
2898                rows,
2899            }),
2900            write_hint: Some(WriteHint {
2901                primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse.into(),
2902            }),
2903        };
2904        KeyValues::new(metadata.as_ref(), mutation).unwrap()
2905    }
2906
2907    fn sparse_metadata_for_test() -> RegionMetadataRef {
2908        let mut metadata = metadata_for_test().as_ref().clone();
2909        metadata.column_metadatas[1].column_schema.data_type = ConcreteDataType::string_datatype();
2910        let mut builder = RegionMetadataBuilder::from_existing(metadata);
2911        let reserved = crate::test_util::sst_util::sst_region_metadata_with_encoding(
2912            PrimaryKeyEncoding::Sparse,
2913        );
2914        for column in reserved.column_metadatas.into_iter().take(2) {
2915            builder.push_column_metadata(column);
2916        }
2917        builder
2918            .primary_key(vec![
2919                ReservedColumnId::table_id(),
2920                ReservedColumnId::tsid(),
2921                0,
2922                1,
2923            ])
2924            .primary_key_encoding(PrimaryKeyEncoding::Sparse);
2925        Arc::new(builder.build().unwrap())
2926    }
2927
2928    #[test]
2929    fn test_bulk_part_converter_sparse_primary_key_encoding() {
2930        let metadata = sparse_metadata_for_test();
2931
2932        let primary_key_codec = build_primary_key_codec(&metadata);
2933        let schema = to_flat_sst_arrow_schema(
2934            &metadata,
2935            &FlatSchemaOptions::from_encoding(metadata.primary_key_encoding),
2936        );
2937
2938        assert_eq!(metadata.primary_key_encoding, PrimaryKeyEncoding::Sparse);
2939        assert_eq!(primary_key_codec.encoding(), PrimaryKeyEncoding::Sparse);
2940
2941        let capacity = 100;
2942        let mut converter = BulkPartConverter::new(
2943            &metadata,
2944            schema.clone(),
2945            capacity,
2946            primary_key_codec.clone(),
2947            true,
2948        );
2949
2950        let key_values1 = build_key_values_with_sparse_encoding(
2951            &metadata,
2952            2048u32, // table_id
2953            100u64,  // tsid
2954            "key11".to_string(),
2955            "key21".to_string(),
2956            vec![1000, 2000].into_iter(),
2957            vec![Some(1.0), Some(2.0)].into_iter(),
2958            1,
2959        );
2960
2961        let mut key_values2 = build_key_values_with_sparse_encoding(
2962            &metadata,
2963            4096u32, // table_id
2964            200u64,  // tsid
2965            "key12".to_string(),
2966            "key22".to_string(),
2967            vec![1500].into_iter(),
2968            vec![Some(3.0)].into_iter(),
2969            2,
2970        );
2971        key_values2.mutation.op_type = OpType::Delete as i32;
2972
2973        let mut raw_mutation = key_values1.mutation.clone();
2974        raw_mutation.write_hint = None;
2975        let rows = raw_mutation.rows.as_mut().unwrap();
2976        rows.schema.splice(
2977            0..1,
2978            ["k0", "k1"].map(|name| api::v1::ColumnSchema {
2979                column_name: name.to_string(),
2980                datatype: api::v1::ColumnDataType::String as i32,
2981                semantic_type: SemanticType::Tag as i32,
2982                ..Default::default()
2983            }),
2984        );
2985        for row in &mut rows.rows {
2986            row.values.splice(
2987                0..1,
2988                ["raw🦀", ""]
2989                    .map(|value| api::v1::value::ValueData::StringValue(value.to_string()).into()),
2990            );
2991        }
2992        rows.schema.extend(
2993            [
2994                ("__table_id", api::v1::ColumnDataType::Uint32),
2995                ("__tsid", api::v1::ColumnDataType::Uint64),
2996            ]
2997            .map(|(name, datatype)| api::v1::ColumnSchema {
2998                column_name: name.into(),
2999                datatype: datatype as i32,
3000                semantic_type: SemanticType::Tag as i32,
3001                ..Default::default()
3002            }),
3003        );
3004        for row in &mut rows.rows {
3005            row.values.extend([
3006                api::v1::value::ValueData::U32Value(2048).into(),
3007                api::v1::value::ValueData::U64Value(100).into(),
3008            ]);
3009        }
3010        let raw = KeyValues::new(&metadata, raw_mutation).unwrap();
3011        let mut raw_converter = BulkPartConverter::new(
3012            &metadata,
3013            schema.clone(),
3014            capacity,
3015            primary_key_codec.clone(),
3016            true,
3017        );
3018        raw_converter.append_key_values(&raw).unwrap();
3019        let raw_part = raw_converter.convert().unwrap();
3020        assert_eq!(2, raw_part.num_rows());
3021        let keys = arrow::compute::cast(
3022            raw_part
3023                .batch
3024                .column_by_name(PRIMARY_KEY_COLUMN_NAME)
3025                .unwrap(),
3026            &ArrowDataType::Binary,
3027        )
3028        .unwrap();
3029        let keys = keys.as_any().downcast_ref::<BinaryArray>().unwrap();
3030        for key in keys.iter().flatten() {
3031            let decoded = primary_key_codec.decode(key).unwrap().into_sparse();
3032            assert_eq!(
3033                Some(&Value::UInt32(2048)),
3034                decoded.get(&ReservedColumnId::table_id())
3035            );
3036            assert_eq!(
3037                Some(&Value::UInt64(100)),
3038                decoded.get(&ReservedColumnId::tsid())
3039            );
3040            assert_eq!(Some(&Value::from("raw🦀")), decoded.get(&0));
3041            assert_eq!(Some(&Value::from("")), decoded.get(&1));
3042        }
3043
3044        for op_type in [OpType::Put, OpType::Delete] {
3045            let mut mutation = key_values1.mutation.clone();
3046            mutation.op_type = op_type as i32;
3047            mutation.rows.as_mut().unwrap().rows[1].values[0].value_data = Some(
3048                api::v1::value::ValueData::BinaryValue(b"truncated".to_vec()),
3049            );
3050            let invalid = KeyValues::new(&metadata, mutation).unwrap();
3051            // Raw rows before or after encoded input must not disable its validation.
3052            for batches in [vec![&invalid], vec![&raw, &invalid], vec![&invalid, &raw]] {
3053                let mut invalid_converter = BulkPartConverter::new(
3054                    &metadata,
3055                    schema.clone(),
3056                    capacity,
3057                    primary_key_codec.clone(),
3058                    true,
3059                );
3060                for batch in batches {
3061                    invalid_converter.append_key_values(batch).unwrap();
3062                }
3063                assert!(invalid_converter.convert().is_err());
3064            }
3065        }
3066
3067        converter.append_key_values(&key_values1).unwrap();
3068        converter.append_key_values(&key_values2).unwrap();
3069
3070        let bulk_part = converter.convert().unwrap();
3071
3072        assert_eq!(bulk_part.num_rows(), 3);
3073        assert_eq!(bulk_part.min_timestamp, 1000);
3074        assert_eq!(bulk_part.max_timestamp, 2000);
3075        assert_eq!(bulk_part.sequence, 2);
3076        assert_eq!(bulk_part.timestamp_index, bulk_part.batch.num_columns() - 4);
3077        assert_eq!(
3078            bulk_part
3079                .batch
3080                .column_by_name("__sequence")
3081                .unwrap()
3082                .as_ref(),
3083            &UInt64Array::from(vec![1, 2, 2]) as &dyn Array,
3084        );
3085        assert_eq!(
3086            bulk_part
3087                .batch
3088                .column_by_name("__op_type")
3089                .unwrap()
3090                .as_ref(),
3091            &UInt8Array::from(vec![
3092                OpType::Put as u8,
3093                OpType::Put as u8,
3094                OpType::Delete as u8
3095            ]) as &dyn Array,
3096        );
3097
3098        // For sparse encoding, primary key columns should NOT be stored individually
3099        // even when store_primary_key_columns is true, because sparse encoding
3100        // stores the encoded primary key in the __primary_key column
3101        let schema = bulk_part.batch.schema();
3102        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
3103        assert_eq!(
3104            field_names,
3105            vec!["v0", "v1", "ts", "__primary_key", "__sequence", "__op_type"]
3106        );
3107
3108        // Verify the __primary_key column contains encoded sparse keys
3109        let primary_key_column = bulk_part.batch.column_by_name("__primary_key").unwrap();
3110        let dict_array = primary_key_column
3111            .as_any()
3112            .downcast_ref::<DictionaryArray<UInt32Type>>()
3113            .unwrap();
3114
3115        // Should have non-zero entries indicating encoded primary keys
3116        assert!(!dict_array.is_empty());
3117        assert_eq!(dict_array.len(), 3); // 3 rows total
3118
3119        // Verify values are properly encoded binary data (not empty)
3120        let values = dict_array
3121            .values()
3122            .as_any()
3123            .downcast_ref::<BinaryArray>()
3124            .unwrap();
3125        for i in 0..values.len() {
3126            assert!(
3127                !values.value(i).is_empty(),
3128                "Encoded primary key should not be empty"
3129            );
3130        }
3131    }
3132
3133    #[test]
3134    fn test_convert_bulk_part_empty() {
3135        let metadata = metadata_for_test();
3136        let schema = to_flat_sst_arrow_schema(
3137            &metadata,
3138            &FlatSchemaOptions::from_encoding(metadata.primary_key_encoding),
3139        );
3140        let primary_key_codec = build_primary_key_codec(&metadata);
3141
3142        // Create empty batch
3143        let empty_batch = RecordBatch::new_empty(schema.clone());
3144        let empty_part = BulkPart {
3145            batch: empty_batch,
3146            max_timestamp: 0,
3147            min_timestamp: 0,
3148            sequence: 0,
3149            min_sequence: 0,
3150            timestamp_index: 0,
3151            raw_data: None,
3152        };
3153
3154        let result =
3155            convert_bulk_part(empty_part, &metadata, primary_key_codec, schema, true).unwrap();
3156        assert!(result.is_none());
3157    }
3158
3159    #[test]
3160    fn test_convert_bulk_part_dense_with_pk_columns() {
3161        let metadata = metadata_for_test();
3162        let primary_key_codec = build_primary_key_codec(&metadata);
3163
3164        let k0_array = Arc::new(arrow::array::StringArray::from(vec![
3165            "key1", "key2", "key1",
3166        ]));
3167        let k1_array = Arc::new(arrow::array::UInt32Array::from(vec![1, 2, 1]));
3168        let v0_array = Arc::new(arrow::array::Int64Array::from(vec![100, 200, 300]));
3169        let v1_array = Arc::new(arrow::array::Float64Array::from(vec![1.0, 2.0, 3.0]));
3170        let ts_array = Arc::new(TimestampMillisecondArray::from(vec![1000, 2000, 1500]));
3171
3172        let input_schema = Arc::new(Schema::new(vec![
3173            Field::new("k0", ArrowDataType::Utf8, false),
3174            Field::new("k1", ArrowDataType::UInt32, false),
3175            Field::new("v0", ArrowDataType::Int64, true),
3176            Field::new("v1", ArrowDataType::Float64, true),
3177            Field::new(
3178                "ts",
3179                ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
3180                false,
3181            ),
3182        ]));
3183
3184        let input_batch = RecordBatch::try_new(
3185            input_schema,
3186            vec![k0_array, k1_array, v0_array, v1_array, ts_array],
3187        )
3188        .unwrap();
3189
3190        let part = BulkPart {
3191            batch: input_batch,
3192            max_timestamp: 2000,
3193            min_timestamp: 1000,
3194            sequence: 5,
3195            min_sequence: 5,
3196            timestamp_index: 4,
3197            raw_data: None,
3198        };
3199
3200        let output_schema = to_flat_sst_arrow_schema(
3201            &metadata,
3202            &FlatSchemaOptions::from_encoding(metadata.primary_key_encoding),
3203        );
3204
3205        let result = convert_bulk_part(
3206            part,
3207            &metadata,
3208            primary_key_codec,
3209            output_schema,
3210            true, // store primary key columns
3211        )
3212        .unwrap();
3213
3214        let converted = result.unwrap();
3215
3216        assert_eq!(converted.num_rows(), 3);
3217        assert_eq!(converted.max_timestamp, 2000);
3218        assert_eq!(converted.min_timestamp, 1000);
3219        assert_eq!(converted.sequence, 5);
3220        assert_eq!(converted.min_sequence, 5);
3221
3222        let schema = converted.batch.schema();
3223        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
3224        assert_eq!(
3225            field_names,
3226            vec![
3227                "k0",
3228                "k1",
3229                "v0",
3230                "v1",
3231                "ts",
3232                "__primary_key",
3233                "__sequence",
3234                "__op_type"
3235            ]
3236        );
3237
3238        let k0_col = converted.batch.column_by_name("k0").unwrap();
3239        assert!(matches!(
3240            k0_col.data_type(),
3241            ArrowDataType::Dictionary(_, _)
3242        ));
3243
3244        let pk_col = converted.batch.column_by_name("__primary_key").unwrap();
3245        let dict_array = pk_col
3246            .as_any()
3247            .downcast_ref::<DictionaryArray<UInt32Type>>()
3248            .unwrap();
3249        let keys = dict_array.keys();
3250
3251        assert_eq!(keys.len(), 3);
3252    }
3253
3254    #[test]
3255    fn test_convert_bulk_part_dense_without_pk_columns() {
3256        let metadata = metadata_for_test();
3257        let primary_key_codec = build_primary_key_codec(&metadata);
3258
3259        // Create input batch with primary key columns (k0, k1)
3260        let k0_array = Arc::new(arrow::array::StringArray::from(vec!["key1", "key2"]));
3261        let k1_array = Arc::new(arrow::array::UInt32Array::from(vec![1, 2]));
3262        let v0_array = Arc::new(arrow::array::Int64Array::from(vec![100, 200]));
3263        let v1_array = Arc::new(arrow::array::Float64Array::from(vec![1.0, 2.0]));
3264        let ts_array = Arc::new(TimestampMillisecondArray::from(vec![1000, 2000]));
3265
3266        let input_schema = Arc::new(Schema::new(vec![
3267            Field::new("k0", ArrowDataType::Utf8, false),
3268            Field::new("k1", ArrowDataType::UInt32, false),
3269            Field::new("v0", ArrowDataType::Int64, true),
3270            Field::new("v1", ArrowDataType::Float64, true),
3271            Field::new(
3272                "ts",
3273                ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
3274                false,
3275            ),
3276        ]));
3277
3278        let input_batch = RecordBatch::try_new(
3279            input_schema,
3280            vec![k0_array, k1_array, v0_array, v1_array, ts_array],
3281        )
3282        .unwrap();
3283
3284        let part = BulkPart {
3285            batch: input_batch,
3286            max_timestamp: 2000,
3287            min_timestamp: 1000,
3288            sequence: 3,
3289            min_sequence: 3,
3290            timestamp_index: 4,
3291            raw_data: None,
3292        };
3293
3294        let output_schema = to_flat_sst_arrow_schema(
3295            &metadata,
3296            &FlatSchemaOptions {
3297                raw_pk_columns: false,
3298                string_pk_use_dict: true,
3299                ..Default::default()
3300            },
3301        );
3302
3303        let result = convert_bulk_part(
3304            part,
3305            &metadata,
3306            primary_key_codec,
3307            output_schema,
3308            false, // don't store primary key columns
3309        )
3310        .unwrap();
3311
3312        let converted = result.unwrap();
3313
3314        assert_eq!(converted.num_rows(), 2);
3315        assert_eq!(converted.max_timestamp, 2000);
3316        assert_eq!(converted.min_timestamp, 1000);
3317        assert_eq!(converted.sequence, 3);
3318
3319        // Verify schema does NOT include individual primary key columns
3320        let schema = converted.batch.schema();
3321        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
3322        assert_eq!(
3323            field_names,
3324            vec!["v0", "v1", "ts", "__primary_key", "__sequence", "__op_type"]
3325        );
3326
3327        // Verify __primary_key column is present and is a dictionary
3328        let pk_col = converted.batch.column_by_name("__primary_key").unwrap();
3329        assert!(matches!(
3330            pk_col.data_type(),
3331            ArrowDataType::Dictionary(_, _)
3332        ));
3333    }
3334
3335    #[test]
3336    fn test_convert_bulk_part_sparse_encoding() {
3337        let metadata = sparse_metadata_for_test();
3338
3339        let primary_key_codec = build_primary_key_codec(&metadata);
3340
3341        // Create input batch with __primary_key column (sparse encoding)
3342        let keys = (1..=2)
3343            .map(|tsid| {
3344                let mut key = Vec::new();
3345                mito_codec::row_converter::SparsePrimaryKeyCodec::schemaless()
3346                    .encode_internal(123, tsid, &mut key)
3347                    .unwrap();
3348                key
3349            })
3350            .collect::<Vec<_>>();
3351        let pk_array = Arc::new(BinaryArray::from_iter_values(&keys));
3352        let v0_array = Arc::new(arrow::array::Int64Array::from(vec![100, 200]));
3353        let v1_array = Arc::new(arrow::array::Float64Array::from(vec![1.0, 2.0]));
3354        let ts_array = Arc::new(TimestampMillisecondArray::from(vec![1000, 2000]));
3355
3356        let input_schema = Arc::new(Schema::new(vec![
3357            Field::new("__primary_key", ArrowDataType::Binary, false),
3358            Field::new("v0", ArrowDataType::Int64, true),
3359            Field::new("v1", ArrowDataType::Float64, true),
3360            Field::new(
3361                "ts",
3362                ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
3363                false,
3364            ),
3365            Field::new("__table_id", ArrowDataType::UInt32, false),
3366        ]));
3367
3368        let input_batch = RecordBatch::try_new(
3369            input_schema,
3370            vec![
3371                pk_array,
3372                v0_array,
3373                v1_array,
3374                ts_array,
3375                Arc::new(UInt32Array::from(vec![123, 123])),
3376            ],
3377        )
3378        .unwrap();
3379
3380        // Partition expressions may need a materialized table ID alongside the key.
3381        // Sparse conversion must keep using the encoded key and omit companion tags.
3382        assert!(!crate::request::check_bulk_insert_batch(&metadata, &input_batch).unwrap());
3383
3384        let part = BulkPart {
3385            batch: input_batch,
3386            max_timestamp: 2000,
3387            min_timestamp: 1000,
3388            sequence: 7,
3389            min_sequence: 7,
3390            timestamp_index: 3,
3391            raw_data: None,
3392        };
3393
3394        let output_schema = to_flat_sst_arrow_schema(
3395            &metadata,
3396            &FlatSchemaOptions::from_encoding(metadata.primary_key_encoding),
3397        );
3398
3399        let dictionary_values = Arc::new(BinaryArray::from(vec![
3400            Some(keys[0].as_slice()),
3401            Some(keys[1].as_slice()),
3402            Some(b"truncated".as_slice()),
3403            None,
3404            Some(keys[0].as_slice()),
3405        ]));
3406        let with_keys = |keys: ArrayRef| {
3407            let mut input = part.clone();
3408            let mut fields = input.batch.schema().fields().to_vec();
3409            fields[0] = Arc::new(Field::new(
3410                PRIMARY_KEY_COLUMN_NAME,
3411                keys.data_type().clone(),
3412                true,
3413            ));
3414            let mut columns = input.batch.columns().to_vec();
3415            columns[0] = keys;
3416            input.batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap();
3417            input
3418        };
3419        // Slicing retains malformed/null dictionary values outside the selected rows.
3420        let sliced = DictionaryArray::try_new(
3421            UInt32Array::from(vec![2, 0, 1, 3]),
3422            dictionary_values.clone(),
3423        )
3424        .unwrap()
3425        .slice(1, 2);
3426        for key_type in [
3427            ArrowDataType::Int8,
3428            ArrowDataType::Int16,
3429            ArrowDataType::Int32,
3430            ArrowDataType::Int64,
3431            ArrowDataType::UInt8,
3432            ArrowDataType::UInt16,
3433            ArrowDataType::UInt32,
3434            ArrowDataType::UInt64,
3435        ] {
3436            let keys = arrow::compute::cast(
3437                &sliced,
3438                &ArrowDataType::Dictionary(Box::new(key_type), Box::new(ArrowDataType::Binary)),
3439            )
3440            .unwrap();
3441            let converted = convert_bulk_part(
3442                with_keys(keys),
3443                &metadata,
3444                primary_key_codec.clone(),
3445                output_schema.clone(),
3446                true,
3447            )
3448            .unwrap()
3449            .unwrap();
3450            let keys = arrow::compute::cast(
3451                converted
3452                    .batch
3453                    .column_by_name(PRIMARY_KEY_COLUMN_NAME)
3454                    .unwrap(),
3455                &ArrowDataType::Binary,
3456            )
3457            .unwrap();
3458            assert_eq!(keys.as_ref(), part.batch.column(0).as_ref());
3459            for (name, index) in [("v0", 1), ("v1", 2), ("ts", 3)] {
3460                assert_eq!(
3461                    converted.batch.column_by_name(name).unwrap().as_ref(),
3462                    part.batch.column(index).as_ref()
3463                );
3464            }
3465            assert_eq!(
3466                converted
3467                    .batch
3468                    .column_by_name("__sequence")
3469                    .unwrap()
3470                    .as_ref(),
3471                &UInt64Array::from(vec![7, 7]) as &dyn Array
3472            );
3473            assert_eq!(
3474                converted
3475                    .batch
3476                    .column_by_name("__op_type")
3477                    .unwrap()
3478                    .as_ref(),
3479                &UInt8Array::from(vec![OpType::Put as u8; 2]) as &dyn Array
3480            );
3481        }
3482        // Equal bytes under distinct dictionary slots remain separate observations.
3483        let repeated =
3484            DictionaryArray::try_new(UInt32Array::from(vec![0, 4]), dictionary_values.clone())
3485                .unwrap();
3486        assert_eq!(
3487            convert_bulk_part(
3488                with_keys(Arc::new(repeated)),
3489                &metadata,
3490                primary_key_codec.clone(),
3491                output_schema.clone(),
3492                true
3493            )
3494            .unwrap()
3495            .unwrap()
3496            .num_rows(),
3497            2
3498        );
3499        for indices in [
3500            vec![Some(0), Some(2)],
3501            vec![Some(0), Some(3)],
3502            vec![Some(0), None],
3503        ] {
3504            let dictionary =
3505                DictionaryArray::try_new(UInt32Array::from(indices), dictionary_values.clone())
3506                    .unwrap();
3507            assert!(
3508                convert_bulk_part(
3509                    with_keys(Arc::new(dictionary)),
3510                    &metadata,
3511                    primary_key_codec.clone(),
3512                    output_schema.clone(),
3513                    true
3514                )
3515                .is_err()
3516            );
3517        }
3518
3519        for invalid_keys in [
3520            Arc::new(arrow::array::StringArray::from(vec!["invalid"; 2])) as ArrayRef,
3521            Arc::new(BinaryArray::from(vec![None::<&[u8]>; 2])),
3522            Arc::new(BinaryArray::from_iter_values([b"truncated"; 2])),
3523        ] {
3524            let mut invalid = part.clone();
3525            let mut fields = invalid.batch.schema().fields().to_vec();
3526            fields[0] = Arc::new(Field::new(
3527                PRIMARY_KEY_COLUMN_NAME,
3528                invalid_keys.data_type().clone(),
3529                true,
3530            ));
3531            let mut columns = invalid.batch.columns().to_vec();
3532            columns[0] = invalid_keys;
3533            invalid.batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap();
3534            assert!(
3535                convert_bulk_part(
3536                    invalid,
3537                    &metadata,
3538                    primary_key_codec.clone(),
3539                    output_schema.clone(),
3540                    true,
3541                )
3542                .is_err()
3543            );
3544        }
3545
3546        let result = convert_bulk_part(
3547            part,
3548            &metadata,
3549            primary_key_codec,
3550            output_schema,
3551            true, // store_primary_key_columns (ignored for sparse)
3552        )
3553        .unwrap();
3554
3555        let converted = result.unwrap();
3556
3557        assert_eq!(converted.num_rows(), 2);
3558        assert_eq!(converted.max_timestamp, 2000);
3559        assert_eq!(converted.min_timestamp, 1000);
3560        assert_eq!(converted.sequence, 7);
3561
3562        // Verify schema does NOT include individual primary key columns (sparse encoding)
3563        let schema = converted.batch.schema();
3564        let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
3565        assert_eq!(
3566            field_names,
3567            vec!["v0", "v1", "ts", "__primary_key", "__sequence", "__op_type"]
3568        );
3569
3570        // Verify __primary_key is dictionary encoded
3571        let pk_col = converted.batch.column_by_name("__primary_key").unwrap();
3572        assert!(matches!(
3573            pk_col.data_type(),
3574            ArrowDataType::Dictionary(_, _)
3575        ));
3576    }
3577
3578    #[test]
3579    fn test_convert_bulk_part_sorting_with_multiple_series() {
3580        let metadata = metadata_for_test();
3581        let primary_key_codec = build_primary_key_codec(&metadata);
3582
3583        // Create unsorted batch with multiple series and timestamps
3584        let k0_array = Arc::new(arrow::array::StringArray::from(vec![
3585            "series_b", "series_a", "series_b", "series_a",
3586        ]));
3587        let k1_array = Arc::new(arrow::array::UInt32Array::from(vec![2, 1, 2, 1]));
3588        let v0_array = Arc::new(arrow::array::Int64Array::from(vec![200, 100, 400, 300]));
3589        let v1_array = Arc::new(arrow::array::Float64Array::from(vec![2.0, 1.0, 4.0, 3.0]));
3590        let ts_array = Arc::new(TimestampMillisecondArray::from(vec![
3591            2000, 1000, 4000, 3000,
3592        ]));
3593
3594        let input_schema = Arc::new(Schema::new(vec![
3595            Field::new("k0", ArrowDataType::Utf8, false),
3596            Field::new("k1", ArrowDataType::UInt32, false),
3597            Field::new("v0", ArrowDataType::Int64, true),
3598            Field::new("v1", ArrowDataType::Float64, true),
3599            Field::new(
3600                "ts",
3601                ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
3602                false,
3603            ),
3604        ]));
3605
3606        let input_batch = RecordBatch::try_new(
3607            input_schema,
3608            vec![k0_array, k1_array, v0_array, v1_array, ts_array],
3609        )
3610        .unwrap();
3611
3612        let part = BulkPart {
3613            batch: input_batch,
3614            max_timestamp: 4000,
3615            min_timestamp: 1000,
3616            sequence: 10,
3617            min_sequence: 10,
3618            timestamp_index: 4,
3619            raw_data: None,
3620        };
3621
3622        let output_schema = to_flat_sst_arrow_schema(
3623            &metadata,
3624            &FlatSchemaOptions::from_encoding(metadata.primary_key_encoding),
3625        );
3626
3627        let result =
3628            convert_bulk_part(part, &metadata, primary_key_codec, output_schema, true).unwrap();
3629
3630        let converted = result.unwrap();
3631
3632        assert_eq!(converted.num_rows(), 4);
3633
3634        // Verify data is sorted by (primary_key, timestamp, sequence desc)
3635        let ts_col = converted.batch.column(converted.timestamp_index);
3636        let ts_array = ts_col
3637            .as_any()
3638            .downcast_ref::<TimestampMillisecondArray>()
3639            .unwrap();
3640
3641        // After sorting by (pk, ts), we should have:
3642        // series_a,1: ts=1000, 3000
3643        // series_b,2: ts=2000, 4000
3644        let timestamps: Vec<i64> = ts_array.values().to_vec();
3645        assert_eq!(timestamps, vec![1000, 3000, 2000, 4000]);
3646    }
3647
3648    /// Helper to create a converted BulkPart (with __primary_key column) from MutationInputs.
3649    fn build_converted_bulk_part(inputs: &[MutationInput]) -> BulkPart {
3650        let metadata = metadata_for_test();
3651        let kvs = inputs
3652            .iter()
3653            .map(|m| {
3654                build_key_values_with_ts_seq_values(
3655                    &metadata,
3656                    m.k0.to_string(),
3657                    m.k1,
3658                    m.timestamps.iter().copied(),
3659                    m.v1.iter().copied(),
3660                    m.sequence,
3661                )
3662            })
3663            .collect::<Vec<_>>();
3664        let schema = to_flat_sst_arrow_schema(&metadata, &FlatSchemaOptions::default());
3665        let primary_key_codec = build_primary_key_codec(&metadata);
3666        let mut converter = BulkPartConverter::new(&metadata, schema, 64, primary_key_codec, true);
3667        for kv in kvs {
3668            converter.append_key_values(&kv).unwrap();
3669        }
3670        converter.convert().unwrap()
3671    }
3672
3673    #[test]
3674    fn test_min_sequence_survives_slicing_and_unordered_part_reuse() {
3675        let metadata = metadata_for_test();
3676        let make_part = |sequence| {
3677            build_converted_bulk_part(&[MutationInput {
3678                k0: "a",
3679                k1: 0,
3680                timestamps: &[2000, 1000],
3681                v1: &[Some(1.0), Some(2.0)],
3682                sequence,
3683            }])
3684        };
3685        let original = make_part(100);
3686        let sliced = crate::memtable::time_partition::filter_record_batch(&original, 1000, 1001)
3687            .unwrap()
3688            .unwrap();
3689        // The remaining row has sequence 101. Inheriting 100 is conservative
3690        // and avoids rescanning the sequence column after each partition split.
3691        assert_eq!(1, sliced.num_rows());
3692        assert_eq!(100, sliced.min_sequence);
3693        assert_eq!(101, sliced.sequence);
3694
3695        let mut unordered = UnorderedPart::new();
3696        unordered.push(sliced.clone());
3697        unordered.push(make_part(10));
3698        let merged = unordered.to_bulk_part(&metadata).unwrap().unwrap();
3699        assert_eq!(3, merged.num_rows());
3700        assert_eq!(10, merged.min_sequence);
3701        assert_eq!(101, merged.sequence);
3702        assert_eq!(10, merged.to_memtable_stats(&metadata).min_sequence);
3703
3704        unordered.clear();
3705        unordered.push(sliced);
3706        let reused = unordered.to_bulk_part(&metadata).unwrap().unwrap();
3707        assert_eq!(1, reused.num_rows());
3708        assert_eq!(100, reused.min_sequence);
3709    }
3710
3711    /// Helper to create a MultiBulkPart where each group becomes a separate batch.
3712    fn build_multi_bulk_part(groups: &[&[MutationInput]]) -> (MultiBulkPart, RegionMetadataRef) {
3713        let metadata = metadata_for_test();
3714        let mut all_batches = Vec::new();
3715        let mut min_ts = i64::MAX;
3716        let mut max_ts = i64::MIN;
3717        let mut min_seq = u64::MAX;
3718        let mut max_seq = 0u64;
3719
3720        for inputs in groups {
3721            let part = build_converted_bulk_part(inputs);
3722            min_ts = min_ts.min(part.min_timestamp);
3723            max_ts = max_ts.max(part.max_timestamp);
3724            min_seq = min_seq.min(part.min_sequence);
3725            max_seq = max_seq.max(part.sequence);
3726            all_batches.push(part.batch);
3727        }
3728
3729        let multi = MultiBulkPart::new(
3730            all_batches,
3731            min_ts,
3732            max_ts,
3733            min_seq,
3734            max_seq,
3735            groups.len(),
3736            &metadata,
3737        );
3738        (multi, metadata)
3739    }
3740
3741    #[test]
3742    fn test_multi_bulk_part_prune_batches() {
3743        // Three batches with distinct k0 ranges: ["a"], ["m"], ["z"].
3744        let (multi, metadata) = build_multi_bulk_part(&[
3745            &[MutationInput {
3746                k0: "a",
3747                k1: 0,
3748                timestamps: &[1, 2],
3749                v1: &[Some(1.0), Some(2.0)],
3750                sequence: 0,
3751            }],
3752            &[MutationInput {
3753                k0: "m",
3754                k1: 0,
3755                timestamps: &[3, 4],
3756                v1: &[Some(3.0), Some(4.0)],
3757                sequence: 1,
3758            }],
3759            &[MutationInput {
3760                k0: "z",
3761                k1: 0,
3762                timestamps: &[5, 6],
3763                v1: &[Some(5.0), Some(6.0)],
3764                sequence: 2,
3765            }],
3766        ]);
3767        assert_eq!(multi.num_rows(), 6);
3768        assert_eq!(multi.num_batches(), 3);
3769
3770        // k0 = "m" => only middle batch (2 rows).
3771        let context = Arc::new(
3772            BulkIterContext::new(
3773                metadata.clone(),
3774                None,
3775                Some(Predicate::new(vec![
3776                    datafusion_expr::col("k0").eq(datafusion_expr::lit("m")),
3777                ])),
3778                false,
3779                crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
3780            )
3781            .unwrap(),
3782        );
3783        let reader = multi
3784            .read(context, None, None)
3785            .unwrap()
3786            .expect("should have results");
3787        let total_rows: usize = reader.map(|r| r.unwrap().num_rows()).sum();
3788        assert_eq!(total_rows, 2);
3789
3790        // k0 = "nonexistent" => all pruned, returns None.
3791        let context = Arc::new(
3792            BulkIterContext::new(
3793                metadata.clone(),
3794                None,
3795                Some(Predicate::new(vec![
3796                    datafusion_expr::col("k0").eq(datafusion_expr::lit("nonexistent")),
3797                ])),
3798                false,
3799                crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
3800            )
3801            .unwrap(),
3802        );
3803        assert!(multi.read(context, None, None).unwrap().is_none());
3804
3805        // No predicate => all 6 rows.
3806        let context = Arc::new(
3807            BulkIterContext::new(
3808                metadata.clone(),
3809                None,
3810                None,
3811                false,
3812                crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
3813            )
3814            .unwrap(),
3815        );
3816        let reader = multi
3817            .read(context, None, None)
3818            .unwrap()
3819            .expect("should have results");
3820        let total_rows: usize = reader.map(|r| r.unwrap().num_rows()).sum();
3821        assert_eq!(total_rows, 6);
3822    }
3823
3824    #[test]
3825    fn test_fill_missing_columns_resets_raw_data() {
3826        let metadata = metadata_for_test();
3827
3828        // A batch missing the `v1` field column, e.g. built against an older
3829        // schema before `v1` was added.
3830        let k0_array = Arc::new(arrow::array::StringArray::from(vec!["key1", "key2"]));
3831        let k1_array = Arc::new(arrow::array::UInt32Array::from(vec![1u32, 2]));
3832        let v0_array = Arc::new(arrow::array::Int64Array::from(vec![100i64, 200]));
3833        let ts_array = Arc::new(TimestampMillisecondArray::from(vec![1000i64, 2000]));
3834        let input_schema = Arc::new(Schema::new(vec![
3835            Field::new("k0", ArrowDataType::Utf8, false),
3836            Field::new("k1", ArrowDataType::UInt32, false),
3837            Field::new("v0", ArrowDataType::Int64, true),
3838            Field::new(
3839                "ts",
3840                ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
3841                false,
3842            ),
3843        ]));
3844        let batch =
3845            RecordBatch::try_new(input_schema, vec![k0_array, k1_array, v0_array, ts_array])
3846                .unwrap();
3847
3848        // Encodes the batch as raw data like the bulk insert request does.
3849        let mut encoder = FlightEncoder::default();
3850        let schema_bytes = encoder.encode_schema(batch.schema().as_ref()).data_header;
3851        let [flight_data] = encoder
3852            .encode(FlightMessage::RecordBatch(batch.clone()))
3853            .try_into()
3854            .unwrap();
3855        let mut part = BulkPart {
3856            batch,
3857            max_timestamp: 2000,
3858            min_timestamp: 1000,
3859            sequence: 5,
3860            min_sequence: 5,
3861            timestamp_index: 3,
3862            raw_data: Some(ArrowIpc {
3863                schema: schema_bytes,
3864                data_header: flight_data.data_header,
3865                payload: flight_data.data_body,
3866            }),
3867        };
3868
3869        part.fill_missing_columns(&metadata).unwrap();
3870        assert!(part.batch.column_by_name("v1").is_some());
3871        // The raw data no longer matches the batch after filling missing
3872        // columns and must be cleared, otherwise the WAL entry built from
3873        // this part loses the filled columns.
3874        assert!(part.raw_data.is_none());
3875
3876        // The WAL entry round trip keeps the filled column.
3877        let entry = BulkWalEntry::try_from(&part).unwrap();
3878        let replayed = BulkPart::try_from(entry).unwrap();
3879        assert_eq!(part.sequence, replayed.min_sequence);
3880        assert_eq!(2, replayed.num_rows());
3881        assert!(replayed.batch.column_by_name("v1").is_some());
3882    }
3883}