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 <discord9@163.com>
This commit is contained in:
discord9
2026-10-28 19:44:37 +08:00
parent e6113268e4
commit 590044bc66
4 changed files with 3322 additions and 236 deletions
@@ -112,6 +112,17 @@ fn map_over(inner: NativeNode, ops: Vec<MathOp>) -> 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(
File diff suppressed because it is too large Load Diff
+104 -188
View File
@@ -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<EvaluatedChunk> {
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<EvaluatedChunk>); 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"
);
}
File diff suppressed because it is too large Load Diff