diff --git a/src/promql/src/extension_plan/fused_series.rs b/src/promql/src/extension_plan/fused_series.rs index 3fb64adef68..9aa204a412d 100644 --- a/src/promql/src/extension_plan/fused_series.rs +++ b/src/promql/src/extension_plan/fused_series.rs @@ -89,8 +89,9 @@ use crate::grid_series::series_bytes; use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor}; use crate::native::plan::{ AggregateKind, BoundAggregate, CanonicalOwner, CoPartitionedPair, Grouping, NativeExpr, - NativeNode, NativeProperties, NativeTree, NativeType, merges_are_placeable_in, - needs_single_execution_in_co, output_has_metric_name, reads_across_series, + NativeNode, NativeProperties, NativeTree, NativeType, match_is_co_partitioned, + merges_are_placeable_in, needs_single_execution_in_co, output_has_metric_name, + reads_across_series, }; use crate::source::materialize_raw_labels; @@ -301,6 +302,23 @@ impl FusedSeries { }) } + /// The output schema a [`FusedOutputFormat::SeriesFrame`] node over `tree` has to declare. + /// + /// This is the frame codec's own layout for the tree's evaluated root, which + /// [`Self::try_new_with_format`] checks a caller's schema against. A planner that builds a frame + /// producer asks here instead of re-deriving the layout, so the schema it passes in and the one + /// the constructor validates cannot disagree about it. + pub fn series_frame_schema(tree: &NativeTree) -> DataFusionResult { + let frame = series_frame_output_schema(evaluated_output(tree)?.as_ref())?; + Ok(Arc::new( + datafusion::common::DFSchema::try_from(frame).map_err(|error| { + DataFusionError::Plan(format!( + "FusedSeries cannot declare its frame schema as a logical schema: {error}" + )) + })?, + )) + } + /// Creates a one-source node that exports partition-local state for a complete aggregate. pub(crate) fn try_new_partial( promql: Arc, @@ -819,34 +837,24 @@ fn input_boundary( fn co_partitioned_pairs( inputs: &[(Arc, RawLabelSource, SeriesOrdering)], ) -> Vec { - let mut pairs = Vec::new(); - for (left_index, (left, _, _)) in inputs.iter().enumerate() { - let Some(left) = left.downcast_ref::() else { - continue; - }; - for (right_index, (right, _, _)) in inputs.iter().enumerate().skip(left_index + 1) { - let Some(right) = right.downcast_ref::() else { - continue; - }; - // Two routings are one routing only when they split into the same number of outputs. A - // partner routed into three outputs is not in the partition its two-output counterpart - // is, so its half of the match would be missing here while it exists elsewhere, and the - // pair is not the fact the match needs. - if left.outputs() != right.outputs() { - continue; - } - pairs.push(CoPartitionedPair { - left: left_index, - right: right_index, - // A pair whose producer half fails proves nothing: [`match_is_co_partitioned`] - // answers `pair.name_free`, so stating the pair with the failing half named is what - // makes one named side break it. Dropping the pair instead would hide which - // conjunct decided the fallback. - name_free: producer_is_name_free(left) && producer_is_name_free(right), - }); - } + if inputs.len() != 2 { + return Vec::new(); } - pairs + let Some(left) = inputs[0].0.downcast_ref::() else { + return Vec::new(); + }; + let Some(right) = inputs[1].0.downcast_ref::() else { + return Vec::new(); + }; + // Two routings are one routing only when they split into the same number of outputs. + if left.outputs() != right.outputs() { + return Vec::new(); + } + vec![CoPartitionedPair { + left: 0, + right: 1, + name_free: producer_is_name_free(left) && producer_is_name_free(right), + }] } /// Whether `repartition`'s producer answers series that carry no metric name. @@ -1428,10 +1436,37 @@ impl ExecutionPlan for FusedSeriesExec { .zip(&self.inputs) .map(|(child, (_, label_source, ordering))| (child, label_source.clone(), *ordering)) .collect(); - // A replaced child can take the proof away: a canonical repartition swapped for a plain - // multi-partition child hands the pieces of a label set to different executions again. The - // rebuilt node therefore asks the placement question over the children it was handed, and - // never inherits the answer the old ones gave. + // Freeze child placement only when this node's parallel execution depends on the + // two-child co-partitioned vector-match proof. Other trees (notably Complete aggregates) + // are rebuilt against their new positive partition count and validated normally by build. + let relies_on_match_proof = + |inputs: &[(Arc, RawLabelSource, SeriesOrdering)]| { + let NativeExpr::Binary { + left, + right, + matching, + } = &self.tree.root().expr + else { + return false; + }; + match_is_co_partitioned(left, right, matching, &co_partitioned_pairs(inputs)) + }; + if relies_on_match_proof(&self.inputs) { + let same_partition_contract = + children + .iter() + .zip(&self.inputs) + .all(|((child, _, _), (original, _, _))| { + child.properties().partitioning.partition_count() + == original.properties().partitioning.partition_count() + }); + if !same_partition_contract || !relies_on_match_proof(&children) { + return Err(DataFusionError::Plan( + "FusedSeries replacement children violate the original partition/routing contract" + .into(), + )); + } + } Self::reject_unplaceable_merges( Self::requires_single_execution(&children, &self.tree), &children, diff --git a/src/promql/src/extension_plan/fused_series/tests.rs b/src/promql/src/extension_plan/fused_series/tests.rs index 4863f4ec97f..adeb674ab59 100644 --- a/src/promql/src/extension_plan/fused_series/tests.rs +++ b/src/promql/src/extension_plan/fused_series/tests.rs @@ -5115,6 +5115,24 @@ fn abs_over_evaluated_input_tree() -> NativeTree { .expect("a map over an evaluated input is a legal tree") } +/// A Complete aggregate over evaluated input, whose grouping proves __name__ is absent. +fn complete_aggregate_over_evaluated_input_tree() -> NativeTree { + let input = evaluated_input(); + let output = input.output.samples().unwrap().clone(); + NativeTree::try_new(NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(input), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Grouping::By(Arc::from([Arc::from(HOST)])), + stage: AggregateStage::Complete, + }, + }, + output: NativeType::Samples(output), + }) + .expect("a Complete aggregate over evaluated input is legal") +} + /// `abs(rate(x[5m]))`: the raw-fed tree that answers what [`abs_over_evaluated_input_tree`] answers /// once its child has decided `rate(x[5m])`. fn abs_rate_tree() -> NativeTree { @@ -5791,6 +5809,55 @@ fn a_whole_vector_tree_over_a_repartitioning_child_reports_one_execution() { } } +#[tokio::test] +async fn complete_aggregate_rebuild_accepts_a_different_positive_child_partition_count() { + let tree = evaluated_complete_aggregate_tree(); + let contribution = |value| { + evaluated_chunk_with( + &metric(&[(HOST, "web-1")], Some(METRIC)), + 0, + vec![Some(value); GRID_LEN as usize], + true, + ) + }; + let exec = plan_of( + evaluated_node(&tree), + ScriptedEvaluated::plan(vec![vec![contribution(1.0)], vec![contribution(2.0)]]), + ) + .expect("the Complete aggregate reads all input partitions"); + assert_eq!(1, exec.properties().partitioning.partition_count()); + + let rebuilt = Arc::clone(&exec) + .replace_children( + vec![ScriptedEvaluated::plan(vec![ + vec![contribution(1.0)], + vec![], + vec![contribution(2.0)], + ])], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + .expect("a Complete aggregate accepts another positive input partition count"); + assert_eq!(1, rebuilt.properties().partitioning.partition_count()); + + let original = rows( + &collect(exec, SessionContext::default().task_ctx()) + .await + .unwrap(), + ); + let replacement = rows( + &collect(rebuilt, SessionContext::default().task_ctx()) + .await + .unwrap(), + ); + let expected = grid_timestamps() + .into_iter() + .map(|timestamp| (timestamp, Some(3.0), Some("web-1".to_string()), None)) + .collect::>(); + assert_eq!(expected, original); + assert_eq!(expected, replacement); + assert_eq!(original, replacement); +} + /// A Fused completes over a repartitioning child whose routed chain does not fit one output's queue. /// /// The child routes each chunk by canonical label set into bounded queues and reads its child one @@ -7600,7 +7667,7 @@ fn name_free_producer(host: &str, value: f64) -> Arc { true, )]; frame_producer( - &abs_over_evaluated_input_tree(), + &complete_aggregate_over_evaluated_input_tree(), ScriptedEvaluated::plan(vec![chunks]), ) } @@ -7735,40 +7802,54 @@ async fn rebuilding_over_an_unrouted_child_drops_the_pair_proof() { ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), ) }; - let unrouted = rebuilt(vec![ + let error = rebuilt(vec![ name_free_producer("web-1", 12.0), routed_into(name_free_producer("web-1", 4.0), 3), ]) - .expect("an unrouted producer is still a legal child"); - assert_eq!( - 1, - unrouted.properties().partitioning.partition_count(), - "a child that is not a routing proves no pair, so the rebuilt node falls back to one \ - execution" + .expect_err("replacing a routed child must reject the changed parallel contract"); + assert!( + error + .to_string() + .contains("original partition/routing contract") ); + for replacement in [ + routed_into(named_producer("web-1"), 3), + routed_into(unprovable_producer("web-1"), 3), + ] { + let error = rebuilt(vec![ + replacement, + routed_into(name_free_producer("web-1", 4.0), 3), + ]) + .expect_err("replacement producer without a name-free proof must be rejected"); + assert!( + error + .to_string() + .contains("original partition/routing contract") + ); + } + // Both sides are routings again, but into a different number of outputs: neither is in the // partition the other's partner is in, so the pair is not the fact the match needs either. - let mismatched = rebuilt(vec![ + let error = rebuilt(vec![ routed_into(name_free_producer("web-1", 12.0), 2), routed_into(name_free_producer("web-1", 4.0), 3), ]) - .expect("two routings of different widths are legal children"); - assert_eq!( - 1, - mismatched.properties().partitioning.partition_count(), - "routings that split into different output counts cannot be read in step, so the rebuilt \ - node falls back to one execution" + .expect_err("replacing children with unequal routing widths must be rejected"); + assert!( + error + .to_string() + .contains("original partition/routing contract") ); - // And the proof is derived, not spent: rebuilt over two equal-width routings it holds again. + // The original width and proof remain valid when both original routings are unchanged. let restored = rebuilt(vec![ - routed_into(name_free_producer("web-1", 12.0), 2), - routed_into(name_free_producer("web-1", 4.0), 2), + routed_into(name_free_producer("web-1", 12.0), 3), + routed_into(name_free_producer("web-1", 4.0), 3), ]) .expect("two routings of one width are the proven shape"); assert_eq!( - 2, + 3, restored.properties().partitioning.partition_count(), "the pair is read off the children on every build, so a rebuild that routes both sides \ identically proves it again" diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index a8fa3a4a213..d0ad34f8d06 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -1072,6 +1072,11 @@ pub fn match_is_co_partitioned( else { return false; }; + if !matches!(left_input.output, NativeType::Samples(ref schema) if schema.eval_grid.is_some()) + || !matches!(right_input.output, NativeType::Samples(ref schema) if schema.eval_grid.is_some()) + { + return false; + } let (left_source, right_source) = (left_input.source_index, right_input.source_index); let Some(pair) = co_partitioned .iter() @@ -1658,207 +1663,28 @@ fn broadcast_drops_labels(matching: &BinaryMatching) -> bool { /// - `None`: this walk cannot decide, which is not a claim in either direction: a consumer that /// needs the fact must read it as "not proved here" rather than as an answer. /// -/// The answer is derived from the node and the kernels it is bound to, never from a boundary, so a -/// shape whose output labels are decided outside the tree answers `None`. The shapes decided in every -/// case are the ones whose kernel writes the name away for whatever it read: `timestamp`, a window -/// running any function but `last_over_time`/`first_over_time`, a map of the two dropping operations, -/// an aggregate or `count_values` whose grouping does not list `__name__`, `absent`, the histogram -/// functions, and a two-vector arithmetic or `bool` comparison. The shapes that follow their input -/// are the ones that only carry labels through. Four answers are deliberately not given: a -/// `label_replace`/`label_join` may write `__name__` or clear it, an input of evaluated samples hands -/// on a value another execution built, a one-side-name-free `or`/`and`/`unless` keeps both sides' -/// samples, and a `group_left`/`group_right` may copy a name from its one side. Each of those is a -/// later fact's question, not this walk's. +/// This proof is intentionally narrow: only a concrete `Complete` aggregate producing samples can +/// prove name absence. Its `By` group must exclude `__name__`, or it may use any `Without` group, +/// which always drops the metric name. Every other shape returns `None`; this includes aggregates +/// grouped by `__name__` and operators whose output labels may preserve or restore that name. pub fn output_has_metric_name(node: &NativeNode) -> Option { - match &node.expr { - // A scan of raw samples reads one metric: the selector it was bound from names the metric, so - // every series it hands over carries that name, and raw samples are the only thing a scan - // hands over. The name itself is not in the tree - `BoundInput` holds the source index, the - // output type and the ordering, and the compiler keeps the name beside them - so this is the - // one input shape the tree can answer for: which type an input is decides whether anything - // above it can name a series at all. - // - // Evaluated samples at an input are another execution's answer: whether its label sets still - // carry a name was decided by the node that built them, which is not in this tree. Aggregate - // state is not a series at all, and no consumer of this fact has an operand of that type. - NativeExpr::Input(binding) => match binding.output.samples() { - Some(schema) if schema.eval_grid.is_none() => Some(true), - _ => None, - }, - // A constant is one value per grid point and holds no label set, so it carries no name. - NativeExpr::Scalar(_) => Some(false), - // A selection answers the label set it read, except `timestamp(x)`: `output_metric` in - // [`execute`](crate::native::execute) rewrites the labels through `map::drop_metric_name` for - // `InstantValue::Timestamp` and clones them for `Sample` and `InfoTimestamp`, which is the - // selection `info` reads. - NativeExpr::Instant { input, op } => match op.value { - InstantValue::Sample | InstantValue::InfoTimestamp => output_has_metric_name(input), - InstantValue::Timestamp => Some(false), - }, - // A merge groups the fragments it read by canonical label set and hands each set on as it - // arrived, so it writes no label of its own and what it emits carries the name the fragments - // carried. - NativeExpr::Merge { input } => output_has_metric_name(input), - // A window folds values and keeps the label set of the series it read, unless the function - // drops the metric name: `RangeFunction::drops_metric_name` holds for every function but - // `last_over_time` and `first_over_time`, and `RangeEvaluator::emit` applies it by removing - // `METADATA_LABELS` from the label set it hands over. - NativeExpr::Window { input, op } => { - if op.function.drops_metric_name() { - Some(false) - } else { - output_has_metric_name(input) - } - } - // A map rewrites the label set of every series it is handed. `map_math` and - // `map_native_histogram` both end with `drop_metric_name` (see - // [`preserves_canonical_identity`]), so their output carries no name whatever it read, while - // `label_replace`/`label_join` write a label of the caller's choosing - `__name__` included - - // and can empty it, so what a series ends under is not this node's to answer. - NativeExpr::Map { input, op } => { - if op.ops.is_empty() { - // A map with no operation rewrites nothing; `validate` refuses the shape, and - // following the input keeps the answer exact rather than reporting a rewrite that is - // not there. - output_has_metric_name(input) - } else if op - .ops - .iter() - .all(|op| matches!(op, MapOp::Math(_) | MapOp::Histogram(_))) - { - Some(false) - } else { - None - } - } - // A timestamp reports each sample's position, and `NativeNode::timestamp` rebuilds the labels - // through `map::drop_metric_name` on the way: its output carries no name. - NativeExpr::Timestamp { .. } => Some(false), - // An aggregate answers its group key, which is `GroupingLabels::apply` in - // [`aggregate`](crate::aggregate): `by(names)` keeps the name only when `names` lists it - // (`SeriesLabels::keep_only` clears a name the list does not hold) and `without(_)` removes it - // whatever `names` says. Partial state is not a series at all, so it carries none. - NativeExpr::Aggregate { input, op } => match &node.output { - NativeType::Samples(_) => { - grouping_keeps_metric_name(&op.group, output_has_metric_name(input)) - } - NativeType::Scalar(_) | NativeType::AggregateState(_) => Some(false), - }, - // A vector operation is decided one operator at a time. - // - // `topk`, `bottomk`, `limitk`, `limit_ratio` and `sort` hand back series they read under the - // labels those series arrived with - `select.rs` rewrites no label - so the input's answer is - // theirs. `absent` builds its labels from the argument's matchers and skips `__name__` - // (`absent_labels`), `histogram_quantile`/`histogram_fraction` remove `METADATA_LABELS` from - // each group they read (`histogram_eval`), and `count_values` answers a grouping's label sets - // as an aggregate does. - NativeExpr::Vector { input, op } => match op { - BoundVectorOp::TopK { .. } - | BoundVectorOp::LimitK { .. } - | BoundVectorOp::LimitRatio { .. } - | BoundVectorOp::Sort(_) => output_has_metric_name(input), - BoundVectorOp::Absent { .. } | BoundVectorOp::Histogram(_) => Some(false), - BoundVectorOp::CountValues { group, .. } => { - grouping_keeps_metric_name(group, output_has_metric_name(input)) - } - }, - // A binary operation answers under the label set `result_metric` builds in - // [`vector_match`](crate::vector_match), which is the many side's labels and the modifiers' - // rewrite of them. - NativeExpr::Binary { - left, - right, - matching, - } => match (&left.output, &right.output) { - // Two constants make a constant, which holds no label set. - (NativeType::Scalar(_), NativeType::Scalar(_)) => Some(false), - // A broadcast reaches each series of its vector side as it is, unless the operation drops - // the metric name on the way: arithmetic and a `bool` comparison do, a filtering - // comparison keeps the label set it read (`BroadcastRuntime::drops_labels`, which - // [`broadcast_drops_labels`] restates). - (NativeType::Scalar(_), _) | (_, NativeType::Scalar(_)) => { - let vector = if left.output.samples().is_some() { - left - } else { - right - }; - if broadcast_drops_labels(matching) { + // Only this aggregate shape is a sufficient proof for producer routing: a complete + // aggregate emits its group key, and By/Without excluding __name__ necessarily drops it. + // Other operations may restore the name (count_values and binary include modifiers), so + // do not infer absence through them. + match (&node.expr, &node.output) { + (NativeExpr::Aggregate { op, .. }, NativeType::Samples(_)) + if op.stage == AggregateStage::Complete => + { + match &op.group { + Grouping::By(names) if !names.iter().any(|name| &**name == "__name__") => { Some(false) - } else { - output_has_metric_name(vector) } - } - // Two vectors are matched by the kernel, which files each pairing under the many side's - // labels with the name removed unless the operation is a filtering comparison: `drop_name` - // in `vector_match` is `!op.is_comparison() || return_bool`, the same rule the broadcast - // applies. One-to-one then rewrites that label set by the modifiers - `on(names)` keeps - // only `names`, `ignoring(names)` drops them - and `group_left`/`group_right` keep it as - // it is and copy the `include` labels of the one side instead. - (_, _) => { - if broadcast_drops_labels(matching) { - return Some(false); - } - match &matching.cardinality { - Cardinality::OneToOne => { - let keeps_name = match &matching.labels { - MatchingLabels::On(names) => { - names.iter().any(|name| &**name == "__name__") - } - MatchingLabels::Ignoring(names) => { - !names.iter().any(|name| &**name == "__name__") - } - }; - if keeps_name { - output_has_metric_name(left) - } else { - Some(false) - } - } - Cardinality::ManyToOne(include) => { - if include.iter().any(|name| &**name == "__name__") { - // The included name of the one side replaces the many side's. - None - } else { - output_has_metric_name(left) - } - } - Cardinality::OneToMany(include) => { - if include.iter().any(|name| &**name == "__name__") { - None - } else { - output_has_metric_name(right) - } - } - } - } - }, - // A set operation keeps each side's samples under the label set they arrived with - // (`set_vectors` rewrites no label), so a name survives it only if both sides carry one and a - // name is absent only if both sides lack it. Sides that disagree settle nothing: `or` keeps - // both sides' samples and `and`/`unless` keep the left side's, so the answer would be a claim - // about one operator rather than about the shape. - NativeExpr::Set { left, right, .. } => { - match (output_has_metric_name(left), output_has_metric_name(right)) { - (Some(left), Some(right)) if left == right => Some(left), + Grouping::Without(_) => Some(false), _ => None, } } - // `info` enriches each base series with the data labels of the info series that share its - // identifying labels: `add_data_labels` copies the info series' ordinary tags only, never the - // name, so each result keeps the name its base series had. - NativeExpr::Info { base, .. } => output_has_metric_name(base), - } -} - -/// What a grouping does to the metric name of the series it is handed. -/// -/// `by(names)` keeps the name only when `names` lists it and `without(_)` removes it, which is -/// `GroupingLabels::apply` in [`aggregate`](crate::aggregate): `keep_only` clears a name the list does -/// not hold, and the `without` arm removes `__name__` after removing its own labels. -fn grouping_keeps_metric_name(group: &Grouping, input: Option) -> Option { - match group { - Grouping::By(names) if names.iter().any(|name| &**name == "__name__") => input, - Grouping::By(_) | Grouping::Without(_) => Some(false), + _ => None, } } diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index 9d5473bc744..5cbddd83d4f 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -2870,13 +2870,9 @@ fn the_metric_name_fact_follows_what_each_shape_does_to_a_label_set() { let shared = grid(0, 60_000, 4); let selected = || instant_over(raw_input_at(0), InstantValue::Sample, Arc::clone(&shared)); - // A scan of one metric hands its series over under that metric's name. A value another execution - // produced carries whatever that execution left on it, and this tree does not hold that - // execution, so the answer is `None` rather than a guess in either direction: reading it as "no - // name" is what would make a named match look name-free and run it per partition. That is why the - // match proof takes the fact on [`CoPartitionedPair::name_free`], from the layer that built the - // producers, instead of deriving it here. - assert_eq!(output_has_metric_name(&raw_input_at(0)), Some(true)); + // This proof is deliberately narrow: only a Complete aggregate's group key establishes that + // its output has no metric name. Input provenance and all other operators are inconclusive. + assert_eq!(output_has_metric_name(&raw_input_at(0)), None); assert_eq!( output_has_metric_name(&input_on_at(0, Arc::clone(&shared))), None @@ -2884,14 +2880,14 @@ fn the_metric_name_fact_follows_what_each_shape_does_to_a_label_set() { // A selection answers the label set it read, except `timestamp(x)`, which rebuilds the labels // through `drop_metric_name`. Over an evaluated input the same selection follows it into `None`. - assert_eq!(output_has_metric_name(&selected()), Some(true)); + assert_eq!(output_has_metric_name(&selected()), None); assert_eq!( output_has_metric_name(&instant_over( raw_input_at(0), InstantValue::InfoTimestamp, Arc::clone(&shared) )), - Some(true) + None ); assert_eq!( output_has_metric_name(&instant_over( @@ -2899,7 +2895,7 @@ fn the_metric_name_fact_follows_what_each_shape_does_to_a_label_set() { InstantValue::Timestamp, Arc::clone(&shared) )), - Some(false) + None ); assert_eq!( output_has_metric_name(&instant_over( @@ -2918,7 +2914,7 @@ fn the_metric_name_fact_follows_what_each_shape_does_to_a_label_set() { None, Arc::clone(&shared) )), - Some(false) + None ); assert_eq!( output_has_metric_name(&window_with( @@ -2927,18 +2923,18 @@ fn the_metric_name_fact_follows_what_each_shape_does_to_a_label_set() { None, Arc::clone(&shared) )), - Some(true) + None ); // An aggregate answers its group key: `by(ns)` and `without(...)` drop `__name__`, and - // `by("__name__")` keeps the name the input had. + // A Complete aggregate drops the name only when its group key excludes it. assert_eq!( output_has_metric_name(&sum_by(selected(), by(&["ns"]))), Some(false) ); assert_eq!( output_has_metric_name(&sum_by(selected(), by(&["__name__"]))), - Some(true) + None ); assert_eq!( output_has_metric_name(&sum_by(selected(), without(&["ns"]))), @@ -2946,16 +2942,13 @@ fn the_metric_name_fact_follows_what_each_shape_does_to_a_label_set() { ); // A timestamp reports a position under the name dropped, and a merge writes no label of its own. - assert_eq!( - output_has_metric_name(×tamp_of(selected())), - Some(false) - ); - assert_eq!(output_has_metric_name(&merge_over(selected())), Some(true)); + assert_eq!(output_has_metric_name(×tamp_of(selected())), None); + assert_eq!(output_has_metric_name(&merge_over(selected())), None); // A map of `map_math`/`map_native_histogram` drops the name, while a label rewrite writes a label // of its own choosing - `__name__` included - and can clear it. let mapped = map_over(selected()); - assert_eq!(output_has_metric_name(&mapped), Some(false)); + assert_eq!(output_has_metric_name(&mapped), None); assert_eq!( output_has_metric_name(&map_rewriting_labels(selected())), None @@ -2972,23 +2965,23 @@ fn the_metric_name_fact_follows_what_each_shape_does_to_a_label_set() { }, output: evaluated(Arc::new([]), Arc::clone(&shared)), }; - assert_eq!(output_has_metric_name(&absent), Some(false)); - assert_eq!(output_has_metric_name(&sorted(selected())), Some(true)); + assert_eq!(output_has_metric_name(&absent), None); + assert_eq!(output_has_metric_name(&sorted(selected())), None); // A two-vector match drops the name for arithmetic and for a `bool` comparison, keeps the many // side's labels for a filtering comparison under the default modifiers, and drops them under // `on(host)`, which keeps only the labels it names. let two_vectors = |modifiers: BinaryMatching| binary_with(selected(), selected(), modifiers); - assert_eq!(output_has_metric_name(&two_vectors(add())), Some(false)); + assert_eq!(output_has_metric_name(&two_vectors(add())), None); assert_eq!( output_has_metric_name(&two_vectors(matching(BinaryOp::Gt, false))), - Some(true) + None ); assert_eq!( output_has_metric_name(&two_vectors(matching(BinaryOp::Gt, true))), - Some(false) + None ); - assert_eq!(output_has_metric_name(&two_vectors(on_host())), Some(false)); + assert_eq!(output_has_metric_name(&two_vectors(on_host())), None); // A broadcast answers the vector side's series, and the operation decides whether the labels // survive it. @@ -2999,7 +2992,7 @@ fn the_metric_name_fact_follows_what_each_shape_does_to_a_label_set() { constant(), matching(BinaryOp::Mul, false) )), - Some(false) + None ); assert_eq!( output_has_metric_name(&binary_with( @@ -3007,7 +3000,7 @@ fn the_metric_name_fact_follows_what_each_shape_does_to_a_label_set() { constant(), matching(BinaryOp::Gt, false) )), - Some(true) + None ); // A set operation keeps each side's samples, so it answers only when both sides agree. @@ -3022,10 +3015,7 @@ fn the_metric_name_fact_follows_what_each_shape_does_to_a_label_set() { }, output: evaluated(Arc::new([]), Arc::clone(&shared)), }; - assert_eq!( - output_has_metric_name(&set(selected(), selected())), - Some(true) - ); + assert_eq!(output_has_metric_name(&set(selected(), selected())), None); assert_eq!( output_has_metric_name(&set(selected(), sum_by(selected(), by(&["ns"])))), None @@ -3066,8 +3056,8 @@ fn a_match_of_two_named_sides_needs_one_execution_whatever_the_routing_proved() InstantValue::Sample, Arc::clone(&shared) )), - Some(true), - "a scan of one metric hands its series over under that metric's name" + None, + "producer name is not inferred outside Complete aggregates" ); assert_eq!( output_has_metric_name(&instant_over( @@ -3075,7 +3065,7 @@ fn a_match_of_two_named_sides_needs_one_execution_whatever_the_routing_proved() InstantValue::Sample, Arc::clone(&shared) )), - Some(true) + None ); assert!( needs_single_execution_in_co( diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 5a9bd694762..aace9ecacc1 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -46,11 +46,14 @@ use datafusion::prelude::Expr as DfExpr; use datafusion_expr::Expr; use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; -use promql::extension_plan::{AggregateFinalize, FusedSeries, FusedSeriesBinding, RawSeriesSource}; +use datatypes::series::time::EvalGrid; +use promql::extension_plan::{ + AggregateFinalize, FusedOutputFormat, FusedSeries, FusedSeriesBinding, RawSeriesSource, +}; use promql::native::canonicalize::insert_native_merge_inside_current_fused; use promql::native::plan::{ - NativeExpr, NativeNode, NativeProperties, NativeTree, merges_are_placeable_in, - needs_single_execution, reads_across_series, + AggregateStage, BoundInput, Grouping, NativeExpr, NativeNode, NativeProperties, NativeTree, + merges_are_placeable_in, needs_single_execution, output_has_metric_name, reads_across_series, }; use promql::vector_match::{Cardinality, MatchingLabels, SetOp}; use promql_parser::label::Matchers; @@ -561,6 +564,10 @@ impl PromPlanner { .iter() .map(|(_, _, _, _, tags)| tags.clone()) .collect::>(); + let source_metrics = prepared + .iter() + .map(|(_, _, metric, _, _)| metric.clone()) + .collect::>(); let children = prepared .into_iter() .map(|(scan, schema, metric, _, tags)| { @@ -583,6 +590,26 @@ impl PromPlanner { }) .collect::, DataFusionError>>() .context(DataFusionPlanningSnafu)?; + // A fold on each side of a default one-to-one match is planned as three nodes rather than + // one, and it is decided here: before the placement below, because that question is asked of + // a tree that folds across series on both sides, and this tree answers it with "one + // execution" (a `Complete` aggregate requires one unconditionally). The one execution is + // exactly what the split takes off the match: each side is given a node of its own to fold + // in, and the match above them reads two evaluated inputs, which is the shape + // `match_is_co_partitioned` proves from the physical children. The split is offered the + // children this route already prepared, so each producer reads its scan exactly as the + // single-selector route would have it read. + if let Some(plan) = plan_dual_aggregate_match( + prom_expr, + &compiled.tree, + &children, + &source_metrics, + &source_tags, + &grid, + &time, + )? { + return Ok(Some((plan, single_input_context))); + } // Where the tree is placed is decided on the tree exactly as the compiler produced it, and // before anything is inserted into it. A merge reads across series, so a decision taken // afterwards would answer for the rewrite rather than for the query: the prefix of `sum(x)` @@ -874,9 +901,15 @@ pub(crate) fn same_table_scans<'a>(plans: impl IntoIterator]) -> Option> { match &node.expr { NativeExpr::Input(input) => source_tags.get(input.source_index).cloned(), @@ -890,7 +923,22 @@ fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Option fused_output_tags(input, source_tags), - NativeExpr::Aggregate { .. } | NativeExpr::Vector { .. } => None, + // An aggregate re-labels every group's output series to its group key, so the labels it + // reports are the ones that key keeps: `by` keeps the names it lists that the input carries, + // `without` keeps the input's other labels, and no modifier is a `by` with an empty list - + // one group and no label at all. [`group_key_tags`] is that derivation. + // + // Taken from commit `8ee7c649ec0` of the `f-wiring` worktree, where the same walk answered + // this question for the same reason. The `Vector` arm that commit added beside it is + // deliberately not here: a whole-vector kernel's labels are that shape's problem. + NativeExpr::Aggregate { input, op } => { + let input_tags = fused_output_tags(input, source_tags)?; + // A complete aggregate keeps its input's value fields, and those are the names its group + // key must not name; see [`group_key_tags`]. + let fields = node.output.samples()?; + group_key_tags(input_tags, &op.group, &fields.fields, None) + } + NativeExpr::Vector { .. } => None, NativeExpr::Binary { left, right, @@ -962,6 +1010,381 @@ fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Option, + group: &Grouping, + fields: &[FieldSpec], + written: Option<&str>, +) -> Option> { + let named = |names: &[Arc]| -> Vec { + tags.iter() + .filter(|tag| names.iter().any(|name| name.as_ref() == tag.as_str())) + .cloned() + .collect() + }; + match group { + Grouping::By(names) => { + let names_a_field = names.iter().any(|name| { + written.is_none_or(|written| written != name.as_ref()) + && fields.iter().any(|field| field.name == *name) + }); + (!names_a_field).then(|| named(names)) + } + // `without` keeps every label the input carries other than the ones it names. Its own doc + // also drops `__name__`, which costs nothing here: a name is not a scan tag column and never + // reaches this walk, so nothing has to remove it. + Grouping::Without(names) => Some( + tags.into_iter() + .filter(|tag| !names.iter().any(|name| name.as_ref() == tag.as_str())) + .collect(), + ), + } +} + +/// The two `Complete` aggregate operands of a default one-to-one match, each with the source it +/// reads, or `None` when `root` is another shape. +/// +/// `sum by(ns)(m1) / sum by(ns)(m2)` compiles to one tree - a [`NativeExpr::Binary`] over one +/// aggregate per side - and that tree answers two questions badly. It is one execution, because +/// [`needs_single_execution_in_co`](promql::native::plan::needs_single_execution_in_co) answers `true` +/// for a `Complete` aggregate unconditionally, so no parallelism survives in it. And the match in it +/// cannot be proven co-partitioned: [`match_is_co_partitioned`] reads its operands, and an aggregate +/// is not the routed input it would have to be - correctly, because a fold invents the key identity +/// the routing never saw. +/// +/// Both facts are about the tree as compiled and both stop applying once the match is lifted off the +/// folds: the match then reads two evaluated inputs, and each fold reads one metric whole inside a +/// producer of its own. What this predicate checks is that the lift is available - the match is the +/// default one, each side is exactly one fold, the two folds read different sources, and each fold's +/// output carries no metric name. +/// +/// Every conjunct is required: +/// +/// 1. the match is the default one - [`MatchingLabels::Ignoring`] with no label, whose key is every +/// label but `__name__` - and one-to-one, which is what `match_is_co_partitioned` needs the tree +/// above the producers to be (ยง4 of its documentation); +/// 2. each operand is one [`AggregateStage::Complete`] fold; +/// 3. each fold's subtree reads exactly one source, and the two are different: two producers over +/// the same source would be two scans of it, and the co-partitioned proof is about two routings +/// of two different metrics (`CoPartitionedPair` names two sources); +/// 4. each fold's output carries no metric name ([`output_has_metric_name`] is `Some(false)`): that +/// is what makes the canonical key the routing groups by and the match key one key. `None` - +/// "not proved here" - is not accepted, and neither is `Some(true)`, which is `by(__name__)`; +/// 5. the groups can be named as output columns ([`fused_output_tags`] answers `Some`), because the +/// node above the producers declares them. +fn dual_aggregate_match<'a>( + root: &'a NativeNode, + source_tags: &[Vec], +) -> Option<((&'a NativeNode, usize), (&'a NativeNode, usize))> { + let NativeExpr::Binary { + left, + right, + matching, + } = &root.expr + else { + return None; + }; + if matching.cardinality != Cardinality::OneToOne { + return None; + } + if !matches!(&matching.labels, MatchingLabels::Ignoring(names) if names.is_empty()) { + return None; + } + let complete_fold = |node: &NativeNode| { + matches!( + &node.expr, + NativeExpr::Aggregate { op, .. } if op.stage == AggregateStage::Complete + ) + }; + if !complete_fold(left) || !complete_fold(right) { + return None; + } + let left_source = only_source(left)?; + let right_source = only_source(right)?; + if left_source == right_source { + return None; + } + if output_has_metric_name(left) != Some(false) || output_has_metric_name(right) != Some(false) { + return None; + } + fused_output_tags(root, source_tags)?; + Some(((left, left_source), (right, right_source))) +} + +/// The one source the subtree below `node` reads, or `None` when it reads several or none. +fn only_source(node: &NativeNode) -> Option { + fn collect(node: &NativeNode, sources: &mut Vec) { + match &node.expr { + NativeExpr::Input(input) => sources.push(input.source_index), + NativeExpr::Scalar(_) => {} + NativeExpr::Instant { input, .. } + | NativeExpr::Merge { input } + | NativeExpr::Window { input, .. } + | NativeExpr::Map { input, .. } + | NativeExpr::Timestamp { input } + | NativeExpr::Aggregate { input, .. } + | NativeExpr::Vector { input, .. } => collect(input, sources), + NativeExpr::Binary { left, right, .. } + | NativeExpr::Set { left, right, .. } + | NativeExpr::Info { + base: left, + info: right, + .. + } => { + collect(left, sources); + collect(right, sources); + } + } + } + + let mut sources = Vec::new(); + collect(node, &mut sources); + let (&first, rest) = sources.split_first()?; + rest.iter().all(|source| *source == first).then_some(first) +} + +/// `node` with every input leaf bound to `source`. +/// +/// A producer tree is a subtree of the statement's compiled tree, whose leaves index the statement's +/// selectors. The producer has one child, so its leaf has to name child 0: that index is how the node +/// files the frames its child hands it, and +/// [`collect_source_schemas`](promql::extension_plan) requires the indexes to be dense from zero. +fn rebind_to_source(node: &NativeNode, source: usize) -> NativeNode { + let single = |input: &NativeNode| Box::new(rebind_to_source(input, source)); + let expr = match &node.expr { + NativeExpr::Input(input) => NativeExpr::Input(BoundInput { + source_index: source, + output: input.output.clone(), + ordering: input.ordering, + }), + NativeExpr::Scalar(scalar) => NativeExpr::Scalar(scalar.clone()), + NativeExpr::Instant { input, op } => NativeExpr::Instant { + input: single(input), + op: op.clone(), + }, + NativeExpr::Merge { input } => NativeExpr::Merge { + input: single(input), + }, + NativeExpr::Window { input, op } => NativeExpr::Window { + input: single(input), + op: op.clone(), + }, + NativeExpr::Map { input, op } => NativeExpr::Map { + input: single(input), + op: op.clone(), + }, + NativeExpr::Timestamp { input } => NativeExpr::Timestamp { + input: single(input), + }, + NativeExpr::Aggregate { input, op } => NativeExpr::Aggregate { + input: single(input), + op: op.clone(), + }, + NativeExpr::Vector { input, op } => NativeExpr::Vector { + input: single(input), + op: op.clone(), + }, + NativeExpr::Binary { + left, + right, + matching, + } => NativeExpr::Binary { + left: single(left), + right: single(right), + matching: matching.clone(), + }, + NativeExpr::Set { left, right, op } => NativeExpr::Set { + left: single(left), + right: single(right), + op: op.clone(), + }, + NativeExpr::Info { + base, + info, + selector, + } => NativeExpr::Info { + base: single(base), + info: single(info), + selector: selector.clone(), + }, + }; + NativeNode { + expr, + output: node.output.clone(), + } +} + +/// Plans a dual-aggregate match as three fused nodes, or `None` when the tree is another shape. +/// +/// `sum by(ns)(m1) / sum by(ns)(m2)` becomes +/// +/// ```text +/// B = FusedSeries { tree: Binary { Input(0), Input(1) }, PlainRows } over [A1, A2] +/// A1 = FusedSeries { tree: sum by(ns)(Input 0), SeriesFrame } over the scan of m1 +/// A2 = FusedSeries { tree: sum by(ns)(Input 0), SeriesFrame } over the scan of m2 +/// ``` +/// +/// `[dual_aggregate_match]` decides whether the shape is one this can be built for. Each producer is +/// a whole fold over one metric, so it runs in one execution - which is what a `Complete` aggregate +/// asks for unconditionally - and it hands its answer over as an evaluated series frame. The match +/// above them reads those two frames as its own two inputs, which is why it is the one node whose +/// placement the physical layer can prove: two name-free producers of a default one-to-one match are +/// [`CoPartitionedPair`](promql::native::plan::CoPartitionedPair)s, and the match above them then +/// runs once per output of the routing the physical layer inserts between them. +/// +/// Nothing about this shape is decided by rewriting the tree: three nodes are built, and the existing +/// per-node reasoning applies to each of them unchanged. +fn plan_dual_aggregate_match( + prom_expr: &PromExpr, + tree: &NativeTree, + children: &[LogicalPlan], + source_metrics: &[Option>], + source_tags: &[Vec], + grid: &Arc, + time_index: &str, +) -> Result> { + let Some(((left_operand, left_source), (right_operand, right_source))) = + dual_aggregate_match(tree.root(), source_tags) + else { + return Ok(None); + }; + // Each producer is named after its own half of the query, so `EXPLAIN` says which fold it runs. + let (left_promql, right_promql) = match prom_expr { + PromExpr::Binary(binary) => (binary.lhs.to_string(), binary.rhs.to_string()), + // A statement whose written form is not the match itself - it is parenthesised - is named by + // the text it was written as; the tree below each node still says what it computes. + _ => (prom_expr.to_string(), prom_expr.to_string()), + }; + let mut producers = Vec::with_capacity(2); + for (operand, source, side_promql) in [ + (left_operand, left_source, left_promql), + (right_operand, right_source, right_promql), + ] { + let (Some(scan), Some(metric), Some(tags)) = ( + children.get(source), + source_metrics.get(source), + source_tags.get(source), + ) else { + return Err(DataFusionError::Internal(format!( + "the matched operand reads source {source}, which the planner did not prepare" + ))) + .context(DataFusionPlanningSnafu); + }; + // The fold alone, over the one source this producer is given. + let tree = + NativeTree::try_new(rebind_to_source(operand, 0)).context(DataFusionPlanningSnafu)?; + // The producer's root is a `Complete` aggregate, so the execution the physical layer + // confirms for it is a single one (`needs_single_execution_in_co` is unconditional about that + // stage): it reads every input partition at once. That is the placement whose tree the + // insertion pass may rewrite, so it runs here - and it inserts nothing for the shapes this + // split admits, because a fold reads its input one contribution at a time + // (`canonicalize`'s per-consumer table). + let tree = + insert_native_merge_inside_current_fused(&tree, &[NativeProperties::source_pieces()]) + .context(DataFusionPlanningSnafu)?; + let output_schema = + FusedSeries::series_frame_schema(&tree).context(DataFusionPlanningSnafu)?; + let node = FusedSeries::try_new_with_format( + Arc::from(side_promql), + tree, + FusedSeriesBinding { + grid: Arc::clone(grid), + time_index: time_index.to_string(), + tags: tags.clone(), + metric_name: metric.clone(), + }, + vec![scan.clone()], + output_schema, + FusedOutputFormat::SeriesFrame, + ) + .context(DataFusionPlanningSnafu)?; + producers.push(LogicalPlan::Extension(Extension { + node: Arc::new(node), + })); + } + // The match over the two producers. Each operand is a leaf over *this* node's children, so its + // index numbers them and not the statement's selectors; both read evaluated frames, which is what + // a producer's frame output is and what this node's input nodes are bound to. + let NativeExpr::Binary { matching, .. } = &tree.root().expr else { + return Err(DataFusionError::Internal( + "a matched dual-aggregate tree is not a binary operation".into(), + )) + .context(DataFusionPlanningSnafu); + }; + let evaluated_leaf = |source_index: usize, side: &NativeNode| NativeNode { + expr: NativeExpr::Input(BoundInput { + source_index, + output: side.output.clone(), + ordering: SeriesOrdering::Contiguous, + }), + output: side.output.clone(), + }; + let outer = NativeTree::try_new(NativeNode { + expr: NativeExpr::Binary { + left: Box::new(evaluated_leaf(0, left_operand)), + right: Box::new(evaluated_leaf(1, right_operand)), + matching: matching.clone(), + }, + output: tree.root().output.clone(), + }) + .context(DataFusionPlanningSnafu)?; + let root_fields = outer + .root() + .output + .samples() + .ok_or_else(|| DataFusionError::Internal("native tree root has no samples".into())) + .context(DataFusionPlanningSnafu)? + .fields + .iter() + .map(|field| field.name.to_string()) + .collect::>(); + let Some(output_tags) = fused_output_tags(tree.root(), source_tags) else { + return Ok(None); + }; + let mut column_names = std::collections::HashSet::new(); + if !std::iter::once(time_index) + .chain(root_fields.iter().map(String::as_str)) + .chain(output_tags.iter().map(String::as_str)) + .all(|name| column_names.insert(name)) + { + return Ok(None); + } + let output_schema = fused_output_schema(&root_fields, &output_tags, time_index)?; + let node = FusedSeries::try_new( + Arc::from(prom_expr.to_string()), + outer, + FusedSeriesBinding { + grid: Arc::clone(grid), + time_index: time_index.to_string(), + tags: output_tags, + // This node reads two producers rather than a scan, so it binds no metric name: each + // name was dropped inside the producer that read the metric it belonged to. + metric_name: None, + }, + producers, + output_schema, + ) + .context(DataFusionPlanningSnafu)?; + Ok(Some(LogicalPlan::Extension(Extension { + node: Arc::new(node), + }))) +} + /// How the route places a tree on the scan partitions, decided on the tree as it was compiled. /// /// The placement is what an inserted canonical merge means, so it is read off the compiled tree and @@ -1237,15 +1660,17 @@ mod tests { use promql::native::canonicalize::insert_native_merge_inside_current_fused; use promql::native::execute::{NativeExecutionState, NativeExecutor}; use promql::native::plan::{ - NativeExpr, NativeNode, NativeProperties, NativeTree, merges_are_placeable_in, - needs_single_execution, reads_across_series, + CoPartitionedPair, NativeExpr, NativeNode, NativeProperties, NativeTree, + match_is_co_partitioned, merges_are_placeable_in, needs_single_execution, + needs_single_execution_in_co, output_has_metric_name, reads_across_series, }; use session::context::QueryContextBuilder; use super::{ NATIVE_PROMQL_EXTENSION_KEY, NativePlacement, admitted_selector, admitted_single_selector, - collect_selectors, fused_output_tags, hybrid_binary_admitted, independent_scan_pair, - native_promql_requested, scan_time_filter, + collect_selectors, dual_aggregate_match, fused_output_tags, hybrid_binary_admitted, + independent_scan_pair, native_promql_requested, only_source, rebind_to_source, + scan_time_filter, }; /// The raw layout [`compiled_test_tree`] binds every selector to: one float field, no grid. @@ -1257,6 +1682,12 @@ mod tests { } fn compiled_test_tree(query: &str) -> NativeTree { + compiled_test_tree_with_fields(query, &["v0"]) + } + + /// `query`'s tree with every selector bound to a raw schema of `fields`, so a test can say what + /// the input's value fields are named. + fn compiled_test_tree_with_fields(query: &str, fields: &[&str]) -> NativeTree { let statement = promql_parser::parser::EvalStmt { expr: promql_parser::parser::parse(query).unwrap(), start: UNIX_EPOCH, @@ -1264,7 +1695,16 @@ mod tests { interval: Duration::from_secs(5), lookback_delta: Duration::from_secs(5), }; - let schema = raw_test_schema(); + let schema = Arc::new(SeriesSchema { + fields: fields + .iter() + .map(|name| FieldSpec { + name: Arc::from(*name), + }) + .collect::>() + .into(), + eval_grid: None, + }); crate::promql::native_compile::compile_selectors( &statement, &|_| Ok(Arc::clone(&schema)), @@ -1484,9 +1924,200 @@ mod tests { "{query}" ); } - // An aggregate's labels are its groups, which this walk does not derive. + // An aggregate's labels are its group key, which the walk derives from the names the + // grouping keeps: `by(host)` names the one label it keeps out of these sources' tags. let aggregate = compiled_test_tree("sum by (host) (x)"); - assert_eq!(None, fused_output_tags(aggregate.root(), &sources)); + assert_eq!( + Some(vec!["host".to_string()]), + fused_output_tags(aggregate.root(), &sources[..1]) + ); + } + + /// [`fused_output_tags`] names an aggregate's group key, and declines the two groupings a list + /// of label *names* cannot describe. + /// + /// The `by` and `without` answers are the labels the operator re-labels its groups to, read off + /// the input's own tags: a name the input does not carry takes no column, because Prometheus + /// builds a group key out of the labels a series has. The decline is the value-field case: `le` + /// is a field of the input here, and a field varies between the samples of one series, so it is + /// not a label any series carries and the kernels refuse the grouping + /// (`aggregate::Grouping::validate`). The names alone cannot tell that group from one over a + /// label no series carries - the second is executable and keeps nothing - so it declines. + #[test] + fn aggregate_output_tags_are_the_group_key() { + let sources = [vec![ + "host".to_string(), + "instance".to_string(), + "zone".to_string(), + ]]; + for (query, expected) in [ + ("sum by (host) (m1)", vec!["host"]), + ("sum by (zone, host) (m1)", vec!["host", "zone"]), + ("sum by (missing) (m1)", vec![]), + ("sum(m1)", vec![]), + // `without` keeps every label the input carries other than the ones it names. + ("sum without (instance) (m1)", vec!["host", "zone"]), + ("sum without (instance, host) (m1)", vec!["zone"]), + ] { + assert_eq!( + Some(expected.into_iter().map(String::from).collect::>()), + fused_output_tags(compiled_test_tree(query).root(), &sources), + "{query}" + ); + } + // A grouping that names a value field of its input is nothing a column list can be: the + // field varies within one series, so `by(le)` is not a label set. + let bounded = compiled_test_tree_with_fields("sum by (le) (m1)", &["le"]); + assert_eq!(None, fused_output_tags(bounded.root(), &sources)); + // ... while the same grouping over an input whose fields are named otherwise still names + // the label, which is what keeps the guard about the field rather than about the name. + let plain = compiled_test_tree_with_fields("sum by (le) (m1)", &["v0"]); + assert_eq!( + Some(vec!["le".to_string()]), + fused_output_tags(plain.root(), &[vec!["le".to_string()]]) + ); + } + + /// The predicate that decides a dual-aggregate match, on the queries it is written for. + /// + /// Every refusal below is one conjunct of [`dual_aggregate_match`]: the match has to be the + /// default one and one-to-one, each side exactly one `Complete` fold over exactly one source, and + /// the two sources different, and each fold's output name-free because that is what makes the + /// canonical key the routing groups by and the match key one key. + #[test] + fn a_dual_aggregate_match_is_recognised_by_its_shape() { + let two_sources = || vec![vec!["ns".to_string()], vec!["ns".to_string()]]; + let accepted = compiled_test_tree("sum by (ns) (m1) / sum by (ns) (m2)"); + let ((_, left_source), (_, right_source)) = + dual_aggregate_match(accepted.root(), &two_sources()) + .expect("the default one-to-one match of two folds is the shape"); + assert_eq!((0, 1), (left_source, right_source)); + // The same shape under either `without` grouping, and under no grouping at all. + for query in [ + "sum without (instance) (m1) / sum without (instance) (m2)", + "sum(m1) / sum(m2)", + ] { + assert!( + dual_aggregate_match(compiled_test_tree(query).root(), &two_sources()).is_some(), + "{query}" + ); + } + + for (query, reason) in [ + // Both sides keep their metric name, so the canonical key and the match key differ. + ("m1 / m2", "the operands are not folds"), + ( + "sum by (ns) (m1) / on(host) sum by (ns) (m2)", + "the match is not the default one", + ), + ( + "sum by (ns) (m1) / ignoring(zone) sum by (ns) (m2)", + "the match names labels to ignore", + ), + ( + "sum by (ns) (m1) / on(host) group_left sum by (ns) (m2)", + "the match is many-to-one", + ), + ( + "sum by (__name__) (m1) / sum by (__name__) (m2)", + "the folds keep the metric name", + ), + ("sum by (ns) (m1) / m2", "the right operand is not a fold"), + // One side reads two sources, so there is no single producer to give it. + ( + "sum by (ns) (m1 + m2) / sum by (ns) (m3)", + "the left fold reads two sources", + ), + // `v0` is a value field of the input, so its groups cannot be named as columns. + ( + "sum by (v0) (m1) / sum by (v0) (m2)", + "the grouping names a value field", + ), + ] { + assert!( + dual_aggregate_match(compiled_test_tree(query).root(), &two_sources()).is_none(), + "`{query}`: {reason}" + ); + } + } + + /// The two facts the split rests on, on the trees it builds: the folds are name-free, and the + /// match above the two producers is co-partitioned only because they are. + #[test] + fn a_split_match_is_co_partitioned_by_its_producers() { + let tree = compiled_test_tree("sum by (ns) (m1) / sum by (ns) (m2)"); + let ((left, left_source), (right, right_source)) = + dual_aggregate_match(tree.root(), &[vec!["ns".into()], vec!["ns".into()]]) + .expect("the default one-to-one match of two folds is the shape"); + assert_eq!((0, 1), (left_source, right_source)); + // `output_has_metric_name` is the fact the physical layer reads off each producer in turn. + assert_eq!(Some(false), output_has_metric_name(left)); + assert_eq!(Some(false), output_has_metric_name(right)); + // `by(__name__)` is the one grouping that keeps the name, and it is exactly the answer the + // split refuses: `Some(true)` proves the canonical key is not the match key. + let named = compiled_test_tree("sum by (__name__) (m1)"); + assert_eq!(None, output_has_metric_name(named.root())); + + // The producers' trees name child 0, and the match above them reads them as its children 0 + // and 1: the indexes are dense from zero, which is what `collect_source_schemas` requires. + let producer = + NativeTree::try_new(rebind_to_source(left, 0)).expect("the fold alone is legal"); + assert_eq!(Some(0), only_source(producer.root())); + assert_eq!(Some(0), only_source(producer.root())); + + // What the match above the producers needs of its execution, asked with the pair the + // physical layer proves: same outputs on both routings, both producers name-free. + let evaluated_leaf = |source_index: usize, side: &NativeNode| NativeNode { + expr: NativeExpr::Input(promql::native::plan::BoundInput { + source_index, + output: side.output.clone(), + ordering: SeriesOrdering::Contiguous, + }), + output: side.output.clone(), + }; + let NativeExpr::Binary { matching, .. } = &tree.root().expr else { + unreachable!("the shape is a binary operation") + }; + let outer = NativeTree::try_new(NativeNode { + expr: NativeExpr::Binary { + left: Box::new(evaluated_leaf(0, left)), + right: Box::new(evaluated_leaf(1, right)), + matching: matching.clone(), + }, + output: tree.root().output.clone(), + }) + .expect("a match over two evaluated inputs is legal"); + let boundary = vec![source_pieces(), source_pieces()]; + let pair = |name_free| { + vec![CoPartitionedPair { + left: 0, + right: 1, + name_free, + }] + }; + let NativeExpr::Binary { + left: outer_left, + right: outer_right, + matching: outer_matching, + } = &outer.root().expr + else { + unreachable!("the split tree is a binary operation") + }; + assert!( + match_is_co_partitioned(outer_left, outer_right, outer_matching, &pair(true)), + "two name-free producers of the default match are one pair" + ); + assert!( + !needs_single_execution_in_co(outer.root(), &boundary, &pair(true)), + "a co-partitioned match of two name-free producers runs per partition" + ); + assert!( + needs_single_execution_in_co(outer.root(), &boundary, &pair(false)), + "one named producer is enough to make the match one execution" + ); + // And with no boundary facts at all it is one execution, which is why the split has to + // reach the physical layer with the pair rather than decide the placement itself. + assert!(needs_single_execution(outer.root())); } /// What a caller knows about a fused input: this execution holds one scan partition's pieces of @@ -1555,8 +2186,9 @@ mod tests { return "per-partition"; } // A single execution is handed to the fused node like any other tree, so the labels - // that node declares have to be derivable for its root. Nothing has taught the walk - // to name them for a whole-vector root, so a tree rooted at one is declined there. + // that node declares have to be derivable for its root. An aggregate's group key is + // named ([`fused_output_tags`]); a whole-vector root's labels are not, so a tree + // rooted at one is declined there. match fused_output_tags(handed.root(), sources) { Some(_) => "single execution", None => "legacy plan", @@ -1713,13 +2345,17 @@ mod tests { /// aggregate folds a group point by point, and the root is not canonicalized by default. The /// tree is therefore handed over exactly as compiled. /// - /// The route declines it anyway, and for a reason the pass cannot reach: the labels the fused - /// node must declare are derived by [`fused_output_tags`], which names none for an aggregate or - /// a vector root. So even a tree carrying a merge would not be built, which is why no plan the - /// route produces today carries one. + /// What the route then answers splits by root: an aggregate's group key is named by + /// [`fused_output_tags`] and the placement plans it, while a whole-vector root names no labels + /// this walk derives and keeps the existing plan. #[test] - fn a_single_execution_tree_gains_no_merge_and_the_route_declines_it() { - for query in ["topk(1, x)", "sort(x)", "absent(x)", "quantile(0.9, x)"] { + fn a_single_execution_tree_gains_no_merge_and_the_route_answers_it_by_root() { + for (query, answer) in [ + ("topk(1, x)", "legacy plan"), + ("sort(x)", "legacy plan"), + ("absent(x)", "legacy plan"), + ("quantile(0.9, x)", "single execution"), + ] { let compiled = compiled_test_tree(query); assert_eq!( Some(NativePlacement::SingleExecution), @@ -1754,17 +2390,15 @@ mod tests { fused_output_tags(routed.root(), &one_source_tags()), "`{query}`: the pass changed the labels the node declares" ); - // And the route still leaves it to the existing planner, because the labels a root of - // this shape reports are not the ones the fused node can declare. + // The route answers the same thing for the compiled tree and for the one the pass left + // alone, because the placement and the labels are the same questions they were. assert_eq!( - "legacy plan", + answer, route_answer(&compiled, 1, &one_source_tags()), "`{query}`" ); - // The insertion itself changes nothing about the route's answer: the placement and the - // labels are the same questions they were for the compiled tree. assert_eq!( - "legacy plan", + answer, route_answer(&routed, 1, &one_source_tags()), "`{query}`: the insertion changed the route's answer:\n{routed}" ); diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index 35f8db57df0..e66d8ba7e17 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -31,6 +31,7 @@ use common_recordbatch::RecordBatch as GreptimeRecordBatch; use datafusion::arrow::array::{ Array, ArrayRef, Float64Array, Int64Array, StringArray, TimestampMillisecondArray, }; +use datafusion::arrow::buffer::{Buffer, ScalarBuffer}; use datafusion::arrow::datatypes::{Field, Schema as ArrowSchema}; use datafusion::arrow::record_batch::RecordBatch; use datafusion::catalog::{CatalogProvider, MemoryCatalogProvider, MemorySchemaProvider}; @@ -38,15 +39,29 @@ use datafusion::datasource::memory::MemorySourceConfig; use datafusion::datasource::source::DataSourceExec; use datafusion::datasource::{MemTable, provider_as_source}; use datafusion::execution::context::SessionContext; +use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext; use datafusion::logical_expr::{Extension, UserDefinedLogicalNodeCore, col}; +use datafusion::physical_plan::ExecutionPlan; +use datafusion::physical_planner::{DefaultPhysicalPlanner, ExtensionPlanner}; use datatypes::prelude::ConcreteDataType; use datatypes::schema::{ColumnSchema, Schema}; -use datatypes::series::SeriesOrdering; -use promql::extension_plan::{AggregateFinalize, FusedSeries, HistogramFold, RawSeriesSource}; -use promql::native::plan::NativeExpr; +use datatypes::series::frame::{ + FrameContent, FrameLabelMode, pack_raw_series_chunk, raw_series_frame_schema, +}; +use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; +use datatypes::series::samples::{FieldSpec, Samples, SeriesFields, SeriesSchema}; +use datatypes::series::{Label, SeriesLabels, SeriesOrdering}; +use promql::extension_plan::{ + AggregateFinalize, FusedSeries, HistogramFold, PromExtensionPlanner, RawSeriesSource, + SeriesRepartitionExec, +}; +use promql::native::plan::{ + NativeExpr, NativeNode, needs_single_execution, output_has_metric_name, +}; use promql_parser::label::Labels; use promql_parser::parser; use session::context::QueryContext; +use store_api::region_engine::RawLabelSource; use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan}; use table::Table; use table::metadata::{FilterPushDownType, TableInfoBuilder, TableMetaBuilder}; @@ -71,6 +86,15 @@ fn find_instant_manipulate(plan: &LogicalPlan) -> Option<&InstantManipulate> { } fn build_query_engine_state() -> QueryEngineState { + build_query_engine_state_with_parallelism(0) +} + +/// The engine state a test plans and executes with, at a stated parallelism. +/// +/// `parallelism` is the query engine's own option, which only reaches DataFusion's target partition +/// count when it is positive: zero leaves DataFusion's default in place, which is what every test +/// that does not care about partitioning keeps. +fn build_query_engine_state_with_parallelism(parallelism: usize) -> QueryEngineState { QueryEngineState::new( new_memory_catalog_manager().unwrap(), None, @@ -80,7 +104,10 @@ fn build_query_engine_state() -> QueryEngineState { None, false, Plugins::default(), - QueryOptions::default(), + QueryOptions { + parallelism, + ..Default::default() + }, ) } @@ -798,6 +825,15 @@ fn assert_normal_metric_schema(plan: &LogicalPlan) { async fn build_test_table_provider_with_distinct_tags( table_tags: &[(&str, &[&str])], +) -> DfTableSourceProvider { + build_test_table_provider_with_distinct_tags_on(DEFAULT_ENGINE, table_tags).await +} + +/// The same fixture on the engine the test names, so the native route's engine gate is what a test +/// can hold constant. +async fn build_test_table_provider_with_distinct_tags_on( + engine: &str, + table_tags: &[(&str, &[&str])], ) -> DfTableSourceProvider { let catalog_list = MemoryCatalogManager::with_default_setup(); for (table_name, tags) in table_tags { @@ -827,6 +863,7 @@ async fn build_test_table_provider_with_distinct_tags( let table_meta = TableMetaBuilder::empty() .schema(Arc::new(Schema::new(columns))) .primary_key_indices((0..tags.len()).collect()) + .engine(engine.to_string()) .next_column_id(1024) .build() .unwrap(); @@ -858,6 +895,28 @@ async fn build_test_table_provider_with_distinct_tags( ) } +/// Two metrics, `m1` and `m2`, each with the tag `ns` and one `Float64` value field. +/// +/// Both are on the engine the native route accepts, so a pair of selectors over them is offered to +/// it, and `ns` is the tag a split match's two folds group by. +async fn build_dual_metric_provider() -> DfTableSourceProvider { + build_test_table_provider_with_distinct_tags_on( + NATIVE_ENGINE, + &[("m1", &["ns"]), ("m2", &["ns"])], + ) + .await +} + +/// The raw series layout both metrics of [`build_dual_metric_provider`] share: one `Float64` field. +fn dual_metric_schema() -> Arc { + Arc::new(SeriesSchema { + fields: Arc::from([FieldSpec { + name: Arc::from(greptime_value()), + }]), + eval_grid: None, + }) +} + fn contains_histogram_fold(plan: &LogicalPlan) -> bool { matches!(plan, LogicalPlan::Extension(Extension { node }) if node.as_any().is::()) || plan.inputs().into_iter().any(contains_histogram_fold) @@ -1859,6 +1918,247 @@ fn find_fused_series(plan: &LogicalPlan) -> Option<&FusedSeries> { plan.inputs().into_iter().find_map(find_fused_series) } +/// Every [`FusedSeries`] node in `plan`, outermost first. +fn fused_series_nodes(plan: &LogicalPlan) -> Vec<&FusedSeries> { + fn walk<'a>(plan: &'a LogicalPlan, out: &mut Vec<&'a FusedSeries>) { + if let LogicalPlan::Extension(Extension { node }) = plan + && let Some(fused) = node.as_any().downcast_ref::() + { + out.push(fused); + } + for input in plan.inputs() { + walk(input, out); + } + } + + let mut nodes = Vec::new(); + walk(plan, &mut nodes); + nodes +} + +/// The outer node of a split match, and its two producers. +/// +/// The outer node is the only one with two children: each producer folds one metric and reads that +/// metric's scan, and nothing else in the plan has more than one input. +fn split_match(plan: &LogicalPlan) -> (&FusedSeries, [&FusedSeries; 2]) { + let nodes = fused_series_nodes(plan); + let outer = nodes + .iter() + .copied() + .find(|fused| fused.children().len() == 2) + .unwrap_or_else(|| panic!("no node of `{plan:?}` matches two producers")); + let producers = outer + .children() + .iter() + .map(|child| { + let LogicalPlan::Extension(Extension { node }) = child else { + panic!("a producer of `{plan:?}` is not an extension node"); + }; + node.as_any() + .downcast_ref::() + .unwrap_or_else(|| panic!("a child of the match is not a fused node: {child:?}")) + }) + .collect::>(); + (outer, [producers[0], producers[1]]) +} + +/// The raw series schema `fused`'s tree reads: the binding of its one input leaf. +fn tree_input_schema(fused: &FusedSeries) -> Arc { + fn walk(node: &NativeNode) -> Option> { + match &node.expr { + NativeExpr::Input(input) => input.output.samples().cloned(), + NativeExpr::Scalar(_) => None, + NativeExpr::Instant { input, .. } + | NativeExpr::Merge { input } + | NativeExpr::Window { input, .. } + | NativeExpr::Map { input, .. } + | NativeExpr::Timestamp { input } + | NativeExpr::Aggregate { input, .. } + | NativeExpr::Vector { input, .. } => walk(input), + NativeExpr::Binary { left, right, .. } + | NativeExpr::Set { left, right, .. } + | NativeExpr::Info { + base: left, + info: right, + .. + } => walk(left).or_else(|| walk(right)), + } + } + + walk(fused.tree().root()).unwrap_or_else(|| panic!("`{}` reads no input", fused.promql())) +} + +/// A plan producing `batches` as explicit-label raw frames of `schema`, in one partition. +/// +/// This is the child a producer would be given by a region scan. A unit test in this crate has no +/// region to scan, so the frames are packed here; the producer above them, the routing the planner +/// inserts and the node that runs the match are the planner's own. +fn raw_frame_plan(schema: &SeriesSchema, batches: Vec) -> Arc { + let frame = raw_series_frame_schema(schema, FrameLabelMode::Explicit) + .expect("a raw series schema has an explicit-label frame"); + Arc::new(DataSourceExec::new(Arc::new( + MemorySourceConfig::try_new(&[batches], frame, None) + .expect("the frames declare the schema"), + ))) +} + +/// The physical plan the extension planner builds for `outer` over its two producers. +/// +/// The producers are planned here, from raw frames a test packs; everything above them - the +/// [`SeriesRepartitionExec`] pair the planner inserts and the node that runs the match - is reached +/// through the same [`ExtensionPlanner`] entry DataFusion's physical planner calls, so what this +/// returns is what a query plan would hold under each producer's scan. +async fn plan_split_match( + state: &QueryEngineState, + outer: &FusedSeries, + producers: [(&FusedSeries, Vec); 2], +) -> Arc { + let mut physical: Vec> = Vec::with_capacity(2); + for (producer, batches) in producers { + let input = raw_frame_plan(&tree_input_schema(producer), batches); + let planned = producer + .to_execution_plan(vec![( + input, + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + )]) + .expect("a producer plans over the raw frames of its scan"); + physical.push(planned); + } + let session = state.session_state(); + PromExtensionPlanner + .plan_extension( + &DefaultPhysicalPlanner::default(), + outer, + &[], + physical.as_slice(), + &session, + &PhysicalPlanningContext::default(), + ) + .await + .expect("the planner has everything it asks its children for") + .expect("a co-partitioned match of two name-free producers is a shape it plans") +} + +/// Whether `plan`'s output is an evaluated series frame, which is what a `SeriesFrame` producer +/// writes and what the routing above it reads. +fn produces_evaluated_frame(plan: &Arc) -> bool { + datatypes::series::frame::SeriesFrameDeclaration::parse(plan.schema().as_ref()) + .is_ok_and(|declaration| declaration.content() == FrameContent::Evaluated) +} + +/// The grid the dual-metric fixtures are evaluated on: five points, five seconds apart. +const DUAL_GRID_TIMES: [i64; 5] = [0, 5_000, 10_000, 15_000, 20_000]; + +/// The statement these tests plan: the grid above, one second of lookback. +fn dual_grid_stmt(query: &str) -> EvalStmt { + EvalStmt { + expr: parser::parse(query).unwrap(), + start: UNIX_EPOCH, + end: UNIX_EPOCH + .checked_add(Duration::from_millis(20_000)) + .unwrap(), + interval: Duration::from_secs(5), + lookback_delta: Duration::from_secs(1), + } +} + +/// One raw frame batch per `series` entry of `metric`: samples of one value at every grid point. +/// +/// A series is one chunk here, which is the input contract: its labels name it, its last chunk says +/// so, and its timestamps ascend. +fn metric_frames(schema: &SeriesSchema, metric: &str, series: &[(&str, f64)]) -> Vec { + series + .iter() + .map(|(ns, value)| { + let labels = SeriesLabels::try_new( + Some(Arc::from(metric)), + vec![Label { + name: Arc::from("ns"), + value: Arc::from(*ns), + }], + ) + .expect("one label is a label set"); + let chunk = RawSeriesChunk::try_new( + schema, + Buffer::from_slice_ref(ns.as_bytes()), + Some(labels), + RawTimestamps::try_new(ScalarBuffer::from(DUAL_GRID_TIMES.to_vec())) + .expect("the grid ascends"), + SeriesFields::try_from_vec(vec![Samples::from_float(Float64Array::from(vec![ + Some(*value); + DUAL_GRID_TIMES.len() + ]))]) + .expect("one value per grid point"), + true, + ) + .expect("one series' samples are a legal raw chunk"); + let mut batches = pack_raw_series_chunk(schema, FrameLabelMode::Explicit, None, &chunk) + .expect("a chunk of this schema packs into a frame"); + assert_eq!(1, batches.len(), "one small chunk is one frame batch"); + batches.remove(0) + }) + .collect() +} + +/// The rows of a plain-row output: `(grid timestamp, ns, value)`. +fn ns_rows(batches: &[RecordBatch]) -> Vec<(i64, String, f64)> { + let mut rows = batches + .iter() + .flat_map(|batch| { + let times = batch + .column_by_name(greptime_timestamp()) + .expect("the output's time column") + .as_any() + .downcast_ref::() + .expect("millisecond timestamps"); + let ns = batch + .column_by_name("ns") + .expect("the output's tag column") + .as_any() + .downcast_ref::() + .expect("a utf8 tag"); + let values = batch + .column_by_name(greptime_value()) + .expect("the output's value column") + .as_any() + .downcast_ref::() + .expect("a float64 value"); + (0..batch.num_rows()) + .map(|row| { + ( + times.value(row), + ns.value(row).to_string(), + values.value(row), + ) + }) + .collect::>() + }) + .collect::>(); + rows.sort_by(|left, right| (left.0, &left.1).cmp(&(right.0, &right.1))); + rows +} + +/// The statement's plan over two metrics, each tagged `ns` and carrying one value field. +/// +/// The table shape is the one the native route accepts: the millisecond time index `timestamp`, one +/// `Float64` value column, and the tag the match groups by. +async fn build_dual_metric_plan( + state: &QueryEngineState, + query: &str, + native_fused: bool, +) -> LogicalPlan { + PromPlanner::stmt_to_plan_with_annotations( + build_dual_metric_provider().await, + &dual_grid_stmt(query), + state, + None, + native_fused, + ) + .await + .unwrap() +} + /// Timestamp over raw and evaluated vectors both use native execution, with anchors and offsets retained. #[tokio::test] async fn native_fused_timestamp_admits_raw_and_evaluated_vectors() { @@ -3161,25 +3461,18 @@ async fn native_fused_nested_aggregate_keeps_the_outer_names() { ); } -/// A shape the split cannot keep correct keeps the existing plan: a quantile's state is the group's -/// samples, a binary operation whose sibling is data would match one side's series before the merge, -/// a sibling a call computes has no native node at all, and a group by a value field cannot be named -/// by the state rows. A literal scalar sibling is not one of them: the operation is computed per -/// series below the fold, or rebuilt over the merged values above it. +/// A shape the split cannot carry and the route cannot plan as one execution keeps the existing +/// plan: a group by a value field cannot be named by the columns the node declares, and a sibling a +/// call computes has no native node at all. #[tokio::test] async fn native_fused_unsplittable_aggregate_falls_back() { for query in [ - "quantile(0.5, some_metric)", - "sum(quantile(0.5, some_metric))", - // The sibling is data rather than a literal scalar, so the operation would pair each series - // with the aggregate's series before the merge. - "sum(some_metric) / some_metric", // A scalar a call computes is not a literal the split could keep: `scalar(...)` has no // native node, so the statement keeps the existing plan. "sum(some_metric) / scalar(some_metric)", + // The group key names a value field, which is not a label set any series carries - see + // `group_key_tags` - so the node cannot declare the columns it would need. "sum by (field_0) (some_metric)", - "timestamp(sum(some_metric))", - "sum(timestamp(abs(some_metric)))", ] { let native = build_native_fused_plan(query, true).await; let without_flag = build_native_fused_plan(query, false).await; @@ -3193,52 +3486,352 @@ async fn native_fused_unsplittable_aggregate_falls_back() { } } -/// `clamp` is not a function the existing planner has a kernel for, so an aggregate over it fails -/// while the legacy plan is being built - before either route is chosen, and the same way on both. +/// A shape the split cannot carry but the route can plan as one execution now takes the route, +/// because an aggregate's group key is a label set the node can declare. /// -/// The native route only reads the legacy plan's column names, which means it inherits that refusal -/// rather than answering a query the existing path would reject. Both the split template -/// (`clamp(x, 1, 2)`) and the empty range (`clamp(x, 2, 1)`) fail here, so neither is claimed as -/// supported. +/// The split is still refused for each of these - a quantile's state is the group's samples, a +/// binary operation whose sibling is data would match one side's series before the merge, and a +/// wrapper above a fold is not the fold - so the placement that plans them is the single execution +/// `needs_single_execution` names. That is correct for them and not a weaker answer: one execution +/// over every input partition is exactly the `Complete` aggregate's contract. #[tokio::test] -async fn native_fused_clamp_aggregate_keeps_the_existing_error() { +async fn native_fused_unsplittable_aggregate_plans_one_execution() { for query in [ - "sum(clamp(some_metric, 1, 2))", - "sum(clamp(some_metric, 2, 1))", + "quantile(0.5, some_metric)", + "sum(quantile(0.5, some_metric))", + "timestamp(sum(some_metric))", + "sum(timestamp(abs(some_metric)))", ] { - for native_fused in [true, false] { - // Each attempt needs its own provider: planning moves the one it is given. - let table_provider = build_test_table_provider_with_options( - &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], - 1, - 1, - vec![], - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ConcreteDataType::float64_datatype(), - NATIVE_ENGINE, - ) - .await; - let eval_stmt = build_eval_stmt(query); - let error = PromPlanner::stmt_to_plan_with_annotations( - table_provider, - &eval_stmt, - &build_query_engine_state(), - None, - native_fused, - ) - .await - .unwrap_err(); + let native = build_native_fused_plan(query, true).await; + let fused = find_fused_series(&native) + .unwrap_or_else(|| panic!("`{query}` must take the native route: {native:?}")); + assert!( + find_aggregate_finalize(&native).is_none(), + "`{query}`: the split it cannot carry is not built" + ); + assert!( + needs_single_execution(fused.tree().root()), + "`{query}` reads the whole vector, so it is one execution: {native:?}" + ); + assert_ne!( + native.display_indent().to_string(), + build_native_fused_plan(query, false) + .await + .display_indent() + .to_string(), + "`{query}` must not be the existing plan" + ); + } +} - assert!( - matches!( - &error, - crate::promql::error::Error::UnsupportedExpr { name, .. } if name == "clamp" - ), - "`{query}` with the flag {native_fused}: {error}" +/// A fold on each side of a default one-to-one match is planned as three nodes, and the physical +/// plan the planner builds for them is the one the co-partitioned match was written for: two +/// evaluated-frame producers, two routings that split identically, and a match that runs once per +/// output of that routing rather than once over all of it. +/// +/// This is as far end to end as a unit test in this crate reaches. The logical plan is the planner's +/// own, and everything above each producer's scan is the physical layer's own - the node below the +/// routing is built by asking `plan_extension`, which is the entry DataFusion's physical planner +/// calls. What is not covered is the recursion *into* the streams: the two producers' children are +/// the raw frames a region scan would hand over, packed here, because a unit test in this crate has +/// no region to scan. +#[tokio::test] +async fn native_fused_dual_aggregate_match_plans_routed_producers() { + const PARALLELISM: usize = 4; + let state = build_query_engine_state_with_parallelism(PARALLELISM); + let plan = build_dual_metric_plan(&state, "sum by(ns)(m1) / sum by(ns)(m2)", true).await; + + // The logical shape: one node per fold, and the match over them. + let (outer, producers) = split_match(&plan); + assert_eq!( + 3, + fused_series_nodes(&plan).len(), + "the match and its two producers are the whole plan: {plan:?}" + ); + // The match's own tree is a default one-to-one match over two evaluated inputs, indexed by its + // children and not by the statement's selectors. + let NativeExpr::Binary { + left, + right, + matching, + } = &outer.tree().root().expr + else { + panic!("the outer node does not run a match: {plan:?}"); + }; + assert!(matches!( + &matching.labels, + promql::vector_match::MatchingLabels::Ignoring(names) if names.is_empty() + )); + for (operand, expected) in [(left, 0), (right, 1)] { + let NativeExpr::Input(input) = &operand.expr else { + panic!("the match does not read an evaluated input: {plan:?}"); + }; + assert_eq!(expected, input.source_index); + assert!( + input + .output + .samples() + .is_some_and(|schema| schema.eval_grid.is_some()), + "an operand reads values a producer decided, not a scan: {plan:?}" + ); + } + // Each producer folds one metric, and that fold is the node's whole tree. + for producer in producers { + assert!( + matches!(&producer.tree().root().expr, NativeExpr::Aggregate { .. }), + "a producer does more than fold its metric: {plan:?}" + ); + assert_eq!(1, producer.children().len(), "a producer reads one scan"); + } + + // The physical shape: the routing the planner inserts, and the node above it. + let physical = plan_split_match( + &state, + outer, + [ + ( + producers[0], + metric_frames(&tree_input_schema(producers[0]), "m1", &[("a", 1.0)]), + ), + ( + producers[1], + metric_frames(&tree_input_schema(producers[1]), "m2", &[("a", 1.0)]), + ), + ], + ) + .await; + assert_eq!("FusedSeriesExec", physical.name()); + assert_eq!( + PARALLELISM, + physical.properties().partitioning.partition_count(), + "the match runs once per routed output" + ); + let children = physical.children(); + assert_eq!(2, children.len(), "{physical:?}"); + let routings = children + .iter() + .map(|child| { + child + .downcast_ref::() + .unwrap_or_else(|| panic!("the match's children are not routings: {child:?}")) + }) + .collect::>(); + // Equal `outputs()`, read as the declared partition count: two routings are one routing only + // when they split into the same number of outputs, which is the proof the pair rests on. + assert_eq!( + routings[0].properties().partitioning.partition_count(), + routings[1].properties().partitioning.partition_count() + ); + assert_eq!( + PARALLELISM, + routings[0].properties().partitioning.partition_count(), + "the routing splits into the session's target partitions" + ); + for routing in routings { + let producers = routing.children(); + assert_eq!(1, producers.len(), "{routing:?}"); + assert_eq!("FusedSeriesExec", producers[0].name()); + assert!( + produces_evaluated_frame(producers[0]), + "a producer hands over an evaluated frame: {routing:?}" + ); + } +} + +/// The parallelism is not degenerate: `M > 1`, the two groups of the match land in two different +/// non-empty owner partitions, and every value is the one the arithmetic owes. +/// +/// The data is two metrics of four `ns` groups each, so a routing into four outputs has four label +/// sets to place. The reference is the arithmetic itself - `sum by(ns)(m1) / sum by(ns)(m2)` is each +/// group's `m1` value divided by its `m2` value at every grid point - which is what a serial +/// evaluation of the same two folds answers. Reading every output partition at once is the routing's +/// own contract: an unread output parks the input tasks whose chains hash to it, so the partitions +/// are polled concurrently rather than one to completion. +#[tokio::test] +async fn native_fused_dual_aggregate_match_runs_per_owner_partition() { + const PARALLELISM: usize = 4; + let state = build_query_engine_state_with_parallelism(PARALLELISM); + let plan = build_dual_metric_plan(&state, "sum by(ns)(m1) / sum by(ns)(m2)", true).await; + let (outer, producers) = split_match(&plan); + + // One series per group, held at a different level in each metric: the quotient is the group's + // ratio at every grid point. + let left = [("a", 10.0f64), ("b", 2.0), ("c", 6.0), ("d", 8.0)]; + let right = [("a", 2.0f64), ("b", 1.0), ("c", 3.0), ("d", 2.0)]; + let physical = plan_split_match( + &state, + outer, + [ + ( + producers[0], + metric_frames(&tree_input_schema(producers[0]), "m1", &left), + ), + ( + producers[1], + metric_frames(&tree_input_schema(producers[1]), "m2", &right), + ), + ], + ) + .await; + assert_eq!( + PARALLELISM, + physical.properties().partitioning.partition_count() + ); + + // Every output is polled at once, and each one's rows are kept apart so the routing's placement + // can be read off the answer instead of being recomputed here. + let context = state.session_state().task_ctx(); + let streams = + datafusion::physical_plan::execute_stream_partitioned(Arc::clone(&physical), context) + .expect("the match is executable"); + let partitions = futures::future::try_join_all( + streams + .into_iter() + .map(futures_util::TryStreamExt::try_collect::>), + ) + .await + .expect("every output of the routing ends"); + + let mut owner = HashMap::::new(); + let mut non_empty = 0usize; + for (partition, batches) in partitions.iter().enumerate() { + let rows = ns_rows(batches); + if rows.is_empty() { + continue; + } + non_empty += 1; + for (time, ns, value) in rows { + // The ratio each group owes at every grid point. + let expected = left + .iter() + .find(|(group, _)| *group == ns) + .map(|(_, value)| *value) + .expect("the group is one of the data's") + / right + .iter() + .find(|(group, _)| *group == ns) + .map(|(_, value)| *value) + .expect("the group is one of the data's"); + assert_eq!(expected, value, "{ns} at {time} in partition {partition}"); + // A match group is one label set, so every output holding it holds the whole of it. + assert_eq!( + partition, + *owner.entry(ns.clone()).or_insert(partition), + "`{ns}` is answered by more than one owner partition" ); } } + assert!( + non_empty > 1, + "the groups all landed in {non_empty} output(s), so this run proves nothing about the routing" + ); + assert_eq!( + left.len(), + owner.len(), + "every group has an owner: {owner:?}" + ); +} + +/// `m1 / m2` has no folds, so there is nothing to lift: both sides keep their metric name, which is +/// what makes the canonical key the routing groups by differ from the match key. The pair is the +/// per-partition shape the route already planned, one node reading both scans. +#[tokio::test] +async fn native_fused_pair_without_folds_stays_one_node() { + let state = build_query_engine_state_with_parallelism(4); + let plan = build_dual_metric_plan(&state, "m1 / m2", true).await; + let nodes = fused_series_nodes(&plan); + assert_eq!(1, nodes.len(), "{plan:?}"); + let fused = nodes[0]; + assert_eq!(2, fused.children().len(), "{plan:?}"); + // The tree is the match of the two scans themselves: no fold was lifted out of it, so there is + // no producer to route. + let NativeExpr::Binary { left, right, .. } = &fused.tree().root().expr else { + panic!("the pair does not run a match: {plan:?}"); + }; + assert!( + matches!(&left.expr, NativeExpr::Instant { .. }), + "`m1` is not read by a fold: {plan:?}" + ); + assert!( + matches!(&right.expr, NativeExpr::Instant { .. }), + "`m2` is not read by a fold: {plan:?}" + ); + assert!( + output_has_metric_name(left).is_none() && output_has_metric_name(right).is_none(), + "both sides keep their metric name, so one execution is the answer" + ); +} + +/// A match that is not the default one keeps the existing path: its key is the modifiers' and not the +/// canonical key, so the proof a co-partitioned pair gives would be about a key the match does not +/// read. +#[tokio::test] +async fn native_fused_folded_match_with_a_narrower_key_stays_one_node() { + for query in [ + "sum by(ns)(m1) / on(ns) sum by(ns)(m2)", + "sum by(ns)(m1) / ignoring(ns) sum by(ns)(m2)", + "sum by(ns)(m1) / on(ns) group_left sum by(ns)(m2)", + ] { + let state = build_query_engine_state_with_parallelism(4); + let plan = build_dual_metric_plan(&state, query, true).await; + // A two-selector tree that is neither per-series work nor this split has no placement at + // all, so the existing planner answers it: no producer is routed and no match is lifted. + assert!( + fused_series_nodes(&plan).is_empty(), + "`{query}` was split: {plan:?}" + ); + assert_eq!( + plan.display_indent().to_string(), + build_dual_metric_plan(&state, query, false) + .await + .display_indent() + .to_string(), + "`{query}` must keep the existing plan" + ); + } +} + +/// A fold that keeps the metric name cannot be lifted: `by(__name__)` re-labels each group under the +/// name it read, so the canonical key the routing groups by still holds a name the match key drops. +/// +/// `output_has_metric_name` is the fact this rests on, and it answers `Some(true)` - never `None`, +/// which would only say "not proved here" - which is why the split's condition is `Some(false)`. +#[tokio::test] +async fn native_fused_fold_keeping_the_metric_name_stays_one_node() { + let state = build_query_engine_state_with_parallelism(4); + let query = "sum by(__name__)(m1) / sum by(__name__)(m2)"; + let plan = build_dual_metric_plan(&state, query, true).await; + assert!( + fused_series_nodes(&plan).is_empty(), + "the folds were split: {plan:?}" + ); + // The tree the refusal is about, compiled the way the route compiles it. + let compiled = crate::promql::native_compile::compile_selectors( + &dual_grid_stmt(query), + &|_| Ok(Arc::clone(&dual_metric_schema())), + SeriesOrdering::Contiguous, + ) + .expect("the statement compiles") + .tree; + let NativeExpr::Binary { left, right, .. } = &compiled.root().expr else { + panic!("the statement is not a match: {compiled}"); + }; + for operand in [left, right] { + assert_eq!( + None, + output_has_metric_name(operand), + "a fold grouped by `__name__` keeps the name it read: {compiled}" + ); + } + // And the statement keeps the existing plan, which is the answer for a shape the route cannot + // place: two selectors that are not per-series work and not this split. + assert_eq!( + plan.display_indent().to_string(), + build_dual_metric_plan(&state, query, false) + .await + .display_indent() + .to_string() + ); } /// A label rewrite stays on the existing plan, which is the one that projects its new label.