feat(promql): compile vector binary expressions with independent inputs

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-10-23 17:33:01 +08:00
committed by discord9
parent 936a0eca81
commit f4cdccc769
3 changed files with 1132 additions and 88 deletions
+98 -15
View File
@@ -136,7 +136,9 @@ use promql::native::plan::{
};
use promql::range_eval::{RangeFunction, RangeWindow, subquery_grid};
use promql::select::{LabelMatcher, MatchOp, SortOrder, absent_labels};
use promql::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels};
use promql::vector_match::{
BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, binary_output_schema,
};
use promql_parser::label::MatchOp as ParserMatchOp;
use promql_parser::label::Matchers;
use promql_parser::parser::token::TokenType;
@@ -251,9 +253,10 @@ const SUPPORTED: &str = "a selector — `x`, optionally with an `offset` — a r
`rate(rate(x[5m:1m])[10m:30s])`, and where either matrix shape carries the \
`offset` and `@` anchor written on it as in `rate(x[5m] @ 1234)`; a math \
function over any of them (`abs(rate(x[5m]))`, `clamp_min(x, 0)`), a binary \
operation between one of them and a constant (`2 / (x + 1)`, \
`x > bool 0`), a negation of one of them (`-x`), or one of the aggregators \
that folds a group's values into one value per grid point — \
operation between two of them (`a + b`, `a / on(job) group_left b`, \
`a > bool ignoring(zone) b`) or between one of them and a constant \
(`2 / (x + 1)`, `x > bool 0`), a negation of one of them (`-x`), or one of \
the aggregators that fold a group's values into one value per grid point — \
`sum`, `avg`, `count`, `min`, `max`, `group`, `stddev`, `stdvar` and \
`quantile(<constant>, <expression>)` — over any of them, optionally \
grouped by `by` or `without` as in `avg by(job)(rate(x[5m]) * 100)`; a \
@@ -284,9 +287,10 @@ const SUPPORTED: &str = "a selector — `x`, optionally with an `offset` — a r
/// backstop for a tree built some other way.
///
/// The tree carries no metric name and no matchers, so `rate(x{job="a"}[5m])` and `rate(y[5m])`
/// compile to identical trees, and an `EXPLAIN` built on this display cannot tell them apart. That
/// is fine while a tree has one selector; a tree that reads two scans is refused here, and
/// [`compile_selectors`] is what a caller that knows which scan feeds which selector calls.
/// compile to identical trees, and an `EXPLAIN` built on this display cannot tell them apart. A
/// tree that reads two scans is therefore paired with [`CompiledInput`]s, which carry each
/// selector's requirement; this entry refuses such a statement rather than answering with a tree
/// whose inputs no caller can tell apart.
pub fn compile(
stmt: &EvalStmt,
input: Arc<SeriesSchema>,
@@ -488,16 +492,35 @@ fn binary_operation(context: &Context, binary: &BinaryExpr) -> Result<NativeNode
binary.op
)));
};
// Two vectors are refused before the modifier is looked at, so a vector–vector query with
// matching says what is actually missing. The refusal names the missing identity rather than the
// query, because that is what whoever adds it has to add.
// Two vectors are matched by their labels, so the node carries the modifiers the query wrote and
// each operand is compiled from its own selector.
if binary.lhs.value_type() == ValueType::Vector && binary.rhs.value_type() == ValueType::Vector
{
return Err(not_implemented(&format!(
"the binary operation `{binary}` between two vectors, which needs each input to name \
the selector it reads: an input binding carries its ordering and what it produces, but \
not which selector it was bound to"
)));
// Both operands are compiled before the node is built, so `a + b` binds one input per
// selector and `(a + b) / c` nests. Left before right, because a non-commutative operator
// means what that order says.
let left = compile_expr(context, &binary.lhs)?;
let right = compile_expr(context, &binary.rhs)?;
// A vector-typed expression compiles to evaluated samples, so a side that is not one is a
// compiler defect rather than a query error: the type check above is what a query has to
// pass.
let (Some(lhs), Some(rhs)) = (left.output.samples(), right.output.samples()) else {
return Err(DataFusionError::Internal(format!(
"the binary operation `{binary}` compiled a vector operand to something other than \
samples: a vector-typed expression compiles to samples, so the two disagree"
)));
};
// The output is the kernel's own schema: the two grids have to agree, and the fields are
// paired by position and named after the left side.
let output = NativeType::Samples(binary_output_schema(lhs, rhs)?);
return Ok(NativeNode {
expr: NativeExpr::Binary {
left: Box::new(left),
right: Box::new(right),
matching: vector_matching(binary, op)?,
},
output,
});
}
// What is left has a constant on one side, and a modifier is refused rather than dropped. This
// is deliberately narrower than Prometheus, which drops an `on` or `ignoring` written on a
@@ -588,6 +611,66 @@ fn scalar_matching(op: BinaryOp, return_bool: bool) -> BinaryMatching {
/// separately: `x > 0` and `x > bool 0` are one operator with one field changed. [`arithmetic_op`]
/// is not reused because it decides what a *fold* may do at compile time and a comparison folds
/// nothing, while this map decides what a *node* computes once the query runs.
/// The matching a vector–vector operation records.
///
/// Each part is read from the modifier the query wrote, and a modifier it did not write is the
/// default PromQL applies: every label but `__name__` matches (`ignoring` nothing), one series of
/// each side may share a match group, and no fill value stands in for a missing sample.
///
/// `ManyToMany` is the cardinality of a set operator, which [`binary_operation`] refuses before
/// asking for a matching, so reaching it means the two disagree; it is reported as a shape with no
/// node rather than panicking on a path a query cannot take today.
fn vector_matching(binary: &BinaryExpr, op: BinaryOp) -> Result<BinaryMatching> {
let modifier = binary.modifier.as_ref();
// `Include` is `on`, `Exclude` is `ignoring`: a label list is matched as the names it holds, and
// `__name__` is only a match label when `on` names it.
let labels = match modifier.and_then(|modifier| modifier.matching.as_ref()) {
None => MatchingLabels::Ignoring(Vec::new()),
Some(LabelModifier::Include(labels)) => MatchingLabels::On(label_names(&labels.labels)),
Some(LabelModifier::Exclude(labels)) => {
MatchingLabels::Ignoring(label_names(&labels.labels))
}
};
let cardinality = match modifier.map(|modifier| &modifier.card) {
None | Some(VectorMatchCardinality::OneToOne) => Cardinality::OneToOne,
Some(VectorMatchCardinality::ManyToOne(labels)) => {
Cardinality::ManyToOne(label_names(&labels.labels))
}
Some(VectorMatchCardinality::OneToMany(labels)) => {
Cardinality::OneToMany(label_names(&labels.labels))
}
Some(VectorMatchCardinality::ManyToMany) => {
return Err(not_implemented(&format!(
"the many-to-many matching in `{binary}`, which is the cardinality of a set \
operator: it combines two vectors' series, and this node is an arithmetic or \
comparison operation over values"
)));
}
};
// The two fields keep the parser's names, so `fill_values.lhs` is what `fill_left` wrote and
// `fill_values.rhs` is what `fill_right` wrote. Which sample a fill stands in for depends on the
// cardinality, because the kernel picks the field by which side of the *match* is missing:
// `fill.rhs` answers a many-side series that found no match, and `fill.lhs` a one-side series
// that found none. The default and `group_left` make the many side the left operand;
// `group_right` swaps them.
let fill = modifier.map_or_else(FillValues::default, |modifier| FillValues {
lhs: modifier.fill_values.lhs,
rhs: modifier.fill_values.rhs,
});
Ok(BinaryMatching {
op,
return_bool: binary.return_bool(),
labels,
cardinality,
fill,
})
}
/// The label names of a parser label list, as the matching and the copied-label lists hold them.
fn label_names(labels: &[String]) -> Vec<Arc<str>> {
labels.iter().map(|name| Arc::from(name.as_str())).collect()
}
fn binary_op(op: &TokenType) -> Option<BinaryOp> {
match op.id() {
token::T_ADD => Some(BinaryOp::Add),
+161 -73
View File
@@ -33,7 +33,7 @@ use promql::native::plan::{
Grouping, NativeExpr, NativeNode, NativeTree, NativeType,
};
use promql::range_eval::RangeFunction;
use promql::vector_match::{BinaryMatching, BinaryOp};
use promql::vector_match::{BinaryMatching, BinaryOp, Cardinality, MatchingLabels};
use promql_parser::label::MatchOp;
use promql_parser::parser::{
AtModifier, BinModifier, EvalStmt, Expr as PromExpr, NumberLiteral, Offset,
@@ -42,6 +42,27 @@ use promql_parser::parser::{
use super::{SelectorRequirement, SelectorTiming, compile, compile_selectors};
/// Whether a matching names its labels with `on` (`true`) or `ignoring` (`false`), and which.
fn matching_labels(labels: &MatchingLabels) -> (bool, Vec<&str>) {
match labels {
MatchingLabels::On(names) => (true, names.iter().map(|name| &**name).collect()),
MatchingLabels::Ignoring(names) => (false, names.iter().map(|name| &**name).collect()),
}
}
/// Which cardinality a matching declares, and the labels it copies from the one side.
fn matching_cardinality(cardinality: &Cardinality) -> (&'static str, Vec<&str>) {
match cardinality {
Cardinality::OneToOne => ("one-to-one", Vec::new()),
Cardinality::ManyToOne(names) => {
("many-to-one", names.iter().map(|name| &**name).collect())
}
Cardinality::OneToMany(names) => {
("one-to-many", names.iter().map(|name| &**name).collect())
}
}
}
/// The raw series schema a caller binds from the table: one field and no evaluation grid.
fn raw_schema() -> Arc<SeriesSchema> {
Arc::new(SeriesSchema {
@@ -1624,33 +1645,42 @@ fn a_constant_operand_binds_the_value_it_folds_to() {
}
}
/// An operation between two vectors is refused because the tree cannot say which selector each
/// `Input` reads: `a + b` and `a + a` would compile to the same tree. The refusal names the missing
/// identity rather than the query it found, so whoever adds it knows what to add.
/// Two vectors compile to one input per selector, each named by the position the executor reads it
/// at, and the legacy entry refuses such a statement rather than answering with a tree whose inputs
/// no caller can tell apart.
#[test]
fn an_operation_between_two_vectors_is_refused_for_the_missing_selector_identity() {
for query in [
"a + b",
"a > b",
"rate(a[5m]) * rate(b[5m])",
"sum(a) + sum(b)",
] {
let error = compile(&eval_stmt(query), raw_schema(), SeriesOrdering::KeyThenTime)
.expect_err(&format!("`{query}` compiled, and it should not have"));
assert!(
matches!(error, DataFusionError::NotImplemented(_)),
"`{query}` did not report NotImplemented: {error}"
);
let message = error.to_string();
assert!(
message.contains("between two vectors"),
"`{query}` did not say what it found: {message}"
);
assert!(
message.contains("selector"),
"`{query}` did not name what an input is missing: {message}"
);
}
fn a_two_vector_operation_binds_one_input_per_selector() {
let compiled = compile_selectors(
&eval_stmt("a + b"),
&|_| Ok(raw_schema()),
SeriesOrdering::KeyThenTime,
)
.unwrap_or_else(|error| panic!("`a + b` was refused: {error}"));
assert_eq!(2, compiled.inputs.len());
assert_eq!(compiled.inputs[0].path, NodePath::root().left().input());
assert_eq!(compiled.inputs[1].path, NodePath::root().right().input());
assert_eq!(compiled.inputs[0].requirement.metric.as_deref(), Some("a"));
assert_eq!(compiled.inputs[1].requirement.metric.as_deref(), Some("b"));
assert!(matches!(
compiled.tree.root().expr,
NativeExpr::Binary { .. }
));
// `compile` has one schema for every input, so it cannot say which scan feeds which selector.
let error = compile(
&eval_stmt("a + b"),
raw_schema(),
SeriesOrdering::KeyThenTime,
)
.expect_err("`a + b` needs two inputs, and `compile` binds one");
assert!(
matches!(error, DataFusionError::NotImplemented(_)),
"the refusal is the route declining the shape: {error}"
);
assert!(
error.to_string().contains("use `compile_selectors`"),
"the refusal does not say how to bind two inputs: {error}"
);
}
/// A set operator has no node at all, so it is refused as the set operator it is rather than as an
@@ -4379,52 +4409,6 @@ fn selector_requirement_bounds_account_for_grid_end_open_edges_and_zero_lookback
);
}
/// An anchored instant selection reads one point rather than every grid point, so both edges of its
/// scan come from the anchor. Taking the lower edge from the grid instead would scan from the
/// statement's start, which for an anchor before the statement is the wrong side of the data and
/// for an anchor after it skips the sample the selection reads.
#[test]
fn an_anchored_instant_selector_scans_from_its_anchor() {
// `x @ 50 offset 2s` with a five-second lookback: the sample is read at 48s, so the window it is
// selected from is 43s..=48s even though the statement starts at the epoch.
let requirement = SelectorRequirement {
metric: None,
matchers: promql_parser::label::Matchers::empty(),
offset_ms: 2_000,
at_ms: Some(50_000),
grid_start_ms: 0,
grid_end_ms: 100_000,
timing: SelectorTiming::Instant { lookback_ms: 5_000 },
};
assert_eq!(
requirement.raw_scan_bounds().unwrap(),
(43_000, 48_000, false)
);
// An anchor before the statement scans before it too: the same rule, the other direction. The
// grid's own start would have put the lower edge at a time the anchor never reads.
let requirement = SelectorRequirement {
at_ms: Some(-30_000),
..requirement
};
assert_eq!(
requirement.raw_scan_bounds().unwrap(),
(-37_000, -32_000, false)
);
// A zero lookback closes both edges on the one sample, anchored or not.
let requirement = SelectorRequirement {
at_ms: Some(50_000),
offset_ms: 0,
timing: SelectorTiming::Instant { lookback_ms: 0 },
..requirement
};
assert_eq!(
requirement.raw_scan_bounds().unwrap(),
(50_000, 50_000, true)
);
}
/// An anchor replaces the grid's endpoints on both edges, and a bound that does not fit is reported
/// rather than wrapped.
#[test]
@@ -4452,6 +4436,110 @@ fn selector_requirement_bounds_apply_offset_and_anchor_and_check_overflow() {
assert!(requirement.raw_scan_bounds().is_err());
}
#[test]
fn an_on_matching_binds_the_labels_it_names() {
let compiled = compile_selectors(
&eval_stmt("a / on(job) b"),
&|_| Ok(raw_schema()),
SeriesOrdering::KeyThenTime,
)
.unwrap_or_else(|error| panic!("`a / on(job) b` was refused: {error}"));
let (_, _, matching) = binary_parts(compiled.tree.root());
assert_eq!(matching.op, BinaryOp::Div);
assert_eq!(
matching_labels(&matching.labels),
(true, vec!["job"]),
"`on(job)` was not bound as an `on` list holding `job`"
);
assert_eq!(matching_cardinality(&matching.cardinality).0, "one-to-one");
}
/// `ignoring` and `group_left` are two separate fields of the matching: the labels a series is
/// matched on, and the labels copied from the one side. Binding one into the other computes a
/// different result for a query this compiler accepts.
#[test]
fn an_ignoring_with_group_left_binds_both_lists() {
let compiled = compile_selectors(
&eval_stmt("a / ignoring(instance) group_left(host) b"),
&|_| Ok(raw_schema()),
SeriesOrdering::KeyThenTime,
)
.unwrap_or_else(|error| {
panic!("`a / ignoring(instance) group_left(host) b` was refused: {error}")
});
let (_, _, matching) = binary_parts(compiled.tree.root());
assert_eq!(
matching_labels(&matching.labels),
(false, vec!["instance"]),
"`ignoring(instance)` was not bound as an `ignoring` list holding `instance`"
);
assert_eq!(
matching_cardinality(&matching.cardinality),
("many-to-one", vec!["host"]),
"`group_left(host)` was not bound as a many-to-one cardinality copying `host`"
);
}
/// `group_right` swaps which side is the one side, so the cardinality and the copied labels are
/// asserted on their own: a binding that read `group_left` for both would answer the wrong side.
#[test]
fn a_group_right_binds_the_one_to_many_cardinality() {
let compiled = compile_selectors(
&eval_stmt("a / on(job) group_right(zone) b"),
&|_| Ok(raw_schema()),
SeriesOrdering::KeyThenTime,
)
.unwrap_or_else(|error| panic!("`a / on(job) group_right(zone) b` was refused: {error}"));
let (_, _, matching) = binary_parts(compiled.tree.root());
assert_eq!(
matching_cardinality(&matching.cardinality),
("one-to-many", vec!["zone"]),
"`group_right(zone)` was not bound as a one-to-many cardinality copying `zone`"
);
assert_eq!(matching_labels(&matching.labels), (true, vec!["job"]));
}
/// A fill value stands for the side the query named, and `fill` stands for both, so each field is
/// asserted apart: the kernel picks the field by which side of the match is missing.
#[test]
fn fill_values_bind_the_side_the_query_named() {
for (query, lhs, rhs) in [
("a + fill_left(0) b", Some(0.0), None),
("a + fill_right(1.5) b", None, Some(1.5)),
("a + fill(2) b", Some(2.0), Some(2.0)),
] {
let compiled = compile_selectors(
&eval_stmt(query),
&|_| Ok(raw_schema()),
SeriesOrdering::KeyThenTime,
)
.unwrap_or_else(|error| panic!("`{query}` was refused: {error}"));
let (_, _, matching) = binary_parts(compiled.tree.root());
assert_eq!(matching.fill.lhs, lhs, "`{query}` bound the left fill");
assert_eq!(matching.fill.rhs, rhs, "`{query}` bound the right fill");
}
}
/// A comparison binds its `return_bool` flag, which is the one modifier that changes what the
/// operation computes rather than which series it pairs.
#[test]
fn a_comparison_binds_its_bool_flag() {
for (query, expected) in [("a > b", false), ("a > bool b", true)] {
let compiled = compile_selectors(
&eval_stmt(query),
&|_| Ok(raw_schema()),
SeriesOrdering::KeyThenTime,
)
.unwrap_or_else(|error| panic!("`{query}` was refused: {error}"));
let (_, _, matching) = binary_parts(compiled.tree.root());
assert_eq!(matching.op, BinaryOp::Gt);
assert_eq!(matching.return_bool, expected, "`{query}` bound its flag");
}
}
#[test]
fn selector_binding_propagates_callback_errors() {
let error = compile_selectors(
+873
View File
@@ -0,0 +1,873 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A two-selector query compiled by the real compiler and answered by the real executor.
//!
//! This is an external integration test: the tree comes from
//! [`compile_selectors`], never from a hand-built node, and it is run through
//! [`promql::native::execute`] the way a consumer above these crates would run it. What it checks
//! is what per-selector binding exists for: `a + b` reads two inputs, each selector's samples are
//! fed at the position the compiler says that selector's input sits at, and the operation matches
//! the two vectors by the labels the query wrote.
//!
//! Every case asserts the series count, the label set of each output series and the value at every
//! grid point, because a case that only asserted "something came out" would pass under a wrong label
//! mapping. The grid is five points one second apart starting at the Unix epoch, and the statement's
//! lookback is five seconds, so an instant selection carries the last sample of the previous points
//! forward.
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::{Duration, UNIX_EPOCH};
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool};
use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
use datatypes::arrow::array::Float64Array;
use datatypes::arrow::buffer::{Buffer, ScalarBuffer};
use datatypes::series::raw::{RawSeriesChunk, RawTimestamps};
use datatypes::series::samples::{FieldSpec, SampleRef, Samples, SeriesFields, SeriesSchema};
use datatypes::series::{Label, MetricName, SeriesOrdering};
use promql::evaluated::EvaluatedChunk;
use promql::native::execute::{NativeExecutionState, NativeExecutor};
use promql::native::plan::NativeExpr;
use query::promql::native_compile::SelectorRequirement;
use query::promql::native_compile::{CompiledTree, compile_selectors};
/// The layout every selector of these queries is fed in: one float field of raw samples.
fn raw_schema() -> Arc<SeriesSchema> {
Arc::new(SeriesSchema {
fields: Arc::new([FieldSpec {
name: "value".into(),
}]),
eval_grid: None,
})
}
/// `query` over `0..=4000ms` on a `1000ms` grid with a five-second lookback, which is five points.
fn eval_stmt(query: &str) -> promql_parser::parser::EvalStmt {
promql_parser::parser::EvalStmt {
expr: promql_parser::parser::parse(query).unwrap(),
start: UNIX_EPOCH,
end: UNIX_EPOCH + Duration::from_millis(4_000),
interval: Duration::from_millis(1_000),
lookback_delta: Duration::from_millis(5_000),
}
}
/// `query` compiled by the real compiler, with its tree and the inputs it reads.
fn compile(query: &str) -> CompiledTree {
let schema = raw_schema();
let bindings = |_requirement: &SelectorRequirement| Ok(Arc::clone(&schema));
compile_selectors(&eval_stmt(query), &bindings, SeriesOrdering::KeyThenTime)
.unwrap_or_else(|error| panic!("`{query}` was refused: {error}"))
}
/// The metric `name` with `labels`, as a source series of the samples a scan would read.
fn metric(name: &str, labels: &[(&str, &str)]) -> MetricName {
let tags = labels
.iter()
.map(|(name, value)| Label {
name: (*name).into(),
value: (*value).into(),
})
.collect();
MetricName::try_new(Some(name.into()), tags).expect("distinct label names")
}
/// One raw chunk of `series`, holding `rows` at their source timestamps, closing the series.
///
/// The chunk is built against `schema`, the layout the compiler bound that selector to, so a chunk
/// the input would refuse cannot be pushed here by accident.
fn raw_chunk(
schema: &SeriesSchema,
key: &str,
series: MetricName,
rows: &[(i64, f64)],
) -> RawSeriesChunk {
let timestamps: Vec<i64> = rows.iter().map(|&(time, _)| time).collect();
let values: Vec<f64> = rows.iter().map(|&(_, value)| value).collect();
RawSeriesChunk::try_new(
schema,
Buffer::from_slice_ref(key.as_bytes()),
Some(series),
RawTimestamps::try_new(ScalarBuffer::from(timestamps)).expect("increasing timestamps"),
SeriesFields::one(Samples::from_float(Float64Array::from(values))),
true,
)
.expect("the chunk is bound to the schema it is built against")
}
/// Builds only source rows in the requirement's metric/matcher/time/field selection.
fn scan_rows(
requirement: &SelectorRequirement,
metric_name: &str,
labels: &[(&str, &str)],
rows: &[(i64, f64)],
) -> Vec<(i64, f64)> {
if requirement
.metric
.as_deref()
.is_some_and(|name| name != metric_name)
{
return Vec::new();
}
if !requirement.matchers.matchers.iter().all(|matcher| {
let value = if matcher.name == "__name__" {
metric_name
} else {
labels
.iter()
.find(|(name, _)| *name == matcher.name)
.map_or("", |(_, value)| *value)
};
matcher.is_match(value)
}) {
return Vec::new();
}
let (start, end, inclusive_start) = requirement.raw_scan_bounds().unwrap();
rows.iter()
.copied()
.filter(|(time, _)| (*time > start || (inclusive_start && *time == start)) && *time <= end)
.collect()
}
/// Scans the small fixture source independently for each compiled input and pushes only selected rows.
fn scan_push(
compiled: &CompiledTree,
input: usize,
key: &str,
metric_name: &str,
labels: &[(&str, &str)],
rows: &[(i64, f64)],
) -> Option<(usize, RawSeriesChunk)> {
let input_spec = &compiled.inputs[input];
let rows = scan_rows(&input_spec.requirement, metric_name, labels, rows);
(!rows.is_empty()).then(|| {
(
input,
raw_chunk(
input_spec.schema.as_ref(),
key,
metric(
metric_name,
&labels
.iter()
.copied()
.filter(|(name, _)| *name != "__field__")
.collect::<Vec<_>>(),
),
&rows,
),
)
})
}
/// Runs `compiled` over `pushes`, each naming the input its chunk belongs to by that input's index.
///
/// A binary node retains both operands and decides nothing until its input ends, so every pull
/// before [`NativeExecutor::finish`] has to answer with nothing; a pull that answered earlier would
/// mean a node computed over half a vector.
fn run(compiled: &CompiledTree, pushes: Vec<(usize, RawSeriesChunk)>) -> Vec<EvaluatedChunk> {
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
let metrics = ExecutionPlanMetricsSet::new();
let state = NativeExecutionState::try_new(&compiled.tree, Arc::clone(&pool), &metrics, 0)
.expect("the runtime executes this tree");
let mut executor = NativeExecutor::new(state);
for (index, chunk) in pushes {
let path = &compiled.inputs[index].path;
executor
.push_raw_at(path, chunk)
.unwrap_or_else(|error| panic!("the chunk is bound to the input at {path}: {error}"));
let pulled = executor.next_chunk().expect("the pull succeeds");
assert!(
pulled.is_none(),
"the answer at {path} came before the input ended: {pulled:?}"
);
}
let chunks = executor.finish().expect("every series closed");
assert_eq!(executor.state().reserved_bytes(), 0, "nothing held");
assert_eq!(pool.reserved(), 0, "a finished execution reserves nothing");
chunks
}
/// The label set a chunk's series is filed under, rendered with the metric name first.
fn label_set(chunk: &EvaluatedChunk) -> String {
let metric = &chunk.series.metric;
let mut parts = Vec::new();
if let Some(name) = metric.name() {
parts.push(format!("__name__=\"{name}\""));
}
for label in metric.tags() {
parts.push(format!("{}=\"{}\"", label.name, label.value));
}
format!("{{{}}}", parts.join(", "))
}
/// What every output series holds, as its rendered label set and its value at each grid position.
///
/// A series may arrive as one chunk or as several: a chunk says which series it carries and closes
/// it, and how a node batches what it produces is not this test's to pin. Rows are therefore
/// appended to the entry for their label set, and a series split over two chunks reads as one.
fn results(chunks: &[EvaluatedChunk]) -> BTreeMap<String, Vec<(usize, f64)>> {
let mut output: BTreeMap<String, Vec<(usize, f64)>> = BTreeMap::new();
for chunk in chunks {
let field = chunk
.series
.fields
.as_slice()
.first()
.expect("the result carries the one field it was bound to");
let entry = output.entry(label_set(chunk)).or_default();
for (position, row) in chunk.series.time.positions() {
match field.sample(row) {
SampleRef::Float(value) => entry.push((position, value)),
_ => panic!("the row at {row} holds no float"),
}
}
}
output
}
/// The value at every one of the five grid points.
fn every_point(value: f64) -> Vec<(usize, f64)> {
(0..5).map(|position| (position, value)).collect()
}
/// `a + b` over two genuinely different inputs: different metric names, different matcher sets and
/// different samples. Each input is fed at the position its own selector was bound to, and the sum
/// is asserted point by point.
#[test]
fn two_selectors_are_summed_from_two_inputs() {
let compiled = compile("a{job=\"x\"} + b{job=\"x\", instance=\"i1\"}");
assert_eq!(
compiled.inputs.len(),
2,
"`a + b` did not bind one input per selector"
);
assert_eq!(
compiled.inputs[0].requirement.metric.as_deref(),
Some("a"),
"the first input is not the left selector's"
);
assert_eq!(
compiled.inputs[1].requirement.metric.as_deref(),
Some("b"),
"the second input is not the right selector's"
);
// The two selectors asked for different series, so each input records its own matcher set.
assert_eq!(
compiled.inputs[0].requirement.matchers.matchers.len(),
1,
"the left input did not record the one matcher its selector wrote"
);
assert_eq!(
compiled.inputs[1].requirement.matchers.matchers.len(),
2,
"the right input did not record the two matchers its selector wrote"
);
assert_ne!(
compiled.inputs[0].path, compiled.inputs[1].path,
"two selectors were bound to one position"
);
// `a` holds 1 at t=0 and 2 at t=2000, so an instant selection carries 1 forward to p0 and p1 and
// 2 to p2..p4. `b` holds 10 at t=0 and 40 at t=4000: `[10, 10, 10, 10, 40]`.
let chunks = run(
&compiled,
vec![
(
0,
raw_chunk(
compiled.inputs[0].schema.as_ref(),
"a-job=x-instance=i1",
metric("a", &[("instance", "i1"), ("job", "x")]),
&[(0, 1.0), (2_000, 2.0)],
),
),
(
1,
raw_chunk(
compiled.inputs[1].schema.as_ref(),
"b-job=x-instance=i1",
metric("b", &[("instance", "i1"), ("job", "x")]),
&[(0, 10.0), (4_000, 40.0)],
),
),
],
);
let output = results(&chunks);
assert_eq!(output.len(), 1, "the sum is not one series: {output:?}");
// Arithmetic drops the metric name and keeps the labels the match was made on.
assert_eq!(
output.get("{instance=\"i1\", job=\"x\"}"),
Some(&vec![(0, 11.0), (1, 11.0), (2, 12.0), (3, 12.0), (4, 42.0)]),
"the sum is not the values each side selected: {output:?}"
);
}
/// `a / on(job) b` matches on `job` alone, so two series that differ in `instance` pair up. The same
/// inputs through `a / b` — the default matching, which matches on every label but `__name__` — pair
/// nothing, and that difference is what proves the `on` list reached the kernel.
#[test]
fn an_on_matching_pairs_series_the_default_matching_would_not() {
// Both inputs are the same in both runs: only the compiled matching differs.
let pushes = |compiled: &CompiledTree| {
vec![
(
0,
raw_chunk(
compiled.inputs[0].schema.as_ref(),
"a-job=x-instance=i1",
metric("a", &[("instance", "i1"), ("job", "x")]),
&[(0, 1.0), (2_000, 2.0)],
),
),
(
1,
raw_chunk(
compiled.inputs[1].schema.as_ref(),
"b-job=x-instance=i2",
metric("b", &[("instance", "i2"), ("job", "x")]),
&[(0, 10.0), (4_000, 40.0)],
),
),
]
};
let matched = compile("a{job=\"x\"} / on(job) b{job=\"x\"}");
let output = results(&run(&matched, pushes(&matched)));
assert_eq!(output.len(), 1, "`on(job)` did not match: {output:?}");
// `on` keeps only the labels it matched on, so `instance` is gone.
assert_eq!(
output.get("{job=\"x\"}"),
Some(&vec![
(0, 0.1),
(1, 0.1),
(2, 0.2),
(3, 0.2),
(4, 2.0 / 40.0),
]),
"`on(job)` did not divide each side's value: {output:?}"
);
// The default matching matches on `instance` too, and the two sides disagree on it.
let unmatched = compile("a{job=\"x\"} / b{job=\"x\"}");
let output = results(&run(&unmatched, pushes(&unmatched)));
assert!(
output.is_empty(),
"the default matching paired series that differ in `instance`: {output:?}"
);
}
/// `group_left(env)` reuses one right series for two left series and copies `env` from the right
/// side into each result, which is the cardinality a one-to-one matching cannot express.
#[test]
fn a_group_left_reuses_the_one_side_and_copies_its_label() {
let compiled = compile("a{job=\"x\"} / on(job) group_left(env) b{job=\"x\"}");
let chunks = run(
&compiled,
vec![
(
0,
raw_chunk(
compiled.inputs[0].schema.as_ref(),
"a-job=x-instance=i1",
metric("a", &[("instance", "i1"), ("job", "x")]),
&[(0, 1.0)],
),
),
(
0,
raw_chunk(
compiled.inputs[0].schema.as_ref(),
"a-job=x-instance=i3",
metric("a", &[("instance", "i3"), ("job", "x")]),
&[(0, 2.0)],
),
),
(
1,
raw_chunk(
compiled.inputs[1].schema.as_ref(),
"b-env=prod-job=x",
metric("b", &[("env", "prod"), ("job", "x")]),
&[(0, 10.0)],
),
),
],
);
let output = results(&chunks);
// One right series matched both left series, so both are answered, each keeping its own
// `instance` and gaining the copied `env`.
assert_eq!(
output.len(),
2,
"the left series was not reused: {output:?}"
);
assert_eq!(
output.get("{env=\"prod\", instance=\"i1\", job=\"x\"}"),
Some(&every_point(0.1)),
"the first left series did not keep its own labels beside the copied one: {output:?}"
);
assert_eq!(
output.get("{env=\"prod\", instance=\"i3\", job=\"x\"}"),
Some(&every_point(0.2)),
"the second left series did not keep its own labels beside the copied one: {output:?}"
);
}
/// `fill_right(100)` stands in for a right sample a left series found no match for: `a * on(job) b`
/// drops the left series `job="y"`, and the filled operation answers it from the fill value.
#[test]
fn a_fill_answers_a_left_series_that_found_no_match() {
let pushes = |compiled: &CompiledTree| {
vec![
(
0,
raw_chunk(
compiled.inputs[0].schema.as_ref(),
"a-job=x",
metric("a", &[("job", "x")]),
&[(0, 2.0)],
),
),
(
0,
raw_chunk(
compiled.inputs[0].schema.as_ref(),
"a-job=y",
metric("a", &[("job", "y")]),
&[(0, 3.0)],
),
),
(
1,
raw_chunk(
compiled.inputs[1].schema.as_ref(),
"b-job=x",
metric("b", &[("job", "x")]),
&[(0, 10.0)],
),
),
]
};
let unfilled = compile("a * on(job) b");
let output = results(&run(&unfilled, pushes(&unfilled)));
assert_eq!(
output.len(),
1,
"a series with no match was answered without a fill: {output:?}"
);
assert_eq!(
output.get("{job=\"x\"}"),
Some(&every_point(20.0)),
"the matched series is not the product of the two sides: {output:?}"
);
let filled = compile("a * on(job) fill_right(100) b");
let output = results(&run(&filled, pushes(&filled)));
assert_eq!(
output.len(),
2,
"`fill_right(100)` did not answer the unmatched series: {output:?}"
);
assert_eq!(
output.get("{job=\"x\"}"),
Some(&every_point(20.0)),
"the fill changed the series that did match: {output:?}"
);
assert_eq!(
output.get("{job=\"y\"}"),
Some(&every_point(300.0)),
"the filled series is not `3 * 100`: {output:?}"
);
}
/// The two inputs of a two-selector tree are distinct, so a chunk that names no input is refused
/// rather than matched as whichever operand was found first.
#[test]
fn a_two_input_tree_refuses_a_chunk_that_names_no_input() {
let compiled = compile("a{job=\"x\"} + b{job=\"x\"}");
assert_ne!(
compiled.inputs[0].path, compiled.inputs[1].path,
"the two selectors were bound to one position"
);
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
let state = NativeExecutionState::try_new(
&compiled.tree,
Arc::clone(&pool),
&ExecutionPlanMetricsSet::new(),
0,
)
.expect("the runtime executes this tree");
let mut executor = NativeExecutor::new(state);
let chunk = raw_chunk(
compiled.inputs[0].schema.as_ref(),
"a-job=x",
metric("a", &[("job", "x")]),
&[(0, 1.0)],
);
let error = executor
.push_raw(chunk)
.expect_err("a chunk that names no input was queued");
assert!(
error.to_string().contains("has 2 inputs"),
"the refusal did not say the tree reads two inputs: {error}"
);
}
/// `group_right(env)` makes the right operand the many side and copies `env` from the left one, so
/// one left series answers two right series. The fill then shows the same swap from the other end:
/// the kernel fills its many side from `fill.rhs`, and in `group_right` the many side is the right
/// operand, so a right series with no left match is answered by `fill_right` — the field named
/// after the side the fill *is* rather than the side it stands in for. That mismatch between the
/// field's name and the operand the fill becomes is the point of this case: the arithmetic itself is
/// covered by the kernel's own golden fixtures, so what is pinned here is only that the compiler put
/// `fill_right`'s value in the field the kernel reads for that side.
#[test]
fn a_group_right_swaps_the_many_side_and_fills_the_missing_one_side_sample() {
let pushes = |compiled: &CompiledTree, with_unmatched: bool| {
let mut pushes = vec![
(
0,
raw_chunk(
compiled.inputs[0].schema.as_ref(),
"a-env=prod-job=x",
metric("a", &[("env", "prod"), ("job", "x")]),
&[(0, 2.0)],
),
),
(
1,
raw_chunk(
compiled.inputs[1].schema.as_ref(),
"b-job=x-instance=i1",
metric("b", &[("instance", "i1"), ("job", "x")]),
&[(0, 10.0)],
),
),
(
1,
raw_chunk(
compiled.inputs[1].schema.as_ref(),
"b-job=x-instance=i2",
metric("b", &[("instance", "i2"), ("job", "x")]),
&[(0, 20.0)],
),
),
];
if with_unmatched {
pushes.push((
1,
raw_chunk(
compiled.inputs[1].schema.as_ref(),
"b-job=y-instance=i3",
metric("b", &[("instance", "i3"), ("job", "y")]),
&[(0, 5.0)],
),
));
}
pushes
};
// One left series, two right ones: each right series is answered and gains `env` from the left.
let unfilled = compile("a{job=\"x\"} / on(job) group_right(env) b");
let output = results(&run(&unfilled, pushes(&unfilled, true)));
assert_eq!(
output.len(),
2,
"the many side was not answered once per right series: {output:?}"
);
assert_eq!(
output.get("{env=\"prod\", instance=\"i1\", job=\"x\"}"),
Some(&every_point(0.2)),
"the first right series is not `2 / 10`: {output:?}"
);
assert_eq!(
output.get("{env=\"prod\", instance=\"i2\", job=\"x\"}"),
Some(&every_point(0.1)),
"the second right series is not `2 / 20`: {output:?}"
);
// `fill_right(100)` supplies the stand-in for the left operand: `group_right` makes the right
// operand the many side, the kernel fills that side from `fill.rhs`, and so the query writes
// `fill_right` for a sample that stands in for a missing left-hand one. The `job="y"` right
// series has no left match, so it is answered as `100 / 5` while the two matched series keep
// their own values.
let filled = compile("a{job=\"x\"} / on(job) group_right(env) fill_right(100) b");
let output = results(&run(&filled, pushes(&filled, true)));
assert_eq!(
output.len(),
3,
"`fill_right(100)` did not answer the right series with no left match: {output:?}"
);
assert_eq!(
output.get("{env=\"prod\", instance=\"i1\", job=\"x\"}"),
Some(&every_point(0.2)),
"the fill changed the first matched series: {output:?}"
);
assert_eq!(
output.get("{env=\"prod\", instance=\"i2\", job=\"x\"}"),
Some(&every_point(0.1)),
"the fill changed the second matched series: {output:?}"
);
// A fill row pairs no two series, so there is no one side to copy `env` from: `group_right`'s
// included label is removed rather than invented, which is why the filled series carries no
// `env` while its value is `100 / 5`.
assert_eq!(
output.get("{instance=\"i3\", job=\"y\"}"),
Some(&every_point(20.0)),
"the filled series is not `100 / 5`: {output:?}"
);
assert!(
!output.contains_key("{env=\"prod\", instance=\"i3\", job=\"y\"}"),
"the filled series invented the included label from the side it stands in for: {output:?}"
);
}
#[test]
fn requirements_drive_scans_for_repeated_metric_nested_windows_and_fields() {
let stmt =
eval_stmt("abs(rate(a{__field__=\"value\"}[2s])) + on() rate(a{__field__=\"other\"}[3s])");
let compiled = compile_selectors(
&stmt,
&|requirement| {
let field = requirement
.matchers
.matchers
.iter()
.find(|matcher| matcher.name == "__field__")
.map_or("value", |matcher| matcher.value.as_str());
Ok(Arc::new(SeriesSchema {
fields: Arc::new([FieldSpec { name: field.into() }]),
eval_grid: None,
}))
},
SeriesOrdering::KeyThenTime,
)
.unwrap();
assert_eq!(compiled.inputs.len(), 2);
assert_eq!(
compiled.inputs[0].requirement.metric,
compiled.inputs[1].requirement.metric
);
assert_ne!(
compiled.inputs[0].requirement.raw_scan_bounds().unwrap(),
compiled.inputs[1].requirement.raw_scan_bounds().unwrap()
);
// Each selector binds only its requested field before its selected scan rows reach the executor.
let mut pushes = Vec::new();
for (field, rows) in [
(
"value",
&[(0, 1.0), (1_000, 3.0), (2_000, 5.0), (3_000, 7.0)][..],
),
(
"other",
&[(0, 2.0), (1_000, 4.0), (2_000, 6.0), (3_000, 8.0)][..],
),
] {
for index in 0..compiled.inputs.len() {
if let Some(push) = scan_push(&compiled, index, "a", "a", &[("__field__", field)], rows)
{
pushes.push(push);
}
}
}
assert_eq!(
pushes.len(),
2,
"each field requirement selects only its own source field"
);
assert_eq!(pushes[0].0, 0);
assert_eq!(pushes[1].0, 1);
assert!(pushes.iter().all(|(_, chunk)| chunk.fields.len() == 1));
let output_chunks = run(&compiled, pushes);
let output = results(&output_chunks);
assert_eq!(
output.len(),
1,
"the same-metric windows did not match: {output:?}"
);
assert_eq!(compiled.inputs[0].schema.fields[0].name.as_ref(), "value");
assert_eq!(compiled.inputs[1].schema.fields[0].name.as_ref(), "other");
assert_eq!(output_chunks[0].series.fields.len(), 1);
assert_eq!(
output.values().next().unwrap(),
&vec![(1, 2.5), (2, 4.0), (3, 4.0)],
"the two separately scanned rates were not added: {output:?}"
);
let nested = compile("(a + b) / c");
let rows_a = [
(0, 2.0),
(1_000, 2.0),
(2_000, 2.0),
(3_000, 2.0),
(4_000, 2.0),
];
let rows_b = [
(0, 6.0),
(1_000, 6.0),
(2_000, 6.0),
(3_000, 6.0),
(4_000, 6.0),
];
let rows_c = [
(0, 4.0),
(1_000, 4.0),
(2_000, 4.0),
(3_000, 4.0),
(4_000, 4.0),
];
let pushes = [
scan_push(&nested, 0, "a", "a", &[], &rows_a).unwrap(),
scan_push(&nested, 1, "b", "b", &[], &rows_b).unwrap(),
scan_push(&nested, 2, "c", "c", &[], &rows_c).unwrap(),
];
let output = results(&run(&nested, pushes.into()));
assert_eq!(
output.len(),
1,
"nested/repeated selectors did not match: {output:?}"
);
assert_eq!(output.values().next().unwrap(), &every_point(2.0));
}
#[test]
fn compiled_comparisons_preserve_filter_and_bool_semantics() {
for (query, expected_bool) in [("a > b", false), ("a > bool b", true)] {
let compiled = compile(query);
let NativeExpr::Binary { matching, .. } = &compiled.tree.root().expr else {
panic!("`{query}` did not compile to a binary node");
};
assert_eq!(
matching.return_bool, expected_bool,
"comparison mode for `{query}`"
);
let requirement = &compiled.inputs[0].requirement;
assert_eq!(requirement.metric.as_deref(), Some("a"));
let (start, end, inclusive) = requirement.raw_scan_bounds().unwrap();
assert!(start <= 0 && end >= 4_000);
assert!(!inclusive);
let rows_a = [
(0, 1.0),
(1_000, 2.0),
(2_000, 3.0),
(3_000, 4.0),
(4_000, 5.0),
];
let rows_b = [
(0, 0.0),
(1_000, 1.0),
(2_000, 4.0),
(3_000, 2.0),
(4_000, 6.0),
];
let left = scan_push(&compiled, 0, "a", "a", &[], &rows_a).unwrap();
let right = scan_push(&compiled, 1, "b", "b", &[], &rows_b).unwrap();
let output = results(&run(&compiled, vec![left, right]));
let expected = if expected_bool {
BTreeMap::from([(
"{}".to_string(),
vec![(0, 1.0), (1, 1.0), (2, 0.0), (3, 1.0), (4, 0.0)],
)])
} else {
BTreeMap::from([(
"{__name__=\"a\"}".to_string(),
vec![(0, 1.0), (1, 2.0), (3, 4.0)],
)])
};
assert_eq!(
output, expected,
"wrong vector comparison result for `{query}`"
);
}
}
#[test]
fn ignoring_matching_uses_compiled_selectors_and_scanned_inputs() {
let compiled = compile("a{job=\"x\"} / ignoring(instance) b{job=\"x\"}");
let NativeExpr::Binary { matching, .. } = &compiled.tree.root().expr else {
panic!("the expression did not compile to a binary node");
};
assert_eq!(
matching.labels,
promql::vector_match::MatchingLabels::Ignoring(vec![Arc::from("instance")])
);
let rows = [(0, 1.0), (2_000, 2.0), (4_000, 9.0), (5_000, 12.0)];
let left = scan_push(
&compiled,
0,
"left",
"a",
&[("job", "x"), ("instance", "i1")],
&rows,
)
.unwrap();
let right = scan_push(
&compiled,
1,
"right",
"b",
&[("job", "x"), ("instance", "i2")],
&rows,
)
.unwrap();
assert_eq!(left.0, 0);
assert_eq!(right.0, 1);
assert_eq!(left.1.time.len(), 3);
assert_eq!(right.1.time.len(), 3);
let output = results(&run(&compiled, vec![left, right]));
assert_eq!(
output.len(),
1,
"ignoring matching did not pair differing instance labels: {output:?}"
);
assert_eq!(
output.values().next().unwrap(),
&vec![(0, 1.0), (1, 1.0), (2, 1.0), (3, 1.0), (4, 1.0)],
"ignoring match output did not divide the vectors: {output:?}"
);
assert!(scan_push(&compiled, 0, "wrong-metric", "b", &[("job", "x")], &rows).is_none());
assert!(scan_push(&compiled, 0, "wrong-matcher", "a", &[("job", "y")], &rows).is_none());
}
#[test]
fn historical_range_sources_are_not_clipped_to_the_statement_start() {
let stmt = promql_parser::parser::EvalStmt {
expr: promql_parser::parser::parse("sum_over_time(a[2s]) + sum_over_time(a[3s])").unwrap(),
start: UNIX_EPOCH,
end: UNIX_EPOCH,
interval: Duration::from_secs(1),
lookback_delta: Duration::from_secs(5),
};
let compiled =
compile_selectors(&stmt, &|_| Ok(raw_schema()), SeriesOrdering::KeyThenTime).unwrap();
assert_eq!(compiled.inputs.len(), 2);
let rows = [(-2_500, 10.0), (-1_500, 20.0), (-500, 30.0)];
let short = scan_push(&compiled, 0, "a-short", "a", &[], &rows).unwrap();
let long = scan_push(&compiled, 1, "a-long", "a", &[], &rows).unwrap();
assert_eq!(short.1.time.len(), 2);
assert_eq!(long.1.time.len(), 3);
let output = results(&run(&compiled, vec![short, long]));
assert_eq!(
output,
BTreeMap::from([("{}".to_string(), vec![(0, 110.0)])]),
"historical range samples were clipped or a selector reused the other window"
);
}