From 10b6cf9477ac4aa818b9ef424acf602581345075 Mon Sep 17 00:00:00 2001 From: discord9 Date: Wed, 2 Dec 2026 06:30:59 +0000 Subject: [PATCH] feat(query): add windowed PromQL evaluation (#10797) * feat(query): add windowed PromQL evaluation Signed-off-by: discord9 * docs(query): clarify window allowlist and drop unused grid bound The public end_ms_exclusive duplicated point_ms(points) without a caller. max_input_range_ms stays public for the stacked sequence-probe cache. Signed-off-by: discord9 * refactor(query): trim window docs and merge overlapping allowlist tests Apply review: state the allowlist in a few lines instead of arguing for it, drop doc that restates the code or another item's doc, and make max_input_range_ms private since nothing outside window.rs calls it. Collapse the allowlist tests into one positive table that asserts the source table and the input range per row, and one negative table that asserts NotEligible once per shape. The grid tests keep the point_ms(points) continuation the frontend cache relies on and gain the negative-start phase case. The differential test drops asserts implied by full == merged and the SumRate arm that re-derived the aggregate. Signed-off-by: discord9 * docs(query): shorten window docs and cover sum(selector) in the differential Apply review: state the grid rule and the caller's duty in a few lines, point the selector helper at windowed_source_table instead of repeating its reasoning, and drop the doc that restates the GridSpec bound. Add sum(window_diff) as a fourth differential shape so the aggregate the allowlist admits over a bare selector is compared on both routes too. Make max_input_range_ms public again: the sequence-probe cache reads the input range to bound what a chunk depends on, and WindowGrid::of alone does not expose it. Signed-off-by: discord9 --------- Signed-off-by: discord9 --- src/query/src/promql.rs | 1 + src/query/src/promql/window.rs | 656 +++++++++++++++++++++ tests-integration/src/tests/promql_test.rs | 401 +++++++++++++ 3 files changed, 1058 insertions(+) create mode 100644 src/query/src/promql/window.rs diff --git a/src/query/src/promql.rs b/src/query/src/promql.rs index 424204b5d95..0f403cb4d9a 100644 --- a/src/query/src/promql.rs +++ b/src/query/src/promql.rs @@ -16,6 +16,7 @@ pub mod error; pub mod label_values; pub mod native_compile; pub mod planner; +pub mod window; use datafusion_common::tree_node::{TreeNode as _, TreeNodeRecursion}; use datafusion_expr::{Extension, LogicalPlan}; diff --git a/src/query/src/promql/window.rs b/src/query/src/promql/window.rs new file mode 100644 index 00000000000..f24e5e646ad --- /dev/null +++ b/src/query/src/promql/window.rs @@ -0,0 +1,656 @@ +// 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. + +//! A planner-agnostic evaluation-window helper for incremental rollups. +//! +//! This module deliberately does not know about the legacy or native PromQL +//! planner, a cache, a materialized sink, or Flow. It only turns a span of +//! indices on an already parsed statement's grid into a smaller [`EvalStmt`]. + +use std::fmt; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use datatypes::series::time::GridSpec; +use promql_parser::parser::{ + AggregateExpr, Call, EvalStmt, Expr as PromExpr, MatrixSelector, ParenExpr, VectorSelector, + token, +}; + +use crate::promql::label_values::signed_millis_since_epoch; + +/// A statement span that cannot be turned into an evaluation window. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WindowError { + /// The expression is outside the deliberately small v1 allowlist. + NotEligible, + /// The requested grid span is empty or lies outside the original grid. + InvalidSpan, + /// The grid arithmetic cannot be represented. + Overflow, +} + +impl fmt::Display for WindowError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NotEligible => f.write_str("the PromQL expression is not windowable"), + Self::InvalidSpan => f.write_str("the requested evaluation span is invalid"), + Self::Overflow => f.write_str("the evaluation span overflows the time grid"), + } + } +} + +impl std::error::Error for WindowError {} + +/// Returns the statement for output grid indices `[first, last)`. +/// +/// The grid is the planners' millisecond grid: `start` and `end` are floored to +/// whole milliseconds and points are `start_ms + i * step_ms`. Expression, step +/// and lookback are kept, and a statement planning would refuse yields no window. +/// The caller must still read the input history each point needs (e.g. the full +/// range of `rate(x[5m])`). +pub fn windowed_eval_stmt( + original: &EvalStmt, + first: usize, + last: usize, +) -> Result { + WindowGrid::of(original)?.window(original, first, last) +} + +/// Whether `expr` is in the deliberately small v1 allowlist: +/// - a named instant vector selector with no `@`, no `offset`, and no `__name__`, +/// `__schema__`, or `__database__` matcher; +/// - `rate()` with no `@` and no `offset`; +/// - `sum()`, with or without a `by (...)`/`without (...)` grouping +/// clause. +/// +/// Parentheses are transparent. Everything else fails closed: every other +/// aggregate, binaries, subqueries, other functions, dynamic metric discovery, and +/// any `@`/`offset` modifier. +pub fn is_windowable(expr: &PromExpr) -> bool { + admit(expr).is_some() +} + +/// The named source table of an expression admitted by the window allowlist. +/// +/// Selectors name the table directly; `rate` uses its matrix selector's name, +/// `sum` uses its child's name, and parentheses are transparent. Multi-input, +/// unnamed, and other expressions outside the allowlist fail closed, and so does a +/// selector that qualifies its table with a `__name__`, `__schema__`, or +/// `__database__` matcher: only the table name comes back, and a window tracking a +/// differently-qualified table than the selector reads would answer for the wrong +/// one. +pub fn windowed_source_table(expr: &PromExpr) -> Result<&str, WindowError> { + admit(expr) + .map(|admitted| admitted.source_table) + .ok_or(WindowError::NotEligible) +} + +/// The range of an admitted `rate`'s matrix selector in milliseconds, or zero for a selector. +/// +/// [`WindowGrid::of`] runs this to refuse what planning refuses; the frontend's sequence-probe +/// cache also reads the value to bound the input a chunk depends on. +pub fn max_input_range_ms(expr: &PromExpr) -> Result { + let admitted = admit(expr).ok_or(WindowError::NotEligible)?; + match admitted.matrix { + Some(matrix) => range_millis(matrix.range), + None => Ok(0), + } +} + +/// What the v1 allowlist admits, beyond the expression being windowable at all. +struct Admitted<'a> { + /// The named selector's source table. + source_table: &'a str, + /// The range of an admitted `rate`'s matrix selector, which planning narrows + /// to milliseconds before it folds a window of them. + matrix: Option<&'a MatrixSelector>, +} + +/// The allowlist, in one place: `None` outside it. +fn admit(expr: &PromExpr) -> Option> { + match expr { + PromExpr::Paren(ParenExpr { expr }) => admit(expr), + PromExpr::VectorSelector(selector) => Some(Admitted { + source_table: named_selector(selector)?, + matrix: None, + }), + PromExpr::Call(Call { func, args }) if func.name == "rate" && args.args.len() == 1 => { + match unparen(&args.args[0]) { + PromExpr::MatrixSelector(selector) => Some(Admitted { + source_table: named_selector(&selector.vs)?, + matrix: Some(selector), + }), + _ => None, + } + } + PromExpr::Aggregate(AggregateExpr { + op, + expr, + param: None, + .. + }) if op.id() == token::T_SUM => admit(expr), + _ => None, + } +} + +fn unparen(mut expr: &PromExpr) -> &PromExpr { + while let PromExpr::Paren(ParenExpr { expr: inner }) = expr { + expr = inner; + } + expr +} + +/// The table `selector` names, or `None` for `@`/`offset`, `or` matchers, or a +/// `__name__`/`__schema__`/`__database__` matcher (see [`windowed_source_table`]). +fn named_selector(selector: &VectorSelector) -> Option<&str> { + if selector.at.is_some() + || selector.offset.is_some() + || !selector.matchers.or_matchers.is_empty() + || selector.matchers.matchers.iter().any(|matcher| { + matches!( + matcher.name.as_str(), + "__name__" | "__schema__" | "__database__" + ) + }) + { + return None; + } + selector.name.as_deref() +} + +/// A step as the positive whole number of milliseconds planning lays its grid out with. +/// +/// The step is the grid, so a step carrying a sub-millisecond part is refused rather +/// than narrowed: the narrowed step would lay out a different grid than the statement +/// asked for, and every point of a window would move with it. +fn step_millis(duration: Duration) -> Result { + if !duration.subsec_nanos().is_multiple_of(1_000_000) { + return Err(WindowError::InvalidSpan); + } + let millis = i64::try_from(duration.as_millis()).map_err(|_| WindowError::Overflow)?; + if millis <= 0 { + return Err(WindowError::InvalidSpan); + } + Ok(millis) +} + +/// A range selector's window as the positive millisecond count planning narrows it to. +/// +/// Planning narrows a range by truncation, so a fractional millisecond folds what its +/// whole milliseconds fold; a positive range that narrows to zero folds nothing and +/// selects nothing, which is not a window this helper can split. +fn range_millis(duration: Duration) -> Result { + let millis = i64::try_from(duration.as_millis()).map_err(|_| WindowError::Overflow)?; + if millis <= 0 { + return Err(WindowError::InvalidSpan); + } + Ok(millis) +} + +/// The millisecond evaluation grid both planners use for a statement. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct WindowGrid { + spec: GridSpec, + /// Last grid point, in milliseconds since the epoch. + last_ms: i64, +} + +impl WindowGrid { + /// The grid `stmt` is evaluated on, refusing what planning refuses. + pub fn of(stmt: &EvalStmt) -> Result { + max_input_range_ms(&stmt.expr)?; + let step_ms = step_millis(stmt.interval)?; + // Planning keeps the lookback in i64 milliseconds. + i64::try_from(stmt.lookback_delta.as_millis()).map_err(|_| WindowError::Overflow)?; + + let spec = grid_spec(millis(stmt.start)?, millis(stmt.end)?, step_ms)?; + Ok(Self { + spec, + last_ms: grid_last_ms(&spec)?, + }) + } + + /// First grid point, in milliseconds since the epoch. + pub fn start_ms(&self) -> i64 { + self.spec.start_ms + } + + /// Positive length of one step, in milliseconds. + pub fn step_ms(&self) -> i64 { + self.spec.step_ms + } + + /// How many points the grid holds. + pub fn points(&self) -> u64 { + self.spec.len + } + + /// Last grid point, in milliseconds since the epoch. + pub fn last_ms(&self) -> i64 { + self.last_ms + } + + /// The phase of the grid, in milliseconds: the distance from the last + /// step-aligned instant at or before its first point. + /// + /// Two statements with the same step evaluate on the same grid exactly when + /// their phases are equal, so this is what makes spans laid out from one + /// statement's grid reusable by another. + pub fn phase_ms(&self) -> i64 { + self.spec.start_ms.rem_euclid(self.spec.step_ms) + } + + /// The timestamp of grid index `index`, in milliseconds since the epoch. + /// + /// An index at or past [`WindowGrid::points`] continues the grid rather than + /// failing, so a caller can name the instant just past its last point. + pub fn point_ms(&self, index: u64) -> Result { + let offset = i128::from(index) * i128::from(self.spec.step_ms); + i64::try_from(i128::from(self.spec.start_ms) + offset).map_err(|_| WindowError::Overflow) + } + + fn window( + &self, + original: &EvalStmt, + first: usize, + last: usize, + ) -> Result { + if first >= last { + return Err(WindowError::InvalidSpan); + } + let first = u64::try_from(first).map_err(|_| WindowError::Overflow)?; + let last = u64::try_from(last).map_err(|_| WindowError::Overflow)?; + if last > self.spec.len { + return Err(WindowError::InvalidSpan); + } + + Ok(EvalStmt { + expr: original.expr.clone(), + start: system_time(self.point_ms(first)?)?, + end: system_time(self.point_ms(last - 1)?)?, + interval: original.interval, + lookback_delta: original.lookback_delta, + }) + } +} + +/// The grid of `start_ms..=end_ms` at `step_ms`; an inverted range is `InvalidSpan`, not `Overflow`. +fn grid_spec(start_ms: i64, end_ms: i64, step_ms: i64) -> Result { + if end_ms < start_ms { + return Err(WindowError::InvalidSpan); + } + GridSpec::try_from_range(start_ms, end_ms, step_ms).map_err(|_| WindowError::Overflow) +} + +/// The last point of `spec`, in milliseconds since the epoch. +fn grid_last_ms(spec: &GridSpec) -> Result { + let offset = i128::from(spec.len - 1) * i128::from(spec.step_ms); + i64::try_from(i128::from(spec.start_ms) + offset).map_err(|_| WindowError::Overflow) +} + +/// A time as the millisecond the planners read for it. +fn millis(time: SystemTime) -> Result { + signed_millis_since_epoch(time).map_err(|_| WindowError::Overflow) +} + +/// The [`SystemTime`] of a whole millisecond, on either side of the epoch. +/// +/// Both planners floor a time to milliseconds, so a window bound carrying a +/// sub-millisecond field would be read as the millisecond below it. Building +/// every bound here keeps the window on the grid instead. +fn system_time(millis: i64) -> Result { + let magnitude = Duration::from_millis(millis.unsigned_abs()); + let time = if millis >= 0 { + UNIX_EPOCH.checked_add(magnitude) + } else { + UNIX_EPOCH.checked_sub(magnitude) + }; + time.ok_or(WindowError::Overflow) +} + +#[cfg(test)] +mod tests { + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + use promql_parser::parser::parse; + + use super::*; + + fn stmt(expr: &str) -> EvalStmt { + let expr = parse(expr).expect("the expression parses"); + EvalStmt { + expr, + start: UNIX_EPOCH + Duration::from_secs(1), + end: UNIX_EPOCH + Duration::from_secs(1) + Duration::from_secs(37 * 4), + interval: Duration::from_secs(37), + lookback_delta: Duration::from_secs(300), + } + } + + fn stmt_between(expr: &str, start: SystemTime, end: SystemTime, step: Duration) -> EvalStmt { + EvalStmt { + start, + end, + interval: step, + ..stmt(expr) + } + } + + /// [`stmt`] with the range of the matrix selector its `rate` folds over replaced. + fn stmt_with_range(expr: &str, range: Duration) -> EvalStmt { + let mut original = stmt(expr); + let PromExpr::Call(call) = &mut original.expr else { + panic!("{expr} is a call") + }; + let PromExpr::MatrixSelector(matrix) = &mut *call.args.args[0] else { + panic!("{expr} folds a matrix selector") + }; + matrix.range = range; + original + } + + fn millis(time: SystemTime) -> u128 { + time.duration_since(UNIX_EPOCH).unwrap().as_millis() + } + + #[test] + fn slices_on_the_original_grid_without_rounding() { + let original = stmt("rate(x[5m])"); + let window = windowed_eval_stmt(&original, 2, 5).unwrap(); + + assert_eq!(millis(window.start), 1_000 + 2 * 37_000); + assert_eq!(millis(window.end), 1_000 + 4 * 37_000); + assert_eq!(window.interval, original.interval); + assert_eq!(window.lookback_delta, original.lookback_delta); + assert_eq!(window.expr, original.expr); + assert_eq!(millis(original.start), 1_000); + assert_eq!(millis(original.end), 1_000 + 4 * 37_000); + } + + #[test] + fn rejects_empty_or_out_of_grid_spans() { + let original = stmt("x"); + assert_eq!( + windowed_eval_stmt(&original, 3, 3).unwrap_err(), + WindowError::InvalidSpan + ); + assert_eq!( + windowed_eval_stmt(&original, 0, 6).unwrap_err(), + WindowError::InvalidSpan + ); + assert_eq!( + windowed_eval_stmt(&original, 5, 6).unwrap_err(), + WindowError::InvalidSpan + ); + + let mut backwards = original.clone(); + backwards.end = backwards.start - Duration::from_secs(1); + assert_eq!( + windowed_eval_stmt(&backwards, 0, 1).unwrap_err(), + WindowError::InvalidSpan + ); + + let mut zero = original.clone(); + zero.interval = Duration::ZERO; + assert_eq!( + windowed_eval_stmt(&zero, 0, 1).unwrap_err(), + WindowError::InvalidSpan + ); + + let mut sub_millisecond = original.clone(); + sub_millisecond.interval = Duration::from_nanos(1); + assert_eq!( + windowed_eval_stmt(&sub_millisecond, 0, 1).unwrap_err(), + WindowError::InvalidSpan + ); + + let mut fractional_millisecond = original.clone(); + fractional_millisecond.interval = Duration::from_nanos(1_500_000); + assert_eq!( + windowed_eval_stmt(&fractional_millisecond, 0, 1).unwrap_err(), + WindowError::InvalidSpan + ); + } + + /// The grid is the integer one both planners build from their own + /// millisecond endpoints, not one laid out from the `SystemTime`s: a start + /// with a sub-millisecond field is not a grid point of either. + #[test] + fn windows_start_on_the_planners_millisecond_grid() { + // `[epoch .. epoch + 2ms]` at `1ms`: planning floors the start to `0` and + // holds three points, at 0ms, 1ms and 2ms. + let original = stmt_between( + "x", + UNIX_EPOCH + Duration::from_micros(900), + UNIX_EPOCH + Duration::from_millis(2), + Duration::from_millis(1), + ); + let third = windowed_eval_stmt(&original, 2, 3).unwrap(); + assert_eq!(millis(third.start), 2); + assert_eq!(millis(third.end), 2); + assert_eq!(third.start, UNIX_EPOCH + Duration::from_millis(2)); + + // The first window starts on the floored point, not on `epoch + 900µs`. + let first = windowed_eval_stmt(&original, 0, 1).unwrap(); + assert_eq!(first.start, UNIX_EPOCH); + assert_eq!(first.end, UNIX_EPOCH); + + // An end that is not on the grid keeps the last point it can hold. + let original = stmt_between( + "x", + UNIX_EPOCH + Duration::from_micros(900), + UNIX_EPOCH + Duration::from_micros(3_600), + Duration::from_millis(1), + ); + let window = windowed_eval_stmt(&original, 1, 3).unwrap(); + assert_eq!(millis(window.start), 1); + assert_eq!(millis(window.end), 2); + } + + /// Times before the epoch floor the other way, and a window keeps that grid. + #[test] + fn windows_keep_the_pre_epoch_grid() { + // `-1.5ms .. 1.5ms` floor to `-2ms .. 1ms`, four points at 1ms. + let original = stmt_between( + "x", + UNIX_EPOCH - Duration::from_micros(1_500), + UNIX_EPOCH + Duration::from_micros(1_500), + Duration::from_millis(1), + ); + let window = windowed_eval_stmt(&original, 1, 3).unwrap(); + assert_eq!(window.start, UNIX_EPOCH - Duration::from_millis(1)); + assert_eq!(window.end, UNIX_EPOCH); + + let last = windowed_eval_stmt(&original, 3, 4).unwrap(); + assert_eq!(last.start, UNIX_EPOCH + Duration::from_millis(1)); + assert_eq!(last.end, UNIX_EPOCH + Duration::from_millis(1)); + } + + /// A step the planners cannot narrow to `i64` milliseconds is one they refuse: + /// a singleton span must not report a window it would evaluate with a wrapped step. + #[test] + fn rejects_a_step_planning_cannot_represent() { + let mut original = stmt("x"); + original.end = original.start; + original.interval = Duration::from_millis(i64::MAX as u64 + 1); + assert_eq!( + windowed_eval_stmt(&original, 0, 1).unwrap_err(), + WindowError::Overflow + ); + + // The largest representable step still windows a singleton. + original.interval = Duration::from_millis(i64::MAX as u64); + let window = windowed_eval_stmt(&original, 0, 1).unwrap(); + assert_eq!(window.start, window.end); + } + + #[test] + fn rejects_a_lookback_planning_cannot_represent() { + let mut original = stmt("x"); + original.lookback_delta = Duration::from_millis(i64::MAX as u64 + 1); + assert_eq!( + windowed_eval_stmt(&original, 0, 1).unwrap_err(), + WindowError::Overflow + ); + } + + /// The grid is the integer one both planners build from their own millisecond + /// endpoints, so each of its points is the start of its own window. + #[test] + fn a_grid_reads_the_points_the_windows_are_cut_from() { + let original = stmt("rate(x[5m])"); + let grid = WindowGrid::of(&original).unwrap(); + assert_eq!(grid.point_ms(grid.points()).unwrap(), 1_000 + 5 * 37_000); + + for index in 0..grid.points() { + let window = windowed_eval_stmt(&original, index as usize, index as usize + 1) + .expect("every point of the grid windows"); + assert_eq!( + grid.point_ms(index).unwrap(), + i64::try_from(millis(window.start)).unwrap() + ); + } + + // A start below the epoch keeps its residue as the phase: `-1.5s` at a `1s` step is + // the grid `-2s, -1s, 0s, ...`, whose phase is `500ms`. + let pre_epoch = stmt_between( + "x", + UNIX_EPOCH - Duration::from_millis(1_500), + UNIX_EPOCH + Duration::from_millis(1_500), + Duration::from_secs(1), + ); + assert_eq!(WindowGrid::of(&pre_epoch).unwrap().phase_ms(), 500); + } + + #[test] + fn input_range_rejects_zero_and_overflow_after_narrowing() { + for range in [Duration::ZERO, Duration::from_micros(999)] { + let original = stmt_with_range("rate(x[10m])", range); + assert_eq!( + max_input_range_ms(&original.expr), + Err(WindowError::InvalidSpan) + ); + } + let overflow = stmt_with_range("rate(x[10m])", Duration::from_millis(i64::MAX as u64 + 1)); + assert_eq!( + max_input_range_ms(&overflow.expr), + Err(WindowError::Overflow) + ); + + let largest = stmt_with_range("rate(x[10m])", Duration::from_millis(i64::MAX as u64)); + assert_eq!(max_input_range_ms(&largest.expr), Ok(i64::MAX)); + let fractional = stmt_with_range("rate(x[10m])", Duration::from_micros(1_500)); + assert_eq!(max_input_range_ms(&fractional.expr), Ok(1)); + } + + /// The v1 allowlist, row by row: what each admitted expression reads and how far back + /// it has to read it. + #[test] + fn source_table_follows_the_window_allowlist() { + for (query, table, range_ms) in [ + ("x", "x", 0), + ("((x))", "x", 0), + ("cpu{host=\"a\"}", "cpu", 0), + ("rate(x[5m])", "x", 300_000), + ("rate((x[5m]))", "x", 300_000), + ("rate(((x[5m])))", "x", 300_000), + ("((rate((x[5m]))))", "x", 300_000), + ("rate(cpu{host=\"a\"}[5m])", "cpu", 300_000), + ("rate(requests_total[5m])", "requests_total", 300_000), + ("rate(x[10m])", "x", 600_000), + ("sum(x)", "x", 0), + ("sum((sum(x)))", "x", 0), + ("sum(rate(x[5m]))", "x", 300_000), + ("sum((rate(x[5m])))", "x", 300_000), + ("sum(((rate((x[5m])))))", "x", 300_000), + ("sum(rate(cpu{host=\"a\"}[5m]))", "cpu", 300_000), + ("sum(rate(x[10m]))", "x", 600_000), + ("sum by (host) (rate(x[10m]))", "x", 600_000), + ( + "sum by (host) (rate(requests_total[5m]))", + "requests_total", + 300_000, + ), + ("sum without (host) (rate(x[5m]))", "x", 300_000), + ("((sum by (host) ((rate(x[5m])))))", "x", 300_000), + ("((sum((sum(rate(((cpu[5m]))))))))", "cpu", 300_000), + ] { + assert_eq!( + windowed_source_table(&stmt(query).expr), + Ok(table), + "{query}" + ); + assert_eq!( + max_input_range_ms(&stmt(query).expr), + Ok(range_ms), + "{query}" + ); + } + } + + /// Everything the allowlist fails closed on: modifiers, other aggregates, binaries, + /// subqueries, other functions, dynamic metric discovery, and a selector that qualifies + /// the table it reads (`__name__` names it, `__schema__`/`__database__` move it, so the + /// table name alone would not be the table the selector reads). + #[test] + fn rejects_modifiers_and_non_allowlisted_expressions() { + for query in [ + "x @ 123", + "x offset 1m", + "rate(x[5m] @ end())", + "rate(x[5m] offset 1m)", + "rate((x[5m] @ end()))", + "rate((x[5m] offset 1m))", + "sum(x @ 123)", + "sum(x offset 1m)", + "sum(rate(x[5m] @ end()))", + "sum(rate(x[5m] offset 1m))", + "rate(x[5m:30s])", + "avg(rate(x[5m]))", + "min(rate(x[5m]))", + "max(rate(x[5m]))", + "count(rate(x[5m]))", + "quantile(0.9, rate(x[5m]))", + "sum(topk(5, x))", + "topk(5, x)", + "avg(cpu)", + "abs(cpu)", + "cpu + memory", + "sum(rate(x[5m])) + 1", + "sum(rate(cpu[5m]) + rate(memory[5m]))", + "{host=\"a\"}", + "{__name__=\"x\"}", + "cpu{__schema__=\"archive\"}", + "cpu{__database__=\"other\"}", + "((cpu{__schema__=\"archive\"}))", + "rate(cpu{__schema__=\"archive\"}[5m])", + "sum(rate(cpu{__database__=\"other\"}[5m]))", + "sum((rate(cpu{__schema__=\"archive\"}[5m])))", + "{__schema__=\"archive\"}", + "{__database__=\"other\"}", + ] { + assert_eq!( + windowed_source_table(&stmt(query).expr), + Err(WindowError::NotEligible), + "{query}" + ); + } + + // The statement entry point refuses them too, not only the table reader. + assert_eq!( + windowed_eval_stmt(&stmt("avg(rate(x[5m]))"), 0, 1).unwrap_err(), + WindowError::NotEligible + ); + } +} diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index 9ed36eb03ef..9e84ce71ba8 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::collections::BTreeMap; use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -40,6 +41,7 @@ use query::options::QueryOptions; use query::parser::{PromQuery, QueryLanguageParser, QueryStatement}; use query::physical_wrapper::{PhysicalPlanWrapper, PhysicalPlanWrapperRef}; use query::promql::planner::NATIVE_PROMQL_EXTENSION_KEY; +use query::promql::window::windowed_eval_stmt; use rstest::rstest; use rstest_reuse::apply; use servers::query_handler::sql::SqlQueryHandler; @@ -20318,3 +20320,402 @@ async fn narthex_native_histograms_match_parquet() { series } } + +// --------------------------------------------------------------------------------------------- +// Windowed evaluation. +// +// `query::promql::window::windowed_eval_stmt` splits the output grid of one parsed statement into +// smaller statements. The test below pins what that split has to preserve when the statements are +// executed for real: the grid phase, the endpoints, the points a series is missing at, and - the +// part a count cannot show - the history before a window that its first points still read. +// --------------------------------------------------------------------------------------------- + +/// The evaluation grid of the windowed differential test. +/// +/// The start is deliberately not a multiple of the step (`1_700_000_000_000 % 7_000 == 6_000`) and +/// the step is odd, so a window that rounded its bounds to a wall-clock bucket would move every +/// timestamp instead of agreeing by luck. +const DIFFERENTIAL_TABLE: &str = "window_diff"; +const DIFFERENTIAL_START_MS: i64 = 1_700_000_000_000; +const DIFFERENTIAL_STEP_MS: i64 = 7_000; +/// Grid indices `0..DIFFERENTIAL_POINTS`, so the statement spans `40 * 7s = 280s`. +const DIFFERENTIAL_POINTS: usize = 41; +/// A non-trivial split: neither the middle of the grid nor aligned to anything the fixture repeats. +const DIFFERENTIAL_SPLIT: usize = 17; +const DIFFERENTIAL_LOOKBACK_MS: i64 = 30_000; +const DIFFERENTIAL_RANGE: &str = "60s"; +const DIFFERENTIAL_RANGE_MS: i64 = 60_000; + +const DIFFERENTIAL_CREATE: &str = "CREATE TABLE window_diff_phy (ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE=metric WITH ('physical_metric_table' = 'true'); \ + CREATE TABLE window_diff (host STRING, ts TIMESTAMP TIME INDEX, val DOUBLE, PRIMARY KEY(host)) ENGINE=metric WITH ('on_physical_table' = 'window_diff_phy')"; + +fn differential_timestamp(index: usize) -> i64 { + DIFFERENTIAL_START_MS + index as i64 * DIFFERENTIAL_STEP_MS +} + +/// The grid index of `timestamp`, which the caller first checks in on the grid. +fn differential_index(timestamp: i64) -> i64 { + (timestamp - DIFFERENTIAL_START_MS) / DIFFERENTIAL_STEP_MS +} + +/// The samples of the one metric table: three series over the whole grid, none at the epoch. +/// +/// - `a` steps a counter by 7 on every grid point and resets at exactly the split index, so the +/// first point of the second window reads history the window itself does not contain. It also +/// has no samples at indices `20..=25`: its instant value is missing at 24 and 25 (35s and 42s +/// after the last sample, past the 30s lookback) while `rate` still answers there from its range. +/// - `b` samples every other index and carries a pair of samples one millisecond apart around the +/// open left edge of `rate(...[60s])` at the split index: `t17 - 60s` is outside the range and +/// `t17 - 60s + 1ms` is inside it. +/// - `c` samples twice, 140s apart: present at the head of the grid, absent through the middle, +/// present again from index 20, and absent for the tail. +fn differential_samples() -> Vec<(&'static str, i64, f64)> { + let mut samples = Vec::new(); + for index in 0..DIFFERENTIAL_POINTS { + let timestamp = differential_timestamp(index); + if !(20..=25).contains(&index) { + let value = if index < DIFFERENTIAL_SPLIT { + 100.0 + 7.0 * index as f64 + } else { + 3.0 + 7.0 * (index - DIFFERENTIAL_SPLIT) as f64 + }; + samples.push(("a", timestamp, value)); + } + if index % 2 == 0 { + samples.push(("b", timestamp, 2000.0 * index as f64)); + } + } + let range_edge = differential_timestamp(DIFFERENTIAL_SPLIT) - DIFFERENTIAL_RANGE_MS; + samples.push(("b", range_edge, 17_000.0)); + samples.push(("b", range_edge + 1, 17_000.5)); + samples.push(("c", differential_timestamp(0), 5.0)); + samples.push(("c", differential_timestamp(20), 9.0)); + samples.sort_by_key(|(_, timestamp, _)| *timestamp); + samples +} + +fn differential_insert() -> String { + let rows = differential_samples() + .into_iter() + .map(|(host, timestamp, value)| format!("('{host}', {timestamp}, {value})")) + .collect::>() + .join(", "); + format!("INSERT INTO {DIFFERENTIAL_TABLE} (host, ts, val) VALUES {rows}") +} + +/// The statement `query` builds over the whole differential grid, as a query builds it. +/// +/// This is the baseline the windows are compared with, and it never passes through +/// `windowed_eval_stmt`: a helper that moved every span the same way would otherwise agree with +/// itself instead of with the statement the query really asks for. +fn differential_full(query: &str) -> QueryStatement { + let prom = PromQuery { + query: query.to_string(), + ..PromQuery::default() + }; + let QueryStatement::Promql(mut statement, _) = + QueryLanguageParser::parse_promql(&prom, &QueryContext::arc()).unwrap() + else { + unreachable!() + }; + statement.start = UNIX_EPOCH + Duration::from_millis(DIFFERENTIAL_START_MS as u64); + statement.end = + UNIX_EPOCH + Duration::from_millis(differential_timestamp(DIFFERENTIAL_POINTS - 1) as u64); + statement.interval = Duration::from_millis(DIFFERENTIAL_STEP_MS as u64); + statement.lookback_delta = Duration::from_millis(DIFFERENTIAL_LOOKBACK_MS as u64); + QueryStatement::Promql(statement, None) +} + +/// The statement for `query` over the grid indices `[first, last)`, on the differential grid. +/// +/// Only the span differs from [`differential_full`], and the window is cut by +/// `windowed_eval_stmt` rather than by the test. +fn differential_window(query: &str, first: usize, last: usize) -> QueryStatement { + let QueryStatement::Promql(statement, _) = differential_full(query) else { + unreachable!() + }; + let window = windowed_eval_stmt(&statement, first, last).expect("the span is on the grid"); + QueryStatement::Promql(window, None) +} + +/// A shape the window allowlist admits, and what a row of its answer is named by. +#[derive(Clone, Copy, Debug)] +enum DifferentialShape { + /// The bare selector `window_diff`. + Selector, + /// `rate(window_diff[60s])`. + Rate, + /// `sum(rate(window_diff[60s]))`, the aggregate over the range function. + SumRate, + /// `sum(window_diff)`, the aggregate over a bare selector. + SumSelector, +} + +impl DifferentialShape { + /// What names a row of this shape's answer, in the sense of [`native_rows`]. + /// + /// The first two shapes keep their hosts, so a row is its `host`. The aggregate without a + /// grouping clause folds every host away, so there is no `host` label to read and a row is + /// whatever label columns the route leaves - all of them, `None` says - and not a name this + /// test gets to assume. + fn row_label(self) -> Option<&'static str> { + match self { + Self::Selector | Self::Rate => Some("host"), + Self::SumSelector | Self::SumRate => None, + } + } +} + +/// The name column of an answer, keyed by the payload row each name belongs to. +type DifferentialNames = BTreeMap<(i64, String), Option>; + +/// The rows of one statement on the requested route through the frontend statement executor, +/// plus the declared name column's value of every row. +/// +/// The names are keyed by the `(timestamp, label)` that names their row rather than zipped with +/// the rows by position: a merge reorders the two windows' answers, so a positional comparison +/// would compare the names of different rows, and a route that lost a name while keeping its rows +/// would compare equal. +async fn differential_rows_and_names( + instance: &Arc, + statement: QueryStatement, + native: bool, + label: Option<&str>, +) -> (Vec<(i64, String, f64)>, Option) { + let output = instance + .statement_executor() + .execute_stmt(statement, native_query_context(native, 4)) + .await + .unwrap(); + let (rows, names) = native_rows_and_names(output, label).await; + let names = names.map(|names| { + rows.iter() + .zip(names) + .map(|((timestamp, label, _), name)| ((*timestamp, label.clone()), name)) + .collect() + }); + (rows, names) +} + +/// The rows of both windows, in the order the comparison expects, refusing an overlap. +fn differential_merge( + first: Vec<(i64, String, f64)>, + second: Vec<(i64, String, f64)>, +) -> Vec<(i64, String, f64)> { + let mut merged = first; + merged.extend(second); + // Both routes answer in this order already; sorting keeps the comparison independent of it. + merged.sort_by(|left, right| (left.0, &left.1).cmp(&(right.0, &right.1))); + for pair in merged.windows(2) { + assert!( + pair[0].0 != pair[1].0 || pair[0].1 != pair[1].1, + "the two windows answered the same point twice: {} at {}", + pair[0].1, + pair[0].0 + ); + } + merged +} + +/// Both windows' name columns, keyed by row, refusing a route that declared the column in one +/// window and not in the other. +fn differential_merge_names( + first: Option, + second: Option, +) -> Option { + match (first, second) { + (None, None) => None, + (Some(mut first), Some(second)) => { + first.extend(second); + Some(first) + } + _ => panic!("the two windows disagree on whether the answer declares a name column"), + } +} + +/// Asserts every row sits on the original grid and returns the grid indices they cover. +fn differential_indices(rows: &[(i64, String, f64)], what: &str) -> Vec { + rows.iter() + .map(|(timestamp, host, _)| { + assert_eq!( + 0, + (timestamp - DIFFERENTIAL_START_MS) % DIFFERENTIAL_STEP_MS, + "{what}: {host} at {timestamp} left the {}ms grid started at {DIFFERENTIAL_START_MS}", + DIFFERENTIAL_STEP_MS + ); + let index = differential_index(*timestamp); + assert!( + (0..DIFFERENTIAL_POINTS as i64).contains(&index), + "{what}: {host} at {timestamp} is outside the statement's grid (index {index})" + ); + index + }) + .collect() +} + +#[tokio::test(flavor = "multi_thread")] +async fn windowed_promql_evaluation_matches_full_range_evaluation() { + common_telemetry::init_default_ut_logging(); + let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( + "windowed_promql_differential", + )) + .await; + let instance = standalone.fe_instance().clone(); + execute_all( + &instance, + &format!("{DIFFERENTIAL_CREATE}; {}", differential_insert()), + QueryContext::arc(), + ) + .await; + + // A bare selector, a range function, and the `sum` of each: the four shapes the v1 allowlist + // admits. Each runs on both routes, and each route is checked against itself only - the + // comparison is full range versus the windows of the same route, never one route against the + // other. + let range_function = format!("rate({DIFFERENTIAL_TABLE}[{DIFFERENTIAL_RANGE}])"); + let sum_of_range_function = format!("sum({range_function})"); + for (query, shape) in [ + (DIFFERENTIAL_TABLE.to_string(), DifferentialShape::Selector), + (range_function.clone(), DifferentialShape::Rate), + (sum_of_range_function, DifferentialShape::SumRate), + ( + format!("sum({DIFFERENTIAL_TABLE})"), + DifferentialShape::SumSelector, + ), + ] { + for native in [false, true] { + let route = if native { "native" } else { "legacy" }; + let what = |span: &str| format!("{query} on the {route} route, {span}"); + let label = shape.row_label(); + + observer.clear(); + let (full, full_names) = + differential_rows_and_names(&instance, differential_full(&query), native, label) + .await; + assert_eq!( + native, + observer.fused().is_some(), + "{}", + what("the route did not run what it was asked for") + ); + assert!(!full.is_empty(), "{}", what("answered no rows")); + + observer.clear(); + let (first, first_names) = differential_rows_and_names( + &instance, + differential_window(&query, 0, DIFFERENTIAL_SPLIT), + native, + label, + ) + .await; + assert_eq!( + native, + observer.fused().is_some(), + "{}", + what("the first window did not run the route it was asked for") + ); + observer.clear(); + let (second, second_names) = differential_rows_and_names( + &instance, + differential_window(&query, DIFFERENTIAL_SPLIT, DIFFERENTIAL_POINTS), + native, + label, + ) + .await; + assert_eq!( + native, + observer.fused().is_some(), + "{}", + what("the second window did not run the route it was asked for") + ); + + let first_indices = differential_indices(&first, &what("the first window")); + let second_indices = differential_indices(&second, &what("the second window")); + let merged = differential_merge(first, second); + let merged_names = differential_merge_names(first_names, second_names); + + // The windows are the halves of the grid and neither reaches past its own end. + assert!( + first_indices + .iter() + .all(|index| *index < DIFFERENTIAL_SPLIT as i64), + "{}", + what("the first window answered past its end") + ); + assert!( + second_indices + .iter() + .all(|index| *index >= DIFFERENTIAL_SPLIT as i64), + "{}", + what("the second window answered before its start") + ); + + // The whole point: the split changes what each statement reads, not what it answers. + assert_eq!( + full, + merged, + "{}", + what("the windows do not answer what the full statement answers") + ); + + // The name column is part of the answer too: whether the statement declares one at all, + // and what each row carries in it, has to survive the split. The names are read row by + // row, keyed by the row they belong to, so a window that lost a name while keeping its + // rows is caught rather than compared against another row's name. + assert_eq!( + full_names, + merged_names, + "{}", + what("the windows do not name the rows the way the full statement names them") + ); + + match shape { + DifferentialShape::Selector => { + // A selector that reads one sample per point keeps the fixture's holes: `a` has + // nothing inside the lookback at indices 24 and 25, and answers on both sides. + for (index, present) in [(23, true), (24, false), (25, false), (26, true)] { + assert_eq!( + present, + full.iter().any(|(timestamp, host, _)| host == "a" + && differential_index(*timestamp) == index), + "{}", + what(&format!("host a at index {index}")) + ); + } + // `c` is the series that is missing for most of the grid. + for (index, present) in [(0, true), (10, false), (20, true), (40, false)] { + assert_eq!( + present, + full.iter().any(|(timestamp, host, _)| host == "c" + && differential_index(*timestamp) == index), + "{}", + what(&format!("host c at index {index}")) + ); + } + } + DifferentialShape::Rate => { + // `rate` answers at the split index even though the window starts there: the reset + // sample and the increments before it are history the second window has to read. + assert!( + full.iter().any(|(timestamp, host, _)| host == "a" + && differential_index(*timestamp) == DIFFERENTIAL_SPLIT as i64), + "{}", + what("rate did not answer at the split index") + ); + // Its range still answers through the lookback holes of the selector. + for index in [24, 25] { + assert!( + full.iter().any(|(timestamp, host, _)| host == "a" + && differential_index(*timestamp) == index), + "{}", + what(&format!("rate at index {index}")) + ); + } + } + // Compared by `full == merged` above: the split does not split a point's vector, + // and an aggregate folds to at most one row per point either way. + DifferentialShape::SumRate | DifferentialShape::SumSelector => {} + } + } + } +}