From 06b28e08d8adefcb332e6d997daf511fc62824d5 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:01:43 +0800 Subject: [PATCH] refactor(promql): bind fused inputs by execution source index Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/promql/AGENTS.md | 39 +- src/promql/src/extension_plan.rs | 4 +- src/promql/src/extension_plan/fused_series.rs | 811 ++++---- .../src/extension_plan/fused_series/tests.rs | 1655 ++++++++--------- src/promql/src/extension_plan/planner.rs | 54 +- src/promql/src/native/display.rs | 29 +- src/promql/src/native/display/tests.rs | 96 +- src/promql/src/native/execute.rs | 95 + src/promql/src/native/execute/tests.rs | 346 ++++ src/promql/src/native/metrics.rs | 1 + src/promql/src/native/plan.rs | 5 + src/promql/src/native/plan/tests.rs | 7 + src/promql/tests/native_binary.rs | 1 + src/query/src/dist_plan/analyzer.rs | 21 +- src/query/src/dist_plan/commutativity.rs | 154 +- src/query/src/optimizer/scan_hint.rs | 23 +- src/query/src/promql/native_compile.rs | 38 +- src/query/src/promql/native_compile/tests.rs | 63 +- src/query/src/promql/planner/native.rs | 390 ++-- src/query/src/promql/planner/test.rs | 114 +- src/query/tests/native_multi_selector.rs | 28 +- 21 files changed, 2392 insertions(+), 1582 deletions(-) diff --git a/src/promql/AGENTS.md b/src/promql/AGENTS.md index 53e7c663309..d45f636b698 100644 --- a/src/promql/AGENTS.md +++ b/src/promql/AGENTS.md @@ -31,16 +31,18 @@ operators. Statement-to-plan translation lives in `src/query/src/promql/`. options are enabled and the per-request `query.experimental_native_promql` extension is true. Accepted plans use process-local `FusedSeries`; declined or unsupported shapes fall back to the existing planner. `compile_selectors` - binds each selector to its own scan, and the route accepts one selector over a - direct scan with a bound metric name, or two occurrences of one selector when - both read one identical final scan, matched one-to-one over the whole series - identity with a point-wise operand on each side. Label matchers are not a - reason to decline: each scan applies its own. Only trees that read one series at - a time are admitted, so an aggregate or a whole-vector operation (`sort`, - `absent`, ...) anywhere in the tree falls back, as does an ineligible - raw-series table/field set or an unsupported expression/grid. Metric scans - retain the static `__table_id` predicate. Hybrid CTEs and CREATE VIEW TQL - creation currently fall back to the existing planner. + binds each selector to its own scan and stamps that scan's position on the + tree input it creates (`BoundInput::source_index`), so `FusedSeries` holds one + logical child per index and the tree itself says which child feeds which input. + The route accepts one selector over a direct scan with a bound metric name, or + two occurrences of one selector when both read one identical final scan, + matched one-to-one over the whole series identity with a point-wise operand on + each side. Label matchers are not a reason to decline: each scan applies its + own. Only trees that read one series at a time are admitted, so an aggregate + or a whole-vector operation (`sort`, `absent`, ...) anywhere in the tree falls + back, as does an ineligible raw-series table/field set or an unsupported + expression/grid. Metric scans retain the static `__table_id` predicate. Hybrid + CTEs and CREATE VIEW TQL creation currently fall back to the existing planner. ## Change coupling @@ -56,6 +58,16 @@ operators. Statement-to-plan translation lives in `src/query/src/promql/`. - A new logical node also needs its physical planner reachable from `DfQueryPlanner::create_physical_plan`, assembled in `src/query/src/query_engine/state.rs`. +- A fused plan's inputs are described once. `BoundInput::source_index` names which + source of one `NativeExecutor` invocation produced an input's chunks; + `FusedSeries` maps that index to its DataFusion child by position, and the + raw-series schema the input was compiled against is the layout its frame is + decoded with. Neither the logical node nor `FusedSeriesExec` therefore keeps a + per-child schema or destination list, while the binding's grid, time column, + tags and metric name and the executor's `(plan, RawLabelSource, SeriesOrdering)` + tuple stay as they are. A change to how a source is bound touches `BoundInput` + (its `ordering` included, which the executor checks against the producer), + `FusedSeries`'s source walk and the executor's `push_raw_source` together. ## Gotchas @@ -66,6 +78,13 @@ operators. Statement-to-plan translation lives in `src/query/src/promql/`. its doc is written for a caller that does not exist. - **A native window requires non-interleaved input.** Only `Contiguous` and `KeyThenTime` are accepted; `Interleaved` is refused when compiled. +- **A fused tree is logical over N sources, physical over one.** `FusedSeries` + accepts one child per source index, but `FusedSeriesExec` runs exactly one + child, at that child's own partition count, and queues its chunks with + `NativeExecutor::push_raw_source(0, ..)`. A second source (needs a + label-pairing exchange) and a constant scalar (needs a scalar-to-batch + conversion) are refused when the physical node is built, never answered with + an empty result. - **A series closes exactly once**, on the chunk that says so — per input series, not per label set. A node that rewrites labels can hand two input series over under one label set, and each closes on its own chunk, so a label set may be diff --git a/src/promql/src/extension_plan.rs b/src/promql/src/extension_plan.rs index 11bcf7fbaeb..baf57a275c8 100644 --- a/src/promql/src/extension_plan.rs +++ b/src/promql/src/extension_plan.rs @@ -38,9 +38,7 @@ 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, FusedSeriesInput, FusedSeriesStream, -}; +pub use fused_series::{FusedSeries, FusedSeriesBinding, FusedSeriesExec, 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 594208f031a..c307f65d32a 100644 --- a/src/promql/src/extension_plan/fused_series.rs +++ b/src/promql/src/extension_plan/fused_series.rs @@ -15,16 +15,18 @@ //! One node that runs a compiled native tree over raw series. //! //! [`FusedSeries`] is the logical half: it holds the PromQL text the tree was compiled from, the -//! tree itself and the binding its input was compiled against. [`FusedSeriesExec`] is the physical -//! half: it owns one execution of that tree per partition and decodes its input frames into raw -//! series chunks and converts its evaluated chunks back into batches. +//! tree itself, the binding it was compiled against and one logical child per actual source. +//! [`FusedSeriesExec`] is the physical half: it owns one execution of that tree per partition and +//! decodes its input frames into raw series chunks and converts its evaluated chunks back into +//! batches. //! -//! One actual source can feed several tree inputs: a query that names the same selector twice reads -//! the same series twice. The binding therefore lists the tree input nodes its one plan feeds, and -//! the node runs that plan once and queues the chunks it produced at every one of those positions. -//! Several actual sources stay several plans: they run only when each has a single partition, so -//! that one execution of the tree sees every series of every source and a match pairs them by -//! label, which is the only pairing this node has. +//! Which child produces a tree input is the input's own `source_index`, not a list beside the tree: +//! one actual source can feed several tree inputs - a query that names the same selector twice reads +//! the same series twice - so the tree says where every chunk goes. The logical node keeps its +//! children in that index order and checks that every index is bound. The physical node runs one +//! child: a second child would have to pair its series with the first by label, which needs an +//! exchange this node does not have, and no child at all is a constant scalar, whose rows the +//! conversion does not produce yet. //! //! The two halves show different things in `EXPLAIN`, which is the point of having both. The //! logical node prints the query a reader wrote ([`FusedSeries`]'s `fmt_for_explain`), and the @@ -59,8 +61,8 @@ use datafusion::arrow::array::{ use datafusion::arrow::buffer::ScalarBuffer; use datafusion::arrow::datatypes::{DataType, SchemaRef, TimeUnit}; use datafusion::arrow::record_batch::RecordBatch; -use datafusion::common::DFSchemaRef; use datafusion::common::tree_node::TreeNodeRecursion; +use datafusion::common::{DFSchema, DFSchemaRef}; use datafusion::error::{DataFusionError, Result as DataFusionResult}; use datafusion::execution::context::TaskContext; use datafusion::execution::memory_pool::{ @@ -79,14 +81,13 @@ use datatypes::series::raw::RawSeriesChunk; use datatypes::series::samples::{DenseSamplesRef, SampleRef, Samples, Series, SeriesSchema}; use datatypes::series::time::EvalGrid; use futures::Stream; -use futures::stream::{SelectAll, StreamExt}; -use store_api::region_engine::RawLabelSource; +use store_api::region_engine::{RawLabelSource, SendableRawSeriesStream}; use crate::evaluated::EvaluatedChunk; use crate::grid_series::{LabelSet, label_set}; use crate::native::execute::{NativeExecutionState, NativeExecutor}; use crate::native::metrics::{self, NodePath}; -use crate::native::plan::{NativeExpr, NativeTree}; +use crate::native::plan::{NativeExpr, NativeTree, NativeType}; use crate::native::runs::{Run, absorb}; use crate::source::materialize_raw_labels; @@ -101,43 +102,36 @@ const METRIC_NAME: &str = "__name__"; /// A chunk that settles no batch is the cost this bounds: raw samples before the first evaluation /// point settle nothing, so an input of many such chunks would otherwise be read to its end inside /// one poll, holding the task's thread for an unbounded time and delaying both other tasks on it -/// and the cancellation the consumer asked for. The budget does not bound how many child streams -/// [`SelectAll`](futures::stream::SelectAll) polls to find readiness; it bounds only the chunks -/// this node hands to the executor. A poll that stops early wakes itself, so nothing is lost. +/// and the cancellation the consumer asked for. The budget bounds only the chunks this node hands +/// to the executor. A poll that stops early wakes itself, so nothing is lost. const POLL_BUDGET: usize = 64; -/// One actual source's decoded chunks, tagged with the tree input nodes they queue at. +/// What the tree was compiled against, and how its output columns are named. /// -/// The tag is a list because one source can feed several tree inputs: the chunks are the same rows -/// at each of them, which is what reading one series twice means. -type TaggedInputStream = Pin< - Box< - dyn Stream< - Item = ( - Vec, - Result, - ), - > + Send, - >, ->; - -/// What the tree's input was compiled against, and how its output columns are named. +/// The binding travels with the tree: a tree is legal only on the grid it was bound to, and a +/// reader of the output needs to know which grid a chunk's absolute positions are on. Keeping these +/// four facts in one value is what lets the logical node carry what the writer decided and the +/// physical node take the same output columns from it. /// -/// The binding travels with the tree: a tree is legal only against the schema it was bound to, and -/// a reader of the output needs to know which grid a chunk's absolute positions are on. Keeping it -/// in one value is what lets the logical node be built from the same description, and the physical -/// node reads the same facts back off the tree rather than trusting a second copy of them. +/// It is not a mirror of any schema: the raw layout a frame is decoded with is the one the tree's +/// own input declares, read back off the tree on both sides. What the binding cannot check is +/// whether the caller named the metric and tags the query meant, or whether [`time_index`] is the +/// column the query reports positions in - from here both are indistinguishable from a correct +/// binding, so picking them is the caller's obligation. /// -/// What the logical node checks is that the schema the tree's input node declares is the one this -/// binding names. What it cannot check is whether the caller meant *some other* schema with the -/// same field names, or whether [`time_index`](Self::time_index) is the column the query reports -/// positions in: from here both are indistinguishable from a correct binding, so picking them is -/// the caller's obligation. The physical node reads neither the metric name nor a time column from -/// the input — a raw frame carries the labels of each series and its own timestamps. +/// [`metric_name`]: Self::metric_name +/// [`tags`]: Self::tags +/// [`time_index`]: Self::time_index #[derive(Clone, Debug)] pub struct FusedSeriesBinding { /// The statement's evaluation grid. pub grid: Arc, + /// The output column holding the grid timestamps. + pub time_index: String, + /// The logical tag columns of the output, `__name__` included when the query reports it. + pub tags: Vec, + /// The metric name the scans below are read under, when the query binds one. + pub metric_name: Option>, } impl PartialEq for FusedSeriesBinding { @@ -145,6 +139,9 @@ impl PartialEq for FusedSeriesBinding { 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) + && self.time_index == other.time_index + && self.tags == other.tags + && self.metric_name == other.metric_name } } impl Eq for FusedSeriesBinding {} @@ -152,48 +149,48 @@ impl Hash for FusedSeriesBinding { fn hash(&self, state: &mut H) { let s = self.grid.spec(); (s.start_ms, s.step_ms, s.len).hash(state); + self.time_index.hash(state); + self.tags.hash(state); + self.metric_name.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)) + match (a.start_ms, a.step_ms, a.len).partial_cmp(&(b.start_ms, b.step_ms, b.len)) { + 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, + } + self.metric_name + .as_deref() + .partial_cmp(&other.metric_name.as_deref()) } } -/// 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 tree input nodes this one plan feeds. - /// - /// One actual source may be read at several tree inputs - a query that names the same selector - /// twice reads the same series twice - so a binding lists the destinations rather than owning - /// one. The list is never empty, and the destinations together are exactly the tree's raw - /// inputs, one binding each. - pub paths: Vec, -} - /// The logical plan of one node that runs a compiled native tree. /// /// The node adds nothing to the tree: it records the query the tree was compiled from, so /// `EXPLAIN` shows the reader their own query rather than the shape it compiled to, and it carries -/// the binding the tree's input was compiled against so the execution plan can be built from it. +/// the binding the tree was compiled against so the execution plan can be built from it. #[derive(Debug)] pub struct FusedSeries { /// The PromQL text this tree was compiled from. promql: Arc, /// The compiled tree to run. tree: NativeTree, - /// What the tree's input was compiled against. + /// What the tree was compiled against. binding: FusedSeriesBinding, - /// The plan producing the input series. - inputs: Vec, + /// The plans producing the input series, one per source index the tree binds. + children: Vec, /// The columns this node produces. output_schema: DFSchemaRef, } @@ -204,20 +201,24 @@ impl FusedSeries { "FusedSeries" } - /// Creates the node, checking that `tree` is legal against `binding`. + /// Creates the node, checking that `tree` is legal against `binding` and `children`. + /// + /// The children are the tree's actual sources, in `source_index` order: which child feeds which + /// tree input is the input's own index, so this list carries no per-child description a caller + /// could let drift from the tree. pub fn try_new( promql: Arc, tree: NativeTree, binding: FusedSeriesBinding, - inputs: Vec, + children: Vec, output_schema: DFSchemaRef, ) -> DataFusionResult { - validate_binding(&tree, &binding, &inputs)?; + validate_binding(&tree, &binding, &children)?; Ok(Self { promql, tree, binding, - inputs, + children, output_schema, }) } @@ -232,67 +233,47 @@ impl FusedSeries { &self.tree } - /// What the tree's input was compiled against. + /// What the tree was compiled against. pub fn binding(&self) -> &FusedSeriesBinding { &self.binding } - pub fn fused_inputs(&self) -> &[FusedSeriesInput] { - &self.inputs + + /// The plans producing the input series, in `source_index` order. + pub fn children(&self) -> &[LogicalPlan] { + &self.children } - /// The physical node that runs `exec_inputs` as this node's inputs. + /// The physical node that runs `exec_children` as this node's children. /// - /// One execution input per bound source, in the order the bindings are listed. `label_source` - /// and `ordering` are the binding of the frames `exec_input` produces: the frame carries the - /// encoded key and, in explicit mode, the complete labels, but no schema can say which of the - /// two a producer meant or how it ordered the series, so the caller that built the frame passes - /// both on. Building the node rejects a tree the runtime cannot execute, a frame schema the - /// tree's input was not compiled against, and a schema the conversion cannot classify, so a - /// plan that is built is a plan that runs. + /// One execution input per child, in source order. `label_source` and `ordering` are the + /// binding of the frames that child produces: the frame carries the encoded key and, in explicit + /// mode, the complete labels, but no schema can say which of the two a producer meant or how it + /// ordered the series, so the caller that built the frame passes both on. Building the node + /// rejects a tree the runtime cannot execute, a frame schema the tree's input was not compiled + /// against, and a schema the conversion cannot classify, so a plan that is built is a plan that + /// runs. pub fn to_execution_plan( &self, - exec_inputs: Vec<(Arc, RawLabelSource, SeriesOrdering)>, + exec_children: Vec<(Arc, RawLabelSource, SeriesOrdering)>, ) -> DataFusionResult> { // Arity is checked before the two lists are paired: a zip would silently drop whichever side - // is longer, and a node built from fewer inputs than it binds would run a tree over half its - // sources. - if exec_inputs.len() != self.inputs.len() { + // is longer, and a node built from fewer children than it binds would run a tree over half + // its sources. + if exec_children.len() != self.children.len() { return Err(DataFusionError::Plan(format!( "FusedSeries binds {} inputs, but {} execution inputs were given", - self.inputs.len(), - exec_inputs.len() + self.children.len(), + exec_children.len() ))); } let output_schema: SchemaRef = self.output_schema.inner().clone(); - let bound = self - .inputs - .iter() - .zip(exec_inputs) - .map(|(input, (exec, source, ordering))| { - ( - exec, - source, - ordering, - // The destinations are the binding's own, not read off the tree again: which - // tree input a source feeds is a fact the binding carries, and a traversal - // would have to agree with it rather than replace it. - input.paths.clone(), - Arc::clone(&input.series_schema), - ) - }) - .collect(); - let Some(first) = self.inputs.first() else { - return Err(DataFusionError::Plan( - "FusedSeries binds no input to run its tree over".to_string(), - )); - }; Ok(Arc::new(FusedSeriesExec::try_new( Arc::clone(&self.promql), - bound, + exec_children, Arc::new(self.tree.clone()), output_schema, - first.time_index.clone(), - first.tags.clone(), + self.binding.time_index.clone(), + self.binding.tags.clone(), )?)) } } @@ -303,7 +284,7 @@ impl UserDefinedLogicalNodeCore for FusedSeries { } fn inputs(&self) -> Vec<&LogicalPlan> { - self.inputs.iter().map(|input| &input.input).collect() + self.children.iter().collect() } fn schema(&self) -> &DFSchemaRef { @@ -325,25 +306,15 @@ impl UserDefinedLogicalNodeCore for FusedSeries { _exprs: Vec, inputs: Vec, ) -> DataFusionResult { - if inputs.len() != self.inputs.len() { + if inputs.len() != self.children.len() { return Err(DataFusionError::Internal(format!( "FusedSeries expected {} inputs", - self.inputs.len() + self.children.len() ))); } - let inputs = self - .inputs - .iter() - .cloned() - .zip(inputs) - .map(|(mut binding, input)| { - binding.input = input; - binding - }) - .collect(); - // Rebuilt rather than patched: the destinations the bindings name are checked against the - // tree again, and the schema the node reports keeps its metadata. A rewrite that changed an - // input's shape therefore cannot leave a binding the tree no longer covers. + // Rebuilt rather than patched: the sources each tree input names are checked against the + // tree again, and the schema the node reports keeps its metadata. A rewrite that changed a + // child's shape therefore cannot leave a tree whose raw inputs no longer fit it. Self::try_new( Arc::clone(&self.promql), self.tree.clone(), @@ -357,21 +328,14 @@ impl UserDefinedLogicalNodeCore for FusedSeries { impl PartialEq for FusedSeries { fn eq(&self, other: &Self) -> bool { // `NativeTree` carries no structural equality, so the rendered tree stands in for it. The - // renderer names every node with its bound operation and grids, which is what makes two - // nodes the same computation; comparing the text alone would call two different trees - // equal whenever their PromQL happens to read the same. + // renderer names every node with its bound operation, its grids and the source index its + // input reads, which is what makes two nodes the same computation; comparing the PromQL + // text alone would call two different trees equal whenever their query happens to read the + // same. self.promql == other.promql && self.tree.to_string() == other.tree.to_string() && self.binding == other.binding - && 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 - && a.paths == b.paths - && same_schema_fields(&a.series_schema, &b.series_schema) - }) + && self.children == other.children && self.output_schema == other.output_schema } } @@ -382,13 +346,7 @@ impl Hash for FusedSeries { fn hash(&self, state: &mut H) { self.promql.hash(state); self.binding.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); - input.paths.hash(state); - } + self.children.hash(state); self.output_schema.hash(state); } } @@ -399,31 +357,14 @@ impl PartialOrd for FusedSeries { Some(Ordering::Equal) => {} ord => return ord, } - 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, - )) { + match self.binding.partial_cmp(&other.binding) { Some(Ordering::Equal) => {} ord => return ord, } - match self.inputs.len().partial_cmp(&other.inputs.len()) { + match self.children.partial_cmp(&other.children) { 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 - || mine.paths != theirs.paths - || !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, @@ -436,22 +377,16 @@ impl PartialOrd for FusedSeries { } } -/// Checks that `bindings` names exactly the raw inputs of `tree`, each destination once. +/// The raw series schema each source index of `tree` reads, in source order. /// -/// A binding is one actual source and the destinations it feeds, so what has to hold is that every -/// binding lists at least one destination, that no destination is listed twice or is not an input of -/// this tree, that no input is left without a source, and that the schema a destination was compiled -/// against is the one its source was bound to. Nothing here depends on the order of the walk or of a -/// binding's list: each destination is looked up by its path, so neither list has to agree with the -/// other position by position. -fn validate_paths<'a>( - tree: &NativeTree, - bindings: impl IntoIterator, -) -> DataFusionResult<()> { - // The tree is the one authority on where its inputs sit and what they read: a caller's binding - // 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. - let mut nodes: Vec<(NodePath, Arc)> = Vec::new(); +/// A derived view, never stored: the tree is the one authority on where its inputs sit, what they +/// read and which child produces them, so both halves read it here instead of each keeping a copy +/// that could drift. The result is `source_index`-indexed rather than in visit order, and it is +/// exactly `0..len` - a tree that binds index `n` without binding every index below it is refused, +/// since a child at an index no input reads would be a source the tree cannot use. A caller +/// comparing it to a child list therefore only has to check that the lengths agree. +fn tree_sources(tree: &NativeTree) -> DataFusionResult>> { + let mut inputs: Vec<(usize, NodePath, Arc)> = Vec::new(); let mut not_raw: Option = None; metrics::walk(tree.root(), &mut |node, path| { if let NativeExpr::Input(input) = &node.expr { @@ -460,7 +395,7 @@ fn validate_paths<'a>( .samples() .filter(|schema| schema.eval_grid.is_none()) { - Some(schema) => nodes.push((path.clone(), Arc::clone(schema))), + Some(schema) => inputs.push((input.source_index, path.clone(), Arc::clone(schema))), None => { not_raw.get_or_insert_with(|| path.clone()); } @@ -472,46 +407,84 @@ fn validate_paths<'a>( "FusedSeries runs a tree whose input `{path}` is not raw series" ))); } - if nodes.is_empty() { - return Err(DataFusionError::Plan( - "FusedSeries runs a tree with 0 inputs, and it needs at least one".to_string(), - )); + // Indexed rather than pushed in visit order: a binary node whose operands name sources 1 and 0 + // is the same legal tree as one naming them 0 and 1, and only the set of indices says so. + // + // Every index is bounded by the number of input occurrences first, before any width is computed + // or any slot is sized. A dense `0..n` set has n values of at most `n - 1`, so a legal tree + // always satisfies this; a tree naming `usize::MAX` or one far past its own input count is + // refused here instead of overflowing `index + 1` or reserving slots for indices no input reads. + if let Some((index, path, _)) = inputs.iter().find(|entry| entry.0 >= inputs.len()) { + return Err(DataFusionError::Plan(format!( + "FusedSeries tree binds source index {index} at `{path}`, but it reads {} inputs in \ + total: every source index has to be below that count", + inputs.len() + ))); } - let mut covered: Vec> = vec![None; nodes.len()]; - for (index, paths, schema) in bindings { - if paths.is_empty() { - return Err(DataFusionError::Plan(format!( - "FusedSeries input {index} names no tree input path" - ))); - } - for path in paths { - let Some(at) = nodes.iter().position(|(node, _)| node == path) else { - return Err(DataFusionError::Plan(format!( - "FusedSeries input {index} names `{path}`, which is not an input of its tree" - ))); - }; - if covered[at].is_some() { - return Err(DataFusionError::Plan(format!( - "FusedSeries binds the tree input `{path}` more than once" - ))); + let width = inputs + .iter() + .map(|(index, ..)| index + 1) + .max() + .unwrap_or_default(); + let mut slots: Vec)>> = vec![None; width]; + for (index, path, schema) in inputs { + match &slots[index] { + Some((first, declared)) => { + // One child can be read more than once, and both reads have to see the same layout: + // the one frame this child produces is decoded once, so a second schema would name + // a column the decode never fills. + if !same_schema_fields(declared, &schema) { + return Err(DataFusionError::Plan(format!( + "FusedSeries tree reads source {index} at `{first}` and `{path}` through two \ + raw series schemas, and one child has one layout" + ))); + } } - covered[at] = Some((index, schema)); + None => slots[index] = Some((path, schema)), } } - for ((path, schema), bound) in nodes.iter().zip(covered) { - let Some((index, declared)) = bound else { - return Err(DataFusionError::Plan(format!( - "FusedSeries binds no source for the tree input `{path}`" - ))); - }; - if !same_schema_fields(schema, declared) { - return Err(DataFusionError::Plan(format!( - "FusedSeries input {index} binds a raw series schema the tree's input `{path}` was \ - not compiled against" - ))); - } - } - Ok(()) + slots + .into_iter() + .enumerate() + .map(|(index, slot)| match slot { + Some((_, schema)) => Ok(schema), + // `width` is the largest bound index plus one, so every hole has a bound index above + // it: the refused tree binds a source without the ones below it. + None => Err(DataFusionError::Plan(format!( + "FusedSeries tree binds source index {}, but not every index below it: source \ + {index} is unbound", + width - 1 + ))), + }) + .collect() +} + +/// The raw series field names each source index of `tree` reads, in source order. +/// +/// A caller asks the scan below for exactly these columns, so they are read off the tree that will +/// consume them rather than kept in a second description beside it. +pub(crate) fn tree_source_fields(tree: &NativeTree) -> DataFusionResult>> { + Ok(tree_sources(tree)? + .into_iter() + .map(|schema| { + schema + .fields + .iter() + .map(|field| field.name.to_string()) + .collect() + }) + .collect()) +} + +/// Whether `tree` is the constant scalar `grid` claims and reads no raw input at all. +/// +/// A scalar is declared by the type that produces it, not by a child: what makes one constant is +/// that it is a bound [`NativeExpr::Scalar`], so this is the one tree that can be legal with no +/// child. A tree whose root is samples cannot be: samples with no input would be an empty vector +/// reported as an answer, which is the shape this node must never invent. +fn is_constant_scalar(tree: &NativeTree, grid: &EvalGrid) -> bool { + matches!(tree.root().expr, NativeExpr::Scalar(_)) + && matches!(&tree.root().output, NativeType::Scalar(spec) if spec.spec() == grid.spec()) } /// Refuses a tree whose logical series can be split across the partitions this node runs. @@ -621,7 +594,35 @@ fn same_schema_fields(left: &SeriesSchema, right: &SeriesSchema) -> bool { .all(|(a, b)| a.name == b.name) } -/// Checks that `tree` reads the schema `binding` declares, on the grid it declares. +/// Whether `schema` carries a field named `name`, as a column or inside a struct column. +/// +/// A table scan names each series field as a column of its own, while a raw series frame names them +/// inside its `fields` struct: both can hand the tree the field it read, and a child that names it +/// nowhere cannot. This asks whether the layout can produce a field, which is all the tree needs; a +/// label identity is not read off a schema, so nothing here stands in for a label binding. +fn carries_field(schema: &DFSchema, name: &str) -> bool { + fn inside(data_type: &DataType, name: &str) -> bool { + match data_type { + DataType::Struct(fields) => fields + .iter() + .any(|field| field.name().as_str() == name || inside(field.data_type(), name)), + DataType::List(element) => inside(element.data_type(), name), + _ => false, + } + } + schema + .fields() + .iter() + .any(|field| field.name().as_str() == name || inside(field.data_type(), name)) +} + +/// Checks that `tree` reads what `children` can give it, on the grid `binding` declares. +/// +/// The tree names its sources: every raw input carries the `source_index` of the child that feeds +/// it, so what has to hold is that each of those indices names one of `children`, that every child +/// is read by at least one input, and that the child at an index can produce the fields the inputs +/// bound to it read. A tree with no raw input at all is legal only as a constant scalar, which reads +/// nothing and is the one shape whose every row the node can produce without a child. /// /// The output grid is compared by [`EvalGrid::spec`], not by allocation: that is the rule /// [`NativeTree`]'s own validation and the kernels apply, and a chunk's timestamps already come @@ -630,39 +631,55 @@ fn same_schema_fields(left: &SeriesSchema, right: &SeriesSchema) -> bool { fn validate_binding( tree: &NativeTree, binding: &FusedSeriesBinding, - inputs: &[FusedSeriesInput], + children: &[LogicalPlan], ) -> DataFusionResult<()> { - // The destinations are checked first, so a binding that names the wrong tree input is refused - // before anything is read off the input it names. - validate_paths( - tree, - inputs - .iter() - .enumerate() - .map(|(index, input)| (index, input.paths.as_slice(), input.series_schema.as_ref())), - )?; - for declared in inputs { - if declared.series_schema.eval_grid.is_some() { + if binding.tags.iter().any(|tag| tag == METRIC_NAME) && binding.metric_name.is_none() { + return Err(DataFusionError::Plan(format!( + "FusedSeries declares a {METRIC_NAME:?} tag column but binds no metric name" + ))); + } + // The sources are read first, so a child list of the wrong length is refused before anything is + // read off the children it names. + let sources = tree_sources(tree)?; + if sources.is_empty() { + if !children.is_empty() { + return Err(DataFusionError::Plan(format!( + "FusedSeries runs a tree that reads no source, but {} children were given", + children.len() + ))); + } + if !is_constant_scalar(tree, &binding.grid) { return Err(DataFusionError::Plan( - "FusedSeries binds a raw series schema, which cannot have an evaluation grid" + "FusedSeries runs a tree that reads no source, and only a constant scalar on the \ + statement's grid is legal without one" .to_string(), )); } - if declared.tags.iter().any(|tag| tag == METRIC_NAME) && declared.metric_name.is_none() { + } else { + if children.len() != sources.len() { return Err(DataFusionError::Plan(format!( - "FusedSeries declares a {METRIC_NAME:?} tag column but binds no metric name" + "FusedSeries runs a tree that reads {} sources, but {} children were given", + sources.len(), + children.len() ))); } - } - match tree.root().output.samples() { - Some(schema) - if schema - .eval_grid - .as_ref() - .is_some_and(|grid| grid.spec() == binding.grid.spec()) => - { - Ok(()) + for (index, (source, child)) in sources.iter().zip(children).enumerate() { + // Which child a tree input reads is the input's own index, so a field it declared has + // to be one *that* child can produce: reading it off another child, or off the tree + // alone, would decode a frame the child never produced. + for field in source.fields.iter() { + if !carries_field(child.schema(), field.name.as_ref()) { + return Err(DataFusionError::Plan(format!( + "FusedSeries child {index} has no column {:?} for the field the tree input \ + bound to it reads", + field.name + ))); + } + } } + } + match tree.root().output.grid() { + Some(grid) if grid.spec() == binding.grid.spec() => Ok(()), _ => Err(DataFusionError::Plan( "FusedSeries runs a tree whose output is not evaluated on the statement's grid" .to_string(), @@ -816,33 +833,18 @@ 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 nodes the chunks are queued at - one -/// actual source may feed several destinations - 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, - Vec, - 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, - input_bindings: Vec<( - Arc, - RawLabelSource, - SeriesOrdering, - Vec, - )>, + /// The label source and ordering of each child's frames, in child order. + /// + /// The frame carries the encoded key and, in explicit mode, the complete labels, but no schema + /// can say which of the two a producer meant or how it ordered the series, so the caller that + /// built the frame passes both on and they are kept here to check a rebuilt child against. + child_bindings: Vec<(RawLabelSource, SeriesOrdering)>, /// 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 @@ -851,7 +853,7 @@ pub struct FusedSeriesExec { /// The tag column names, indexed by [`OutputColumn::Tag`]. tags: Arc<[String]>, /// The plans producing the raw series frames. - inputs: Vec>, + children: 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 @@ -873,32 +875,97 @@ impl FusedSeriesExec { /// [`RawLabelSource::Explicit`]. `time_column` and `tags` name the columns of the output, which /// is a row table rather than a frame. /// - /// A child lists the tree input nodes it feeds, so the number of children is the number of scans - /// and not the number of tree inputs. Several children run only when each has one partition: what - /// pairs a series of one source with the matching series of another is the label, and this node - /// has no exchange that would move them together, so it refuses that shape instead of pairing - /// whatever a partition happens to hold. + /// The children are the tree's sources in `source_index` order, so their number must be the + /// number of sources the tree reads. Exactly one is executed: a second child would have to pair + /// its series with the first by label, which needs an exchange this node does not have, and no + /// child at all is a constant scalar, whose rows the conversion does not produce yet. Both are + /// refused rather than answered with an empty result. + /// + /// Which frame layout the child must produce is not passed in: it is the raw series schema the + /// tree's own input was compiled against, so there is no second description to drift from it. + /// The ordering the caller declares is checked against every input node's binding, so a + /// producer weaker than one of them is refused before the tree reads a frame. /// /// The parameters stay separate because each is a fact its own caller has: the query, the plans /// 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. pub fn try_new( promql: Arc, - inputs: Vec, + children: Vec<(Arc, RawLabelSource, SeriesOrdering)>, tree: Arc, output_schema: SchemaRef, time_column: String, tags: Vec, ) -> DataFusionResult { - validate_paths( - &tree, - inputs - .iter() - .enumerate() - .map(|(index, (_, _, _, paths, schema))| { - (index, paths.as_slice(), schema.as_ref()) - }), - )?; + // Several children are refused on their count alone, before the tree is walked: what they + // would need is an exchange that pairs their series by label, and no tree shape makes that + // available to this node. + if children.len() > 1 { + return Err(DataFusionError::Plan(format!( + "FusedSeriesExec reads {} sources as one tree: pairing several sources needs an \ + exchange that pairs their series by label, which this node does not have", + children.len() + ))); + } + let sources = tree_sources(&tree)?; + if children.len() != sources.len() { + return Err(DataFusionError::Plan(format!( + "FusedSeriesExec runs a tree that reads {} sources, but {} children were given", + sources.len(), + children.len() + ))); + } + // No child is a constant scalar: a tree this node cannot run at all, and refused before the + // output schema is read, so the refusal names the missing conversion rather than a column. + if children.is_empty() { + return Err(DataFusionError::Plan( + "FusedSeriesExec runs a tree that reads no source: a constant scalar's rows are not \ + produced by this node yet" + .to_string(), + )); + } + // One child and one tree source, which the arity check above has just made equal in count: + // taking both without indexing keeps this total even though neither can be empty here. + let (Some((child, source, ordering)), Some(tree_source)) = + (children.first(), sources.first()) + else { + return Err(DataFusionError::Plan( + "FusedSeriesExec runs a tree whose sources do not pair with its children" + .to_string(), + )); + }; + // The producer's ordering is a promise each input node was compiled against, so it has to + // satisfy every one of them, not only the input the frames happen to reach first: a stream + // that may interleave two series cannot feed a node that reads one series to its last chunk, + // and merely contiguous frames are not yet the identity-then-time order an input may be + // bound to. Only one child is executed, and `tree_sources` has just made every input's + // source index name one of them, so all of them read this child's ordering. + let producer = *ordering; + let mut ordering_error: Option = None; + metrics::walk(tree.root(), &mut |node, path| { + let NativeExpr::Input(bound) = &node.expr else { + return; + }; + let required = bound.ordering; + let satisfied = match required { + // The weakest guarantee asks nothing of the producer, and an input declaring + // `Interleaved` is refused when the run state is built rather than here. + SeriesOrdering::Interleaved => true, + SeriesOrdering::Contiguous => producer != SeriesOrdering::Interleaved, + SeriesOrdering::KeyThenTime => producer == SeriesOrdering::KeyThenTime, + }; + if !satisfied && ordering_error.is_none() { + let index = bound.source_index; + ordering_error = Some(format!( + "FusedSeriesExec reads source {index} through {producer:?} frames, but the tree \ + input at `{path}` was bound to {required:?} frames, which is a stronger ordering \ + the producer does not provide" + )); + } + }); + if let Some(message) = ordering_error { + return Err(DataFusionError::Plan(message)); + } let _ = NativeExecutionState::try_new( &tree, Arc::new(UnboundedMemoryPool::default()), @@ -920,76 +987,38 @@ impl FusedSeriesExec { })? .clone(); let classification = classify_output(&output_schema, &root_schema, &tags, &time_column)?; - for (index, (input, source, _, _, schema)) in inputs.iter().enumerate() { - if input.properties().partitioning.partition_count() == 0 { - return Err(DataFusionError::Plan(format!( - "FusedSeriesExec input {index} has no partitions" - ))); - } - 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 source 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, and a source - // that feeds several tree inputs feeds each of them the same chunks. Several sources cannot - // be executed that way without an exchange that pairs the matching series of each source, so - // they are refused unless each is one partition - there every series is in the one execution - // the tree sees, and a match pairs by label as it does in Prometheus. - let Some(first) = inputs.first() else { + let partition_count = child.properties().partitioning.partition_count(); + if partition_count == 0 { return Err(DataFusionError::Plan( - "FusedSeriesExec has no child to run its tree over".to_string(), + "FusedSeriesExec child has no partitions".to_string(), )); - }; - let partition_count = if inputs.len() == 1 { - first.0.properties().partitioning.partition_count() - } else { - if let Some((index, child)) = inputs - .iter() - .enumerate() - .find(|(_, child)| child.0.properties().partitioning.partition_count() > 1) - { - return Err(DataFusionError::Plan(format!( - "FusedSeriesExec reads {} sources as one tree, and input {index} has {} \ - partitions: pairing several sources needs an exchange that pairs their series \ - by label, which this node does not have", - inputs.len(), - child.0.properties().partitioning.partition_count() - ))); - } - 1 - }; + } + // The frame is checked against the schema the tree's own input was compiled against, which + // is the one the decoder is given in `execute`: no other schema is stored, so a child that + // changed shape cannot be decoded with a stale layout. + ensure_frame_matches_label_source(child.schema().as_ref(), source)?; + unpack_raw_series( + Box::pin(RecordBatchStreamAdapter::new( + child.schema(), + futures::stream::empty(), + )), + Some(Arc::clone(tree_source)), + )?; reject_a_split_logical_series(&tree, partition_count)?; - let first = first.0.properties(); let properties = Arc::new(PlanProperties::new( EquivalenceProperties::new(output_schema.clone()), Partitioning::UnknownPartitioning(partition_count), - first.emission_type, - first.boundedness, + child.properties().emission_type, + child.properties().boundedness, )); - let input_bindings = inputs - .iter() - .map(|(_, source, ordering, paths, schema)| { - (Arc::clone(schema), source.clone(), *ordering, paths.clone()) - }) - .collect(); - let inputs = inputs - .into_iter() - .map(|(input, _, _, _, _)| input) - .collect(); Ok(Self { promql, tree, - input_bindings, + child_bindings: vec![(source.clone(), *ordering)], classification: classification.into(), time_column, tags: tags.into(), - inputs, + children: vec![Arc::clone(child)], output_schema, labels: Arc::new(Mutex::new(LabelSets::default())), metric: ExecutionPlanMetricsSet::new(), @@ -1036,7 +1065,7 @@ impl ExecutionPlan for FusedSeriesExec { fn input_distribution_requirements(&self) -> InputDistributionRequirements { InputDistributionRequirements::new(vec![ Distribution::UnspecifiedDistribution; - self.inputs.len() + self.children.len() ]) } @@ -1044,11 +1073,11 @@ impl ExecutionPlan for FusedSeriesExec { /// 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; self.inputs.len()] + vec![false; self.children.len()] } fn children(&self) -> Vec<&Arc> { - self.inputs.iter().collect() + self.children.iter().collect() } fn apply_expressions( @@ -1063,31 +1092,23 @@ impl ExecutionPlan for FusedSeriesExec { self: Arc, children: Vec>, ) -> DataFusionResult> { - if children.len() != self.inputs.len() { + if children.len() != self.children.len() { return Err(DataFusionError::Plan(format!( "FusedSeriesExec requires {} children, got {}", - self.inputs.len(), + self.children.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. - // The destinations each child feeds are the binding's own, and they are checked against the - // tree again. + // Rebuilt rather than patched: the schema the tree names is what the new child's frame is + // validated against, so a child that changed shape is refused instead of decoded with a + // stale layout. A child keeps the position it had, and so the source index it feeds: which + // child a tree input reads is never inferred from a schema. Ok(Arc::new(Self::try_new( Arc::clone(&self.promql), children .into_iter() - .zip(&self.input_bindings) - .map(|(input, (schema, source, ordering, paths))| { - ( - input, - source.clone(), - *ordering, - paths.clone(), - Arc::clone(schema), - ) - }) + .zip(&self.child_bindings) + .map(|(child, (source, ordering))| (child, source.clone(), *ordering)) .collect(), Arc::clone(&self.tree), self.output_schema.clone(), @@ -1109,19 +1130,31 @@ impl ExecutionPlan for FusedSeriesExec { .lock() .unwrap_or_else(|e| e.into_inner()) .attach(&context.runtime_env().memory_pool); - // Each source is executed once, at the partition this node was asked for, because a series + // The child is executed once, at the partition this node was asked for, because a series // never spans two partitions: an execution of the tree owns every chunk of every series the - // source reports in that partition. A source that feeds several tree inputs hands those - // chunks to each of them, so the same series is read at both destinations. - let mut inputs = Vec::with_capacity(self.inputs.len()); - for (input, (schema, source, _, paths)) in self.inputs.iter().zip(&self.input_bindings) { - let stream = input.execute(partition, 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((paths.clone(), stream)); - } + // child reports in that partition, and the chunks are queued at every tree input bound to + // source 0, so a tree that reads one series twice reads the same rows at both. + let (Some(child), Some((label_source, _))) = + (self.children.first(), self.child_bindings.first()) + else { + return Err(DataFusionError::Execution( + "FusedSeriesExec executes one child, and its plan holds another number".to_string(), + )); + }; + // The layout the frame is decoded against is the one the tree's own input was compiled + // against, read back off the tree here rather than kept on the node: a stored copy could + // only disagree with it. The walk is tree-sized and runs once per execution, not per chunk. + let sources = tree_sources(&self.tree)?; + let [tree_source] = sources.as_slice() else { + return Err(DataFusionError::Execution( + "FusedSeriesExec runs a tree that reads no source".to_string(), + )); + }; + let stream = child.execute(partition, Arc::clone(&context))?; + ensure_frame_matches_label_source(child.schema().as_ref(), label_source)?; + let stream = unpack_raw_series(stream, Some(Arc::clone(tree_source)))?; + let stream = + materialize_raw_labels(stream).map_err(|e| DataFusionError::External(Box::new(e)))?; // The execution name is the partition it answers, which is the one it was asked for. let state = NativeExecutionState::try_new( &self.tree, @@ -1131,13 +1164,8 @@ impl ExecutionPlan for FusedSeriesExec { )?; // 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. - let inputs = inputs.into_iter().map(|(paths, stream)| { - Box::pin(stream.map(move |item| (paths.clone(), item))) as TaggedInputStream - }); - let mut input_streams = SelectAll::new(); - input_streams.extend(inputs); Ok(Box::pin(FusedSeriesStream { - inputs: input_streams, + input: Some(stream), executor: Some(NativeExecutor::new(state)), classification: Arc::clone(&self.classification), tags: Arc::clone(&self.tags), @@ -1503,7 +1531,8 @@ fn colliding_field(stored: &[Vec], runs: &[Vec]) -> Option { /// The batches one execution of [`FusedSeriesExec`] yields. pub struct FusedSeriesStream { - inputs: SelectAll, + /// The one child's decoded chunks, or `None` once the stream let go of it. + input: Option, /// The execution of this node's tree, or `None` once it has been closed. executor: Option, /// Where each output column comes from. @@ -1525,25 +1554,17 @@ pub struct FusedSeriesStream { } impl FusedSeriesStream { - /// Pushes one chunk of one actual source at every tree input it feeds. + /// Pushes one chunk of the child's frames at every tree input bound to its source. /// - /// The last destination takes the chunk by value and the ones before it take a copy: the same - /// rows have to reach each destination, and the chunk is what carries them. - fn push_at(&mut self, paths: &[NodePath], chunk: RawSeriesChunk) -> DataFusionResult<()> { + /// Which inputs those are is the tree's own binding: a tree that reads one series twice has two + /// input nodes on source 0, and the executor hands both the same rows. + fn push(&mut self, chunk: RawSeriesChunk) -> DataFusionResult<()> { let executor = self.executor.as_mut().ok_or_else(|| { DataFusionError::Execution( "FusedSeriesExec stream pushed a chunk after its execution closed".into(), ) })?; - let Some((last, rest)) = paths.split_last() else { - return Err(DataFusionError::Execution( - "FusedSeriesExec stream pushed a chunk for no tree input".into(), - )); - }; - for path in rest { - executor.push_raw_at(path, chunk.clone())?; - } - executor.push_raw_at(last, chunk)?; + executor.push_raw_source(0, chunk)?; let mut settled = Vec::new(); while let Some(chunk) = executor.next_chunk()? { settled.push(chunk); @@ -1594,7 +1615,9 @@ impl FusedSeriesStream { fn fail(&mut self) { self.done = true; self.executor = None; - self.inputs.clear(); + // The child's stream is dropped here: its plan, its decoder and whatever batch it was + // holding are released as soon as this node stops reading them. + self.input = None; // 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. @@ -1669,15 +1692,21 @@ impl Stream for FusedSeriesStream { } continue; } - match Pin::new(&mut this.inputs).poll_next(cx) { + let Some(input) = this.input.as_mut() else { + // Only `fail` lets go of the child, and it sets `done`, which the loop above + // returns on, so reaching this means nothing more will be read. + return Poll::Ready(None); + }; + let polled = input.as_mut().poll_next(cx); + match polled { Poll::Pending => return Poll::Pending, - Poll::Ready(Some((_path, Err(error)))) => { + Poll::Ready(Some(Err(error))) => { this.fail(); return Poll::Ready(Some(Err(DataFusionError::External(Box::new(error))))); } - Poll::Ready(Some((paths, Ok(chunk)))) => { + Poll::Ready(Some(Ok(chunk))) => { budget -= 1; - if let Err(error) = this.push_at(&paths, chunk) { + if let Err(error) = this.push(chunk) { this.fail(); return Poll::Ready(Some(Err(error))); } @@ -1692,7 +1721,7 @@ impl Stream for FusedSeriesStream { } } // Reaching the chunk budget means there is productive input still to process. Wake the - // parent to continue; a genuinely pending SelectAll already registered child wakers. + // parent to continue; a genuinely pending input already registered its own waker. cx.waker().wake_by_ref(); Poll::Pending } diff --git a/src/promql/src/extension_plan/fused_series/tests.rs b/src/promql/src/extension_plan/fused_series/tests.rs index 29829ea1822..6109f337101 100644 --- a/src/promql/src/extension_plan/fused_series/tests.rs +++ b/src/promql/src/extension_plan/fused_series/tests.rs @@ -25,6 +25,11 @@ //! says which series a chunk belongs to and whether it closes it instead of relying on where a row //! boundary happens to fall. //! +//! One actual source is what the runtime runs: every tree input of the admitted trees is bound to +//! source `0`, and the one child's chunks are handed to each of them. A tree that names a source +//! index no child covers, or a plan given more than one child, is refused where the plan is built +//! rather than run against half of its input. +//! //! Kernel numerics are not the subject: `rate` is checked against a counter that advances one //! second per second, so the value it has to produce is exactly 1 (or 2) at every grid point and //! any position or finalization mistake shows up as a wrong, missing or duplicated row. @@ -71,16 +76,16 @@ use futures::{Stream, StreamExt, TryStreamExt}; use store_api::region_engine::RawLabelSource; use super::{ - FusedSeries, FusedSeriesBinding, FusedSeriesChild, FusedSeriesExec, FusedSeriesInput, - LabelSets, OutputColumn, POLL_BUDGET, label_set, occupied_runs, series_to_record_batch, + FusedSeries, FusedSeriesBinding, FusedSeriesExec, LabelSets, OutputColumn, POLL_BUDGET, + label_set, occupied_runs, series_to_record_batch, }; use crate::evaluated::EvaluatedChunk; use crate::extension_plan::PromExtensionPlanner; use crate::native::execute::{NativeExecutionState, NativeExecutor}; use crate::native::metrics::{NodeMetric, NodePath}; use crate::native::plan::{ - AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundWindow, Grouping, - NativeExpr, NativeNode, NativeTree, NativeType, + AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundScalar, + BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, NativeType, }; use crate::native::runs::absorb_rebuilds; use crate::range_eval::{RangeFunction, RangeWindow}; @@ -147,6 +152,16 @@ fn two_field_schema() -> Arc { /// The tree `rate(x[5m])` compiles to over `schema`: raw samples folded by one window onto the grid. fn rate_tree_of(schema: Arc) -> NativeTree { + rate_tree_at(schema, 0) +} + +/// [`rate_tree_of`] with its input bound to the child at `source_index`. +/// +/// The input declares `Contiguous`, which is what every plan these fixtures build presents +/// ([`plan_of`]): a tree is legal only against frames that satisfy the ordering each of its inputs +/// declares, so a fixture declares the ordering its own plans really hand over. A test that needs +/// another declaration rewrites it on a clone with [`declaring_orderings`]. +fn rate_tree_at(schema: Arc, source_index: usize) -> NativeTree { let grid = grid(); // One schema shared by the window's binding and its output, which is what `NativeTree`'s // validation compares by identity. @@ -159,8 +174,9 @@ fn rate_tree_of(schema: Arc) -> NativeTree { expr: NativeExpr::Window { input: Box::new(NativeNode { expr: NativeExpr::Input(BoundInput { + source_index, output: raw.clone(), - ordering: SeriesOrdering::KeyThenTime, + ordering: SeriesOrdering::Contiguous, }), output: raw, }), @@ -186,19 +202,25 @@ fn rate_tree() -> NativeTree { rate_tree_of(raw_schema()) } +/// `left + right` on one grid, both operands reading the one actual source. fn binary_tree(left_schema: Arc, right_schema: Arc) -> NativeTree { - binary_tree_op(BinaryOp::Add, left_schema, right_schema) + binary_tree_over_sources(BinaryOp::Add, left_schema, right_schema, 0, 0) } -/// [`binary_tree`] over `op`, for a test that needs an operator its operands cannot exchange. +/// A binary tree over `op` whose operands are bound to the given source indexes. /// /// `left_schema` is the operand at `root.left` and `right_schema` the one at `root.right`, so a -/// subtracting tree answers `left - right` and a routing that swapped the two would answer the -/// negative of that. -fn binary_tree_op( +/// subtracting tree answers `left - right`. One source read at both operands is what a statement +/// that names one selector twice plans to; two different indexes are what a statement whose +/// operands are two scans plans to, which the runtime refuses for now. The tree is the same shape +/// either way, and the renderer names the index each input reads, so the trees are distinct +/// computations. +fn binary_tree_over_sources( op: BinaryOp, left_schema: Arc, right_schema: Arc, + left_source: usize, + right_source: usize, ) -> NativeTree { let grid = grid(); let left_eval = Arc::new(SeriesSchema { @@ -216,8 +238,9 @@ fn binary_tree_op( expr: NativeExpr::Instant { input: Box::new(NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: left_source, output: NativeType::Samples(Arc::clone(&raw_left)), - ordering: SeriesOrdering::KeyThenTime, + ordering: SeriesOrdering::Contiguous, }), output: NativeType::Samples(raw_left), }), @@ -233,8 +256,9 @@ fn binary_tree_op( expr: NativeExpr::Instant { input: Box::new(NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: right_source, output: NativeType::Samples(Arc::clone(&raw_right)), - ordering: SeriesOrdering::KeyThenTime, + ordering: SeriesOrdering::Contiguous, }), output: NativeType::Samples(raw_right), }), @@ -263,6 +287,133 @@ fn binary_tree_op( .unwrap() } +/// The constant scalar `value`, evaluated on `grid`. +/// +/// A scalar is the one thing a tree can produce while reading no source, so this is the tree the +/// zero-child case is about. +fn scalar_tree(grid: Arc, value: f64) -> NativeTree { + NativeTree::try_new(NativeNode { + expr: NativeExpr::Scalar(BoundScalar { value }), + output: NativeType::Scalar(grid), + }) + .expect("a constant scalar is a legal tree") +} + +/// An instant selection over the tree input bound to `source_index`. +fn instant_of(source_index: usize, grid: &Arc) -> NativeNode { + let raw = NativeType::Samples(raw_schema()); + NativeNode { + expr: NativeExpr::Instant { + input: Box::new(NativeNode { + expr: NativeExpr::Input(BoundInput { + source_index, + output: raw.clone(), + ordering: SeriesOrdering::Contiguous, + }), + output: raw, + }), + op: BoundInstant { + lookback_ms: 0, + offset_ms: 0, + output_grid: Arc::clone(grid), + }, + }, + output: evaluated_of(&raw_schema(), grid), + } +} + +/// `raw_schema`'s fields on `grid`: one value per grid point. +fn evaluated_of(schema: &SeriesSchema, grid: &Arc) -> NativeType { + NativeType::Samples(Arc::new(SeriesSchema { + fields: schema.fields.clone(), + eval_grid: Some(Arc::clone(grid)), + })) +} + +/// `tree` with the orderings its input nodes declare replaced, in the order the nodes are reached. +/// +/// The fixtures here declare `Contiguous`, which is what the plans below them present, so a test +/// that needs another declaration rewrites it on a clone rather than keeping a second tree builder +/// beside the first. The rewrite is revalidated by [`NativeTree::try_new`], so one that broke a +/// contract of the tree is refused here instead of at the node under test. +fn declaring_orderings(tree: &NativeTree, orderings: &[SeriesOrdering]) -> NativeTree { + fn rewrite(node: &NativeNode, orderings: &[SeriesOrdering], seen: &mut usize) -> NativeNode { + let mut expr = node.expr.clone(); + match &mut expr { + NativeExpr::Input(bound) => { + bound.ordering = orderings[*seen]; + *seen += 1; + } + // A constant reads no source, so it declares no ordering. + NativeExpr::Scalar(_) => {} + NativeExpr::Instant { input, .. } + | NativeExpr::Window { input, .. } + | NativeExpr::Map { input, .. } + | NativeExpr::Aggregate { input, .. } + | NativeExpr::Vector { input, .. } => { + **input = rewrite(input, orderings, seen); + } + NativeExpr::Binary { left, right, .. } => { + **left = rewrite(left, orderings, seen); + **right = rewrite(right, orderings, seen); + } + } + NativeNode { + expr, + output: node.output.clone(), + } + } + let mut seen = 0; + let tree = NativeTree::try_new(rewrite(tree.root(), orderings, &mut seen)) + .expect("another declared ordering keeps the tree legal"); + assert_eq!(orderings.len(), seen, "one ordering per input of the tree"); + tree +} + +/// `x - 2 * x`: one source read at both operands, with a scalar multiplier on the right. +/// +/// The subtraction and the multiplier together make the answer depend on which operand is which: +/// this tree answers `-x` at every grid point, and the same operands paired the other way round +/// answer `+x`. `x - x` would answer zero either way and could not tell the two apart. +fn subtracted_scaled_tree() -> NativeTree { + let grid = grid(); + let output = evaluated_of(&raw_schema(), &grid); + let doubled = NativeNode { + expr: NativeExpr::Binary { + left: Box::new(instant_of(0, &grid)), + right: Box::new(NativeNode { + expr: NativeExpr::Scalar(BoundScalar { value: 2.0 }), + output: NativeType::Scalar(Arc::clone(&grid)), + }), + matching: BinaryMatching { + op: BinaryOp::Mul, + return_bool: false, + // What a scalar broadcast binds: the modifiers of a vector-vector match have no + // meaning here, and the runtime refuses a constant carrying them. + labels: MatchingLabels::Ignoring(Vec::new()), + cardinality: Cardinality::OneToOne, + fill: FillValues::default(), + }, + }, + output: output.clone(), + }; + NativeTree::try_new(NativeNode { + expr: NativeExpr::Binary { + left: Box::new(instant_of(0, &grid)), + right: Box::new(doubled), + matching: BinaryMatching { + op: BinaryOp::Sub, + return_bool: false, + labels: MatchingLabels::On(vec![Arc::from(HOST)]), + cardinality: Cardinality::OneToOne, + fill: FillValues::default(), + }, + }, + output, + }) + .expect("the bound tree is legal") +} + /// An instant selection feeding a range window. fn instant_window_tree() -> NativeTree { let instant = instant_tree().root().clone(); @@ -319,8 +470,9 @@ fn nested_window_tree() -> NativeTree { expr: NativeExpr::Window { input: Box::new(NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: raw.clone(), - ordering: SeriesOrdering::KeyThenTime, + ordering: SeriesOrdering::Contiguous, }), output: raw, }), @@ -422,8 +574,9 @@ fn instant_tree() -> NativeTree { expr: NativeExpr::Instant { input: Box::new(NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: raw.clone(), - ordering: SeriesOrdering::KeyThenTime, + ordering: SeriesOrdering::Contiguous, }), output: raw, }), @@ -438,84 +591,53 @@ fn instant_tree() -> NativeTree { .expect("the bound tree is legal") } -/// 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, -) -> FusedSeriesBinding { - FusedSeriesBinding { - grid: tree - .root() +/// The grid `tree` is evaluated on, which is the grid its binding declares. +fn tree_grid(tree: &NativeTree) -> Arc { + Arc::clone( + tree.root() .output - .samples() - .unwrap() - .eval_grid - .clone() - .unwrap(), - } -} -fn one_input(tree: &NativeTree, plan: LogicalPlan) -> Vec { - one_input_tags(tree, plan, vec![HOST.to_string(), NAME.to_string()]) + .grid() + .expect("these trees produce an evaluated value"), + ) } -/// One binding for the tree's single input, at the destination the tree itself names. -fn one_input_tags( - tree: &NativeTree, - plan: LogicalPlan, - tags: Vec, -) -> Vec { - let mut found = Vec::new(); - crate::native::metrics::walk(tree.root(), &mut |node, path| { - if let NativeExpr::Input(input) = &node.expr { - found.push((Arc::clone(input.output.samples().unwrap()), path.clone())); - } - }); - assert_eq!(1, found.len(), "these trees read one input"); - let (series_schema, path) = found.remove(0); - vec![FusedSeriesInput { - series_schema, - metric_name: Some(Arc::from(METRIC)), +/// The tags the output reports: the series' host and the metric name. +fn default_tags() -> Vec { + vec![HOST.to_string(), NAME.to_string()] +} + +/// The binding of these tests' scans over `tree`, reporting `tags` as the output's tag columns. +fn binding_of(tree: &NativeTree, tags: Vec) -> FusedSeriesBinding { + FusedSeriesBinding { + grid: tree_grid(tree), time_index: TIME.to_string(), tags, - input: plan, - // The tree's own destination, not `root.input` assumed: a window above the input moves it. - paths: vec![path], - }] -} - -/// What the tree's input was compiled against, read off the tree itself. -fn binding(tree: &NativeTree) -> FusedSeriesBinding { - binding_of(tree, raw_schema(), vec![HOST.to_string(), NAME.to_string()]) -} - -/// The destinations of [`binary_tree`], left operand first. -fn binary_paths() -> [NodePath; 2] { - [ - NodePath::root().left().input(), - NodePath::root().right().input(), - ] -} - -/// One binding of the one-field schema of these tests, reading `plan` at `paths`. -fn binding_at(paths: Vec, plan: LogicalPlan) -> FusedSeriesInput { - FusedSeriesInput { - series_schema: raw_schema(), metric_name: Some(Arc::from(METRIC)), - time_index: TIME.to_string(), - tags: vec![HOST.to_string(), NAME.to_string()], - input: plan, - paths, } } -/// The logical node of `tree` over `inputs`, with the grid the tree was evaluated on. -fn logical(tree: &NativeTree, inputs: Vec) -> DataFusionResult { +/// The binding of the one-field schema of these tests, read off the tree itself. +fn binding(tree: &NativeTree) -> FusedSeriesBinding { + binding_of(tree, default_tags()) +} + +/// One logical child: the plan a scan stands in for when the caller is not testing the plans below. +fn child() -> LogicalPlan { + input_plan(frame_schema()) +} + +/// `count` logical children, each on the frame schema of these tests. +fn children(count: usize) -> Vec { + vec![child(); count] +} + +/// The logical node of `tree` over `children`, with the grid the tree was evaluated on. +fn logical(tree: &NativeTree, children: Vec) -> DataFusionResult { FusedSeries::try_new( Arc::from("a + on(host) a"), tree.clone(), binding(tree), - inputs, + children, output_schema().to_dfschema_ref().unwrap(), ) } @@ -839,7 +961,7 @@ fn fused(tree: NativeTree) -> FusedSeries { Arc::from(PROMQL), tree.clone(), binding, - one_input(&tree, input_plan(frame_schema())), + vec![child()], output_schema().to_dfschema_ref().unwrap(), ) .expect("the binding matches the tree") @@ -865,17 +987,6 @@ fn plan( plan_of(fused(tree), input) } -/// One physical child of the one-field schema of these tests, reading `batches` at `paths`. -fn child_at(paths: Vec, batches: Vec) -> FusedSeriesChild { - ( - memory_exec(batches), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - paths, - raw_schema(), - ) -} - /// The timestamps of `rows`. fn times_of(rows: &[(i64, f64)]) -> Vec { rows.iter().map(|(time, _)| *time).collect() @@ -1069,20 +1180,14 @@ fn zone_output_schema() -> SchemaRef { /// `rate(x[5m])` over frames that carry `zone` as well as `host`, with both in the output. fn zone_node() -> FusedSeries { let tree = rate_tree(); - let binding = binding_of( - &tree, - raw_schema(), - vec![HOST.to_string(), ZONE.to_string(), NAME.to_string()], - ); FusedSeries::try_new( Arc::from(PROMQL), tree.clone(), - binding, - one_input_tags( + binding_of( &tree, - input_plan(frame_schema()), vec![HOST.to_string(), ZONE.to_string(), NAME.to_string()], ), + vec![child()], zone_output_schema().to_dfschema_ref().unwrap(), ) .expect("the binding matches the tree") @@ -1094,20 +1199,14 @@ fn zone_node() -> FusedSeries { /// frame wrote it. fn instant_node() -> FusedSeries { let tree = instant_tree(); - let binding = binding_of( - &tree, - raw_schema(), - vec![HOST.to_string(), ZONE.to_string(), NAME.to_string()], - ); FusedSeries::try_new( Arc::from(PROMQL), tree.clone(), - binding, - one_input_tags( + binding_of( &tree, - input_plan(frame_schema()), vec![HOST.to_string(), ZONE.to_string(), NAME.to_string()], ), + vec![child()], zone_output_schema().to_dfschema_ref().unwrap(), ) .expect("the binding matches the tree") @@ -1279,7 +1378,8 @@ fn grid_timestamps() -> Vec { /// A waker a test can ask whether it was notified. /// -/// The poll tests use this to drive only when a child or the bounded-work continuation woke them. +/// The remaining poll test uses it to see that a poll which stopped on its budget wakes the +/// consumer, which is what makes a stopped poll resumable rather than a lost one. #[derive(Default)] struct CountingWake(AtomicBool); @@ -1293,10 +1393,6 @@ impl CountingWake { fn woken(&self) -> bool { self.0.load(Ordering::SeqCst) } - - fn clear(&self) { - self.0.store(false, Ordering::SeqCst); - } } /// One series as many chunks that settle nothing: one sample per chunk, all before the grid starts. @@ -1391,8 +1487,8 @@ fn fmt_as_prints_the_native_tree() { "the node line carries the tree it runs: {text}" ); assert!( - text.contains("input Input raw samples"), - "the node line carries the tree's source: {text}" + text.contains("input Input source=0 raw samples"), + "the node line carries the tree's source and the child it reads: {text}" ); } @@ -1461,278 +1557,97 @@ 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()), - // The two bindings of this direct test name the destinations explicitly: one - // source per operand, which is the shape a match over two scans keeps. - paths: vec![NodePath::root().left().input()], - }, - 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()), - paths: vec![NodePath::root().right().input()], - }, - ], - 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, - vec![NodePath::root().left().input()], - left_schema, - ), - ( - memory_exec(frames(&[series_chunk("job", &[(GRID_START, 7.0)], true)])), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - vec![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); -} - -/// A child is routed by the path it names, not by the position it was given in. +/// One child read at both operands of `x - 2 * x` answers `-x`, so the operands cannot be swapped. /// -/// The tree subtracts, so its two operands cannot be exchanged without the answer changing sign, and -/// the children are listed in the opposite order to the operands: the source that names the right -/// operand comes first. A node that paired children with tree inputs by position would put `10` at -/// the right operand and `7` at the left and answer `-3`; the same tree evaluated with the children -/// in operand order would answer `3` for that reason alone, and neither is `10 - 7`. The value is -/// therefore evidence about the routing and not about the arithmetic. +/// A statement that names one selector twice plans to one scan and two tree inputs, and the tree +/// hands every chunk of that scan to both of them. What each input reads is its own +/// `source_index`, so both read the one child and no per-child list of destinations exists to +/// disagree with the tree. The subtraction and the scalar multiplier together make the answer +/// order-sensitive: `x - 2 * x` is `-x` at every grid point, while the same samples paired the other +/// way round answer `+x`. `x - x` would answer zero whichever way it was paired and could not tell. #[tokio::test] -async fn a_binary_exec_routes_its_children_by_path_not_by_position() { - let tree = binary_tree_op(BinaryOp::Sub, raw_schema(), raw_schema()); - let [left_path, right_path] = binary_paths(); - let physical = FusedSeriesExec::try_new( - Arc::from("a - on(host) b"), - vec![ - // The right operand's source first, so only the path can say which is which. - ( - memory_exec(frames(&[series_chunk("job", &[(GRID_START, 7.0)], true)])), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - vec![right_path], - raw_schema(), - ), - ( - memory_exec(frames(&[series_chunk("job", &[(GRID_START, 10.0)], true)])), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - vec![left_path], - raw_schema(), - ), - ], - Arc::new(tree), - output_schema(), - TIME.into(), - vec![HOST.into(), NAME.into()], - ) - .expect("the two children cover the tree's two inputs"); - let batches = collect(Arc::new(physical), SessionContext::default().task_ctx()) - .await - .expect("the sole output partition executes"); - let rows = rows(&batches); - assert_eq!(1, rows.len(), "{rows:?}"); - let (time, value, host, name) = &rows[0]; - assert_eq!(&GRID_START, time, "the one grid point both samples sit on"); - assert_eq!( - Some(3.0), - *value, - "the left operand minus the right one, which a positional pairing answers as -3 or 17" - ); - assert_eq!( - Some("job"), - host.as_deref(), - "the label both operands match on" - ); - // Arithmetic drops the metric name, on whichever operand the left path named. - assert_eq!(None, *name, "{name:?}"); -} +async fn one_child_read_at_both_operands_answers_a_scalar_scaled_subtraction() { + let tree = subtracted_scaled_tree(); + let node = logical(&tree, vec![child()]).expect("one child covers both of the tree's inputs"); + assert_eq!(1, node.children().len(), "one actual source"); -/// Two sources that are each read in several partitions are refused, not gathered. -/// -/// A match pairs two scans' series by label, and neither scan says where the other put the series it -/// is looking for: `h1` can be in the left scan's first partition and the right scan's last. Reading -/// each source once per partition would then hand one execution half of a pair, and reading every -/// partition of both into one execution would be the gather this node no longer has - it would read -/// the two sources' partitions out of order behind the tree's back, and it would do so silently. -/// The shape is refused where it is built, and it names the input that has more than one partition. -#[tokio::test] -async fn several_sources_read_in_several_partitions_are_refused() { - let left_schema = raw_schema(); - let right_schema = raw_schema(); - let tree = binary_tree(Arc::clone(&left_schema), Arc::clone(&right_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()), - paths: vec![NodePath::root().left().input()], - }, - 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()), - paths: vec![NodePath::root().right().input()], - }, - ], - output_schema() - .to_dfschema_ref() - .expect("the output schema is valid"), + let samples = series_samples(1.0); + let exec = plan_of( + node, + memory_exec(frames(&[series_chunk("h1", &samples, true)])), ) - .expect("the two-input binding matches the tree"); - let rows_of = |scale: f64| frames(&[series_chunk("h1", &series_samples(scale), true)]); - let one = |batches: Vec| memory_exec_partitioned(vec![batches]); - let two = |batches: Vec| memory_exec_partitioned(vec![batches.clone(), batches]); - // The first source is one partition and the second two: the refusal names the source that - // cannot be paired, and neither count is silently reduced to one. - let error = node - .to_execution_plan(vec![ - ( - one(rows_of(1.0)), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ( - two(rows_of(2.0)), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ]) - .expect_err("the second source has two partitions, and pairing it needs an exchange"); - let message = error.to_string(); - assert!( - message.contains("input 1"), - "the refusal must name it: {message}" - ); - assert!( - message.contains("2 partitions"), - "the refusal must name the count: {message}" - ); - assert!( - message.contains("2 sources"), - "the refusal must name how many sources it would run: {message}" - ); - // Two sources of one partition each are the accepted shape: one execution sees every series of - // both, so a match pairs them by label. - let physical = node - .to_execution_plan(vec![ - ( - one(rows_of(1.0)), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ( - one(rows_of(2.0)), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ]) - .expect("two single-partition sources are one execution"); - assert_eq!( - 1, - physical - .properties() - .output_partitioning() - .partition_count() - ); - let batches = collect(physical, SessionContext::default().task_ctx()) + .expect("the physical node builds"); + let batches = collect(exec, SessionContext::default().task_ctx()) .await - .expect("the sole output partition executes"); - let mut rows = rows(&batches); - rows.sort_by_key(|row| row.0); + .expect("the one partition answers"); + let rows = rows(&batches); let expected = grid_timestamps() .into_iter() .map(|stamp| { - let value = 3.0 * stamp as f64 / 1_000.0; - (stamp, Some(value)) + let sample = samples + .iter() + .find_map(|(time, value)| (*time == stamp).then_some(*value)) + .expect("the samples cover every grid point"); + (stamp, Some(-sample), Some("h1".to_string())) }) .collect::>(); assert_eq!( expected, - rows.iter().map(|row| (row.0, row.1)).collect::>(), - "each grid point holds the sum of the two sources" + rows.iter() + .map(|row| (row.0, row.1, row.2.clone())) + .collect::>(), + "the left operand minus the doubled right one, not the other way round" + ); +} + +/// A second child is refused, even when each child has one partition. +/// +/// Pairing two children's series by label needs an exchange that merges them, which this node does +/// not have: one execution would read both children's partitions out of order behind the tree's +/// back. The refusal is on the count and not on the partitioning, so two children of one partition +/// each are refused exactly like two children of several. The tree below is the two-source shape +/// such a query plans to, and it is refused where the execution plan is built. +#[test] +fn a_second_child_is_refused() { + let tree = binary_tree_over_sources(BinaryOp::Add, raw_schema(), raw_schema(), 0, 1); + let node = logical(&tree, children(2)).expect("the tree names both of its children"); + let rows = frames(&[series_chunk("h1", &series_samples(1.0), true)]); + let error = node + .to_execution_plan(vec![ + ( + memory_exec(rows.clone()), + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + ), + ( + memory_exec(rows), + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + ), + ]) + .expect_err("two children would have to be paired by label"); + let message = error.to_string(); + assert!( + message.contains("2 sources"), + "the refusal must name how many sources it would run: {message}" ); assert!( - rows.iter().all(|row| row.2.as_deref() == Some("h1")), - "the match is on the host the two series share: {rows:?}" + message.contains("exchange"), + "the refusal must name what is missing: {message}" ); } /// One source feeding both operands is read once and answered as `x + x`, not as `x`. /// /// This is the shape a statement that names one selector twice plans to: one scan and two tree -/// destinations. The tree sees the same samples at both operands, so every grid point holds the -/// sample summed with itself. Answering `x` is what a node that queued the chunk at only one -/// destination - or that resolved a destination by traversal order instead of by path - would -/// produce, and that is what this test separates from the sum. +/// inputs. The tree sees the same samples at both operands, so every grid point holds the sample +/// summed with itself. Answering `x` is what a node that queued the chunk at only one of the two +/// inputs would produce, and that is what this test separates from the sum. #[tokio::test] async fn one_source_read_at_both_operands_answers_x_plus_x() { let tree = binary_tree(raw_schema(), raw_schema()); - let node = logical( - &tree, - vec![binding_at( - binary_paths().to_vec(), - input_plan(frame_schema()), - )], - ) - .expect("one source covers both of the tree's inputs"); - assert_eq!(1, node.fused_inputs().len(), "one actual source"); - assert_eq!(2, node.fused_inputs()[0].paths.len(), "two destinations"); + let node = logical(&tree, vec![child()]).expect("one source covers both of the tree's inputs"); + assert_eq!(1, node.children().len(), "one actual source"); let samples = series_samples(1.0); let exec = plan_of( @@ -1763,7 +1678,7 @@ async fn one_source_read_at_both_operands_answers_x_plus_x() { ); } -/// A source read at both destinations is executed once per partition, and each partition is its own. +/// A source read at both inputs is executed once per partition, and each partition is its own. /// /// Each of the `partitions` series sits in a partition of its own in one scan, so each execution of /// the tree owns one series and reads it at both operands. Three things are checked at once: the @@ -1778,14 +1693,8 @@ async fn one_source_read_at_both_operands_answers_x_plus_x() { async fn one_source_read_at_both_operands_is_executed_once_per_partition() { for partitions in [2_usize, 4] { let tree = binary_tree(raw_schema(), raw_schema()); - let node = logical( - &tree, - vec![binding_at( - binary_paths().to_vec(), - input_plan(frame_schema()), - )], - ) - .expect("one source covers both of the tree's inputs"); + let node = + logical(&tree, vec![child()]).expect("one source covers both of the tree's inputs"); let scales = (1..=partitions).map(|n| n as f64).collect::>(); let source_partitions = scales .iter() @@ -1876,96 +1785,468 @@ async fn one_source_read_at_both_operands_is_executed_once_per_partition() { } } -/// A binding names each of the tree's raw inputs exactly once, and the tree names them all. -#[test] -fn a_binding_must_name_one_destination_per_tree_input() { - let tree = binary_tree(raw_schema(), raw_schema()); - let [left, right] = binary_paths(); - let cases: [(&str, Vec>, &str); 6] = [ - ( - "a binding with no destination", - vec![vec![]], - "names no tree input path", - ), - ( - "a destination the tree does not have", - vec![vec![NodePath::root().input()]], - "is not an input of its tree", - ), - ( - "one destination listed twice by one binding", - vec![vec![left.clone(), left.clone(), right.clone()]], - "more than once", - ), - ( - "one destination listed by two bindings", - vec![vec![left.clone()], vec![left.clone()]], - "more than once", - ), - ( - "a destination no binding names", - vec![vec![left.clone()]], - "binds no source for the tree input `root.right.input`", - ), - ( - "no bindings at all", - vec![], - "binds no source for the tree input `root.left.input`", - ), - ]; - for (case, paths, expected) in cases { - let inputs = paths - .into_iter() - .map(|paths| binding_at(paths, input_plan(frame_schema()))) - .collect(); - let error = logical(&tree, inputs).expect_err(case); - let message = error.to_string(); - assert!(message.contains(expected), "{case}: {message}"); - } - // Both destinations, in either order: the list is looked up by path rather than zipped against - // the tree's walk, so the order it is written in does not matter. - for paths in [ - vec![left.clone(), right.clone()], - vec![right.clone(), left.clone()], +/// Two stateful windows over one child each receive every chunk of the series. +/// +/// `rate(x[5m]) - rate(x[5m])` names one selector twice, so both windows are bound to source `0` +/// and one child's chunks are queued at both of them. A window never hands a chunk on, but it does +/// not hold a series either: it keeps only the samples its remaining windows still read and hands +/// out each grid point as the pushed samples complete its window. So the subtraction is not the +/// delivery proof: `rate - rate` is zero wherever both operands decided a point, and the counter +/// here advances one second per second, so a sample both windows missed costs neither one its +/// rate - identical omissions are invisible to a comparison of the two sides or to the values +/// themselves. +/// +/// What rules omissions out is what the runtime reports per input: each one counts one +/// [`NodeMetric::INPUT_BATCHES`] per batch of the child ([`one_series_frames`] sends three) and one +/// completed series, so a window handed less of the stream than the other is visible even at the +/// points where its answer would have been right. +#[tokio::test] +async fn two_windows_over_one_child_each_read_the_whole_series() { + // `rate(x[5m]) - rate(x[5m])` over one source: the two operands are the window's own root, + // cloned so both halves share its bindings and its grid by allocation. + let rate = rate_tree(); + let window = rate.root().clone(); + let output = crate::vector_match::binary_output_schema( + window + .output + .samples() + .expect("a window produces evaluated samples"), + window + .output + .samples() + .expect("a window produces evaluated samples"), + ) + .expect("both operands are evaluated on the one grid"); + let tree = NativeTree::try_new(NativeNode { + expr: NativeExpr::Binary { + left: Box::new(window.clone()), + right: Box::new(window), + matching: BinaryMatching { + op: BinaryOp::Sub, + return_bool: false, + labels: MatchingLabels::On(vec![Arc::from(HOST)]), + cardinality: Cardinality::OneToOne, + fill: FillValues::default(), + }, + }, + output: NativeType::Samples(output), + }) + .expect("two windows over one source are a legal tree"); + let node = logical(&tree, vec![child()]).expect("one child feeds both windows"); + assert_eq!(1, node.children().len(), "one actual source"); + + let batches = one_series_frames(); + let chunks = batches.len(); + assert!( + chunks > 1, + "the fixture has to arrive in several chunks: {chunks}" + ); + let calls = Arc::new(Mutex::new(Vec::new())); + let source = ExecuteRecorder::counting(memory_exec(batches), &calls); + let exec = plan_of(node, source).expect("the physical node builds"); + + let answered = collect(Arc::clone(&exec), SessionContext::default().task_ctx()) + .await + .expect("the one partition answers"); + let rows = rows(&answered); + // The whole grid, in order, with the host `rate` kept and the name it dropped: `rate - rate` + // is zero at every point both windows decided, which is the shape of the answer. + let expected = grid_timestamps() + .into_iter() + .map(|stamp| (stamp, Some(0.0), Some("web-1".to_string()), None)) + .collect::>(); + assert_eq!(expected, rows, "every grid point holds rate minus rate"); + + // The one child was executed once, for the partition this node answers. + let called = calls.lock().unwrap_or_else(|e| e.into_inner()).clone(); + assert_eq!( + vec![0], + called, + "the child is executed once, at partition 0" + ); + + // Each window completed the one series it read, and the subtraction completed its one result. + // A window that never received the closing chunk reports no completed series, so this is the + // stateful half of the claim the rows above make. + let metrics = exec + .metrics() + .expect("the node reports its runtime's metrics"); + for node in [ + NodePath::root(), + NodePath::root().left(), + NodePath::root().right(), ] { - logical(&tree, vec![binding_at(paths, input_plan(frame_schema()))]) - .expect("one source at both destinations is the admitted shape"); + assert_eq!( + 1, + count(&metrics, &node.metric_name(NodeMetric::COMPLETED_SERIES)), + "{node} did not complete the one series it read" + ); + } + + // Both inputs were fed the whole stream: one batch per batch of the child, which is what the + // two windows' answers cannot say on their own. + let left = NodePath::root().left().input(); + let right = NodePath::root().right().input(); + for input in [&left, &right] { + assert_eq!( + chunks, + count(&metrics, &input.metric_name(NodeMetric::INPUT_BATCHES)), + "{input} did not receive every chunk of the series" + ); + assert_eq!( + 1, + count(&metrics, &input.metric_name(NodeMetric::COMPLETED_SERIES)), + "{input} did not close the one series it read" + ); } } -/// A binding's schema is checked against the schema of every destination it names. +/// One source read at two inputs must be read through one raw series schema. /// -/// The two operands of this tree were compiled against different schemas, so no one binding can -/// serve both: decoding one frame against either layout would hand the other operand a column set -/// it never bound. The refusal names the destination that disagrees. +/// Both inputs of this tree name source `0`, so one child's frames are decoded for both of them. +/// The two operands were compiled against different field lists: decoding the one frame either way +/// would hand the other operand a column it never bound, so the job is refused while it is built. +/// There is no per-input copy of the schema to mutate here - the schema each input reads is the one +/// its own node carries - so what is compared is the tree against itself. #[test] -fn a_binding_must_agree_with_the_schema_of_each_destination() { +fn a_source_shared_by_both_inputs_must_read_one_schema() { let tree = binary_tree(raw_schema(), two_field_schema()); - let error = logical( - &tree, - vec![binding_at( - binary_paths().to_vec(), - input_plan(frame_schema()), - )], - ) - .expect_err("one binding cannot be the layout of both operands"); + let error = + logical(&tree, vec![child()]).expect_err("one child cannot be decoded through two layouts"); let message = error.to_string(); assert!( - message.contains("`root.right.input`"), - "the refusal must name the destination that disagrees: {message}" + message.contains("source 0"), + "the refusal must name the source both inputs read: {message}" ); assert!( - message.contains("not compiled against"), - "refused for another reason: {message}" + message.contains("layout"), + "the refusal must say why one child cannot serve both: {message}" ); } -/// The execution inputs are one per binding, in both directions. +/// A tree input that is not raw samples is refused by the logical node. /// -/// A zip would drop the longer side, so a caller that passes one scan too many would have it +/// The right operand below reads evaluated samples at source `0` - the shape an exchange boundary +/// hands over - while the left one reads raw samples from the same child, and the tree is otherwise +/// valid: both sides are on one grid and the binary operation is legal. This node decodes raw series +/// frames, so every input it runs has to be raw; the tree is refused where the node is created, +/// before any execution plan exists to run. +#[test] +fn a_tree_input_that_is_not_raw_series_is_refused() { + let grid = grid(); + let evaluated = evaluated_of(&raw_schema(), &grid); + let tree = NativeTree::try_new(NativeNode { + expr: NativeExpr::Binary { + left: Box::new(instant_of(0, &grid)), + right: Box::new(NativeNode { + expr: NativeExpr::Input(BoundInput { + source_index: 0, + output: evaluated.clone(), + ordering: SeriesOrdering::Contiguous, + }), + output: evaluated.clone(), + }), + matching: BinaryMatching { + op: BinaryOp::Add, + return_bool: false, + labels: MatchingLabels::On(vec![Arc::from(HOST)]), + cardinality: Cardinality::OneToOne, + fill: FillValues::default(), + }, + }, + output: evaluated, + }) + .expect("an evaluated input is a legal tree: it is what an exchange boundary hands over"); + let error = FusedSeries::try_new( + Arc::from(PROMQL), + tree.clone(), + binding(&tree), + vec![child()], + output_schema().to_dfschema_ref().unwrap(), + ) + .expect_err("the node decodes raw frames, so an evaluated input cannot be run"); + assert!(matches!(error, DataFusionError::Plan(_)), "{error}"); + let message = error.to_string(); + // The operand *is* the input node - nothing sits below it - so the walk reaches it at + // `root.right`, not at a `root.right.input` that does not exist in this tree. + assert!( + message.contains("`root.right`"), + "the refusal must name the input node that is not raw: {message}" + ); + assert!( + !message.contains("`root.right.input`"), + "an input node is its own position, so the refusal cannot name a node below it: {message}" + ); + assert!( + message.contains("not raw series"), + "the refusal must say what the input has to be: {message}" + ); +} + +/// The ordering a tree input declares has to be met by the frames its child produces. +/// +/// This is the whole matrix of the two facts: what an input declares, and what the producer +/// promises. `Contiguous` frames satisfy an input bound to `Contiguous` and one bound to the +/// stronger `KeyThenTime` does not - contiguous says only that a series' chunks are adjacent, not +/// that the series arrive in identity order. `KeyThenTime` frames satisfy both, because they are +/// the stronger promise. `Interleaved` frames satisfy neither: they may split one series' chunks +/// with another's, and both admitted inputs are read one series to its last chunk. The refusal +/// names the source, the ordering the producer promises, the one the input asked for, and the input +/// itself. +#[test] +fn the_declared_ordering_must_be_met_by_the_producer() { + let contiguous = SeriesOrdering::Contiguous; + let key_then_time = SeriesOrdering::KeyThenTime; + let interleaved = SeriesOrdering::Interleaved; + // (declared by the tree input, promised by the producer, admitted) + let cases = [ + (contiguous, contiguous, true), + (contiguous, key_then_time, true), + (key_then_time, key_then_time, true), + (key_then_time, contiguous, false), + (contiguous, interleaved, false), + (key_then_time, interleaved, false), + ]; + for (declared, actual, accepted) in cases { + let tree = declaring_orderings(&rate_tree(), &[declared]); + let node = logical(&tree, vec![child()]).expect("the binding matches the tree"); + let built = node.to_execution_plan(vec![( + memory_exec(Vec::new()), + RawLabelSource::Explicit, + actual, + )]); + match (accepted, built) { + (true, Ok(exec)) => assert_eq!( + 1, + exec.properties().output_partitioning().partition_count(), + "{actual:?} frames satisfy an input bound to {declared:?}" + ), + (true, Err(error)) => { + panic!("{actual:?} frames were refused for an input bound to {declared:?}: {error}") + } + (false, Ok(_)) => panic!( + "{actual:?} frames were accepted for an input bound to {declared:?}, which asks \ + for more than they promise" + ), + (false, Err(error)) => { + assert!( + matches!(error, DataFusionError::Plan(_)), + "{declared:?} against {actual:?}: {error}" + ); + let message = error.to_string(); + assert!( + message.contains("ordering"), + "the refusal must say what it is about: {message}" + ); + assert!( + message.contains("source 0"), + "the refusal must name the source: {message}" + ); + assert!( + message.contains(&format!("{actual:?}")), + "the refusal must name the ordering the producer promises: {message}" + ); + assert!( + message.contains(&format!("{declared:?}")), + "the refusal must name the ordering the input asked for: {message}" + ); + assert!( + message.contains("`root.input`"), + "the refusal must name the input that asked for it: {message}" + ); + } + } + } +} + +/// Every input's ordering is checked, not only the first one's. +/// +/// Both operands of this tree are fed by the one child - `x + x` over one scan - but the left one +/// was compiled against contiguous frames and the right one against identity-then-time frames. A +/// check that read only the first input would admit this plan and then run the right operand over +/// frames it never bound. The refusal names the right input, and the same tree builds over frames +/// that really are identity-then-time, which is what makes it about the promise and not the shape. +#[test] +fn every_inputs_ordering_is_checked_not_only_the_first() { + let tree = declaring_orderings( + &binary_tree(raw_schema(), raw_schema()), + &[SeriesOrdering::Contiguous, SeriesOrdering::KeyThenTime], + ); + let node = logical(&tree, vec![child()]).expect("the binding matches the tree"); + let error = node + .to_execution_plan(vec![( + memory_exec(Vec::new()), + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + )]) + .expect_err("the right operand asked for more than the child promises"); + assert!(matches!(error, DataFusionError::Plan(_)), "{error}"); + let message = error.to_string(); + assert!( + message.contains("source 0"), + "the refusal must name the source both inputs read: {message}" + ); + assert!( + message.contains("`root.right.input`"), + "the refusal must name the input that asked for the stronger ordering, not the first \ + one: {message}" + ); + assert!( + message.contains("Contiguous") && message.contains("KeyThenTime"), + "the refusal must name both orderings: {message}" + ); + node.to_execution_plan(vec![( + memory_exec(Vec::new()), + RawLabelSource::Explicit, + SeriesOrdering::KeyThenTime, + )]) + .expect("identity-then-time frames satisfy both inputs"); +} + +/// A tree whose inputs name a source index past the sources it reads is refused. +/// +/// The index is the input's own fact, so a tree that skips an index has no child to read it from: +/// source `1` with no source `0` would silently read the wrong child, and a source past the list +/// would read nothing at all. The refusal names the index. +/// +/// Every index is bounded by the number of input occurrences before any per-index state is sized, +/// so the four indexes below - a skip of one, a sparse one, and the two extremes - are refused +/// rather than reserving slots no input can ever fill: were the bound checked after the sizing, +/// these cases would abort on the allocation instead of answering an error. The sparse index is a +/// shift of `usize::BITS` rather than a fixed literal, so it is out of any real source list's range +/// on a 32-bit target as well as a 64-bit one. +#[test] +fn a_source_index_without_the_sources_below_it_is_refused() { + for index in [1, 1usize << (usize::BITS / 2), usize::MAX / 2, usize::MAX] { + let tree = rate_tree_at(raw_schema(), index); + let error = match logical(&tree, vec![child()]) { + Ok(_) => panic!("source {index} has no source 0 below it, yet the tree was admitted"), + Err(error) => error, + }; + let message = error.to_string(); + assert!( + message.contains(&format!("source index {index}")), + "the refusal must name the index the tree binds: {message}" + ); + } + // The same tree with its input bound to the only child it has is legal, which is what makes the + // refusal about the index and not about the number of children. + logical(&rate_tree_at(raw_schema(), 0), vec![child()]).expect("source 0 is the first child"); +} + +/// A child list that is not one child per source is refused, in both directions. +/// +/// The children are the tree's sources, in source order, so a list that is too short leaves a +/// source unread and a list that is too long carries a child no input names. Both are refused +/// rather than zipped, which would drop whichever side is longer. +#[test] +fn a_tree_wants_one_child_per_source() { + let two_sources = binary_tree_over_sources(BinaryOp::Add, raw_schema(), raw_schema(), 0, 1); + let error = logical(&two_sources, vec![child()]).expect_err("source 1 has no child"); + let message = error.to_string(); + assert!( + message.contains("2 sources") && message.contains("1 child"), + "the refusal must name both counts: {message}" + ); + let one_source = rate_tree(); + let error = logical(&one_source, children(2)).expect_err("the second child is unreferenced"); + let message = error.to_string(); + assert!( + message.contains("1 source") && message.contains("2 child"), + "the refusal must name both counts: {message}" + ); +} + +/// A tree that reads no source is legal only as the statement's constant scalar. +/// +/// A scalar is declared by the type that produces it, so the one zero-input tree this node accepts +/// is a bound [`NativeExpr::Scalar`] on the statement's grid: it reads nothing and its rows are the +/// same value at every grid point. A scalar on another grid is a different value at every grid +/// point than the one the binding names, so it is refused; a tree that produces samples with no +/// input at all would be an empty vector reported as an answer, which is not a shape this node +/// invents. Nothing is read for the scalar yet, so asking for its physical node is refused rather +/// than answered with an empty result. +#[test] +fn a_zero_child_tree_must_be_a_constant_scalar_on_the_statement_grid() { + let scalar = scalar_tree(grid(), 7.0); + let node = FusedSeries::try_new( + Arc::from("7"), + scalar.clone(), + binding(&scalar), + Vec::new(), + output_schema().to_dfschema_ref().unwrap(), + ) + .expect("a constant scalar on the statement's grid reads no source"); + assert!(node.children().is_empty(), "the scalar binds no child"); + let error = node + .to_execution_plan(Vec::new()) + .expect_err("a constant scalar's rows are not produced yet"); + assert!( + matches!( + error, + DataFusionError::Plan(_) | DataFusionError::NotImplemented(_) + ), + "the refusal is explicit, not an empty answer: {error}" + ); + + // The same tree evaluated on another grid is not the statement's scalar. + let elsewhere = scalar_tree( + Arc::new(EvalGrid::try_new(GridSpec::try_new(0, GRID_STEP, GRID_LEN).unwrap()).unwrap()), + 7.0, + ); + let error = FusedSeries::try_new( + Arc::from("7"), + elsewhere.clone(), + FusedSeriesBinding { + grid: binding(&scalar).grid, + ..binding(&elsewhere) + }, + Vec::new(), + output_schema().to_dfschema_ref().unwrap(), + ) + .expect_err("the scalar is not evaluated on the grid the binding names"); + assert!( + error.to_string().contains("constant scalar"), + "the refusal must say the zero-child tree has to be a constant scalar: {error}" + ); +} + +/// The child a tree input reads is part of what the tree is. +/// +/// `a - b` over two scans and the same subtraction with the scans bound the other way round are the +/// same shape while still reading different children at each operand: what tells them apart is the +/// index that makes it part of the tree's own text, and that text is what the logical node compares +/// since the tree carries no structural equality of its own. +#[test] +fn a_source_index_is_part_of_the_tree() { + let left_first = binary_tree_over_sources(BinaryOp::Sub, raw_schema(), raw_schema(), 0, 1); + let right_first = binary_tree_over_sources(BinaryOp::Sub, raw_schema(), raw_schema(), 1, 0); + assert!( + left_first.to_string().contains("source=0") && left_first.to_string().contains("source=1"), + "the tree's text names the source each input reads: {left_first}" + ); + assert_ne!( + left_first.to_string(), + right_first.to_string(), + "the two bindings of the same subtraction are different trees" + ); + + let mine = logical(&left_first, children(2)).expect("both sources have a child"); + let theirs = logical(&right_first, children(2)).expect("the same sources, bound the other way"); + assert_ne!(mine, theirs, "the swapped tree is another computation"); + assert_ne!( + Some(std::cmp::Ordering::Equal), + mine.partial_cmp(&theirs), + "a different tree is not ordered equal to this one" + ); +} + +/// The execution children are one per child, in both directions. +/// +/// A zip would drop the longer side, so a caller that passes one child too many would have it /// silently ignored and a caller that passes one too few would run a tree over half its sources. #[test] -fn the_execution_inputs_must_be_one_per_binding() { +fn the_execution_children_must_be_one_per_child() { let tree = rate_tree(); let node = fused(tree); let bare = || memory_exec(Vec::new()); @@ -1974,31 +2255,31 @@ fn the_execution_inputs_must_be_one_per_binding() { (bare(), RawLabelSource::Explicit, SeriesOrdering::Contiguous), (bare(), RawLabelSource::Explicit, SeriesOrdering::Contiguous), ]) - .expect_err("two execution inputs for one binding"); + .expect_err("two execution children for one child"); assert!( error.to_string().contains("2 execution inputs were given"), "{error}" ); let error = node .to_execution_plan(Vec::new()) - .expect_err("no execution input for one binding"); + .expect_err("no execution child for one child"); assert!( error.to_string().contains("0 execution inputs were given"), "{error}" ); } -/// The physical inputs of the node must number its bindings, whoever plans it. +/// The physical inputs of the node must number its children, whoever plans it. /// /// DataFusion plans every physical child before it asks for the node, so its own route always -/// matches the count. A direct call of `plan_extension` need not, and the bindings are paired with +/// matches the count. A direct call of `plan_extension` need not, and the children are paired with /// the inputs by position, so a list of another length is a plan error naming both counts instead -/// of a binding read past its end or an input silently ignored. The inputs here are memory sources, +/// of a child read past its end or an input silently ignored. The inputs here are memory sources, /// which this node cannot read as raw series: that they are refused for their count and not for /// their type is what shows the count is asked before a child is looked at, since the scan check /// would have answered `Ok(None)` for both counts instead. #[tokio::test] -async fn the_physical_inputs_must_number_the_bindings() { +async fn the_physical_inputs_must_number_the_children() { let node = fused(rate_tree()); let planner = DefaultPhysicalPlanner::default(); let session = SessionContext::default(); @@ -2011,14 +2292,8 @@ async fn the_physical_inputs_must_number_the_bindings() { let error = PromExtensionPlanner .plan_extension(&planner, &node, &[], &inputs, &state, &planning_ctx) .await - .expect_err("the node binds one input, whatever it was given"); + .expect_err("the node binds one child, whatever it was given"); assert!(matches!(error, DataFusionError::Plan(_)), "{error}"); - assert!( - error.to_string().contains(&format!( - "binds 1 inputs, but {count} physical inputs were given" - )), - "{error}" - ); } let planned = PromExtensionPlanner .plan_extension( @@ -2037,67 +2312,51 @@ async fn the_physical_inputs_must_number_the_bindings() { ); } -/// The physical children cover the tree's destinations exactly, one child per actual source. +/// The physical children must number the tree's sources. +/// +/// The tree's own input nodes say how many children it reads, so a child list of another length is +/// refused where the physical node is built: a shorter one leaves a source unread, and the tree +/// would run over part of its input. #[test] -fn the_physical_children_must_cover_every_destination() { - let tree = binary_tree(raw_schema(), raw_schema()); - let [left, right] = binary_paths(); - let build = |children: Vec| { - FusedSeriesExec::try_new( - Arc::from("a + on(host) a"), - children, - Arc::new(tree.clone()), - output_schema(), - TIME.into(), - vec![HOST.into(), NAME.into()], - ) - }; - let error = build(vec![child_at(vec![left.clone()], Vec::new())]) - .expect_err("the right destination has no child"); +fn the_physical_children_must_number_the_trees_sources() { + let tree = binary_tree_over_sources(BinaryOp::Add, raw_schema(), raw_schema(), 0, 1); + let error = FusedSeriesExec::try_new( + Arc::from("a + on(host) b"), + vec![( + memory_exec(Vec::new()), + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + )], + Arc::new(tree), + output_schema(), + TIME.into(), + default_tags(), + ) + .expect_err("the tree reads two sources and was given one child"); + let message = error.to_string(); assert!( - error - .to_string() - .contains("binds no source for the tree input `root.right.input`"), - "{error}" - ); - let error = build(vec![ - child_at(vec![left.clone()], Vec::new()), - child_at(vec![left.clone()], Vec::new()), - child_at(vec![right.clone()], Vec::new()), - ]) - .expect_err("two children read the left destination"); - assert!(error.to_string().contains("more than once"), "{error}"); - let mut two_fields = child_at(vec![left.clone(), right.clone()], Vec::new()); - two_fields.4 = two_field_schema(); - let error = build(vec![two_fields]).expect_err("the tree's inputs read one field"); - assert!( - error.to_string().contains("not compiled against"), - "{error}" + message.contains("2 sources") && message.contains("1 child"), + "the refusal must name both counts: {message}" ); } -/// Rebuilding a node over new inputs keeps the destinations, and revalidation decides. +/// Rebuilding a node over new children keeps the arity and the fields they must provide. /// -/// A rewrite above this node replaces the plans below it and nothing else: the destinations are the -/// node's own fact, so they travel unchanged, while the arity the bindings demand is asked again. +/// A rewrite above this node replaces the plans below it and nothing else: the binding is the +/// node's own fact, so it travels unchanged, while the number of children and the fields each of +/// them must carry are asked again. A replacement child missing a field the tree reads is refused +/// rather than decoded with a stale layout. #[test] -fn with_exprs_and_inputs_keeps_the_destinations() { +fn with_exprs_and_inputs_keeps_the_arity_and_the_fields() { let tree = binary_tree(raw_schema(), raw_schema()); - let node = logical( - &tree, - vec![binding_at( - binary_paths().to_vec(), - input_plan(frame_schema()), - )], - ) - .expect("one source covers both of the tree's inputs"); + let node = logical(&tree, vec![child()]).expect("one child covers both of the tree's inputs"); let rebuilt = node - .with_exprs_and_inputs(vec![], vec![input_plan(frame_schema())]) - .expect("one plan still covers both destinations"); + .with_exprs_and_inputs(vec![], vec![child()]) + .expect("one child still covers both of the tree's inputs"); assert_eq!( - binary_paths().to_vec(), - rebuilt.fused_inputs()[0].paths, - "the destinations must survive a rewrite above the node" + node.binding(), + rebuilt.binding(), + "the binding must survive a rewrite above the node" ); assert_eq!( node.schema(), @@ -2106,8 +2365,21 @@ fn with_exprs_and_inputs_keeps_the_destinations() { ); let error = node .with_exprs_and_inputs(vec![], Vec::new()) - .expect_err("the one binding needs one plan"); + .expect_err("the one child cannot be dropped"); assert!(error.to_string().contains("expected 1 inputs"), "{error}"); + // The replacement has to carry the field the tree's input reads. + let other = input_plan(Arc::new(Schema::new(vec![Field::new( + OTHER, + DataType::Float64, + true, + )]))); + let error = node + .with_exprs_and_inputs(vec![], vec![other]) + .expect_err("the replacement child has no `value` column"); + assert!( + error.to_string().contains("no column"), + "the refusal must name the missing column: {error}" + ); } /// A tree the runtime does not execute is refused when the execution plan is built. @@ -2134,12 +2406,14 @@ 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 }; let error = FusedSeries::try_new( Arc::from(PROMQL), tree.clone(), - binding, - one_input(&tree, input_plan(frame_schema())), + FusedSeriesBinding { + grid: other_grid, + ..binding(&tree) + }, + vec![child()], output_schema().to_dfschema_ref().unwrap(), ) .expect_err("the tree is not evaluated on the declared grid"); @@ -2162,12 +2436,14 @@ 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 }; let _node = FusedSeries::try_new( Arc::from(PROMQL), tree.clone(), - binding, - one_input(&tree, input_plan(frame_schema())), + FusedSeriesBinding { + grid: equal, + ..binding(&tree) + }, + vec![child()], output_schema().to_dfschema_ref().unwrap(), ) .expect("an equal grid spec is the same grid"); @@ -2452,321 +2728,6 @@ fn a_window_over_raw_input_on_two_partitions_is_accepted() { .expect("ordinary input-to-window trees do not split a logical series"); } -/// A child that notifies between parent polls is not lost behind an all-pending combinator pass. -/// -/// `SelectAll` polls every child once and cooperatively wakes the parent, then parks until a child -/// notifies. The wake from that first pass is cleared here so the wake asserted after it is the -/// child's own, and the parent is only polled while that notification is outstanding. -#[test] -fn a_child_woken_between_parent_polls_is_not_lost() { - let schema = raw_schema(); - let woken = Arc::new(CountingWake::default()); - let child_count = POLL_BUDGET + 1; - let poll_counts = (0..child_count) - .map(|_| Arc::new(AtomicUsize::new(0))) - .collect::>(); - let child_waker = Arc::new(std::sync::Mutex::new(None)); - let child_ready = Arc::new(AtomicBool::new(false)); - let inputs: Vec<_> = poll_counts - .iter() - .enumerate() - .map(|(index, count)| { - let count = Arc::clone(count); - let child_waker = Arc::clone(&child_waker); - let child_ready = Arc::clone(&child_ready); - let batches = Box::pin( - datafusion::physical_plan::stream::RecordBatchStreamAdapter::new( - frame_schema(), - futures::stream::poll_fn({ - let child_waker = Arc::clone(&child_waker); - let child_ready = Arc::clone(&child_ready); - move |cx| { - count.fetch_add(1, Ordering::SeqCst); - if index == 0 { - *child_waker.lock().unwrap() = Some(cx.waker().clone()); - if child_ready.load(Ordering::SeqCst) { - return Poll::Ready(Some(Err(DataFusionError::Execution( - "woken first child failed".to_string(), - )))); - } - } - Poll::Pending - } - }), - ), - ); - let decoded = super::unpack_raw_series(batches, Some(Arc::clone(&schema))) - .expect("the empty raw-frame stream decodes"); - let stream = super::materialize_raw_labels(decoded) - .expect("the empty raw-frame stream materializes labels"); - (vec![NodePath::root().input()], Some(stream), false) - }) - .collect(); - let mut stream = super::FusedSeriesStream { - inputs: inputs.into_iter().fold( - futures::stream::SelectAll::new(), - |mut all, (path, stream, _)| { - all.push(Box::pin( - stream - .expect("input stream exists") - .map(move |item| (path.clone(), item)), - ) as super::TaggedInputStream); - all - }, - ), - executor: None, - classification: Arc::from([]), - tags: Arc::from([]), - output_schema: output_schema(), - labels: Arc::new(std::sync::Mutex::new(super::LabelSets::default())), - ready: VecDeque::new(), - input_ended: false, - done: false, - }; - - let waker = futures::task::waker(Arc::clone(&woken)); - let mut context = Context::from_waker(&waker); - assert!(Pin::new(&mut stream).poll_next(&mut context).is_pending()); - assert!(child_waker.lock().unwrap().is_some(), "child 0 was polled"); - assert!( - woken.woken(), - "the combinator's first all-pending pass wakes once" - ); - // Clear that cooperative yield so the next wake can only be the child's. - woken.clear(); - child_ready.store(true, Ordering::SeqCst); - child_waker.lock().unwrap().as_ref().unwrap().wake_by_ref(); - assert!(woken.woken(), "the child notification reaches the parent"); - let mut saw_error = false; - for _ in 0..4 { - assert!(woken.woken(), "drive only on a notification"); - woken.clear(); - match Pin::new(&mut stream).poll_next(&mut context) { - Poll::Ready(Some(Err(DataFusionError::External(error)))) => { - assert!(error.to_string().contains("woken first child failed")); - saw_error = true; - break; - } - Poll::Pending => {} - other => panic!("unexpected stream result: {other:?}"), - } - } - assert!(saw_error, "the woken child error must be observed"); - assert_eq!( - 2, - poll_counts[0].load(Ordering::SeqCst), - "child 0 was polled by the first pass and again after its wake" - ); - assert_eq!(1, poll_counts[POLL_BUDGET].load(Ordering::SeqCst)); - assert!(stream.done, "the error ends the stream"); - assert!(stream.executor.is_none(), "the error releases the executor"); - assert!(stream.ready.is_empty(), "the error drops queued batches"); - assert!(stream.inputs.is_empty(), "the error releases every input"); - let counts: Vec<_> = poll_counts - .iter() - .map(|count| count.load(Ordering::SeqCst)) - .collect(); - assert!(matches!( - Pin::new(&mut stream).poll_next(&mut context), - Poll::Ready(None) - )); - assert_eq!( - counts, - poll_counts - .iter() - .map(|count| count.load(Ordering::SeqCst)) - .collect::>(), - "a terminal poll polls no child" - ); -} - -/// A ready error at child 65 is not starved behind earlier pending children. -#[test] -fn late_child_error_is_not_starved() { - let schema = raw_schema(); - let poll_counts = (0..=POLL_BUDGET) - .map(|_| Arc::new(AtomicUsize::new(0))) - .collect::>(); - let inputs: Vec<_> = poll_counts - .iter() - .enumerate() - .map(|(index, count)| { - let count = Arc::clone(count); - let batches = Box::pin( - datafusion::physical_plan::stream::RecordBatchStreamAdapter::new( - frame_schema(), - futures::stream::poll_fn(move |_| { - count.fetch_add(1, Ordering::SeqCst); - if index == POLL_BUDGET { - Poll::Ready(Some(Err(DataFusionError::Execution( - "late child failed".to_string(), - )))) - } else { - Poll::Pending - } - }), - ), - ); - let decoded = super::unpack_raw_series(batches, Some(Arc::clone(&schema))) - .expect("the empty raw-frame stream decodes"); - let stream = super::materialize_raw_labels(decoded) - .expect("the empty raw-frame stream materializes labels"); - (vec![NodePath::root().input()], stream) - }) - .collect(); - let mut input_streams = futures::stream::SelectAll::new(); - input_streams.extend(inputs.into_iter().map(|(path, stream)| { - Box::pin(stream.map(move |item| (path.clone(), item))) as super::TaggedInputStream - })); - let mut stream = super::FusedSeriesStream { - inputs: input_streams, - executor: None, - classification: Arc::from([]), - tags: Arc::from([]), - output_schema: output_schema(), - labels: Arc::new(std::sync::Mutex::new(super::LabelSets::default())), - ready: VecDeque::new(), - input_ended: false, - done: false, - }; - let waker = futures::task::noop_waker(); - let mut context = Context::from_waker(&waker); - assert!(matches!( - Pin::new(&mut stream).poll_next(&mut context), - Poll::Ready(Some(Err(DataFusionError::External(error)))) - if error.to_string().contains("late child failed") - )); - assert!( - poll_counts - .iter() - .all(|count| count.load(Ordering::SeqCst) == 1), - "the first combinator pass polls every child once, the last one included" - ); - assert!(stream.done); - assert!(stream.executor.is_none()); - assert!(stream.ready.is_empty()); - assert!(stream.inputs.is_empty()); - let counts: Vec<_> = poll_counts - .iter() - .map(|count| count.load(Ordering::SeqCst)) - .collect(); - assert!(matches!( - Pin::new(&mut stream).poll_next(&mut context), - Poll::Ready(None) - )); - assert_eq!( - counts, - poll_counts - .iter() - .map(|count| count.load(Ordering::SeqCst)) - .collect::>() - ); -} - -/// A fully pending input set parks after the combinator's one cooperative yield. -#[test] -fn all_pending_children_park_without_self_wake() { - for child_count in [POLL_BUDGET, POLL_BUDGET + 1] { - let schema = raw_schema(); - let woken = Arc::new(CountingWake::default()); - let poll_counts = (0..child_count) - .map(|_| Arc::new(AtomicUsize::new(0))) - .collect::>(); - let inputs: Vec<_> = poll_counts - .iter() - .map(|count| { - let count = Arc::clone(count); - let batches = Box::pin( - datafusion::physical_plan::stream::RecordBatchStreamAdapter::new( - frame_schema(), - futures::stream::poll_fn(move |_| { - count.fetch_add(1, Ordering::SeqCst); - Poll::Pending - }), - ), - ); - let decoded = super::unpack_raw_series(batches, Some(Arc::clone(&schema))) - .expect("the empty raw-frame stream decodes"); - let stream = super::materialize_raw_labels(decoded) - .expect("the empty raw-frame stream materializes labels"); - (vec![NodePath::root().input()], Some(stream), false) - }) - .collect(); - let mut stream = super::FusedSeriesStream { - inputs: inputs.into_iter().fold( - futures::stream::SelectAll::new(), - |mut all, (path, stream, _)| { - all.push(Box::pin( - stream - .expect("input stream exists") - .map(move |item| (path.clone(), item)), - ) as super::TaggedInputStream); - all - }, - ), - executor: None, - classification: Arc::from([]), - tags: Arc::from([]), - output_schema: output_schema(), - labels: Arc::new(std::sync::Mutex::new(super::LabelSets::default())), - ready: VecDeque::new(), - input_ended: false, - done: false, - }; - let waker = futures::task::waker(Arc::clone(&woken)); - let mut context = Context::from_waker(&waker); - // The first pass polls every child once, then the combinator wakes once to yield. - assert!(Pin::new(&mut stream).poll_next(&mut context).is_pending()); - assert!( - woken.woken(), - "the combinator's first all-pending pass wakes once" - ); - assert!( - poll_counts - .iter() - .all(|count| count.load(Ordering::SeqCst) == 1), - "every child is polled exactly once in the first pass" - ); - let mut drained = 0; - for _ in 0..4 { - if !woken.woken() { - break; - } - woken.clear(); - assert!(Pin::new(&mut stream).poll_next(&mut context).is_pending()); - drained += 1; - } - assert!(drained > 0, "the cooperative yield is drained"); - assert!( - !woken.woken(), - "a parked all-pending set must not self-wake" - ); - assert!( - poll_counts - .iter() - .all(|count| count.load(Ordering::SeqCst) == 1), - "no child is polled again without a notification" - ); - let counts: Vec<_> = poll_counts - .iter() - .map(|count| count.load(Ordering::SeqCst)) - .collect(); - assert!(Pin::new(&mut stream).poll_next(&mut context).is_pending()); - assert!( - !woken.woken(), - "an unnotified poll of a parked set must not self-wake" - ); - assert_eq!( - counts, - poll_counts - .iter() - .map(|count| count.load(Ordering::SeqCst)) - .collect::>(), - "an unnotified poll of a parked set polls no child" - ); - } -} - /// One poll reads at most [`POLL_BUDGET`] chunks of input, and stopping there loses nothing. /// /// `rate(x[5m])` decides nothing until a sample reaches the grid's first point, so a series can @@ -3320,16 +3281,11 @@ async fn a_partition_past_the_inputs_count_is_refused() { /// The `rate(x[5m])` tree over two fields, with both fields and the tags in the output. fn two_field_node() -> FusedSeries { let tree = rate_tree_of(two_field_schema()); - let binding = binding_of( - &tree, - two_field_schema(), - vec![HOST.to_string(), NAME.to_string()], - ); FusedSeries::try_new( Arc::from(PROMQL), tree.clone(), - binding, - one_input(&tree, input_plan(frame_schema_of(&two_field_schema()))), + binding(&tree), + vec![input_plan(frame_schema_of(&two_field_schema()))], two_field_output_schema().to_dfschema_ref().unwrap(), ) .expect("the binding matches the tree") @@ -3965,24 +3921,21 @@ fn a_refused_growth_keeps_shared_label_entry_unchanged() { ); } -/// Binding ordering includes field names, while schema ordering refuses unequal DF schemas. +/// A binding is ordered by its grid, its time column, its tags and its metric, while a node is +/// ordered last by its output schema and refuses unequal DF schemas. #[test] fn unequal_binding_and_output_schema_are_not_ordered_equal() { let tree = rate_tree(); let left = binding(&tree); - let other_schema = Arc::new(SeriesSchema { - fields: Arc::from([FieldSpec { - name: "different".into(), - }]), - eval_grid: None, - }); - let right = binding_of( - &tree, - other_schema, - vec![HOST.to_string(), NAME.to_string()], - ); + let right = binding_of(&tree, default_tags()); assert_eq!(left, right); assert_eq!(Some(std::cmp::Ordering::Equal), left.partial_cmp(&right)); + let named = FusedSeriesBinding { + metric_name: Some(Arc::from("another_metric")), + ..binding(&tree) + }; + assert_ne!(left, named); + assert_ne!(Some(std::cmp::Ordering::Equal), left.partial_cmp(&named)); let left_node = fused(tree.clone()); let nullability_changed = Arc::new(Schema::new(vec![ @@ -3999,7 +3952,7 @@ fn unequal_binding_and_output_schema_are_not_ordered_equal() { Arc::from(PROMQL), tree.clone(), binding(&rate_tree()), - one_input(&tree, input_plan(frame_schema())), + vec![child()], 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 266f063f058..9278bf668bb 100644 --- a/src/promql/src/extension_plan/planner.rs +++ b/src/promql/src/extension_plan/planner.rs @@ -82,7 +82,7 @@ impl ExtensionPlanner for PromExtensionPlanner { /// column of any region. const METRIC_NAME: &str = "__name__"; -/// Builds the physical node of a [`FusedSeries`] over the raw series leaf its input can provide. +/// Builds the physical node of a [`FusedSeries`] over the raw series leaf its one child can provide. /// /// The node reads a raw series frame, so what it needs below it is the region scan itself: the /// scan's own raw-series entrypoint is what packs a series' chunks contiguously and declares their @@ -96,29 +96,54 @@ const METRIC_NAME: &str = "__name__"; /// reported as an error that names the reason instead of silently producing no plan. /// The fused leaf needs a prepared scan: range assignment runs after physical planning and cannot /// see a `SeriesScanExec`. Preparation keeps the scan's parallel layout, and the series-producer -/// contract guarantees that one series stays in one scan partition. +/// contract guarantees that one series stays in one scan partition. The fields the scan is asked +/// for are the tree's own, and a node with no child (a constant scalar) or with several (which +/// would need a label-pairing exchange) is refused here rather than planned into a node that +/// cannot run it. fn plan_fused_series( fused: &FusedSeries, physical_inputs: &[Arc], target_partitions: usize, ) -> DfResult>> { - // The bindings and the physical inputs are paired by position below, so an input list of another + // The children and the physical inputs are paired by position below, so an input list of another // length is refused before anything is read off it. DataFusion plans every child of an extension // node before it calls here, so its own route always matches this count; a direct call of // `plan_extension` need not. - let expected = fused.fused_inputs().len(); - if physical_inputs.len() != expected { + let children = fused.children(); + if physical_inputs.len() != children.len() { return Err(DataFusionError::Plan(format!( - "FusedSeries binds {expected} inputs, but {} physical inputs were given", + "FusedSeries binds {} inputs, but {} physical inputs were given", + children.len(), physical_inputs.len() ))); } - let mut prepared = Vec::new(); + // One plan below is one actual source, which is what the physical node reads. A constant scalar + // has no plan to read and several sources would have to be paired by label, which needs an + // exchange this layer does not build: both are refused by name rather than planned into a node + // that cannot run them. + if children.is_empty() { + return Err(DataFusionError::Plan( + "the FusedSeries node reads no source: a constant scalar is not planned by this layer \ + yet" + .to_string(), + )); + } + if children.len() > 1 { + return Err(DataFusionError::Plan(format!( + "the FusedSeries node reads {} sources, and planning several of them as one tree is not \ + supported", + children.len() + ))); + } + // Which columns the scan below must produce are the fields the tree's own input reads, not a + // description kept beside the tree. + let source_fields = super::fused_series::tree_source_fields(fused.tree())?; + let binding = fused.binding(); + let mut prepared = Vec::with_capacity(children.len()); 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(), @@ -130,12 +155,11 @@ fn plan_fused_series( .filter(|tag| tag.as_str() != METRIC_NAME) .cloned() .collect::>(); - let fields = binding - .series_schema - .fields - .iter() - .map(|field| field.name.to_string()) - .collect::>(); + let Some(fields) = source_fields.get(index) else { + return Err(DataFusionError::Plan(format!( + "the FusedSeries tree reads no input at source {index}" + ))); + }; let scan = if scan.is_partition_set() { Arc::new(scan.clone()) } else { @@ -147,7 +171,7 @@ fn plan_fused_series( .map_err(|e| DataFusionError::External(e.into_inner()))?, ) }; - let Some(series_scan) = scan.try_to_named_series_scan(metric_name, &tags, &fields)? else { + 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:?}" ))); diff --git a/src/promql/src/native/display.rs b/src/promql/src/native/display.rs index 2ec085a7d60..550ed7238c8 100644 --- a/src/promql/src/native/display.rs +++ b/src/promql/src/native/display.rs @@ -29,8 +29,8 @@ use crate::histogram_eval::HistogramFunction; use crate::map::MathOp; use crate::native::metrics::{self, NodePath}; use crate::native::plan::{ - AggregateKind, AggregateStage, BoundVectorOp, BoundWindow, Grouping, MapOp, NativeExpr, - NativeNode, NativeTree, NativeType, + AggregateKind, AggregateStage, BoundInput, BoundVectorOp, BoundWindow, Grouping, MapOp, + NativeExpr, NativeNode, NativeTree, NativeType, }; use crate::range_eval::RangeFunction; use crate::select::SortOrder; @@ -84,14 +84,11 @@ fn ordering(ordering: SeriesOrdering) -> &'static str { /// The operation a node computes, in the words of the query that produced it. fn describe(node: &NativeNode) -> String { match &node.expr { - NativeExpr::Input(input) => match &input.output { - NativeType::Samples(schema) if schema.eval_grid.is_some() => { - format!("evaluated samples{}", ordering(input.ordering)) - } - NativeType::Samples(_) => format!("raw samples{}", ordering(input.ordering)), - NativeType::Scalar(grid) => format!("scalar on grid {}", grid_name(grid)), - NativeType::AggregateState(_) => "aggregate state".to_string(), - }, + // The source index is part of the input: inputs over different sources are different + // inputs even when they hand over the same layout and ordering. + NativeExpr::Input(input) => { + format!("source={} {}", input.source_index, input_value(input)) + } NativeExpr::Scalar(scalar) => scalar.value.to_string(), NativeExpr::Instant { op, .. } => format!( "lookback {}ms offset {} on grid {}", @@ -165,6 +162,18 @@ fn describe(node: &NativeNode) -> String { } } +/// What an input hands over: its samples or state, with the ordering it guarantees. +fn input_value(input: &BoundInput) -> String { + match &input.output { + NativeType::Samples(schema) if schema.eval_grid.is_some() => { + format!("evaluated samples{}", ordering(input.ordering)) + } + NativeType::Samples(_) => format!("raw samples{}", ordering(input.ordering)), + NativeType::Scalar(grid) => format!("scalar on grid {}", grid_name(grid)), + NativeType::AggregateState(_) => "aggregate state".to_string(), + } +} + fn fill(values: FillValues) -> String { let side = |name: &str, value: Option| { value diff --git a/src/promql/src/native/display/tests.rs b/src/promql/src/native/display/tests.rs index 84210f4ee0c..98d680992cf 100644 --- a/src/promql/src/native/display/tests.rs +++ b/src/promql/src/native/display/tests.rs @@ -48,6 +48,11 @@ fn evaluated(grid: Arc) -> NativeType { /// An unqualified scan over raw samples, which is what a compiled query starts from. fn raw_input() -> NativeNode { + raw_input_from(0) +} + +/// The same scan bound to child `source_index` of the final execution tree. +fn raw_input_from(source_index: usize) -> NativeNode { // One allocation shared by the binding and the output: `validate` checks allocation identity. // The fields are the ones a window over this input reports, because a window keeps its input's // layout and `validate` rejects a node that declares a different count. @@ -57,6 +62,7 @@ fn raw_input() -> NativeNode { })); NativeNode { expr: NativeExpr::Input(BoundInput { + source_index, output: output.clone(), ordering: SeriesOrdering::KeyThenTime, }), @@ -117,7 +123,7 @@ fn the_first_line_names_the_tree() { assert_eq!( tree.to_string(), - shown(&["NativeTree", " root Input raw samples"]) + shown(&["NativeTree", " root Input source=0 raw samples"]) ); assert_eq!(tree.to_string().lines().next(), Some("NativeTree")); } @@ -141,7 +147,7 @@ fn a_window_over_raw_samples_is_shown_once_per_node() { shown(&[ "NativeTree", " root Window rate [300000ms] offset 0 anchor - on grid 0/60000x4", - " input Input raw samples", + " input Input source=0 raw samples", ]) ); } @@ -169,7 +175,7 @@ fn a_map_nests_below_the_window_it_maps() { "NativeTree", " root Map abs, round 3", " input Window rate [300000ms] offset 60000 anchor - on grid 0/60000x4", - " input Input raw samples", + " input Input source=0 raw samples", ]) ); } @@ -193,7 +199,7 @@ fn a_window_names_its_constant_argument_and_its_anchor() { shown(&[ "NativeTree", " root Window quantile_over_time 0.9 [60000ms] offset 0 anchor 42 on grid 1000/60000x4", - " input Input raw samples", + " input Input source=0 raw samples", ]) ); } @@ -208,6 +214,7 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() { })); let evaluated_input = NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: contiguous.clone(), ordering: SeriesOrdering::Contiguous, }), @@ -216,7 +223,10 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() { let tree = NativeTree::try_new(evaluated_input).unwrap(); assert_eq!( tree.to_string(), - shown(&["NativeTree", " root Input evaluated samples, contiguous",]) + shown(&[ + "NativeTree", + " root Input source=0 evaluated samples, contiguous", + ]) ); let interleaved = NativeType::Samples(Arc::new(SeriesSchema { @@ -225,6 +235,7 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() { })); let raw_input = NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: interleaved.clone(), ordering: SeriesOrdering::Interleaved, }), @@ -233,7 +244,72 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() { let tree = NativeTree::try_new(raw_input).unwrap(); assert_eq!( tree.to_string(), - shown(&["NativeTree", " root Input raw samples, interleaved"]) + shown(&[ + "NativeTree", + " root Input source=0 raw samples, interleaved" + ]) + ); +} + +/// The child an input reads is part of its line: two trees over different children, or over one +/// child shared by both inputs, do not render as the same text. +#[test] +fn an_input_names_the_child_it_reads() { + let out = grid(0, 60_000, 4); + let selected = |source_index: usize| NativeNode { + expr: NativeExpr::Instant { + input: Box::new(raw_input_from(source_index)), + op: BoundInstant { + lookback_ms: 300_000, + offset_ms: 0, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(Arc::clone(&out)), + }; + let tree = |left: usize, right: usize| { + NativeTree::try_new(NativeNode { + expr: NativeExpr::Binary { + left: Box::new(selected(left)), + right: Box::new(selected(right)), + matching: BinaryMatching { + op: BinaryOp::Add, + return_bool: false, + labels: MatchingLabels::Ignoring(Vec::new()), + cardinality: Cardinality::OneToOne, + fill: FillValues::default(), + }, + }, + output: evaluated(Arc::clone(&out)), + }) + .unwrap() + }; + + let distinct = tree(0, 1).to_string(); + assert_eq!( + distinct, + shown(&[ + "NativeTree", + " root Binary + ignoring [] one-to-one", + " left Instant lookback 300000ms offset 0 on grid 0/60000x4", + " input Input source=0 raw samples", + " right Instant lookback 300000ms offset 0 on grid 0/60000x4", + " input Input source=1 raw samples", + ]) + ); + + let shared = tree(0, 0).to_string(); + assert_eq!( + shared + .lines() + .filter(|line| line.ends_with("Input source=0 raw samples")) + .count(), + 2, + "{shared}" + ); + assert_ne!( + shared, distinct, + "two trees differ in the child each input reads" ); } @@ -266,7 +342,7 @@ fn a_scalar_and_an_instant_line_show_what_they_hold() { shown(&[ "NativeTree", " root Instant lookback 300000ms offset 60000 on grid 0/60000x4", - " input Input raw samples", + " input Input source=0 raw samples", ]) ); } @@ -301,7 +377,7 @@ fn an_aggregate_and_a_binary_name_their_binding() { "NativeTree", " root Aggregate sum by [job] complete", " input Window rate [300000ms] offset 0 anchor - on grid 0/60000x4", - " input Input raw samples", + " input Input source=0 raw samples", ]) ); @@ -339,7 +415,7 @@ fn an_aggregate_and_a_binary_name_their_binding() { " root Binary + ignoring [] one-to-one", " left Scalar 2", " right Window rate [300000ms] offset 0 anchor - on grid 0/60000x4", - " input Input raw samples", + " input Input source=0 raw samples", ]) ); @@ -392,7 +468,7 @@ fn a_without_grouping_does_not_read_as_by() { "NativeTree", " root Aggregate sum without [job] complete", " input Window rate [300000ms] offset 0 anchor - on grid 0/60000x4", - " input Input raw samples", + " input Input source=0 raw samples", ]) ); } diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 9770d800a37..8e53cbfcbc8 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -384,6 +384,10 @@ struct NodeSpec { /// The index of this node's input, which is the node the build pass reaches next: the one /// input of a unary node, the left operand of a binary node, and none for an input node. input: Option, + /// The index of the input source an input node reads; `None` for every other node. + /// + /// The index is local to this execution, and several inputs may carry the same one. + source_index: Option, } /// The series whose first chunk this buffer received and whose closing chunk it has not seen. @@ -2885,6 +2889,7 @@ pub struct NativeExecutionState { /// /// A tree of unary nodes has one, and a binary node adds one per operand: a tree of nested /// binary nodes has as many as it has leaves, and a queued chunk names the one it belongs to. + /// Several of them may share a `NodeSpec::source_index`, so one source's chunk feeds them all. sources: Vec, } @@ -3129,9 +3134,15 @@ impl NativeExecutionState { true } }; + // The source an input reads; every other node is fed by the one its spec names. + let source_index = match &node.expr { + NativeExpr::Input(bound) => Some(bound.source_index), + _ => None, + }; nodes.push(NodeSpec { tag, input: reads_input.then_some(index + 1), + source_index, }); exprs.push(&node.expr); paths.push(path.clone()); @@ -3557,6 +3568,20 @@ impl NativeExecutor { self.push_source(Some(path), NativeChunk::Raw(chunk)) } + /// Queues one raw source chunk at every input bound to source `source_index`. + /// + /// The index is local to this execution, and several inputs may name one source: each of them + /// gets the chunk -- all but the last from a copy. The inputs of one index have to read the + /// same raw samples, and an index no input names is refused; either stops the execution. + pub fn push_raw_source(&mut self, source_index: usize, chunk: RawSeriesChunk) -> Result<()> { + self.check_running()?; + let result = self.queue_raw_source(source_index, chunk); + if let Err(error) = &result { + self.stop(error); + } + result + } + /// Queues one evaluated source chunk at the input node at `path`. pub fn push_evaluated_at(&mut self, path: &NodePath, chunk: EvaluatedChunk) -> Result<()> { self.push_source(Some(path), NativeChunk::Evaluated(chunk)) @@ -4097,6 +4122,76 @@ impl NativeExecutor { /// Queues a source chunk at one input node, checking it against that input's binding. fn queue_source(&mut self, path: Option<&NodePath>, chunk: NativeChunk) -> Result<()> { let source = self.source_index(path)?; + self.queue_source_at(source, chunk) + } + + /// Queues one raw source chunk at every input bound to source `source_index`, in traversal + /// order: the last of them takes the caller's chunk, the ones before it a copy. + fn queue_raw_source(&mut self, source_index: usize, chunk: RawSeriesChunk) -> Result<()> { + let last = self + .state + .sources + .iter() + .rposition(|&source| self.state.nodes[source].source_index == Some(source_index)) + .ok_or_else(|| { + DataFusionError::Execution(format!( + "the native execution has no input bound to source {source_index}" + )) + })?; + // One chunk reaches every one of them, so they have to read the same raw samples: an input + // of another layout, or one over an evaluated series, cannot take it. The check runs before + // the first copy is queued, so a refusal leaves no input holding one. + let mut baseline: Option<(usize, Arc)> = None; + for &source in &self.state.sources[..=last] { + if self.state.nodes[source].source_index != Some(source_index) { + continue; + } + let at = &self.state.paths[source]; + let schema = self.state.runtimes[source] + .source_schema + .clone() + .ok_or_else(|| { + DataFusionError::Execution(format!( + "the input node at {at} does not produce samples" + )) + })?; + if schema.eval_grid.is_some() { + return Err(DataFusionError::Execution(format!( + "the native source {source_index} hands over raw samples, but the input at {at} \ + reads an evaluated series" + ))); + } + match &baseline { + None => baseline = Some((source, schema)), + Some((first, bound)) => { + if !schema + .fields + .iter() + .map(|field| &field.name) + .eq(bound.fields.iter().map(|field| &field.name)) + { + return Err(DataFusionError::Execution(format!( + "the native source {source_index} feeds two layouts: the inputs at {} \ + and {at} differ in their fields", + self.state.paths[*first] + ))); + } + } + } + } + for position in 0..last { + let source = self.state.sources[position]; + if self.state.nodes[source].source_index != Some(source_index) { + continue; + } + self.queue_source_at(source, NativeChunk::Raw(chunk.clone()))?; + } + let source = self.state.sources[last]; + self.queue_source_at(source, NativeChunk::Raw(chunk)) + } + + /// Queues a source chunk at the input node at `source`, checking it against its binding. + fn queue_source_at(&mut self, source: usize, chunk: NativeChunk) -> Result<()> { let at = &self.state.paths[source]; let Some(binding) = self.state.runtimes[source].source_schema.as_ref() else { return Err(DataFusionError::Execution(format!( diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index eca5992c05d..e77c76ad4f9 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -107,9 +107,17 @@ fn input() -> NativeNode { /// The same raw source, declaring `ordering`. fn raw_input_with_ordering(ordering: SeriesOrdering) -> NativeNode { + raw_input_from(0, ordering) +} + +/// A raw source bound to input source `source_index`, declaring `ordering`. +/// +/// Two nodes built from one index read the same source: a chunk queued for it reaches both. +fn raw_input_from(source_index: usize, ordering: SeriesOrdering) -> NativeNode { let output = NativeType::Samples(raw_schema()); NativeNode { expr: NativeExpr::Input(BoundInput { + source_index, output: output.clone(), ordering, }), @@ -122,6 +130,7 @@ fn raw_input_of(count: usize) -> NativeNode { let output = NativeType::Samples(raw_schema_of(field_count(count))); NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: output.clone(), ordering: SeriesOrdering::KeyThenTime, }), @@ -139,6 +148,7 @@ fn evaluated_input_with_ordering(grid: Arc, ordering: SeriesOrdering) let output = evaluated(grid); NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: output.clone(), ordering, }), @@ -4207,6 +4217,7 @@ fn evaluated_input_of(count: usize, grid: Arc) -> NativeNode { })); NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: output.clone(), ordering: SeriesOrdering::KeyThenTime, }), @@ -5869,6 +5880,341 @@ fn a_queued_chunk_names_its_input() { assert_eq!(left, NodePath::root().left()); } +// --------------------------------------------------------------------------- +// Source routing: one input source, one or more inputs reading it. +// --------------------------------------------------------------------------- + +/// One queued chunk of a shared source reaches every input bound to it. +/// +/// Both inputs read source 0, and the subtraction is not commutative: the right selection reads one +/// step earlier, so a chunk that reached one input only would not produce this answer. +#[test] +fn a_raw_source_feeds_every_input_bound_to_it() { + let out = grid(0, 60_000, 3); + let shared = |source_index: usize| raw_input_from(source_index, SeriesOrdering::KeyThenTime); + let tree = NativeTree::try_new(binary_of( + instant(shared(0), 1, 0, Arc::clone(&out)), + instant(shared(0), 60_000, 60_000, Arc::clone(&out)), + binary_matching(BinaryOp::Sub), + )) + .unwrap(); + + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + execution + .push_raw_source( + 0, + raw_chunk( + &raw_schema(), + &[0, 60_000, 120_000], + &[1.0, 10.0, 100.0], + true, + ), + ) + .unwrap(); + + // p0 has no earlier sample for the right side, so the subtraction decides p1 and p2 only. + assert_eq!( + decided(&run(&mut execution)), + vec![(1, Some(9.0)), (2, Some(90.0))] + ); + // Both nodes were handed the same chunk, and each copy was released with its node. + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); +} + +/// Inputs bound to different sources are fed separately: a chunk reaches only the inputs bound to +/// the index it was queued at. +#[test] +fn a_raw_source_reaches_only_the_inputs_bound_to_it() { + let out = grid(0, 60_000, 2); + let source = |source_index: usize| raw_input_from(source_index, SeriesOrdering::KeyThenTime); + let tree = NativeTree::try_new(binary_of( + instant(source(0), 1, 0, Arc::clone(&out)), + instant(source(1), 1, 0, Arc::clone(&out)), + binary_matching(BinaryOp::Add), + )) + .unwrap(); + + let schema = raw_schema(); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_raw_source( + 0, + raw_chunk_of( + &schema, + b"series-a", + metric(), + &[0, 60_000], + &[1.0, 2.0], + true, + ), + ) + .unwrap(); + execution + .push_raw_source( + 1, + raw_chunk_of( + &schema, + b"series-b", + metric(), + &[0, 60_000], + &[10.0, 20.0], + true, + ), + ) + .unwrap(); + + // The two sources hold one series each, and the add pairs them. + assert_eq!( + decided(&run(&mut execution)), + vec![(0, Some(11.0)), (1, Some(22.0))] + ); +} + +/// A chunk queued for a source no input is bound to is refused, and the execution stops holding +/// anything, like any other refused chunk. +#[test] +fn a_chunk_for_an_unknown_source_stops_the_execution() { + let tree = NativeTree::try_new(instant(input(), 300_000, 0, grid(0, 60_000, 2))).unwrap(); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + let schema = raw_schema(); + + // The tree's one input is bound to source 0, so the queued chunk is held for it. + execution + .push_raw_source(0, raw_chunk(&schema, &[0], &[1.0], true)) + .unwrap(); + assert!(pool.reserved() > 0, "the queued chunk reserved nothing"); + + // Source 7 is read by no input of this tree: the chunk has nowhere to go, and reporting that + // must not leave the chunk already queued charged to the pool. + let error = execution + .push_raw_source(7, raw_chunk(&schema, &[0], &[1.0], true)) + .unwrap_err(); + assert!( + error.to_string().contains("no input bound to source 7"), + "{error}" + ); + assert_eq!(pool.reserved(), 0, "the stopped execution kept its queue"); + assert_eq!(execution.state().reserved_bytes(), 0); + + // The execution stopped rather than waiting for another chunk, so even a source it knows is + // refused from here on. + let again = execution + .push_raw_source(0, raw_chunk(&schema, &[0], &[1.0], true)) + .unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); +} + +/// A shared source whose second copy the pool refuses stops the execution and gives the first back. +/// +/// Both inputs here read source 0, so one queued chunk is held by two queues: a budget of one copy +/// admits the first queue and refuses the second, which leaves a copy already queued when the +/// handover fails. Nothing of it may be handed out, and its bytes must go back while the executor +/// is alive. +#[test] +fn a_refused_copy_of_a_shared_source_stops_the_execution() { + let out = grid(0, 60_000, 1); + let shared = || raw_input_from(0, SeriesOrdering::KeyThenTime); + let tree = NativeTree::try_new(binary_of( + instant(shared(), 1, 0, Arc::clone(&out)), + instant(shared(), 1, 0, Arc::clone(&out)), + binary_matching(BinaryOp::Add), + )) + .unwrap(); + let schema = raw_schema(); + let chunk = raw_chunk(&schema, &[0], &[1.0], true); + + // What one input charges for the chunk, which is the figure its queue grows by. The unbounded + // pool holds exactly one copy per input and nothing before them, so that figure is the budget + // that admits the first copy and refuses the second. + let one = raw_bytes(&chunk); + let reference = pool(); + let mut measured = executor( + &tree, + Arc::clone(&reference), + &ExecutionPlanMetricsSet::new(), + ); + assert_eq!( + measured.state().reserved_bytes(), + 0, + "the tree holds bytes before its input" + ); + measured.push_raw_source(0, chunk.clone()).unwrap(); + assert_eq!( + reference.reserved(), + 2 * one, + "one handover is not held once per input" + ); + + let pool = bounded_pool(one); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); + let error = execution.push_raw_source(0, chunk).unwrap_err(); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "{error}" + ); + // The copy queued first is the left input's and the refused one the right's, so the handover + // reached one input and no further. + assert!( + error + .to_string() + .contains(NodePath::root().right().input().as_str()), + "{error}" + ); + assert_eq!(pool.reserved(), 0, "the stopped execution kept the copy"); + assert_eq!(execution.state().reserved_bytes(), 0); + + // The half-fed tree hands nothing out, and another chunk of the same source is refused. + let pulled = execution.next_chunk().unwrap_err(); + assert!( + pulled + .to_string() + .contains("stopped after an earlier error"), + "{pulled}" + ); + let again = execution + .push_raw_source(0, raw_chunk(&schema, &[0], &[1.0], true)) + .unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); +} + +/// Two layouts on one source index are refused before either input is handed a copy. +/// +/// One queued chunk is the same columns for every input it reaches, so `[a, b]` and `[b, a]` -- +/// equal in width, different in order -- cannot share a handover. Nothing is queued, so neither +/// input reports a batch nor reserves a byte, and the execution does not continue. +#[test] +fn a_shared_source_of_two_layouts_is_refused_before_any_copy() { + let out = grid(0, 60_000, 1); + let layout = |names: [&str; 2]| { + let fields: Arc<[FieldSpec]> = names + .iter() + .map(|name| FieldSpec { + name: (*name).into(), + }) + .collect(); + let schema = raw_schema_of(fields); + let output = NativeType::Samples(Arc::clone(&schema)); + let node = NativeNode { + expr: NativeExpr::Input(BoundInput { + source_index: 0, + output: output.clone(), + ordering: SeriesOrdering::KeyThenTime, + }), + output, + }; + (schema, node) + }; + let (schema, left) = layout(["a", "b"]); + let (_, right) = layout(["b", "a"]); + let tree = NativeTree::try_new(binary_of( + instant(left, 1, 0, Arc::clone(&out)), + instant(right, 1, 0, Arc::clone(&out)), + binary_matching(BinaryOp::Add), + )) + .unwrap(); + let set = ExecutionPlanMetricsSet::new(); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &set); + let error = execution + .push_raw_source(0, raw_chunk_repeated(&schema, &[0], &[1.0], true)) + .unwrap_err(); + assert!( + matches!(error, DataFusionError::Execution(_)), + "a layout mismatch was answered by the pool: {error}" + ); + assert!( + error.to_string().contains("source 0 feeds two layouts"), + "{error}" + ); + assert!( + error + .to_string() + .contains(NodePath::root().right().input().as_str()), + "the refusal does not name the conflicting input: {error}" + ); + + // The check ran before the first copy, so neither input took the chunk. + for path in [ + NodePath::root().left().input(), + NodePath::root().right().input(), + ] { + assert_eq!(count(&set, &path, NodeMetric::INPUT_BATCHES), 0, "{path}"); + } + assert_eq!(pool.reserved(), 0, "a refused handover queued a copy"); + assert_eq!(execution.state().reserved_bytes(), 0); + + // The execution stopped instead of waiting for a source it can feed. + let again = execution + .push_raw_source(0, raw_chunk_repeated(&schema, &[0], &[1.0], true)) + .unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); + assert!(execution.next_chunk().is_err(), "a stopped tree answered"); +} + +/// A raw and an evaluated input on one source index are refused before either is fed. +/// +/// `push_raw_source` hands raw chunks to every input it names, so an input bound to an evaluated +/// series has no way to take one: the handover is refused whole, and the raw side keeps nothing. +#[test] +fn a_raw_and_an_evaluated_input_on_one_source_are_refused() { + let out = grid(0, 60_000, 1); + let tree = NativeTree::try_new(binary_of( + instant( + raw_input_from(0, SeriesOrdering::KeyThenTime), + 1, + 0, + Arc::clone(&out), + ), + evaluated_input_with_ordering(Arc::clone(&out), SeriesOrdering::KeyThenTime), + binary_matching(BinaryOp::Add), + )) + .unwrap(); + + let set = ExecutionPlanMetricsSet::new(); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &set); + let error = execution + .push_raw_source(0, raw_chunk(&raw_schema(), &[0], &[1.0], true)) + .unwrap_err(); + assert!( + error + .to_string() + .contains("the input at root.right reads an evaluated series"), + "{error}" + ); + assert_eq!( + count( + &set, + &NodePath::root().left().input(), + NodeMetric::INPUT_BATCHES + ), + 0, + "the raw side took a copy of a refused handover" + ); + assert_eq!(pool.reserved(), 0); + assert_eq!(execution.state().reserved_bytes(), 0); + + let again = execution + .push_raw_source(0, raw_chunk(&raw_schema(), &[0], &[1.0], true)) + .unwrap_err(); + assert!( + again.to_string().contains("stopped after an earlier error"), + "{again}" + ); +} + /// A map above a binary, and a window above a binary, pull its result through their own loops. #[test] fn a_binary_beneath_a_map_and_a_window_is_pulled_recursively() { diff --git a/src/promql/src/native/metrics.rs b/src/promql/src/native/metrics.rs index 68eae22f536..2ddc6d1a134 100644 --- a/src/promql/src/native/metrics.rs +++ b/src/promql/src/native/metrics.rs @@ -386,6 +386,7 @@ mod tests { let output = NativeType::Samples(schema()); NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: output.clone(), ordering: datatypes::series::SeriesOrdering::KeyThenTime, }), diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 2d6ee4090cc..b295e995777 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -129,6 +129,11 @@ pub struct AggregateStateSchema { /// rejecting an interleaved input; no other consumer reads it yet. #[derive(Clone, Debug)] pub struct BoundInput { + /// The index of the input source, of this execution, whose chunks feed this input. + /// + /// The index is local to one execution: several inputs may name one source, and then share + /// every chunk queued for it. + pub source_index: usize, /// What the input produces: raw samples from a scan, or state from an exchange boundary. pub output: NativeType, /// The ordering the input guarantees. diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index f19d4f3aa12..f0947ae10e4 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -61,6 +61,7 @@ fn input() -> NativeNode { let output = raw(); NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: output.clone(), ordering: SeriesOrdering::KeyThenTime, }), @@ -74,6 +75,7 @@ fn input_on(grid: Arc) -> NativeNode { let output = evaluated(Arc::new([]), grid); NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: output.clone(), ordering: SeriesOrdering::Contiguous, }), @@ -89,6 +91,7 @@ fn input_with_fields(count: usize) -> NativeNode { })); NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: output.clone(), ordering: SeriesOrdering::KeyThenTime, }), @@ -101,6 +104,7 @@ fn interleaved_input() -> NativeNode { let output = raw(); NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: output.clone(), ordering: SeriesOrdering::Interleaved, }), @@ -1182,6 +1186,7 @@ fn a_scalar_node_must_produce_a_scalar() { fn an_input_must_report_the_binding_it_was_bound_to() { let node = NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: raw(), ordering: SeriesOrdering::KeyThenTime, }), @@ -1197,6 +1202,7 @@ fn an_input_can_bind_aggregate_state() { let state = partial_aggregate(window_over(input(), None)); let bound = NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: state.output.clone(), ordering: SeriesOrdering::Contiguous, }), @@ -1210,6 +1216,7 @@ fn an_input_can_bind_aggregate_state() { // A fresh state allocation is a different binding, so it cannot be reported as the bound one. let other = NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: state.output.clone(), ordering: SeriesOrdering::Contiguous, }), diff --git a/src/promql/tests/native_binary.rs b/src/promql/tests/native_binary.rs index a4e6f248d73..3945569aa42 100644 --- a/src/promql/tests/native_binary.rs +++ b/src/promql/tests/native_binary.rs @@ -111,6 +111,7 @@ fn source(schema: &Arc) -> NativeNode { let output = NativeType::Samples(Arc::clone(schema)); NativeNode { expr: NativeExpr::Input(BoundInput { + source_index: 0, output: output.clone(), ordering: SeriesOrdering::KeyThenTime, }), diff --git a/src/query/src/dist_plan/analyzer.rs b/src/query/src/dist_plan/analyzer.rs index f629ca092f7..a99752f563d 100644 --- a/src/query/src/dist_plan/analyzer.rs +++ b/src/query/src/dist_plan/analyzer.rs @@ -977,25 +977,10 @@ impl TreeNodeRewriter for EnforceDistRequirementRewriter { fn f_down(&mut self, node: Self::Node) -> DfResult> { // 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. + // is a branch whose children would all share one level, so the walk refuses it rather than + // assigning them levels that mean nothing. Every node this rewriter expands is on one such + // chain, and the fused PromQL node is one input over one scan like any other node here. 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 556ee4c43c0..4e2390e5313 100644 --- a/src/query/src/dist_plan/commutativity.rs +++ b/src/query/src/dist_plan/commutativity.rs @@ -23,14 +23,13 @@ use datafusion_expr::{Expr, LogicalPlan, UserDefinedLogicalNode}; use promql::extension_plan::{ EmptyMetric, FusedSeries, InstantManipulate, RangeManipulate, SeriesDivide, SeriesNormalize, }; -use promql::native::plan::{NativeExpr, NativeNode, reads_across_series}; -use promql::vector_match::Cardinality; +use promql::native::plan::reads_across_series; use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME; use crate::dist_plan::MergeScanLogicalPlan; use crate::dist_plan::analyzer::AliasMapping; use crate::dist_plan::merge_sort::{MergeSortLogicalPlan, merge_sort_transformer}; -use crate::promql::planner::native::{matching_keys_on_identity, pointwise_operand}; +use crate::promql::planner::native::{pointwise_operand, two_occurrences_pair_one_source}; pub struct StepTransformAction { extra_parent_plans: Vec, @@ -245,21 +244,21 @@ impl Categorizer { } name if name == FusedSeries::name() => { let fused = plan.as_any().downcast_ref::().unwrap(); - // A region builds this node from the region scans themselves: the conversion takes a + // A region builds this node from the region scan itself: the conversion takes a // scan's raw-series entrypoint and cannot look through anything in between, so a - // 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. A binding is one actual source, so a node - // that lists its raw inputs as several bindings reads several plans and a region has - // nothing to build for it either. - let [input] = fused.fused_inputs() else { + // node over anything but one scan has nothing to read where it would be placed and + // stays where it was planned. A match over one selector is still one child: the + // planner binds both occurrences of it to the one plan they read. + let [child] = fused.children() else { return Commutativity::NonCommutative; }; - let LogicalPlan::TableScan(_) = &input.input else { + let LogicalPlan::TableScan(_) = child else { 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 input.metric_name.is_none() { + let binding = fused.binding(); + if binding.metric_name.is_none() { return Commutativity::NonCommutative; } // A region evaluates the tree over whatever series its own scan returns, so the tree @@ -271,11 +270,8 @@ impl Categorizer { // collapsed onto this one plan, a one-to-one match over the whole series identity // with a point-wise operand on each side. let root = fused.tree().root(); - let per_series = match input.paths.as_slice() { - [_] => pointwise_operand(root), - [_, _] => two_occurrences_pair_one_series(root, &input.tags), - _ => false, - }; + let per_series = + pointwise_operand(root) || two_occurrences_pair_one_source(root, &binding.tags); if reads_across_series(root) && !per_series { return Commutativity::NonCommutative; } @@ -402,27 +398,6 @@ impl Categorizer { } } -/// Whether `root` pairs the two occurrences one plan feeds point-wise over the whole identity. -/// -/// The two occurrences are one scan, so both sides hold the same series in the same partition: what -/// is left to check is that the tree between them is a one-to-one match over the key that names the -/// whole series ([`matching_keys_on_identity`]) with a point-wise operand on each side, which is the -/// shape `PromPlanner` collapses onto one input. Anything else keeps the node on the frontend. -fn two_occurrences_pair_one_series(root: &NativeNode, tags: &[String]) -> bool { - let NativeExpr::Binary { - left, - right, - matching, - } = &root.expr - else { - return false; - }; - matching.cardinality == Cardinality::OneToOne - && pointwise_operand(left) - && pointwise_operand(right) - && matching_keys_on_identity(&matching.labels, tags) -} - #[cfg(test)] mod tests { use std::collections::{BTreeMap, BTreeSet}; @@ -442,11 +417,10 @@ mod tests { use datafusion_optimizer::analyzer::AnalyzerRule; use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; - use promql::extension_plan::{FusedSeries, FusedSeriesBinding, FusedSeriesInput}; + use promql::extension_plan::{FusedSeries, FusedSeriesBinding}; use promql::functions::{ NativeHistogramDrop, NativeHistogramFraction, NativeHistogramQuantile, }; - use promql::native::metrics::NodePath; use promql::native::plan::{NativeExpr, NativeTree}; use promql_parser::parser; use store_api::storage::RegionId; @@ -456,6 +430,7 @@ mod tests { use crate::dist_plan::DistPlannerAnalyzer; use crate::optimizer::test_util::mock_table_provider; use crate::promql::native_compile::{compile, compile_selectors, statement_grid}; + use crate::promql::planner::native::collapsed_pair_tree; use crate::query_engine::DefaultSerializer; #[test] @@ -528,23 +503,10 @@ mod tests { .unwrap(); let binding = FusedSeriesBinding { grid: statement_grid(&stmt).unwrap(), - }; - // The tree names the destination its selector compiled to, which this test reads off the - // tree rather than assuming. - let mut paths = Vec::new(); - promql::native::metrics::walk(tree.root(), &mut |node, path| { - if matches!(node.expr, NativeExpr::Input(_)) { - paths.push(path.clone()); - } - }); - let inputs = vec![FusedSeriesInput { - series_schema, - metric_name: metric_name.map(Arc::from), time_index: "ts".to_string(), tags: Vec::new(), - input, - paths, - }]; + metric_name: metric_name.map(Arc::from), + }; let output_schema: DFSchemaRef = Arc::new( DFSchema::new_with_metadata( vec![ @@ -572,7 +534,7 @@ mod tests { Arc::from("some_metric"), tree, binding, - inputs, + vec![input], output_schema, ) .unwrap(), @@ -768,13 +730,7 @@ mod tests { } /// The tree `query` compiles to, with the raw-series schema every input is bound to. - fn query_tree( - query: &str, - ) -> ( - NativeTree, - Arc, - promql_parser::parser::EvalStmt, - ) { + fn query_tree(query: &str) -> (NativeTree, promql_parser::parser::EvalStmt) { let stmt = eval_statement(query); let series_schema = Arc::new(SeriesSchema { fields: Arc::from([FieldSpec { name: "v0".into() }]), @@ -790,39 +746,38 @@ mod tests { .unwrap() .tree }; - (tree, series_schema, stmt) + (tree, stmt) } - /// The paths of a tree's raw inputs, in walk order. - fn tree_input_paths(tree: &NativeTree) -> Vec { - let mut paths = Vec::new(); - promql::native::metrics::walk(tree.root(), &mut |node, path| { + /// The number of raw inputs a tree reads, in walk order. + fn tree_input_count(tree: &NativeTree) -> usize { + let mut inputs = 0; + promql::native::metrics::walk(tree.root(), &mut |node, _| { if matches!(node.expr, NativeExpr::Input(_)) { - paths.push(path.clone()); + inputs += 1; } }); - paths + inputs } /// A `FusedSeries` node over `query`, with `one_source` deciding how its raw inputs bind. /// - /// `one_source` binds every tree input to one plan - the shape a two-occurrence statement - /// collapses to - and otherwise binds one plan per input. + /// `one_source` binds both occurrences of a two-occurrence statement to one plan - the shape + /// the planner collapses to, with both tree inputs numbered after that child - and otherwise + /// gives every occurrence its own plan. fn occurrence_plan(query: &str, tags: &[&str], one_source: bool) -> LogicalPlan { - let (tree, series_schema, stmt) = query_tree(query); - let paths = tree_input_paths(&tree); - let binding = |paths| FusedSeriesInput { - series_schema: Arc::clone(&series_schema), - metric_name: Some(Arc::from("some_metric")), - time_index: "ts".to_string(), - tags: tags.iter().map(|tag| (*tag).to_string()).collect(), - input: table_scan_plan(), - paths, - }; - let inputs = if one_source { - vec![binding(paths)] - } else { - paths.into_iter().map(|path| binding(vec![path])).collect() + let (tree, stmt) = query_tree(query); + let input_count = tree_input_count(&tree); + let (tree, children) = match (one_source, input_count) { + // A statement that names its selector once reads one child already. + (_, 1) => (tree, vec![table_scan_plan()]), + // Both occurrences read the one plan the planner collapsed them onto. + (true, _) => ( + collapsed_pair_tree(&tree).expect("the fixture is a two-occurrence pair"), + vec![table_scan_plan()], + ), + // Every occurrence reads a plan of its own. + (false, _) => (tree, (0..input_count).map(|_| table_scan_plan()).collect()), }; let output_schema: DFSchemaRef = Arc::new( DFSchema::new_with_metadata( @@ -851,8 +806,11 @@ mod tests { tree, FusedSeriesBinding { grid: statement_grid(&stmt).unwrap(), + time_index: "ts".to_string(), + tags: tags.iter().map(|tag| (*tag).to_string()).collect(), + metric_name: Some(Arc::from("some_metric")), }, - inputs, + children, output_schema, ) .unwrap(), @@ -900,8 +858,9 @@ mod tests { } } - /// A node that lists its raw inputs as two bindings reads two plans, and a region has nothing - /// to build for it. + /// A node over two children reads two plans, and a region has nothing to build for it: the + /// planner collapses a pair onto one child, so this is the shape that keeps the node where it + /// was planned rather than a match one region cannot answer. #[test] fn fused_series_over_two_actual_scans_is_not_commutative() { let plan = occurrence_plan("some_metric + on(host) some_metric", &["host"], false); @@ -930,16 +889,21 @@ mod tests { } /// A tree that reads a whole vector or folds a group reads across series, whether it is the - /// root or sits below the match the planner collapsed. + /// root or sits below a map. + /// + /// Each case below reads one scan, which is the only shape such a tree can have here: a + /// two-occurrence statement is collapsed onto one child only when both of its operands are + /// point-wise, and the planner refuses the pair otherwise. The categorizer reads the same + /// predicate ([`two_occurrences_pair_one_source`]) the planner admits with, so it cannot place + /// a pair the planner declined — that case is covered where the query falls back. #[test] fn fused_series_whose_tree_reads_across_series_is_not_commutative() { - for (query, one_source) in [ - ("sort(some_metric)", true), - ("sum(some_metric)", true), - ("sort(some_metric) + on(host) sort(some_metric)", true), - ("sum(some_metric) + on(host) sum(some_metric)", true), + for query in [ + "sort(some_metric)", + "sum(some_metric)", + "abs(sort(some_metric)) * 2", ] { - let plan = occurrence_plan(query, &["host"], one_source); + let plan = occurrence_plan(query, &["host"], true); assert!( matches!(commutativity_of(&plan), Commutativity::NonCommutative), "{query}" diff --git a/src/query/src/optimizer/scan_hint.rs b/src/query/src/optimizer/scan_hint.rs index b5a28535e88..1765e8199aa 100644 --- a/src/query/src/optimizer/scan_hint.rs +++ b/src/query/src/optimizer/scan_hint.rs @@ -497,9 +497,7 @@ mod test { use datatypes::schema::ColumnSchema; use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; - use promql::extension_plan::{ - FusedSeries, FusedSeriesBinding, FusedSeriesInput, RangeManipulate, - }; + use promql::extension_plan::{FusedSeries, FusedSeriesBinding, RangeManipulate}; use promql_parser::parser; use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME; @@ -1585,23 +1583,10 @@ mod test { .unwrap(); let binding = FusedSeriesBinding { grid: statement_grid(&stmt).unwrap(), - }; - // The tree names the destination its selector compiled to, which this test reads off the - // tree rather than assuming. - let mut paths = Vec::new(); - promql::native::metrics::walk(tree.root(), &mut |node, path| { - if matches!(node.expr, promql::native::plan::NativeExpr::Input(_)) { - paths.push(path.clone()); - } - }); - let inputs = vec![FusedSeriesInput { - series_schema, - metric_name: Some("some_metric".into()), time_index: "ts".to_string(), tags: Vec::new(), - input, - paths, - }]; + metric_name: Some(Arc::from("some_metric")), + }; let output_schema: DFSchemaRef = Arc::new( DFSchema::new_with_metadata( vec![ @@ -1626,7 +1611,7 @@ mod test { Arc::from("some_metric"), tree, binding, - inputs, + vec![input], output_schema, ) .unwrap(), diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index 08917cd43cd..1ac8e469c28 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -226,6 +226,13 @@ impl SelectorRequirement { } /// One input a compiled tree reads, and the selector it was bound to. +/// +/// The record describes the scan side of one occurrence: what the selector asked a scan for and +/// which layout it was bound to. The tree side is the input node at [`path`](Self::path), whose +/// `source_index` names the input source its chunks come from — an index local to one execution of +/// the tree, not an identity any enclosing plan assigns. That index is not mirrored here: an +/// occurrence's position in this list is the index the compiler gave its node, and a caller that +/// collapses two occurrences onto one source rewrites the node rather than another record. #[derive(Clone, Debug)] pub struct CompiledInput { /// Where the executor reads this input in the compiled tree. @@ -331,6 +338,13 @@ pub fn compile( /// Each selector's path is recorded as its recursive node is compiled, so its requirement and /// schema stay structurally paired with the input the executor names at that position; the finished /// tree is then walked once to check that pairing ([`validate_inputs`]). +/// +/// Each input node also carries a `source_index`, naming which input source of one execution its +/// chunks come from. The compiler numbers occurrences in binding order from zero, so the i-th +/// selector compiled reads input source i, and `x + x` binds two indices even when both occurrences +/// are fed one schema. How those indices map onto a caller's actual sources is the caller's to +/// say — the fused planner, for one, proves that two occurrences read one scan and rebinds them to +/// the single child position it prepared. pub fn compile_selectors( stmt: &EvalStmt, bindings: &dyn Fn(&SelectorRequirement) -> Result>, @@ -1166,7 +1180,7 @@ fn window_selection( // A range function reports one value per input field, so the layout is the input's. let (start_ms, end_ms) = grid_endpoints(&output_grid)?; - let raw_schema = bind_selector( + let (source_index, raw_schema) = bind_selector( context, SelectorRequirement { metric: vs.name.clone(), @@ -1192,6 +1206,7 @@ fn window_selection( expr: NativeExpr::Window { input: Box::new(NativeNode { expr: NativeExpr::Input(BoundInput { + source_index, output: raw.clone(), ordering: context.ordering, }), @@ -1351,7 +1366,7 @@ fn instant_selection(context: &Context, selector: &VectorSelector) -> Result Result Result Result> { +/// +/// The returned index is the occurrence's position in binding order, which its input node carries +/// as [`BoundInput::source_index`]: the input source that node's chunks come from, local to one +/// execution of the tree. It is read off the record list rather than kept in a counter, so the +/// record a selector appends and the index its node names cannot drift apart. Two occurrences of one +/// selector are numbered separately here — a compiler describes occurrences — and a caller that +/// proves two of them read one source rebinds their nodes to that source. +fn bind_selector( + context: &Context, + requirement: SelectorRequirement, +) -> Result<(usize, Arc)> { let schema = (context.bindings)(&requirement)?; - context.inputs.borrow_mut().push(CompiledInput { + let mut inputs = context.inputs.borrow_mut(); + let source_index = inputs.len(); + inputs.push(CompiledInput { path: context.path.input(), requirement, schema: Arc::clone(&schema), ordering: context.ordering, }); - Ok(schema) + Ok((source_index, schema)) } /// The first and last point of `grid`, as milliseconds since the Unix epoch. diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index b1245d6090d..79ce607c04e 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -1050,7 +1050,7 @@ fn the_display_of_a_compiled_tree_is_the_tree() { [ "NativeTree", " root Window rate [300000ms] offset 0 anchor - on grid 0/5000x21", - " input Input raw samples", + " input Input source=0 raw samples", ] .join("\n") ); @@ -1069,7 +1069,7 @@ fn the_display_of_a_tree_the_batch_added_to_is_the_query() { " root Aggregate sum by [job] complete", " input Binary * ignoring [] one-to-one", " left Window rate [300000ms] offset 0 anchor - on grid 0/5000x21", - " input Input raw samples", + " input Input source=0 raw samples", " right Scalar 100", ], ), @@ -1080,7 +1080,7 @@ fn the_display_of_a_tree_the_batch_added_to_is_the_query() { " root Binary * ignoring [] one-to-one", " left Scalar -1", " right Instant lookback 5000ms offset 0 on grid 0/5000x21", - " input Input raw samples", + " input Input source=0 raw samples", ], ), ( @@ -1090,7 +1090,7 @@ fn the_display_of_a_tree_the_batch_added_to_is_the_query() { " root Binary < ignoring [] one-to-one", " left Scalar 0", " right Instant lookback 5000ms offset 0 on grid 0/5000x21", - " input Input raw samples", + " input Input source=0 raw samples", ], ), ]; @@ -4507,6 +4507,7 @@ fn selector_binding_returns_requirement_and_input_path() { panic!("inner expression is not a window"); }; let NativeExpr::Input(BoundInput { + source_index, output: NativeType::Samples(bound_schema), ordering, }) = &window_input.expr @@ -4518,6 +4519,8 @@ fn selector_binding_returns_requirement_and_input_path() { }; assert!(Arc::ptr_eq(bound_schema, &schema)); assert_eq!(*ordering, SeriesOrdering::KeyThenTime); + // The only selector of the statement read the first child of the final tree. + assert_eq!(*source_index, 0); } /// Scan bounds follow the grid the selector is actually evaluated on, open a window's lower edge, and @@ -4776,11 +4779,12 @@ fn vector_binary_inputs_follow_structural_paths() { let mut tree_inputs = Vec::new(); walk(compiled.tree.root(), &mut |node, path| { if let NativeExpr::Input(BoundInput { + source_index, output: NativeType::Samples(schema), ordering, }) = &node.expr { - tree_inputs.push((path.clone(), Arc::clone(schema), *ordering)); + tree_inputs.push((path.clone(), Arc::clone(schema), *ordering, *source_index)); } }); assert_eq!(tree_inputs.len(), expected.len()); @@ -4791,10 +4795,13 @@ fn vector_binary_inputs_follow_structural_paths() { assert_eq!(bound.requirement.metric.as_deref(), Some(*metric)); assert!(Arc::ptr_eq(&bound.schema, &schemas[*schema_index])); assert_eq!(bound.ordering, SeriesOrdering::KeyThenTime); - let (tree_path, tree_schema, tree_ordering) = &tree_inputs[index]; + let (tree_path, tree_schema, tree_ordering, source_index) = &tree_inputs[index]; assert_eq!(tree_path.as_str(), *expected_path); assert!(Arc::ptr_eq(tree_schema, &bound.schema)); assert_eq!(*tree_ordering, bound.ordering); + // The selectors are numbered in the order they were bound, which is the order this test + // lists them in: `x + y`, then `z`. + assert_eq!(*source_index, *schema_index); } } @@ -4850,20 +4857,28 @@ fn selector_bindings_follow_structural_input_paths() { let mut tree_inputs = Vec::new(); walk(compiled.tree.root(), &mut |node, path| { if let NativeExpr::Input(BoundInput { + source_index, output: NativeType::Samples(bound_schema), ordering, }) = &node.expr { - tree_inputs.push((path.clone(), Arc::clone(bound_schema), *ordering)); + tree_inputs.push(( + path.clone(), + Arc::clone(bound_schema), + *ordering, + *source_index, + )); } }); assert_eq!(tree_inputs.len(), compiled.inputs.len(), "query: {query}"); - for ((path, tree_schema, tree_ordering), bound) in + for ((path, tree_schema, tree_ordering, source_index), bound) in tree_inputs.iter().zip(compiled.inputs.iter()) { assert_eq!(path, &bound.path, "query: {query}"); assert!(Arc::ptr_eq(tree_schema, &bound.schema), "query: {query}"); assert_eq!(*tree_ordering, bound.ordering, "query: {query}"); + // One selector: the statement's only occurrence reads the first child. + assert_eq!(*source_index, 0, "query: {query}"); } } } @@ -4926,3 +4941,35 @@ fn recorded_inputs_are_exactly_the_trees_input_nodes() { assert!(matches!(error, DataFusionError::Internal(_)), "{error}"); assert!(error.to_string().contains("not its input nodes"), "{error}"); } + +/// The compiler numbers each input node by the occurrence it was bound for, from zero. +/// +/// The number is what the executor reads a chunk from, so it describes occurrences rather than +/// scans: `x + x` names one selector twice and binds two children, which is why a caller that +/// proves both occurrences read one scan rebinds their nodes rather than trusting the numbering. +#[test] +fn input_nodes_are_numbered_by_binding_order_from_zero() { + for (query, expected) in [ + ("x", vec![0]), + ("rate(x[5m])", vec![0]), + ("abs(x) * 2", vec![0]), + ("x + y", vec![0, 1]), + ("x + x", vec![0, 1]), + ("(x + y) / z", vec![0, 1, 2]), + ("x + y * z", vec![0, 1, 2]), + ] { + let compiled = compile_selectors( + &eval_stmt(query), + &|_| Ok(raw_schema()), + SeriesOrdering::KeyThenTime, + ) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); + let mut indices = Vec::new(); + walk(compiled.tree.root(), &mut |node, _| { + if let NativeExpr::Input(BoundInput { source_index, .. }) = &node.expr { + indices.push(*source_index); + } + }); + assert_eq!(indices, expected, "query: {query}"); + } +} diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 9f22bf8a7b9..7a4bc6673fe 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -20,12 +20,14 @@ //! the normal answer: every shape the compiler does not accept, and every query this route cannot //! bind to a scan faithfully, keeps the plan the existing planner builds. //! -//! What the node needs from here is three things the existing planner already resolves: the raw -//! series schema the tree's input was compiled against (the selector's selected field columns), the -//! statement's evaluation grid, and the logical tag names the output carries. The output schema is -//! built to the shape the existing unary pipeline produces — the time index, then the series -//! fields, then the tags — so a node planned here can be consumed by the same code that consumes a -//! `SeriesNormalize` output. +//! What the node needs from here is what the existing planner already resolves: the selector's own +//! table scan with its matchers and compiled time bounds pushed down, the statement's evaluation +//! grid, and the columns a series is reported under — the time index, the tags and the metric name. +//! The tree's inputs are numbered, and each number is the position of the child whose chunks that +//! input reads; a statement whose two occurrences were proven to read one scan is planned with that +//! one child and both inputs rebound to it. The output schema is built to the shape the existing +//! unary pipeline produces — the time index, then the series fields, then the tags — so a node +//! planned here can be consumed by the same code that consumes a `SeriesNormalize` output. use std::sync::Arc; use std::time::{Duration, UNIX_EPOCH}; @@ -39,7 +41,7 @@ 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, FusedSeriesInput}; +use promql::extension_plan::{FusedSeries, FusedSeriesBinding}; use promql::native::plan::{NativeExpr, NativeNode, NativeTree, reads_across_series}; use promql::vector_match::{Cardinality, MatchingLabels}; use promql_parser::label::Matchers; @@ -102,6 +104,21 @@ const NATIVE_ORDERING: SeriesOrdering = SeriesOrdering::Contiguous; /// longer names the series the partition holds. const METADATA_KEY_TAGS: [&str; 3] = ["__name__", "__type__", "__unit__"]; +/// One prepared occurrence of a selector: the scan that reads it, the raw-series layout it was +/// prepared against, and the columns its series are reported under. +/// +/// The last three are the node's rather than one scan's — the binding names a time index, a tag list +/// and a metric name once — so they are compared across the occurrences and then travel to the +/// binding together. The first two are what [`same_source`] compares, which is the check that two +/// occurrences of one selector are one scan. +type PreparedInput = ( + LogicalPlan, + Arc, + Option>, + String, + Vec, +); + impl PromPlanner { /// Plans `prom_expr` as one [`FusedSeries`] node, or returns `None` to keep the existing plan. /// @@ -120,11 +137,15 @@ impl PromPlanner { /// native histogram field, or an unusable grid. /// /// A statement with two occurrences of one selector is admitted only when both read one scan - /// point-wise. That is the only shape this node can run over every partition of one input + /// point-wise. That is the only shape this node can run over every partition of one child /// independently: both sides then see the same series in the same partition, so the series a - /// partition holds is whole. Everything else — a different scan, different bounds, a match key - /// that is not the whole series identity, a shape that reads a whole series as a group — - /// keeps the existing plan rather than gathering every partition into one execution. + /// partition holds is whole. Such a statement is planned over that one child, with both of its + /// tree inputs bound to it; the node's binding names the columns a series is reported under — + /// the time index, the tags and the metric name — once for all of them. Everything else — a + /// different scan, different bounds, a match key that is not the whole series identity, a shape + /// that reads a whole series as a group — keeps the existing plan rather than gathering every + /// partition into one execution, because a match over two actual sources cannot be answered one + /// region at a time. pub(super) async fn try_plan_native_fused( &mut self, prom_expr: &PromExpr, @@ -164,7 +185,7 @@ impl PromPlanner { }; let original_context = self.ctx.clone(); let preparation = async { - let mut prepared: Vec = Vec::new(); + let mut prepared: Vec = Vec::new(); for selector in &selectors { self.ctx = original_context.clone(); let matchers = @@ -317,26 +338,34 @@ impl PromPlanner { } else { return Ok(None); } - prepared.push(FusedSeriesInput { - series_schema, - metric_name: Some(Arc::from(metric)), - time_index: time, - tags, - input, - // Filled from the compiled tree, which is what names an input. - paths: Vec::new(), - }); + prepared.push((input, series_schema, Some(Arc::from(metric)), time, tags)); } Ok(Some(prepared)) } .await; self.ctx = original_context; - let Some(prepared) = preparation? else { + let Some(mut prepared) = preparation? else { return Ok(None); }; + // The time index, the tag list and the metric name are the node's, not one scan's: the + // output schema and the binding name them once, and every occurrence reports its series + // under them. Two occurrences that disagree are two different reportings, which one node + // cannot be built for. Both occurrences of an admitted pair share the layout, so the first + // one's schema also speaks for the node below. + let Some((_, series_schema, metric, time, tags)) = prepared.first() else { + return Ok(None); + }; + let (series_schema, metric, time, tags) = ( + Arc::clone(series_schema), + metric.clone(), + time.clone(), + tags.clone(), + ); if prepared - .windows(2) - .any(|w| w[0].time_index != w[1].time_index || w[0].tags != w[1].tags) + .iter() + .any(|(_, _, other_metric, other_time, other_tags)| { + *other_metric != metric || *other_time != time || *other_tags != tags + }) { return Ok(None); } @@ -370,7 +399,7 @@ impl PromPlanner { &|req| { let i = bind_index.get(); bind_index.set(i + 1); - let (Some(prepared_input), Some(identity)) = (prepared.get(i), identities.get(i)) + let (Some((_, schema, ..)), Some(identity)) = (prepared.get(i), identities.get(i)) else { return Err(DataFusionError::Internal( "a selector was bound that the planner did not prepare".into(), @@ -388,7 +417,7 @@ impl PromPlanner { "the compiler and the planner walk the selectors differently".into(), )); } - Ok(Arc::clone(&prepared_input.series_schema)) + Ok(Arc::clone(schema)) }, NATIVE_ORDERING, ) { @@ -404,33 +433,41 @@ impl PromPlanner { )) .context(DataFusionPlanningSnafu); } - let mut inputs = Vec::with_capacity(prepared.len()); - for (index, (compiled_input, mut input)) in compiled.inputs.iter().zip(prepared).enumerate() + for (index, (compiled_input, (scan, _, _, _, _))) in + compiled.inputs.iter().zip(prepared.iter_mut()).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. + // the whole range outside the statement's. The bound belongs to the scan, so it is + // pushed down before two occurrences are compared: two selectors over different windows + // or offsets read different rows even when nothing else about them differs. 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) { + 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" + "the child at {index} is not the table scan this route prepared" ))) .context(DataFusionPlanningSnafu); } - input.input = scan; - // The tree names the input this occurrence compiled to, and the collapse below joins - // two of them onto one plan. - input.paths = vec![compiled_input.path.clone()]; - inputs.push(input); } + // Two occurrences are admitted only when both read one scan plan: the node then runs one + // execution per partition of that one child, and both sides of the match see the same series + // in the same partition. Two actual scans — a different table, different matchers, different + // bounds — stay with the existing planner, which is where a match over more than one source + // is answered rather than in a region that holds part of it. + if selectors.len() == 2 && !(prepared.len() == 2 && same_source(&prepared[0], &prepared[1])) + { + return Ok(None); + } + let mut children = prepared + .into_iter() + .map(|(scan, _, _, _, _)| scan) + .collect::>(); // A tree run once per scan partition has to read one series at a time: an aggregate folds a // label set's series together and a vector operation (`sort`, `absent`, `topk`, // `histogram_quantile`, ...) reads the whole vector at a grid point, so one region's share @@ -439,35 +476,36 @@ impl PromPlanner { // declining to push it down would leave a node the physical layer must build anyway. What // does read one series at a time is one occurrence's samples - a selection, a window, a map // over either, or a constant broadcast - and, for a statement that names one selector - // twice, a one-to-one match whose key holds the whole identity, which the collapse below - // then reads as one scan. - if reads_across_series(compiled.tree.root()) - && !(pointwise_operand(compiled.tree.root()) - || (selectors.len() == 2 - && two_occurrences_read_one_source(&compiled.tree, &inputs))) + // twice, a one-to-one match whose key holds the whole identity over one scan, which the + // collapse below reads as that scan. + let root = compiled.tree.root(); + if reads_across_series(root) + && !(pointwise_operand(root) + || (selectors.len() == 2 && two_occurrences_pair_one_source(root, &tags))) { return Ok(None); } // Two occurrences of one selector read the same series only when the tree between them is - // point-wise and both scans are the same scan, which the check above has just admitted. - // Then both inputs are one plan, and this node runs one execution per partition of it - // instead of one execution over every partition. - if selectors.len() == 2 { - // The tree still names two input paths, so the second occurrence's destination moves - // onto the first plan rather than being dropped with the plan that carried it. `append` - // leaves the second list empty, which is what makes removing that plan lose nothing. - let prepared_inputs = inputs.len(); - let [first, second] = &mut inputs[..] else { - return Err(DataFusionError::Internal(format!( - "two occurrences prepared {prepared_inputs} input(s) rather than a pair" - ))) - .context(DataFusionPlanningSnafu); - }; - first.paths.append(&mut second.paths); - inputs.remove(1); - } - let root_fields = compiled - .tree + // point-wise, both scans are the same scan, and the match key holds the whole identity, + // which the checks above have just admitted. Both occurrences are then one child, so the + // tree is rebuilt with both inputs bound to it. A tree this route admits but cannot rebind + // is a compiler defect it declines (`NotImplemented`) rather than rewrites, and the existing + // plan answers the query; an error of any other kind is a defect to report. + let tree = if selectors.len() == 2 { + match collapsed_pair_tree(&compiled.tree) { + Ok(tree) => { + // Both occurrences read the one plan, so the two prepared children are that + // same plan and only one of them is kept. + children.truncate(1); + tree + } + Err(DataFusionError::NotImplemented(_)) => return Ok(None), + Err(e) => return Err(e).context(DataFusionPlanningSnafu), + } + } else { + compiled.tree + }; + let root_fields = tree .root() .output .samples() @@ -478,24 +516,24 @@ impl PromPlanner { .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) - }) + !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()), - compiled.tree, - FusedSeriesBinding { grid }, - inputs, + tree, + FusedSeriesBinding { + grid, + time_index: time, + tags, + metric_name: metric, + }, + children, output_schema, ) .context(DataFusionPlanningSnafu)?; @@ -642,7 +680,7 @@ fn literal_or_next(start: i64) -> Option { )) } -/// Whether a tree's two occurrences may be read as one source. +/// Whether a tree is two occurrences of one selector matched point-wise over the whole identity. /// /// The claim is about one series: it is whole in the partition it was scanned in, so a tree whose /// nodes each read one series separately can run one execution per partition. What breaks that is a @@ -656,35 +694,35 @@ fn literal_or_next(start: i64) -> Option { /// `fill_left`/`fill_right` for a one-to-one match too, and what the admission rests on is the key /// and the operands, not the absence of a fill — see [`matching_keys_on_identity`]. /// +/// The pair's scans are the caller's claim: this function reads the tree and the tags, and a caller +/// that admits a pair on two actual scans would still be admitting a match over two sources. Both +/// the planner that collapses a pair onto one scan and the categorizer that places the node +/// region-side ask this, so the two cannot disagree about which pairs read one series: a pair +/// admitted here but refused there becomes a node the physical layer cannot build. +/// /// The raw keys themselves are proven to name one logical series each by the caller's preparation, /// which checks the table's primary key against the tags this binding reports /// (`identity_keys_are_injective`). That is a planning-time check over the scan the planner /// prepared, not a property this function re-derives: a tree and binding built by anything other /// than this planner carries no such proof, so a manual `FusedSeries` node is only as safe as the /// binding its builder passed. -fn two_occurrences_read_one_source(tree: &NativeTree, inputs: &[FusedSeriesInput]) -> bool { +pub(crate) fn two_occurrences_pair_one_source(root: &NativeNode, tags: &[String]) -> bool { let NativeExpr::Binary { left, right, matching, - } = &tree.root().expr + } = &root.expr else { return false; }; // A root with a constant on one side is a broadcast of that constant, not two occurrences // matched, and `group_left`/`group_right` pair a group against one series. - if matching.cardinality != Cardinality::OneToOne - || !pointwise_operand(left) - || !pointwise_operand(right) - { - return false; - } - let [first, second] = inputs else { - return false; - }; - // A key that does not hold the whole identity pairs series Prometheus keeps apart, and a - // partition that holds one of them cannot tell that the other is missing. - matching_keys_on_identity(&matching.labels, &first.tags) && same_source(first, second) + matching.cardinality == Cardinality::OneToOne + && pointwise_operand(left) + && pointwise_operand(right) + // A key that does not hold the whole identity pairs series Prometheus keeps apart, and a + // partition that holds one of them cannot tell that the other is missing. + && matching_keys_on_identity(&matching.labels, tags) } /// Whether `node` reads samples point-wise, so that one partitioned execution is one answer. @@ -781,31 +819,90 @@ fn identity_keys_are_injective(matchers: &Matchers, meta: &TableMeta, tags: &[St }) } -/// Whether two prepared inputs read the same scan, and so produce the same series. +/// Whether two prepared occurrences read the same scan, and so produce the same series. /// /// Everything below the node is compared, not only the table name: two selectors over one table /// with different matchers or different bounds read different rows, and a partition that holds one /// of them is not the partition that holds the other. DataFusion's own scan comparison covers the /// table name, the projection, the schema, the filters and the fetch; the source is compared by -/// identity, because it is what resolves those rows in the first place. The time index and the tag -/// list are not compared here: both are checked once for every prepared input, above. -fn same_source(left: &FusedSeriesInput, right: &FusedSeriesInput) -> bool { +/// identity, because it is what resolves those rows in the first place. The reporting columns — the +/// metric name, the time index and the tags — are not compared here: they are checked once for +/// every prepared occurrence, before this runs. +fn same_source(left: &PreparedInput, right: &PreparedInput) -> bool { + let (left_input, left_schema, ..) = left; + let (right_input, right_schema, ..) = right; let (LogicalPlan::TableScan(left_scan), LogicalPlan::TableScan(right_scan)) = - (&left.input, &right.input) + (left_input, right_input) else { return false; }; // Both schemas are raw series schemas, so the fields are what the tree's input was compiled // against, in the order it reads them. - left.metric_name == right.metric_name - && left - .series_schema - .fields - .iter() - .map(|field| &field.name) - .eq(right.series_schema.fields.iter().map(|field| &field.name)) - && left_scan == right_scan - && Arc::ptr_eq(&left_scan.source, &right_scan.source) + let same_fields = left_schema + .fields + .iter() + .map(|field| &field.name) + .eq(right_schema.fields.iter().map(|field| &field.name)); + same_fields && left_scan == right_scan && Arc::ptr_eq(&left_scan.source, &right_scan.source) +} + +/// Rebuilds an admitted pair's tree so both of its occurrences read the one child prepared for them. +/// +/// The compiler numbers occurrences in binding order, so an admitted pair's two input nodes are +/// numbered `0` and `1`; the planner prepared one plan for them, which is child `0`. Giving every +/// input node that index is what makes the executor hand each chunk of that child to both of them, +/// and what makes the node report one child for the whole match. +/// +/// The tree is rebuilt rather than patched in place because a node's inputs are shared: the rebuilt +/// tree is validated again by [`NativeTree::try_new`], so a rebind can never produce a tree the +/// runtime would refuse. A tree whose inputs are not exactly those two occurrences is a compiler +/// defect this route declines with `NotImplemented` — the caller keeps the existing plan rather than +/// running a tree whose inputs it cannot name. +/// +/// It is `pub(crate)` for the categorizer's own tests, which build the node the planner would have +/// built: the region-side placement has to accept exactly the shape this collapse produces, so a +/// fixture that bound the pair by hand could agree with the categorizer while disagreeing with the +/// planner. +pub(crate) fn collapsed_pair_tree(tree: &NativeTree) -> datafusion::error::Result { + let mut root = tree.root().clone(); + let mut occurrences = 0; + let numbered = rebind_pair_inputs(&mut root, &mut occurrences); + if !numbered || occurrences != 2 { + return Err(DataFusionError::NotImplemented(format!( + "a two-occurrence tree whose {occurrences} input(s) are not the two occurrences \ + numbered from zero, which this route cannot bind to one child" + ))); + } + NativeTree::try_new(root) +} + +/// Rebinds every input below `node` to child `0`, counting them and checking their numbering. +/// +/// The walk visits inputs in the order the compiler bound them — an operand before the next one, the +/// left operand before the right — so occurrence `i` of the walk is the input the compiler numbered +/// `i`. `false` means the tree is not the pair this route admitted: a node carried a number the walk +/// did not expect, or a shape the admission does not cover. An `Aggregate` or a `Vector` below the +/// root is one of those shapes — neither is point-wise, so the pair was never admitted — and the +/// walk refuses it rather than rebinding a tree this route does not run. +fn rebind_pair_inputs(node: &mut NativeNode, next: &mut usize) -> bool { + match &mut node.expr { + NativeExpr::Input(bound) => { + let numbered = bound.source_index == *next; + bound.source_index = 0; + *next += 1; + numbered + } + NativeExpr::Scalar(_) => true, + NativeExpr::Instant { input, .. } + | NativeExpr::Window { input, .. } + | NativeExpr::Map { input, .. } => rebind_pair_inputs(input, next), + NativeExpr::Binary { left, right, .. } => { + let left_numbered = rebind_pair_inputs(left, next); + let right_numbered = rebind_pair_inputs(right, next); + left_numbered && right_numbered + } + NativeExpr::Aggregate { .. } | NativeExpr::Vector { .. } => false, + } } /// The columns a [`FusedSeries`] node produces. @@ -935,10 +1032,14 @@ fn metric_scan_and_table_id( #[cfg(test)] mod tests { use std::sync::Arc; + use std::time::{Duration, UNIX_EPOCH}; + use datatypes::series::SeriesOrdering; + use datatypes::series::samples::{FieldSpec, SeriesSchema}; + use promql::native::plan::{NativeExpr, NativeNode}; use session::context::QueryContextBuilder; - use super::{NATIVE_PROMQL_EXTENSION_KEY, native_promql_requested}; + use super::{NATIVE_PROMQL_EXTENSION_KEY, collapsed_pair_tree, native_promql_requested}; #[test] fn native_promql_requested_is_false_when_extension_is_absent() { @@ -960,6 +1061,85 @@ mod tests { } } + /// The statement `query` is compiled against: one selector over five seconds of grid. + fn native_test_statement(query: &str) -> promql_parser::parser::EvalStmt { + promql_parser::parser::EvalStmt { + expr: promql_parser::parser::parse(query).unwrap(), + start: UNIX_EPOCH, + end: UNIX_EPOCH + Duration::from_secs(10), + interval: Duration::from_secs(5), + lookback_delta: Duration::from_secs(5), + } + } + + /// `query` compiled against one raw-series layout, every selector bound to it. + /// + /// The entry is `compile_selectors` rather than the compatibility `compile`, because the pair + /// these tests are about names one selector twice and `compile` refuses a statement whose two + /// occurrences it cannot tell apart. Binding both occurrences to one layout is the test's + /// choice of scan, not a claim the compiler makes. + fn native_test_tree(query: &str) -> promql::native::plan::NativeTree { + let schema = Arc::new(SeriesSchema { + fields: Arc::from([FieldSpec { name: "v0".into() }]), + eval_grid: None, + }); + let stmt = native_test_statement(query); + crate::promql::native_compile::compile_selectors( + &stmt, + &|_| Ok(Arc::clone(&schema)), + SeriesOrdering::KeyThenTime, + ) + .unwrap() + .tree + } + + /// The child each raw input below `root` reads, in the order the compiler bound them. + fn native_test_input_sources(root: &NativeNode) -> Vec { + let mut sources = Vec::new(); + promql::native::metrics::walk(root, &mut |node, _| { + if let NativeExpr::Input(bound) = &node.expr { + sources.push(bound.source_index); + } + }); + sources + } + + /// Collapsing a pair binds both occurrences to the one child the planner prepared for them. + #[test] + fn a_pair_tree_is_rebound_to_its_one_child() { + let tree = native_test_tree("x + x"); + assert_eq!( + native_test_input_sources(tree.root()), + vec![0, 1], + "the compiler numbers occurrences" + ); + + let collapsed = collapsed_pair_tree(&tree).unwrap(); + assert_eq!(native_test_input_sources(collapsed.root()), vec![0, 0]); + // The rest of the tree is the one that was compiled: only the bindings moved. + assert!(matches!(collapsed.root().expr, NativeExpr::Binary { .. })); + assert_eq!( + tree.to_string().replace("source=1", "source=0"), + collapsed.to_string(), + "the collapse changed something other than the child each input reads" + ); + } + + /// A tree whose inputs are not the two occurrences is declined, and the refusal is the one the + /// route answers with the existing plan — not an internal error to report. + #[test] + fn a_tree_that_is_not_a_pair_is_declined_by_the_collapse() { + let error = collapsed_pair_tree(&native_test_tree("x")).unwrap_err(); + assert!( + matches!(error, datafusion::error::DataFusionError::NotImplemented(_)), + "{error}" + ); + assert!( + error.to_string().contains("cannot bind to one child"), + "{error}" + ); + } + #[test] fn native_promql_requested_rejects_false_and_unrecognized_values() { for value in ["false", "FALSE", "yes", "1", " true ", ""] { diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index 7c1853bd30b..7aa14af00ee 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -38,7 +38,7 @@ use datafusion::datasource::memory::MemorySourceConfig; use datafusion::datasource::source::DataSourceExec; use datafusion::datasource::{MemTable, provider_as_source}; use datafusion::execution::context::SessionContext; -use datafusion::logical_expr::{Extension, UserDefinedLogicalNodeCore, col}; +use datafusion::logical_expr::{Extension, col}; use datatypes::prelude::ConcreteDataType; use datatypes::schema::{ColumnSchema, Schema}; use datatypes::series::SeriesOrdering; @@ -1841,7 +1841,7 @@ fn find_metric_physical_scan(plan: &LogicalPlan) -> Option node .as_any() .downcast_ref::() - .and_then(|fused| match fused.inputs().first() { + .and_then(|fused| match fused.children().first() { Some(LogicalPlan::TableScan(scan)) => Some(scan.clone()), _ => None, }), @@ -1862,29 +1862,60 @@ fn find_fused_series(plan: &LogicalPlan) -> Option<&FusedSeries> { plan.inputs().into_iter().find_map(find_fused_series) } -/// Two occurrences of one selector over one scan plan as one input carrying both occurrences. +/// Two occurrences of one selector over one scan plan as one child both occurrences read. #[tokio::test] async fn native_fused_binary_collapses_two_occurrences_onto_one_scan() { 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!(1, fused.fused_inputs().len()); - let input = &fused.fused_inputs()[0]; + assert_eq!(1, fused.children().len()); assert!( - matches!(input.input, LogicalPlan::TableScan(_)), - "the input should be the selector's own scan: {:?}", - input.input + matches!(fused.children()[0], LogicalPlan::TableScan(_)), + "the child should be the selector's own scan: {:?}", + fused.children()[0] ); - // Both occurrences are recorded on the one source, because the tree reads two inputs and both - // of them read these rows. - let paths = input - .paths - .iter() - .map(|path| path.as_str().to_string()) - .collect::>(); - assert_eq!(2, paths.len(), "{paths:?}"); - assert_ne!(paths[0], paths[1], "{paths:?}"); - assert!(paths[0].starts_with("root.left"), "{paths:?}"); - assert!(paths[1].starts_with("root.right"), "{paths:?}"); + // Both occurrences name the one child, because the tree reads two inputs and both of them read + // these rows. + let inputs = tree_inputs(fused); + assert_eq!( + inputs, + vec![ + ("root.left.input".to_string(), 0), + ("root.right.input".to_string(), 0) + ], + "the occurrences were not rebound to the one child" + ); + // The columns a series is reported under are the node's: one binding names them for both + // occurrences, rather than each occurrence carrying its own copy. + let binding = fused.binding(); + assert_eq!(binding.metric_name.as_deref(), Some("some_metric")); + assert_eq!(binding.time_index, "timestamp"); + assert_eq!(binding.tags, vec!["tag_0".to_string()]); +} + +/// Two occurrences that read one table over different bounds read different rows, so they are two +/// actual sources and keep the existing plan. +#[tokio::test] +async fn native_fused_two_occurrences_decline_different_bounds() { + let tags = [("host", false), ("zone", false)]; + for query in [ + // One side reads a window ten seconds earlier than the other. + "some_metric{host!=\"\"} + some_metric{host!=\"\"} offset 10s", + // One side folds the same window around a fixed anchor, the other around every grid point. + "rate(some_metric{host!=\"\"}[5m]) + rate(some_metric{host!=\"\"}[5m] @ 300)", + ] { + assert_two_occurrences_fall_back(&tags, query).await; + } +} + +/// The raw input nodes of `fused`'s tree, as their structural path and the child each reads. +fn tree_inputs(fused: &FusedSeries) -> Vec<(String, usize)> { + let mut inputs = Vec::new(); + promql::native::metrics::walk(fused.tree().root(), &mut |node, path| { + if let NativeExpr::Input(bound) = &node.expr { + inputs.push((path.as_str().to_string(), bound.source_index)); + } + }); + inputs } /// Two occurrences whose matchers differ read different rows, so they keep the existing plan. @@ -1923,28 +1954,28 @@ async fn build_identity_fused_plan( build_native_fused_plan_with_provider(query, native_fused, table_provider).await } -/// The paths an admitted two-occurrence statement records on its one input. +/// The input nodes an admitted two-occurrence statement binds, as their paths. +/// +/// Both occurrences read the one child the statement was collapsed onto, so both are numbered after +/// it: a plan that left the two occurrences on two children would hand each side of the match half +/// the partitions, which is the shape this route declines. fn admitted_two_occurrence_paths(plan: &LogicalPlan) -> Vec { let fused = find_fused_series(plan).expect("the statement should plan to one native node"); assert_eq!( 1, - fused.fused_inputs().len(), - "two occurrences over one scan are one input" + fused.children().len(), + "two occurrences over one scan are one child" ); - let input = &fused.fused_inputs()[0]; assert!( - matches!(input.input, LogicalPlan::TableScan(_)), - "the input should be the selector's own scan: {:?}", - input.input + matches!(fused.children()[0], LogicalPlan::TableScan(_)), + "the child should be the selector's own scan: {:?}", + fused.children()[0] ); - let paths = input - .paths - .iter() - .map(|path| path.as_str().to_string()) - .collect::>(); - assert_eq!(2, paths.len(), "{paths:?}"); - assert_ne!(paths[0], paths[1], "{paths:?}"); - paths + let inputs = tree_inputs(fused); + assert_eq!(2, inputs.len(), "{inputs:?}"); + assert_ne!(inputs[0].0, inputs[1].0, "{inputs:?}"); + assert_eq!((0, 0), (inputs[0].1, inputs[1].1), "{inputs:?}"); + inputs.into_iter().map(|(path, _)| path).collect() } /// Asserts `query` plans exactly as it does with the native route off. @@ -2087,8 +2118,8 @@ async fn native_fused_two_occurrences_decline_metadata_key() { } } -/// A statement that names its selector once reads one scan, so it records one path however many -/// positional operands its tree has. +/// A statement that names its selector once reads one scan, so it binds one child and one input, +/// however many positional operands its tree has. #[tokio::test] async fn native_fused_one_occurrence_records_one_path() { for query in [ @@ -2103,14 +2134,15 @@ async fn native_fused_one_occurrence_records_one_path() { let plan = build_native_fused_plan(query, true).await; let fused = find_fused_series(&plan) .unwrap_or_else(|| panic!("{query}: {}", plan.display_indent())); - assert_eq!(1, fused.fused_inputs().len(), "{query}"); - let input = &fused.fused_inputs()[0]; + assert_eq!(1, fused.children().len(), "{query}"); assert!( - matches!(input.input, LogicalPlan::TableScan(_)), + matches!(fused.children()[0], LogicalPlan::TableScan(_)), "{query}: {:?}", - input.input + fused.children()[0] ); - assert_eq!(1, input.paths.len(), "{query}: {:?}", input.paths); + let inputs = tree_inputs(fused); + assert_eq!(1, inputs.len(), "{query}: {inputs:?}"); + assert_eq!(0, inputs[0].1, "{query}: {inputs:?}"); } } diff --git a/src/query/tests/native_multi_selector.rs b/src/query/tests/native_multi_selector.rs index 050cf41190d..abff3d30e61 100644 --- a/src/query/tests/native_multi_selector.rs +++ b/src/query/tests/native_multi_selector.rs @@ -40,7 +40,7 @@ use datatypes::series::samples::{FieldSpec, SampleRef, Samples, SeriesFields, Se use datatypes::series::{Label, MetricName, SeriesOrdering}; use promql::evaluated::EvaluatedChunk; use promql::native::execute::{NativeExecutionState, NativeExecutor}; -use promql::native::plan::NativeExpr; +use promql::native::plan::{BoundInput, NativeExpr}; use query::promql::native_compile::SelectorRequirement; use query::promql::native_compile::{CompiledTree, compile_selectors}; @@ -244,6 +244,32 @@ fn every_point(value: f64) -> Vec<(usize, f64)> { (0..5).map(|position| (position, value)).collect() } +/// Each compiled input's tree node names the child of the final tree it reads: occurrence `i` reads +/// child `i`, which is what makes the handful of sources a caller holds a tree it can feed. +/// +/// The compiler numbers occurrences, so `a + a` binds two children even though both reads see the +/// same series; a caller that knows they are one scan rebinds them, which is a decision made above +/// this compiler. +#[test] +fn compiled_inputs_are_numbered_by_binding_occurrence() { + for (query, expected) in [ + ("a", vec![0]), + ("a + b", vec![0, 1]), + ("a + a", vec![0, 1]), + ("(a + b) / a", vec![0, 1, 2]), + ] { + let compiled = compile(query); + let mut indices = Vec::new(); + promql::native::metrics::walk(compiled.tree.root(), &mut |node, _| { + if let NativeExpr::Input(BoundInput { source_index, .. }) = &node.expr { + indices.push(*source_index); + } + }); + assert_eq!(indices, expected, "query: {query}"); + assert_eq!(compiled.inputs.len(), expected.len(), "query: {query}"); + } +} + /// `a + b` over two genuinely different inputs: different metric names, different matcher sets and /// different samples. Each input is fed at the position its own selector was bound to, and the sum /// is asserted point by point.