diff --git a/src/promql/src/extension_plan/fused_series.rs b/src/promql/src/extension_plan/fused_series.rs index 4aa8aca4699..031ca2f2e4e 100644 --- a/src/promql/src/extension_plan/fused_series.rs +++ b/src/promql/src/extension_plan/fused_series.rs @@ -19,6 +19,13 @@ //! 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. +//! //! 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 //! physical node prints the tree it will run ([`FusedSeriesExec`]'s `fmt_as`, which embeds @@ -99,11 +106,15 @@ const METRIC_NAME: &str = "__name__"; /// 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. +/// +/// 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 = ( - NodePath, + Vec, Result, ), > + Send, @@ -159,6 +170,13 @@ pub struct FusedSeriesInput { 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. @@ -222,42 +240,59 @@ impl FusedSeries { &self.inputs } - /// The physical node that runs `exec_input` as this node's input. + /// The physical node that runs `exec_inputs` as this node's inputs. /// - /// `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 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. pub fn to_execution_plan( &self, exec_inputs: 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() { + return Err(DataFusionError::Plan(format!( + "FusedSeries binds {} inputs, but {} execution inputs were given", + self.inputs.len(), + exec_inputs.len() + ))); + } let output_schema: SchemaRef = self.output_schema.inner().clone(); - let tree_inputs = tree_inputs(&self.tree)?; let bound = self .inputs .iter() .zip(exec_inputs) - .zip(tree_inputs) - .map(|((input, (exec, source, ordering)), tree_input)| { + .map(|(input, (exec, source, ordering))| { ( exec, source, ordering, - tree_input.path, + // 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, Arc::new(self.tree.clone()), output_schema, - self.inputs[0].time_index.clone(), - self.inputs[0].tags.clone(), + first.time_index.clone(), + first.tags.clone(), )?)) } } @@ -306,13 +341,16 @@ impl UserDefinedLogicalNodeCore for FusedSeries { binding }) .collect(); - Ok(Self { - promql: Arc::clone(&self.promql), - tree: self.tree.clone(), - binding: self.binding.clone(), + // 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. + Self::try_new( + Arc::clone(&self.promql), + self.tree.clone(), + self.binding.clone(), inputs, - output_schema: Arc::clone(&self.output_schema), - }) + Arc::clone(&self.output_schema), + ) } } @@ -331,6 +369,7 @@ impl PartialEq for FusedSeries { && 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.output_schema == other.output_schema @@ -348,6 +387,7 @@ impl Hash for FusedSeries { input.metric_name.hash(state); input.time_index.hash(state); input.tags.hash(state); + input.paths.hash(state); } self.output_schema.hash(state); } @@ -378,6 +418,7 @@ impl PartialOrd for FusedSeries { || 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; @@ -395,37 +436,82 @@ impl PartialOrd for FusedSeries { } } -/// What the tree's input node reads, read off the tree itself. +/// Checks that `bindings` names exactly the raw inputs of `tree`, each destination once. /// -/// The tree is the one authority on the schema its input was compiled against: 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. -struct TreeInput { - path: NodePath, - schema: Arc, -} - -fn tree_inputs(tree: &NativeTree) -> DataFusionResult> { - let mut inputs = Vec::new(); +/// 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(); + let mut not_raw: Option = None; metrics::walk(tree.root(), &mut |node, path| { - if let NativeExpr::Input(input) = &node.expr - && let Some(schema) = input + if let NativeExpr::Input(input) = &node.expr { + match input .output .samples() .filter(|schema| schema.eval_grid.is_none()) - { - inputs.push(TreeInput { - path: path.clone(), - schema: Arc::clone(schema), - }); + { + Some(schema) => nodes.push((path.clone(), Arc::clone(schema))), + None => { + not_raw.get_or_insert_with(|| path.clone()); + } + } } }); - if inputs.is_empty() { + if let Some(path) = not_raw { + return Err(DataFusionError::Plan(format!( + "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(), )); } - Ok(inputs) + 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" + ))); + } + covered[at] = Some((index, 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(()) } /// Refuses a tree whose logical series can be split across the partitions this node runs. @@ -525,15 +611,10 @@ fn reject_a_split_logical_series( ))) } -/// Checks that `tree` reads the schema `binding` declares, on the grid it declares. +/// Whether `left` and `right` hold the same fields, in the same order. /// -/// 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 -/// from its absolute grid positions, so a separately allocated grid with the same spec is the same -/// grid to everything downstream. -/// -/// Answers with what the tree's input reads, which is what a caller names when it hands a raw chunk -/// over. +/// A raw frame's field list is its layout, so two schemas that name different fields are two +/// layouts: decoding one as the other would hand the tree a column it never bound. fn same_schema_fields(left: &SeriesSchema, right: &SeriesSchema) -> bool { left.fields.len() == right.fields.len() && left @@ -543,48 +624,33 @@ 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. +/// +/// 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 +/// from its absolute grid positions, so a separately allocated grid with the same spec is the same +/// grid to everything downstream. fn validate_binding( tree: &NativeTree, binding: &FusedSeriesBinding, inputs: &[FusedSeriesInput], ) -> DataFusionResult<()> { - let mut tree_inputs = Vec::new(); - metrics::walk(tree.root(), &mut |node, path| { - if let NativeExpr::Input(input) = &node.expr { - tree_inputs.push(( - path.clone(), - input - .output - .samples() - .filter(|schema| schema.eval_grid.is_none()) - .map(Arc::clone), - )); - } - }); - if tree_inputs.len() != inputs.len() { - return Err(DataFusionError::Plan(format!( - "FusedSeries runs a tree with {} inputs, but {} inputs were bound", - tree_inputs.len(), - inputs.len() - ))); - } - for (index, ((_, schema), declared)) in tree_inputs.iter().zip(inputs).enumerate() { - let Some(schema) = schema else { - return Err(DataFusionError::Plan( - "FusedSeries runs a tree whose input is not raw series".to_string(), - )); - }; + // 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() { return Err(DataFusionError::Plan( "FusedSeries binds a raw series schema, which cannot have an evaluation grid" .to_string(), )); } - if !same_schema_fields(schema, &declared.series_schema) { - return Err(DataFusionError::Plan(format!( - "FusedSeries input {index} binds a raw series schema the tree's input was not compiled against" - ))); - } if declared.tags.iter().any(|tag| tag == METRIC_NAME) && declared.metric_name.is_none() { return Err(DataFusionError::Plan(format!( "FusedSeries declares a {METRIC_NAME:?} tag column but binds no metric name" @@ -756,14 +822,15 @@ fn classify_output( /// One child of [`FusedSeriesExec`], with everything the node has to know about it. /// /// The plan produces the frames, and the other four are what those frames mean: which label source -/// the producer chose, the ordering it declares, the tree input the chunks are queued at, and the -/// layout the frames were encoded against. They travel together because the node checks each of them -/// against the tree before it runs, and a child that lost any one of them could not be checked. +/// 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, - NodePath, + Vec, Arc, ); @@ -773,7 +840,12 @@ pub struct FusedSeriesExec { promql: Arc, /// The tree this node runs, shared by every partition's execution. tree: Arc, - input_bindings: Vec<(Arc, RawLabelSource, SeriesOrdering, NodePath)>, + input_bindings: Vec<( + Arc, + RawLabelSource, + SeriesOrdering, + Vec, + )>, /// 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 @@ -799,12 +871,18 @@ pub struct FusedSeriesExec { impl FusedSeriesExec { /// Creates the node, rejecting whatever this node cannot execute or convert. /// - /// `input` produces native raw series frames: the series' encoded key, its finality, its - /// timestamps and its fields, plus the complete labels when `label_source` is + /// Each child produces native raw series frames: the series' encoded key, its finality, its + /// timestamps and its fields, plus the complete labels when its `label_source` is /// [`RawLabelSource::Explicit`]. `time_column` and `tags` name the columns of the output, which /// is a row table rather than a frame. /// - /// The parameters stay separate because each is a fact its own caller has: the query, the plan + /// 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 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( @@ -815,14 +893,15 @@ impl FusedSeriesExec { time_column: String, tags: Vec, ) -> DataFusionResult { - let tree_inputs = tree_inputs(&tree)?; - if inputs.len() != tree_inputs.len() { - return Err(DataFusionError::Plan(format!( - "FusedSeriesExec has {} children for {} tree inputs", - inputs.len(), - tree_inputs.len() - ))); - } + validate_paths( + &tree, + inputs + .iter() + .enumerate() + .map(|(index, (_, _, _, paths, schema))| { + (index, paths.as_slice(), schema.as_ref()) + }), + )?; let _ = NativeExecutionState::try_new( &tree, Arc::new(UnboundedMemoryPool::default()), @@ -844,19 +923,12 @@ impl FusedSeriesExec { })? .clone(); let classification = classify_output(&output_schema, &root_schema, &tags, &time_column)?; - for (index, (input, source, _, path, schema)) in inputs.iter().enumerate() { + 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" ))); } - if path != &tree_inputs[index].path - || !same_schema_fields(schema, &tree_inputs[index].schema) - { - return Err(DataFusionError::Plan(format!( - "FusedSeriesExec child {index} does not match its tree input" - ))); - } ensure_frame_matches_label_source(input.schema().as_ref(), source)?; unpack_raw_series( Box::pin(RecordBatchStreamAdapter::new( @@ -866,18 +938,37 @@ impl FusedSeriesExec { Some(Arc::clone(schema)), )?; } - // One input runs one tree per partition, because the series producer keeps a whole series - // in one partition: each tree then owns every chunk of every series it reports. Several - // inputs cannot be executed that way without an exchange that pairs the matching series of - // each input, so they are run by one execution that reads every partition of every input - // (see [`Self::execute`]). + // 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 { + return Err(DataFusionError::Plan( + "FusedSeriesExec has no child to run its tree over".to_string(), + )); + }; let partition_count = if inputs.len() == 1 { - inputs[0].0.properties().partitioning.partition_count() + 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 }; reject_a_split_logical_series(&tree, partition_count)?; - let first = inputs[0].0.properties(); + let first = first.0.properties(); let properties = Arc::new(PlanProperties::new( EquivalenceProperties::new(output_schema.clone()), Partitioning::UnknownPartitioning(partition_count), @@ -886,8 +977,8 @@ impl FusedSeriesExec { )); let input_bindings = inputs .iter() - .map(|(_, source, ordering, path, schema)| { - (Arc::clone(schema), source.clone(), *ordering, path.clone()) + .map(|(_, source, ordering, paths, schema)| { + (Arc::clone(schema), source.clone(), *ordering, paths.clone()) }) .collect(); let inputs = inputs @@ -984,17 +1075,19 @@ impl ExecutionPlan for FusedSeriesExec { } // 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. Ok(Arc::new(Self::try_new( Arc::clone(&self.promql), children .into_iter() .zip(&self.input_bindings) - .map(|(input, (schema, source, ordering, path))| { + .map(|(input, (schema, source, ordering, paths))| { ( input, source.clone(), *ordering, - path.clone(), + paths.clone(), Arc::clone(schema), ) }) @@ -1019,37 +1112,30 @@ impl ExecutionPlan for FusedSeriesExec { .lock() .unwrap_or_else(|e| e.into_inner()) .attach(&context.runtime_env().memory_pool); - // One input is executed a partition at a time, because a series never spans two of them. - // Several inputs cannot be: a match pairs series that two scans may have placed in - // different partitions, and there is no exchange above this node that would move them - // together. One execution reads every partition of every input instead, so the tree sees - // every series of every input and matches them where they are. + // Each source 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, _, path)) in self.inputs.iter().zip(&self.input_bindings) { - let stream = if self.inputs.len() == 1 { - input.execute(partition, Arc::clone(&context))? - } else { - gather_partitions(Arc::clone(input), Arc::clone(&context)) - }; + 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((path.clone(), stream)); + inputs.push((paths.clone(), stream)); } - // Several inputs are one execution, so it is the first partition of the node; one input is - // one execution per scan partition, and the metrics name it. - let execution_partition = if self.inputs.len() == 1 { partition } else { 0 }; + // The execution name is the partition it answers, which is the one it was asked for. let state = NativeExecutionState::try_new( &self.tree, Arc::clone(&context.runtime_env().memory_pool), &self.metric, - execution_partition, + partition, )?; // What the label sets hold is charged to the reservation attached above, so nothing is // reserved per stream: the entries outlive every stream and are released with the plan. - let inputs = inputs.into_iter().map(|(path, stream)| { - Box::pin(stream.map(move |item| (path.clone(), item))) as TaggedInputStream + 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); @@ -1071,62 +1157,6 @@ impl ExecutionPlan for FusedSeriesExec { } } -/// Every partition of `input`, read one after another, as one stream. -/// -/// The series producer keeps a whole series in one partition, so reading the partitions in order -/// keeps each series contiguous: a series appears in exactly one of them, and its chunks keep the -/// order it was written in. A partition is executed when this stream reaches it rather than up -/// front, so the plan below stays a plan until it is read, and a partition that is never reached -/// costs nothing. -fn gather_partitions( - input: Arc, - context: Arc, -) -> SendableRecordBatchStream { - /// What the gathered stream has read so far: the plan, where it stands, and the partition it is - /// reading now. - struct Gathered { - input: Arc, - context: Arc, - partition: usize, - partitions: usize, - current: Option, - } - let schema = input.schema(); - let partitions = input.properties().partitioning.partition_count(); - assert!( - partitions > 0, - "a partitioned plan has at least one partition" - ); - let state = Gathered { - input, - context, - partition: 0, - partitions, - current: None, - }; - let stream = futures::stream::try_unfold(state, |mut state| async move { - loop { - if state.current.is_none() { - if state.partition >= state.partitions { - return Ok(None); - } - let next = state - .input - .execute(state.partition, Arc::clone(&state.context))?; - state.partition += 1; - state.current = Some(next); - } - let stream = state.current.as_mut().expect("a partition stream is set"); - match futures::StreamExt::next(stream).await { - Some(Ok(batch)) => return Ok(Some((batch, state))), - Some(Err(error)) => return Err(error), - None => state.current = None, - } - } - }); - Box::pin(RecordBatchStreamAdapter::new(schema, stream)) -} - /// Converts one evaluated chunk into one output batch. /// /// The time column is the absolute grid positions the chunk carries, missing samples are nulls and @@ -1498,13 +1528,25 @@ pub struct FusedSeriesStream { } impl FusedSeriesStream { - fn push_at(&mut self, path: &NodePath, chunk: RawSeriesChunk) -> DataFusionResult<()> { + /// Pushes one chunk of one actual source at every tree input it feeds. + /// + /// 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<()> { let executor = self.executor.as_mut().ok_or_else(|| { DataFusionError::Execution( "FusedSeriesExec stream pushed a chunk after its execution closed".into(), ) })?; - executor.push_raw_at(path, chunk)?; + let 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)?; let mut settled = Vec::new(); while let Some(chunk) = executor.next_chunk()? { settled.push(chunk); @@ -1636,9 +1678,9 @@ impl Stream for FusedSeriesStream { this.fail(); return Poll::Ready(Some(Err(DataFusionError::External(Box::new(error))))); } - Poll::Ready(Some((path, Ok(chunk)))) => { + Poll::Ready(Some((paths, Ok(chunk)))) => { budget -= 1; - if let Err(error) = this.push_at(&path, chunk) { + if let Err(error) = this.push_at(&paths, chunk) { this.fail(); return Poll::Ready(Some(Err(error))); } diff --git a/src/promql/src/extension_plan/fused_series/tests.rs b/src/promql/src/extension_plan/fused_series/tests.rs index 0f6516da9fb..037d3d966ec 100644 --- a/src/promql/src/extension_plan/fused_series/tests.rs +++ b/src/promql/src/extension_plan/fused_series/tests.rs @@ -32,8 +32,8 @@ use std::collections::VecDeque; use std::fmt::{self, Display, Formatter}; use std::pin::Pin; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; use datafusion::arrow::array::{Array, Float64Array, StringArray, TimestampMillisecondArray}; @@ -69,12 +69,12 @@ use futures::{Stream, StreamExt, TryStreamExt}; use store_api::region_engine::RawLabelSource; use super::{ - FusedSeries, FusedSeriesBinding, FusedSeriesExec, FusedSeriesInput, LabelSets, OutputColumn, - POLL_BUDGET, label_set, occupied_runs, series_to_record_batch, + FusedSeries, FusedSeriesBinding, FusedSeriesChild, FusedSeriesExec, FusedSeriesInput, + LabelSets, OutputColumn, POLL_BUDGET, label_set, occupied_runs, series_to_record_batch, }; use crate::evaluated::EvaluatedChunk; use crate::native::execute::{NativeExecutionState, NativeExecutor}; -use crate::native::metrics::NodePath; +use crate::native::metrics::{NodeMetric, NodePath}; use crate::native::plan::{ AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundWindow, Grouping, NativeExpr, NativeNode, NativeTree, NativeType, @@ -184,6 +184,19 @@ fn rate_tree() -> NativeTree { } fn binary_tree(left_schema: Arc, right_schema: Arc) -> NativeTree { + binary_tree_op(BinaryOp::Add, left_schema, right_schema) +} + +/// [`binary_tree`] over `op`, for a test that needs an operator its operands cannot exchange. +/// +/// `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( + op: BinaryOp, + left_schema: Arc, + right_schema: Arc, +) -> NativeTree { let grid = grid(); let left_eval = Arc::new(SeriesSchema { fields: left_schema.fields.clone(), @@ -235,7 +248,7 @@ fn binary_tree(left_schema: Arc, right_schema: Arc) left: Box::new(left), right: Box::new(right), matching: BinaryMatching { - op: BinaryOp::Add, + op, return_bool: false, labels: MatchingLabels::On(vec![Arc::from(HOST)]), cardinality: Cardinality::OneToOne, @@ -442,23 +455,29 @@ fn binding_of( fn one_input(tree: &NativeTree, plan: LogicalPlan) -> Vec { one_input_tags(tree, plan, vec![HOST.to_string(), NAME.to_string()]) } + +/// 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, _| { + crate::native::metrics::walk(tree.root(), &mut |node, path| { if let NativeExpr::Input(input) = &node.expr { - found.push(Arc::clone(input.output.samples().unwrap())); + 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: found.remove(0), + series_schema, metric_name: Some(Arc::from(METRIC)), 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], }] } @@ -467,6 +486,37 @@ 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 { + FusedSeries::try_new( + Arc::from("a + on(host) a"), + tree.clone(), + binding(tree), + inputs, + output_schema().to_dfschema_ref().unwrap(), + ) +} + /// The schema of a frame carrying series of `schema` with their labels explicit. fn frame_schema_of(schema: &SeriesSchema) -> SchemaRef { raw_series_frame_schema(schema, RawLabelMode::Explicit).expect("explicit labels are a frame") @@ -527,6 +577,80 @@ fn memory_exec_partitioned(partitions: Vec>) -> Arc, + calls: Arc>>, +} + +impl ExecuteRecorder { + fn counting( + input: Arc, + calls: &Arc>>, + ) -> Arc { + Arc::new(Self { + input, + calls: Arc::clone(calls), + }) + } +} + +impl std::fmt::Debug for ExecuteRecorder { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("ExecuteRecorder").finish() + } +} + +impl DisplayAs for ExecuteRecorder { + fn fmt_as(&self, _t: DisplayFormatType, _f: &mut Formatter) -> fmt::Result { + Ok(()) + } +} + +impl ExecutionPlan for ExecuteRecorder { + fn name(&self) -> &str { + "ExecuteRecorder" + } + + fn properties(&self) -> &Arc { + self.input.properties() + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + + fn apply_expressions( + &self, + f: &mut dyn FnMut(&Arc) -> DataFusionResult, + ) -> DataFusionResult { + self.input.apply_expressions(f) + } + + fn with_new_children( + self: Arc, + _children: Vec>, + ) -> DataFusionResult> { + Ok(self) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> DataFusionResult { + self.calls + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(partition); + self.input.execute(partition, context) + } +} + /// A task context whose memory pool is `pool`, so what the node charges can be read afterwards. fn task_context(pool: &Arc) -> Arc { let runtime = RuntimeEnvBuilder::new() @@ -738,6 +862,17 @@ 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() @@ -1210,6 +1345,14 @@ fn count(metrics: &MetricsSet, name: &str) -> usize { } } +/// The gauge `name` reports, which must be one the node records. +fn gauge(metrics: &MetricsSet, name: &str) -> usize { + match metrics.sum_by_name(name) { + Some(MetricValue::Gauge { gauge, .. }) => gauge.value(), + other => panic!("no gauge named {name}: {other:?}"), + } +} + /// Prints `node` the way the logical `EXPLAIN` prints it. struct Explain<'a>(&'a FusedSeries); @@ -1341,6 +1484,9 @@ async fn two_input_binary_exec_routes_each_raw_stream_to_its_tree_path() { 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(), @@ -1348,6 +1494,7 @@ async fn two_input_binary_exec_routes_each_raw_stream_to_its_tree_path() { 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(), @@ -1360,14 +1507,14 @@ async fn two_input_binary_exec_routes_each_raw_stream_to_its_tree_path() { memory_exec(frames(&[series_chunk("job", &[(GRID_START, 10.0)], true)])), RawLabelSource::Explicit, SeriesOrdering::Contiguous, - NodePath::root().left().input(), + vec![NodePath::root().left().input()], left_schema, ), ( memory_exec(frames(&[series_chunk("job", &[(GRID_START, 7.0)], true)])), RawLabelSource::Explicit, SeriesOrdering::Contiguous, - NodePath::root().right().input(), + vec![NodePath::root().right().input()], right_schema, ), ], @@ -1387,12 +1534,77 @@ async fn two_input_binary_exec_routes_each_raw_stream_to_its_tree_path() { 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. +/// +/// 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. #[tokio::test] -async fn two_inputs_match_across_every_partition_of_each_scan() { +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:?}"); +} + +/// 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 output = output_schema(); let node = FusedSeries::try_new( Arc::from("a + on(host) b"), tree.clone(), @@ -1404,6 +1616,7 @@ async fn two_inputs_match_across_every_partition_of_each_scan() { 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(), @@ -1411,32 +1624,62 @@ async fn two_inputs_match_across_every_partition_of_each_scan() { time_index: TIME.into(), tags: vec![HOST.into(), NAME.into()], input: input_plan(frame_schema()), + paths: vec![NodePath::root().right().input()], }, ], - output + output_schema() .to_dfschema_ref() .expect("the output schema is valid"), ) .expect("the two-input binding matches the tree"); - // The two scans need not even agree on how many partitions they have: what pairs their series is - // the label, not the partition index, so the counts only decide how much each scan reads at once. - let left_rows = series_samples(1.0); - let right_rows = series_samples(2.0); - let left = memory_exec_partitioned(vec![ - frames(&[series_chunk("h1", &left_rows, true)]), - frames(&[series_chunk("h2", &left_rows, true)]), - ]); - let right = memory_exec_partitioned(vec![ - frames(&[series_chunk("h2", &right_rows, true)]), - frames(&[series_chunk("h1", &right_rows, true)]), - Vec::new(), - ]); + let 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![ - (left, RawLabelSource::Explicit, SeriesOrdering::Contiguous), - (right, RawLabelSource::Explicit, SeriesOrdering::Contiguous), + ( + one(rows_of(1.0)), + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + ), + ( + one(rows_of(2.0)), + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + ), ]) - .expect("the two-input physical plan builds"); + .expect("two single-partition sources are one execution"); assert_eq!( 1, physical @@ -1444,35 +1687,375 @@ async fn two_inputs_match_across_every_partition_of_each_scan() { .output_partitioning() .partition_count() ); - let batches = collect(Arc::clone(&physical), SessionContext::default().task_ctx()) + let batches = collect(physical, SessionContext::default().task_ctx()) .await .expect("the sole output partition executes"); - let actual = rows(&batches); - // A grid of its own, and the sample of each side that sits exactly on each of its points. - let grid_stamps = grid_timestamps(); - let expected = grid_stamps - .iter() - .map(|&stamp| { - let left = left_rows - .iter() - .find_map(|(time, value)| (*time == stamp).then_some(*value)) - .expect("the left samples cover every grid point"); - let right = right_rows - .iter() - .find_map(|(time, value)| (*time == stamp).then_some(*value)) - .expect("the right samples cover every grid point"); - (stamp, Some(left + right)) + let mut rows = rows(&batches); + rows.sort_by_key(|row| row.0); + let expected = grid_timestamps() + .into_iter() + .map(|stamp| { + let value = 3.0 * stamp as f64 / 1_000.0; + (stamp, Some(value)) }) .collect::>(); - for host in ["h1", "h2"] { - let series = actual + assert_eq!( + expected, + rows.iter().map(|row| (row.0, row.1)).collect::>(), + "each grid point holds the sum of the two sources" + ); + assert!( + rows.iter().all(|row| row.2.as_deref() == Some("h1")), + "the match is on the host the two series share: {rows:?}" + ); +} + +/// 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. +#[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 samples = series_samples(1.0); + let exec = plan_of( + node, + memory_exec(frames(&[series_chunk("h1", &samples, true)])), + ) + .expect("the physical node builds"); + let batches = collect(exec, SessionContext::default().task_ctx()) + .await + .expect("the one partition answers"); + let rows = rows(&batches); + let expected = grid_timestamps() + .into_iter() + .map(|stamp| { + let sample = samples + .iter() + .find_map(|(time, value)| (*time == stamp).then_some(*value)) + .expect("the samples cover every grid point"); + (stamp, Some(2.0 * sample), Some("h1".to_string())) + }) + .collect::>(); + assert_eq!( + expected, + rows.iter() + .map(|row| (row.0, row.1, row.2.clone())) + .collect::>(), + "every grid point must hold the sample of the series plus itself, on the label it carries" + ); +} + +/// A source read at both destinations 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 +/// source is asked for each partition exactly once (a second execution in one partition would read +/// the series twice), the count the node declares is the count it is given rather than a fixed one, +/// and each partition's peak is reported under its own name, which is what a figure that must not be +/// summed across partitions looks like. +/// +/// The count is checked at two values on purpose: a node that ran only the first two partitions, or +/// that answered a partition from a hardcoded executors-per-source figure, reads as correct at one. +#[tokio::test] +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 scales = (1..=partitions).map(|n| n as f64).collect::>(); + let source_partitions = scales .iter() - .filter(|row| row.2.as_deref() == Some(host)) - .map(|row| (row.0, row.1)) + .enumerate() + .map(|(index, scale)| { + frames(&[series_chunk( + &format!("web-{index}"), + &series_samples(*scale), + true, + )]) + }) .collect::>(); - assert_eq!(expected, series, "the complete summed series for {host}"); + let calls = Arc::new(Mutex::new(Vec::new())); + let source = ExecuteRecorder::counting(memory_exec_partitioned(source_partitions), &calls); + let exec = plan_of(node, source).expect("the physical node builds"); + assert_eq!( + partitions, + exec.properties().output_partitioning().partition_count(), + "the node's count is its one source's" + ); + + // The optimizer leaves the child alone at this count as well, so the series each execution + // owns still arrives whole: an exchange under the node would move half of one to another. + let mut config = ConfigOptions::new(); + config.execution.target_partitions = partitions; + let optimized = EnsureRequirements::new() + .optimize(Arc::clone(&exec), &config) + .expect("the rule accepts the plan"); + let exchanges = exchanges_between(&optimized, &exec); + assert!( + exchanges.is_empty(), + "the optimizer inserted {exchanges:?} under a {partitions}-partition source" + ); + + let batches = collect(Arc::clone(&exec), SessionContext::default().task_ctx()) + .await + .expect("each partition runs its own tree"); + let actual = rows(&batches); + assert_eq!( + partitions * GRID_LEN as usize, + actual.len(), + "{partitions} partitions: {actual:?}" + ); + for (index, scale) in scales.iter().enumerate() { + let host = format!("web-{index}"); + let series = actual + .iter() + .filter(|row| row.2.as_deref() == Some(host.as_str())) + .cloned() + .collect::>(); + assert_eq!(GRID_LEN as usize, series.len(), "{host}: {series:?}"); + for (row, stamp) in series.iter().zip(grid_timestamps()) { + assert_eq!(stamp, row.0, "{host}"); + let value = row + .1 + .unwrap_or_else(|| panic!("{host} at {stamp} holds no value")); + let expected = 2.0 * scale * stamp as f64 / 1_000.0; + assert!( + (expected - value).abs() < 1e-9, + "{host} at {stamp}: {value} is not {expected}" + ); + } + } + // One execution per partition, and no partition executed twice. + let mut called = calls.lock().unwrap_or_else(|e| e.into_inner()).clone(); + called.sort_unstable(); + assert_eq!( + (0..partitions).collect::>(), + called, + "{partitions} partitions were not executed once each" + ); + // The peak of each partition is named after it, so the collector cannot sum one partition's + // peak into another's and report a figure that is neither. + let metrics = exec + .metrics() + .expect("the node reports its runtime's metrics"); + for partition in 0..partitions { + let peak = gauge( + &metrics, + &NodePath::root() + .partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, partition), + ); + assert!( + peak > 0, + "partition {partition} of {partitions} ran its tree but reported no peak" + ); + } } - assert_eq!(2 * GRID_LEN as usize, actual.len()); +} + +/// 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()], + ] { + logical(&tree, vec![binding_at(paths, input_plan(frame_schema()))]) + .expect("one source at both destinations is the admitted shape"); + } +} + +/// A binding's schema is checked against the schema of every destination it names. +/// +/// 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. +#[test] +fn a_binding_must_agree_with_the_schema_of_each_destination() { + 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 message = error.to_string(); + assert!( + message.contains("`root.right.input`"), + "the refusal must name the destination that disagrees: {message}" + ); + assert!( + message.contains("not compiled against"), + "refused for another reason: {message}" + ); +} + +/// The execution inputs are one per binding, in both directions. +/// +/// A zip would drop the longer side, so a caller that passes one scan 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() { + let tree = rate_tree(); + let node = fused(tree); + let bare = || memory_exec(Vec::new()); + let error = node + .to_execution_plan(vec![ + (bare(), RawLabelSource::Explicit, SeriesOrdering::Contiguous), + (bare(), RawLabelSource::Explicit, SeriesOrdering::Contiguous), + ]) + .expect_err("two execution inputs for one binding"); + 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"); + assert!( + error.to_string().contains("0 execution inputs were given"), + "{error}" + ); +} + +/// The physical children cover the tree's destinations exactly, one child per actual source. +#[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"); + 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}" + ); +} + +/// Rebuilding a node over new inputs keeps the destinations, and revalidation decides. +/// +/// 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. +#[test] +fn with_exprs_and_inputs_keeps_the_destinations() { + 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 rebuilt = node + .with_exprs_and_inputs(vec![], vec![input_plan(frame_schema())]) + .expect("one plan still covers both destinations"); + assert_eq!( + binary_paths().to_vec(), + rebuilt.fused_inputs()[0].paths, + "the destinations must survive a rewrite above the node" + ); + assert_eq!( + node.schema(), + rebuilt.schema(), + "the columns the node reports, and their metadata, are the node's own" + ); + let error = node + .with_exprs_and_inputs(vec![], Vec::new()) + .expect_err("the one binding needs one plan"); + assert!(error.to_string().contains("expected 1 inputs"), "{error}"); } /// A tree the runtime does not execute is refused when the execution plan is built. @@ -1864,7 +2447,7 @@ fn a_child_woken_between_parent_polls_is_not_lost() { .expect("the empty raw-frame stream decodes"); let stream = super::materialize_raw_labels(decoded) .expect("the empty raw-frame stream materializes labels"); - (NodePath::root().input(), Some(stream), false) + (vec![NodePath::root().input()], Some(stream), false) }) .collect(); let mut stream = super::FusedSeriesStream { @@ -1976,7 +2559,7 @@ fn late_child_error_is_not_starved() { .expect("the empty raw-frame stream decodes"); let stream = super::materialize_raw_labels(decoded) .expect("the empty raw-frame stream materializes labels"); - (NodePath::root().input(), stream) + (vec![NodePath::root().input()], stream) }) .collect(); let mut input_streams = futures::stream::SelectAll::new(); @@ -2054,7 +2637,7 @@ fn all_pending_children_park_without_self_wake() { .expect("the empty raw-frame stream decodes"); let stream = super::materialize_raw_labels(decoded) .expect("the empty raw-frame stream materializes labels"); - (NodePath::root().input(), Some(stream), false) + (vec![NodePath::root().input()], Some(stream), false) }) .collect(); let mut stream = super::FusedSeriesStream { diff --git a/src/query/src/dist_plan/commutativity.rs b/src/query/src/dist_plan/commutativity.rs index fc20423ea38..0c179be960b 100644 --- a/src/query/src/dist_plan/commutativity.rs +++ b/src/query/src/dist_plan/commutativity.rs @@ -543,12 +543,21 @@ mod tests { 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: metric_name.map(Arc::from), time_index: "ts".to_string(), tags: Vec::new(), input, + paths, }]; let output_schema: DFSchemaRef = Arc::new( DFSchema::new_with_metadata( diff --git a/src/query/src/optimizer/scan_hint.rs b/src/query/src/optimizer/scan_hint.rs index c7d856273df..b5a28535e88 100644 --- a/src/query/src/optimizer/scan_hint.rs +++ b/src/query/src/optimizer/scan_hint.rs @@ -1586,12 +1586,21 @@ mod test { 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, }]; let output_schema: DFSchemaRef = Arc::new( DFSchema::new_with_metadata( diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 5b40bbeb63a..311252a510b 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -40,7 +40,8 @@ use datafusion_expr::Expr; use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; use promql::extension_plan::{FusedSeries, FusedSeriesBinding, FusedSeriesInput}; -use promql::native::plan::{NativeExpr, reads_across_series}; +use promql::native::plan::{NativeExpr, NativeNode, NativeTree, reads_across_series}; +use promql::vector_match::{Cardinality, MatchingLabels}; use promql_parser::label::Matchers; use promql_parser::parser::value::ValueType; use promql_parser::parser::{ @@ -49,6 +50,7 @@ use promql_parser::parser::{ use session::context::QueryContextRef; use snafu::ResultExt; use store_api::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_ENGINE_NAME}; +use table::metadata::TableMeta; use crate::parser::{EXPLAIN_NODE_NAME, EXPLAIN_VERBOSE_NODE_NAME}; use crate::promql::error::{DataFusionPlanningSnafu, Result}; @@ -91,6 +93,15 @@ pub(crate) fn native_promql_requested(query_ctx: &QueryContextRef) -> bool { /// `Interleaved`, so a tree compiled here runs on either scanner. const NATIVE_ORDERING: SeriesOrdering = SeriesOrdering::Contiguous; +/// The primary-key column names that carry pipeline metadata rather than series identity. +/// +/// A window, a map and a binary operation drop these three labels wherever they read them, while +/// this route reports a series under the primary key it carries. A key column with one of these +/// names therefore keeps the existing plan however whole the rest of the key is: a node that drops +/// one of them can leave two raw series on one canonical label set, and the label set then no +/// longer names the series the partition holds. +const METADATA_KEY_TAGS: [&str; 3] = ["__name__", "__type__", "__unit__"]; + impl PromPlanner { /// Plans `prom_expr` as one [`FusedSeries`] node, or returns `None` to keep the existing plan. /// @@ -107,6 +118,13 @@ impl PromPlanner { /// what it found) and a query this route cannot bind faithfully — unsupported aggregates or /// subqueries, a label matcher the bare scan below the node would not apply, a missing table, a /// 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 + /// 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. pub(super) async fn try_plan_native_fused( &mut self, prom_expr: &PromExpr, @@ -132,6 +150,12 @@ impl PromPlanner { if selectors.is_empty() { return Ok(None); } + // One occurrence keeps the single-scan route below unchanged. Two are admitted only as one + // source read point-wise; three or more would need a match over more than two series sets, + // which the collapse at the end of this method cannot express. + if selectors.len() > 2 { + return Ok(None); + } let Some(stmt) = self.native_statement(prom_expr) else { return Ok(None); }; @@ -264,6 +288,16 @@ impl PromPlanner { if !Self::field_columns_are_raw_series_servable(input.schema(), &fields) { return Ok(None); } + // Two occurrences are admitted only when the scan's raw series keys name one + // logical series each, so that either occurrence reads the same series in whichever + // partition holds it. A single occurrence needs no such proof: it reads its own scan + // once, and the checks above are the ones it has always had. + if selectors.len() == 2 + && (!selector.matchers.or_matchers.is_empty() + || !identity_keys_are_injective(&matchers, table_meta, &tags)) + { + return Ok(None); + } let series_schema = Arc::new(SeriesSchema { fields: fields .iter() @@ -289,6 +323,8 @@ impl PromPlanner { time_index: time, tags, input, + // Filled from the compiled tree, which is what names an input. + paths: Vec::new(), }); } Ok(Some(prepared)) @@ -408,8 +444,33 @@ impl PromPlanner { .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 of one selector read the same series only when the tree between them is + // point-wise and both scans are the same scan. Then both inputs are one plan, and this node + // runs one execution per partition of it instead of one execution over every partition. + // Anything else keeps the existing plan: a match that pairs two scans' series needs an + // exchange that pairs them, which this node does not have. + if selectors.len() == 2 { + if !two_occurrences_read_one_source(&compiled.tree, &inputs) { + return Ok(None); + } + // 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 .root() @@ -586,6 +647,163 @@ fn literal_or_next(start: i64) -> Option { )) } +/// Whether a tree's two occurrences may be read as one source. +/// +/// 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 +/// node that reads a *series* rather than its samples point by point — an aggregate folds a group, +/// and two vectors matched against each other pair one series with another — so those keep the +/// existing plan. The remaining shapes are the ones a scan's own samples support: an instant +/// selection or a window directly over the raw input, a point-wise map over either, and a binary +/// operation with a constant on one side, which is a broadcast over the same positions. +/// +/// A one-to-one match is admitted without looking at its fill values: the compiler refuses to bind +/// `fill_left` or `fill_right` on anything but a `group_left`/`group_right` match, so a one-to-one +/// node has none to account for. +fn two_occurrences_read_one_source(tree: &NativeTree, inputs: &[FusedSeriesInput]) -> bool { + let NativeExpr::Binary { + left, + right, + matching, + } = &tree.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) +} + +/// Whether `node` reads samples point-wise, so that one partitioned execution is one answer. +/// +/// A node's output type is not checked here: [`NativeNode::validate`] already refuses a selection, +/// a map or a binary operation whose operands are not evaluated vectors, so every branch below is +/// one that produces values rather than raw samples. +fn pointwise_operand(node: &NativeNode) -> bool { + match &node.expr { + // A selection reads the raw samples below it; anything else below it is a value computed + // from a whole series, not a scan. + NativeExpr::Instant { input, .. } | NativeExpr::Window { input, .. } => { + matches!(input.expr, NativeExpr::Input(_)) + } + NativeExpr::Map { input, .. } => pointwise_operand(input), + // A constant on one side is broadcast over the vector side's positions. Two vectors are a + // match between two series sets, which is the shape this route cannot split. + NativeExpr::Binary { + left, + right, + matching, + } => { + matching.cardinality == Cardinality::OneToOne + && match (&left.expr, &right.expr) { + (NativeExpr::Scalar(_), NativeExpr::Scalar(_)) => false, + (NativeExpr::Scalar(_), _) => pointwise_operand(right), + (_, NativeExpr::Scalar(_)) => pointwise_operand(left), + _ => false, + } + } + NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::Aggregate { .. } => false, + // A vector operation (`sort`, `absent`, `topk`, `histogram_quantile`, ...) reads the whole + // vector at each grid point, so it is not a point-wise operand of one series. + NativeExpr::Vector { .. } => false, + } +} + +/// Whether `labels` matches on the whole series identity `tags` names. +/// +/// `on(...)` keeps the identity when every tag is listed, because two series that differ in any +/// tag then differ in the key. Anything else — a tag left out of `on`, or a tag named in +/// `ignoring` — pairs two series that Prometheus reads as two, and each partition would then +/// answer for the half it happens to hold. +fn matching_keys_on_identity(labels: &MatchingLabels, tags: &[String]) -> bool { + match labels { + MatchingLabels::On(names) => tags + .iter() + .all(|tag| names.iter().any(|name| name.as_ref() == tag.as_str())), + MatchingLabels::Ignoring(names) => tags + .iter() + .all(|tag| !names.iter().any(|name| name.as_ref() == tag.as_str())), + } +} + +/// Whether the raw series keys `meta` declares name one logical series each. +/// +/// The label set this route reports is the primary key it reads off a series, so the key is only a +/// faithful identity when it is the whole label set and its values are distinct strings: a hidden +/// key column (a metric engine's internals), a key column with a metadata name a window or a map +/// drops, and a key column that can read both NULL and the empty string — Prometheus's one absent +/// label, but two raw keys — all keep the existing plan. A matcher that rejects the empty value is +/// what makes a nullable key column safe: it leaves no row whose key could read either way. +fn identity_keys_are_injective(matchers: &Matchers, meta: &TableMeta, tags: &[String]) -> bool { + // A table with no key column has one label set for every series, and a metric engine keeps its + // identity in columns the planner hides from `tags`. + if tags.is_empty() || meta.engine == METRIC_ENGINE_NAME { + return false; + } + // The planner hides exactly `__table_id` and `__tsid`; a key that differs from the columns this + // route reports means part of the identity is not in the label set. + if !meta.row_key_column_names().eq(tags.iter()) { + return false; + } + tags.iter().all(|tag| { + if METADATA_KEY_TAGS.contains(&tag.as_str()) { + return false; + } + let Some(column) = meta.schema.column_schema_by_name(tag) else { + return false; + }; + // The label set is reported as strings, which is what a string key column already is. + if column.data_type != datatypes::prelude::ConcreteDataType::string_datatype() { + return false; + } + // A non-nullable column cannot read NULL, so an empty value and an absent one are two + // different keys. + !column.is_nullable() + || matchers + .matchers + .iter() + .any(|matcher| matcher.name == tag.as_str() && !matcher.is_match("")) + }) +} + +/// Whether two prepared inputs 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 { + let (LogicalPlan::TableScan(left_scan), LogicalPlan::TableScan(right_scan)) = + (&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) +} + /// The columns a [`FusedSeries`] node produces. /// /// The shape is the one the existing unary pipeline consumes — the time index, then the series diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index 9bf753f81a8..667aed7e6a0 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -1054,6 +1054,73 @@ async fn build_test_table_provider_with_options( ) } +/// A table whose primary key is exactly `tags`, each column nullable or not as asked. +/// +/// The default fixture keeps every tag non-nullable, which is the ordinary Mito shape. A nullable +/// tag column is what a label shared between several logical metrics looks like, and it is the shape +/// where a NULL and an empty string are two raw series keys but one Prometheus label. +async fn build_test_identity_table_provider( + table_name: &str, + tags: &[(&str, bool)], +) -> DfTableSourceProvider { + let catalog_list = MemoryCatalogManager::with_default_setup(); + let mut columns = tags + .iter() + .map(|(tag, nullable)| { + ColumnSchema::new( + (*tag).to_string(), + ConcreteDataType::string_datatype(), + *nullable, + ) + }) + .collect::>(); + columns.push( + ColumnSchema::new( + "timestamp".to_string(), + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ) + .with_time_index(true), + ); + columns.push(ColumnSchema::new( + "field_0".to_string(), + ConcreteDataType::float64_datatype(), + true, + )); + let table_meta = TableMetaBuilder::empty() + .schema(Arc::new(Schema::new(columns))) + .primary_key_indices((0..tags.len()).collect()) + .value_indices(vec![tags.len() + 1]) + .next_column_id(1024) + .build() + .unwrap(); + let table_info = TableInfoBuilder::default() + .name(table_name) + .meta(table_meta) + .build() + .unwrap(); + + assert!( + catalog_list + .register_table_sync(RegisterTableRequest { + catalog: DEFAULT_CATALOG_NAME.to_string(), + schema: DEFAULT_SCHEMA_NAME.to_string(), + table_name: table_name.to_string(), + table_id: 1024, + table: EmptyTable::from_table_info(&table_info), + }) + .is_ok() + ); + + DfTableSourceProvider::new( + catalog_list, + false, + QueryContext::arc(), + DummyDecoder::arc(), + false, + ) +} + async fn build_test_native_histogram_table_provider(table_name: &str) -> DfTableSourceProvider { build_test_native_histogram_table_provider_with_marker(table_name, false).await } @@ -1792,47 +1859,46 @@ 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. #[tokio::test] -async fn native_fused_binary_has_two_independent_scans() { +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!(2, fused.fused_inputs().len()); + assert_eq!(1, fused.fused_inputs().len()); + let input = &fused.fused_inputs()[0]; + assert!( + matches!(input.input, LogicalPlan::TableScan(_)), + "the input should be the selector's own scan: {:?}", + input.input + ); + // 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:?}"); } +/// Two occurrences whose matchers differ read different rows, so they keep the existing plan. #[tokio::test] async fn native_fused_binary_matchers_are_per_scan() { - let plan = build_native_fused_plan( - "some_metric{tag_0=\"a\"} + on(tag_0) some_metric{tag_0=\"b\"}", - true, - ) - .await; - let fused = find_fused_series(&plan).expect("native binary fused route"); - assert_eq!(2, fused.fused_inputs().len()); - let scans = fused - .fused_inputs() - .iter() - .map(|input| match &input.input { - LogicalPlan::TableScan(scan) => scan, - other => panic!("expected TableScan, got {other:?}"), - }) - .collect::>(); - assert_eq!(2, scans[0].filters.len()); - assert_eq!(2, scans[1].filters.len()); - let left = scans[0] - .filters - .iter() - .map(ToString::to_string) - .collect::>() - .join(" AND "); - let right = scans[1] - .filters - .iter() - .map(ToString::to_string) - .collect::>() - .join(" AND "); - assert!(left.contains("a"), "{left}"); - assert!(right.contains("b"), "{right}"); - assert_ne!(left, right); + let query = "some_metric{tag_0=\"a\"} + on(tag_0) some_metric{tag_0=\"b\"}"; + let plan = build_native_fused_plan(query, true).await; + let legacy = build_native_fused_plan(query, false).await; + assert_eq!( + plan.display_indent_schema().to_string(), + legacy.display_indent_schema().to_string(), + "two occurrences over different scans must keep the existing plan" + ); + // The legacy plan still applies each selector's own matcher to its own scan. + let display = legacy.display_indent().to_string(); + assert!(display.contains("Utf8(\"a\")"), "{display}"); + assert!(display.contains("Utf8(\"b\")"), "{display}"); } #[tokio::test] @@ -1841,6 +1907,201 @@ async fn native_fused_binary_flag_off_has_no_fused_node() { assert!(find_fused_series(&plan).is_none()); } +/// Plans `query` over a table whose primary key is exactly `tags`. +/// +/// The tag list is the whole identity: the route admits two occurrences of one selector only when +/// the scan's raw series keys name one logical series each, so a fixture states that key directly. +async fn build_identity_fused_plan( + tags: &[(&str, bool)], + query: &str, + native_fused: bool, +) -> LogicalPlan { + let table_provider = build_test_identity_table_provider("some_metric", tags).await; + build_native_fused_plan_with_provider(query, native_fused, table_provider).await +} + +/// The paths an admitted two-occurrence statement records on its one input. +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" + ); + let input = &fused.fused_inputs()[0]; + assert!( + matches!(input.input, LogicalPlan::TableScan(_)), + "the input should be the selector's own scan: {:?}", + input.input + ); + 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 +} + +/// Asserts `query` plans exactly as it does with the native route off. +async fn assert_two_occurrences_fall_back(tags: &[(&str, bool)], query: &str) { + let native = build_identity_fused_plan(tags, query, true).await; + let legacy = build_identity_fused_plan(tags, query, false).await; + + let display = native.display_indent().to_string(); + assert!(!display.contains("FusedSeries"), "{query}: {display}"); + assert_eq!( + native.display_indent_schema().to_string(), + legacy.display_indent_schema().to_string(), + "{query}: a two-occurrence profile this route cannot read must keep the existing plan" + ); +} + +/// Two occurrences of one selector over one primary key, with matchers that keep the key whole. +#[tokio::test] +async fn native_fused_two_occurrences_admit_one_source_pointwise() { + let tags = [("host", false), ("zone", false)]; + for query in [ + "some_metric{host!=\"\"} + some_metric{host!=\"\"}", + "abs(some_metric{host!=\"\"}) + some_metric{host!=\"\"}", + "rate(some_metric{host!=\"\"}[5m]) / rate(some_metric{host!=\"\"}[5m])", + "some_metric{host!=\"\"} * 2 + some_metric{host!=\"\"} * 2", + ] { + let plan = build_identity_fused_plan(&tags, query, true).await; + let paths = admitted_two_occurrence_paths(&plan); + assert!(paths[0].starts_with("root.left"), "{query}: {paths:?}"); + assert!(paths[1].starts_with("root.right"), "{query}: {paths:?}"); + } +} + +/// A match key that keeps every identity tag pairs one series of one side with itself. +#[tokio::test] +async fn native_fused_two_occurrences_admit_full_key_matching() { + let tags = [("host", false), ("zone", false)]; + for query in [ + "some_metric + on(host, zone) some_metric", + "some_metric + ignoring(__name__) some_metric", + ] { + let plan = build_identity_fused_plan(&tags, query, true).await; + assert_eq!(2, admitted_two_occurrence_paths(&plan).len(), "{query}"); + } +} + +/// A match key that drops an identity tag pairs two series Prometheus keeps apart. +#[tokio::test] +async fn native_fused_two_occurrences_decline_partial_key_matching() { + let tags = [("host", false), ("zone", false)]; + for query in [ + "some_metric + on(host) some_metric", + "some_metric + ignoring(zone) some_metric", + ] { + assert_two_occurrences_fall_back(&tags, query).await; + } +} + +/// `group_left` and `group_right` pair a group against one series. +#[tokio::test] +async fn native_fused_two_occurrences_decline_group_cardinality() { + let tags = [("host", false), ("zone", false)]; + for query in [ + "some_metric + on(host, zone) group_left some_metric", + "some_metric + on(host, zone) group_right some_metric", + ] { + assert_two_occurrences_fall_back(&tags, query).await; + } +} + +/// Two scans, or one scan read over two ranges, are two series sets rather than one. +#[tokio::test] +async fn native_fused_two_occurrences_decline_different_scan_or_bounds() { + let tags = [("host", false), ("zone", false)]; + for query in [ + "some_metric{host=\"a\"} + some_metric{host=\"b\"}", + "rate(some_metric[5m]) + rate(some_metric[10m])", + "rate(some_metric[5m]) + rate(some_metric[5m] offset 1m)", + ] { + assert_two_occurrences_fall_back(&tags, query).await; + } +} + +/// A shape that reads a whole series as a group, or nests one, is not one series point-wise. +#[tokio::test] +async fn native_fused_two_occurrences_decline_nested_and_broadcast_profiles() { + let tags = [("host", false), ("zone", false)]; + for query in [ + // The match itself is nested under a map, so the root is not the operation being matched. + "abs(some_metric + some_metric)", + // A constant broadcast above the match: the root is not a vector-vector operation. + "(some_metric + some_metric) * 2", + // Three occurrences, which one input carrying two paths cannot express. + "some_metric + some_metric + some_metric", + ] { + assert_two_occurrences_fall_back(&tags, query).await; + } +} + +/// A nullable identity tag reads one label set as two raw keys, which stays on the existing plan. +#[tokio::test] +async fn native_fused_two_occurrences_decline_nullable_key_without_proof() { + let tags = [("host", true)]; + for query in [ + // NULL and `""` are two raw keys and one Prometheus label, so a partition holding one half + // cannot answer for the other. + "some_metric + some_metric", + // The cross-partition counterexample: `(m>0)` and `(m<0)` can each hold one of the halves. + "(some_metric > 0) + (some_metric < 0)", + ] { + assert_two_occurrences_fall_back(&tags, query).await; + } +} + +/// A matcher that rejects the empty value leaves no row whose key could read either way. +#[tokio::test] +async fn native_fused_two_occurrences_admit_nullable_key_when_matcher_rejects_empty() { + let plan = build_identity_fused_plan( + &[("host", true)], + "some_metric{host!=\"\"} + some_metric{host!=\"\"}", + true, + ) + .await; + assert_eq!(2, admitted_two_occurrence_paths(&plan).len()); +} + +/// A key column named like pipeline metadata is dropped by the nodes above it. +/// +/// The route reports a series under its primary key, and a window, a map and a binary operation drop +/// `__name__`, `__type__` and `__unit__` wherever they read them, so a key holding one of them names +/// no series on its own. Each case is compared against the same statement with the route off. +#[tokio::test] +async fn native_fused_two_occurrences_decline_metadata_key() { + for tags in [ + [("__name__", false), ("host", false)], + [("__type__", false), ("host", false)], + [("__unit__", false), ("host", false)], + ] { + assert_two_occurrences_fall_back(&tags, "some_metric + some_metric").await; + } +} + +/// Two different metrics are two different scans, however alike their schemas are. +#[tokio::test] +async fn native_fused_two_occurrences_decline_different_table() { + let query = "some_metric + other_metric"; + let table_provider = build_test_table_provider( + &[ + (DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string()), + (DEFAULT_SCHEMA_NAME.to_string(), "other_metric".to_string()), + ], + 1, + 1, + ) + .await; + let plan = build_native_fused_plan_with_provider(query, true, table_provider).await; + let display = plan.display_indent().to_string(); + assert!(!display.contains("FusedSeries"), "{query}: {display}"); +} + /// The flag on and a shape the compiler accepts: the statement plans to one native node. #[tokio::test] async fn native_fused_rate_plans_to_a_fused_series_node() {