fix(promql): make the bound tree's type contracts match what each stage consumes

Four review findings on the bound tree, all about checks that passed the wrong
things.

An aggregate's stage decided its output but not its input. Every stage first
required its input to be evaluated, which aggregate state is not, so
`Final(Partial(...))` was rejected and `Final(Window(...))` was accepted. Each
stage now states its pair: `Complete` takes a vector and produces one on the
same grid, `Partial` takes a vector and produces state on that grid with the
bound grouping, `Final` takes state with the bound grouping and produces a
vector on the state's grid.

Window and instant selections accepted aggregate state. The cause was asking
`is_evaluated()`, which is false both for raw samples and for state, since
state has no grid: `Instant(Partial(...))` and a window bound to
`input_grid: None` over `Partial(...)` both passed and would have read state as
raw samples. Both now match on `NativeType::Samples` first and only then on the
grid, so state is rejected by what it is rather than by lacking a grid.

Scalars were modelled as a grid-less evaluated sample, and `BoundScalar`'s doc
claimed a value varying per grid point is not a scalar. That is wrong for
PromQL: `time()` and `scalar(v)` produce a scalar per evaluation time. A scalar
is now its own `NativeType::Scalar(grid)`, so a binary operation can tell a
broadcast from label matching -- `sum by(job)(rate(x[5m])) + time()` broadcasts
rather than matching on the empty label set -- and `Map`, `Aggregate`, `Instant`
and `Window` reject it by type. The `time()` kernel itself is not in scope.

An input could bind only samples, so an exchange boundary could not bind the
state a `Final` aggregate consumes. `BoundInput` holds a `NativeType`, and input
nodes check that their output is the same binding rather than the same schema.

A peak is the one figure the collector must not add up: it groups metrics by
name, clears the partition and sums gauges, so partition peaks of 1024 and 2048
reported 3072, which is neither peak. `PEAK_RESERVED_BYTES` now carries the
partition in its name (`native.p0.root.peak_reserved_bytes`), while counts and
the other gauges still sum across partitions, where a sum is meaningful. The
test that claimed the peak kept its partition only checked a name prefix; it now
registers two partitions, runs the real `aggregate_by_name`, and asserts both
peaks survive with their own values.

The walkthrough's `+1` test was wrong twice over: it took a `Final` aggregate
directly over a `Window` -- the case the first finding now rejects -- and
applied `MathOp::Abs`, which is not `+1`. It now builds a real binary `+` with a
scalar operand.

Signed-off-by: discord9 <discord9@users.noreply.github.com>
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
discord9
2026-10-20 01:01:00 +08:00
parent 4b78eb61f5
commit 9b815e9dea
3 changed files with 568 additions and 116 deletions
+55 -11
View File
@@ -73,6 +73,14 @@ impl NodePath {
pub fn metric_name(&self, metric: &str) -> String {
format!("{NATIVE_PREFIX}.{}.{}", self.0, metric)
}
/// The full metric name for `metric` at this position in `partition`.
///
/// A figure that must not be merged across partitions needs the partition in its name: the
/// collector aggregates by name first, and a sum of peaks is not a peak.
pub fn partitioned_metric_name(&self, metric: &str, partition: usize) -> String {
format!("{NATIVE_PREFIX}.p{partition}.{}.{metric}", self.0)
}
}
impl std::fmt::Display for NodePath {
@@ -189,8 +197,9 @@ impl Default for NodeMetrics {
impl NodeMetrics {
/// Registers this node's metrics under `path` in `set`.
///
/// `partition` is part of the registration, so two partitions of one plan report separately
/// and a peak never gets summed across them.
/// `partition` is part of the registration, so two partitions of one plan report separately.
/// It is also part of the peak's name, because a peak is the one figure a collector must not
/// add up across partitions.
pub fn register(&self, path: &NodePath, set: &ExecutionPlanMetricsSet, partition: usize) {
fn count(set: &ExecutionPlanMetricsSet, partition: usize, name: String, count: &Count) {
MetricBuilder::new(set)
@@ -251,10 +260,14 @@ impl NodeMetrics {
path.metric_name(NodeMetric::CURRENT_RESERVED_BYTES),
&self.current_reserved_bytes,
);
// The peak is the one figure named per partition. The collector groups by name and sums
// gauges, and a sum of two peaks is neither peak: partitions peak at different moments.
// Summing the other gauges and counts stays meaningful — the memory held now, the groups
// tracked and the samples seen all add up across partitions.
gauge(
set,
partition,
path.metric_name(NodeMetric::PEAK_RESERVED_BYTES),
path.partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, partition),
&self.peak_reserved_bytes,
);
gauge(
@@ -343,6 +356,7 @@ pub fn register_tree(
mod tests {
use std::sync::Arc;
use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricValue};
use datatypes::series::samples::SeriesSchema;
use datatypes::series::time::{EvalGrid, GridSpec};
@@ -365,13 +379,13 @@ mod tests {
}
fn input() -> NativeNode {
let schema = schema();
let output = NativeType::Samples(schema());
NativeNode {
expr: NativeExpr::Input(BoundInput {
schema: Arc::clone(&schema),
output: output.clone(),
ordering: datatypes::series::SeriesOrdering::KeyThenTime,
}),
output: NativeType::Samples(schema),
output,
}
}
@@ -470,14 +484,44 @@ mod tests {
path.metric_name(NodeMetric::SELF_COMPUTE_TIME_NS),
"native.root.left.input.self_compute_time_ns"
);
// The peak keeps the partition, because two partitions peak at different moments.
assert!(
NodePath::root()
.metric_name(NodeMetric::PEAK_RESERVED_BYTES)
.starts_with("native.root.")
assert_eq!(
path.partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, 1),
"native.p1.root.left.input.peak_reserved_bytes"
);
}
/// The peak keeps the partition in its name, so the collector's aggregation by name cannot add
/// two partitions' peaks: 1024 and 2048 peak at different moments, and 3072 is neither peak.
#[test]
fn a_peak_is_not_merged_across_partitions() {
let root = map(window(input()));
let set = ExecutionPlanMetricsSet::new();
let peaks = [(0, 1024), (1, 2048)];
for (partition, peak) in peaks {
let registered = register_tree(&root, &set, partition);
// The root comes first in traversal order.
registered[0].1.record_reserved_bytes(peak);
}
// The real collector path: `aggregate_by_name` groups by metric name and sums the
// values in each group.
let aggregated = set.clone_inner().aggregate_by_name();
let peak = |partition: usize| -> Option<usize> {
let expected = NodePath::root()
.partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, partition);
aggregated.iter().find_map(|metric| match metric.value() {
MetricValue::Gauge { name, gauge } if name.as_ref() == expected.as_str() => {
Some(gauge.value())
}
_ => None,
})
};
// Two separate names, each holding its own partition's peak: had the name not carried the
// partition, aggregation would have merged them into one gauge summing to 3072.
assert_eq!(peak(0), Some(1024));
assert_eq!(peak(1), Some(2048));
}
/// Registration covers every node, so no node is executed without a way to observe it.
#[test]
fn registration_covers_every_node() {
+202 -66
View File
@@ -37,34 +37,65 @@ use crate::vector_match::BinaryMatching;
/// What one node produces.
///
/// A sample type with an evaluation grid is an evaluated series: one value per grid point. Without
/// a grid it is raw samples carrying their own timestamps. Intermediate aggregate state is a
/// different type altogether, so an operation that cannot consume it is rejected by type rather
/// than by convention.
/// a grid it is raw samples carrying their own timestamps. A scalar is one value per grid point
/// and no labels. Intermediate aggregate state is a different type altogether, so an operation
/// that cannot consume it is rejected by type rather than by convention.
#[derive(Clone, Debug)]
pub enum NativeType {
/// Samples, evaluated when the schema carries a grid and raw otherwise.
Samples(Arc<SeriesSchema>),
/// One value per grid point and no labels, which binary operations broadcast.
///
/// PromQL scalars vary with the evaluation time (`time()`, `scalar(v)`), so this carries the
/// grid it is evaluated on. Its value carrier is a series without labels, but its type is
/// what keeps a broadcast from becoming label matching.
Scalar(Arc<EvalGrid>),
/// Intermediate aggregate state, not a query value.
AggregateState(Arc<AggregateStateSchema>),
}
impl NativeType {
/// The schema of a sample type, or `None` for aggregate state.
/// The schema of a sample type, or `None` for a scalar or aggregate state.
pub fn samples(&self) -> Option<&Arc<SeriesSchema>> {
match self {
Self::Samples(schema) => Some(schema),
Self::AggregateState(_) => None,
Self::Scalar(_) | Self::AggregateState(_) => None,
}
}
/// The grid this type is evaluated on, or `None` when it holds raw samples or state.
///
/// A scalar is evaluated on its grid like a vector, which is what lets a binary operation
/// line it up with a vector point by point; only raw samples and state have no positions.
pub fn grid(&self) -> Option<&Arc<EvalGrid>> {
self.samples().and_then(|schema| schema.eval_grid.as_ref())
match self {
Self::Samples(schema) => schema.eval_grid.as_ref(),
Self::Scalar(grid) => Some(grid),
Self::AggregateState(_) => None,
}
}
/// Whether this type is an evaluated series, which is what operations over values consume.
pub fn is_evaluated(&self) -> bool {
self.grid().is_some()
/// What this type is, for a rejection that has to say what a consumer was handed.
fn describe(&self) -> &'static str {
match self {
Self::Samples(schema) if schema.eval_grid.is_some() => "an evaluated vector",
Self::Samples(_) => "raw samples",
Self::Scalar(_) => "a scalar",
Self::AggregateState(_) => "aggregate state",
}
}
/// Whether `self` binds the same thing as `other`: the same samples or the same state.
///
/// Bindings are compared by allocation identity, because a compiler that meant one schema or
/// one state has no reason to allocate it twice. A scalar is produced by a node and never
/// handed to one by a source, so it never matches.
fn same_binding(&self, other: &NativeType) -> bool {
match (self, other) {
(Self::Samples(mine), Self::Samples(theirs)) => Arc::ptr_eq(mine, theirs),
(Self::AggregateState(mine), Self::AggregateState(theirs)) => Arc::ptr_eq(mine, theirs),
_ => false,
}
}
}
@@ -82,22 +113,23 @@ pub struct AggregateStateSchema {
pub grid: Arc<EvalGrid>,
}
/// A scan bound as a node input.
/// A scan or exchange boundary bound as a node input.
///
/// The binding records what the input already guarantees, so the compiler can check a consumer's
/// requirement instead of assuming it.
#[derive(Clone, Debug)]
pub struct BoundInput {
/// The samples the input produces.
pub schema: Arc<SeriesSchema>,
/// What the input produces: raw samples from a scan, or state from an exchange boundary.
pub output: NativeType,
/// The ordering the input guarantees.
pub ordering: SeriesOrdering,
}
/// A scalar bound for broadcast.
/// A constant scalar bound for broadcast.
///
/// A value that varies per grid point is not a scalar: it is an evaluated input, and it travels
/// as one. Only a constant is broadcast, which is why this carries no grid.
/// A scalar that varies per grid point is the same [`NativeType::Scalar`] as this constant: what
/// keeps a binary operation from label-matching it is its type, not its constness. This binding
/// only holds the constant case.
#[derive(Clone, Debug)]
pub struct BoundScalar {
/// The constant value.
@@ -156,13 +188,6 @@ pub enum AggregateStage {
Final,
}
impl AggregateStage {
/// Whether this stage produces a query value rather than intermediate state.
pub fn produces_value(self) -> bool {
matches!(self, Self::Complete | Self::Final)
}
}
/// An aggregate bound to its kind, grouping and stage.
#[derive(Clone, Debug)]
pub struct BoundAggregate {
@@ -177,9 +202,9 @@ pub struct BoundAggregate {
/// What a node computes. Every variant holds a bound operation, never a name to resolve.
#[derive(Clone, Debug)]
pub enum NativeExpr {
/// A scan.
/// A scan or an exchange boundary.
Input(BoundInput),
/// A scalar.
/// A constant scalar, evaluated on the statement's grid.
Scalar(BoundScalar),
/// An instant selection over its input.
Instant {
@@ -202,6 +227,8 @@ pub enum NativeExpr {
op: BoundAggregate,
},
/// A binary operation between two inputs, with its matching rules.
///
/// Scalar operands are broadcast, so `matching` only applies to vector–vector operations.
Binary {
left: Box<NativeNode>,
right: Box<NativeNode>,
@@ -248,31 +275,52 @@ impl NativeNode {
pub fn validate(&self) -> Result<()> {
match &self.expr {
NativeExpr::Input(input) => {
ensure_samples(&self.output, "an input")?;
let schema = self.output.samples().expect("checked above");
if !Arc::ptr_eq(schema, &input.schema) {
// An input node's output is exactly the binding it was bound to: a scan hands over
// the samples it was created for, and an exchange boundary the state.
if !self.output.same_binding(&input.output) {
return Err(invalid(
"an input node's output schema is not the schema it was bound to",
"an input node's output is not the binding it was bound to",
));
}
}
NativeExpr::Scalar(_) => {
ensure_samples(&self.output, "a scalar")?;
// A scalar's output is the scalar type: one value per grid point and no labels.
if !matches!(self.output, NativeType::Scalar(_)) {
return Err(invalid("a scalar node does not produce a scalar"));
}
}
NativeExpr::Instant { input, op } => {
input.validate()?;
// An instant selection reads raw samples and stamps them onto its own grid.
if input.output.is_evaluated() {
return Err(invalid("an instant selection reads evaluated values"));
// An instant selection reads raw samples and stamps them onto its own grid: an
// evaluated vector is already stamped, and a scalar has no timestamps at all.
match &input.output {
NativeType::Samples(schema) if schema.eval_grid.is_none() => {}
NativeType::Samples(_) => {
return Err(invalid("an instant selection reads evaluated values"));
}
other => {
return Err(invalid(&format!(
"an instant selection consumes raw samples, not {}",
other.describe()
)));
}
}
ensure_samples(&self.output, "an instant selection")?;
ensure_grid(&self.output, &op.output_grid, "an instant selection")?;
}
NativeExpr::Window { input, op } => {
input.validate()?;
// A window reads a range of samples per grid point, so it consumes samples: state
// is not a sample stream and a scalar has no timestamps.
let NativeType::Samples(schema) = &input.output else {
return Err(invalid(&format!(
"a window consumes samples, not {}",
input.output.describe()
)));
};
// The declared input grid has to be the grid the input actually produces, or the
// window would read positions the input never wrote.
match (op.input_grid.as_ref(), input.output.grid()) {
match (op.input_grid.as_ref(), schema.eval_grid.as_ref()) {
(None, None) => {}
(Some(bound), Some(actual)) if Arc::ptr_eq(bound, actual) => {}
_ => {
@@ -286,35 +334,53 @@ impl NativeNode {
}
NativeExpr::Map { input, op } => {
input.validate()?;
// A map is point-wise over values, so it needs a grid to be point-wise over.
if !input.output.is_evaluated() {
return Err(invalid("a map consumes values that are not evaluated"));
}
// A map is point-wise over an evaluated vector: raw samples have no shared
// positions to be point-wise over, and a scalar is not a vector.
let Some(input_grid) = evaluated_grid(&input.output) else {
return Err(invalid(&format!(
"a map consumes an evaluated vector, not {}",
input.output.describe()
)));
};
if op.ops.is_empty() {
return Err(invalid("a map holds no operation"));
}
ensure_samples(&self.output, "a map")?;
let input_grid = input.output.grid().expect("checked above");
ensure_grid(&self.output, input_grid, "a map")?;
}
NativeExpr::Aggregate { input, op } => {
input.validate()?;
if !input.output.is_evaluated() {
return Err(invalid(
"an aggregate consumes values that are not evaluated",
));
}
match (&self.output, op.stage.produces_value()) {
(NativeType::Samples(schema), true) => {
ensure_grid(
&self.output,
input.output.grid().expect("checked above"),
"an aggregate",
)?;
debug_assert!(schema.eval_grid.is_some());
// A stage's contract is a pair of types, not only what it produces: `Partial`
// turns a vector into state and `Final` turns state back into a vector, so state
// never sits where a value is expected and a value never sits where state is.
match op.stage {
AggregateStage::Complete => {
// Every contribution lies within this execution: vector in, vector out,
// both on the input's grid.
let Some(input_grid) = evaluated_grid(&input.output) else {
return Err(invalid(&format!(
"a complete aggregate consumes an evaluated vector, not {}",
input.output.describe()
)));
};
ensure_samples(&self.output, "a complete aggregate")?;
ensure_grid(&self.output, input_grid, "a complete aggregate")?;
}
(NativeType::AggregateState(state), false) => {
let input_grid = input.output.grid().expect("checked above");
AggregateStage::Partial => {
// Only this execution's contributions were seen, so the output is state
// for a later merge: on the input's grid, grouped the same way.
let Some(input_grid) = evaluated_grid(&input.output) else {
return Err(invalid(&format!(
"a partial aggregate consumes an evaluated vector, not {}",
input.output.describe()
)));
};
let NativeType::AggregateState(state) = &self.output else {
return Err(invalid(&format!(
"a partial aggregate produces aggregate state, not {}",
self.output.describe()
)));
};
if !Arc::ptr_eq(&state.grid, input_grid) {
return Err(invalid(
"aggregate state is indexed on a grid the input does not produce",
@@ -324,34 +390,104 @@ impl NativeNode {
return Err(invalid("aggregate state groups differ from the binding"));
}
}
_ => {
return Err(invalid(
"an aggregate's output type does not match its stage",
));
AggregateStage::Final => {
// The state was collected from every contributing execution, so the
// output is the complete value on the grid that state is indexed on.
let NativeType::AggregateState(state) = &input.output else {
return Err(invalid(&format!(
"a final aggregate consumes aggregate state, not {}",
input.output.describe()
)));
};
if state.group != op.group {
return Err(invalid("aggregate state groups differ from the binding"));
}
ensure_samples(&self.output, "a final aggregate")?;
ensure_grid(&self.output, &state.grid, "a final aggregate")?;
}
}
}
NativeExpr::Binary { left, right, .. } => {
left.validate()?;
right.validate()?;
if !left.output.is_evaluated() || !right.output.is_evaluated() {
return Err(invalid(
"a binary operation consumes values that are not evaluated",
));
}
let left_grid = left.output.grid().expect("checked above");
let right_grid = right.output.grid().expect("checked above");
// A binary operation is point-wise, so both sides are evaluated on the statement's
// grid: state has no positions at all, and raw samples carry their own timestamps
// instead of positions on a shared grid.
let Some(left_grid) = left.output.grid() else {
return Err(invalid(&format!(
"a binary operation consumes evaluated values, not {} on its left",
left.output.describe()
)));
};
let Some(right_grid) = right.output.grid() else {
return Err(invalid(&format!(
"a binary operation consumes evaluated values, not {} on its right",
right.output.describe()
)));
};
if !Arc::ptr_eq(left_grid, right_grid) {
return Err(invalid("a binary operation aligns two different grids"));
}
ensure_samples(&self.output, "a binary operation")?;
ensure_grid(&self.output, left_grid, "a binary operation")?;
match (&left.output, &right.output) {
// Two scalars make a scalar: there is nothing to match and nothing to keep.
(NativeType::Scalar(_), NativeType::Scalar(_)) => {
if !matches!(&self.output, NativeType::Scalar(grid) if Arc::ptr_eq(grid, left_grid))
{
return Err(invalid(
"two scalars do not produce a scalar on the statement's grid",
));
}
}
// A scalar side carries no labels and no fields, so the operation is a
// broadcast on the statement's grid and `matching` is not consulted. A scalar
// has no fields of its own, so the broadcast keeps the vector side's fields.
(NativeType::Scalar(_), NativeType::Samples(vector))
| (NativeType::Samples(vector), NativeType::Scalar(_)) => {
let Some(output) = self.output.samples() else {
return Err(invalid(&format!(
"a scalar broadcast produces the vector side's samples, not {}",
self.output.describe()
)));
};
ensure_grid(&self.output, left_grid, "a scalar broadcast")?;
if output.fields.len() != vector.fields.len() {
return Err(invalid(
"a scalar broadcast does not produce the vector side's fields",
));
}
}
// Two vectors are matched by `matching` on the grid they share.
(NativeType::Samples(_), NativeType::Samples(_)) => {
if self.output.samples().is_none() {
return Err(invalid(&format!(
"a binary operation over two vectors produces samples, not {}",
self.output.describe()
)));
}
ensure_grid(&self.output, left_grid, "a binary operation")?;
}
// Both sides carry a grid, so this is state, which the checks above reject.
// Kept as an error rather than a panic so a future type cannot slip through.
_ => {
return Err(invalid(
"a binary operation consumes aggregate state, not a value",
));
}
}
}
}
Ok(())
}
}
/// The grid of an evaluated vector, or `None` when `ty` is raw samples, a scalar or state.
///
/// An operation over values needs both halves: that its input is samples at all, which rules out
/// a scalar, and that those samples are stamped onto a grid, which rules out raw samples.
fn evaluated_grid(ty: &NativeType) -> Option<&Arc<EvalGrid>> {
ty.samples().and_then(|schema| schema.eval_grid.as_ref())
}
fn ensure_samples(ty: &NativeType, what: &str) -> Result<()> {
if matches!(ty, NativeType::Samples(_)) {
Ok(())
+311 -39
View File
@@ -48,31 +48,80 @@ fn raw() -> NativeType {
}
fn input() -> NativeNode {
let NativeType::Samples(schema) = raw() else {
unreachable!()
};
let output = raw();
NativeNode {
expr: NativeExpr::Input(BoundInput {
schema: Arc::clone(&schema),
output: output.clone(),
ordering: SeriesOrdering::KeyThenTime,
}),
output: NativeType::Samples(schema),
output,
}
}
fn input_on(grid: Arc<EvalGrid>) -> NativeNode {
// One allocation shared by the binding and the output: `validate` checks allocation identity,
// because a compiler that meant one grid has no reason to allocate it twice.
let schema = Arc::new(SeriesSchema {
fields: Arc::new([]),
eval_grid: Some(grid),
});
let output = evaluated(Arc::new([]), grid);
NativeNode {
expr: NativeExpr::Input(BoundInput {
schema: Arc::clone(&schema),
output: output.clone(),
ordering: SeriesOrdering::Contiguous,
}),
output: NativeType::Samples(schema),
output,
}
}
/// A constant scalar, which is a scalar type evaluated on the statement's grid.
fn scalar_on(value: f64, grid: Arc<EvalGrid>) -> NativeNode {
NativeNode {
expr: NativeExpr::Scalar(BoundScalar { value }),
output: NativeType::Scalar(grid),
}
}
/// The grid a state node is indexed on.
fn state_grid(node: &NativeNode) -> Arc<EvalGrid> {
let NativeType::AggregateState(schema) = &node.output else {
unreachable!("expected aggregate state")
};
Arc::clone(&schema.grid)
}
fn partial_aggregate(inner: NativeNode) -> NativeNode {
let grid = inner
.output
.grid()
.expect("a partial aggregate consumes an evaluated vector")
.clone();
NativeNode {
expr: NativeExpr::Aggregate {
input: Box::new(inner),
op: BoundAggregate {
kind: AggregateKind::Sum,
group: Arc::new(["job".into()]),
stage: AggregateStage::Partial,
},
},
output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema {
group: Arc::new(["job".into()]),
accumulators: Arc::new([]),
grid,
})),
}
}
fn final_aggregate(state: NativeNode) -> NativeNode {
let grid = state_grid(&state);
NativeNode {
expr: NativeExpr::Aggregate {
input: Box::new(state),
op: BoundAggregate {
kind: AggregateKind::Sum,
group: Arc::new(["job".into()]),
stage: AggregateStage::Final,
},
},
output: evaluated(Arc::new([]), grid),
}
}
@@ -158,7 +207,24 @@ fn a_map_cannot_consume_raw_samples() {
output: evaluated(Arc::new([]), grid(0, 60_000, 4)),
};
let error = node.validate().unwrap_err();
assert!(error.to_string().contains("not evaluated"), "{error}");
assert!(error.to_string().contains("an evaluated vector"), "{error}");
}
/// A scalar is one value per grid point, not a vector, so there are no fields to map.
#[test]
fn a_map_cannot_consume_a_scalar() {
let out = grid(0, 60_000, 4);
let node = NativeNode {
expr: NativeExpr::Map {
input: Box::new(scalar_on(1.0, Arc::clone(&out))),
op: BoundMap {
ops: Arc::new([MathOp::Abs]),
},
},
output: evaluated(Arc::new([]), out),
};
let error = node.validate().unwrap_err();
assert!(error.to_string().contains("not a scalar"), "{error}");
}
/// A map with no operation would be a node that does nothing, which is a compiler mistake.
@@ -197,6 +263,29 @@ fn an_instant_selection_reads_raw_samples() {
assert!(error.to_string().contains("reads evaluated"), "{error}");
}
/// Aggregate state is not a sample stream, so an instant selection cannot read it.
#[test]
fn an_instant_selection_cannot_consume_state() {
let out = grid(0, 60_000, 4);
let node = NativeNode {
expr: NativeExpr::Instant {
input: Box::new(partial_aggregate(window_on(
input(),
None,
Arc::clone(&out),
))),
op: BoundInstant {
lookback_ms: 300_000,
offset_ms: 0,
output_grid: Arc::clone(&out),
},
},
output: evaluated(Arc::new([]), out),
};
let error = node.validate().unwrap_err();
assert!(error.to_string().contains("aggregate state"), "{error}");
}
/// A window's declared input grid has to be the grid its input actually produces.
#[test]
fn a_window_checks_its_declared_input_grid() {
@@ -213,6 +302,32 @@ fn a_window_checks_its_declared_input_grid() {
);
}
/// A window consumes samples: state holds accumulators, not a sample stream to range over.
#[test]
fn a_window_cannot_consume_state() {
let out = grid(0, 60_000, 4);
let node = window_on(
partial_aggregate(window_on(input(), None, Arc::clone(&out))),
None,
grid(0, 60_000, 4),
);
let error = node.validate().unwrap_err();
assert!(error.to_string().contains("aggregate state"), "{error}");
}
/// A window ranges over timestamps, and a scalar has none of its own.
#[test]
fn a_window_cannot_consume_a_scalar() {
let out = grid(0, 60_000, 4);
let node = window_on(
scalar_on(1.0, Arc::clone(&out)),
Some(out),
grid(0, 60_000, 4),
);
let error = node.validate().unwrap_err();
assert!(error.to_string().contains("not a scalar"), "{error}");
}
/// A binary node aligns two inputs, so two different grids cannot be aligned implicitly.
#[test]
fn a_binary_operation_rejects_two_grids() {
@@ -248,6 +363,69 @@ fn a_binary_operation_over_one_grid_is_valid() {
assert!(node.validate().is_ok());
}
/// A scalar side is broadcast, not matched: `sum by(job)(rate(x[5m])) + time()` has no labels to
/// line up, so `matching` is not consulted and the output keeps the vector side's fields.
#[test]
fn a_binary_operation_broadcasts_a_scalar() {
let shared = grid(0, 60_000, 4);
let vector = window_on(input(), None, Arc::clone(&shared));
let node = NativeNode {
expr: NativeExpr::Binary {
left: Box::new(vector),
right: Box::new(scalar_on(1.0, Arc::clone(&shared))),
matching: add(),
},
output: evaluated(Arc::new([]), Arc::clone(&shared)),
};
assert!(node.validate().is_ok());
// The mirror case: the scalar on the left keeps the right side's fields.
let node = NativeNode {
expr: NativeExpr::Binary {
left: Box::new(scalar_on(1.0, Arc::clone(&shared))),
right: Box::new(window_on(input(), None, Arc::clone(&shared))),
matching: add(),
},
output: evaluated(Arc::new([]), Arc::clone(&shared)),
};
assert!(node.validate().is_ok());
}
/// Two scalars make a scalar, because there is nothing to attach labels or fields to.
#[test]
fn two_scalars_make_a_scalar() {
let shared = grid(0, 60_000, 4);
let node = NativeNode {
expr: NativeExpr::Binary {
left: Box::new(scalar_on(1.0, Arc::clone(&shared))),
right: Box::new(scalar_on(2.0, Arc::clone(&shared))),
matching: add(),
},
output: NativeType::Scalar(Arc::clone(&shared)),
};
assert!(node.validate().is_ok());
}
/// State is not a value, so neither side of a binary operation may be state.
#[test]
fn a_binary_operation_cannot_consume_state() {
let shared = grid(0, 60_000, 4);
let node = NativeNode {
expr: NativeExpr::Binary {
left: Box::new(window_on(input(), None, Arc::clone(&shared))),
right: Box::new(partial_aggregate(window_on(
input(),
None,
Arc::clone(&shared),
))),
matching: add(),
},
output: evaluated(Arc::new([]), Arc::clone(&shared)),
};
let error = node.validate().unwrap_err();
assert!(error.to_string().contains("aggregate state"), "{error}");
}
/// A partial aggregate produces state, not a value; a complete one produces a value on the same
/// grid as its input.
#[test]
@@ -304,7 +482,75 @@ fn an_aggregate_stage_must_agree_with_its_type() {
};
let error = node.validate().unwrap_err();
assert!(
error.to_string().contains("does not match its stage"),
error.to_string().contains("produces aggregate state"),
"{error}"
);
}
/// A `Partial` aggregate turns a vector into state: the output is the state type, indexed on the
/// vector's grid.
#[test]
fn a_partial_aggregate_produces_state() {
let state = partial_aggregate(window_over(input(), None));
assert!(state.validate().is_ok());
assert!(matches!(state.output, NativeType::AggregateState(_)));
}
/// A `Final` aggregate consumes the state a `Partial` produced, which is what an exchange
/// boundary hands over between the two stages.
#[test]
fn a_final_aggregate_merges_partial_state() {
let shared = grid(0, 60_000, 4);
let state = partial_aggregate(window_on(input(), None, Arc::clone(&shared)));
let merged = final_aggregate(state);
assert!(merged.validate().is_ok());
assert!(
matches!(&merged.output, NativeType::Samples(schema) if schema.eval_grid.as_ref().is_some_and(|grid| Arc::ptr_eq(grid, &shared)))
);
}
/// A `Final` aggregate consumes state, so a vector is not something it can merge.
#[test]
fn a_final_aggregate_cannot_consume_a_window() {
let inner = window_over(input(), None);
let value_grid = inner.output.grid().unwrap().clone();
let node = NativeNode {
expr: NativeExpr::Aggregate {
input: Box::new(inner),
op: BoundAggregate {
kind: AggregateKind::Sum,
group: Arc::new(["job".into()]),
stage: AggregateStage::Final,
},
},
output: evaluated(Arc::new([]), value_grid),
};
let error = node.validate().unwrap_err();
assert!(
error.to_string().contains("consumes aggregate state"),
"{error}"
);
}
/// A `Complete` aggregate aggregates vectors, so state is not something it can consume.
#[test]
fn a_complete_aggregate_cannot_consume_state() {
let state = partial_aggregate(window_over(input(), None));
let state_grid = state_grid(&state);
let node = NativeNode {
expr: NativeExpr::Aggregate {
input: Box::new(state),
op: BoundAggregate {
kind: AggregateKind::Sum,
group: Arc::new(["job".into()]),
stage: AggregateStage::Complete,
},
},
output: evaluated(Arc::new([]), state_grid),
};
let error = node.validate().unwrap_err();
assert!(
error.to_string().contains("consumes an evaluated vector"),
"{error}"
);
}
@@ -335,53 +581,79 @@ fn the_walkthrough_shapes_are_trees() {
};
assert!(sum.validate().is_ok());
// `sum by(job)(rate(x[5m])) + 1`: the scalar applies to the completed value, not to state.
// `sum by(job)(rate(x[5m])) + 1`: the aggregate is complete, and the scalar side is
// broadcast, so `matching` is not consulted for it.
let plus_one = NativeNode {
expr: NativeExpr::Map {
input: Box::new(NativeNode {
expr: NativeExpr::Aggregate {
input: Box::new(window_on(input(), None, Arc::clone(&statement_grid))),
op: BoundAggregate {
kind: AggregateKind::Sum,
group: Arc::new(["job".into()]),
stage: AggregateStage::Final,
},
},
output: evaluated(Arc::new([]), Arc::clone(&statement_grid)),
}),
op: BoundMap {
ops: Arc::new([MathOp::Abs]),
},
expr: NativeExpr::Binary {
left: Box::new(sum.clone()),
right: Box::new(scalar_on(1.0, Arc::clone(&statement_grid))),
matching: add(),
},
output: evaluated(Arc::new([]), statement_grid),
};
assert!(plus_one.validate().is_ok());
}
/// A scalar node is legal on its own; a raw input is not evaluated, so nothing consuming values
/// may sit above it.
/// A scalar node's output is the scalar type, which is what keeps a broadcast from turning into
/// label matching.
#[test]
fn a_scalar_node_is_valid() {
let node = scalar_on(1.0, grid(0, 60_000, 4));
assert!(node.validate().is_ok());
}
/// A scalar node declared as a vector would let a broadcast be planned as a match.
#[test]
fn a_scalar_node_must_produce_a_scalar() {
let node = NativeNode {
expr: NativeExpr::Scalar(BoundScalar { value: 1.0 }),
output: evaluated(Arc::new([]), grid(0, 60_000, 4)),
};
assert!(node.validate().is_ok());
let error = node.validate().unwrap_err();
assert!(
error.to_string().contains("does not produce a scalar"),
"{error}"
);
}
/// An input whose declared schema is not the schema it was bound to cannot be trusted.
/// An input whose declared output is not the binding it was bound to cannot be trusted.
#[test]
fn an_input_must_report_the_schema_it_was_bound_to() {
fn an_input_must_report_the_binding_it_was_bound_to() {
let node = NativeNode {
expr: NativeExpr::Input(BoundInput {
schema: Arc::new(SeriesSchema {
fields: Arc::new([]),
eval_grid: None,
}),
output: raw(),
ordering: SeriesOrdering::KeyThenTime,
}),
output: raw(),
};
let error = node.validate().unwrap_err();
assert!(error.to_string().contains("not the schema"), "{error}");
assert!(error.to_string().contains("not the binding"), "{error}");
}
/// An exchange boundary binds state, and the node has to report that same state.
#[test]
fn an_input_can_bind_aggregate_state() {
let state = partial_aggregate(window_over(input(), None));
let bound = NativeNode {
expr: NativeExpr::Input(BoundInput {
output: state.output.clone(),
ordering: SeriesOrdering::Contiguous,
}),
output: state.output.clone(),
};
assert!(bound.validate().is_ok());
// A `Final` aggregate can then consume it, which is the shape of a distributed aggregate.
assert!(final_aggregate(bound).validate().is_ok());
// A fresh state allocation is a different binding, so it cannot be reported as the bound one.
let other = NativeNode {
expr: NativeExpr::Input(BoundInput {
output: state.output.clone(),
ordering: SeriesOrdering::Contiguous,
}),
output: partial_aggregate(window_over(input(), None)).output,
};
let error = other.validate().unwrap_err();
assert!(error.to_string().contains("not the binding"), "{error}");
}