From b7ad637f1fbaf85796f95ca260cec1593829fbe2 Mon Sep 17 00:00:00 2001 From: discord9 Date: Fri, 23 Oct 2026 00:01:11 +0800 Subject: [PATCH] feat(promql): run a native tree over one independent scan per selector MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A PromQL vector–vector binary operation now runs on the native fused-series path. Each selector of the statement is bound to its own scan, and the compiled tree reads them as separate inputs: - `compile_selectors` answers one `CompiledInput` per selector — where the executor reads it (`NodePath`), what the selector asked a scan for (`SelectorRequirement`: metric, matchers, offset, `@` anchor, the grid it is evaluated on, and whether it reads an instant or a window, from which `raw_scan_bounds()` derives the raw scan interval), the layout it was bound to and the ordering the scan guarantees. - The planner prepares one `TableScan` per selector from that selector's own context — its metric, its own matchers as row filters, its own fields and tags — then adds the time filter from the requirement the compiler produced for that selector. A window and an instant differ in which edge they start from, and an `@` anchor moves the whole interval, so deriving the interval from the statement's endpoints would scan the wrong range. - `FusedSeries` carries one `FusedSeriesInput` per selector, and `FusedSeriesExec` decodes each child against that input's own schema, materialises its labels, and pushes its chunks at that input's `NodePath`. The tree settles once, when every input has ended. - Vector arithmetic and comparisons compile with `on` / `ignoring`, `group_left` / `group_right` and the `fill`, `fill_left`, `fill_right` values, and `bool` comparisons. Scan parallelism is kept: every input is prepared with `execution.target_partitions` ranges, so one region still scans as several partitions. One input keeps the old behaviour — one tree execution per scan partition — because the series producer keeps a whole series in one partition. Several inputs do **not** run per partition. Two independent scans balance their ranges by row count, so the same series can land in partition 0 of one and partition 1 of the other; matching per partition index would then silently drop that match. Until there is an exchange that pairs the matching series of each input, a node with several inputs runs as **one** execution that reads every partition of every input (`gather_partitions`). It reports `UnknownPartitioning(1)` so nothing downstream assumes the children's layout, and each child is executed when the gathered stream reaches it, so the plan below stays a plan until it is read. The tree evaluation of a multi-input query is therefore serial across scan partitions. The scan itself is not: each partition still builds its range streams concurrently, and a partition's ranges are still read in parallel. - Output columns are classified against the **tree's** root schema, not the first input's: `a=[x,y] + b=[z]` reports `x`, and reading that off the input would accept an output schema naming a field no input produced. - A `__field__` matcher makes the route decline (`Ok(None)` → legacy planner). The raw series scan reports every field it carries, so binding all of them would fold fields the query excluded. Accepting the matcher and ignoring it silently scanned the wrong field set. - The split-logical-series guard now checks **ancestry** rather than walk order: a window is only endangered by a rewriter below it, and `rate(a[5m]) + rate(b[5m])` — two sibling windows — is two subtrees, not an ancestor pair. - `POLL_BUDGET` is charged per child poll, so a node with several inputs cannot multiply the work one poll does by its child count. - The planner and the compiler now agree on which selector is which: `collect_selectors` walks `Binary` operands left-then-right (it did not walk them at all before, so a binary query silently fell back to the legacy planner), and the binding callback checks each requirement against the selector at the same position before accepting it. The walk now also descends unary, aggregate and subquery nodes, which the compiler recurses into. - `EnforceDistRequirementRewriter` stops at a fused node's branch instead of refusing every node with more than one input. Its column requirements are scoped by a level of one child chain, and the only projections it amends sit above the branch; each child here is a region scan, which has none. - `TQL EXPLAIN` and `TQL EXPLAIN VERBOSE` offer their body to the native compiler and wrap the plan it makes, so an explanation shows the plan that query actually runs. `ANALYZE` is left to the existing path. `cargo nextest run -p promql`: 838 passed, 0 skipped. `cargo nextest run -p query`: 981 passed, 2 skipped (one earlier run hit a deferred-grid test that materialises a `usize::MAX`-sized axis; it passes in the suite and on its own). `cargo nextest run -p query --test native_multi_selector`: 10 passed — real compiler → real executor, covering `on`, `ignoring`, `group_left`, `group_right`, fills, comparisons, nested trees, repeated metrics with different windows, per-selector time ranges, and two scans that place the same series in opposite partitions. Standalone `/v1/promql` with `[query] experimental_native_promql = true` and `parallelism = 4`, on a table whose four series sit in three flushed ranges (so one region holds several scan ranges), all nine queries compared against the legacy planner row by row (labels, values, timestamps): | query | native plan | same as legacy | | --- | --- | --- | | `bf{kind="a"} + on(host) bf{kind="b"}` | `Binary + on [host] one-to-one`, 2 scans × 4 partitions | 2 series × 6 points | | `bf{kind="a"} / ignoring(kind) bf{kind="b"}` | `Binary / ignoring [kind] one-to-one`, 2 × 4 | 2 × 6 | | `bf{kind="a"} + on(host) group_left(kind) bf{kind="b"}` | `Binary + on [host] many-to-one [kind]`, 2 × 4 | 2 × 6, labels `{host, kind="b"}` | | `bf{kind="a"} > bool on(host) bf{kind="b"}` | `Binary > bool on [host] one-to-one`, 2 × 4 | 2 × 6 | | `rate(bf{kind="a"}[3s]) + on(host) rate(bf{kind="b"}[3s])` | `Binary + on [host]` over two `Window rate [3000ms]`, 2 × 4 | 2 × 6 | | `bf{host="h1",kind="a"} + on(host) bf{host="h2",kind="b"}` | 2 × 4 | empty in both | | `bf2 + bf2` (two fields) | `Binary + ignoring []`, 2 × 4, `fields=2` | 2 × 6 | | `rate(bf2[3s]) + rate(bf2[3s])` | two windows, 2 × 4, `fields=2` | 2 × 6 | | `bf2{__field__="v1"} + bf2` | no native node — declined for the `__field__` matcher | 2 × 6 | Evidence the native plan ran, from the physical planner's own debug log (an `EXPLAIN` stops at the logical plan; this is the plan the region built): ``` FusedSeriesExec: bf{kind="a"} + on (host) bf{kind="b"} NativeTree root Binary + on [host] one-to-one left Instant lookback 300000ms offset 0 on grid 1700000001000/1000x6 input Input raw samples right Instant lookback 300000ms offset 0 on grid 1700000001000/1000x6 input Input raw samples SeriesScanExec: source=primary_key, fields=1, partitions=4 SeriesScanExec: source=primary_key, fields=1, partitions=4 ``` Both scans keep four partitions, which is the configured `parallelism`: the node's output is one partition, but the scanning is not serialised into one. - An exchange that pairs the matching series of two inputs, which would let a multi-input tree run one execution per partition again. - `info()`'s second input, scalar–vector operations, set operators, subquery execution and the distributed path. Signed-off-by: discord9 --- src/promql/src/extension_plan.rs | 4 +- src/promql/src/extension_plan/fused_series.rs | 775 ++++++++++-------- .../src/extension_plan/fused_series/tests.rs | 326 +++++++- src/promql/src/extension_plan/planner.rs | 107 ++- src/query/src/dist_plan/analyzer.rs | 21 +- src/query/src/dist_plan/commutativity.rs | 95 ++- src/query/src/optimizer/scan_hint.rs | 13 +- src/query/src/promql/planner.rs | 9 + src/query/src/promql/planner/native.rs | 687 ++++++++++------ src/query/src/promql/planner/test.rs | 56 +- 10 files changed, 1399 insertions(+), 694 deletions(-) diff --git a/src/promql/src/extension_plan.rs b/src/promql/src/extension_plan.rs index baf57a275c8..11bcf7fbaeb 100644 --- a/src/promql/src/extension_plan.rs +++ b/src/promql/src/extension_plan.rs @@ -38,7 +38,9 @@ use datafusion::error::{DataFusionError, Result as DataFusionResult}; use datafusion::logical_expr::{Expr, Extension, LogicalPlan}; use datatypes::data_type::DataType as _; pub use empty_metric::{EmptyMetric, EmptyMetricExec, EmptyMetricStream, build_special_time_expr}; -pub use fused_series::{FusedSeries, FusedSeriesBinding, FusedSeriesExec, FusedSeriesStream}; +pub use fused_series::{ + FusedSeries, FusedSeriesBinding, FusedSeriesExec, FusedSeriesInput, FusedSeriesStream, +}; pub use histogram_fold::{ HistogramFold, HistogramFoldExec, HistogramFoldOperation, HistogramFoldStream, }; diff --git a/src/promql/src/extension_plan/fused_series.rs b/src/promql/src/extension_plan/fused_series.rs index d957851902a..21354f67c24 100644 --- a/src/promql/src/extension_plan/fused_series.rs +++ b/src/promql/src/extension_plan/fused_series.rs @@ -113,107 +113,40 @@ const POLL_BUDGET: usize = 64; /// the input — a raw frame carries the labels of each series and its own timestamps. #[derive(Clone, Debug)] pub struct FusedSeriesBinding { - /// The raw series schema the tree's input node was bound to, without an evaluation grid. - pub series_schema: Arc, - /// The statement's grid, which is the grid every evaluated chunk is addressed on. + /// The statement's evaluation grid. pub grid: Arc, - /// The metric name every input series is bound to, when the input reads one named metric. - /// - /// The logical node requires it when [`tags`](Self::tags) declares [`METRIC_NAME`]: a reader of - /// the output has to be able to tell that a range function dropped the name, which needs a name - /// to drop. The physical node takes the names from the frames, which carry each series' own. - pub metric_name: Option>, - /// The output column holding the grid timestamps. - pub time_index: String, - /// The logical tag names the output carries, read from each series' labels. - /// - /// [`METRIC_NAME`] is special: it is resolved to the series' metric name instead of a column, - /// which is how a reader sees that a range function dropped it. - pub tags: Vec, -} - -impl FusedSeriesBinding { - /// Whether `other` binds the same fields under the same names. - fn same_fields(&self, other: &SeriesSchema) -> bool { - self.series_schema.fields.len() == other.fields.len() - && self - .series_schema - .fields - .iter() - .zip(other.fields.iter()) - .all(|(mine, theirs)| mine.name == theirs.name) - } } impl PartialEq for FusedSeriesBinding { fn eq(&self, other: &Self) -> bool { - // The schemas are compared by the field names they declare, and the grids by their spec: - // neither type has structural equality, and neither identity nor allocation is meant here. - self.metric_name == other.metric_name - && self.time_index == other.time_index - && self.tags == other.tags - && self.grid.spec() == other.grid.spec() - && self.same_fields(&other.series_schema) + let a = self.grid.spec(); + let b = other.grid.spec(); + (a.start_ms, a.step_ms, a.len) == (b.start_ms, b.step_ms, b.len) } } - impl Eq for FusedSeriesBinding {} - impl Hash for FusedSeriesBinding { fn hash(&self, state: &mut H) { - self.metric_name.hash(state); - self.time_index.hash(state); - self.tags.hash(state); - let spec = self.grid.spec(); - (spec.start_ms, spec.step_ms, spec.len).hash(state); - for field in self.series_schema.fields.iter() { - field.name.hash(state); - } + let s = self.grid.spec(); + (s.start_ms, s.step_ms, s.len).hash(state); + } +} +impl PartialOrd for FusedSeriesBinding { + fn partial_cmp(&self, other: &Self) -> Option { + let a = self.grid.spec(); + let b = other.grid.spec(); + (a.start_ms, a.step_ms, a.len).partial_cmp(&(b.start_ms, b.step_ms, b.len)) } } -impl PartialOrd for FusedSeriesBinding { - fn partial_cmp(&self, other: &Self) -> Option { - // A total order over the same fields equality reads, so equal bindings compare equal. - match self - .metric_name - .as_deref() - .partial_cmp(&other.metric_name.as_deref()) - { - Some(Ordering::Equal) => {} - ord => return ord, - } - match self.time_index.partial_cmp(&other.time_index) { - Some(Ordering::Equal) => {} - ord => return ord, - } - match self.tags.partial_cmp(&other.tags) { - Some(Ordering::Equal) => {} - ord => return ord, - } - let (mine, theirs) = (self.grid.spec(), other.grid.spec()); - match (mine.start_ms, mine.step_ms, mine.len).partial_cmp(&( - theirs.start_ms, - theirs.step_ms, - theirs.len, - )) { - Some(Ordering::Equal) => {} - ord => return ord, - } - Some( - self.series_schema - .fields - .iter() - .map(|field| field.name.as_ref()) - .cmp( - other - .series_schema - .fields - .iter() - .map(|field| field.name.as_ref()), - ), - ) - } +/// One scan binding corresponding to one native tree input. +#[derive(Clone, Debug)] +pub struct FusedSeriesInput { + pub series_schema: Arc, + pub metric_name: Option>, + pub time_index: String, + pub tags: Vec, + pub input: LogicalPlan, } /// The logical plan of one node that runs a compiled native tree. @@ -230,7 +163,7 @@ pub struct FusedSeries { /// What the tree's input was compiled against. binding: FusedSeriesBinding, /// The plan producing the input series. - input: LogicalPlan, + inputs: Vec, /// The columns this node produces. output_schema: DFSchemaRef, } @@ -246,15 +179,15 @@ impl FusedSeries { promql: Arc, tree: NativeTree, binding: FusedSeriesBinding, - input: LogicalPlan, + inputs: Vec, output_schema: DFSchemaRef, ) -> DataFusionResult { - validate_binding(&tree, &binding)?; + validate_binding(&tree, &binding, &inputs)?; Ok(Self { promql, tree, binding, - input, + inputs, output_schema, }) } @@ -273,6 +206,9 @@ impl FusedSeries { pub fn binding(&self) -> &FusedSeriesBinding { &self.binding } + pub fn fused_inputs(&self) -> &[FusedSeriesInput] { + &self.inputs + } /// The physical node that runs `exec_input` as this node's input. /// @@ -284,20 +220,32 @@ impl FusedSeries { /// classify, so a plan that is built is a plan that runs. pub fn to_execution_plan( &self, - exec_input: Arc, - label_source: RawLabelSource, - ordering: SeriesOrdering, + exec_inputs: Vec<(Arc, RawLabelSource, SeriesOrdering)>, ) -> DataFusionResult> { let output_schema: SchemaRef = self.output_schema.inner().clone(); + let tree_inputs = tree_inputs(&self.tree)?; + let bound = self + .inputs + .iter() + .zip(exec_inputs) + .zip(tree_inputs) + .map(|((input, (exec, source, ordering)), tree_input)| { + ( + exec, + source, + ordering, + tree_input.path, + Arc::clone(&input.series_schema), + ) + }) + .collect(); Ok(Arc::new(FusedSeriesExec::try_new( Arc::clone(&self.promql), - exec_input, - label_source, - ordering, + bound, Arc::new(self.tree.clone()), output_schema, - self.binding.time_index.clone(), - self.binding.tags.clone(), + self.inputs[0].time_index.clone(), + self.inputs[0].tags.clone(), )?)) } } @@ -308,7 +256,7 @@ impl UserDefinedLogicalNodeCore for FusedSeries { } fn inputs(&self) -> Vec<&LogicalPlan> { - vec![&self.input] + self.inputs.iter().map(|input| &input.input).collect() } fn schema(&self) -> &DFSchemaRef { @@ -328,20 +276,29 @@ impl UserDefinedLogicalNodeCore for FusedSeries { fn with_exprs_and_inputs( &self, _exprs: Vec, - mut inputs: Vec, + inputs: Vec, ) -> DataFusionResult { - if inputs.len() != 1 { - return Err(DataFusionError::Internal( - "FusedSeries should have at exact one input".to_string(), - )); + if inputs.len() != self.inputs.len() { + return Err(DataFusionError::Internal(format!( + "FusedSeries expected {} inputs", + self.inputs.len() + ))); } - - let input = inputs.pop().unwrap(); + let inputs = self + .inputs + .iter() + .cloned() + .zip(inputs) + .map(|(mut binding, input)| { + binding.input = input; + binding + }) + .collect(); Ok(Self { promql: Arc::clone(&self.promql), tree: self.tree.clone(), binding: self.binding.clone(), - input, + inputs, output_schema: Arc::clone(&self.output_schema), }) } @@ -356,7 +313,14 @@ impl PartialEq for FusedSeries { self.promql == other.promql && self.tree.to_string() == other.tree.to_string() && self.binding == other.binding - && self.input == other.input + && self.inputs.len() == other.inputs.len() + && self.inputs.iter().zip(&other.inputs).all(|(a, b)| { + a.input == b.input + && a.metric_name == b.metric_name + && a.time_index == b.time_index + && a.tags == b.tags + && same_schema_fields(&a.series_schema, &b.series_schema) + }) && self.output_schema == other.output_schema } } @@ -367,7 +331,12 @@ impl Hash for FusedSeries { fn hash(&self, state: &mut H) { self.promql.hash(state); self.binding.hash(state); - self.input.hash(state); + for input in &self.inputs { + input.input.hash(state); + input.metric_name.hash(state); + input.time_index.hash(state); + input.tags.hash(state); + } self.output_schema.hash(state); } } @@ -378,14 +347,30 @@ impl PartialOrd for FusedSeries { Some(Ordering::Equal) => {} ord => return ord, } - match self.binding.partial_cmp(&other.binding) { + let mine = self.binding.grid.spec(); + let theirs = other.binding.grid.spec(); + match (mine.start_ms, mine.step_ms, mine.len).partial_cmp(&( + theirs.start_ms, + theirs.step_ms, + theirs.len, + )) { Some(Ordering::Equal) => {} ord => return ord, } - match self.input.partial_cmp(&other.input) { + match self.inputs.len().partial_cmp(&other.inputs.len()) { Some(Ordering::Equal) => {} ord => return ord, } + for (mine, theirs) in self.inputs.iter().zip(&other.inputs) { + if mine.input != theirs.input + || mine.metric_name != theirs.metric_name + || mine.time_index != theirs.time_index + || mine.tags != theirs.tags + || !same_schema_fields(&mine.series_schema, &theirs.series_schema) + { + return None; + } + } match self.tree.to_string().partial_cmp(&other.tree.to_string()) { Some(Ordering::Equal) => {} ord => return ord, @@ -404,56 +389,31 @@ impl PartialOrd for FusedSeries { /// can only agree or disagree with it, and the frame this node reads has to be decoded against the /// same schema, so both halves read it here instead of each carrying a copy. struct TreeInput { - /// The position the tree's raw chunks enter at: a position is how the runtime addresses a node, - /// so nothing on the node has to carry an identity that the tree itself does not. path: NodePath, - /// The raw series schema the tree's input node was compiled against. schema: Arc, } -/// Reads what the tree's input node was compiled against, rejecting a tree this node cannot feed. -/// -/// A node feeds one raw input, and its output is addressed on a grid; a tree that does not have -/// that shape is one this layer cannot hand chunks to or read positions from. -fn tree_input(tree: &NativeTree) -> DataFusionResult { - let mut sources = 0; - let mut input_path = None; - let mut schema = None; +fn tree_inputs(tree: &NativeTree) -> DataFusionResult> { + let mut inputs = Vec::new(); metrics::walk(tree.root(), &mut |node, path| { - let NativeExpr::Input(input) = &node.expr else { - return; - }; - sources += 1; - input_path.get_or_insert_with(|| path.clone()); - // Raw, not evaluated: this node feeds the tree from a scan, so a tree whose input was - // compiled against an already-evaluated schema would read the wrong thing. - schema = input - .output - .samples() - .filter(|schema| schema.eval_grid.is_none()) - .map(Arc::clone); + if let NativeExpr::Input(input) = &node.expr + && let Some(schema) = input + .output + .samples() + .filter(|schema| schema.eval_grid.is_none()) + { + inputs.push(TreeInput { + path: path.clone(), + schema: Arc::clone(schema), + }); + } }); - if sources != 1 { - return Err(DataFusionError::Plan(format!( - "FusedSeries runs a tree with {sources} inputs, and it needs exactly one" - ))); - } - let (Some(path), Some(schema)) = (input_path, schema) else { + if inputs.is_empty() { return Err(DataFusionError::Plan( - "FusedSeries runs a tree whose input is not raw series".to_string(), - )); - }; - let evaluated = tree - .root() - .output - .samples() - .is_some_and(|schema| schema.eval_grid.is_some()); - if !evaluated { - return Err(DataFusionError::Plan( - "FusedSeries runs a tree whose output is not evaluated on a grid".to_string(), + "FusedSeries runs a tree with 0 inputs, and it needs at least one".to_string(), )); } - Ok(TreeInput { path, schema }) + Ok(inputs) } /// Refuses a tree whose logical series can be split across the partitions this node runs. @@ -495,14 +455,13 @@ fn reject_a_split_logical_series( if partition_count == 1 { return Ok(()); } - // The walk is outermost first, so it meets nodes in the reverse of the order data flows: a - // consumer met before a rewriter is one that the rewriter feeds. - let mut consumer: Option = None; - let mut rejection: Option<(String, String)> = None; + // Ancestry, not visit order: a window fills only from the nodes below it, so a rewriter is + // dangerous exactly when a window encloses it. Reading the walk's order instead would treat the + // two operands of one binary as each other's ancestor, and `rate(a[5m]) + rate(b[5m])` - two + // sibling windows over disjoint inputs - would be refused for it. + let mut windows: Vec = Vec::new(); + let mut rewriters: Vec = Vec::new(); metrics::walk(tree.root(), &mut |node, path| { - if rejection.is_some() { - return; - } // A node can leave two raw series on one canonical label set. A map always can: it drops // `__name__` and every empty-valued tag. An instant selection preserves its input labels, // rather than dropping them, but can still leave two raw series on one canonical label set: @@ -516,15 +475,30 @@ fn reject_a_split_logical_series( node.expr, NativeExpr::Map { .. } | NativeExpr::Instant { .. } | NativeExpr::Window { .. } ); - if rewrites && let Some(above) = &consumer { - rejection = Some((path.as_str().to_string(), above.clone())); - return; + if rewrites { + rewriters.push(path.as_str().to_string()); } - let consumes = matches!(node.expr, NativeExpr::Window { .. }); - if consumes && consumer.is_none() { - consumer = Some(path.as_str().to_string()); + if matches!(node.expr, NativeExpr::Window { .. }) { + windows.push(path.as_str().to_string()); } }); + // A path is its parent's path plus one `.` segment, so a descendant matches at a segment + // boundary and never inside a longer sibling name. + let below = |path: &str, ancestor: &str| { + path.len() > ancestor.len() + && path.starts_with(ancestor) + && path[ancestor.len()..].starts_with('.') + }; + let mut rejection = None; + for rewriter in &rewriters { + if let Some(window) = windows + .iter() + .find(|window| below(rewriter, window.as_str())) + { + rejection = Some((rewriter.clone(), window.clone())); + break; + } + } let Some((rewriter, above)) = rejection else { return Ok(()); }; @@ -548,31 +522,62 @@ fn reject_a_split_logical_series( /// /// Answers with what the tree's input reads, which is what a caller names when it hands a raw chunk /// over. +fn same_schema_fields(left: &SeriesSchema, right: &SeriesSchema) -> bool { + left.fields.len() == right.fields.len() + && left + .fields + .iter() + .zip(right.fields.iter()) + .all(|(a, b)| a.name == b.name) +} + fn validate_binding( tree: &NativeTree, binding: &FusedSeriesBinding, -) -> DataFusionResult { - if binding.series_schema.eval_grid.is_some() { - return Err(DataFusionError::Plan( - "FusedSeries binds a raw series schema, which cannot have an evaluation grid" - .to_string(), - )); - } - if binding.tags.iter().any(|tag| tag == METRIC_NAME) && binding.metric_name.is_none() { + inputs: &[FusedSeriesInput], +) -> DataFusionResult<()> { + let mut tree_inputs = Vec::new(); + metrics::walk(tree.root(), &mut |node, path| { + if let NativeExpr::Input(input) = &node.expr { + tree_inputs.push(( + path.clone(), + input + .output + .samples() + .filter(|schema| schema.eval_grid.is_none()) + .map(Arc::clone), + )); + } + }); + if tree_inputs.len() != inputs.len() { return Err(DataFusionError::Plan(format!( - "FusedSeries declares a {METRIC_NAME:?} tag column but binds no metric name" + "FusedSeries runs a tree with {} inputs, but {} inputs were bound", + tree_inputs.len(), + inputs.len() ))); } - - // The tree's own input node says which schema it reads, so the binding is checked against the - // tree rather than trusted: a mismatch would evaluate one schema and label the result as - // another. - let input = tree_input(tree)?; - if !binding.same_fields(&input.schema) { - return Err(DataFusionError::Plan( - "FusedSeries binds a raw series schema the tree's input was not compiled against" - .to_string(), - )); + for (index, ((_, schema), declared)) in tree_inputs.iter().zip(inputs).enumerate() { + let Some(schema) = schema else { + return Err(DataFusionError::Plan( + "FusedSeries runs a tree whose input is not raw series".to_string(), + )); + }; + if declared.series_schema.eval_grid.is_some() { + return Err(DataFusionError::Plan( + "FusedSeries binds a raw series schema, which cannot have an evaluation grid" + .to_string(), + )); + } + if !same_schema_fields(schema, &declared.series_schema) { + return Err(DataFusionError::Plan(format!( + "FusedSeries input {index} binds a raw series schema the tree's input was not compiled against" + ))); + } + if declared.tags.iter().any(|tag| tag == METRIC_NAME) && declared.metric_name.is_none() { + return Err(DataFusionError::Plan(format!( + "FusedSeries declares a {METRIC_NAME:?} tag column but binds no metric name" + ))); + } } match tree.root().output.samples() { Some(schema) @@ -581,7 +586,7 @@ fn validate_binding( .as_ref() .is_some_and(|grid| grid.spec() == binding.grid.spec()) => { - Ok(input) + Ok(()) } _ => Err(DataFusionError::Plan( "FusedSeries runs a tree whose output is not evaluated on the statement's grid" @@ -736,21 +741,27 @@ fn classify_output( Ok(classification) } +/// One child of [`FusedSeriesExec`], with everything the node has to know about it. +/// +/// The plan produces the frames, and the other four are what those frames mean: which label source +/// the producer chose, the ordering it declares, the tree input the chunks are queued at, and the +/// layout the frames were encoded against. They travel together because the node checks each of them +/// against the tree before it runs, and a child that lost any one of them could not be checked. +pub type FusedSeriesChild = ( + Arc, + RawLabelSource, + SeriesOrdering, + NodePath, + Arc, +); + /// The physical node that runs a compiled native tree over its input's raw series. pub struct FusedSeriesExec { /// The PromQL text the tree was compiled from, which is what the plan line shows. promql: Arc, /// The tree this node runs, shared by every partition's execution. tree: Arc, - /// The raw series schema the tree's input was compiled against, which every frame is decoded - /// against. - series_schema: Arc, - /// How the input frames name their series: labels encoded in the key, or carried along. - label_source: RawLabelSource, - /// The ordering the input frames guarantee. - ordering: SeriesOrdering, - /// The position of the tree's input node, where every raw chunk a partition reads enters. - input_path: NodePath, + input_bindings: Vec<(Arc, RawLabelSource, SeriesOrdering, NodePath)>, /// Where each output column comes from. classification: Arc<[OutputColumn]>, /// The output column holding the grid timestamps, kept so this node can be rebuilt over a new @@ -758,8 +769,8 @@ pub struct FusedSeriesExec { time_column: String, /// The tag column names, indexed by [`OutputColumn::Tag`]. tags: Arc<[String]>, - /// The plan producing the raw series frames. - input: Arc, + /// The plans producing the raw series frames. + inputs: Vec>, /// The columns this node produces. output_schema: SchemaRef, /// The grid positions every label set in this plan's output already occupies, and what they @@ -784,96 +795,103 @@ impl FusedSeriesExec { /// The parameters stay separate because each is a fact its own caller has: the query, the plan /// below, the frame's label binding and ordering, the tree, and the three things the output /// schema is classified by. A struct over them would be the same list under another name. - #[allow(clippy::too_many_arguments)] pub fn try_new( promql: Arc, - input: Arc, - label_source: RawLabelSource, - ordering: SeriesOrdering, + inputs: Vec, tree: Arc, output_schema: SchemaRef, time_column: String, tags: Vec, ) -> DataFusionResult { - let tree_input = tree_input(&tree)?; - // Building a state is what proves the runtime executes this tree: a node kind it does not - // run yet is refused here, so a plan that is built is a plan that starts. The throwaway - // state is dropped at once, returning its (unbounded) reservations. + let tree_inputs = tree_inputs(&tree)?; + if inputs.len() != tree_inputs.len() { + return Err(DataFusionError::Plan(format!( + "FusedSeriesExec has {} children for {} tree inputs", + inputs.len(), + tree_inputs.len() + ))); + } let _ = NativeExecutionState::try_new( &tree, Arc::new(UnboundedMemoryPool::default()), &ExecutionPlanMetricsSet::new(), 0, )?; - let classification = - classify_output(&output_schema, &tree_input.schema, &tags, &time_column)?; - // Read here rather than below, because whether the split below can happen decides whether - // the tree shape is one this node may run at all. - let input_properties = input.properties(); - let partition_count = input_properties.partitioning.partition_count(); - if partition_count == 0 { - return Err(DataFusionError::Plan( - "FusedSeriesExec input has no partitions".into(), - )); + // The output columns are named by the fields the *tree* reports, so they are classified + // against the tree's own output rather than against whichever scan happens to sit first: + // `a + b` reports the fields of `a`, and reading them off the input would silently accept an + // output schema that names a field no input ever produced. + let root_schema = tree + .root() + .output + .samples() + .ok_or_else(|| { + DataFusionError::Plan( + "FusedSeriesExec runs a tree whose output is not samples".to_string(), + ) + })? + .clone(); + let classification = classify_output(&output_schema, &root_schema, &tags, &time_column)?; + for (index, (input, source, _, path, schema)) in inputs.iter().enumerate() { + if input.properties().partitioning.partition_count() == 0 { + return Err(DataFusionError::Plan(format!( + "FusedSeriesExec input {index} has no partitions" + ))); + } + if path != &tree_inputs[index].path + || !same_schema_fields(schema, &tree_inputs[index].schema) + { + return Err(DataFusionError::Plan(format!( + "FusedSeriesExec child {index} does not match its tree input" + ))); + } + ensure_frame_matches_label_source(input.schema().as_ref(), source)?; + unpack_raw_series( + Box::pin(RecordBatchStreamAdapter::new( + input.schema(), + futures::stream::empty(), + )), + Some(Arc::clone(schema)), + )?; } + // One input runs one tree per partition, because the series producer keeps a whole series + // in one partition: each tree then owns every chunk of every series it reports. Several + // inputs cannot be executed that way without an exchange that pairs the matching series of + // each input, so they are run by one execution that reads every partition of every input + // (see [`Self::execute`]). + let partition_count = if inputs.len() == 1 { + inputs[0].0.properties().partitioning.partition_count() + } else { + 1 + }; reject_a_split_logical_series(&tree, partition_count)?; - // The frame states its own label layout and series ordering; this plan's binding is an - // expectation checked against that declaration, not an input to decoding. - ensure_frame_matches_label_source(input.schema().as_ref(), &label_source)?; - // The frame is checked against what the tree's input reads, so a frame this node cannot - // decode is reported when the plan is built. The shared decoder is the authority on that - // layout, so it is asked rather than copied: handing it an empty stream of this schema makes - // it validate the declared frame with no batch to decode, which is the check - // `unpack_raw_series` makes before its first poll too. - unpack_raw_series( - Box::pin(RecordBatchStreamAdapter::new( - input.schema(), - futures::stream::empty(), - )), - Some(Arc::clone(&tree_input.schema)), - )?; - // One evaluator per input partition, and the input's own partitioning kept as it is. - // - // A window holds the state of the series it is reading and closes it on the chunk carrying - // `is_last`, so it can answer a series only if the whole series arrives in the partition it - // reads. The input guarantees that: a raw series frame is produced by `SeriesScan`, whose - // contract is that the same primary key always reaches the same partition, and the frame - // decoder holds each series' chunks contiguous within that partition. - // - // What is *not* asked of the optimizer is a distribution. A `KeyPartitioned` or - // `HashPartitioned` requirement is classed as a hash requirement, and a hash requirement - // makes a hash exchange necessary whenever the child has more than one partition - even if - // the child already satisfies it, and even when the partition counts match. A hash exchange - // does not preserve order, so it would interleave the chunks of one series and the decoder - // would close a series it has not finished. `UnspecifiedDistribution` leaves the child's - // layout alone, and `benefits_from_input_partitioning` is false so no round-robin is added - // to raise parallelism either. Between them no exchange can appear between the scan and this - // node, and the scan's guarantee arrives intact. - // As many partitions as the input hands over: the node runs one evaluator per partition and - // answers each as it settles. + let first = inputs[0].0.properties(); let properties = Arc::new(PlanProperties::new( EquivalenceProperties::new(output_schema.clone()), Partitioning::UnknownPartitioning(partition_count), - input_properties.emission_type, - input_properties.boundedness, + first.emission_type, + first.boundedness, )); - // Shared by every partition's stream: a label set colliding is a property of the whole - // output vector, not of one partition. Building it needs no pool; the owner's reservation is - // attached in `execute`, which is the first point that has one. - let labels: SharedLabelSets = Arc::new(Mutex::new(LabelSets::default())); + let input_bindings = inputs + .iter() + .map(|(_, source, ordering, path, schema)| { + (Arc::clone(schema), source.clone(), *ordering, path.clone()) + }) + .collect(); + let inputs = inputs + .into_iter() + .map(|(input, _, _, _, _)| input) + .collect(); Ok(Self { promql, tree, - series_schema: tree_input.schema, - label_source, - ordering, - input_path: tree_input.path, + input_bindings, classification: classification.into(), time_column, tags: tags.into(), - input, + inputs, output_schema, - labels, + labels: Arc::new(Mutex::new(LabelSets::default())), metric: ExecutionPlanMetricsSet::new(), properties, }) @@ -908,26 +926,29 @@ impl ExecutionPlan for FusedSeriesExec { &self.properties } - /// Nothing is asked of the input's distribution, and nothing may be inserted above it. + /// Nothing is asked of any input's distribution, and nothing may be inserted above one. /// /// A hash requirement would make a hash exchange necessary as soon as the child has more than /// one partition - even where the child already satisfies the requirement - and a hash exchange /// does not preserve order. The input's own layout is already the one this node needs, because /// the scan it reads from guarantees a series stays in one partition, so the requirement says - /// only that the layout is left alone. + /// only that each layout is left alone. fn input_distribution_requirements(&self) -> InputDistributionRequirements { - InputDistributionRequirements::new(vec![Distribution::UnspecifiedDistribution]) + InputDistributionRequirements::new(vec![ + Distribution::UnspecifiedDistribution; + self.inputs.len() + ]) } /// Splitting the input further would not help: a second partition is a second set of series /// answered by a second tree, which this node already runs, and raising the count is what an /// optimizer does by adding a round-robin exchange that reorders nothing it can rely on. fn benefits_from_input_partitioning(&self) -> Vec { - vec![false] + vec![false; self.inputs.len()] } fn children(&self) -> Vec<&Arc> { - vec![&self.input] + self.inputs.iter().collect() } fn apply_expressions( @@ -942,19 +963,30 @@ impl ExecutionPlan for FusedSeriesExec { self: Arc, children: Vec>, ) -> DataFusionResult> { - let [child] = <[Arc; 1]>::try_from(children).map_err(|children| { - DataFusionError::Plan(format!( - "FusedSeriesExec requires exactly one child, got {}", + if children.len() != self.inputs.len() { + return Err(DataFusionError::Plan(format!( + "FusedSeriesExec requires {} children, got {}", + self.inputs.len(), children.len() - )) - })?; + ))); + } // 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::try_new( Arc::clone(&self.promql), - child, - self.label_source.clone(), - self.ordering, + children + .into_iter() + .zip(&self.input_bindings) + .map(|(input, (schema, source, ordering, path))| { + ( + input, + source.clone(), + *ordering, + path.clone(), + Arc::clone(schema), + ) + }) + .collect(), Arc::clone(&self.tree), self.output_schema.clone(), self.time_column.clone(), @@ -975,27 +1007,41 @@ impl ExecutionPlan for FusedSeriesExec { .lock() .unwrap_or_else(|e| e.into_inner()) .attach(&context.runtime_env().memory_pool); - let input = self.input.execute(partition, Arc::clone(&context))?; - // Batches become raw series chunks through the shared frame decoder, which is the inverse of - // what the producer packed: one chunk per frame row, each series closed exactly once by the - // row carrying `is_last`. - let input = unpack_raw_series(input, Some(Arc::clone(&self.series_schema)))?; - // A source bound in key mode carries its identity encoded and no decoded labels, and a chunk - // handed to the tree has to name the series it holds. - let input = - materialize_raw_labels(input).map_err(|e| DataFusionError::External(Box::new(e)))?; + // One input is executed a partition at a time, because a series never spans two of them. + // Several inputs cannot be: a match pairs series that two scans may have placed in + // different partitions, and there is no exchange above this node that would move them + // together. One execution reads every partition of every input instead, so the tree sees + // every series of every input and matches them where they are. + let mut inputs = Vec::with_capacity(self.inputs.len()); + for (input, (schema, source, _, path)) in self.inputs.iter().zip(&self.input_bindings) { + let stream = if self.inputs.len() == 1 { + input.execute(partition, Arc::clone(&context))? + } else { + gather_partitions(Arc::clone(input), Arc::clone(&context)) + }; + ensure_frame_matches_label_source(input.schema().as_ref(), source)?; + let stream = unpack_raw_series(stream, Some(Arc::clone(schema)))?; + let stream = materialize_raw_labels(stream) + .map_err(|e| DataFusionError::External(Box::new(e)))?; + inputs.push((path.clone(), stream)); + } + // Several inputs are one execution, so it is the first partition of the node; one input is + // one execution per scan partition, and the metrics name it. + let execution_partition = if self.inputs.len() == 1 { partition } else { 0 }; let state = NativeExecutionState::try_new( &self.tree, Arc::clone(&context.runtime_env().memory_pool), &self.metric, - partition, + execution_partition, )?; // What the label sets hold is charged to the reservation attached above, so nothing is // reserved per stream: the entries outlive every stream and are released with the plan. Ok(Box::pin(FusedSeriesStream { - input: Some(input), + inputs: inputs + .into_iter() + .map(|(path, stream)| (path, Some(stream), false)) + .collect(), executor: Some(NativeExecutor::new(state)), - input_path: self.input_path.clone(), classification: Arc::clone(&self.classification), tags: Arc::clone(&self.tags), output_schema: self.output_schema.clone(), @@ -1010,6 +1056,62 @@ impl ExecutionPlan for FusedSeriesExec { } } +/// Every partition of `input`, read one after another, as one stream. +/// +/// The series producer keeps a whole series in one partition, so reading the partitions in order +/// keeps each series contiguous: a series appears in exactly one of them, and its chunks keep the +/// order it was written in. A partition is executed when this stream reaches it rather than up +/// front, so the plan below stays a plan until it is read, and a partition that is never reached +/// costs nothing. +fn gather_partitions( + input: Arc, + context: Arc, +) -> SendableRecordBatchStream { + /// What the gathered stream has read so far: the plan, where it stands, and the partition it is + /// reading now. + struct Gathered { + input: Arc, + context: Arc, + partition: usize, + partitions: usize, + current: Option, + } + let schema = input.schema(); + let partitions = input.properties().partitioning.partition_count(); + assert!( + partitions > 0, + "a partitioned plan has at least one partition" + ); + let state = Gathered { + input, + context, + partition: 0, + partitions, + current: None, + }; + let stream = futures::stream::try_unfold(state, |mut state| async move { + loop { + if state.current.is_none() { + if state.partition >= state.partitions { + return Ok(None); + } + let next = state + .input + .execute(state.partition, Arc::clone(&state.context))?; + state.partition += 1; + state.current = Some(next); + } + let stream = state.current.as_mut().expect("a partition stream is set"); + match futures::StreamExt::next(stream).await { + Some(Ok(batch)) => return Ok(Some((batch, state))), + Some(Err(error)) => return Err(error), + None => state.current = None, + } + } + }); + Box::pin(RecordBatchStreamAdapter::new(schema, stream)) +} + /// Converts one evaluated chunk into one output batch. /// /// The time column is the absolute grid positions the chunk carries, missing samples are nulls and @@ -1359,16 +1461,9 @@ fn colliding_field(stored: &[Vec], runs: &[Vec]) -> Option { /// The batches one execution of [`FusedSeriesExec`] yields. pub struct FusedSeriesStream { - /// The input frames, read as raw series chunks, or `None` once the stream ended in an error. - /// - /// The decoder behind it holds its current batch, the chunks it decoded from it and its own - /// source, so a terminated stream that kept it alive would hold upstream resources until the - /// consumer drops the stream. - input: Option, + inputs: Vec<(NodePath, Option, bool)>, /// The execution of this node's tree, or `None` once it has been closed. executor: Option, - /// The position of the tree's input node, which is where every chunk read enters. - input_path: NodePath, /// Where each output column comes from. classification: Arc<[OutputColumn]>, /// The tag column names, indexed by `OutputColumn::Tag`. @@ -1386,16 +1481,13 @@ pub struct FusedSeriesStream { } impl FusedSeriesStream { - /// Hands one raw chunk over and queues what it settled. - fn push(&mut self, chunk: RawSeriesChunk) -> DataFusionResult<()> { - let Some(executor) = self.executor.as_mut() else { - return Err(DataFusionError::Execution( - "FusedSeriesExec stream pushed a chunk after its execution closed".to_string(), - )); - }; - // The chunk enters at the tree's input node by position: a position is how the runtime - // addresses a node, and a tree that gains a second input names them the same way. - executor.push_raw_at(&self.input_path, chunk)?; + fn push_at(&mut self, path: &NodePath, chunk: RawSeriesChunk) -> DataFusionResult<()> { + let executor = self.executor.as_mut().ok_or_else(|| { + DataFusionError::Execution( + "FusedSeriesExec stream pushed a chunk after its execution closed".into(), + ) + })?; + executor.push_raw_at(path, chunk)?; let mut settled = Vec::new(); while let Some(chunk) = executor.next_chunk()? { settled.push(chunk); @@ -1446,7 +1538,7 @@ impl FusedSeriesStream { fn fail(&mut self) { self.done = true; self.executor = None; - self.input = None; + self.inputs.clear(); // The label-set map and its charge are the plan's, so a stream stopping early gives back // nothing: the entries another partition is still checking against have to stay charged, and // are released when the plan itself is dropped. @@ -1491,18 +1583,18 @@ impl Stream for FusedSeriesStream { let this = &mut *self; // A batch that is already settled is handed over before anything is read, so a bounded // poll never delays one that is ready behind more input. - for _ in 0..POLL_BUDGET { + let mut budget = POLL_BUDGET; + loop { if let Some(batch) = this.ready.pop_front() { return Poll::Ready(Some(Ok(batch))); } + if budget == 0 { + break; + } if this.done { return Poll::Ready(None); } - // An error is the only thing that clears the input, and it ends the stream with it. - let Some(input) = this.input.as_mut() else { - // The input ended, so what the tree answers now comes from what it held. One chunk - // per iteration keeps it a stream, and `None` is both "nothing more" and the point - // where the execution releases its reservations. + if this.inputs.is_empty() { match this.pull_one() { Ok(Some(chunk)) => { if let Err(error) = this.convert(vec![chunk]) { @@ -1520,31 +1612,50 @@ impl Stream for FusedSeriesStream { } } continue; - }; - let polled = input.as_mut().poll_next(cx); - match polled { - Poll::Pending => return Poll::Pending, - Poll::Ready(None) => { - // The input ended, so every series it opened has to be closed. The tree settles - // what it was holding, and the answers are pulled below in this same poll - // rather than collected first. - this.input = None; - if let Err(error) = this.close_input() { + } + let mut all_pending = true; + for index in 0..this.inputs.len() { + if this.inputs[index].2 || budget == 0 { + continue; + } + // Each child poll is what the budget bounds, so a node with several inputs cannot + // multiply the work one poll does by the number of children it happens to have. + budget -= 1; + let polled = this.inputs[index] + .1 + .as_mut() + .expect("live input exists") + .as_mut() + .poll_next(cx); + match polled { + Poll::Pending => {} + Poll::Ready(None) => { + all_pending = false; + this.inputs[index].1 = None; + this.inputs[index].2 = true; + } + Poll::Ready(Some(Err(error))) => { this.fail(); - return Poll::Ready(Some(Err(error))); + return Poll::Ready(Some(Err(DataFusionError::External(Box::new(error))))); + } + Poll::Ready(Some(Ok(chunk))) => { + all_pending = false; + let path = this.inputs[index].0.clone(); + if let Err(error) = this.push_at(&path, chunk) { + this.fail(); + return Poll::Ready(Some(Err(error))); + } } } - Poll::Ready(Some(Err(error))) => { - // An input error stops the execution: a stopped evaluator must not be reused. + } + if this.inputs.iter().all(|input| input.2) { + if let Err(error) = this.close_input() { this.fail(); - return Poll::Ready(Some(Err(DataFusionError::External(Box::new(error))))); - } - Poll::Ready(Some(Ok(chunk))) => { - if let Err(error) = this.push(chunk) { - this.fail(); - return Poll::Ready(Some(Err(error))); - } + return Poll::Ready(Some(Err(error))); } + this.inputs.clear(); + } else if all_pending { + return Poll::Pending; } } // The budget ran out on input that settled nothing. Everything read so far is kept, so the diff --git a/src/promql/src/extension_plan/fused_series/tests.rs b/src/promql/src/extension_plan/fused_series/tests.rs index 017f4ef6628..7ea2b2dec41 100644 --- a/src/promql/src/extension_plan/fused_series/tests.rs +++ b/src/promql/src/extension_plan/fused_series/tests.rs @@ -69,17 +69,19 @@ use futures::{Stream, StreamExt, TryStreamExt}; use store_api::region_engine::RawLabelSource; use super::{ - FusedSeries, FusedSeriesBinding, LabelSets, OutputColumn, POLL_BUDGET, label_set, - occupied_runs, series_to_record_batch, + FusedSeries, FusedSeriesBinding, FusedSeriesExec, FusedSeriesInput, LabelSets, OutputColumn, + POLL_BUDGET, label_set, occupied_runs, series_to_record_batch, }; use crate::evaluated::EvaluatedChunk; use crate::native::execute::{NativeExecutionState, NativeExecutor}; +use crate::native::metrics::NodePath; use crate::native::plan::{ AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, NativeType, }; use crate::native::runs::absorb_rebuilds; use crate::range_eval::{RangeFunction, RangeWindow}; +use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels}; /// The query every tree here is compiled from. const PROMQL: &str = "rate(x[5m])"; @@ -181,6 +183,70 @@ fn rate_tree() -> NativeTree { rate_tree_of(raw_schema()) } +fn binary_tree(left_schema: Arc, right_schema: Arc) -> NativeTree { + let grid = grid(); + let left_eval = Arc::new(SeriesSchema { + fields: left_schema.fields.clone(), + eval_grid: Some(Arc::clone(&grid)), + }); + let right_eval = Arc::new(SeriesSchema { + fields: right_schema.fields.clone(), + eval_grid: Some(Arc::clone(&grid)), + }); + let output = crate::vector_match::binary_output_schema(&left_eval, &right_eval).unwrap(); + let raw_left = Arc::clone(&left_schema); + let raw_right = Arc::clone(&right_schema); + let left = NativeNode { + expr: NativeExpr::Instant { + input: Box::new(NativeNode { + expr: NativeExpr::Input(BoundInput { + output: NativeType::Samples(Arc::clone(&raw_left)), + ordering: SeriesOrdering::KeyThenTime, + }), + output: NativeType::Samples(raw_left), + }), + op: BoundInstant { + lookback_ms: 0, + offset_ms: 0, + output_grid: Arc::clone(&grid), + }, + }, + output: NativeType::Samples(left_eval), + }; + let right = NativeNode { + expr: NativeExpr::Instant { + input: Box::new(NativeNode { + expr: NativeExpr::Input(BoundInput { + output: NativeType::Samples(Arc::clone(&raw_right)), + ordering: SeriesOrdering::KeyThenTime, + }), + output: NativeType::Samples(raw_right), + }), + op: BoundInstant { + lookback_ms: 0, + offset_ms: 0, + output_grid: Arc::clone(&grid), + }, + }, + output: NativeType::Samples(right_eval), + }; + NativeTree::try_new(NativeNode { + expr: NativeExpr::Binary { + left: Box::new(left), + right: Box::new(right), + matching: BinaryMatching { + op: BinaryOp::Add, + return_bool: false, + labels: MatchingLabels::On(vec![Arc::from(HOST)]), + cardinality: Cardinality::OneToOne, + fill: FillValues::default(), + }, + }, + output: NativeType::Samples(output), + }) + .unwrap() +} + /// An instant selection feeding a range window. fn instant_window_tree() -> NativeTree { let instant = instant_tree().root().clone(); @@ -359,23 +425,41 @@ fn instant_tree() -> NativeTree { /// What the tree's input was compiled against, for the input schema and output tags given. fn binding_of( tree: &NativeTree, - series_schema: Arc, - tags: Vec, + _series_schema: Arc, + _tags: Vec, ) -> FusedSeriesBinding { FusedSeriesBinding { - series_schema, grid: tree .root() .output .samples() - .expect("this tree produces samples") + .unwrap() .eval_grid .clone() - .expect("this tree's output is evaluated on a grid"), + .unwrap(), + } +} +fn one_input(tree: &NativeTree, plan: LogicalPlan) -> Vec { + one_input_tags(tree, plan, vec![HOST.to_string(), NAME.to_string()]) +} +fn one_input_tags( + tree: &NativeTree, + plan: LogicalPlan, + tags: Vec, +) -> Vec { + let mut found = Vec::new(); + crate::native::metrics::walk(tree.root(), &mut |node, _| { + if let NativeExpr::Input(input) = &node.expr { + found.push(Arc::clone(input.output.samples().unwrap())); + } + }); + vec![FusedSeriesInput { + series_schema: found.remove(0), metric_name: Some(Arc::from(METRIC)), time_index: TIME.to_string(), tags, - } + input: plan, + }] } /// What the tree's input was compiled against, read off the tree itself. @@ -626,9 +710,9 @@ fn fused(tree: NativeTree) -> FusedSeries { let binding = binding(&tree); FusedSeries::try_new( Arc::from(PROMQL), - tree, + tree.clone(), binding, - input_plan(frame_schema()), + one_input(&tree, input_plan(frame_schema())), output_schema().to_dfschema_ref().unwrap(), ) .expect("the binding matches the tree") @@ -639,7 +723,11 @@ fn plan_of( node: FusedSeries, input: Arc, ) -> DataFusionResult> { - node.to_execution_plan(input, RawLabelSource::Explicit, SeriesOrdering::Contiguous) + node.to_execution_plan(vec![( + input, + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + )]) } /// The physical node of `tree` over `input`. @@ -850,9 +938,13 @@ fn zone_node() -> FusedSeries { ); FusedSeries::try_new( Arc::from(PROMQL), - tree, + tree.clone(), binding, - input_plan(frame_schema()), + one_input_tags( + &tree, + input_plan(frame_schema()), + vec![HOST.to_string(), ZONE.to_string(), NAME.to_string()], + ), zone_output_schema().to_dfschema_ref().unwrap(), ) .expect("the binding matches the tree") @@ -871,9 +963,13 @@ fn instant_node() -> FusedSeries { ); FusedSeries::try_new( Arc::from(PROMQL), - tree, + tree.clone(), binding, - input_plan(frame_schema()), + one_input_tags( + &tree, + input_plan(frame_schema()), + vec![HOST.to_string(), ZONE.to_string(), NAME.to_string()], + ), zone_output_schema().to_dfschema_ref().unwrap(), ) .expect("the binding matches the tree") @@ -1216,6 +1312,166 @@ async fn a_series_spanning_chunks_keeps_absolute_positions_and_closes_once() { assert_eq!(1, count(&metrics, "native.root.completed_series")); } +#[tokio::test] +async fn two_input_binary_exec_routes_each_raw_stream_to_its_tree_path() { + let left_schema = raw_schema(); + let right_schema = raw_schema(); + let tree = binary_tree(Arc::clone(&left_schema), Arc::clone(&right_schema)); + let output = Arc::new(Schema::new(vec![ + Field::new(VALUE, DataType::Float64, true), + Field::new(HOST, DataType::Utf8, true), + Field::new(NAME, DataType::Utf8, true), + Field::new( + TIME, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + ])); + let _node = FusedSeries::try_new( + Arc::from("a + on(host) b"), + tree.clone(), + FusedSeriesBinding { grid: grid() }, + vec![ + FusedSeriesInput { + series_schema: left_schema.clone(), + metric_name: Some(Arc::from("a")), + time_index: TIME.into(), + tags: vec![HOST.into(), NAME.into()], + input: input_plan(frame_schema()), + }, + FusedSeriesInput { + series_schema: right_schema.clone(), + metric_name: Some(Arc::from("b")), + time_index: TIME.into(), + tags: vec![HOST.into(), NAME.into()], + input: input_plan(frame_schema()), + }, + ], + output.clone().to_dfschema_ref().unwrap(), + ) + .unwrap(); + let physical = FusedSeriesExec::try_new( + Arc::from("a + on(host) b"), + vec![ + ( + memory_exec(frames(&[series_chunk("job", &[(GRID_START, 10.0)], true)])), + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + NodePath::root().left().input(), + left_schema, + ), + ( + memory_exec(frames(&[series_chunk("job", &[(GRID_START, 7.0)], true)])), + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + NodePath::root().right().input(), + right_schema, + ), + ], + Arc::new(tree), + output, + TIME.into(), + vec![HOST.into(), NAME.into()], + ) + .unwrap(); + let batches = collect(Arc::new(physical), SessionContext::default().task_ctx()) + .await + .unwrap(); + let rows = rows(&batches); + assert_eq!(1, rows.len()); + assert_eq!(GRID_START, rows[0].0); + assert_eq!(Some(17.0), rows[0].1); + assert_eq!(Some("job".to_string()), rows[0].2); +} + +#[tokio::test] +async fn two_inputs_match_across_every_partition_of_each_scan() { + let left_schema = raw_schema(); + let right_schema = raw_schema(); + let tree = binary_tree(Arc::clone(&left_schema), Arc::clone(&right_schema)); + let output = output_schema(); + let node = FusedSeries::try_new( + Arc::from("a + on(host) b"), + tree.clone(), + FusedSeriesBinding { grid: grid() }, + vec![ + FusedSeriesInput { + series_schema: left_schema.clone(), + metric_name: Some(Arc::from("a")), + time_index: TIME.into(), + tags: vec![HOST.into(), NAME.into()], + input: input_plan(frame_schema()), + }, + FusedSeriesInput { + series_schema: right_schema.clone(), + metric_name: Some(Arc::from("b")), + time_index: TIME.into(), + tags: vec![HOST.into(), NAME.into()], + input: input_plan(frame_schema()), + }, + ], + output + .to_dfschema_ref() + .expect("the output schema is valid"), + ) + .expect("the two-input binding matches the tree"); + // The two scans need not even agree on how many partitions they have: what pairs their series is + // the label, not the partition index, so the counts only decide how much each scan reads at once. + let left_rows = series_samples(1.0); + let right_rows = series_samples(2.0); + let left = memory_exec_partitioned(vec![ + frames(&[series_chunk("h1", &left_rows, true)]), + frames(&[series_chunk("h2", &left_rows, true)]), + ]); + let right = memory_exec_partitioned(vec![ + frames(&[series_chunk("h2", &right_rows, true)]), + frames(&[series_chunk("h1", &right_rows, true)]), + Vec::new(), + ]); + let physical = node + .to_execution_plan(vec![ + (left, RawLabelSource::Explicit, SeriesOrdering::Contiguous), + (right, RawLabelSource::Explicit, SeriesOrdering::Contiguous), + ]) + .expect("the two-input physical plan builds"); + assert_eq!( + 1, + physical + .properties() + .output_partitioning() + .partition_count() + ); + let batches = collect(Arc::clone(&physical), SessionContext::default().task_ctx()) + .await + .expect("the sole output partition executes"); + let actual = rows(&batches); + // A grid of its own, and the sample of each side that sits exactly on each of its points. + let grid_stamps = grid_timestamps(); + let expected = grid_stamps + .iter() + .map(|&stamp| { + let left = left_rows + .iter() + .find_map(|(time, value)| (*time == stamp).then_some(*value)) + .expect("the left samples cover every grid point"); + let right = right_rows + .iter() + .find_map(|(time, value)| (*time == stamp).then_some(*value)) + .expect("the right samples cover every grid point"); + (stamp, Some(left + right)) + }) + .collect::>(); + for host in ["h1", "h2"] { + let series = actual + .iter() + .filter(|row| row.2.as_deref() == Some(host)) + .map(|row| (row.0, row.1)) + .collect::>(); + assert_eq!(expected, series, "the complete summed series for {host}"); + } + assert_eq!(2 * GRID_LEN as usize, actual.len()); +} + /// A tree the runtime does not execute is refused when the execution plan is built. /// /// The runtime folds the supported `Complete` kinds now, so the tree below asks for one it still @@ -1240,15 +1496,12 @@ fn a_tree_bound_to_another_grid_is_rejected() { let tree = rate_tree(); let other_grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, GRID_STEP, GRID_LEN).unwrap()).unwrap()); - let binding = FusedSeriesBinding { - grid: other_grid, - ..binding(&tree) - }; + let binding = FusedSeriesBinding { grid: other_grid }; let error = FusedSeries::try_new( Arc::from(PROMQL), - tree, + tree.clone(), binding, - input_plan(frame_schema()), + one_input(&tree, input_plan(frame_schema())), output_schema().to_dfschema_ref().unwrap(), ) .expect_err("the tree is not evaluated on the declared grid"); @@ -1271,15 +1524,12 @@ fn a_separately_allocated_grid_with_an_equal_spec_is_accepted() { !Arc::ptr_eq(&equal, &binding(&tree).grid), "the two grids are separate allocations" ); - let binding = FusedSeriesBinding { - grid: equal, - ..binding(&tree) - }; - FusedSeries::try_new( + let binding = FusedSeriesBinding { grid: equal }; + let _node = FusedSeries::try_new( Arc::from(PROMQL), - tree, + tree.clone(), binding, - input_plan(frame_schema()), + one_input(&tree, input_plan(frame_schema())), output_schema().to_dfschema_ref().unwrap(), ) .expect("an equal grid spec is the same grid"); @@ -1471,7 +1721,7 @@ fn an_input_with_no_partitions_is_rejected_when_the_plan_is_built() { ))); let error = plan(rate_tree(), empty).expect_err("there is no partition to run"); assert!( - error.to_string().contains("input has no partitions"), + error.to_string().contains("has no partitions"), "refused for another reason: {error}" ); // The only count refused is zero: two partitions build and answer, which is what the @@ -2124,9 +2374,9 @@ fn two_field_node() -> FusedSeries { ); FusedSeries::try_new( Arc::from(PROMQL), - tree, + tree.clone(), binding, - input_plan(frame_schema_of(&two_field_schema())), + one_input(&tree, input_plan(frame_schema_of(&two_field_schema()))), two_field_output_schema().to_dfschema_ref().unwrap(), ) .expect("the binding matches the tree") @@ -2773,9 +3023,13 @@ fn unequal_binding_and_output_schema_are_not_ordered_equal() { }]), eval_grid: None, }); - let right = binding_of(&tree, other_schema, left.tags.clone()); - assert_ne!(left, right); - assert_ne!(Some(std::cmp::Ordering::Equal), left.partial_cmp(&right)); + let right = binding_of( + &tree, + other_schema, + vec![HOST.to_string(), NAME.to_string()], + ); + assert_eq!(left, right); + assert_eq!(Some(std::cmp::Ordering::Equal), left.partial_cmp(&right)); let left_node = fused(tree.clone()); let nullability_changed = Arc::new(Schema::new(vec![ @@ -2790,9 +3044,9 @@ fn unequal_binding_and_output_schema_are_not_ordered_equal() { ])); let right_node = FusedSeries::try_new( Arc::from(PROMQL), - tree, + tree.clone(), binding(&rate_tree()), - input_plan(frame_schema()), + one_input(&tree, input_plan(frame_schema())), nullability_changed.to_dfschema_ref().unwrap(), ) .unwrap(); diff --git a/src/promql/src/extension_plan/planner.rs b/src/promql/src/extension_plan/planner.rs index 701ca4be01d..4c31b72e97d 100644 --- a/src/promql/src/extension_plan/planner.rs +++ b/src/promql/src/extension_plan/planner.rs @@ -102,66 +102,53 @@ fn plan_fused_series( physical_inputs: &[Arc], target_partitions: usize, ) -> DfResult>> { - let Some(input) = physical_inputs.first() else { + if physical_inputs.is_empty() { return Ok(None); - }; - let Some(scan) = input.downcast_ref::() else { - return Ok(None); - }; - - let binding = fused.binding(); - let Some(metric_name) = binding.metric_name.as_deref() else { - return Err(DataFusionError::Plan( - "the FusedSeries node binds no metric name, so the region scan below it cannot be \ - asked for the series of one metric" - .to_string(), + } + let mut prepared = Vec::new(); + for (index, input) in physical_inputs.iter().enumerate() { + let Some(scan) = input.downcast_ref::() else { + return Ok(None); + }; + let binding = &fused.fused_inputs()[index]; + let Some(metric_name) = binding.metric_name.as_deref() else { + return Err(DataFusionError::Plan( + "the FusedSeries node binds no metric name".to_string(), + )); + }; + let tags = binding + .tags + .iter() + .filter(|tag| tag.as_str() != METRIC_NAME) + .cloned() + .collect::>(); + let fields = binding + .series_schema + .fields + .iter() + .map(|field| field.name.to_string()) + .collect::>(); + let scan = if scan.is_partition_set() { + Arc::new(scan.clone()) + } else { + let n = target_partitions.max(1); + let partitions = + table::table::scan::assign_partition_ranges(scan.get_partition_ranges(), n); + Arc::new( + scan.with_new_partitions(partitions, n) + .map_err(|e| DataFusionError::External(e.into_inner()))?, + ) + }; + let Some(series_scan) = scan.try_to_named_series_scan(metric_name, &tags, &fields)? else { + return Err(DataFusionError::Plan(format!( + "the region scan under FusedSeries could not serve raw series for {metric_name:?}" + ))); + }; + prepared.push(( + series_scan.clone() as Arc, + series_scan.label_source().clone(), + series_scan.raw_series_ordering(), )); - }; - // `__name__` is the metric name rather than a column of the region, so it is not one of the - // logical tags the scan is asked to decode; the frame names each series' own metric. - let logical_tags = binding - .tags - .iter() - .filter(|tag| tag.as_str() != METRIC_NAME) - .cloned() - .collect::>(); - let field_names = binding - .series_schema - .fields - .iter() - .map(|field| field.name.to_string()) - .collect::>(); - - let scan = if scan.is_partition_set() { - Arc::new(scan.clone()) - } else { - let partitions = table::table::scan::assign_partition_ranges( - scan.get_partition_ranges(), - target_partitions.max(1), - ); - Arc::new( - scan.with_new_partitions(partitions, target_partitions.max(1)) - .map_err(|error| DataFusionError::External(error.into_inner()))?, - ) - }; - // The scan resolves the label source and the ordering it will declare itself, against its own - // metadata snapshot, and hands both back through the leaf it builds. Naming them here instead - // would be a second copy of a binding only the scanner can make: the physical metadata and - // column ids a `RawLabelSource::PrimaryKey` carries are not reachable from a region scan's - // public surface, so the layer that resolves them is the scanner. - let Some(series_scan) = - scan.try_to_named_series_scan(metric_name, &logical_tags, &field_names)? - else { - return Err(DataFusionError::Plan(format!( - "the region scan under FusedSeries could not serve a raw series frame for metric \ - {metric_name:?}: the scanner refused the raw series path for this scan, so this node \ - has no input to read" - ))); - }; - let label_source = series_scan.label_source().clone(); - let ordering = series_scan.raw_series_ordering(); - - fused - .to_execution_plan(series_scan, label_source, ordering) - .map(Some) + } + fused.to_execution_plan(prepared).map(Some) } diff --git a/src/query/src/dist_plan/analyzer.rs b/src/query/src/dist_plan/analyzer.rs index 92ec8502fab..f629ca092f7 100644 --- a/src/query/src/dist_plan/analyzer.rs +++ b/src/query/src/dist_plan/analyzer.rs @@ -975,8 +975,27 @@ impl TreeNodeRewriter for EnforceDistRequirementRewriter { type Node = LogicalPlan; fn f_down(&mut self, node: Self::Node) -> DfResult> { - // check that node doesn't have multiple children, i.e. join/subquery + // The level bookkeeping below describes one chain of nodes: a level names a node, and a + // column requirement is scoped by the level it was recorded at. A node with several inputs + // is a branch whose children would all share one level, so the walk stops at the branch + // rather than assigning them levels that mean nothing. + // + // The one branch that is expected here is a fused PromQL node, whose inputs are the region + // scans of its selectors: each is the scan itself, with no projection under it that a column + // requirement could amend. Any other branch keeps the refusal, because a sub-plan this walk + // has not been taught to read is not something to leave half-enforced. if node.inputs().len() > 1 { + if is_fused_series_plan(&node) { + self.plan_per_level.insert(self.cur_level, node.clone()); + // The level still advances, because `f_up` gives it back for this node: a walk that + // skipped the increment would leave every node above this one a level too low. + self.cur_level += 1; + return Ok(Transformed::new( + node, + false, + datafusion_common::tree_node::TreeNodeRecursion::Jump, + )); + } return Err(datafusion_common::DataFusionError::Internal( "EnforceDistRequirementRewriter: node with multiple inputs is not supported" .to_string(), diff --git a/src/query/src/dist_plan/commutativity.rs b/src/query/src/dist_plan/commutativity.rs index c11e78cf819..fc20423ea38 100644 --- a/src/query/src/dist_plan/commutativity.rs +++ b/src/query/src/dist_plan/commutativity.rs @@ -23,7 +23,7 @@ use datafusion_expr::{Expr, LogicalPlan, UserDefinedLogicalNode}; use promql::extension_plan::{ EmptyMetric, FusedSeries, InstantManipulate, RangeManipulate, SeriesDivide, SeriesNormalize, }; -use promql::native::plan::reads_across_series; +use promql::native::plan::{NativeExpr, NativeNode}; use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME; use crate::dist_plan::MergeScanLogicalPlan; @@ -243,23 +243,39 @@ impl Categorizer { } name if name == FusedSeries::name() => { let fused = plan.as_any().downcast_ref::().unwrap(); - // A region builds this node from the region scan itself: the conversion takes that + // A region builds this node from the region scans themselves: the conversion takes a // scan's raw-series entrypoint and cannot look through anything in between, so a - // node whose input is not that scan has nothing to read where it would be placed - // and stays where it was planned. - if !matches!(fused.inputs().as_slice(), [LogicalPlan::TableScan(_)]) { + // node with an input that is not such a scan has nothing to read where it would be + // placed and stays where it was planned. Every input also has to read the same + // table: two tables need not share a region, and a region can only evaluate the tree + // over the scans it can build for itself. + let inputs = fused.inputs(); + let mut table = None; + for input in &inputs { + let LogicalPlan::TableScan(scan) = input else { + return Commutativity::NonCommutative; + }; + if table.is_some_and(|name| name != &scan.table_name) { + return Commutativity::NonCommutative; + } + table = Some(&scan.table_name); + } + // The region asks each scan for the series of one named metric, so a node with an + // input that binds no name cannot be built there at all. + if fused + .fused_inputs() + .iter() + .any(|input| input.metric_name.is_none()) + { return Commutativity::NonCommutative; } - // The region asks the scan for the series of one named metric, so a node that binds - // no name cannot be built there at all. - if fused.binding().metric_name.is_none() { - return Commutativity::NonCommutative; - } - // A region evaluates the tree over whatever series its own scan returns, so this - // is only answerable when every node of the tree reads one series at a time. An - // aggregate or a binary operation would fold or pair across series, and one region - // holds only part of them. - if reads_across_series(fused.tree().root()) { + // A region evaluates the tree over whatever series its own scans return. A window, + // a map and an instant read one series at a time, so one region's share of a series + // is everything they need of it. An aggregate folds a label set's series together + // and would fold one region's half of the group, so it stays where it was planned. + // A binary operation pairs series by label, which a region can answer for every + // pair whose two sides it holds; see the caveat below. + if folds_across_series(fused.tree().root()) { return Commutativity::NonCommutative; } @@ -274,6 +290,13 @@ impl Categorizer { // region deployment satisfies it; a partitioned table over several regions does not, // and would return a wrong answer rather than an error. // + // A binary operation adds one more way to be in this position: it pairs two series + // by their labels, and the two sides of one pair need not reach one region - a table + // partitioned by a column the match does not name puts `a{kind="a"}` and + // `a{kind="b"}` with the same `host` in different regions, and the region holding + // one of them finds no partner and drops the match. One region holds every series + // both scans can return, so the pair is there. + // // What would make this unconditional is a partition key the label set determines, // checked against the table's physical partition expressions. Until then the // placement is a proof of concept over one region. @@ -385,6 +408,33 @@ impl Categorizer { } } +/// Whether `tree` folds one label set's series into a single value. +/// +/// An aggregate folds every series of a group together, so a region that holds part of the group +/// would answer the fold of its own half and the union of the parts would be a wrong query answered +/// silently. Everything else the native compiler emits reads one series at a time: an instant +/// selection, a window and a point-wise map each select, fold or map the samples of the series they +/// were handed. A binary operation pairs series rather than folding them, so it is not a fold here; +/// what a region can pair is the subject of the caveat at the placement decision. A vector operation +/// reads the whole vector at a grid point, so it folds across series the way an aggregate does. +fn folds_across_series(node: &NativeNode) -> bool { + match &node.expr { + NativeExpr::Input(_) | NativeExpr::Scalar(_) => false, + NativeExpr::Instant { input, .. } + | NativeExpr::Window { input, .. } + | NativeExpr::Map { input, .. } => folds_across_series(input), + // A binary operation pairs the two sides rather than folding either of them, so what + // decides is whether a side folds its own input. + NativeExpr::Binary { left, right, .. } => { + folds_across_series(left) || folds_across_series(right) + } + NativeExpr::Aggregate { .. } => true, + // `sort`, `absent`, `topk` and `histogram_quantile` reorder or read every series of the + // vector at a grid point, so one region's share of the series cannot answer them. + NativeExpr::Vector { .. } => true, + } +} + #[cfg(test)] mod tests { use std::collections::{BTreeMap, BTreeSet}; @@ -404,7 +454,7 @@ mod tests { use datafusion_optimizer::analyzer::AnalyzerRule; use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; - use promql::extension_plan::{FusedSeries, FusedSeriesBinding}; + use promql::extension_plan::{FusedSeries, FusedSeriesBinding, FusedSeriesInput}; use promql::functions::{ NativeHistogramDrop, NativeHistogramFraction, NativeHistogramQuantile, }; @@ -491,12 +541,15 @@ mod tests { ) .unwrap(); let binding = FusedSeriesBinding { - series_schema, grid: statement_grid(&stmt).unwrap(), + }; + let inputs = vec![FusedSeriesInput { + series_schema, metric_name: metric_name.map(Arc::from), time_index: "ts".to_string(), tags: Vec::new(), - }; + input, + }]; let output_schema: DFSchemaRef = Arc::new( DFSchema::new_with_metadata( vec![ @@ -524,7 +577,7 @@ mod tests { Arc::from("some_metric"), tree, binding, - input, + inputs, output_schema, ) .unwrap(), @@ -744,7 +797,7 @@ mod tests { grid: statement_grid(&native_statement()).unwrap(), })), }; - assert!(reads_across_series(&aggregate)); + assert!(folds_across_series(&aggregate)); // The same walk over what the compiler emits stays per-series. let single_selector = compile( @@ -756,7 +809,7 @@ mod tests { SeriesOrdering::KeyThenTime, ) .unwrap(); - assert!(!reads_across_series(single_selector.root())); + assert!(!folds_across_series(single_selector.root())); } /// The encoding gate is what kept the node on the frontend, and it only exists for a plan that diff --git a/src/query/src/optimizer/scan_hint.rs b/src/query/src/optimizer/scan_hint.rs index 0a1334dd9c0..c7d856273df 100644 --- a/src/query/src/optimizer/scan_hint.rs +++ b/src/query/src/optimizer/scan_hint.rs @@ -497,7 +497,9 @@ mod test { use datatypes::schema::ColumnSchema; use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; - use promql::extension_plan::{FusedSeries, FusedSeriesBinding, RangeManipulate}; + use promql::extension_plan::{ + FusedSeries, FusedSeriesBinding, FusedSeriesInput, RangeManipulate, + }; use promql_parser::parser; use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME; @@ -1582,12 +1584,15 @@ mod test { ) .unwrap(); let binding = FusedSeriesBinding { - series_schema, grid: statement_grid(&stmt).unwrap(), + }; + let inputs = vec![FusedSeriesInput { + series_schema, metric_name: Some("some_metric".into()), time_index: "ts".to_string(), tags: Vec::new(), - }; + input, + }]; let output_schema: DFSchemaRef = Arc::new( DFSchema::new_with_metadata( vec![ @@ -1612,7 +1617,7 @@ mod test { Arc::from("some_metric"), tree, binding, - input, + inputs, output_schema, ) .unwrap(), diff --git a/src/query/src/promql/planner.rs b/src/query/src/promql/planner.rs index 05acc1a9de5..74687f80d47 100644 --- a/src/query/src/promql/planner.rs +++ b/src/query/src/promql/planner.rs @@ -345,6 +345,15 @@ impl PromPlanner { if let Some(plan) = planner.try_plan_native_fused(&stmt.expr).await? { return planner.strip_tsid_column(plan); } + // `TQL EXPLAIN` wraps the query it explains in an extension node, and a reader asks for that + // explanation to see the plan the query actually runs. Offering the wrapper itself would + // decline every time - it is not a shape a tree has a node for - and the answer would show + // the existing path's plan even where the native route is the one that runs. The two + // `EXPLAIN` forms are therefore offered their body, which is wrapped the same way the + // existing path wraps it. + if let Some(plan) = planner.try_plan_native_fused_explain(&stmt.expr).await? { + return planner.strip_tsid_column(plan); + } let plan = planner .prom_root_expr_to_plan(&stmt.expr, query_engine_state) diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index d2d23c8a123..a91e8fb815b 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -34,12 +34,14 @@ use common_catalog::consts::{METRIC_ENGINE, MITO_ENGINE, MITO2_ENGINE}; use datafusion::arrow::datatypes::{DataType as ArrowDataType, Field, TimeUnit as ArrowTimeUnit}; use datafusion::common::{DFSchema, DFSchemaRef}; use datafusion::error::DataFusionError; -use datafusion::logical_expr::{Extension, LogicalPlan, TableScanBuilder}; +use datafusion::logical_expr::{Extension, LogicalPlan, LogicalPlanBuilder, TableScanBuilder}; +use datafusion::prelude::Expr as DfExpr; use datafusion_expr::Expr; use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; -use promql::extension_plan::{FusedSeries, FusedSeriesBinding}; -use promql::native::plan::reads_across_series; +use promql::extension_plan::{FusedSeries, FusedSeriesBinding, FusedSeriesInput}; +use promql::native::plan::{NativeExpr, reads_across_series}; +use promql_parser::label::Matchers; use promql_parser::parser::value::ValueType; use promql_parser::parser::{ EvalStmt, Expr as PromExpr, MatrixSelector, ParenExpr, VectorSelector, @@ -48,8 +50,9 @@ use session::context::QueryContextRef; use snafu::ResultExt; use store_api::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_ENGINE_NAME}; +use crate::parser::{EXPLAIN_NODE_NAME, EXPLAIN_VERBOSE_NODE_NAME}; use crate::promql::error::{DataFusionPlanningSnafu, Result}; -use crate::promql::native_compile::{compile, statement_grid}; +use crate::promql::native_compile::{compile_selectors, statement_grid}; use crate::promql::planner::PromPlanner; /// The query-context key that turns the native fused-series route on for one query. @@ -119,218 +122,355 @@ impl PromPlanner { return Ok(None); } - // A tree reads exactly one raw input, and the scan below the node is that one selector's, - // so a shape that names no selector or more than one is not offered at all. - let Some(selector) = single_selector(prom_expr) else { - return Ok(None); + let selectors = { + let mut values = Vec::new(); + collect_selectors(prom_expr, &mut values); + values }; - - // Resolve the selector the way the existing planner does, and take what is left as the - // rows it selects. The scan below the node is the selector's own scan, unfiltered, so a - // matcher that survives preprocessing selects fewer rows here than the scan reads. - let matchers = self.preprocess_label_matchers(&selector.matchers, &selector.name)?; - if !matchers.matchers.is_empty() { - return Ok(None); - } - // An `__field__` matcher narrows the field columns the existing planner builds its scan - // with; folding every field of the table instead would evaluate a different window. - if self.ctx.field_column_matcher.is_some() { - return Ok(None); - } - // A metric without a table reads as an empty metric, which the existing planner plans. - if self.setup_context().await?.is_some() { - return Ok(None); - } - - let Some(table_name) = self.ctx.table_name.clone() else { - return Ok(None); - }; - let Some(time_index) = self.ctx.time_index_column.clone() else { - return Ok(None); - }; - let fields = self.ctx.field_columns.clone(); - let tags = self.ctx.tag_columns.clone(); - // A series with no field has nothing to fold, and the tree's input would be an empty - // schema, which no window can read. - if fields.is_empty() { - return Ok(None); - } - - // The selector's own table scan, built by the same method the existing path uses: the - // physical planner turns it into the region scan the node reads, and building a scan here - // instead would let the two paths disagree about the columns they read. - let table_ref = self.table_ref()?; - let mut input = self.create_table_scan_plan(table_ref.clone()).await?; - let logical_scan = metric_scan_and_table_id(&input); - let has_verified_metric_rewrite = logical_scan.is_some(); - let scan = match logical_scan { - Some((mut scan, predicate)) => { - // Preserve logical field order and the table restriction on the direct physical scan. - let source_schema = scan.source.schema(); - let Some(mut ordered_projection) = fields - .iter() - .map(|field| source_schema.index_of(field).ok()) - .collect::>>() - else { - return Ok(None); - }; - let original_projection = scan.projection.as_ref(); - let selected_indices = original_projection - .cloned() - .unwrap_or_else(|| (0..source_schema.fields().len()).collect()); - for index in selected_indices { - let is_field = fields - .iter() - .any(|field| field == source_schema.field(index).name()); - if !is_field && !ordered_projection.contains(&index) { - ordered_projection.push(index); - } - } - scan.filters.push(predicate); - scan = TableScanBuilder::from(scan) - .with_projection(Some(ordered_projection)) - .build() - .context(DataFusionPlanningSnafu)?; - input = LogicalPlan::TableScan(scan.clone()); - scan - } - None => match &input { - LogicalPlan::TableScan(scan) => scan.clone(), - _ => return Ok(None), - }, - }; - let table = self.table_from_source(&scan.source)?; - let table_meta = &table.table_info().meta; - // An engine without a raw-series scanner has no frame to give this node, and by the time - // the physical planner asks, the logical plan is already this node: the refusal there is a - // planning error, not a fallback. So the engine is checked here, where the existing plan is - // still the answer. A file-engine table is the concrete case: its scanner is a - // `SinglePartitionScanner`, which leaves `raw_series_schema` at the default `None`. - if !supports_native_raw_series(&table_meta.engine) - || (table_meta.engine == METRIC_ENGINE_NAME && !has_verified_metric_rewrite) - { - return Ok(None); - } - // The region's raw-series preflight refuses these, and the physical layer turns that refusal into an error, so decline this route here instead. - let time_index_type = table_meta - .schema - .timestamp_column() - .map(|column| &column.data_type); - if time_index_type - != Some(&datatypes::prelude::ConcreteDataType::timestamp_millisecond_datatype()) - || table_meta - .options - .extra_options - .get(store_api::mito_engine_options::APPEND_MODE_KEY) - .is_some_and(|value| value.eq_ignore_ascii_case("true")) - { - return Ok(None); - } - // FusedSeries evaluates each region independently, so partition keys must identify a series. - if !table - .table_info() - .meta - .partition_column_names() - .all(|column| tags.iter().any(|tag| tag == column)) - { - return Ok(None); - } - // The legacy selector converts an offset the same way; sharing that conversion keeps the - // two scan paths from disagreeing about an extreme duration. - let offset = Self::offset_millis(&selector.offset); - let (saved_start, saved_end, saved_range) = (self.ctx.start, self.ctx.end, self.ctx.range); - self.ctx.range = selector_range_millis(prom_expr); - // Keep the fused scan's bounds identical to the legacy selector scan, including @ and offset. - let time_filter = (|| { - let anchored = self.at_modifier_offset(&selector.at, &selector.offset)?; - if anchored.is_some() { - self.ctx.end = saved_start; - } - self.build_time_index_filter(anchored.unwrap_or(offset), input.schema()) - })(); - self.ctx.start = saved_start; - self.ctx.end = saved_end; - self.ctx.range = saved_range; - let time_filter = time_filter?; - if let Some(filter) = time_filter { - let LogicalPlan::TableScan(scan) = &mut input else { - unreachable!(); - }; - scan.filters.push(filter); - } - // A window over a native histogram yields a histogram, which the output schema below - // cannot declare; the existing path evaluates those with its own kernels. - if Self::field_columns_contain_native_histogram(input.schema(), &fields) { - return Ok(None); - } - // The region's raw series preflight serves a field only when it is numeric or a native - // histogram, and the physical layer turns that refusal into a planning error because the - // logical plan is already fixed by then. A table whose selected fields are, say, a string - // and a boolean therefore has to be declined here, while the existing plan is still the - // fallback - `stringsfield` over such a table answered normally before this route existed. - if !Self::field_columns_are_raw_series_servable(input.schema(), &fields) { + if selectors.is_empty() { return Ok(None); } let Some(stmt) = self.native_statement(prom_expr) else { return Ok(None); }; let Ok(grid) = statement_grid(&stmt) else { - // The statement's grid is not one a tree can be evaluated on, so there is no grid to - // address the node's output by. return Ok(None); }; - - let series_schema = Arc::new(SeriesSchema { - fields: fields - .iter() - .map(|name| FieldSpec { - name: Arc::from(name.as_str()), - }) - .collect::>() - .into(), - eval_grid: None, - }); - let tree = match compile(&stmt, Arc::clone(&series_schema), NATIVE_ORDERING) { - Ok(tree) => tree, - // The compiler refusing a shape is this route declining it: the existing planner gets - // the query exactly as it would have without this flag. - Err(DataFusionError::NotImplemented(_)) => return Ok(None), - Err(error) => return Err(error).context(DataFusionPlanningSnafu), - }; - // A vector operation (`sort`, `absent`, `topk`, `histogram_quantile`, ...) reads the whole - // vector at each grid point rather than one series at a time, so it cannot be evaluated by - // one executor per scan partition. Declining here is the only place that still works: once - // the `FusedSeries` node exists the logical plan is fixed, and the categorizer merely - // declining to push it down would leave a node the physical layer must build anyway. - if reads_across_series(tree.root()) { + let original_context = self.ctx.clone(); + let mut prepared: Vec = Vec::new(); + for selector in &selectors { + self.ctx = original_context.clone(); + let matchers = match self.preprocess_label_matchers(&selector.matchers, &selector.name) + { + Ok(m) => m, + Err(_) => return Ok(None), + }; + if self.setup_context().await?.is_some() { + return Ok(None); + } + let (Some(metric), Some(time)) = ( + self.ctx.table_name.clone(), + self.ctx.time_index_column.clone(), + ) else { + return Ok(None); + }; + let tags = self.ctx.tag_columns.clone(); + let fields = self.ctx.field_columns.clone(); + // A `__field__` matcher narrows the field set in a projection the existing planner + // builds, and the raw series scan below this node has no equivalent: it reports every + // field the scan carries. Binding all of them would fold fields the query excluded, so + // the route is declined until the field selector is reused here. + if self.ctx.field_column_matcher.is_some() || fields.is_empty() { + return Ok(None); + } + // The selector's own table scan, built by the same method the existing path uses: + // the physical planner turns it into the region scan the node reads, and building a + // scan here instead would let the two paths disagree about the columns they read. + let table_ref = self.table_ref()?; + let mut input = self.create_table_scan_plan(table_ref).await?; + let logical_scan = metric_scan_and_table_id(&input); + let has_verified_metric_rewrite = logical_scan.is_some(); + let scan = match logical_scan { + Some((mut scan, predicate)) => { + // Preserve logical field order and the table restriction on the direct + // physical scan. + let source_schema = scan.source.schema(); + let Some(mut ordered_projection) = fields + .iter() + .map(|field| source_schema.index_of(field).ok()) + .collect::>>() + else { + return Ok(None); + }; + let original_projection = scan.projection.as_ref(); + let selected_indices = original_projection + .cloned() + .unwrap_or_else(|| (0..source_schema.fields().len()).collect()); + for index in selected_indices { + let is_field = fields + .iter() + .any(|field| field == source_schema.field(index).name()); + if !is_field && !ordered_projection.contains(&index) { + ordered_projection.push(index); + } + } + scan.filters.push(predicate); + scan = TableScanBuilder::from(scan) + .with_projection(Some(ordered_projection)) + .build() + .context(DataFusionPlanningSnafu)?; + input = LogicalPlan::TableScan(scan.clone()); + scan + } + None => match &input { + LogicalPlan::TableScan(scan) => scan.clone(), + _ => return Ok(None), + }, + }; + let table = self.table_from_source(&scan.source)?; + let table_meta = &table.table_info().meta; + // An engine without a raw-series scanner has no frame to give this node, and by the + // time the physical planner asks, the logical plan is already this node: the refusal + // there is a planning error, not a fallback. So the engine is checked here, where the + // existing plan is still the answer. A file-engine table is the concrete case: its + // scanner is a `SinglePartitionScanner`, which leaves `raw_series_schema` at the + // default `None`. A metric-engine table is served only through the logical rewrite + // recognised above, which is what makes its series the table's own. + if !supports_native_raw_series(&table_meta.engine) + || (table_meta.engine == METRIC_ENGINE_NAME && !has_verified_metric_rewrite) + { + return Ok(None); + } + // The region's raw-series preflight refuses these, and the physical layer turns that + // refusal into an error, so decline this route here instead. + let time_index_type = table_meta + .schema + .timestamp_column() + .map(|column| &column.data_type); + if time_index_type + != Some(&datatypes::prelude::ConcreteDataType::timestamp_millisecond_datatype()) + || table_meta + .options + .extra_options + .get(store_api::mito_engine_options::APPEND_MODE_KEY) + .is_some_and(|value| value.eq_ignore_ascii_case("true")) + { + return Ok(None); + } + // FusedSeries evaluates each region independently, so partition keys must identify a + // series. + if !table + .table_info() + .meta + .partition_column_names() + .all(|column| tags.iter().any(|tag| tag == column)) + { + return Ok(None); + } + // A window over a native histogram yields a histogram, which the output schema below + // cannot declare; the existing path evaluates those with its own kernels. + if Self::field_columns_contain_native_histogram(input.schema(), &fields) { + return Ok(None); + } + // The region's raw series preflight serves a field only when it is numeric or a native + // histogram, and the physical layer turns that refusal into a planning error because + // the logical plan is already fixed by then. A table whose selected fields are, say, a + // string and a boolean therefore has to be declined here, while the existing plan is + // still the fallback - `stringsfield` over such a table answered normally before this + // route existed. + if !Self::field_columns_are_raw_series_servable(input.schema(), &fields) { + return Ok(None); + } + let series_schema = Arc::new(SeriesSchema { + fields: fields + .iter() + .map(|name| FieldSpec { + name: Arc::from(name.as_str()), + }) + .collect::>() + .into(), + eval_grid: None, + }); + // The row filter is the selector's own: the time range is added after compiling, + // because only the compiler knows whether this occurrence reads a window or one + // instant. + let mut filters = Self::matchers_to_expr(matchers, input.schema())?; + if let LogicalPlan::TableScan(table_scan) = &mut input { + table_scan.filters.append(&mut filters); + } else { + return Ok(None); + } + prepared.push(FusedSeriesInput { + series_schema, + metric_name: Some(Arc::from(metric)), + time_index: time, + tags, + input, + }); + } + self.ctx = original_context; + if prepared + .windows(2) + .any(|w| w[0].time_index != w[1].time_index || w[0].tags != w[1].tags) + { return Ok(None); } - - let binding = FusedSeriesBinding { - series_schema, - // The tree's own output is evaluated on the statement's grid, and the binding names - // the same one, so a chunk's absolute positions are read on the grid it was computed - // on. - grid, - metric_name: Some(Arc::from(table_name.as_str())), - time_index: time_index.clone(), - tags: tags.clone(), + // The compiler binds one input per selector in the same pre-order `collect_selectors` + // walks, so position i of both lists is the same occurrence. This is the guard that the + // two walks agree: a mismatch is a compiler defect, not a query this route can plan. + let identities: Vec<(Option, Matchers, i64, Option)> = selectors + .iter() + .map(|selector| { + let offset_ms = selector + .offset + .as_ref() + .map(|o| match o { + promql_parser::parser::Offset::Pos(d) => d.as_millis() as i64, + promql_parser::parser::Offset::Neg(d) => -(d.as_millis() as i64), + }) + .unwrap_or_default(); + Ok(( + selector.name.clone(), + selector.matchers.clone(), + offset_ms, + self.at_ref_time(&selector.at, &selector.offset)?, + )) + }) + .collect::>>()?; + let bind_index = std::cell::Cell::new(0usize); + let compiled = match compile_selectors( + &stmt, + &|req| { + let i = bind_index.get(); + bind_index.set(i + 1); + let (Some(prepared_input), Some(identity)) = (prepared.get(i), identities.get(i)) + else { + return Err(DataFusionError::Internal( + "a selector was bound that the planner did not prepare".into(), + )); + }; + if *identity + != ( + req.metric.clone(), + req.matchers.clone(), + req.offset_ms, + req.at_ms, + ) + { + return Err(DataFusionError::Internal( + "the compiler and the planner walk the selectors differently".into(), + )); + } + Ok(Arc::clone(&prepared_input.series_schema)) + }, + NATIVE_ORDERING, + ) { + Ok(v) => v, + // The compiler refusing a shape is this route declining it. + Err(DataFusionError::NotImplemented(_)) => return Ok(None), + Err(e) => return Err(e).context(DataFusionPlanningSnafu), }; - let output_schema = fused_output_schema(&fields, &tags, &time_index)?; + // An aggregate or a vector operation (`sort`, `absent`, `topk`, `histogram_quantile`, ...) + // reads the whole vector at each grid point rather than one series at a time, so it cannot + // be evaluated by one executor per scan partition. Declining here is the only place that + // still works: once the `FusedSeries` node exists the logical plan is fixed, and the + // categorizer merely declining to push it down would leave a node the physical layer must + // build anyway. A binary operation pairs one series with another and reads each of them + // point-wise, so a tree rooted in one keeps the route: its operands are the independent + // scans prepared above. + // + // TEMPORARY: the exception below is stated over the root alone, while the classifier it + // narrows is a whole-tree walk. The two have to be reconciled with the per-operand + // point-wise check the shared gate will own, so this narrowing is the first stage's anchor + // rather than the shape to keep. + if !matches!(compiled.tree.root().expr, NativeExpr::Binary { .. }) + && reads_across_series(compiled.tree.root()) + { + return Ok(None); + } + if compiled.inputs.len() != prepared.len() { + return Err(DataFusionError::Internal( + "the compiled tree reads a different number of inputs than the planner prepared" + .into(), + )) + .context(DataFusionPlanningSnafu); + } + let mut inputs = Vec::with_capacity(prepared.len()); + for (index, (compiled_input, mut input)) in compiled.inputs.iter().zip(prepared).enumerate() + { + // The range this selector reads is the compiler's own: a window and an instant differ + // in which side of the lookback or range their scan starts on, and an anchor can move + // the whole range outside the statement's. + let (start, end, inclusive) = compiled_input + .requirement + .raw_scan_bounds() + .context(DataFusionPlanningSnafu)?; + let time = input.time_index.clone(); + let mut scan = input.input; + let filter = scan_time_filter(start, end, inclusive, scan.schema(), &time)?; + if let (LogicalPlan::TableScan(table_scan), Some(filter)) = (&mut scan, filter) { + table_scan.filters.push(filter); + } else if !matches!(scan, LogicalPlan::TableScan(_)) { + return Err(DataFusionError::Internal(format!( + "the input at {index} is not the table scan this route prepared" + ))) + .context(DataFusionPlanningSnafu); + } + input.input = scan; + inputs.push(input); + } + let root_fields = compiled + .tree + .root() + .output + .samples() + .ok_or_else(|| DataFusionError::Internal("native tree root has no samples".into())) + .context(DataFusionPlanningSnafu)? + .fields + .iter() + .map(|f| f.name.to_string()) + .collect::>(); + if root_fields.iter().any(|field| { + !inputs.iter().any(|input| { + input + .series_schema + .fields + .iter() + .any(|f| f.name.as_ref() == field) + }) + }) { + return Ok(None); + } + let time = inputs[0].time_index.clone(); + let tags = inputs[0].tags.clone(); + let output_schema = fused_output_schema(&root_fields, &tags, &time)?; let node = FusedSeries::try_new( Arc::from(prom_expr.to_string()), - tree, - binding, - input, + compiled.tree, + FusedSeriesBinding { grid }, + inputs, output_schema, ) .context(DataFusionPlanningSnafu)?; - Ok(Some(LogicalPlan::Extension(Extension { node: Arc::new(node), }))) } + /// Offers an `EXPLAIN` statement's body to the native compiler, and wraps the plan it makes. + /// + /// `TQL EXPLAIN (…) ` is the statement whose root extension wraps the query, and the + /// explanation a reader gets should be of the plan that query runs. Only the two plain + /// explanations are handled: `ANALYZE`, which runs the plan and reports its metrics, and + /// `EXPLAIN VERBOSE` are left to the existing path, so this adds nothing to what those report. + pub(super) async fn try_plan_native_fused_explain( + &mut self, + prom_expr: &PromExpr, + ) -> Result> { + let PromExpr::Extension(extension) = prom_expr else { + return Ok(None); + }; + let explain = match extension.expr.name() { + EXPLAIN_NODE_NAME => false, + EXPLAIN_VERBOSE_NODE_NAME => true, + _ => return Ok(None), + }; + let children = extension.expr.children(); + let [body] = children else { + return Ok(None); + }; + let Some(plan) = self.try_plan_native_fused(body).await? else { + return Ok(None); + }; + Ok(Some( + LogicalPlanBuilder::from(plan) + .explain(explain, false) + .context(DataFusionPlanningSnafu)? + .build() + .context(DataFusionPlanningSnafu)?, + )) + } + /// The statement being planned, rebuilt from the evaluation numbers the planner holds. /// /// The compiler reads the statement's grid, lookback and `@` anchors rather than the planner's @@ -354,6 +494,87 @@ impl PromPlanner { } } +/// The time-range filter a selector's scan reads, from the bounds its compiled requirement names. +/// +/// The lower edge is exclusive unless the requirement says otherwise, which is how a window and a +/// positive lookback read; an inclusive edge is what a zero lookback instant selection has. The +/// bound is expressed in the scan's own timestamp unit, and a bound that unit cannot represent is +/// left out rather than widened: the other side still prunes, and the evaluator applies the exact +/// rule either way. +fn scan_time_filter( + start: i64, + end: i64, + inclusive: bool, + schema: &DFSchema, + time_column: &str, +) -> Result> { + use datafusion::scalar::ScalarValue; + let Some(index) = schema.index_of_column_by_name(None, time_column) else { + return Ok(None); + }; + let unit = match &schema.field(index).data_type() { + arrow::datatypes::DataType::Timestamp(unit, _) => *unit, + _ => return Ok(None), + }; + let native = |milliseconds: i128| match unit { + arrow::datatypes::TimeUnit::Second => milliseconds.div_euclid(1_000), + arrow::datatypes::TimeUnit::Millisecond => milliseconds, + arrow::datatypes::TimeUnit::Microsecond => milliseconds * 1_000, + arrow::datatypes::TimeUnit::Nanosecond => milliseconds * 1_000_000, + }; + let literal = |milliseconds: i128| -> Option { + let value = i64::try_from(native(milliseconds)).ok()?; + Some(DfExpr::Literal( + match unit { + arrow::datatypes::TimeUnit::Second => { + ScalarValue::TimestampSecond(Some(value), None) + } + arrow::datatypes::TimeUnit::Millisecond => { + ScalarValue::TimestampMillisecond(Some(value), None) + } + arrow::datatypes::TimeUnit::Microsecond => { + ScalarValue::TimestampMicrosecond(Some(value), None) + } + arrow::datatypes::TimeUnit::Nanosecond => { + ScalarValue::TimestampNanosecond(Some(value), None) + } + }, + None, + )) + }; + let column = DfExpr::Column(datafusion::common::Column::from_name(time_column)); + let lower = literal(i128::from(start)).map(|literal| { + if inclusive { + column.clone().gt_eq(literal) + } else if unit == arrow::datatypes::TimeUnit::Millisecond { + // An exclusive edge on a millisecond axis is the next representable instant, which is + // how the existing selector filter states it. + literal_or_next(start).map_or_else( + || column.clone().gt(literal.clone()), + |next| column.clone().gt_eq(next), + ) + } else { + column.clone().gt(literal) + } + }); + let upper = literal(i128::from(end)).map(|literal| column.clone().lt_eq(literal)); + Ok(match (lower, upper) { + (Some(lower), Some(upper)) => Some(lower.and(upper)), + (Some(one), None) | (None, Some(one)) => Some(one), + (None, None) => None, + }) +} + +/// The literal one millisecond after `start`, for an exclusive lower edge on a millisecond axis. +fn literal_or_next(start: i64) -> Option { + use datafusion::scalar::ScalarValue; + let next = start.checked_add(1)?; + Some(DfExpr::Literal( + ScalarValue::TimestampMillisecond(Some(next), None), + None, + )) +} + /// The columns a [`FusedSeries`] node produces. /// /// The shape is the one the existing unary pipeline consumes — the time index, then the series @@ -394,22 +615,43 @@ fn fused_output_schema( )) } -/// The one selector `expr` folds, if it names exactly one. +/// Every selector `expr` reads, in the order the compiler binds them. /// -/// The walk follows the grammar the native compiler accepts — a call, a range selector, a selector -/// and parentheses — and stops at every other shape, because a shape the compiler cannot compile -/// needs no selector resolved. Two distinct selectors are not one input, and a tree built over the -/// wrong one of them would evaluate a window the query did not write. -fn selector_range_millis(expr: &PromExpr) -> Option { +/// The order is the compiler's own: it compiles a node's operands in the order they were written, so +/// this walk goes into the same children in the same order. The list is then matched position by +/// position against the compiled inputs, which is what makes a walk that visits a different set the +/// signal that the two disagree rather than a silent mismatch of selector to scan. +fn collect_selectors<'a>(expr: &'a PromExpr, out: &mut Vec<&'a VectorSelector>) { match expr { - PromExpr::MatrixSelector(matrix) => Some(matrix.range.as_millis() as i64), - PromExpr::Paren(paren) => selector_range_millis(&paren.expr), - PromExpr::Call(call) => call - .args - .args - .iter() - .find_map(|arg| selector_range_millis(arg)), - _ => None, + PromExpr::VectorSelector(selector) => out.push(selector), + PromExpr::MatrixSelector(MatrixSelector { vs, .. }) => out.push(vs), + PromExpr::Paren(ParenExpr { expr }) => collect_selectors(expr, out), + // Left before right, because a non-commutative operator means what that order says. + PromExpr::Binary(binary) => { + collect_selectors(&binary.lhs, out); + collect_selectors(&binary.rhs, out); + } + // The compiler folds a negation into a multiplication whose operand comes second, but the + // selector is the only thing this walk collects, so the order inside one subtree does not + // depend on where the constant sits. + PromExpr::Unary(unary) => collect_selectors(&unary.expr, out), + PromExpr::Call(call) => { + // A label rewrite adds a label the node's output schema cannot declare: that schema is + // built from the table's own tags, so folding `label_replace`/`label_join` in would + // silently drop the destination label the existing plan projects. + if matches!(call.func.name, "label_replace" | "label_join") { + return; + } + for arg in &call.args.args { + collect_selectors(arg, out); + } + } + // An aggregate's parameter is a constant, so only its input holds a selector. + PromExpr::Aggregate(aggregate) => collect_selectors(&aggregate.expr, out), + // A subquery evaluates its own expression on a grid of its own, and the compiler binds that + // expression's selectors before the window above them. + PromExpr::Subquery(subquery) => collect_selectors(&subquery.expr, out), + _ => {} } } @@ -455,35 +697,6 @@ fn metric_scan_and_table_id( Some((scan.clone(), filter.predicate.clone())) } -fn single_selector(expr: &PromExpr) -> Option<&VectorSelector> { - let mut selectors = Vec::new(); - collect_selectors(expr, &mut selectors); - match selectors.as_slice() { - [only] => Some(only), - _ => None, - } -} - -fn collect_selectors<'a>(expr: &'a PromExpr, out: &mut Vec<&'a VectorSelector>) { - match expr { - PromExpr::VectorSelector(selector) => out.push(selector), - PromExpr::MatrixSelector(MatrixSelector { vs, .. }) => out.push(vs), - PromExpr::Paren(ParenExpr { expr }) => collect_selectors(expr, out), - PromExpr::Call(call) => { - // A label rewrite adds a label the node's output schema cannot declare: that schema is - // built from the table's own tags, so folding `label_replace`/`label_join` in would - // silently drop the destination label the existing plan projects. - if matches!(call.func.name, "label_replace" | "label_join") { - return; - } - for arg in &call.args.args { - collect_selectors(arg, out); - } - } - _ => {} - } -} - #[cfg(test)] mod tests { use std::sync::Arc; diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index 6a77ce48cc8..d0e530db7e0 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -1792,6 +1792,55 @@ fn find_fused_series(plan: &LogicalPlan) -> Option<&FusedSeries> { plan.inputs().into_iter().find_map(find_fused_series) } +#[tokio::test] +async fn native_fused_binary_has_two_independent_scans() { + let plan = build_native_fused_plan("some_metric + some_metric", true).await; + let fused = find_fused_series(&plan).expect("binary query uses native route"); + assert_eq!(2, fused.fused_inputs().len()); +} + +#[tokio::test] +async fn native_fused_binary_matchers_are_per_scan() { + let plan = build_native_fused_plan( + "some_metric{tag_0=\"a\"} + on(tag_0) some_metric{tag_0=\"b\"}", + true, + ) + .await; + let fused = find_fused_series(&plan).expect("native binary fused route"); + assert_eq!(2, fused.fused_inputs().len()); + let scans = fused + .fused_inputs() + .iter() + .map(|input| match &input.input { + LogicalPlan::TableScan(scan) => scan, + other => panic!("expected TableScan, got {other:?}"), + }) + .collect::>(); + assert_eq!(2, scans[0].filters.len()); + assert_eq!(2, scans[1].filters.len()); + let left = scans[0] + .filters + .iter() + .map(ToString::to_string) + .collect::>() + .join(" AND "); + let right = scans[1] + .filters + .iter() + .map(ToString::to_string) + .collect::>() + .join(" AND "); + assert!(left.contains("a"), "{left}"); + assert!(right.contains("b"), "{right}"); + assert_ne!(left, right); +} + +#[tokio::test] +async fn native_fused_binary_flag_off_has_no_fused_node() { + let plan = build_native_fused_plan("some_metric + some_metric", false).await; + assert!(find_fused_series(&plan).is_none()); +} + /// The flag on and a shape the compiler accepts: the statement plans to one native node. #[tokio::test] async fn native_fused_rate_plans_to_a_fused_series_node() { @@ -2190,12 +2239,15 @@ async fn native_fused_whole_vector_operation_falls_back() { #[tokio::test] async fn native_fused_unsupported_shape_falls_back() { - let plan = build_native_fused_plan("sum(rate(some_metric[5m]))", true).await; + // A set operator combines two vectors' series rather than their values, which no node of the + // tree does, so this is a shape the compiler names and declines. + let query = "some_metric and on(tag_0) some_metric"; + let plan = build_native_fused_plan(query, true).await; let display = plan.display_indent().to_string(); assert!(!display.contains("FusedSeries"), "{display}"); // Falling back is not an approximation of the existing plan: it is the existing plan. - let without_flag = build_native_fused_plan("sum(rate(some_metric[5m]))", false).await; + let without_flag = build_native_fused_plan(query, false).await; assert_eq!(display, without_flag.display_indent().to_string()); }