Skip to main content

mito2/
sst.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//! Sorted strings tables.
16
17use std::collections::HashMap;
18use std::sync::Arc;
19
20use api::v1::SemanticType;
21use arrow_schema::DataType;
22use arrow_schema::extension::{EXTENSION_TYPE_NAME_KEY, ExtensionType};
23use common_base::readable_size::ReadableSize;
24use common_query::native_histogram::{
25    is_native_histogram_value_type, native_histogram_list_element_id, native_histogram_subfield_id,
26};
27use datatypes::arrow::datatypes::{
28    DataType as ArrowDataType, Field, FieldRef, Fields, Schema, SchemaRef,
29};
30use datatypes::arrow::record_batch::RecordBatch;
31use datatypes::extension::histogram::HistogramExtensionType;
32use datatypes::prelude::ConcreteDataType;
33use datatypes::timestamp::timestamp_array_to_primitive;
34use serde::{Deserialize, Serialize};
35use store_api::codec::PrimaryKeyEncoding;
36use store_api::metadata::RegionMetadata;
37use store_api::storage::consts::{
38    OP_TYPE_COLUMN_NAME, PRIMARY_KEY_COLUMN_NAME, SEQUENCE_COLUMN_NAME,
39};
40
41use crate::error::{InvalidNativeHistogramFieldIdSnafu, InvalidNativeHistogramSubfieldSnafu};
42use crate::sst::parquet::flat_format::time_index_column_index;
43
44pub mod file;
45pub mod file_metadata;
46pub mod file_purger;
47pub mod file_ref;
48pub mod index;
49pub mod location;
50pub(crate) mod narthex;
51pub mod parquet;
52pub(crate) mod primary_key;
53pub(crate) mod upload;
54pub(crate) mod version;
55
56/// Default write buffer size, it should be greater than the default minimum upload part of S3 (5mb).
57pub const DEFAULT_WRITE_BUFFER_SIZE: ReadableSize = ReadableSize::mb(8);
58
59/// Default number of concurrent write, it only works on object store backend(e.g., S3).
60pub const DEFAULT_WRITE_CONCURRENCY: usize = 8;
61
62/// Format type of the SST file.
63#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::EnumString)]
64#[serde(rename_all = "snake_case")]
65#[strum(serialize_all = "snake_case")]
66pub enum FormatType {
67    /// Parquet with primary key encoded.
68    #[default]
69    PrimaryKey,
70    /// Flat Parquet format.
71    Flat,
72    /// Narthex samples and optional series indexes.
73    Narthex,
74}
75
76/// Iceberg-compatible column field ID key stored in Parquet column metadata.
77pub const PARQUET_FIELD_ID_KEY: &str = "PARQUET:field_id";
78
79/// Adds `PARQUET:field_id` metadata to a top-level Arrow field.
80///
81/// Native-histogram sub-field ids are stamped separately at parquet-write
82/// time by [`stamp_native_histogram_subfield_ids`], not here.
83pub fn with_field_id(mut field: Field, column_id: u32) -> Field {
84    field
85        .metadata_mut()
86        .insert(PARQUET_FIELD_ID_KEY.to_string(), column_id.to_string());
87    field
88}
89
90/// Stamps the `greptime.histogram` extension and reserved `PARQUET:field_id`s
91/// onto a native-histogram struct field (and its sub-fields / list element
92/// fields), so external readers can identify it by extension and resolve
93/// nested fields by id.
94///
95/// Detection is by the exact native-histogram struct type
96/// (`is_native_histogram_value_type`); other struct columns are left untouched.
97/// mito2 reads SST columns by schema position, never by field metadata, so this
98/// only affects external readers.
99///
100/// Returns an error if the parent column's `PARQUET:field_id` is missing,
101/// malformed, or exceeds `i32::MAX`, or if a sub-field id cannot be derived
102/// — because the sub-field name is not a known native-histogram field, or
103/// the derived id overflows a positive `i32` (an absurdly large parent
104/// `column_id`); see [`native_histogram_subfield_id`].
105fn stamp_native_histogram_subfield_ids(field: &mut Field) -> crate::error::Result<()> {
106    if !is_native_histogram_value_type(&ConcreteDataType::from_arrow_type(field.data_type())) {
107        return Ok(());
108    }
109    // Namespace sub-field ids by the parent column's field id (its
110    // `PARQUET:field_id`, stamped earlier by `with_field_id`) so several
111    // histogram columns in one table get disjoint ids. Fail loudly if the id
112    // is absent, malformed, or too large to fit a positive `i32`.
113    let column_id = field
114        .metadata()
115        .get(PARQUET_FIELD_ID_KEY)
116        .and_then(|s| s.parse::<i32>().ok())
117        .ok_or_else(|| {
118            InvalidNativeHistogramFieldIdSnafu {
119                field_name: field.name().clone(),
120            }
121            .build()
122        })?;
123    // Tag the field with the greptime.histogram extension.
124    field.metadata_mut().insert(
125        EXTENSION_TYPE_NAME_KEY.to_string(),
126        HistogramExtensionType::NAME.to_string(),
127    );
128    let ArrowDataType::Struct(children) = field.data_type() else {
129        return Ok(());
130    };
131    let new_children: crate::error::Result<Fields> = children
132        .iter()
133        .map(|child| {
134            let mut c = (**child).clone();
135            // `None` here means either the sub-field name is not a known
136            // native-histogram field, or the derived id overflowed i32.
137            // Surface it as an error rather than silently leaving the field
138            // without an id.
139            let id = native_histogram_subfield_id(column_id, c.name()).ok_or_else(|| {
140                InvalidNativeHistogramSubfieldSnafu {
141                    column_id,
142                    field_name: c.name().clone(),
143                }
144                .build()
145            })?;
146            // Stamp the sub-field's own id.
147            c.metadata_mut()
148                .insert(PARQUET_FIELD_ID_KEY.to_string(), id.to_string());
149            // If the sub-field is a list, stamp its element field's id.
150            if let ArrowDataType::List(elem) = c.data_type() {
151                let elem_id =
152                    native_histogram_list_element_id(column_id, c.name()).ok_or_else(|| {
153                        InvalidNativeHistogramSubfieldSnafu {
154                            column_id,
155                            field_name: c.name().clone(),
156                        }
157                        .build()
158                    })?;
159                let mut new_elem = (**elem).clone();
160                new_elem
161                    .metadata_mut()
162                    .insert(PARQUET_FIELD_ID_KEY.to_string(), elem_id.to_string());
163                c.set_data_type(ArrowDataType::List(Arc::new(new_elem)));
164            }
165            Ok(Arc::new(c))
166        })
167        .collect();
168    field.set_data_type(ArrowDataType::Struct(new_children?));
169    Ok(())
170}
171
172/// Returns a copy of `schema` with native-histogram sub-field ids stamped,
173/// for the parquet writer.
174///
175/// This is called on the schema handed to `AsyncArrowWriter`, not in
176/// [`with_field_id`], because the SST arrow schema is also the memtable's
177/// in-memory schema, whose `Struct` equality (`PartialEq`) is
178/// metadata-sensitive — stamping there would break writes. The parquet writer
179/// compares types with `DataType::equals_datatype`, which ignores field
180/// metadata, so a stamped schema accepts an unstamped batch.
181pub fn maybe_wrap_schema(schema: &SchemaRef) -> crate::error::Result<SchemaRef> {
182    // Fast path: only a struct column can be a native histogram; if there are
183    // none, skip the rebuild.
184    if !schema
185        .fields()
186        .iter()
187        .any(|f| matches!(f.data_type(), ArrowDataType::Struct(_)))
188    {
189        return Ok(schema.clone());
190    }
191    let new_fields: crate::error::Result<Vec<FieldRef>> = schema
192        .fields()
193        .iter()
194        .map(|f| {
195            let mut field = (**f).clone();
196            stamp_native_histogram_subfield_ids(&mut field)?;
197            Ok(Arc::new(field))
198        })
199        .collect();
200    Ok(Arc::new(Schema::new_with_metadata(
201        Fields::from(new_fields?),
202        schema.metadata().clone(),
203    )))
204}
205
206/// Parquet field ID base for internal columns (__primary_key, __sequence, __op_type).
207/// Uses bit 30 to distinguish from user column IDs and fit in positive i32 range.
208pub(crate) const INTERNAL_PARQUET_FIELD_ID_BASE: u32 = 1 << 30;
209
210/// Parquet field ID for the __primary_key column.
211pub(crate) const PRIMARY_KEY_PARQUET_FIELD_ID: u32 = INTERNAL_PARQUET_FIELD_ID_BASE;
212/// Parquet field ID for the __sequence column.
213pub(crate) const SEQUENCE_PARQUET_FIELD_ID: u32 = INTERNAL_PARQUET_FIELD_ID_BASE + 1;
214/// Parquet field ID for the __op_type column.
215pub(crate) const OP_TYPE_PARQUET_FIELD_ID: u32 = INTERNAL_PARQUET_FIELD_ID_BASE + 2;
216
217/// Gets the arrow schema to store in parquet.
218pub fn to_sst_arrow_schema(metadata: &RegionMetadata) -> SchemaRef {
219    let fields = Fields::from_iter(
220        metadata
221            .schema
222            .arrow_schema()
223            .fields()
224            .iter()
225            .zip(&metadata.column_metadatas)
226            .filter_map(|(field, column_meta)| {
227                if column_meta.semantic_type == SemanticType::Field {
228                    Some(Arc::new(with_field_id(
229                        (**field).clone(),
230                        column_meta.column_id,
231                    )))
232                } else {
233                    // We have fixed positions for tags (primary key) and time index.
234                    None
235                }
236            })
237            .chain([Arc::new(with_field_id(
238                (*metadata.time_index_field()).clone(),
239                metadata.time_index_column().column_id,
240            ))])
241            .chain(internal_fields()),
242    );
243
244    Arc::new(Schema::new(fields))
245}
246
247/// Options of flat schema.
248pub struct FlatSchemaOptions {
249    /// Whether to store primary key columns additionally instead of an encoded column.
250    pub raw_pk_columns: bool,
251    /// Whether to use dictionary encoding for string primary key columns
252    /// when storing primary key columns.
253    /// Only takes effect when `raw_pk_columns` is true.
254    pub string_pk_use_dict: bool,
255    /// The column's concretized JSON types, to be set into Arrow schema.
256    /// Otherwise it's empty struct in the Arrow schema.
257    pub concretized_json_types: HashMap<String, DataType>,
258}
259
260impl Default for FlatSchemaOptions {
261    fn default() -> Self {
262        Self {
263            raw_pk_columns: true,
264            string_pk_use_dict: true,
265            concretized_json_types: HashMap::new(),
266        }
267    }
268}
269
270impl FlatSchemaOptions {
271    /// Creates a options according to the primary key encoding.
272    pub fn from_encoding(encoding: PrimaryKeyEncoding) -> Self {
273        if encoding == PrimaryKeyEncoding::Dense {
274            Self::default()
275        } else {
276            Self {
277                raw_pk_columns: false,
278                string_pk_use_dict: false,
279                concretized_json_types: HashMap::new(),
280            }
281        }
282    }
283}
284
285/// Gets the arrow schema to store in parquet.
286///
287/// The schema is:
288/// ```text
289/// primary key columns, field columns, time index, __primary_key, __sequence, __op_type
290/// ```
291///
292/// # Panics
293/// Panics if the metadata is invalid.
294pub fn to_flat_sst_arrow_schema(
295    metadata: &RegionMetadata,
296    options: &FlatSchemaOptions,
297) -> SchemaRef {
298    let num_fields = flat_sst_arrow_schema_column_num(metadata, options);
299    let mut fields = Vec::with_capacity(num_fields);
300    let schema = metadata.schema.arrow_schema();
301    if options.raw_pk_columns {
302        for pk_id in &metadata.primary_key {
303            let pk_index = metadata.column_index_by_id(*pk_id).unwrap();
304            let column_id = metadata.column_metadatas[pk_index].column_id;
305            if options.string_pk_use_dict {
306                let old_field = &schema.fields[pk_index];
307                let new_field = tag_maybe_to_dictionary_field(
308                    &metadata.column_metadatas[pk_index].column_schema.data_type,
309                    old_field,
310                );
311                let new_field = concretize_json_type(new_field, options);
312                fields.push(Arc::new(with_field_id((*new_field).clone(), column_id)));
313            }
314        }
315    }
316    let remaining_fields = schema
317        .fields()
318        .iter()
319        .zip(&metadata.column_metadatas)
320        .filter_map(|(field, column_meta)| {
321            if column_meta.semantic_type == SemanticType::Field {
322                let field = concretize_json_type(field.clone(), options);
323                Some(Arc::new(with_field_id(
324                    Arc::unwrap_or_clone(field),
325                    column_meta.column_id,
326                )))
327            } else {
328                None
329            }
330        })
331        .chain([Arc::new(with_field_id(
332            (*metadata.time_index_field()).clone(),
333            metadata.time_index_column().column_id,
334        ))])
335        .chain(internal_fields());
336    for field in remaining_fields {
337        fields.push(field);
338    }
339
340    Arc::new(Schema::new(fields))
341}
342
343fn concretize_json_type(field: Arc<Field>, options: &FlatSchemaOptions) -> Arc<Field> {
344    if let Some(data_type) = options.concretized_json_types.get(field.name()) {
345        let mut field = Arc::unwrap_or_clone(field);
346        field.set_data_type(data_type.clone());
347        Arc::new(field)
348    } else {
349        field
350    }
351}
352
353/// Returns the number of columns in the flat format.
354pub fn flat_sst_arrow_schema_column_num(
355    metadata: &RegionMetadata,
356    options: &FlatSchemaOptions,
357) -> usize {
358    if options.raw_pk_columns {
359        metadata.column_metadatas.len() + 3
360    } else {
361        metadata.column_metadatas.len() + 3 - metadata.primary_key.len()
362    }
363}
364
365/// Helper function to create a dictionary field from a field.
366fn to_dictionary_field(field: &Field) -> Field {
367    let mut new_field = Field::new_dictionary(
368        field.name(),
369        datatypes::arrow::datatypes::DataType::UInt32,
370        field.data_type().clone(),
371        field.is_nullable(),
372    );
373
374    // retain field_id metadata
375    if let Some(field_id) = field.metadata().get(PARQUET_FIELD_ID_KEY) {
376        new_field
377            .metadata_mut()
378            .insert(PARQUET_FIELD_ID_KEY.to_string(), field_id.clone());
379    }
380
381    new_field
382}
383
384/// Helper function to create a dictionary field from a field if it is a string column.
385pub(crate) fn tag_maybe_to_dictionary_field(
386    data_type: &ConcreteDataType,
387    field: &Arc<Field>,
388) -> Arc<Field> {
389    if data_type.is_string() {
390        Arc::new(to_dictionary_field(field))
391    } else {
392        field.clone()
393    }
394}
395
396/// Fields for internal columns.
397pub(crate) fn internal_fields() -> [FieldRef; 3] {
398    // Internal columns are always not null.
399    [
400        Arc::new(with_field_id(
401            Field::new_dictionary(
402                PRIMARY_KEY_COLUMN_NAME,
403                ArrowDataType::UInt32,
404                ArrowDataType::Binary,
405                false,
406            ),
407            PRIMARY_KEY_PARQUET_FIELD_ID,
408        )),
409        Arc::new(with_field_id(
410            Field::new(SEQUENCE_COLUMN_NAME, ArrowDataType::UInt64, false),
411            SEQUENCE_PARQUET_FIELD_ID,
412        )),
413        Arc::new(with_field_id(
414            Field::new(OP_TYPE_COLUMN_NAME, ArrowDataType::UInt8, false),
415            OP_TYPE_PARQUET_FIELD_ID,
416        )),
417    ]
418}
419
420/// Returns a copy of `schema` with the `__primary_key` field replaced by a plain `Binary` field.
421pub(crate) fn override_pk_field_to_binary(schema: &SchemaRef) -> SchemaRef {
422    let new_fields = schema
423        .fields()
424        .iter()
425        .map(|field| {
426            if field.name() == PRIMARY_KEY_COLUMN_NAME {
427                let mut new_field = Field::new(
428                    PRIMARY_KEY_COLUMN_NAME,
429                    ArrowDataType::Binary,
430                    field.is_nullable(),
431                );
432                // Preserve the field_id metadata so parquet readers that require
433                // all columns to carry a field_id don't fail.
434                if let Some(field_id) = field.metadata().get(PARQUET_FIELD_ID_KEY) {
435                    new_field
436                        .metadata_mut()
437                        .insert(PARQUET_FIELD_ID_KEY.to_string(), field_id.clone());
438                }
439                Arc::new(new_field)
440            } else {
441                field.clone()
442            }
443        })
444        .collect::<Vec<_>>();
445    Arc::new(Schema::new(new_fields))
446}
447
448/// Gets the estimated number of series from record batches.
449///
450/// This struct tracks the last timestamp value to detect series boundaries
451/// by observing when timestamps decrease (indicating a new series).
452#[derive(Default)]
453pub(crate) struct SeriesEstimator {
454    /// The last timestamp value seen
455    last_timestamp: Option<i64>,
456    /// The estimated number of series
457    series_count: u64,
458}
459
460impl SeriesEstimator {
461    /// Updates the estimator with a new record batch in flat format.
462    ///
463    /// This method examines the time index column to detect series boundaries.
464    pub(crate) fn update_flat(&mut self, record_batch: &RecordBatch) {
465        let batch_rows = record_batch.num_rows();
466        if batch_rows == 0 {
467            return;
468        }
469
470        let time_index_pos = time_index_column_index(record_batch.num_columns());
471        let timestamps = record_batch.column(time_index_pos);
472        let Some((ts_values, _unit)) = timestamp_array_to_primitive(timestamps) else {
473            return;
474        };
475        let values = ts_values.values();
476
477        // Checks if there's a boundary between the last batch and this batch
478        if let Some(last_ts) = self.last_timestamp {
479            if values[0] <= last_ts {
480                self.series_count += 1;
481            }
482        } else {
483            // First batch, counts as first series
484            self.series_count = 1;
485        }
486
487        // Counts series boundaries within this batch.
488        for i in 0..batch_rows - 1 {
489            // We assumes the same timestamp as a new series, which is different from
490            // how we split batches.
491            if values[i] >= values[i + 1] {
492                self.series_count += 1;
493            }
494        }
495
496        // Updates the last timestamp
497        self.last_timestamp = Some(values[batch_rows - 1]);
498    }
499
500    /// Returns the estimated number of series.
501    pub(crate) fn finish(&mut self) -> u64 {
502        self.last_timestamp = None;
503        let count = self.series_count;
504        self.series_count = 0;
505
506        count
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    use std::sync::Arc;
513
514    use ::parquet::arrow::AsyncArrowWriter;
515    use ::parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
516    use ::parquet::basic::LogicalType;
517    use ::parquet::variant::{VariantArray, VariantType, json_to_variant};
518    use common_query::prelude::greptime_native_histogram;
519    use datatypes::arrow::array::{
520        ArrayRef, BinaryArray, DictionaryArray, Int64Array, StringArray, StructArray,
521        TimestampMillisecondArray, UInt8Array, UInt32Array, UInt64Array,
522    };
523    use datatypes::arrow::datatypes::{DataType as ArrowDataType, Field, Schema, TimeUnit};
524    use datatypes::arrow::record_batch::RecordBatch;
525    use datatypes::extension::json::{Json2ExtensionType, Json2PhysicalLayout};
526    use datatypes::vectors::json::array::JsonArray;
527    use serde_json::json;
528
529    use super::*;
530
531    #[test]
532    fn test_narthex_format_name() {
533        let name = "narthex";
534        assert_eq!(name.parse::<FormatType>().unwrap(), FormatType::Narthex);
535        let options = crate::region::options::RegionOptions::try_from_options(
536            store_api::storage::RegionId::new(0, 0),
537            &HashMap::from([("sst_format".to_string(), name.to_string())]),
538        )
539        .unwrap();
540        assert_eq!(options.sst_format, Some(FormatType::Narthex));
541        assert_eq!(
542            serde_json::from_value::<FormatType>(json!(name)).unwrap(),
543            FormatType::Narthex
544        );
545        assert_eq!(
546            serde_json::to_value(FormatType::Narthex).unwrap(),
547            json!("narthex")
548        );
549    }
550
551    fn new_flat_record_batch(timestamps: &[i64]) -> RecordBatch {
552        // Flat format has: [fields..., time_index, __primary_key, __sequence, __op_type]
553        let num_cols = 4; // time_index + 3 internal columns
554        let time_index_pos = time_index_column_index(num_cols);
555        assert_eq!(time_index_pos, 0); // For 4 columns, time index should be at position 0
556
557        let time_array = Arc::new(TimestampMillisecondArray::from(timestamps.to_vec()));
558        let pk_array = Arc::new(DictionaryArray::new(
559            UInt32Array::from(vec![0; timestamps.len()]),
560            Arc::new(BinaryArray::from(vec![b"test".as_slice()])),
561        ));
562        let seq_array = Arc::new(UInt64Array::from(vec![1; timestamps.len()]));
563        let op_array = Arc::new(UInt8Array::from(vec![1; timestamps.len()]));
564
565        let schema = Arc::new(Schema::new(vec![
566            Field::new(
567                "time",
568                ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
569                false,
570            ),
571            Field::new_dictionary(
572                "__primary_key",
573                ArrowDataType::UInt32,
574                ArrowDataType::Binary,
575                false,
576            ),
577            Field::new("__sequence", ArrowDataType::UInt64, false),
578            Field::new("__op_type", ArrowDataType::UInt8, false),
579        ]));
580
581        RecordBatch::try_new(schema, vec![time_array, pk_array, seq_array, op_array]).unwrap()
582    }
583
584    #[test]
585    fn test_series_estimator_flat_empty_batch() {
586        let mut estimator = SeriesEstimator::default();
587        let record_batch = new_flat_record_batch(&[]);
588        estimator.update_flat(&record_batch);
589        assert_eq!(0, estimator.finish());
590    }
591
592    #[test]
593    fn test_series_estimator_flat_single_batch() {
594        let mut estimator = SeriesEstimator::default();
595        let record_batch = new_flat_record_batch(&[1, 2, 3]);
596        estimator.update_flat(&record_batch);
597        assert_eq!(1, estimator.finish());
598    }
599
600    #[test]
601    fn test_series_estimator_flat_series_boundary_within_batch() {
602        let mut estimator = SeriesEstimator::default();
603        // Timestamps decrease from 3 to 2, indicating a series boundary
604        let record_batch = new_flat_record_batch(&[1, 2, 3, 2, 4, 5]);
605        estimator.update_flat(&record_batch);
606        // Should detect boundary at position 3 (3 >= 2)
607        assert_eq!(2, estimator.finish());
608    }
609
610    #[test]
611    fn test_series_estimator_flat_multiple_boundaries_within_batch() {
612        let mut estimator = SeriesEstimator::default();
613        // Multiple series boundaries: 5>=4, 6>=3
614        let record_batch = new_flat_record_batch(&[1, 2, 5, 4, 6, 3, 7]);
615        estimator.update_flat(&record_batch);
616        assert_eq!(3, estimator.finish());
617    }
618
619    #[test]
620    fn test_series_estimator_flat_equal_timestamps() {
621        let mut estimator = SeriesEstimator::default();
622        // Equal timestamps are considered as new series
623        let record_batch = new_flat_record_batch(&[1, 2, 2, 3, 3, 3, 4]);
624        estimator.update_flat(&record_batch);
625        // Boundaries at: 2>=2, 3>=3, 3>=3
626        assert_eq!(4, estimator.finish());
627    }
628
629    #[test]
630    fn test_series_estimator_flat_multiple_batches_continuation() {
631        let mut estimator = SeriesEstimator::default();
632
633        // First batch: timestamps 1, 2, 3
634        let batch1 = new_flat_record_batch(&[1, 2, 3]);
635        estimator.update_flat(&batch1);
636
637        // Second batch: timestamps 4, 5, 6 (continuation)
638        let batch2 = new_flat_record_batch(&[4, 5, 6]);
639        estimator.update_flat(&batch2);
640
641        assert_eq!(1, estimator.finish());
642    }
643
644    #[test]
645    fn test_series_estimator_flat_multiple_batches_new_series() {
646        let mut estimator = SeriesEstimator::default();
647
648        // First batch: timestamps 1, 2, 3
649        let batch1 = new_flat_record_batch(&[1, 2, 3]);
650        estimator.update_flat(&batch1);
651
652        // Second batch: timestamps 2, 3, 4 (goes back to 2, new series)
653        let batch2 = new_flat_record_batch(&[2, 3, 4]);
654        estimator.update_flat(&batch2);
655
656        assert_eq!(2, estimator.finish());
657    }
658
659    #[test]
660    fn test_series_estimator_flat_boundary_at_batch_edge_equal() {
661        let mut estimator = SeriesEstimator::default();
662
663        // First batch ending at 5
664        let batch1 = new_flat_record_batch(&[1, 2, 5]);
665        estimator.update_flat(&batch1);
666
667        // Second batch starting at 5 (equal timestamp, new series)
668        let batch2 = new_flat_record_batch(&[5, 6, 7]);
669        estimator.update_flat(&batch2);
670
671        assert_eq!(2, estimator.finish());
672    }
673
674    #[test]
675    fn test_series_estimator_flat_mixed_batches() {
676        let mut estimator = SeriesEstimator::default();
677
678        // Batch 1: single series [10, 20, 30]
679        let batch1 = new_flat_record_batch(&[10, 20, 30]);
680        estimator.update_flat(&batch1);
681
682        // Batch 2: starts new series [5, 15], boundary within batch [15, 10, 25]
683        let batch2 = new_flat_record_batch(&[5, 15, 10, 25]);
684        estimator.update_flat(&batch2);
685
686        // Batch 3: continues from 25 to [30, 35]
687        let batch3 = new_flat_record_batch(&[30, 35]);
688        estimator.update_flat(&batch3);
689
690        // Expected: 1 (batch1) + 1 (batch2 start) + 1 (within batch2) = 3
691        assert_eq!(3, estimator.finish());
692    }
693
694    #[test]
695    fn test_series_estimator_flat_descending_timestamps() {
696        let mut estimator = SeriesEstimator::default();
697        // Strictly descending timestamps - each pair creates a boundary
698        let record_batch = new_flat_record_batch(&[10, 9, 8, 7, 6]);
699        estimator.update_flat(&record_batch);
700        // Boundaries: 10>=9, 9>=8, 8>=7, 7>=6 = 4 boundaries + 1 initial = 5 series
701        assert_eq!(5, estimator.finish());
702    }
703
704    #[test]
705    fn test_series_estimator_flat_finish_resets_state() {
706        let mut estimator = SeriesEstimator::default();
707
708        let batch1 = new_flat_record_batch(&[1, 2, 3]);
709        estimator.update_flat(&batch1);
710
711        assert_eq!(1, estimator.finish());
712
713        // After finish, state should be reset
714        let batch2 = new_flat_record_batch(&[4, 5, 6]);
715        estimator.update_flat(&batch2);
716
717        assert_eq!(1, estimator.finish());
718    }
719
720    /// Build a native-histogram struct field whose top-level `PARQUET:field_id`
721    /// is `column_id` (as `with_field_id` does on the real write path).
722    fn histogram_field(name: &str, column_id: u32) -> Field {
723        use common_query::native_histogram::native_histogram_value_type;
724        use datatypes::data_type::DataType;
725        with_field_id(
726            Field::new(name, native_histogram_value_type().as_arrow_type(), true),
727            column_id,
728        )
729    }
730
731    /// Asserts `field` is a stamped native-histogram struct: it carries the
732    /// `greptime.histogram` extension and every sub-field (and list element)
733    /// carries its reserved `PARQUET:field_id` namespaced by `column_id`.
734    fn assert_histogram_stamped(field: &Field, column_id: i32) {
735        use arrow_schema::extension::ExtensionType;
736        use common_query::native_histogram::{
737            native_histogram_list_element_id, native_histogram_subfield_id,
738        };
739        use datatypes::extension::histogram::HistogramExtensionType;
740
741        assert_eq!(
742            field
743                .metadata()
744                .get(arrow_schema::extension::EXTENSION_TYPE_NAME_KEY)
745                .map(|s| s.as_str()),
746            Some(HistogramExtensionType::NAME),
747            "histogram field must carry the greptime.histogram extension"
748        );
749        let ArrowDataType::Struct(children) = field.data_type() else {
750            panic!("expected a struct, got {:?}", field.data_type());
751        };
752        for child in children {
753            let expected = native_histogram_subfield_id(column_id, child.name())
754                .unwrap_or_else(|| panic!("no id for sub-field {}", child.name()));
755            let got: i32 = child
756                .metadata()
757                .get(PARQUET_FIELD_ID_KEY)
758                .unwrap_or_else(|| panic!("sub-field {} missing field id", child.name()))
759                .parse()
760                .unwrap();
761            assert_eq!(got, expected, "sub-field {} id", child.name());
762            if let ArrowDataType::List(elem) = child.data_type() {
763                let elem_expected =
764                    native_histogram_list_element_id(column_id, child.name()).unwrap();
765                let elem_got: i32 = elem
766                    .metadata()
767                    .get(PARQUET_FIELD_ID_KEY)
768                    .unwrap_or_else(|| panic!("list element of {} missing id", child.name()))
769                    .parse()
770                    .unwrap();
771                assert_eq!(
772                    elem_got,
773                    elem_expected,
774                    "list element id of {}",
775                    child.name()
776                );
777            }
778        }
779    }
780
781    #[test]
782    fn test_maybe_wrap_schema_native_histogram() {
783        let schema = Arc::new(Schema::new(vec![
784            Field::new(
785                "greptime_timestamp",
786                ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
787                false,
788            ),
789            histogram_field(greptime_native_histogram(), 1),
790        ]));
791
792        let wrapped = maybe_wrap_schema(&schema).unwrap();
793        let hist = wrapped
794            .field_with_name(greptime_native_histogram())
795            .expect("histogram field present");
796        // The struct has 18 sub-fields.
797        let ArrowDataType::Struct(children) = hist.data_type() else {
798            unreachable!()
799        };
800        assert_eq!(children.len(), 18);
801        assert_histogram_stamped(hist, 1);
802    }
803
804    #[test]
805    fn test_maybe_wrap_schema_multiple_histograms_disjoint_ids() {
806        // Two histogram columns with distinct parent column ids get disjoint
807        // sub-field ids (defensive: the metric engine yields at most one
808        // histogram column, but the scheme must stay correct if more appear).
809        use common_query::native_histogram::native_histogram_subfield_id;
810
811        let schema = Arc::new(Schema::new(vec![
812            histogram_field(greptime_native_histogram(), 1),
813            histogram_field(greptime_native_histogram(), 7),
814        ]));
815        let wrapped = maybe_wrap_schema(&schema).unwrap();
816        let h1 = &wrapped.fields()[0];
817        let h2 = &wrapped.fields()[1];
818        assert_histogram_stamped(h1, 1);
819        assert_histogram_stamped(h2, 7);
820        // The same sub-field name resolves to different ids across columns.
821        assert_ne!(
822            native_histogram_subfield_id(1, "sum"),
823            native_histogram_subfield_id(7, "sum")
824        );
825    }
826
827    #[test]
828    fn test_maybe_wrap_schema_recognizes_histogram_by_type() {
829        let schema = Arc::new(Schema::new(vec![histogram_field("custom_histogram", 5)]));
830
831        let wrapped = maybe_wrap_schema(&schema).unwrap();
832        let hist = wrapped.field_with_name("custom_histogram").unwrap();
833        assert_histogram_stamped(hist, 5);
834    }
835
836    #[test]
837    fn test_maybe_wrap_schema_plain_struct_not_stamped() {
838        use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY;
839
840        let plain = ArrowDataType::Struct(
841            vec![
842                Arc::new(Field::new("a", ArrowDataType::Int32, true)),
843                Arc::new(Field::new("b", ArrowDataType::Utf8, true)),
844            ]
845            .into(),
846        );
847        let schema = Arc::new(Schema::new(vec![
848            Field::new(
849                "ts",
850                ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
851                false,
852            ),
853            Field::new("data", plain, true),
854        ]));
855
856        let wrapped = maybe_wrap_schema(&schema).unwrap();
857        let data = wrapped.field_with_name("data").unwrap();
858        assert!(
859            data.metadata().get(EXTENSION_TYPE_NAME_KEY).is_none(),
860            "non-histogram struct must not get the extension"
861        );
862        if let ArrowDataType::Struct(children) = data.data_type() {
863            for child in children {
864                assert!(
865                    child.metadata().get(PARQUET_FIELD_ID_KEY).is_none(),
866                    "non-histogram sub-field {} must not get a field id",
867                    child.name()
868                );
869            }
870        }
871    }
872
873    #[test]
874    fn test_maybe_wrap_schema_no_struct_unchanged() {
875        let schema: Arc<Schema> = Arc::new(Schema::new(vec![
876            Field::new(
877                "ts",
878                ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
879                false,
880            ),
881            Field::new("v", ArrowDataType::Float64, true),
882        ]));
883        let wrapped = maybe_wrap_schema(&schema).unwrap();
884        assert!(
885            Arc::ptr_eq(&wrapped, &schema),
886            "a schema without any struct column must be returned unchanged"
887        );
888    }
889
890    /// Writes `schema` through `maybe_wrap_schema` and a real parquet
891    /// [`ArrowWriter`], then returns the arrow schema read back from the file
892    /// footer. This proves the `greptime.histogram` extension and the nested
893    /// `PARQUET:field_id`s actually land on disk, not just in memory.
894    ///
895    /// `maybe_wrap_schema` is exactly what the SST parquet writer hands to
896    /// `AsyncArrowWriter` (see `writer.rs`); the sync [`ArrowWriter`] shares
897    /// the same arrow-to-parquet schema conversion, so the footer it emits is
898    /// the on-disk contract this change introduces. An empty batch suffices
899    /// because the parquet footer always carries the schema.
900    fn parquet_footer_arrow_schema(schema: &SchemaRef) -> SchemaRef {
901        use ::parquet::arrow::ArrowWriter;
902        use ::parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
903        use ::parquet::file::properties::WriterProperties;
904        use bytes::Bytes;
905
906        let wrapped = maybe_wrap_schema(schema).unwrap();
907        let mut bytes = Vec::new();
908        let props = WriterProperties::builder().build();
909        let mut writer = ArrowWriter::try_new(&mut bytes, wrapped.clone(), Some(props)).unwrap();
910        writer
911            .write(&RecordBatch::new_empty(wrapped.clone()))
912            .unwrap();
913        writer.close().unwrap();
914
915        ParquetRecordBatchReaderBuilder::try_new(Bytes::from(bytes))
916            .unwrap()
917            .schema()
918            .clone()
919    }
920
921    #[test]
922    fn test_maybe_wrap_schema_survives_parquet_roundtrip() {
923        // On-disk contract: after writing through the parquet writer path, the
924        // footer still carries the greptime.histogram extension and every
925        // nested (sub-field + list-element) PARQUET:field_id.
926        let schema = Arc::new(Schema::new(vec![
927            Field::new(
928                "greptime_timestamp",
929                ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
930                false,
931            ),
932            histogram_field(greptime_native_histogram(), 3),
933        ]));
934
935        let on_disk = parquet_footer_arrow_schema(&schema);
936        let hist = on_disk
937            .field_with_name(greptime_native_histogram())
938            .expect("histogram field present");
939        assert_histogram_stamped(hist, 3);
940    }
941
942    #[test]
943    fn test_parquet_roundtrip_recognizes_histogram_by_type() {
944        // The persisted type, rather than a process-local configured name,
945        // identifies native histograms across upgrades and prefix changes.
946        let schema = Arc::new(Schema::new(vec![
947            Field::new(
948                "ts",
949                ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
950                false,
951            ),
952            histogram_field("custom_histogram", 9),
953        ]));
954
955        let on_disk = parquet_footer_arrow_schema(&schema);
956        let hist = on_disk.field_with_name("custom_histogram").unwrap();
957        assert_histogram_stamped(hist, 9);
958    }
959
960    #[test]
961    fn test_maybe_wrap_schema_overflows_return_error() {
962        // A column id of 12_582_912 makes the derived sub-field id overflow
963        // i32 (BASE + column_id*64 == i32::MAX + 1). The write path must
964        // surface this as an error rather than silently dropping the field
965        // id, wrapping, or panicking.
966        let schema = Arc::new(Schema::new(vec![
967            Field::new(
968                "greptime_timestamp",
969                ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
970                false,
971            ),
972            histogram_field(greptime_native_histogram(), 12_582_912),
973        ]));
974        let err = maybe_wrap_schema(&schema).unwrap_err();
975        assert!(
976            matches!(
977                err,
978                crate::error::Error::InvalidNativeHistogramSubfield { .. }
979            ),
980            "expected InvalidNativeHistogramSubfield, got {:?}",
981            err
982        );
983    }
984
985    #[test]
986    fn test_maybe_wrap_schema_missing_field_id_returns_error() {
987        // The parent column's PARQUET:field_id namespaces every sub-field id.
988        // If it is absent (e.g. a histogram struct handed to the writer
989        // without the write path's stamping), the writer must fail loudly
990        // rather than silently namespace under column 0, which would collide
991        // with that column's nested ids.
992        use common_query::native_histogram::native_histogram_value_type;
993        use datatypes::data_type::DataType;
994
995        let field = Field::new(
996            greptime_native_histogram(),
997            native_histogram_value_type().as_arrow_type(),
998            true,
999        );
1000        assert!(
1001            field.metadata().get(PARQUET_FIELD_ID_KEY).is_none(),
1002            "fixture must not carry a field id"
1003        );
1004        let schema = Arc::new(Schema::new(vec![field]));
1005        let err = maybe_wrap_schema(&schema).unwrap_err();
1006        assert!(
1007            matches!(
1008                err,
1009                crate::error::Error::InvalidNativeHistogramFieldId { .. }
1010            ),
1011            "expected InvalidNativeHistogramFieldId, got {:?}",
1012            err
1013        );
1014    }
1015
1016    #[test]
1017    fn test_maybe_wrap_schema_field_id_above_i32_max_returns_error() {
1018        // `with_field_id` serializes the column id from a u32, so a valid id
1019        // above i32::MAX (e.g. u32::MAX) must not be silently parsed as a
1020        // failed i32 and collapsed onto column 0's nested ids. It must
1021        // surface a checked-conversion error instead.
1022        let schema = Arc::new(Schema::new(vec![
1023            Field::new(
1024                "greptime_timestamp",
1025                ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
1026                false,
1027            ),
1028            histogram_field(greptime_native_histogram(), u32::MAX),
1029        ]));
1030        let err = maybe_wrap_schema(&schema).unwrap_err();
1031        assert!(
1032            matches!(
1033                err,
1034                crate::error::Error::InvalidNativeHistogramFieldId { .. }
1035            ),
1036            "expected InvalidNativeHistogramFieldId, got {:?}",
1037            err
1038        );
1039    }
1040
1041    fn json2_v2_test_type() -> ArrowDataType {
1042        ArrowDataType::Struct(
1043            vec![
1044                Arc::new(Field::new("active", ArrowDataType::Boolean, true)),
1045                Arc::new(Field::new("hot", ArrowDataType::Int64, true)),
1046                Arc::new(Field::new("name", ArrowDataType::Utf8, true)),
1047            ]
1048            .into(),
1049        )
1050    }
1051
1052    /// Validates the persisted-format foundation for the JSON2 v2 remainder.
1053    ///
1054    /// JSON2 will store `!__remainder__!` as a nested Variant child of its root
1055    /// Struct. Before enabling that layout in production, this test ensures the
1056    /// SST schema wrapper and Arrow writer preserve the Variant extension,
1057    /// encode the Parquet Variant logical type, and round-trip the values
1058    /// without changing the surrounding Struct.
1059    #[tokio::test]
1060    async fn test_nested_variant_survives_sst_writer_schema_roundtrip()
1061    -> Result<(), Box<dyn std::error::Error>> {
1062        let json: ArrayRef = Arc::new(StringArray::from(vec![
1063            Some(r#"{}"#),
1064            Some(r#"{"name":"Alice","active":true}"#),
1065            Some(r#"{"nested":{"count":42},"items":[1,"two",null]}"#),
1066            Some(r#"{"\u5b57\u6bb5":"\u503c"}"#),
1067            None,
1068        ]));
1069        let remainder = json_to_variant(&json)?;
1070        let remainder_field = remainder.field("!__remainder__!");
1071        let remainder_array = ArrayRef::from(remainder);
1072        let hot_field = Field::new("hot", ArrowDataType::Int64, true);
1073        let data_array = Arc::new(StructArray::new(
1074            vec![remainder_field.clone(), hot_field.clone()].into(),
1075            vec![
1076                remainder_array,
1077                Arc::new(Int64Array::from(vec![
1078                    Some(1),
1079                    Some(2),
1080                    Some(3),
1081                    Some(4),
1082                    None,
1083                ])),
1084            ],
1085            None,
1086        ));
1087        let data_field = Field::new(
1088            "data",
1089            ArrowDataType::Struct(vec![remainder_field, hot_field].into()),
1090            true,
1091        )
1092        .with_extension_type(Json2ExtensionType::default());
1093        let schema = Arc::new(Schema::new(vec![data_field]));
1094        let source = RecordBatch::try_new(schema.clone(), vec![data_array])?;
1095
1096        let wrapped = maybe_wrap_schema(&schema)?;
1097        let mut buffer = Vec::new();
1098        let mut writer = AsyncArrowWriter::try_new(&mut buffer, wrapped, None)?;
1099        writer.write(&source).await?;
1100        writer.close().await?;
1101
1102        let builder = ParquetRecordBatchReaderBuilder::try_new(bytes::Bytes::from(buffer))?;
1103        let parquet_remainder =
1104            &builder.parquet_schema().root_schema().get_fields()[0].get_fields()[0];
1105        assert_eq!(
1106            parquet_remainder.get_basic_info().logical_type_ref(),
1107            Some(&LogicalType::variant(None))
1108        );
1109
1110        let ArrowDataType::Struct(children) = builder.schema().field_with_name("data")?.data_type()
1111        else {
1112            unreachable!();
1113        };
1114        assert!(children[0].has_valid_extension_type::<VariantType>());
1115
1116        let mut reader = builder.build()?;
1117        let result = reader.next().unwrap()?;
1118        assert_eq!(source, result);
1119        let result_field = result.schema().field(0).clone();
1120        let result = result
1121            .column(0)
1122            .as_any()
1123            .downcast_ref::<StructArray>()
1124            .unwrap();
1125        VariantArray::try_new(result.column(0))?;
1126        let result: ArrayRef = Arc::new(result.clone());
1127        let result =
1128            JsonArray::from(&result).project_to_v2(&result_field, &json2_v2_test_type())?;
1129        assert_eq!(
1130            json!({"active": true, "hot": 2, "name": "Alice"}),
1131            JsonArray::from(&result).try_get_value(1)?
1132        );
1133        Ok(())
1134    }
1135
1136    /// Ensures future readers retain compatibility with the first JSON2 v2 layout.
1137    #[test]
1138    fn test_read_json2_v2_fixture() -> Result<(), Box<dyn std::error::Error>> {
1139        let bytes = bytes::Bytes::from_static(include_bytes!("../test-data/json2-v2.parquet"));
1140        let builder = ParquetRecordBatchReaderBuilder::try_new(bytes)?;
1141        let field = builder.schema().field(0).clone();
1142        assert!(Json2PhysicalLayout::try_from_root(&field)?.is_version_2());
1143
1144        let batch = builder.build()?.next().unwrap()?;
1145        let data = batch
1146            .column(0)
1147            .as_any()
1148            .downcast_ref::<StructArray>()
1149            .unwrap();
1150        VariantArray::try_new(data.column(0))?;
1151        let data: ArrayRef = Arc::new(data.clone());
1152        let data = JsonArray::from(&data).project_to_v2(&field, &json2_v2_test_type())?;
1153        assert_eq!(
1154            json!({"active": true, "hot": 2, "name": "Alice"}),
1155            JsonArray::from(&data).try_get_value(1)?
1156        );
1157        Ok(())
1158    }
1159}