diff --git a/src/promql/src/extension_plan.rs b/src/promql/src/extension_plan.rs index baf57a275c8..38928ddcf63 100644 --- a/src/promql/src/extension_plan.rs +++ b/src/promql/src/extension_plan.rs @@ -14,6 +14,7 @@ mod absent; mod empty_metric; +mod evaluated_frame; mod fused_series; mod histogram_fold; mod instant_manipulate; @@ -25,6 +26,7 @@ mod series_divide; #[cfg(test)] mod test_util; mod union_distinct_on; +mod vector_select; pub use absent::{Absent, AbsentExec, AbsentStream}; use common_query::native_histogram::{SUM_FIELD, native_histogram_value_type}; @@ -49,6 +51,7 @@ pub use range_manipulate::{RangeManipulate, RangeManipulateExec, RangeManipulate pub use scalar_calculate::ScalarCalculate; pub use series_divide::{SeriesDivide, SeriesDivideExec, SeriesDivideStream}; pub use union_distinct_on::{UnionDistinctOn, UnionDistinctOnExec, UnionDistinctOnStream}; +pub use vector_select::VectorSelect; pub type Millisecond = ::Native; diff --git a/src/promql/src/extension_plan/evaluated_frame.rs b/src/promql/src/extension_plan/evaluated_frame.rs new file mode 100644 index 00000000000..369df87f7b8 --- /dev/null +++ b/src/promql/src/extension_plan/evaluated_frame.rs @@ -0,0 +1,426 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The private in-process frame between the parallel prefix and the global consumer. +//! +//! One [`EvaluatedChunk`] is one Arrow row of a fixed layout: the metric, its labels, the absolute +//! grid positions the chunk carries and their values. The frame names no grid, so the consumer +//! binds the [`SeriesSchema`] the chunks were evaluated against and the plan keeps that binding. +//! An empty row is a real row: it is how a series closes without holding a value. DataFusion may +//! rebatch, so [`read`] takes the row it wants and keeps nothing. [`Sequence`] checks the +//! producer/ordinal ordering a single row cannot state. + +use std::sync::Arc; + +use datafusion::arrow::array::{ + Array, ArrayRef, BooleanArray, Float64Array, ListArray, StringArray, UInt64Array, +}; +use datafusion::arrow::buffer::{OffsetBuffer, ScalarBuffer}; +use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use datafusion::arrow::record_batch::RecordBatch; +use datafusion::error::{DataFusionError, Result}; +use datatypes::series::samples::{ + DenseSamplesRef, SampleRef, Samples, Series, SeriesFields, SeriesSchema, +}; +use datatypes::series::time::{GridSpan, TimeAxis}; +use datatypes::series::{Label, MetricName}; + +use crate::evaluated::EvaluatedChunk; + +/// The output stream the chunk belongs to. +const PRODUCER: &str = "producer"; +/// The chunk's position in its producer's output. +const FRAME_ORDINAL: &str = "frame_ordinal"; +/// The metric name; null when the series has none, empty when it is `""`. +const METRIC_NAME: &str = "metric_name"; +/// The ordinary label names, parallel to [`LABEL_VALUES`]. +const LABEL_NAMES: &str = "label_names"; +/// The ordinary label values, parallel to [`LABEL_NAMES`]. +const LABEL_VALUES: &str = "label_values"; +/// The absolute grid positions of the chunk's rows. +const POSITIONS: &str = "positions"; +/// The chunk's float values, parallel to [`POSITIONS`]. +const VALUES: &str = "values"; +/// Whether this chunk closes its series. +const IS_LAST: &str = "is_last"; +/// Arrow's name for the child field of a list. +const LIST_ITEM: &str = "item"; + +/// The fixed frame layout: only the metric name and the values may be null, and a label is absent +/// by being absent from the parallel lists rather than by a null entry. +pub(crate) fn schema() -> SchemaRef { + let list = |name: &str, item: DataType, nullable: bool| { + Field::new( + name, + DataType::List(Arc::new(Field::new(LIST_ITEM, item, nullable))), + false, + ) + }; + Arc::new(Schema::new(vec![ + Field::new(PRODUCER, DataType::UInt64, false), + Field::new(FRAME_ORDINAL, DataType::UInt64, false), + Field::new(METRIC_NAME, DataType::Utf8, true), + list(LABEL_NAMES, DataType::Utf8, false), + list(LABEL_VALUES, DataType::Utf8, false), + list(POSITIONS, DataType::UInt64, false), + list(VALUES, DataType::Float64, true), + Field::new(IS_LAST, DataType::Boolean, false), + ])) +} + +/// Packs one evaluated chunk into a one-row batch of [`schema`]. +/// +/// `series_schema` must name exactly one field and one grid, and the chunk is validated against it +/// through [`Series::try_new`] before the axis is reduced to positions. Samples must be float +/// segments, so a histogram or mixed segment is refused even when it holds no row; chunked float +/// segments are accepted. Nulls, NaN bits, sparse positions and an empty closing chunk are carried +/// through unchanged. +pub(crate) fn pack( + chunk: &EvaluatedChunk, + series_schema: &SeriesSchema, + producer: u64, + frame_ordinal: u64, +) -> Result { + if series_schema.fields.len() != 1 || series_schema.eval_grid.is_none() { + return Err(DataFusionError::Execution( + "an evaluated frame requires one field and a grid".to_string(), + )); + } + let series = Series::try_new( + series_schema, + chunk.series.metric.clone(), + chunk.series.time.clone(), + chunk.series.fields.clone(), + ) + .map_err(series_error)?; + let samples = + series.fields.as_slice().first().ok_or_else(|| { + DataFusionError::Execution("evaluated chunk holds no field".to_string()) + })?; + // Every segment is checked, so an empty histogram segment is refused just like a filled one. + for segment in samples.segments() { + if !matches!(segment.dense(), Some(DenseSamplesRef::Float(_))) { + return Err(DataFusionError::NotImplemented( + "an evaluated frame carries float samples only".to_string(), + )); + } + } + + // `positions` walks the carried rows, so the holes between runs never become rows. + let mut positions: Vec = Vec::with_capacity(samples.len()); + let mut values: Vec> = Vec::with_capacity(samples.len()); + let mut cursor = samples.cursor(); + for (position, row) in series.time.positions() { + positions.push(u64::try_from(position).map_err(|_| { + DataFusionError::Execution("evaluated frame position does not fit UInt64".to_string()) + })?); + match cursor.at(row) { + Some(SampleRef::Float(value)) => values.push(Some(value)), + Some(SampleRef::Missing) => values.push(None), + Some(SampleRef::Histogram(_)) => { + return Err(DataFusionError::NotImplemented( + "an evaluated frame carries float samples only".to_string(), + )); + } + None => { + return Err(DataFusionError::Execution(format!( + "evaluated chunk row {row} is missing from its field" + ))); + } + } + } + + let names: Vec<&str> = series + .metric + .tags() + .iter() + .map(|tag| tag.name.as_ref()) + .collect(); + let labels: Vec<&str> = series + .metric + .tags() + .iter() + .map(|tag| tag.value.as_ref()) + .collect(); + let columns: Vec = vec![ + Arc::new(UInt64Array::from(vec![producer])), + Arc::new(UInt64Array::from(vec![frame_ordinal])), + Arc::new(StringArray::from(vec![series.metric.name()])), + Arc::new(list( + DataType::Utf8, + false, + Arc::new(StringArray::from(names)), + )?), + Arc::new(list( + DataType::Utf8, + false, + Arc::new(StringArray::from(labels)), + )?), + Arc::new(list( + DataType::UInt64, + false, + Arc::new(UInt64Array::from(positions)), + )?), + Arc::new(list( + DataType::Float64, + true, + Arc::new(Float64Array::from(values)), + )?), + Arc::new(BooleanArray::from(vec![chunk.is_last])), + ]; + Ok(RecordBatch::try_new(schema(), columns)?) +} + +/// Reads the chunk held by `row` of `batch`. +/// +/// `series_schema` is the binding that supplies the grid absolute positions refer to: it must name +/// exactly one field and one grid. The batch must carry exactly [`schema`], every required column +/// must be non-null at `row`, the label lists must be parallel and name one label set (`__name__` +/// stays the metric name), positions must be strictly increasing and inside the grid, and one value +/// must exist per position. The axis is rebuilt compactly, so no row is materialized for a hole. +pub(crate) fn read( + batch: &RecordBatch, + row: usize, + series_schema: &Arc, +) -> Result<(u64, u64, EvaluatedChunk)> { + if batch.schema().as_ref() != schema().as_ref() { + return Err(DataFusionError::Execution( + "evaluated frame schema mismatch".to_string(), + )); + } + if row >= batch.num_rows() { + return Err(DataFusionError::Execution(format!( + "evaluated frame row {row} is outside a batch of {} rows", + batch.num_rows() + ))); + } + if series_schema.fields.len() != 1 { + return Err(DataFusionError::Execution( + "an evaluated frame requires one field".to_string(), + )); + } + let Some(grid) = series_schema.eval_grid.clone() else { + return Err(DataFusionError::Execution( + "an evaluated frame requires a grid".to_string(), + )); + }; + let columns = batch.columns(); + for (column, index) in [ + (PRODUCER, 0), + (FRAME_ORDINAL, 1), + (LABEL_NAMES, 3), + (LABEL_VALUES, 4), + (POSITIONS, 5), + (VALUES, 6), + (IS_LAST, 7), + ] { + if columns[index].is_null(row) { + return Err(DataFusionError::Execution(format!( + "evaluated frame requires a non-null {column} at row {row}" + ))); + } + } + let producers = down::(&columns[0], PRODUCER)?; + let ordinals = down::(&columns[1], FRAME_ORDINAL)?; + let names = down::(&columns[2], METRIC_NAME)?; + let label_names = down::(&columns[3], LABEL_NAMES)?; + let label_values = down::(&columns[4], LABEL_VALUES)?; + let position_list = down::(&columns[5], POSITIONS)?; + let value_list = down::(&columns[6], VALUES)?; + let lasts = down::(&columns[7], IS_LAST)?; + + let name = (!names.is_null(row)).then(|| Arc::::from(names.value(row))); + let names = strings(label_names, row, LABEL_NAMES)?; + let labels = strings(label_values, row, LABEL_VALUES)?; + if names.len() != labels.len() { + return Err(DataFusionError::Execution(format!( + "evaluated frame has {} label names and {} label values", + names.len(), + labels.len() + ))); + } + let tags: Vec