diff --git a/docs/formats/mito-samples.md b/docs/formats/mito-samples.md index d5127060b92..a185fdbf036 100644 --- a/docs/formats/mito-samples.md +++ b/docs/formats/mito-samples.md @@ -38,8 +38,8 @@ the block descriptors: its `identity_encoding` value is the older part is first read. It shares artifact conventions with [Narthex series-index format](mito-series.md). -Samples store nullable Float64 fields, timestamps, sequences, and operation types -in single-series blocks bounded by rows and decoded bytes. +Samples store nullable Float64 and native histogram fields, timestamps, sequences, +and operation types in single-series blocks bounded by rows and decoded bytes. ## Artifact manifest @@ -99,7 +99,9 @@ signed i64 counts since the Unix epoch in that unit. There is no dataset-relativ origin, unit conversion, or timezone in the file. The timestamp is non-null. The field list records the build-time region field schema in metadata order. -Require 1..=1,024 fields, each with `type = "float64"` and `nullable = true`. +Require 1..=1,024 fields, each with `type` `"float64"` or `"native_histogram"` and +`nullable = true`. `native_histogram` is the canonical nullable +`greptime_native_histogram` Arrow struct, the same type the Parquet path stores. A non-nullable source Float64 field is represented by this same nullable logical type with no null values. Sparse logical-table fields may be entirely null. Timestamp and field IDs must be distinct. All output names must be unique, @@ -107,7 +109,7 @@ including the internal names below. Tags are not sample fields and are not store The stored logical Arrow schema is `__table_id: UInt32`, `__tsid: UInt64`, the timestamp column with its recorded unit, `__sequence: UInt64`, `__op_type: UInt8`, -then nullable Float64 fields in manifest order, and finally +then the nullable value fields in manifest order, and finally `__primary_key: Binary` naming the exact key of the block that produced each row. The five internal columns and `__primary_key` are non-null; value fields stay nullable, as the manifest declares them. `__table_id`/`__tsid` are the coarse, @@ -210,9 +212,18 @@ N * (8 timestamp + 8 sequence + 1 operation + 8 * F values) + F * ceil(N / 8) validity bytes ``` -Require this to be at most 262,144 bytes. Count all manifest fields, including -omitted/all-null fields, and reserve validity bytes even for all-valid fields. -This is a bound on decoded column buffers, not total allocator usage or RSS. +Require this to be at most 262,144 bytes. A native histogram field counts as one +8-byte value per row here, so the formula does not bound its decoded buffers: its +18 struct children and bucket lists are bounded only by its chunk, and the reader +reserves memory for them from the chunk header (see encoding 8). A +writer also ends a block before a histogram chunk's encoded size bound would exceed +the 1 MiB chunk limit: 1 byte plus 11 bytes per struct child and per list item for +each row, and 16 bytes plus 64 bytes per child and the validity bytes for the +chunk. A sample that exceeds the limit on its own is rejected when it is written +to a Narthex region. Count all manifest fields, including omitted/all-null +fields, and reserve validity bytes even for all-valid fields. +Without histogram fields, this is a bound on decoded column buffers, not total +allocator usage or RSS. The effective row cap is the largest integer satisfying both limits: 8,192 for one field and 31 for 1,024 fields. Encoded buffers and metadata have separate bounds below. Increasing the reader maximum requires an explicit compatibility @@ -476,6 +487,7 @@ namespaces as well. Never reuse an assigned ID with a different meaning. | Column encoding | 5 | Nullable Float64 XOR | | Column encoding | 6 | Constant operation type | | Column encoding | 7 | Raw operation types | +| Column encoding | 8 | Native histogram struct, column by child | | Metadata encoding | 1 | Leaf/internal page layout above | | Compression | 0 | Raw encoded bytes | | Compression | 1 | Zstd frame | @@ -539,6 +551,61 @@ scatter according to validity. Preserve all bits, including signed zero, NaN payloads, infinities, and subnormals. Null and NaN are distinct. The unspecified value-buffer bits behind nulls are not part of the logical preservation contract. +### Native histogram encoding 8 + +```text +child_count +child_kinds # 1 Float64, 2 Int32, 3 Int64, 4 Timestamp(ms); + # 0x10 | kind for a list +list_items # items of all valid lists in the chunk +validity # only when the descriptor null count is nonzero +per child, in struct order: + scalar: section(row_count values) + list: section(row_count lengths, null for a null list), then + section(list item values) unless the child has no items +section(n): + null_count + unless null_count == n: + byte_length + body # encoding 5 over the n values +``` + +The struct order is fixed. The header records only child kinds, so children of the +same kind, such as `zero_threshold` and `sum`, are told apart by position alone: + +| # | Child | Kind | +| --- | --- | --- | +| 0 | `schema` | Int32 | +| 1 | `zero_threshold` | Float64 | +| 2 | `sum` | Float64 | +| 3 | `reset_hint` | Int32 | +| 4 | `start_timestamp` | Timestamp(ms) | +| 5 | `custom_values` | List of Float64 | +| 6 | `positive_span_offsets` | List of Int32 | +| 7 | `positive_span_lengths` | List of Int32 | +| 8 | `negative_span_offsets` | List of Int32 | +| 9 | `negative_span_lengths` | List of Int32 | +| 10 | `count_i64` | Int64 | +| 11 | `zero_count_i64` | Int64 | +| 12 | `positive_buckets_i64` | List of Int64 | +| 13 | `negative_buckets_i64` | List of Int64 | +| 14 | `count_f64` | Float64 | +| 15 | `zero_count_f64` | Float64 | +| 16 | `positive_buckets_f64` | List of Float64 | +| 17 | `negative_buckets_f64` | List of Float64 | + +A chunk holds every row of the block, null rows included, one child after another. +Values map to u64 before encoding 5: Float64 keeps its bit pattern; integers and +timestamps are ZigZag-mapped. A null list has no items; the item section holds the +items of the valid lists in row order. The descriptor's null count is the struct's +own null count, and the validity bitmap follows the rules of encoding 5. + +Child count and kinds must match the manifest field's struct type exactly, so a +chunk is never decoded as another type. `list_items` must equal the lengths read and +must not exceed 1,048,576. The reader reserves memory from `row_count`, the child +count and `list_items` before it decodes a chunk. All-null fields have no descriptor +or payload, as for Float64. + ### Operation encodings 6 and 7 Operation values are u8: 0 delete, 1 put, matching Mito's current `OpType` values. @@ -560,8 +627,10 @@ subject to the same block bound even when chunks are omitted. Unknown file versions, depths, reserved fields, roles, or metadata codecs fail open/read explicitly. Column role must agree with its encoding: time 1/2, -sequence 3/4, Float64 5, operation 6/7. An unknown column encoding or compression -can be skipped if its chunk is not needed, but attempting to decode it returns +sequence 3/4, Float64 5, native histogram 8, operation 6/7. A value chunk's known +encoding must also be the one its manifest field type is stored with. An unknown +column encoding or compression can be skipped if its chunk is not needed, but +attempting to decode it returns an unsupported-codec error. Known encodings assigned to a different role are invalid metadata, even for an unprojected column. Unknown fields or malformed references must not be interpreted as omitted all-null columns. diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index f5d73705d95..08a6a4e41a2 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -108,7 +108,7 @@ pending. DDL cancellation retains its existing scheduling fence and priority. compaction-window width and SST summaries keyed by aligned start in both catalogs and Parquet footers. - **Local index cache**: startup checks a root layout version before workers start; missing or incompatible versions reset the whole rebuildable cache, including catalogs and range indexes. Samples use one generation directory; source SST identity stays in metadata. - **Columnar samples**: `series_index/samples.rs` implements opt-in sample artifacts, - including nullable Float64 fields and preserved sequence/delete rows. Its wire + including nullable Float64 and native histogram fields and preserved sequence/delete rows. Its wire contract is `docs/formats/mito-samples.md`; time/ID bounds may overlap across leaves and parts. Both columnar backends share cancellation-safe output ownership in `series_index/artifact_writer.rs`. Format readers do not apply query visibility; the prepared-source adapter applies visibility and the existing merge/dedup pipeline. Eligible sample merges use identity-only keys and omit tag columns; candidates retain memory-accounted series batch/row labels, and the raw adapter attaches explicit labels with region-qualified identities. Scanner preflight declares that representation so lazy streams and planned frames agree. Non-separable tag/sample residuals retain the full flat schema. Manual reconciliation covers all snapshot SSTs regardless of maintenance eligibility, but retains the soft disk limit. Manual builds validate columnar sample and tag schemas before reuse. Columnar reconciliation consolidates snapshot SSTs into UTC-day sample generations; catalogs record all source IDs. Grouped reads require complete daily coverage and all sources still visible, open each artifact once, and fall back for source-sequence-pruned scans. SST replacement invalidates a whole affected generation; catalog publication and reader handles govern retirement. diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index 5f9c224a3e2..44df0464faf 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -90,6 +90,205 @@ async fn test_narthex_sparse_upsert_after_adding_nullable_tag() -> WhateverResul check_sparse_upsert_after_adding_nullable_tag("narthex").await } +/// A Narthex region refuses a native histogram sample too large for one samples chunk before it +/// accepts the write, so flushes never meet a sample they cannot store. +#[tokio::test] +async fn test_narthex_rejects_oversized_histogram_sample() -> WhateverResult<()> { + use api::greptime_proto::io::prometheus::write::v2::histogram::Count; + use api::greptime_proto::io::prometheus::write::v2::{BucketSpan, Histogram}; + use api::v1::{Row, Value}; + use common_query::native_histogram::{ + encode_native_histogram, native_histogram_column_schema, native_histogram_value_type, + }; + use store_api::region_request::RegionPutRequest; + + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let mut request = sparse_metric_create_request("narthex"); + let field = request + .column_metadatas + .iter_mut() + .find(|c| c.semantic_type == SemanticType::Field) + .unwrap(); + field.column_schema = ColumnSchema::new( + field.column_schema.name.clone(), + native_histogram_value_type().clone(), + true, + ); + let field = field.column_schema.name.clone(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await?; + let metadata = engine.get_region(region_id).unwrap().metadata(); + let key = new_sparse_primary_key(&["api"], &metadata, 42, 7); + let mut histogram_schema = native_histogram_column_schema().unwrap(); + histogram_schema.column_name = field; + let put = |buckets: u32| { + let mut deltas = vec![0; buckets as usize]; + deltas[0] = 1; + // Custom buckets: exponential bucket indexes are bounded, custom bounds are not. + let histogram = Histogram { + schema: -53, + custom_values: (1..buckets).map(f64::from).collect(), + count: Some(Count::CountInt(u64::from(buckets))), + positive_spans: vec![BucketSpan { + offset: 0, + length: buckets, + }], + positive_deltas: deltas, + timestamp: 1000, + ..Default::default() + }; + let schema = vec![ + api::v1::ColumnSchema { + column_name: "__primary_key".into(), + datatype: ColumnDataType::Binary as i32, + semantic_type: SemanticType::Tag as i32, + ..Default::default() + }, + api::v1::ColumnSchema { + column_name: "ts".into(), + datatype: ColumnDataType::TimestampMillisecond as i32, + semantic_type: SemanticType::Timestamp as i32, + ..Default::default() + }, + histogram_schema.clone(), + ]; + let values = [ + ValueData::BinaryValue(key.clone()), + ValueData::TimestampMillisecondValue(1000), + encode_native_histogram(&histogram).unwrap(), + ] + .into_iter() + .map(|value| Value { + value_data: Some(value), + }) + .collect(); + RegionRequest::Put(RegionPutRequest { + rows: Rows { + schema, + rows: vec![Row { values }], + }, + hint: Some(WriteHint { + primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse.into(), + }), + skip_wal: false, + partition_expr_version: None, + }) + }; + let Err(error) = engine.handle_request(region_id, put(100_000)).await else { + panic!("an oversized histogram sample must be refused"); + }; + assert!(error.to_string().contains("chunk limit"), "{error}"); + engine.handle_request(region_id, put(8)).await?; + test_util::flush_region(&engine, region_id, None).await; + let rows = RecordBatches::try_collect( + engine + .scan_to_stream(region_id, ScanRequest::default()) + .await?, + ) + .await?; + assert_eq!(1, rows.iter().map(|b| b.num_rows()).sum::()); + Ok(()) +} + +/// The bulk path refuses an oversized native histogram sample before its WAL entry or memtable +/// write, while a sample that fits takes the same path to the memtable and a flushed file. +#[tokio::test] +async fn test_narthex_bulk_rejects_oversized_histogram_sample() -> WhateverResult<()> { + use common_query::native_histogram::native_histogram_value_type; + use datatypes::arrow::array::Array; + + use crate::series_index::samples::{TestHistogram, histogram_array}; + + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let mut request = sparse_metric_create_request("narthex"); + let table_dir = request.table_dir.clone(); + let field = request + .column_metadatas + .iter_mut() + .find(|c| c.semantic_type == SemanticType::Field) + .unwrap(); + field.column_schema = ColumnSchema::new( + field.column_schema.name.clone(), + native_histogram_value_type().clone(), + true, + ); + let field = field.column_schema.name.clone(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await?; + let metadata = engine.get_region(region_id).unwrap().metadata(); + let key = new_sparse_primary_key(&["api"], &metadata, 42, 7); + let bulk = |buckets: u32, ts: i64| { + let histogram = histogram_array(&[Some(TestHistogram { + schema: -53, + custom_values: Some((1..buckets).map(f64::from).collect()), + positive_spans: vec![(0, buckets as i32)], + floats: Some((f64::from(buckets), 0.0, vec![1.0; buckets as usize], vec![])), + ..Default::default() + })]); + let schema = Arc::new(Schema::new(vec![ + Field::new("__primary_key", DataType::Binary, false), + Field::new( + "ts", + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new(&field, histogram.data_type().clone(), true), + ])); + let payload = DfRecordBatch::try_new( + schema, + vec![ + Arc::new(datatypes::arrow::array::BinaryArray::from_iter_values([ + key.as_slice(), + ])) as ArrayRef, + Arc::new(TimestampMillisecondArray::from_iter_values([ts])), + Arc::new(histogram), + ], + ) + .unwrap(); + let (schema, record_batch) = encode_to_flight_data(payload.clone()); + RegionRequest::BulkInserts(RegionBulkInsertsRequest { + skip_wal: false, + region_id, + payload, + raw_data: ArrowIpc { + schema: schema.data_header, + data_header: record_batch.data_header, + payload: record_batch.data_body, + }, + partition_expr_version: None, + aligned_schema_version: None, + }) + }; + let Err(error) = engine.handle_request(region_id, bulk(100_000, 1000)).await else { + panic!("an oversized histogram sample must be refused"); + }; + assert!(error.to_string().contains("chunk limit"), "{error}"); + engine.handle_request(region_id, bulk(8, 2000)).await?; + let rows = |engine: crate::engine::MitoEngine| async move { + let batches = RecordBatches::try_collect( + engine + .scan_to_stream(region_id, ScanRequest::default()) + .await + .unwrap(), + ) + .await + .unwrap(); + batches.iter().map(|b| b.num_rows()).sum::() + }; + // The replayed WAL holds the accepted sample only. + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + assert_eq!(1, rows(engine.clone()).await); + test_util::flush_region(&engine, region_id, None).await; + assert_eq!(1, rows(engine.clone()).await); + Ok(()) +} + #[tokio::test] async fn test_narthex_series_index_survives_added_label() -> WhateverResult<()> { let reads = Arc::new(std::sync::Mutex::new(Vec::new())); diff --git a/src/mito2/src/read/series_scan.rs b/src/mito2/src/read/series_scan.rs index d8924737bcf..015c0f8fd36 100644 --- a/src/mito2/src/read/series_scan.rs +++ b/src/mito2/src/read/series_scan.rs @@ -320,8 +320,8 @@ impl SeriesScan { .is_some_and(|context| context.format == crate::config::SeriesIndexFormat::Columnar) } - /// Whether every selected *field* is a `Float64`, which is all the columnar prepared reader - /// serves. + /// Whether every selected *field* is a `Float64` or a native histogram struct, which is all the + /// columnar prepared reader serves. /// /// Only field columns count: the projection also carries tags and the time index, and those are /// no part of the samples the prepared reader hands over. Checking them here would send an @@ -338,7 +338,10 @@ impl SeriesScan { && column.semantic_type == SemanticType::Field }) }) - .all(|output| output.data_type == ConcreteDataType::float64_datatype()) + .all(|output| { + output.data_type == ConcreteDataType::float64_datatype() + || is_native_histogram_value_type(&output.data_type) + }) } /// Returns whether raw series come from the columnar prepared source. @@ -475,11 +478,11 @@ impl SeriesScan { let selected = input.mapper.output_schema(); let mut fields = Vec::new(); let mut specs = Vec::new(); - // The columnar prepared reader serves `Float64` fields only. A selection carrying another - // kind the raw path supports - a native histogram struct, today - is read by the ordinary - // scan instead: the columnar samples are an artifact beside the SST rows, so the same - // sources are still reachable, and the frame schema and ordering follow the reader that - // actually answers. + // The columnar prepared reader serves `Float64` and native histogram fields. A selection + // carrying another kind the raw path supports - a numeric field it casts - is read by the + // ordinary scan instead: the columnar samples are an artifact beside the SST rows, so the + // same sources are still reachable, and the frame schema and ordering follow the reader + // that actually answers. let columnar_fields_supported = self.columnar_fields_supported(); for output in selected.column_schemas() { let Some(column) = metadata.column_metadatas.iter().find(|column| { diff --git a/src/mito2/src/series_index/samples.rs b/src/mito2/src/series_index/samples.rs index 1d0a56fc441..1e7ff392701 100644 --- a/src/mito2/src/series_index/samples.rs +++ b/src/mito2/src/series_index/samples.rs @@ -16,7 +16,10 @@ pub(crate) mod bulk; mod codec; +mod histogram; mod metadata; +#[cfg(test)] +pub(crate) use histogram::tests::{TestHistogram, histogram_array}; pub(crate) mod reader; #[cfg(test)] mod tests; @@ -26,6 +29,7 @@ use std::collections::HashSet; use std::sync::Arc; use async_trait::async_trait; +use common_query::native_histogram::{is_native_histogram_value_type, native_histogram_value_type}; use datatypes::arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit}; use datatypes::data_type::DataType as _; use object_store::ObjectStore; @@ -58,14 +62,61 @@ pub(crate) fn validate_narthex_metadata( )?; for column in metadata.field_columns() { require( - column.column_schema.data_type.as_arrow_type() == DataType::Float64 - && column.column_schema.is_nullable(), - "Narthex samples require nullable Float64 fields", + ValueColumn::new(column).is_ok() && column.column_schema.is_nullable(), + "Narthex samples require nullable Float64 or native histogram fields", )?; } Ok(()) } +/// Rejects native histogram samples a Narthex region could not store, before the write is +/// accepted: every sample must fit one samples chunk on its own. +pub(crate) fn check_histogram_rows( + metadata: &store_api::metadata::RegionMetadata, + rows: &api::v1::Rows, +) -> Result<()> { + use api::v1::value::ValueData; + + for (index, column) in rows.schema.iter().enumerate() { + if !metadata + .column_by_name(&column.column_name) + .is_some_and(|c| is_native_histogram_value_type(&c.column_schema.data_type)) + { + continue; + } + for row in &rows.rows { + let Some(ValueData::StructValue(value)) = + row.values.get(index).and_then(|v| v.value_data.as_ref()) + else { + continue; + }; + let list_items = value + .items + .iter() + .map(|item| match &item.value_data { + Some(ValueData::ListValue(list)) => list.items.len(), + _ => 0, + }) + .sum(); + histogram::check_sample_size(value.items.len(), list_items)?; + } + } + Ok(()) +} + +/// [`check_histogram_rows`] for a bulk write batch. +pub(crate) fn check_histogram_batch( + batch: &datatypes::arrow::record_batch::RecordBatch, +) -> Result<()> { + use datatypes::arrow::array::AsArray; + + batch + .columns() + .iter() + .filter_map(|column| column.as_struct_opt()) + .try_for_each(histogram::check_array_sample_sizes) +} + const VERSION: u32 = 1; const MANIFEST_LIMIT: usize = 64 * 1024 * 1024; const MAX_ROWS: usize = 8192; @@ -167,6 +218,51 @@ struct ValueColumn { data_type: String, nullable: bool, } +const FLOAT64_TYPE: &str = "float64"; +const NATIVE_HISTOGRAM_TYPE: &str = "native_histogram"; +/// Sample column encoding ID of a nullable Float64 field. +const FLOAT64_ENCODING: u16 = 5; +impl ValueColumn { + fn new(column: &store_api::metadata::ColumnMetadata) -> Result { + let data_type = &column.column_schema.data_type; + let data_type = if data_type.as_arrow_type() == DataType::Float64 { + FLOAT64_TYPE + } else if is_native_histogram_value_type(data_type) { + NATIVE_HISTOGRAM_TYPE + } else { + return Err(invalid( + "samples support only Float64 and native histogram fields", + )); + }; + Ok(Self { + column_id: column.column_id, + name: column.column_schema.name.clone(), + data_type: data_type.to_string(), + nullable: true, + }) + } + + fn is_histogram(&self) -> bool { + self.data_type == NATIVE_HISTOGRAM_TYPE + } + + /// The only column encoding a chunk of this field may carry. + fn encoding(&self) -> Result { + match self.data_type.as_str() { + FLOAT64_TYPE => Ok(FLOAT64_ENCODING), + NATIVE_HISTOGRAM_TYPE => Ok(histogram::ENCODING), + _ => Err(invalid("unsupported samples field type")), + } + } + + fn arrow_type(&self) -> DataType { + if self.is_histogram() { + native_histogram_value_type().as_arrow_type() + } else { + DataType::Float64 + } + } +} #[derive(Debug, Clone, Serialize, Deserialize)] struct Part { part_id: u32, @@ -238,7 +334,7 @@ impl Manifest { let mut ids = HashSet::from([self.timestamp.column_id]); for field in &self.fields { require( - field.data_type == "float64" && field.nullable, + field.encoding().is_ok() && field.nullable, "unsupported samples field type/nullability", )?; require( @@ -264,7 +360,7 @@ impl Manifest { Field::new(OPERATION, DataType::UInt8, false), ]; fields.extend(self.fields.iter().map(|f| { - crate::sst::with_field_id(Field::new(&f.name, DataType::Float64, true), f.column_id) + crate::sst::with_field_id(Field::new(&f.name, f.arrow_type(), true), f.column_id) })); // Appended after the data fields so stored row indices stay stable. The column is the // artifact's exact-identity marker: readers attribute every row of a batch by the key diff --git a/src/mito2/src/series_index/samples/bulk.rs b/src/mito2/src/series_index/samples/bulk.rs index 29ecebc54f9..457da90d630 100644 --- a/src/mito2/src/series_index/samples/bulk.rs +++ b/src/mito2/src/series_index/samples/bulk.rs @@ -18,7 +18,8 @@ use std::sync::Arc; use bytes::Bytes; use datatypes::arrow::array::{ - Array, ArrayRef, BinaryArray, Float64Array, Int64Array, UInt8Array, UInt64Array, + Array, ArrayRef, AsArray, BinaryArray, Float64Array, Int64Array, StructArray, UInt8Array, + UInt64Array, }; use datatypes::arrow::compute::cast; use datatypes::arrow::datatypes::{DataType, SchemaRef}; @@ -27,6 +28,7 @@ use snafu::ResultExt; use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME; use crate::error::{ComputeArrowSnafu, NewRecordBatchSnafu, Result}; +use crate::series_index::samples::histogram::{self, ChunkBound}; use crate::series_index::samples::{MAX_ROWS, codec, invalid, require}; #[derive(Debug, Clone, Default)] @@ -46,6 +48,7 @@ enum NarthexBulkColumn { Key, Numbers { encoding: u16, bytes: Bytes }, Float { nulls: u32, bytes: Bytes }, + Histogram { nulls: u32, bytes: Bytes }, Operations { encoding: u16, bytes: Bytes }, } @@ -63,13 +66,26 @@ impl NarthexBulkPart { .downcast_ref::() .ok_or_else(|| invalid("narthex bulk key must be binary"))?; require(keys.null_count() == 0, "narthex bulk key must not be null")?; + let histograms = batch + .columns() + .iter() + .filter_map(|column| column.as_struct_opt()) + .collect::>(); let mut start = 0; while start < batch.num_rows() { + // A block also ends before its histogram chunks would outgrow the limit the samples + // writer packs them to, so both decode with the same bounds. + let mut bounds = histogram_bounds(&histograms, &[], start) + .ok_or_else(|| invalid("native histogram sample exceeds the chunk limit"))?; let mut end = start + 1; while end < batch.num_rows() && end - start < MAX_ROWS && keys.value(end) == keys.value(start) { + let Some(next) = histogram_bounds(&histograms, &bounds, end) else { + break; + }; + bounds = next; end += 1; } let slice = batch.slice(start, end - start); @@ -96,6 +112,15 @@ impl NarthexBulkPart { bytes: codec::encode_float(&bits).into(), } } + DataType::Struct(_) => { + let values = array + .as_struct_opt() + .ok_or_else(|| invalid("invalid narthex bulk histogram column"))?; + NarthexBulkColumn::Histogram { + nulls: array.null_count() as u32, + bytes: histogram::encode(values)?.into(), + } + } DataType::Timestamp(_, _) => { require(array.null_count() == 0, "null narthex bulk timestamp")?; let array = cast(array, &DataType::Int64).context(ComputeArrowSnafu)?; @@ -168,6 +193,7 @@ impl NarthexBulkPart { NarthexBulkColumn::Key => 0, NarthexBulkColumn::Numbers { bytes, .. } | NarthexBulkColumn::Float { bytes, .. } + | NarthexBulkColumn::Histogram { bytes, .. } | NarthexBulkColumn::Operations { bytes, .. } => bytes.len(), } }) @@ -191,44 +217,69 @@ impl NarthexBulkPart { } } +/// Each histogram column's chunk bound with row `row` appended to `bounds`, or `None` when a +/// chunk would no longer fit. An empty `bounds` starts a block. +fn histogram_bounds( + histograms: &[&StructArray], + bounds: &[ChunkBound], + row: usize, +) -> Option> { + histograms + .iter() + .enumerate() + .map(|(i, array)| { + bounds + .get(i) + .copied() + .unwrap_or_default() + .with_row(array, row) + }) + .collect() +} + impl NarthexBulkBlock { fn decode(&self, schema: SchemaRef) -> Result { - let columns = self - .columns - .iter() - .zip(schema.fields()) - .map(|(column, field)| { - let array: ArrayRef = match column { - NarthexBulkColumn::Key => { - let array: ArrayRef = Arc::new(BinaryArray::from_iter_values( - std::iter::repeat_n(self.key.as_ref(), self.rows), - )); - cast(&array, field.data_type()).context(ComputeArrowSnafu)? - } - NarthexBulkColumn::Numbers { encoding, bytes } => { - let values = codec::decode_numbers(bytes, *encoding, self.rows)?; - if matches!(field.data_type(), DataType::Timestamp(_, _)) { - let array: ArrayRef = Arc::new(Int64Array::from( - values.into_iter().map(|v| v as i64).collect::>(), + let columns = + self.columns + .iter() + .zip(schema.fields()) + .map(|(column, field)| { + let array: ArrayRef = match column { + NarthexBulkColumn::Key => { + let array: ArrayRef = Arc::new(BinaryArray::from_iter_values( + std::iter::repeat_n(self.key.as_ref(), self.rows), )); cast(&array, field.data_type()).context(ComputeArrowSnafu)? - } else { - Arc::new(UInt64Array::from(values)) } - } - NarthexBulkColumn::Float { bytes, nulls } => Arc::new(Float64Array::from( - codec::decode_float(bytes, self.rows, *nulls)? - .into_iter() - .map(|v| v.map(f64::from_bits)) - .collect::>(), - )), - NarthexBulkColumn::Operations { encoding, bytes } => Arc::new( - UInt8Array::from(codec::decode_operations(bytes, *encoding, self.rows)?), - ), - }; - Ok(array) - }) - .collect::>>()?; + NarthexBulkColumn::Numbers { encoding, bytes } => { + let values = codec::decode_numbers(bytes, *encoding, self.rows)?; + if matches!(field.data_type(), DataType::Timestamp(_, _)) { + let array: ArrayRef = Arc::new(Int64Array::from( + values.into_iter().map(|v| v as i64).collect::>(), + )); + cast(&array, field.data_type()).context(ComputeArrowSnafu)? + } else { + Arc::new(UInt64Array::from(values)) + } + } + NarthexBulkColumn::Float { bytes, nulls } => Arc::new(Float64Array::from( + codec::decode_float(bytes, self.rows, *nulls)? + .into_iter() + .map(|v| v.map(f64::from_bits)) + .collect::>(), + )), + NarthexBulkColumn::Histogram { bytes, nulls } => Arc::new( + histogram::decode(bytes, field.data_type(), self.rows, *nulls)?, + ), + NarthexBulkColumn::Operations { encoding, bytes } => { + Arc::new(UInt8Array::from(codec::decode_operations( + bytes, *encoding, self.rows, + )?)) + } + }; + Ok(array) + }) + .collect::>>()?; RecordBatch::try_new(schema, columns).context(NewRecordBatchSnafu) } } @@ -240,6 +291,72 @@ mod tests { use datatypes::arrow::datatypes::{Field, Schema, TimeUnit}; use store_api::storage::consts::{OP_TYPE_COLUMN_NAME, SEQUENCE_COLUMN_NAME}; + /// Large histograms of one series are cut into blocks whose chunks stay within the samples + /// chunk limit, and the blocks read back as the input. + #[test] + fn narthex_bulk_splits_histogram_blocks_by_chunk_limit() { + use datatypes::arrow::compute::concat_batches; + + use crate::series_index::samples::metadata::CHUNK_LIMIT; + use crate::series_index::samples::{TestHistogram, histogram_array}; + + let histograms = histogram_array( + &(0..24) + .map(|i| { + Some(TestHistogram { + sum: i as f64, + positive_spans: vec![(0, 8000)], + floats: Some(( + 8000.0, + 0.0, + (0..8000).map(|j| ((i * 8000 + j) as f64).sqrt()).collect(), + vec![], + )), + ..Default::default() + }) + }) + .collect::>(), + ); + assert!(histogram::encode(&histograms).unwrap().len() > CHUNK_LIMIT); + let rows = histograms.len(); + let schema = Arc::new(Schema::new(vec![ + Field::new("value", histograms.data_type().clone(), true), + Field::new( + "ts", + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + Field::new(PRIMARY_KEY_COLUMN_NAME, DataType::Binary, false), + Field::new(SEQUENCE_COLUMN_NAME, DataType::UInt64, false), + Field::new(OP_TYPE_COLUMN_NAME, DataType::UInt8, false), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(histograms), + Arc::new(TimestampMillisecondArray::from_iter_values(0..rows as i64)), + Arc::new(BinaryArray::from_iter_values(vec![b"a".as_slice(); rows])), + Arc::new(UInt64Array::from(vec![1; rows])), + Arc::new(UInt8Array::from(vec![1; rows])), + ], + ) + .unwrap(); + let mut part = NarthexBulkPart::default(); + part.push(&batch).unwrap(); + assert!(part.blocks.len() > 1); + for block in part.blocks.iter() { + let NarthexBulkColumn::Histogram { bytes, .. } = &block.columns[0] else { + panic!("the first column is the histogram field"); + }; + assert!(bytes.len() <= CHUNK_LIMIT); + } + let decoded = part + .read(schema.clone()) + .collect::>>() + .unwrap(); + assert_eq!(batch, concat_batches(&schema, &decoded).unwrap()); + } + #[test] fn narthex_bulk_codec_preserves_keys_nulls_sequences_and_float_bits() { let schema = Arc::new(Schema::new(vec![ diff --git a/src/mito2/src/series_index/samples/codec.rs b/src/mito2/src/series_index/samples/codec.rs index bc05f4a7720..a784db96f4c 100644 --- a/src/mito2/src/series_index/samples/codec.rs +++ b/src/mito2/src/series_index/samples/codec.rs @@ -20,10 +20,10 @@ pub(super) use crate::series_index::columnar::codec::{ }; use crate::series_index::samples::{MAX_ROWS, require, unsupported}; -fn zig(x: i64) -> u64 { +pub(super) fn zig(x: i64) -> u64 { ((x as u64) << 1) ^ ((x >> 63) as u64) } -fn unzig(x: u64) -> u64 { +pub(super) fn unzig(x: u64) -> u64 { (x >> 1) ^ (0u64.wrapping_sub(x & 1)) } @@ -151,6 +151,14 @@ pub(super) fn decode_float(bytes: &[u8], rows: usize, nulls: u32) -> Result Result>> { + require(nulls < rows, "invalid samples value count")?; let mut c = Cursor::new(bytes); let bitmap = match c.u8()? { 0 => { @@ -168,7 +176,7 @@ pub(super) fn decode_float(bytes: &[u8], rows: usize, nulls: u32) -> Result Result +//! 1 zero_threshold Float64 10 count_i64 Int64 +//! 2 sum Float64 11 zero_count_i64 Int64 +//! 3 reset_hint Int32 12 positive_buckets_i64 List +//! 4 start_timestamp Timestamp(ms) 13 negative_buckets_i64 List +//! 5 custom_values List 14 count_f64 Float64 +//! 6 positive_span_offsets List 15 zero_count_f64 Float64 +//! 7 positive_span_lengths List 16 positive_buckets_f64 List +//! 8 negative_span_offsets List 17 negative_buckets_f64 List +//! ``` +//! +//! The part-file layout around the chunk is in `docs/formats/mito-samples.md`, "Native +//! histogram encoding 8". + +use std::sync::Arc; + +use datatypes::arrow::array::{ + Array, ArrayRef, AsArray, Float64Array, Int32Array, Int64Array, ListArray, StructArray, + TimestampMillisecondArray, +}; +use datatypes::arrow::buffer::{BooleanBuffer, Buffer, NullBuffer, OffsetBuffer}; +use datatypes::arrow::datatypes::{ + DataType, Fields, Float64Type, Int32Type, Int64Type, TimeUnit, TimestampMillisecondType, +}; + +use crate::error::Result; +use crate::series_index::samples::codec::{self, Cursor, put_varint}; +use crate::series_index::samples::metadata::CHUNK_LIMIT; +use crate::series_index::samples::{MAX_ROWS, invalid, require}; + +/// Sample column encoding ID of a native histogram struct chunk. +pub(super) const ENCODING: u16 = 8; +/// Upper bound of one encoded value, its validity bit included: a full varint plus a bitmap +/// byte, which also covers a section's 8-byte first value. +const VALUE_BOUND: usize = 11; +/// Upper bound of one row's framing: its struct validity bit. +const ROW_FRAMING_BOUND: usize = 1; +/// Upper bound of one child's framing: its kind byte and the count/length varints of at most +/// two nullable sections. +const CHILD_FRAMING_BOUND: usize = 64; +/// Upper bound of the chunk header besides child framing and struct validity: the child count +/// and the list item count. +const HEADER_BOUND: usize = 16; +/// Memory a reader retains per decoded value: the decoded `Option`, its Arrow value and +/// offset, and a copy of both when the block is narrowed to the selected rows. +const DECODED_VALUE_BYTES: usize = 48; + +/// Encodes a native histogram struct column. All rows are encoded, null rows included, and the +/// struct validity is kept apart from the children's own validity. +pub(super) fn encode(array: &StructArray) -> Result> { + let layout = layout(array.fields())?; + let rows = array.len(); + let mut body = Vec::new(); + let mut list_values = 0usize; + for (child, column) in layout.iter().zip(array.columns()) { + match child { + Child::Scalar(scalar) => { + let values = Values::new(*scalar, column.as_ref())?; + put_nullable( + &mut body, + &(0..rows).map(|i| values.get(i)).collect::>(), + ); + } + Child::List(scalar) => { + let list = column + .as_list_opt::() + .ok_or_else(|| invalid("invalid native histogram list child"))?; + let offsets = list.value_offsets(); + let lengths = (0..rows) + .map(|i| { + list.is_valid(i) + .then(|| (offsets[i + 1] - offsets[i]) as u64) + }) + .collect::>(); + put_nullable(&mut body, &lengths); + let values = Values::new(*scalar, list.values().as_ref())?; + // A null list's slot range is not part of its value, so only valid lists + // contribute items. + let items = (0..rows) + .filter(|&i| list.is_valid(i)) + .flat_map(|i| offsets[i] as usize..offsets[i + 1] as usize) + .map(|j| values.get(j)) + .collect::>(); + if !items.is_empty() { + put_nullable(&mut body, &items); + } + list_values += items.len(); + } + } + } + let mut out = vec![ + u8::try_from(layout.len()).map_err(|_| invalid("too many native histogram children"))?, + ]; + out.extend(layout.iter().map(|child| child.code())); + put_varint(&mut out, list_values as u64); + if array.null_count() > 0 { + let start = out.len(); + out.resize(start + rows.div_ceil(8), 0); + for i in (0..rows).filter(|&i| array.is_valid(i)) { + out[start + i / 8] |= 1 << (i % 8); + } + } + out.extend(body); + Ok(out) +} + +/// Memory the reader must account for before decoding a chunk of `rows` rows. +pub(super) fn decoded_bytes(bytes: &[u8], rows: usize) -> Result { + let mut c = Cursor::new(bytes); + let children = c.u8()? as usize; + c.take(children)?; + let list_values = list_value_count(&mut c)?; + Ok((rows * children + list_values) * DECODED_VALUE_BYTES) +} + +/// Decodes a chunk written by [`encode`] as `data_type`, which must be the struct type the chunk +/// was written for. `nulls` is the descriptor's struct-level null count. +pub(super) fn decode( + bytes: &[u8], + data_type: &DataType, + rows: usize, + nulls: u32, +) -> Result { + let DataType::Struct(fields) = data_type else { + return Err(invalid("native histogram chunk requires a struct type")); + }; + let layout = layout(fields)?; + let nulls = nulls as usize; + require( + (1..=MAX_ROWS).contains(&rows) && nulls <= rows, + "invalid native histogram row count", + )?; + let mut c = Cursor::new(bytes); + require( + c.u8()? as usize == layout.len(), + "native histogram child count mismatch", + )?; + for child in &layout { + require( + c.u8()? == child.code(), + "native histogram child kind mismatch", + )?; + } + let mut remaining = list_value_count(&mut c)?; + let validity = if nulls == 0 { + None + } else { + let bitmap = c.take(rows.div_ceil(8))?; + if !rows.is_multiple_of(8) { + require( + bitmap[bitmap.len() - 1] >> (rows % 8) == 0, + "nonzero native histogram validity padding", + )?; + } + let validity = BooleanBuffer::new(Buffer::from(bitmap.to_vec()), 0, rows); + require( + validity.count_set_bits() + nulls == rows, + "native histogram validity count mismatch", + )?; + Some(NullBuffer::new(validity)) + }; + let mut children = Vec::with_capacity(layout.len()); + for (child, field) in layout.iter().zip(fields.iter()) { + let array = match child { + Child::Scalar(scalar) => scalar.build(take_nullable(&mut c, rows)?)?, + Child::List(scalar) => { + let DataType::List(item) = field.data_type() else { + return Err(invalid("native histogram list child requires a list type")); + }; + let lengths = take_nullable(&mut c, rows)?; + let mut offsets = Vec::with_capacity(rows + 1); + offsets.push(0i32); + let mut total = 0usize; + for length in &lengths { + total = total + .checked_add(length.unwrap_or(0) as usize) + .filter(|total| *total <= remaining) + .ok_or_else(|| invalid("native histogram list value count mismatch"))?; + // `remaining` is at most `CHUNK_LIMIT`, so every offset fits `i32`. + offsets.push(total as i32); + } + remaining -= total; + let items = if total == 0 { + Vec::new() + } else { + take_nullable(&mut c, total)? + }; + let list_nulls = lengths + .iter() + .any(Option::is_none) + .then(|| NullBuffer::from_iter(lengths.iter().map(Option::is_some))); + Arc::new( + ListArray::try_new( + item.clone(), + OffsetBuffer::new(offsets.into()), + scalar.build(items)?, + list_nulls, + ) + .map_err(|e| invalid(format!("invalid native histogram list: {e}")))?, + ) + } + }; + children.push(array); + } + require(remaining == 0, "native histogram list value count mismatch")?; + c.end()?; + StructArray::try_new(fields.clone(), children, validity) + .map_err(|e| invalid(format!("invalid native histogram struct: {e}"))) +} + +/// Requires one sample with `children` struct children and `list_items` bucket list items to +/// fit a chunk on its own, which is what lets the writers place every accepted sample. +pub(crate) fn check_sample_size(children: usize, list_items: usize) -> Result<()> { + require( + ChunkBound::default() + .with_bytes(children, row_bytes(children, list_items)) + .is_some(), + "native histogram sample exceeds the Narthex samples chunk limit", + ) +} + +/// Requires every row of a native histogram column to fit a chunk on its own. +pub(crate) fn check_array_sample_sizes(array: &StructArray) -> Result<()> { + (0..array.len()) + .try_for_each(|row| check_sample_size(array.num_columns(), list_items(array, row))) +} + +/// The encoded size bound of a chunk that is still being filled, so a writer can cut a block +/// before its histogram chunk would exceed [`CHUNK_LIMIT`]. +#[derive(Debug, Clone, Copy, Default)] +pub(super) struct ChunkBound { + rows: usize, + bytes: usize, +} + +impl ChunkBound { + /// The bound with `array[row]` appended, or `None` when that row no longer fits the chunk. + pub(super) fn with_row(&self, array: &StructArray, row: usize) -> Option { + self.with_bytes( + array.num_columns(), + row_bytes(array.num_columns(), list_items(array, row)), + ) + } + + fn with_bytes(&self, children: usize, row_bytes: usize) -> Option { + let bytes = self.bytes + row_bytes; + let rows = self.rows + 1; + let chunk = HEADER_BOUND + children * CHILD_FRAMING_BOUND + rows.div_ceil(8) + bytes; + (chunk <= CHUNK_LIMIT).then_some(Self { rows, bytes }) + } +} + +/// Upper bound of the bytes one row adds to a chunk: one value per child, which covers a list's +/// length, one value per list item, and its struct validity bit. +fn row_bytes(children: usize, list_items: usize) -> usize { + ROW_FRAMING_BOUND + VALUE_BOUND * (children + list_items) +} + +/// Items of the valid lists of `array[row]`. +fn list_items(array: &StructArray, row: usize) -> usize { + array + .columns() + .iter() + .filter_map(|column| column.as_list_opt::()) + .filter(|list| list.is_valid(row)) + .map(|list| list.value_length(row) as usize) + .sum() +} + +/// Reads the chunk's total list item count. A writer cuts chunks by [`ChunkBound`], which charges +/// every item [`VALUE_BOUND`] bytes, so a larger count is corrupt rather than merely large. +fn list_value_count(c: &mut Cursor<'_>) -> Result { + let count = c.varint()?; + require( + count <= CHUNK_LIMIT as u64, + "native histogram list value count exceeds limit", + )?; + Ok(count as usize) +} + +/// Writes `values` as a null count followed, unless every value is null, by the byte length +/// and body of encoding 5. +fn put_nullable(out: &mut Vec, values: &[Option]) { + let nulls = values.iter().filter(|v| v.is_none()).count(); + put_varint(out, nulls as u64); + if nulls < values.len() { + let bytes = codec::encode_float(values); + put_varint(out, bytes.len() as u64); + out.extend(bytes); + } +} + +/// Reads `count` values written by [`put_nullable`]. The caller bounds `count`. +fn take_nullable(c: &mut Cursor<'_>, count: usize) -> Result>> { + let nulls = c.varint()?; + require( + nulls <= count as u64, + "native histogram null count exceeds values", + )?; + let nulls = nulls as usize; + if nulls == count { + return Ok(vec![None; count]); + } + let length = usize::try_from(c.varint()?) + .map_err(|_| invalid("native histogram section length overflow"))?; + codec::decode_xor(c.take(length)?, count, nulls) +} + +/// A child value type and its lossless `u64` mapping. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Scalar { + Float64, + Int32, + Int64, + TimestampMillisecond, +} + +impl Scalar { + fn from_arrow(data_type: &DataType) -> Result { + match data_type { + DataType::Float64 => Ok(Self::Float64), + DataType::Int32 => Ok(Self::Int32), + DataType::Int64 => Ok(Self::Int64), + DataType::Timestamp(TimeUnit::Millisecond, None) => Ok(Self::TimestampMillisecond), + other => Err(invalid(format!( + "unsupported native histogram child type {other}" + ))), + } + } + + fn code(self) -> u8 { + match self { + Self::Float64 => 1, + Self::Int32 => 2, + Self::Int64 => 3, + Self::TimestampMillisecond => 4, + } + } + + fn build(self, values: Vec>) -> Result { + let signed = |bits: u64| codec::unzig(bits) as i64; + Ok(match self { + Self::Float64 => Arc::new(Float64Array::from_iter( + values.into_iter().map(|v| v.map(f64::from_bits)), + )), + Self::Int32 => Arc::new(Int32Array::from( + values + .into_iter() + .map(|v| { + v.map(|bits| { + i32::try_from(signed(bits)) + .map_err(|_| invalid("native histogram Int32 value overflow")) + }) + .transpose() + }) + .collect::>>()?, + )), + Self::Int64 => Arc::new(Int64Array::from_iter( + values.into_iter().map(|v| v.map(signed)), + )), + Self::TimestampMillisecond => Arc::new(TimestampMillisecondArray::from_iter( + values.into_iter().map(|v| v.map(signed)), + )), + }) + } +} + +/// Typed access to one child's values as their `u64` mapping. +enum Values<'a> { + Float64(&'a Float64Array), + Int32(&'a Int32Array), + Int64(&'a Int64Array), + TimestampMillisecond(&'a TimestampMillisecondArray), +} + +impl<'a> Values<'a> { + fn new(scalar: Scalar, array: &'a dyn Array) -> Result { + let values = match scalar { + Scalar::Float64 => array.as_primitive_opt::().map(Self::Float64), + Scalar::Int32 => array.as_primitive_opt::().map(Self::Int32), + Scalar::Int64 => array.as_primitive_opt::().map(Self::Int64), + Scalar::TimestampMillisecond => array + .as_primitive_opt::() + .map(Self::TimestampMillisecond), + }; + values.ok_or_else(|| invalid("native histogram child does not match its type")) + } + + fn get(&self, index: usize) -> Option { + match self { + Self::Float64(a) => a.is_valid(index).then(|| a.value(index).to_bits()), + Self::Int32(a) => a + .is_valid(index) + .then(|| codec::zig(i64::from(a.value(index)))), + Self::Int64(a) => a.is_valid(index).then(|| codec::zig(a.value(index))), + Self::TimestampMillisecond(a) => a.is_valid(index).then(|| codec::zig(a.value(index))), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Child { + Scalar(Scalar), + List(Scalar), +} + +impl Child { + fn code(self) -> u8 { + match self { + Self::Scalar(scalar) => scalar.code(), + Self::List(scalar) => 0x10 | scalar.code(), + } + } +} + +fn layout(fields: &Fields) -> Result> { + fields + .iter() + .map(|field| match field.data_type() { + DataType::List(item) => Scalar::from_arrow(item.data_type()).map(Child::List), + other => Scalar::from_arrow(other).map(Child::Scalar), + }) + .collect() +} + +#[cfg(test)] +pub(crate) mod tests { + use common_query::native_histogram::{ + COUNT_F64_FIELD, COUNT_I64_FIELD, COUNTER_RESET_HINT, CUSTOM_BUCKETS_SCHEMA, + CUSTOM_VALUES_FIELD, GAUGE_RESET_HINT, NEGATIVE_BUCKETS_F64_FIELD, + NEGATIVE_BUCKETS_I64_FIELD, NEGATIVE_SPAN_LENGTHS_FIELD, NEGATIVE_SPAN_OFFSETS_FIELD, + NOT_COUNTER_RESET_HINT, POSITIVE_BUCKETS_F64_FIELD, POSITIVE_BUCKETS_I64_FIELD, + POSITIVE_SPAN_LENGTHS_FIELD, POSITIVE_SPAN_OFFSETS_FIELD, RESET_HINT_FIELD, SCHEMA_FIELD, + START_TIMESTAMP_FIELD, SUM_FIELD, ZERO_COUNT_F64_FIELD, ZERO_COUNT_I64_FIELD, + ZERO_THRESHOLD_FIELD, native_histogram_value_type, + }; + use datatypes::arrow::array::new_empty_array; + use datatypes::arrow::compute::concat; + use datatypes::arrow::datatypes::Field; + use datatypes::data_type::DataType as _; + + use super::*; + + /// One histogram row of a test fixture; the count family it carries is the populated one. + #[derive(Debug, Clone, Default)] + pub(crate) struct TestHistogram { + pub(crate) schema: i32, + pub(crate) zero_threshold: f64, + pub(crate) sum: f64, + pub(crate) reset_hint: i32, + pub(crate) start: Option, + pub(crate) custom_values: Option>, + pub(crate) positive_spans: Vec<(i32, i32)>, + pub(crate) negative_spans: Vec<(i32, i32)>, + /// `(count, zero_count, positive deltas, negative deltas)`. + pub(crate) ints: Option<(i64, i64, Vec, Vec)>, + /// `(count, zero_count, positive counts, negative counts)`. + pub(crate) floats: Option<(f64, f64, Vec, Vec)>, + } + + /// Builds the canonical struct column, with null children under a null row as ingestion + /// writes them. + pub(crate) fn histogram_array(rows: &[Option]) -> StructArray { + let DataType::Struct(fields) = native_histogram_value_type().as_arrow_type() else { + unreachable!("the native histogram type is a struct") + }; + let floats = |f: &dyn Fn(&TestHistogram) -> Option| -> ArrayRef { + Arc::new(Float64Array::from_iter( + rows.iter().map(|row| row.as_ref().and_then(f)), + )) + }; + let ints = |f: &dyn Fn(&TestHistogram) -> Option| -> ArrayRef { + Arc::new(Int64Array::from_iter( + rows.iter().map(|row| row.as_ref().and_then(f)), + )) + }; + let int32s = |f: &dyn Fn(&TestHistogram) -> i32| -> ArrayRef { + Arc::new(Int32Array::from_iter( + rows.iter().map(|row| row.as_ref().map(f)), + )) + }; + let children = fields + .iter() + .map(|field| -> ArrayRef { + let list = |f: &dyn Fn(&TestHistogram) -> Option| { + list_array( + field, + &rows + .iter() + .map(|row| row.as_ref().and_then(f)) + .collect::>(), + ) + }; + let spans = |spans: &[(i32, i32)], offsets: bool| -> ArrayRef { + Arc::new(Int32Array::from_iter_values( + spans + .iter() + .map(|(offset, length)| if offsets { *offset } else { *length }), + )) + }; + match field.name().as_str() { + SCHEMA_FIELD => int32s(&|h| h.schema), + RESET_HINT_FIELD => int32s(&|h| h.reset_hint), + ZERO_THRESHOLD_FIELD => floats(&|h| Some(h.zero_threshold)), + SUM_FIELD => floats(&|h| Some(h.sum)), + START_TIMESTAMP_FIELD => Arc::new(TimestampMillisecondArray::from_iter( + rows.iter().map(|row| row.as_ref().and_then(|h| h.start)), + )), + CUSTOM_VALUES_FIELD => list(&|h| { + h.custom_values + .clone() + .map(|v| Arc::new(Float64Array::from(v)) as ArrayRef) + }), + POSITIVE_SPAN_OFFSETS_FIELD => list(&|h| Some(spans(&h.positive_spans, true))), + POSITIVE_SPAN_LENGTHS_FIELD => list(&|h| Some(spans(&h.positive_spans, false))), + NEGATIVE_SPAN_OFFSETS_FIELD => list(&|h| Some(spans(&h.negative_spans, true))), + NEGATIVE_SPAN_LENGTHS_FIELD => list(&|h| Some(spans(&h.negative_spans, false))), + COUNT_I64_FIELD => ints(&|h| h.ints.as_ref().map(|i| i.0)), + ZERO_COUNT_I64_FIELD => ints(&|h| h.ints.as_ref().map(|i| i.1)), + POSITIVE_BUCKETS_I64_FIELD => list(&|h| { + h.ints + .as_ref() + .map(|i| Arc::new(Int64Array::from(i.2.clone())) as ArrayRef) + }), + NEGATIVE_BUCKETS_I64_FIELD => list(&|h| { + h.ints + .as_ref() + .map(|i| Arc::new(Int64Array::from(i.3.clone())) as ArrayRef) + }), + COUNT_F64_FIELD => floats(&|h| h.floats.as_ref().map(|f| f.0)), + ZERO_COUNT_F64_FIELD => floats(&|h| h.floats.as_ref().map(|f| f.1)), + POSITIVE_BUCKETS_F64_FIELD => list(&|h| { + h.floats + .as_ref() + .map(|f| Arc::new(Float64Array::from(f.2.clone())) as ArrayRef) + }), + NEGATIVE_BUCKETS_F64_FIELD => list(&|h| { + h.floats + .as_ref() + .map(|f| Arc::new(Float64Array::from(f.3.clone())) as ArrayRef) + }), + other => unreachable!("unknown native histogram field {other}"), + } + }) + .collect(); + let validity = NullBuffer::from_iter(rows.iter().map(Option::is_some)); + StructArray::new( + fields, + children, + (validity.null_count() > 0).then_some(validity), + ) + } + + fn list_array(field: &Field, rows: &[Option]) -> ArrayRef { + let DataType::List(item) = field.data_type() else { + unreachable!("{} is a list", field.name()) + }; + let mut offsets = vec![0i32]; + for row in rows { + offsets.push(offsets.last().unwrap() + row.as_ref().map_or(0, |a| a.len() as i32)); + } + let parts = rows + .iter() + .flatten() + .map(|a| a.as_ref()) + .collect::>(); + let values = if parts.is_empty() { + new_empty_array(item.data_type()) + } else { + concat(&parts).unwrap() + }; + let validity = NullBuffer::from_iter(rows.iter().map(Option::is_some)); + Arc::new(ListArray::new( + item.clone(), + OffsetBuffer::new(offsets.into()), + values, + (validity.null_count() > 0).then_some(validity), + )) + } + + pub(crate) fn fixture() -> Vec> { + vec![ + // Exponential integer histogram with a negative span offset and a counter reset. + Some(TestHistogram { + schema: 3, + zero_threshold: 0.001, + sum: 12.5, + reset_hint: COUNTER_RESET_HINT.into(), + start: Some(-1_000), + positive_spans: vec![(-2, 2), (3, 1)], + negative_spans: vec![(0, 1)], + ints: Some((7, 1, vec![2, -1, 1], vec![-3])), + ..Default::default() + }), + None, + // Float gauge histogram with no populated bucket at all. + Some(TestHistogram { + sum: -0.0, + reset_hint: GAUGE_RESET_HINT.into(), + floats: Some((0.0, 0.0, vec![], vec![])), + ..Default::default() + }), + // Custom buckets carry their bounds, including +Inf. + Some(TestHistogram { + schema: CUSTOM_BUCKETS_SCHEMA, + sum: 4.25, + reset_hint: NOT_COUNTER_RESET_HINT.into(), + custom_values: Some(vec![0.1, 0.5, f64::INFINITY]), + positive_spans: vec![(0, 3)], + floats: Some((6.0, 0.0, vec![1.0, 2.5, 2.5], vec![])), + ..Default::default() + }), + ] + } + + #[test] + fn histogram_chunk_round_trips_and_names_its_type() { + let array = histogram_array(&fixture()); + let bytes = encode(&array).unwrap(); + let decoded = decode( + &bytes, + array.data_type(), + array.len(), + array.null_count() as u32, + ) + .unwrap(); + assert_eq!(array, decoded); + // One-row slices keep their own offsets: a slice of the custom-bucket row and a slice of + // the null row decode to the same rows. + for row in [3, 1] { + let slice = array.slice(row, 1); + let decoded = decode( + &encode(&slice).unwrap(), + slice.data_type(), + 1, + slice.null_count() as u32, + ) + .unwrap(); + assert_eq!(slice, decoded); + } + + // The chunk is only readable as the struct it was written for. + let DataType::Struct(fields) = array.data_type() else { + unreachable!() + }; + let mut changed = fields + .iter() + .map(|f| f.as_ref().clone()) + .collect::>(); + changed[0] = Field::new(changed[0].name(), DataType::Int64, true); + let error = decode( + &bytes, + &DataType::Struct(changed.into()), + array.len(), + array.null_count() as u32, + ) + .unwrap_err(); + assert!(error.to_string().contains("child kind mismatch"), "{error}"); + let fewer = fields.iter().skip(1).cloned().collect::(); + let error = decode(&bytes, &DataType::Struct(fewer), array.len(), 1).unwrap_err(); + assert!( + error.to_string().contains("child count mismatch"), + "{error}" + ); + // The descriptor's struct null count must agree with the stored validity. + assert!(decode(&bytes, array.data_type(), array.len(), 0).is_err()); + } +} diff --git a/src/mito2/src/series_index/samples/metadata.rs b/src/mito2/src/series_index/samples/metadata.rs index e0cb3a98432..a2cc86f5f6c 100644 --- a/src/mito2/src/series_index/samples/metadata.rs +++ b/src/mito2/src/series_index/samples/metadata.rs @@ -17,7 +17,7 @@ use crate::error::Result; use crate::series_index::samples::codec::{self, Cursor, put_u32, put_u64}; use crate::series_index::samples::{ - Manifest, MetricSeriesId, VERSION, invalid, require, unsupported, valid_rows, + Manifest, MetricSeriesId, VERSION, histogram, invalid, require, unsupported, valid_rows, }; pub(super) const MAGIC: &[u8; 8] = b"GTSAMPLE"; @@ -26,7 +26,7 @@ pub(super) const TRAILER_SIZE: u64 = 120; pub(super) const PAGE_LIMIT: usize = 65536; pub(super) const ROOT_CAPACITY: usize = (PAGE_LIMIT - 12) / 72; /// Largest decoded block payload, and therefore the largest frame a decoder has to decompress. -const CHUNK_LIMIT: usize = 1024 * 1024; +pub(super) const CHUNK_LIMIT: usize = 1024 * 1024; /// Fixed part of a block descriptor, before its 44-byte column descriptors. /// /// The exact series key is not part of it. A descriptor keeps a fixed-size [`KeyRef`] into @@ -515,13 +515,21 @@ impl Block { .ok_or_else(|| invalid("unknown or unordered sample field"))? + next_field; next_field = position + 1; + // A known value encoding must be the one its field's type is stored with, so a + // chunk is never decoded as another kind of value. + if payload.encoding <= histogram::ENCODING { + require( + payload.encoding == manifest.fields[position].encoding()?, + "sample field codec does not match its field type", + )?; + } } - if payload.encoding <= 7 { + if payload.encoding <= histogram::ENCODING { let valid = match role { 1 => matches!(payload.encoding, 1 | 2), 2 => matches!(payload.encoding, 3 | 4), 3 => matches!(payload.encoding, 6 | 7), - 4 => payload.encoding == 5, + 4 => matches!(payload.encoding, 5 | histogram::ENCODING), _ => false, }; require(valid, "sample codec role mismatch")?; diff --git a/src/mito2/src/series_index/samples/reader.rs b/src/mito2/src/series_index/samples/reader.rs index 4e8f6baf145..c79a99cfa03 100644 --- a/src/mito2/src/series_index/samples/reader.rs +++ b/src/mito2/src/series_index/samples/reader.rs @@ -23,6 +23,7 @@ use datatypes::arrow::array::{ ArrayRef, BinaryArray, Float64Array, TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray, TimestampSecondArray, UInt8Array, UInt32Array, UInt64Array, }; +use datatypes::arrow::compute::take; use datatypes::arrow::datatypes::SchemaRef; use datatypes::arrow::record_batch::{RecordBatch, RecordBatchOptions}; use futures::stream::BoxStream; @@ -31,17 +32,17 @@ use snafu::ResultExt; use tokio::sync::OnceCell; use crate::cache::columnar::{self as metadata_cache, MetadataCache}; -use crate::error::{NewRecordBatchSnafu, OpenDalSnafu, Result}; +use crate::error::{ComputeArrowSnafu, NewRecordBatchSnafu, OpenDalSnafu, Result}; use crate::metrics::ColumnarReadMetrics; use crate::series_index::artifact::{ArtifactFormat, SamplesFileHandle}; use crate::series_index::format::{SamplesBatch, SamplesFormatReader, SamplesReadRequest}; use crate::series_index::identity::{ExactSeriesKey, IdentityEncoding}; -use crate::series_index::samples::codec; use crate::series_index::samples::metadata::{ self, Areas, Block, BlockOrder, Bounds, Column, Page, PageReference, Trailer, }; use crate::series_index::samples::{ - MANIFEST_LIMIT, Manifest, MetricSeriesId, TimestampUnit, VERSION, invalid, require, unsupported, + MANIFEST_LIMIT, Manifest, MetricSeriesId, TimestampUnit, VERSION, codec, histogram, invalid, + require, unsupported, }; use crate::sst::parquet::helper::fetch_byte_ranges; @@ -812,7 +813,7 @@ fn load_column_chunk<'a>( 1 => matches!(column.payload.encoding, 1 | 2), 2 => matches!(column.payload.encoding, 3 | 4), 3 => matches!(column.payload.encoding, 6 | 7), - 4 => column.payload.encoding == 5, + 4 => matches!(column.payload.encoding, 5 | histogram::ENCODING), _ => false, }; if !allowed { @@ -964,13 +965,7 @@ async fn read_block( if let Some(reservation) = &reservation { let mut result = reservation.try_grow(bytes); if result.is_err() && !prefetched.buffers.is_empty() { - // Read-ahead must not prevent a block that fits on its own from being read. - // Drop every shared slice and its reservation before retrying, and avoid - // attempting the same window again on the next block. - *prefetched = PrefetchedBlocks { - end: prefetched.end, - ..Default::default() - }; + release_read_ahead(prefetched, &mut scratch.buffers); result = reservation.try_grow(bytes); } result.context(crate::error::ScanMemoryExhaustedSnafu)?; @@ -1087,7 +1082,60 @@ async fn read_block( .get(field - 5) .ok_or_else(|| invalid("unknown sample field"))?; let id = field.column_id; - if let Some(column) = block.columns.iter().find(|c| c.role == 4 && c.id == id) { + let column = block.columns.iter().find(|c| c.role == 4 && c.id == id); + if field.is_histogram() { + let data_type = schema + .field( + projection + .iter() + .position(|&p| p == index) + .ok_or_else(|| invalid("unprojected sample field"))?, + ) + .data_type(); + match column { + Some(column) => { + let mut bytes = + load_column_chunk(&scratch.buffers, column, decoder)?; + // Decoded histograms outgrow their chunk by far more than the + // per-row terms reserved above, so their values are charged + // from the chunk's own counts before they are built. + if let Some(reservation) = &reservation { + let decoded = + histogram::decoded_bytes(bytes, block.rows as usize)?; + if reservation.try_grow(decoded).is_err() { + release_read_ahead(prefetched, &mut scratch.buffers); + reservation + .try_grow(decoded) + .context(crate::error::ScanMemoryExhaustedSnafu)?; + // The release replaced the slices `bytes` borrowed. + bytes = + load_column_chunk(&scratch.buffers, column, decoder)?; + } + } + let array: ArrayRef = Arc::new(histogram::decode( + bytes, + data_type, + block.rows as usize, + column.nulls, + )?); + if selected.len() == array.len() { + array + } else { + take( + &array, + &UInt32Array::from_iter_values( + selected.iter().map(|&i| i as u32), + ), + None, + ) + .context(ComputeArrowSnafu)? + } + } + None => { + datatypes::arrow::array::new_null_array(data_type, selected.len()) + } + } + } else if let Some(column) = column { let values = codec::decode_float( load_column_chunk(&scratch.buffers, column, decoder)?, block.rows as usize, @@ -1250,6 +1298,23 @@ fn merge_read_ranges_into(ranges: &[std::ops::Range], merged: &mut Vec) { + for (offset, bytes) in buffers.iter_mut() { + if prefetched.buffers.contains_key(offset) { + *bytes = bytes::Bytes::copy_from_slice(bytes); + } + } + *prefetched = PrefetchedBlocks { + end: prefetched.end, + ..Default::default() + }; +} + /// A bounded read-ahead window. Byte slices retain the shared fetched allocation; /// the reservation therefore lives until the whole window is replaced or cancelled. #[derive(Default)] diff --git a/src/mito2/src/series_index/samples/tests.rs b/src/mito2/src/series_index/samples/tests.rs index 69afdc6f482..1c1110808d1 100644 --- a/src/mito2/src/series_index/samples/tests.rs +++ b/src/mito2/src/series_index/samples/tests.rs @@ -2651,3 +2651,253 @@ async fn narthex_prepared_discovery_empty_projection_skips_payload() { ); } } + +/// Native histogram fields round-trip through an artifact. A block ends before its histogram +/// chunk would outgrow the chunk limit, and the stored chunk is only readable as the field type +/// the manifest records. +#[tokio::test] +async fn native_histogram_fields_round_trip_and_split_by_chunk_limit() { + use datatypes::arrow::compute::concat; + + use super::histogram::tests::{TestHistogram, fixture, histogram_array}; + + let mut m = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Sparse); + m.column_metadatas + .iter_mut() + .find(|c| c.column_id == 2) + .unwrap() + .column_schema + .data_type = native_histogram_value_type().clone(); + let m = Arc::new(m); + let small = histogram_array(&fixture()); + // Bucket counts whose XOR deltas stay wide, so the rows together encode past one chunk. + let large = histogram_array( + &(0..24) + .map(|i| { + Some(TestHistogram { + sum: i as f64, + positive_spans: vec![(0, 8000)], + floats: Some(( + 8000.0, + 0.0, + (0..8000).map(|j| ((i * 8000 + j) as f64).sqrt()).collect(), + vec![], + )), + ..Default::default() + }) + }) + .collect::>(), + ); + assert!(histogram::encode(&large).unwrap().len() > metadata::CHUNK_LIMIT); + let values = concat(&[&small as &dyn Array, &large]).unwrap(); + let keys = (0..values.len()) + .map(|i| new_sparse_primary_key(&["a", "b"], &m, 1, if i < small.len() { 1 } else { 2 })) + .collect::>(); + let times = (0..small.len() as i64) + .chain(0..large.len() as i64) + .collect::>(); + let input = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("field_0", values.data_type().clone(), true), + Field::new( + "ts", + DataType::Timestamp(datatypes::arrow::datatypes::TimeUnit::Millisecond, None), + false, + ), + Field::new("__primary_key", DataType::Binary, false), + Field::new(SEQUENCE, DataType::UInt64, false), + Field::new(OPERATION, DataType::UInt8, false), + ])), + vec![ + values.clone(), + Arc::new(datatypes::arrow::array::TimestampMillisecondArray::from( + times, + )), + Arc::new(BinaryArray::from_iter_values( + keys.iter().map(Vec::as_slice), + )), + Arc::new(UInt64Array::from(vec![1; values.len()])), + Arc::new(UInt8Array::from(vec![1; values.len()])), + ], + ) + .unwrap(); + let store = store(); + let format = ColumnarSamplesFormat::default(); + // Two input batches, so a block also concatenates rows borrowed from different batches. + let handle = build( + &format, + &store, + m.clone(), + &[input.slice(0, 10), input.slice(10, input.num_rows() - 10)], + ) + .await; + let read = |handle: SamplesFileHandle| { + let store = store.clone(); + let format = format.clone(); + async move { + format + .reader(store, handle) + .await + .unwrap() + .read(request(&["field_0"])) + .unwrap() + .try_collect::>() + .await + } + }; + let batches = read(handle.clone()).await.unwrap(); + assert!( + batches.len() > 2, + "the large series spans more than one block" + ); + let decoded = concat( + &batches + .iter() + .map(|b| b.column(0).as_ref()) + .collect::>(), + ) + .unwrap(); + assert_eq!(&values, &decoded); + + let mut stored = manifest(&store, &handle).await; + stored.fields[0].data_type = FLOAT64_TYPE.to_string(); + let json = serde_json::to_vec(&stored).unwrap(); + store.write(&stored.path(), json.clone()).await.unwrap(); + let mut entry = handle.entry().clone(); + for object in &mut entry.artifact.objects { + if object.path == stored.path() { + object.file_size = json.len() as u64; + } + } + entry.artifact.file_size = entry.artifact.objects.iter().map(|o| o.file_size).sum(); + let (purger, _receiver) = series_index_channel(store.clone()); + let error = read(SamplesFileHandle::new(handle.file_id(), entry, purger)) + .await + .unwrap_err(); + assert!( + error.to_string().contains("does not match its field type"), + "{error}" + ); +} + +/// Read-ahead must not fail a histogram block that fits the pool on its own. The histogram +/// reservation is only known once the chunk header is read, after the block's first reservation. +#[tokio::test] +async fn histogram_reservation_releases_read_ahead() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool, MemoryReservation}; + + #[derive(Debug)] + struct PeakPool { + inner: GreedyMemoryPool, + peak: AtomicUsize, + } + impl std::fmt::Display for PeakPool { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "peak") + } + } + impl MemoryPool for PeakPool { + fn name(&self) -> &str { + "peak" + } + fn grow(&self, reservation: &MemoryReservation, additional: usize) { + self.inner.grow(reservation, additional); + self.peak + .fetch_max(self.inner.reserved(), Ordering::Relaxed); + } + fn shrink(&self, reservation: &MemoryReservation, shrink: usize) { + self.inner.shrink(reservation, shrink); + } + fn try_grow( + &self, + reservation: &MemoryReservation, + additional: usize, + ) -> datafusion::common::Result<()> { + self.inner.try_grow(reservation, additional)?; + self.peak + .fetch_max(self.inner.reserved(), Ordering::Relaxed); + Ok(()) + } + fn reserved(&self) -> usize { + self.inner.reserved() + } + } + + let mut m = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Sparse); + m.column_metadatas + .iter_mut() + .find(|c| c.column_id == 2) + .unwrap() + .column_schema + .data_type = native_histogram_value_type().clone(); + let m = Arc::new(m); + // Equal, compressible rows: several equal blocks whose chunks all fit one read-ahead window. + let values = histogram_array( + &(0..300) + .map(|_| { + Some(TestHistogram { + positive_spans: vec![(0, 1000)], + floats: Some((1000.0, 0.0, vec![1.0; 1000], vec![])), + ..Default::default() + }) + }) + .collect::>(), + ); + let store = store(); + let format = ColumnarSamplesFormat::default(); + let rows = values.len(); + let key = new_sparse_primary_key(&["a", "b"], &m, 1, 1); + let input = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("field_0", values.data_type().clone(), true), + Field::new( + "ts", + DataType::Timestamp(datatypes::arrow::datatypes::TimeUnit::Millisecond, None), + false, + ), + Field::new("__primary_key", DataType::Binary, false), + Field::new(SEQUENCE, DataType::UInt64, false), + Field::new(OPERATION, DataType::UInt8, false), + ])), + vec![ + Arc::new(values.clone()), + Arc::new( + datatypes::arrow::array::TimestampMillisecondArray::from_iter_values( + 0..rows as i64, + ), + ), + Arc::new(BinaryArray::from_iter_values(vec![key.as_slice(); rows])), + Arc::new(UInt64Array::from(vec![1; rows])), + Arc::new(UInt8Array::from(vec![1; rows])), + ], + ) + .unwrap(); + let handle = build(&format, &store, m.clone(), &[input]).await; + let reader = format.reader(store, handle).await.unwrap(); + let read = |pool: Arc| { + let mut request = request(&["field_0"]); + request.memory_pool = Some(pool); + reader.read(request).unwrap().try_collect::>() + }; + let peak = Arc::new(PeakPool { + inner: GreedyMemoryPool::new(usize::MAX), + peak: AtomicUsize::new(0), + }); + assert!(read(peak.clone()).await.unwrap().len() > 2); + // The peak decodes a block while the window is held. The same block needs less without the + // window, so a pool one byte smaller must still read everything. + let pool = Arc::new(GreedyMemoryPool::new(peak.peak.load(Ordering::Relaxed) - 1)); + let batches = read(pool.clone()).await.unwrap(); + let decoded = datatypes::arrow::compute::concat( + &batches + .iter() + .map(|b| b.column(0).as_ref()) + .collect::>(), + ) + .unwrap(); + assert_eq!(&values as &dyn Array, decoded.as_ref()); + drop(batches); + assert_eq!(0, pool.reserved()); +} diff --git a/src/mito2/src/series_index/samples/writer.rs b/src/mito2/src/series_index/samples/writer.rs index 334656c83c5..af844a9f381 100644 --- a/src/mito2/src/series_index/samples/writer.rs +++ b/src/mito2/src/series_index/samples/writer.rs @@ -14,10 +14,14 @@ //! Streaming sample writing with bounded blocks and owned outputs. +use std::sync::Arc; + use async_trait::async_trait; use datatypes::arrow::array::{ - Array, BinaryArray, DictionaryArray, Float64Array, UInt8Array, UInt64Array, + Array, ArrayRef, AsArray, BinaryArray, DictionaryArray, Float64Array, StructArray, UInt8Array, + UInt64Array, }; +use datatypes::arrow::compute::concat; use datatypes::arrow::datatypes::{DataType, UInt32Type}; use datatypes::arrow::record_batch::RecordBatch; use datatypes::prelude::DataType as _; @@ -28,18 +32,19 @@ use snafu::ResultExt; use store_api::metadata::RegionMetadataRef; use store_api::storage::{FileId, consts}; -use crate::error::{Result, SerdeJsonSnafu}; +use crate::error::{ComputeArrowSnafu, Result, SerdeJsonSnafu}; use crate::series_index::artifact::{ArtifactFormat, ArtifactMetadata, ArtifactObject}; use crate::series_index::artifact_writer::Outputs; use crate::series_index::format::FormatWriter; use crate::series_index::identity::{ExactSeriesKey, IdentityEncoding, decode_series_id}; -use crate::series_index::samples::codec; +use crate::series_index::samples::histogram::ChunkBound; use crate::series_index::samples::metadata::{ self, Block, Column, KeyRef, Page, PageReference, Trailer, pack, }; use crate::series_index::samples::{ - ColumnarSamplesFormat, MANIFEST_LIMIT, Manifest, MetricSeriesId, Part, TimestampColumn, - TimestampUnit, VERSION, ValueColumn, invalid, require, valid_rows, + ColumnarSamplesFormat, FLOAT64_ENCODING, MANIFEST_LIMIT, Manifest, MetricSeriesId, Part, + TimestampColumn, TimestampUnit, VERSION, ValueColumn, codec, histogram, invalid, require, + valid_rows, }; use crate::sst::DEFAULT_WRITE_BUFFER_SIZE; @@ -80,7 +85,32 @@ struct Row { time: i64, sequence: u64, operation: u8, - fields: Vec>, +} +/// One field's values for the rows of the pending block, in row order. +enum PendingField { + Float(Vec>), + /// Runs of rows borrowed from input batches, concatenated once when the block is encoded. + Histogram { + runs: Vec<(ArrayRef, usize, usize)>, + bound: ChunkBound, + }, +} +impl PendingField { + fn new(field: &ValueColumn) -> Self { + if field.is_histogram() { + Self::Histogram { + runs: Vec::new(), + bound: ChunkBound::default(), + } + } else { + Self::Float(Vec::new()) + } + } +} +/// One input batch's column for a field. +enum FieldInput<'a> { + Float(&'a Float64Array), + Histogram(&'a ArrayRef, &'a StructArray), } /// A block descriptor whose exact key has not been placed in the part's key area yet. /// @@ -164,6 +194,8 @@ pub(super) struct SamplesWriter { /// Canonical sparse key of the series that owns `rows` and `last`. series_key: Option, rows: Vec, + /// Field values of `rows`, one entry per manifest field. + fields: Vec, last: Option<(MetricSeriesId, i64, u64)>, ordinal: u64, leaves: Vec>, @@ -205,19 +237,9 @@ impl SamplesWriter { }; let fields = metadata .field_columns() - .map(|column| { - require( - column.column_schema.data_type.as_arrow_type() == DataType::Float64, - "samples support only Float64 fields", - )?; - Ok(ValueColumn { - column_id: column.column_id, - name: column.column_schema.name.clone(), - data_type: "float64".into(), - nullable: true, - }) - }) + .map(ValueColumn::new) .collect::>>()?; + let pending_fields = fields.iter().map(PendingField::new).collect(); let manifest = Manifest { prefix: Some(prefix.to_string()), format: ArtifactFormat::ColumnarSamples, @@ -257,6 +279,7 @@ impl SamplesWriter { offsets: SparseOffsetsCache::new(), series_key: None, rows: Vec::new(), + fields: pending_fields, last: None, ordinal: 0, leaves: Vec::new(), @@ -303,10 +326,15 @@ impl SamplesWriter { .fields .iter() .map(|field| { - column(&field.name)? - .as_any() - .downcast_ref::() - .ok_or_else(|| invalid("invalid sample field array")) + let array = column(&field.name)?; + let input = if field.is_histogram() { + array + .as_struct_opt() + .map(|s| FieldInput::Histogram(array, s)) + } else { + array.as_any().downcast_ref().map(FieldInput::Float) + }; + input.ok_or_else(|| invalid("invalid sample field array")) }) .collect::>>()?; let keys = column(consts::PRIMARY_KEY_COLUMN_NAME)?; @@ -374,41 +402,76 @@ impl SamplesWriter { } _ => decode_series_id(key, &mut self.offsets)?, }; + let mut bounds = self.histogram_bounds(&fields, i); if self.rows.len() == self.options.block_rows || !valid_rows(self.rows.len() + 1, fields.len()) + || bounds.is_none() { self.flush_block().await?; + bounds = self.histogram_bounds(&fields, i); } + let mut bounds = bounds + .ok_or_else(|| invalid("native histogram sample exceeds the chunk limit"))? + .into_iter(); self.rows.push(Row { id, time, sequence: seq, operation: op, - fields: fields - .iter() - .map(|field| { - if field.is_null(i) { - None - } else { - Some(field.value(i).to_bits()) - } - }) - .collect(), }); + for (pending, input) in self.fields.iter_mut().zip(&fields) { + match (pending, input) { + (PendingField::Float(values), FieldInput::Float(array)) => { + values.push(array.is_valid(i).then(|| array.value(i).to_bits())); + } + (PendingField::Histogram { runs, bound }, FieldInput::Histogram(array, _)) => { + *bound = bounds + .next() + .ok_or_else(|| invalid("missing native histogram bound"))?; + match runs.last_mut() { + Some((run, start, len)) + if Arc::ptr_eq(run, array) && *start + *len == i => + { + *len += 1 + } + _ => runs.push(((*array).clone(), i, 1)), + } + } + _ => return Err(invalid("sample field kind changed between rows")), + } + } self.last = Some((id, time, seq)); } Ok(()) } + /// Each histogram field's chunk bound with row `i` appended to the pending block, in field + /// order, or `None` when one of those chunks would no longer fit. + fn histogram_bounds(&self, fields: &[FieldInput<'_>], i: usize) -> Option> { + self.fields + .iter() + .zip(fields) + .filter_map(|(pending, input)| match (pending, input) { + (PendingField::Histogram { bound, .. }, FieldInput::Histogram(_, array)) => { + Some(bound.with_row(array, i)) + } + _ => None, + }) + .collect() + } async fn flush_block(&mut self) -> Result<()> { if self.rows.is_empty() { return Ok(()); } let rows = std::mem::take(&mut self.rows); + let fields = std::mem::replace( + &mut self.fields, + self.manifest.fields.iter().map(PendingField::new).collect(), + ); let key = self .series_key .as_ref() .ok_or_else(|| invalid("sample block has no series key"))?; - let (mut block, chunks) = encode_block(&rows, key, &self.manifest, self.ordinal)?; + let (mut block, chunks) = encode_block(&rows, fields, key, &self.manifest, self.ordinal)?; // Bytes one copy of this series' key costs in a part's key area: the key and its stored // checksum. let key_len = key.bytes().len() as u64 + metadata::KEY_CHECKSUM_BYTES; @@ -640,6 +703,7 @@ impl FormatWriter for SamplesWriter { } fn encode_block( rows: &[Row], + fields: Vec, key: &ExactSeriesKey, manifest: &Manifest, ordinal: u64, @@ -678,17 +742,46 @@ fn encode_block( let (encoding, bytes) = codec::encode_operations(&rows.iter().map(|r| r.operation).collect::>()); push(3, 0, encoding, bytes, 0)?; - for (index, field) in manifest.fields.iter().enumerate() { - let values: Vec<_> = rows.iter().map(|r| r.fields[index]).collect(); - let nulls = values.iter().filter(|v| v.is_none()).count(); - if nulls != rows.len() { - push( - 4, - field.column_id, - 5, - codec::encode_float(&values), - nulls as u32, - )?; + for (field, pending) in manifest.fields.iter().zip(fields) { + match pending { + PendingField::Float(values) => { + require( + values.len() == rows.len(), + "sample field row count mismatch", + )?; + let nulls = values.iter().filter(|v| v.is_none()).count(); + if nulls != rows.len() { + push( + 4, + field.column_id, + FLOAT64_ENCODING, + codec::encode_float(&values), + nulls as u32, + )?; + } + } + PendingField::Histogram { runs, .. } => { + let slices = runs + .iter() + .map(|(array, start, len)| array.slice(*start, *len)) + .collect::>(); + let array = concat(&slices.iter().map(|a| a.as_ref()).collect::>()) + .context(ComputeArrowSnafu)?; + let array = array + .as_struct_opt() + .ok_or_else(|| invalid("invalid native histogram sample array"))?; + require(array.len() == rows.len(), "sample field row count mismatch")?; + // An all-null field has no chunk, as for Float64 fields. + if array.null_count() != rows.len() { + push( + 4, + field.column_id, + histogram::ENCODING, + histogram::encode(array)?, + array.null_count() as u32, + )?; + } + } } } Ok((block, chunks)) diff --git a/src/mito2/src/worker/handle_write.rs b/src/mito2/src/worker/handle_write.rs index 52f2c9a5762..7ef7fac02a3 100644 --- a/src/mito2/src/worker/handle_write.rs +++ b/src/mito2/src/worker/handle_write.rs @@ -38,6 +38,7 @@ use crate::region_write_ctx::{RegionWriteCtx, WriteSource}; use crate::request::{ SenderBulkRequest, SenderWriteRequest, WriteRequest, check_bulk_insert_batch, }; +use crate::sst::FormatType; use crate::wal::Wal; use crate::worker::RegionWorkerLoop; @@ -457,6 +458,15 @@ impl RegionWorkerLoop { sender_req.sender.send(Err(e)); continue; } + if region_ctx.version().options.sst_format == Some(FormatType::Narthex) + && let Err(e) = crate::series_index::samples::check_histogram_rows( + ®ion_ctx.version().metadata, + &sender_req.request.rows, + ) + { + sender_req.sender.send(Err(e)); + continue; + } // Double check the request schema let need_fill_missing_columns = @@ -628,6 +638,15 @@ impl RegionWorkerLoop { } } + // Checked after the fill, which may add histogram columns from defaults. + if region_ctx.version().options.sst_format == Some(FormatType::Narthex) + && let Err(e) = + crate::series_index::samples::check_histogram_batch(&bulk_req.request.batch) + { + bulk_req.sender.send(Err(e)); + continue; + } + // Collect requests by region. if !region_ctx.push_bulk(bulk_req.sender, bulk_req.request, None, bulk_req.skip_wal) { continue; diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 849958e3dde..86184656904 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -465,10 +465,6 @@ impl PromPlanner { // that do not cast, so a float here is only the same answer where the statement's own shape says // the existing plan reports `Float64` too; [`read_field_type`] states that per field. // - // `Float64` fields are answered by the columnar series-index reader when a region prepares one. A - // histogram field is not, since the logical plan cannot tell which reader a region will prepare, so - // such a selection falls back to the ordinary scan. - // // A numeric field whose statement publishes the field's own type keeps the existing plan. Naming // that refusal here keeps it apart from a selection whose fields genuinely disagree, and it is the // refusal a reader can act on: the expression needs an operator that casts - an arithmetic one, a diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index b14004d29e7..096b6c9fa23 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -18246,3 +18246,446 @@ async fn native_promql_matrix_root_matches_legacy() { let legacy = run(&instance, &observer, sql, false).await; assert_eq!(native, legacy); } + +/// Native histograms in a Narthex physical table, and in a Parquet one served by a columnar +/// series-index sidecar, answer what the same samples answer in a plain Parquet table: PromQL on +/// both routes and remote read, from the memtable, after flushes, after a compaction and after a +/// reopen. +#[tokio::test(flavor = "multi_thread")] +async fn narthex_native_histograms_match_parquet() { + use api::helper::ColumnDataTypeWrapper; + use api::v1::greptime_request::Request; + use api::v1::{ColumnDataType, ColumnDef, CreateTableExpr, DdlRequest, SemanticType}; + use common_query::native_histogram::{native_histogram_value_type, read_histogram}; + use common_query::prelude::{greptime_native_histogram, greptime_timestamp}; + use servers::query_handler::grpc::GrpcQueryHandler; + + use super::test_util::{MockInstanceBuilder, RebuildableMockInstance, TestContext}; + + common_telemetry::init_default_ut_logging(); + // A plan observer plugin cannot survive the rebuild below, so `TQL ANALYZE` shows the route. + let builder = GreptimeDbStandaloneBuilder::new("narthex_native_histograms") + .with_mito_config(mito2::config::MitoConfig { + experimental_series_scan_v2: true, + experimental_enable_series_index: true, + experimental_series_index_format: mito2::config::SeriesIndexFormat::Columnar, + // Only the manual build below publishes a sidecar, so the plain Parquet table never + // gets one. + experimental_series_index_maintenance_interval: Duration::from_secs(3600), + ..Default::default() + }) + .with_query_options(QueryOptions { + experimental_native_promql: true, + ..Default::default() + }); + let mut context = TestContext::new(MockInstanceBuilder::Standalone(builder)).await; + let instance = context.frontend(); + + // Remote write creates physical tables with a float value field, so each histogram-only + // physical table is created up front. + let (data_type, datatype_extension) = + ColumnDataTypeWrapper::try_from(native_histogram_value_type().clone()) + .unwrap() + .into_parts(); + // The plain Parquet table at index 1 is the baseline the others are compared against. + let tables = [ + ("narthex_hist", "narthex_phy"), + ("parquet_hist", "parquet_phy"), + ("sidecar_hist", "sidecar_phy"), + ]; + for (format, (_, physical)) in ["narthex", "flat", "flat"].into_iter().zip(tables) { + let expr = CreateTableExpr { + catalog_name: DEFAULT_CATALOG_NAME.to_string(), + schema_name: DEFAULT_SCHEMA_NAME.to_string(), + table_name: physical.to_string(), + column_defs: vec![ + ColumnDef { + name: greptime_timestamp().to_string(), + data_type: ColumnDataType::TimestampMillisecond as i32, + semantic_type: SemanticType::Timestamp as i32, + ..Default::default() + }, + ColumnDef { + name: greptime_native_histogram().to_string(), + data_type: data_type as i32, + is_nullable: true, + semantic_type: SemanticType::Field as i32, + datatype_extension: datatype_extension.clone(), + ..Default::default() + }, + ], + time_index: greptime_timestamp().to_string(), + table_options: [ + ("physical_metric_table".to_string(), "true".to_string()), + ("sst_format".to_string(), format.to_string()), + ] + .into(), + engine: "metric".to_string(), + ..Default::default() + }; + GrpcQueryHandler::do_query( + instance.as_ref(), + Request::Ddl(DdlRequest { + expr: Some(api::v1::ddl_request::Expr::CreateTable(expr)), + }), + QueryContext::arc(), + ) + .await + .unwrap(); + } + + // Steps 0..=5 go in before the first flush and 6..=10 after it, so the compaction merges two + // files of each table. + write_histograms(&instance, &tables, 0..=5).await; + assert_histograms_match(&instance, &tables, "memtable").await; + for (_, physical) in tables { + run_sql(&instance, &format!("ADMIN FLUSH_TABLE('{physical}')")).await; + } + write_histograms(&instance, &tables, 6..=10).await; + assert_histograms_match(&instance, &tables, "flushed and memtable").await; + for (_, physical) in tables { + run_sql(&instance, &format!("ADMIN FLUSH_TABLE('{physical}')")).await; + run_sql(&instance, &format!("ADMIN COMPACT_TABLE('{physical}')")).await; + } + run_sql(&instance, "ADMIN BUILD_SERIES_INDEX('sidecar_phy')").await; + assert_histograms_match(&instance, &tables, "compacted").await; + // The sidecar's histogram samples answer a native read: the columnar reader decodes rows. + // Reopening rebuilds every region's sidecar, the plain table's included, so only this stage + // compares the sidecar against plain Parquet reads. + let decoded = columnar_decoded_rows(); + let output = native_tql_output( + &instance, + "TQL EVAL (0, 600, '60s') histogram_count(rate(sidecar_hist[5m]))", + true, + ) + .await; + assert!(!float_answer_rows(output).await.is_empty()); + assert!( + columnar_decoded_rows() > decoded, + "the columnar sidecar did not serve the histogram read" + ); + context.rebuild().await; + let instance = context.frontend(); + assert_histograms_match(&instance, &tables, "reopened").await; + + /// Rows the Mito columnar readers have decoded in this process. + fn columnar_decoded_rows() -> u64 { + common_telemetry::dump_metrics() + .unwrap() + .lines() + .filter(|line| { + line.starts_with("greptime_mito_columnar_read_count{") + && line.contains("type=\"decoded_rows\"") + }) + .filter_map(|line| line.rsplit(' ').next()?.parse::().ok()) + .sum::() as u64 + } + + async fn run_sql(instance: &Arc, sql: &str) { + SqlQueryHandler::do_query(instance.as_ref(), sql, QueryContext::arc()) + .await + .remove(0) + .unwrap(); + } + + /// Writes the same histograms under each metric. `api` carries integer deltas whose bucket + /// layout changes between samples; `web` carries float counts over custom buckets. + async fn write_histograms( + instance: &Arc, + tables: &[(&str, &str)], + steps: std::ops::RangeInclusive, + ) { + use api::greptime_proto::io::prometheus::write::v2::histogram::{Count, ZeroCount}; + use api::greptime_proto::io::prometheus::write::v2::{BucketSpan, Histogram}; + use axum::body::{Body, to_bytes}; + use http::Request; + use prost::Message; + use servers::prom_remote_write::v2::test_util as remote_write_v2; + use servers::prom_store::snappy_compress; + use tower::ServiceExt; + + let span = |offset, length| BucketSpan { offset, length }; + let server = + crate::test_util::build_test_prom_server(instance.clone(), false, None).build(); + let router = server.build(server.make_app()).unwrap(); + for (metric, physical) in tables { + for job in ["api", "web"] { + let histograms = steps + .clone() + .map(|k| { + let timestamp = k * 60_000; + if job == "api" { + let positive_spans = if k % 3 == 0 { + vec![span(-1, 2), span(2, 1)] + } else { + vec![span(0, 3)] + }; + Histogram { + timestamp, + schema: 1, + zero_threshold: 0.001, + count: Some(Count::CountInt(4 * k as u64 + 5)), + zero_count: Some(ZeroCount::ZeroCountInt(1)), + sum: 2.5 * k as f64, + positive_spans, + positive_deltas: vec![k + 1, 1, -1], + negative_spans: vec![span(0, 1)], + negative_deltas: vec![k], + ..Default::default() + } + } else { + let k = k as f64; + Histogram { + timestamp, + schema: -53, + custom_values: vec![0.1, 0.5, 1.0], + count: Some(Count::CountFloat(4.0 * k + 1.0)), + sum: 0.75 * k, + positive_spans: vec![span(0, 4)], + positive_counts: vec![k, 2.0 * k, k, 1.0], + ..Default::default() + } + } + }) + .collect(); + let request = remote_write_v2::request_with_labels_and_histograms( + vec![ + ("__name__", metric), + ("job", job), + ("__physical_table__", physical), + ], + histograms, + ); + let response = router + .clone() + .oneshot( + Request::post("/v1/prometheus/write") + .header("Content-Encoding", "snappy") + .header( + "Content-Type", + "application/x-protobuf;proto=io.prometheus.write.v2.Request", + ) + .body(Body::from( + snappy_compress(&request.encode_to_vec()).unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status(), + 204, + "{:?}", + to_bytes(response.into_body(), usize::MAX).await.unwrap() + ); + } + } + } + + /// Asserts every metric answers the baseline's rows: PromQL on each route, and remote read. + async fn assert_histograms_match( + instance: &Arc, + tables: &[(&str, &str)], + stage: &str, + ) { + use datatypes::arrow::array::StructArray; + + let narthex = tables[0].0; + let metrics = tables.iter().map(|(metric, _)| *metric).collect::>(); + // The aggregates over histograms run on the existing route only: the native planner + // fails to plan their split state, whatever the storage. + for (query, routes) in [ + ("histogram_quantile(0.9, rate({m}[5m]))", &[false, true][..]), + ("histogram_count(rate({m}[5m]))", &[false, true]), + ("histogram_sum({m})", &[false, true]), + ( + "histogram_quantile(0.5, sum by (job) (rate({m}[5m])))", + &[false], + ), + ("histogram_count(sum by (job) (rate({m}[5m])))", &[false]), + ] { + for &native in routes { + let mut answers = Vec::new(); + for metric in &metrics { + let query = query.replace("{m}", metric); + let sql = format!("TQL EVAL (0, 600, '60s') {query}"); + if native { + let analyze = native_tql_output( + instance, + &format!("TQL ANALYZE (0, 600, '60s') {query}"), + true, + ) + .await; + assert!( + native_output_text(analyze) + .await + .contains("FusedSeriesExec"), + "{stage}: {sql} did not run natively" + ); + } + let output = native_tql_output(instance, &sql, native).await; + answers.push(float_answer_rows(output).await); + } + assert!(!answers[1].is_empty(), "{stage}: {query} answered nothing"); + for (metric, answer) in metrics.iter().zip(&answers) { + assert_eq!( + answer, &answers[1], + "{stage}: {query} (native: {native}) differs between {metric} and Parquet" + ); + } + } + } + + let server = + crate::test_util::build_test_prom_server(instance.clone(), false, None).build(); + let router = server.build(server.make_app()).unwrap(); + let mut answers = Vec::new(); + for metric in &metrics { + answers.push(remote_read_histograms(&router, metric).await); + } + assert_eq!(answers[1].len(), 2, "{stage}: remote read series"); + for (metric, answer) in metrics.iter().zip(&answers) { + assert_eq!( + answer, &answers[1], + "{stage}: remote read differs between {metric} and Parquet" + ); + } + + // A raw histogram read back is the one written at step 5. + let output = native_tql_output( + instance, + &format!("TQL EVAL (300, 300, '60s') {narthex}{{job=\"web\"}}"), + true, + ) + .await; + let batches = match output.data { + OutputData::Stream(stream) => collect_batches(stream).await.unwrap(), + OutputData::RecordBatches(batches) => batches, + _ => unreachable!("PromQL answers record batches"), + }; + let histogram = batches + .iter() + .find_map(|batch| { + batch + .df_record_batch() + .columns() + .iter() + .find_map(|column| column.as_any().downcast_ref::().cloned()) + }) + .expect("a histogram column"); + let histogram = read_histogram(&histogram, 0).unwrap().unwrap(); + assert_eq!((histogram.count, histogram.sum), (21.0, 3.75), "{stage}"); + } + + /// Rows of a float PromQL answer as `(time, labels, value bits)`, sorted, without the metric + /// name that tells the two tables apart. + async fn float_answer_rows(output: Output) -> Vec<(i64, String, u64)> { + let batches = match output.data { + OutputData::Stream(stream) => collect_batches(stream).await.unwrap(), + OutputData::RecordBatches(batches) => batches, + _ => unreachable!("PromQL answers record batches"), + }; + let mut rows = Vec::new(); + for batch in batches.iter() { + let batch = batch.df_record_batch(); + let schema = batch.schema(); + let time = schema + .fields() + .iter() + .position(|f| matches!(f.data_type(), DataType::Timestamp(_, _))) + .unwrap(); + let value = schema + .fields() + .iter() + .position(|f| f.data_type() == &DataType::Float64) + .unwrap(); + let times = cast(batch.column(time), &DataType::Int64).unwrap(); + let times = times.as_any().downcast_ref::().unwrap(); + let values = batch + .column(value) + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + let labels = schema + .fields() + .iter() + .enumerate() + .filter(|(i, f)| *i != time && *i != value && f.name() != "__name__") + .filter_map(|(i, f)| { + let column = cast(batch.column(i), &DataType::Utf8).ok()?; + let column = column.as_any().downcast_ref::()?; + column + .is_valid(row) + .then(|| format!("{}={}", f.name(), column.value(row))) + }) + .collect::>() + .join(","); + if values.is_valid(row) { + rows.push((times.value(row), labels, values.value(row).to_bits())); + } + } + } + rows.sort(); + rows + } + + /// Remote-read histograms per series, keyed by the labels other than the metric name. + async fn remote_read_histograms( + router: &axum::Router, + metric: &str, + ) -> Vec<( + Vec<(String, String)>, + Vec, + )> { + use api::prom_store::remote::{LabelMatcher, Query, ReadRequest, ReadResponse}; + use axum::body::{Body, to_bytes}; + use prost::Message; + use servers::prom_store::{snappy_compress, snappy_decompress}; + use tower::ServiceExt; + + let request = ReadRequest { + queries: vec![Query { + start_timestamp_ms: 0, + end_timestamp_ms: 700_000, + matchers: vec![LabelMatcher { + name: "__name__".to_string(), + value: metric.to_string(), + r#type: 0, + }], + ..Default::default() + }], + accepted_response_types: vec![], + }; + let response = router + .clone() + .oneshot( + http::Request::post("/v1/prometheus/read") + .body(Body::from( + snappy_compress(&request.encode_to_vec()).unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), 200); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let response = ReadResponse::decode(snappy_decompress(&body).unwrap().as_slice()).unwrap(); + let mut series = response.results[0] + .timeseries + .iter() + .map(|series| { + let mut labels = series + .labels + .iter() + .filter(|label| label.name != "__name__") + .map(|label| (label.name.clone(), label.value.clone())) + .collect::>(); + labels.sort(); + (labels, series.histograms.clone()) + }) + .collect::>(); + series.sort_by(|a, b| a.0.cmp(&b.0)); + series + } +}