From c12058a5c63d1fe6768b679b0fe2c9cd79519be3 Mon Sep 17 00:00:00 2001 From: discord9 Date: Fri, 23 Oct 2026 19:59:37 +0800 Subject: [PATCH] feat(promql): run a root ranking over the evaluated per-series prefix A `topk`/`bottomk` statement answers over the whole vector: which `k` series a group keeps at a grid point depends on every series present there, so a per-partition answer is that partition's best, not the query's. This adds one global node for exactly that root shape and leaves the parallel prefix alone. The prefix stays one `FusedSeries` per scan partition, so every partition still decodes and evaluates its own series. It now emits its evaluated chunks as rows of a private Arrow frame layout instead of the row table, carrying each chunk's complete labels, absolute grid positions, nulls and finality. Existing DataFusion operators gather and order those frames by producer and ordinal, and the new `VectorSelectExec` feeds them to one existing native runtime, which ranks only after the frames have all arrived. Nothing is gathered before it has been computed, and no raw input, wire format or region protocol is extended. Admission is a single logical check before any extension node exists, so a shape this node does not answer keeps the complete existing plan rather than failing at physical planning. It requires a root ranking over a tree that reads one series at a time, exactly one Float64 field, one raw input, and a table whose DDL leaves it one region: the frames are numbered by the region-local partition index, so more than one region cannot be told apart. The frame stream and the ranking release the schema and grid they read when they end or fail, so an ended stream a consumer keeps does not pin the statement's grid. The acceptance test runs a real standalone with four non-empty scan and fused partitions in one region, holds every fused partition until all four have computed a first batch, and compares the ranked answer with an independently computed top two of the unranked window and with the existing planner's answer. Signed-off-by: discord9 --- src/promql/src/extension_plan.rs | 3 + .../src/extension_plan/evaluated_frame.rs | 426 +++++++ .../extension_plan/evaluated_frame/tests.rs | 670 +++++++++++ src/promql/src/extension_plan/fused_series.rs | 266 ++++- .../src/extension_plan/fused_series/tests.rs | 778 +++++++++--- src/promql/src/extension_plan/planner.rs | 24 +- src/promql/src/extension_plan/test_util.rs | 212 +++- .../src/extension_plan/vector_select.rs | 808 +++++++++++++ .../src/extension_plan/vector_select/tests.rs | 1064 +++++++++++++++++ src/query/src/dist_plan/analyzer.rs | 40 +- src/query/src/dist_plan/commutativity.rs | 262 ++++ src/query/src/promql/planner/native.rs | 122 +- src/query/src/promql/planner/test.rs | 323 ++++- tests-integration/src/tests/promql_test.rs | 642 +++++++++- 14 files changed, 5356 insertions(+), 284 deletions(-) create mode 100644 src/promql/src/extension_plan/evaluated_frame.rs create mode 100644 src/promql/src/extension_plan/evaluated_frame/tests.rs create mode 100644 src/promql/src/extension_plan/vector_select.rs create mode 100644 src/promql/src/extension_plan/vector_select/tests.rs 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