From d4f55de30acdefed80c54ac9b90ea9369cc5f066 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Mon, 19 Oct 2026 12:59:38 +0800 Subject: [PATCH 01/17] feat(promql): add the bound tree and batch protocol for native execution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A native PromQL evaluation needs a compiled form whose operations are already bound to kernels, fields and grids. Recognising an opportunity from a finished physical plan cannot provide that: the opportunity then depends on how the optimizer happened to arrange a subtree, and every new shape widens a fixed template. `NativeExpr` instead covers input, scalar, instant, window, map, aggregate and binary nodes, each carrying a bound operation and a declared output type. Legality becomes a question about types and data dependencies, which `NativeNode::validate` answers, so a new combination of supported operations is an ordinary tree rather than another matcher. Two properties are checked there rather than assumed: a window's declared input grid must be the grid its input produces, so a subquery's inner grid is consumed as it is instead of being resampled, and an aggregate's output type must match its stage, so intermediate state cannot pass for a query value. `EvaluatedChunk` is the batch a node hands to the next one: an ordinary Rust value, addressed on absolute grid positions, closing a series exactly once. An empty final chunk is still meaningful — it is how a closed prefix is reported, which a consumer needs in order to tell "nothing more here" from "no more input". Nodes are identified by their position in the tree rather than by an id. The position is derived by the one traversal both `DisplayAs` and run-time construction use, so what is shown and what is registered cannot disagree. It stays in the metric name because the collector aggregates by name first, which would otherwise merge two nodes of the same operation. This adds the tree and the batch protocol only. The evaluator's chunked interface, memory reservation and execution are not part of it. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/lib.rs | 1 + src/promql/src/native/batch.rs | 164 +++++++++ src/promql/src/native/metrics.rs | 520 ++++++++++++++++++++++++++++ src/promql/src/native/mod.rs | 33 ++ src/promql/src/native/plan.rs | 380 ++++++++++++++++++++ src/promql/src/native/plan/tests.rs | 387 +++++++++++++++++++++ 6 files changed, 1485 insertions(+) create mode 100644 src/promql/src/native/batch.rs create mode 100644 src/promql/src/native/metrics.rs create mode 100644 src/promql/src/native/mod.rs create mode 100644 src/promql/src/native/plan.rs create mode 100644 src/promql/src/native/plan/tests.rs diff --git a/src/promql/src/lib.rs b/src/promql/src/lib.rs index 4ba3a66b96a..c9ee89ff62c 100644 --- a/src/promql/src/lib.rs +++ b/src/promql/src/lib.rs @@ -27,6 +27,7 @@ pub mod map; pub mod map_label; pub mod map_time; mod metrics; +pub mod native; pub mod range_array; pub mod range_eval; pub mod select; diff --git a/src/promql/src/native/batch.rs b/src/promql/src/native/batch.rs new file mode 100644 index 00000000000..eec665130f7 --- /dev/null +++ b/src/promql/src/native/batch.rs @@ -0,0 +1,164 @@ +// 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 batches native nodes hand to each other. +//! +//! These are ordinary Rust values passed by call, not DataFusion streams and not encoded messages: +//! the Arrow arrays, buffers and shared schemas inside them are reused as they are. +//! +//! Two rules make a chunk self-describing: +//! +//! - A grid position is absolute on the chunk's grid. Batch-local row numbers never stand in for +//! one, and an inner grid is never addressed with an outer grid's index. +//! - A series closes exactly once, on the chunk that carries [`EvaluatedChunk::is_last`]. A closed +//! prefix still has to be followed by a final chunk even when that chunk holds no values, so a +//! consumer can tell "nothing more here" from "no more input". + +use datafusion::error::{DataFusionError, Result}; +use datatypes::series::samples::Series; +use datatypes::series::time::TimeAxis; + +/// One slice of one evaluated series. +/// +/// The series' [`TimeAxis::Grid`] covers the positions this chunk has finished evaluating. Those +/// positions are absolute on the grid, and they are contiguous with the previous chunk of the same +/// series. +#[derive(Clone, Debug)] +pub struct EvaluatedChunk { + /// The evaluated values, addressed on their absolute grid positions. + pub series: Series, + /// Whether this is the final chunk of this series. + pub is_last: bool, +} + +impl EvaluatedChunk { + /// Wraps `series`, checking that it is addressed on a grid. + pub fn try_new(series: Series, is_last: bool) -> Result { + if !matches!(series.time, TimeAxis::Grid(_)) { + return Err(DataFusionError::Execution( + "an evaluated chunk must be addressed on a grid".to_string(), + )); + } + Ok(Self { series, is_last }) + } + + /// The absolute grid range this chunk covers. + /// + /// An empty range is meaningful: it reports that the chunk closed a prefix of the grid without + /// producing new values, which a consumer needs in order to advance. + pub fn range(&self) -> &datatypes::series::time::GridRange { + match &self.series.time { + TimeAxis::Grid(range) => range, + // `try_new` rejects anything else, and `series` is public, so a chunk built by struct + // literal is checked here rather than trusted. + _ => unreachable!("an evaluated chunk is always addressed on a grid"), + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use datatypes::arrow::array::Float64Array; + use datatypes::series::MetricName; + use datatypes::series::samples::{Samples, Series, SeriesFields, SeriesSchema}; + use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; + + use super::EvaluatedChunk; + + fn grid() -> Arc { + Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 60_000, 4).unwrap()).unwrap()) + } + + fn schema() -> SeriesSchema { + SeriesSchema { + fields: Arc::from([datatypes::series::samples::FieldSpec { name: "v0".into() }]), + eval_grid: Some(grid()), + } + } + + /// `values` are the floats this chunk finished evaluating; `start` is their absolute offset. + fn chunk( + schema: &SeriesSchema, + start: usize, + values: Vec, + is_last: bool, + ) -> EvaluatedChunk { + let samples = Samples::from_float(Float64Array::from(values)); + let range = + GridRange::try_new(schema.eval_grid.clone().unwrap(), start, samples.len()).unwrap(); + let series = Series { + metric: MetricName::try_new(Some("requests".into()), Vec::new()).unwrap(), + time: TimeAxis::Grid(range), + fields: SeriesFields::try_from_vec(vec![samples]).unwrap(), + }; + EvaluatedChunk::try_new(series, is_last).unwrap() + } + + /// A chunk without values is still a chunk: it is how a closed prefix is reported, and a + /// consumer needs it to tell "nothing more here" from "no more input". + #[test] + fn a_chunk_can_cover_no_positions() { + let schema = schema(); + let empty = Samples::from_float(Float64Array::from(Vec::::new())); + let range = GridRange::try_new(schema.eval_grid.clone().unwrap(), 4, 0).unwrap(); + assert!(range.is_empty()); + let series = Series { + metric: MetricName::try_new(Some("requests".into()), Vec::new()).unwrap(), + time: TimeAxis::Grid(range), + fields: SeriesFields::try_from_vec(vec![empty]).unwrap(), + }; + let chunk = EvaluatedChunk::try_new(series, true).unwrap(); + assert!(chunk.range().is_empty()); + assert!(chunk.is_last); + } + + /// The range is absolute, so concatenating two chunks of one series never reorders them. + #[test] + fn a_range_is_absolute_on_its_grid() { + let schema = schema(); + let first = chunk(&schema, 0, vec![1.0, 2.0], false); + let second = chunk(&schema, 2, vec![3.0, 4.0], true); + assert_eq!((first.range().start(), first.range().len()), (0, 2)); + assert_eq!((second.range().start(), second.range().len()), (2, 2)); + assert!(!first.is_last); + assert!(second.is_last); + } + + /// A chunk that is not addressed on a grid cannot be indexed by a native node. + #[test] + fn a_chunk_must_be_addressed_on_a_grid() { + let samples = Samples::from_float(Float64Array::from(vec![1.0])); + let series = Series { + metric: MetricName::try_new(Some("requests".into()), Vec::new()).unwrap(), + time: TimeAxis::Explicit(datatypes::arrow::buffer::ScalarBuffer::from(vec![0i64])), + fields: SeriesFields::try_from_vec(vec![samples]).unwrap(), + }; + assert!(EvaluatedChunk::try_new(series, true).is_err()); + } + + /// A schema with a grid is what marks a sample type as evaluated; the same fields without a + /// grid are raw samples. + #[test] + fn a_grid_in_the_schema_marks_an_evaluated_type() { + let evaluated = schema(); + assert!(evaluated.eval_grid.is_some()); + let raw = SeriesSchema { + fields: evaluated.fields.clone(), + eval_grid: None, + }; + assert!(raw.eval_grid.is_none()); + } +} diff --git a/src/promql/src/native/metrics.rs b/src/promql/src/native/metrics.rs new file mode 100644 index 00000000000..22819923da5 --- /dev/null +++ b/src/promql/src/native/metrics.rs @@ -0,0 +1,520 @@ +// 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. + +//! Where a node sits in the final execution tree, and the metrics named after that position. +//! +//! A node is identified by its structural position — `root`, `.input`, `.left`, `.right` — rather +//! than by an id it carries. The position is not stored on the node: it is derived while walking +//! the tree, which is the same walk that both `DisplayAs` and run-time construction use, so the +//! name shown and the name registered cannot disagree. +//! +//! The position stays in the metric name because the collector aggregates by name first: two +//! `rate` nodes sharing a bare name would be merged into one number. Positions are only an +//! observation detail of one plan — they are not stable across queries, plan rewrites or versions, +//! so nothing may depend on them beyond correlating a metric with a tree it was taken from. + +use std::sync::Arc; + +use datafusion::physical_plan::metrics::MetricValue; +use datafusion::physical_plan::metrics::{ + Count, ExecutionPlanMetricsSet, Gauge, MetricBuilder, Time, +}; + +use super::plan::{NativeExpr, NativeNode}; + +/// The reserved first segment of every native metric name. +const NATIVE_PREFIX: &str = "native"; + +/// A node's position in the final tree. +/// +/// Rendering allocates a short string once, when the run-time state is created; the hot path holds +/// the metric handles instead of looking anything up by name. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct NodePath(String); + +impl NodePath { + /// The position of the root node. + pub fn root() -> Self { + Self("root".to_string()) + } + + /// The position of a unary node's input. + pub fn input(&self) -> Self { + Self(format!("{}.input", self.0)) + } + + /// The position of a binary node's left input. + pub fn left(&self) -> Self { + Self(format!("{}.left", self.0)) + } + + /// The position of a binary node's right input. + pub fn right(&self) -> Self { + Self(format!("{}.right", self.0)) + } + + /// The path without the metric namespace. + pub fn as_str(&self) -> &str { + &self.0 + } + + /// The full metric name for `metric` at this position. + pub fn metric_name(&self, metric: &str) -> String { + format!("{NATIVE_PREFIX}.{}.{}", self.0, metric) + } +} + +impl std::fmt::Display for NodePath { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +/// Visits every node of `root` with its position, outermost first. +/// +/// This is the one traversal rule: `DisplayAs` and run-time construction both call it, so a node +/// cannot be shown at one position and registered at another. +pub fn walk(root: &NativeNode, visit: &mut dyn FnMut(&NativeNode, &NodePath)) { + fn go(node: &NativeNode, path: &NodePath, visit: &mut dyn FnMut(&NativeNode, &NodePath)) { + visit(node, path); + match &node.expr { + NativeExpr::Input(_) | NativeExpr::Scalar(_) => {} + NativeExpr::Instant { input, .. } + | NativeExpr::Window { input, .. } + | NativeExpr::Map { input, .. } + | NativeExpr::Aggregate { input, .. } => go(input, &path.input(), visit), + NativeExpr::Binary { left, right, .. } => { + go(left, &path.left(), visit); + go(right, &path.right(), visit); + } + } + } + go(root, &NodePath::root(), visit); +} + +/// The metric names one node reports. +/// +/// [`Self::ALL`] is the single list both registration and documentation read, so a metric cannot be +/// registered without being named here. +pub struct NodeMetric; + +impl NodeMetric { + /// How many batches this node consumed. + pub const INPUT_BATCHES: &'static str = "input_batches"; + /// How many batches this node produced. + pub const OUTPUT_BATCHES: &'static str = "output_batches"; + /// How many sample positions this node ingested. + pub const INPUT_SAMPLES: &'static str = "input_samples"; + /// How many grid positions this node evaluated, including those with no valid result. + pub const EVALUATED_GRID_POINTS: &'static str = "evaluated_grid_points"; + /// How many valid values this node produced. + pub const OUTPUT_VALUES: &'static str = "output_values"; + /// How many series this node closed. + pub const COMPLETED_SERIES: &'static str = "completed_series"; + /// Time this node spent in its own work, excluding its inputs. + pub const SELF_COMPUTE_TIME_NS: &'static str = "self_compute_time_ns"; + /// Bytes this node currently reserves. + pub const CURRENT_RESERVED_BYTES: &'static str = "current_reserved_bytes"; + /// The highest byte count this node reserved during the execution. + pub const PEAK_RESERVED_BYTES: &'static str = "peak_reserved_bytes"; + /// How many groups this node tracks. + pub const GROUPS: &'static str = "groups"; + /// How many state entries this node tracks. + pub const STATE_ENTRIES: &'static str = "state_entries"; + + /// Every metric a node may report. + pub const ALL: &'static [&'static str] = &[ + Self::INPUT_BATCHES, + Self::OUTPUT_BATCHES, + Self::INPUT_SAMPLES, + Self::EVALUATED_GRID_POINTS, + Self::OUTPUT_VALUES, + Self::COMPLETED_SERIES, + Self::SELF_COMPUTE_TIME_NS, + Self::CURRENT_RESERVED_BYTES, + Self::PEAK_RESERVED_BYTES, + Self::GROUPS, + Self::STATE_ENTRIES, + ]; +} + +/// The metric handles one node updates as it runs. +/// +/// The node writes these directly; it never looks a metric up by name, and it never formats a path +/// on the hot path. +#[derive(Clone, Debug)] +pub struct NodeMetrics { + input_batches: Count, + output_batches: Count, + input_samples: Count, + evaluated_grid_points: Count, + output_values: Count, + completed_series: Count, + self_compute_time: Time, + current_reserved_bytes: Gauge, + peak_reserved_bytes: Gauge, + groups: Gauge, + state_entries: Gauge, +} + +impl Default for NodeMetrics { + fn default() -> Self { + Self { + input_batches: Count::new(), + output_batches: Count::new(), + input_samples: Count::new(), + evaluated_grid_points: Count::new(), + output_values: Count::new(), + completed_series: Count::new(), + self_compute_time: Time::new(), + current_reserved_bytes: Gauge::new(), + peak_reserved_bytes: Gauge::new(), + groups: Gauge::new(), + state_entries: Gauge::new(), + } + } +} + +impl NodeMetrics { + /// Registers this node's metrics under `path` in `set`. + /// + /// `partition` is part of the registration, so two partitions of one plan report separately + /// and a peak never gets summed across them. + pub fn register(&self, path: &NodePath, set: &ExecutionPlanMetricsSet, partition: usize) { + fn count(set: &ExecutionPlanMetricsSet, partition: usize, name: String, count: &Count) { + MetricBuilder::new(set) + .with_partition(partition) + .build(MetricValue::Count { + name: name.into(), + count: count.clone(), + }); + } + fn gauge(set: &ExecutionPlanMetricsSet, partition: usize, name: String, gauge: &Gauge) { + MetricBuilder::new(set) + .with_partition(partition) + .build(MetricValue::Gauge { + name: name.into(), + gauge: gauge.clone(), + }); + } + + count( + set, + partition, + path.metric_name(NodeMetric::INPUT_BATCHES), + &self.input_batches, + ); + count( + set, + partition, + path.metric_name(NodeMetric::OUTPUT_BATCHES), + &self.output_batches, + ); + count( + set, + partition, + path.metric_name(NodeMetric::INPUT_SAMPLES), + &self.input_samples, + ); + count( + set, + partition, + path.metric_name(NodeMetric::EVALUATED_GRID_POINTS), + &self.evaluated_grid_points, + ); + count( + set, + partition, + path.metric_name(NodeMetric::OUTPUT_VALUES), + &self.output_values, + ); + count( + set, + partition, + path.metric_name(NodeMetric::COMPLETED_SERIES), + &self.completed_series, + ); + gauge( + set, + partition, + path.metric_name(NodeMetric::CURRENT_RESERVED_BYTES), + &self.current_reserved_bytes, + ); + gauge( + set, + partition, + path.metric_name(NodeMetric::PEAK_RESERVED_BYTES), + &self.peak_reserved_bytes, + ); + gauge( + set, + partition, + path.metric_name(NodeMetric::GROUPS), + &self.groups, + ); + gauge( + set, + partition, + path.metric_name(NodeMetric::STATE_ENTRIES), + &self.state_entries, + ); + MetricBuilder::new(set) + .with_partition(partition) + .build(MetricValue::Time { + name: path.metric_name(NodeMetric::SELF_COMPUTE_TIME_NS).into(), + time: self.self_compute_time.clone(), + }); + } + + /// Records that this node ingested `batches` batches carrying `samples` sample positions. + pub fn record_input(&self, batches: usize, samples: usize) { + self.input_batches.add(batches); + self.input_samples.add(samples); + } + + /// Records that this node produced `batches` batches carrying `values` valid values. + pub fn record_output(&self, batches: usize, values: usize) { + self.output_batches.add(batches); + self.output_values.add(values); + } + + /// Records that this node evaluated `points` grid positions. + pub fn record_grid_points(&self, points: usize) { + self.evaluated_grid_points.add(points); + } + + /// Records that this node closed `series` series. + pub fn record_completed_series(&self, series: usize) { + self.completed_series.add(series); + } + + /// Records that this node now reserves `bytes`. + /// + /// The peak is a high-water mark of this node in this partition, never a sum of the peaks of + /// different nodes: those peaks can happen at different times. + pub fn record_reserved_bytes(&self, bytes: usize) { + self.current_reserved_bytes.set(bytes); + // A high-water mark, not a sum: two nodes peak at different moments. + self.peak_reserved_bytes.set_max(bytes); + } + + /// Records the size of the grouping and state this node holds. + pub fn record_state(&self, groups: usize, entries: usize) { + self.groups.set(groups); + self.state_entries.set(entries); + } + + /// Starts timing this node's own work. + /// + /// The returned timer must be dropped before the node polls its input: a node's self time + /// excludes the work its inputs do. + pub fn timer(&self) -> datafusion::physical_plan::metrics::ScopedTimerGuard<'_> { + self.self_compute_time.timer() + } +} + +/// Registers every node of `root` in `set` and returns the handles in traversal order. +pub fn register_tree( + root: &NativeNode, + set: &ExecutionPlanMetricsSet, + partition: usize, +) -> Vec<(NodePath, Arc)> { + let mut out = Vec::new(); + walk(root, &mut |_, path| { + let metrics = Arc::new(NodeMetrics::default()); + metrics.register(path, set, partition); + out.push((path.clone(), metrics)); + }); + out +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use datatypes::series::samples::SeriesSchema; + use datatypes::series::time::{EvalGrid, GridSpec}; + + use super::{NodeMetric, NodePath, register_tree, walk}; + use crate::map::MathOp; + use crate::native::plan::{ + BoundInput, BoundMap, BoundWindow, NativeExpr, NativeNode, NativeType, + }; + use crate::range_eval::{RangeFunction, RangeWindow}; + + fn grid() -> Arc { + Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 60_000, 4).unwrap()).unwrap()) + } + + fn schema() -> Arc { + Arc::new(SeriesSchema { + fields: Arc::new([]), + eval_grid: None, + }) + } + + fn input() -> NativeNode { + let schema = schema(); + NativeNode { + expr: NativeExpr::Input(BoundInput { + schema: Arc::clone(&schema), + ordering: datatypes::series::SeriesOrdering::KeyThenTime, + }), + output: NativeType::Samples(schema), + } + } + + fn window(inner: NativeNode) -> NativeNode { + let grid = grid(); + NativeNode { + expr: NativeExpr::Window { + input: Box::new(inner), + op: BoundWindow { + function: RangeFunction::Rate, + window: RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + input_grid: None, + output_grid: Arc::clone(&grid), + }, + }, + output: NativeType::Samples(Arc::new(SeriesSchema { + fields: Arc::new([]), + eval_grid: Some(grid), + })), + } + } + + fn map(inner: NativeNode) -> NativeNode { + let grid = inner.output.grid().expect("a map needs a grid").clone(); + NativeNode { + expr: NativeExpr::Map { + input: Box::new(inner), + op: BoundMap { + ops: Arc::new([MathOp::Abs]), + }, + }, + output: NativeType::Samples(Arc::new(SeriesSchema { + fields: Arc::new([]), + eval_grid: Some(grid), + })), + } + } + + /// A unary chain is addressed by `.input`, so a metric can be attributed to one node. + #[test] + fn a_unary_chain_is_addressed_by_input_steps() { + let root = map(window(input())); + let mut paths = Vec::new(); + walk(&root, &mut |_, path| paths.push(path.to_string())); + assert_eq!(paths, vec!["root", "root.input", "root.input.input"]); + } + + /// A binary node addresses its two sides by name, so the two `rate` subtrees stay distinct. + #[test] + fn a_binary_node_addresses_both_sides() { + let binary = crate::native::plan::NativeNode { + expr: NativeExpr::Binary { + left: Box::new(window(input())), + right: Box::new(map(window(input()))), + matching: crate::vector_match::BinaryMatching { + op: crate::vector_match::BinaryOp::Add, + return_bool: false, + labels: crate::vector_match::MatchingLabels::Ignoring(Vec::new()), + cardinality: crate::vector_match::Cardinality::OneToOne, + }, + }, + output: { + let grid = grid(); + NativeType::Samples(Arc::new(SeriesSchema { + fields: Arc::new([]), + eval_grid: Some(grid), + })) + }, + }; + let mut paths = Vec::new(); + walk(&binary, &mut |_, path| paths.push(path.to_string())); + assert_eq!( + paths, + vec![ + "root", + "root.left", + "root.left.input", + "root.right", + "root.right.input", + "root.right.input.input", + ] + ); + } + + /// The name carries the position because the collector aggregates by name; a bare name would + /// merge two nodes of the same operation into one number. + #[test] + fn a_metric_name_carries_its_position() { + let path = NodePath::root().left().input(); + assert_eq!(path.as_str(), "root.left.input"); + assert_eq!( + path.metric_name(NodeMetric::SELF_COMPUTE_TIME_NS), + "native.root.left.input.self_compute_time_ns" + ); + // The peak keeps the partition, because two partitions peak at different moments. + assert!( + NodePath::root() + .metric_name(NodeMetric::PEAK_RESERVED_BYTES) + .starts_with("native.root.") + ); + } + + /// Registration covers every node, so no node is executed without a way to observe it. + #[test] + fn registration_covers_every_node() { + let root = map(window(input())); + let set = datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new(); + let registered = register_tree(&root, &set, 2); + assert_eq!(registered.len(), 3); + let names: Vec = registered + .iter() + .map(|(path, _)| path.metric_name(NodeMetric::OUTPUT_VALUES)) + .collect(); + assert_eq!( + names, + vec![ + "native.root.output_values", + "native.root.input.output_values", + "native.root.input.input.output_values", + ] + ); + } + + /// Every metric a node reports is listed in one place, so registration cannot drift from the + /// documented set. + #[test] + fn every_metric_is_declared() { + assert_eq!(NodeMetric::ALL.len(), 11); + assert!(NodeMetric::ALL.contains(&NodeMetric::SELF_COMPUTE_TIME_NS)); + assert!(NodeMetric::ALL.contains(&NodeMetric::PEAK_RESERVED_BYTES)); + } + + /// A peak is a high-water mark of one node, so it survives a later drop in reservations. + #[test] + fn a_peak_is_a_high_water_mark() { + let metrics = super::NodeMetrics::default(); + metrics.record_reserved_bytes(1024); + metrics.record_reserved_bytes(64); + assert_eq!(metrics.peak_reserved_bytes.value(), 1024); + assert_eq!(metrics.current_reserved_bytes.value(), 64); + } +} diff --git a/src/promql/src/native/mod.rs b/src/promql/src/native/mod.rs new file mode 100644 index 00000000000..cef95d339bb --- /dev/null +++ b/src/promql/src/native/mod.rs @@ -0,0 +1,33 @@ +// 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 native PromQL evaluation model. +//! +//! A query compiles to a [`plan::NativeTree`]: nodes whose operations, fields and grids are already +//! bound. Nodes hand each other [`batch::EvaluatedChunk`]s as ordinary Rust values, so no row batch +//! is materialised between them. [`metrics`] names each node after its position in that tree, so +//! `EXPLAIN` and `ANALYZE` describe the same structure. +//! +//! Three properties keep this apart from recognising a query shape in a finished physical plan: +//! +//! - Legality is a type and data-dependency question ([`plan::NativeNode::validate`]), so a new +//! combination of supported operations is an ordinary tree, not another matcher. +//! - A window binds its input and output grids separately, so a subquery's inner grid is consumed +//! as it is instead of being resampled onto the outer grid. +//! - A series closes exactly once, on the chunk that says so, so a consumer can tell "nothing more +//! here" from "no more input". + +pub mod batch; +pub mod metrics; +pub mod plan; diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs new file mode 100644 index 00000000000..5fbbfd8f0e7 --- /dev/null +++ b/src/promql/src/native/plan.rs @@ -0,0 +1,380 @@ +// 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 bound tree a native PromQL evaluation compiles to. +//! +//! A query is compiled into [`NativeTree`]: [`NativeNode`]s whose operations are already bound to +//! kernels, fields and grids. Nothing in this module interprets a function name, resolves a label +//! or picks a column at run time; those decisions are made before the tree exists, so the hot +//! path only feeds batches to kernels it was handed. +//! +//! The tree is also the unit of legality. [`NativeNode::validate`] checks the contract every +//! operation states about its input, which is what lets a new combination of supported operations +//! be an ordinary tree instead of another hand-written shape. + +use std::sync::Arc; + +use datafusion::error::{DataFusionError, Result}; +use datatypes::series::SeriesOrdering; +use datatypes::series::samples::{FieldSpec, SeriesSchema}; +use datatypes::series::time::EvalGrid; + +use crate::map::MathOp; +use crate::range_eval::{RangeFunction, RangeWindow}; +use crate::vector_match::BinaryMatching; + +/// What one node produces. +/// +/// A sample type with an evaluation grid is an evaluated series: one value per grid point. Without +/// a grid it is raw samples carrying their own timestamps. Intermediate aggregate state is a +/// different type altogether, so an operation that cannot consume it is rejected by type rather +/// than by convention. +#[derive(Clone, Debug)] +pub enum NativeType { + /// Samples, evaluated when the schema carries a grid and raw otherwise. + Samples(Arc), + /// Intermediate aggregate state, not a query value. + AggregateState(Arc), +} + +impl NativeType { + /// The schema of a sample type, or `None` for aggregate state. + pub fn samples(&self) -> Option<&Arc> { + match self { + Self::Samples(schema) => Some(schema), + Self::AggregateState(_) => None, + } + } + + /// The grid this type is evaluated on, or `None` when it holds raw samples or state. + pub fn grid(&self) -> Option<&Arc> { + self.samples().and_then(|schema| schema.eval_grid.as_ref()) + } + + /// Whether this type is an evaluated series, which is what operations over values consume. + pub fn is_evaluated(&self) -> bool { + self.grid().is_some() + } +} + +/// The layout of intermediate aggregate state. +/// +/// State is indexed by `(group labels, absolute grid index)`, so it carries the grid it was +/// accumulated on. It is not a query value and does not pretend to be one. +#[derive(Clone, Debug)] +pub struct AggregateStateSchema { + /// The labels a group is identified by, in output order. + pub group: Arc<[Arc]>, + /// The accumulator columns, one per aggregated field. + pub accumulators: Arc<[FieldSpec]>, + /// The grid the state is indexed on. + pub grid: Arc, +} + +/// A scan bound as a node input. +/// +/// The binding records what the input already guarantees, so the compiler can check a consumer's +/// requirement instead of assuming it. +#[derive(Clone, Debug)] +pub struct BoundInput { + /// The samples the input produces. + pub schema: Arc, + /// The ordering the input guarantees. + pub ordering: SeriesOrdering, +} + +/// A scalar bound for broadcast. +/// +/// A value that varies per grid point is not a scalar: it is an evaluated input, and it travels +/// as one. Only a constant is broadcast, which is why this carries no grid. +#[derive(Clone, Debug)] +pub struct BoundScalar { + /// The constant value. + pub value: f64, +} + +/// An instant selection: the last sample at or before each grid point, within a lookback. +#[derive(Clone, Debug)] +pub struct BoundInstant { + /// How far back a sample may lie before it counts as stale. + pub lookback_ms: i64, + /// Selector offset; positive reads earlier samples. + pub offset_ms: i64, + /// The grid the selection produces values on. + pub output_grid: Arc, +} + +/// A window function over raw samples or over an evaluated input. +/// +/// The input and output grids are bound separately: a subquery evaluates its inner expression on +/// its own grid and consumes the result directly, without resampling it onto the outer grid. +#[derive(Clone, Debug)] +pub struct BoundWindow { + /// The function this node runs. + pub function: RangeFunction, + /// The window length, offset and anchor. + pub window: RangeWindow, + /// The grid the input is evaluated on, or `None` when the input is raw samples. + pub input_grid: Option>, + /// The grid this node produces values on. + pub output_grid: Arc, +} + +/// A chain of point-wise operations applied to a whole evaluated value. +#[derive(Clone, Debug)] +pub struct BoundMap { + /// The operations, applied in order. + pub ops: Arc<[MathOp]>, +} + +/// Which aggregate a node computes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AggregateKind { + /// `sum` over the values of each group at each grid point. + Sum, +} + +/// Where an aggregate sits in the execution, which decides whether its output is a query value. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AggregateStage { + /// Every contribution to each group lies within this execution, so the output is complete. + Complete, + /// Only this execution's contributions were seen, so the output is state for a later merge. + Partial, + /// The state was collected from every contributing execution, so the output is complete. + Final, +} + +impl AggregateStage { + /// Whether this stage produces a query value rather than intermediate state. + pub fn produces_value(self) -> bool { + matches!(self, Self::Complete | Self::Final) + } +} + +/// An aggregate bound to its kind, grouping and stage. +#[derive(Clone, Debug)] +pub struct BoundAggregate { + /// Which aggregate to compute. + pub kind: AggregateKind, + /// The labels a group is identified by. + pub group: Arc<[Arc]>, + /// Where this aggregate sits in the execution. + pub stage: AggregateStage, +} + +/// What a node computes. Every variant holds a bound operation, never a name to resolve. +#[derive(Clone, Debug)] +pub enum NativeExpr { + /// A scan. + Input(BoundInput), + /// A scalar. + Scalar(BoundScalar), + /// An instant selection over its input. + Instant { + input: Box, + op: BoundInstant, + }, + /// A window function over its input. + Window { + input: Box, + op: BoundWindow, + }, + /// Point-wise operations over its input. + Map { + input: Box, + op: BoundMap, + }, + /// An aggregate over its input. + Aggregate { + input: Box, + op: BoundAggregate, + }, + /// A binary operation between two inputs, with its matching rules. + Binary { + left: Box, + right: Box, + matching: BinaryMatching, + }, +} + +/// One node of a bound tree. +#[derive(Clone, Debug)] +pub struct NativeNode { + /// What this node computes, including its bound operands. + pub expr: NativeExpr, + /// What this node produces. + pub output: NativeType, +} + +/// A bound evaluation tree. +/// +/// The tree itself carries no run-time state: every execution builds its own, so one compiled plan +/// can serve every partition. +#[derive(Clone, Debug)] +pub struct NativeTree { + root: NativeNode, +} + +impl NativeTree { + /// Creates a tree over `root`, checking that every node's contract holds. + /// + /// A rejected tree is a compiler defect rather than a query error: the compiler only builds a + /// node after deciding that this combination is supported. + pub fn try_new(root: NativeNode) -> Result { + root.validate()?; + Ok(Self { root }) + } + + /// The root node. + pub fn root(&self) -> &NativeNode { + &self.root + } +} + +impl NativeNode { + /// Checks this node and its inputs against the contract of its operation. + pub fn validate(&self) -> Result<()> { + match &self.expr { + NativeExpr::Input(input) => { + ensure_samples(&self.output, "an input")?; + let schema = self.output.samples().expect("checked above"); + if !Arc::ptr_eq(schema, &input.schema) { + return Err(invalid( + "an input node's output schema is not the schema it was bound to", + )); + } + } + NativeExpr::Scalar(_) => { + ensure_samples(&self.output, "a scalar")?; + } + NativeExpr::Instant { input, op } => { + input.validate()?; + // An instant selection reads raw samples and stamps them onto its own grid. + if input.output.is_evaluated() { + return Err(invalid("an instant selection reads evaluated values")); + } + ensure_samples(&self.output, "an instant selection")?; + ensure_grid(&self.output, &op.output_grid, "an instant selection")?; + } + NativeExpr::Window { input, op } => { + input.validate()?; + // The declared input grid has to be the grid the input actually produces, or the + // window would read positions the input never wrote. + match (op.input_grid.as_ref(), input.output.grid()) { + (None, None) => {} + (Some(bound), Some(actual)) if Arc::ptr_eq(bound, actual) => {} + _ => { + return Err(invalid( + "a window's declared input grid is not the input's grid", + )); + } + } + ensure_samples(&self.output, "a window")?; + ensure_grid(&self.output, &op.output_grid, "a window")?; + } + NativeExpr::Map { input, op } => { + input.validate()?; + // A map is point-wise over values, so it needs a grid to be point-wise over. + if !input.output.is_evaluated() { + return Err(invalid("a map consumes values that are not evaluated")); + } + if op.ops.is_empty() { + return Err(invalid("a map holds no operation")); + } + ensure_samples(&self.output, "a map")?; + let input_grid = input.output.grid().expect("checked above"); + ensure_grid(&self.output, input_grid, "a map")?; + } + NativeExpr::Aggregate { input, op } => { + input.validate()?; + if !input.output.is_evaluated() { + return Err(invalid( + "an aggregate consumes values that are not evaluated", + )); + } + match (&self.output, op.stage.produces_value()) { + (NativeType::Samples(schema), true) => { + ensure_grid( + &self.output, + input.output.grid().expect("checked above"), + "an aggregate", + )?; + debug_assert!(schema.eval_grid.is_some()); + } + (NativeType::AggregateState(state), false) => { + let input_grid = input.output.grid().expect("checked above"); + if !Arc::ptr_eq(&state.grid, input_grid) { + return Err(invalid( + "aggregate state is indexed on a grid the input does not produce", + )); + } + if state.group != op.group { + return Err(invalid("aggregate state groups differ from the binding")); + } + } + _ => { + return Err(invalid( + "an aggregate's output type does not match its stage", + )); + } + } + } + NativeExpr::Binary { left, right, .. } => { + left.validate()?; + right.validate()?; + if !left.output.is_evaluated() || !right.output.is_evaluated() { + return Err(invalid( + "a binary operation consumes values that are not evaluated", + )); + } + let left_grid = left.output.grid().expect("checked above"); + let right_grid = right.output.grid().expect("checked above"); + if !Arc::ptr_eq(left_grid, right_grid) { + return Err(invalid("a binary operation aligns two different grids")); + } + ensure_samples(&self.output, "a binary operation")?; + ensure_grid(&self.output, left_grid, "a binary operation")?; + } + } + Ok(()) + } +} + +fn ensure_samples(ty: &NativeType, what: &str) -> Result<()> { + if matches!(ty, NativeType::Samples(_)) { + Ok(()) + } else { + Err(invalid(&format!("{what} does not produce samples"))) + } +} + +fn ensure_grid(ty: &NativeType, expected: &Arc, what: &str) -> Result<()> { + match ty.grid() { + Some(actual) if Arc::ptr_eq(actual, expected) => Ok(()), + Some(_) => Err(invalid(&format!( + "{what} declares a grid its output does not carry" + ))), + None => Err(invalid(&format!("{what} produces values without a grid"))), + } +} + +fn invalid(reason: &str) -> DataFusionError { + // A rejected tree is a compiler defect, not a query error: the compiler only builds a node + // after deciding that this combination is supported. + DataFusionError::Plan(reason.to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs new file mode 100644 index 00000000000..3eab716cf58 --- /dev/null +++ b/src/promql/src/native/plan/tests.rs @@ -0,0 +1,387 @@ +// 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. + +use std::sync::Arc; + +use datatypes::series::SeriesOrdering; +use datatypes::series::samples::SeriesSchema; +use datatypes::series::time::{EvalGrid, GridSpec}; + +use super::{ + AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar, + BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, +}; +use crate::map::MathOp; +use crate::range_eval::{RangeFunction, RangeWindow}; +use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, MatchingLabels}; + +fn grid(start: i64, step: i64, len: u64) -> Arc { + Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap()) +} + +fn evaluated( + schema_fields: Arc<[datatypes::series::samples::FieldSpec]>, + grid: Arc, +) -> NativeType { + NativeType::Samples(Arc::new(SeriesSchema { + fields: schema_fields, + eval_grid: Some(grid), + })) +} + +fn raw() -> NativeType { + NativeType::Samples(Arc::new(SeriesSchema { + fields: Arc::new([]), + eval_grid: None, + })) +} + +fn input() -> NativeNode { + let NativeType::Samples(schema) = raw() else { + unreachable!() + }; + NativeNode { + expr: NativeExpr::Input(BoundInput { + schema: Arc::clone(&schema), + ordering: SeriesOrdering::KeyThenTime, + }), + output: NativeType::Samples(schema), + } +} + +fn input_on(grid: Arc) -> NativeNode { + // One allocation shared by the binding and the output: `validate` checks allocation identity, + // because a compiler that meant one grid has no reason to allocate it twice. + let schema = Arc::new(SeriesSchema { + fields: Arc::new([]), + eval_grid: Some(grid), + }); + NativeNode { + expr: NativeExpr::Input(BoundInput { + schema: Arc::clone(&schema), + ordering: SeriesOrdering::Contiguous, + }), + output: NativeType::Samples(schema), + } +} + +fn window_over(inner: NativeNode, input_grid: Option>) -> NativeNode { + window_on(inner, input_grid, grid(0, 60_000, 4)) +} + +/// A window over `inner` that produces `out`, so two windows can be given the same grid. +fn window_on( + inner: NativeNode, + input_grid: Option>, + out: Arc, +) -> NativeNode { + NativeNode { + expr: NativeExpr::Window { + input: Box::new(inner), + op: BoundWindow { + function: RangeFunction::Rate, + window: RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + input_grid, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(Arc::new([]), out), + } +} + +fn map_over(inner: NativeNode) -> NativeNode { + let out = inner.output.grid().expect("a map needs a grid").clone(); + NativeNode { + expr: NativeExpr::Map { + input: Box::new(inner), + op: BoundMap { + ops: Arc::new([MathOp::Abs]), + }, + }, + output: evaluated(Arc::new([]), out), + } +} + +fn add() -> BinaryMatching { + BinaryMatching { + op: BinaryOp::Add, + return_bool: false, + labels: MatchingLabels::Ignoring(Vec::new()), + cardinality: Cardinality::OneToOne, + } +} + +/// A compiled tree is accepted when every node's contract holds. +#[test] +fn a_window_over_raw_samples_is_valid() { + let root = window_over(input(), None); + assert!(NativeTree::try_new(root).is_ok()); +} + +/// Adding a map to a window changes the tree and nothing else: no new shape is recognised. +#[test] +fn adding_a_map_only_changes_the_tree() { + let bare = window_over(input(), None); + let mapped = map_over(window_over(input(), None)); + assert_eq!(bare.validate().is_ok(), mapped.validate().is_ok()); + // The mapped tree has one more node, and it is the same window below it. + let mut depth = 0; + super::super::metrics::walk(&mapped, &mut |_, _| depth += 1); + assert_eq!(depth, 3); +} + +/// A map is point-wise over values, so raw samples are not something it can consume. +#[test] +fn a_map_cannot_consume_raw_samples() { + let node = NativeNode { + expr: NativeExpr::Map { + input: Box::new(input()), + op: BoundMap { + ops: Arc::new([MathOp::Abs]), + }, + }, + output: evaluated(Arc::new([]), grid(0, 60_000, 4)), + }; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("not evaluated"), "{error}"); +} + +/// A map with no operation would be a node that does nothing, which is a compiler mistake. +#[test] +fn a_map_needs_an_operation() { + let inner = window_over(input(), None); + let out = inner.output.grid().unwrap().clone(); + let node = NativeNode { + expr: NativeExpr::Map { + input: Box::new(inner), + op: BoundMap { ops: Arc::new([]) }, + }, + output: evaluated(Arc::new([]), out), + }; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("no operation"), "{error}"); +} + +/// An instant selection reads raw samples; feeding it evaluated values would re-anchor a grid +/// that is already fixed. +#[test] +fn an_instant_selection_reads_raw_samples() { + let out = grid(0, 60_000, 4); + let node = NativeNode { + expr: NativeExpr::Instant { + input: Box::new(window_over(input(), None)), + op: BoundInstant { + lookback_ms: 300_000, + offset_ms: 0, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(Arc::new([]), out), + }; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("reads evaluated"), "{error}"); +} + +/// A window's declared input grid has to be the grid its input actually produces. +#[test] +fn a_window_checks_its_declared_input_grid() { + let inner_grid = grid(0, 60_000, 4); + let other_grid = grid(0, 30_000, 8); + // The input produces `inner_grid`, but the window claims a different one. + let node = window_over(input_on(inner_grid), Some(other_grid)); + let error = node.validate().unwrap_err(); + assert!( + error + .to_string() + .contains("input grid is not the input's grid"), + "{error}" + ); +} + +/// A binary node aligns two inputs, so two different grids cannot be aligned implicitly. +#[test] +fn a_binary_operation_rejects_two_grids() { + let left = window_over(input(), None); + let left_grid = left.output.grid().unwrap().clone(); + let right = window_on(input(), None, grid(0, 30_000, 8)); + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(left), + right: Box::new(right), + matching: add(), + }, + output: evaluated(Arc::new([]), left_grid), + }; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("different grids"), "{error}"); +} + +/// Two inputs on the same grid are a legal binary operation, which is how +/// `rate(a[5m]) + rate(b[5m])` becomes an ordinary tree. +#[test] +fn a_binary_operation_over_one_grid_is_valid() { + // Both sides evaluate on the statement's grid, so the compiler binds one grid to both. + let shared = grid(0, 60_000, 4); + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(window_on(input(), None, Arc::clone(&shared))), + right: Box::new(window_on(input(), None, Arc::clone(&shared))), + matching: add(), + }, + output: evaluated(Arc::new([]), shared), + }; + assert!(node.validate().is_ok()); +} + +/// A partial aggregate produces state, not a value; a complete one produces a value on the same +/// grid as its input. +#[test] +fn an_aggregate_output_matches_its_stage() { + let inner = window_over(input(), None); + let value_grid = inner.output.grid().unwrap().clone(); + + let complete = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(inner.clone()), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Complete, + }, + }, + output: evaluated(Arc::new([]), Arc::clone(&value_grid)), + }; + assert!(complete.validate().is_ok()); + + let partial = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(inner), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Partial, + }, + }, + output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema { + group: Arc::new(["job".into()]), + accumulators: Arc::new([]), + grid: value_grid, + })), + }; + assert!(partial.validate().is_ok()); +} + +/// Declaring a value where the stage produces state is a compiler mistake, and is rejected. +#[test] +fn an_aggregate_stage_must_agree_with_its_type() { + let inner = window_over(input(), None); + let value_grid = inner.output.grid().unwrap().clone(); + let node = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(inner), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Partial, + }, + }, + output: evaluated(Arc::new([]), value_grid), + }; + let error = node.validate().unwrap_err(); + assert!( + error.to_string().contains("does not match its stage"), + "{error}" + ); +} + +/// The first-phase walkthrough shapes compile to trees, which is the acceptance the RFC states +/// for composition. +#[test] +fn the_walkthrough_shapes_are_trees() { + // Every node in one query evaluates on the statement's grid, so the compiler binds one grid + // and shares it; `validate` checks that identity. + let statement_grid = grid(0, 60_000, 4); + + // `abs(rate(x[5m]))` + let abs_rate = map_over(window_over(input(), None)); + assert!(abs_rate.validate().is_ok()); + + // `sum by(job)(rate(x[5m]))`, complete because one execution sees every contribution. + let sum = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(window_on(input(), None, Arc::clone(&statement_grid))), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Complete, + }, + }, + output: evaluated(Arc::new([]), Arc::clone(&statement_grid)), + }; + assert!(sum.validate().is_ok()); + + // `sum by(job)(rate(x[5m])) + 1`: the scalar applies to the completed value, not to state. + let plus_one = NativeNode { + expr: NativeExpr::Map { + input: Box::new(NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(window_on(input(), None, Arc::clone(&statement_grid))), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Final, + }, + }, + output: evaluated(Arc::new([]), Arc::clone(&statement_grid)), + }), + op: BoundMap { + ops: Arc::new([MathOp::Abs]), + }, + }, + output: evaluated(Arc::new([]), statement_grid), + }; + assert!(plus_one.validate().is_ok()); +} + +/// A scalar node is legal on its own; a raw input is not evaluated, so nothing consuming values +/// may sit above it. +#[test] +fn a_scalar_node_is_valid() { + let node = NativeNode { + expr: NativeExpr::Scalar(BoundScalar { value: 1.0 }), + output: evaluated(Arc::new([]), grid(0, 60_000, 4)), + }; + assert!(node.validate().is_ok()); +} + +/// An input whose declared schema is not the schema it was bound to cannot be trusted. +#[test] +fn an_input_must_report_the_schema_it_was_bound_to() { + let node = NativeNode { + expr: NativeExpr::Input(BoundInput { + schema: Arc::new(SeriesSchema { + fields: Arc::new([]), + eval_grid: None, + }), + ordering: SeriesOrdering::KeyThenTime, + }), + output: raw(), + }; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("not the schema"), "{error}"); +} From 97b97fce39070687596f7a1e7f6031728d2272ba Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Mon, 19 Oct 2026 14:53:53 +0800 Subject: [PATCH 02/17] fix(promql): make the bound tree's type contracts match what each stage consumes Four review findings on the bound tree, all about checks that passed the wrong things. An aggregate's stage decided its output but not its input. Every stage first required its input to be evaluated, which aggregate state is not, so `Final(Partial(...))` was rejected and `Final(Window(...))` was accepted. Each stage now states its pair: `Complete` takes a vector and produces one on the same grid, `Partial` takes a vector and produces state on that grid with the bound grouping, `Final` takes state with the bound grouping and produces a vector on the state's grid. Window and instant selections accepted aggregate state. The cause was asking `is_evaluated()`, which is false both for raw samples and for state, since state has no grid: `Instant(Partial(...))` and a window bound to `input_grid: None` over `Partial(...)` both passed and would have read state as raw samples. Both now match on `NativeType::Samples` first and only then on the grid, so state is rejected by what it is rather than by lacking a grid. Scalars were modelled as a grid-less evaluated sample, and `BoundScalar`'s doc claimed a value varying per grid point is not a scalar. That is wrong for PromQL: `time()` and `scalar(v)` produce a scalar per evaluation time. A scalar is now its own `NativeType::Scalar(grid)`, so a binary operation can tell a broadcast from label matching -- `sum by(job)(rate(x[5m])) + time()` broadcasts rather than matching on the empty label set -- and `Map`, `Aggregate`, `Instant` and `Window` reject it by type. The `time()` kernel itself is not in scope. An input could bind only samples, so an exchange boundary could not bind the state a `Final` aggregate consumes. `BoundInput` holds a `NativeType`, and input nodes check that their output is the same binding rather than the same schema. A peak is the one figure the collector must not add up: it groups metrics by name, clears the partition and sums gauges, so partition peaks of 1024 and 2048 reported 3072, which is neither peak. `PEAK_RESERVED_BYTES` now carries the partition in its name (`native.p0.root.peak_reserved_bytes`), while counts and the other gauges still sum across partitions, where a sum is meaningful. The test that claimed the peak kept its partition only checked a name prefix; it now registers two partitions, runs the real `aggregate_by_name`, and asserts both peaks survive with their own values. The walkthrough's `+1` test was wrong twice over: it took a `Final` aggregate directly over a `Window` -- the case the first finding now rejects -- and applied `MathOp::Abs`, which is not `+1`. It now builds a real binary `+` with a scalar operand. Signed-off-by: discord9 Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/metrics.rs | 66 +++++- src/promql/src/native/plan.rs | 268 +++++++++++++++------ src/promql/src/native/plan/tests.rs | 350 ++++++++++++++++++++++++---- 3 files changed, 568 insertions(+), 116 deletions(-) diff --git a/src/promql/src/native/metrics.rs b/src/promql/src/native/metrics.rs index 22819923da5..03739bda53c 100644 --- a/src/promql/src/native/metrics.rs +++ b/src/promql/src/native/metrics.rs @@ -73,6 +73,14 @@ impl NodePath { pub fn metric_name(&self, metric: &str) -> String { format!("{NATIVE_PREFIX}.{}.{}", self.0, metric) } + + /// The full metric name for `metric` at this position in `partition`. + /// + /// A figure that must not be merged across partitions needs the partition in its name: the + /// collector aggregates by name first, and a sum of peaks is not a peak. + pub fn partitioned_metric_name(&self, metric: &str, partition: usize) -> String { + format!("{NATIVE_PREFIX}.p{partition}.{}.{metric}", self.0) + } } impl std::fmt::Display for NodePath { @@ -189,8 +197,9 @@ impl Default for NodeMetrics { impl NodeMetrics { /// Registers this node's metrics under `path` in `set`. /// - /// `partition` is part of the registration, so two partitions of one plan report separately - /// and a peak never gets summed across them. + /// `partition` is part of the registration, so two partitions of one plan report separately. + /// It is also part of the peak's name, because a peak is the one figure a collector must not + /// add up across partitions. pub fn register(&self, path: &NodePath, set: &ExecutionPlanMetricsSet, partition: usize) { fn count(set: &ExecutionPlanMetricsSet, partition: usize, name: String, count: &Count) { MetricBuilder::new(set) @@ -251,10 +260,14 @@ impl NodeMetrics { path.metric_name(NodeMetric::CURRENT_RESERVED_BYTES), &self.current_reserved_bytes, ); + // The peak is the one figure named per partition. The collector groups by name and sums + // gauges, and a sum of two peaks is neither peak: partitions peak at different moments. + // Summing the other gauges and counts stays meaningful — the memory held now, the groups + // tracked and the samples seen all add up across partitions. gauge( set, partition, - path.metric_name(NodeMetric::PEAK_RESERVED_BYTES), + path.partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, partition), &self.peak_reserved_bytes, ); gauge( @@ -343,6 +356,7 @@ pub fn register_tree( mod tests { use std::sync::Arc; + use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricValue}; use datatypes::series::samples::SeriesSchema; use datatypes::series::time::{EvalGrid, GridSpec}; @@ -365,13 +379,13 @@ mod tests { } fn input() -> NativeNode { - let schema = schema(); + let output = NativeType::Samples(schema()); NativeNode { expr: NativeExpr::Input(BoundInput { - schema: Arc::clone(&schema), + output: output.clone(), ordering: datatypes::series::SeriesOrdering::KeyThenTime, }), - output: NativeType::Samples(schema), + output, } } @@ -470,14 +484,44 @@ mod tests { path.metric_name(NodeMetric::SELF_COMPUTE_TIME_NS), "native.root.left.input.self_compute_time_ns" ); - // The peak keeps the partition, because two partitions peak at different moments. - assert!( - NodePath::root() - .metric_name(NodeMetric::PEAK_RESERVED_BYTES) - .starts_with("native.root.") + assert_eq!( + path.partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, 1), + "native.p1.root.left.input.peak_reserved_bytes" ); } + /// The peak keeps the partition in its name, so the collector's aggregation by name cannot add + /// two partitions' peaks: 1024 and 2048 peak at different moments, and 3072 is neither peak. + #[test] + fn a_peak_is_not_merged_across_partitions() { + let root = map(window(input())); + let set = ExecutionPlanMetricsSet::new(); + let peaks = [(0, 1024), (1, 2048)]; + for (partition, peak) in peaks { + let registered = register_tree(&root, &set, partition); + // The root comes first in traversal order. + registered[0].1.record_reserved_bytes(peak); + } + + // The real collector path: `aggregate_by_name` groups by metric name and sums the + // values in each group. + let aggregated = set.clone_inner().aggregate_by_name(); + let peak = |partition: usize| -> Option { + let expected = NodePath::root() + .partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, partition); + aggregated.iter().find_map(|metric| match metric.value() { + MetricValue::Gauge { name, gauge } if name.as_ref() == expected.as_str() => { + Some(gauge.value()) + } + _ => None, + }) + }; + // Two separate names, each holding its own partition's peak: had the name not carried the + // partition, aggregation would have merged them into one gauge summing to 3072. + assert_eq!(peak(0), Some(1024)); + assert_eq!(peak(1), Some(2048)); + } + /// Registration covers every node, so no node is executed without a way to observe it. #[test] fn registration_covers_every_node() { diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 5fbbfd8f0e7..068ab68d5a8 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -37,34 +37,65 @@ use crate::vector_match::BinaryMatching; /// What one node produces. /// /// A sample type with an evaluation grid is an evaluated series: one value per grid point. Without -/// a grid it is raw samples carrying their own timestamps. Intermediate aggregate state is a -/// different type altogether, so an operation that cannot consume it is rejected by type rather -/// than by convention. +/// a grid it is raw samples carrying their own timestamps. A scalar is one value per grid point +/// and no labels. Intermediate aggregate state is a different type altogether, so an operation +/// that cannot consume it is rejected by type rather than by convention. #[derive(Clone, Debug)] pub enum NativeType { /// Samples, evaluated when the schema carries a grid and raw otherwise. Samples(Arc), + /// One value per grid point and no labels, which binary operations broadcast. + /// + /// PromQL scalars vary with the evaluation time (`time()`, `scalar(v)`), so this carries the + /// grid it is evaluated on. Its value carrier is a series without labels, but its type is + /// what keeps a broadcast from becoming label matching. + Scalar(Arc), /// Intermediate aggregate state, not a query value. AggregateState(Arc), } impl NativeType { - /// The schema of a sample type, or `None` for aggregate state. + /// The schema of a sample type, or `None` for a scalar or aggregate state. pub fn samples(&self) -> Option<&Arc> { match self { Self::Samples(schema) => Some(schema), - Self::AggregateState(_) => None, + Self::Scalar(_) | Self::AggregateState(_) => None, } } /// The grid this type is evaluated on, or `None` when it holds raw samples or state. + /// + /// A scalar is evaluated on its grid like a vector, which is what lets a binary operation + /// line it up with a vector point by point; only raw samples and state have no positions. pub fn grid(&self) -> Option<&Arc> { - self.samples().and_then(|schema| schema.eval_grid.as_ref()) + match self { + Self::Samples(schema) => schema.eval_grid.as_ref(), + Self::Scalar(grid) => Some(grid), + Self::AggregateState(_) => None, + } } - /// Whether this type is an evaluated series, which is what operations over values consume. - pub fn is_evaluated(&self) -> bool { - self.grid().is_some() + /// What this type is, for a rejection that has to say what a consumer was handed. + fn describe(&self) -> &'static str { + match self { + Self::Samples(schema) if schema.eval_grid.is_some() => "an evaluated vector", + Self::Samples(_) => "raw samples", + Self::Scalar(_) => "a scalar", + Self::AggregateState(_) => "aggregate state", + } + } + + /// Whether `self` binds the same thing as `other`: the same samples or the same state. + /// + /// Bindings are compared by allocation identity, because a compiler that meant one schema or + /// one state has no reason to allocate it twice. A scalar is produced by a node and never + /// handed to one by a source, so it never matches. + fn same_binding(&self, other: &NativeType) -> bool { + match (self, other) { + (Self::Samples(mine), Self::Samples(theirs)) => Arc::ptr_eq(mine, theirs), + (Self::AggregateState(mine), Self::AggregateState(theirs)) => Arc::ptr_eq(mine, theirs), + _ => false, + } } } @@ -82,22 +113,23 @@ pub struct AggregateStateSchema { pub grid: Arc, } -/// A scan bound as a node input. +/// A scan or exchange boundary bound as a node input. /// /// The binding records what the input already guarantees, so the compiler can check a consumer's /// requirement instead of assuming it. #[derive(Clone, Debug)] pub struct BoundInput { - /// The samples the input produces. - pub schema: Arc, + /// What the input produces: raw samples from a scan, or state from an exchange boundary. + pub output: NativeType, /// The ordering the input guarantees. pub ordering: SeriesOrdering, } -/// A scalar bound for broadcast. +/// A constant scalar bound for broadcast. /// -/// A value that varies per grid point is not a scalar: it is an evaluated input, and it travels -/// as one. Only a constant is broadcast, which is why this carries no grid. +/// A scalar that varies per grid point is the same [`NativeType::Scalar`] as this constant: what +/// keeps a binary operation from label-matching it is its type, not its constness. This binding +/// only holds the constant case. #[derive(Clone, Debug)] pub struct BoundScalar { /// The constant value. @@ -156,13 +188,6 @@ pub enum AggregateStage { Final, } -impl AggregateStage { - /// Whether this stage produces a query value rather than intermediate state. - pub fn produces_value(self) -> bool { - matches!(self, Self::Complete | Self::Final) - } -} - /// An aggregate bound to its kind, grouping and stage. #[derive(Clone, Debug)] pub struct BoundAggregate { @@ -177,9 +202,9 @@ pub struct BoundAggregate { /// What a node computes. Every variant holds a bound operation, never a name to resolve. #[derive(Clone, Debug)] pub enum NativeExpr { - /// A scan. + /// A scan or an exchange boundary. Input(BoundInput), - /// A scalar. + /// A constant scalar, evaluated on the statement's grid. Scalar(BoundScalar), /// An instant selection over its input. Instant { @@ -202,6 +227,8 @@ pub enum NativeExpr { op: BoundAggregate, }, /// A binary operation between two inputs, with its matching rules. + /// + /// Scalar operands are broadcast, so `matching` only applies to vector–vector operations. Binary { left: Box, right: Box, @@ -248,31 +275,52 @@ impl NativeNode { pub fn validate(&self) -> Result<()> { match &self.expr { NativeExpr::Input(input) => { - ensure_samples(&self.output, "an input")?; - let schema = self.output.samples().expect("checked above"); - if !Arc::ptr_eq(schema, &input.schema) { + // An input node's output is exactly the binding it was bound to: a scan hands over + // the samples it was created for, and an exchange boundary the state. + if !self.output.same_binding(&input.output) { return Err(invalid( - "an input node's output schema is not the schema it was bound to", + "an input node's output is not the binding it was bound to", )); } } NativeExpr::Scalar(_) => { - ensure_samples(&self.output, "a scalar")?; + // A scalar's output is the scalar type: one value per grid point and no labels. + if !matches!(self.output, NativeType::Scalar(_)) { + return Err(invalid("a scalar node does not produce a scalar")); + } } NativeExpr::Instant { input, op } => { input.validate()?; - // An instant selection reads raw samples and stamps them onto its own grid. - if input.output.is_evaluated() { - return Err(invalid("an instant selection reads evaluated values")); + // An instant selection reads raw samples and stamps them onto its own grid: an + // evaluated vector is already stamped, and a scalar has no timestamps at all. + match &input.output { + NativeType::Samples(schema) if schema.eval_grid.is_none() => {} + NativeType::Samples(_) => { + return Err(invalid("an instant selection reads evaluated values")); + } + other => { + return Err(invalid(&format!( + "an instant selection consumes raw samples, not {}", + other.describe() + ))); + } } ensure_samples(&self.output, "an instant selection")?; ensure_grid(&self.output, &op.output_grid, "an instant selection")?; } NativeExpr::Window { input, op } => { input.validate()?; + // A window reads a range of samples per grid point, so it consumes samples: state + // is not a sample stream and a scalar has no timestamps. + let NativeType::Samples(schema) = &input.output else { + return Err(invalid(&format!( + "a window consumes samples, not {}", + input.output.describe() + ))); + }; // The declared input grid has to be the grid the input actually produces, or the // window would read positions the input never wrote. - match (op.input_grid.as_ref(), input.output.grid()) { + match (op.input_grid.as_ref(), schema.eval_grid.as_ref()) { (None, None) => {} (Some(bound), Some(actual)) if Arc::ptr_eq(bound, actual) => {} _ => { @@ -286,35 +334,53 @@ impl NativeNode { } NativeExpr::Map { input, op } => { input.validate()?; - // A map is point-wise over values, so it needs a grid to be point-wise over. - if !input.output.is_evaluated() { - return Err(invalid("a map consumes values that are not evaluated")); - } + // A map is point-wise over an evaluated vector: raw samples have no shared + // positions to be point-wise over, and a scalar is not a vector. + let Some(input_grid) = evaluated_grid(&input.output) else { + return Err(invalid(&format!( + "a map consumes an evaluated vector, not {}", + input.output.describe() + ))); + }; if op.ops.is_empty() { return Err(invalid("a map holds no operation")); } ensure_samples(&self.output, "a map")?; - let input_grid = input.output.grid().expect("checked above"); ensure_grid(&self.output, input_grid, "a map")?; } NativeExpr::Aggregate { input, op } => { input.validate()?; - if !input.output.is_evaluated() { - return Err(invalid( - "an aggregate consumes values that are not evaluated", - )); - } - match (&self.output, op.stage.produces_value()) { - (NativeType::Samples(schema), true) => { - ensure_grid( - &self.output, - input.output.grid().expect("checked above"), - "an aggregate", - )?; - debug_assert!(schema.eval_grid.is_some()); + // A stage's contract is a pair of types, not only what it produces: `Partial` + // turns a vector into state and `Final` turns state back into a vector, so state + // never sits where a value is expected and a value never sits where state is. + match op.stage { + AggregateStage::Complete => { + // Every contribution lies within this execution: vector in, vector out, + // both on the input's grid. + let Some(input_grid) = evaluated_grid(&input.output) else { + return Err(invalid(&format!( + "a complete aggregate consumes an evaluated vector, not {}", + input.output.describe() + ))); + }; + ensure_samples(&self.output, "a complete aggregate")?; + ensure_grid(&self.output, input_grid, "a complete aggregate")?; } - (NativeType::AggregateState(state), false) => { - let input_grid = input.output.grid().expect("checked above"); + AggregateStage::Partial => { + // Only this execution's contributions were seen, so the output is state + // for a later merge: on the input's grid, grouped the same way. + let Some(input_grid) = evaluated_grid(&input.output) else { + return Err(invalid(&format!( + "a partial aggregate consumes an evaluated vector, not {}", + input.output.describe() + ))); + }; + let NativeType::AggregateState(state) = &self.output else { + return Err(invalid(&format!( + "a partial aggregate produces aggregate state, not {}", + self.output.describe() + ))); + }; if !Arc::ptr_eq(&state.grid, input_grid) { return Err(invalid( "aggregate state is indexed on a grid the input does not produce", @@ -324,34 +390,104 @@ impl NativeNode { return Err(invalid("aggregate state groups differ from the binding")); } } - _ => { - return Err(invalid( - "an aggregate's output type does not match its stage", - )); + AggregateStage::Final => { + // The state was collected from every contributing execution, so the + // output is the complete value on the grid that state is indexed on. + let NativeType::AggregateState(state) = &input.output else { + return Err(invalid(&format!( + "a final aggregate consumes aggregate state, not {}", + input.output.describe() + ))); + }; + if state.group != op.group { + return Err(invalid("aggregate state groups differ from the binding")); + } + ensure_samples(&self.output, "a final aggregate")?; + ensure_grid(&self.output, &state.grid, "a final aggregate")?; } } } NativeExpr::Binary { left, right, .. } => { left.validate()?; right.validate()?; - if !left.output.is_evaluated() || !right.output.is_evaluated() { - return Err(invalid( - "a binary operation consumes values that are not evaluated", - )); - } - let left_grid = left.output.grid().expect("checked above"); - let right_grid = right.output.grid().expect("checked above"); + // A binary operation is point-wise, so both sides are evaluated on the statement's + // grid: state has no positions at all, and raw samples carry their own timestamps + // instead of positions on a shared grid. + let Some(left_grid) = left.output.grid() else { + return Err(invalid(&format!( + "a binary operation consumes evaluated values, not {} on its left", + left.output.describe() + ))); + }; + let Some(right_grid) = right.output.grid() else { + return Err(invalid(&format!( + "a binary operation consumes evaluated values, not {} on its right", + right.output.describe() + ))); + }; if !Arc::ptr_eq(left_grid, right_grid) { return Err(invalid("a binary operation aligns two different grids")); } - ensure_samples(&self.output, "a binary operation")?; - ensure_grid(&self.output, left_grid, "a binary operation")?; + match (&left.output, &right.output) { + // Two scalars make a scalar: there is nothing to match and nothing to keep. + (NativeType::Scalar(_), NativeType::Scalar(_)) => { + if !matches!(&self.output, NativeType::Scalar(grid) if Arc::ptr_eq(grid, left_grid)) + { + return Err(invalid( + "two scalars do not produce a scalar on the statement's grid", + )); + } + } + // A scalar side carries no labels and no fields, so the operation is a + // broadcast on the statement's grid and `matching` is not consulted. A scalar + // has no fields of its own, so the broadcast keeps the vector side's fields. + (NativeType::Scalar(_), NativeType::Samples(vector)) + | (NativeType::Samples(vector), NativeType::Scalar(_)) => { + let Some(output) = self.output.samples() else { + return Err(invalid(&format!( + "a scalar broadcast produces the vector side's samples, not {}", + self.output.describe() + ))); + }; + ensure_grid(&self.output, left_grid, "a scalar broadcast")?; + if output.fields.len() != vector.fields.len() { + return Err(invalid( + "a scalar broadcast does not produce the vector side's fields", + )); + } + } + // Two vectors are matched by `matching` on the grid they share. + (NativeType::Samples(_), NativeType::Samples(_)) => { + if self.output.samples().is_none() { + return Err(invalid(&format!( + "a binary operation over two vectors produces samples, not {}", + self.output.describe() + ))); + } + ensure_grid(&self.output, left_grid, "a binary operation")?; + } + // Both sides carry a grid, so this is state, which the checks above reject. + // Kept as an error rather than a panic so a future type cannot slip through. + _ => { + return Err(invalid( + "a binary operation consumes aggregate state, not a value", + )); + } + } } } Ok(()) } } +/// The grid of an evaluated vector, or `None` when `ty` is raw samples, a scalar or state. +/// +/// An operation over values needs both halves: that its input is samples at all, which rules out +/// a scalar, and that those samples are stamped onto a grid, which rules out raw samples. +fn evaluated_grid(ty: &NativeType) -> Option<&Arc> { + ty.samples().and_then(|schema| schema.eval_grid.as_ref()) +} + fn ensure_samples(ty: &NativeType, what: &str) -> Result<()> { if matches!(ty, NativeType::Samples(_)) { Ok(()) diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index 3eab716cf58..ff2c47f4421 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -48,31 +48,80 @@ fn raw() -> NativeType { } fn input() -> NativeNode { - let NativeType::Samples(schema) = raw() else { - unreachable!() - }; + let output = raw(); NativeNode { expr: NativeExpr::Input(BoundInput { - schema: Arc::clone(&schema), + output: output.clone(), ordering: SeriesOrdering::KeyThenTime, }), - output: NativeType::Samples(schema), + output, } } fn input_on(grid: Arc) -> NativeNode { // One allocation shared by the binding and the output: `validate` checks allocation identity, // because a compiler that meant one grid has no reason to allocate it twice. - let schema = Arc::new(SeriesSchema { - fields: Arc::new([]), - eval_grid: Some(grid), - }); + let output = evaluated(Arc::new([]), grid); NativeNode { expr: NativeExpr::Input(BoundInput { - schema: Arc::clone(&schema), + output: output.clone(), ordering: SeriesOrdering::Contiguous, }), - output: NativeType::Samples(schema), + output, + } +} + +/// A constant scalar, which is a scalar type evaluated on the statement's grid. +fn scalar_on(value: f64, grid: Arc) -> NativeNode { + NativeNode { + expr: NativeExpr::Scalar(BoundScalar { value }), + output: NativeType::Scalar(grid), + } +} + +/// The grid a state node is indexed on. +fn state_grid(node: &NativeNode) -> Arc { + let NativeType::AggregateState(schema) = &node.output else { + unreachable!("expected aggregate state") + }; + Arc::clone(&schema.grid) +} + +fn partial_aggregate(inner: NativeNode) -> NativeNode { + let grid = inner + .output + .grid() + .expect("a partial aggregate consumes an evaluated vector") + .clone(); + NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(inner), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Partial, + }, + }, + output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema { + group: Arc::new(["job".into()]), + accumulators: Arc::new([]), + grid, + })), + } +} + +fn final_aggregate(state: NativeNode) -> NativeNode { + let grid = state_grid(&state); + NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(state), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Final, + }, + }, + output: evaluated(Arc::new([]), grid), } } @@ -158,7 +207,24 @@ fn a_map_cannot_consume_raw_samples() { output: evaluated(Arc::new([]), grid(0, 60_000, 4)), }; let error = node.validate().unwrap_err(); - assert!(error.to_string().contains("not evaluated"), "{error}"); + assert!(error.to_string().contains("an evaluated vector"), "{error}"); +} + +/// A scalar is one value per grid point, not a vector, so there are no fields to map. +#[test] +fn a_map_cannot_consume_a_scalar() { + let out = grid(0, 60_000, 4); + let node = NativeNode { + expr: NativeExpr::Map { + input: Box::new(scalar_on(1.0, Arc::clone(&out))), + op: BoundMap { + ops: Arc::new([MathOp::Abs]), + }, + }, + output: evaluated(Arc::new([]), out), + }; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("not a scalar"), "{error}"); } /// A map with no operation would be a node that does nothing, which is a compiler mistake. @@ -197,6 +263,29 @@ fn an_instant_selection_reads_raw_samples() { assert!(error.to_string().contains("reads evaluated"), "{error}"); } +/// Aggregate state is not a sample stream, so an instant selection cannot read it. +#[test] +fn an_instant_selection_cannot_consume_state() { + let out = grid(0, 60_000, 4); + let node = NativeNode { + expr: NativeExpr::Instant { + input: Box::new(partial_aggregate(window_on( + input(), + None, + Arc::clone(&out), + ))), + op: BoundInstant { + lookback_ms: 300_000, + offset_ms: 0, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(Arc::new([]), out), + }; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("aggregate state"), "{error}"); +} + /// A window's declared input grid has to be the grid its input actually produces. #[test] fn a_window_checks_its_declared_input_grid() { @@ -213,6 +302,32 @@ fn a_window_checks_its_declared_input_grid() { ); } +/// A window consumes samples: state holds accumulators, not a sample stream to range over. +#[test] +fn a_window_cannot_consume_state() { + let out = grid(0, 60_000, 4); + let node = window_on( + partial_aggregate(window_on(input(), None, Arc::clone(&out))), + None, + grid(0, 60_000, 4), + ); + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("aggregate state"), "{error}"); +} + +/// A window ranges over timestamps, and a scalar has none of its own. +#[test] +fn a_window_cannot_consume_a_scalar() { + let out = grid(0, 60_000, 4); + let node = window_on( + scalar_on(1.0, Arc::clone(&out)), + Some(out), + grid(0, 60_000, 4), + ); + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("not a scalar"), "{error}"); +} + /// A binary node aligns two inputs, so two different grids cannot be aligned implicitly. #[test] fn a_binary_operation_rejects_two_grids() { @@ -248,6 +363,69 @@ fn a_binary_operation_over_one_grid_is_valid() { assert!(node.validate().is_ok()); } +/// A scalar side is broadcast, not matched: `sum by(job)(rate(x[5m])) + time()` has no labels to +/// line up, so `matching` is not consulted and the output keeps the vector side's fields. +#[test] +fn a_binary_operation_broadcasts_a_scalar() { + let shared = grid(0, 60_000, 4); + let vector = window_on(input(), None, Arc::clone(&shared)); + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(vector), + right: Box::new(scalar_on(1.0, Arc::clone(&shared))), + matching: add(), + }, + output: evaluated(Arc::new([]), Arc::clone(&shared)), + }; + assert!(node.validate().is_ok()); + + // The mirror case: the scalar on the left keeps the right side's fields. + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(scalar_on(1.0, Arc::clone(&shared))), + right: Box::new(window_on(input(), None, Arc::clone(&shared))), + matching: add(), + }, + output: evaluated(Arc::new([]), Arc::clone(&shared)), + }; + assert!(node.validate().is_ok()); +} + +/// Two scalars make a scalar, because there is nothing to attach labels or fields to. +#[test] +fn two_scalars_make_a_scalar() { + let shared = grid(0, 60_000, 4); + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(scalar_on(1.0, Arc::clone(&shared))), + right: Box::new(scalar_on(2.0, Arc::clone(&shared))), + matching: add(), + }, + output: NativeType::Scalar(Arc::clone(&shared)), + }; + assert!(node.validate().is_ok()); +} + +/// State is not a value, so neither side of a binary operation may be state. +#[test] +fn a_binary_operation_cannot_consume_state() { + let shared = grid(0, 60_000, 4); + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(window_on(input(), None, Arc::clone(&shared))), + right: Box::new(partial_aggregate(window_on( + input(), + None, + Arc::clone(&shared), + ))), + matching: add(), + }, + output: evaluated(Arc::new([]), Arc::clone(&shared)), + }; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("aggregate state"), "{error}"); +} + /// A partial aggregate produces state, not a value; a complete one produces a value on the same /// grid as its input. #[test] @@ -304,7 +482,75 @@ fn an_aggregate_stage_must_agree_with_its_type() { }; let error = node.validate().unwrap_err(); assert!( - error.to_string().contains("does not match its stage"), + error.to_string().contains("produces aggregate state"), + "{error}" + ); +} + +/// A `Partial` aggregate turns a vector into state: the output is the state type, indexed on the +/// vector's grid. +#[test] +fn a_partial_aggregate_produces_state() { + let state = partial_aggregate(window_over(input(), None)); + assert!(state.validate().is_ok()); + assert!(matches!(state.output, NativeType::AggregateState(_))); +} + +/// A `Final` aggregate consumes the state a `Partial` produced, which is what an exchange +/// boundary hands over between the two stages. +#[test] +fn a_final_aggregate_merges_partial_state() { + let shared = grid(0, 60_000, 4); + let state = partial_aggregate(window_on(input(), None, Arc::clone(&shared))); + let merged = final_aggregate(state); + assert!(merged.validate().is_ok()); + assert!( + matches!(&merged.output, NativeType::Samples(schema) if schema.eval_grid.as_ref().is_some_and(|grid| Arc::ptr_eq(grid, &shared))) + ); +} + +/// A `Final` aggregate consumes state, so a vector is not something it can merge. +#[test] +fn a_final_aggregate_cannot_consume_a_window() { + let inner = window_over(input(), None); + let value_grid = inner.output.grid().unwrap().clone(); + let node = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(inner), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Final, + }, + }, + output: evaluated(Arc::new([]), value_grid), + }; + let error = node.validate().unwrap_err(); + assert!( + error.to_string().contains("consumes aggregate state"), + "{error}" + ); +} + +/// A `Complete` aggregate aggregates vectors, so state is not something it can consume. +#[test] +fn a_complete_aggregate_cannot_consume_state() { + let state = partial_aggregate(window_over(input(), None)); + let state_grid = state_grid(&state); + let node = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(state), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Complete, + }, + }, + output: evaluated(Arc::new([]), state_grid), + }; + let error = node.validate().unwrap_err(); + assert!( + error.to_string().contains("consumes an evaluated vector"), "{error}" ); } @@ -335,53 +581,79 @@ fn the_walkthrough_shapes_are_trees() { }; assert!(sum.validate().is_ok()); - // `sum by(job)(rate(x[5m])) + 1`: the scalar applies to the completed value, not to state. + // `sum by(job)(rate(x[5m])) + 1`: the aggregate is complete, and the scalar side is + // broadcast, so `matching` is not consulted for it. let plus_one = NativeNode { - expr: NativeExpr::Map { - input: Box::new(NativeNode { - expr: NativeExpr::Aggregate { - input: Box::new(window_on(input(), None, Arc::clone(&statement_grid))), - op: BoundAggregate { - kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), - stage: AggregateStage::Final, - }, - }, - output: evaluated(Arc::new([]), Arc::clone(&statement_grid)), - }), - op: BoundMap { - ops: Arc::new([MathOp::Abs]), - }, + expr: NativeExpr::Binary { + left: Box::new(sum.clone()), + right: Box::new(scalar_on(1.0, Arc::clone(&statement_grid))), + matching: add(), }, output: evaluated(Arc::new([]), statement_grid), }; assert!(plus_one.validate().is_ok()); } -/// A scalar node is legal on its own; a raw input is not evaluated, so nothing consuming values -/// may sit above it. +/// A scalar node's output is the scalar type, which is what keeps a broadcast from turning into +/// label matching. #[test] fn a_scalar_node_is_valid() { + let node = scalar_on(1.0, grid(0, 60_000, 4)); + assert!(node.validate().is_ok()); +} + +/// A scalar node declared as a vector would let a broadcast be planned as a match. +#[test] +fn a_scalar_node_must_produce_a_scalar() { let node = NativeNode { expr: NativeExpr::Scalar(BoundScalar { value: 1.0 }), output: evaluated(Arc::new([]), grid(0, 60_000, 4)), }; - assert!(node.validate().is_ok()); + let error = node.validate().unwrap_err(); + assert!( + error.to_string().contains("does not produce a scalar"), + "{error}" + ); } -/// An input whose declared schema is not the schema it was bound to cannot be trusted. +/// An input whose declared output is not the binding it was bound to cannot be trusted. #[test] -fn an_input_must_report_the_schema_it_was_bound_to() { +fn an_input_must_report_the_binding_it_was_bound_to() { let node = NativeNode { expr: NativeExpr::Input(BoundInput { - schema: Arc::new(SeriesSchema { - fields: Arc::new([]), - eval_grid: None, - }), + output: raw(), ordering: SeriesOrdering::KeyThenTime, }), output: raw(), }; let error = node.validate().unwrap_err(); - assert!(error.to_string().contains("not the schema"), "{error}"); + assert!(error.to_string().contains("not the binding"), "{error}"); +} + +/// An exchange boundary binds state, and the node has to report that same state. +#[test] +fn an_input_can_bind_aggregate_state() { + let state = partial_aggregate(window_over(input(), None)); + let bound = NativeNode { + expr: NativeExpr::Input(BoundInput { + output: state.output.clone(), + ordering: SeriesOrdering::Contiguous, + }), + output: state.output.clone(), + }; + assert!(bound.validate().is_ok()); + + // A `Final` aggregate can then consume it, which is the shape of a distributed aggregate. + assert!(final_aggregate(bound).validate().is_ok()); + + // A fresh state allocation is a different binding, so it cannot be reported as the bound one. + let other = NativeNode { + expr: NativeExpr::Input(BoundInput { + output: state.output.clone(), + ordering: SeriesOrdering::Contiguous, + }), + output: partial_aggregate(window_over(input(), None)).output, + }; + let error = other.validate().unwrap_err(); + assert!(error.to_string().contains("not the binding"), "{error}"); } From 8e9c8b0e54019ff4543efa420ac15c76c44ae509 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:45:59 +0800 Subject: [PATCH 03/17] refactor(promql): use the evaluator's chunk type for native batches `native/batch.rs` defined its own `EvaluatedChunk` with the same two fields as `promql::evaluated::EvaluatedChunk`. Two definitions of one protocol drift: the evaluator's chunk could not be handed to a native node without translation, and a change to either would have to be mirrored. Use `crate::evaluated::EvaluatedChunk` instead. The type moves here with the evaluator's documentation, which states the same two rules this module did: a grid position is absolute, and `is_last` is the only thing that closes a series. The module keeps its own doc explaining the rules native nodes rely on and re-exports the type, so `native::batch::EvaluatedChunk` still names it. Signed-off-by: discord9 Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/batch.rs | 46 +++++----------------------------- 1 file changed, 6 insertions(+), 40 deletions(-) diff --git a/src/promql/src/native/batch.rs b/src/promql/src/native/batch.rs index eec665130f7..f8f6f0c2b93 100644 --- a/src/promql/src/native/batch.rs +++ b/src/promql/src/native/batch.rs @@ -25,47 +25,13 @@ //! prefix still has to be followed by a final chunk even when that chunk holds no values, so a //! consumer can tell "nothing more here" from "no more input". -use datafusion::error::{DataFusionError, Result}; -use datatypes::series::samples::Series; -use datatypes::series::time::TimeAxis; +//! +//! The chunk type itself is [`crate::evaluated::EvaluatedChunk`]: one chunk protocol serves both the +//! evaluator that produces chunks and the native nodes that consume them. Defining a second one +//! here would let the two drift apart, and a chunk produced by the evaluator could not be handed to +//! a node without translation. -/// One slice of one evaluated series. -/// -/// The series' [`TimeAxis::Grid`] covers the positions this chunk has finished evaluating. Those -/// positions are absolute on the grid, and they are contiguous with the previous chunk of the same -/// series. -#[derive(Clone, Debug)] -pub struct EvaluatedChunk { - /// The evaluated values, addressed on their absolute grid positions. - pub series: Series, - /// Whether this is the final chunk of this series. - pub is_last: bool, -} - -impl EvaluatedChunk { - /// Wraps `series`, checking that it is addressed on a grid. - pub fn try_new(series: Series, is_last: bool) -> Result { - if !matches!(series.time, TimeAxis::Grid(_)) { - return Err(DataFusionError::Execution( - "an evaluated chunk must be addressed on a grid".to_string(), - )); - } - Ok(Self { series, is_last }) - } - - /// The absolute grid range this chunk covers. - /// - /// An empty range is meaningful: it reports that the chunk closed a prefix of the grid without - /// producing new values, which a consumer needs in order to advance. - pub fn range(&self) -> &datatypes::series::time::GridRange { - match &self.series.time { - TimeAxis::Grid(range) => range, - // `try_new` rejects anything else, and `series` is public, so a chunk built by struct - // literal is checked here rather than trusted. - _ => unreachable!("an evaluated chunk is always addressed on a grid"), - } - } -} +pub use crate::evaluated::EvaluatedChunk; #[cfg(test)] mod tests { From e0ac0f8067f73ebfd8bf716960c347454f76c989 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:27:11 +0800 Subject: [PATCH 04/17] fix(promql): reject a node that declares a different field count than it consumes A window and a map both report one value per input field, so they keep the layout of their input. Validation checked that both sides were samples and that the grids matched, but not that the field counts did, so a tree could declare two output fields over a one-field input and still pass `NativeTree::try_new`. The mismatch then surfaced at run time, against a schema the tree was supposed to have validated. Signed-off-by: discord9 Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/plan.rs | 22 +++++++++++ src/promql/src/native/plan/tests.rs | 57 +++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 068ab68d5a8..0410a5a2395 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -330,6 +330,7 @@ impl NativeNode { } } ensure_samples(&self.output, "a window")?; + ensure_same_fields(&input.output, &self.output, "a window")?; ensure_grid(&self.output, &op.output_grid, "a window")?; } NativeExpr::Map { input, op } => { @@ -346,6 +347,7 @@ impl NativeNode { return Err(invalid("a map holds no operation")); } ensure_samples(&self.output, "a map")?; + ensure_same_fields(&input.output, &self.output, "a map")?; ensure_grid(&self.output, input_grid, "a map")?; } NativeExpr::Aggregate { input, op } => { @@ -488,6 +490,26 @@ fn evaluated_grid(ty: &NativeType) -> Option<&Arc> { ty.samples().and_then(|schema| schema.eval_grid.as_ref()) } +/// Checks that a node declares the field layout it consumes. +/// +/// A window and a map both report one value per input field, so they keep the layout of their +/// input. A node that declares a different number of fields than it consumes describes a +/// computation this model has no meaning for, and letting it through would only surface at run +/// time as a field count mismatch against a schema the tree was supposed to have validated. +fn ensure_same_fields(input: &NativeType, output: &NativeType, what: &str) -> Result<()> { + let (NativeType::Samples(input), NativeType::Samples(output)) = (input, output) else { + return Ok(()); + }; + if input.fields.len() != output.fields.len() { + return Err(invalid(&format!( + "{what} declares {} field(s) and consumes {}", + output.fields.len(), + input.fields.len() + ))); + } + Ok(()) +} + fn ensure_samples(ty: &NativeType, what: &str) -> Result<()> { if matches!(ty, NativeType::Samples(_)) { Ok(()) diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index ff2c47f4421..8ab47efff78 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -243,6 +243,63 @@ fn a_map_needs_an_operation() { assert!(error.to_string().contains("no operation"), "{error}"); } +/// A map reports one value per input field, so it cannot declare a layout its input does not +/// have. Without this check the tree would validate and only fail when the runtime compared the +/// node's schema against the one its input actually produces. +#[test] +fn a_map_cannot_change_the_field_count() { + let inner = window_over(input(), None); + let out = inner.output.grid().unwrap().clone(); + let node = NativeNode { + expr: NativeExpr::Map { + input: Box::new(inner), + op: BoundMap { + ops: Arc::new([MathOp::Abs]), + }, + }, + output: evaluated( + Arc::new([datatypes::series::samples::FieldSpec { + name: Arc::from("value"), + }]), + out, + ), + }; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("field(s)"), "{error}"); +} + +/// A window reports one value per input field, so it carries the same rule as a map. +#[test] +fn a_window_cannot_change_the_field_count() { + let inner = window_over(input(), None); + // The output grid is the input's, so the grid check passes and the field check is what the + // test actually exercises. + let out = inner.output.grid().unwrap().clone(); + let node = NativeNode { + expr: NativeExpr::Window { + input: Box::new(inner), + op: BoundWindow { + function: RangeFunction::Rate, + window: RangeWindow { + range_ms: 30_000, + offset_ms: 0, + anchor_ms: None, + }, + input_grid: Some(Arc::clone(&out)), + output_grid: Arc::clone(&out), + }, + }, + output: evaluated( + Arc::new([datatypes::series::samples::FieldSpec { + name: Arc::from("value"), + }]), + out, + ), + }; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("field(s)"), "{error}"); +} + /// An instant selection reads raw samples; feeding it evaluated values would re-anchor a grid /// that is already fixed. #[test] From 8cb6e48fa5db12bd893099c298dd47d851a70b89 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:51:57 +0800 Subject: [PATCH 05/17] fix(promql): validate the field layout of every node that declares one Field counts were checked for a window and a map and nothing else, so an instant selection, either aggregate stage and a binary operation could each declare a layout their kernel does not produce and still pass validation, surfacing at run time against a schema the tree was supposed to have validated. Each node is now checked against the count its own kernel produces, which for a binary over two vectors is the shorter side. Grids are compared by their specification, as the kernels compare them, instead of by allocation. A compiler that allocates one grid per window -- `rate(a[5m]) + rate(b[5m])` -- built a tree the runtime would run and validation rejected. Binding identity is still compared by allocation: an input has to report the one binding it was given, which is a different question from what two equal grids mean. A rejected tree is a compiler defect, so it is reported as an internal error rather than as a mistake in the client's statement, which `Plan` would have implied. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/metrics.rs | 52 +++++- src/promql/src/native/mod.rs | 5 +- src/promql/src/native/plan.rs | 124 ++++++++----- src/promql/src/native/plan/tests.rs | 266 +++++++++++++++++++++++++++- 4 files changed, 391 insertions(+), 56 deletions(-) diff --git a/src/promql/src/native/metrics.rs b/src/promql/src/native/metrics.rs index 03739bda53c..f0ebe48c08d 100644 --- a/src/promql/src/native/metrics.rs +++ b/src/promql/src/native/metrics.rs @@ -16,8 +16,9 @@ //! //! A node is identified by its structural position — `root`, `.input`, `.left`, `.right` — rather //! than by an id it carries. The position is not stored on the node: it is derived while walking -//! the tree, which is the same walk that both `DisplayAs` and run-time construction use, so the -//! name shown and the name registered cannot disagree. +//! the tree, which is the one traversal rule run-time construction uses. A tree description +//! rendered from the same walk — intended for `EXPLAIN` and `ANALYZE`, neither of which renders a +//! native tree today — would show the positions that were registered. //! //! The position stays in the metric name because the collector aggregates by name first: two //! `rate` nodes sharing a bare name would be merged into one number. Positions are only an @@ -31,7 +32,7 @@ use datafusion::physical_plan::metrics::{ Count, ExecutionPlanMetricsSet, Gauge, MetricBuilder, Time, }; -use super::plan::{NativeExpr, NativeNode}; +use crate::native::plan::{NativeExpr, NativeNode}; /// The reserved first segment of every native metric name. const NATIVE_PREFIX: &str = "native"; @@ -91,8 +92,9 @@ impl std::fmt::Display for NodePath { /// Visits every node of `root` with its position, outermost first. /// -/// This is the one traversal rule: `DisplayAs` and run-time construction both call it, so a node -/// cannot be shown at one position and registered at another. +/// This is the one traversal rule: [`register_tree`] calls it when the run-time state is created, +/// and a tree description is intended to render from it, so a node cannot be shown at one position +/// and registered at another. pub fn walk(root: &NativeNode, visit: &mut dyn FnMut(&NativeNode, &NodePath)) { fn go(node: &NativeNode, path: &NodePath, visit: &mut dyn FnMut(&NativeNode, &NodePath)) { visit(node, path); @@ -113,8 +115,9 @@ pub fn walk(root: &NativeNode, visit: &mut dyn FnMut(&NativeNode, &NodePath)) { /// The metric names one node reports. /// -/// [`Self::ALL`] is the single list both registration and documentation read, so a metric cannot be -/// registered without being named here. +/// [`Self::ALL`] is the list a reader should treat as complete: [`NodeMetrics::register`] names each +/// handle itself, and `registered_metrics_are_exactly_the_declared_set` fails when the two sides +/// drift apart. pub struct NodeMetric; impl NodeMetric { @@ -552,6 +555,41 @@ mod tests { assert!(NodeMetric::ALL.contains(&NodeMetric::PEAK_RESERVED_BYTES)); } + /// Registration reports exactly the metrics `ALL` declares, in both directions. + /// + /// The names are read back from the set a node registered in, so the check is against what + /// registration actually did, not against `ALL` itself. Adding a metric to `ALL` without + /// registering it in `register`, or registering a metric that `ALL` does not list, fails this + /// test: it compares the two sides instead of trusting either. + #[test] + fn registered_metrics_are_exactly_the_declared_set() { + let root = map(window(input())); + let set = ExecutionPlanMetricsSet::new(); + register_tree(&root, &set, 0); + + // One node reports each metric once; the node paths and the partition prefix separate + // nodes, so the bare name is the last dot-separated segment. + let set = set.clone_inner(); + let mut registered: Vec<&str> = set + .iter() + .map(|metric| { + metric + .value() + .name() + .rsplit('.') + .next() + .expect("a metric name has a last segment") + }) + .collect(); + registered.sort_unstable(); + registered.dedup(); + + let mut declared: Vec<&str> = NodeMetric::ALL.to_vec(); + declared.sort_unstable(); + + assert_eq!(registered, declared); + } + /// A peak is a high-water mark of one node, so it survives a later drop in reservations. #[test] fn a_peak_is_a_high_water_mark() { diff --git a/src/promql/src/native/mod.rs b/src/promql/src/native/mod.rs index cef95d339bb..9cdb7f6c54a 100644 --- a/src/promql/src/native/mod.rs +++ b/src/promql/src/native/mod.rs @@ -16,8 +16,9 @@ //! //! A query compiles to a [`plan::NativeTree`]: nodes whose operations, fields and grids are already //! bound. Nodes hand each other [`batch::EvaluatedChunk`]s as ordinary Rust values, so no row batch -//! is materialised between them. [`metrics`] names each node after its position in that tree, so -//! `EXPLAIN` and `ANALYZE` describe the same structure. +//! is materialised between them. [`metrics`] names each node after its position in that tree, +//! which is what an `EXPLAIN` or `ANALYZE` of a native plan is intended to render; no native plan +//! renders one today. //! //! Three properties keep this apart from recognising a query shape in a finished physical plan: //! diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 0410a5a2395..38a085093e6 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -89,7 +89,8 @@ impl NativeType { /// /// Bindings are compared by allocation identity, because a compiler that meant one schema or /// one state has no reason to allocate it twice. A scalar is produced by a node and never - /// handed to one by a source, so it never matches. + /// handed to one by a source, so it never matches. This is about the binding itself: grids are + /// aligned by [`EvalGrid::spec`] everywhere else, here and in the kernels. fn same_binding(&self, other: &NativeType) -> bool { match (self, other) { (Self::Samples(mine), Self::Samples(theirs)) => Arc::ptr_eq(mine, theirs), @@ -115,8 +116,9 @@ pub struct AggregateStateSchema { /// A scan or exchange boundary bound as a node input. /// -/// The binding records what the input already guarantees, so the compiler can check a consumer's -/// requirement instead of assuming it. +/// The binding records what the input was created for: the output a consumer type-checks against, +/// and the ordering it guarantees. No consumer reads the ordering today; it is recorded so a +/// consumer that needs one can check it instead of assuming it. #[derive(Clone, Debug)] pub struct BoundInput { /// What the input produces: raw samples from a scan, or state from an exchange boundary. @@ -258,7 +260,8 @@ impl NativeTree { /// Creates a tree over `root`, checking that every node's contract holds. /// /// A rejected tree is a compiler defect rather than a query error: the compiler only builds a - /// node after deciding that this combination is supported. + /// node after deciding that this combination is supported, so the error is + /// [`DataFusionError::Internal`] and not a statement the client wrote wrong. pub fn try_new(root: NativeNode) -> Result { root.validate()?; Ok(Self { root }) @@ -306,6 +309,10 @@ impl NativeNode { } } ensure_samples(&self.output, "an instant selection")?; + // A selection is one source row per grid point: `select_instants` picks row + // indices and every field is taken at them, so it carries one value per input + // field. + ensure_same_fields(&input.output, &self.output, "an instant selection")?; ensure_grid(&self.output, &op.output_grid, "an instant selection")?; } NativeExpr::Window { input, op } => { @@ -322,7 +329,7 @@ impl NativeNode { // window would read positions the input never wrote. match (op.input_grid.as_ref(), schema.eval_grid.as_ref()) { (None, None) => {} - (Some(bound), Some(actual)) if Arc::ptr_eq(bound, actual) => {} + (Some(bound), Some(actual)) if bound.spec() == actual.spec() => {} _ => { return Err(invalid( "a window's declared input grid is not the input's grid", @@ -337,7 +344,7 @@ impl NativeNode { input.validate()?; // A map is point-wise over an evaluated vector: raw samples have no shared // positions to be point-wise over, and a scalar is not a vector. - let Some(input_grid) = evaluated_grid(&input.output) else { + let Some((_, input_grid)) = evaluated_vector(&input.output) else { return Err(invalid(&format!( "a map consumes an evaluated vector, not {}", input.output.describe() @@ -358,20 +365,23 @@ impl NativeNode { match op.stage { AggregateStage::Complete => { // Every contribution lies within this execution: vector in, vector out, - // both on the input's grid. - let Some(input_grid) = evaluated_grid(&input.output) else { + // both on the input's grid, one value per input field. + let Some((_, input_grid)) = evaluated_vector(&input.output) else { return Err(invalid(&format!( "a complete aggregate consumes an evaluated vector, not {}", input.output.describe() ))); }; ensure_samples(&self.output, "a complete aggregate")?; + ensure_same_fields(&input.output, &self.output, "a complete aggregate")?; ensure_grid(&self.output, input_grid, "a complete aggregate")?; } AggregateStage::Partial => { // Only this execution's contributions were seen, so the output is state - // for a later merge: on the input's grid, grouped the same way. - let Some(input_grid) = evaluated_grid(&input.output) else { + // for a later merge: on the input's grid, grouped the same way, one + // accumulator per input field. + let Some((input_schema, input_grid)) = evaluated_vector(&input.output) + else { return Err(invalid(&format!( "a partial aggregate consumes an evaluated vector, not {}", input.output.describe() @@ -383,7 +393,12 @@ impl NativeNode { self.output.describe() ))); }; - if !Arc::ptr_eq(&state.grid, input_grid) { + ensure_field_count( + state.accumulators.len(), + input_schema.fields.len(), + "a partial aggregate", + )?; + if state.grid.spec() != input_grid.spec() { return Err(invalid( "aggregate state is indexed on a grid the input does not produce", )); @@ -404,7 +419,13 @@ impl NativeNode { if state.group != op.group { return Err(invalid("aggregate state groups differ from the binding")); } - ensure_samples(&self.output, "a final aggregate")?; + let output = ensure_samples(&self.output, "a final aggregate")?; + // The merged value carries one value per accumulator the state holds. + ensure_field_count( + output.fields.len(), + state.accumulators.len(), + "a final aggregate", + )?; ensure_grid(&self.output, &state.grid, "a final aggregate")?; } } @@ -427,13 +448,13 @@ impl NativeNode { right.output.describe() ))); }; - if !Arc::ptr_eq(left_grid, right_grid) { + if left_grid.spec() != right_grid.spec() { return Err(invalid("a binary operation aligns two different grids")); } match (&left.output, &right.output) { // Two scalars make a scalar: there is nothing to match and nothing to keep. (NativeType::Scalar(_), NativeType::Scalar(_)) => { - if !matches!(&self.output, NativeType::Scalar(grid) if Arc::ptr_eq(grid, left_grid)) + if !matches!(&self.output, NativeType::Scalar(grid) if grid.spec() == left_grid.spec()) { return Err(invalid( "two scalars do not produce a scalar on the statement's grid", @@ -458,14 +479,20 @@ impl NativeNode { )); } } - // Two vectors are matched by `matching` on the grid they share. - (NativeType::Samples(_), NativeType::Samples(_)) => { - if self.output.samples().is_none() { + // Two vectors are matched by `matching` on the grid they share, and the match + // pairs fields by position, so it keeps the shorter side's fields. + (NativeType::Samples(left_vector), NativeType::Samples(right_vector)) => { + let Some(output) = self.output.samples() else { return Err(invalid(&format!( "a binary operation over two vectors produces samples, not {}", self.output.describe() ))); - } + }; + ensure_field_count( + output.fields.len(), + left_vector.fields.len().min(right_vector.fields.len()), + "a binary operation over two vectors", + )?; ensure_grid(&self.output, left_grid, "a binary operation")?; } // Both sides carry a grid, so this is state, which the checks above reject. @@ -482,45 +509,61 @@ impl NativeNode { } } -/// The grid of an evaluated vector, or `None` when `ty` is raw samples, a scalar or state. +/// The schema and grid of an evaluated vector, or `None` when `ty` is raw samples, a scalar or +/// state. /// /// An operation over values needs both halves: that its input is samples at all, which rules out -/// a scalar, and that those samples are stamped onto a grid, which rules out raw samples. -fn evaluated_grid(ty: &NativeType) -> Option<&Arc> { - ty.samples().and_then(|schema| schema.eval_grid.as_ref()) +/// a scalar, and that those samples are stamped onto a grid, which rules out raw samples. The +/// schema comes back with the grid because a consumer that needs the grid also declares a field +/// layout for the fields the schema carries. +fn evaluated_vector(ty: &NativeType) -> Option<(&Arc, &Arc)> { + let schema = ty.samples().filter(|schema| schema.eval_grid.is_some())?; + Some((schema, schema.eval_grid.as_ref()?)) } -/// Checks that a node declares the field layout it consumes. +/// Checks that a node declares the field layout its input produces. /// -/// A window and a map both report one value per input field, so they keep the layout of their -/// input. A node that declares a different number of fields than it consumes describes a -/// computation this model has no meaning for, and letting it through would only surface at run -/// time as a field count mismatch against a schema the tree was supposed to have validated. +/// A window, a map, an instant selection and a complete aggregate all report one value per input +/// field, so they keep the layout of their input. A node that declares a different number of +/// fields than it consumes describes a computation this model has no meaning for, and letting it +/// through would only surface at run time as a field count mismatch against a schema the tree was +/// supposed to have validated. fn ensure_same_fields(input: &NativeType, output: &NativeType, what: &str) -> Result<()> { let (NativeType::Samples(input), NativeType::Samples(output)) = (input, output) else { return Ok(()); }; - if input.fields.len() != output.fields.len() { + ensure_field_count(output.fields.len(), input.fields.len(), what) +} + +/// Checks that a node declares `declared` fields where its input provides `expected`. +/// +/// Some nodes compute their layout instead of keeping their input's: a final aggregate produces one +/// value per accumulator the state holds, and a vector-vector binary operation produces one field +/// per matched pair, which is the shorter side's count. Both are checked against the count the +/// kernel produces, so the message names the node and both numbers. +fn ensure_field_count(declared: usize, expected: usize, what: &str) -> Result<()> { + if declared != expected { return Err(invalid(&format!( - "{what} declares {} field(s) and consumes {}", - output.fields.len(), - input.fields.len() + "{what} declares {declared} field(s) but its input provides {expected}" ))); } Ok(()) } -fn ensure_samples(ty: &NativeType, what: &str) -> Result<()> { - if matches!(ty, NativeType::Samples(_)) { - Ok(()) - } else { - Err(invalid(&format!("{what} does not produce samples"))) - } +/// Checks that `ty` produces samples and returns them. +fn ensure_samples<'a>(ty: &'a NativeType, what: &str) -> Result<&'a Arc> { + ty.samples() + .ok_or_else(|| invalid(&format!("{what} does not produce samples"))) } +/// Checks that `ty` is evaluated on the grid `expected` describes. +/// +/// The comparison is by [`EvalGrid::spec`], not by allocation: that is the rule the kernels apply +/// (`vector_match::same_grid`), so a compiler that allocates one grid per window but binds equal +/// specs produces a tree the kernel runs correctly. fn ensure_grid(ty: &NativeType, expected: &Arc, what: &str) -> Result<()> { match ty.grid() { - Some(actual) if Arc::ptr_eq(actual, expected) => Ok(()), + Some(actual) if actual.spec() == expected.spec() => Ok(()), Some(_) => Err(invalid(&format!( "{what} declares a grid its output does not carry" ))), @@ -530,8 +573,9 @@ fn ensure_grid(ty: &NativeType, expected: &Arc, what: &str) -> Result< fn invalid(reason: &str) -> DataFusionError { // A rejected tree is a compiler defect, not a query error: the compiler only builds a node - // after deciding that this combination is supported. - DataFusionError::Plan(reason.to_string()) + // after deciding that this combination is supported. `Internal` keeps that meaning on the wire + // instead of reporting a mistake in the client's statement, which `Plan` would. + DataFusionError::Internal(reason.to_string()) } #[cfg(test)] diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index 8ab47efff78..f0ca5301af4 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -15,7 +15,7 @@ use std::sync::Arc; use datatypes::series::SeriesOrdering; -use datatypes::series::samples::SeriesSchema; +use datatypes::series::samples::{FieldSpec, SeriesSchema}; use datatypes::series::time::{EvalGrid, GridSpec}; use super::{ @@ -40,6 +40,16 @@ fn evaluated( })) } +/// `count` fields named `f0`, `f1`, ..., which is the layout a multi-field source has. +fn fields(count: usize) -> Arc<[FieldSpec]> { + (0..count) + .map(|index| FieldSpec { + name: Arc::from(format!("f{index}")), + }) + .collect::>() + .into() +} + fn raw() -> NativeType { NativeType::Samples(Arc::new(SeriesSchema { fields: Arc::new([]), @@ -59,8 +69,8 @@ fn input() -> NativeNode { } fn input_on(grid: Arc) -> NativeNode { - // One allocation shared by the binding and the output: `validate` checks allocation identity, - // because a compiler that meant one grid has no reason to allocate it twice. + // One schema allocation shared by the binding and the output: `validate` checks that the output + // is the binding it was bound to, which is about the binding itself, not the grid's spec. let output = evaluated(Arc::new([]), grid); NativeNode { expr: NativeExpr::Input(BoundInput { @@ -71,6 +81,21 @@ fn input_on(grid: Arc) -> NativeNode { } } +/// A scan of `count` fields, so a consumer's field check has something to disagree with. +fn input_with_fields(count: usize) -> NativeNode { + let output = NativeType::Samples(Arc::new(SeriesSchema { + fields: fields(count), + eval_grid: None, + })); + NativeNode { + expr: NativeExpr::Input(BoundInput { + output: output.clone(), + ordering: SeriesOrdering::KeyThenTime, + }), + output, + } +} + /// A constant scalar, which is a scalar type evaluated on the statement's grid. fn scalar_on(value: f64, grid: Arc) -> NativeNode { NativeNode { @@ -129,6 +154,27 @@ fn window_over(inner: NativeNode, input_grid: Option>) -> NativeNo window_on(inner, input_grid, grid(0, 60_000, 4)) } +/// A window over `inner` that produces `count` fields on `out`, so a consumer of it can be given a +/// layout the window itself holds legally. +fn window_fields(inner: NativeNode, out: Arc, count: usize) -> NativeNode { + NativeNode { + expr: NativeExpr::Window { + input: Box::new(inner), + op: BoundWindow { + function: RangeFunction::Rate, + window: RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + input_grid: None, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(fields(count), out), + } +} + /// A window over `inner` that produces `out`, so two windows can be given the same grid. fn window_on( inner: NativeNode, @@ -265,7 +311,12 @@ fn a_map_cannot_change_the_field_count() { ), }; let error = node.validate().unwrap_err(); - assert!(error.to_string().contains("field(s)"), "{error}"); + assert!( + error + .to_string() + .contains("a map declares 1 field(s) but its input provides 0"), + "{error}" + ); } /// A window reports one value per input field, so it carries the same rule as a map. @@ -297,7 +348,39 @@ fn a_window_cannot_change_the_field_count() { ), }; let error = node.validate().unwrap_err(); - assert!(error.to_string().contains("field(s)"), "{error}"); + assert!( + error + .to_string() + .contains("a window declares 1 field(s) but its input provides 0"), + "{error}" + ); +} + +/// An instant selection picks one row of the source per grid point, so it carries one value per +/// input field. A tree that declares anything else would only fail at run time, against a schema +/// the tree was supposed to have validated. +#[test] +fn an_instant_selection_cannot_change_the_field_count() { + let out = grid(0, 60_000, 4); + // The source has two fields; the selection declares one value. + let node = NativeNode { + expr: NativeExpr::Instant { + input: Box::new(input_with_fields(2)), + op: BoundInstant { + lookback_ms: 300_000, + offset_ms: 0, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(fields(1), out), + }; + let error = node.validate().unwrap_err(); + assert!( + error + .to_string() + .contains("an instant selection declares 1 field(s) but its input provides 2"), + "{error}" + ); } /// An instant selection reads raw samples; feeding it evaluated values would re-anchor a grid @@ -420,6 +503,36 @@ fn a_binary_operation_over_one_grid_is_valid() { assert!(node.validate().is_ok()); } +/// A compiler that allocates one grid per window still produces one grid: the kernel aligns +/// operands by `EvalGrid::spec` (`vector_match::same_grid`), so `validate` compares specs too and +/// does not reject a tree the runtime would run correctly. +#[test] +fn a_binary_operation_aligns_separately_allocated_equal_specs() { + // Two windows, one fresh `EvalGrid` each, and the statement's grid a third: equal specs, no + // shared allocation anywhere in the tree. + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(window_on(input(), None, grid(0, 60_000, 4))), + right: Box::new(window_on(input(), None, grid(0, 60_000, 4))), + matching: add(), + }, + output: evaluated(Arc::new([]), grid(0, 60_000, 4)), + }; + assert!(node.validate().is_ok(), "{}", node.validate().unwrap_err()); + + // The same tree with a different spec is still rejected: the kernel rejects that pair too. + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(window_on(input(), None, grid(0, 60_000, 4))), + right: Box::new(window_on(input(), None, grid(30_000, 60_000, 4))), + matching: add(), + }, + output: evaluated(Arc::new([]), grid(0, 60_000, 4)), + }; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("different grids"), "{error}"); +} + /// A scalar side is broadcast, not matched: `sum by(job)(rate(x[5m])) + time()` has no labels to /// line up, so `matching` is not consulted and the output keeps the vector side's fields. #[test] @@ -448,6 +561,41 @@ fn a_binary_operation_broadcasts_a_scalar() { assert!(node.validate().is_ok()); } +/// Two vectors pair their fields by position, so the match reports the shorter side's count +/// (`vector_match::binary_output_schema` takes `min(lhs, rhs)`); a tree declaring anything else is +/// rejected instead of failing at run time. +#[test] +fn a_binary_operation_over_two_vectors_matches_the_shorter_side() { + let shared = grid(0, 60_000, 4); + // Two fields matched against one: the match produces one field, not two. + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(window_fields(input_with_fields(2), Arc::clone(&shared), 2)), + right: Box::new(window_fields(input_with_fields(1), Arc::clone(&shared), 1)), + matching: add(), + }, + output: evaluated(fields(2), Arc::clone(&shared)), + }; + let error = node.validate().unwrap_err(); + assert!( + error.to_string().contains( + "a binary operation over two vectors declares 2 field(s) but its input provides 1" + ), + "{error}" + ); + + // Declaring the shorter side's count is the legal tree, so the check is not vacuous. + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(window_fields(input_with_fields(2), Arc::clone(&shared), 2)), + right: Box::new(window_fields(input_with_fields(1), Arc::clone(&shared), 1)), + matching: add(), + }, + output: evaluated(fields(1), shared), + }; + assert!(node.validate().is_ok(), "{}", node.validate().unwrap_err()); +} + /// Two scalars make a scalar, because there is nothing to attach labels or fields to. #[test] fn two_scalars_make_a_scalar() { @@ -521,6 +669,32 @@ fn an_aggregate_output_matches_its_stage() { assert!(partial.validate().is_ok()); } +/// A complete aggregate folds each field on its own, so it reports one value per input field +/// (`aggregate::aggregate_float` builds its rows from the input schema's fields). +#[test] +fn a_complete_aggregate_cannot_change_the_field_count() { + let out = grid(0, 60_000, 4); + // The input is a legal two-field window; the aggregate declares one value. + let node = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(window_fields(input_with_fields(2), Arc::clone(&out), 2)), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Complete, + }, + }, + output: evaluated(fields(1), out), + }; + let error = node.validate().unwrap_err(); + assert!( + error + .to_string() + .contains("a complete aggregate declares 1 field(s) but its input provides 2"), + "{error}" + ); +} + /// Declaring a value where the stage produces state is a compiler mistake, and is rejected. #[test] fn an_aggregate_stage_must_agree_with_its_type() { @@ -553,6 +727,36 @@ fn a_partial_aggregate_produces_state() { assert!(matches!(state.output, NativeType::AggregateState(_))); } +/// A `Partial` aggregate keeps one accumulator per input field (`aggregate_float` lays its state +/// out in `schema.fields.len()`-sized points), so state declaring another count is rejected. +#[test] +fn a_partial_aggregate_cannot_change_the_accumulator_count() { + let out = grid(0, 60_000, 4); + // The input is a legal two-field window; the state declares one accumulator. + let node = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(window_fields(input_with_fields(2), Arc::clone(&out), 2)), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Partial, + }, + }, + output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema { + group: Arc::new(["job".into()]), + accumulators: fields(1), + grid: out, + })), + }; + let error = node.validate().unwrap_err(); + assert!( + error + .to_string() + .contains("a partial aggregate declares 1 field(s) but its input provides 2"), + "{error}" + ); +} + /// A `Final` aggregate consumes the state a `Partial` produced, which is what an exchange /// boundary hands over between the two stages. #[test] @@ -566,6 +770,54 @@ fn a_final_aggregate_merges_partial_state() { ); } +/// A `Final` aggregate merges the state into one value per accumulator, so it reports the state's +/// count and nothing else. +#[test] +fn a_final_aggregate_cannot_change_the_field_count() { + let out = grid(0, 60_000, 4); + // A legal partial aggregate: two input fields, two accumulators. + let state = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(window_fields(input_with_fields(2), Arc::clone(&out), 2)), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Partial, + }, + }, + output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema { + group: Arc::new(["job".into()]), + accumulators: fields(2), + grid: Arc::clone(&out), + })), + }; + assert!( + state.validate().is_ok(), + "{}", + state.validate().unwrap_err() + ); + + // The merge declares one value for the state's two accumulators. + let node = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(state), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Final, + }, + }, + output: evaluated(fields(1), out), + }; + let error = node.validate().unwrap_err(); + assert!( + error + .to_string() + .contains("a final aggregate declares 1 field(s) but its input provides 2"), + "{error}" + ); +} + /// A `Final` aggregate consumes state, so a vector is not something it can merge. #[test] fn a_final_aggregate_cannot_consume_a_window() { @@ -616,8 +868,8 @@ fn a_complete_aggregate_cannot_consume_state() { /// for composition. #[test] fn the_walkthrough_shapes_are_trees() { - // Every node in one query evaluates on the statement's grid, so the compiler binds one grid - // and shares it; `validate` checks that identity. + // Every node in one query evaluates on the statement's grid; `validate` compares the specs of + // the grids, not their allocations, which is the rule the kernels apply. let statement_grid = grid(0, 60_000, 4); // `abs(rate(x[5m]))` From 9e2ab2a0b4dd888e355bcc92aadbaeafb26f139f Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:06:50 +0800 Subject: [PATCH 06/17] fix(promql): check a window's input ordering and range, and drop the tests that only repeat another module `validate` accepted an interleaved input for a window, although the range evaluator reads one series to its last chunk before it starts the next, so the tree this layer builds was guaranteed to fail at run time. A window now rejects both an interleaved input and a range that is not positive. An instant selection reads one series at a time, so it keeps accepting an interleaved input and now says why. The grid comment claimed the input grid is checked to cover the window's read range. It is not: only a subquery feeds an evaluated input to a window, and this compiler does not accept subqueries yet. The binary operation's catch-all arm is unreachable at run time -- state has no grid and the grid checks return before the match -- but the match still has to cover the state pairs, so they are spelled out and say so instead of claiming a value arrived. Rejection branches had no tests, so deleting any of them kept the suite green. Each now has one. The four tests in `native/batch.rs` repeated the ones in `evaluated.rs` through the re-export, so they could not fail on their own; they are gone, and the coverage stays in `evaluated.rs`. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/batch.rs | 96 ------------- src/promql/src/native/metrics.rs | 40 +++--- src/promql/src/native/mod.rs | 4 +- src/promql/src/native/plan.rs | 47 ++++-- src/promql/src/native/plan/tests.rs | 212 ++++++++++++++++++++++++++-- 5 files changed, 264 insertions(+), 135 deletions(-) diff --git a/src/promql/src/native/batch.rs b/src/promql/src/native/batch.rs index f8f6f0c2b93..f3982a0115e 100644 --- a/src/promql/src/native/batch.rs +++ b/src/promql/src/native/batch.rs @@ -32,99 +32,3 @@ //! a node without translation. pub use crate::evaluated::EvaluatedChunk; - -#[cfg(test)] -mod tests { - use std::sync::Arc; - - use datatypes::arrow::array::Float64Array; - use datatypes::series::MetricName; - use datatypes::series::samples::{Samples, Series, SeriesFields, SeriesSchema}; - use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; - - use super::EvaluatedChunk; - - fn grid() -> Arc { - Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 60_000, 4).unwrap()).unwrap()) - } - - fn schema() -> SeriesSchema { - SeriesSchema { - fields: Arc::from([datatypes::series::samples::FieldSpec { name: "v0".into() }]), - eval_grid: Some(grid()), - } - } - - /// `values` are the floats this chunk finished evaluating; `start` is their absolute offset. - fn chunk( - schema: &SeriesSchema, - start: usize, - values: Vec, - is_last: bool, - ) -> EvaluatedChunk { - let samples = Samples::from_float(Float64Array::from(values)); - let range = - GridRange::try_new(schema.eval_grid.clone().unwrap(), start, samples.len()).unwrap(); - let series = Series { - metric: MetricName::try_new(Some("requests".into()), Vec::new()).unwrap(), - time: TimeAxis::Grid(range), - fields: SeriesFields::try_from_vec(vec![samples]).unwrap(), - }; - EvaluatedChunk::try_new(series, is_last).unwrap() - } - - /// A chunk without values is still a chunk: it is how a closed prefix is reported, and a - /// consumer needs it to tell "nothing more here" from "no more input". - #[test] - fn a_chunk_can_cover_no_positions() { - let schema = schema(); - let empty = Samples::from_float(Float64Array::from(Vec::::new())); - let range = GridRange::try_new(schema.eval_grid.clone().unwrap(), 4, 0).unwrap(); - assert!(range.is_empty()); - let series = Series { - metric: MetricName::try_new(Some("requests".into()), Vec::new()).unwrap(), - time: TimeAxis::Grid(range), - fields: SeriesFields::try_from_vec(vec![empty]).unwrap(), - }; - let chunk = EvaluatedChunk::try_new(series, true).unwrap(); - assert!(chunk.range().is_empty()); - assert!(chunk.is_last); - } - - /// The range is absolute, so concatenating two chunks of one series never reorders them. - #[test] - fn a_range_is_absolute_on_its_grid() { - let schema = schema(); - let first = chunk(&schema, 0, vec![1.0, 2.0], false); - let second = chunk(&schema, 2, vec![3.0, 4.0], true); - assert_eq!((first.range().start(), first.range().len()), (0, 2)); - assert_eq!((second.range().start(), second.range().len()), (2, 2)); - assert!(!first.is_last); - assert!(second.is_last); - } - - /// A chunk that is not addressed on a grid cannot be indexed by a native node. - #[test] - fn a_chunk_must_be_addressed_on_a_grid() { - let samples = Samples::from_float(Float64Array::from(vec![1.0])); - let series = Series { - metric: MetricName::try_new(Some("requests".into()), Vec::new()).unwrap(), - time: TimeAxis::Explicit(datatypes::arrow::buffer::ScalarBuffer::from(vec![0i64])), - fields: SeriesFields::try_from_vec(vec![samples]).unwrap(), - }; - assert!(EvaluatedChunk::try_new(series, true).is_err()); - } - - /// A schema with a grid is what marks a sample type as evaluated; the same fields without a - /// grid are raw samples. - #[test] - fn a_grid_in_the_schema_marks_an_evaluated_type() { - let evaluated = schema(); - assert!(evaluated.eval_grid.is_some()); - let raw = SeriesSchema { - fields: evaluated.fields.clone(), - eval_grid: None, - }; - assert!(raw.eval_grid.is_none()); - } -} diff --git a/src/promql/src/native/metrics.rs b/src/promql/src/native/metrics.rs index f0ebe48c08d..3f66c73e4b0 100644 --- a/src/promql/src/native/metrics.rs +++ b/src/promql/src/native/metrics.rs @@ -16,9 +16,7 @@ //! //! A node is identified by its structural position — `root`, `.input`, `.left`, `.right` — rather //! than by an id it carries. The position is not stored on the node: it is derived while walking -//! the tree, which is the one traversal rule run-time construction uses. A tree description -//! rendered from the same walk — intended for `EXPLAIN` and `ANALYZE`, neither of which renders a -//! native tree today — would show the positions that were registered. +//! the tree. [`walk`] is the one traversal rule, and [`register_tree`] is its caller. //! //! The position stays in the metric name because the collector aggregates by name first: two //! `rate` nodes sharing a bare name would be merged into one number. Positions are only an @@ -92,9 +90,8 @@ impl std::fmt::Display for NodePath { /// Visits every node of `root` with its position, outermost first. /// -/// This is the one traversal rule: [`register_tree`] calls it when the run-time state is created, -/// and a tree description is intended to render from it, so a node cannot be shown at one position -/// and registered at another. +/// This is the one traversal rule: [`register_tree`] is its caller, so a node's metric is always +/// named after the position this walk gives it. pub fn walk(root: &NativeNode, visit: &mut dyn FnMut(&NativeNode, &NodePath)) { fn go(node: &NativeNode, path: &NodePath, visit: &mut dyn FnMut(&NativeNode, &NodePath)) { visit(node, path); @@ -526,24 +523,31 @@ mod tests { } /// Registration covers every node, so no node is executed without a way to observe it. + /// + /// The set is read back rather than named again from the tree, so this checks what + /// registration actually did. #[test] fn registration_covers_every_node() { let root = map(window(input())); let set = datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new(); let registered = register_tree(&root, &set, 2); assert_eq!(registered.len(), 3); - let names: Vec = registered - .iter() - .map(|(path, _)| path.metric_name(NodeMetric::OUTPUT_VALUES)) - .collect(); - assert_eq!( - names, - vec![ - "native.root.output_values", - "native.root.input.output_values", - "native.root.input.input.output_values", - ] - ); + + // Read the names back from the set registration wrote to, so the check is against what + // registration did rather than against the names built a second time here. + let set = set.clone_inner(); + let names: Vec<&str> = set.iter().map(|metric| metric.value().name()).collect(); + // One entry per node per declared metric, and every node's position among them: no node + // is executed without a way to observe it. + assert_eq!(names.len(), registered.len() * NodeMetric::ALL.len()); + for (path, _) in ®istered { + // The peak is named per partition, so a plain name stands for the node here. + let name = path.metric_name(NodeMetric::OUTPUT_VALUES); + assert!( + names.contains(&name.as_str()), + "{path} registered nothing under its own position" + ); + } } /// Every metric a node reports is listed in one place, so registration cannot drift from the diff --git a/src/promql/src/native/mod.rs b/src/promql/src/native/mod.rs index 9cdb7f6c54a..89926c77d4b 100644 --- a/src/promql/src/native/mod.rs +++ b/src/promql/src/native/mod.rs @@ -16,9 +16,7 @@ //! //! A query compiles to a [`plan::NativeTree`]: nodes whose operations, fields and grids are already //! bound. Nodes hand each other [`batch::EvaluatedChunk`]s as ordinary Rust values, so no row batch -//! is materialised between them. [`metrics`] names each node after its position in that tree, -//! which is what an `EXPLAIN` or `ANALYZE` of a native plan is intended to render; no native plan -//! renders one today. +//! is materialised between them. [`metrics`] names each node after its position in that tree. //! //! Three properties keep this apart from recognising a query shape in a finished physical plan: //! diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 38a085093e6..3aae7e2237a 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -22,6 +22,11 @@ //! The tree is also the unit of legality. [`NativeNode::validate`] checks the contract every //! operation states about its input, which is what lets a new combination of supported operations //! be an ordinary tree instead of another hand-written shape. +//! +//! What the tree cannot express yet is deliberate for this stage: [`NativeExpr::Binary`] holds an +//! arithmetic or comparison operation, so `and`, `or` and `unless` have no node, and +//! [`NativeExpr::Scalar`] holds a constant, so `time()` and `scalar(v)` have no node either. The +//! legality below is therefore about the operations that exist, not about PromQL's whole surface. use std::sync::Arc; @@ -117,8 +122,8 @@ pub struct AggregateStateSchema { /// A scan or exchange boundary bound as a node input. /// /// The binding records what the input was created for: the output a consumer type-checks against, -/// and the ordering it guarantees. No consumer reads the ordering today; it is recorded so a -/// consumer that needs one can check it instead of assuming it. +/// and the ordering it guarantees. A window reads the ordering, rejecting an interleaved input; no +/// other consumer reads it yet. #[derive(Clone, Debug)] pub struct BoundInput { /// What the input produces: raw samples from a scan, or state from an exchange boundary. @@ -314,6 +319,8 @@ impl NativeNode { // field. ensure_same_fields(&input.output, &self.output, "an instant selection")?; ensure_grid(&self.output, &op.output_grid, "an instant selection")?; + // `select_instants` reads one series at a time and holds no cross-series state, so + // an interleaved input is enough for it: no ordering check here. } NativeExpr::Window { input, op } => { input.validate()?; @@ -325,8 +332,29 @@ impl NativeNode { input.output.describe() ))); }; - // The declared input grid has to be the grid the input actually produces, or the - // window would read positions the input never wrote. + // A range that is not positive reads nothing at every grid point. + if op.window.range_ms <= 0 { + return Err(invalid( + "a window reads an empty range: its range must be positive", + )); + } + // A range evaluator consumes one series to its last chunk before it starts the + // next, so interleaved chunks of different series cannot be fed to it. Only an + // input node carries an ordering, so only there is there one to check. + if let NativeExpr::Input(binding) = &input.expr + && binding.ordering == SeriesOrdering::Interleaved + { + return Err(invalid( + "a window reads one series to its last chunk before the next, so \ + interleaved chunks cannot be fed to it", + )); + } + // What is checked here and just below is that the declared input grid equals the + // input's grid, and that the output grid matches the declared one. The grid is + // not checked to cover the window's read range + // `(out.start - offset - range, out.end - offset]`: only a subquery feeds an + // evaluated input to a window, and this compiler does not accept subqueries yet, + // so that coverage check waits for it. match (op.input_grid.as_ref(), schema.eval_grid.as_ref()) { (None, None) => {} (Some(bound), Some(actual)) if bound.spec() == actual.spec() => {} @@ -495,11 +523,14 @@ impl NativeNode { )?; ensure_grid(&self.output, left_grid, "a binary operation")?; } - // Both sides carry a grid, so this is state, which the checks above reject. - // Kept as an error rather than a panic so a future type cannot slip through. - _ => { + // State has no grid, so the grid checks above return for either side before + // this match and these two arms cannot be reached at run time. They are + // spelled out because `NativeType` names `AggregateState` and the match has to + // cover the pair; the message says so rather than pretending a value arrived. + (NativeType::AggregateState(_), _) | (_, NativeType::AggregateState(_)) => { return Err(invalid( - "a binary operation consumes aggregate state, not a value", + "a binary operation reached aggregate state, which has no grid: the \ + grid check above should have rejected it", )); } } diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index f0ca5301af4..518e9a93b2c 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -233,11 +233,21 @@ fn a_window_over_raw_samples_is_valid() { fn adding_a_map_only_changes_the_tree() { let bare = window_over(input(), None); let mapped = map_over(window_over(input(), None)); - assert_eq!(bare.validate().is_ok(), mapped.validate().is_ok()); + // Both trees are legal, so the comparison below is about the shape and not about both failing. + assert!(bare.validate().is_ok(), "{}", bare.validate().unwrap_err()); + assert!( + mapped.validate().is_ok(), + "{}", + mapped.validate().unwrap_err() + ); // The mapped tree has one more node, and it is the same window below it. let mut depth = 0; super::super::metrics::walk(&mapped, &mut |_, _| depth += 1); assert_eq!(depth, 3); + let NativeExpr::Map { input, .. } = &mapped.expr else { + unreachable!("the mapped tree's root is a map") + }; + assert!(matches!(input.expr, NativeExpr::Window { .. })); } /// A map is point-wise over values, so raw samples are not something it can consume. @@ -442,6 +452,57 @@ fn a_window_checks_its_declared_input_grid() { ); } +/// A range evaluator reads one raw series to its last chunk before it starts the next, so raw +/// chunks of different series may not interleave. +#[test] +fn a_window_cannot_read_interleaved_input() { + let output = raw(); + let interleaved = NativeNode { + expr: NativeExpr::Input(BoundInput { + output: output.clone(), + ordering: SeriesOrdering::Interleaved, + }), + output, + }; + let error = window_over(interleaved, None).validate().unwrap_err(); + assert!( + error + .to_string() + .contains("interleaved chunks cannot be fed to it"), + "{error}" + ); +} + +/// A window whose range is empty or negative reads nothing at every grid point. +#[test] +fn a_window_reads_a_non_empty_range() { + let mut node = window_over(input(), None); + let NativeExpr::Window { op, .. } = &mut node.expr else { + unreachable!("a window tree has a window root") + }; + op.window.range_ms = 0; + let error = node.validate().unwrap_err(); + assert!(error.to_string().contains("empty range"), "{error}"); +} + +/// A node that declares an output grid its output does not carry would be addressed on one grid +/// and hand out positions on another. +#[test] +fn a_window_checks_its_output_grid() { + let mut node = window_over(input(), None); + let NativeExpr::Window { op, .. } = &mut node.expr else { + unreachable!("a window tree has a window root") + }; + op.output_grid = grid(0, 30_000, 8); + let error = node.validate().unwrap_err(); + assert!( + error + .to_string() + .contains("declares a grid its output does not carry"), + "{error}" + ); +} + /// A window consumes samples: state holds accumulators, not a sample stream to range over. #[test] fn a_window_cannot_consume_state() { @@ -561,6 +622,29 @@ fn a_binary_operation_broadcasts_a_scalar() { assert!(node.validate().is_ok()); } +/// A scalar has no fields of its own, so a broadcast that declares a different count than the +/// vector side would report a layout the kernel does not produce. +#[test] +fn a_scalar_broadcast_cannot_change_the_field_count() { + let shared = grid(0, 60_000, 4); + // The vector side has two fields; the broadcast declares one. + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(window_fields(input_with_fields(2), Arc::clone(&shared), 2)), + right: Box::new(scalar_on(1.0, Arc::clone(&shared))), + matching: add(), + }, + output: evaluated(fields(1), shared), + }; + let error = node.validate().unwrap_err(); + assert!( + error + .to_string() + .contains("does not produce the vector side's fields"), + "{error}" + ); +} + /// Two vectors pair their fields by position, so the match reports the shorter side's count /// (`vector_match::binary_output_schema` takes `min(lhs, rhs)`); a tree declaring anything else is /// rejected instead of failing at run time. @@ -611,6 +695,63 @@ fn two_scalars_make_a_scalar() { assert!(node.validate().is_ok()); } +/// Two scalars have nothing to attach labels or fields to, so they cannot produce a vector. +#[test] +fn two_scalars_cannot_produce_a_vector() { + let shared = grid(0, 60_000, 4); + let node = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(scalar_on(1.0, Arc::clone(&shared))), + right: Box::new(scalar_on(2.0, Arc::clone(&shared))), + matching: add(), + }, + output: evaluated(Arc::new([]), shared), + }; + let error = node.validate().unwrap_err(); + assert!( + error + .to_string() + .contains("two scalars do not produce a scalar"), + "{error}" + ); +} + +/// A binary operation is point-wise on a grid, so a side of raw samples has no positions to line +/// up with the other side. +#[test] +fn a_binary_operation_cannot_consume_raw_samples() { + let shared = grid(0, 60_000, 4); + let vector = || window_on(input(), None, Arc::clone(&shared)); + + let left_raw = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(input()), + right: Box::new(vector()), + matching: add(), + }, + output: evaluated(Arc::new([]), Arc::clone(&shared)), + }; + let error = left_raw.validate().unwrap_err(); + assert!( + error.to_string().contains("not raw samples on its left"), + "{error}" + ); + + let right_raw = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(vector()), + right: Box::new(input()), + matching: add(), + }, + output: evaluated(Arc::new([]), shared), + }; + let error = right_raw.validate().unwrap_err(); + assert!( + error.to_string().contains("not raw samples on its right"), + "{error}" + ); +} + /// State is not a value, so neither side of a binary operation may be state. #[test] fn a_binary_operation_cannot_consume_state() { @@ -718,15 +859,6 @@ fn an_aggregate_stage_must_agree_with_its_type() { ); } -/// A `Partial` aggregate turns a vector into state: the output is the state type, indexed on the -/// vector's grid. -#[test] -fn a_partial_aggregate_produces_state() { - let state = partial_aggregate(window_over(input(), None)); - assert!(state.validate().is_ok()); - assert!(matches!(state.output, NativeType::AggregateState(_))); -} - /// A `Partial` aggregate keeps one accumulator per input field (`aggregate_float` lays its state /// out in `schema.fields.len()`-sized points), so state declaring another count is rejected. #[test] @@ -757,6 +889,66 @@ fn a_partial_aggregate_cannot_change_the_accumulator_count() { ); } +/// A `Partial` aggregate's state is grouped by the binding's group labels, so state declaring +/// other labels is not the state this aggregate produces. +#[test] +fn a_partial_aggregate_groups_its_state_like_its_binding() { + let mut node = partial_aggregate(window_over(input(), None)); + let NativeExpr::Aggregate { op, .. } = &mut node.expr else { + unreachable!("a partial aggregate tree has an aggregate root") + }; + op.group = Arc::new(["instance".into()]); + let error = node.validate().unwrap_err(); + assert!( + error.to_string().contains("groups differ from the binding"), + "{error}" + ); +} + +/// A `Partial` aggregate indexes its state on the grid its input produces, so state on another +/// grid is addressed with positions the input never wrote. +#[test] +fn a_partial_aggregate_indexes_its_state_on_the_inputs_grid() { + let node = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(window_over(input(), None)), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Partial, + }, + }, + output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema { + group: Arc::new(["job".into()]), + accumulators: Arc::new([]), + grid: grid(0, 30_000, 8), + })), + }; + let error = node.validate().unwrap_err(); + assert!( + error + .to_string() + .contains("indexed on a grid the input does not produce"), + "{error}" + ); +} + +/// A `Final` aggregate merges into the binding's group labels, so the state it reads has to be +/// grouped the same way. +#[test] +fn a_final_aggregate_groups_its_state_like_its_binding() { + let mut node = final_aggregate(partial_aggregate(window_over(input(), None))); + let NativeExpr::Aggregate { op, .. } = &mut node.expr else { + unreachable!("a final aggregate tree has an aggregate root") + }; + op.group = Arc::new(["instance".into()]); + let error = node.validate().unwrap_err(); + assert!( + error.to_string().contains("groups differ from the binding"), + "{error}" + ); +} + /// A `Final` aggregate consumes the state a `Partial` produced, which is what an exchange /// boundary hands over between the two stages. #[test] From 3b8ab5b6411b3d39a43a7f655771db5e7ccf80af Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:08:28 +0800 Subject: [PATCH 07/17] fix(promql): bind a grouping as `by` or `without`, not as a label list A label list can only spell `by`: `sum without (instance) (rate(x[5m]))` has no list of group labels, because its key is every label the series has except the ones named. Spelling that as a list would group the query by labels it meant to remove, and the kernel takes both shapes already (`aggregate::Grouping::{By, Without}`), so the tree had no way to say what the engine can already do. State carries its grouping in the same terms now, so a `Final` also refuses state built for the other shape, not only state built from a different label list. The `groups` gauge counts per partition: a `Partial` aggregate sees one group in every partition it reaches, so the summed gauge is the total of per-partition entries rather than distinct groups. Both the metric's doc and the comment that claimed otherwise now say so. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/metrics.rs | 9 ++-- src/promql/src/native/plan.rs | 34 +++++++++++--- src/promql/src/native/plan/tests.rs | 69 ++++++++++++++++++++--------- 3 files changed, 82 insertions(+), 30 deletions(-) diff --git a/src/promql/src/native/metrics.rs b/src/promql/src/native/metrics.rs index 3f66c73e4b0..bcae9ddcdd0 100644 --- a/src/promql/src/native/metrics.rs +++ b/src/promql/src/native/metrics.rs @@ -136,7 +136,8 @@ impl NodeMetric { pub const CURRENT_RESERVED_BYTES: &'static str = "current_reserved_bytes"; /// The highest byte count this node reserved during the execution. pub const PEAK_RESERVED_BYTES: &'static str = "peak_reserved_bytes"; - /// How many groups this node tracks. + /// How many groups this node tracks, counted per partition: a group reached by several + /// partitions is one entry in each. pub const GROUPS: &'static str = "groups"; /// How many state entries this node tracks. pub const STATE_ENTRIES: &'static str = "state_entries"; @@ -262,8 +263,10 @@ impl NodeMetrics { ); // The peak is the one figure named per partition. The collector groups by name and sums // gauges, and a sum of two peaks is neither peak: partitions peak at different moments. - // Summing the other gauges and counts stays meaningful — the memory held now, the groups - // tracked and the samples seen all add up across partitions. + // Summing the other gauges and counts stays meaningful — the memory held now and the + // samples seen add up across partitions. `groups` does not: a `Partial` aggregate sees the + // same group in every partition it reaches, so the sum is per-partition entries, not + // distinct groups. gauge( set, partition, diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 3aae7e2237a..6cca42134f3 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -111,8 +111,8 @@ impl NativeType { /// accumulated on. It is not a query value and does not pretend to be one. #[derive(Clone, Debug)] pub struct AggregateStateSchema { - /// The labels a group is identified by, in output order. - pub group: Arc<[Arc]>, + /// How the groups its rows are indexed by are identified. + pub group: Grouping, /// The accumulator columns, one per aggregated field. pub accumulators: Arc<[FieldSpec]>, /// The grid the state is indexed on. @@ -195,13 +195,29 @@ pub enum AggregateStage { Final, } +/// How an aggregate's groups are identified, in the binding's own terms. +/// +/// The kernel already takes both shapes ([`aggregate::Grouping`]), and the two are not +/// interchangeable: `by(job)` keeps `job` and drops everything else, while `without(job)` keeps +/// every other label and drops `job` too. A list of group labels can only spell the first, so a +/// `without` written that way would group a query by labels it meant to remove. +/// +/// [`aggregate::Grouping`]: crate::aggregate::Grouping +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Grouping { + /// The labels a group is identified by; every other label is dropped. + By(Arc<[Arc]>), + /// The labels a group is not identified by; these are dropped, and so is `__name__`. + Without(Arc<[Arc]>), +} + /// An aggregate bound to its kind, grouping and stage. #[derive(Clone, Debug)] pub struct BoundAggregate { /// Which aggregate to compute. pub kind: AggregateKind, - /// The labels a group is identified by. - pub group: Arc<[Arc]>, + /// How its groups are identified. + pub group: Grouping, /// Where this aggregate sits in the execution. pub stage: AggregateStage, } @@ -432,7 +448,10 @@ impl NativeNode { )); } if state.group != op.group { - return Err(invalid("aggregate state groups differ from the binding")); + return Err(invalid( + "aggregate state groups differ from the binding: state built for \ + one `by` or `without` cannot be merged into another", + )); } } AggregateStage::Final => { @@ -445,7 +464,10 @@ impl NativeNode { ))); }; if state.group != op.group { - return Err(invalid("aggregate state groups differ from the binding")); + return Err(invalid( + "aggregate state groups differ from the binding: state built for \ + one `by` or `without` cannot be merged into another", + )); } let output = ensure_samples(&self.output, "a final aggregate")?; // The merged value carries one value per accumulator the state holds. diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index 518e9a93b2c..85be7426a58 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -20,7 +20,7 @@ use datatypes::series::time::{EvalGrid, GridSpec}; use super::{ AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar, - BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, + BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, NativeType, }; use crate::map::MathOp; use crate::range_eval::{RangeFunction, RangeWindow}; @@ -123,12 +123,12 @@ fn partial_aggregate(inner: NativeNode) -> NativeNode { input: Box::new(inner), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Partial, }, }, output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema { - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), accumulators: Arc::new([]), grid, })), @@ -142,7 +142,7 @@ fn final_aggregate(state: NativeNode) -> NativeNode { input: Box::new(state), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Final, }, }, @@ -784,7 +784,7 @@ fn an_aggregate_output_matches_its_stage() { input: Box::new(inner.clone()), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Complete, }, }, @@ -797,12 +797,12 @@ fn an_aggregate_output_matches_its_stage() { input: Box::new(inner), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Partial, }, }, output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema { - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), accumulators: Arc::new([]), grid: value_grid, })), @@ -821,7 +821,7 @@ fn a_complete_aggregate_cannot_change_the_field_count() { input: Box::new(window_fields(input_with_fields(2), Arc::clone(&out), 2)), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Complete, }, }, @@ -846,7 +846,7 @@ fn an_aggregate_stage_must_agree_with_its_type() { input: Box::new(inner), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Partial, }, }, @@ -870,12 +870,12 @@ fn a_partial_aggregate_cannot_change_the_accumulator_count() { input: Box::new(window_fields(input_with_fields(2), Arc::clone(&out), 2)), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Partial, }, }, output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema { - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), accumulators: fields(1), grid: out, })), @@ -897,7 +897,7 @@ fn a_partial_aggregate_groups_its_state_like_its_binding() { let NativeExpr::Aggregate { op, .. } = &mut node.expr else { unreachable!("a partial aggregate tree has an aggregate root") }; - op.group = Arc::new(["instance".into()]); + op.group = Grouping::By(Arc::new(["instance".into()])); let error = node.validate().unwrap_err(); assert!( error.to_string().contains("groups differ from the binding"), @@ -914,12 +914,12 @@ fn a_partial_aggregate_indexes_its_state_on_the_inputs_grid() { input: Box::new(window_over(input(), None)), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Partial, }, }, output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema { - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), accumulators: Arc::new([]), grid: grid(0, 30_000, 8), })), @@ -941,7 +941,7 @@ fn a_final_aggregate_groups_its_state_like_its_binding() { let NativeExpr::Aggregate { op, .. } = &mut node.expr else { unreachable!("a final aggregate tree has an aggregate root") }; - op.group = Arc::new(["instance".into()]); + op.group = Grouping::By(Arc::new(["instance".into()])); let error = node.validate().unwrap_err(); assert!( error.to_string().contains("groups differ from the binding"), @@ -949,6 +949,33 @@ fn a_final_aggregate_groups_its_state_like_its_binding() { ); } +/// `by` and `without` are not interchangeable, even over the same label. +/// +/// `by(job)` keeps `job` and drops every other label; `without(job)` drops `job` and keeps the +/// rest. A binding that spelled `without` as a label list could only produce the first, so state +/// built for one has to be refused for the other rather than merged under the wrong labels. +#[test] +fn a_grouping_cannot_swap_by_for_without() { + let mut node = final_aggregate(partial_aggregate(window_over(input(), None))); + let NativeExpr::Aggregate { op, .. } = &mut node.expr else { + unreachable!("a final aggregate tree has an aggregate root") + }; + op.group = Grouping::Without(Arc::new(["job".into()])); + let error = node.validate().unwrap_err(); + assert!( + error.to_string().contains("groups differ from the binding"), + "{error}" + ); + + // The same labels under the same shape validate, so the refusal is about the shape. + let mut node = final_aggregate(partial_aggregate(window_over(input(), None))); + let NativeExpr::Aggregate { op, .. } = &mut node.expr else { + unreachable!("a final aggregate tree has an aggregate root") + }; + op.group = Grouping::By(Arc::new(["job".into()])); + assert!(node.validate().is_ok()); +} + /// A `Final` aggregate consumes the state a `Partial` produced, which is what an exchange /// boundary hands over between the two stages. #[test] @@ -973,12 +1000,12 @@ fn a_final_aggregate_cannot_change_the_field_count() { input: Box::new(window_fields(input_with_fields(2), Arc::clone(&out), 2)), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Partial, }, }, output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema { - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), accumulators: fields(2), grid: Arc::clone(&out), })), @@ -995,7 +1022,7 @@ fn a_final_aggregate_cannot_change_the_field_count() { input: Box::new(state), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Final, }, }, @@ -1020,7 +1047,7 @@ fn a_final_aggregate_cannot_consume_a_window() { input: Box::new(inner), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Final, }, }, @@ -1043,7 +1070,7 @@ fn a_complete_aggregate_cannot_consume_state() { input: Box::new(state), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Complete, }, }, @@ -1074,7 +1101,7 @@ fn the_walkthrough_shapes_are_trees() { input: Box::new(window_on(input(), None, Arc::clone(&statement_grid))), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Complete, }, }, From ab528e7bb94ec20a680dc56e187c80c208805a38 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Mon, 19 Oct 2026 21:10:46 +0800 Subject: [PATCH 08/17] feat(promql): compile a PromQL statement into a native tree Compile a range selector and its surrounding shape into the native plan nodes introduced earlier, and render the resulting tree through `Display` so an `EXPLAIN` can show it. The display carries each node's operation, its bound window and the fields it reports. Field layout is validated here rather than at execution: a node that declares a different number of fields than it consumes is a planning error, which is what the fixture tests pin. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/display.rs | 295 ++++++++++++++++ src/promql/src/native/display/tests.rs | 344 ++++++++++++++++++ src/promql/src/native/mod.rs | 1 + src/query/src/promql.rs | 1 + src/query/src/promql/native_compile.rs | 239 +++++++++++++ src/query/src/promql/native_compile/tests.rs | 351 +++++++++++++++++++ 6 files changed, 1231 insertions(+) create mode 100644 src/promql/src/native/display.rs create mode 100644 src/promql/src/native/display/tests.rs create mode 100644 src/query/src/promql/native_compile.rs create mode 100644 src/query/src/promql/native_compile/tests.rs diff --git a/src/promql/src/native/display.rs b/src/promql/src/native/display.rs new file mode 100644 index 00000000000..b61493b87b2 --- /dev/null +++ b/src/promql/src/native/display.rs @@ -0,0 +1,295 @@ +// 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. + +//! One line per node of a [`NativeTree`]. +//! +//! The position a node is shown at is derived by [`metrics::walk`], the same traversal that names +//! the node's metrics, so a node cannot be shown at one place and measured at another. The +//! display is an observation of a compiled tree: it runs nothing, and a node whose operation has +//! no executor says so instead of reading like an operation that will happen. + +use std::fmt::{self, Write}; +use std::sync::Arc; + +use datatypes::series::SeriesOrdering; +use datatypes::series::time::EvalGrid; + +use crate::map::MathOp; +use crate::native::metrics::{self, NodePath}; +use crate::native::plan::{ + AggregateKind, AggregateStage, BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, +}; +use crate::range_eval::RangeFunction; +use crate::vector_match::{BinaryOp, Cardinality, MatchingLabels}; + +/// The header line of every tree. +const HEADER: &str = "NativeTree"; + +/// What a node without an executor is marked with, so its line does not read like a run. +const NO_EXECUTOR: &str = " (no executor)"; + +/// How deep `path` is: the root is at depth zero, its input at one. +fn depth(path: &NodePath) -> usize { + path.as_str().matches('.').count() +} + +/// The last segment of `path`, which is the name of the node in its parent. +fn name(path: &NodePath) -> &str { + // `NodePath` only ever appends `.segment`, so the last segment is never empty. + path.as_str().rsplit('.').next().unwrap_or(path.as_str()) +} + +/// A grid as `/x`. +fn grid_name(grid: &EvalGrid) -> String { + let spec = grid.spec(); + format!( + "{}/{step}x{len}", + spec.start_ms, + step = spec.step_ms, + len = spec.len + ) +} + +/// A label list in the order it was bound. +fn label_list(labels: &[Arc]) -> String { + labels + .iter() + .map(|label| label.to_string()) + .collect::>() + .join(", ") +} + +/// The ordering an input guarantees, when it is weaker than the scan's default. +fn ordering(ordering: SeriesOrdering) -> &'static str { + // `KeyThenTime` is what a scan that orders anything at all provides, so it is the + // uninteresting case; a weaker guarantee is what a consumer has to know about. + match ordering { + SeriesOrdering::KeyThenTime => "", + SeriesOrdering::Contiguous => ", contiguous", + SeriesOrdering::Interleaved => ", interleaved", + } +} + +/// The operation a node computes, in the words of the query that produced it. +fn describe(node: &NativeNode) -> String { + match &node.expr { + NativeExpr::Input(input) => match &input.output { + NativeType::Samples(schema) if schema.eval_grid.is_some() => { + format!("evaluated samples{}", ordering(input.ordering)) + } + NativeType::Samples(_) => format!("raw samples{}", ordering(input.ordering)), + NativeType::Scalar(grid) => format!("scalar on grid {}", grid_name(grid)), + NativeType::AggregateState(_) => "aggregate state".to_string(), + }, + NativeExpr::Scalar(scalar) => scalar.value.to_string(), + NativeExpr::Instant { op, .. } => format!( + "lookback {}ms offset {} on grid {}", + op.lookback_ms, + op.offset_ms, + grid_name(&op.output_grid) + ), + NativeExpr::Window { op, .. } => window(op), + NativeExpr::Map { op, .. } => { + let ops: Vec = op.ops.iter().map(math_op).collect(); + ops.join(", ") + } + NativeExpr::Aggregate { op, .. } => format!( + "{} by [{}] {}", + match op.kind { + AggregateKind::Sum => "sum", + }, + label_list(&op.group), + match op.stage { + AggregateStage::Complete => "complete", + AggregateStage::Partial => "partial", + AggregateStage::Final => "final", + } + ), + NativeExpr::Binary { matching, .. } => format!( + "{}{} {} {}", + binary_op(matching.op), + if matching.return_bool { " bool" } else { "" }, + match &matching.labels { + MatchingLabels::On(labels) => format!("on [{}]", label_list(labels)), + MatchingLabels::Ignoring(labels) => format!("ignoring [{}]", label_list(labels)), + }, + match &matching.cardinality { + Cardinality::OneToOne => "one-to-one".to_string(), + Cardinality::ManyToOne(labels) => format!("many-to-one [{}]", label_list(labels)), + Cardinality::OneToMany(labels) => format!("one-to-many [{}]", label_list(labels)), + } + ), + } +} + +/// A window: what it runs, over which range, and where it lands. +fn window(op: &BoundWindow) -> String { + format!( + "{} [{}ms] offset {} anchor {} on grid {}", + function(op.function), + op.window.range_ms, + op.window.offset_ms, + match op.window.anchor_ms { + Some(anchor_ms) => anchor_ms.to_string(), + None => "-".to_string(), + }, + grid_name(&op.output_grid) + ) +} + +/// The PromQL name of a range function, with the constant argument it was bound to. +fn function(function: RangeFunction) -> String { + match function { + RangeFunction::Rate => "rate".to_string(), + RangeFunction::Increase => "increase".to_string(), + RangeFunction::Delta => "delta".to_string(), + RangeFunction::Irate => "irate".to_string(), + RangeFunction::Idelta => "idelta".to_string(), + RangeFunction::AvgOverTime => "avg_over_time".to_string(), + RangeFunction::MinOverTime => "min_over_time".to_string(), + RangeFunction::MaxOverTime => "max_over_time".to_string(), + RangeFunction::SumOverTime => "sum_over_time".to_string(), + RangeFunction::CountOverTime => "count_over_time".to_string(), + RangeFunction::LastOverTime => "last_over_time".to_string(), + RangeFunction::PresentOverTime => "present_over_time".to_string(), + RangeFunction::StddevOverTime => "stddev_over_time".to_string(), + RangeFunction::StdvarOverTime => "stdvar_over_time".to_string(), + RangeFunction::QuantileOverTime(quantile) => format!("quantile_over_time {quantile}"), + RangeFunction::Resets => "resets".to_string(), + RangeFunction::Changes => "changes".to_string(), + RangeFunction::Deriv => "deriv".to_string(), + RangeFunction::PredictLinear(seconds) => format!("predict_linear {seconds}"), + RangeFunction::DoubleExponentialSmoothing { smoothing, trend } => { + format!("double_exponential_smoothing {smoothing} {trend}") + } + RangeFunction::FirstOverTime => "first_over_time".to_string(), + RangeFunction::MadOverTime => "mad_over_time".to_string(), + RangeFunction::TsOfFirstOverTime => "ts_of_first_over_time".to_string(), + RangeFunction::TsOfLastOverTime => "ts_of_last_over_time".to_string(), + RangeFunction::TsOfMinOverTime => "ts_of_min_over_time".to_string(), + RangeFunction::TsOfMaxOverTime => "ts_of_max_over_time".to_string(), + } +} + +/// The PromQL name of a point-wise operation, with the constant arguments it was bound to. +fn math_op(op: &MathOp) -> String { + match op { + MathOp::Abs => "abs".to_string(), + MathOp::Ceil => "ceil".to_string(), + MathOp::Floor => "floor".to_string(), + MathOp::Sqrt => "sqrt".to_string(), + MathOp::Round { nearest } => format!("round {nearest}"), + MathOp::Exp => "exp".to_string(), + MathOp::Ln => "ln".to_string(), + MathOp::Log2 => "log2".to_string(), + MathOp::Log10 => "log10".to_string(), + MathOp::Sin => "sin".to_string(), + MathOp::Cos => "cos".to_string(), + MathOp::Tan => "tan".to_string(), + MathOp::Asin => "asin".to_string(), + MathOp::Acos => "acos".to_string(), + MathOp::Atan => "atan".to_string(), + MathOp::Sinh => "sinh".to_string(), + MathOp::Cosh => "cosh".to_string(), + MathOp::Tanh => "tanh".to_string(), + MathOp::Asinh => "asinh".to_string(), + MathOp::Acosh => "acosh".to_string(), + MathOp::Atanh => "atanh".to_string(), + MathOp::Deg => "deg".to_string(), + MathOp::Rad => "rad".to_string(), + MathOp::Sgn => "sgn".to_string(), + MathOp::Clamp { min, max } => format!("clamp {min} {max}"), + MathOp::ClampMin { min } => format!("clamp_min {min}"), + MathOp::ClampMax { max } => format!("clamp_max {max}"), + } +} + +/// The PromQL symbol of a binary operator. +fn binary_op(op: BinaryOp) -> &'static str { + match op { + BinaryOp::Add => "+", + BinaryOp::Sub => "-", + BinaryOp::Mul => "*", + BinaryOp::Div => "/", + BinaryOp::Mod => "%", + BinaryOp::Pow => "^", + BinaryOp::Atan2 => "atan2", + BinaryOp::Eq => "==", + BinaryOp::Ne => "!=", + BinaryOp::Gt => ">", + BinaryOp::Lt => "<", + BinaryOp::Ge => ">=", + BinaryOp::Le => "<=", + } +} + +/// What kind of node this is, as its line names it. +fn kind(expr: &NativeExpr) -> &'static str { + match expr { + NativeExpr::Input(_) => "Input", + NativeExpr::Scalar(_) => "Scalar", + NativeExpr::Instant { .. } => "Instant", + NativeExpr::Window { .. } => "Window", + NativeExpr::Map { .. } => "Map", + NativeExpr::Aggregate { .. } => "Aggregate", + NativeExpr::Binary { .. } => "Binary", + } +} + +/// Whether the node's operation has an executor, so its line may read like something that runs. +fn has_executor(expr: &NativeExpr) -> bool { + matches!( + expr, + NativeExpr::Input(_) | NativeExpr::Window { .. } | NativeExpr::Map { .. } + ) +} + +/// The line a node is shown as, without its indentation. +fn line(node: &NativeNode, path: &NodePath) -> String { + format!( + "{} {} {}{}", + name(path), + kind(&node.expr), + describe(node), + if has_executor(&node.expr) { + "" + } else { + NO_EXECUTOR + } + ) +} + +impl fmt::Display for NativeTree { + /// One line per node, outermost first, indented two spaces per depth below the header. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(HEADER)?; + let mut lines = Vec::new(); + metrics::walk(self.root(), &mut |node, path| { + lines.push((depth(path), line(node, path))); + }); + for (depth, line) in lines { + f.write_char('\n')?; + // The root sits one level in from the header, and each input one level below its + // consumer, so the shape of the tree is the shape of the output. + for _ in 0..depth + 1 { + f.write_str(" ")?; + } + f.write_str(&line)?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests; diff --git a/src/promql/src/native/display/tests.rs b/src/promql/src/native/display/tests.rs new file mode 100644 index 00000000000..45722028fb8 --- /dev/null +++ b/src/promql/src/native/display/tests.rs @@ -0,0 +1,344 @@ +// 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. + +use std::sync::Arc; + +use datatypes::series::SeriesOrdering; +use datatypes::series::samples::{FieldSpec, SeriesSchema}; +use datatypes::series::time::{EvalGrid, GridSpec}; + +use super::super::plan::{ + AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar, + BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, +}; +use crate::map::MathOp; +use crate::range_eval::{RangeFunction, RangeWindow}; +use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, MatchingLabels}; + +fn grid(start: i64, step: i64, len: u64) -> Arc { + Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap()) +} + +fn fields() -> Arc<[FieldSpec]> { + Arc::new([FieldSpec { + name: "value".into(), + }]) +} + +/// The samples a node produces on `grid`. +fn evaluated(grid: Arc) -> NativeType { + NativeType::Samples(Arc::new(SeriesSchema { + fields: fields(), + eval_grid: Some(grid), + })) +} + +/// An unqualified scan over raw samples, which is what a compiled query starts from. +fn raw_input() -> NativeNode { + // One allocation shared by the binding and the output: `validate` checks allocation identity. + // The fields are the ones a window over this input reports, because a window keeps its input's + // layout and `validate` rejects a node that declares a different count. + let output = NativeType::Samples(Arc::new(SeriesSchema { + fields: fields(), + eval_grid: None, + })); + NativeNode { + expr: NativeExpr::Input(BoundInput { + output: output.clone(), + ordering: SeriesOrdering::KeyThenTime, + }), + output, + } +} + +fn window_over( + inner: NativeNode, + function: RangeFunction, + range_ms: i64, + offset_ms: i64, + anchor_ms: Option, + out: Arc, +) -> NativeNode { + NativeNode { + expr: NativeExpr::Window { + input: Box::new(inner), + op: BoundWindow { + function, + window: RangeWindow { + range_ms, + offset_ms, + anchor_ms, + }, + input_grid: None, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(out), + } +} + +fn map(inner: NativeNode, ops: Vec) -> NativeNode { + let out = inner.output.grid().expect("a map needs a grid").clone(); + NativeNode { + expr: NativeExpr::Map { + input: Box::new(inner), + op: BoundMap { + ops: Arc::from(ops), + }, + }, + output: evaluated(out), + } +} + +/// The expected display of a tree, one string per line, so a change in wording, order or +/// indentation fails the test rather than passing as a substring. +fn shown(lines: &[&str]) -> String { + lines.join("\n") +} + +/// The header comes first and is exactly `NativeTree`, so the output says what it is before it +/// says anything about the tree. +#[test] +fn the_first_line_names_the_tree() { + let tree = NativeTree::try_new(raw_input()).unwrap(); + + assert_eq!( + tree.to_string(), + shown(&["NativeTree", " root Input raw samples"]) + ); + assert_eq!(tree.to_string().lines().next(), Some("NativeTree")); +} + +/// A compiled tree is one line per node, outermost first: the window is the root and the scan it +/// folds is shown beneath it. +#[test] +fn a_window_over_raw_samples_is_shown_once_per_node() { + let tree = NativeTree::try_new(window_over( + raw_input(), + RangeFunction::Rate, + 300_000, + 0, + None, + grid(0, 60_000, 4), + )) + .unwrap(); + + assert_eq!( + tree.to_string(), + shown(&[ + "NativeTree", + " root Window rate [300000ms] offset 0 anchor - on grid 0/60000x4", + " input Input raw samples", + ]) + ); +} + +/// A map nests one level deeper than the window it reads, and lists its operations in the order +/// they are applied. +#[test] +fn a_map_nests_below_the_window_it_maps() { + let tree = NativeTree::try_new(map( + window_over( + raw_input(), + RangeFunction::Rate, + 300_000, + 60_000, + None, + grid(0, 60_000, 4), + ), + vec![MathOp::Abs, MathOp::Round { nearest: 3.0 }], + )) + .unwrap(); + + assert_eq!( + tree.to_string(), + shown(&[ + "NativeTree", + " root Map abs, round 3", + " input Window rate [300000ms] offset 60000 anchor - on grid 0/60000x4", + " input Input raw samples", + ]) + ); +} + +/// A parameterised window names the constant it was bound to, and an anchored one names its +/// anchor instead of printing the absent case. +#[test] +fn a_window_names_its_constant_argument_and_its_anchor() { + let tree = NativeTree::try_new(window_over( + raw_input(), + RangeFunction::QuantileOverTime(0.9), + 60_000, + 0, + Some(42), + grid(1_000, 60_000, 4), + )) + .unwrap(); + + assert_eq!( + tree.to_string(), + shown(&[ + "NativeTree", + " root Window quantile_over_time 0.9 [60000ms] offset 0 anchor 42 on grid 1000/60000x4", + " input Input raw samples", + ]) + ); +} + +/// An input says whether its samples are raw or already evaluated, and reports the ordering it +/// guarantees when that is weaker than the scan default. +#[test] +fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() { + let contiguous = NativeType::Samples(Arc::new(SeriesSchema { + fields: fields(), + eval_grid: Some(grid(0, 60_000, 4)), + })); + let evaluated_input = NativeNode { + expr: NativeExpr::Input(BoundInput { + output: contiguous.clone(), + ordering: SeriesOrdering::Contiguous, + }), + output: contiguous, + }; + let tree = NativeTree::try_new(evaluated_input).unwrap(); + assert_eq!( + tree.to_string(), + shown(&["NativeTree", " root Input evaluated samples, contiguous",]) + ); + + let interleaved = NativeType::Samples(Arc::new(SeriesSchema { + fields: fields(), + eval_grid: None, + })); + let raw_input = NativeNode { + expr: NativeExpr::Input(BoundInput { + output: interleaved.clone(), + ordering: SeriesOrdering::Interleaved, + }), + output: interleaved, + }; + let tree = NativeTree::try_new(raw_input).unwrap(); + assert_eq!( + tree.to_string(), + shown(&["NativeTree", " root Input raw samples, interleaved"]) + ); +} + +/// A kind with no executor says so, so its line is not read as an operation that will run. +#[test] +fn a_kind_without_an_executor_says_so() { + let out = grid(0, 60_000, 4); + let scalar = NativeNode { + expr: NativeExpr::Scalar(BoundScalar { value: 2.0 }), + output: NativeType::Scalar(Arc::clone(&out)), + }; + let tree = NativeTree::try_new(scalar).unwrap(); + assert_eq!( + tree.to_string(), + shown(&["NativeTree", " root Scalar 2 (no executor)"]) + ); + + let instant = NativeNode { + expr: NativeExpr::Instant { + input: Box::new(raw_input()), + op: BoundInstant { + lookback_ms: 300_000, + offset_ms: 60_000, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(out), + }; + let tree = NativeTree::try_new(instant).unwrap(); + assert_eq!( + tree.to_string(), + shown(&[ + "NativeTree", + " root Instant lookback 300000ms offset 60000 on grid 0/60000x4 (no executor)", + " input Input raw samples", + ]) + ); +} + +/// An aggregate and a binary operation name the binding they were compiled with, which is what +/// makes the line worth reading once they have executors. +#[test] +fn an_aggregate_and_a_binary_name_their_binding() { + let out = grid(0, 60_000, 4); + let aggregate = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(window_over( + raw_input(), + RangeFunction::Rate, + 300_000, + 0, + None, + Arc::clone(&out), + )), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Arc::new(["job".into()]), + stage: AggregateStage::Complete, + }, + }, + output: evaluated(Arc::clone(&out)), + }; + let tree = NativeTree::try_new(aggregate).unwrap(); + assert_eq!( + tree.to_string(), + shown(&[ + "NativeTree", + " root Aggregate sum by [job] complete (no executor)", + " input Window rate [300000ms] offset 0 anchor - on grid 0/60000x4", + " input Input raw samples", + ]) + ); + + // A scalar broadcast, which is the one binary shape whose matching rules are never consulted: + // the display still prints them, because the binding is what the compiler decided. + let binary = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(NativeNode { + expr: NativeExpr::Scalar(BoundScalar { value: 2.0 }), + output: NativeType::Scalar(Arc::clone(&out)), + }), + right: Box::new(window_over( + raw_input(), + RangeFunction::Rate, + 300_000, + 0, + None, + Arc::clone(&out), + )), + matching: BinaryMatching { + op: BinaryOp::Add, + return_bool: false, + labels: MatchingLabels::Ignoring(Vec::new()), + cardinality: Cardinality::OneToOne, + }, + }, + output: evaluated(out), + }; + let tree = NativeTree::try_new(binary).unwrap(); + assert_eq!( + tree.to_string(), + shown(&[ + "NativeTree", + " root Binary + ignoring [] one-to-one (no executor)", + " left Scalar 2 (no executor)", + " right Window rate [300000ms] offset 0 anchor - on grid 0/60000x4", + " input Input raw samples", + ]) + ); +} diff --git a/src/promql/src/native/mod.rs b/src/promql/src/native/mod.rs index 89926c77d4b..e843c0169be 100644 --- a/src/promql/src/native/mod.rs +++ b/src/promql/src/native/mod.rs @@ -28,5 +28,6 @@ //! here" from "no more input". pub mod batch; +mod display; pub mod metrics; pub mod plan; diff --git a/src/query/src/promql.rs b/src/query/src/promql.rs index db682ca6a89..424204b5d95 100644 --- a/src/query/src/promql.rs +++ b/src/query/src/promql.rs @@ -14,6 +14,7 @@ pub mod error; pub mod label_values; +pub mod native_compile; pub mod planner; use datafusion_common::tree_node::{TreeNode as _, TreeNodeRecursion}; diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs new file mode 100644 index 00000000000..4268f87ad82 --- /dev/null +++ b/src/query/src/promql/native_compile.rs @@ -0,0 +1,239 @@ +// 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. + +//! Compiles a PromQL AST into a [`NativeTree`]. +//! +//! This is the front half of the native evaluation model: it reads the parsed statement and writes +//! down what it means as bound nodes. It runs nothing, and nothing calls it yet, so the subset it +//! accepts is deliberately one shape: +//! +//! ```text +//! ([]) e.g. rate(x[5m]) +//! ``` +//! +//! which becomes `Input` (raw samples) → `Window` (the range function over the statement's grid). +//! Everything else is a [`DataFusionError::NotImplemented`] that names what was found and quotes +//! the shape above, because rejecting a query the compiler does not understand is the only honest +//! alternative to compiling it into something else. +//! +//! The statement's grid and the selector's window are the only numbers derived here; the legality +//! of the tree is not checked here. [`NativeTree::try_new`] is the single authority on that, so a +//! node added later cannot be legal in one place and illegal in another. + +use std::sync::Arc; + +use datafusion::error::{DataFusionError, Result}; +use datatypes::series::SeriesOrdering; +use datatypes::series::samples::SeriesSchema; +use datatypes::series::time::{EvalGrid, GridSpec}; +use promql::native::plan::{ + BoundInput, BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, +}; +use promql::range_eval::{RangeFunction, RangeWindow}; +use promql_parser::parser::{Call, EvalStmt, Expr as PromExpr, MatrixSelector, Offset}; + +use crate::promql::label_values::signed_millis_since_epoch; + +/// The one shape this compiler accepts, quoted in every rejection. +const SUPPORTED: &str = "`([])`, for example `rate(x[5m])`"; + +/// Compiles `stmt` into a tree that reads `input` and folds it with the statement's one window. +/// +/// `input` is the raw series schema the caller bound from the table: the AST alone cannot produce +/// it, because it says which series the query reads but not which fields they carry. `ordering` is +/// what the caller's scan guarantees, and the tree records it rather than assuming one. +pub fn compile( + stmt: &EvalStmt, + input: Arc, + ordering: SeriesOrdering, +) -> Result { + let PromExpr::Call(Call { func, args }) = &stmt.expr else { + return Err(not_implemented(&format!("the expression `{}`", stmt.expr))); + }; + let Some(function) = range_function(func.name) else { + return Err(not_implemented(&format!( + "a call to `{}`, which has no native range kernel", + func.name + ))); + }; + let [argument] = args.args.as_slice() else { + return Err(not_implemented(&format!( + "a call to `{}` with {} argument(s)", + func.name, + args.args.len() + ))); + }; + let PromExpr::MatrixSelector(MatrixSelector { vs, range }) = argument.as_ref() else { + return Err(not_implemented(&format!( + "a call to `{}` whose argument is `{}`", + func.name, argument + ))); + }; + // An `@`-anchored selector is step-invariant: every step folds the same samples, which the + // native model would have to replay over the grid. That replay is not part of this subset, so + // the anchor is refused rather than dropped. + if vs.at.is_some() { + return Err(not_implemented(&format!( + "a call to `{}` over an `@`-anchored selector, whose window is fixed rather than \ + following the evaluation grid and would need the step-invariant replay the native \ + compiler does not implement yet", + func.name + ))); + } + let range_ms = range_millis(range.as_millis())?; + let offset_ms = selector_offset_ms(&vs.offset)?; + // The grid is the last thing built: a query refused above, or a window that cannot exist, + // never pays for a grid nothing would read. + let output_grid = statement_grid(stmt)?; + + // A range function reports one value per input field, so the layout is the input's. + let output = NativeType::Samples(Arc::new(SeriesSchema { + fields: Arc::clone(&input.fields), + eval_grid: Some(Arc::clone(&output_grid)), + })); + + // One allocation shared by the binding and the node's output: `NativeTree::try_new` compares + // them by identity, because a compiler that meant one schema has no reason to allocate it + // twice. + let raw = NativeType::Samples(input); + + NativeTree::try_new(NativeNode { + expr: NativeExpr::Window { + input: Box::new(NativeNode { + expr: NativeExpr::Input(BoundInput { + output: raw.clone(), + ordering, + }), + output: raw, + }), + op: BoundWindow { + function, + window: RangeWindow { + range_ms, + offset_ms, + // Only `@` sets an anchor, and an anchored selector is rejected above. + anchor_ms: None, + }, + // The input is raw samples, so it has no grid of its own. + input_grid: None, + output_grid, + }, + }, + output, + }) +} + +/// The grid the statement is evaluated on: `(end - start) / step + 1` points, the last of which +/// does not pass `end`. +fn statement_grid(stmt: &EvalStmt) -> Result> { + let start_ms = signed_millis_since_epoch(stmt.start)?; + let end_ms = signed_millis_since_epoch(stmt.end)?; + // The step is narrowed before [`GridSpec`] sees it, so an interval to which no millisecond + // step corresponds is reported as its own value rather than as a step of zero. + let step_ms = millis(stmt.interval.as_millis()).ok_or_else(|| { + DataFusionError::Plan(format!( + "the statement's evaluation step of {}ms is out of range", + stmt.interval.as_millis() + )) + })?; + // A positive step, ordered endpoints and an inclusive length that fits are the grid's contract, + // so [`GridSpec`] owns them; re-deriving any of them here would be a second copy of it. + let spec = GridSpec::try_from_range(start_ms, end_ms, step_ms).map_err(|error| { + DataFusionError::Plan(format!( + "the statement's grid of {start_ms}ms..{end_ms}ms at {step_ms}ms per step is invalid: \ + {error}" + )) + })?; + Ok(Arc::new(EvalGrid::try_new(spec).map_err(grid_error)?)) +} + +/// The window length of a range selector, which has to be longer than zero to select anything. +fn range_millis(range: u128) -> Result { + let range_ms = millis(range).ok_or_else(|| { + DataFusionError::Plan(format!( + "the range selector's window of {range}ms is out of range" + )) + })?; + if range_ms <= 0 { + return Err(DataFusionError::Plan(format!( + "the range selector's window is {range_ms}ms, and a window has to be longer than zero" + ))); + } + Ok(range_ms) +} + +/// The selector's offset in milliseconds; positive reads earlier samples. +fn selector_offset_ms(offset: &Option) -> Result { + let Some(offset) = offset else { + return Ok(0); + }; + let (magnitude, sign) = match offset { + Offset::Pos(duration) => (duration.as_millis(), 1), + Offset::Neg(duration) => (duration.as_millis(), -1), + }; + millis(magnitude) + .and_then(|magnitude| magnitude.checked_mul(sign)) + .ok_or_else(|| { + DataFusionError::Plan(format!( + "the selector's offset of {magnitude}ms is out of range" + )) + }) +} + +/// A millisecond magnitude as an `i64`, or `None` when it does not fit. +fn millis(millis: u128) -> Option { + i64::try_from(millis).ok() +} + +fn grid_error(error: datatypes::error::Error) -> DataFusionError { + DataFusionError::Plan(format!("the statement's grid is invalid: {error}")) +} + +/// The range function a PromQL name denotes, or `None` when this compiler has no kernel for it. +/// +/// The map is explicit on purpose: a name that is not listed here is rejected, so supporting one +/// more function is a decision made in one place rather than a consequence of a name looking +/// familiar. +fn range_function(name: &str) -> Option { + match name { + "rate" => Some(RangeFunction::Rate), + "increase" => Some(RangeFunction::Increase), + "delta" => Some(RangeFunction::Delta), + "irate" => Some(RangeFunction::Irate), + "idelta" => Some(RangeFunction::Idelta), + "avg_over_time" => Some(RangeFunction::AvgOverTime), + "min_over_time" => Some(RangeFunction::MinOverTime), + "max_over_time" => Some(RangeFunction::MaxOverTime), + "sum_over_time" => Some(RangeFunction::SumOverTime), + "count_over_time" => Some(RangeFunction::CountOverTime), + "last_over_time" => Some(RangeFunction::LastOverTime), + "present_over_time" => Some(RangeFunction::PresentOverTime), + "stddev_over_time" => Some(RangeFunction::StddevOverTime), + "stdvar_over_time" => Some(RangeFunction::StdvarOverTime), + "resets" => Some(RangeFunction::Resets), + "changes" => Some(RangeFunction::Changes), + "deriv" => Some(RangeFunction::Deriv), + _ => None, + } +} + +/// A rejection of a shape outside [`SUPPORTED`]. +fn not_implemented(found: &str) -> DataFusionError { + DataFusionError::NotImplemented(format!( + "the native PromQL compiler supports only {SUPPORTED} for now, but found {found}" + )) +} + +#[cfg(test)] +mod tests; diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs new file mode 100644 index 00000000000..b30a4e5be36 --- /dev/null +++ b/src/query/src/promql/native_compile/tests.rs @@ -0,0 +1,351 @@ +// 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. + +use std::sync::Arc; +use std::time::{Duration, UNIX_EPOCH}; + +use datafusion::error::DataFusionError; +use datatypes::series::SeriesOrdering; +use datatypes::series::samples::{FieldSpec, SeriesSchema}; +use promql::native::plan::{BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType}; +use promql::range_eval::RangeFunction; +use promql_parser::parser::{EvalStmt, Expr as PromExpr}; + +use super::compile; + +/// The raw series schema a caller binds from the table: one field and no evaluation grid. +fn raw_schema() -> Arc { + Arc::new(SeriesSchema { + fields: Arc::new([FieldSpec { + name: "value".into(), + }]), + eval_grid: None, + }) +} + +/// A statement over 100 seconds in 5-second steps, which is 21 grid points. +fn eval_stmt(query: &str) -> EvalStmt { + EvalStmt { + expr: promql_parser::parser::parse(query).unwrap(), + start: UNIX_EPOCH, + end: UNIX_EPOCH + Duration::from_secs(100), + interval: Duration::from_secs(5), + lookback_delta: Duration::from_secs(5), + } +} + +/// `rate(x[])` with the selector's range set directly: the parser refuses a zero-length +/// range, so a zero-length window can only be handed to the compiler here. +fn with_selector_range(range: Duration) -> EvalStmt { + let mut stmt = eval_stmt("rate(x[5m])"); + let PromExpr::Call(call) = &mut stmt.expr else { + unreachable!("`rate(x[5m])` parses to a call"); + }; + let PromExpr::MatrixSelector(selector) = &mut *call.args.args[0] else { + unreachable!("`rate(x[5m])`'s argument parses to a range selector"); + }; + selector.range = range; + stmt +} + +/// The window at the root of `tree`, which is the only shape `compile` produces. +fn root_window(tree: &NativeTree) -> (&NativeNode, &BoundWindow) { + let NativeExpr::Window { input, op } = &tree.root().expr else { + panic!("the root is not a window: {:?}", tree.root().expr); + }; + (input, op) +} + +/// `rate(x[5m])` becomes a window over the raw input, on the statement's grid. +#[test] +fn a_rate_over_a_selector_becomes_a_window_over_raw_input() { + // `compile` returns `NativeTree::try_new`'s result, so unwrapping is the validation. + let tree = compile( + &eval_stmt("rate(x[5m])"), + raw_schema(), + SeriesOrdering::KeyThenTime, + ) + .unwrap(); + + let NativeExpr::Window { input, op } = &tree.root().expr else { + panic!("the root is not a window: {:?}", tree.root().expr); + }; + assert_eq!(op.function, RangeFunction::Rate); + assert_eq!(op.window.range_ms, 300_000); + assert_eq!(op.window.offset_ms, 0); + assert_eq!(op.window.anchor_ms, None); + assert!(op.input_grid.is_none(), "raw input has no grid to declare"); + + // The statement's grid: 0, 5s, ..., 100s. + let spec = op.output_grid.spec(); + assert_eq!( + (spec.start_ms, spec.step_ms, spec.len), + (0, 5_000, 21), + "the window does not land on the statement's grid" + ); + + let NativeExpr::Input(bound) = &input.expr else { + panic!("the window's input is not an input: {:?}", input.expr); + }; + assert!( + matches!(&bound.output, NativeType::Samples(schema) if schema.eval_grid.is_none()), + "the input is not raw samples: {:?}", + bound.output + ); + assert_eq!(bound.ordering, SeriesOrdering::KeyThenTime); +} + +/// Every mapped name produces its own kernel; a name that fell through to the same kernel as +/// another would be caught here. +#[test] +fn the_supported_range_functions_map_to_their_kernels() { + let cases = [ + ("rate", RangeFunction::Rate), + ("increase", RangeFunction::Increase), + ("delta", RangeFunction::Delta), + ("irate", RangeFunction::Irate), + ("idelta", RangeFunction::Idelta), + ("avg_over_time", RangeFunction::AvgOverTime), + ("min_over_time", RangeFunction::MinOverTime), + ("max_over_time", RangeFunction::MaxOverTime), + ("sum_over_time", RangeFunction::SumOverTime), + ("count_over_time", RangeFunction::CountOverTime), + ("last_over_time", RangeFunction::LastOverTime), + ("present_over_time", RangeFunction::PresentOverTime), + ("stddev_over_time", RangeFunction::StddevOverTime), + ("stdvar_over_time", RangeFunction::StdvarOverTime), + ("resets", RangeFunction::Resets), + ("changes", RangeFunction::Changes), + ("deriv", RangeFunction::Deriv), + ]; + + for (name, kernel) in cases { + let tree = compile( + &eval_stmt(&format!("{name}(x[1m])")), + raw_schema(), + SeriesOrdering::KeyThenTime, + ) + .unwrap(); + let NativeExpr::Window { op, .. } = &tree.root().expr else { + panic!( + "`{name}` did not compile to a window: {:?}", + tree.root().expr + ); + }; + assert_eq!(op.function, kernel, "`{name}` produced the wrong kernel"); + assert_eq!(op.window.range_ms, 60_000, "`{name}` lost its window"); + } +} + +/// The numbers a tree is made of, at the edges: a span the step does not divide, offsets in either +/// direction, ranges that cannot be a window, and an ordering the scan did not default to. +#[test] +fn the_numeric_edges_of_a_statement_are_bound_as_given() { + /// What a row asserts about the tree `compile` returns. + enum Expected { + /// The statement's grid, by its start, step and length. + Grid { step_ms: i64, len: u64 }, + /// The window's offset, in milliseconds. + Offset(i64), + /// The input's ordering. + Ordering(SeriesOrdering), + /// The query is refused. + Rejected(Rejection), + } + + /// How a refused query is reported. + enum Rejection { + Plan, + NotImplemented, + } + + let cases = [ + // 100s at 7s per step is 14 whole steps and a remainder: the grid keeps the last point + // that does not pass the end, so the remainder is not a point. + ( + "a span the step does not divide", + EvalStmt { + end: UNIX_EPOCH + Duration::from_secs(100), + interval: Duration::from_secs(7), + ..eval_stmt("rate(x[5m])") + }, + SeriesOrdering::KeyThenTime, + Expected::Grid { + step_ms: 7_000, + len: 15, + }, + ), + // The offset's sign is what decides whether the window reads earlier or later samples. + ( + "a positive offset", + eval_stmt("rate(x[5m] offset 1m)"), + SeriesOrdering::KeyThenTime, + Expected::Offset(60_000), + ), + ( + "a negative offset", + eval_stmt("rate(x[5m] offset -1m)"), + SeriesOrdering::KeyThenTime, + Expected::Offset(-60_000), + ), + // A selector that selects nothing, and one whose length no millisecond count can hold. + ( + "a zero-length range", + with_selector_range(Duration::ZERO), + SeriesOrdering::KeyThenTime, + Expected::Rejected(Rejection::Plan), + ), + ( + "a range wider than i64 milliseconds", + eval_stmt("rate(x[4294967295y])"), + SeriesOrdering::KeyThenTime, + Expected::Rejected(Rejection::Plan), + ), + // The ordering a scan guarantees is recorded on the input rather than dropped. + ( + "a non-default ordering", + eval_stmt("rate(x[5m])"), + SeriesOrdering::Interleaved, + Expected::Ordering(SeriesOrdering::Interleaved), + ), + // A shape outside the subset is refused for its shape, whatever its timing: the statement + // range of an unsupported query is not read, so it cannot turn a refusal into a plan error. + ( + "an unsupported shape with an inverted range", + EvalStmt { + end: UNIX_EPOCH, + start: UNIX_EPOCH + Duration::from_secs(100), + ..eval_stmt("x + 1") + }, + SeriesOrdering::KeyThenTime, + Expected::Rejected(Rejection::NotImplemented), + ), + ]; + + for (case, stmt, ordering, expected) in cases { + match (expected, &compile(&stmt, raw_schema(), ordering)) { + (Expected::Rejected(rejection), Err(error)) => { + let as_expected = match rejection { + Rejection::Plan => matches!(error, DataFusionError::Plan(_)), + Rejection::NotImplemented => { + matches!(error, DataFusionError::NotImplemented(_)) + } + }; + assert!( + as_expected, + "`{case}` was rejected with the wrong kind of error: {error}" + ); + } + (Expected::Rejected(_), Ok(_)) => panic!("`{case}` compiled, and it should not have"), + (_, Err(error)) => panic!("`{case}` did not compile: {error}"), + (Expected::Grid { step_ms, len }, Ok(tree)) => { + let (_, op) = root_window(tree); + let spec = op.output_grid.spec(); + assert_eq!( + (spec.start_ms, spec.step_ms, spec.len), + (0, step_ms, len), + "`{case}` did not land on the statement's grid" + ); + } + (Expected::Offset(offset_ms), Ok(tree)) => { + let (_, op) = root_window(tree); + assert_eq!( + op.window.offset_ms, offset_ms, + "`{case}` lost the offset's sign" + ); + } + (Expected::Ordering(want), Ok(tree)) => { + let (input, _) = root_window(tree); + let NativeExpr::Input(bound) = &input.expr else { + panic!("`{case}`'s window has no input: {:?}", input.expr); + }; + assert_eq!( + bound.ordering, want, + "`{case}` dropped the caller's ordering" + ); + } + } + } +} + +/// A shape outside the subset is refused, and the error says what was found so the query can be +/// rewritten rather than guessed at. +#[test] +fn an_unsupported_shape_is_rejected_and_names_what_it_found() { + let cases = [ + // A bare selector reads every sample; there is no window to bind. + ("x", "the expression `x`"), + ("x + 1", "the expression `x + 1`"), + ("sum(x)", "the expression `sum(x)`"), + ("x[5m:]", "the expression `x[5m:]`"), + // Nested shapes are refused by the argument check, not skipped over. A subquery is the + // reachable case of an argument that is not a range selector: the parser type-checks + // function arguments, so `rate(x)` never gets past parsing. + ( + "rate(x[5m:])", + "a call to `rate` whose argument is `x[5m:]`", + ), + // A function with no kernel, whether or not it takes a constant argument. + ( + "quantile_over_time(0.9, x[5m])", + "a call to `quantile_over_time`", + ), + ( + "absent(x)", + "a call to `absent`, which has no native range kernel", + ), + // An anchored window is step-invariant, which the native model cannot replay yet. + ("rate(x[5m] @ 100)", "`@`-anchored selector"), + ]; + + for (query, named) in cases { + let error = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime) + .expect_err(&format!("`{query}` compiled, and it should not have")); + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "`{query}` did not report NotImplemented: {error}" + ); + let message = error.to_string(); + assert!( + message.contains(named), + "`{query}` did not name `{named}`: {message}" + ); + assert!( + message.contains("rate(x[5m])"), + "`{query}` did not quote the supported shape: {message}" + ); + } +} + +/// The display of a compiled tree, checked as a whole so the compiler and the display cannot drift +/// apart: a wrong grid, kernel or nesting shows up on a line someone would read. +#[test] +fn the_display_of_a_compiled_tree_is_the_tree() { + let tree = compile( + &eval_stmt("rate(x[5m])"), + raw_schema(), + SeriesOrdering::KeyThenTime, + ) + .unwrap(); + + assert_eq!( + tree.to_string(), + [ + "NativeTree", + " root Window rate [300000ms] offset 0 anchor - on grid 0/5000x21", + " input Input raw samples", + ] + .join("\n") + ); +} From 457d3a811c041e15a865944c4dfb448bd76258bb Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 00:59:11 +0800 Subject: [PATCH 09/17] fix(promql): strip parentheses the native compiler does not read through Parentheses group; they say nothing about the expression inside them, so `(rate(x[5m]))` asks for exactly what `rate(x[5m])` asks for. The compiler matched the bare shape only and refused the parenthesised one as NotImplemented, rejecting a statement on how it was typed rather than on what it means. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/query/src/promql/native_compile.rs | 16 ++++++++++-- src/query/src/promql/native_compile/tests.rs | 27 ++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index 4268f87ad82..af069c3a685 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -58,7 +58,7 @@ pub fn compile( input: Arc, ordering: SeriesOrdering, ) -> Result { - let PromExpr::Call(Call { func, args }) = &stmt.expr else { + let PromExpr::Call(Call { func, args }) = unparen(&stmt.expr) else { return Err(not_implemented(&format!("the expression `{}`", stmt.expr))); }; let Some(function) = range_function(func.name) else { @@ -74,7 +74,7 @@ pub fn compile( args.args.len() ))); }; - let PromExpr::MatrixSelector(MatrixSelector { vs, range }) = argument.as_ref() else { + let PromExpr::MatrixSelector(MatrixSelector { vs, range }) = unparen(argument) else { return Err(not_implemented(&format!( "a call to `{}` whose argument is `{}`", func.name, argument @@ -228,6 +228,18 @@ fn range_function(name: &str) -> Option { } } +/// The expression a parenthesised one wraps, however many parentheses were written. +/// +/// Parentheses group, so they say nothing about the expression inside them: `rate((x[5m]))` asks +/// for exactly what `rate(x[5m])` asks for. Refusing it would reject a statement on the way it was +/// typed rather than on what it means. +fn unparen(mut expr: &PromExpr) -> &PromExpr { + while let PromExpr::Paren(paren) = expr { + expr = &paren.expr; + } + expr +} + /// A rejection of a shape outside [`SUPPORTED`]. fn not_implemented(found: &str) -> DataFusionError { DataFusionError::NotImplemented(format!( diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index b30a4e5be36..95179fa0996 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -349,3 +349,30 @@ fn the_display_of_a_compiled_tree_is_the_tree() { .join("\n") ); } + +/// Parentheses group; they do not change what a statement asks for. A compiler that refused them +/// would reject a query on how it was typed rather than on what it means, and a statement written +/// with them is otherwise exactly the shape the compiler accepts. +#[test] +fn parentheses_around_the_accepted_shape_are_transparent() { + let bare = compile( + &eval_stmt("rate(x[5m])"), + raw_schema(), + SeriesOrdering::KeyThenTime, + ) + .unwrap(); + for query in [ + "(rate(x[5m]))", + "rate((x[5m]))", + "rate(((x[5m])))", + "((rate((x[5m]))))", + ] { + let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); + assert_eq!( + tree.to_string(), + bare.to_string(), + "`{query}` did not compile to the tree `rate(x[5m])` does" + ); + } +} From 7ba47913a24532a796471eda15e1a877e94e3629 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:32:06 +0800 Subject: [PATCH 10/17] fix(promql): refuse an ordering a window cannot consume, and stop claiming an executor that does not exist `compile` recorded the scan's ordering without checking it, so `compile(rate(x[5m]), schema, Interleaved)` built a tree that `validate` accepted and the range evaluator was guaranteed to reject at run time: it reads one series to its last chunk before the next. The ordering is refused where it is declared now, and the tree's own window check is the backstop. The tree carries no metric name or matchers, so the contract on `input` decides correctness and was nowhere written: matchers, `__field__` among them, have to be applied before `input` is bound, and `input.fields` is the post-`__field__` set. The display marked a hand-written list of nodes "(no executor)". No executor exists at this point in the stack, so `Window` and `Map` read as runnable while `Instant` was marked as not, although `select_instants` runs in production. The marker is gone; every line reads as the node it is and claims nothing about whether it could run. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/display.rs | 27 ++---------- src/promql/src/native/display/tests.rs | 20 ++++----- src/query/src/promql/native_compile.rs | 44 ++++++++++++++++---- src/query/src/promql/native_compile/tests.rs | 18 ++++++-- 4 files changed, 61 insertions(+), 48 deletions(-) diff --git a/src/promql/src/native/display.rs b/src/promql/src/native/display.rs index b61493b87b2..928e00e6ee9 100644 --- a/src/promql/src/native/display.rs +++ b/src/promql/src/native/display.rs @@ -16,8 +16,8 @@ //! //! The position a node is shown at is derived by [`metrics::walk`], the same traversal that names //! the node's metrics, so a node cannot be shown at one place and measured at another. The -//! display is an observation of a compiled tree: it runs nothing, and a node whose operation has -//! no executor says so instead of reading like an operation that will happen. +//! display is an observation of a compiled tree: it runs nothing, and every line reads as the node +//! it is, making no claim about whether that node could run. use std::fmt::{self, Write}; use std::sync::Arc; @@ -36,9 +36,6 @@ use crate::vector_match::{BinaryOp, Cardinality, MatchingLabels}; /// The header line of every tree. const HEADER: &str = "NativeTree"; -/// What a node without an executor is marked with, so its line does not read like a run. -const NO_EXECUTOR: &str = " (no executor)"; - /// How deep `path` is: the root is at depth zero, its input at one. fn depth(path: &NodePath) -> usize { path.as_str().matches('.').count() @@ -247,27 +244,9 @@ fn kind(expr: &NativeExpr) -> &'static str { } } -/// Whether the node's operation has an executor, so its line may read like something that runs. -fn has_executor(expr: &NativeExpr) -> bool { - matches!( - expr, - NativeExpr::Input(_) | NativeExpr::Window { .. } | NativeExpr::Map { .. } - ) -} - /// The line a node is shown as, without its indentation. fn line(node: &NativeNode, path: &NodePath) -> String { - format!( - "{} {} {}{}", - name(path), - kind(&node.expr), - describe(node), - if has_executor(&node.expr) { - "" - } else { - NO_EXECUTOR - } - ) + format!("{} {} {}", name(path), kind(&node.expr), describe(node)) } impl fmt::Display for NativeTree { diff --git a/src/promql/src/native/display/tests.rs b/src/promql/src/native/display/tests.rs index 45722028fb8..2c30ab6cb21 100644 --- a/src/promql/src/native/display/tests.rs +++ b/src/promql/src/native/display/tests.rs @@ -235,19 +235,17 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() { ); } -/// A kind with no executor says so, so its line is not read as an operation that will run. +/// A leaf kind renders what it holds, whether or not anything could run it: the line names the +/// node it is and makes no claim about executability. #[test] -fn a_kind_without_an_executor_says_so() { +fn a_scalar_and_an_instant_line_show_what_they_hold() { let out = grid(0, 60_000, 4); let scalar = NativeNode { expr: NativeExpr::Scalar(BoundScalar { value: 2.0 }), output: NativeType::Scalar(Arc::clone(&out)), }; let tree = NativeTree::try_new(scalar).unwrap(); - assert_eq!( - tree.to_string(), - shown(&["NativeTree", " root Scalar 2 (no executor)"]) - ); + assert_eq!(tree.to_string(), shown(&["NativeTree", " root Scalar 2"])); let instant = NativeNode { expr: NativeExpr::Instant { @@ -265,14 +263,14 @@ fn a_kind_without_an_executor_says_so() { tree.to_string(), shown(&[ "NativeTree", - " root Instant lookback 300000ms offset 60000 on grid 0/60000x4 (no executor)", + " root Instant lookback 300000ms offset 60000 on grid 0/60000x4", " input Input raw samples", ]) ); } /// An aggregate and a binary operation name the binding they were compiled with, which is what -/// makes the line worth reading once they have executors. +/// makes the line worth reading. #[test] fn an_aggregate_and_a_binary_name_their_binding() { let out = grid(0, 60_000, 4); @@ -299,7 +297,7 @@ fn an_aggregate_and_a_binary_name_their_binding() { tree.to_string(), shown(&[ "NativeTree", - " root Aggregate sum by [job] complete (no executor)", + " root Aggregate sum by [job] complete", " input Window rate [300000ms] offset 0 anchor - on grid 0/60000x4", " input Input raw samples", ]) @@ -335,8 +333,8 @@ fn an_aggregate_and_a_binary_name_their_binding() { tree.to_string(), shown(&[ "NativeTree", - " root Binary + ignoring [] one-to-one (no executor)", - " left Scalar 2 (no executor)", + " root Binary + ignoring [] one-to-one", + " left Scalar 2", " right Window rate [300000ms] offset 0 anchor - on grid 0/60000x4", " input Input raw samples", ]) diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index af069c3a685..89fbe95d611 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -50,9 +50,26 @@ const SUPPORTED: &str = "`([])`, for example `r /// Compiles `stmt` into a tree that reads `input` and folds it with the statement's one window. /// -/// `input` is the raw series schema the caller bound from the table: the AST alone cannot produce -/// it, because it says which series the query reads but not which fields they carry. `ordering` is -/// what the caller's scan guarantees, and the tree records it rather than assuming one. +/// `input` is the raw series schema the caller bound from the table, and the caller has to apply the +/// selector's matchers before binding it: `__field__`, `__schema__` and `__database__` select rows +/// and fields the same way they do in the existing planner, and the AST cannot restate that +/// afterwards. `input.fields` is therefore the post-`__field__` field set, not the table's; a caller +/// that binds every field of the table instead compiles a different, wrong window, because +/// `rate(x{__field__="a"}[5m])` over fields `[a, b]` would fold two fields where the planner folds +/// one. +/// +/// `ordering` is what the caller's scan guarantees, and the tree records it rather than assuming +/// one. Only `Contiguous` and `KeyThenTime` are accepted: a native range window consumes one series +/// to its last chunk before the next, so chunks of different series may not interleave, and an +/// `Interleaved` declaration is refused here — which is where the refusal belongs, since a tree that +/// declares it under a window cannot be built by this compiler at all. [`NativeTree::validate`]'s +/// window branch checks the same thing, so if both land this refusal comes first and the tree check +/// is a backstop for a tree built some other way. +/// +/// The tree carries no metric name and no matchers, so `rate(x{job="a"}[5m])` and `rate(y[5m])` +/// compile to identical trees, and an `EXPLAIN` built on this display cannot tell them apart. That +/// is fine while a tree has one selector; a tree with two inputs will need each `Input` to name its +/// selector. pub fn compile( stmt: &EvalStmt, input: Arc, @@ -80,14 +97,23 @@ pub fn compile( func.name, argument ))); }; - // An `@`-anchored selector is step-invariant: every step folds the same samples, which the - // native model would have to replay over the grid. That replay is not part of this subset, so - // the anchor is refused rather than dropped. + // A native range window reads one series to its last chunk before it reads the next, so raw + // samples whose chunks of different series interleave cannot be folded by it. The declaration + // is refused here rather than recorded onto an input the tree is built over and fails on. + if ordering == SeriesOrdering::Interleaved { + return Err(not_implemented( + "raw samples whose series interleave, which this compiler cannot consume: its range \ + window reads one series to its last chunk before the next, so chunks of different \ + series may not interleave", + )); + } + // An `@`-anchored selector fixes its window instead of following the evaluation grid, which the + // native model binds as an absolute millisecond anchor. Resolving `@` into that value is not + // part of this subset, so the anchor is refused rather than dropped. if vs.at.is_some() { return Err(not_implemented(&format!( - "a call to `{}` over an `@`-anchored selector, whose window is fixed rather than \ - following the evaluation grid and would need the step-invariant replay the native \ - compiler does not implement yet", + "a call to `{}` over an `@`-anchored selector, whose anchor is not resolved into an \ + absolute millisecond value yet and so cannot be bound", func.name ))); } diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index 95179fa0996..c0917236f41 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -212,12 +212,21 @@ fn the_numeric_edges_of_a_statement_are_bound_as_given() { SeriesOrdering::KeyThenTime, Expected::Rejected(Rejection::Plan), ), - // The ordering a scan guarantees is recorded on the input rather than dropped. + // A range window reads one series to its last chunk before the next, so a scan whose + // chunks of different series interleave is refused instead of recorded onto an input the + // window would fail on. ( - "a non-default ordering", + "an interleaved ordering, which a window cannot consume to its last chunk", eval_stmt("rate(x[5m])"), SeriesOrdering::Interleaved, - Expected::Ordering(SeriesOrdering::Interleaved), + Expected::Rejected(Rejection::NotImplemented), + ), + // A supported ordering is recorded on the input rather than dropped. + ( + "a non-default ordering a window can consume", + eval_stmt("rate(x[5m])"), + SeriesOrdering::Contiguous, + Expected::Ordering(SeriesOrdering::Contiguous), ), // A shape outside the subset is refused for its shape, whatever its timing: the statement // range of an unsupported query is not read, so it cannot turn a refusal into a plan error. @@ -305,7 +314,8 @@ fn an_unsupported_shape_is_rejected_and_names_what_it_found() { "absent(x)", "a call to `absent`, which has no native range kernel", ), - // An anchored window is step-invariant, which the native model cannot replay yet. + // An anchored selector needs its anchor resolved to an absolute millisecond value, which + // this compiler does not do yet. ("rate(x[5m] @ 100)", "`@`-anchored selector"), ]; From 3bedb09d6134a692efc874c61cefd35393e8a902 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:23:10 +0800 Subject: [PATCH 11/17] fix(promql): render a grouping as the shape it was bound as MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tree now binds an aggregate's grouping as `Grouping::{By, Without}` (#9723), so `label_list(&op.group)` no longer type-checks: the argument is a `Grouping`, and the function takes `&[Arc]`. This is production code, not a test helper, so the merged stack would not build. Rendering on the `By`/ `Without` shape fixes more than the type error: both were printed as `by [... ]`, which would show `by(job)` and `without(job)` — two different queries over the same label list — as the same query. A `without` aggregate now reads `sum without [job] complete`, and `a_without_grouping_does_not_read_as_by` pins it. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/src/native/display.rs | 13 ++++++-- src/promql/src/native/display/tests.rs | 42 ++++++++++++++++++++++++-- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/src/promql/src/native/display.rs b/src/promql/src/native/display.rs index 928e00e6ee9..7e0e82c2b5e 100644 --- a/src/promql/src/native/display.rs +++ b/src/promql/src/native/display.rs @@ -28,7 +28,8 @@ use datatypes::series::time::EvalGrid; use crate::map::MathOp; use crate::native::metrics::{self, NodePath}; use crate::native::plan::{ - AggregateKind, AggregateStage, BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, + AggregateKind, AggregateStage, BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, + NativeType, }; use crate::range_eval::RangeFunction; use crate::vector_match::{BinaryOp, Cardinality, MatchingLabels}; @@ -102,11 +103,17 @@ fn describe(node: &NativeNode) -> String { ops.join(", ") } NativeExpr::Aggregate { op, .. } => format!( - "{} by [{}] {}", + "{} {} [{}] {}", match op.kind { AggregateKind::Sum => "sum", }, - label_list(&op.group), + match &op.group { + Grouping::By(_) => "by", + Grouping::Without(_) => "without", + }, + label_list(match &op.group { + Grouping::By(labels) | Grouping::Without(labels) => labels, + }), match op.stage { AggregateStage::Complete => "complete", AggregateStage::Partial => "partial", diff --git a/src/promql/src/native/display/tests.rs b/src/promql/src/native/display/tests.rs index 2c30ab6cb21..8166bad3c98 100644 --- a/src/promql/src/native/display/tests.rs +++ b/src/promql/src/native/display/tests.rs @@ -20,7 +20,7 @@ use datatypes::series::time::{EvalGrid, GridSpec}; use super::super::plan::{ AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar, - BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, + BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, NativeType, }; use crate::map::MathOp; use crate::range_eval::{RangeFunction, RangeWindow}; @@ -286,7 +286,7 @@ fn an_aggregate_and_a_binary_name_their_binding() { )), op: BoundAggregate { kind: AggregateKind::Sum, - group: Arc::new(["job".into()]), + group: Grouping::By(Arc::new(["job".into()])), stage: AggregateStage::Complete, }, }, @@ -340,3 +340,41 @@ fn an_aggregate_and_a_binary_name_their_binding() { ]) ); } + +/// A `without` grouping reads as `without [...]`, not as `by [...]`. +/// +/// The two are different queries over the same label list: `by(job)` keeps `job` and drops the +/// rest, `without(job)` drops `job` and keeps the rest. A rendering that spelled both `by` would +/// show two different queries as one. +#[test] +fn a_without_grouping_does_not_read_as_by() { + let out = grid(0, 60_000, 4); + let aggregate = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(window_over( + raw_input(), + RangeFunction::Rate, + 300_000, + 0, + None, + Arc::clone(&out), + )), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Grouping::Without(Arc::new(["job".into()])), + stage: AggregateStage::Complete, + }, + }, + output: evaluated(Arc::clone(&out)), + }; + let tree = NativeTree::try_new(aggregate).unwrap(); + assert_eq!( + tree.to_string(), + shown(&[ + "NativeTree", + " root Aggregate sum without [job] complete", + " input Window rate [300000ms] offset 0 anchor - on grid 0/60000x4", + " input Input raw samples", + ]) + ); +} From 2dfb66b3256db9894603cee2012f65588659dc2a Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:06:40 +0800 Subject: [PATCH 12/17] feat(promql): compile a bare selector and an anchored range window The compiler refused a bare instant selector and any `@` anchor, so the two shapes an ordinary query starts from could not reach the tree. It now binds a selector's lookback, offset and output grid into an instant node, and resolves `@ 1234`, `@ start()` and `@ end()` into the millisecond anchor a range window already carries, bound apart from the offset so a shift and an anchor are not folded into one number. A bare selector's own anchor stays refused: an instant node binds a lookback, an offset and a grid and has no field to anchor one. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/query/src/promql/native_compile.rs | 130 +++++++++++--- src/query/src/promql/native_compile/tests.rs | 171 ++++++++++++++++++- 2 files changed, 269 insertions(+), 32 deletions(-) diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index 89fbe95d611..1d5a0801e84 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -16,20 +16,24 @@ //! //! This is the front half of the native evaluation model: it reads the parsed statement and writes //! down what it means as bound nodes. It runs nothing, and nothing calls it yet, so the subset it -//! accepts is deliberately one shape: +//! accepts is deliberately two shapes: //! //! ```text +//! e.g. x //! ([]) e.g. rate(x[5m]) //! ``` //! -//! which becomes `Input` (raw samples) → `Window` (the range function over the statement's grid). -//! Everything else is a [`DataFusionError::NotImplemented`] that names what was found and quotes -//! the shape above, because rejecting a query the compiler does not understand is the only honest -//! alternative to compiling it into something else. +//! which become `Input` (raw samples) → `Instant` (the last sample within the statement's lookback) +//! and `Input` (raw samples) → `Window` (the range function over the statement's grid). A selector +//! may carry `offset` in either shape and, in the window shape, an `@` anchor. Everything else is a +//! [`DataFusionError::NotImplemented`] that names what was found and quotes the shapes above, +//! because rejecting a query the compiler does not understand is the only honest alternative to +//! compiling it into something else. //! -//! The statement's grid and the selector's window are the only numbers derived here; the legality -//! of the tree is not checked here. [`NativeTree::try_new`] is the single authority on that, so a -//! node added later cannot be legal in one place and illegal in another. +//! The statement's grid, the selector's lookback, window, offset and anchor are the only numbers +//! derived here; the legality of the tree is not checked here. [`NativeTree::try_new`] is the +//! single authority on that, so a node added later cannot be legal in one place and illegal in +//! another. use std::sync::Arc; @@ -38,17 +42,21 @@ use datatypes::series::SeriesOrdering; use datatypes::series::samples::SeriesSchema; use datatypes::series::time::{EvalGrid, GridSpec}; use promql::native::plan::{ - BoundInput, BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, + BoundInput, BoundInstant, BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, }; use promql::range_eval::{RangeFunction, RangeWindow}; -use promql_parser::parser::{Call, EvalStmt, Expr as PromExpr, MatrixSelector, Offset}; +use promql_parser::parser::{ + AtModifier, Call, EvalStmt, Expr as PromExpr, MatrixSelector, Offset, VectorSelector, +}; use crate::promql::label_values::signed_millis_since_epoch; -/// The one shape this compiler accepts, quoted in every rejection. -const SUPPORTED: &str = "`([])`, for example `rate(x[5m])`"; +/// The shapes this compiler accepts, quoted in every rejection. +const SUPPORTED: &str = "a bare selector or `([])`, for example \ + `x` or `rate(x[5m])`"; -/// Compiles `stmt` into a tree that reads `input` and folds it with the statement's one window. +/// Compiles `stmt` into a tree that reads `input` and either selects from it or folds it with the +/// statement's one window. /// /// `input` is the raw series schema the caller bound from the table, and the caller has to apply the /// selector's matchers before binding it: `__field__`, `__schema__` and `__database__` select rows @@ -75,6 +83,10 @@ pub fn compile( input: Arc, ordering: SeriesOrdering, ) -> Result { + // A bare selector is the other shape: an instant selection over the same raw input. + if let PromExpr::VectorSelector(selector) = unparen(&stmt.expr) { + return instant_selection(stmt, selector, input, ordering); + } let PromExpr::Call(Call { func, args }) = unparen(&stmt.expr) else { return Err(not_implemented(&format!("the expression `{}`", stmt.expr))); }; @@ -107,18 +119,11 @@ pub fn compile( series may not interleave", )); } - // An `@`-anchored selector fixes its window instead of following the evaluation grid, which the - // native model binds as an absolute millisecond anchor. Resolving `@` into that value is not - // part of this subset, so the anchor is refused rather than dropped. - if vs.at.is_some() { - return Err(not_implemented(&format!( - "a call to `{}` over an `@`-anchored selector, whose anchor is not resolved into an \ - absolute millisecond value yet and so cannot be bound", - func.name - ))); - } + // An `@` anchor is step-invariant: every step folds the same samples, which the window's + // `anchor_ms` tells `RangeEvaluator` to replay over the grid. let range_ms = range_millis(range.as_millis())?; let offset_ms = selector_offset_ms(&vs.offset)?; + let anchor_ms = selector_anchor_ms(&vs.at, stmt)?; // The grid is the last thing built: a query refused above, or a window that cannot exist, // never pays for a grid nothing would read. let output_grid = statement_grid(stmt)?; @@ -148,8 +153,7 @@ pub fn compile( window: RangeWindow { range_ms, offset_ms, - // Only `@` sets an anchor, and an anchored selector is rejected above. - anchor_ms: None, + anchor_ms, }, // The input is raw samples, so it has no grid of its own. input_grid: None, @@ -160,6 +164,58 @@ pub fn compile( }) } +/// Compiles a bare selector into an instant selection over the raw input. +/// +/// The lookback, the offset and the grid are the whole of an instant selection: it reports the last +/// sample at or before each grid point, within the statement's lookback. +fn instant_selection( + stmt: &EvalStmt, + selector: &VectorSelector, + input: Arc, + ordering: SeriesOrdering, +) -> Result { + // An `@` anchor is bound on a range window, which carries `anchor_ms`; an instant selection has + // no such field, so the anchor has nowhere to go. Refusing it is the only alternative to + // dropping it, which would silently select around every grid point instead of one anchor. + if selector.at.is_some() { + return Err(not_implemented(&format!( + "the `@`-anchored selector `{selector}`, whose anchor the instant selection node has \ + no field for: an instant selection binds a lookback, an offset and a grid, while \ + anchoring is bound on a range window, as in `rate(x[5m] @ 1234)`" + ))); + } + let lookback_ms = lookback_millis(stmt.lookback_delta.as_millis())?; + let offset_ms = selector_offset_ms(&selector.offset)?; + let output_grid = statement_grid(stmt)?; + + // An instant selection reports one value per input field, so the layout is the input's. + let output = NativeType::Samples(Arc::new(SeriesSchema { + fields: Arc::clone(&input.fields), + eval_grid: Some(Arc::clone(&output_grid)), + })); + + // One allocation shared by the binding and the node's output, as in the window shape. + let raw = NativeType::Samples(input); + + NativeTree::try_new(NativeNode { + expr: NativeExpr::Instant { + input: Box::new(NativeNode { + expr: NativeExpr::Input(BoundInput { + output: raw.clone(), + ordering, + }), + output: raw, + }), + op: BoundInstant { + lookback_ms, + offset_ms, + output_grid, + }, + }, + output, + }) +} + /// The grid the statement is evaluated on: `(end - start) / step + 1` points, the last of which /// does not pass `end`. fn statement_grid(stmt: &EvalStmt) -> Result> { @@ -199,6 +255,30 @@ fn range_millis(range: u128) -> Result { Ok(range_ms) } +/// The statement's lookback in milliseconds, which is how far back an instant selection reads. +fn lookback_millis(lookback: u128) -> Result { + millis(lookback).ok_or_else(|| { + DataFusionError::Plan(format!( + "the statement's lookback of {lookback}ms is out of range" + )) + }) +} + +/// The selector's `@` anchor in milliseconds since the Unix epoch, or `None` when it has none. +/// +/// `start()` and `end()` stay symbolic in the AST, because only the statement knows which evaluation +/// range they name, so they are resolved against `stmt.start` and `stmt.end` here. The offset is not +/// folded in: [`RangeWindow`] keeps anchor and offset apart and ends the window at +/// `anchor_ms - offset_ms` at run time. +fn selector_anchor_ms(at: &Option, stmt: &EvalStmt) -> Result> { + match at { + None => Ok(None), + Some(AtModifier::Start) => Ok(Some(signed_millis_since_epoch(stmt.start)?)), + Some(AtModifier::End) => Ok(Some(signed_millis_since_epoch(stmt.end)?)), + Some(AtModifier::At(time)) => Ok(Some(signed_millis_since_epoch(*time)?)), + } +} + /// The selector's offset in milliseconds; positive reads earlier samples. fn selector_offset_ms(offset: &Option) -> Result { let Some(offset) = offset else { diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index c0917236f41..9fcc4194b9a 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -18,7 +18,9 @@ use std::time::{Duration, UNIX_EPOCH}; use datafusion::error::DataFusionError; use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; -use promql::native::plan::{BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType}; +use promql::native::plan::{ + BoundInstant, BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, +}; use promql::range_eval::RangeFunction; use promql_parser::parser::{EvalStmt, Expr as PromExpr}; @@ -59,7 +61,7 @@ fn with_selector_range(range: Duration) -> EvalStmt { stmt } -/// The window at the root of `tree`, which is the only shape `compile` produces. +/// The window at the root of `tree`, for the range-function shape. fn root_window(tree: &NativeTree) -> (&NativeNode, &BoundWindow) { let NativeExpr::Window { input, op } = &tree.root().expr else { panic!("the root is not a window: {:?}", tree.root().expr); @@ -67,6 +69,17 @@ fn root_window(tree: &NativeTree) -> (&NativeNode, &BoundWindow) { (input, op) } +/// The instant selection at the root of `tree`, for the bare-selector shape. +fn root_instant(tree: &NativeTree) -> (&NativeNode, &BoundInstant) { + let NativeExpr::Instant { input, op } = &tree.root().expr else { + panic!( + "the root is not an instant selection: {:?}", + tree.root().expr + ); + }; + (input, op) +} + /// `rate(x[5m])` becomes a window over the raw input, on the statement's grid. #[test] fn a_rate_over_a_selector_becomes_a_window_over_raw_input() { @@ -148,6 +161,145 @@ fn the_supported_range_functions_map_to_their_kernels() { } } +/// `x` becomes an instant selection over the raw input, on the statement's grid, with the +/// statement's lookback and the input's fields. +#[test] +fn a_bare_selector_becomes_an_instant_over_raw_input() { + let input = raw_schema(); + // A lookback the statement chose, so the binding cannot be a default the compiler invented. + let stmt = EvalStmt { + lookback_delta: Duration::from_secs(120), + ..eval_stmt("x") + }; + let tree = compile(&stmt, Arc::clone(&input), SeriesOrdering::KeyThenTime).unwrap(); + + let (input_node, op) = root_instant(&tree); + assert_eq!(op.lookback_ms, 120_000); + assert_eq!(op.offset_ms, 0); + + // The statement's grid: 0, 5s, ..., 100s. + let spec = op.output_grid.spec(); + assert_eq!( + (spec.start_ms, spec.step_ms, spec.len), + (0, 5_000, 21), + "the instant selection does not land on the statement's grid" + ); + + // The output is the input's fields, evaluated on the statement's grid. + let output = tree + .root() + .output + .samples() + .expect("an instant selection produces samples"); + assert!( + Arc::ptr_eq(&output.fields, &input.fields), + "the instant selection did not keep the input's fields" + ); + let output_grid = output + .eval_grid + .as_ref() + .expect("an instant selection produces evaluated values"); + assert!( + Arc::ptr_eq(output_grid, &op.output_grid), + "the output grid is not the bound grid" + ); + + let NativeExpr::Input(bound) = &input_node.expr else { + panic!( + "the instant selection's input is not an input: {:?}", + input_node.expr + ); + }; + assert!( + matches!(&bound.output, NativeType::Samples(schema) if schema.eval_grid.is_none()), + "the input is not raw samples: {:?}", + bound.output + ); + assert_eq!(bound.ordering, SeriesOrdering::KeyThenTime); +} + +/// A bare selector's offset reaches the instant binding with its sign. +#[test] +fn an_offset_on_a_bare_selector_keeps_its_sign() { + let cases = [("x offset 1m", 60_000), ("x offset -1m", -60_000)]; + + for (query, offset_ms) in cases { + let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime).unwrap(); + let (_, op) = root_instant(&tree); + assert_eq!(op.offset_ms, offset_ms, "`{query}` lost the offset's sign"); + assert_eq!(op.lookback_ms, 5_000, "`{query}` lost the lookback"); + } +} + +/// An `@`-anchored bare selector is refused because the instant node has no anchor field, not +/// because anchoring is unsupported: the window shape binds an anchor. +#[test] +fn an_anchored_instant_selector_is_refused_for_the_missing_anchor_field() { + let error = compile( + &eval_stmt("x @ 100"), + raw_schema(), + SeriesOrdering::KeyThenTime, + ) + .expect_err("`x @ 100` compiled, and it should not have"); + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "`x @ 100` did not report NotImplemented: {error}" + ); + let message = error.to_string(); + assert!( + message.contains("whose anchor the instant selection node has no field for"), + "`x @ 100` did not say why its anchor cannot be bound: {message}" + ); +} + +/// A window's `@` anchor is bound as an absolute millisecond timestamp: `start()` and `end()` are +/// the statement's own bounds, and a number is the unix second it names. +#[test] +fn an_anchor_on_a_window_resolves_to_absolute_milliseconds() { + let cases = [ + // `@ `: 1234 is unix second 1234, which is 1_234_000 ms. + ("rate(x[5m] @ 1234)", 1_234_000), + // A sub-second anchor resolves to the millisecond it names. + ("rate(x[5m] @ 1.234)", 1_234), + // The statement here is UNIX_EPOCH..100s, which is what `start()` and `end()` mean. + ("rate(x[5m] @ start())", 0), + ("rate(x[5m] @ end())", 100_000), + ]; + + for (query, anchor_ms) in cases { + let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime).unwrap(); + let (_, op) = root_window(&tree); + assert_eq!( + op.window.anchor_ms, + Some(anchor_ms), + "`{query}` bound the wrong anchor" + ); + assert_eq!(op.window.offset_ms, 0, "`{query}` invented an offset"); + } +} + +/// An anchor and an offset are bound apart: the window ends at `anchor - offset`, which the +/// runtime folds, so both numbers have to survive compilation. +#[test] +fn an_anchor_and_an_offset_are_bound_apart() { + let cases = [ + ("rate(x[5m] @ 1.234 offset 1m)", 1_234, 60_000), + ("rate(x[5m] @ 1234 offset 1m)", 1_234_000, 60_000), + ("rate(x[5m] @ 1.234 offset -1m)", 1_234, -60_000), + ]; + + for (query, anchor_ms, offset_ms) in cases { + let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime).unwrap(); + let (_, op) = root_window(&tree); + assert_eq!( + op.window.anchor_ms, + Some(anchor_ms), + "`{query}` lost the anchor" + ); + assert_eq!(op.window.offset_ms, offset_ms, "`{query}` lost the offset"); + } +} + /// The numbers a tree is made of, at the edges: a span the step does not divide, offsets in either /// direction, ranges that cannot be a window, and an ordering the scan did not default to. #[test] @@ -212,6 +364,16 @@ fn the_numeric_edges_of_a_statement_are_bound_as_given() { SeriesOrdering::KeyThenTime, Expected::Rejected(Rejection::Plan), ), + // An instant selection's lookback is narrowed like every other duration. + ( + "a lookback wider than i64 milliseconds", + EvalStmt { + lookback_delta: Duration::from_millis(u64::MAX), + ..eval_stmt("x") + }, + SeriesOrdering::KeyThenTime, + Expected::Rejected(Rejection::Plan), + ), // A range window reads one series to its last chunk before the next, so a scan whose // chunks of different series interleave is refused instead of recorded onto an input the // window would fail on. @@ -293,8 +455,6 @@ fn the_numeric_edges_of_a_statement_are_bound_as_given() { #[test] fn an_unsupported_shape_is_rejected_and_names_what_it_found() { let cases = [ - // A bare selector reads every sample; there is no window to bind. - ("x", "the expression `x`"), ("x + 1", "the expression `x + 1`"), ("sum(x)", "the expression `sum(x)`"), ("x[5m:]", "the expression `x[5m:]`"), @@ -314,9 +474,6 @@ fn an_unsupported_shape_is_rejected_and_names_what_it_found() { "absent(x)", "a call to `absent`, which has no native range kernel", ), - // An anchored selector needs its anchor resolved to an absolute millisecond value, which - // this compiler does not do yet. - ("rate(x[5m] @ 100)", "`@`-anchored selector"), ]; for (query, named) in cases { From 9b96a186c8552fd3f5c4cbc2cc60f75255cb34c9 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:22:22 +0800 Subject: [PATCH 13/17] test(promql): tell `@ end()` apart from the last grid point The anchor test used a statement ending at 100s on a 5s step, so its last grid point was also 100s: binding `end()` to the last grid point instead of to the statement's own end would have passed. The end is now a parameter of the statement helper, and a statement ending at 103s pins the two apart, asserting both the anchor and that the grid still stops at 100s. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/query/src/promql/native_compile/tests.rs | 40 +++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index 9fcc4194b9a..59cac16f6df 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -38,10 +38,18 @@ fn raw_schema() -> Arc { /// A statement over 100 seconds in 5-second steps, which is 21 grid points. fn eval_stmt(query: &str) -> EvalStmt { + eval_stmt_over(query, Duration::from_secs(100)) +} + +/// The statement `query` over `UNIX_EPOCH..=end`, on a 5s grid. +/// +/// The end is a parameter because a grid stops before an end it does not land on, which is the only +/// way `end()` and the last grid point can be told apart. +fn eval_stmt_over(query: &str, end: Duration) -> EvalStmt { EvalStmt { expr: promql_parser::parser::parse(query).unwrap(), start: UNIX_EPOCH, - end: UNIX_EPOCH + Duration::from_secs(100), + end: UNIX_EPOCH + end, interval: Duration::from_secs(5), lookback_delta: Duration::from_secs(5), } @@ -278,6 +286,36 @@ fn an_anchor_on_a_window_resolves_to_absolute_milliseconds() { } } +/// `end()` is the statement's end, not the last grid point. +/// +/// The grid stops before an end it does not land on, so an end of 103s over a 5s step has its last +/// point at 100s. Binding `end()` to that point instead of to the statement's own end would pass a +/// test whose end is a multiple of the step; here the two numbers differ. +#[test] +fn end_resolves_to_the_statement_end_not_the_last_grid_point() { + let stmt = eval_stmt_over("rate(x[5m] @ end())", Duration::from_secs(103)); + let tree = compile(&stmt, raw_schema(), SeriesOrdering::KeyThenTime).unwrap(); + let (_, op) = root_window(&tree); + assert_eq!( + op.window.anchor_ms, + Some(103_000), + "`@ end()` bound something other than the statement's end" + ); + + // The grid the same statement compiles onto ends at 100s, so the two are not the same number. + let spec = op.output_grid.spec(); + let last_point = spec.start_ms + (spec.len as i64 - 1) * spec.step_ms; + assert_eq!( + last_point, 100_000, + "the test's own grid does not stop before the statement end" + ); + assert_ne!( + op.window.anchor_ms, + Some(last_point), + "`@ end()` bound the last grid point rather than the statement's end" + ); +} + /// An anchor and an offset are bound apart: the window ends at `anchor - offset`, which the /// runtime folds, so both numbers have to survive compilation. #[test] From 52fa3a2e166c2d520d0cdfe9555d985347de9303 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:14:23 +0800 Subject: [PATCH 14/17] docs(promql): write down what an anchored window reads, and cover a pre-epoch anchor An `@`-anchored window reads `(anchor - offset - range, anchor - offset]`, which can lie entirely outside the statement's own range, so whoever binds the scan has to derive it from the window rather than from `stmt.start` and `stmt.end`. A scan bound to the statement alone leaves such a window with no samples, and the query returns empty without an error. That contract was nowhere in the code. The anchor cases only covered non-negative anchors, so a helper that defaulted a pre-epoch anchor to zero would have kept the suite green. `rate(x[5m] @ -1.5)` now pins -1500, which is the `Err(earlier)` branch of the conversion. The `assert_ne!` at the end of the `end()` test was implied by the two equalities above it and could not fail on its own. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/query/src/promql/native_compile.rs | 7 +++++++ src/query/src/promql/native_compile/tests.rs | 8 +++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index 1d5a0801e84..831f10eab6d 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -270,6 +270,13 @@ fn lookback_millis(lookback: u128) -> Result { /// range they name, so they are resolved against `stmt.start` and `stmt.end` here. The offset is not /// folded in: [`RangeWindow`] keeps anchor and offset apart and ends the window at /// `anchor_ms - offset_ms` at run time. +/// +/// An anchor decouples the window's read range from the statement's: it reads +/// `(anchor_ms - offset_ms - range_ms, anchor_ms - offset_ms]`, which for an anchor like `@ 1234` can +/// lie entirely outside `[stmt.start - range_ms, stmt.end]`. Whoever binds the scan therefore has to +/// derive its range from the window's anchor, offset and range rather than from `stmt.start` and +/// `stmt.end`; a scan bound to the statement alone leaves such a window with no samples, and the +/// query silently returns empty instead of failing. fn selector_anchor_ms(at: &Option, stmt: &EvalStmt) -> Result> { match at { None => Ok(None), diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index 59cac16f6df..1918ce3ec2e 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -269,6 +269,9 @@ fn an_anchor_on_a_window_resolves_to_absolute_milliseconds() { ("rate(x[5m] @ 1234)", 1_234_000), // A sub-second anchor resolves to the millisecond it names. ("rate(x[5m] @ 1.234)", 1_234), + // Prometheus allows a pre-epoch anchor: `signed_millis_since_epoch` takes `Err(earlier)`, + // where a `duration_since(UNIX_EPOCH).unwrap_or_default()` helper would silently give 0. + ("rate(x[5m] @ -1.5)", -1_500), // The statement here is UNIX_EPOCH..100s, which is what `start()` and `end()` mean. ("rate(x[5m] @ start())", 0), ("rate(x[5m] @ end())", 100_000), @@ -309,11 +312,6 @@ fn end_resolves_to_the_statement_end_not_the_last_grid_point() { last_point, 100_000, "the test's own grid does not stop before the statement end" ); - assert_ne!( - op.window.anchor_ms, - Some(last_point), - "`@ end()` bound the last grid point rather than the statement's end" - ); } /// An anchor and an offset are bound apart: the window ends at `anchor - offset`, which the From 875efc91cba882e1abab7724410ade80d8cecd19 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Mon, 19 Oct 2026 21:56:52 +0800 Subject: [PATCH 15/17] feat(promql): compile a parameterised range function `quantile_over_time(q, x[r])` now compiles: the quantile is bound as a number literal and the range selector is bound by the same path a function without parameters takes. The two shapes share one binder, so the range, the offset, the anchor and the grid cannot drift between them. The quantile is not range-checked. Prometheus binds any value and the kernel answers `-Infinity` below zero and `+Infinity` above one, so refusing it here would be this compiler inventing a rule the engine does not have. A parameter in parentheses binds the same quantile: the planner already looks through the parentheses when it reads a literal, so a query written `quantile_over_time((0.9), x[5m])` keeps working on this path too. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/query/src/promql/native_compile.rs | 120 +++++++++++-- src/query/src/promql/native_compile/tests.rs | 177 ++++++++++++++++++- 2 files changed, 284 insertions(+), 13 deletions(-) diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index 831f10eab6d..31fc6d69dd4 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -16,11 +16,12 @@ //! //! This is the front half of the native evaluation model: it reads the parsed statement and writes //! down what it means as bound nodes. It runs nothing, and nothing calls it yet, so the subset it -//! accepts is deliberately two shapes: +//! accepts is deliberately three shapes: //! //! ```text -//! e.g. x -//! ([]) e.g. rate(x[5m]) +//! e.g. x +//! ([]) e.g. rate(x[5m]) +//! (, []) e.g. quantile_over_time(0.9, x[5m]) //! ``` //! //! which become `Input` (raw samples) → `Instant` (the last sample within the statement's lookback) @@ -36,6 +37,7 @@ //! another. use std::sync::Arc; +use std::time::Duration; use datafusion::error::{DataFusionError, Result}; use datatypes::series::SeriesOrdering; @@ -46,14 +48,17 @@ use promql::native::plan::{ }; use promql::range_eval::{RangeFunction, RangeWindow}; use promql_parser::parser::{ - AtModifier, Call, EvalStmt, Expr as PromExpr, MatrixSelector, Offset, VectorSelector, + AtModifier, Call, EvalStmt, Expr as PromExpr, MatrixSelector, NumberLiteral, Offset, + VectorSelector, }; use crate::promql::label_values::signed_millis_since_epoch; /// The shapes this compiler accepts, quoted in every rejection. -const SUPPORTED: &str = "a bare selector or `([])`, for example \ - `x` or `rate(x[5m])`"; +const SUPPORTED: &str = "a bare selector, a range function over a selector — \ + `([])` — or a parameterised one, \ + `(, [])`, for example `x`, \ + `rate(x[5m])` or `quantile_over_time(0.9, x[5m])`"; /// Compiles `stmt` into a tree that reads `input` and either selects from it or folds it with the /// statement's one window. @@ -90,19 +95,31 @@ pub fn compile( let PromExpr::Call(Call { func, args }) = unparen(&stmt.expr) else { return Err(not_implemented(&format!("the expression `{}`", stmt.expr))); }; - let Some(function) = range_function(func.name) else { + let Some(signature) = range_signature(func.name) else { return Err(not_implemented(&format!( "a call to `{}`, which has no native range kernel", func.name ))); }; - let [argument] = args.args.as_slice() else { + // The count is the signature's, so the rejection names what this function takes rather than + // what one argument happens to be. + let expected = signature.parameters() + 1; + if args.args.len() != expected { return Err(not_implemented(&format!( - "a call to `{}` with {} argument(s)", + "a call to `{}` with {} argument(s), where it takes {expected}: {}", func.name, - args.args.len() + args.args.len(), + signature.arguments() ))); + } + // The parameters come first and the range selector is last, for both signatures: a function + // without parameters has no `parameters` to read. + let (parameters, selector) = args.args.split_at(signature.parameters()); + let function = match signature { + RangeSignature::Selector(function) => function, + RangeSignature::Scalar(bind) => bind(scalar_parameter(func.name, ¶meters[0])?), }; + let argument = &selector[0]; let PromExpr::MatrixSelector(MatrixSelector { vs, range }) = unparen(argument) else { return Err(not_implemented(&format!( "a call to `{}` whose argument is `{}`", @@ -119,6 +136,22 @@ pub fn compile( series may not interleave", )); } + window_selection(stmt, function, vs, range, input, ordering) +} + +/// Binds `function` over the range selector `vs[range]` into a window over the raw input. +/// +/// Both shapes reach this: the range, the offset, the anchor, the grid and the output are the same +/// whichever function reads them, so a parameterised function only decides *what* folds the window, +/// never *which* window is folded. +fn window_selection( + stmt: &EvalStmt, + function: RangeFunction, + vs: &VectorSelector, + range: &Duration, + input: Arc, + ordering: SeriesOrdering, +) -> Result { // An `@` anchor is step-invariant: every step folds the same samples, which the window's // `anchor_ms` tells `RangeEvaluator` to replay over the grid. let range_ms = range_millis(range.as_millis())?; @@ -313,6 +346,73 @@ fn grid_error(error: datatypes::error::Error) -> DataFusionError { DataFusionError::Plan(format!("the statement's grid is invalid: {error}")) } +/// What a call to a range function has to be: the parameters it reads, and how to bind them. +#[derive(Clone, Copy)] +enum RangeSignature { + /// A function that reads only its range selector, as in `rate(x[5m])`. + Selector(RangeFunction), + /// A function that reads one number literal before its range selector, and the function that + /// number binds, as in `quantile_over_time(0.9, x[5m])`. + /// + /// The number is kept out of the variant name because only the call site knows it. + Scalar(fn(f64) -> RangeFunction), +} + +impl RangeSignature { + /// How many scalar parameters the function reads before its range selector. + fn parameters(self) -> usize { + match self { + Self::Selector(_) => 0, + Self::Scalar(_) => 1, + } + } + + /// What the call's arguments are, for the arity rejection to name them. + fn arguments(self) -> &'static str { + match self { + Self::Selector(_) => "its range selector", + Self::Scalar(_) => "a number and its range selector", + } + } +} + +/// The signature the PromQL name calls, or `None` when this compiler has no kernel for it. +/// +/// The map is explicit on purpose, as in [`range_function`]: a name that is not listed is rejected, +/// so supporting one more function is a decision made in one place rather than a consequence of a +/// name looking familiar. A parameterised function is named here rather than in the map, because +/// its name alone cannot produce the variant the tree binds. +fn range_signature(name: &str) -> Option { + match name { + "quantile_over_time" => Some(RangeSignature::Scalar(RangeFunction::QuantileOverTime)), + _ => range_function(name).map(RangeSignature::Selector), + } +} + +/// The number a parameterised range function was given, as the literal it was written as. +/// +/// A literal is the only parameter this compiler binds: a parameter computed at run time, such as +/// `time()` or `1 + 1`, would make the kernel's constant a query-time value, which the tree has no +/// field for. A quantile outside `[0, 1]` is not refused here: Prometheus binds it and the kernel +/// reports `-Infinity` below zero and `+Infinity` above one, so refusing it would be this compiler +/// inventing a rule the query engine does not have. +/// +/// Parentheses are looked through, as the planner looks through them when it reads a literal: a +/// query written `(0.9)` is the same query, and the plan it already runs says so. +fn scalar_parameter(name: &str, parameter: &PromExpr) -> Result { + let mut parameter = parameter; + while let PromExpr::Paren(paren) = parameter { + parameter = &paren.expr; + } + match parameter { + PromExpr::NumberLiteral(NumberLiteral { val }) => Ok(*val), + found => Err(not_implemented(&format!( + "a call to `{name}` whose first argument is `{found}`, where it has to be a number \ + literal" + ))), + } +} + /// The range function a PromQL name denotes, or `None` when this compiler has no kernel for it. /// /// The map is explicit on purpose: a name that is not listed here is rejected, so supporting one diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index 1918ce3ec2e..58d7b6bc6f1 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -22,7 +22,7 @@ use promql::native::plan::{ BoundInstant, BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, }; use promql::range_eval::RangeFunction; -use promql_parser::parser::{EvalStmt, Expr as PromExpr}; +use promql_parser::parser::{EvalStmt, Expr as PromExpr, NumberLiteral}; use super::compile; @@ -69,6 +69,19 @@ fn with_selector_range(range: Duration) -> EvalStmt { stmt } +/// `query`'s statement with its call's arguments edited by `edit`. +/// +/// The parser checks arity, so a call with the wrong number of arguments cannot be parsed: the only +/// way to hand one to the compiler is to edit a tree the parser accepted. +fn with_call_arguments(query: &str, edit: impl FnOnce(&mut Vec>)) -> EvalStmt { + let mut stmt = eval_stmt(query); + let PromExpr::Call(call) = &mut stmt.expr else { + unreachable!("`{query}` parses to a call"); + }; + edit(&mut call.args.args); + stmt +} + /// The window at the root of `tree`, for the range-function shape. fn root_window(tree: &NativeTree) -> (&NativeNode, &BoundWindow) { let NativeExpr::Window { input, op } = &tree.root().expr else { @@ -169,6 +182,164 @@ fn the_supported_range_functions_map_to_their_kernels() { } } +/// `quantile_over_time(0.9, x[5m])` binds the quantile the query wrote, over the same window a +/// function without parameters would fold: a parameter decides what folds the window, not which +/// window is folded. +#[test] +fn a_quantile_over_time_binds_its_quantile_and_its_window() { + let tree = compile( + &eval_stmt("quantile_over_time(0.9, x[5m])"), + raw_schema(), + SeriesOrdering::KeyThenTime, + ) + .unwrap(); + + let (_, op) = root_window(&tree); + assert_eq!(op.function, RangeFunction::QuantileOverTime(0.9)); + assert_eq!(op.window.range_ms, 300_000); + assert_eq!(op.window.offset_ms, 0); + assert_eq!(op.window.anchor_ms, None); + assert!(op.input_grid.is_none(), "raw input has no grid to declare"); + + // The statement's grid: 0, 5s, ..., 100s. + let spec = op.output_grid.spec(); + assert_eq!( + (spec.start_ms, spec.step_ms, spec.len), + (0, 5_000, 21), + "the window does not land on the statement's grid" + ); +} + +/// A quantile outside `[0, 1]` compiles, because it is not an error in Prometheus: the kernel +/// returns `-Infinity` below zero, `+Infinity` above one, and a real quantile at either bound. A +/// compiler that refused it would invent a rule the query engine does not have, so the number is +/// bound exactly as written. +#[test] +fn a_quantile_outside_the_unit_interval_is_bound_as_given() { + let cases = [("-1.0", -1.0), ("2.0", 2.0), ("0.0", 0.0), ("1.0", 1.0)]; + + for (written, quantile) in cases { + let query = format!("quantile_over_time({written}, x[5m])"); + let tree = compile( + &eval_stmt(&query), + raw_schema(), + SeriesOrdering::KeyThenTime, + ) + .unwrap_or_else(|error| panic!("`{query}` did not compile: {error}")); + let (_, op) = root_window(&tree); + assert_eq!( + op.function, + RangeFunction::QuantileOverTime(quantile), + "`{query}` did not bind the quantile it wrote" + ); + assert_eq!(op.window.range_ms, 300_000, "`{query}` lost its window"); + } +} + +/// A parameter in parentheses binds the same quantile, because it is the same query: the planner +/// already looks through the parentheses when it reads a literal, so the native compiler does too. +#[test] +fn a_parenthesised_quantile_binds_as_written() { + let tree = compile( + &eval_stmt("quantile_over_time((0.9), x[5m])"), + raw_schema(), + SeriesOrdering::KeyThenTime, + ) + .expect("a parenthesised literal is the same quantile"); + + let (_, op) = root_window(&tree); + assert_eq!(op.function, RangeFunction::QuantileOverTime(0.9)); +} + +/// A parameter computed at query time is refused, and the error names it: the tree binds a kernel's +/// constant, so a quantile that would only exist at run time has no field to go in. +#[test] +fn a_computed_quantile_is_refused_and_names_what_it_found() { + // `time()` is a scalar, so the parser accepts it as the quantile; the compiler binds literals. + let query = "quantile_over_time(time(), x[5m])"; + let error = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime) + .expect_err(&format!("`{query}` compiled, and it should not have")); + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "`{query}` did not report NotImplemented: {error}" + ); + let message = error.to_string(); + assert!( + message.contains("whose first argument is `time()`"), + "`{query}` did not name the argument it found: {message}" + ); + assert!( + message.contains("number literal"), + "`{query}` did not say what the argument has to be: {message}" + ); +} + +/// A parameterised window binds its anchor and its offset exactly as an unparameterised one does. +/// The two are asserted apart because the runtime folds `anchor - offset`, so a binding that +/// dropped either number would still compile a window, and only these assertions would notice. +#[test] +fn a_quantile_over_time_binds_an_anchor_and_an_offset_apart() { + let tree = compile( + &eval_stmt("quantile_over_time(0.9, x[5m] @ 1234 offset 1m)"), + raw_schema(), + SeriesOrdering::KeyThenTime, + ) + .unwrap(); + + let (_, op) = root_window(&tree); + assert_eq!(op.function, RangeFunction::QuantileOverTime(0.9)); + assert_eq!(op.window.range_ms, 300_000, "the window was not bound"); + assert_eq!( + op.window.anchor_ms, + Some(1_234_000), + "the anchor was not bound" + ); + assert_eq!(op.window.offset_ms, 60_000, "the offset was not bound"); +} + +/// A call with the wrong number of arguments names the count its function takes, rather than +/// reporting whatever the compiler does with one argument. The parser checks arity too, so a +/// mismatched call can only reach the compiler as an edited tree. +#[test] +fn a_call_with_the_wrong_number_of_arguments_names_the_count_it_takes() { + let cases = [ + // `quantile_over_time` takes its quantile and its range selector: two arguments. + ( + with_call_arguments("quantile_over_time(0.9, x[5m])", |args| { + args.remove(1); + }), + "quantile_over_time", + "where it takes 2", + ), + // `rate` takes one argument, so nothing can be passed in front of its range selector. + ( + with_call_arguments("rate(x[5m])", |args| { + args.push(Box::new(PromExpr::NumberLiteral(NumberLiteral::new(1.0)))); + }), + "rate", + "where it takes 1", + ), + ]; + + for (stmt, name, expected) in cases { + let error = compile(&stmt, raw_schema(), SeriesOrdering::KeyThenTime) + .expect_err(&format!("`{name}` with the wrong argument count compiled")); + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "`{name}` did not report NotImplemented: {error}" + ); + let message = error.to_string(); + assert!( + message.contains(&format!("a call to `{name}`")), + "`{name}` did not name itself: {message}" + ); + assert!( + message.contains(expected), + "`{name}` did not name the count it takes: {message}" + ); + } +} + /// `x` becomes an instant selection over the raw input, on the statement's grid, with the /// statement's lookback and the input's fields. #[test] @@ -503,8 +674,8 @@ fn an_unsupported_shape_is_rejected_and_names_what_it_found() { ), // A function with no kernel, whether or not it takes a constant argument. ( - "quantile_over_time(0.9, x[5m])", - "a call to `quantile_over_time`", + "predict_linear(x[5m], 300)", + "a call to `predict_linear`, which has no native range kernel", ), ( "absent(x)", From da1ec3320bc811489988d435eef80be34968ea98 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 01:05:39 +0800 Subject: [PATCH 16/17] test(promql): cover a parenthesised selector of a parameterised function The unparen rule applies to the selector a parameterised function binds, not only to the one a plain range function binds: a query that writes its range selector in parentheses asks for the same tree. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/query/src/promql/native_compile/tests.rs | 26 ++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index 58d7b6bc6f1..3b4d7e74fd7 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -251,6 +251,32 @@ fn a_parenthesised_quantile_binds_as_written() { assert_eq!(op.function, RangeFunction::QuantileOverTime(0.9)); } +/// The selector of a parameterised function is looked through its parentheses too, so the range +/// function and the parameter are both read from a statement that was merely typed with grouping. +#[test] +fn a_parenthesised_selector_binds_as_written() { + let bare = compile( + &eval_stmt("quantile_over_time(0.9, x[5m])"), + raw_schema(), + SeriesOrdering::KeyThenTime, + ) + .expect("the bare selector binds"); + + for query in [ + "quantile_over_time(0.9, (x[5m]))", + "quantile_over_time((0.9), (x[5m]))", + "(quantile_over_time(0.9, (x[5m])))", + ] { + let tree = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); + assert_eq!( + tree.to_string(), + bare.to_string(), + "`{query}` did not compile to the tree `quantile_over_time(0.9, x[5m])` does" + ); + } +} + /// A parameter computed at query time is refused, and the error names it: the tree binds a kernel's /// constant, so a quantile that would only exist at run time has no field to go in. #[test] From fa2ae4fa71d258390bde804e7e94377172cf3b1e Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:27:25 +0800 Subject: [PATCH 17/17] docs(promql): name the real run-time parameter, and reuse `unparen` The doc said `1 + 1` is computed at run time. It is not: `try_build_literal_expr` folds `Paren`, `Unary` and literal-only `Binary` in the existing planner, so `quantile_over_time(1 - 0.1, x[5m])` and `quantile_over_time(-(0.9), x[5m])` plan today and reach this compiler unfolded. Refusing them is the agreed behaviour for this stage, not a run-time-only case, and the doc now says so; `time()` is the real run-time example. A test pins both folded forms as refused, so implementing folding later is a deliberate change rather than a silent one. `scalar_parameter` open-coded the parenthesis loop `unparen` already implements, so the rule for transparent wrappers now lives in one place. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/query/src/promql/native_compile.rs | 26 +++++++++++--------- src/query/src/promql/native_compile/tests.rs | 24 ++++++++++++++++++ 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index 31fc6d69dd4..88e5023aa42 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -391,20 +391,22 @@ fn range_signature(name: &str) -> Option { /// The number a parameterised range function was given, as the literal it was written as. /// -/// A literal is the only parameter this compiler binds: a parameter computed at run time, such as -/// `time()` or `1 + 1`, would make the kernel's constant a query-time value, which the tree has no -/// field for. A quantile outside `[0, 1]` is not refused here: Prometheus binds it and the kernel -/// reports `-Infinity` below zero and `+Infinity` above one, so refusing it would be this compiler -/// inventing a rule the query engine does not have. +/// A number literal is the only parameter this compiler binds. A parameter whose value is only +/// known at run time, `time()` being the real case, would make the kernel's constant a query-time +/// value, which the tree has no field for. /// -/// Parentheses are looked through, as the planner looks through them when it reads a literal: a -/// query written `(0.9)` is the same query, and the plan it already runs says so. +/// A parameter written as an expression the existing planner folds to a literal is refused here +/// and is a gap this stage leaves open on purpose: `quantile_over_time(1 - 0.1, x[5m])` and +/// `quantile_over_time(-(0.9), x[5m])` plan today through `try_build_literal_expr`, which folds +/// `Paren`, `Unary` and literal-only `Binary`, and reach this function still unfolded. They are +/// refused rather than answered from the wrong number, and folding them here would be the work +/// to close the gap. +/// +/// A quantile outside `[0, 1]` is not refused here: Prometheus binds it and the kernel reports +/// `-Infinity` below zero and `+Infinity` above one, so refusing it would be this compiler +/// inventing a rule the query engine does not have. fn scalar_parameter(name: &str, parameter: &PromExpr) -> Result { - let mut parameter = parameter; - while let PromExpr::Paren(paren) = parameter { - parameter = &paren.expr; - } - match parameter { + match unparen(parameter) { PromExpr::NumberLiteral(NumberLiteral { val }) => Ok(*val), found => Err(not_implemented(&format!( "a call to `{name}` whose first argument is `{found}`, where it has to be a number \ diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index 3b4d7e74fd7..5e375858111 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -277,6 +277,30 @@ fn a_parenthesised_selector_binds_as_written() { } } +/// A parameter the planner folds to a literal is still refused, and that gap is deliberate: the +/// kernel's constant is a field of the tree, so binding `1 - 0.1` means folding it here rather than +/// carrying an expression. A refusal is the agreed behaviour for this stage; an answer computed +/// from the wrong number would not be. +#[test] +fn a_parameter_folded_from_an_expression_is_refused() { + for query in [ + "quantile_over_time(1 - 0.1, x[5m])", + "quantile_over_time(-(0.9), x[5m])", + ] { + let error = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime) + .expect_err(&format!("`{query}` compiled, and it should not have")); + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "`{query}` did not report NotImplemented: {error}" + ); + let message = error.to_string(); + assert!( + message.contains("number literal"), + "`{query}` did not say what the argument has to be: {message}" + ); + } +} + /// A parameter computed at query time is refused, and the error names it: the tree binds a kernel's /// constant, so a quantile that would only exist at run time has no field to go in. #[test]