diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 6fc96b79526..3f0ec130fa9 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -1579,11 +1579,6 @@ pub fn reads_across_series(node: &NativeNode) -> bool { } } -/// The evaluated vector a [`NativeExpr::Merge`] child hands over, or `None` if it is not one. -fn merge_shape_supported(node: &NativeNode) -> Option<(&Arc, &Arc)> { - evaluated_vector(&node.output) -} - /// A validated bound evaluation tree. It carries no run-time state, so one tree serves every /// partition. #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash)] @@ -1878,9 +1873,7 @@ impl NativeNode { } NativeExpr::ScalarOf { input } => { input.validate()?; - let Some((_, input_grid)) = evaluated_vector(&input.output) else { - return Err(invalid("scalar() consumes an evaluated vector")); - }; + let (_, input_grid) = ensure_evaluated(&input.output, "scalar()")?; let NativeType::Scalar(output_grid) = &self.output else { return Err(invalid("scalar() does not produce a scalar")); }; @@ -1893,8 +1886,7 @@ impl NativeNode { let NativeType::Scalar(input_grid) = &input.output else { return Err(invalid("vector() consumes a scalar")); }; - ensure_samples(&self.output, "vector()")?; - if !self.output.samples().is_some_and(|s| s.fields.len() == 1) { + if ensure_samples(&self.output, "vector()")?.fields.len() != 1 { return Err(invalid("vector() produces one field")); } ensure_grid(&self.output, input_grid, "vector()")?; @@ -1924,15 +1916,8 @@ impl NativeNode { } NativeExpr::Merge { input } => { input.validate()?; - let Some((_input_schema, input_grid)) = merge_shape_supported(input) else { - return Err(invalid(&format!( - "a merge consumes an evaluated vector, not {}", - input.output.describe() - ))); - }; - ensure_samples(&self.output, "a merge")?; - ensure_same_fields(&input.output, &self.output, "a merge")?; - ensure_grid(&self.output, input_grid, "a merge")?; + let (_, input_grid) = ensure_evaluated(&input.output, "a merge")?; + ensure_vector_of(self, input, input_grid, "a merge")?; } NativeExpr::Window { input, op } => { input.validate()?; @@ -1958,24 +1943,15 @@ impl NativeNode { )); } } - ensure_samples(&self.output, "a window")?; - ensure_same_fields(&input.output, &self.output, "a window")?; - ensure_grid(&self.output, &op.output_grid, "a window")?; + ensure_vector_of(self, input, &op.output_grid, "a window")?; } NativeExpr::Map { input, op } => { input.validate()?; - let Some((_, input_grid)) = evaluated_vector(&input.output) else { - return Err(invalid(&format!( - "a map consumes an evaluated vector, not {}", - input.output.describe() - ))); - }; + let (_, input_grid) = ensure_evaluated(&input.output, "a map")?; if op.ops.is_empty() { return Err(invalid("a map holds no operation")); } - ensure_samples(&self.output, "a map")?; - ensure_same_fields(&input.output, &self.output, "a map")?; - ensure_grid(&self.output, input_grid, "a map")?; + ensure_vector_of(self, input, input_grid, "a map")?; } NativeExpr::ParameterizedMap { input, @@ -1990,15 +1966,9 @@ impl NativeNode { input.output.describe() ))); }; - Arc::clone(input_grid) + input_grid } else { - let Some((_, input_grid)) = evaluated_vector(&input.output) else { - return Err(invalid(&format!( - "a map consumes an evaluated vector, not {}", - input.output.describe() - ))); - }; - Arc::clone(input_grid) + ensure_evaluated(&input.output, "a map")?.1 }; if parameters.len() != op.arity() { return Err(invalid(&format!( @@ -2007,26 +1977,13 @@ impl NativeNode { parameters.len() ))); } - for parameter in parameters { - parameter.validate()?; - if !matches!(¶meter.output, NativeType::Scalar(grid) if grid.spec() == input_grid.spec()) - { - return Err(invalid( - "a map parameter is not a scalar on its input's grid", - )); - } - } - if op.takes_a_scalar_input() { - if !matches!(&self.output, NativeType::Scalar(grid) if grid.spec() == input_grid.spec()) - { - return Err(invalid( - "a map over a scalar does not answer a scalar on its input's grid", - )); - } - } else { - ensure_samples(&self.output, "a parameterized map")?; - ensure_same_fields(&input.output, &self.output, "a parameterized map")?; - ensure_grid(&self.output, &input_grid, "a parameterized map")?; + ensure_scalar_parameters(parameters, input_grid, "a map parameter")?; + if !op.takes_a_scalar_input() { + ensure_vector_of(self, input, input_grid, "a parameterized map")?; + } else if !is_scalar_on(&self.output, input_grid) { + return Err(invalid( + "a map over a scalar does not answer a scalar on its input's grid", + )); } } NativeExpr::ParameterizedTopK { @@ -2035,27 +1992,16 @@ impl NativeNode { parameter, } => { input.validate()?; - parameter.validate()?; if !matches!(op, BoundVectorOp::TopK { .. }) { return Err(invalid("a parameterized topk operation is not TopK")); } - let Some((_, output_grid)) = evaluated_vector(&self.output) else { - return Err(invalid( - "a parameterized topk does not produce an evaluated vector", - )); - }; - if !matches!(¶meter.output, NativeType::Scalar(grid) if grid.spec() == output_grid.spec()) - { - return Err(invalid( - "a topk parameter is not a scalar on its output grid", - )); - } - let Some((_, input_grid)) = evaluated_vector(&input.output) else { - return Err(invalid("a parameterized topk consumes a non-vector")); - }; - ensure_same_fields(&input.output, &self.output, "a vector operation")?; - ensure_grid(&input.output, input_grid, "a vector operation")?; - ensure_grid(&self.output, input_grid, "a vector operation")?; + let (_, input_grid) = ensure_evaluated(&input.output, "a parameterized topk")?; + ensure_scalar_parameters( + std::slice::from_ref(parameter.as_ref()), + input_grid, + "a topk parameter", + )?; + ensure_vector_of(self, input, input_grid, "a parameterized topk")?; } NativeExpr::ParameterizedHistogram { input, @@ -2063,55 +2009,30 @@ impl NativeNode { parameters, } => { input.validate()?; - if !matches!(op, BoundVectorOp::Histogram(_)) { - return Err(invalid( - "a parameterized histogram operation is not Histogram", - )); - } - let expected = match op { + let arity = match op { BoundVectorOp::Histogram(HistogramFunction::Quantile(_)) => 1, BoundVectorOp::Histogram(HistogramFunction::Fraction { .. }) => 2, _ => { return Err(invalid( - "parameterized histogram operation is not Histogram", + "a parameterized histogram operation is not Histogram", )); } }; - if parameters.len() != expected { + if parameters.len() != arity { return Err(invalid("parameterized histogram has the wrong arity")); } - let Some((_, input_grid)) = evaluated_vector(&input.output) else { - return Err(invalid("a parameterized histogram consumes a non-vector")); - }; - for parameter in parameters { - parameter.validate()?; - if !matches!(¶meter.output, NativeType::Scalar(grid) if grid.spec() == input_grid.spec()) - { - return Err(invalid( - "a histogram parameter is not a scalar on its input grid", - )); - } - } - ensure_same_fields(&input.output, &self.output, "a vector operation")?; - ensure_grid(&self.output, input_grid, "a vector operation")?; + let (_, input_grid) = ensure_evaluated(&input.output, "a parameterized histogram")?; + ensure_scalar_parameters(parameters, input_grid, "a histogram parameter")?; + ensure_vector_of(self, input, input_grid, "a parameterized histogram")?; } NativeExpr::Vector { input, .. } => { input.validate()?; - let Some((_, input_grid)) = evaluated_vector(&input.output) else { - return Err(invalid(&format!( - "a vector operation consumes an evaluated vector, not {}", - input.output.describe() - ))); - }; - ensure_samples(&self.output, "a vector operation")?; - ensure_same_fields(&input.output, &self.output, "a vector operation")?; - ensure_grid(&self.output, input_grid, "a vector operation")?; + let (_, input_grid) = ensure_evaluated(&input.output, "a vector operation")?; + ensure_vector_of(self, input, input_grid, "a vector operation")?; } NativeExpr::Timestamp { input } => { input.validate()?; - let Some((_, input_grid)) = evaluated_vector(&input.output) else { - return Err(invalid("timestamp consumes an evaluated vector")); - }; + let (_, input_grid) = ensure_evaluated(&input.output, "timestamp")?; ensure_samples(&self.output, "timestamp")?; ensure_timestamp_fields(&input.output, &self.output)?; ensure_grid(&self.output, input_grid, "timestamp")?; @@ -2121,24 +2042,13 @@ impl NativeNode { // `Partial` turns a vector into state and `Final` turns state back into a vector. match op.stage { AggregateStage::Complete => { - let Some((_, input_grid)) = evaluated_vector(&input.output) else { - return Err(invalid(&format!( - "a complete aggregate consumes an evaluated vector, not {}", - input.output.describe() - ))); - }; - ensure_samples(&self.output, "a complete aggregate")?; - ensure_same_fields(&input.output, &self.output, "a complete aggregate")?; - ensure_grid(&self.output, input_grid, "a complete aggregate")?; + let (_, input_grid) = + ensure_evaluated(&input.output, "a complete aggregate")?; + ensure_vector_of(self, input, input_grid, "a complete aggregate")?; } AggregateStage::Partial => { - let Some((input_schema, input_grid)) = evaluated_vector(&input.output) - else { - return Err(invalid(&format!( - "a partial aggregate consumes an evaluated vector, not {}", - input.output.describe() - ))); - }; + let (input_schema, input_grid) = + ensure_evaluated(&input.output, "a partial aggregate")?; let NativeType::AggregateState(state) = &self.output else { return Err(invalid(&format!( "a partial aggregate produces aggregate state, not {}", @@ -2150,37 +2060,12 @@ impl NativeNode { input_schema.fields.len(), "a partial aggregate", )?; - let Some((expected_kind, expected_components)) = - aggregate_state_binding(op.kind, op.field_kind) - else { - return Err(DataFusionError::NotImplemented(format!( - "aggregate state is not defined for {:?}", - op.kind - ))); - }; - if state.kind != expected_kind - || state.components.as_ref() != expected_components - { - return Err(DataFusionError::NotImplemented(format!( - "partial {:?} aggregate requires state kind {:?} with components {:?}, found {:?} with {:?}", - op.kind, - expected_kind, - expected_components, - state.kind, - state.components - ))); - } + ensure_state_binding(op, state, "partial")?; if state.grid.spec() != input_grid.spec() { return Err(invalid( "aggregate state is indexed on a grid the input does not produce", )); } - if state.group != op.group { - return Err(invalid( - "aggregate state groups differ from the binding: state built for \ - one `by` or `without` cannot be merged into another", - )); - } } AggregateStage::Final => { let NativeType::AggregateState(state) = &input.output else { @@ -2189,32 +2074,7 @@ impl NativeNode { input.output.describe() ))); }; - let Some((expected_kind, expected_components)) = - aggregate_state_binding(op.kind, op.field_kind) - else { - return Err(DataFusionError::NotImplemented(format!( - "aggregate state is not defined for {:?}", - op.kind - ))); - }; - if state.kind != expected_kind - || state.components.as_ref() != expected_components - { - return Err(DataFusionError::NotImplemented(format!( - "final {:?} aggregate requires state kind {:?} with components {:?}, found {:?} with {:?}", - op.kind, - expected_kind, - expected_components, - state.kind, - state.components - ))); - } - if state.group != op.group { - return Err(invalid( - "aggregate state groups differ from the binding: state built for \ - one `by` or `without` cannot be merged into another", - )); - } + ensure_state_binding(op, state, "final")?; let output = ensure_samples(&self.output, "a final aggregate")?; ensure_field_count( output.fields.len(), @@ -2231,7 +2091,6 @@ impl NativeNode { parameter, } => { input.validate()?; - parameter.validate()?; // φ is read off the parameter's chunks, and a literal hands over none; the compiler // binds a constant φ on the `Aggregate` instead. if matches!(parameter.expr, NativeExpr::Scalar(_)) { @@ -2250,30 +2109,16 @@ impl NativeNode { "a parameterized aggregate at a stage other than `Complete`", )); } - let Some((_, output_grid)) = evaluated_vector(&self.output) else { - return Err(invalid( - "a parameterized aggregate does not produce an evaluated vector", - )); - }; - if !matches!(¶meter.output, NativeType::Scalar(grid) if grid.spec() == output_grid.spec()) - { - return Err(invalid( - "an aggregate parameter is not a scalar on its output grid", - )); - } - let Some((_, input_grid)) = evaluated_vector(&input.output) else { - return Err(invalid(&format!( - "a complete aggregate consumes an evaluated vector, not {}", - input.output.describe() - ))); - }; - ensure_same_fields( - &input.output, - &self.output, - "a parameterized complete aggregate", + let (_, input_grid) = + ensure_evaluated(&input.output, "a parameterized complete aggregate")?; + ensure_scalar_parameters( + std::slice::from_ref(parameter.as_ref()), + input_grid, + "an aggregate parameter", )?; - ensure_grid( - &self.output, + ensure_vector_of( + self, + input, input_grid, "a parameterized complete aggregate", )?; @@ -2296,17 +2141,16 @@ impl NativeNode { if left_grid.spec() != right_grid.spec() { return Err(invalid("a binary operation aligns two different grids")); } - match (&left.output, &right.output) { - (NativeType::Scalar(_), NativeType::Scalar(_)) => { - if !matches!(&self.output, NativeType::Scalar(grid) if grid.spec() == left_grid.spec()) - { + // Both sides carry a grid, so each is a scalar or an evaluated vector. + match (left.output.samples(), right.output.samples()) { + (None, None) => { + if !is_scalar_on(&self.output, left_grid) { return Err(invalid( "two scalars do not produce a scalar on the statement's grid", )); } } - (NativeType::Scalar(_), NativeType::Samples(vector)) - | (NativeType::Samples(vector), NativeType::Scalar(_)) => { + (Some(vector), None) | (None, Some(vector)) => { let Some(output) = self.output.samples() else { return Err(invalid(&format!( "a scalar broadcast produces the vector side's samples, not {}", @@ -2321,7 +2165,7 @@ impl NativeNode { } } // The match pairs fields by position, so it keeps the shorter side's count. - (NativeType::Samples(left_vector), NativeType::Samples(right_vector)) => { + (Some(left_vector), Some(right_vector)) => { let Some(output) = self.output.samples() else { return Err(invalid(&format!( "a binary operation over two vectors produces samples, not {}", @@ -2335,13 +2179,6 @@ impl NativeNode { )?; ensure_grid(&self.output, left_grid, "a binary operation")?; } - // Unreachable: state has no grid, so the checks above already returned. - (NativeType::AggregateState(_), _) | (_, NativeType::AggregateState(_)) => { - return Err(invalid( - "a binary operation reached aggregate state, which has no grid: the \ - grid check above should have rejected it", - )); - } } } NativeExpr::Set { left, right, .. } => { @@ -2370,19 +2207,12 @@ impl NativeNode { right_schema.fields.len() ))); } - ensure_samples(&self.output, "a set operation")?; - ensure_same_fields(&left.output, &self.output, "a set operation")?; - ensure_grid(&self.output, left_grid, "a set operation")?; + ensure_vector_of(self, left, left_grid, "a set operation")?; } NativeExpr::Info { base, info, .. } => { base.validate()?; info.validate()?; - let Some((_, base_grid)) = evaluated_vector(&base.output) else { - return Err(invalid(&format!( - "info consumes an evaluated vector, not {}", - base.output.describe() - ))); - }; + let (_, base_grid) = ensure_evaluated(&base.output, "info")?; // The kernel reads the info side's values as sample times, so it must be an // `InfoTimestamp` selection; a merge above it passes the times through unchanged. let mut source = info.as_ref(); @@ -2412,9 +2242,7 @@ impl NativeNode { if base_grid.spec() != info_grid.spec() { return Err(invalid("info aligns two different grids")); } - ensure_samples(&self.output, "info")?; - ensure_same_fields(&base.output, &self.output, "info")?; - ensure_grid(&self.output, base_grid, "info")?; + ensure_vector_of(self, base, base_grid, "info")?; } } Ok(()) @@ -2542,6 +2370,76 @@ fn evaluated_vector(ty: &NativeType) -> Option<(&Arc, &Arc( + ty: &'a NativeType, + what: &str, +) -> Result<(&'a Arc, &'a Arc)> { + evaluated_vector(ty).ok_or_else(|| { + invalid(&format!( + "{what} consumes an evaluated vector, not {}", + ty.describe() + )) + }) +} + +/// Checks that `node` produces the fields of `input` on `grid`. +fn ensure_vector_of( + node: &NativeNode, + input: &NativeNode, + grid: &Arc, + what: &str, +) -> Result<()> { + ensure_samples(&node.output, what)?; + ensure_same_fields(&input.output, &node.output, what)?; + ensure_grid(&node.output, grid, what) +} + +fn is_scalar_on(ty: &NativeType, grid: &EvalGrid) -> bool { + matches!(ty, NativeType::Scalar(actual) if actual.spec() == grid.spec()) +} + +/// Validates each parameter and checks that it is a scalar on `grid`. +fn ensure_scalar_parameters(parameters: &[NativeNode], grid: &EvalGrid, what: &str) -> Result<()> { + for parameter in parameters { + parameter.validate()?; + if !is_scalar_on(¶meter.output, grid) { + return Err(invalid(&format!( + "{what} is not a scalar on its input's grid" + ))); + } + } + Ok(()) +} + +/// Checks that `state` is the state `op` writes or reads at `stage`. +fn ensure_state_binding( + op: &BoundAggregate, + state: &AggregateStateSchema, + stage: &str, +) -> Result<()> { + let Some((kind, components)) = aggregate_state_binding(op.kind, op.field_kind) else { + return Err(DataFusionError::NotImplemented(format!( + "aggregate state is not defined for {:?}", + op.kind + ))); + }; + if state.kind != kind || state.components.as_ref() != components { + return Err(DataFusionError::NotImplemented(format!( + "{stage} {:?} aggregate requires state kind {kind:?} with components {components:?}, \ + found {:?} with {:?}", + op.kind, state.kind, state.components + ))); + } + if state.group != op.group { + return Err(invalid( + "aggregate state groups differ from the binding: state built for one `by` or \ + `without` cannot be merged into another", + )); + } + Ok(()) +} + /// Checks that a node declares as many fields as its input produces. fn ensure_same_fields(input: &NativeType, output: &NativeType, what: &str) -> Result<()> { let (NativeType::Samples(input), NativeType::Samples(output)) = (input, output) else { diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index f6814b5b1c0..f394885c8fd 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -363,6 +363,31 @@ fn parameterized_topk_validates_scalar_and_grid() { ); } +/// The executor only answers samples here, so a deserialized tree declaring a scalar must not pass. +#[test] +fn a_parameterized_histogram_produces_samples() { + use crate::histogram_eval::HistogramFunction; + + let out = grid(0, 60_000, 4); + let vector = map_over(window_on(input(), None, Arc::clone(&out))); + let make = |output| NativeNode { + expr: NativeExpr::ParameterizedHistogram { + input: Box::new(vector.clone()), + op: BoundVectorOp::Histogram(HistogramFunction::Quantile(0.0)), + parameters: vec![scalar_on(0.9, Arc::clone(&out))], + }, + output, + }; + assert!(make(vector.output.clone()).validate().is_ok()); + let error = make(NativeType::Scalar(Arc::clone(&out))) + .validate() + .unwrap_err(); + assert!( + error.to_string().contains("does not produce samples"), + "{error}" + ); +} + /// A literal hands over no chunk, so the fold would wait for a `φ` that never arrives. #[test] fn a_literal_quantile_parameter_is_refused() {