diff --git a/src/datatypes/src/series/frame.rs b/src/datatypes/src/series/frame.rs index d9f9c1ee347..27902ecf805 100644 --- a/src/datatypes/src/series/frame.rs +++ b/src/datatypes/src/series/frame.rs @@ -13,6 +13,12 @@ // limitations under the License. //! Finite Arrow batches for raw series chunks. Field names preserve the logical series schema in order. +//! +//! Packing accumulates bounded multi-row batches: [`RawSeriesChunkCursor`] walks one validated +//! chunk and [`RawSeriesFrameBuilder`] emits rows directly as Arrow arrays once a row or estimated +//! byte bound is reached. Decoding reuses one prepared schema per stream through +//! [`RawSeriesFrameDecoder`]. Column layout, metadata, and wire strings stay on the frozen `v1` +//! contract. #[cfg(test)] mod tests; @@ -24,12 +30,13 @@ use arrow::array::{ StructArray, UInt32Array, }; use arrow::buffer::{Buffer, NullBuffer, OffsetBuffer, ScalarBuffer}; +use arrow::compute::concat; use arrow::datatypes::{DataType, Field, Fields, Schema, SchemaRef}; use arrow::record_batch::{RecordBatch, RecordBatchOptions}; use crate::error::{InvalidSeriesSnafu, Result}; use crate::series::histogram::{HistogramBatch, fields as histogram_fields}; -use crate::series::raw::{RawSeriesChunk, RawTimeAxis}; +use crate::series::raw::{RawSeriesChunk, RawTimestamps}; use crate::series::samples::{ DenseSamplesRef, HistogramSamples, Samples, SeriesFields, SeriesSchema, }; @@ -130,66 +137,714 @@ pub fn raw_series_frame_schema(schema: &SeriesSchema, mode: RawLabelMode) -> Res Ok(Arc::new(Schema::new_with_metadata(columns, metadata))) } -/// Packs one raw chunk into one-row batches at the union of field segment boundaries. +/// Bounded multi-row builder for finite raw frame batches. +/// +/// Rows accumulate until the row limit or the estimated byte limit is reached; the next +/// [`RawSeriesChunkCursor::append_to`] call then emits them as one batch. `max_bytes` is stored as +/// the effective group cap `min(requested, i32::MAX)`, and each row carries a measure that +/// dominates every cumulative Arrow offset domain, so any admitted group can be encoded. The +/// measure is an internal work estimate, not an exact IPC size and not a resident-memory cap: one +/// individually representable row that exceeds the requested cap is still accepted and emitted +/// alone, because that slice cannot be split into smaller legal rows. +pub struct RawSeriesFrameBuilder { + schema: SeriesSchema, + frame_schema: SchemaRef, + mode: RawLabelMode, + max_rows: usize, + max_bytes: usize, + rows: Vec, + bytes: usize, +} + +impl RawSeriesFrameBuilder { + /// Default maximum rows in one packed batch when no explicit bound is needed. + pub const DEFAULT_MAX_ROWS: usize = 256; + /// Default maximum estimated encoded bytes in one packed batch when no explicit bound is + /// needed. + pub const DEFAULT_MAX_BYTES: usize = 1024 * 1024; + + /// Creates an empty builder for the given schema, label mode, and nonzero bounds. + /// + /// The frame schema is built once here and reused for every emitted batch. + pub fn try_new( + schema: &SeriesSchema, + mode: RawLabelMode, + max_rows: usize, + max_bytes: usize, + ) -> Result { + if max_rows == 0 || max_bytes == 0 { + return invalid_series("raw series frame limits must be nonzero"); + } + Ok(Self { + schema: schema.clone(), + frame_schema: raw_series_frame_schema(schema, mode)?, + mode, + max_rows, + max_bytes: max_bytes.min(i32::MAX as usize), + rows: Vec::new(), + bytes: 0, + }) + } + + /// The frame schema of every batch this builder emits. + pub fn schema(&self) -> &SchemaRef { + &self.frame_schema + } + + /// Emits the accumulated rows as one batch, or `None` when nothing is buffered. + pub fn flush(&mut self) -> Result> { + if self.rows.is_empty() { + return Ok(None); + } + let batch = encode_rows(&self.frame_schema, self.mode, &self.rows)?; + self.rows.clear(); + self.bytes = 0; + Ok(Some(batch)) + } + + /// Whether the buffered rows reached either bound. + fn is_full(&self) -> bool { + self.rows.len() >= self.max_rows || self.bytes >= self.max_bytes + } + + /// Whether `row` may join the buffered rows without crossing either bound. + /// + /// An empty builder accepts any individually measured row; a group total that would overflow + /// or exceed the cap flushes the buffered rows before this row is consumed, never dropping or + /// splitting the row. + fn accepts(&self, row: &RawFrameRow) -> bool { + self.rows.is_empty() + || (self.bytes < self.max_bytes + && self.rows.len() < self.max_rows + && self + .bytes + .checked_add(row.bytes) + .is_some_and(|total| total <= self.max_bytes)) + } + + /// Buffers one individually measured row. + fn push(&mut self, row: RawFrameRow) -> Result<()> { + self.bytes = add_checked(self.bytes, row.bytes)?; + self.rows.push(row); + Ok(()) + } +} + +/// One validated chunk walked segment by segment into a bounded builder. +pub struct RawSeriesChunkCursor { + schema: SeriesSchema, + mode: RawLabelMode, + chunk: RawSeriesChunk, + segments: Vec, + offsets: Vec, + pos: usize, + pending: Option, +} + +impl RawSeriesChunkCursor { + /// Validates one public chunk's shape and label mode once, taking ownership of it. + pub fn try_new( + schema: &SeriesSchema, + mode: RawLabelMode, + chunk: RawSeriesChunk, + ) -> Result { + let RawSeriesChunk { + primary_key, + metric, + time, + fields, + is_last, + } = chunk; + let chunk = RawSeriesChunk::try_new(schema, primary_key, metric, time, fields, is_last)?; + match (mode, &chunk.metric) { + (RawLabelMode::Key, None) | (RawLabelMode::Explicit, Some(_)) => {} + _ => return invalid_series("raw chunk label mode does not match frame mode"), + } + let segments = vec![0usize; chunk.fields.len()]; + let offsets = vec![0usize; chunk.fields.len()]; + Ok(Self { + schema: schema.clone(), + mode, + chunk, + segments, + offsets, + pos: 0, + pending: None, + }) + } + + /// Appends rows to the builder until one batch is ready or this chunk is exhausted. + /// + /// `None` means the cursor is exhausted; calling again returns `None` without touching the + /// builder. The single pending row is measured once by [`Self::next_row`] and retried after the + /// buffered rows are emitted. + pub fn append_to( + &mut self, + builder: &mut RawSeriesFrameBuilder, + ) -> Result> { + self.compatible(builder)?; + loop { + let row = match self.pending.take() { + Some(row) => row, + None => match self.next_row()? { + Some(row) => { + self.pending = Some(row); + continue; + } + None => return Ok(None), + }, + }; + if !builder.accepts(&row) { + // Reinstate the row before flushing so a flush error cannot consume it. + self.pending = Some(row); + let batch = builder + .flush()? + .ok_or_else(|| err("raw frame builder rejected a row without buffered rows"))?; + return Ok(Some(batch)); + } + builder.push(row)?; + if builder.is_full() { + if let Some(batch) = builder.flush()? { + return Ok(Some(batch)); + } + } + } + } + + /// The cursor and builder must describe the same fields and label mode. + fn compatible(&self, builder: &RawSeriesFrameBuilder) -> Result<()> { + let same_fields = self.schema.fields.len() == builder.schema.fields.len() + && self + .schema + .fields + .iter() + .zip(builder.schema.fields.iter()) + .all(|(left, right)| left.name == right.name); + if self.mode != builder.mode + || self.schema.eval_grid.is_some() != builder.schema.eval_grid.is_some() + || !same_fields + { + return invalid_series("raw frame cursor and builder schema mismatch"); + } + Ok(()) + } + + /// Builds and measures the next union-of-segment row, or `None` when the chunk is exhausted. + /// + /// The chunk fields are walked three times so no per-row temporary vectors are allocated; the + /// offsets advance only after the row measure succeeded. + fn next_row(&mut self) -> Result> { + if self.pos >= self.chunk.time.len() { + return Ok(None); + } + let time_axis = self.chunk.time.as_buffer(); + let mut take = time_axis.len() - self.pos; + for (index, field) in self.chunk.fields.iter().enumerate() { + let part = segment(field, self.segments[index])?; + take = take.min(part.len().saturating_sub(self.offsets[index])); + } + if take == 0 { + return invalid_series("empty sample segment"); + } + let mut samples = Vec::with_capacity(self.chunk.fields.len()); + for (index, field) in self.chunk.fields.iter().enumerate() { + let part = segment(field, self.segments[index])?; + samples.push(part.slice(self.offsets[index], take)?); + } + let mut row = RawFrameRow { + primary_key: self.chunk.primary_key.clone(), + metric: self.chunk.metric.clone(), + is_last: self.chunk.is_last && self.pos + take == self.chunk.time.len(), + times: time_axis.slice(self.pos, take), + samples, + bytes: 0, + }; + row.bytes = measure_row(&row)?; + self.pos += take; + for (index, field) in self.chunk.fields.iter().enumerate() { + let length = segment(field, self.segments[index])?.len(); + self.offsets[index] += take; + if self.offsets[index] == length { + self.segments[index] += 1; + self.offsets[index] = 0; + } + } + Ok(Some(row)) + } +} + +/// The next dense segment of one field, or an error when the walk left the segment list. +fn segment(field: &Samples, index: usize) -> Result<&Samples> { + field + .segments() + .get(index) + .ok_or_else(|| err("empty sample segment")) +} + +/// Packs one raw chunk, retaining the `Vec` compatibility signature. +/// +/// The chunk packs into bounded multi-row batches; callers that need streaming behavior should +/// drive [`RawSeriesChunkCursor`] and [`RawSeriesFrameBuilder`] directly instead of collecting. pub fn pack_raw_series_chunk( schema: &SeriesSchema, mode: RawLabelMode, chunk: &RawSeriesChunk, ) -> Result> { - let checked = RawSeriesChunk::try_new( + let mut builder = RawSeriesFrameBuilder::try_new( schema, - chunk.read_key.clone(), - chunk.metric.clone(), - chunk.time.clone(), - chunk.fields.clone(), - chunk.is_last, + mode, + RawSeriesFrameBuilder::DEFAULT_MAX_ROWS, + RawSeriesFrameBuilder::DEFAULT_MAX_BYTES, )?; - match (mode, &checked.metric) { - (RawLabelMode::Key, None) | (RawLabelMode::Explicit, Some(_)) => {} - _ => return invalid_series("raw chunk label mode does not match frame mode"), - } - let frame_schema = raw_series_frame_schema(schema, mode)?; - let RawTimeAxis::Explicit(times) = &checked.time; - let all: Vec<&[Samples]> = checked.fields.iter().map(Samples::segments).collect(); - let mut segment = vec![0usize; all.len()]; - let mut offset = vec![0usize; all.len()]; - let mut pos = 0usize; + let mut cursor = RawSeriesChunkCursor::try_new(schema, mode, chunk.clone())?; let mut batches = Vec::new(); - while pos < times.len() { - let take = all - .iter() - .enumerate() - .map(|(i, parts)| parts[segment[i]].len() - offset[i]) - .min() - .unwrap_or(times.len()) - .min(times.len() - pos); - if take == 0 { - return invalid_series("empty sample segment"); - } - let pieces = all - .iter() - .enumerate() - .map(|(i, parts)| parts[segment[i]].slice(offset[i], take)) - .collect::>>()?; - batches.push(encode_row( - &frame_schema, - mode, - &checked.read_key, - checked.metric.as_ref(), - checked.is_last && pos + take == times.len(), - times.slice(pos, take), - &pieces, - )?); - pos += take; - for (i, parts) in all.iter().enumerate() { - offset[i] += take; - if offset[i] == parts[segment[i]].len() { - segment[i] += 1; - offset[i] = 0; + while let Some(batch) = cursor.append_to(&mut builder)? { + batches.push(batch); + } + if let Some(batch) = builder.flush()? { + batches.push(batch); + } + Ok(batches) +} + +/// One pending output row: a complete key with one dense sample slice per field and its checked +/// encoded-size measure. +struct RawFrameRow { + primary_key: Buffer, + metric: Option, + is_last: bool, + times: ScalarBuffer, + samples: Vec, + bytes: usize, +} + +/// Per-row encoded-size measure, computed once per row when the cursor produces it. +/// +/// The measure dominates every cumulative offset domain the encoder writes: binary/UTF-8 child +/// bytes, list element counts, bitmap bytes, and the visible extent of each histogram table list. +/// A group total of `min(max_bytes, i32::MAX)` therefore guarantees that all Arrow offsets and +/// lengths stay representable, without tracking a separate offset counter. This is a bound used +/// for batching work, not the exact encoded size. +fn measure_row(row: &RawFrameRow) -> Result { + checked_offset(row.primary_key.len())?; + checked_offset(row.times.len())?; + let mut bytes = add_checked(ROW_CHARGE, row.primary_key.len())?; + bytes = add_checked(bytes, mul_checked(row.times.len(), 8)?)?; + for samples in &row.samples { + bytes = add_checked(bytes, FIELD_CHARGE)?; + match samples + .dense() + .ok_or_else(|| err("sample segment is not dense"))? + { + DenseSamplesRef::Float(values) => { + bytes = add_checked(bytes, float_charge(values.len())?)? + } + DenseSamplesRef::Histogram(values) => { + bytes = add_checked(bytes, histogram_charge(values)?)? + } + DenseSamplesRef::Mixed(values) => { + bytes = add_checked(bytes, float_charge(values.floats().len())?)?; + bytes = add_checked(bytes, histogram_charge(values.histograms())?)?; } } } - Ok(batches) + if let Some(metric) = &row.metric { + if let Some(name) = metric.name() { + checked_offset(name.len())?; + bytes = add_checked(bytes, name.len())?; + } + checked_offset(metric.tags().len())?; + bytes = add_checked(bytes, mul_checked(metric.tags().len(), 16)?)?; + let mut names = 0usize; + let mut values = 0usize; + for label in metric.tags() { + names = add_checked(names, label.name.len())?; + values = add_checked(values, label.value.len())?; + } + checked_offset(names)?; + checked_offset(values)?; + bytes = add_checked(bytes, names)?; + bytes = add_checked(bytes, values)?; + } + Ok(bytes) +} + +/// Float values plus their validity bitmap. +fn float_charge(len: usize) -> Result { + checked_offset(len)?; + add_checked(mul_checked(len, 8)?, bitmap_bytes(len)) +} + +/// Reference indices plus their bitmap and the full referenced histogram table. +fn histogram_charge(values: &HistogramSamples) -> Result { + let indices = values.indices(); + checked_offset(indices.len())?; + let mut bytes = add_checked(mul_checked(indices.len(), 4)?, bitmap_bytes(indices.len()))?; + let table = values.batch().as_arrow(); + checked_offset(table.len())?; + bytes = add_checked( + bytes, + add_checked( + HISTOGRAM_TABLE_CHARGE, + mul_checked(table.len(), HISTOGRAM_ROW_CHARGE)?, + )?, + )?; + for (position, width) in HISTOGRAM_LIST_WIDTHS.iter().enumerate() { + let list = table + .column(7 + position) + .as_any() + .downcast_ref::() + .ok_or_else(|| err("histogram table schema mismatch"))?; + // `value_offsets` is already a view of the visible slice; the retained child array may be + // wider than the offsets span, so charge the visible extent rather than its length. + let offsets = list.value_offsets(); + let first = offsets + .first() + .copied() + .ok_or_else(|| err("histogram table schema mismatch"))?; + let last = offsets + .get(list.len()) + .copied() + .ok_or_else(|| err("histogram table schema mismatch"))?; + let span = last + .checked_sub(first) + .and_then(|span| usize::try_from(span).ok()) + .ok_or_else(|| err("histogram table offsets are invalid"))?; + bytes = add_checked(bytes, mul_checked(span, *width)?)?; + } + Ok(bytes) +} + +/// Encodes buffered rows as one batch with direct N-row Arrow array construction. +/// +/// Row-local histogram indices stay exactly as encoded: physical tables are concatenated under +/// cumulative row list offsets, so no index is remapped. Each histogram-bearing row carries its +/// complete table, including unreferenced entries; many segments referencing one large table can +/// therefore repeat that table in the encoded batch. A single constituent child array is reused +/// by clone (sharing its buffers); multiple constituents are concatenated, which copies. +fn encode_rows( + schema: &SchemaRef, + mode: RawLabelMode, + rows: &[RawFrameRow], +) -> Result { + let count = rows.len(); + let DataType::Struct(time_fields) = schema.field(2).data_type() else { + return invalid_series("time schema mismatch"); + }; + let DataType::List(time_item) = time_fields[0].data_type() else { + return invalid_series("time schema mismatch"); + }; + let DataType::Struct(field_types) = schema.field(3).data_type() else { + return invalid_series("fields schema mismatch"); + }; + let mut time_lengths = Vec::with_capacity(count); + let mut time_parts: Vec = Vec::with_capacity(count); + for row in rows { + time_lengths.push(row.times.len()); + time_parts.push(Arc::new(Int64Array::new(row.times.clone(), None))); + } + let time_child = materialize_parts(&time_parts, || { + Ok(Arc::new(Int64Array::new_null(0)) as ArrayRef) + })?; + let times = list_array(&time_lengths, time_child, time_item.as_ref().clone(), None)?; + let time = struct_array(time_fields.clone(), vec![Arc::new(times)])?; + + let mut empty_table: Option = None; + let mut field_arrays = Vec::with_capacity(field_types.len()); + for (index, field) in field_types.iter().enumerate() { + let DataType::Struct(payload) = field.data_type() else { + return invalid_series("payload schema mismatch"); + }; + let DataType::List(float_item) = payload[0].data_type() else { + return invalid_series("float values schema mismatch"); + }; + let DataType::Struct(histogram_fields) = payload[1].data_type() else { + return invalid_series("histogram schema mismatch"); + }; + let DataType::List(index_item) = histogram_fields[0].data_type() else { + return invalid_series("histogram index schema mismatch"); + }; + let DataType::List(table_item) = histogram_fields[1].data_type() else { + return invalid_series("histogram table schema mismatch"); + }; + let DataType::Struct(table_fields) = table_item.data_type() else { + return invalid_series("histogram table schema mismatch"); + }; + let mut float_lengths = Vec::with_capacity(count); + let mut float_parts: Vec = Vec::new(); + let mut float_valid = Vec::with_capacity(count); + let mut index_lengths = Vec::with_capacity(count); + let mut index_parts: Vec = Vec::new(); + let mut table_lengths = Vec::with_capacity(count); + let mut table_parts: Vec = Vec::new(); + let mut histogram_valid = Vec::with_capacity(count); + for row in rows { + let dense = row + .samples + .get(index) + .ok_or_else(|| err("raw frame row field count mismatch"))? + .dense() + .ok_or_else(|| err("sample segment is not dense"))?; + match dense { + DenseSamplesRef::Float(values) => { + float_lengths.push(values.len()); + float_parts.push(Arc::new(values.clone())); + float_valid.push(true); + index_lengths.push(0); + table_lengths.push(0); + histogram_valid.push(false); + } + DenseSamplesRef::Histogram(values) => { + float_lengths.push(0); + float_valid.push(false); + index_lengths.push(values.len()); + index_parts.push(Arc::new(values.indices().clone())); + table_lengths.push(values.batch().len()); + table_parts.push(Arc::new(values.batch().as_arrow().clone())); + histogram_valid.push(true); + } + DenseSamplesRef::Mixed(values) => { + float_lengths.push(values.floats().len()); + float_parts.push(Arc::new(values.floats().clone())); + float_valid.push(true); + index_lengths.push(values.histograms().len()); + index_parts.push(Arc::new(values.histograms().indices().clone())); + table_lengths.push(values.histograms().batch().len()); + table_parts.push(Arc::new(values.histograms().batch().as_arrow().clone())); + histogram_valid.push(true); + } + } + } + let float_child = materialize_parts(&float_parts, || { + Ok(Arc::new(Float64Array::new_null(0)) as ArrayRef) + })?; + let floats = list_array( + &float_lengths, + float_child, + float_item.as_ref().clone(), + validity(&float_valid), + )?; + let index_child = materialize_parts(&index_parts, || { + Ok(Arc::new(UInt32Array::new_null(0)) as ArrayRef) + })?; + let indices = list_array( + &index_lengths, + index_child, + index_item.as_ref().clone(), + None, + )?; + // A batch without histogram tables shares one empty schema-typed table, built once here + // instead of per float-only row. + let table_child = if table_parts.is_empty() { + match &empty_table { + Some(table) => table.clone(), + None => { + let table = empty_histogram_table(table_fields)?; + empty_table = Some(table.clone()); + table + } + } + } else { + materialize_parts(&table_parts, || Err(err("missing histogram table values")))? + }; + let tables = list_array( + &table_lengths, + table_child, + table_item.as_ref().clone(), + None, + )?; + let histogram = arrow(StructArray::try_new( + histogram_fields.clone(), + vec![Arc::new(indices), Arc::new(tables)], + validity(&histogram_valid), + ))?; + field_arrays.push(Arc::new(struct_array( + payload.clone(), + vec![Arc::new(floats), Arc::new(histogram)], + )?) as ArrayRef); + } + let fields = struct_array(field_types.clone(), field_arrays)?; + + let mut columns: Vec = vec![ + Arc::new(binary_array(rows)?), + Arc::new(BooleanArray::from( + rows.iter().map(|row| row.is_last).collect::>(), + )), + Arc::new(time), + Arc::new(fields), + ]; + if mode == RawLabelMode::Explicit { + columns.push(Arc::new( + rows.iter() + .map(|row| row.metric.as_ref().and_then(MetricName::name)) + .collect::(), + )); + let DataType::List(label_item) = schema.field(5).data_type() else { + return invalid_series("labels schema mismatch"); + }; + let DataType::Struct(label_fields) = label_item.data_type() else { + return invalid_series("labels schema mismatch"); + }; + let mut label_lengths = Vec::with_capacity(count); + let mut tag_names: Vec<&str> = Vec::new(); + let mut tag_values: Vec<&str> = Vec::new(); + for row in rows { + let metric = row + .metric + .as_ref() + .ok_or_else(|| err("explicit labels missing"))?; + label_lengths.push(metric.tags().len()); + for label in metric.tags() { + tag_names.push(label.name.as_ref()); + tag_values.push(label.value.as_ref()); + } + } + let labels = struct_array( + label_fields.clone(), + vec![ + Arc::new(StringArray::from_iter_values(tag_names)), + Arc::new(StringArray::from_iter_values(tag_values)), + ], + )?; + columns.push(Arc::new(list_array( + &label_lengths, + Arc::new(labels), + label_item.as_ref().clone(), + None, + )?)); + } + + arrow(RecordBatch::try_new_with_options( + schema.clone(), + columns, + &RecordBatchOptions::new().with_row_count(Some(count)), + )) +} + +/// Row-level binary keys; keys are copied exactly like the previous single-row encoder. +fn binary_array(rows: &[RawFrameRow]) -> Result { + let mut offsets = Vec::with_capacity(rows.len() + 1); + let mut total = 0usize; + offsets.push(0); + for row in rows { + total = add_checked(total, row.primary_key.len())?; + offsets.push(checked_offset(total)?); + } + let mut values = Vec::with_capacity(total); + for row in rows { + values.extend_from_slice(row.primary_key.as_slice()); + } + arrow(BinaryArray::try_new( + OffsetBuffer::new(ScalarBuffer::from(offsets)), + Buffer::from_vec(values), + None, + )) +} + +/// Per-row charge for key/time/nullable overhead shared by every row. +const ROW_CHARGE: usize = 64; +/// Per-field charge for the payload struct, nested list and validity overhead. +const FIELD_CHARGE: usize = 64; +/// Conservative per-table-row charge: the fixed fourteen-column histogram schema has seven +/// primitive columns plus seven list columns whose item widths are [`HISTOGRAM_LIST_WIDTHS`]. +const HISTOGRAM_ROW_CHARGE: usize = 128; +/// Fixed per-histogram charge for the seven list columns' offset and validity overhead. +const HISTOGRAM_TABLE_CHARGE: usize = 28; +/// Item widths of histogram table list columns `7..=13`, in that order. +const HISTOGRAM_LIST_WIDTHS: [usize; 7] = [8, 4, 4, 8, 4, 4, 8]; + +fn list_array( + lengths: &[usize], + values: ArrayRef, + item: Field, + nulls: Option, +) -> Result { + arrow(ListArray::try_new( + Arc::new(item), + offset_buffer(lengths)?, + values, + nulls, + )) +} + +fn offset_buffer(lengths: &[usize]) -> Result> { + let mut offsets = Vec::with_capacity(lengths.len() + 1); + let mut total = 0usize; + offsets.push(0); + for length in lengths { + total = add_checked(total, *length)?; + offsets.push(checked_offset(total)?); + } + Ok(OffsetBuffer::new(ScalarBuffer::from(offsets))) +} + +/// Materializes one list child: a single constituent is cloned to keep its buffers shared. +fn materialize_parts( + parts: &[ArrayRef], + empty: impl FnOnce() -> Result, +) -> Result { + match parts { + [] => empty(), + [only] => Ok(only.clone()), + _ => arrow(concat( + &parts.iter().map(|array| &**array).collect::>(), + )), + } +} + +fn empty_histogram_table(fields: &Fields) -> Result { + let columns = fields + .iter() + .map(|field| arrow::array::new_null_array(field.data_type(), 0)) + .collect(); + arrow(StructArray::try_new(fields.clone(), columns, None)) + .map(|table| Arc::new(table) as ArrayRef) +} + +fn validity(valid: &[bool]) -> Option { + if valid.iter().all(|valid| *valid) { + None + } else { + Some(NullBuffer::from(valid.to_vec())) + } +} + +fn bitmap_bytes(len: usize) -> usize { + len.div_ceil(8) +} + +fn add_checked(total: usize, amount: usize) -> Result { + total + .checked_add(amount) + .ok_or_else(|| err("raw series frame offset overflow")) +} + +fn mul_checked(len: usize, width: usize) -> Result { + len.checked_mul(width) + .ok_or_else(|| err("raw series frame offset overflow")) +} + +/// Reuses one prepared frame schema while decoding all batches of a stream. +pub struct RawSeriesFrameDecoder { + schema: SeriesSchema, + mode: RawLabelMode, + expected: SchemaRef, +} + +impl RawSeriesFrameDecoder { + /// Builds the expected frame schema once from the series schema and label mode. + pub fn try_new(schema: &SeriesSchema, mode: RawLabelMode) -> Result { + Ok(Self { + schema: schema.clone(), + mode, + expected: raw_series_frame_schema(schema, mode)?, + }) + } + + /// Decodes all rows of one batch, checking its reserved metadata, declared fields, and rows. + pub fn decode(&self, batch: &RecordBatch) -> Result> { + decode_raw_series_frame(&self.schema, self.mode, &self.expected, batch) + } } /// Decodes all rows of a raw frame; any malformed row makes the entire call fail. @@ -198,7 +853,15 @@ pub fn unpack_raw_series_frame( mode: RawLabelMode, batch: &RecordBatch, ) -> Result> { - let expected = raw_series_frame_schema(schema, mode)?; + RawSeriesFrameDecoder::try_new(schema, mode)?.decode(batch) +} + +fn decode_raw_series_frame( + schema: &SeriesSchema, + mode: RawLabelMode, + expected: &SchemaRef, + batch: &RecordBatch, +) -> Result> { let actual = batch.schema(); for key in [LAYOUT, CONTENT, LABELS, TIME] { if actual.metadata().get(key) != expected.metadata().get(key) { @@ -307,18 +970,17 @@ pub fn unpack_raw_series_frame( } let table = down::(&tables.value(row), "histogram table")?.clone(); let batch = Arc::new(HistogramBatch::try_from_arrow(table)?); - let hs = HistogramSamples::try_new(indices, batch)?; if has_float { - Samples::try_from_mixed(floats, hs)? + Samples::try_from_mixed(floats, HistogramSamples::try_new(indices, batch)?)? } else { - Samples::try_from_histogram(hs.indices().clone(), hs.batch().clone())? + Samples::try_from_histogram(indices, batch)? } }; decoded.push(samples); } let fields = SeriesFields::try_from_vec(decoded)?; let key = binary_slice(keys, row)?; - let raw_time = RawTimeAxis::try_new(time)?; + let raw_time = RawTimestamps::try_new(time)?; out.push(RawSeriesChunk::try_new( schema, key, @@ -331,149 +993,6 @@ pub fn unpack_raw_series_frame( Ok(out) } -fn encode_row( - schema: &SchemaRef, - mode: RawLabelMode, - key: &Buffer, - metric: Option<&MetricName>, - last: bool, - times: ScalarBuffer, - samples: &[Samples], -) -> Result { - let mut arrays: Vec = vec![ - Arc::new(binary_one(key.as_slice())?), - Arc::new(BooleanArray::from(vec![last])), - ]; - let ts = wrap_list( - Arc::new(Int64Array::new(times, None)), - DataType::Int64, - false, - )?; - let DataType::Struct(time_fields) = schema.field(2).data_type() else { - return invalid_series("time schema mismatch"); - }; - arrays.push(Arc::new(struct_array( - time_fields.clone(), - vec![Arc::new(ts)], - )?)); - let DataType::Struct(field_schema) = schema.field(3).data_type() else { - return invalid_series("fields schema mismatch"); - }; - let DataType::Struct(first_payload) = field_schema[0].data_type() else { - return invalid_series("payload schema mismatch"); - }; - let DataType::Struct(histogram_fields) = first_payload[1].data_type() else { - return invalid_series("histogram schema mismatch"); - }; - let mut field_arrays = Vec::new(); - for sample in samples { - let DataType::Struct(dtype) = field_schema[field_arrays.len()].data_type() else { - return invalid_series("payload schema mismatch"); - }; - let (floats, hist) = encode_payload(sample, histogram_fields)?; - field_arrays.push(Arc::new(struct_array(dtype.clone(), vec![floats, hist])?) as ArrayRef); - } - arrays.push(Arc::new(struct_array(field_schema.clone(), field_arrays)?)); - if mode == RawLabelMode::Explicit { - let metric = metric.ok_or_else(|| err("explicit labels missing"))?; - checked_offset(metric.name().map_or(0, str::len))?; - arrays.push(Arc::new(StringArray::from(vec![metric.name()]))); - checked_offset(metric.tags().len())?; - checked_offset( - metric - .tags() - .iter() - .try_fold(0usize, |n, l| n.checked_add(l.name.len())) - .ok_or_else(|| err("label name length overflow"))?, - )?; - checked_offset( - metric - .tags() - .iter() - .try_fold(0usize, |n, l| n.checked_add(l.value.len())) - .ok_or_else(|| err("label value length overflow"))?, - )?; - let names: StringArray = metric - .tags() - .iter() - .map(|l| Some(l.name.as_ref())) - .collect(); - let values: StringArray = metric - .tags() - .iter() - .map(|l| Some(l.value.as_ref())) - .collect(); - let DataType::List(label_list) = schema.field(5).data_type() else { - return invalid_series("labels schema mismatch"); - }; - let DataType::Struct(label_fields) = label_list.data_type() else { - return invalid_series("label struct schema mismatch"); - }; - let labels = struct_array( - label_fields.clone(), - vec![Arc::new(names), Arc::new(values)], - )?; - arrays.push(Arc::new(wrap_list( - Arc::new(labels), - DataType::Struct(label_fields.clone()), - false, - )?)); - } - arrow(RecordBatch::try_new_with_options( - schema.clone(), - arrays, - &RecordBatchOptions::new().with_row_count(Some(1)), - )) -} - -fn encode_payload(samples: &Samples, histogram_fields: &Fields) -> Result<(ArrayRef, ArrayRef)> { - let (floats, histograms) = match samples - .dense() - .ok_or_else(|| err("sample segment is not dense"))? - { - DenseSamplesRef::Float(values) => (Some(values), None), - DenseSamplesRef::Histogram(values) => (None, Some(values)), - DenseSamplesRef::Mixed(values) => (Some(values.floats()), Some(values.histograms())), - }; - let float_array = match floats { - Some(values) => Arc::new(wrap_list( - Arc::new(values.clone()), - DataType::Float64, - true, - )?) as ArrayRef, - None => Arc::new(ListArray::new_null( - Arc::new(Field::new("item", DataType::Float64, true)), - 1, - )) as ArrayRef, - }; - let hist_array = match histograms { - Some(values) => { - let DataType::List(indices_field) = histogram_fields[0].data_type() else { - return invalid_series("histogram index schema mismatch"); - }; - let DataType::List(table_field) = histogram_fields[1].data_type() else { - return invalid_series("histogram table schema mismatch"); - }; - let indices = wrap_list( - Arc::new(values.indices().clone()), - indices_field.data_type().clone(), - true, - )?; - let table = wrap_list( - Arc::new(values.batch().as_arrow().clone()), - table_field.data_type().clone(), - false, - )?; - Arc::new(struct_array( - histogram_fields.clone(), - vec![Arc::new(indices), Arc::new(table)], - )?) as ArrayRef - } - None => null_histogram(histogram_fields)?, - }; - Ok((float_array, hist_array)) -} - fn binary_slice(array: &BinaryArray, row: usize) -> Result { let offsets = array.value_offsets(); let start = usize::try_from(offsets[row]).map_err(|_| err("negative binary offset"))?; @@ -483,68 +1002,29 @@ fn binary_slice(array: &BinaryArray, row: usize) -> Result { .ok_or_else(|| err("invalid binary offsets"))?; Ok(array.values().slice_with_length(start, len)) } -fn binary_one(value: &[u8]) -> Result { - checked_offset(value.len())?; - Ok(BinaryArray::from(vec![Some(value)])) -} + fn checked_offset(len: usize) -> Result { i32::try_from(len).map_err(|_| err("Arrow offset limit exceeded")) } -fn offsets(len: usize) -> Result> { - let len = checked_offset(len)?; - Ok(OffsetBuffer::new(ScalarBuffer::from(vec![0, len]))) -} -fn wrap_list(values: ArrayRef, item: DataType, nullable: bool) -> Result { - let len = values.len(); - arrow(ListArray::try_new( - Arc::new(Field::new("item", item, nullable)), - offsets(len)?, - values, - None, - )) -} -fn null_histogram(fields: &Fields) -> Result { - let DataType::List(indices_field) = fields[0].data_type() else { - return invalid_series("histogram index schema mismatch"); - }; - let DataType::List(table_field) = fields[1].data_type() else { - return invalid_series("histogram table schema mismatch"); - }; - let DataType::Struct(table_fields) = table_field.data_type() else { - return invalid_series("histogram table schema mismatch"); - }; - let indices = wrap_list( - Arc::new(UInt32Array::new_null(0)), - indices_field.data_type().clone(), - true, - )?; - let columns = table_fields - .iter() - .map(|f| arrow::array::new_null_array(f.data_type(), 0)) - .collect(); - let table = arrow(StructArray::try_new(table_fields.clone(), columns, None))?; - let table = wrap_list(Arc::new(table), table_field.data_type().clone(), false)?; - Ok(Arc::new(arrow(StructArray::try_new( - fields.clone(), - vec![Arc::new(indices), Arc::new(table)], - Some(NullBuffer::new_null(1)), - ))?)) -} + fn struct_array(fields: Fields, arrays: Vec) -> Result { arrow(StructArray::try_new(fields, arrays, None)) } + fn down<'a, T: Array + 'static>(array: &'a ArrayRef, label: &str) -> Result<&'a T> { array .as_any() .downcast_ref() .ok_or_else(|| err(format!("{label} type mismatch"))) } + fn err(reason: impl Into) -> crate::error::Error { InvalidSeriesSnafu { reason: reason.into(), } .build() } + fn arrow(result: std::result::Result) -> Result { result.map_err(|e| err(e.to_string())) } diff --git a/src/datatypes/src/series/frame/tests.rs b/src/datatypes/src/series/frame/tests.rs index 7edc38168b5..976a433ee27 100644 --- a/src/datatypes/src/series/frame/tests.rs +++ b/src/datatypes/src/series/frame/tests.rs @@ -15,11 +15,13 @@ use std::sync::Arc; use arrow::array::{ - Array, Float64Array, Int64Array, ListArray, StringArray, StructArray, UInt32Array, + Array, BinaryArray, BooleanArray, Float64Array, Int64Array, ListArray, StringArray, + StructArray, UInt32Array, }; use arrow::buffer::{Buffer, OffsetBuffer, ScalarBuffer}; use arrow::compute::concat_batches; use arrow::datatypes::{DataType, Field, Schema}; +use arrow::ipc::{reader::StreamReader, writer::StreamWriter}; use super::*; use crate::series::histogram::{BucketSideView, CounterResetHint, HistogramBatchBuilder}; @@ -67,7 +69,7 @@ fn float_chunk( schema, Buffer::from(key.to_vec()), metric, - RawTimeAxis::try_new(times.into()).unwrap(), + RawTimestamps::try_new(times.into()).unwrap(), SeriesFields::one(Samples::from_float(Float64Array::from(values))), is_last, ) @@ -247,6 +249,107 @@ fn assert_float_bits(actual: &Samples, expected: &[Option]) { } } +/// Packs one owned chunk through the public cursor/builder pair, mirroring the explicit +/// single-chunk wrapper: every batch the walk produces, then the final flush. +fn pack_chunk_with_budget( + schema: &SeriesSchema, + mode: RawLabelMode, + chunk: &RawSeriesChunk, + max_rows: usize, + max_bytes: usize, +) -> crate::error::Result> { + let mut builder = RawSeriesFrameBuilder::try_new(schema, mode, max_rows, max_bytes)?; + let mut cursor = RawSeriesChunkCursor::try_new(schema, mode, chunk.clone())?; + let mut batches = Vec::new(); + while let Some(batch) = cursor.append_to(&mut builder)? { + batches.push(batch); + } + if let Some(batch) = builder.flush()? { + batches.push(batch); + } + Ok(batches) +} + +/// Advances one owned chunk through an existing builder. A partially filled buffer stays buffered +/// instead of becoming a batch of its own, which is what makes cross-chunk grouping observable. +fn append_chunk( + builder: &mut RawSeriesFrameBuilder, + schema: &SeriesSchema, + mode: RawLabelMode, + chunk: &RawSeriesChunk, +) -> crate::error::Result> { + let mut cursor = RawSeriesChunkCursor::try_new(schema, mode, chunk.clone())?; + let mut batches = Vec::new(); + while let Some(batch) = cursor.append_to(builder)? { + batches.push(batch); + } + Ok(batches) +} + +/// Decodes every batch with one reused decoder, so repeated calls exercise the cached schema. +fn decode_batches( + schema: &SeriesSchema, + mode: RawLabelMode, + batches: &[RecordBatch], +) -> Vec { + let decoder = RawSeriesFrameDecoder::try_new(schema, mode).unwrap(); + batches + .iter() + .flat_map(|batch| decoder.decode(batch).unwrap()) + .collect() +} + +/// Row-local histogram index and table lists of one field payload of a frame batch. +fn frame_histogram_lists(batch: &RecordBatch, field: usize) -> (ListArray, ListArray) { + let histogram = frame_field_payload(batch, field) + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + let indices = histogram + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .clone(); + let tables = histogram + .column(1) + .as_any() + .downcast_ref::() + .unwrap() + .clone(); + (indices, tables) +} + +/// Every row is expected to resolve index 0 inside its own table only, with the whole table +/// retained and the other index entry null. +fn assert_row_local_histogram_rows(rows: &[RawSeriesChunk]) { + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].time.as_buffer().as_ref(), &[1_i64, 2]); + assert_eq!(rows[1].time.as_buffer().as_ref(), &[3_i64, 4]); + + let DenseSamplesRef::Histogram(first) = rows[0].fields.get(0).unwrap().dense().unwrap() else { + panic!("expected histogram samples"); + }; + assert_eq!(first.batch().len(), 2); + assert_eq!(first.indices().len(), 2); + assert_eq!(first.indices().value(0), 0); + assert!(!first.indices().is_valid(1)); + assert_histogram(first.view_at(0).unwrap(), -9.5); + assert_unreferenced_histogram(first.batch().view(1).unwrap()); + + let DenseSamplesRef::Histogram(second) = rows[1].fields.get(0).unwrap().dense().unwrap() else { + panic!("expected histogram samples"); + }; + assert_eq!(second.batch().len(), 2); + assert_eq!(second.indices().len(), 2); + assert!(!second.indices().is_valid(0)); + assert_eq!(second.indices().value(1), 0); + // A global index remap would resolve index 0 into the first row's table instead. + assert_histogram(second.view_at(1).unwrap(), 42.25); + assert_histogram_with_start(second.batch().view(1).unwrap(), 142.25, None); +} + #[test] fn sliced_histogram_frames_densify_without_duplicating_shared_table() { let schema = test_schema(&["histogram"]); @@ -263,13 +366,22 @@ fn sliced_histogram_frames_densify_without_duplicating_shared_table() { &schema, Buffer::from(vec![0x42_u8]), None, - RawTimeAxis::try_new((0_i64..64).collect::>().into()).unwrap(), + RawTimestamps::try_new((0_i64..64).collect::>().into()).unwrap(), SeriesFields::one(samples), true, ) .unwrap(); - let frames = pack_raw_series_chunk(&schema, RawLabelMode::Key, &chunk).unwrap(); + // One row per batch keeps the original segment-boundary granularity, so the shared-table fast + // paths below stay observable; the default budget coalesces the same rows later on. + let frames = pack_chunk_with_budget( + &schema, + RawLabelMode::Key, + &chunk, + 1, + RawSeriesFrameBuilder::DEFAULT_MAX_BYTES, + ) + .unwrap(); assert_eq!(frames.len(), 64); let mut decoded_chunks = Vec::with_capacity(frames.len()); for frame in &frames { @@ -305,6 +417,24 @@ fn sliced_histogram_frames_densify_without_duplicating_shared_table() { second_values.values().as_ptr() ); + // The default budget groups the same 64 rows into one multirow batch; every row still decodes + // to its own slice of the shared table with bit-exact values. + let coalesced = pack_raw_series_chunk(&schema, RawLabelMode::Key, &chunk).unwrap(); + assert_eq!(coalesced.len(), 1); + assert_eq!(coalesced[0].num_rows(), 64); + let coalesced_rows = decode_batches(&schema, RawLabelMode::Key, &coalesced); + assert_eq!(coalesced_rows.len(), 64); + for (position, row) in coalesced_rows.iter().enumerate() { + assert_eq!(row.primary_key.as_slice(), &[0x42]); + assert_eq!(row.time.timestamp(0), Some(position as i64)); + let DenseSamplesRef::Histogram(histograms) = row.fields.get(0).unwrap().dense().unwrap() + else { + panic!("expected histogram samples"); + }; + assert_eq!(histograms.batch().len(), first_table.len()); + assert_histogram(histograms.view_at(0).unwrap(), -9.5); + } + let samples = Samples::try_from_chunks( decoded_chunks .iter() @@ -354,7 +484,7 @@ fn raw_frame_field_names_bind_payloads_to_their_schema() { &schema, Buffer::from(vec![0xaa_u8]), metric, - RawTimeAxis::try_new(vec![100, 200].into()).unwrap(), + RawTimestamps::try_new(vec![100, 200].into()).unwrap(), fields.clone(), true, ) @@ -375,9 +505,9 @@ fn raw_frame_field_names_bind_payloads_to_their_schema() { ); let decoded = unpack_raw_series_frame(&schema, mode, batch).unwrap(); - assert_eq!(decoded[0].read_key.as_slice(), &[0xaa]); + assert_eq!(decoded[0].primary_key.as_slice(), &[0xaa]); assert!(decoded[0].is_last); - let RawTimeAxis::Explicit(times) = &decoded[0].time; + let times = decoded[0].time.as_buffer(); assert_eq!(times.as_ref(), &[100, 200]); assert_float_bits(decoded[0].fields.get(0).unwrap(), &[Some(1.0), Some(2.0)]); assert_float_bits(decoded[0].fields.get(1).unwrap(), &[Some(10.0), Some(20.0)]); @@ -499,7 +629,7 @@ fn schema_and_key_explicit_round_trips_preserve_identity_and_bits() { assert_eq!(packed.len(), 1); let decoded = unpack_raw_series_frame(&schema, RawLabelMode::Key, &packed[0]).unwrap(); assert_eq!(decoded.len(), 1); - assert_eq!(decoded[0].read_key.as_slice(), &[0, 0xff, 0, 0x80]); + assert_eq!(decoded[0].primary_key.as_slice(), &[0, 0xff, 0, 0x80]); assert!(decoded[0].metric.is_none()); assert!(decoded[0].is_last); assert_eq!( @@ -520,7 +650,7 @@ fn schema_and_key_explicit_round_trips_preserve_identity_and_bits() { ); let packed = pack_raw_series_chunk(&schema, RawLabelMode::Explicit, &explicit).unwrap(); let decoded = unpack_raw_series_frame(&schema, RawLabelMode::Explicit, &packed[0]).unwrap(); - assert_eq!(decoded[0].read_key.as_slice(), &[0x80, 0, 0xff]); + assert_eq!(decoded[0].primary_key.as_slice(), &[0x80, 0, 0xff]); assert!(!decoded[0].is_last); let labels = decoded[0].metric.as_ref().unwrap(); assert_eq!(labels.name(), None); @@ -577,28 +707,31 @@ fn segmented_mixed_fields_emit_every_aligned_position_and_marker() { &schema, Buffer::from(vec![0_u8, 0x91, 0xfe]), None, - RawTimeAxis::try_new(vec![10_i64, 20, 30, 40].into()).unwrap(), + RawTimestamps::try_new(vec![10_i64, 20, 30, 40].into()).unwrap(), SeriesFields::try_from_vec(vec![first, second]).unwrap(), true, ) .unwrap(); + // Variable field boundaries now group every aligned interval into one multirow batch instead + // of one batch per boundary, so decode the actual rows that batch carries. let frames = pack_raw_series_chunk(&schema, RawLabelMode::Key, &chunk).unwrap(); - assert_eq!(frames.len(), 4); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].num_rows(), 4); let mut observed_times = Vec::new(); let mut observed_first = Vec::new(); let mut observed_second = Vec::new(); let mut observed_keys = Vec::new(); let mut observed_markers = Vec::new(); - for (frame_index, frame) in frames.iter().enumerate() { - let decoded = unpack_raw_series_frame(&schema, RawLabelMode::Key, frame).unwrap(); - assert_eq!(decoded.len(), 1); - assert_eq!(decoded[0].is_last, frame_index == frames.len() - 1); - observed_markers.push(decoded[0].is_last); - assert_eq!(decoded[0].read_key.as_slice(), &[0, 0x91, 0xfe]); - observed_keys.push(decoded[0].read_key.as_slice().to_vec()); - for position in 0..decoded[0].time.len() { - observed_times.push(decoded[0].time.timestamp(position).unwrap()); - match decoded[0].fields.get(0).unwrap().sample(position) { + let rows = unpack_raw_series_frame(&schema, RawLabelMode::Key, &frames[0]).unwrap(); + assert_eq!(rows.len(), 4); + for (row_index, row) in rows.iter().enumerate() { + assert_eq!(row.is_last, row_index == rows.len() - 1); + observed_markers.push(row.is_last); + assert_eq!(row.primary_key.as_slice(), &[0, 0x91, 0xfe]); + observed_keys.push(row.primary_key.as_slice().to_vec()); + for position in 0..row.time.len() { + observed_times.push(row.time.timestamp(position).unwrap()); + match row.fields.get(0).unwrap().sample(position) { SampleRef::Missing => observed_first.push(("m", 0.0_f64.to_bits())), SampleRef::Float(value) => observed_first.push(("f", value.to_bits())), SampleRef::Histogram(histogram) => { @@ -606,7 +739,7 @@ fn segmented_mixed_fields_emit_every_aligned_position_and_marker() { observed_first.push(("h", histogram.sum.to_bits())); } } - match decoded[0].fields.get(1).unwrap().sample(position) { + match row.fields.get(1).unwrap().sample(position) { SampleRef::Missing => observed_second.push(("m", 0.0_f64.to_bits())), SampleRef::Float(value) => observed_second.push(("f", value.to_bits())), SampleRef::Histogram(histogram) => { @@ -657,59 +790,59 @@ fn segmented_mixed_fields_emit_every_aligned_position_and_marker() { &aligned_schema, Buffer::from(vec![0xa1_u8]), None, - RawTimeAxis::try_new(vec![101_i64, 102, 103, 104, 105].into()).unwrap(), + RawTimestamps::try_new(vec![101_i64, 102, 103, 104, 105].into()).unwrap(), SeriesFields::try_from_vec(vec![a, b]).unwrap(), true, ) .unwrap(); let aligned_frames = pack_raw_series_chunk(&aligned_schema, RawLabelMode::Key, &aligned_chunk).unwrap(); + assert_eq!(aligned_frames.len(), 1); + assert_eq!(aligned_frames[0].num_rows(), 3); + let aligned_rows = + unpack_raw_series_frame(&aligned_schema, RawLabelMode::Key, &aligned_frames[0]).unwrap(); + assert_eq!(aligned_rows.len(), 3); let mut interval_lengths = Vec::new(); let mut aligned_times = Vec::new(); let mut aligned_a = Vec::new(); let mut aligned_b = Vec::new(); - for (i, batch) in aligned_frames.iter().enumerate() { - let decoded = unpack_raw_series_frame(&aligned_schema, RawLabelMode::Key, batch).unwrap(); - assert_eq!(decoded[0].is_last, i == 2); - interval_lengths.push(decoded[0].time.len()); + for (i, row) in aligned_rows.iter().enumerate() { + assert_eq!(row.is_last, i == aligned_rows.len() - 1); + interval_lengths.push(row.time.len()); let start = aligned_times.len(); - let DenseSamplesRef::Float(decoded_a) = decoded[0].fields.get(0).unwrap().dense().unwrap() - else { + let DenseSamplesRef::Float(decoded_a) = row.fields.get(0).unwrap().dense().unwrap() else { panic!("expected float field"); }; - let DenseSamplesRef::Float(decoded_b) = decoded[0].fields.get(1).unwrap().dense().unwrap() - else { + let DenseSamplesRef::Float(decoded_b) = row.fields.get(1).unwrap().dense().unwrap() else { panic!("expected float field"); }; - assert_eq!( - decoded_a.values().as_ptr(), - a_owner.values().as_ptr().wrapping_add(start) - ); - assert_eq!( - decoded_b.values().as_ptr(), - b_owner.values().as_ptr().wrapping_add(start) - ); + // Grouping several constituents into one row may copy their payloads, so compare values + // and validity bit-exactly instead of requiring the source buffers by pointer. for (decoded_values, owner) in [(&decoded_a, &a_owner), (&decoded_b, &b_owner)] { - match (decoded_values.nulls(), owner.nulls()) { - (Some(decoded_nulls), Some(owner_nulls)) => { - assert_eq!( - decoded_nulls.buffer().as_ptr(), - owner_nulls.buffer().as_ptr() - ); - assert_eq!(decoded_nulls.offset(), owner_nulls.offset() + start); + assert_eq!(decoded_values.len(), row.time.len()); + for position in 0..decoded_values.len() { + match ( + decoded_values.is_valid(position), + owner.is_valid(start + position), + ) { + (true, true) => assert_eq!( + decoded_values.value(position).to_bits(), + owner.value(start + position).to_bits(), + "grouping changed a value" + ), + (false, false) => {} + _ => panic!("grouping changed validity representation"), } - (None, None) => {} - _ => panic!("fragment changed validity representation"), } } - for position in 0..decoded[0].time.len() { - aligned_times.push(decoded[0].time.timestamp(position).unwrap()); - aligned_a.push(match decoded[0].fields.get(0).unwrap().sample(position) { + for position in 0..row.time.len() { + aligned_times.push(row.time.timestamp(position).unwrap()); + aligned_a.push(match row.fields.get(0).unwrap().sample(position) { SampleRef::Missing => None, SampleRef::Float(value) => Some(value.to_bits()), SampleRef::Histogram(_) => panic!("expected float field"), }); - aligned_b.push(match decoded[0].fields.get(1).unwrap().sample(position) { + aligned_b.push(match row.fields.get(1).unwrap().sample(position) { SampleRef::Missing => None, SampleRef::Float(value) => Some(value.to_bits()), SampleRef::Histogram(_) => panic!("expected float field"), @@ -757,7 +890,7 @@ fn segmented_mixed_fields_emit_every_aligned_position_and_marker() { &alternate_schema, Buffer::from(vec![0xde_u8, 0xad]), None, - RawTimeAxis::try_new(vec![100_i64].into()).unwrap(), + RawTimestamps::try_new(vec![100_i64].into()).unwrap(), SeriesFields::try_from_vec(vec![first_distinct, second_distinct]).unwrap(), false, ) @@ -781,7 +914,7 @@ fn segmented_mixed_fields_emit_every_aligned_position_and_marker() { .collect::>(), [10, 20, 30, 40, 100] ); - assert_eq!(decoded[4].read_key.as_slice(), &[0xde, 0xad]); + assert_eq!(decoded[4].primary_key.as_slice(), &[0xde, 0xad]); assert!( matches!(decoded[4].fields.get(0).unwrap().sample(0), SampleRef::Histogram(h) if h.sum.to_bits() == 123.0_f64.to_bits()) ); @@ -807,7 +940,7 @@ fn segmented_mixed_fields_emit_every_aligned_position_and_marker() { assert_eq!( sliced_rows .iter() - .map(|row| row.read_key.as_slice()) + .map(|row| row.primary_key.as_slice()) .collect::>(), [&[0xee][..], &[0xef][..], &[0xed][..]] ); @@ -837,7 +970,7 @@ fn segmented_mixed_fields_emit_every_aligned_position_and_marker() { &schema, Buffer::from(vec![0_u8, 0x91, 0xfe]), None, - RawTimeAxis::try_new(vec![50_i64, 60, 70, 80].into()).unwrap(), + RawTimestamps::try_new(vec![50_i64, 60, 70, 80].into()).unwrap(), chunk.fields.clone(), false, ) @@ -898,7 +1031,7 @@ fn histogram_payload_and_present_all_null_representation_survive() { &schema, Buffer::from(vec![0x12_u8, 0x00]), None, - RawTimeAxis::try_new(vec![1_i64, 2].into()).unwrap(), + RawTimestamps::try_new(vec![1_i64, 2].into()).unwrap(), fields, false, ) @@ -950,7 +1083,7 @@ fn histogram_payload_and_present_all_null_representation_survive() { &mixed_schema, Buffer::from(vec![0x42_u8]), None, - RawTimeAxis::try_new(vec![5_i64, 6].into()).unwrap(), + RawTimestamps::try_new(vec![5_i64, 6].into()).unwrap(), SeriesFields::one(mixed), false, ) @@ -1089,6 +1222,9 @@ fn rejects_invalid_schema_and_metadata_and_accepts_valid_empty() { #[test] fn rejects_invalid_timestamps_and_empty_raw_payloads() { + assert!(RawTimestamps::try_new(vec![1_i64, 1].into()).is_err()); + assert!(RawTimestamps::try_new(vec![2_i64, 1].into()).is_err()); + let schema = test_schema(&["value"]); let chunk = float_chunk(&schema, &[1], None, vec![1], vec![Some(2.0)], false); let valid = pack_raw_series_chunk(&schema, RawLabelMode::Key, &chunk) @@ -1335,7 +1471,7 @@ fn rejects_malformed_histogram_and_payload_encodings() { &hist_schema, Buffer::from(vec![1_u8]), None, - RawTimeAxis::try_new(vec![1_i64].into()).unwrap(), + RawTimestamps::try_new(vec![1_i64].into()).unwrap(), SeriesFields::one( Samples::try_from_histogram(UInt32Array::from(vec![Some(0)]), histogram_batch()) .unwrap(), @@ -1705,7 +1841,7 @@ fn decoded_key_and_payload_slices_keep_buffers_alive() { &schema, Buffer::from(vec![0xaa_u8, 0x10, 0x20, 0xbb]), None, - RawTimeAxis::try_new(vec![0_i64, 11, 22, 33].into()) + RawTimestamps::try_new(vec![0_i64, 11, 22, 33].into()) .unwrap() .slice(1, 2) .unwrap(), @@ -1776,9 +1912,9 @@ fn decoded_key_and_payload_slices_keep_buffers_alive() { .as_any() .downcast_ref::() .unwrap(); - let crate::series::raw::RawTimeAxis::Explicit(decoded_time) = &decoded[0].time; + let decoded_time = decoded[0].time.as_buffer(); assert_eq!(decoded_time.as_ptr(), time_values.values().as_ptr()); - let crate::series::raw::RawTimeAxis::Explicit(source_time) = &chunk.time; + let source_time = chunk.time.as_buffer(); assert_eq!(decoded_time.as_ptr(), source_time.as_ptr()); drop(owner); drop(chunk); @@ -1790,7 +1926,7 @@ fn decoded_key_and_payload_slices_keep_buffers_alive() { decoded[0].fields.get(0).unwrap().sample(1), SampleRef::Missing )); - assert_eq!(decoded[0].read_key.as_slice(), &[0xaa, 0x10, 0x20, 0xbb]); + assert_eq!(decoded[0].primary_key.as_slice(), &[0xaa, 0x10, 0x20, 0xbb]); } #[test] @@ -1855,7 +1991,7 @@ fn sliced_canonical_mixed_histogram_round_trip_keeps_buffers_alive() { &schema, Buffer::from(vec![0x42_u8]), None, - RawTimeAxis::try_new(vec![0_i64, 11, 22, 33].into()) + RawTimestamps::try_new(vec![0_i64, 11, 22, 33].into()) .unwrap() .slice(1, 2) .unwrap(), @@ -1948,9 +2084,19 @@ fn sliced_canonical_mixed_histogram_round_trip_keeps_buffers_alive() { .values() .as_ptr() ); - let crate::series::raw::RawTimeAxis::Explicit(source_times) = &chunk.time; + let source_times = chunk.time.as_buffer(); - let frames = pack_raw_series_chunk(&schema, RawLabelMode::Key, &chunk).unwrap(); + // One row per batch keeps this fixture's single constituents and their nonzero offsets + // observable: the default budget could coalesce several rows and copy their payloads. + let frames = pack_chunk_with_budget( + &schema, + RawLabelMode::Key, + &chunk, + 1, + RawSeriesFrameBuilder::DEFAULT_MAX_BYTES, + ) + .unwrap(); + assert_eq!(frames.len(), 1); let packed = &frames[0]; let packed_times = packed .column(2) @@ -2064,7 +2210,7 @@ fn sliced_canonical_mixed_histogram_round_trip_keeps_buffers_alive() { else { panic!("histogram representation was normalized"); }; - let crate::series::raw::RawTimeAxis::Explicit(decoded_time_values) = &decoded[0].time; + let decoded_time_values = decoded[0].time.as_buffer(); assert_eq!(decoded_time_values.as_ptr(), packed_times.values().as_ptr()); assert_eq!(decoded_time_values, source_times); for (decoded_indices, source_indices) in [ @@ -2310,3 +2456,605 @@ fn public_segments_are_flat_ordered_and_retain_empty_dense_kinds() { Some(DenseSamplesRef::Float(_)) )); } + +#[test] +fn cross_chunk_rows_coalesce_into_one_multirow_batch() { + let schema = test_schema(&["value"]); + let first = float_chunk( + &schema, + &[0xaa], + None, + vec![10, 20], + vec![Some(1.0), None], + false, + ); + let second = float_chunk( + &schema, + &[0xbb], + None, + vec![30, 40, 50], + vec![Some(3.0), Some(4.0), None], + true, + ); + assert_eq!(RawSeriesFrameBuilder::DEFAULT_MAX_ROWS, 256); + assert_eq!(RawSeriesFrameBuilder::DEFAULT_MAX_BYTES, 1 << 20); + let expected = raw_series_frame_schema(&schema, RawLabelMode::Key).unwrap(); + + let mut builder = RawSeriesFrameBuilder::try_new( + &schema, + RawLabelMode::Key, + RawSeriesFrameBuilder::DEFAULT_MAX_ROWS, + RawSeriesFrameBuilder::DEFAULT_MAX_BYTES, + ) + .unwrap(); + assert_eq!(builder.schema(), &expected); + + let mut batches = append_chunk(&mut builder, &schema, RawLabelMode::Key, &first).unwrap(); + batches.extend(append_chunk(&mut builder, &schema, RawLabelMode::Key, &second).unwrap()); + if let Some(batch) = builder.flush().unwrap() { + batches.push(batch); + } + // Rows of both chunks coalesce into one batch: a partially filled buffer must survive the + // cursor boundary instead of becoming a batch of its own. + assert_eq!(batches.len(), 1); + let batch = &batches[0]; + assert_eq!(batch.num_rows(), 2); + assert_eq!(batch.schema(), expected); + assert_eq!( + batch + .schema() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>(), + ["read_key", "is_last", "time", "fields"] + ); + for (key, value) in [ + ("greptime.series.layout", "v1"), + ("greptime.series.content", "raw"), + ("greptime.series.labels", "key"), + ("greptime.series.time", "timestamps"), + ] { + assert_eq!( + batch.schema().metadata().get(key).map(String::as_str), + Some(value) + ); + } + + let keys = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(keys.value(0), &[0xaa]); + assert_eq!(keys.value(1), &[0xbb]); + let lasts = batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + (0..2).map(|row| lasts.value(row)).collect::>(), + [false, true] + ); + let times = batch + .column(2) + .as_any() + .downcast_ref::() + .unwrap() + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(times.value_offsets(), [0, 2, 5]); + assert_eq!( + times + .values() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .as_ref(), + &[10_i64, 20, 30, 40, 50] + ); + let floats = frame_field_payload(batch, 0) + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(floats.value_offsets(), [0, 2, 5]); + let float_values = floats + .values() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + (0..float_values.len()) + .map(|position| float_values.is_valid(position)) + .collect::>(), + [true, false, true, true, false] + ); + assert_eq!(float_values.value(0).to_bits(), 1.0_f64.to_bits()); + assert_eq!(float_values.value(2).to_bits(), 3.0_f64.to_bits()); + assert_eq!(float_values.value(3).to_bits(), 4.0_f64.to_bits()); + + let decoded = decode_batches(&schema, RawLabelMode::Key, &batches); + assert_eq!(decoded.len(), 2); + assert_eq!(decoded[0].primary_key.as_slice(), &[0xaa]); + assert!(!decoded[0].is_last); + assert_eq!( + (0..decoded[0].time.len()) + .map(|position| decoded[0].time.timestamp(position).unwrap()) + .collect::>(), + [10, 20] + ); + assert_float_bits(decoded[0].fields.get(0).unwrap(), &[Some(1.0), None]); + assert_eq!(decoded[1].primary_key.as_slice(), &[0xbb]); + assert!(decoded[1].is_last); + assert_eq!( + (0..decoded[1].time.len()) + .map(|position| decoded[1].time.timestamp(position).unwrap()) + .collect::>(), + [30, 40, 50] + ); + assert_float_bits( + decoded[1].fields.get(0).unwrap(), + &[Some(3.0), Some(4.0), None], + ); + assert_eq!(decoded.iter().map(|row| row.time.len()).sum::(), 5); +} + +#[test] +fn raw_frame_builder_emits_at_the_row_budget_without_another_cursor() { + let schema = test_schema(&["value"]); + let chunks = [ + float_chunk(&schema, &[1], None, vec![1], vec![Some(1.0)], false), + float_chunk(&schema, &[2], None, vec![2], vec![Some(2.0)], false), + float_chunk(&schema, &[3], None, vec![3], vec![Some(3.0)], true), + ]; + + for max_rows in [2usize, 3] { + let mut builder = RawSeriesFrameBuilder::try_new( + &schema, + RawLabelMode::Key, + max_rows, + RawSeriesFrameBuilder::DEFAULT_MAX_BYTES, + ) + .unwrap(); + let mut emitted_at = None; + let mut batches = Vec::new(); + for (index, chunk) in chunks.iter().enumerate() { + let produced = append_chunk(&mut builder, &schema, RawLabelMode::Key, chunk).unwrap(); + assert!(produced.len() <= 1, "one cursor emits at most one batch"); + if let Some(batch) = produced.first() { + assert!( + emitted_at.replace(index).is_none(), + "the row bound is reached once, without another cursor" + ); + batches.push(batch.clone()); + } + } + if let Some(batch) = builder.flush().unwrap() { + batches.push(batch); + } + // Three one-row chunks emit at the max_rows-th row: a budget of two is reached during the + // second chunk and a budget of three during the third, so no further cursor is needed. + assert_eq!(emitted_at, Some(max_rows - 1)); + assert_eq!(batches[0].num_rows(), max_rows); + assert_eq!( + batches.iter().map(|batch| batch.num_rows()).sum::(), + 3 + ); + assert!(batches.iter().all(|batch| batch.num_rows() <= max_rows)); + let keys = batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + (0..max_rows) + .map(|row| keys.value(row).to_vec()) + .collect::>(), + (1..=max_rows) + .map(|key| vec![key as u8]) + .collect::>() + ); + + let decoded = decode_batches(&schema, RawLabelMode::Key, &batches); + assert_eq!(decoded.len(), 3); + assert_eq!( + decoded + .iter() + .map(|row| row.time.timestamp(0).unwrap()) + .collect::>(), + [1, 2, 3] + ); + assert_eq!( + decoded.iter().map(|row| row.is_last).collect::>(), + [false, false, true] + ); + } +} + +#[test] +fn raw_frame_builder_rejects_zero_budgets_and_bounds_offsets() { + let schema = test_schema(&["value"]); + // Zero in either budget is not a legal configuration; the literals take the parameter's type. + assert!( + RawSeriesFrameBuilder::try_new( + &schema, + RawLabelMode::Key, + 0, + RawSeriesFrameBuilder::DEFAULT_MAX_BYTES, + ) + .is_err() + ); + assert!( + RawSeriesFrameBuilder::try_new( + &schema, + RawLabelMode::Key, + RawSeriesFrameBuilder::DEFAULT_MAX_ROWS, + 0, + ) + .is_err() + ); + assert!(RawSeriesFrameBuilder::try_new(&schema, RawLabelMode::Key, 0, 0).is_err()); + assert!( + RawSeriesFrameBuilder::try_new( + &schema, + RawLabelMode::Key, + 1, + RawSeriesFrameBuilder::DEFAULT_MAX_BYTES, + ) + .is_ok() + ); + + // Cumulative Arrow list offsets are bounded through the shared helper, so the limit is proven + // without allocating a two-gigabyte fixture. + assert_eq!(checked_offset(i32::MAX as usize).unwrap(), i32::MAX); + assert!(checked_offset(i32::MAX as usize + 1).is_err()); + assert!(checked_offset(usize::MAX).is_err()); +} + +#[test] +fn byte_budget_emits_legal_oversized_rows_without_dropping_them() { + let schema = test_schema(&["value"]); + let owner = Float64Array::from(vec![Some(1.0), Some(2.0), Some(3.0)]); + let samples = Samples::try_from_chunks( + (0..3) + .map(|position| Samples::from_float(owner.slice(position, 1))) + .collect(), + ) + .unwrap(); + let chunk = RawSeriesChunk::try_new( + &schema, + Buffer::from(vec![0x9a_u8]), + None, + RawTimestamps::try_new(vec![7_i64, 8, 9].into()).unwrap(), + SeriesFields::one(samples), + true, + ) + .unwrap(); + + // A one-byte budget cannot hold any row, yet every legal row is still emitted as its own + // batch instead of being dropped or merged. + let batches = pack_chunk_with_budget( + &schema, + RawLabelMode::Key, + &chunk, + RawSeriesFrameBuilder::DEFAULT_MAX_ROWS, + 1, + ) + .unwrap(); + assert_eq!(batches.len(), 3); + assert!( + batches + .iter() + .all(|batch| batch.num_rows() == 1 && batch.schema() == batches[0].schema()), + "an oversized row is emitted alone, never dropped" + ); + + let decoded = decode_batches(&schema, RawLabelMode::Key, &batches); + assert_eq!(decoded.len(), 3); + for (position, row) in decoded.iter().enumerate() { + assert_eq!(row.primary_key.as_slice(), &[0x9a]); + assert_eq!(row.time.timestamp(0), Some(7 + position as i64)); + assert_eq!(row.is_last, position == 2); + assert_float_bits(row.fields.get(0).unwrap(), &[Some(position as f64 + 1.0)]); + } +} + +#[test] +fn byte_budget_flushes_before_exceeding_and_retries_the_pending_row() { + let schema = test_schema(&["value"]); + let chunks = [ + float_chunk(&schema, &[1], None, vec![10], vec![Some(1.0)], false), + float_chunk(&schema, &[2], None, vec![20], vec![Some(2.0)], true), + ]; + // The bound comes from the real rows instead of a fabricated counter: one byte less than + // both rows together fits the first row alone, so the second one must not join it. + let mut measured = Vec::with_capacity(chunks.len()); + for chunk in &chunks { + let mut cursor = + RawSeriesChunkCursor::try_new(&schema, RawLabelMode::Key, chunk.clone()).unwrap(); + measured.push(cursor.next_row().unwrap().unwrap().bytes); + } + let budget = measured[0] + measured[1] - 1; + + let mut builder = RawSeriesFrameBuilder::try_new( + &schema, + RawLabelMode::Key, + RawSeriesFrameBuilder::DEFAULT_MAX_ROWS, + budget, + ) + .unwrap(); + let mut first = + RawSeriesChunkCursor::try_new(&schema, RawLabelMode::Key, chunks[0].clone()).unwrap(); + assert!(first.append_to(&mut builder).unwrap().is_none()); + + let mut second = + RawSeriesChunkCursor::try_new(&schema, RawLabelMode::Key, chunks[1].clone()).unwrap(); + let emitted = second.append_to(&mut builder).unwrap().unwrap(); + assert_eq!(emitted.num_rows(), 1, "the first row is flushed alone"); + // The second row stays pending across the flush and is retried, never dropped. + assert!(second.append_to(&mut builder).unwrap().is_none()); + let remainder = builder.flush().unwrap().unwrap(); + assert_eq!(remainder.num_rows(), 1); + + let decoded = decode_batches(&schema, RawLabelMode::Key, &[emitted, remainder]); + assert_eq!(decoded.len(), 2); + assert_eq!(decoded[0].primary_key.as_slice(), &[1]); + assert_eq!(decoded[1].primary_key.as_slice(), &[2]); + assert_eq!(decoded[0].time.timestamp(0), Some(10)); + assert_eq!(decoded[1].time.timestamp(0), Some(20)); + assert_eq!( + decoded.iter().map(|row| row.is_last).collect::>(), + [false, true] + ); + assert_float_bits(decoded[0].fields.get(0).unwrap(), &[Some(1.0)]); + assert_float_bits(decoded[1].fields.get(0).unwrap(), &[Some(2.0)]); + + // A requested byte bound is clamped to the representable cumulative offset range, and that + // range is rejected before any child array is allocated. + let clamped = RawSeriesFrameBuilder::try_new( + &schema, + RawLabelMode::Key, + RawSeriesFrameBuilder::DEFAULT_MAX_ROWS, + usize::MAX, + ) + .unwrap(); + assert_eq!(clamped.max_bytes, i32::MAX as usize); + assert!(offset_buffer(&[i32::MAX as usize, 1]).is_err()); +} + +#[test] +fn multirow_histogram_rows_keep_row_local_indices_and_tables() { + let schema = test_schema(&["histogram"]); + let first_table = histogram_batch(); + let second_table = histogram_batch_with_sum(42.25); + let first_row = + Samples::try_from_histogram(UInt32Array::from(vec![Some(0), None]), first_table).unwrap(); + let second_row = + Samples::try_from_histogram(UInt32Array::from(vec![None, Some(0)]), second_table).unwrap(); + let fields = SeriesFields::one(Samples::try_from_chunks(vec![first_row, second_row]).unwrap()); + let chunk = RawSeriesChunk::try_new( + &schema, + Buffer::from(vec![0x5a_u8]), + None, + RawTimestamps::try_new(vec![1_i64, 2, 3, 4].into()).unwrap(), + fields, + true, + ) + .unwrap(); + + // The public wrapper groups two independent rows into one multirow batch. + let packed = pack_raw_series_chunk(&schema, RawLabelMode::Key, &chunk).unwrap(); + assert_eq!(packed.len(), 1); + assert_eq!(packed[0].num_rows(), 2); + + let (indices, tables) = frame_histogram_lists(&packed[0], 0); + let encoded_first = indices.value(0); + let encoded_first = encoded_first + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(encoded_first.value(0), 0); + assert!(!encoded_first.is_valid(1)); + let encoded_second = indices.value(1); + let encoded_second = encoded_second + .as_any() + .downcast_ref::() + .unwrap(); + assert!(!encoded_second.is_valid(0)); + assert_eq!( + encoded_second.value(1), + 0, + "row-local indices must not be remapped" + ); + // The second row references its own table through a nonzero slice of the concatenated child. + assert_eq!(tables.value_offsets(), [0, 2, 4]); + let concatenated = tables + .values() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(concatenated.len(), 4); + + let decoded = decode_batches(&schema, RawLabelMode::Key, std::slice::from_ref(&packed[0])); + assert_row_local_histogram_rows(&decoded); + + // A real Arrow IPC round trip keeps the schema, the whole tables, the null index entries and + // the bit-exact payloads. + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &packed[0].schema()).unwrap(); + writer.write(&packed[0]).unwrap(); + writer.finish().unwrap(); + } + let reader = StreamReader::try_new(std::io::Cursor::new(ipc), None).unwrap(); + let restored = reader.map(|batch| batch.unwrap()).collect::>(); + assert_eq!(restored.len(), 1); + assert_eq!(restored[0].schema(), packed[0].schema()); + assert_eq!(restored[0].num_rows(), 2); + let (restored_indices, restored_tables) = frame_histogram_lists(&restored[0], 0); + assert_eq!(restored_tables.value_offsets(), tables.value_offsets()); + let restored_second = restored_indices.value(1); + assert_eq!( + restored_second + .as_any() + .downcast_ref::() + .unwrap() + .value(1), + 0 + ); + let restored_rows = decode_batches(&schema, RawLabelMode::Key, &restored); + assert_row_local_histogram_rows(&restored_rows); +} + +#[test] +fn decoder_reuses_cached_schema_and_rejects_schema_evolution() { + let schema = test_schema(&["value"]); + let expected = raw_series_frame_schema(&schema, RawLabelMode::Key).unwrap(); + let first = pack_raw_series_chunk( + &schema, + RawLabelMode::Key, + &float_chunk( + &schema, + &[1], + None, + vec![1, 2], + vec![Some(1.0), Some(2.0)], + false, + ), + ) + .unwrap() + .remove(0); + let second = pack_raw_series_chunk( + &schema, + RawLabelMode::Key, + &float_chunk(&schema, &[2], None, vec![3], vec![Some(3.0)], true), + ) + .unwrap() + .remove(0); + + let key_decoder = RawSeriesFrameDecoder::try_new(&schema, RawLabelMode::Key).unwrap(); + let decoded = key_decoder.decode(&first).unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded[0].primary_key.as_slice(), &[1]); + assert_eq!( + (0..decoded[0].time.len()) + .map(|position| decoded[0].time.timestamp(position).unwrap()) + .collect::>(), + [1, 2] + ); + // The same decoder accepts a later valid batch before the malformed ones below. + let decoded = key_decoder.decode(&second).unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded[0].primary_key.as_slice(), &[2]); + assert!(decoded[0].is_last); + + // Unrelated metadata is not part of the raw frame contract. + let mut unrelated_metadata = second.schema().metadata().clone(); + unrelated_metadata.insert("application.note".to_string(), "ignored".to_string()); + let unrelated = arrow::record_batch::RecordBatch::try_new( + Arc::new(Schema::new_with_metadata( + expected.fields().clone(), + unrelated_metadata, + )), + second.columns().to_vec(), + ) + .unwrap(); + assert_eq!(key_decoder.decode(&unrelated).unwrap().len(), 1); + + // Reserved metadata and evolved fields are rejected, including by a zero-row batch. + for (key, value) in [ + ("greptime.series.layout", "v2"), + ("greptime.series.content", "evaluated"), + ("greptime.series.labels", "explicit"), + ("greptime.series.time", "grid"), + ] { + let mut metadata = second.schema().metadata().clone(); + metadata.insert(key.to_string(), value.to_string()); + let contaminated = arrow::record_batch::RecordBatch::try_new( + Arc::new(Schema::new_with_metadata( + expected.fields().clone(), + metadata, + )), + second.columns().to_vec(), + ) + .unwrap(); + assert!( + key_decoder.decode(&contaminated).is_err(), + "{key} must be rejected" + ); + } + let evolved_schema = test_schema(&["other"]); + let evolved = pack_raw_series_chunk( + &evolved_schema, + RawLabelMode::Key, + &float_chunk(&evolved_schema, &[3], None, vec![4], vec![Some(4.0)], false), + ) + .unwrap() + .remove(0); + assert!(key_decoder.decode(&evolved).is_err()); + let empty_evolved = arrow::record_batch::RecordBatch::new_empty( + raw_series_frame_schema(&evolved_schema, RawLabelMode::Key).unwrap(), + ); + assert!(key_decoder.decode(&empty_evolved).is_err()); + // Rejections leave the cached schema usable, and a valid zero-row batch stays valid. + assert_eq!(key_decoder.decode(&first).unwrap().len(), 1); + assert!( + key_decoder + .decode(&arrow::record_batch::RecordBatch::new_empty( + expected.clone() + )) + .unwrap() + .is_empty() + ); + + // Explicit mode reuses one decoder for a present but nameless metric and a named one. + let explicit_decoder = RawSeriesFrameDecoder::try_new(&schema, RawLabelMode::Explicit).unwrap(); + let nameless = pack_raw_series_chunk( + &schema, + RawLabelMode::Explicit, + &float_chunk( + &schema, + &[7], + Some(metric(None, &[("zone", "west")])), + vec![5], + vec![Some(5.0)], + true, + ), + ) + .unwrap() + .remove(0); + let named = pack_raw_series_chunk( + &schema, + RawLabelMode::Explicit, + &float_chunk( + &schema, + &[8], + Some(metric(Some("cpu"), &[])), + vec![6], + vec![Some(6.0)], + false, + ), + ) + .unwrap() + .remove(0); + let decoded = explicit_decoder.decode(&nameless).unwrap(); + let labels = decoded[0].metric.as_ref().unwrap(); + assert_eq!(labels.name(), None); + assert_eq!(labels.get("zone"), Some("west")); + assert_eq!( + explicit_decoder.decode(&named).unwrap()[0] + .metric + .as_ref() + .unwrap() + .name(), + Some("cpu") + ); + // Label modes are not interchangeable. + assert!(explicit_decoder.decode(&first).is_err()); + assert!(key_decoder.decode(&nameless).is_err()); +} diff --git a/src/datatypes/src/series/samples.rs b/src/datatypes/src/series/samples.rs index 12e3e17eaac..42b1d4bba0b 100644 --- a/src/datatypes/src/series/samples.rs +++ b/src/datatypes/src/series/samples.rs @@ -389,13 +389,15 @@ impl Samples { SampleStorage::Mixed(mixed) => Some(&mixed.histograms.batch), SampleStorage::Float(_) | SampleStorage::Chunks(_, _) => None, }); + let mut first_data = None; let shared_batch = histogram_batches.next().filter(|first| { histogram_batches.all(|batch| { - Arc::ptr_eq(first, batch) - || first - .as_arrow() - .to_data() - .ptr_eq(&batch.as_arrow().to_data()) + if Arc::ptr_eq(first, batch) { + return true; + } + first_data + .get_or_insert_with(|| first.as_arrow().to_data()) + .ptr_eq(&batch.as_arrow().to_data()) }) }); let needs_float = chunks.iter().any(|chunk| {