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] 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") + ); +}