diff --git a/src/promql/src/extension_plan/fused_series.rs b/src/promql/src/extension_plan/fused_series.rs index a71f14b9bef..47ed17790ca 100644 --- a/src/promql/src/extension_plan/fused_series.rs +++ b/src/promql/src/extension_plan/fused_series.rs @@ -1369,11 +1369,13 @@ fn same_source(node: &NativeNode) -> Option { | NativeExpr::EvalTime { .. } | NativeExpr::Map { .. } | NativeExpr::ParameterizedMap { .. } - // `scalar()`, `topk` and a histogram function read the whole vector at a point, so they - // answer one value (or a whole ranking) rather than one output series per input series. + // `scalar()`, `topk`, a histogram function and a fold with a per-point argument read the + // whole vector at a point, so they answer one value (or a whole ranking, or one series per + // group) rather than one output series per input series. | NativeExpr::ScalarOf { .. } | NativeExpr::ParameterizedTopK { .. } - | NativeExpr::ParameterizedHistogram { .. } => None, + | NativeExpr::ParameterizedHistogram { .. } + | NativeExpr::ParameterizedAggregate { .. } => None, } } @@ -1497,6 +1499,12 @@ fn needs_vector_matching(node: &NativeNode) -> bool { NativeExpr::ParameterizedHistogram { input, parameters, .. } => needs_vector_matching(input) || parameters.iter().any(needs_vector_matching), + // The fold reads its group, and its argument may be a scalar expression with a match of its + // own inside it: `quantile(scalar(a * on(k) b), c)`. A vector match anywhere in the tree + // needs its match keys co-located, wherever it sits. + NativeExpr::ParameterizedAggregate { + input, parameter, .. + } => needs_vector_matching(input) || needs_vector_matching(parameter), NativeExpr::Set { left, right, .. } => { needs_vector_matching(left) || needs_vector_matching(right) } @@ -1598,44 +1606,66 @@ pub fn input_locality(root: &NativeNode) -> InputLocality { /// State rows already carry the cut's full group labels. Histogram suffixes need a coarser key: /// every bound of one histogram and every histogram whose metadata-free outputs collide must /// meet, while the Final kernel still folds separately by the original group labels. +/// +/// A suffix that folds across groups needs every group's rows in one place, whatever the Final's +/// grouping is: splitting the rows of one vector by group would answer one fold per owner rather +/// than the fold of the whole vector. Such a consumer is a whole-vector operation -- the ranking +/// operations, `scalar()`, and the fold whose argument is read per point -- and the walk below +/// records it as it descends, so a `quantile(time(), v)` above a grouped `Final` reads every owner +/// instead of one, and one whose parameter is the state itself reads it at all. fn state_routing(root: &NativeNode) -> Option<(StateGroup, SeriesRouting)> { - fn find(node: &NativeNode, histogram: bool) -> Option<(&Grouping, bool)> { + /// `gathered` says whether a node passed on the way down reads more than one group at a time. + fn find(node: &NativeNode, histogram: bool, gathered: bool) -> Option<(&Grouping, bool, bool)> { match &node.expr { NativeExpr::Aggregate { op, .. } if op.stage == AggregateStage::Final => { - Some((&op.group, histogram)) + Some((&op.group, histogram, gathered)) } + // A fold that is not this one reads the values of the rows below it and folds whole + // groups together, so what it reads has to be in one place. + NativeExpr::Aggregate { input, .. } => find(input, histogram, true), NativeExpr::Vector { input, op } => find( input, histogram || matches!(op, crate::native::plan::BoundVectorOp::Histogram(_)), + gathered, ), // A parameterized histogram is a histogram suffix too: its function folds the bounds of // one histogram, so every bound has to meet where it runs. NativeExpr::ParameterizedHistogram { input, op, .. } => find( input, histogram || matches!(op, crate::native::plan::BoundVectorOp::Histogram(_)), + gathered, ), + // These answer from the whole vector rather than from one series at a time: `scalar()` + // and the per-point `k` of a ranking operation read every series. + NativeExpr::ScalarOf { input } | NativeExpr::ParameterizedTopK { input, .. } => { + find(input, histogram, true) + } + // A fold whose argument is read per point folds its group's whole sample set, and the + // state it reads may sit under either child: as the vector it folds, or as the series + // its `scalar()` argument is answered from. Either way this node reads across groups, + // so neither half may be left to another owner. + NativeExpr::ParameterizedAggregate { + input, parameter, .. + } => find(input, histogram, true).or_else(|| find(parameter, histogram, true)), NativeExpr::Instant { input, .. } | NativeExpr::Window { input, .. } | NativeExpr::Merge { input } | NativeExpr::Map { input, .. } | NativeExpr::Timestamp { input } | NativeExpr::VectorOf { input } - | NativeExpr::ParameterizedMap { input, .. } - | NativeExpr::ScalarOf { input } - | NativeExpr::ParameterizedTopK { input, .. } - | NativeExpr::Aggregate { input, .. } => find(input, histogram), + | NativeExpr::ParameterizedMap { input, .. } => find(input, histogram, gathered), NativeExpr::Binary { left, right, .. } | NativeExpr::Set { left, right, .. } => { - find(left, histogram).or_else(|| find(right, histogram)) + find(left, histogram, gathered).or_else(|| find(right, histogram, gathered)) } NativeExpr::Info { base, info, .. } => { - find(base, histogram).or_else(|| find(info, histogram)) + find(base, histogram, gathered).or_else(|| find(info, histogram, gathered)) } NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => None, } } - let (group, histogram) = find(root, false)?; + let (group, histogram, gathered) = find(root, false, false)?; if histogram { - let owners = if crate::native::split::histogram_group_is_single(group) { + let owners = if gathered || crate::native::split::histogram_group_is_single(group) { StateGroup::Single } else { StateGroup::Grouped @@ -1653,6 +1683,7 @@ fn state_routing(root: &NativeNode) -> Option<(StateGroup, SeriesRouting)> { )) } else { let owners = match group { + _ if gathered => StateGroup::Single, Grouping::By(labels) if labels.is_empty() => StateGroup::Single, _ => StateGroup::Grouped, }; diff --git a/src/promql/src/extension_plan/fused_series/tests.rs b/src/promql/src/extension_plan/fused_series/tests.rs index e0f5cb1e029..9aad09198ef 100644 --- a/src/promql/src/extension_plan/fused_series/tests.rs +++ b/src/promql/src/extension_plan/fused_series/tests.rs @@ -554,6 +554,9 @@ fn declaring_orderings(tree: &NativeTree, orderings: &[SeriesOrdering]) -> Nativ } NativeExpr::ParameterizedTopK { input, parameter, .. + } + | NativeExpr::ParameterizedAggregate { + input, parameter, .. } => { **input = rewrite(input, orderings, seen); **parameter = rewrite(parameter, orderings, seen); @@ -8945,6 +8948,146 @@ fn histogram_split_carries_a_per_point_parameter() { ); } +/// A `quantile` exports no state, with a per-point `φ` or without: the split declines both. +/// +/// Its answer is the quantile of a group's whole sample set, and the quantile of two partitions' +/// quantiles is not the quantile of their union. Reading the `φ` per point changes where the number +/// comes from and nothing about that, so the fold that binds a number and the one that reads the +/// statement's are declined by the same rule. +#[test] +fn a_per_point_quantile_is_not_split() { + let window = rate_tree().root().clone(); + let grid = window + .output + .samples() + .expect("a window produces samples") + .eval_grid + .clone() + .expect("a window's output is evaluated on a grid"); + let output = NativeType::Samples(Arc::new(SeriesSchema { + fields: raw_schema().fields.clone(), + eval_grid: Some(grid.clone()), + })); + let quantile = |parameter: NativeNode| NativeNode { + expr: NativeExpr::ParameterizedAggregate { + input: Box::new(window.clone()), + // Unused: the `φ` this fold reads is its parameter's. + op: BoundAggregate { + kind: AggregateKind::Quantile { quantile: 0.0 }, + group: Grouping::By(Arc::from([Arc::from(JOB)])), + stage: AggregateStage::Complete, + field_kind: FieldKind::Float, + }, + parameter: Box::new(parameter), + }, + output: output.clone(), + }; + // `time()`, and a scalar the statement reads from the series the split would read. + let eval_time = NativeNode { + expr: NativeExpr::EvalTime { date: None }, + output: NativeType::Scalar(Arc::clone(&grid)), + }; + let scalar_of_window = NativeNode { + expr: NativeExpr::ScalarOf { + input: Box::new(window.clone()), + }, + output: NativeType::Scalar(Arc::clone(&grid)), + }; + for parameter in [eval_time, scalar_of_window] { + let tree = NativeTree::try_new(quantile(parameter)).expect("the bound tree is legal"); + assert!( + FusedSeries::split_aggregate(&tree, TIME).unwrap().is_none(), + "a per-point quantile must keep the plan it had: {tree}" + ); + } +} + +/// A fold above a state input reads every owner of the `Final` it folds. +/// +/// The rows of a grouped `Final` state are split by their group's labels, which is how a split +/// aggregate folds in parallel: each owner folds its own groups. A fold above that `Final` reads +/// whole vectors, though, so the same split answers something else there: an ungrouped `quantile` +/// is the quantile of every group's samples at once, and one fold per owner is a set of per-group +/// quantiles instead. The state is therefore gathered when the fold above it reads across groups, +/// wherever that fold sits: `quantile(time(), v)` reads the state as its input, and +/// `quantile(scalar(v), v)` reads it through the parameter, where the routing walk finds it too. +#[test] +fn a_fold_across_groups_gathers_the_state_it_reads() { + let out = grid(); + let samples = NativeType::Samples(Arc::new(SeriesSchema { + fields: raw_schema().fields.clone(), + eval_grid: Some(Arc::clone(&out)), + })); + let state = Arc::new(AggregateStateSchema { + group: Grouping::By(Arc::new([Arc::from(JOB)])), + kind: AggregateStateKind::Sum, + components: Arc::from([StateComponent::Value, StateComponent::Compensation]), + accumulators: raw_schema().fields.clone(), + grid: Arc::clone(&out), + }); + let bound_input = |output: NativeType| NativeNode { + expr: NativeExpr::Input(BoundInput { + output: output.clone(), + source_index: 0, + ordering: SeriesOrdering::Contiguous, + }), + output, + }; + // `sum by (job) (…)` at the end of its fold: one row per group and point. + let final_over_state = NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(bound_input(NativeType::AggregateState(Arc::clone(&state)))), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Grouping::By(Arc::new([Arc::from(JOB)])), + stage: AggregateStage::Final, + field_kind: FieldKind::Float, + }, + }, + output: samples.clone(), + }; + let eval_time = NativeNode { + expr: NativeExpr::EvalTime { date: None }, + output: NativeType::Scalar(Arc::clone(&out)), + }; + let quantile = |input: NativeNode, parameter: NativeNode| NativeNode { + expr: NativeExpr::ParameterizedAggregate { + input: Box::new(input), + op: BoundAggregate { + kind: AggregateKind::Quantile { quantile: 0.5 }, + group: Grouping::By(Arc::from([])), + stage: AggregateStage::Complete, + field_kind: FieldKind::Float, + }, + parameter: Box::new(parameter), + }, + output: samples.clone(), + }; + // `quantile(time(), sum by (job) (…))`: ungrouped, so the fold folds every group together. + let across = quantile(final_over_state.clone(), eval_time); + assert_eq!( + Some((super::StateGroup::Single, SeriesRouting::CanonicalLabels)), + super::state_routing(&across), + "a fold across the Final's groups must read them on one owner" + ); + // `quantile(scalar(sum by (job) (…)), v)`: the state is read by the parameter, which is one + // value of the whole vector, so it is as much a fold across groups as the one above. + let through_parameter = quantile( + bound_input(samples.clone()), + NativeNode { + expr: NativeExpr::ScalarOf { + input: Box::new(final_over_state), + }, + output: NativeType::Scalar(Arc::clone(&out)), + }, + ); + assert_eq!( + Some((super::StateGroup::Single, SeriesRouting::CanonicalLabels)), + super::state_routing(&through_parameter), + "the Final under the fold's parameter is the state this tree reads" + ); +} + #[test] fn histogram_final_replaces_incompatible_state_router() { for (group, old_width, target_width, required_width, old_policy, reuse) in [ diff --git a/src/promql/src/native/aggregate.rs b/src/promql/src/native/aggregate.rs index c99d5d0a02d..128ad9b4aa6 100644 --- a/src/promql/src/native/aggregate.rs +++ b/src/promql/src/native/aggregate.rs @@ -101,9 +101,18 @@ enum Fold { /// would have. Nothing here is grouped: the kernel groups, and it groups the same way for a chunk as /// for a series of its own. struct QuantileInput { - /// The φ the query wrote. The kernel reads it as Prometheus does, so a value outside `[0, 1]` - /// answers `-Infinity` or `+Infinity` rather than being refused here. - quantile: f64, + /// The φ the query wrote, when the query wrote it: a fold that bound its argument folds with + /// this one number at every point. The kernel reads it as Prometheus does, so a value outside + /// `[0, 1]` answers `-Infinity` or `+Infinity` rather than being refused here. `None` for a fold + /// whose φ is read per point, which is what `parameter` holds instead. + quantile: Option, + /// The φ read per point, when the query left it to the statement's own evaluation: the one + /// unlabelled scalar series the node held from its parameter child, on this node's grid. + /// + /// It is kept beside the retained input because the kernel reads it per point, exactly as the + /// parameter a bound φ is turned into is read: `q` with no sample at a point leaves the point + /// unanswered, as it does for the built one. + parameter: Option, /// One entry per series this node was handed. series: Vec, /// The histogram tables the retained chunks index into, by the address of the allocation behind @@ -152,6 +161,17 @@ impl QuantileInput { /// capacity here counts every slot the vector owns, occupied or not. Counting the struct in both /// would charge each occupied slot twice; counting it in neither would leave every slot the /// vector holds uncovered. + /// + /// The parameter is the third figure: a φ read per point is one series this node holds from the + /// moment its parameter child hands it over until the kernel reads it, so it is counted from + /// [`series_bytes`] however long it stays. A φ the query bound is not held at all - it is + /// rebuilt from the binding's one number when the fold answers. + /// + /// That series sits inline, in the `Option` slot of this struct, so the descriptor is + /// what `size_of::()` above already counts: the parameter adds the heap beside it and not + /// a second descriptor. [`series_bytes`] measures a series it takes by reference, so it counts + /// the struct as well; the subtraction here is what keeps one held series from being billed one + /// descriptor twice. fn bytes(&self) -> usize { std::mem::size_of::() .saturating_add( @@ -159,6 +179,9 @@ impl QuantileInput { .capacity() .saturating_mul(std::mem::size_of::()), ) + .saturating_add(self.parameter.as_ref().map_or(0, |parameter| { + series_bytes(parameter).saturating_sub(std::mem::size_of::()) + })) .saturating_add(self.held) } } @@ -245,7 +268,7 @@ impl AggregateRuntime { // own and is built by [`Self::new_quantile`]. The φ is the only parameter an aggregate // carries, and the arm that names the kind is the one place it is read. AggregateKind::Quantile { quantile } => { - return Self::new_quantile(op, quantile, schema, buffer); + return Self::new_quantile(op, Some(quantile), schema, buffer); } }; let (state_kind, state_components) = aggregate_state_binding(op.kind, op.field_kind) @@ -325,12 +348,13 @@ impl AggregateRuntime { /// so the grid the kernel reads its parameter on is there before this runs. fn new_quantile( op: BoundAggregate, - quantile: f64, + quantile: Option, schema: Arc, buffer: &mut NodeBuffer, ) -> Result { let retained = QuantileInput { quantile, + parameter: None, series: Vec::new(), tables: HashSet::new(), buffers: HashSet::new(), @@ -350,6 +374,53 @@ impl AggregateRuntime { }) } + /// The states of a `Complete` aggregate whose one argument is read at every grid point. + /// + /// Only `quantile` has such an argument, and its fold keeps no number of its own: the φ arrives + /// as a series from the node's parameter child ([`Self::hold_parameter`]), so the binding's + /// constant is not read here at all. Everything else about the fold is the bound one's -- the + /// stage, the layout, and the sample set it keeps until the input ends -- which is why this is + /// [`Self::new_quantile`] with no constant to fall back on rather than a second kind of state. + pub(crate) fn new_parameterized( + op: BoundAggregate, + schema: Arc, + buffer: &mut NodeBuffer, + ) -> Result { + if !matches!(op.kind, AggregateKind::Quantile { .. }) { + return Err(DataFusionError::NotImplemented(format!( + "the runtime reads a per-point argument only for `quantile`, not for {:?}", + op.kind + ))); + } + Self::new_quantile(op, None, schema, buffer) + } + + /// Keeps the φ this node reads at every grid point, in the one unlabelled scalar series its + /// parameter child handed over. + /// + /// The series is already reserved: it arrives through the driver's `hold_scalar`, which grows the + /// same reservation by [`series_bytes`] before the chunk is kept, exactly as it does for a + /// broadcast scalar or a `topk` parameter. Adopting it therefore only settles on what the node + /// holds -- which counts it once, from [`QuantileInput::bytes`] -- rather than growing for a + /// second allocation that was never made: a pool that holds the handoff must not refuse a + /// handoff that allocates nothing. + pub(crate) fn hold_parameter( + &mut self, + parameter: Series, + buffer: &mut NodeBuffer, + ) -> Result<()> { + let Some(retained) = self.retained.as_mut() else { + return Err(no_fold(&self.describe())); + }; + if retained.parameter.is_some() { + return Err(DataFusionError::Execution( + "a `quantile` aggregate reads one parameter, and it already holds one".into(), + )); + } + retained.parameter = Some(parameter); + buffer.resize(retained.bytes()) + } + /// What consuming `chunk` reserves while it is consumed. /// /// A point-wise fold drops the chunk at the end of the call and keeps only its states, so the @@ -709,17 +780,22 @@ impl AggregateRuntime { } /// Answers a `quantile` from the input it kept, and hands the series over. /// - /// The parameter is the number the query wrote, so every point it covers carries it: the kernel - /// reads `q` per point from an unlabelled single-field scalar on the aggregate's own grid, and a - /// point that scalar has no value at is a point with no result. That case cannot arise from a - /// constant, but the kernel keeps the rule for the parameter it is written for. + /// The kernel reads `q` per point from an unlabelled single-field scalar on the aggregate's own + /// grid, and a point that scalar has no value at is a point with no result. Which scalar that is + /// depends on what the query wrote: the φ the node held from its parameter child, or -- for a + /// number bound on the tree -- one built over the points the input holds, so that every point it + /// covers carries it. (A point the held series has no sample at is unanswered, exactly as a + /// missing `q` is in the kernel; `scalar(...)`, the shape that produces one per point, answers + /// NaN rather than no sample, so a statement whose `foo` holds nothing answers NaN there.) /// - /// The parameter covers the points the input holds and not the window they sit in: the kernel - /// reads `q` only where a member has a sample, so a sparse input's parameter is as wide as its - /// rows. A parameter over the envelope would instead allocate every position between two + /// A built parameter covers the points the input holds and not the window they sit in: the + /// kernel reads `q` only where a member has a sample, so a sparse input's parameter is as wide + /// as its rows. A parameter over the envelope would instead allocate every position between two /// far-apart points -- a span sized by the statement's range rather than by the data it reads, /// which the pool never admitted. The parameter is booked from the bound its rows give before it - /// exists, and settles on its exact figure once it is built. + /// exists, and settles on its exact figure once it is built. A held parameter is not built here + /// and needs no such bound: it was reserved when the node adopted it, which is what + /// [`QuantileInput::bytes`] counts ever since. /// /// The reservation covers what is held while the kernel runs -- the input, that parameter, and /// the kernel's workspace -- and then settles on the series the kernel answered, exactly as a @@ -738,25 +814,57 @@ impl AggregateRuntime { "a `quantile` aggregate needs an evaluated grid to read its parameter on".into(), ) })?; - let workspace = quantile_workspace_bytes(&self.schema, &input); - // Admitted before the parameter exists, because building it is what makes this node hold - // it: the bound is what a parameter over the input's points can take, and the resize below - // settles on what it did take. + // The points the kernel copies the parameter over. A held `φ` covers the grid the statement + // evaluated it on, which the input's rows say nothing about: one row of input beside a + // `time()` over a million grid points is a million pairs, not one. A built one covers the + // points the input holds, and the input's rows bound those. + let parameter_points = match &input.parameter { + Some(parameter) => parameter.time.len(), + None => input.series.iter().map(|series| series.time.len()).sum(), + }; + let workspace = quantile_workspace_bytes(&self.schema, &input, parameter_points); + // A built parameter is admitted before it exists, because building it is what makes this + // node hold it: the bound is what a parameter over the input's points can take, and the + // resize below settles on what it did take. A held one is already counted by + // `input.bytes()`, so reserving for it again would charge the same series twice. + let built_bound = match (&input.parameter, input.quantile) { + (None, Some(_)) => quantile_parameter_bound_bytes(&input), + _ => 0, + }; buffer.resize( input .bytes() - .saturating_add(quantile_parameter_bound_bytes(&input)) + .saturating_add(built_bound) .saturating_add(workspace) .saturating_add(queue_bytes), )?; - let positions = quantile_positions(&input); - let parameter = quantile_parameter(&grid, input.quantile, &positions)?; - // The collected positions are what the bound above covered and what this node no longer - // holds, so they go before the figure settles. - drop(positions); + // The φ the kernel reads: the series this node held from its parameter child, or -- when the + // query bound the number -- one built over the points the input holds. + let mut built = None; + if input.parameter.is_none() { + let Some(quantile) = input.quantile else { + return Err(DataFusionError::Internal( + "a per-point `quantile` parameter was never handed over".into(), + )); + }; + let positions = quantile_positions(&input); + built = Some(quantile_parameter(&grid, quantile, &positions)?); + // The collected positions are what the bound above covered and what this node no longer + // holds, so they go before the figure settles. + drop(positions); + } + let parameter = input + .parameter + .as_ref() + .or(built.as_ref()) + .expect("a parameter is either held or built just above"); let held = input .bytes() - .saturating_add(series_bytes(¶meter)) + .saturating_add(if input.parameter.is_some() { + 0 + } else { + series_bytes(parameter) + }) .saturating_add(workspace); buffer.resize(held.saturating_add(queue_bytes))?; let names: Vec<&str> = match &self.op.group { @@ -768,10 +876,13 @@ impl AggregateRuntime { BoundGrouping::By(_) => Grouping::By(&names), BoundGrouping::Without(_) => Grouping::Without(&names), }; - let output = aggregate_quantile(&self.schema, &input.series, ¶meter, grouping) + let output = aggregate_quantile(&self.schema, &input.series, parameter, grouping) .map_err(|error| folded_chunk(&self.describe(), error))?; drop(names); - drop(parameter); + // The parameter's use ends with the kernel call, and a built one is dropped here for the + // same reason the input is: the settle below names what the node holds from then on. A + // held one goes with the input it is part of. + drop(built); // The input is what this node held until the kernel answered, and it is given back before // the reservation settles on the answer: the settle below is what the node holds from then // on, so it must be read from the set that is really alive -- the answer and the queue -- @@ -857,13 +968,22 @@ fn quantile_parameter_bound_bytes(input: &QuantileInput) -> usize { /// [`aggregate_quantile`] reports no workspace as it allocates, so this is an estimate reserved once /// before it runs, in the same spirit as the whole-vector kernels'. What it covers: the state it /// keeps per member (one position list, one heap entry and one cursor per field), its own copy of the -/// parameter (one `(position, φ)` pair per point the parameter covers, which the input's rows bound -/// because the parameter is only built over the points the input holds), the temporaries of one grid -/// point (its members' values, the copy the kernel sorts, and one row of the width it folds), and the -/// rows it builds -- the group being built and the groups it has already handed over. The row count is -/// the input's own: a group's rows are the points at least one of its members holds a sample at, so -/// the input's rows bound every group's rows and their sum. -fn quantile_workspace_bytes(schema: &SeriesSchema, input: &QuantileInput) -> usize { +/// parameter, the temporaries of one grid point (its members' values, the copy the kernel sorts, and +/// one row of the width it folds), and the rows it builds -- the group being built and the groups it +/// has already handed over. The row count is the input's own: a group's rows are the points at least +/// one of its members holds a sample at, so the input's rows bound every group's rows and their sum. +/// +/// The parameter copy is `parameter_points` pairs and not the input's rows: the kernel reads the +/// whole parameter into one `(position, φ)` per point it covers before it folds anything, so a dense +/// `time()` read against one row of input copies every point of the grid, and sizing that copy from +/// the input's one row would reserve a pair for a million points. What the kernel iterates are the +/// parameter's own positions -- the points a bound `φ` was built over and the points a held one +/// covers -- so the caller reports that count rather than this reading the input for it. +fn quantile_workspace_bytes( + schema: &SeriesSchema, + input: &QuantileInput, + parameter_points: usize, +) -> usize { let width = schema.fields.len(); let members = input.series.len(); let rows: usize = input.series.iter().map(|series| series.time.len()).sum(); @@ -880,7 +1000,7 @@ fn quantile_workspace_bytes(schema: &SeriesSchema, input: &QuantileInput) -> usi .saturating_add(2 * std::mem::size_of::()) .saturating_add(1); // The parameter copy, charged twice for the capacity a growing vector keeps over its length. - let parameter_copy = 2 * rows.saturating_mul(std::mem::size_of::<(usize, f64)>()); + let parameter_copy = 2 * parameter_points.saturating_mul(std::mem::size_of::<(usize, f64)>()); members .saturating_mul(per_member) .saturating_add(per_point) @@ -981,6 +1101,71 @@ mod tests { .unwrap() } + /// The φ this node folds is a series over `points` grid points, as `time()` or `scalar()` + /// hands one over. + fn parameter_series(points: usize) -> Series { + let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1, 4).unwrap()).unwrap()); + let schema = Arc::new(SeriesSchema { + fields: vec![FieldSpec { + name: Arc::from("scalar"), + }] + .into(), + eval_grid: Some(Arc::clone(&grid)), + }); + constant_series(&schema, GridRange::try_new(grid, 0, points).unwrap(), 0.5).unwrap() + } + + /// Adopting the parameter transfers the charge it arrived with, and bills it once. + /// + /// The series is grown onto this node's reservation before it is handed over, because it + /// outlives the child that produced it; `hold_scalar` is what does that, and it does it on this + /// node's buffer. Adopting it allocates nothing, so the node settles on what it holds -- the + /// series once, its descriptor counted by the state that holds it inline -- and a pool of + /// exactly that figure admits the handoff. Growing for the same series again would ask for the + /// double of what arrived, and a pool that holds the handoff would refuse it. + #[test] + fn adopting_a_parameter_charges_it_once() { + let parameter = parameter_series(4); + let held = series_bytes(¶meter); + // What the node holds once the series arrived and was grown onto it, and what it holds with + // the same series adopted: the second is the first less the descriptor the state carries + // inline, because a series held in a slot costs the slot and the heap and not the slot + // twice. The pool holds exactly the handoff, so an admission that asks for the series a + // second time has nowhere to put it. + let handoff = std::mem::size_of::() + held; + let adopted = handoff - std::mem::size_of::(); + let pool: Arc = Arc::new( + datafusion::execution::memory_pool::GreedyMemoryPool::new(handoff), + ); + let mut buffer = NodeBuffer::new( + "test quantile", + Arc::new(crate::native::metrics::NodeMetrics::default()), + &pool, + ); + let mut runtime = AggregateRuntime::new_parameterized( + BoundAggregate { + kind: AggregateKind::Quantile { quantile: 0.0 }, + group: BoundGrouping::By(Arc::new([])), + stage: AggregateStage::Complete, + field_kind: crate::extension_plan::FieldKind::Float, + }, + schema(), + &mut buffer, + ) + .unwrap(); + // The handoff the parameter child makes: the series is reserved on this node's buffer + // before it is kept, exactly as `hold_scalar` does for every scalar operand. + buffer.grow(held).unwrap(); + runtime + .hold_parameter(parameter, &mut buffer) + .expect("a pool that holds the handoff refused the adoption"); + assert_eq!( + pool.reserved(), + adopted, + "the adopted parameter is billed once, descriptor included" + ); + } + fn collected(collector: &PromqlAnnotationCollector) -> (Vec, Vec) { let (mut warnings, mut infos) = (Vec::new(), Vec::new()); collector.append_to(&mut warnings, &mut infos); diff --git a/src/promql/src/native/canonicalize.rs b/src/promql/src/native/canonicalize.rs index 900b85d09c5..f2d5a8b2004 100644 --- a/src/promql/src/native/canonicalize.rs +++ b/src/promql/src/native/canonicalize.rs @@ -181,6 +181,18 @@ fn rewrite(node: &NativeNode, source_tags: &[Vec]) -> DfResult NativeExpr::ParameterizedAggregate { + input: Box::new(canonical(rewrite(input, source_tags)?, source_tags)), + op: op.clone(), + parameter: Box::new(rewrite(parameter, source_tags)?), + }, // Vector operations consume canonical series: ranking counts them, and presence checks and // folds must not silently consume overlapping fragments that a merge would reject. NativeExpr::Vector { input, op } => NativeExpr::Vector { diff --git a/src/promql/src/native/canonicalize/tests.rs b/src/promql/src/native/canonicalize/tests.rs index 8b58bb8b21b..203f27737a9 100644 --- a/src/promql/src/native/canonicalize/tests.rs +++ b/src/promql/src/native/canonicalize/tests.rs @@ -313,6 +313,9 @@ fn merges(tree: &NativeTree) -> usize { | NativeExpr::Merge { input } | NativeExpr::Aggregate { input, .. } | NativeExpr::Vector { input, .. } => vec![input.as_ref()], + NativeExpr::ParameterizedAggregate { + input, parameter, .. + } => vec![input.as_ref(), parameter.as_ref()], NativeExpr::Binary { left, right, .. } | NativeExpr::Set { left, right, .. } | NativeExpr::Info { diff --git a/src/promql/src/native/display.rs b/src/promql/src/native/display.rs index 95b34eda0b8..393b8c54522 100644 --- a/src/promql/src/native/display.rs +++ b/src/promql/src/native/display.rs @@ -35,8 +35,8 @@ use crate::histogram_eval::HistogramFunction; use crate::map::MathOp; use crate::native::metrics::NodeMetricsSnapshot; use crate::native::plan::{ - AggregateKind, AggregateStage, BoundVectorOp, BoundWindow, Grouping, InstantValue, MapOp, - NativeExpr, NativeNode, NativeTree, NativeType, ParameterizedOp, + AggregateKind, AggregateStage, BoundAggregate, BoundVectorOp, BoundWindow, Grouping, + InstantValue, MapOp, NativeExpr, NativeNode, NativeTree, NativeType, ParameterizedOp, }; use crate::range_eval::RangeFunction; use crate::select::{MatchOp, SortOrder}; @@ -217,21 +217,12 @@ fn describe(node: &NativeNode) -> String { format!("count_values {label:?} {}", grouping(group)) } }, - NativeExpr::Aggregate { op, .. } => format!( - "{} {} [{}] {}", - aggregate_kind(op.kind), - match &op.group { - Grouping::By(_) => "by", - Grouping::Without(_) => "without", - }, - label_list(match &op.group { - Grouping::By(labels) | Grouping::Without(labels) => labels, - }), - match op.stage { - AggregateStage::Complete => "complete", - AggregateStage::Partial => "partial", - AggregateStage::Final => "final", - } + NativeExpr::Aggregate { op, .. } => describe_aggregate(op, &aggregate_kind(op.kind)), + // The `φ` this fold reads is not on its binding, so the line leaves the constant out and + // says where the value comes from instead. + NativeExpr::ParameterizedAggregate { op, .. } => format!( + "{}, parameter per point", + describe_aggregate(op, aggregate_name(op.kind)) ), NativeExpr::Binary { matching, .. } => format!( "{}{} {} {}{}", @@ -300,18 +291,49 @@ fn fill(values: FillValues) -> String { ) } +/// An aggregate: what it folds, how its groups are identified and which stage it reports. +/// +/// `folded` is how the kind is named: with the constant it bound, for a fold that reads one, and +/// without it for a fold whose argument is read per point. +fn describe_aggregate(op: &BoundAggregate, folded: &str) -> String { + format!( + "{} {} [{}] {}", + folded, + match &op.group { + Grouping::By(_) => "by", + Grouping::Without(_) => "without", + }, + label_list(match &op.group { + Grouping::By(labels) | Grouping::Without(labels) => labels.as_ref(), + }), + match op.stage { + AggregateStage::Complete => "complete", + AggregateStage::Partial => "partial", + AggregateStage::Final => "final", + } + ) +} + /// The PromQL name of an aggregate, with the constant argument it was bound to. fn aggregate_kind(kind: AggregateKind) -> String { match kind { - AggregateKind::Sum => "sum".to_string(), - AggregateKind::Avg => "avg".to_string(), - AggregateKind::Count => "count".to_string(), - AggregateKind::Min => "min".to_string(), - AggregateKind::Max => "max".to_string(), - AggregateKind::Group => "group".to_string(), - AggregateKind::Stddev => "stddev".to_string(), - AggregateKind::Stdvar => "stdvar".to_string(), AggregateKind::Quantile { quantile } => format!("quantile {quantile}"), + other => aggregate_name(other).to_string(), + } +} + +/// The PromQL name of an aggregate, without the argument it may have bound. +fn aggregate_name(kind: AggregateKind) -> &'static str { + match kind { + AggregateKind::Sum => "sum", + AggregateKind::Avg => "avg", + AggregateKind::Count => "count", + AggregateKind::Min => "min", + AggregateKind::Max => "max", + AggregateKind::Group => "group", + AggregateKind::Stddev => "stddev", + AggregateKind::Stdvar => "stdvar", + AggregateKind::Quantile { .. } => "quantile", } } @@ -472,6 +494,7 @@ fn kind(expr: &NativeExpr) -> &'static str { NativeExpr::ScalarOf { .. } => "ScalarOf", NativeExpr::ParameterizedMap { .. } => "ParameterizedMap", NativeExpr::ParameterizedTopK { .. } => "ParameterizedTopK", + NativeExpr::ParameterizedAggregate { .. } => "ParameterizedAggregate", NativeExpr::ParameterizedHistogram { .. } => "ParameterizedHistogram", NativeExpr::Set { .. } => "Set", NativeExpr::Info { .. } => "Info", @@ -509,6 +532,12 @@ fn child_segments(node: &NativeNode) -> Vec<(&NativeNode, Cow<'static, str>)> { child(&mut children, "input", input); child(&mut children, "parameter", parameter); } + NativeExpr::ParameterizedAggregate { + input, parameter, .. + } => { + child(&mut children, "input", input); + child(&mut children, "parameter", parameter); + } NativeExpr::ParameterizedHistogram { input, parameters, .. } => { diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 22023182916..ebc22264a0f 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -2792,6 +2792,13 @@ enum RuntimeOp { vector: VectorRuntime, state: NodeState, }, + ParameterizedAggregate { + input: Box, + // Taken and dropped once the fold holds the series it answers with. + parameter: Option>, + aggregate: AggregateRuntime, + state: NodeState, + }, ParameterizedHistogram { input: Box, // Each parameter is taken and dropped after its scalar values are installed. @@ -2863,10 +2870,26 @@ impl LeafKind { struct InputSlot { source_index: usize, kind: LeafKind, + /// Whether the series whose chunk this leaf most recently handed over is still open. open_source_series: bool, + /// Whether the series whose chunk the caller most recently queued here is still open. + /// + /// Finality is a property of what the caller sent and not of what the tree has pulled: a node + /// that decides nothing before its whole input is there, such as an aggregate waiting for its + /// parameter, can end a run with a chunk still queued, and that chunk is what says whether the + /// input was closed. Following the handovers alone would read the queued chunk as never having + /// arrived, and the truncated input it holds as a closed one. + open_queued_series: bool, state: NodeState, } +impl InputSlot { + /// Whether an input the caller ended here left a series open, handed over or still queued. + fn ends_open(&self) -> bool { + self.open_source_series || self.open_queued_series + } +} + /// State for one execution of a bound tree. The live tree and input slots are dropped together /// when the executor finishes or fails; the public state remains available for inspection. pub struct NativeExecutionState { @@ -2966,6 +2989,7 @@ impl RuntimeNode { source_index: bound.source_index, kind: LeafKind::of(&node.output)?, open_source_series: false, + open_queued_series: false, state: NodeState::new( format!( "native.input at {location} (source_index={})", @@ -3466,6 +3490,53 @@ impl RuntimeNode { state, } } + NativeExpr::ParameterizedAggregate { + input, + op, + parameter, + } => { + let schema = node + .output + .samples() + .or_else(|| input.output.samples()) + .cloned() + .ok_or_else(|| { + DataFusionError::Execution( + "a parameterized aggregate does not produce samples".into(), + ) + })?; + let mut state = NodeState::new( + format!("native.aggregate at {location}"), + Arc::clone(&metrics), + pool, + ); + let aggregate = + AggregateRuntime::new_parameterized(op.clone(), schema, &mut state.buffer)?; + let child = Self::build( + input, + pool, + inputs, + binary_before, + format!("{location}.input"), + duplicate_evidence.clone(), + )?; + // The input is built before the parameter, the order the selector walk binds the + // two sources in. + let parameter = Self::build( + parameter, + pool, + inputs, + binary_before, + format!("{location}.parameter"), + duplicate_evidence.clone(), + )?; + RuntimeOp::ParameterizedAggregate { + input: Box::new(child), + parameter: Some(Box::new(parameter)), + aggregate, + state, + } + } NativeExpr::ParameterizedTopK { input, op, @@ -3645,6 +3716,9 @@ impl RuntimeNode { } RuntimeOp::ParameterizedTopK { input, parameter, .. + } + | RuntimeOp::ParameterizedAggregate { + input, parameter, .. } => { input.register_metrics(&format!("{name}.input"), set, partition); if let Some(parameter) = parameter { @@ -3724,6 +3798,12 @@ impl RuntimeNode { parameter, state, .. + } + | RuntimeOp::ParameterizedAggregate { + input, + parameter, + state, + .. } => state .buffer .reservation @@ -3803,6 +3883,20 @@ impl RuntimeNode { aggregate.set_annotations(collector.clone()); input.set_annotations(collector); } + RuntimeOp::ParameterizedAggregate { + input, + parameter, + aggregate, + .. + } => { + // The fold reports skipped samples exactly as the bound one does, so it needs the + // collector too; a parameter is a scalar expression and reads none of them. + aggregate.set_annotations(collector.clone()); + input.set_annotations(collector.clone()); + if let Some(parameter) = parameter { + parameter.set_annotations(collector); + } + } RuntimeOp::Timestamp { input, .. } => input.set_annotations(collector), RuntimeOp::Vector { input, vector, .. } => { vector.annotations = Some(collector.clone()); @@ -4318,6 +4412,72 @@ impl RuntimeNode { // are counted rather than read as its positions, as a binary result's are. state.pop_queued(evaluated_values) } + RuntimeOp::ParameterizedAggregate { + input, + parameter, + aggregate, + state, + } => { + let fold = aggregate; + // The φ is read at every point the fold answers, so it is drained whole before the + // fold computes an answer: a point's answer is decided from the group's samples and + // the φ the statement evaluated there, and the fold keeps the group's samples rather + // than a per-point state, so it cannot be handed the φ later. What has arrived of + // the input is still read while the φ is pending, which is what keeps it out of the + // source queue (see the pull below). + if let Some(parameter_node) = parameter.as_mut() { + let mut slot = None; + let mut held = 0usize; + while let Some(chunk) = parameter_node.pull(inputs, inputs_finished)? { + state + .hold_scalar(&mut held, &mut slot, chunk) + .map_err(|error| state.context(error))?; + } + let series = { + // A parameter that folds its own input (a `scalar()` over a selector) has + // nothing to hand over until that input ends, so its absence is a reason to + // be pulled again rather than a failure. Being pulled again is not idling: + // this fold keeps its whole input, so the chunks that have arrived are + // retained now, exactly as they would be once the φ is in hand. Leaving them + // where they are would bill them twice over for the same buffer -- the queue + // charges every queued chunk for the whole allocation it is a slice of + // (`NativeChunk::bytes`, where the retainer below bills that allocation + // once), so an input of a thousand slices of one buffer would be refused by + // a pool that holds the buffer a thousand times rather than once. + if !parameter_node.settled(inputs) { + while let Some(chunk) = input.pull(inputs, inputs_finished)? { + state + .retain_aggregate(fold, chunk) + .map_err(|error| state.context(error))?; + } + return Ok(None); + } + slot.ok_or_else(|| { + DataFusionError::Execution( + "the quantile parameter produced no scalar".into(), + ) + })? + }; + fold.hold_parameter(series, &mut state.buffer) + .map_err(|error| state.context(error))?; + // Finish windows before dropping the consumed subtree; its children may still + // hold charged emitted history or scalar series even after the scalar was read. + parameter_node.finish_windows()?; + *parameter = None; + } + while let Some(chunk) = input.pull(inputs, inputs_finished)? { + state + .retain_aggregate(fold, chunk) + .map_err(|error| state.context(error))?; + } + if !inputs_finished || !input.settled(inputs) { + return Ok(None); + } + state + .compute_aggregate(fold) + .map_err(|error| state.context(error))?; + state.pop_queued(evaluated_values) + } RuntimeOp::ParameterizedTopK { input, parameter, @@ -4624,6 +4784,14 @@ impl RuntimeNode { aggregate, state, } => state.queued.is_empty() && aggregate.computed && input.settled(inputs), + // The same fold, with its parameter released after the fold holds it: `computed` already + // implies the parameter was consumed. + RuntimeOp::ParameterizedAggregate { + input, + aggregate, + state, + .. + } => state.queued.is_empty() && aggregate.computed && input.settled(inputs), RuntimeOp::Vector { input, vector, @@ -4685,6 +4853,9 @@ impl RuntimeNode { } RuntimeOp::ParameterizedTopK { input, parameter, .. + } + | RuntimeOp::ParameterizedAggregate { + input, parameter, .. } => { let mut flushed = input.flush_ready_merges(inputs)?; if let Some(parameter) = parameter { @@ -4757,6 +4928,9 @@ impl RuntimeNode { } RuntimeOp::ParameterizedTopK { input, parameter, .. + } + | RuntimeOp::ParameterizedAggregate { + input, parameter, .. } => { input.any_merge_pending() || parameter.as_ref().is_some_and(|p| p.any_merge_pending()) @@ -4817,6 +4991,17 @@ impl RuntimeNode { } Ok(()) } + // The fold keeps its input rather than folding it away, so a series that ended inside + // the fold's input is exactly what this checks for; the parameter is one scalar series. + RuntimeOp::ParameterizedAggregate { + input, parameter, .. + } => { + input.unclosed()?; + if let Some(parameter) = parameter { + parameter.unclosed()?; + } + Ok(()) + } RuntimeOp::ParameterizedHistogram { input, parameters, @@ -4889,6 +5074,9 @@ impl RuntimeNode { | RuntimeOp::Merge { input, .. } => input.finish_windows(), RuntimeOp::ParameterizedTopK { input, parameter, .. + } + | RuntimeOp::ParameterizedAggregate { + input, parameter, .. } => { let first = input.finish_windows(); let parameter = parameter.as_mut().map_or(Ok(()), |p| p.finish_windows()); @@ -5048,7 +5236,7 @@ impl LiveExecution { /// only then the nodes, because a node that retains its whole input reports the same truncation in /// its own terms. fn unclosed(&self) -> Result<()> { - if let Some(index) = self.inputs.iter().position(|slot| slot.open_source_series) { + if let Some(index) = self.inputs.iter().position(InputSlot::ends_open) { let slot = &self.inputs[index]; return Err(slot.state.context(truncated_input(InputId::new(index)))); } @@ -6038,9 +6226,16 @@ impl InputSlot { chunk.describe(), )))); } + // Finality is recorded on receipt as well as on handover: a chunk the tree has not pulled + // yet is still a chunk the caller sent, and whether it closes its series says so whether or + // not anything above this leaf ever reads it. A chunk the pool refuses never arrived, so + // the flag follows the queue. + let closing = chunk.is_last(); self.state .enqueue(chunk) - .map_err(|error| self.state.context(error)) + .map_err(|error| self.state.context(error))?; + self.open_queued_series = !closing; + Ok(()) } /// Hands over the next queued source chunk, if there is one. diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index d16241b3d41..541f108dbfe 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -750,6 +750,7 @@ fn source_runtime(pool: &Arc) -> InputSlot { source_index: 0, kind: super::LeafKind::Raw, open_source_series: false, + open_queued_series: false, state: NodeState::new( "native.input at root (source_index=0)", Arc::new(NodeMetrics::default()), @@ -1684,6 +1685,9 @@ fn node_metrics(execution: &NativeExecutor) -> Vec> { } RuntimeOp::ParameterizedTopK { input, parameter, .. + } + | RuntimeOp::ParameterizedAggregate { + input, parameter, .. } => { walk(input, out); if let Some(parameter) = parameter { @@ -1860,8 +1864,12 @@ fn finishing_a_window_propagates_its_error_and_drops_the_live_tree() { drop(execution.next_chunk().unwrap()); assert!(pool.reserved() > 0); // The source-level check normally catches truncation first; leave the evaluator open so the - // actual terminal finish pass exercises its own error and context propagation. - execution.state.live.as_mut().unwrap().inputs[0].open_source_series = false; + // actual terminal finish pass exercises its own error and context propagation. Both halves of + // that check are cleared: the chunk was handed over and it was also the last one received, so + // the leaf reports `is_last` was sent only to the evaluator that never saw it. + let slot = &mut execution.state.live.as_mut().unwrap().inputs[0]; + slot.open_source_series = false; + slot.open_queued_series = false; execution.end_of_input().unwrap(); let error = execution.next_chunk().unwrap_err(); assert!( @@ -12464,6 +12472,324 @@ fn a_quantile_over_no_input_answers_nothing() { assert_eq!(pool.reserved(), 0); } +/// A `Complete` aggregate whose one argument is read per point, over `inner` and `parameter`. +/// +/// The fold answers one value per field on its input's grid, exactly as its bound counterpart does: +/// only where its `φ` comes from differs. +fn parameterized_aggregate( + inner: NativeNode, + op: BoundAggregate, + parameter: NativeNode, +) -> NativeNode { + let fields = inner + .output + .samples() + .expect("a parameterized aggregate reads samples") + .fields + .clone(); + let grid = inner + .output + .grid() + .expect("a parameterized aggregate reads an evaluated vector") + .clone(); + let output = NativeType::Samples(Arc::new(SeriesSchema { + fields, + eval_grid: Some(grid), + })); + NativeNode { + expr: NativeExpr::ParameterizedAggregate { + input: Box::new(inner), + op, + parameter: Box::new(parameter), + }, + output, + } +} + +/// A `Complete` `quantile` grouped as `group` whose `φ` is read at every grid point. +fn per_point_quantile(group: Grouping) -> BoundAggregate { + BoundAggregate { + // Unused by this fold: the `φ` it reads is its parameter's, one value per point. The + // constant is here because it is what a `Quantile` carries, as a parameterized `topk` + // carries an unused `k`. + kind: AggregateKind::Quantile { quantile: 0.0 }, + group, + stage: AggregateStage::Complete, + field_kind: FieldKind::Float, + } +} + +/// The value `answer` decided at `point`, from the one group at `index`. +fn value_at(answer: &[GroupResult], index: usize, point: usize) -> Option { + answer[index] + .2 + .iter() + .find(|(at, _)| *at == point) + .map(|(_, value)| *value) + .unwrap_or_else(|| panic!("group {index} answered no value at point {point}")) +} + +/// A `quantile` reads its argument at every step, and answers there what the same fold bound to +/// that step's `φ` answers. +/// +/// The argument is `time() / 120`, which is `0`, `0.5` and `1` on this grid, so each of the three steps +/// is compared against `quantile(, m)` computed on its own: the bound fold is the +/// constant path, and comparing against it is comparing against the value the query means. The +/// grouping is checked in both shapes, because a fold that reads its `φ` per point groups exactly as +/// the one that binds it: `by (job)` folds one group per job, and the `φ` is read beside the fold +/// rather than once per group. +#[test] +fn a_quantile_reads_its_parameter_at_every_grid_point() { + let grid = grid(0, 60_000, 3); + let schema = evaluated_schema(Arc::clone(&grid)); + let members = [ + ( + job_instance_metric("requests", "api", "a"), + vec![Some(1.0); 3], + ), + ( + job_instance_metric("requests", "db", "b"), + vec![Some(10.0); 3], + ), + ]; + let chunks: Vec = members + .iter() + .map(|(metric, values)| { + evaluated_chunk_of(&schema, metric.clone(), 0, values.clone(), true) + }) + .collect(); + // `time() / 120` over this grid is `0`, `0.5`, `1`: `time()` reports seconds since the epoch and + // the grid steps a minute. + let per_point = scalar_binary( + eval_time(None, Arc::clone(&grid)), + scalar(120.0, Arc::clone(&grid)), + binary_matching(BinaryOp::Div), + ); + let quantiles = [0.0, 0.5, 1.0]; + let run = |root: NativeNode| { + let tree = NativeTree::try_new(root).expect("the fixture is a legal tree"); + let pool = bounded_pool(1 << 20); + let mut execution = executor(&tree, Arc::clone(&pool)); + for chunk in &chunks { + execution + .push_evaluated(InputId::new(0), chunk.clone()) + .unwrap(); + } + let output = execution.finish().unwrap(); + assert_eq!(pool.reserved(), 0, "the fold left the pool holding input"); + groups_of(&output) + }; + for grouping in [ + Grouping::By(Arc::new([])), + Grouping::By(Arc::new(["job".into()])), + ] { + let answer = run(parameterized_aggregate( + evaluated_input(Arc::clone(&grid)), + per_point_quantile(grouping.clone()), + per_point.clone(), + )); + let bound = quantiles.map(|quantile| { + run(aggregate( + evaluated_input(Arc::clone(&grid)), + BoundAggregate { + kind: AggregateKind::Quantile { quantile }, + group: grouping.clone(), + stage: AggregateStage::Complete, + field_kind: FieldKind::Float, + }, + )) + }); + assert_eq!(answer.len(), bound[0].len(), "{grouping:?}"); + for (index, group) in answer.iter().enumerate() { + // The same group in each separately computed answer, by its tags. + assert_eq!(group.0, bound[0][index].0, "{grouping:?}"); + assert_eq!(group.1, bound[0][index].1, "{grouping:?}"); + let answered: Vec> = (0..quantiles.len()) + .map(|point| value_at(&answer, index, point)) + .collect(); + let separately: Vec> = (0..quantiles.len()) + .map(|point| value_at(&bound[point], index, point)) + .collect(); + assert_eq!(answered, separately, "{grouping:?} at {index}"); + } + } + // The one group over both members: half of `{1, 10}` is `5.5`, and the ends are the ends. + let ungrouped = run(parameterized_aggregate( + evaluated_input(Arc::clone(&grid)), + per_point_quantile(Grouping::By(Arc::new([]))), + per_point, + )); + assert_eq!( + ungrouped, + vec![unlabelled(vec![ + (0, Some(1.0)), + (1, Some(5.5)), + (2, Some(10.0)), + ])] + ); +} + +/// A step whose `φ` the statement has no sample for answers NaN there, not no point. +/// +/// `scalar(foo)` answers one value per grid point -- NaN where `foo` holds no float sample -- so the +/// series this fold holds covers every step, and a step it covers with NaN is a step with a +/// `quantile` answer: Prometheus' `quantile` of a NaN `φ` is NaN. A step the parameter had no sample +/// at at all would be unanswered instead, which is the rule the kernel applies to a parameter series +/// with a gap; this node is handed one that never has one. +#[test] +fn a_quantile_answers_nan_where_its_parameter_is_nan() { + let grid = grid(0, 60_000, 3); + let schema = evaluated_schema(Arc::clone(&grid)); + // `foo` holds a sample at the first and last step and none in between, so `scalar(foo)` is the + // value it holds there and NaN at the step it holds none. + let foo = scalar_of(evaluated_input_with_source_index(Arc::clone(&grid), 1)); + let tree = NativeTree::try_new(parameterized_aggregate( + evaluated_input(Arc::clone(&grid)), + per_point_quantile(Grouping::By(Arc::new([]))), + foo, + )) + .unwrap(); + let pool = bounded_pool(1 << 20); + let mut execution = executor(&tree, Arc::clone(&pool)); + let parameter = execution.state().input_ids(1).next().unwrap(); + execution + .push_evaluated( + parameter, + evaluated_chunk_of(&schema, metric(), 0, vec![Some(0.5), None, Some(1.0)], true), + ) + .unwrap(); + for (metric, value) in [ + (job_instance_metric("requests", "api", "a"), 1.0), + (job_instance_metric("requests", "db", "b"), 10.0), + ] { + execution + .push_evaluated( + InputId::new(0), + evaluated_chunk_of(&schema, metric, 0, vec![Some(value); 3], true), + ) + .unwrap(); + } + let output = execution.finish().unwrap(); + let values = decided(&output); + assert_eq!(values.len(), 3, "every step holds a sample"); + assert_eq!(values[0].1, Some(5.5)); + assert!( + values[1].1.is_some_and(f64::is_nan), + "the NaN step answered {:?} rather than NaN", + values[1].1 + ); + assert_eq!(values[2].1, Some(10.0)); + assert_eq!(pool.reserved(), 0); +} + +/// An input that ends with a chunk still queued is refused as truncated, not folded. +/// +/// The fold reads its parameter before it reads any input, and a parameter that answers only once +/// its own input ended leaves the fold with nothing to do but wait. A caller that ends the input +/// while the vector's last chunk still waits in the leaf's queue therefore ends a run in which the +/// fold has never looked at that chunk: it says `is_last` was not sent, and the fold would fold half +/// a vector into a quantile if it were read as closed. Finality is what the caller sent, so the +/// queued chunk is what reports the truncation. +#[test] +fn a_quantile_refuses_a_queued_chunk_that_never_closed() { + let grid = grid(0, 60_000, 3); + let schema = evaluated_schema(Arc::clone(&grid)); + // The parameter is `scalar(foo)` over a source of its own, which answers only once that source + // has ended: neither leaf has been drained when the caller ends the input. + let parameter_tree = scalar_of(evaluated_input_with_source_index(Arc::clone(&grid), 1)); + let tree = NativeTree::try_new(parameterized_aggregate( + evaluated_input(Arc::clone(&grid)), + per_point_quantile(Grouping::By(Arc::new([]))), + parameter_tree, + )) + .unwrap(); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool)); + let parameter = execution.state().input_ids(1).next().unwrap(); + // `foo` closes properly, so the only truncation is the fold's own input. + execution + .push_evaluated( + parameter, + evaluated_chunk_of(&schema, metric(), 0, vec![Some(0.5); 3], true), + ) + .unwrap(); + // The fold's input never sends the chunk that closes its series. + execution + .push_evaluated( + InputId::new(0), + evaluated_chunk_of( + &schema, + metric(), + 0, + vec![Some(1.0), Some(2.0), Some(3.0)], + false, + ), + ) + .unwrap(); + + let error = execution + .finish() + .expect_err("an input that ended mid-series was folded"); + assert!( + error + .to_string() + .contains("ended before the last chunk of a series"), + "the fold reported {error} instead of a truncated input" + ); + assert_eq!(pool.reserved(), 0); +} + +/// A `quantile` bills the parameter it holds across the handoff and while it computes. +/// +/// The parameter here is `time()` over a grid far wider than the fold's input: one row of `m`, so +/// the input says nothing about the parameter's width at all. Its own series costs eight bytes a +/// point, and the kernel reads the whole of it into one `(position, φ)` pair per point before it +/// folds anything, so the fold answers only over a pool that holds the series and that copy. +/// +/// A pool of the values alone is refused by the source that produces the parameter (`POINTS`), one +/// that holds the parameter but not the copy the kernel reads is refused after the handoff +/// (`24 * POINTS`: over the series and under the copy), and one that holds both answers the query +/// and is left empty (`64 * POINTS`). +#[test] +fn a_parameterized_quantile_bills_the_parameter_it_holds() { + // Eight bytes a point for the values alone, and the axis, the validity slots and the descriptor + // on top of them; the kernel's copy is two pairs of eight bytes a point on top of that. + const POINTS: usize = 1 << 16; + let grid = grid(0, 1_000, POINTS as u64); + let schema = evaluated_schema(Arc::clone(&grid)); + let tree = NativeTree::try_new(parameterized_aggregate( + evaluated_input(Arc::clone(&grid)), + per_point_quantile(Grouping::By(Arc::new([]))), + eval_time(None, Arc::clone(&grid)), + )) + .unwrap(); + for (budget, fits) in [(POINTS, false), (24 * POINTS, false), (64 * POINTS, true)] { + let pool = bounded_pool(budget); + let mut execution = executor(&tree, Arc::clone(&pool)); + execution + .push_evaluated( + InputId::new(0), + evaluated_chunk_of(&schema, metric(), 0, vec![Some(1.0)], true), + ) + .unwrap(); + let result = execution.finish(); + if fits { + assert!( + result.is_ok(), + "a pool that holds the parameter refused it: {:?}", + result.err() + ); + } else { + let error = result.expect_err("a parameter that does not fit the pool was admitted"); + assert!( + matches!(error.find_root(), DataFusionError::ResourcesExhausted(_)), + "the parameter was not reserved before it was held: {error}" + ); + } + assert_eq!(pool.reserved(), 0, "the query left the pool holding memory"); + } +} + /// A `quantile` bills the buffer its chunks are slices of once, not once per chunk. /// /// One 2000-sample Arrow allocation is handed over as 2000 one-row chunks, which is what a source @@ -12477,6 +12803,13 @@ fn a_quantile_over_no_input_answers_nothing() { /// each billed once by the first chunk that references one (`unbilled_sample_buffers`) -- the input /// costs its rows, its descriptors and one charge for the buffer they slice: under a megabyte, so /// the fold answers and leaves the pool empty. +/// +/// The φ is read at every grid point in the second fold below, as `scalar()`, which has nothing to hand over until that source has ended. The chunks that arrive +/// while it waits are retained as they come, so this fold pays the same figure: a fold that waited +/// without reading its input would leave those chunks in the source queue, which bills every queued +/// chunk for the whole buffer it points into -- 2000 x 16 392 bytes ≈ 32 MB, refused by this 4 MiB +/// pool at the 255th slice -- and the pool would answer the queue's figure rather than the input's. #[test] fn a_quantile_bills_a_shared_buffer_once() { const ROWS: usize = 2_000; @@ -12506,8 +12839,44 @@ fn a_quantile_bills_a_shared_buffer_once() { would admit, so this input does not reproduce the double billing" ); - let run = |kind: AggregateKind, pool: Arc| { - let tree = NativeTree::try_new(aggregate( + // The φ the statement evaluates: the one closed series of the second source, which `scalar()` + // answers with a value a point for once that source ended. + let parameter = || { + ( + InputId::new(1), + evaluated_chunk_of(&schema, metric(), 0, vec![Some(0.5); ROWS], true), + ) + }; + // One source hands the chunks over and one pulls after each: a source queue holds the chunk the + // caller just pushed, so a pull per push keeps what the pool holds to what the nodes retain + // rather than to the whole input stream. An aggregate answers once its input ended, so nothing + // has settled here yet. + let run = |tree: &NativeTree, + parameter: Option<(InputId, EvaluatedChunk)>, + pool: Arc| { + let mut execution = executor(tree, Arc::clone(&pool)); + if let Some((input, parameter)) = parameter { + execution.push_evaluated(input, parameter).unwrap(); + } + for chunk in &chunks { + execution + .push_evaluated(InputId::new(0), chunk.clone()) + .unwrap(); + assert!( + execution.next_chunk().unwrap().is_none(), + "the fold answered early" + ); + } + let output = execution.finish().unwrap(); + assert_eq!( + pool.reserved(), + 0, + "the fold left the pool holding input it was finished with" + ); + output + }; + let bound = |kind: AggregateKind| { + NativeTree::try_new(aggregate( evaluated_input(Arc::clone(&grid)), BoundAggregate { kind, @@ -12516,36 +12885,28 @@ fn a_quantile_bills_a_shared_buffer_once() { field_kind: FieldKind::Float, }, )) - .unwrap(); - let mut execution = executor(&tree, Arc::clone(&pool)); - for chunk in &chunks { - execution - .push_evaluated(InputId::new(0), chunk.clone()) - .unwrap(); - // A source queue holds the chunk the caller just pushed, so a pull per push keeps what - // the pool holds to what the nodes retain rather than to the whole input stream. An - // aggregate answers once, when its input ends, so nothing has settled here yet. - assert!( - execution.next_chunk().unwrap().is_none(), - "{kind:?} answered early" - ); - } - let output = execution.finish().unwrap(); - assert_eq!( - pool.reserved(), - 0, - "{kind:?} left the pool holding input it was finished with" - ); - output + .unwrap() }; - let minimum = run(AggregateKind::Min, bounded_pool(POOL)); + let minimum = run(&bound(AggregateKind::Min), None, bounded_pool(POOL)); let quantile = run( - AggregateKind::Quantile { quantile: 0.5 }, + &bound(AggregateKind::Quantile { quantile: 0.5 }), + None, + bounded_pool(POOL), + ); + let per_point = run( + &NativeTree::try_new(parameterized_aggregate( + evaluated_input(Arc::clone(&grid)), + per_point_quantile(Grouping::By(Arc::new([]))), + scalar_of(evaluated_input_with_source_index(Arc::clone(&grid), 1)), + )) + .unwrap(), + Some(parameter()), bounded_pool(POOL), ); // Every point of this input holds exactly one value, so the φ-quantile of a point is that value - // and the two aggregates answer the same series. + // and all three aggregates answer the same series. assert_eq!(groups_of(&quantile), groups_of(&minimum)); + assert_eq!(groups_of(&per_point), groups_of(&minimum)); } /// A `quantile` bills the allocation its chunks' slices point into, once, and not the rows it holds of diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index f30a7e67d5f..09a1c859b9f 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -167,21 +167,11 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti // does. A grouping by `__name__` keeps the name where the input reports one; a named scan // only reports it among the runtime labels, so the aggregate keeps it there and publishes no // column for it, which is what `sum by (__name__)` over one metric reports. - NativeExpr::Aggregate { input, op } => { - let input_tags = fused_output_tags(input, source_tags)?; - Some(match &op.group { - Grouping::By(kept) => input_tags - .into_iter() - .filter(|tag| kept.iter().any(|name| name.as_ref() == tag.as_str())) - .collect(), - Grouping::Without(dropped) => input_tags - .into_iter() - .filter(|tag| { - tag != METRIC_NAME - && !dropped.iter().any(|name| name.as_ref() == tag.as_str()) - }) - .collect(), - }) + NativeExpr::Aggregate { input, op } => grouped_output_tags(input, op, source_tags), + // Its parameter is a scalar, which carries no labels, so a fold that reads it per point + // reports the same columns as the one that binds its `φ`. + NativeExpr::ParameterizedAggregate { input, op, .. } => { + grouped_output_tags(input, op, source_tags) } // Selecting some of the input's series keeps each one's own labels, and `count_values` // keeps its grouping's; `histogram` folds bucket series into one histogram, so it does not @@ -420,6 +410,36 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti } } } + +/// The labels an aggregate reports: the ones its grouping keeps among those its input carries. +/// +/// `by(...)` keeps exactly the labels it names, and `without(...)` keeps the rest and drops the +/// metric name, as Prometheus does. A grouping by `__name__` keeps the name where the input reports +/// one; a named scan only reports it among the runtime labels, so the aggregate keeps it there and +/// publishes no column for it, which is what `sum by (__name__)` over one metric reports. +/// +/// Both the fold that binds its argument and the one that reads it per point answer this way: what +/// decides the columns is the grouping, not where the aggregate's one argument comes from. +fn grouped_output_tags( + input: &NativeNode, + op: &BoundAggregate, + source_tags: &[Vec], +) -> Option> { + let input_tags = fused_output_tags(input, source_tags)?; + Some(match &op.group { + Grouping::By(kept) => input_tags + .into_iter() + .filter(|tag| kept.iter().any(|name| name.as_ref() == tag.as_str())) + .collect(), + Grouping::Without(dropped) => input_tags + .into_iter() + .filter(|tag| { + tag != METRIC_NAME && !dropped.iter().any(|name| name.as_ref() == tag.as_str()) + }) + .collect(), + }) +} + /// Whether a binary operation reports the samples of the side it keeps, name included. /// /// A filtering comparison reports those samples, so the name survives it. Every other binary @@ -683,6 +703,9 @@ impl NativeNode { // float otherwise. Naming it here is what lets `sum(count_over_time(h[5m]))` - a float // built from histograms - declare a float column, and `sum(h)` declare a histogram one. NativeExpr::Aggregate { op, .. } => Some(aggregate_output_kind(op)), + // A per-point parameter decides the `φ` the fold reads, not the layout it answers, so + // the kind is the one the same aggregate's state carries. + NativeExpr::ParameterizedAggregate { op, .. } => Some(aggregate_output_kind(op)), _ => None, } } @@ -1140,6 +1163,19 @@ pub enum NativeExpr { op: BoundVectorOp, parameters: Vec, }, + /// An aggregate whose argument is read at every grid point instead of bound as a constant: + /// `quantile(<φ per point>, v)`. + /// + /// `op` is still the `Quantile` the constant path binds; its `φ` is unused here, because the + /// value this node folds with is the parameter's, read once per point -- exactly as + /// [`Self::ParameterizedTopK`] ignores the `k` its own binding carries. What the fold keeps is + /// its group's sample set either way, so a parameter read per point changes what is folded, not + /// how. + ParameterizedAggregate { + input: Box, + op: BoundAggregate, + parameter: Box, + }, } /// One node of a bound tree. @@ -1177,6 +1213,9 @@ impl NativeExpr { .collect(), NativeExpr::ParameterizedTopK { input, parameter, .. + } + | NativeExpr::ParameterizedAggregate { + input, parameter, .. } => vec![input, parameter], NativeExpr::Binary { left, right, .. } | NativeExpr::Set { left, right, .. } => { vec![left, right] @@ -1226,6 +1265,11 @@ impl NativeExpr { op: op.clone(), parameter: Box::new(next()), }, + NativeExpr::ParameterizedAggregate { op, .. } => NativeExpr::ParameterizedAggregate { + input: Box::new(next()), + op: op.clone(), + parameter: Box::new(next()), + }, NativeExpr::ParameterizedHistogram { op, parameters, .. } => { NativeExpr::ParameterizedHistogram { input: Box::new(next()), @@ -1378,7 +1422,7 @@ pub fn duplicates_canonical_labels(node: &NativeNode, source_tags: &[Vec || duplicates_canonical_labels(input, source_tags) } // A fold answers one series per group, which is one label set per group. - NativeExpr::Aggregate { .. } => false, + NativeExpr::Aggregate { .. } | NativeExpr::ParameterizedAggregate { .. } => false, NativeExpr::Vector { input, op } => match op { // These keep and order the series they read, so they alias exactly as their input does. BoundVectorOp::TopK { .. } @@ -1449,10 +1493,10 @@ fn map_writes_existing_label( } /// Whether `node` reads the whole input vector at a point rather than one series at a time. /// -/// An `Aggregate` folds every series of its group, a `Binary` and a `Set` pair two vectors' series -/// by label, an `Info` looks the info series of each series up by its identifying labels, and a -/// `Vector` operation (`sort`, `absent`, `topk`, `limitk`, `histogram_quantile`, ...) reorders or -/// reads the whole vector at a grid point. +/// An `Aggregate` folds every series of its group, whether its argument is bound or read per point, +/// a `Binary` and a `Set` pair two vectors' series by label, an `Info` looks the info series of each +/// series up by its identifying labels, and a `Vector` operation (`sort`, `absent`, `topk`, `limitk`, +/// `histogram_quantile`, ...) reorders or reads the whole vector at a grid point. /// /// `Merge` answers one series per label set, and the label sets it answers span every input series: /// two of them can collapse into the one it emits. It is therefore whole-vector too, which is why it @@ -1498,6 +1542,7 @@ pub fn reads_across_series(node: &NativeNode) -> bool { // decides which series survive. NativeExpr::ParameterizedTopK { .. } | NativeExpr::ParameterizedHistogram { .. } => true, NativeExpr::Aggregate { .. } + | NativeExpr::ParameterizedAggregate { .. } | NativeExpr::Vector { .. } | NativeExpr::Set { .. } | NativeExpr::Info { .. } @@ -1677,6 +1722,21 @@ fn native_node_supported_within_stack(node: &NativeNode) -> bool { NativeExpr::Aggregate { input, op } => { native_node_supported(input) && aggregate_supported(node, input, op) } + // A per-point argument does not change which fold runs, only where its `φ` comes from: the + // same aggregate checks apply, and the parameter is a subtree like any other. That it is a + // scalar on this fold's grid is a type contract `validate` already refuses. + NativeExpr::ParameterizedAggregate { + input, + op, + parameter, + } => { + native_node_supported(input) + && native_node_supported(parameter) + // A literal hands over no chunk, so the fold could never read a value from it: + // `validate` refuses one, and a tree this predicate admits must be one it does not. + && !matches!(parameter.expr, NativeExpr::Scalar(_)) + && aggregate_supported(node, input, op) + } NativeExpr::Vector { input, op } => { native_node_supported(input) && node @@ -1754,10 +1814,9 @@ fn binary_supported(left: &NativeNode, right: &NativeNode, matching: &BinaryMatc /// Whether the runtime folds `op` over `input` with the layout `node` declares. /// -/// `quantile` has no kernel on this route, so it is refused at every stage. A `Complete` or -/// `Partial` node folds values into groups it keys by series labels only, while `Final` merges -/// state that was already grouped, which is why only the folding stages are checked against the -/// schema. +/// A `Complete` or `Partial` node folds values into groups it keys by series labels only, while +/// `Final` merges state that was already grouped, which is why only the folding stages are checked +/// against the schema. fn aggregate_supported(node: &NativeNode, input: &NativeNode, op: &BoundAggregate) -> bool { match op.kind { AggregateKind::Sum @@ -2300,6 +2359,71 @@ impl NativeNode { } } } + NativeExpr::ParameterizedAggregate { + input, + op, + parameter, + } => { + input.validate()?; + parameter.validate()?; + // The parameter is read off the chunk its node hands over, once per grid point, so + // it has to be a scalar the node answers a series for -- `scalar()`, `time()` and + // the like all do. A literal has no chunk of its own: its value is on the binding + // of a node that carries it, and a fold that never receives one would run to the + // end of its input and fail instead of folding. A query that writes a constant gets + // the constant path, which binds the number on the fold itself; a tree that reaches + // here with one was not built by the compiler, so it is refused before it runs. + if matches!(parameter.expr, NativeExpr::Scalar(_)) { + return Err(invalid( + "a parameterized aggregate reads a parameter node that hands over a \ + scalar series, not a literal", + )); + } + // Only a `quantile` takes an argument a query reads per point: it is the one + // aggregate whose argument is a value rather than a name, and every other kind + // binds its parameter into its own op (or is not an aggregate at all). + if !matches!(op.kind, AggregateKind::Quantile { .. }) { + return Err(invalid( + "a parameterized aggregate that is not a `quantile`", + )); + } + // A quantile answers from its group's whole sample set, so it keeps no state: the + // stage that reads a parameter is the one that folds, exactly as for the bound `φ`. + if op.stage != AggregateStage::Complete { + return Err(invalid( + "a parameterized aggregate at a stage other than `Complete`", + )); + } + // The parameter is read at every point the fold answers, one value per point and no + // labels, so it is a scalar on the grid the answer is stamped on. + 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", + )?; + ensure_grid( + &self.output, + input_grid, + "a parameterized complete aggregate", + )?; + } NativeExpr::Binary { left, right, .. } => { left.validate()?; right.validate()?; @@ -2585,8 +2709,9 @@ pub fn unifies_its_own_contributions(node: &NativeNode) -> Option { // label set. NativeExpr::Info { .. } => Some(true), // A finished aggregate emits one series per group, and two groups are two label sets. - // `Partial` state is not a series at all, which is not several either. - NativeExpr::Aggregate { .. } => Some(true), + // `Partial` state is not a series at all, which is not several either. A per-point parameter + // does not change that: the labels a group is filed under are its grouping's. + NativeExpr::Aggregate { .. } | NativeExpr::ParameterizedAggregate { .. } => Some(true), // `topk`, `limit_ratio` and `sort` hand back the series they read with their labels, so the // input's answer is theirs. The four that read the whole vector - `limitk`, `absent`, // `histogram_*` and `count_values` - emit one series per label set: `limitk` counts series diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index 3ccea9949d7..9d47c4f2b86 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -24,7 +24,7 @@ use super::{ AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar, BoundVectorOp, BoundWindow, Grouping, InstantValue, MapOp, NativeExpr, NativeNode, NativeTree, NativeType, ParameterizedOp, aggregate_state_binding, duplicates_canonical_labels, - fused_output_tags, reads_across_series, unifies_its_own_contributions, + fused_output_tags, native_node_supported, reads_across_series, unifies_its_own_contributions, }; use crate::extension_plan::FieldKind; use crate::extension_plan::{FusedSeries, FusedSeriesBinding}; @@ -322,6 +322,54 @@ fn parameterized_topk_validates_scalar_and_grid() { ); } +/// A per-point `quantile` whose argument is a literal is refused by the tree's own check. +/// +/// A literal is one value on a binding, not a series a node hands over: the fold reads its `φ` per +/// point from the series its parameter child hands over, so a literal leaves it waiting for a chunk +/// that never arrives. It would run to the end of its input and only then refuse the run, after +/// every chunk was retained and folded. `validate` is where a tree says what it is, so the shape is +/// refused there, and the admission predicate agrees so a decoded tree never reaches that wait. +#[test] +fn a_literal_quantile_parameter_is_refused() { + let out = grid(0, 60_000, 4); + let vector = map_over(window_on(input(), None, Arc::clone(&out))); + let node = |parameter: NativeNode| NativeNode { + expr: NativeExpr::ParameterizedAggregate { + input: Box::new(vector.clone()), + op: BoundAggregate { + kind: AggregateKind::Quantile { quantile: 0.0 }, + group: Grouping::By(Arc::from([])), + stage: AggregateStage::Complete, + field_kind: FieldKind::Float, + }, + parameter: Box::new(parameter), + }, + output: vector.output.clone(), + }; + let literal = node(scalar_on(0.5, Arc::clone(&out))); + let error = literal + .validate() + .expect_err("a fold that can never read its parameter was admitted"); + assert!( + error.to_string().contains("not a literal"), + "the literal parameter was refused for another reason: {error}" + ); + assert!( + !native_node_supported(&literal), + "the admission predicate admits a tree `validate` refuses" + ); + // A parameter that hands over a series is what the fold reads, so the check is the literal and + // not a scalar output. + assert!( + node(NativeNode { + expr: NativeExpr::EvalTime { date: None }, + output: NativeType::Scalar(Arc::clone(&out)), + }) + .validate() + .is_ok() + ); +} + #[test] fn binary_histogram_float_kind_matches_supported_operations() { use crate::extension_plan::FieldKind; @@ -2851,7 +2899,7 @@ fn native_expr_variant_indices_are_a_wire_contract() { 10, "Aggregate", ), - // The dynamic forms are the last three, which is what keeps every index above them. + // The dynamic forms are the last four, which is what keeps every index above them. ( NativeExpr::ScalarOf { input: Box::new(vector()), @@ -2881,6 +2929,20 @@ fn native_expr_variant_indices_are_a_wire_contract() { 17, "ParameterizedHistogram", ), + ( + NativeExpr::ParameterizedAggregate { + input: Box::new(vector()), + op: BoundAggregate { + kind: AggregateKind::Quantile { quantile: 0.0 }, + group: Grouping::By(Arc::new(["job".into()])), + stage: AggregateStage::Complete, + field_kind: FieldKind::Float, + }, + parameter: Box::new(scalar()), + }, + 18, + "ParameterizedAggregate", + ), ]; for (expr, index, variant) in cases { assert_eq!(index, tag(&expr), "{variant} changed the index it encodes"); diff --git a/src/promql/src/native/segment.rs b/src/promql/src/native/segment.rs index fd3aa799b82..14c9794600b 100644 --- a/src/promql/src/native/segment.rs +++ b/src/promql/src/native/segment.rs @@ -104,7 +104,8 @@ pub fn pointwise_operand(node: &NativeNode) -> bool { } // An aggregate folds a group, a vector operation reads the whole vector, and a bare input or // scalar is not a per-series evaluation. A parameterized topk or histogram reads the whole - // vector, and `scalar()` answers from it. + // vector, `scalar()` answers from it, and a per-point `φ` is read beside the fold over the + // whole group. NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } @@ -112,6 +113,7 @@ pub fn pointwise_operand(node: &NativeNode) -> bool { | NativeExpr::ScalarOf { .. } | NativeExpr::ParameterizedTopK { .. } | NativeExpr::ParameterizedHistogram { .. } + | NativeExpr::ParameterizedAggregate { .. } | NativeExpr::Aggregate { .. } | NativeExpr::Vector { .. } | NativeExpr::Set { .. } @@ -177,6 +179,17 @@ pub fn groups_by_metric_name(node: &NativeNode) -> bool { NativeExpr::Aggregate { input, op } => { grouping_names_metric(op) || groups_by_metric_name(input) } + // A per-point argument does not change what the fold groups by, and the parameter is a + // scalar expression that can itself hold an aggregate. + NativeExpr::ParameterizedAggregate { + input, + op, + parameter, + } => { + grouping_names_metric(op) + || groups_by_metric_name(input) + || groups_by_metric_name(parameter) + } NativeExpr::ParameterizedMap { input, parameters, .. } => groups_by_metric_name(input) || parameters.iter().any(groups_by_metric_name), @@ -314,10 +327,18 @@ pub fn contains_global_consumer(node: &NativeNode) -> bool { /// Whole-vector consumers remain global, but can be cut out as evaluated segments so a pointwise /// parent does not inherit their single-partition placement. +/// +/// A per-point `φ` does not make the fold it reads any less of a whole-vector consumer: a +/// `quantile` answers from every series of its group whichever node its argument comes from, so the +/// parameterized variant is admitted here exactly as the bound one is. Leaving it out would read a +/// fold that requires one partition as a node that does not, and the cut below it would be chosen +/// as though its parent could run per partition. fn is_global_consumer(node: &NativeNode) -> bool { matches!( node.expr, - NativeExpr::Aggregate { .. } | NativeExpr::Vector { .. } + NativeExpr::Aggregate { .. } + | NativeExpr::ParameterizedAggregate { .. } + | NativeExpr::Vector { .. } ) && matches!(input_locality(node), InputLocality::SinglePartition) } @@ -1266,3 +1287,125 @@ pub fn segment_tree( node: Arc::new(plan), })) } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use datatypes::series::SeriesOrdering; + use datatypes::series::samples::{FieldSpec, SeriesSchema}; + use datatypes::series::time::{EvalGrid, GridSpec}; + + use super::*; + use crate::map::MathOp; + use crate::native::plan::{ + AggregateKind, AggregateStage, BoundInput, BoundInstant, BoundMap, InstantValue, MapOp, + }; + + fn grid() -> Arc { + Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1, 4).unwrap()).unwrap()) + } + + /// The evaluated layout of the only field these trees carry. + fn evaluated(grid: &Arc) -> NativeType { + NativeType::Samples(Arc::new(SeriesSchema { + fields: vec![FieldSpec { + name: Arc::from("value"), + }] + .into(), + eval_grid: Some(Arc::clone(grid)), + })) + } + + /// `abs(…)` over `inner`, as a pointwise rewrite above a cut would be. + fn map_over(inner: NativeNode) -> NativeNode { + let output = inner + .output + .grid() + .expect("a map reads an evaluated vector") + .clone(); + NativeNode { + expr: NativeExpr::Map { + input: Box::new(inner), + op: BoundMap { + ops: vec![MapOp::Math(MathOp::Abs)].into(), + }, + }, + output: evaluated(&output), + } + } + + /// `inner` selected at every grid point. + fn selection(inner: NativeNode, output: NativeType) -> NativeNode { + let grid = output + .grid() + .expect("a selection answers on a grid") + .clone(); + NativeNode { + expr: NativeExpr::Instant { + input: Box::new(inner), + op: BoundInstant { + lookback_ms: 300_000, + offset_ms: 0, + at_ms: None, + value: InstantValue::Sample, + output_grid: grid, + }, + }, + output, + } + } + + /// A fold that reads its argument at every step is a whole-vector consumer. + /// + /// A `quantile` answers from its group's whole sample set wherever its `φ` comes from, so a + /// fold that reads that `φ` per point needs every series of the vector in one place exactly as + /// the fold that binds the number does. [`segment_tree`] asks [`contains_global_consumer`] + /// where a tree may be cut and whether a cut it cannot build has to be declined, and a parent + /// that answers one series at a time -- the `abs` below, as a canonical label rewrite would be + /// -- must not hide the gather under it: read as a per-partition node, the cut beneath would be + /// chosen for a parent that cannot run there. + #[test] + fn a_fold_that_reads_its_parameter_is_a_global_consumer() { + let grid = grid(); + let output = evaluated(&grid); + let source = NativeNode { + expr: NativeExpr::Input(BoundInput { + output: output.clone(), + source_index: 0, + ordering: SeriesOrdering::Contiguous, + }), + output: output.clone(), + }; + let fold = NativeNode { + expr: NativeExpr::ParameterizedAggregate { + input: Box::new(selection(source.clone(), output.clone())), + op: BoundAggregate { + kind: AggregateKind::Quantile { quantile: 0.0 }, + group: Grouping::By(Arc::from([])), + stage: AggregateStage::Complete, + field_kind: FieldKind::Float, + }, + parameter: Box::new(NativeNode { + expr: NativeExpr::EvalTime { date: None }, + output: NativeType::Scalar(Arc::clone(&grid)), + }), + }, + output: output.clone(), + }; + assert!( + contains_global_consumer(&fold), + "a fold that reads its `φ` per point reads the whole vector" + ); + assert!( + contains_global_consumer(&map_over(fold)), + "a pointwise parent must not hide the fold's gather" + ); + // The predicate is about that fold and not about every subtree: a pointwise rewrite of a + // selection answers each series on its own, so it stays cuttable where it stands. + assert!( + !contains_global_consumer(&map_over(selection(source, output))), + "a selection is not a whole-vector consumer" + ); + } +} diff --git a/src/promql/src/native/split.rs b/src/promql/src/native/split.rs index c33c0540047..5b916d0bd5f 100644 --- a/src/promql/src/native/split.rs +++ b/src/promql/src/native/split.rs @@ -229,6 +229,10 @@ pub(crate) fn split( op: BoundVectorOp::TopK { .. }, .. } => Err(declined("a whole-vector operation above a split aggregate")), + // A per-point `φ` does not make the fold splittable: `check_cut` declines every `quantile`, + // whose state is its group's samples however its argument is read. A `ParameterizedAggregate` + // is only ever that fold, so there is nothing here to admit. + NativeExpr::ParameterizedAggregate { .. } => Err(declined("a `quantile` aggregate")), NativeExpr::Merge { .. } => Err(declined("an aggregate split across a canonical merge")), // A window whose input is already evaluated - a subquery - applies to the merged values the // suffix reads, provided it evaluates on a grid. The declared grid and the input's grid are diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index afd5e08075d..5e3649c4e2b 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -46,7 +46,7 @@ //! e.g. avg by(job)(rate(x[5m]) * 100) //! () [(by|without)()] //! e.g. count (x) by(job) -//! quantile(, ) [(by|without)()] +//! quantile(, ) [(by|without)()] //! e.g. quantile(0.9, x) by(job) //! (, ) [(by|without)()] //! e.g. topk(3, x) by(job), limit_ratio(0.5, x) @@ -57,7 +57,8 @@ //! | [:] //! a subquery: evaluated on a grid; //! the step may be omitted as `[:]` -//! | time() | +//! | time() | scalar() +//! | //! nothing, `offset `, `@ `, or //! both, in either order — e.g. `x[5m] @ 1234 //! offset 1m` @@ -257,14 +258,15 @@ const SUPPORTED: &str = "a selector — `x`, optionally with an `offset` — a r (`label_replace(x, \"a\", \"$1\", \"b\", \"(.*)\")`), a binary \ operation between one of them and a scalar (`2 / (x + 1)`, \ `x > bool time()`, `time() - timestamp(x)`), a scalar — a constant, \ - `time()` or a binary operation between scalars — \ + `time()`, `scalar()` or a binary operation between \ + scalars — \ `vector()`, a date function without an argument (`hour()`), a \ negation of one of them (`-x`), a set operation between two of them \ (`x and on(job) y`, `x or y`, `x unless y`), `info` over any of them with \ one info metric (`info(x, {version=~\".+\"})`), or one of the \ aggregators that folds a group's values into one value per grid point — \ `sum`, `avg`, `count`, `min`, `max`, `group`, `stddev`, `stdvar` and \ - `quantile(, )` — over any of them, optionally \ + `quantile(, )` — over any of them, optionally \ grouped by `by` or `without` as in `avg by(job)(rate(x[5m]) * 100)`; \ `topk`, `bottomk`, `limitk`, `limit_ratio` or `count_values` over any of \ them, as in `topk(3, x) by(job)` and `count_values(\"v\", x)`; a \ @@ -938,6 +940,11 @@ fn binary_op(op: &TokenType) -> Option { /// "no modifier": every label is dropped, `__name__` included, and every series of the input falls /// into one group. /// +/// `quantile` is the one kind that takes an argument at run time, so it has two shapes: a number the +/// statement decides is bound on the fold ([`NativeExpr::Aggregate`]), and a scalar the query +/// evaluates is bound beside it as the fold's second operand +/// ([`NativeExpr::ParameterizedAggregate`]), because Prometheus reads it at every step. +/// /// The stage is [`AggregateStage::Complete`], which says that every contribution to each group is in /// this execution's input. The module documentation says what keeping that claim costs a caller. fn aggregate_expr(context: &Context, aggregate: &AggregateExpr) -> Result { @@ -947,6 +954,11 @@ fn aggregate_expr(context: &Context, aggregate: &AggregateExpr) -> Result AggregateKind::Sum, token::T_AVG => AggregateKind::Avg, @@ -959,16 +971,33 @@ fn aggregate_expr(context: &Context, aggregate: &AggregateExpr) -> Result { // `quantile` is the only one of the nine with a parameter, and the parser always gives // it one: a `quantile` with no quantile written is refused before the compiler sees it. - // The quantile is the call's first argument, so a parameter that is not a constant is - // refused under that name rather than answered from a number bound too early. + // The quantile is the call's first argument, so a parameter this compiler cannot bind - + // more than one value at a point, or a number it must not fold - is refused under that + // name rather than answered from a number bound too early. let param = param.as_ref().ok_or_else(|| { not_implemented(&format!( "the aggregate `{op}` in `{aggregate}`, which takes its quantile as its first \ argument" )) })?; + // A parameter the statement itself decides stays on the constant path, folded by + // `constant_argument` below: `quantile(0.25 + 0.1 + 0.15, v)` is one number, and binding + // the expression it was written as would answer nothing else. What is left is a scalar + // the query evaluates - `scalar(foo)`, `time()`, an arithmetic expression of them - + // which is one value per grid point, exactly what the kernel reads `q` as. + // + // A vector is neither: Prometheus refuses `quantile(foo, v)` at type check, and leaving + // it to `constant_argument` keeps that refusal where and what it was. + if constant_value(param).is_none() && param.value_type() == ValueType::Scalar { + per_point = Some(param); + } AggregateKind::Quantile { - quantile: constant_argument(&op.to_string(), param, 0)?, + // Unused by a fold that reads its φ per point, exactly as a parameterized `topk` + // ignores the `k` its own binding carries. + quantile: match per_point { + Some(_) => 0.0, + None => constant_argument(&op.to_string(), param, 0)?, + }, } } // A ranking aggregate keeps some of the input's series, and `count_values` writes one @@ -1020,18 +1049,26 @@ fn aggregate_expr(context: &Context, aggregate: &AggregateExpr) -> Result NativeExpr::ParameterizedAggregate { input: Box::new(input), - op: BoundAggregate { - kind, - group: grouping(modifier.as_ref()), - stage: AggregateStage::Complete, - field_kind, - }, + op, + parameter: Box::new(compile_expr(context, parameter)?), }, - output, - }) + None => NativeExpr::Aggregate { + input: Box::new(input), + op, + }, + }; + Ok(NativeNode { expr, output }) } /// Binds `topk`, `bottomk`, `limitk`, `limit_ratio` or `count_values` as a vector operation over diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index 566ee8c1a82..4b88a26e909 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -2333,6 +2333,87 @@ fn a_math_function_with_a_varying_parameter_binds_its_parameters_as_scalars() { )); } +/// `quantile` is the one aggregate whose argument a query can evaluate, and that argument binds as a +/// second operand of the fold rather than as the number it is not. +/// +/// Prometheus reads the parameter at every step, so `quantile(scalar(x), y)` is the fold of `y` with +/// the value `scalar(x)` answers at that point. The input is compiled first and the argument second, +/// which is the order the selector walk binds their scans in. A number the statement itself decides, +/// written as a literal or as arithmetic over literals, stays on the constant path, and a vector +/// argument is refused: Prometheus rejects `quantile(x, y)` at type check, and this route never +/// bound it. +#[test] +fn a_quantile_reads_its_argument_per_point() { + let compiled = |query: &str| { + compile_selectors( + &eval_stmt(query), + &|_| Ok(raw_schema()), + SeriesOrdering::KeyThenTime, + Some(FieldKind::Float), + ) + }; + let per_point = |query: &str| match &compiled(query) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")) + .tree + .root() + .expr + { + NativeExpr::ParameterizedAggregate { .. } => {} + other => panic!("`{query}`: expected a parameterized aggregate, got {other:?}"), + }; + let tree = compiled("quantile(scalar(x), y)").unwrap().tree; + let NativeExpr::ParameterizedAggregate { + input, + op, + parameter, + } = &tree.root().expr + else { + panic!( + "expected a parameterized aggregate, got {:?}", + tree.root().expr + ); + }; + assert!( + matches!(op.kind, AggregateKind::Quantile { .. }), + "{:?}", + op.kind + ); + assert_eq!(op.stage, AggregateStage::Complete); + // The fold reads `y`, the argument reads `x`: the input is the first source, the argument the + // second one the walk bound. + assert!(matches!(input.expr, NativeExpr::Instant { .. })); + assert!(matches!(parameter.expr, NativeExpr::ScalarOf { .. })); + assert!(matches!(tree.root().output, NativeType::Samples(_))); + assert_eq!(tree.root().inputs().len(), 2); + // An argument that varies at every point is no different from one that reads a selector. + per_point("quantile(time() / 150 + 0.5, y)"); + per_point("quantile(scalar(x), y) by (tag_0)"); + + // A number the statement decides stays bound on the fold, whether it was written as one or as + // the arithmetic it means. + for (query, quantile) in [ + ("quantile(0.25 + 0.1 + 0.15, y)", 0.25 + 0.1 + 0.15), + ("quantile(pi() / 4, y)", std::f64::consts::PI / 4.0), + ] { + let tree = compiled(query).unwrap().tree; + let NativeExpr::Aggregate { op, .. } = &tree.root().expr else { + panic!("`{query}`: the constant argument left the constant path"); + }; + assert!( + matches!(op.kind, AggregateKind::Quantile { quantile: value } if value.to_bits() == quantile.to_bits()), + "`{query}`: {:?}", + op.kind + ); + } + + // A vector argument never reaches this compiler: the parser's type check refuses it, which is + // where Prometheus refuses `quantile(foo, v)` as well. + assert!( + promql_parser::parser::parse("quantile(x, y)").is_err(), + "a vector argument parsed" + ); +} + /// `max_of` and `min_of` take two scalars and answer a scalar, so the call binds the first argument /// as the map's input and the second as its one parameter. The two are `(scalar, scalar) -> scalar` /// in Prometheus, which is why neither of them carries a vector here. @@ -2888,31 +2969,77 @@ fn a_quantile_aggregate_binds_the_quantile_it_was_written_with() { } } -/// An aggregate's quantile computed at query time is refused, and the error names the argument: the -/// tree binds a quantile as a constant, so one that only exists at run time has nowhere to go. This -/// is the same refusal a parameterised range function gets, because it is the same missing field. +/// An aggregate's quantile written as a vector is refused, and the error names the argument. +/// +/// A scalar the query evaluates is bound beside the fold - the value the kernel reads `q` as, one +/// per grid point - so `quantile(time(), x)` compiles. A vector is not a value at all: Prometheus +/// refuses `quantile(foo, x)` at type check, and the parser this statement comes through refuses it +/// before the compiler sees it, exactly as it did before. The compiler keeps its own refusal for a +/// tree handed to it another way, under the name it always used. #[test] -fn a_computed_aggregate_quantile_is_refused_and_names_the_argument() { - let query = "quantile(time(), x)"; - let error = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime) - .expect_err(&format!("`{query}` compiled, and it should not have")); +fn an_aggregate_quantile_over_a_vector_is_refused_and_names_the_argument() { + let query = "quantile(x, y)"; + let error = promql_parser::parser::parse(query) + .expect_err(&format!("`{query}` parsed, and it should not have")); + assert!( + error.contains("expected type scalar"), + "`{query}` was refused by something other than the argument's type: {error}" + ); + + // The scalar the query evaluates instead is the argument this compiler binds per point, so the + // statement the old refusal was written for is one this route now answers. + let tree = compile( + &eval_stmt("quantile(time(), x)"), + raw_schema(), + SeriesOrdering::KeyThenTime, + ) + .expect("a scalar argument is a per-point `φ`"); + assert!(matches!( + tree.root().expr, + NativeExpr::ParameterizedAggregate { .. } + )); + + // The same fold with a vector argument, as a caller that did not come through the parser could + // build it: refused under the name it always was, which is what keeps such a statement off this + // route. + let PromExpr::VectorSelector(selector) = promql_parser::parser::parse("x").unwrap() else { + unreachable!("`x` is a selector") + }; + let PromExpr::Aggregate(mut aggregate) = + promql_parser::parser::parse("quantile(0.5, x)").unwrap() + else { + unreachable!("`quantile(0.5, x)` is an aggregate") + }; + aggregate.param = Some(Box::new(PromExpr::VectorSelector(selector))); + // The statement's grid is the one its well-formed twin would have; only the argument changes. + let stmt = EvalStmt { + expr: PromExpr::Aggregate(aggregate), + ..eval_stmt("quantile(0.5, x)") + }; + let error = compile(&stmt, raw_schema(), SeriesOrdering::KeyThenTime) + .expect_err("a vector argument compiled"); assert!( matches!(error, DataFusionError::NotImplemented(_)), - "`{query}` did not report NotImplemented: {error}" + "a vector argument did not report NotImplemented: {error}" ); let message = error.to_string(); assert!( - message.contains("whose first argument is `time()`"), - "`{query}` did not name the argument it found: {message}" + message.contains("whose first argument is `x`"), + "the refusal did not name the argument it found: {message}" ); assert!( message.contains("number literal"), - "`{query}` did not say what the argument has to be: {message}" + "the refusal did not say what the argument has to be: {message}" ); } +/// A fill inside an aggregate's quantile argument is refused where the fill is written. +/// +/// The argument is compiled as the scalar expression it is, so a binary operation carrying a fill is +/// refused by the same rule that refuses one anywhere else, naming the operation it found. The +/// statement is a `NotImplemented` either way, which is what keeps it on the existing plan. #[test] -fn a_fill_inside_an_aggregate_quantile_is_refused_and_names_the_argument() { +fn a_fill_inside_an_aggregate_quantile_is_refused_where_the_fill_is() { let query = "quantile(0.5 + fill(0) 0.1, x)"; let error = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime) .expect_err(&format!("`{query}` compiled, and it should not have")); @@ -2922,8 +3049,8 @@ fn a_fill_inside_an_aggregate_quantile_is_refused_and_names_the_argument() { ); let message = error.to_string(); assert!( - message.contains("first argument"), - "`{query}` blamed the wrong argument: {message}" + message.contains("0.5 + fill (0) 0.1"), + "`{query}` did not name the argument it found: {message}" ); assert!( message.contains("fill"), @@ -5622,6 +5749,9 @@ fn validate_inputs_rejects_misbound_occurrences_and_accepts_scalar_wrappers() { } NativeExpr::ParameterizedTopK { input, parameter, .. + } + | NativeExpr::ParameterizedAggregate { + input, parameter, .. } => { set_input_source(input, source); set_input_source(parameter, source); diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 8e8e297c283..a12500e529f 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -2264,6 +2264,11 @@ fn depends_on_input_order(node: &NativeNode) -> bool { NativeExpr::ParameterizedTopK { input, parameter, .. } => depends_on_input_order(input) || depends_on_input_order(parameter), + // The fold's own order is its input's, and the argument it reads per point can hold an + // order-dependent selection of its own (`quantile(scalar(limitk(1, a)), b)`). + NativeExpr::ParameterizedAggregate { + input, parameter, .. + } => depends_on_input_order(input) || depends_on_input_order(parameter), NativeExpr::ParameterizedHistogram { input, parameters, .. } => depends_on_input_order(input) || parameters.iter().any(depends_on_input_order), diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index d84ca9ab0be..1d0bc49e167 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -5716,6 +5716,9 @@ async fn native_fused_binary_keeps_independent_scan_occurrences() { } NativeExpr::ParameterizedTopK { input, parameter, .. + } + | NativeExpr::ParameterizedAggregate { + input, parameter, .. } => { sources(input, out); sources(parameter, out); @@ -6460,6 +6463,9 @@ async fn native_fused_three_selector_trees_bind_every_occurrence() { } NativeExpr::ParameterizedTopK { input, parameter, .. + } + | NativeExpr::ParameterizedAggregate { + input, parameter, .. } => { child(input); child(parameter); @@ -7701,6 +7707,255 @@ async fn native_fused_quantile_is_a_complete_aggregate() { } } +/// A `quantile` whose argument the query evaluates binds that argument beside the fold, and answers +/// per point. +/// +/// Prometheus reads the parameter at every step, so `quantile(scalar(foo), m)` is not the quantile of +/// a number bound before the query ran: the tree holds one `Complete` fold with its argument as a +/// second operand, the fold's input first. Neither route splits it - a quantile exports no state to +/// combine and a partition's quantile is not part of the group's - and a constant written as an +/// expression stays the number it folds to, exactly as it was. +#[tokio::test] +async fn native_fused_quantile_reads_a_per_point_parameter() { + // A constant the statement decides - a literal or arithmetic over literals - is bound on the + // fold, so the tree keeps the constant path it always had. + for (query, quantile) in [ + ( + "quantile(0.25 + 0.1 + 0.15, some_metric)", + 0.25 + 0.1 + 0.15, + ), + ( + "quantile(pi() / 4, some_metric)", + std::f64::consts::PI / 4.0, + ), + ] { + let plan = build_native_fused_plan(query, true).await; + let display = plan.display_indent().to_string(); + let fused = find_fused_series(&plan).unwrap_or_else(|| panic!("`{query}`: {display}")); + let NativeExpr::Aggregate { op, .. } = &fused.tree().root().expr else { + panic!("`{query}`: the folded constant left the constant path: {display}"); + }; + assert!( + matches!( + op.kind, + AggregateKind::Quantile { quantile: value } if value.to_bits() == quantile.to_bits() + ), + "`{query}`: {:?}", + op.kind + ); + } + + // An argument the statement evaluates: the fold reads it once per grid point. The columns are + // the grouping's either way, which is why the ungrouped statements publish no tag at all. + for (query, tags, grouped) in [ + ( + "quantile(scalar(some_metric), some_metric)", + &["__name__"][..], + false, + ), + ( + "quantile(time() / 150 + 0.5, some_metric)", + &["__name__"][..], + false, + ), + ( + "quantile(scalar(some_metric), some_metric) by (tag_0)", + &["__name__", "tag_0"][..], + true, + ), + ] { + let plan = build_native_fused_plan(query, true).await; + let display = plan.display_indent().to_string(); + let fused = find_fused_series(&plan).unwrap_or_else(|| panic!("`{query}`: {display}")); + // A quantile exports no state, so there is no split half for it, with an argument or without. + assert!(find_final_split(&plan).is_none(), "`{query}`: {display}"); + let NativeExpr::ParameterizedAggregate { + input, + op, + parameter, + } = &fused.tree().root().expr + else { + panic!("`{query}`: the root is not a per-point fold: {display}"); + }; + assert!( + matches!(op.kind, AggregateKind::Quantile { .. }) + && op.stage == AggregateStage::Complete, + "`{query}`: {display}" + ); + assert_eq!( + grouped, + matches!(&op.group, Grouping::By(labels) if !labels.is_empty()), + "`{query}`: {display}" + ); + // The fold reads the vector, the argument the scalar expression beside it. + assert!( + matches!( + input.expr, + NativeExpr::Instant { .. } | NativeExpr::Input(_) + ), + "`{query}`: {display}" + ); + assert!( + matches!(parameter.output, NativeType::Scalar(_)), + "`{query}`: the argument is not a scalar: {display}" + ); + assert_eq!( + // The value column the statement publishes is the expression it wrote, and the argument + // adds no column of its own: a scalar carries no labels. + expected_native_column_names(query, tags), + sorted_column_names(&plan), + "`{query}`" + ); + } +} + +/// A fold that reads its argument per point keeps the canonical boundary below it. +/// +/// `label_replace` rewrites the label set two series can share, so the fragments it produces meet +/// at a canonical merge before anything folds them. The fold above that merge reads the whole +/// vector - a `quantile` answers from its group's whole sample set, with a `φ` the statement +/// evaluates or with a number bound on it - so it is a global consumer of the same kind the bound +/// fold is, and the segmentation has to read it as one: the fold is cut out as its own segment and +/// the merge below it keeps its own boundary. Read as a per-partition node instead, the whole +/// subtree would be cut over the scans in one go, and the label-set merge would run once per +/// partition with nothing above it to collect the pieces. +#[tokio::test] +async fn native_fused_nested_per_point_quantile_keeps_its_canonical_boundary() { + let query = r#"quantile(time() / 2400, label_replace(some_metric, "tag_0", "same", "tag_0", ".*")) + 0"#; + let plan = build_native_fused_plan(query, true).await; + let display = plan.display_indent().to_string(); + fn segment_of(plan: &LogicalPlan) -> &FusedSeries { + let LogicalPlan::Extension(Extension { node }) = plan else { + panic!("a segment is an extension node"); + }; + node.as_any() + .downcast_ref::() + .expect("the extension is not a fused segment") + } + // The root is the pointwise rewrite, and what it reads is the fold as a segment of its own. + let root = find_fused_series(&plan).unwrap_or_else(|| panic!("`{query}`: {display}")); + let [fold] = root.children() else { + panic!("`{query}`: the rewrite must read the fold and nothing else: {display}"); + }; + let fold = segment_of(fold); + assert!( + matches!( + fold.tree().root().expr, + NativeExpr::ParameterizedAggregate { .. } + ), + "`{query}`: the fold is not a segment of its own: {display}" + ); + // Below the fold is the canonical boundary the label rewrite needs, as its own segment over the + // scan it reads. + let [producer] = fold.children() else { + panic!("`{query}`: the fold must read the canonical boundary: {display}"); + }; + let producer = segment_of(producer); + assert!( + producer.is_canonical_producer() + && matches!(producer.tree().root().expr, NativeExpr::Merge { .. }), + "`{query}`: the label-set merge is not a boundary below the fold: {display}" + ); + let [source] = producer.children() else { + panic!("`{query}`: the producer must read the scan it merges: {display}"); + }; + assert!( + find_fused_series(source).is_none(), + "`{query}`: the producer reads the scan itself, not another segment: {display}" + ); + assert!(find_final_split(&plan).is_none(), "`{query}`: {display}"); +} + +/// A `quantile` whose argument reads a second table still runs as one native execution. +/// +/// The argument is a scalar expression over another metric, so the statement reads two tables: the +/// fold reads one and its argument the other, and one execution above both is what folds them. +#[tokio::test] +async fn native_fused_quantile_parameter_over_a_second_table() { + let tables = [ + (DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string()), + (DEFAULT_SCHEMA_NAME.to_string(), "other_metric".to_string()), + ]; + let provider = || build_test_table_provider_with_tsid(&tables, 1, 1); + let query = "quantile(scalar(some_metric), other_metric)"; + let plan = build_native_fused_plan_with_provider(query, true, provider().await).await; + let display = plan.display_indent().to_string(); + let fused = find_fused_series(&plan).unwrap_or_else(|| panic!("`{query}`: {display}")); + assert_eq!(None, fused.binding().metric_name, "`{query}`: {display}"); + assert!( + matches!( + fused.tree().root().expr, + NativeExpr::ParameterizedAggregate { .. } + ), + "`{query}`: {display}" + ); + // The fold's input is bound first and its argument second, which is the order the sources are + // read in, and the statement still reads both tables. + assert_eq!( + vec!["other_metric", "some_metric"], + fused_input_metrics(&plan), + "`{query}`: {display}" + ); + assert!(find_final_split(&plan).is_none(), "`{query}`: {display}"); +} + +/// An argument that ranks its series in input order is refused by the native route. +/// +/// `scalar()` hands the fold one value per grid point, so the `limitk` inside the argument ranks the +/// argument's own source, and a tree over more than one input reads its inputs in whichever order the +/// gather finishes them: which series the ranking keeps would be the schedule's answer rather than the +/// statement's. The gate that refuses such a tree reads the fold's argument as well as the vector it +/// folds, and the argument is the only place an order-dependent selection sits here - the same +/// statement with an order-independent argument plans natively in +/// [`native_fused_quantile_parameter_over_a_second_table`]. +/// +/// The refusal is asserted on the native attempt alone rather than on the plan the statement gets: the +/// existing planner binds a `quantile` argument only as a literal and answers a per-point one with +/// `Invalid function argument for quantile`, so a tree this gate refuses has no other route - the +/// statement is answered natively or not at all. +#[tokio::test] +async fn native_fused_declines_an_order_dependent_quantile_argument() { + let state = build_query_engine_state(); + for (query, native) in [ + // The argument keeps the first series `limitk` is handed, so which one survives two gathered + // inputs is the schedule's answer. + ( + "quantile(scalar(limitk(1, some_metric)), other_metric)", + false, + ), + // Neither fold reads its source in arrival order, so the argument is what the refusal turns + // on rather than the two-table shape or a per-point argument as such. + ( + "quantile(scalar(max by (tag_0) (some_metric)), other_metric)", + true, + ), + ] { + let tables = [ + (DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string()), + (DEFAULT_SCHEMA_NAME.to_string(), "other_metric".to_string()), + ]; + let stmt = build_eval_stmt(query); + let mut planner = PromPlanner { + table_provider: build_test_table_provider_with_tsid(&tables, 1, 1).await, + ctx: PromPlannerContext::from_eval_stmt(&stmt).unwrap(), + promql_annotations: None, + native_fused: true, + }; + let planned = planner + .try_plan_native_fused(&stmt.expr, &state) + .await + .unwrap(); + assert_eq!( + native, + planned.is_some(), + "`{query}`: the gate must read the fold's argument as well as its vector: {}", + planned + .map(|plan| plan.display_indent().to_string()) + .unwrap_or_default() + ); + } +} + /// A `quantile` over a histogram column folds it natively, exactly as `min` and `max` do. /// /// The phi-quantile orders the samples it reads, so a histogram is one it cannot order: Prometheus diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index 1548ea55ec0..2b118dafae3 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -14884,6 +14884,197 @@ async fn native_promql_dynamic_histogram_quantile() { assert_eq!(wrapped_actual, wrapped_expected, "{wrapped_sql}"); } +/// A `quantile` whose parameter is evaluated reads it at every step and answers there what +/// `quantile(, m)` answers on its own. +/// +/// The vector holds two series, one at 1 and one at 10 at every step, so the `φ`-quantile of a step +/// is `1 + φ * 9` -- the linear interpolation Prometheus computes -- and a step whose `φ` the +/// statement has no sample for is a NaN `φ`, which Prometheus' `quantile` answers with NaN rather +/// than by dropping the point. The parameter is read from a second table, so the statement runs as +/// one native execution over two inputs. +#[tokio::test(flavor = "multi_thread")] +async fn native_promql_dynamic_quantile() { + common_telemetry::init_default_ut_logging(); + let config = mito2::config::MitoConfig { + experimental_series_scan_v2: true, + ..Default::default() + }; + let (standalone, observer) = native_test_instance( + GreptimeDbStandaloneBuilder::new("native_promql_dynamic_quantile").with_mito_config(config), + ) + .await; + let instance = standalone.fe_instance().clone(); + execute_all( + &instance, + "CREATE TABLE native_dyn_quantile (ts TIMESTAMP TIME INDEX, idc STRING, val DOUBLE, PRIMARY KEY(idc)); + INSERT INTO native_dyn_quantile (ts, idc, val) VALUES + (-600000, 'a', 1), (0, 'a', 1), (600000, 'a', 1), (1200000, 'a', 1), + (-600000, 'b', 10), (0, 'b', 10), (600000, 'b', 10), (1200000, 'b', 10); + CREATE TABLE native_dyn_phi (ts TIMESTAMP TIME INDEX, val DOUBLE); + INSERT INTO native_dyn_phi (ts, val) VALUES (0, 0.25), (600000, 0.75)", + QueryContext::arc(), + ) + .await; + + // `scalar(native_dyn_phi)` is 0.25 at 0s, 0.75 at 600s, and NaN at 1200s: the 5m lookback of an + // instant selection reaches no sample there, and `scalar()` answers NaN for a point that does + // not hold exactly one. + let phi = "scalar(native_dyn_phi)"; + let dynamic = format!("TQL EVAL (0, 1200, '600s') quantile({phi}, native_dyn_quantile)"); + observer.clear(); + let native = native_labelled_rows(native_tql_output(&instance, &dynamic, true).await).await; + assert!( + observer.fused().is_some(), + "the per-point quantile did not run natively: {dynamic}" + ); + let values: Vec<(i64, f64)> = native + .1 + .iter() + .map(|(ts, _, value)| (*ts, *value)) + .collect(); + assert_eq!(values.len(), 3, "{dynamic}: {values:?}"); + // `quantile(0.25, {1, 10})` and `quantile(0.75, {1, 10})`, and then the NaN step: a NaN `φ` + // answers a NaN sample, which is a point of the result rather than a missing one. + assert_eq!((values[0].0, values[0].1), (0, 3.25), "{dynamic}"); + assert_eq!((values[1].0, values[1].1), (600_000, 7.75), "{dynamic}"); + assert_eq!(values[2].0, 1_200_000, "{dynamic}"); + assert!(values[2].1.is_nan(), "{dynamic}: {:?}", values[2]); + assert!( + native.1.iter().all(|(_, labels, _)| labels.is_empty()), + "the ungrouped fold reported labels: {:?}", + native.1 + ); + + // The same statement with each step's `φ` written as a number: the per-point answer is the + // constant one at every step that has one. + for (step, quantile, expected) in [(0, 0.25, 3.25), (600, 0.75, 7.75)] { + let literal = + format!("TQL EVAL ({step}, {step}, '600s') quantile({quantile}, native_dyn_quantile)"); + let (_, rows) = + native_labelled_rows(native_tql_output(&instance, &literal, false).await).await; + assert_eq!( + rows.iter() + .map(|(ts, _, value)| (*ts, *value)) + .collect::>(), + vec![(step * 1_000, expected)], + "{literal}" + ); + } + + // A parameter that varies at every point, read from the evaluation time: `0`, `0.25`, `0.5`. + let time_sql = "TQL EVAL (0, 1200, '600s') quantile(time() / 2400, native_dyn_quantile)"; + observer.clear(); + let by_time = native_labelled_rows(native_tql_output(&instance, time_sql, true).await).await; + assert!( + observer.fused().is_some(), + "a `time()` parameter did not run natively: {time_sql}" + ); + assert_eq!( + by_time + .1 + .iter() + .map(|(ts, _, value)| (*ts, *value)) + .collect::>(), + vec![(0, 1.0), (600_000, 3.25), (1_200_000, 5.5)], + "{time_sql}" + ); + + // The grouping is untouched: each group is one member, so it answers that member's value at + // every step with a `φ`, and NaN at the step without one. + let grouped = + format!("TQL EVAL (0, 1200, '600s') quantile({phi}, native_dyn_quantile) by (idc)"); + observer.clear(); + let by_idc = native_labelled_rows(native_tql_output(&instance, &grouped, true).await).await; + assert!( + observer.fused().is_some(), + "a grouped per-point quantile did not run natively: {grouped}" + ); + let mut grouped_values: Vec<(i64, String, f64)> = by_idc + .1 + .iter() + .map(|(ts, labels, value)| (*ts, labels["idc"].clone(), *value)) + .collect(); + grouped_values.sort_by(|left, right| (&left.0, &left.1).cmp(&(&right.0, &right.1))); + let mut expected_grouped = [ + (0, "a".to_string(), 1.0), + (600_000, "a".to_string(), 1.0), + (0, "b".to_string(), 10.0), + (600_000, "b".to_string(), 10.0), + ]; + expected_grouped.sort_by(|left, right| (&left.0, &left.1).cmp(&(&right.0, &right.1))); + // Two groups at each of the three steps: the two steps with a `φ`, and the NaN step both + // groups answer too. The row count is asserted before the rows are read, so a group that + // answered nothing at the NaN step is a failure rather than a shorter list that happens to + // hold no wrong row. + assert_eq!( + 6, + grouped_values.len(), + "the grouped fold did not answer every group at every step: {grouped_values:?}" + ); + assert_eq!(grouped_values[..4], expected_grouped[..], "{grouped}"); + assert_eq!( + vec![(1_200_000, "a"), (1_200_000, "b")], + grouped_values[4..] + .iter() + .map(|(ts, group, _)| (*ts, group.as_str())) + .collect::>(), + "the grouped NaN step answered something else: {grouped_values:?}" + ); + assert!( + grouped_values[4..] + .iter() + .all(|(_, _, value)| value.is_nan()), + "the grouped NaN step answered a value rather than NaN: {grouped_values:?}" + ); + + // A vector argument is not a scalar, which Prometheus refuses at type check: the native route + // keeps declining it, so the statement is answered by the existing plan and fails there. + let vector_parameter = + "TQL EVAL (0, 1200, '600s') quantile(native_dyn_quantile, native_dyn_quantile)"; + observer.clear(); + let error = instance + .do_query(vector_parameter, native_query_context(true, 4)) + .await + .remove(0) + .unwrap_err(); + assert!( + observer.fused().is_none(), + "a vector parameter was admitted: {vector_parameter}" + ); + assert!( + format!("{error:?}").contains("quantile"), + "unexpected vector-parameter error: {error:?}" + ); + + // A constant written as an expression stays the number it folds to, and answers it natively. + let folded = "TQL EVAL (0, 1200, '600s') quantile(0.25 + 0.1 + 0.15, native_dyn_quantile)"; + let literal = "TQL EVAL (0, 1200, '600s') quantile(0.5, native_dyn_quantile)"; + observer.clear(); + let folded_native = + native_labelled_rows(native_tql_output(&instance, folded, true).await).await; + assert!( + observer.fused().is_some(), + "the folded constant did not run natively: {folded}" + ); + observer.clear(); + let literal_native = + native_labelled_rows(native_tql_output(&instance, literal, true).await).await; + assert!( + observer.fused().is_some(), + "the literal did not run natively: {literal}" + ); + assert_eq!(folded_native.1, literal_native.1, "{folded} != {literal}"); + assert_eq!( + folded_native + .1 + .iter() + .map(|(ts, _, value)| (*ts, *value)) + .collect::>(), + vec![(0, 5.5), (600_000, 5.5), (1_200_000, 5.5)], + "{folded}" + ); +} + /// A dynamic `topk` parameter is evaluated at each TQL evaluation timestamp. `time() / 60 + 1` /// truncates to k = 1, 2, 3 at 0s, 60s, and 120s respectively. #[tokio::test(flavor = "multi_thread")]