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]