From 590044bc66d2f44a7ecca3b2f308b211f0aa9991 Mon Sep 17 00:00:00 2001 From: discord9 Date: Wed, 28 Oct 2026 19:44:37 +0800 Subject: [PATCH] test(promql): cover the canonical merge and the routing node end to end The tests for the two commits this stacks on, kept apart so their diffs stay readable as production changes. What is here and why it is here rather than with the code: - plan/tests.rs - the property derivation, and the placement questions that read it: which node proves one series per label set, what a label rewrite downgrades, that a broadcast derives only its vector side (both operand orders), and that a match needs matching-key co-location while a merge does not. These state the rules the pass and the placement depend on, in the place the rules live. - canonicalize/tests.rs - the insertion pass over whole trees, including the hand-bound merge whose pieces resolve to one label set, and the idempotence of running it twice. - fused_series/tests.rs - the compositions, built from real physical nodes rather than scripted children: a real Fused feeding a real repartition feeding a real Fused with a merge inside, at N=M=2 and at N=2,M=3 so a partition-index assumption cannot hide behind equal counts; the aliased label set whose pieces must meet on one owner; the empty closing chunk; the duplicate-series match that must be refused rather than answered twice locally; and a frame of the other content failing the query. - execute/tests.rs and aggregate_finalize/tests.rs - the runtime cases the new nodes participate in. The suite is the whole branch: promql and query together are 2083 passed, 2 skipped, the same count the combined branch had. Signed-off-by: discord9 --- .../aggregate_finalize/tests.rs | 105 + .../src/extension_plan/fused_series/tests.rs | 1988 ++++++++++++++++- src/promql/src/native/execute/tests.rs | 292 +-- src/promql/src/native/plan/tests.rs | 1173 +++++++++- 4 files changed, 3322 insertions(+), 236 deletions(-) diff --git a/src/promql/src/extension_plan/aggregate_finalize/tests.rs b/src/promql/src/extension_plan/aggregate_finalize/tests.rs index c051f276678..4078880a31a 100644 --- a/src/promql/src/extension_plan/aggregate_finalize/tests.rs +++ b/src/promql/src/extension_plan/aggregate_finalize/tests.rs @@ -112,6 +112,17 @@ fn map_over(inner: NativeNode, ops: Vec) -> NativeNode { } } +/// A canonical merge over `inner`, which reports its input's layout. +fn merge_over(inner: NativeNode) -> NativeNode { + let output = inner.output.clone(); + NativeNode { + expr: NativeExpr::Merge { + input: Box::new(inner), + }, + output, + } +} + fn aggregate_over( inner: NativeNode, kind: AggregateKind, @@ -384,6 +395,100 @@ fn topk_and_bottomk_run_after_the_aggregate_cut() { } } +/// A canonical merge above the cut canonicalizes values the aggregate already evaluated, so it is +/// part of the suffix exactly as an aggregate above the cut is: it runs once, over the merged series, +/// and it cannot tell they were assembled from partitions rather than produced by one execution. +#[test] +fn a_merge_above_the_cut_lands_in_the_suffix() { + let root = merge_over(complete(AggregateKind::Sum, by(&["k0"]))(window())); + let tree = NativeTree::try_new(root.clone()).unwrap(); + assert!( + AggregateFinalize::can_split(&tree, &raw_fields(), "ts"), + "a merge above the cut no longer refuses the split" + ); + + // The cut is still the innermost aggregate, and the prefix is the per-series half below it: the + // window, and no merge at all. + let split = split(tree.root(), &raw_fields(), "ts") + .unwrap() + .expect("the tree holds the aggregate the cut takes out"); + assert_eq!(AggregateKind::Sum, split.op.kind); + assert_eq!(AggregateStage::Complete, split.op.stage); + let prefix = NativeTree::try_new(split.prefix.clone()) + .unwrap() + .to_string(); + assert!(prefix.contains("Window"), "{prefix}"); + assert!(!prefix.contains("Merge"), "{prefix}"); + assert!(!prefix.contains("Aggregate"), "{prefix}"); + + // The suffix holds the merge the query wrote, over the input its merged values enter at. + let NativeExpr::Merge { input } = &split.suffix.expr else { + panic!( + "the merge stays above the cut: {}", + NativeTree::try_new(split.suffix.clone()).unwrap() + ); + }; + assert!( + matches!(&input.expr, NativeExpr::Input(bound) if bound.source_index == 0), + "the merged values enter where the aggregate was" + ); + + // The node builds both halves, which validates the re-wrapped merge on the way in. + let node = finalize(root, output_schema(&["sum(v0)"], &["k0"])).unwrap(); + let producer = producer(&node).tree().to_string(); + assert!(producer.contains("Window"), "{producer}"); + assert!(!producer.contains("Merge"), "{producer}"); + let suffix = node.suffix.to_string(); + assert!(suffix.contains("Merge"), "{suffix}"); + assert!(suffix.contains("Input"), "{suffix}"); + assert!(!suffix.contains("Window"), "{suffix}"); +} + +/// A merge below the cut is in the per-series prefix, which does not hold one series' samples: the +/// merge reads the whole vector, and two of its input series can collapse into the one it answers. +/// The prefix therefore refuses it, and the query keeps the plan it would have had without the split. +/// +/// The shape the split would have to walk is the one validation lets through, because a merge over +/// raw samples is refused before the split ever sees it: see +/// [`a_merge_over_raw_samples_is_refused_at_the_tree_boundary`] below. +#[test] +fn a_merge_below_the_cut_is_declined_by_the_prefix() { + let root = complete(AggregateKind::Sum, by(&["k0"]))(merge_over(window())); + let tree = NativeTree::try_new(root.clone()).unwrap(); + assert!(!AggregateFinalize::can_split(&tree, &raw_fields(), "ts")); + let error = match split(tree.root(), &raw_fields(), "ts") { + Err(error) => error, + Ok(_) => panic!("a prefix across a merge is not one series at a time"), + }; + assert!( + matches!(error, DataFusionError::NotImplemented(_)), + "{error}" + ); + assert!( + error.to_string().contains("canonical merge"), + "the refusal names the merge the prefix would hold: {error}" + ); + assert!( + error.to_string().contains("whole vector"), + "the refusal says why a prefix cannot hold it: {error}" + ); + assert!(finalize(root, output_schema(&["sum(v0)"], &["k0"])).is_err()); +} + +/// `sum(merge(...))` with the merge directly over the scan is not a tree at all: the merge consumes an +/// evaluated vector, and a scan's samples are not one. The tree boundary refuses it, before any split +/// is asked for. +#[test] +fn a_merge_over_raw_samples_is_refused_at_the_tree_boundary() { + let error = NativeTree::try_new(complete(AggregateKind::Sum, by(&["k0"]))(merge_over(raw()))) + .unwrap_err(); + assert!(matches!(error, DataFusionError::Internal(_)), "{error}"); + assert!( + error.to_string().contains("evaluated vector"), + "the refusal names what a merge needs: {error}" + ); +} + #[test] fn limitk_above_the_cut_is_declined_because_merge_does_not_preserve_input_order() { let error = finalize( diff --git a/src/promql/src/extension_plan/fused_series/tests.rs b/src/promql/src/extension_plan/fused_series/tests.rs index 8b4e375b5c6..34639617672 100644 --- a/src/promql/src/extension_plan/fused_series/tests.rs +++ b/src/promql/src/extension_plan/fused_series/tests.rs @@ -35,8 +35,12 @@ use std::pin::Pin; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; +use std::time::Duration; -use common_query::series_frame::unpack_evaluated_series; +use common_error::ext::BoxedError; +use common_query::series_frame::{ + SendableEvaluatedSeriesStream, pack_evaluated_series, unpack_evaluated_series, +}; use datafusion::arrow::array::{Array, Float64Array, StringArray, TimestampMillisecondArray}; use datafusion::arrow::buffer::{Buffer, ScalarBuffer}; use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit}; @@ -87,6 +91,7 @@ use super::{ }; use crate::evaluated::EvaluatedChunk; use crate::extension_plan::aggregate_exchange::state_schema; +use crate::extension_plan::series_repartition::SeriesRepartitionExec; use crate::info::InfoSelector; use crate::map_label::LabelRewrite; use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor}; @@ -2841,18 +2846,6 @@ async fn every_partition_evaluates_its_own_series() { } } -/// The rows of the series `host` rates `rate` at, in time order. -fn one_series(rows: &[Row], rate: f64, host: &str) -> Vec { - let mut series = rows - .iter() - .filter(|row| row.2.as_deref() == Some(host)) - .filter(|row| row.1.is_some_and(|value| (value - rate).abs() < 1e-9)) - .cloned() - .collect::>(); - series.sort_by_key(|row| row.0); - series -} - /// A tree that reads the whole vector runs once over every scan partition, and that one execution /// sees the series of both. /// @@ -2919,6 +2912,22 @@ async fn a_whole_vector_tree_runs_once_over_every_partition() { ); assert_series_rates(&rows, &[(5.0, "web-1")]); } + +/// The rows of the series `host` rates `rate` at, in time order. +/// +/// Neither the name nor the value alone identifies a series here: the fixtures differ in both, so a +/// row of another series cannot be mistaken for one of these. +fn one_series(rows: &[Row], rate: f64, host: &str) -> Vec { + let mut series = rows + .iter() + .filter(|row| row.2.as_deref() == Some(host)) + .filter(|row| row.1.is_some_and(|value| (value - rate).abs() < 1e-9)) + .cloned() + .collect::>(); + series.sort_by_key(|row| row.0); + series +} + /// One repeated source, read once inside one execution, still applies its operands in order. /// /// Both leaves of the tree bind the same source and the outer node is an `on(host)` one-to-one @@ -5073,3 +5082,1956 @@ fn an_info_tree_still_answers_the_newer_info_series() { info_answer(&tree, base, info) ); } + +/// `x` over the tree's input, which is bound to the grid: the tree a Fused reads when its child +/// already decided the values. +/// +/// A map is point-wise over an evaluated vector, so this is the smallest tree whose input node +/// reads evaluated chunks rather than raw samples. The absolute value is its own inverse on the +/// non-negative values the tests below feed, which is what keeps the comparison to the raw-fed +/// tree about the input path rather than about the kernel. +fn abs_over_evaluated_input_tree() -> NativeTree { + let evaluated = evaluated_of(&raw_schema(), &grid()); + NativeTree::try_new(NativeNode { + expr: NativeExpr::Map { + input: Box::new(NativeNode { + expr: NativeExpr::Input(BoundInput { + source_index: 0, + output: evaluated.clone(), + ordering: SeriesOrdering::Contiguous, + }), + output: evaluated.clone(), + }), + op: BoundMap { + ops: Arc::from([MapOp::Math(crate::map::MathOp::Abs)]), + }, + }, + output: evaluated, + }) + .expect("a map over an evaluated input is a legal tree") +} + +/// `abs(rate(x[5m]))`: the raw-fed tree that answers what [`abs_over_evaluated_input_tree`] answers +/// once its child has decided `rate(x[5m])`. +fn abs_rate_tree() -> NativeTree { + let rate = rate_tree(); + NativeTree::try_new(NativeNode { + expr: NativeExpr::Map { + input: Box::new(rate.root().clone()), + op: BoundMap { + ops: Arc::from([MapOp::Math(crate::map::MathOp::Abs)]), + }, + }, + output: rate.root().output.clone(), + }) + .expect("a map over a rate tree is a legal tree") +} + +/// The logical node of `tree` in `format`, over one child carrying that tree's input frames. +fn formatted(tree: &NativeTree, format: FusedOutputFormat) -> FusedSeries { + let output_schema = if format == FusedOutputFormat::SeriesFrame { + canonical_frame_schema(tree) + } else { + output_schema().to_dfschema_ref().unwrap() + }; + FusedSeries::try_new_with_format( + Arc::from(PROMQL), + tree.clone(), + binding(tree), + vec![input_plan(frame_schema())], + output_schema, + format, + ) + .expect("the binding matches the tree") +} + +/// A [`Row`] with the value held as its bits, so the whole row is ordered. +type OrderedRow = (i64, Option, Option, Option); + +/// The rows of a node, ordered by every column, so two runs that differ only in arrival order +/// compare equal. +fn sorted_rows(batches: &[RecordBatch]) -> Vec { + let mut rows = rows(batches) + .into_iter() + .map(|(time, value, host, name)| (time, value.map(f64::to_bits), host, name)) + .collect::>(); + rows.sort(); + rows +} + +/// A Fused whose child is another Fused's evaluated frame answers the same rows as the raw-fed one. +/// +/// This is the RFC's `Fused A -> Fused B` shape without the repartition between them: `A` is +/// `abs(rate(x[5m]))` fed the raw series, it exports an evaluated frame, and `B` is `abs(x)` whose +/// only child is that frame. `B` therefore has to decode an evaluated frame rather than raw +/// samples, and its answer has to be exactly `A`'s own row answer: the values are the same points +/// on the same grid under the same labels, so anything the evaluated path dropped, re-addressed or +/// closed twice shows up as a different row. +#[tokio::test] +async fn a_fused_reads_another_fuseds_evaluated_frame() { + let raw_tree = abs_rate_tree(); + // What the raw-fed tree answers on its own, which is the answer the frame has to carry over. + let plain = plan_of( + formatted(&raw_tree, FusedOutputFormat::PlainRows), + memory_exec(two_series_frames()), + ) + .expect("the runtime executes the raw-fed tree"); + let expected = sorted_rows( + &collect(plain, SessionContext::default().task_ctx()) + .await + .expect("the raw-fed tree runs"), + ); + assert_eq!(2 * GRID_LEN as usize, expected.len(), "{expected:?}"); + + // `A` exports the same answer as an evaluated frame. + let exported = plan_of( + formatted(&raw_tree, FusedOutputFormat::SeriesFrame), + memory_exec(two_series_frames()), + ) + .expect("the runtime executes the frame-exporting tree"); + let frame_schema = exported.schema(); + let frames = collect(exported, SessionContext::default().task_ctx()) + .await + .expect("the exporting tree runs"); + assert!(!frames.is_empty(), "the frame carries the answer"); + + // `B` reads that frame: its input node is bound to the grid, so the node has to decode the + // frame as evaluated values and queue them at the evaluated input path. + let evaluated_tree = abs_over_evaluated_input_tree(); + let read = plan_of( + formatted(&evaluated_tree, FusedOutputFormat::PlainRows), + memory_exec_with(frame_schema, frames), + ) + .expect("the runtime executes the evaluated-fed tree"); + let actual = sorted_rows( + &collect(read, SessionContext::default().task_ctx()) + .await + .expect("the evaluated-fed tree runs"), + ); + + assert_eq!(expected, actual); + // The labels travel in the frame, so the same series are named on the way out. + assert!( + actual + .iter() + .any(|(_, _, host, _)| host.as_deref() == Some("web-1")), + "the frame's labels reach the output: {actual:?}" + ); + assert!( + actual.iter().all(|(_, _, _, name)| name.is_none()), + "rate dropped the metric name before the frame was written: {actual:?}" + ); +} + +/// A frame that declares the other content than its consumer reads fails the query. +/// +/// The frame says what its rows are and the tree's input node says what it was compiled to read; +/// the two decoders refuse a frame that declares the other content, so the plan is refused when it +/// is built rather than run with a child decoded as something it is not. Both directions are +/// checked, and each one asserts the decoder's own words: nothing here is silently skipped. +#[tokio::test] +async fn a_frame_of_the_other_content_fails_the_query() { + // An evaluated frame: what `A` exports, which a raw-bound input may not read. + let raw_tree = abs_rate_tree(); + let exporting = plan_of( + formatted(&raw_tree, FusedOutputFormat::SeriesFrame), + memory_exec(two_series_frames()), + ) + .expect("the runtime executes the frame-exporting tree"); + let frame_schema = exporting.schema(); + let frames = collect(exporting, SessionContext::default().task_ctx()) + .await + .expect("the exporting tree runs"); + assert!(!frames.is_empty()); + + let error = plan_of( + formatted(&raw_tree, FusedOutputFormat::PlainRows), + memory_exec_with(frame_schema, frames), + ) + .expect_err("a raw-bound input cannot read evaluated values"); + let message = error_chain(&error); + assert!( + message.contains("expected a raw frame, found an evaluated one"), + "refused for another reason: {message}" + ); + + // Raw frames where the input node was compiled to read evaluated values. + let evaluated_tree = abs_over_evaluated_input_tree(); + let error = plan_of( + formatted(&evaluated_tree, FusedOutputFormat::PlainRows), + memory_exec(two_series_frames()), + ) + .expect_err("a grid-bound input cannot read raw samples"); + let message = error_chain(&error); + assert!( + message.contains("expected an evaluated frame, found a raw one"), + "refused for another reason: {message}" + ); +} + +/// The schema the tree's input is bound to when its child already decided the values: `raw_schema`'s +/// one field, on [`grid`]. +fn evaluated_schema() -> Arc { + Arc::new(SeriesSchema { + fields: raw_schema().fields.clone(), + eval_grid: Some(grid()), + }) +} + +/// One evaluated chunk of `metric`: `len` rows from grid position `start`, each holding its own +/// position as its value, and whether it closes the series. +/// +/// A chunk of no rows is the closing chunk a series sends when nothing is left of it, which is a +/// shape of its own: it carries the finality and no position. +fn evaluated_chunk( + metric: &SeriesLabels, + start: usize, + len: usize, + is_last: bool, +) -> (Series, bool) { + let schema = evaluated_schema(); + let spans = if len == 0 { + Vec::new() + } else { + vec![GridSpan::new(start, len)] + }; + let time = TimeAxis::from_grid_spans(grid(), spans).expect("one run on the grid"); + let values = (0..len) + .map(|index| Some((start + index) as f64)) + .collect::>(); + ( + Series::try_new( + &schema, + metric.clone(), + time, + SeriesFields::one(Samples::from_float(Float64Array::from(values))), + ) + .expect("a chunk of this schema"), + is_last, + ) +} + +/// A physical input over evaluated chunks: each of its partitions hands over the chunks scripted for +/// it, packed into the frame the node above decodes. +/// +/// It declares [`Partitioning::UnknownPartitioning`], which is what a node says when it reorders +/// without claiming a relation between its partitions: nothing about the declaration proves which +/// series share a label set. +struct ScriptedEvaluated { + series_schema: Arc, + partitions: Vec>, + properties: Arc, +} + +impl ScriptedEvaluated { + /// The child plan over `partitions`, one partition per list of chunks. + fn plan(partitions: Vec>) -> Arc { + let series_schema = evaluated_schema(); + let frame = pack_evaluated_series( + Box::pin(futures::stream::empty()), + Arc::clone(&series_schema), + ) + .expect("an evaluated schema declares a frame") + .schema(); + Arc::new(Self { + series_schema, + properties: Arc::new(PlanProperties::new( + EquivalenceProperties::new(frame), + Partitioning::UnknownPartitioning(partitions.len()), + EmissionType::Incremental, + Boundedness::Bounded, + )), + partitions, + }) + } +} + +impl std::fmt::Debug for ScriptedEvaluated { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("ScriptedEvaluated") + .field("partitions", &self.partitions.len()) + .finish() + } +} + +impl DisplayAs for ScriptedEvaluated { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { + write!(f, "ScriptedEvaluated: partitions={}", self.partitions.len()) + } +} + +impl ExecutionPlan for ScriptedEvaluated { + fn name(&self) -> &str { + "ScriptedEvaluated" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + Vec::new() + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> DataFusionResult, + ) -> DataFusionResult { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DataFusionResult> { + assert!(children.is_empty(), "a scripted child has no children"); + Ok(self) + } + + fn execute( + &self, + partition: usize, + _context: Arc, + ) -> DataFusionResult { + let chunks = self.partitions.get(partition).cloned().ok_or_else(|| { + DataFusionError::Execution(format!("ScriptedEvaluated has no partition {partition}")) + })?; + let chunks = chunks.into_iter().map(Ok::<_, BoxedError>); + let source: SendableEvaluatedSeriesStream = Box::pin(futures::stream::iter(chunks)); + pack_evaluated_series(source, Arc::clone(&self.series_schema)) + } +} + +/// The tree's input node, bound to the grid: what a Fused reads when its child already decided the +/// values. +fn evaluated_input() -> NativeNode { + let evaluated = evaluated_of(&raw_schema(), &grid()); + NativeNode { + expr: NativeExpr::Input(BoundInput { + source_index: 0, + output: evaluated.clone(), + ordering: SeriesOrdering::Contiguous, + }), + output: evaluated, + } +} + +/// `merge(x)` over the tree's input: the smallest canonical merge, over a child that says nothing +/// about which series share a label set. +fn evaluated_merge_tree() -> NativeTree { + let input = evaluated_input(); + let output = input.output.clone(); + NativeTree::try_new(NativeNode { + expr: NativeExpr::Merge { + input: Box::new(input), + }, + output, + }) + .expect("a merge over an evaluated input is a legal tree") +} + +/// `topk(2, x)` over the tree's input: a whole-vector operator over an evaluated child. +fn evaluated_vector_tree() -> NativeTree { + let input = evaluated_input(); + let output = input.output.clone(); + NativeTree::try_new(NativeNode { + expr: NativeExpr::Vector { + input: Box::new(input), + op: BoundVectorOp::TopK { + k: 2.0, + top: true, + group: Grouping::By(Arc::new([])), + }, + }, + output, + }) + .expect("a vector operation over an evaluated input is a legal tree") +} + +/// `sum by (host) (x)` over the tree's input: a `Complete` aggregate over an evaluated child, which +/// reads every contribution to a group and so needs one execution of its own. +fn evaluated_complete_aggregate_tree() -> NativeTree { + let input = evaluated_input(); + let output = input.output.clone(); + NativeTree::try_new(NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(input), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Grouping::By(Arc::new([HOST.into()])), + stage: AggregateStage::Complete, + }, + }, + output, + }) + .expect("a complete aggregate over an evaluated input is a legal tree") +} + +/// The physical node of `tree` over `child`, ready to run: the logical child is the frame the tree's +/// input was compiled against. +fn evaluated_node(tree: &NativeTree) -> FusedSeries { + formatted(tree, FusedOutputFormat::PlainRows) +} + +/// Which output partition a two-output [`SeriesRepartitionExec`] sends each of `hosts` to. +/// +/// The node routes a chunk by the canonical label set of its series, and its module states that the +/// decision is a function of the label set and the output count alone: one execution's answer holds +/// for the next. A test that needs a label set on a named output therefore asks the node instead of +/// restating its hash. +/// +/// Every output is read at once, which is what the node requires of its caller: one output's queue +/// fills and suspends the read, so reading an output to its end before starting the next would test +/// the backpressure rather than the routing. +async fn routed_outputs(hosts: &[&str], outputs: usize) -> Vec { + let chunks = hosts + .iter() + .map(|host| evaluated_chunk(&metric(&[(HOST, host)], Some(METRIC)), 0, 1, true)) + .collect::>(); + let node = SeriesRepartitionExec::try_new(ScriptedEvaluated::plan(vec![chunks]), outputs) + .expect("the repartition node is built"); + let context = SessionContext::default().task_ctx(); + let per_output = futures::future::try_join_all((0..outputs).map(|partition| { + let stream = node + .execute(partition, Arc::clone(&context)) + .expect("the output executes"); + unpack_evaluated_series(stream, None) + .expect("an output declares an evaluated frame") + .try_collect::>() + })) + .await + .expect("every output is read"); + let mut landed = Vec::new(); + for (partition, chunks) in per_output.iter().enumerate() { + for (series, _) in chunks { + let host = series + .metric + .get(HOST) + .expect("a probe series names its host") + .to_string(); + landed.push((host, partition)); + } + } + hosts + .iter() + .map(|host| { + landed + .iter() + .find(|(found, _)| found == host) + .expect("every probe series is read once") + .1 + }) + .collect() +} + +/// A label set that the two-output [`SeriesRepartitionExec`] of a test routes to `output`. +async fn label_set_routed_to(output: usize) -> SeriesLabels { + let hosts = (0..16) + .map(|index| format!("routed-{index}")) + .collect::>(); + let names = hosts.iter().map(String::as_str).collect::>(); + let routed = routed_outputs(&names, 2).await; + let host = names + .iter() + .zip(routed) + .find(|(_, landed)| *landed == output) + .map(|(host, _)| *host) + .expect("sixteen label sets reach both outputs of a two-output repartition"); + metric(&[(HOST, host)], Some(METRIC)) +} + +/// Every output partition of `plan`, each collected on its own but all of them polled at once. +/// +/// All of them at once is what a caller of a repartitioning child owes it, and what makes the rows +/// of one partition distinguishable from another's. +async fn rows_of_every_partition(plan: &Arc) -> Vec> { + let context = SessionContext::default().task_ctx(); + let partitions = (0..plan.properties().partitioning.partition_count()) + .map(|partition| { + let stream = plan + .execute(partition, Arc::clone(&context)) + .expect("the partition executes"); + stream.try_collect::>() + }) + .collect::>(); + futures::future::try_join_all(partitions) + .await + .expect("every partition of the plan runs") + .iter() + .map(|batches| rows(batches)) + .collect() +} + +/// A canonical merge over a child that holds every piece of a label set in the partition it names +/// keeps one execution per partition. +/// +/// The signal is the child itself: an output of [`SeriesRepartitionExec`] holds every piece of the +/// label sets it names, which is the canonical-key ownership a merge needs, so the merge below reads +/// each label set whole in whichever partition holds it. Three outputs are three executions, each naming +/// one output of that child - not one execution over all three, which is what a merge used to force +/// whenever the tree held one at all. +#[tokio::test] +async fn a_merge_over_a_repartitioning_child_keeps_its_partitions() { + let routed = SeriesRepartitionExec::try_new( + ScriptedEvaluated::plan(vec![ + vec![evaluated_chunk( + &metric(&[(HOST, "web-1")], Some(METRIC)), + 0, + GRID_LEN as usize, + true, + )], + vec![evaluated_chunk( + &metric(&[(HOST, "web-2")], Some(METRIC)), + 0, + GRID_LEN as usize, + true, + )], + ]), + 3, + ) + .expect("the repartition node is built"); + let tree = evaluated_merge_tree(); + let exec = plan_of(evaluated_node(&tree), Arc::new(routed)).expect("the runtime executes it"); + + assert_eq!( + 3, + exec.properties().partitioning.partition_count(), + "the child names three label-set owners, so the merge runs once per owner" + ); + + // Each execution reads the one output partition it names, so what it answers is that owner's + // series and nothing else: two of the three outputs hold a series here and the third holds none. + let per_partition = rows_of_every_partition(&exec).await; + let mut hosts = Vec::new(); + let mut answered = Vec::new(); + for partition in &per_partition { + let mut named = partition + .iter() + .filter_map(|(_, _, host, _)| host.clone()) + .collect::>(); + named.sort(); + named.dedup(); + assert!( + named.len() <= 1, + "one execution answered more than its own owner's series: {named:?}" + ); + hosts.extend(named); + answered.extend(partition.iter().cloned()); + } + hosts.sort(); + assert_eq!( + vec!["web-1".to_string(), "web-2".to_string()], + hosts, + "both owners answer in the partitions the repartition put them on" + ); + let expected = ["web-1", "web-2"] + .into_iter() + .flat_map(|host| { + grid_timestamps() + .into_iter() + .enumerate() + .map(move |(position, time)| { + ( + time, + Some(position as f64), + Some(host.to_string()), + Some(METRIC.to_string()), + ) + }) + }) + .collect::>(); + answered.sort_by(|left, right| left.partial_cmp(right).expect("rows of a grid compare")); + let mut expected = expected; + expected.sort_by(|left, right| left.partial_cmp(right).expect("rows of a grid compare")); + assert_eq!(expected, answered, "each owner's series is answered whole"); +} + +/// The declared partitioning is not the proof: a child that declares the same +/// [`Partitioning::UnknownPartitioning`] without being the repartition node is refused, not given one +/// execution. +/// +/// `UnknownPartitioning(M)` says the relation between the partitions is unknown, which is what a +/// union, a coalesce and every reordering node declare as well. Nothing there proves that pieces of +/// one label set sit together, so a merge above such a child cannot answer a canonical series and the +/// node must not read the declaration as the proof. +/// +/// This used to keep one execution: the merge answered that it needed one whenever nothing proved the +/// pieces co-located, and the node collapsed its child's three partitions into one to serve it. That +/// is the arrangement the architecture fix removed - it took the caller's parallelism away to serve a +/// tree nobody had proved was placeable - so the shape is now declined instead, and the assertion +/// below is the refusal rather than a partition count of one. +#[test] +fn a_merge_over_an_unknown_partitioning_child_is_refused() { + let child = ScriptedEvaluated::plan(vec![ + vec![evaluated_chunk( + &metric(&[(HOST, "web-1")], Some(METRIC)), + 0, + 1, + true, + )], + vec![evaluated_chunk( + &metric(&[(HOST, "web-2")], Some(METRIC)), + 0, + 1, + true, + )], + Vec::new(), + ]); + assert_eq!(3, child.properties().partitioning.partition_count()); + let tree = evaluated_merge_tree(); + let error = plan_of(evaluated_node(&tree), child) + .expect_err("a child that proves nothing about label-set ownership cannot answer a merge"); + let message = error.to_string(); + assert!( + message.contains("canonical merge") && message.contains("co-located"), + "refused for another reason than the missing co-location proof: {message}" + ); +} + +/// A per-series tree over a multi-partition child still reports the child's partition count. +/// +/// Nothing in this tree reads the whole vector, so one execution per partition is the parallelism +/// that keeps its answers cheap, and a child's ownership makes no difference to that. +#[tokio::test] +async fn a_per_series_tree_keeps_the_childs_partitions() { + let routed = SeriesRepartitionExec::try_new( + ScriptedEvaluated::plan(vec![ + vec![evaluated_chunk( + &metric(&[(HOST, "web-1")], Some(METRIC)), + 0, + 1, + true, + )], + vec![evaluated_chunk( + &metric(&[(HOST, "web-2")], Some(METRIC)), + 0, + 1, + true, + )], + ]), + 3, + ) + .expect("the repartition node is built"); + let tree = abs_over_evaluated_input_tree(); + let exec = plan_of(evaluated_node(&tree), Arc::new(routed)).expect("the runtime executes it"); + assert_eq!(3, exec.properties().partitioning.partition_count()); + + let plain = ScriptedEvaluated::plan(vec![ + vec![evaluated_chunk( + &metric(&[(HOST, "web-1")], Some(METRIC)), + 0, + 1, + true, + )], + Vec::new(), + ]); + let exec = plan_of(evaluated_node(&tree), plain).expect("the runtime executes it"); + assert_eq!( + 2, + exec.properties().partitioning.partition_count(), + "a per-series tree follows the child's partition count" + ); +} + +/// A whole-vector tree reports one execution, whatever its child proves. +/// +/// A `Vector` operation ranks a group's series against each other and a `Complete` aggregate folds +/// every contribution to a group, so neither answers the result over part of the metric: one +/// execution is what they need even when the child already routes by canonical label set. +#[test] +fn a_whole_vector_tree_over_a_repartitioning_child_reports_one_execution() { + for tree in [evaluated_vector_tree(), evaluated_complete_aggregate_tree()] { + let routed = SeriesRepartitionExec::try_new( + ScriptedEvaluated::plan(vec![vec![evaluated_chunk( + &metric(&[(HOST, "web-1")], Some(METRIC)), + 0, + 1, + true, + )]]), + 3, + ) + .expect("the repartition node is built"); + assert_eq!(3, routed.properties().partitioning.partition_count()); + let exec = + plan_of(evaluated_node(&tree), Arc::new(routed)).expect("the tree is executable"); + assert_eq!( + 1, + exec.properties().partitioning.partition_count(), + "a whole-vector tree reads every partition in one execution" + ); + } +} + +/// A Fused completes over a repartitioning child whose routed chain does not fit one output's queue. +/// +/// The child routes each chunk by canonical label set into bounded queues and reads its child one +/// chain at a time, so a chain longer than one queue holds can only reach the Fused while the Fused +/// keeps reading the output it went to: the first output's stream cannot end before the read behind +/// it ends, and the read cannot end while the second output's full queue is unread. Reading one +/// partition to its end before the next - which is what this node did - therefore deadlocked, and +/// the timeout below is what turns that into a failure instead of a suite that never finishes. +/// +/// The repartition node is kept alive beside the Fused for as long as it is read, which is not +/// incidental: its output streams are bare receivers, while the task feeding them belongs to the +/// plan, and dropping the plan aborts that task +/// (`SharedExecution::drop` in [`crate::extension_plan::series_repartition`]). `collect` drops the +/// plan it was handed as soon as `execute` returns, so a plan holding the only handle to its own +/// producer stops mid-chain and its output reports an unfinished chain rather than an answer. Keeping +/// the node here measures this node's read discipline rather than that abort; a caller that keeps its +/// physical plan alive for the query - which is what DataFusion's own executor does - owes no such +/// care. The abort is not this node's to fix and is reported rather than worked around. +#[tokio::test] +async fn a_fused_drains_every_partition_of_a_repartitioning_child() { + let on_second = label_set_routed_to(1).await; + let on_first = label_set_routed_to(0).await; + // One chain of five chunks, more than the four chunks an output queues, on the output a + // single-partition read never reaches; the other output holds one series and ends with it. + let long = (0..GRID_LEN as usize) + .map(|position| evaluated_chunk(&on_second, position, 1, position == GRID_LEN as usize - 1)) + .collect::>(); + assert!( + long.len() > 4, + "the chain has to outgrow one output's queue: {} chunks", + long.len() + ); + let routed: Arc = Arc::new( + SeriesRepartitionExec::try_new( + ScriptedEvaluated::plan(vec![long, vec![evaluated_chunk(&on_first, 0, 1, true)]]), + 2, + ) + .expect("the repartition node is built"), + ); + // `sum by (host)` reads every contribution to a group, so this tree is one execution over both + // outputs of the child - the read path that used to stop at the first one. + // + // The node is handed over rather than kept alive beside the plan: a consumer that takes the + // streams and drops the plan is the shape `execute_stream_partitioned` drives, and it has to + // finish. Keeping a reference here would hide a producer that stops when the plan goes, which + // is exactly what this test exists to catch. + let tree = evaluated_complete_aggregate_tree(); + let exec = plan_of(evaluated_node(&tree), routed).expect("the runtime executes it"); + assert_eq!( + 1, + exec.properties().partitioning.partition_count(), + "a complete aggregate reads every partition in one execution" + ); + + let batches = tokio::time::timeout( + Duration::from_secs(30), + collect(exec, SessionContext::default().task_ctx()), + ) + .await + .expect("the Fused finishes instead of waiting for a partition it never reads") + .expect("both outputs of the child are read"); + + let host_of = |metric: &SeriesLabels| { + metric + .get(HOST) + .expect("the probe label set names its host") + .to_string() + }; + let mut actual = batches + .iter() + .flat_map(|batch| rows(std::slice::from_ref(batch))) + .map(|(time, value, host, _)| (time, value, host)) + .collect::>(); + actual.sort_by(|left, right| left.partial_cmp(right).expect("rows of a grid compare")); + let mut expected = vec![(grid_timestamps()[0], Some(0.0), Some(host_of(&on_first)))]; + expected.extend( + grid_timestamps() + .into_iter() + .enumerate() + .map(|(position, time)| (time, Some(position as f64), Some(host_of(&on_second)))), + ); + expected.sort_by(|left, right| left.partial_cmp(right).expect("rows of a grid compare")); + assert_eq!( + expected, actual, + "every chunk of the chain that went to the second output is answered" + ); +} + +/// `topk(1, merge(x))` over the tree's input: a merge under an operator that reads the whole vector. +/// +/// A merge names no partitioning of its own, so an execution reading one input partition answers it +/// only where the boundary proves the pieces co-located. `topk` reads every series at a grid point, +/// so the tree is one execution - and that execution reads every input partition, which is where the +/// pieces of a label set are. The merge is therefore placed, and it is the `topk` that buys the +/// execution, not the merge: a merge alone no longer asks for one. +fn ranked_merge_tree() -> NativeTree { + let input = evaluated_input(); + let merged = NativeNode { + expr: NativeExpr::Merge { + input: Box::new(input.clone()), + }, + output: input.output.clone(), + }; + let output = input.output.clone(); + NativeTree::try_new(NativeNode { + expr: NativeExpr::Vector { + input: Box::new(merged), + op: BoundVectorOp::TopK { + k: 1.0, + top: true, + group: Grouping::By(Arc::new([])), + }, + }, + output, + }) + .expect("a vector operation over a merge over an evaluated input is a legal tree") +} + +/// Two partitions' pieces of one label set arrive as two chains, not as one interleaved stream. +/// +/// The runtime requires a series to arrive whole: its chunks contiguous, its runs increasing and its +/// identity unchanged until the chunk that closes it. Two partitions holding two pieces of the same +/// label set satisfy that only while exactly one chain is handed over at a time, which is what the +/// gather does - and the pieces are laid out here so that an interleaved hand-over cannot pass +/// unnoticed: the first partition's piece sits at the end of the grid and the second's at its start, +/// so a chunk of the second handed over while the first is open runs backwards, which the merge +/// refuses with its own error. Arriving at the merged answer is therefore the assertion that both +/// chains were kept apart, and the merge is what puts their pieces back into one series. +/// +/// The one execution here is the `topk`'s: a merge does not ask for it, and a merge in a +/// per-partition execution is refused when the child proves nothing about label-set ownership +/// (`a_merge_over_an_unknown_partitioning_child_is_refused`). What this test is about is the read +/// discipline under that execution - both of the child's partitions gathered, one chain at a time - +/// which is why the tree carries a whole-vector operator instead of the bare merge it used to. +#[tokio::test] +async fn two_partitions_pieces_of_one_label_set_arrive_as_two_chains() { + let metric = metric(&[(HOST, "web-1")], Some(METRIC)); + // One label set, two pieces, and the second partition's piece first on the grid. + let child = ScriptedEvaluated::plan(vec![ + vec![ + evaluated_chunk(&metric, 3, 2, false), + evaluated_chunk(&metric, GRID_LEN as usize, 0, true), + ], + vec![ + evaluated_chunk(&metric, 0, 2, false), + evaluated_chunk(&metric, 2, 1, true), + ], + ]); + let tree = ranked_merge_tree(); + let exec = plan_of(evaluated_node(&tree), child).expect("the runtime executes it"); + assert_eq!( + 1, + exec.properties().partitioning.partition_count(), + "the `topk` reads every partition, so the merge under it reads both partitions' pieces" + ); + + let batches = tokio::time::timeout( + Duration::from_secs(30), + collect(exec, SessionContext::default().task_ctx()), + ) + .await + .expect("the merge finishes instead of stalling on two open chains") + .expect("both chains are whole, so the merge accepts them"); + + let mut actual = batches + .iter() + .flat_map(|batch| rows(std::slice::from_ref(batch))) + .collect::>(); + actual.sort_by(|left, right| left.partial_cmp(right).expect("rows of a grid compare")); + let expected = grid_timestamps() + .into_iter() + .enumerate() + .map(|(position, time)| { + ( + time, + Some(position as f64), + Some("web-1".to_string()), + Some(METRIC.to_string()), + ) + }) + .collect::>(); + assert_eq!( + expected, actual, + "the merge answers one series carrying both partitions' pieces" + ); +} + +/// The sample time of the piece that fills the start of the statement's grid. +/// +/// `count_over_time(x[5m])` reads the window `(g - 5m, g]` at grid point `g`, so one sample at 180s +/// is inside the windows ending at 300s, 360s and 420s and outside the one ending at 480s (which +/// starts at 180s and excludes it) and the one ending at 540s. +const EARLY_PIECE_MS: [i64; 1] = [180_000]; + +/// The sample times of the piece that fills the end of the grid: both are inside the windows ending +/// at 480s and 540s and outside the one ending at 420s, which starts at 120s. +const LATE_PIECE_MS: [i64; 2] = [450_000, 480_000]; + +/// The tree `count_over_time(x[5m])` compiles to: a window over raw samples that drops the metric +/// name, which is the label rewrite a canonical merge exists to undo. +fn count_over_time_tree() -> NativeTree { + let grid = grid(); + let raw = NativeType::Samples(raw_schema()); + let evaluated = evaluated_of(&raw_schema(), &grid); + NativeTree::try_new(NativeNode { + expr: NativeExpr::Window { + input: Box::new(NativeNode { + expr: NativeExpr::Input(BoundInput { + output: raw.clone(), + source_index: 0, + ordering: SeriesOrdering::Contiguous, + }), + output: raw, + }), + op: BoundWindow { + function: RangeFunction::CountOverTime, + window: RangeWindow { + range_ms: RANGE_MS, + offset_ms: 0, + anchor_ms: None, + modifier: None, + }, + // The input is raw samples, so it has no grid of its own. + input_grid: None, + output_grid: grid, + }, + }, + output: evaluated, + }) + .expect("a window over raw samples is a legal tree") +} + +/// The tree `sum_over_time(merge(x)[5m])` compiles to over an evaluated child: the merge that +/// reassembles each canonical label set, then a window that folds the series it produced. +fn merged_window_tree() -> NativeTree { + let grid = grid(); + let evaluated = evaluated_of(&raw_schema(), &grid); + let input = NativeNode { + expr: NativeExpr::Input(BoundInput { + source_index: 0, + output: evaluated.clone(), + ordering: SeriesOrdering::Contiguous, + }), + output: evaluated.clone(), + }; + NativeTree::try_new(NativeNode { + expr: NativeExpr::Window { + input: Box::new(NativeNode { + expr: NativeExpr::Merge { + input: Box::new(input), + }, + output: evaluated.clone(), + }), + op: BoundWindow { + function: RangeFunction::SumOverTime, + window: RangeWindow { + range_ms: RANGE_MS, + offset_ms: 0, + anchor_ms: None, + modifier: None, + }, + // The window reads the merged series on the grid its child declares. + input_grid: Some(Arc::clone(&grid)), + output_grid: grid, + }, + }, + output: evaluated, + }) + .expect("a window over a merge is a legal tree") +} + +/// One raw chunk of the series `{__name__ = name, host}`, holding one sample of 1.0 at each of +/// `times` and closing it: `count_over_time` counts the samples, so what they hold never reaches +/// the answer. +fn named_series_chunk(host: &str, name: &str, times: &[i64]) -> RawSeriesChunk { + chunk_of( + &raw_schema(), + &format!("{host}/{name}"), + metric(&[(HOST, host)], Some(name)), + times, + vec![times.iter().map(|_| Some(1.0)).collect()], + true, + ) +} + +/// The tokio task that first polled each partition of a test-only leaf child. +type PolledTasks = Arc>>>; + +/// A leaf child that records, per partition, the task that first polls it. +/// +/// A partition count says how many parts a node declares, not how many tasks compute them: one task +/// polling every partition in turn declares the same number. What this records is the task itself, +/// read from [`tokio::task::try_id`] inside the poll - which is where a partition's `execute` +/// really runs, and hence what the partition count actually bought. +struct RecordingTasks { + input: Arc, + polled: PolledTasks, +} + +impl std::fmt::Debug for RecordingTasks { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("RecordingTasks").finish() + } +} + +impl DisplayAs for RecordingTasks { + fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { + self.input.fmt_as(t, f) + } +} + +impl ExecutionPlan for RecordingTasks { + fn name(&self) -> &str { + "RecordingTasks" + } + + 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, + mut children: Vec>, + ) -> DataFusionResult> { + if children.len() != 1 { + return Err(DataFusionError::Plan( + "RecordingTasks requires one child".into(), + )); + } + Ok(Arc::new(Self { + input: children.remove(0), + polled: Arc::clone(&self.polled), + })) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> DataFusionResult { + let mut input = self.input.execute(partition, context)?; + let schema = input.schema(); + let polled = Arc::clone(&self.polled); + let mut recorded = false; + // The task is taken on the first poll, not here: this call may run on the consumer's task + // while the reading is what another task does. + let stream = futures::stream::poll_fn(move |cx| { + if !recorded { + recorded = true; + let mut polled = polled.lock().unwrap_or_else(|error| error.into_inner()); + polled[partition] = tokio::task::try_id(); + } + input.poll_next_unpin(cx) + }); + Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) + } +} + +/// A real `FusedSeriesExec` running `count_over_time(x[5m])` over `partitions`, exporting one +/// evaluated frame per partition: `A` of the three-node composition. +/// +/// The returned record holds, per partition of the leaf, the task that first polled it: that is the +/// task `A`'s window for that partition ran on. +fn count_over_every_partition( + partitions: Vec>, +) -> (Arc, PolledTasks) { + let polled: PolledTasks = Arc::new(Mutex::new(vec![None; partitions.len()])); + let leaf = Arc::new(RecordingTasks { + input: memory_exec_partitioned(partitions), + polled: Arc::clone(&polled), + }); + let tree = count_over_time_tree(); + let node = FusedSeries::try_new_with_format( + Arc::from("count_over_time(x[5m])"), + tree.clone(), + binding(&tree), + vec![input_plan(frame_schema())], + canonical_frame_schema(&tree), + FusedOutputFormat::SeriesFrame, + ) + .expect("the binding matches the tree"); + let plan = plan_of(node, leaf).expect("the runtime executes the counting tree"); + (plan, polled) +} + +/// A real `FusedSeriesExec` running `sum_over_time(merge(x)[5m])` over `input`: `B`. +fn merge_then_window_over(input: Arc) -> Arc { + plan_of(evaluated_node(&merged_window_tree()), input) + .expect("the runtime executes the merging tree") +} + +/// Which output of a two-output `SeriesRepartitionExec` the canonical label set of each of `hosts` +/// reaches once it has passed through a real `Fused A`. +/// +/// The label set a chunk is routed by is the one `A`'s window *wrote*, not the one the raw series +/// carried: the window drops `__name__`, so the only place the routing can be read is after the +/// rewrite. Asking the real nodes is also what keeps this test from restating the node's hash: the +/// answer is a function of the label set and the output count alone, so one measurement holds for +/// the composition that follows. +/// +/// Every output is read at once, which is what the node requires of its caller. The plan is kept +/// alive beside the reads because its producer task belongs to it. +async fn counted_series_routing(hosts: &[&str], outputs: usize) -> Vec { + let one_partition = hosts + .iter() + .map(|host| frame(&named_series_chunk(host, METRIC, &EARLY_PIECE_MS))) + .collect::>(); + let (a, _) = count_over_every_partition(vec![one_partition]); + let repartition = Arc::new( + SeriesRepartitionExec::try_new(a, outputs) + .expect("the repartition node is built over A's evaluated frames"), + ); + let context = SessionContext::default().task_ctx(); + let reads = (0..outputs) + .map(|output| { + let repartition = Arc::clone(&repartition); + let context = Arc::clone(&context); + async move { + let frames = repartition + .execute(output, context) + .expect("the output executes"); + unpack_evaluated_series(frames, None) + .expect("an output declares an evaluated frame") + .try_collect::>() + .await + } + }) + .collect::>(); + let per_output = futures::future::try_join_all(reads) + .await + .expect("every output is read"); + let mut landed = Vec::new(); + for (output, chunks) in per_output.iter().enumerate() { + for (series, _) in chunks { + let host = series + .metric + .get(HOST) + .expect("`A`'s window keeps the host label") + .to_string(); + landed.push((host, output)); + } + } + hosts + .iter() + .map(|host| { + landed + .iter() + .find(|(found, _)| found == host) + .unwrap_or_else(|| panic!("`{host}` reaches no output: {landed:?}")) + .1 + }) + .collect() +} + +/// The rows `sum_over_time(merge(x)[5m])` answers for one canonical label set whose merged values +/// are `sums`, one per grid point, and no metric name because the window below dropped it. +fn summed_series(host: &str, sums: &[f64]) -> Vec { + grid_timestamps() + .into_iter() + .zip(sums.iter().copied()) + .map(|(time, value)| (time, Some(value), Some(host.to_string()), None)) + .collect() +} + +/// `rows` ordered by every column, so two runs that differ only in arrival order compare equal. +fn ordered(rows: &[Row]) -> Vec { + let mut rows = rows.to_vec(); + rows.sort_by(|left, right| left.partial_cmp(right).expect("rows of a grid compare")); + rows +} + +/// Each output partition of `plan`, polled on a stream of its own while all of them are polled at +/// once - which is what a repartitioning child requires of its consumer - with the rows that +/// partition answered and whether the poll after its end reported `None` again. +async fn polled_partition_rows(plan: &Arc) -> Vec<(Vec, bool)> { + let context = SessionContext::default().task_ctx(); + let partitions = (0..plan.properties().partitioning.partition_count()) + .map(|partition| { + let plan = Arc::clone(plan); + let context = Arc::clone(&context); + async move { + let mut stream = plan + .execute(partition, context) + .expect("the partition executes"); + let mut batches = Vec::new(); + while let Some(batch) = stream.next().await { + batches.push(batch.expect("the partition answers instead of failing")); + } + // The end above is the input's own: a chain the producer abandoned arrives as an + // error rather than as an end, so what is left to check is that the end is final. + (rows(&batches), stream.next().await.is_none()) + } + }) + .collect::>(); + futures::future::join_all(partitions).await +} + +/// A real `Fused A` with two partitions, a two-output `SeriesRepartitionExec` and a real `Fused B` +/// holding a merge: the composition a canonical merge needs, wired from actual physical nodes +/// rather than from a scripted child. +/// +/// `A` is `count_over_time(x[5m])`, whose window drops `__name__` as every range function but +/// `last_over_time`/`first_over_time` does. That rewrite is what creates the aliasing this +/// composition exists for, and the test builds it deliberately: `http_requests_total{host="web-1"}` +/// and `http_errors_total{host="web-1"}` are two identities to the raw scan, and both leave the +/// window as the one canonical label set `{host="web-1"}`. They are placed on *different* A +/// partitions - which is the whole point, since the native runtime refuses two raw keys that close +/// on one label set inside a single execution +/// (`differing_raw_keys_that_close_on_one_label_set_are_refused`) - so the same canonical label set +/// reaches the repartition twice, from two partitions, and a merge in either partition alone would +/// present a piece of that series as a canonical one. +/// +/// The two pieces hold disjoint grid positions, which is what makes them merge into one series +/// instead of colliding on one: the early sample lands inside the windows of grid points 0..=2 and +/// outside the rest, so `count_over_time` answers 1 there and nothing after, while the late samples +/// land inside only the windows of the last two points and answer 2 there and nothing before. +/// Merged, `{host=}` is one series of `1, 1, 1, 2, 2`, and `B`'s `sum_over_time` folds it +/// to `1, 2, 3, 5, 7` - values that only hold if both pieces reached one owner. +/// +/// A second canonical label set has to be routed to the *other* output, or a two-output repartition +/// would be distributing nothing. Which output each label set reaches is measured through these +/// same nodes first (`counted_series_routing`) and asserted here rather than assumed: the routing is +/// a function of the label set the window wrote, and the probe is the only place that fact can be +/// read. The composition runs twice, differing only in which A partition holds which piece of the +/// aliased label set, and the owner and the answer must not depend on that. +#[tokio::test] +async fn a_real_merge_over_a_repartition_of_a_real_fused_merges_every_aliased_piece() { + tokio::time::timeout(Duration::from_secs(30), async { + // Where `A`'s rewritten label sets go, asked of these nodes instead of restated from the + // node's hash. Sixteen candidates reach both outputs of a two-output repartition. + let probes = (0..16) + .map(|index| format!("probe-{index}")) + .collect::>(); + let names = probes.iter().map(String::as_str).collect::>(); + let landed = counted_series_routing(&names, 2).await; + let host_on = |output: usize| { + names + .iter() + .zip(&landed) + .find(|(_, reached)| **reached == output) + .map(|(host, _)| host.to_string()) + .unwrap_or_else(|| panic!("no probe label set reached output {output}: {landed:?}")) + }; + // The aliased label set goes to output 0 and the plain one to output 1, so the + // composition below exercises both owners. + let aliased_at = 0; + let plain_at = 1; + let aliased = host_on(aliased_at); + let plain = host_on(plain_at); + + let aliased_early = || named_series_chunk(&aliased, "http_requests_total", &EARLY_PIECE_MS); + let aliased_late = || named_series_chunk(&aliased, "http_errors_total", &LATE_PIECE_MS); + let plain_series = || named_series_chunk(&plain, "http_requests_total", &EARLY_PIECE_MS); + + let mut runs = Vec::new(); + for swapped in [false, true] { + // Which of A's two partitions holds which piece of the aliased label set: the one + // thing the routing must not depend on. The plain label set rides along on the + // second partition in both runs, so the input always holds two canonical label sets. + let partitions = if swapped { + vec![ + vec![frame(&aliased_late())], + vec![frame(&aliased_early()), frame(&plain_series())], + ] + } else { + vec![ + vec![frame(&aliased_early())], + vec![frame(&aliased_late()), frame(&plain_series())], + ] + }; + + let (a, polled_tasks) = count_over_every_partition(partitions); + assert_eq!( + 2, + a.properties().partitioning.partition_count(), + "A runs its window once per scan partition, not once over both: its tree answers \ + one series from one series' rows" + ); + let repartition: Arc = Arc::new( + SeriesRepartitionExec::try_new(Arc::clone(&a), 2) + .expect("the repartition node is built over A's evaluated frames"), + ); + assert_eq!( + 2, + repartition.properties().partitioning.partition_count(), + "the repartition publishes the outputs it was asked for" + ); + let b = merge_then_window_over(Arc::clone(&repartition)); + assert_eq!( + 2, + b.properties().partitioning.partition_count(), + "the merge reads each canonical label set whole in the partition that owns it, so \ + B keeps the M owners instead of collapsing to one execution" + ); + + // The repartition node is kept alive beside B, but that is not what keeps the read + // running: each output stream owns the read through an `OutputLease` on the execution, + // so it lives while any output is being read and stops only when none is being read and + // none is left to hand out (`claimed` and `remaining` both at zero, + // `SharedExecution::release_output` in `series_repartition`). Dropping the plan + // therefore does not abort a read its streams still need, and a caller that keeps it + // for the query - as DataFusion's own executor does - is one owner among several. + let polled = polled_partition_rows(&b).await; + + for (partition, (_, ended)) in polled.iter().enumerate() { + assert!( + *ended, + "partition {partition} of B reported the end of its stream, and the poll after \ + it reported `None` again" + ); + } + + // A's own computation, measured where it ran: `partition_count()` says how many parts A + // declares, and what is asked here is which tasks computed them. + let consumer = tokio::task::try_id(); + let recorded = polled_tasks + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + assert_eq!( + 2, + recorded.len(), + "the leaf holds one partition per A partition" + ); + let tasks = recorded + .iter() + .map(|task| task.unwrap_or_else(|| panic!("a leaf partition was never polled"))) + .collect::>(); + assert_ne!( + tasks[0], tasks[1], + "A's two partitions were polled by two different tasks, so one partition's window \ + did not wait for the other's" + ); + assert!( + tasks.iter().all(|task| Some(*task) != consumer), + "neither partition ran on the consumer's task, so A's computation stayed on the \ + tasks the repartition reads its child on: {tasks:?} against {consumer:?}" + ); + + let answering = polled + .iter() + .enumerate() + .filter(|(_, (rows, _))| !rows.is_empty()) + .map(|(partition, (rows, _))| (partition, rows.clone())) + .collect::>(); + assert_eq!( + 2, + answering.len(), + "one owner per canonical label set, and the two label sets were routed to \ + different outputs: {answering:?}" + ); + + let series_owned_by = |host: &str| -> (usize, Vec) { + let mut owners = answering.iter().filter(|(_, rows)| { + rows.iter() + .all(|(_, _, row_host, _)| row_host.as_deref() == Some(host)) + }); + let (partition, rows) = owners + .next() + .unwrap_or_else(|| panic!("`{host}` answers in no output: {answering:?}")); + assert!( + owners.next().is_none(), + "`{host}` answers in more than one output, so its pieces were not collected" + ); + (*partition, rows.clone()) + }; + let (aliased_owner, aliased_rows) = series_owned_by(&aliased); + let (plain_owner, plain_rows) = series_owned_by(&plain); + assert_ne!( + aliased_owner, plain_owner, + "the two canonical label sets have to be routed to different outputs, or the \ + two-output repartition is not distributing anything" + ); + // The owner is the one the probe measured for the same label set: it is a function of + // the label set alone, which is what makes a merge per owner sound even though one of + // the two pieces travelled through the other A partition in the second run. + assert_eq!(aliased_at, aliased_owner); + assert_eq!(plain_at, plain_owner); + + // Both partitions' pieces are in the answer and nowhere else: the values below only + // hold for the merged series. A piece alone would answer 1, 1, 1 and nothing after + // (the early one) or nothing before and 2, 2 (the late one), and `sum_over_time` of + // either never reaches 5 or 7. This is the assertion the repartition is for: without + // it the merge runs inside each partition, sees one piece, and answers the two pieces + // as two series under one label set. + assert_eq!( + summed_series(&aliased, &[1.0, 2.0, 3.0, 5.0, 7.0]), + ordered(&aliased_rows), + "`{{host=\"{aliased}\"}}` is one series over the whole grid, carrying both A \ + partitions' pieces" + ); + assert_eq!( + summed_series(&plain, &[1.0, 2.0, 3.0, 3.0, 3.0]), + ordered(&plain_rows), + "`{{host=\"{plain}\"}}` is its own series, answered in the other owner" + ); + runs.push(( + aliased_owner, + plain_owner, + ordered(&aliased_rows), + ordered(&plain_rows), + )); + } + + assert_eq!( + runs[0], runs[1], + "the owner of a label set and its answer are functions of the label set alone: moving \ + both pieces of the aliased label set to the other A partition changed neither" + ); + }) + .await + .expect("the composition finishes instead of waiting for a partition nobody reads"); +} + +/// Every output of `plan`, read at once, with the evaluated chunks each of them handed over. +/// +/// Reading all of them at once is what the node requires of its caller: one output's queue fills and +/// suspends the input tasks whose chains belong there, so draining one output to its end before +/// starting the next would test the backpressure rather than what was routed. An output may be +/// executed once - a second `execute` of the same output is refused as a second read of it - so a +/// test that wants the chunks again builds the plan again. +async fn output_chunks(plan: &Arc) -> Vec> { + let context = SessionContext::default().task_ctx(); + let reads = (0..plan.properties().partitioning.partition_count()) + .map(|output| { + let plan = Arc::clone(plan); + let context = Arc::clone(&context); + async move { + let frames = plan.execute(output, context).expect("the output executes"); + unpack_evaluated_series(frames, None) + .expect("an output declares an evaluated frame") + .try_collect::>() + .await + } + }) + .collect::>(); + futures::future::try_join_all(reads) + .await + .expect("every output is read") +} + +/// Asserts that every chain `chunks` hands over is whole, in the terms a merge downstream reads it. +/// +/// `series_repartition`'s own tests check this with a helper of the same name, but it is private to +/// that module and a composition test in this one cannot call it; the rules checked here are the +/// ones it states. A chunk that leaves a series open must be followed by the same series' next +/// chunk, at a position after the last one the chain carried: another series' chunk in between is +/// what a merge downstream cannot repair, because it would have to hold two open series to read +/// either, and a position that does not advance is a chunk the merge would have to reorder to read. +/// Ending with a chain open fails too, since that means a chunk's finality was lost on the way, and a +/// chunk of no rows fails unless it is the closing chunk of the chain it belongs to - the shape a +/// series ends in when nothing of it is left. +fn assert_output_chains_are_whole(chunks: &[(Series, bool)]) { + let named = |labels: &SeriesLabels| format!("{:?}", labels.get(HOST)); + // What the validator keeps of a chain it has not seen close: the identity it opened with, and + // the last position it carried. + let mut open: Option<(SeriesLabels, usize)> = None; + for (series, is_last) in chunks { + let (Some(first), Some(last)) = (series.time.first_position(), series.time.last_position()) + else { + assert!( + *is_last, + "{} carries no positions and does not close its series", + named(&series.metric) + ); + if let Some((open_labels, _)) = &open { + assert_eq!( + open_labels, &series.metric, + "another series' chunk interrupted an open chain" + ); + } + open = None; + continue; + }; + if let Some((open_labels, previous)) = &open { + assert_eq!( + open_labels, &series.metric, + "another series' chunk interrupted an open chain" + ); + assert!( + first > *previous, + "the positions of one chain did not advance across its chunks: {} starts at \ + {first} after the chain's previous chunk ended at {previous}", + named(&series.metric) + ); + } + open = (!*is_last).then(|| (series.metric.clone(), last)); + } + assert!(open.is_none(), "an output ended with a chain open"); +} + +/// A real `Fused A` with **two** partitions, a **three**-output `SeriesRepartitionExec` and a real +/// `Fused B` with **three** partitions: the composition of +/// `a_real_merge_over_a_repartition_of_a_real_fused_merges_every_aliased_piece`, with N != M. +/// +/// The equal-count case cannot tell a correct composition from one that assumes a partition index is +/// preserved: two outputs and two partitions hide "output `i` is A's partition `i`", and the merge +/// would answer correctly under that assumption as long as it held. Three outputs over two upstream +/// partitions cannot hide it - there is no such index to carry - so this test states the stages +/// separately (2, 3, 3) and lets no count stand for another. +/// +/// The input is the aliasing this composition exists for: `http_requests_total{host=..}` and +/// `http_errors_total{host=..}` are two raw identities that both leave `count_over_time`'s window as +/// the one canonical label set `{host=..}`, on disjoint grid positions (see +/// `EARLY_PIECE_MS`/`LATE_PIECE_MS`), so the two pieces only form one series (`1, 1, 1, 2, 2`) once +/// they reach one owner and `sum_over_time` folds it to `1, 2, 3, 5, 7`. They are placed on +/// *different* A partitions, which is what keeps them from being refused as two raw keys closing on +/// one label set inside a single execution. +/// +/// Which of the three outputs each label set reaches is measured through these same nodes +/// (`counted_series_routing`) and asserted rather than assumed. The repartition is also read on its +/// own, before the composition, so that what it hands over is checked where it decides it: every +/// output is a run of whole chains, and every chunk that went in comes out of exactly one output. +#[tokio::test] +async fn a_real_three_owner_repartition_between_two_real_fuseds_merges_every_piece() { + tokio::time::timeout(Duration::from_secs(30), async { + // Where `A`'s rewritten label sets go, asked of these nodes instead of restated from the + // node's hash. Sixteen candidates reach more than one of the three outputs. + let probes = (0..16) + .map(|index| format!("probe-{index}")) + .collect::>(); + let names = probes.iter().map(String::as_str).collect::>(); + let landed = counted_series_routing(&names, 3).await; + let aliased = names[0].to_string(); + let aliased_at = landed[0]; + let (plain, plain_at) = names + .iter() + .zip(&landed) + .find(|(_, output)| **output != aliased_at) + .map(|(host, output)| (host.to_string(), *output)) + .unwrap_or_else(|| { + panic!("every probe label set reached output {aliased_at}: {landed:?}") + }); + + let aliased_early = || named_series_chunk(&aliased, "http_requests_total", &EARLY_PIECE_MS); + let aliased_late = || named_series_chunk(&aliased, "http_errors_total", &LATE_PIECE_MS); + let plain_series = || named_series_chunk(&plain, "http_requests_total", &EARLY_PIECE_MS); + // Two partitions: the early piece of the aliased label set on one, the late piece beside the + // plain series on the other, so two canonical label sets go in over two partitions. + let partitions = vec![ + vec![frame(&aliased_early())], + vec![frame(&aliased_late()), frame(&plain_series())], + ]; + + // First the repartition alone: both of its stages, and what it hands over. + let (probe_a, _) = count_over_every_partition(partitions.clone()); + assert_eq!( + 2, + probe_a.properties().partitioning.partition_count(), + "A runs its window once per scan partition, so two partitions go in" + ); + let probe: Arc = Arc::new( + SeriesRepartitionExec::try_new(probe_a, 3) + .expect("the repartition node is built over A's evaluated frames"), + ); + assert_eq!( + 3, + probe.properties().partitioning.partition_count(), + "the repartition publishes the three outputs it was asked for, and not A's two" + ); + + let routed = output_chunks(&probe).await; + assert_eq!(3, routed.len(), "one read per output, all of them at once"); + let handed_over: usize = routed.iter().map(Vec::len).sum(); + assert_eq!( + partitions.iter().flatten().count(), + handed_over, + "every chunk that went in came out of exactly one output" + ); + let mut label_sets_in = vec![aliased.clone(), plain.clone()]; + label_sets_in.sort(); + let mut label_sets_out = routed + .iter() + .flatten() + .map(|(series, _)| { + series + .metric + .get(HOST) + .expect("`A`'s window keeps the host label") + .to_string() + }) + .collect::>(); + label_sets_out.sort(); + label_sets_out.dedup(); + assert_eq!( + label_sets_in, label_sets_out, + "the two canonical label sets that went in are the two that came out" + ); + for (output, chunks) in routed.iter().enumerate() { + assert_output_chains_are_whole(chunks); + let mut expected = Vec::new(); + if output == aliased_at { + expected.push(aliased.clone()); + } + if output == plain_at { + expected.push(plain.clone()); + } + let mut found = chunks + .iter() + .map(|(series, _)| { + series + .metric + .get(HOST) + .expect("`A`'s window keeps the host label") + .to_string() + }) + .collect::>(); + found.sort(); + found.dedup(); + assert_eq!( + expected, found, + "output {output} hands over the label sets the probe measured for it and no other" + ); + } + // Both pieces of the aliased label set reach one owner, and only there: a piece left on + // another output would be a partial series presented as a canonical one. + let aliased_pieces = routed + .iter() + .enumerate() + .flat_map(|(output, chunks)| { + chunks + .iter() + .filter(|(series, _)| series.metric.get(HOST) == Some(aliased.as_str())) + .map(move |_| output) + }) + .collect::>(); + assert_eq!( + 2, + aliased_pieces.len(), + "both pieces of the aliased label set are handed over, once each" + ); + assert!( + aliased_pieces.iter().all(|output| *output == aliased_at), + "the pieces reached more than one owner: {aliased_pieces:?} against {aliased_at}" + ); + + // Then the whole composition, on the same fixtures. + let (a, _) = count_over_every_partition(partitions); + assert_eq!( + 2, + a.properties().partitioning.partition_count(), + "A's own stage: one window per scan partition, so two" + ); + let repartition: Arc = Arc::new( + SeriesRepartitionExec::try_new(a, 3) + .expect("the repartition node is built over A's evaluated frames"), + ); + assert_eq!( + 3, + repartition.properties().partitioning.partition_count(), + "the repartition's own stage: three owners over two upstream partitions" + ); + let b = merge_then_window_over(Arc::clone(&repartition)); + assert_eq!( + 3, + b.properties().partitioning.partition_count(), + "the merge reads each canonical label set whole in the output that owns it, so B keeps \ + the three owners instead of collapsing to one execution or following A's two" + ); + + let polled = polled_partition_rows(&b).await; + assert_eq!(3, polled.len(), "B runs once per output of the repartition"); + for (partition, (_, ended)) in polled.iter().enumerate() { + assert!( + *ended, + "partition {partition} of B reported the end of its stream, and the poll after it \ + reported `None` again" + ); + } + + let answering = polled + .iter() + .enumerate() + .filter(|(_, (rows, _))| !rows.is_empty()) + .map(|(partition, (rows, _))| (partition, rows.clone())) + .collect::>(); + assert_eq!( + 2, + answering.len(), + "one owner per canonical label set, and the third output answers nothing: {answering:?}" + ); + // Each answering output holds one series, in the output the probe measured for its label + // set: a merge that assumed output `i` were A's partition `i` could not place both here. + for (output, rows) in &answering { + let mut hosts = rows + .iter() + .map(|(_, _, row_host, _)| { + row_host.clone().expect("`B`'s window keeps the host label") + }) + .collect::>(); + hosts.sort(); + hosts.dedup(); + assert_eq!( + 1, + hosts.len(), + "output {output} answers more than one canonical label set: {hosts:?}" + ); + let expected_owner = match hosts[0].as_str() { + host if host == aliased.as_str() => aliased_at, + host if host == plain.as_str() => plain_at, + other => { + panic!("output {output} answered a label set the probe never routed: {other}") + } + }; + assert_eq!( + expected_owner, *output, + "`{}` answers in an output the probe did not put it on: {} against {}", + hosts[0], output, expected_owner + ); + } + let rows_of = |host: &str| -> Vec { + answering + .iter() + .find(|(_, rows)| { + rows.iter() + .all(|(_, _, row_host, _)| row_host.as_deref() == Some(host)) + }) + .map(|(_, rows)| rows.clone()) + .unwrap_or_else(|| panic!("`{host}` answers in no output: {answering:?}")) + }; + // The values only hold if both pieces reached the one owner and were merged there: the early + // piece alone answers 1, 1, 1 and nothing after, the late one nothing before and 2, 2, and + // `sum_over_time` of either never reaches 5 or 7. + assert_eq!( + summed_series(&aliased, &[1.0, 2.0, 3.0, 5.0, 7.0]), + ordered(&rows_of(&aliased)), + "`{{host=\"{aliased}\"}}` is one series over the whole grid, carrying both A \ + partitions' pieces" + ); + assert_eq!( + summed_series(&plain, &[1.0, 2.0, 3.0, 3.0, 3.0]), + ordered(&rows_of(&plain)), + "`{{host=\"{plain}\"}}` is its own series, answered in its own owner" + ); + // In and out agree at the end of the chain too: two canonical label sets went in and two + // series are answered, each over the whole grid and each in exactly one output. + assert_eq!( + 2 * GRID_LEN as usize, + answering.iter().map(|(_, rows)| rows.len()).sum::(), + "two canonical label sets in, two series out, one row per grid point" + ); + }) + .await + .expect("the composition finishes instead of waiting for a partition nobody reads"); +} + +/// The raw sample times of the two zoned series of the duplicate-match test: one per minute from +/// three minutes to eight. +/// +/// `count_over_time(x[5m])` reads the window `(g - 5m, g]`, so every one of the statement's grid +/// points has a sample inside its window and the two label sets are present at the same positions. +/// The duplicate a whole match owes is decided at the first point where two series of one match +/// group are present, and both series are present at every point here. +const ZONED_SAMPLES_MS: [i64; 6] = [180_000, 240_000, 300_000, 360_000, 420_000, 480_000]; + +/// One raw chunk of the series `{__name__ = METRIC, host, zone}`, holding one sample of 1.0 at each +/// of `times` and closing it: `count_over_time` counts the samples, so what they hold never reaches +/// the answer. +fn zoned_series_chunk(host: &str, zone: &str, times: &[i64]) -> RawSeriesChunk { + chunk_of( + &raw_schema(), + &format!("{host}/{zone}"), + metric(&[(HOST, host), (ZONE, zone)], Some(METRIC)), + times, + vec![times.iter().map(|_| Some(1.0)).collect()], + true, + ) +} + +/// `merge(x) + on(host) merge(x)`: one source read twice, each occurrence canonicalized, and a +/// one-to-one `on(host)` match over the two merges. +/// +/// This is the shape a canonical-merge placement reports: each `Merge(Input(0))` needs every piece +/// of ONE canonical label set, which an output of a repartition proves, and the match above them +/// needs something narrower that the same placement does not prove - every series of one +/// `on(host)` group in the execution that pairs them. +fn matched_merge_tree() -> NativeTree { + let input = evaluated_input(); + let merge = || NativeNode { + expr: NativeExpr::Merge { + input: Box::new(input.clone()), + }, + output: input.output.clone(), + }; + let (left, right) = (merge(), merge()); + let output = crate::vector_match::binary_output_schema( + left.output.samples().expect("a merge answers samples"), + right.output.samples().expect("a merge answers samples"), + ) + .expect("an `on(host)` one-to-one match has an output schema"); + NativeTree::try_new(NativeNode { + expr: NativeExpr::Binary { + left: Box::new(left), + right: Box::new(right), + matching: BinaryMatching { + op: BinaryOp::Add, + return_bool: false, + labels: MatchingLabels::On(vec![Arc::from(HOST)]), + cardinality: Cardinality::OneToOne, + fill: FillValues::default(), + }, + }, + output: NativeType::Samples(output), + }) + .expect("an `on(host)` match over two merges is a legal tree") +} + +/// Which output of an `outputs`-way [`SeriesRepartitionExec`] the canonical label set of each of +/// `label_sets` reaches, once it has passed through a real `Fused` running `count_over_time(x[5m])`. +/// +/// The window this `A` runs keeps `host` and `zone` and drops only the metric name, so the label set +/// the repartition routes by is the one the chunk carried minus the name. Which output that is, is +/// asked of these nodes rather than restated from the node's hash: the decision is a function of the +/// label set and the output count alone, so one measurement holds for a composition built from the +/// same nodes. +/// +/// Every output is read at once, which is what the node requires of its caller. +async fn zoned_series_routing(label_sets: &[(&str, &str)], outputs: usize) -> Vec { + let chunks = label_sets + .iter() + .map(|(host, zone)| frame(&zoned_series_chunk(host, zone, &ZONED_SAMPLES_MS))) + .collect::>(); + let (a, _) = count_over_every_partition(vec![chunks]); + let repartition: Arc = Arc::new( + SeriesRepartitionExec::try_new(a, outputs) + .expect("the repartition node is built over A's evaluated frames"), + ); + let per_output = output_chunks(&repartition).await; + let mut landed = Vec::new(); + for (output, chunks) in per_output.iter().enumerate() { + for (series, _) in chunks { + let found = ( + series + .metric + .get(HOST) + .expect("`A`'s window keeps the host label") + .to_string(), + series + .metric + .get(ZONE) + .expect("`A`'s window keeps the zone label") + .to_string(), + ); + landed.push((found, output)); + } + } + label_sets + .iter() + .map(|(host, zone)| { + landed + .iter() + .find(|((found_host, found_zone), _)| found_host == host && found_zone == zone) + .unwrap_or_else(|| { + panic!("`{{host=\"{host}\", zone=\"{zone}\"}}` reaches no output: {landed:?}") + }) + .1 + }) + .collect() +} + +/// The refusal a whole `on(host)` match owes when two series of one match group reach it. +/// +/// This is the message `vector_match::binary_field` appends when the one side of a match group holds +/// two series present at one point (the `one_duplicate` message, rank 0, which is what +/// `earliest_error` reports first at the point it names). The one side of a one-to-one match is the +/// right one, and `render` prints a group as `{name="value"}` pairs. +fn duplicate_series_message(host: &str, timestamp_ms: i64) -> String { + format!( + "found duplicate series for the match group {{host=\"{host}\"}} on the right hand-side of \ + the operation at {timestamp_ms} ms; many-to-many matching not allowed: matching labels \ + must be unique on one side" + ) +} + +/// A match over two canonical owners of one `on(host)` group is refused, not answered locally. +/// +/// `{host="h", zone="a"}` and `{host="h", zone="b"}` are two canonical label sets and one `on(host)` +/// match group. A repartition routes each to an output of its own - asserted here, not assumed - so +/// each owner holds one series of that group on each side. Read per owner, the match finds one +/// candidate per side, pairs them, and the duplicate check a whole match owes over the real group +/// never runs: the user gets two partial answers where Prometheus reports many-to-many matching. +/// +/// The fix this test is the regression for is a placement rule, and the test asserts both halves of +/// it. `needs_single_execution_in` asks a match for `matching_co_located` - both sides in +/// `SinglePartition` - instead of the canonical-key ownership a merge needs, so the node declares +/// one execution here and reads both owners in it. Only then does the group reach +/// `vector_match::binary_field` whole, and only then is the refusal below produced at all. A +/// placement that accepted `ByCanonicalKey` would answer here, which is what the failure of this +/// test would report. +#[tokio::test] +async fn a_match_over_two_canonical_owners_is_refused_instead_of_answered_locally() { + tokio::time::timeout(Duration::from_secs(30), async { + // One host, two zones. Which of these label sets reach different outputs is asked of the + // real nodes: a two-output repartition splits this group over two owners only when the two + // label sets do not collide on one output, and that is a fact about the hash. + let hosts = (0..16) + .map(|index| format!("zoned-{index}")) + .collect::>(); + let candidates = hosts + .iter() + .flat_map(|host| [(host.as_str(), "a"), (host.as_str(), "b")]) + .collect::>(); + let landed = zoned_series_routing(&candidates, 2).await; + let (host, first_owner, second_owner) = hosts + .iter() + .enumerate() + .find(|(index, _)| landed[2 * index] != landed[2 * index + 1]) + .map(|(index, host)| (host.clone(), landed[2 * index], landed[2 * index + 1])) + .unwrap_or_else(|| { + panic!("no host's two zone label sets reached different outputs: {landed:?}") + }); + assert_ne!( + first_owner, second_owner, + "the same host's two zone label sets landed on one output: {landed:?}" + ); + + // The composition: both series of that host through `A` and the two-output repartition, + // then the match over two merges of the same source. + let partitions = vec![vec![ + frame(&zoned_series_chunk(&host, "a", &ZONED_SAMPLES_MS)), + frame(&zoned_series_chunk(&host, "b", &ZONED_SAMPLES_MS)), + ]]; + let (a, _) = count_over_every_partition(partitions); + let repartition: Arc = Arc::new( + SeriesRepartitionExec::try_new(a, 2) + .expect("the repartition node is built over A's evaluated frames"), + ); + assert_eq!( + 2, + repartition.properties().partitioning.partition_count(), + "the repartition publishes the two owners it was asked for" + ); + let exec = plan_of(fused(matched_merge_tree()), Arc::clone(&repartition)) + .expect("the runtime executes a match over two merges"); + assert_eq!( + 1, + exec.properties().partitioning.partition_count(), + "an `on(host)` match pairs by `host`, which is not the canonical key the owners divide, \ + so the node reads both owners in one execution instead of pairing each owner's series \ + with its own" + ); + + // The run: the match needs every series of the group, the group holds two, and a whole match + // owes an error rather than two answers that each paired a series with itself. + let pool = Arc::new(GreedyMemoryPool::new(1 << 26)); + let error = collect(exec, task_context(&pool)) + .await + .expect_err("the match group holds two series, so the match owes its refusal"); + let message = error_chain(&error); + assert!( + message.contains(&duplicate_series_message(&host, GRID_START)), + "refused for another reason: {message}" + ); + assert_eq!( + 0, + pool.reserved(), + "the failed execution holds no bytes after it ended" + ); + }) + .await + .expect("the match is refused instead of waiting for a partition nobody reads"); +} diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index db10580a4fe..4ef00c76624 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -52,11 +52,12 @@ use crate::info::InfoSelector; use crate::instant_eval::select_instants; use crate::map::MathOp; use crate::map_label::LabelRewrite; +use crate::native::canonicalize::insert_native_merge_inside_current_fused; use crate::native::metrics::{NodeMetric, NodeMetrics}; use crate::native::plan::{ AggregateKind, AggregateStage, AggregateStateSchema, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar, BoundSetOp, BoundVectorOp, BoundWindow, Grouping, InstantValue, MapOp, - NativeExpr, NativeNode, NativeTree, NativeType, unifies_its_own_contributions, + NativeExpr, NativeNode, NativeProperties, NativeTree, NativeType, }; use crate::range_eval::{RangeEvaluator, RangeFunction, RangeWindow}; use crate::select::SortOrder; @@ -10794,204 +10795,119 @@ fn a_chunk_pushed_after_the_input_ended_is_refused() { assert_eq!(pool.reserved(), 0); } -// --------------------------------------------------------------------------- -// The one rule the runtime and the tree rewrite share. -// --------------------------------------------------------------------------- - -/// `timestamp(inner)`, which reports a position under the metric name dropped. -fn timestamp_of(inner: NativeNode) -> NativeNode { - let output = inner.output.clone(); - NativeNode { - expr: NativeExpr::Timestamp { - input: Box::new(inner), - }, - output, +/// Runs `tree` over `inputs` and answers every chunk it produced. +/// +/// The inputs are pushed in order and the input is ended before anything is pulled: a merge answers +/// nothing until its input ends, so pulling earlier would only prove that. +fn run_to_end(tree: &NativeTree, inputs: &[EvaluatedChunk]) -> Vec { + let pool = pool(); + let mut execution = executor(tree, Arc::clone(&pool)); + for chunk in inputs { + execution + .push_evaluated(InputId::new(0), chunk.clone()) + .unwrap(); } + execution.end_of_input().unwrap(); + let mut out = Vec::new(); + while let Some(chunk) = execution.next_chunk().unwrap() { + out.push(chunk); + } + assert_eq!(execution.state().reserved_bytes(), 0); + assert_eq!(pool.reserved(), 0); + out } -/// The `shared` flag [`RuntimeNode::build`] answers is [`unifies_its_own_contributions`]'s answer, -/// node for node: `shared` holds exactly when the plan-level function says the node may hand over -/// several contributions of one canonical label set. +/// A merge the insertion pass put above a per-series tree answers the rows the tree answered without +/// it. /// -/// That flag is what the runtime collects on - a window builds its `MergeInput` from its child's, -/// and a `limitk` sets `vector.merge_input` from its input's - so this is the assertion that the -/// insertion pass asks the runtime's own question when it decides where a merge goes. It is made -/// here, on `build`'s return value, because `shared` is not reachable from the tree: `RuntimeNode` -/// and `RuntimeOp` are private to this module. -/// -/// The `false` the flag reports is not one fact but two, and the plan-level function is what tells -/// them apart: a node that has unified and a leaf that claims nothing both report `false` (a -/// `MergeInput` cannot be placed over a leaf's raw samples), while only the second is collected by -/// the pass. The rows below cover both: `None` for the two boundary shapes and the nodes that pass -/// that answer on, `Some(true)` for the nodes that have established one series per label set, and -/// `Some(false)` for the nodes that report their own fragments. +/// The tree is the one the route compiles for `abs(x)` and the merge is the pass's own output, not a +/// node placed by the fixture, so what runs here is the shape a production tree gains. Two streams +/// are checked: a label set arriving whole, and one arriving as two fragments, which is what one +/// scan partition hands over when the series is split across chunks. #[test] -fn the_predicate_and_the_runtime_agree() { - let g = grid(0, 60_000, 4); - let by_job = || Grouping::By(Arc::from([Arc::from("job")])); - // A window over the scan, evaluated on `g`. - let over_scan = |function| window_with(input(), function, 300_000, None, Arc::clone(&g)); - // A window over an already-evaluated boundary, on the same grid. - let over_boundary = |function| { - window_with( - evaluated_input(Arc::clone(&g)), - function, - 300_000, - Some(Arc::clone(&g)), - Arc::clone(&g), - ) - }; - let nodes: Vec<(&str, NativeNode)> = vec![ - // Nothing is claimed: a raw scan and a fused evaluated boundary. - ("`x` - a raw scan", input()), +fn an_inserted_merge_answers_the_rows_the_unmerged_tree_answered() { + let grid = grid(0, 60_000, 4); + let schema = evaluated_schema(Arc::clone(&grid)); + let unmerged = NativeTree::try_new(map(evaluated_input(Arc::clone(&grid)), vec![MathOp::Abs])) + .expect("a map over an evaluated input is a legal tree"); + let merged = + insert_native_merge_inside_current_fused(&unmerged, &[NativeProperties::source_pieces()]) + .expect("the pass keeps the tree legal"); + // What is executed below is the pass's insertion: the pass put the merge at the root. + assert!( + matches!(merged.root().expr, NativeExpr::Merge { .. }), + "{merged}" + ); + assert_eq!(1, merged.to_string().matches("Merge").count(), "{merged}"); + + let metric = named_metric("some_metric", "x"); + let cases: [(&str, Vec); 2] = [ ( - "an already-evaluated boundary", - evaluated_input(Arc::clone(&g)), - ), - // Labels rewritten or fragments reported: what the runtime collects itself. - ( - "`last_over_time(x[5m])` - a window that keeps the metric name", - over_scan(RangeFunction::LastOverTime), + "one label set arriving whole", + vec![evaluated_chunk_of( + &schema, + metric.clone(), + 0, + vec![Some(-1.0), Some(2.0), Some(-3.0), Some(4.0)], + true, + )], ), ( - "`rate(x[5m])` - a window that drops it", - over_scan(RangeFunction::Rate), - ), - ( - "`abs(last_over_time(x[5m]))` - a map", - map(over_scan(RangeFunction::LastOverTime), vec![MathOp::Abs]), - ), - ( - "`timestamp(last_over_time(x[5m]))`", - timestamp_of(over_scan(RangeFunction::LastOverTime)), - ), - ( - "`rate(x[5m]) * 2` - a broadcast that drops the metric name", - broadcast_of( - over_scan(RangeFunction::Rate), - scalar(2.0, Arc::clone(&g)), - binary_matching(BinaryOp::Mul), - ), - ), - ( - "`rate(x[5m]) > 0` - a filtering comparison", - broadcast_of( - over_scan(RangeFunction::Rate), - scalar(0.0, Arc::clone(&g)), - binary_matching(BinaryOp::Gt), - ), - ), - ( - "`topk(1, x)` - a `Vector` that keeps the series it read, over a window", - vector_op( - over_boundary(RangeFunction::Rate), - BoundVectorOp::TopK { - k: 1.0, - top: true, - group: by_job(), - }, - ), - ), - ( - "`topk(1, x)` over a report of fragments", - vector_op( - map(over_boundary(RangeFunction::Rate), vec![MathOp::Abs]), - BoundVectorOp::TopK { - k: 1.0, - top: true, - group: by_job(), - }, - ), - ), - ( - "`limit_ratio(0.5, x)` over a report of fragments", - vector_op( - map(over_boundary(RangeFunction::Rate), vec![MathOp::Abs]), - BoundVectorOp::LimitRatio { ratio: 0.5 }, - ), - ), - ( - "`limitk(1, x)` - it counts series, so it reads the whole vector", - vector_op( - over_boundary(RangeFunction::Rate), - BoundVectorOp::LimitK { - k: 1.0, - group: by_job(), - }, - ), - ), - ( - "`absent(x)` - it reads presence over the whole vector", - vector_op( - over_boundary(RangeFunction::Rate), - BoundVectorOp::Absent { - labels: SeriesLabels::try_new(None, Vec::new()).unwrap(), - }, - ), - ), - // What has already unified. - ("a merge", merge(evaluated_input(Arc::clone(&g)))), - ("`sum without() (rate(x[5m]))`", { - let inner = over_scan(RangeFunction::Rate); - aggregate(inner, sum_grouping(Grouping::By(Arc::from([])))) - }), - ( - "`rate(x[5m]) + rate(x[5m])` - two vectors, matched by the kernel", - binary_of( - over_scan(RangeFunction::Rate), - over_boundary(RangeFunction::Rate), - binary_matching(BinaryOp::Add), - ), - ), - ( - "`and(rate(x[5m]), rate(x[5m]))` - a set operation", - set_of( - over_scan(RangeFunction::Rate), - over_boundary(RangeFunction::Rate), - SetOp::And, - MatchingLabels::Ignoring(Vec::new()), - ), - ), - ("a constant", scalar(1.0, Arc::clone(&g))), - ( - "`x` selected at each grid point", - instant(input(), 300_000, 0, Arc::clone(&g)), + "one label set arriving as two fragments", + vec![ + evaluated_chunk_of( + &schema, + metric.clone(), + 0, + vec![Some(-1.0), Some(2.0)], + false, + ), + evaluated_chunk_of( + &schema, + metric.clone(), + 2, + vec![Some(-3.0), Some(4.0)], + true, + ), + ], ), ]; - for (what, node) in nodes { - let mut inputs = Vec::new(); - let (_, shared) = RuntimeNode::build(&node, &pool(), &mut inputs, "test".to_string()) - .unwrap_or_else(|error| panic!("{what}: the runtime refuses this node: {error}")); + let expected = vec![ + (0, Some(1.0)), + (1, Some(2.0)), + (2, Some(3.0)), + (3, Some(4.0)), + ]; + for (what, inputs) in cases { + let without = run_to_end(&unmerged, &inputs); + let with = run_to_end(&merged, &inputs); assert_eq!( - shared, - matches!(unifies_its_own_contributions(&node), Some(false)), - "{what}: the runtime's `shared` flag and the plan-level answer disagree" + expected, + decided(&without), + "{what}: the tree without the merge" ); + // The merge collects the pieces of one label set, so both streams answer the same rows: the + // merge changed what a consumer receives, not what the query computes. + assert_eq!( + decided(&without), + decided(&with), + "{what}: the inserted merge answered different rows" + ); + // And it answers one series per label set, which is what it was inserted for. The label set + // is the one the unmerged tree answered: `abs` drops `__name__`, and a merge writes no label + // of its own, so both runs name the same series. + assert_eq!(1, with.len(), "{what}: {}", merged); + assert_eq!( + without.first().map(|chunk| chunk.series.metric.clone()), + with.first().map(|chunk| chunk.series.metric.clone()), + "{what}: the inserted merge answered a different series" + ); + if inputs.len() > 1 { + assert_eq!( + 2, + without.len(), + "{what}: the unmerged tree hands the pieces over separately" + ); + } } - // The two `false`s the plan-level answer has to tell apart, stated once here so the loop above - // cannot pass by answering `Some(true)` everywhere: a boundary claims nothing, a merge claims - // what it performed, and a node that hands its input's series back unchanged passes the - // boundary's answer on. - assert_eq!( - None, - unifies_its_own_contributions(&evaluated_input(Arc::clone(&g))), - "a boundary claimed a proof" - ); - assert_eq!( - Some(true), - unifies_its_own_contributions(&merge(evaluated_input(Arc::clone(&g)))), - "a merge did not claim what it performed" - ); - assert_eq!( - None, - unifies_its_own_contributions(&vector_op( - evaluated_input(Arc::clone(&g)), - BoundVectorOp::TopK { - k: 1.0, - top: true, - group: by_job(), - }, - )), - "a `Vector` over a boundary claimed a proof it cannot have" - ); } diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index f91c423b04e..047488fef12 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -21,21 +21,32 @@ use datatypes::series::time::{EvalGrid, GridSpec}; use super::{ AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar, - BoundVectorOp, BoundWindow, CanonicalGrouping, CanonicalOwner, Grouping, InstantValue, MapOp, - NativeExpr, NativeNode, NativeProperties, NativeTree, NativeType, merges_are_placeable_in, - needs_single_execution_in, reads_across_series, + BoundSetOp, BoundVectorOp, BoundWindow, CanonicalGrouping, CanonicalOwner, Grouping, + InstantValue, MapOp, NativeExpr, NativeNode, NativeProperties, NativeTree, NativeType, + merges_are_placeable_in, needs_single_execution, needs_single_execution_in, no_label_sets, + preserves_canonical_identity, reads_across_series, }; use crate::extension_plan::{FusedSeries, FusedSeriesBinding}; +use crate::histogram_eval::NativeHistogramFunction; use crate::info::InfoSelector; use crate::map::MathOp; +use crate::map_label::LabelRewrite; use crate::range_eval::{RangeFunction, RangeWindow}; -use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels}; +use crate::select::SortOrder; +use crate::vector_match::{ + BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, SetOp, +}; -fn grid(start: i64, step: i64, len: u64) -> Arc { +// The tree builders below are `pub(crate)` because the rewrite in [`canonicalize`] is proved with +// the trees they build, rather than with a second set of fixtures that could drift from these. +// +// [`canonicalize`]: crate::native::canonicalize + +pub(crate) fn grid(start: i64, step: i64, len: u64) -> Arc { Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap()) } -fn evaluated( +pub(crate) fn evaluated( schema_fields: Arc<[datatypes::series::samples::FieldSpec]>, grid: Arc, ) -> NativeType { @@ -63,25 +74,38 @@ fn raw() -> NativeType { } fn input() -> NativeNode { + raw_input_at(0) +} + +/// A scan of raw samples bound to source `source_index`. +pub(crate) fn raw_input_at(source_index: usize) -> NativeNode { let output = raw(); NativeNode { expr: NativeExpr::Input(BoundInput { output: output.clone(), - source_index: 0, + source_index, ordering: SeriesOrdering::KeyThenTime, }), output, } } -fn input_on(grid: Arc) -> NativeNode { +pub(crate) fn input_on(grid: Arc) -> NativeNode { + input_on_at(0, grid) +} + +/// A scan bound to source `source_index`, evaluated on `grid`. +/// +/// Two of these are two sources, and the boundary holds one fact for each of them: what tells them +/// apart is the index on the binding, not the order the tree is walked in. +pub(crate) fn input_on_at(source_index: usize, grid: Arc) -> NativeNode { // One schema allocation shared by the binding and the output: `validate` checks that the output // is the binding it was bound to, which is about the binding itself, not the grid's spec. let output = evaluated(Arc::new([]), grid); NativeNode { expr: NativeExpr::Input(BoundInput { output: output.clone(), - source_index: 0, + source_index, ordering: SeriesOrdering::Contiguous, }), output, @@ -198,22 +222,51 @@ fn window_fields(inner: NativeNode, out: Arc, count: usize) -> NativeN } /// A window over `inner` that produces `out`, so two windows can be given the same grid. -fn window_on( +pub(crate) fn window_on( inner: NativeNode, input_grid: Option>, out: Arc, +) -> NativeNode { + window_with(inner, RangeFunction::Rate, input_grid, out) +} + +/// A window of `range_ms` with no offset, anchor or modifier: the shape a selector's range takes. +pub(crate) fn range(range_ms: i64) -> RangeWindow { + RangeWindow { + range_ms, + offset_ms: 0, + anchor_ms: None, + modifier: None, + } +} + +/// A window running `function` over `inner`, evaluated on `out`. +/// +/// Which function it runs is what decides whether the output keeps the label set it read, so a test +/// about the facts a window hands on picks the function it means. +pub(crate) fn window_with( + inner: NativeNode, + function: RangeFunction, + input_grid: Option>, + out: Arc, +) -> NativeNode { + window_of_range(inner, function, 300_000, input_grid, out) +} + +/// The same, over a window `range_ms` wide. +pub(crate) fn window_of_range( + inner: NativeNode, + function: RangeFunction, + range_ms: i64, + input_grid: Option>, + out: Arc, ) -> NativeNode { NativeNode { expr: NativeExpr::Window { input: Box::new(inner), op: BoundWindow { - function: RangeFunction::Rate, - window: RangeWindow { - range_ms: 300_000, - offset_ms: 0, - anchor_ms: None, - modifier: None, - }, + function, + window: range(range_ms), input_grid, output_grid: Arc::clone(&out), }, @@ -222,7 +275,40 @@ fn window_on( } } -fn map_over(inner: NativeNode) -> NativeNode { +/// An instant selection over raw samples. With `value` other than [`InstantValue::Sample`] it +/// reports a time instead of the sample's value, which is the selection that rewrites the labels. +pub(crate) fn instant_over( + inner: NativeNode, + value: InstantValue, + out: Arc, +) -> NativeNode { + NativeNode { + expr: NativeExpr::Instant { + input: Box::new(inner), + op: BoundInstant { + lookback_ms: 300_000, + offset_ms: 0, + at_ms: None, + value, + output_grid: Arc::clone(&out), + }, + }, + output: evaluated(Arc::new([]), out), + } +} + +/// A timestamp over an evaluated vector: each value replaced by its sample's time. +pub(crate) fn timestamp_of(inner: NativeNode) -> NativeNode { + let output = inner.output.clone(); + NativeNode { + expr: NativeExpr::Timestamp { + input: Box::new(inner), + }, + output, + } +} + +pub(crate) fn map_over(inner: NativeNode) -> NativeNode { let out = inner.output.grid().expect("a map needs a grid").clone(); NativeNode { expr: NativeExpr::Map { @@ -235,7 +321,19 @@ fn map_over(inner: NativeNode) -> NativeNode { } } -fn add() -> BinaryMatching { +/// A canonical merge over `inner`, laid out as `inner` is: a merge writes no field and no grid of its +/// own, so it reports its input's layout. +pub(crate) fn merge_over(inner: NativeNode) -> NativeNode { + let output = inner.output.clone(); + NativeNode { + expr: NativeExpr::Merge { + input: Box::new(inner), + }, + output, + } +} + +pub(crate) fn add() -> BinaryMatching { BinaryMatching { op: BinaryOp::Add, return_bool: false, @@ -245,6 +343,125 @@ fn add() -> BinaryMatching { } } +/// The same modifiers with another operator, which is what decides whether a scalar broadcast drops +/// the label set it read: `broadcast_drops_labels` reads the operator and whether it returns a bool. +fn matching(op: BinaryOp, return_bool: bool) -> BinaryMatching { + BinaryMatching { + op, + return_bool, + ..add() + } +} + +/// `on(host)` one-to-one, the match a caller writes when it means to pair series by a label set of +/// its own rather than by the canonical keys a placement groups by. +fn on_host() -> BinaryMatching { + BinaryMatching { + labels: MatchingLabels::On(vec!["host".into()]), + ..add() + } +} + +/// A `sum by (job)` folded into `inner` within this execution, which is an aggregate whose output is +/// a query value rather than state. +pub(crate) fn complete_aggregate(inner: NativeNode) -> NativeNode { + let out = inner + .output + .grid() + .expect("an aggregate needs a grid") + .clone(); + NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(inner), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Grouping::By(Arc::new(["job".into()])), + stage: AggregateStage::Complete, + }, + }, + output: evaluated(Arc::new([]), out), + } +} + +/// A `sort` over `inner`, which is a vector operation: it decides the whole vector at a point. +pub(crate) fn sorted(inner: NativeNode) -> NativeNode { + let out = inner + .output + .grid() + .expect("a vector operation needs a grid") + .clone(); + NativeNode { + expr: NativeExpr::Vector { + input: Box::new(inner), + op: BoundVectorOp::Sort(SortOrder::Asc), + }, + output: evaluated(Arc::new([]), out), + } +} + +/// `left + right`, which matches two vectors by label. +pub(crate) fn sum_of(left: NativeNode, right: NativeNode) -> NativeNode { + let out = left + .output + .grid() + .expect("a binary operation needs a grid") + .clone(); + NativeNode { + expr: NativeExpr::Binary { + left: Box::new(left), + right: Box::new(right), + matching: add(), + }, + output: evaluated(Arc::new([]), out), + } +} + +/// `left right` with the modifiers `matching` states, on the grid both sides are evaluated on. +/// +/// The output is what the kinds of the two sides make it: two constants make a scalar and anything +/// else an evaluated vector, which is what [`NativeNode::validate`] asks of a binary operation. +pub(crate) fn binary_with( + left: NativeNode, + right: NativeNode, + matching: BinaryMatching, +) -> NativeNode { + let output = match (&left.output, &right.output) { + (NativeType::Scalar(grid), NativeType::Scalar(_)) => NativeType::Scalar(Arc::clone(grid)), + _ => evaluated( + Arc::new([]), + left.output + .grid() + .expect("a binary operation needs a grid") + .clone(), + ), + }; + NativeNode { + expr: NativeExpr::Binary { + left: Box::new(left), + right: Box::new(right), + matching, + }, + output, + } +} + +/// A `label_replace` over `inner`, which writes a label of its own choosing: the one map operation +/// that keeps `__name__` and still changes which series share a label set. +pub(crate) fn map_rewriting_labels(inner: NativeNode) -> NativeNode { + let out = inner.output.grid().expect("a map needs a grid").clone(); + let rewrite = LabelRewrite::replace("dst", "$1", "src", "(.*)") + .expect("a label_replace with a valid expression"); + NativeNode { + expr: NativeExpr::Map { + input: Box::new(inner), + op: BoundMap { + ops: Arc::new([MapOp::Label(Arc::new(rewrite))]), + }, + }, + output: evaluated(Arc::new([]), out), + } +} + /// A compiled tree is accepted when every node's contract holds. #[test] fn a_window_over_raw_samples_is_valid() { @@ -340,6 +557,405 @@ fn merge_rejects_raw_and_mismatched_input_shapes() { assert!(fields_error.to_string().contains("field"), "{fields_error}"); } +/// A merge canonicalizes evaluated fragments and names no operator below it, so any tree whose output +/// is an evaluated vector is one it may sit over: a scan's samples, a window's rate, an aggregate's +/// fold, a vector operation's choice and a binary operation's match all hand over the same thing. +/// An input that is not an evaluated vector at all is still refused. +#[test] +fn a_merge_sits_over_any_evaluated_vector() { + let shared = grid(0, 60_000, 4); + let rate = || window_on(input(), None, Arc::clone(&shared)); + + // The prefix the merge was first written for, then the shapes it now also sits over: each of them + // answers evaluated values, which is what the collection reads. + for node in [ + merge_over(input_on(Arc::clone(&shared))), + merge_over(rate()), + merge_over(map_over(rate())), + merge_over(complete_aggregate(rate())), + merge_over(sorted(rate())), + merge_over(sum_of(rate(), rate())), + ] { + assert!(node.validate().is_ok(), "{}", node.validate().unwrap_err()); + assert!(reads_across_series(&node)); + } + + // Raw samples carry their own timestamps instead of positions on a grid, so there is nothing to + // merge by: a scan is the one input a merge refuses however many fields it carries. + for inner in [input(), input_with_fields(1)] { + let error = merge_over(inner).validate().unwrap_err(); + assert!(error.to_string().contains("evaluated vector"), "{error}"); + } + // A scalar is not a vector at all, and a merge reports samples. + let scalar_input = NativeNode { + expr: NativeExpr::Merge { + input: Box::new(scalar_on(1.0, Arc::clone(&shared))), + }, + output: evaluated(Arc::new([]), Arc::clone(&shared)), + }; + let error = scalar_input.validate().unwrap_err(); + assert!(error.to_string().contains("evaluated vector"), "{error}"); +} + +/// What a caller knows about a source it has collected into one series per canonical label set and +/// placed by canonical key: every label set it names is whole in one execution. +fn proven_by_key() -> NativeProperties { + NativeProperties { + owner: CanonicalOwner::ByCanonicalKey, + grouping: CanonicalGrouping::CanonicalComplete, + } +} + +/// The same, in an execution that holds every series there is. +fn proven_in_one_execution() -> NativeProperties { + NativeProperties { + owner: CanonicalOwner::SinglePartition, + ..proven_by_key() + } +} + +/// What a plain raw scan proves about the pieces of a label set: nothing. +/// +/// A scan partitions by storage `read_key` and not by canonical key, so it holds pieces of a metric +/// with nothing grouped - which is the facts the node itself derives for an input. +pub(crate) fn source_pieces() -> NativeProperties { + NativeProperties::source_pieces() +} + +/// The facts a node reports follow what the node does to a label set. +/// +/// This is where the RFC's simplified rule ("a pure numeric map inherits grouping") had to be +/// corrected: none of the three map operations leaves a label set as it is, so a map is one of the +/// nodes that lose grouping rather than pass it on. +#[test] +fn properties_follow_what_each_node_does_to_a_label_set() { + let shared = grid(0, 60_000, 4); + + // What a caller knows about a scan: this execution holds pieces of a metric and nothing has + // grouped those pieces by label set. + let boundary = NativeProperties::source_pieces(); + + // A bare input is the boundary it was bound to, so it proves exactly the entry supplied beside + // it and nothing else. + let bare = input_on(Arc::clone(&shared)); + let scanned = bare.properties(&[boundary]); + assert_eq!( + scanned, + NativeProperties { + owner: CanonicalOwner::Unknown, + grouping: CanonicalGrouping::SourcePiecesOnly, + } + ); + + // A window folds a range of one series' samples, so it hands over the label set it read and each + // series stays one stream: what it proves is what its input proved. + // + // That holds only for the functions that keep the metric name, which is `last_over_time` and + // `first_over_time`; every other one rewrites the labels, and the test below this one is what + // pins that. + let window = |function: RangeFunction| { + window_with( + input_on(Arc::clone(&shared)), + function, + Some(Arc::clone(&shared)), + Arc::clone(&shared), + ) + }; + assert_eq!( + window(RangeFunction::LastOverTime).properties(&[scanned]), + scanned + ); + assert_eq!( + window(RangeFunction::Rate).properties(&[scanned]), + scanned.label_sets_of_its_own() + ); + + // The grouping proof a map could inherit from a complete child is exactly what it loses: a + // series ends under a label set the map built, so no grouping proof survives. + let complete = NativeProperties { + owner: CanonicalOwner::ByCanonicalKey, + grouping: CanonicalGrouping::CanonicalComplete, + }; + // `map_math` ends with `drop_metric_name`, so `abs(x)` and `x` no longer hold one label set: + // this is the case the RFC read as inheriting grouping. + let absolute = map_over(input_on(Arc::clone(&shared))); + let rewritten = absolute.properties(&[complete]); + assert_eq!( + rewritten, + NativeProperties { + owner: CanonicalOwner::Unknown, + grouping: CanonicalGrouping::SourcePiecesOnly, + } + ); + + // A single execution still holds every series it produces, so that ownership is the one a rewrite + // does not invalidate. + let single = NativeProperties { + owner: CanonicalOwner::SinglePartition, + ..complete + }; + assert_eq!( + absolute.properties(&[single]).owner, + CanonicalOwner::SinglePartition + ); + + // The other two variants are no purer: `label_replace` writes a label of its own choosing + // (`__name__` included) and `histogram_*` removes `__name__`, so no map operation preserves a + // label set and none of them can inherit a grouping proof. + assert!(!preserves_canonical_identity(&MapOp::Math(MathOp::Abs))); + assert!(!preserves_canonical_identity(&MapOp::Histogram( + NativeHistogramFunction::Count + ))); + assert!(!preserves_canonical_identity(&MapOp::Label(Arc::new( + LabelRewrite::replace("dst", "$1", "src", "(.*)").expect("a valid expression") + )))); + assert_eq!( + map_rewriting_labels(input_on(Arc::clone(&shared))).properties(&[complete]), + rewritten + ); + + // An aggregate folds a group and a vector operation decides whole series against each other, so + // neither can claim the label sets of the series it read. + let folded = complete_aggregate(input_on(Arc::clone(&shared))); + assert_eq!( + folded.properties(&[complete]).grouping, + CanonicalGrouping::SourcePiecesOnly + ); + // A group's identity is the group key, so an ownership per input key says nothing about it: two + // input label sets placed in different executions can fold into one group. + assert_eq!( + folded.properties(&[complete]).owner, + CanonicalOwner::Unknown + ); + let ordered = sorted(input_on(Arc::clone(&shared))); + assert_eq!( + ordered.properties(&[complete]).grouping, + CanonicalGrouping::SourcePiecesOnly + ); + + // Two vectors are matched by label, which is the operation's own decision about what label set a + // sample ends under, so neither side's grouping is the output's. The two sides are two sources, + // so each reads its own entry of the boundary. + let sum = sum_of( + input_on_at(0, Arc::clone(&shared)), + input_on_at(1, Arc::clone(&shared)), + ); + assert_eq!( + sum.properties(&[complete, complete]).grouping, + CanonicalGrouping::SourcePiecesOnly + ); + // Its output holds series from both sides, so its ownership is only what both agree on - and + // then only if it survives the match, whose output identity is its modifiers and not the keys it + // read. + assert_eq!( + sum.properties(&[complete, complete]).owner, + CanonicalOwner::Unknown + ); + assert_eq!( + sum.properties(&[complete, scanned]).owner, + CanonicalOwner::Unknown + ); + // The per-source indexing is visible here: a boundary that states facts for source 0 only leaves + // source 1 unproved. + assert_eq!(sum.properties(&[complete]).owner, CanonicalOwner::Unknown); + assert_eq!( + sum.properties(&[complete]).grouping, + CanonicalGrouping::SourcePiecesOnly + ); + + // A merge is the node that establishes that fact, and the placement of what it read is the + // placement of what it wrote. + let merged = merge_over(input_on(Arc::clone(&shared))); + assert_eq!( + merged.properties(&[complete]), + NativeProperties { + owner: CanonicalOwner::ByCanonicalKey, + grouping: CanonicalGrouping::CanonicalComplete, + } + ); +} + +/// A scalar broadcast reaches each series of its vector side as it is, so the facts it derives are +/// the vector side's and nothing else: a constant holds no label set, and which side it is written on +/// cannot change the answer. +/// +/// The old derivation united the two sides before looking at them, which answered wrong in both +/// directions: with the vector on the left it took the ownership only the two sides agree on, and a +/// vector side placed by canonical key came out `Unknown` (the constant answers `SinglePartition`); +/// with the vector on the right it kept the left side's grouping, so the constant's +/// `CanonicalComplete` was handed to a vector side that is still only source pieces. +/// The two orders are one query, `x > 0` and `0 < x`, so they are asserted against the same answer. +#[test] +fn a_broadcast_derives_its_vector_sides_properties_whichever_side_the_vector_is_on() { + let shared = grid(0, 60_000, 4); + // `0` broadcast over the vector, which is a filtering comparison and keeps the label set it read. + let constant = || scalar_on(0.0, Arc::clone(&shared)); + let vector = || input_on(Arc::clone(&shared)); + + for boundary in [proven_by_key(), source_pieces()] { + // What the vector side proves on its own, which is what the broadcast has to prove: nothing + // about a label set is added, dropped or rewritten. + let expected = vector().properties(&[boundary]); + // `x > 0` and `0 < x`. + let vector_left = binary_with(vector(), constant(), matching(BinaryOp::Gt, false)); + let vector_right = binary_with(constant(), vector(), matching(BinaryOp::Lt, false)); + assert_eq!(vector_left.properties(&[boundary]), expected); + assert_eq!(vector_right.properties(&[boundary]), expected); + assert_eq!( + vector_left.properties(&[boundary]), + vector_right.properties(&[boundary]) + ); + } + + // The facts the old formula lost, spelled out: a vector side placed by canonical key keeps that + // ownership (which is what a merge above the broadcast needs), and a vector side of source pieces + // stays ungrouped (which is what a merge above it has to collect). + let by_key = binary_with(vector(), constant(), matching(BinaryOp::Gt, false)); + assert_eq!( + by_key.properties(&[proven_by_key()]).owner, + CanonicalOwner::ByCanonicalKey + ); + assert_eq!(by_key.properties(&[proven_by_key()]), proven_by_key()); + let pieces = binary_with(constant(), vector(), matching(BinaryOp::Lt, false)); + assert_eq!( + pieces.properties(&[source_pieces()]).grouping, + CanonicalGrouping::SourcePiecesOnly + ); +} + +/// Arithmetic and a `bool` comparison answer a series under the metric name dropped, so the broadcast +/// derives its vector side's facts rewritten — and, as for a filtering comparison, only its vector +/// side's: the constant's `no_label_sets()` facts never reach the output. +#[test] +fn arithmetic_and_a_bool_comparison_rewrite_the_vector_sides_labels_only() { + let shared = grid(0, 60_000, 4); + let constant = || scalar_on(2.0, Arc::clone(&shared)); + let vector = || input_on(Arc::clone(&shared)); + + for boundary in [proven_by_key(), source_pieces()] { + let expected = vector().properties(&[boundary]).label_sets_of_its_own(); + // `x * 2` and `2 * x`, which drop `__name__` in `BroadcastRuntime`; `x > bool 0` and + // `0 < bool x`, the comparison that keeps a value instead of filtering. + for (vector_left_op, constant_left_op) in [ + ( + matching(BinaryOp::Mul, false), + matching(BinaryOp::Mul, false), + ), + (matching(BinaryOp::Gt, true), matching(BinaryOp::Lt, true)), + ] { + let vector_left = binary_with(vector(), constant(), vector_left_op); + let constant_left = binary_with(constant(), vector(), constant_left_op); + let derived = vector_left.properties(&[boundary]); + assert_eq!(derived, expected); + assert_eq!(constant_left.properties(&[boundary]), expected); + // The rewrite is a real downgrade and not a carried-over proof. + assert_eq!(derived.grouping, CanonicalGrouping::SourcePiecesOnly); + assert_eq!(derived.owner, CanonicalOwner::Unknown); + } + } +} + +/// Two constants answer one value for every series there is, so neither holds a label set and the +/// operation cannot claim one: what it derives is `no_label_sets()`, whatever the boundary says. +#[test] +fn two_constants_hold_no_label_set() { + let shared = grid(0, 60_000, 4); + let node = binary_with( + scalar_on(1.0, Arc::clone(&shared)), + scalar_on(2.0, Arc::clone(&shared)), + add(), + ); + assert!(node.validate().is_ok(), "{}", node.validate().unwrap_err()); + assert_eq!(node.properties(&[]), no_label_sets()); + assert_eq!(node.properties(&[proven_by_key()]), no_label_sets()); +} + +/// A vector/vector match answers series of both sides, so its ownership is only what the two sides +/// agree on, and the match re-derives it for the label sets its modifiers name: `label_sets_of_its_own` keeps +/// a one-execution ownership and downgrades one per canonical key, because the keys it read are not +/// the label sets it writes. +#[test] +fn a_two_vector_match_still_rederives_its_ownership() { + let shared = grid(0, 60_000, 4); + // `rate(a) + rate(b)`, whose two sides are two sources with an entry of their own. + let matched = || { + sum_of( + input_on_at(0, Arc::clone(&shared)), + input_on_at(1, Arc::clone(&shared)), + ) + }; + // What a match proves whatever it read: the grouping is the modifiers' decision. + let whole_vector = |owner: CanonicalOwner| NativeProperties { + owner, + grouping: CanonicalGrouping::SourcePiecesOnly, + }; + + // Both sides placed by canonical key agree on that ownership, and the match still downgrades it. + assert_eq!( + matched().properties(&[proven_by_key(), proven_by_key()]), + whole_vector(CanonicalOwner::Unknown) + ); + // Sides that disagree agree on nothing. + assert_eq!( + matched().properties(&[proven_by_key(), source_pieces()]), + whole_vector(CanonicalOwner::Unknown) + ); + // One execution holds every series there is, so that is the one ownership the match keeps. + assert_eq!( + matched().properties(&[proven_in_one_execution(), proven_in_one_execution()]), + whole_vector(CanonicalOwner::SinglePartition) + ); +} + +/// A timestamp and a timestamp-mode instant replace the identity with the sample's time, so neither +/// can inherit the proof a value selection may. +/// +/// `timestamp(x)` rebuilds the labels through `map::drop_metric_name`, which removes `__name__` +/// together with the type and unit labels, and the selection that reports a time instead of a value +/// does the same in `instant_eval::timestamp_of_selection`. Two series that differed only by metric +/// name therefore answer under one label set, and nothing has assembled them. +#[test] +fn the_two_timestamp_shapes_downgrade_and_a_value_selection_inherits() { + let shared = grid(0, 60_000, 4); + let boundary = [proven_in_one_execution()]; + + // `timestamp(rate(x[5m]))` and `timestamp(x)` both rewrite the labels. + let stamped = timestamp_of(input_on(Arc::clone(&shared))); + assert_eq!( + stamped.properties(&boundary), + boundary[0].label_sets_of_its_own() + ); + assert_eq!( + stamped.properties(&boundary).grouping, + CanonicalGrouping::SourcePiecesOnly + ); + + // A one-execution ownership is not invalidated by a rewrite, a per-key one is. + assert_eq!( + stamped.properties(&boundary).owner, + CanonicalOwner::SinglePartition + ); + assert_eq!( + stamped.properties(&[proven_by_key()]).owner, + CanonicalOwner::Unknown + ); + + // A selection that reports the sample's time is the same rewrite, applied to a selected sample. + let selected = instant_over( + raw_input_at(0), + InstantValue::Timestamp, + Arc::clone(&shared), + ); + assert_eq!( + selected.properties(&boundary), + boundary[0].label_sets_of_its_own() + ); + + // A selection that reports the sample's value keeps the label set it read, so it inherits. + let values = instant_over(raw_input_at(0), InstantValue::Sample, Arc::clone(&shared)); + assert_eq!(values.properties(&boundary), boundary[0]); +} + /// A map is point-wise over values, so raw samples are not something it can consume. #[test] fn a_map_cannot_consume_raw_samples() { @@ -913,6 +1529,509 @@ fn a_constant_operand_reads_one_series_at_a_time() { ))); } +/// A tree needs one execution over every scan partition exactly when one of its operators answers a +/// value for the whole vector; every other tree answers each series on its own and keeps running one +/// execution per partition. +#[test] +fn only_a_whole_vector_tree_needs_one_execution() { + let shared = grid(0, 60_000, 4); + let rate = || window_on(input(), None, Arc::clone(&shared)); + let vector = |inner: NativeNode, op: BoundVectorOp| NativeNode { + expr: NativeExpr::Vector { + input: Box::new(inner), + op, + }, + output: evaluated(Arc::new([]), Arc::clone(&shared)), + }; + let binary = |left: NativeNode, right: NativeNode| NativeNode { + expr: NativeExpr::Binary { + left: Box::new(left), + right: Box::new(right), + matching: add(), + }, + output: evaluated(Arc::new([]), Arc::clone(&shared)), + }; + let aggregate = |inner: NativeNode, stage: AggregateStage| NativeNode { + expr: NativeExpr::Aggregate { + input: Box::new(inner), + op: BoundAggregate { + kind: AggregateKind::Sum, + group: Grouping::By(Arc::new(["job".into()])), + stage, + }, + }, + output: if stage == AggregateStage::Partial { + partial_aggregate(rate()).output + } else { + evaluated(Arc::new([]), Arc::clone(&shared)) + }, + }; + + // One series' rows answer one series: the input, `rate(x[5m])` and `abs(rate(x[5m]))`. + for node in [input(), rate(), map_over(rate())] { + assert!( + !needs_single_execution(&node), + "a per-series tree keeps one execution per partition: {node:?}" + ); + } + // A broadcast reaches each series of the vector side, and a state aggregate is contractually + // one execution's contribution. + assert!(!needs_single_execution(&binary( + scalar_on(1.0, Arc::clone(&shared)), + rate() + ))); + assert!(!needs_single_execution(&aggregate( + rate(), + AggregateStage::Partial + ))); + // `rate(a) + rate(b)` is a match, not a broadcast, so it is *not* per-series: it pairs the two + // sides' series by label, and with no boundary facts there is no proof that one execution holds + // both. This answered `false` while a match was decided by its sides alone, which is the gap the + // match's own co-location proof closes. + assert!(needs_single_execution(&binary(rate(), rate()))); + + // `topk(1, rate(x[5m]))`, `sort(rate(x[5m]))` and `limitk(1, rate(x[5m]))` read every series + // against the others, as does a complete aggregate. + let group = Grouping::By(Arc::new(["job".into()])); + for op in [ + BoundVectorOp::TopK { + k: 1.0, + top: true, + group: group.clone(), + }, + BoundVectorOp::LimitK { + k: 1.0, + group: group.clone(), + }, + BoundVectorOp::Sort(SortOrder::Asc), + ] { + assert!( + needs_single_execution(&vector(rate(), op)), + "a global vector operation needs every series at once" + ); + } + assert!(needs_single_execution(&aggregate( + rate(), + AggregateStage::Complete + ))); + // Depth does not hide it: `sum(rate(x[5m])) + 100` still folds a group, and so does a per-series + // left side over a whole-vector right side. + assert!(needs_single_execution(&binary( + aggregate(rate(), AggregateStage::Complete), + scalar_on(100.0, Arc::clone(&shared)) + ))); + assert!(needs_single_execution(&binary( + rate(), + vector(rate(), BoundVectorOp::Sort(SortOrder::Asc)) + ))); +} + +/// A whole-vector operator reads the input vector itself, so what the boundary says about where the +/// sources sit cannot make one execution unnecessary. +#[test] +fn a_whole_vector_operator_needs_one_execution_whatever_the_boundary() { + let shared = grid(0, 60_000, 4); + // `sort(rate(x[5m]))` orders every series against the others, and `sum(rate(x[5m]))` folds every + // contribution to a group. + let vector = sorted(input_on(Arc::clone(&shared))); + let aggregate = complete_aggregate(input_on(Arc::clone(&shared))); + + for boundary in [ + &[][..], + &[source_pieces()][..], + &[proven_by_key()][..], + &[proven_in_one_execution()][..], + ] { + assert!( + needs_single_execution_in(&vector, boundary), + "a vector operation reads the whole vector: {boundary:?}" + ); + assert!( + needs_single_execution_in(&aggregate, boundary), + "a complete aggregate folds every contribution to its group: {boundary:?}" + ); + // The wrapper that states no facts agrees, because it proves nothing. + assert!(needs_single_execution(&vector)); + assert!(needs_single_execution(&aggregate)); + } +} + +/// A merge needs every piece of one canonical label set and not every label set in one execution, so +/// the boundary's ownership decides where it is placed - and never how many executions the tree +/// takes, which is its input's answer. +/// +/// The fix that split the two questions is what this test now asserts together: a merge over a +/// boundary that proves nothing is not placeable in one partition, and it still does not demand a +/// single execution to make itself placeable. It used to answer the second question with the first, +/// which is what collapsed the caller's partitions. +#[test] +fn a_merge_is_placed_by_the_boundary_and_needs_what_its_input_needs() { + let shared = grid(0, 60_000, 4); + let merge = merge_over(input_on(Arc::clone(&shared))); + + // A raw scan partitions by storage `read_key`, which proves nothing about canonical keys: the + // pieces of one label set can sit in different partitions, and a merge in each of them would + // hand what reads it a partial series as a canonical one. So it is not placeable there - and it + // does not answer that by asking for one execution either. + assert!(!merges_are_placeable_in(&merge, &[source_pieces()], false)); + assert!(!needs_single_execution_in(&merge, &[source_pieces()])); + // No facts at all prove even less: the same answer, and again not one that costs an execution. + assert!(!merges_are_placeable_in(&merge, &[], false)); + assert!(!needs_single_execution_in(&merge, &[])); + // Placed by canonical key, every piece of a label set is in the execution that owns it, so a + // merge per owner partition is the whole answer. + assert!(merges_are_placeable_in(&merge, &[proven_by_key()], false)); + // One execution holds every series there is. + assert!(merges_are_placeable_in( + &merge, + &[proven_in_one_execution()], + false + )); + // Whatever the boundary proves, the merge's own need is its input's, which a scan does not + // raise: one execution is never what a merge asks for. + for boundary in [ + &[][..], + &[source_pieces()][..], + &[proven_by_key()][..], + &[proven_in_one_execution()][..], + ] { + assert!( + !needs_single_execution_in(&merge, boundary), + "a merge demanded a single execution: {boundary:?}" + ); + } + + // What sits above a merge is not proved co-located by what the merge reads: `rate` drops the + // metric name and can put two sources' label sets in one, so the merge over it cannot read each + // label set whole in an owner partition - and still does not demand one execution. + let windowed = merge_over(window_with( + input_on(Arc::clone(&shared)), + RangeFunction::Rate, + Some(Arc::clone(&shared)), + Arc::clone(&shared), + )); + assert!(!merges_are_placeable_in( + &windowed, + &[proven_by_key()], + false + )); + assert!(!needs_single_execution_in(&windowed, &[proven_by_key()])); + // In an execution that reads every input partition, every piece is present and the same merge is + // placeable: the label sets `rate` invented are still whole there. + assert!(merges_are_placeable_in(&windowed, &[proven_by_key()], true)); + + // A window that keeps the metric name hands the same label sets on, so the proof survives it and + // the merge stays within the owner partitions. + let keeping = merge_over(window_with( + input_on(Arc::clone(&shared)), + RangeFunction::LastOverTime, + Some(Arc::clone(&shared)), + Arc::clone(&shared), + )); + assert!(merges_are_placeable_in(&keeping, &[proven_by_key()], false)); + assert!(!needs_single_execution_in(&keeping, &[proven_by_key()])); + + // A complete aggregate below it needs one execution of its own, whatever the merge needs - which + // is the one case where a tree holding a merge does need one, and it is the aggregate's. + let folded = merge_over(complete_aggregate(input_on(Arc::clone(&shared)))); + assert!(needs_single_execution_in( + &folded, + &[proven_in_one_execution()] + )); +} + +/// The reported shape: one source read twice, a canonical merge over each occurrence, and a match +/// over the two merges. +/// +/// `Merge(Input(0))` on both sides is a tree the native API accepts - `collect_source_schemas` takes +/// the same `source_index` in several leaves - and a per-canonical-key placement proves each +/// *canonical* label set whole, which is what each merge needs and is not what the match needs. With +/// `{host="h", zone="a"}` and `{host="h", zone="b"}` under two canonical owners, each owner holds one +/// series per side, matches them locally, and the whole-vector `on(host)` duplicate-series check +/// (`vector_match`) never runs over the real group: a silently wrong answer where an error is owed. +/// +/// Before the fix this answered `false`: both sides were `ByCanonicalKey`, which the match arm took +/// as a proof of its own co-location because the arm asked only what each side needs on its own. +#[test] +fn a_match_over_two_canonical_key_merges_needs_one_execution() { + let shared = grid(0, 60_000, 4); + let matched = || { + binary_with( + merge_over(input_on(Arc::clone(&shared))), + merge_over(input_on(Arc::clone(&shared))), + on_host(), + ) + }; + + assert!( + needs_single_execution_in(&matched(), &[proven_by_key()]), + "an `on(host)` match pairs by `host`, and a canonical key is not that key" + ); + + // Each side alone is the case the merge already settles: one merge over a per-key placement stays + // in its owner partition, so the `true` above is the match's requirement and not the merges'. + let side = || merge_over(input_on(Arc::clone(&shared))); + assert!(!needs_single_execution_in(&side(), &[proven_by_key()])); +} + +/// The same match in an execution that holds every series there is: both sides are already here, so +/// the match needs nothing beyond it and the tree keeps running as the one execution it is. +#[test] +fn a_match_over_two_merges_in_one_execution_stays_parallel() { + let shared = grid(0, 60_000, 4); + let matched = || { + binary_with( + merge_over(input_on(Arc::clone(&shared))), + merge_over(input_on(Arc::clone(&shared))), + on_host(), + ) + }; + + assert!( + !needs_single_execution_in(&matched(), &[proven_in_one_execution()]), + "one execution already pairs every series of the `on(host)` group" + ); +} + +/// A set operation matches two vectors the same way a binary one does, so the boundary answers the +/// same way for it: `ByCanonicalKey` is not a matching-key proof, and one execution needs no proof. +#[test] +fn a_set_over_two_canonical_key_merges_needs_one_execution() { + let shared = grid(0, 60_000, 4); + let set = || NativeNode { + expr: NativeExpr::Set { + left: Box::new(merge_over(input_on(Arc::clone(&shared)))), + right: Box::new(merge_over(input_on(Arc::clone(&shared)))), + op: BoundSetOp { + op: SetOp::Or, + labels: MatchingLabels::On(vec!["host".into()]), + }, + }, + output: evaluated(Arc::new([]), Arc::clone(&shared)), + }; + + assert!( + needs_single_execution_in(&set(), &[proven_by_key()]), + "`or on(host)` pairs by `host`, and a canonical key is not that key" + ); + assert!( + !needs_single_execution_in(&set(), &[proven_in_one_execution()]), + "one execution already pairs every series of the `on(host)` group" + ); +} + +/// A broadcast is not a match: it pairs a vector with one value, so no label set is paired on the +/// constant's side and nothing about matching keys has to be proved for it. The fix for the match +/// must therefore not collapse `x > 0` or `x * 2` into one execution. +#[test] +fn a_scalar_broadcast_over_a_canonical_key_vector_stays_parallel() { + let shared = grid(0, 60_000, 4); + let by_key = [proven_by_key()]; + let vector = || input_on(Arc::clone(&shared)); + let constant = || scalar_on(0.0, Arc::clone(&shared)); + + // `x > 0`, `x * 2` and the same two written with the constant on the left, all over a vector side + // placed by canonical key: each is one value against each series, not a pair of series. + for node in [ + binary_with(vector(), constant(), matching(BinaryOp::Gt, false)), + binary_with(vector(), constant(), matching(BinaryOp::Mul, false)), + binary_with(constant(), vector(), matching(BinaryOp::Lt, false)), + binary_with(constant(), vector(), matching(BinaryOp::Mul, false)), + ] { + assert!( + !needs_single_execution_in(&node, &by_key), + "a broadcast reaches each series of its vector side on its own:\n{node:?}" + ); + } +} + +/// A merge is grouped by the canonical label set, so a per-key boundary is exactly the proof it needs +/// and it must keep staying within the owner partitions the fix above does not touch. +#[test] +fn a_merge_over_canonical_keys_still_keeps_the_owner_partitions() { + let shared = grid(0, 60_000, 4); + let merge = merge_over(input_on(Arc::clone(&shared))); + + assert!( + !needs_single_execution_in(&merge, &[proven_by_key()]), + "a canonical key is what a merge groups by, so it is a proof of a merge's input" + ); + assert!( + merges_are_placeable_in(&merge, &[proven_by_key()], false), + "the proof a canonical key gives is the one a merge is placed by" + ); + // The contrast that keeps the assertion above from being vacuous: the same merge over a scan that + // proves nothing about canonical keys is not placeable in one partition. It does not answer that + // by needing a single execution - a merge's own need is its input's, which a scan does not raise - + // so the unproved shape is declined rather than collapsed. + assert!(!needs_single_execution_in(&merge, &[source_pieces()])); + assert!(!merges_are_placeable_in(&merge, &[source_pieces()], false)); +} + +/// A per-series wrapper composes with the match's requirement by recursing into it: `rate` over the +/// match needs what the match needs and adds no requirement of its own, so the answer is the match's. +#[test] +fn a_window_over_a_match_hands_the_matches_requirement_up_unchanged() { + let shared = grid(0, 60_000, 4); + let matched = || { + binary_with( + merge_over(input_on(Arc::clone(&shared))), + merge_over(input_on(Arc::clone(&shared))), + on_host(), + ) + }; + // `rate()`, with a name-dropping function, so the window itself changes the label sets the + // match pairs and cannot add a co-location proof of its own either way. + let windowed = || { + window_with( + matched(), + RangeFunction::Rate, + Some(Arc::clone(&shared)), + Arc::clone(&shared), + ) + }; + + // One execution holds both sides, so the match is whole there and the window over it needs + // nothing more. + assert!(!needs_single_execution_in( + &windowed(), + &[proven_in_one_execution()] + )); + // Placed by canonical key, the window cannot make the match whole: what it hands on is the + // match's requirement, one execution. + assert!(needs_single_execution_in(&windowed(), &[proven_by_key()])); +} + +/// A tree whose only whole-vector-looking node is a merge is placed per partition once the boundary +/// proves the pieces of a label set arrive together, which is the case that must stop collapsing the +/// owner partitions a canonical repartition just created. +/// +/// The answers below are the split the fix made: the tree never needs one execution, because neither +/// the window nor the merge raises that requirement, and whether it can run per partition is what the +/// boundary's facts decide. The last case is the shape that used to be collapsed - unproved pieces +/// under a merge - and it is now declined instead: `merges_are_placeable_in` says the one partition +/// the node would run in cannot answer it. +#[test] +fn a_merge_alone_does_not_collapse_the_owner_partitions() { + let shared = grid(0, 60_000, 4); + // The shape a repartition hands on: a canonical merge under a per-series window, and no + // whole-vector operator anywhere. + let tree = window_with( + merge_over(input_on_at(1, Arc::clone(&shared))), + RangeFunction::LastOverTime, + Some(Arc::clone(&shared)), + Arc::clone(&shared), + ); + + // Placed by canonical key, the pieces of the label set source 1 reads are already together in the + // partition that owns them. + for boundary in [ + [proven_by_key(), proven_by_key()], + [source_pieces(), proven_by_key()], + [proven_in_one_execution(), source_pieces()], + ] { + assert!( + !needs_single_execution_in(&tree, &boundary), + "a merge under a per-series window demanded one execution: {boundary:?}" + ); + } + assert!( + merges_are_placeable_in(&tree, &[proven_by_key(), proven_by_key()], false), + "the merge reads source 1, whose pieces the boundary proves co-located" + ); + assert!(merges_are_placeable_in( + &tree, + &[source_pieces(), proven_by_key()], + false + )); + // The entries are read per source: source 1 is the one the merge reads, so leaving it unproved + // is what makes the tree unplaceable per partition, however canonical source 0 is. + assert!(!merges_are_placeable_in( + &tree, + &[proven_in_one_execution(), source_pieces()], + false + )); + // The wrapper that states no facts proves nothing about source 1 either, so the answer is the + // same - and it is still not one execution. + assert!(!merges_are_placeable_in(&tree, &[], false)); + assert!(!needs_single_execution(&tree)); +} + +/// The ownership a broadcast derives is what decides where a merge above it is placed, so deriving +/// an arithmetic constant's facts into the vector's had a placement consequence and not only a fact +/// wrong on paper: `x > 0` keeps the label set it read, so a vector side placed by canonical key +/// still proves that the pieces of a label set arrive together and a merge over the comparison stays +/// within the owner partitions a canonical repartition just created. +/// +/// The other comparisons below are what keep the assertions from being vacuous: arithmetic and a +/// `bool` comparison drop the metric name, so a merge over the same vector side cannot read each +/// label set whole there, and neither can a merge over a tree whose facts are the ones the old +/// formula derived - the vector side united with the constant's `no_label_sets()`, whose ownership is +/// `Unknown`. All of them are placement answers: the merge's own need is its input's throughout, so +/// none of these shapes is turned into a single execution by the merge. +#[test] +fn a_merge_over_a_filtering_comparison_keeps_the_owner_partitions() { + let shared = grid(0, 60_000, 4); + let by_key = [proven_by_key()]; + let vector = || input_on(Arc::clone(&shared)); + let constant = || scalar_on(0.0, Arc::clone(&shared)); + // `x > 0`, which keeps the label set it read, and `0 < x`, the same query written the other way. + let filtering = |vector_left: bool| { + if vector_left { + binary_with(vector(), constant(), matching(BinaryOp::Gt, false)) + } else { + binary_with(constant(), vector(), matching(BinaryOp::Lt, false)) + } + }; + + for node in [filtering(true), filtering(false)] { + let merged = merge_over(node); + assert!( + merges_are_placeable_in(&merged, &by_key, false), + "a broadcast that keeps the label set leaves the merge's pieces co-located" + ); + assert!( + !needs_single_execution_in(&merged, &by_key), + "a merge over a broadcast demanded one execution of its own" + ); + } + + // The contrast: a label set the broadcast rewrote is not the one the boundary's keys name, so + // the merge above it cannot read each label set whole - and it still does not ask for one + // execution to get them. + for node in [ + binary_with(vector(), constant(), matching(BinaryOp::Mul, false)), + binary_with(constant(), vector(), matching(BinaryOp::Mul, false)), + binary_with(vector(), constant(), matching(BinaryOp::Gt, true)), + binary_with(constant(), vector(), matching(BinaryOp::Lt, true)), + ] { + let merged = merge_over(node); + assert!( + !merges_are_placeable_in(&merged, &by_key, false), + "a broadcast that drops the metric name leaves the merge's pieces unproved" + ); + assert!(!needs_single_execution_in(&merged, &by_key)); + } + + // The old answer, reproduced through the facts it derived: a vector side placed by canonical key + // united with the constant's facts owns nothing it can name, so a merge over a tree whose vector + // side proves that is not placeable in one owner partition. That is the answer the fix removes + // from the co-located case above. + assert_eq!( + proven_by_key().united(no_label_sets()).owner, + CanonicalOwner::Unknown + ); + assert!(!merges_are_placeable_in( + &merge_over(filtering(true)), + &[proven_by_key().united(no_label_sets())], + false + )); + assert!(!needs_single_execution_in( + &merge_over(filtering(true)), + &[proven_by_key().united(no_label_sets())] + )); +} + /// A binary operation is point-wise on a grid, so a side of raw samples has no positions to line /// up with the other side. #[test] @@ -1478,11 +2597,6 @@ fn info_reads_the_sample_times_of_one_field() { } } -/// What a raw scan proves about the pieces of a label set: nothing. -fn source_pieces() -> NativeProperties { - NativeProperties::source_pieces() -} - /// What a child that routes its chunks by canonical label set proves: this execution holds every /// piece of the label sets it names, and no other output holds a fragment of one of them. fn routed_by_canonical_key() -> NativeProperties { @@ -1492,17 +2606,6 @@ fn routed_by_canonical_key() -> NativeProperties { } } -/// A merge over `inner`, laid out as `inner` is: a merge writes no field and no grid of its own. -fn merge_over(inner: NativeNode) -> NativeNode { - let output = inner.output.clone(); - NativeNode { - expr: NativeExpr::Merge { - input: Box::new(inner), - }, - output, - } -} - /// A `topk` over `inner`, which reads the whole vector at each grid point. fn topk_over(inner: NativeNode) -> NativeNode { let output = inner.output.clone();