diff --git a/src/promql/src/extension_plan/fused_series.rs b/src/promql/src/extension_plan/fused_series.rs index 92d19703a45..19dda710801 100644 --- a/src/promql/src/extension_plan/fused_series.rs +++ b/src/promql/src/extension_plan/fused_series.rs @@ -87,8 +87,8 @@ use crate::extension_plan::series_gather::{SeriesGather, spawn_partitions}; use crate::grid_series::series_bytes; use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor}; use crate::native::plan::{ - AggregateKind, BoundAggregate, CanonicalOwner, Grouping, NativeExpr, NativeNode, - NativeProperties, NativeTree, NativeType, needs_single_execution_in, reads_across_series, + AggregateKind, BoundAggregate, Grouping, NativeExpr, NativeNode, NativeProperties, NativeTree, + NativeType, merges_are_placeable_in, needs_single_execution_in, reads_across_series, }; use crate::source::materialize_raw_labels; @@ -746,13 +746,14 @@ fn validate_physical_tree(tree: &NativeTree) -> DataFusionResult Vec { // What a fused input proves on its own: the pieces of a metric one scan partition holds. // Nothing here places those pieces by canonical key, so nothing is claimed about ownership - a - // merge over what this boundary describes therefore needs every partition, which is the - // conservative answer this node gives every tree it cannot prove more about. + // merge over what this boundary describes is therefore not placeable in a per-partition + // execution, which is what [`merges_are_placeable_in`] is asked and what a single execution + // provides without needing a proof. inputs .iter() .map(|_| NativeProperties::source_pieces()) @@ -1026,10 +1028,10 @@ impl FusedSeriesExec { /// More than one source is one execution: its operands are matched against each other, so a /// partition-by-partition run would pair each side's series with only its own partition's. A /// single-source tree is asked what it reads ([`needs_single_execution_in`]) with the facts - /// [`input_boundary`] reads off the child: a whole-vector operator is one execution, and a merge - /// is one only when the child does not already hand every piece of a label set over in the - /// partition it names. Otherwise every series is an independent answer and one execution per scan - /// partition is the parallelism that keeps those answers cheap. + /// [`input_boundary`] reads off the child: a whole-vector operator is one execution. A merge is + /// not asked for one - what it needs is its input's, because whether a merge can be placed at + /// all is a question about the execution, not a reason to shrink the execution to one. That + /// question is [`merges_are_placeable_in`], asked by [`Self::reject_unplaceable_merges`] below. fn requires_single_execution( inputs: &[(Arc, RawLabelSource, SeriesOrdering)], tree: &NativeTree, @@ -1037,6 +1039,40 @@ impl FusedSeriesExec { inputs.len() > 1 || needs_single_execution_in(tree.root(), &input_boundary(inputs)) } + /// Refuses a tree whose merges the execution this node is about to run cannot answer. + /// + /// A merge collects every piece of one canonical label set and answers one series of it. An + /// execution that reads every input partition has all of them; one that reads a single partition + /// has them only where the boundary proves the pieces arrive together. Nothing else may make a + /// merge work, and collapsing this node to one execution to serve a tree nobody proved was + /// placeable is exactly that error: it takes the caller's parallelism away instead of declining + /// the shape. The planner declines such a tree before it is built + /// (`PromPlanner::try_plan_native_fused_with_context`), so this only fires for a plan that was + /// built by hand or rebuilt over a different child. + fn reject_unplaceable_merges( + single_execution: bool, + inputs: &[(Arc, RawLabelSource, SeriesOrdering)], + tree: &NativeTree, + ) -> DataFusionResult<()> { + // The one case a per-partition execution is not a part of its input is an input of one + // partition: then the partition it reads *is* every partition, and every piece of every + // label set is in it. That is not a proof the child gave but a fact about the boundary, and + // it is why this asks the boundary facts rather than assuming they prove nothing. + let co_located = single_execution + || inputs + .iter() + .all(|(input, _, _)| input.properties().partitioning.partition_count() <= 1); + if merges_are_placeable_in(tree.root(), &input_boundary(inputs), co_located) { + return Ok(()); + } + Err(DataFusionError::Plan( + "FusedSeries cannot place this tree's canonical merge: the execution reads one input \ + partition and nothing proves the pieces of a canonical label set are co-located, so \ + the merge would present one partition's fragments as a whole series" + .to_string(), + )) + } + #[allow(clippy::too_many_arguments)] fn build( promql: Arc, @@ -1160,8 +1196,11 @@ impl FusedSeriesExec { // One execution over every input partition, rather than one execution per partition: a tree // that reads the whole vector has to see every series at once, more than one source is one // execution because its operands are matched against each other, and otherwise what the child - // proves about the pieces of a label set decides. + // proves about the pieces of a label set decides. A merge is not one of those reasons: what a + // merge needs from an execution is asked below, and an execution that cannot answer it is + // refused rather than shrunk to one. let single_execution = Self::requires_single_execution(&inputs, &tree); + Self::reject_unplaceable_merges(single_execution, &inputs, &tree)?; let properties = Arc::new(PlanProperties::new( EquivalenceProperties::new(output_schema.clone()), Partitioning::UnknownPartitioning(if single_execution { 1 } else { partition_count }), @@ -1277,11 +1316,20 @@ impl ExecutionPlan for FusedSeriesExec { children.len() ))); } - let children = children + let children: Vec<_> = children .into_iter() .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. + Self::reject_unplaceable_merges( + Self::requires_single_execution(&children, &self.tree), + &children, + &self.tree, + )?; // Rebuilt rather than patched: the new child's schema is what the frame is validated // against, so a child that changed shape is refused instead of decoded with a stale layout. Ok(Arc::new(Self::build( diff --git a/src/promql/src/extension_plan/fused_series/tests.rs b/src/promql/src/extension_plan/fused_series/tests.rs index d1edc29ddd6..8b4e375b5c6 100644 --- a/src/promql/src/extension_plan/fused_series/tests.rs +++ b/src/promql/src/extension_plan/fused_series/tests.rs @@ -71,8 +71,10 @@ use datatypes::series::frame::{ raw_series_frame_schema, series_frame_schema, }; use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; -use datatypes::series::samples::{FieldSpec, Samples, Series, SeriesFields, SeriesSchema}; -use datatypes::series::time::{EvalGrid, GridSpan, GridSpec, TimeAxis}; +use datatypes::series::samples::{ + FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema, +}; +use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis}; use datatypes::series::{Label, SeriesLabels, SeriesOrdering}; use futures::{Stream, StreamExt, TryStreamExt}; use store_api::region_engine::RawLabelSource; @@ -85,6 +87,7 @@ use super::{ }; use crate::evaluated::EvaluatedChunk; use crate::extension_plan::aggregate_exchange::state_schema; +use crate::info::InfoSelector; use crate::map_label::LabelRewrite; use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor}; use crate::native::plan::{ @@ -4787,3 +4790,286 @@ async fn two_chains_that_close_on_one_label_set_each_keep_their_frame() { ); } } + +// --------------------------------------------------------------------------- +// The merge placement: what this node will and will not run. +// --------------------------------------------------------------------------- + +/// A canonical merge over an instant selection, laid out as the selection is. +/// +/// The selection reports the samples themselves, so nothing rewrites the label sets between the +/// input and the merge: the merge is the only operator in the tree, which is what makes the +/// placement question below about the boundary alone. +fn merged_selection_tree() -> NativeTree { + let grid = grid(); + let inner = instant_of(0, &grid); + let output = inner.output.clone(); + NativeTree::try_new(NativeNode { + expr: NativeExpr::Merge { + input: Box::new(inner), + }, + output, + }) + .expect("a merge over an evaluated selection is a legal tree") +} + +/// A merge over a child whose boundary proves nothing is not placed in one partition. +/// +/// The scan partitions by storage `read_key` and not by canonical key, so nothing says the pieces of +/// one canonical label set are in one partition: a merge answered per partition would hand one +/// partition's fragments over as a canonical series. The node refuses that shape instead of reading +/// every child partition in a single execution, which is what it used to do - taking the caller's +/// parallelism away to serve a tree nobody proved was placeable. +#[tokio::test] +async fn a_merge_over_an_unknown_partitioning_child_is_not_placed() { + let frames_of_partition = |index: usize| { + vec![frame(&series_chunk( + &format!("web-{index}"), + &series_samples(1.0), + true, + ))] + }; + let partitions = (0..3).map(frames_of_partition).collect::>(); + let error = plan(merged_selection_tree(), memory_exec_partitioned(partitions)) + .expect_err("nothing proves the pieces of a label set are co-located"); + let message = error.to_string(); + assert!( + message.contains("canonical merge") && message.contains("co-located"), + "refused for another reason than the missing co-location proof: {message}" + ); + + // The refusal is about the proof and not about merges: the same tree over an input of one + // partition is built, because that one partition is every partition and it holds every piece. + let exec = plan( + merged_selection_tree(), + memory_exec(frames(&[series_chunk("web-0", &series_samples(1.0), true)])), + ) + .expect("a one-partition input proves the pieces arrive together by being one partition"); + assert_eq!( + 1, + exec.properties().output_partitioning().partition_count(), + "the input's one partition is the node's" + ); +} + +/// A rebuilt node asks the placement question again over the children it was handed. +/// +/// A child that placed the pieces of a label set by canonical key can be swapped for one that does +/// not - a plain multi-partition source, a coalesce, a union - and the merge above it would then +/// collect one partition's fragments. The rebuilt node therefore re-derives the answer from the new +/// children instead of inheriting the one the old children gave. +#[tokio::test] +async fn with_new_children_revalidates_the_merge_placement() { + let single = || memory_exec(frames(&[series_chunk("web-0", &series_samples(1.0), true)])); + let exec = + plan(merged_selection_tree(), single()).expect("a one-partition input places the merge"); + // Rebuilt over the child it already had: the same answer, because the same boundary. + let rebuilt = Arc::clone(&exec) + .replace_children( + vec![single()], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + .expect("one partition still holds every piece"); + assert_eq!( + 1, + rebuilt.properties().output_partitioning().partition_count() + ); + + // The same node over a child of three partitions: the old proof is gone and the node says so. + let partitions = (0..3) + .map(|index| { + vec![frame(&series_chunk( + &format!("web-{index}"), + &series_samples(1.0), + true, + ))] + }) + .collect::>(); + let error = Arc::clone(&exec) + .replace_children( + vec![memory_exec_partitioned(partitions)], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + .expect_err("the rebuilt node cannot inherit the old child's proof"); + let message = error.to_string(); + assert!( + message.contains("canonical merge") && message.contains("co-located"), + "the rebuilt node refused for another reason: {message}" + ); +} + +// --------------------------------------------------------------------------- +// `info`, driven through `NativeExecutor`: what its canonical merge must not change. +// --------------------------------------------------------------------------- + +/// `info(base, {})` over an evaluated base at source 0 and the raw info series at source 1, with the +/// info side selected the way the compiler selects it: reporting each selected sample's own time. +fn info_tree_of(grid: &Arc, lookback_ms: i64, selector: InfoSelector) -> NativeTree { + let base_type = evaluated_of(&raw_schema(), grid); + let base = NativeNode { + expr: NativeExpr::Input(BoundInput { + output: base_type.clone(), + source_index: 0, + ordering: SeriesOrdering::Contiguous, + }), + output: base_type.clone(), + }; + let mut info = instant_of(1, grid); + let NativeExpr::Instant { op, .. } = &mut info.expr else { + unreachable!("`instant_of` builds an instant selection"); + }; + op.value = InstantValue::InfoTimestamp; + op.lookback_ms = lookback_ms; + NativeTree::try_new(NativeNode { + expr: NativeExpr::Info { + base: Box::new(base), + info: Box::new(info), + selector, + }, + output: base_type, + }) + .expect("`info` over a sample-time selection is a legal tree") +} + +/// `metric` as `__name__=up,instance=a,version=v1`, the way the runtime files a series. +fn label_set_of(metric: &SeriesLabels) -> String { + metric + .name() + .into_iter() + .map(|name| format!("__name__={name}")) + .chain( + metric + .tags() + .iter() + .map(|tag| format!("{}={}", tag.name, tag.value)), + ) + .collect::>() + .join(",") +} + +/// One answered series: its label set, and the grid positions it holds with the value at each. +type AnsweredSeries = (String, Vec<(usize, Option)>); + +/// Every series `tree` answers from `pushes`, by label set, as the positions it holds and the values +/// there. The executor is drained the way its consumer drains it: until it settles, then closed. +fn info_answer( + tree: &NativeTree, + base: EvaluatedChunk, + info: Vec, +) -> Vec { + let pool: Arc = Arc::new(UnboundedMemoryPool::default()); + let state = NativeExecutionState::try_new(tree, pool).expect("the tree's state builds"); + let mut execution = NativeExecutor::new(state); + let base_id = execution.state().input_ids(0).next().unwrap(); + let info_id = execution.state().input_ids(1).next().unwrap(); + execution.push_evaluated(base_id, base).unwrap(); + for chunk in info { + execution.push_raw(info_id, chunk).unwrap(); + } + // Pulled the way a consumer pulls it: what has settled first, then the ending stages. + let mut chunks = Vec::new(); + while let Some(chunk) = execution.next_chunk().unwrap() { + chunks.push(chunk); + } + chunks.extend(execution.finish().unwrap()); + + let mut answer: Vec = Vec::new(); + for chunk in chunks { + let values = chunk + .series + .fields + .as_slice() + .first() + .map(|field| { + field + .iter() + .map(|sample| match sample { + SampleRef::Float(value) => Some(value), + _ => None, + }) + .collect::>() + }) + .unwrap_or_default(); + let rows = chunk + .series + .time + .positions() + .map(|(position, row)| (position, values.get(row).copied().flatten())) + .collect::>(); + let labels = label_set_of(&chunk.series.metric); + match answer.iter_mut().find(|(seen, _)| *seen == labels) { + Some((_, held)) => held.extend(rows), + None => answer.push((labels, rows)), + } + } + answer.sort_by(|a, b| a.0.cmp(&b.0)); + answer +} + +/// A base series takes the data labels of the newest info series sharing its identifying labels at +/// each point, which only the sample times its info side reports can decide. +/// +/// `version="v1"` is sampled at 0s and 10s and `version="v2"` at 15s and 30s, read within 15s: the +/// points at 0s and 10s see only `v1`, the point at 20s sees both and keeps the newer `v2`, and the +/// point at 30s sees `v2` alone. A canonical merge over the info side collects those pieces into one +/// series per label set and hands the times on unchanged, so the sample time still decides - which +/// is the runtime contract the merge above `info` must not break. +#[test] +fn an_info_tree_still_answers_the_newer_info_series() { + let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 10_000, 4).unwrap()).unwrap()); + let tree = info_tree_of( + &grid, + 15_000, + InfoSelector { + name_matchers: Vec::new(), + data_labels: Vec::new(), + keep_unmatched: true, + }, + ); + let base = { + let samples = Samples::from_float(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0])); + let range = GridRange::try_new(Arc::clone(&grid), 0, samples.len()).unwrap(); + EvaluatedChunk::try_new( + Series { + metric: metric(&[("instance", "a"), ("job", "j")], Some("up")), + time: TimeAxis::Grid(range), + fields: SeriesFields::try_from_vec(vec![samples]).unwrap(), + }, + true, + ) + .expect("the chunk is addressed on the grid") + }; + let info = [ + ("info-v1", "v1", [0i64, 10_000]), + ("info-v2", "v2", [15_000, 30_000]), + ] + .into_iter() + .map(|(key, version, times)| { + chunk_of( + &raw_schema(), + key, + metric( + &[("instance", "a"), ("job", "j"), ("version", version)], + Some("target_info"), + ), + ×, + vec![vec![Some(1.0), Some(1.0)]], + true, + ) + }) + .collect::>(); + + assert_eq!( + vec![ + ( + "__name__=up,instance=a,job=j,version=v1".to_string(), + vec![(0, Some(1.0)), (1, Some(2.0))] + ), + ( + "__name__=up,instance=a,job=j,version=v2".to_string(), + vec![(2, Some(3.0)), (3, Some(4.0))] + ), + ], + info_answer(&tree, base, info) + ); +} diff --git a/src/promql/src/native/canonicalize.rs b/src/promql/src/native/canonicalize.rs index 9717387ab43..470b3be833c 100644 --- a/src/promql/src/native/canonicalize.rs +++ b/src/promql/src/native/canonicalize.rs @@ -30,6 +30,9 @@ use crate::native::plan::{ CanonicalGrouping, NativeExpr, NativeNode, NativeProperties, NativeTree, NativeType, }; +#[cfg(test)] +pub(crate) mod tests; + /// Rewrites `tree` so that every consumer of a whole canonical series is handed one. /// /// `inputs` holds what the caller knows about the fused inputs the tree was compiled over, indexed diff --git a/src/promql/src/native/canonicalize/tests.rs b/src/promql/src/native/canonicalize/tests.rs new file mode 100644 index 00000000000..5dbe6760a93 --- /dev/null +++ b/src/promql/src/native/canonicalize/tests.rs @@ -0,0 +1,217 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! What the insertion pass has to get right: the tree it produces is one its own validator accepts, +//! and the facts it derives are the ones the nodes below it actually preserve. +//! +//! The trees here are built node by node, over the one-field schemas of the `rate(x[5m])` fixture: +//! a raw scan, the window that folds it onto a grid, and - for `info` - the instant selection that +//! reports each info sample's own time. The compiler lives in the `query` crate, which depends on +//! this one, so a test in this crate cannot call it. + +use std::sync::Arc; + +use datatypes::series::SeriesOrdering; +use datatypes::series::samples::{FieldSpec, SeriesSchema}; +use datatypes::series::time::{EvalGrid, GridSpec}; + +use super::insert_native_merge_inside_current_fused; +use crate::info::InfoSelector; +use crate::native::plan::{ + BoundInput, BoundInstant, BoundWindow, CanonicalGrouping, CanonicalOwner, InstantValue, + NativeExpr, NativeNode, NativeProperties, NativeTree, NativeType, +}; +use crate::range_eval::{RangeFunction, RangeWindow}; + +fn grid(start: i64, step: i64, len: u64) -> Arc { + Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap()) +} + +fn fields(count: usize) -> Arc<[FieldSpec]> { + (0..count) + .map(|index| FieldSpec { + name: format!("v{index}").into(), + }) + .collect() +} + +fn evaluated(schema_fields: Arc<[FieldSpec]>, grid: Arc) -> NativeType { + NativeType::Samples(Arc::new(SeriesSchema { + fields: schema_fields, + eval_grid: Some(grid), + })) +} + +/// A scan of raw samples, the leaf every tree here is built over. +fn raw_input(source_index: usize) -> NativeNode { + let output = NativeType::Samples(Arc::new(SeriesSchema { + fields: fields(1), + eval_grid: None, + })); + NativeNode { + expr: NativeExpr::Input(BoundInput { + output: output.clone(), + source_index, + ordering: SeriesOrdering::KeyThenTime, + }), + output, + } +} + +/// `rate(x[5m])` over `inner`: a window that folds raw samples onto `out` and drops the metric name. +fn window_over(inner: NativeNode, out: Arc) -> NativeNode { + NativeNode { + expr: NativeExpr::Window { + input: Box::new(inner), + op: BoundWindow { + function: RangeFunction::Rate, + window: RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + modifier: None, + }, + input_grid: None, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(fields(1), out), + } +} + +/// An instant selection over `inner` that reports what `value` says it reports, on `out`. +fn selection(inner: NativeNode, out: Arc, value: InstantValue) -> NativeNode { + NativeNode { + expr: NativeExpr::Instant { + input: Box::new(inner), + op: BoundInstant { + lookback_ms: 300_000, + offset_ms: 0, + at_ms: None, + value, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(fields(1), out), + } +} + +/// `info(base, {})`: the base series with the data labels of the info series that share theirs. +fn info_over(base: NativeNode, info: NativeNode) -> NativeNode { + let output = base.output.clone(); + NativeNode { + expr: NativeExpr::Info { + base: Box::new(base), + info: Box::new(info), + selector: InfoSelector { + name_matchers: Vec::new(), + data_labels: Vec::new(), + keep_unmatched: true, + }, + }, + output, + } +} + +/// The node for the info side of [`info_over`]: the instant selection that reports sample times. +fn info_selection(out: &Arc) -> NativeNode { + selection(raw_input(1), Arc::clone(out), InstantValue::InfoTimestamp) +} + +/// A legal `info` tree survives the pass, and the tree the pass produces is the one its validator +/// accepts. +/// +/// This is the contract the pass broke: it wraps every whole-series consumer in a merge, `info`'s +/// info side included, and the validator used to require that side be *directly* an instant +/// selection reporting sample times - so the pass built a tree `NativeTree::try_new` then rejected. +/// The merge only collects the pieces of one label set into one series, so the times it hands on are +/// the times it read, and the check looks through it. +#[test] +fn a_legal_info_tree_survives_canonicalize_and_validation() { + let out = grid(0, 60_000, 4); + let tree = NativeTree::try_new(info_over( + window_over(raw_input(0), Arc::clone(&out)), + info_selection(&out), + )) + .expect("the compiled tree is legal"); + let boundary = [NativeProperties::source_pieces()]; + let passed = insert_native_merge_inside_current_fused(&tree, &boundary) + .expect("the pass keeps the tree legal"); + + // The pass wrapped what it had to; what matters is that the info side still *proves* an instant + // selection reporting sample times, however many merges sit above it. + fn through_merges(node: &NativeNode) -> &NativeNode { + let mut node = node; + while let NativeExpr::Merge { input } = &node.expr { + node = input; + } + node + } + let NativeExpr::Info { info, .. } = &through_merges(passed.root()).expr else { + panic!("the passed tree is not an `info` node below its merges:\n{passed}"); + }; + let NativeExpr::Instant { op, .. } = &through_merges(info).expr else { + panic!("the info side is not an instant selection below its merges:\n{passed}"); + }; + assert_eq!( + InstantValue::InfoTimestamp, + op.value, + "the info side no longer proves the sample times `info` reads:\n{passed}" + ); + + // The pass returns a tree it validated, and the same tree validates again from scratch. + NativeTree::try_new(passed.root().clone()).expect("the passed tree is legal on its own"); + + // The pass is idempotent on its own output: every consumer it wrapped is handed a merge already, + // so a second run finds nothing to add. + let again = insert_native_merge_inside_current_fused(&passed, &boundary) + .expect("the pass accepts its own output"); + assert_eq!( + passed.to_string(), + again.to_string(), + "the pass changed its own output" + ); +} + +/// An instant selection that reports an info series' own time keeps every fact its input had: the +/// runtime files that series under all of its labels, so which series share a label set is +/// unchanged. `timestamp(x)` is the one that does not - it drops the metric name on the way - and +/// the two are asserted together so the distinction cannot be lost. +#[test] +fn info_timestamp_keeps_its_input_facts() { + let out = grid(0, 60_000, 4); + // A boundary that proves something, so a downgrade is visible rather than a coincidence of two + // `Unknown`s. + let boundary = [NativeProperties { + owner: CanonicalOwner::ByCanonicalKey, + grouping: CanonicalGrouping::SourcePiecesOnly, + }]; + let facts = |value| selection(raw_input(0), Arc::clone(&out), value).properties(&boundary); + + assert_eq!( + boundary[0], + facts(InstantValue::InfoTimestamp), + "an info timestamp rewrote the label sets it read" + ); + // The sample itself is answered under the label set it was read from, so it is the same answer. + assert_eq!(boundary[0], facts(InstantValue::Sample)); + assert_eq!( + NativeProperties { + owner: CanonicalOwner::Unknown, + grouping: CanonicalGrouping::SourcePiecesOnly, + }, + facts(InstantValue::Timestamp), + "a timestamp kept facts it rewrote" + ); +} diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 82c959c5def..ccbf4edc178 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -573,21 +573,20 @@ impl NativeNode { // A selection answers one series from one series' rows and keeps the label set it read, // so the whole series stays one stream under that label set. // - // The selection that reports the sample's time instead of its value does not: - // `instant_eval::timestamp_of_selection` rewrites the labels with - // `map::drop_metric_name` before it builds the series, so `a{job="x"}` and `b{job="x"}` - // both arrive as `{job="x"}` and the output identity is not the input's. Nothing the - // input proved about which series share a label set survives that, so the facts are a - // rewrite's. + // The selection that reports the sample's *time* keeps the label set it read only when + // the time it reports is the info series' own (`InfoTimestamp`, which `info` reads): the + // runtime files that under every label of the series. `Timestamp` (`timestamp(x)`) + // drops the metric name before it builds the series, so `a{job="x"}` and `b{job="x"}` + // both arrive as `{job="x"}` and nothing the input proved about which series share a + // label set survives that. NativeExpr::Instant { input, op } => { let input = input.properties(boundary); - // `Sample` answers the label set the selection read. `Timestamp` and - // `InfoTimestamp` both report a time instead of the value and rewrite the labels on - // the way, so the facts are a rewrite's. - if matches!(op.value, InstantValue::Sample) { - input - } else { - input.label_sets_of_its_own() + // `Sample` answers the label set the selection read, and so does `InfoTimestamp`. + // `Timestamp` reports a time instead of the value and rewrites the labels on the + // way, so its facts are a rewrite's. + match op.value { + InstantValue::Sample | InstantValue::InfoTimestamp => input, + InstantValue::Timestamp => input.label_sets_of_its_own(), } } // A window folds a range of one series' samples and hands the answer over as that @@ -746,11 +745,13 @@ pub fn reads_across_series(node: &NativeNode) -> bool { /// `Final` aggregate's own stage is not: its contract is exactly the part it was handed, so only what /// sits below it is followed. /// -/// This form proves nothing about where the sources below the tree sit, so it answers as the -/// conservative reading of [`needs_single_execution_in`]: a merge in the tree counts as needing every -/// partition. The native route's placement (`NativePlacement::of` in `promql::planner`) and the -/// region-side admission ask this and both have no boundary facts at hand; a caller that has them, -/// as the canonical-merge rewrite does, asks [`needs_single_execution_in`]. +/// This form passes an empty boundary, so what it asks of a merge is what +/// [`needs_single_execution_in`] answers for one: the merge's own need, which is its input's. Whether +/// a merge can be placed at all is [`merges_are_placeable_in`]'s question, and it is not this one - +/// it is asked by a caller that knows which execution it is placing the tree in. The native route's +/// placement (`NativePlacement::of` in `promql::planner`) and the region-side admission ask this and +/// both have no boundary facts at hand; a caller that has them, as the canonical-merge rewrite does, +/// asks [`needs_single_execution_in`]. /// /// Everything else recurses into its children. A window (`rate`, `sum_over_time`, ...), a map, an /// instant selection and a timestamp compute one series from one series' rows, and a binary @@ -761,8 +762,7 @@ pub fn reads_across_series(node: &NativeNode) -> bool { /// A binary or set operation that *matches* two vectors is not decided by its sides alone, though. /// It pairs the series of one side with the series of the other that shares the match's label set, /// which is a read across the whole vector on both sides, and with no boundary facts at hand a match -/// has no proof that one execution holds both. So it needs one execution, which is the conservative -/// answer for the same reason a merge gets it here. +/// has no proof that one execution holds both. So it needs one execution. /// /// This is about placement, not admission: it says how many executions the tree needs, not whether /// it may run over part of the metric ([`reads_across_series`] answers that). @@ -776,15 +776,12 @@ pub fn needs_single_execution(node: &NativeNode) -> bool { /// `boundary` is the same slice [`NativeNode::properties`] takes: the facts of the fused inputs the /// tree was compiled over, indexed by `source_index`. /// -/// A `Merge` needs every piece of ONE canonical label set, which is where it differs from -/// [`reads_across_series`]: there a merge answers `true` because it reads series the rest of the -/// metric also holds. One execution already holds every piece when the boundary proves the sources -/// below the merge are co-located ([`pieces_co_located`]). When it does not prove that, the merge -/// does need every partition: a scan partitions by storage `read_key` and not by canonical key, so -/// pieces of one canonical label set sit in different partitions and a merge in each of them would -/// hand what reads it a partial series as a canonical one. Forcing one execution for a merge that -/// does not need it is the other error: it collapses the owner partitions a canonical repartition -/// just created back into one. +/// A `Merge` needs every piece of ONE canonical label set, and one execution is one way of having +/// them - but which way applies is not this predicate's question. A merge's own need is therefore +/// its input's ([`NativeExpr::Merge`] below), and whether the execution this tree is placed in can +/// answer a merge at all is [`merges_are_placeable_in`], asked by the caller that knows the +/// placement: a canonical merge is right in a single execution, and in a per-partition one only +/// where the boundary proves the pieces already arrive together ([`pieces_co_located`]). /// /// A *match* needs something else. A `Binary` over two vectors and a `Set` pair each series of one /// side with the series of the other that shares the label set the modifiers name, and a whole match @@ -840,10 +837,57 @@ pub fn needs_single_execution_in(node: &NativeNode, boundary: &[NativeProperties } NativeExpr::Vector { .. } => true, // A merge needs every piece of one canonical label set, and not every label set in one - // execution: given the pieces it answers one series per label set. It is therefore placed - // per partition exactly when the pieces already arrive together. + // execution: given the pieces it answers one series per label set. One execution provides + // that for any input; a per-partition execution provides it only when the pieces are + // co-located. Which of the two applies is not this predicate's question: it answers what the + // tree needs from an execution, and a merge's own need is its input's. Whether the merge can + // be *placed* here is `merges_are_placeable_in`, asked by the caller that knows the + // placement. + NativeExpr::Merge { input } => needs_single_execution_in(input, boundary), + } +} + +/// Whether every merge in `node` can be answered by an execution placed as `co_located` says. +/// +/// `co_located` is what the caller already decided about the execution this tree will run in: +/// `true` when the execution reads every input partition, so every piece of every label set is +/// present and a merge is always placeable; `false` when it reads one partition, so a merge is +/// placeable only where [`pieces_co_located`] proves the pieces arrive together. +/// +/// This is deliberately not part of [`needs_single_execution_in`]: a merge that cannot be placed +/// is a tree this route does not support here, not a tree that needs one execution. Collapsing the +/// partitions to make it work would take the caller's parallelism away to serve a shape nobody +/// proved was placeable. +pub fn merges_are_placeable_in( + node: &NativeNode, + boundary: &[NativeProperties], + co_located: bool, +) -> bool { + match &node.expr { + NativeExpr::Input(_) | NativeExpr::Scalar(_) => true, + NativeExpr::Instant { input, .. } + | NativeExpr::Window { input, .. } + | NativeExpr::Map { input, .. } + | NativeExpr::Timestamp { input } => merges_are_placeable_in(input, boundary, co_located), + // A merge reads the pieces of one canonical label set and answers one series of it, so it is + // placeable where the execution holds every piece. The recursion does not stop here: a merge + // of a merge has to be placeable at every level, and a label-rewriting node between two of + // them rewrites the identity the inner proof was about, so the inner merge can be the one + // that has no proof left. NativeExpr::Merge { input } => { - needs_single_execution_in(input, boundary) || !pieces_co_located(input, boundary) + (co_located || pieces_co_located(input, boundary)) + && merges_are_placeable_in(input, boundary, co_located) + } + NativeExpr::Info { base, info, .. } => { + merges_are_placeable_in(base, boundary, co_located) + && merges_are_placeable_in(info, boundary, co_located) + } + NativeExpr::Aggregate { input, .. } | NativeExpr::Vector { input, .. } => { + merges_are_placeable_in(input, boundary, co_located) + } + NativeExpr::Binary { left, right, .. } | NativeExpr::Set { left, right, .. } => { + merges_are_placeable_in(left, boundary, co_located) + && merges_are_placeable_in(right, boundary, co_located) } } } @@ -1274,8 +1318,16 @@ impl NativeNode { ))); }; // The kernel reads the info side's values as sample times, which only an instant - // selection that reports them produces. - let NativeExpr::Instant { op, .. } = &info.expr else { + // selection that reports them produces. A canonical merge above that selection only + // collects the pieces of one label set into one series, so it hands the times on + // unchanged and the check looks through it. Nothing else is looked through: an + // evaluated value vector is not a set of sample times, and reading one as times + // would compare a sample's value against another's. + let mut source = info.as_ref(); + while let NativeExpr::Merge { input } = &source.expr { + source = input; + } + let NativeExpr::Instant { op, .. } = &source.expr else { return Err(invalid( "info reads its info series from an instant selection", )); diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index 0d493a2de6b..f91c423b04e 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -21,8 +21,9 @@ use datatypes::series::time::{EvalGrid, GridSpec}; use super::{ AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar, - BoundVectorOp, BoundWindow, Grouping, InstantValue, MapOp, NativeExpr, NativeNode, NativeTree, - NativeType, reads_across_series, + BoundVectorOp, BoundWindow, CanonicalGrouping, CanonicalOwner, Grouping, InstantValue, MapOp, + NativeExpr, NativeNode, NativeProperties, NativeTree, NativeType, merges_are_placeable_in, + needs_single_execution_in, reads_across_series, }; use crate::extension_plan::{FusedSeries, FusedSeriesBinding}; use crate::info::InfoSelector; @@ -1476,3 +1477,211 @@ fn info_reads_the_sample_times_of_one_field() { assert!(error.to_string().contains(expected), "{error}"); } } + +/// What a raw scan proves about the pieces of a label set: nothing. +fn source_pieces() -> NativeProperties { + NativeProperties::source_pieces() +} + +/// What a child that routes its chunks by canonical label set proves: this execution holds every +/// piece of the label sets it names, and no other output holds a fragment of one of them. +fn routed_by_canonical_key() -> NativeProperties { + NativeProperties { + owner: CanonicalOwner::ByCanonicalKey, + grouping: CanonicalGrouping::SourcePiecesOnly, + } +} + +/// A merge over `inner`, laid out as `inner` is: a merge writes no field and no grid of its own. +fn merge_over(inner: NativeNode) -> NativeNode { + let output = inner.output.clone(); + NativeNode { + expr: NativeExpr::Merge { + input: Box::new(inner), + }, + output, + } +} + +/// A `topk` over `inner`, which reads the whole vector at each grid point. +fn topk_over(inner: NativeNode) -> NativeNode { + let output = inner.output.clone(); + NativeNode { + expr: NativeExpr::Vector { + input: Box::new(inner), + op: BoundVectorOp::TopK { + k: 1.0, + top: true, + group: Grouping::By(Arc::new([])), + }, + }, + output, + } +} + +/// A merge inherits what its input needs from an execution and demands nothing of its own. +/// +/// This is what the old answer got wrong: a merge whose pieces no boundary proves co-located used +/// to answer `true`, which the fused node turned into one execution over every input partition. The +/// merge does not need that - given the pieces it answers one series per label set - and what it +/// cannot do in a per-partition execution is a fact about the placement, not a reason to take the +/// caller's parallelism away. The two boundaries below are the two ways a boundary proves nothing: +/// an empty one, where the caller said nothing, and [`source_pieces`], which is a scan's own facts. +#[test] +fn a_merge_inherits_and_never_demands_a_single_execution() { + let merge = merge_over(input_on(grid(0, 60_000, 4))); + for boundary in [Vec::new(), vec![source_pieces()]] { + assert!( + !needs_single_execution_in(&merge, &boundary), + "a merge demanded a single execution of a boundary that proves nothing" + ); + // ... and it is nevertheless not placeable per partition: that is the other answer, and it + // is the one the scan's boundary gives. + assert!( + !merges_are_placeable_in(&merge, &boundary, false), + "a merge over an unproven boundary was placed in a single partition" + ); + } + // One execution reads every input partition, so every piece is present and the merge is + // placeable there whatever the boundary proves. + assert!(merges_are_placeable_in(&merge, &[], true)); + + // What the merge does inherit is its input's need: a `topk` below it still reads the whole + // vector, so the tree needs one execution for the `topk` and not for the merge. + let ranked = merge_over(topk_over(input_on(grid(0, 60_000, 4)))); + assert!( + needs_single_execution_in(&ranked, &[]), + "the `topk` below the merge no longer needs one execution" + ); + assert!(merges_are_placeable_in(&ranked, &[], true)); +} + +/// A merge over a child that routes pieces by canonical key keeps the partitions it was given. +/// +/// The proof arrives in the boundary and not in a single execution: such a child hands every piece +/// of each label set it names to one partition and no other partition a fragment of them, so the +/// merge reads each label set whole inside the partition it runs in. This is the legal parallel path, +/// where the node is neither collapsed to one execution nor refused, and it is why a merge no longer +/// answers the "needs one execution" question with its own placement. +#[test] +fn a_merge_over_a_repartitioning_child_keeps_its_partitions() { + let merge = merge_over(input_on(grid(0, 60_000, 4))); + let boundary = [routed_by_canonical_key()]; + assert!( + !needs_single_execution_in(&merge, &boundary), + "the merge demanded a single execution of a boundary that already proves co-location" + ); + assert!( + merges_are_placeable_in(&merge, &boundary, false), + "the merge was not placeable where the pieces are co-located" + ); + // The proof is about the label sets the child names, so it survives an operator that leaves the + // identity alone and stops at one that does not (the next test). + assert!(merges_are_placeable_in(&merge, &boundary, false)); +} + +/// A proof about the label sets a child names does not survive a rewrite of those label sets. +/// +/// `rate` drops the metric name, so `rate(a)` and `rate(b)` coincide on the labels they have left +/// where `a` and `b` did not: the window invents label sets the boundary's keys do not name, and a +/// merge over what it answers reads the pieces of a label set the proof never covered. The merge is +/// then not placeable per partition - and, again, it is not a reason to run the tree in one +/// execution either: the shape is declined instead. +#[test] +fn a_label_rewrite_under_a_repartition_invalidates_the_merge_proof() { + let boundary = [routed_by_canonical_key()]; + let rewritten = merge_over(window_over(input(), None)); + assert!( + !needs_single_execution_in(&rewritten, &boundary), + "a merge demanded a single execution because its proof was lost" + ); + assert!( + !merges_are_placeable_in(&rewritten, &boundary, false), + "the proof survived a window that drops the metric name" + ); + // A map that drops the name loses it the same way, so losing the proof is not about windows. + let mapped = merge_over(map_over(input_on(grid(0, 60_000, 4)))); + assert!(!merges_are_placeable_in(&mapped, &boundary, false)); + // A merge of a merge is checked at every level, so the recursion does not stop at the outer + // merge: the rewrite takes the proof away and neither level has it. + let nested = merge_over(merge_over(window_over(input(), None))); + assert!(!merges_are_placeable_in(&nested, &boundary, false)); +} + +/// A canonical merge above the instant selection preserves the sample times it was handed, so the +/// check looks through it; an operation that computes values is not looked through, because a +/// sample's value is not a sample's time and reading one as the other would compare values. +/// +/// The merge is what the insertion pass puts over the info side of a legal `info` tree, so a check +/// that did not look through it rejected the tree the pass had just built. +#[test] +fn info_reads_the_sample_times_of_a_merged_selection_and_nothing_else() { + let out = grid(0, 60_000, 4); + let selection = |value: InstantValue| NativeNode { + expr: NativeExpr::Instant { + input: Box::new(input_with_fields(1)), + op: BoundInstant { + lookback_ms: 300_000, + offset_ms: 0, + at_ms: None, + value, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(fields(1), Arc::clone(&out)), + }; + let info_of = |info: NativeNode| NativeNode { + expr: NativeExpr::Info { + base: Box::new(window_fields(input_with_fields(1), Arc::clone(&out), 1)), + info: Box::new(info), + selector: InfoSelector { + name_matchers: Vec::new(), + data_labels: Vec::new(), + keep_unmatched: true, + }, + }, + output: evaluated(fields(1), Arc::clone(&out)), + }; + + // The merged selection reports sample times, and the merge hands them on unchanged. + let merged = merge_over(selection(InstantValue::InfoTimestamp)); + assert!( + info_of(merged.clone()).validate().is_ok(), + "a canonical merge over the info side rejected the tree the pass builds: {}", + info_of(merged).validate().unwrap_err() + ); + // Merges nest, and the check looks through every one of them. + assert!( + info_of(merge_over(merged.clone())).validate().is_ok(), + "a merge of a merge over the info side was not looked through" + ); + + // A merge over values is not a set of sample times, so what the merge wraps is what decides: + // the selection is still read there, but a node that computes values is not an instant + // selection and is refused. + let selected = selection(InstantValue::InfoTimestamp); + let value_source = NativeNode { + expr: NativeExpr::Map { + input: Box::new(selected.clone()), + op: BoundMap { + ops: Arc::new([MapOp::Math(MathOp::Abs)]), + }, + }, + output: selected.output.clone(), + }; + let error = info_of(merge_over(value_source)).validate().unwrap_err(); + assert!( + error.to_string().contains("instant selection"), + "values were read as sample times: {error}" + ); + + // A merge over the samples themselves is refused for the same reason, whether or not it is + // merged: the check unwraps and then requires the sample times. + let error = info_of(merge_over(selection(InstantValue::Sample))) + .validate() + .unwrap_err(); + assert!( + error.to_string().contains("not their values"), + "a selection of samples was read as sample times: {error}" + ); +} diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index c994e527ffd..926be75b76f 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -49,8 +49,8 @@ use datatypes::series::samples::{FieldSpec, SeriesSchema}; use promql::extension_plan::{AggregateFinalize, FusedSeries, FusedSeriesBinding, RawSeriesSource}; use promql::native::canonicalize::insert_native_merge_inside_current_fused; use promql::native::plan::{ - NativeExpr, NativeNode, NativeProperties, NativeTree, needs_single_execution, - reads_across_series, + NativeExpr, NativeNode, NativeProperties, NativeTree, merges_are_placeable_in, + needs_single_execution, reads_across_series, }; use promql::vector_match::{Cardinality, MatchingLabels, SetOp}; use promql_parser::label::Matchers; @@ -597,6 +597,15 @@ impl PromPlanner { ) else { return Ok(None); }; + // What the route knows about each fused input: one scan partition's pieces of the metric, + // read by the pass at the leaf the compiler bound to that source index. It is the whole + // boundary this route has, and it proves nothing about where the pieces of a label set sit. + let boundary = vec![NativeProperties::source_pieces(); children.len()]; + // Whether the execution this placement runs in reads every input partition, which is the + // question a canonical merge turns on. A single execution reads all of them - every piece of + // every label set is in it - and a per-partition one reads one, where the boundary above + // proves no co-location at all. + let co_located = matches!(placement, NativePlacement::SingleExecution); if let NativePlacement::SplitAggregate = placement { // A split inserts nothing. Its prefix is per-partition per-series work and its finalize // already merges the state every partition exports, so a canonical merge would both @@ -637,22 +646,26 @@ impl PromPlanner { ))); } // What a merge may be inserted for is a property of the placement, so this is where the - // pass runs and nowhere else. A single execution reads every input partition at once, so - // the pieces of one label set arrive together and a consumer that needs the whole series - // can be handed a merge. A per-partition execution reads one of them, so the tree is handed - // over exactly as compiled: a merge there could only collect that partition's fragments and - // would present them as a canonical series, which is worse than no merge at all. - // Cross-partition aliasing therefore stays unsolved on a per-partition placement until a - // repartition node makes more placements single-execution. - let tree = if let NativePlacement::SingleExecution = placement { - // What the route knows about each fused input: one scan partition's pieces of the - // metric, read by the pass at the leaf the compiler bound to that source index. - let boundary = vec![NativeProperties::source_pieces(); children.len()]; + // pass runs and nowhere else. A single execution reads every input partition at once, so the + // pieces of one label set arrive together and a consumer that needs the whole series can be + // handed a merge. A per-partition execution reads one of them, so the tree is handed over + // exactly as compiled: a merge there could only collect that partition's fragments and would + // present them as a canonical series. + let tree = if co_located { insert_native_merge_inside_current_fused(&compiled.tree, &boundary) .context(DataFusionPlanningSnafu)? } else { compiled.tree }; + // The tree the route hands over is then checked against the execution that will run it, and + // the decision belongs here rather than to the node's constructor. What must not happen is + // the answer this route used to give: a merge the execution cannot place turned into one + // execution over every input partition, which makes the shape work by taking the caller's + // parallelism away. A tree that carries such a merge is therefore declined, and the existing + // planner answers the query instead. + if !merges_are_placeable_in(tree.root(), &boundary, co_located) { + return Ok(None); + } let root_fields = tree .root() .output @@ -1224,8 +1237,8 @@ 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, needs_single_execution, - reads_across_series, + NativeExpr, NativeNode, NativeProperties, NativeTree, merges_are_placeable_in, + needs_single_execution, reads_across_series, }; use session::context::QueryContextBuilder; @@ -1505,37 +1518,68 @@ mod tests { NativePlacement::of(tree, selectors, &[FieldSpec { name: "v0".into() }], "ts") } + /// The tree [`PromPlanner::try_plan_native_fused_with_context`] hands over for the *compiled* + /// tree `tree`, or `None` when the route declines the shape. + /// + /// This is the planner's own decision, asked in the order the planner asks it: the placement is + /// read off the compiled tree, the pass runs only for the placement whose execution reads every + /// input partition, and what is handed over is then checked against the execution that will run + /// it. A tree carrying a merge that execution cannot place is declined, never handed over and + /// never made to work by collapsing the node to one execution. + fn handed_over(tree: &NativeTree, selectors: usize) -> Option { + let boundary = vec![source_pieces(); selectors]; + let co_located = placement_of(tree, selectors) == Some(NativePlacement::SingleExecution); + let handed = if co_located { + insert_native_merge_inside_current_fused(tree, &boundary) + .expect("the pass keeps the tree legal") + } else { + tree.clone() + }; + merges_are_placeable_in(handed.root(), &boundary, co_located).then_some(handed) + } + /// What the route answers for `tree`, in the order /// [`PromPlanner::try_plan_native_fused_with_context`] applies it: the placement first, then - /// whether the labels the fused node declares can be derived for the tree's root. + /// whether the tree this placement would hand over is placeable in it, then whether the labels + /// the fused node declares can be derivable for that tree's root. /// /// `sources` holds the tags of each selector's scan, which the label walk reads. fn route_answer(tree: &NativeTree, selectors: usize, sources: &[Vec]) -> &'static str { match placement_of(tree, selectors) { - Some(NativePlacement::PerPartition) => "per-partition", Some(NativePlacement::SplitAggregate) => "split aggregate", - // 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. - Some(NativePlacement::SingleExecution) => match fused_output_tags(tree.root(), sources) - { - Some(_) => "single execution", - None => "legacy plan", - }, + Some(placement) => { + let Some(handed) = handed_over(tree, selectors) else { + return "legacy plan"; + }; + if placement != NativePlacement::SingleExecution { + 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. + match fused_output_tags(handed.root(), sources) { + Some(_) => "single execution", + None => "legacy plan", + } + } None => "legacy plan", } } - /// The tree [`PromPlanner::try_plan_native_fused_with_context`] hands to the node it builds: the - /// compiled tree, or - when the placement is a single execution - the one the insertion pass - /// canonicalized. - fn routed_tree(query: &str) -> NativeTree { + /// The tree [`PromPlanner::try_plan_native_fused_with_context`] hands to the node it builds, or + /// `None` when the route declines `query`. + /// + /// A split inserts nothing and is handed its tree as compiled; a single execution is handed the + /// one the insertion pass canonicalized; a per-partition placement is handed the tree as + /// compiled, because a merge there could only collect one partition's fragments. + fn routed_tree(query: &str) -> Option { let selectors = collected_selectors(query).len(); - let tree = compiled_test_tree(query); - if placement_of(&tree, selectors) == Some(NativePlacement::SingleExecution) { - return passed_tree(query, selectors); + let compiled = compiled_test_tree(query); + match placement_of(&compiled, selectors) { + Some(NativePlacement::SplitAggregate) => Some(compiled), + Some(_) => handed_over(&compiled, selectors), + None => None, } - tree } /// The labels a one-selector statement's scan reports, for the label walk. @@ -1569,7 +1613,7 @@ mod tests { "`{query}`" ); // A split inserts nothing, so the finalize is handed the tree as compiled. - let routed = routed_tree(query); + let routed = routed_tree(query).expect("a split is a shape the route plans"); assert_eq!( 0, routed.to_string().matches("Merge").count(), @@ -1603,6 +1647,11 @@ mod tests { /// only collect the fragments of the partition it happens to run on - a partial merge presented /// as a canonical series - so the tree is handed over as compiled and cross-partition aliasing /// stays unsolved until a repartition node exists. + /// + /// What that costs is not the placement: the pass wraps these trees (the second half of each + /// case), and the route refuses to hand a merge over here instead of collapsing the node to one + /// execution to serve it. The tree it does hand over is the compiled one, which carries no merge + /// for this execution to be unable to place. #[test] fn the_insertion_pass_does_not_take_a_per_series_tree_off_the_route() { for query in ["rate(x[5m])", "x", "abs(x)", "x * 2"] { @@ -1618,7 +1667,7 @@ mod tests { "`{query}`" ); // The placement inserts nothing, so what the node is handed is the compiled tree. - let routed = routed_tree(query); + let routed = routed_tree(query).expect("a per-series tree is what the route plans"); assert_eq!( 0, routed.to_string().matches("Merge").count(), @@ -1666,8 +1715,8 @@ mod tests { needs_single_execution(compiled.root()), "`{query}`: the placement and the tree disagree" ); - // The pass runs for this placement, and it is the only one it runs for. - let routed = routed_tree(query); + // The pass runs for this placement, which is the only one that can place its merges. + let routed = routed_tree(query).expect("a single execution places every merge"); assert!( routed.to_string().matches("Merge").count() >= 2, "`{query}`: the single-execution tree gained no merge:\n{routed}" @@ -1677,10 +1726,13 @@ mod tests { routed.to_string(), "`{query}`: the route handed over the tree as compiled" ); - // The insertion leaves the placement and the labels alone. + // The insertion leaves the placement and the labels alone. What still needs one + // execution is the vector operation under the merge's input, and not the merge itself: + // a merge inherits what its input needs and demands nothing of its own, so the + // placement survives an insertion that adds one above it. assert!( needs_single_execution(routed.root()), - "`{query}`: the merge took the single execution away:\n{routed}" + "`{query}`: the insertion took the single execution away:\n{routed}" ); assert_eq!( fused_output_tags(compiled.root(), &one_source_tags()), @@ -1694,6 +1746,8 @@ mod tests { 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", route_answer(&routed, 1, &one_source_tags()), @@ -1822,7 +1876,7 @@ mod tests { placement_of(&compiled, 1), "{compiled}" ); - let inserted = routed_tree(query); + let inserted = routed_tree(query).expect("a single execution places every merge"); assert!( inserted.to_string().matches("Merge").count() > 0, "the single execution did not gain a merge:\n{inserted}" @@ -1900,13 +1954,16 @@ mod tests { "`{query}`: the placement changed\n{compiled}" ); let routed = routed_tree(query); - let merges = routed.to_string().matches("Merge").count(); + let merges = routed + .as_ref() + .map(|routed| routed.to_string().matches("Merge").count()) + .unwrap_or(0); let answer = route_answer(&compiled, selectors, &sources); if placement == NativePlacement::SingleExecution { // The only placement that inserts, and it is not built. assert!( merges > 0, - "`{query}`: a single execution gained no merge:\n{routed}" + "`{query}`: a single execution gained no merge:\n{routed:?}" ); assert_eq!( "legacy plan", answer, @@ -1916,7 +1973,7 @@ mod tests { } else { assert_eq!( 0, merges, - "`{query}`: the {placement:?} placement inserted a merge:\n{routed}" + "`{query}`: the {placement:?} placement inserted a merge:\n{routed:?}" ); assert_ne!( "legacy plan", answer, @@ -1928,7 +1985,8 @@ mod tests { /// The pass's own insertion, kept in view from the planner's side: the window still reads its /// raw input and what the pass adds above it is one merge, but a per-partition placement does not - /// run the pass, so the route hands over the window. + /// run the pass, so the route hands over the window - and refuses the wrapped tree, because that + /// merge has no co-location proof in this execution. /// /// A merge writes no label of its own, so the shape the pass would produce declares the same tags /// the compiled tree declares - which is what lets the walk above stay a function of the tree. @@ -1961,12 +2019,69 @@ mod tests { "`{query}`: the pass changed the labels the node declares" ); // What the route hands over is the window, not the wrapped tree: a per-partition execution - // would present one partition's fragments as a canonical series. + // would present one partition's fragments as a canonical series. The wrapped tree is the + // shape the route declines rather than one it answers. assert_eq!( unpassed.to_string(), - routed_tree(query).to_string(), + routed_tree(query) + .expect("a per-series tree is what the route plans") + .to_string(), "`{query}`: the route handed over a passed tree" ); + assert!( + handed_over(&passed, 1).is_none(), + "`{query}`: the route answered the merge it cannot place" + ); + } + + /// A tree that carries a merge its execution cannot place is declined by the route. + /// + /// The merge's own need is its input's, so nothing in this tree asks for a single execution: the + /// placement stays per-partition, which is the whole point of the change. What the merge does + /// ask for is that the pieces of one canonical label set arrive together, and a per-partition + /// execution has no proof of that. The two answers the route must not give are the ones that + /// used to be given: running the tree anyway presents one partition's fragments as a canonical + /// series, and collapsing the node to one execution makes the shape work by taking the caller's + /// parallelism away. Declining it leaves the existing planner to answer. + #[test] + fn a_per_partition_tree_that_carries_an_unplaceable_merge_is_declined() { + let compiled = compiled_test_tree("rate(x[5m])"); + assert_eq!( + Some(NativePlacement::PerPartition), + placement_of(&compiled, 1), + "{compiled}" + ); + // The shape a filter, a repartition pass or a hand-built plan can hand this route: the same + // tree with a canonical merge over it. + let merged = + NativeTree::try_new(merge_of(compiled.root())).expect("a merge over a window is legal"); + assert!( + !needs_single_execution(merged.root()), + "the merge demanded a single execution of a per-series tree" + ); + assert!( + handed_over(&merged, 1).is_none(), + "the route answered a tree its execution cannot place: {merged}" + ); + assert_eq!( + "legacy plan", + route_answer(&merged, 1, &one_source_tags()), + "the route did not decline the unplaceable merge" + ); + + // The decline is about the merge and not about the tree around it: the compiled tree, which + // carries none, is placed exactly as it was. + assert_eq!( + "per-partition", + route_answer(&compiled, 1, &one_source_tags()) + ); + // A single execution would place the same merge, which is why the answer is a decline and + // not a refusal of the shape altogether: the *same* merge is placeable where the execution + // reads every partition. + assert!( + merges_are_placeable_in(&merge_of(compiled.root()), &[source_pieces()], true), + "a single execution places any merge" + ); } /// A canonical merge collects the pieces one label set arrived in and writes no label of its