diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index 6afaa9be5cb..6db212c336e 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -25,6 +25,7 @@ //! ([, ]*) e.g. abs(rate(x[5m])), clamp_min(x, 0) //! e.g. x * 100, x > bool 0 //! e.g. 1 / x, 0 < x +//! e.g. a + b, a / on(job) group_left(env) b //! - e.g. -x //! ``` //! @@ -55,11 +56,22 @@ //! its own: `-x` binds as the multiplication by `-1` that it is, which the multiplication kernel //! already computes. //! -//! What a tree cannot yet express is deliberate too. The one input binding carries the ordering it -//! guarantees and what it produces, but not the selector it reads, so a tree with two selectors -//! cannot tell its inputs apart and an operation between two vectors is refused. A statement whose -//! value is a scalar has nothing to read, so it is refused as well: a constant is bound next to a -//! vector that gives it something to broadcast over. +//! What a tree cannot yet express is deliberate too. A statement whose value is a scalar has +//! nothing to read, so it is refused: a constant is bound next to a vector that gives it something +//! to broadcast over. A set operator combines two vectors' series rather than their values, and the +//! tree has no node for it, so `and`, `or` and `unless` are refused as the set operators they are. +//! +//! A tree with two selectors reads two inputs, and each one is bound to the selector it was +//! compiled from: [`CompiledInput`] carries the selector's [`SelectorRequirement`] (its metric, its +//! matchers, its offset and its anchor) beside the layout the caller said it would feed and the +//! position the executor names it by. That is what makes `a + b` and `a + a` different trees, and +//! it is why a vector–vector operation is an ordinary node: the two operands read different +//! selectors, and [`BinaryMatching`] says how their series pair up. +//! +//! The position an input is named by is not written down here. [`promql::native::metrics::walk`] +//! is the one traversal rule that gives every node its position, and the executor builds its state +//! from the same walk, so [`compile_selectors`] reads each input's path from that walk rather than +//! re-deriving it: a node kind added later cannot make the two copies disagree. //! //! The statement's grid, the selector's lookback, window, offset and anchor are the only numbers //! derived here; the legality of the tree is not checked here. [`NativeTree::try_new`] is the @@ -68,6 +80,7 @@ //! chunks of different series that interleave, so an `Interleaved` ordering is refused once, at the //! entry, and [`NativeNode::validate`] refuses the same ordering for a tree built some other way. +use std::cell::RefCell; use std::sync::Arc; use std::time::Duration; @@ -76,17 +89,21 @@ use datatypes::series::SeriesOrdering; use datatypes::series::samples::SeriesSchema; use datatypes::series::time::{EvalGrid, GridSpec}; use promql::map::{ArithmeticOp, MathOp}; +use promql::native::metrics::{self, NodePath}; use promql::native::plan::{ BoundInput, BoundInstant, BoundMap, BoundScalar, BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, }; use promql::range_eval::{RangeFunction, RangeWindow}; -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::Matchers; use promql_parser::parser::token::TokenType; use promql_parser::parser::value::ValueType; use promql_parser::parser::{ - AtModifier, BinaryExpr, Call, EvalStmt, Expr as PromExpr, MatrixSelector, NumberLiteral, - Offset, VectorMatchCardinality, VectorMatchFillValues, VectorSelector, token, + AtModifier, BinaryExpr, Call, EvalStmt, Expr as PromExpr, LabelModifier, MatrixSelector, + NumberLiteral, Offset, VectorMatchCardinality, VectorMatchFillValues, VectorSelector, token, }; use crate::promql::label_values::signed_millis_since_epoch; @@ -95,10 +112,40 @@ use crate::promql::label_values::signed_millis_since_epoch; const SUPPORTED: &str = "a selector, a range function over a range selector — \ `([])`, with its constants in front of \ the selector as in `quantile_over_time(0.9, x[5m])` — a math function over \ - any of them, a binary operation between one of them and a constant, or a \ - negation of one of them, as in `x`, `rate(x[5m])`, \ - `quantile_over_time(0.9, x[5m])`, `abs(rate(x[5m]))`, `2 / (x + 1)` or \ - `-x`"; + any of them, a binary operation between two of them or between one of them \ + and a constant, or a negation of one of them, as in `x`, `rate(x[5m])`, \ + `quantile_over_time(0.9, x[5m])`, `abs(rate(x[5m]))`, `2 / (x + 1)`, \ + `a / on(job) b` or `-x`"; + +/// What one selector asks a scan for, apart from the layout it is bound to. +/// +/// The statement contributes the grid and the lookback, which every selector of one query shares; +/// what differs per selector is which series it names and how it shifts their time axis. +#[derive(Clone, Debug)] +pub struct SelectorRequirement { + pub metric: Option, + pub matchers: Matchers, + pub offset_ms: i64, + pub at_ms: Option, +} + +/// One input a compiled tree reads, and the selector it was bound to. +#[derive(Clone, Debug)] +pub struct CompiledInput { + /// The position the executor names this input by; `push_raw_at` takes it. + pub path: NodePath, + pub requirement: SelectorRequirement, + /// The layout the caller said it will feed for this selector. + pub schema: Arc, + pub ordering: SeriesOrdering, +} + +/// A tree together with the inputs it reads. +#[derive(Clone, Debug)] +pub struct CompiledTree { + pub tree: NativeTree, + pub inputs: Arc<[CompiledInput]>, +} /// Compiles `stmt` into a tree that reads `input` and evaluates the statement's expression over it. /// @@ -110,23 +157,40 @@ const SUPPORTED: &str = "a selector, a range function over a range selector — /// `rate(x{__field__="a"}[5m])` over fields `[a, b]` would fold two fields where the planner folds /// one. /// -/// `ordering` is what the caller's scan guarantees, and the tree records it rather than assuming -/// one. Only `Contiguous` and `KeyThenTime` are accepted: every shape this compiler accepts reads -/// one series to its last chunk before the next, so an `Interleaved` declaration is refused at the -/// entry, before any shape is built — the bare selector included, which returns before a window -/// exists — and a shape added later inherits the refusal instead of restating it. -/// [`NativeNode::validate`] refuses the same ordering in its `Instant` and `Window` branches, as a -/// 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 with two inputs will need each `Input` to name its -/// selector. +/// Every selector is bound to that one layout. A query whose selectors are fed by different layouts, +/// and a caller that has to know which input belongs to which selector, calls [`compile_selectors`] +/// instead; this function keeps its signature for the callers that read one input, and drops the +/// inputs it bound. pub fn compile( stmt: &EvalStmt, input: Arc, ordering: SeriesOrdering, ) -> Result { + compile_selectors(stmt, &|_selector| Ok(Arc::clone(&input)), ordering) + .map(|compiled| compiled.tree) +} + +/// Compiles `stmt` into a tree and the inputs it reads, binding each selector through `bindings`. +/// +/// `bindings` answers what a scan of one selector produces, so two selectors of one query may be fed +/// differently shaped samples. It is a plain callback: the answer depends on the selector and on +/// what the caller already holds, and there is no state of the compiler's to keep between calls. +/// `ordering` is what the caller's scan guarantees for every one of them, and each input records it +/// rather than assuming one. Only `Contiguous` and `KeyThenTime` are accepted: every shape this +/// compiler accepts reads one series to its last chunk before the next, so an `Interleaved` +/// declaration is refused at the entry, before any shape is built — the bare selector included, +/// which returns before a window exists — and a shape added later inherits the refusal instead of +/// restating it. [`NativeNode::validate`] refuses the same ordering in its `Instant` and `Window` +/// branches, as a backstop for a tree built some other way. +/// +/// The inputs come back in the order they were bound, which is the executor's visit order: left +/// before right. Their paths are [`promql::native::metrics::walk`]'s, read from the finished tree, +/// so the position a caller pushes a chunk at is the position the executor names that input by. +pub fn compile_selectors( + stmt: &EvalStmt, + bindings: &dyn Fn(&VectorSelector) -> Result>, + ordering: SeriesOrdering, +) -> Result { // Every shape this compiler accepts reads one series to its last chunk before the next, so raw // samples whose chunks of different series interleave cannot be fed to any of them. The refusal // is here rather than in a shape's branch so that a shape added later inherits it. @@ -151,27 +215,86 @@ pub fn compile( } let context = Context { stmt, - input, + bindings, ordering, + inputs: RefCell::new(Vec::new()), }; // The whole tree is validated once, here: a node compiled as another node's input is checked as // part of the tree rather than on its own, so the same node cannot be legal in one place and // illegal in another. - NativeTree::try_new(compile_expr(&context, &stmt.expr)?) + let tree = NativeTree::try_new(compile_expr(&context, &stmt.expr)?)?; + let bound = context.inputs.into_inner(); + let inputs = name_inputs(&tree, bound)?; + Ok(CompiledTree { + tree, + inputs: inputs.into(), + }) +} + +/// The inputs `tree` reads, each named by the position the executor names it by. +/// +/// Both orders are the same pre-order walk — a binary operation compiles its left operand before its +/// right, and [`metrics::walk`] descends left before right — so the inputs a compilation bound in +/// order name the input nodes in order. A count that disagrees is a compiler defect, which is why it +/// is reported as one instead of zipping whatever there is. +fn name_inputs(tree: &NativeTree, bound: Vec) -> Result> { + let bound_count = bound.len(); + let mut bound = bound.into_iter(); + let mut named = 0usize; + let mut inputs = Vec::new(); + metrics::walk(tree.root(), &mut |node, path| { + if matches!(&node.expr, NativeExpr::Input(_)) { + named += 1; + if let Some(input) = bound.next() { + inputs.push(CompiledInput { + path: path.clone(), + requirement: input.requirement, + schema: input.schema, + ordering: input.ordering, + }); + } + } + }); + if named != bound_count { + return Err(input_count_mismatch(bound_count, named)); + } + Ok(inputs) +} + +/// The rejection of a tree whose input nodes and bound selectors do not line up. +fn input_count_mismatch(bound: usize, named: usize) -> DataFusionError { + DataFusionError::Internal(format!( + "the native compiler bound {bound} selector(s) but the tree has {named} input node(s): \ + every selector compiles to an input node, so the two walks disagree" + )) +} + +/// One input as it is bound, before the tree's walk gives it its position. +/// +/// A selector is compiled where its subtree is built, and the position it lands at is only known +/// once the whole tree exists, so the path is added by [`name_inputs`] rather than guessed here. +struct PendingInput { + requirement: SelectorRequirement, + schema: Arc, + ordering: SeriesOrdering, } /// What every node of one compilation derives from the statement rather than from the expression. /// -/// The three are the same for the whole tree: one statement decides the grid, the lookback and the -/// anchors, one caller binds the raw input, and one scan guarantees the ordering. Passing them as -/// one value is what lets [`compile_expr`] recurse without restating what it was handed. +/// The same for the whole tree: one statement decides the grid, the lookback and the anchors, one +/// caller binds every selector's layout, and one scan guarantees the ordering. The inputs it bound +/// are collected here, because a selector is compiled where its subtree is built rather than at the +/// top. Passing these as one value is what lets [`compile_expr`] recurse without restating what it +/// was handed. struct Context<'a> { /// The statement being compiled. stmt: &'a EvalStmt, - /// The raw series the caller bound; shared by every input node rather than copied per node. - input: Arc, + /// The layout to feed each selector in, asked once per selector. + bindings: &'a dyn Fn(&VectorSelector) -> Result>, /// The ordering the caller's scan guarantees. ordering: SeriesOrdering, + /// The inputs bound so far, in the order they were bound. + inputs: RefCell>, } /// Compiles `expr` into the node it denotes, recursing into whatever it is made of. @@ -229,13 +352,12 @@ fn negate(context: &Context, operand: &PromExpr) -> Result { )) } -/// Compiles a binary operation whose operands are not both vectors. +/// Compiles a binary operation over its two operands. /// -/// The tree holds one input binding, and that binding carries the ordering it guarantees and what it -/// produces but not the selector it reads, so two vectors cannot be told apart: `a + b` and `a + a` -/// would compile to the same tree. That is why a vector–vector operation is refused until an input -/// names its selector, and why an operation over one vector and one scalar is the shape the tree can -/// bind: a scalar carries no labels, so broadcasting it is unambiguous. +/// Two vectors are an ordinary node: each operand is compiled from its own selector, so the two +/// inputs are told apart by which selector they were bound to, and [`vector_matching`] binds the +/// modifiers the query wrote. A vector and a constant is a broadcast instead — a scalar carries no +/// labels, so there is nothing to match and [`broadcast`] is the node. fn binary_operation(context: &Context, binary: &BinaryExpr) -> Result { // A set operator combines two vectors' series rather than their values, and the tree has no node // for it at all. Its name is reported before the operands are looked at, so a set operation @@ -255,22 +377,40 @@ fn binary_operation(context: &Context, binary: &BinaryExpr) -> Result Result Result { + 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, field for field. That is a name-preserving copy + // and nothing more: it does not say that `fill_left` always stands in for the original left + // operand. 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 rather than by which operand was + // written first: `fill.rhs` answers a many-side series that found no match, standing in for the + // missing one-side sample, and `fill.lhs` answers a one-side series that found no match, + // standing in for the missing many-side sample. The default and `group_left` make the many side + // the left operand; `group_right` swaps them, so there `fill_right` fills a missing left-hand + // sample and `fill_left` a missing right-hand one. [`FillValues`] states the same thing. + 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> { + labels.iter().map(|name| Arc::from(name.as_str())).collect() +} + /// Wraps two compiled operands in the binary node that applies `op` to them. /// /// The output is the vector side's own binding, because a scalar carries no fields: a broadcast keeps @@ -476,15 +680,25 @@ fn window_selection( let output_grid = statement_grid(context.stmt)?; // A range function reports one value per input field, so the layout is the input's. + let raw_schema = bind_selector( + context, + vs, + SelectorRequirement { + metric: vs.name.clone(), + matchers: vs.matchers.clone(), + offset_ms, + at_ms: anchor_ms, + }, + )?; let output = NativeType::Samples(Arc::new(SeriesSchema { - fields: Arc::clone(&context.input.fields), + fields: Arc::clone(&raw_schema.fields), eval_grid: Some(Arc::clone(&output_grid)), })); // One allocation shared by the binding and the node's output: `NativeTree::try_new` compares // them by identity, because a compiler that meant one schema has no reason to allocate it // twice. - let raw = NativeType::Samples(Arc::clone(&context.input)); + let raw = NativeType::Samples(Arc::clone(&raw_schema)); Ok(NativeNode { expr: NativeExpr::Window { @@ -531,13 +745,24 @@ fn instant_selection(context: &Context, selector: &VectorSelector) -> Result Result Result> { + let schema = (context.bindings)(selector)?; + context.inputs.borrow_mut().push(PendingInput { + requirement, + schema: Arc::clone(&schema), + ordering: context.ordering, + }); + Ok(schema) +} + /// The grid the statement is evaluated on: `(end - start) / step + 1` points, the last of which /// does not pass `end`. fn statement_grid(stmt: &EvalStmt) -> Result> { diff --git a/src/query/src/promql/native_compile/tests.rs b/src/query/src/promql/native_compile/tests.rs index af07850e19b..5e94eccad15 100644 --- a/src/query/src/promql/native_compile/tests.rs +++ b/src/query/src/promql/native_compile/tests.rs @@ -15,20 +15,21 @@ use std::sync::Arc; use std::time::{Duration, UNIX_EPOCH}; -use datafusion::error::DataFusionError; +use datafusion::error::{DataFusionError, Result}; use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; use promql::map::MathOp; +use promql::native::metrics::NodePath; use promql::native::plan::{ BoundInstant, BoundMap, BoundWindow, NativeExpr, NativeNode, NativeTree, NativeType, }; use promql::range_eval::RangeFunction; -use promql::vector_match::{BinaryMatching, BinaryOp}; +use promql::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels}; use promql_parser::parser::{ - BinModifier, EvalStmt, Expr as PromExpr, NumberLiteral, VectorMatchFillValues, + BinModifier, EvalStmt, Expr as PromExpr, NumberLiteral, VectorMatchFillValues, VectorSelector, }; -use super::compile; +use super::{CompiledTree, compile, compile_selectors}; /// The raw series schema a caller binds from the table: one field and no evaluation grid. fn raw_schema() -> Arc { @@ -1489,31 +1490,27 @@ 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. +/// An operation between two vectors is an ordinary node now that each input names the selector it +/// was bound to: the shapes that used to be refused for the missing identity compile, and each one +/// binds one input per selector it reads. #[test] -fn an_operation_between_two_vectors_is_refused_for_the_missing_selector_identity() { +fn an_operation_between_two_vectors_binds_one_input_per_selector() { for query in [ "a + b", "a > b", "rate(a[5m]) * rate(b[5m])", "abs(a) + abs(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}" + let compiled = compile_selectors( + &eval_stmt(query), + &one_schema(raw_schema()), + SeriesOrdering::KeyThenTime, + ) + .unwrap_or_else(|error| panic!("`{query}` was refused: {error}")); + assert_eq!( + input_metrics(&compiled), + vec![Some("a".to_string()), Some("b".to_string())], + "`{query}` did not bind one input per selector" ); } } @@ -1647,3 +1644,292 @@ fn the_batch_acceptance_queries_compile() { ); } } + +/// A raw series layout of one field named `name`. +/// +/// Two of these differ in the field they produce, which is the only difference a binding can have +/// while both selectors read raw samples. +fn raw_schema_of_field(name: &str) -> Arc { + Arc::new(SeriesSchema { + fields: Arc::new([FieldSpec { name: name.into() }]), + eval_grid: None, + }) +} + +/// The layout every selector is fed in when the query reads only one: `schema`, whatever was asked. +/// +/// This is what [`compile`] answers for every selector, and the tests that only care about one +/// layout use it so the callback does not have to be written out at each call site. +fn one_schema(schema: Arc) -> impl Fn(&VectorSelector) -> Result> { + move |_selector| Ok(Arc::clone(&schema)) +} + +/// 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 metric each bound input records, in the order the inputs were bound. +fn input_metrics(compiled: &CompiledTree) -> Vec> { + compiled + .inputs + .iter() + .map(|input| input.requirement.metric.clone()) + .collect() +} + +/// `a + b`: two selectors bound two inputs, each at the position its own operand gives it, and each +/// recording the selector it was bound to. The operation itself is an ordinary vector–vector node +/// whose matching is the default: every label but `__name__` matches, one series to one. +#[test] +fn two_selectors_bind_two_inputs_named_by_their_operands() { + let compiled = compile_selectors( + &eval_stmt("a + b"), + &one_schema(raw_schema()), + SeriesOrdering::KeyThenTime, + ) + .unwrap_or_else(|error| panic!("`a + b` was refused: {error}")); + + // One input per selector, in the order the executor visits them: left before right. + let inputs = &compiled.inputs; + assert_eq!( + inputs.len(), + 2, + "`a + b` did not bind one input per selector: {inputs:?}" + ); + assert_eq!( + inputs[0].path, + NodePath::root().left().input(), + "the left selector is not bound where its operand's input sits" + ); + assert_eq!( + inputs[1].path, + NodePath::root().right().input(), + "the right selector is not bound where its operand's input sits" + ); + assert_eq!( + input_metrics(&compiled), + vec![Some("a".to_string()), Some("b".to_string())], + "the inputs did not record the selectors they were bound to" + ); + for input in inputs.iter() { + assert_eq!(input.ordering, SeriesOrdering::KeyThenTime); + assert_eq!(input.requirement.offset_ms, 0, "the selector has no offset"); + assert_eq!(input.requirement.at_ms, None, "the selector has no anchor"); + assert!(input.schema.eval_grid.is_none(), "the input is not raw"); + } + + assert!( + matches!(&compiled.tree.root().expr, NativeExpr::Binary { .. }), + "`a + b` did not compile to a binary node: {:?}", + compiled.tree.root().expr + ); + let (_, _, matching) = binary_parts(compiled.tree.root()); + assert_eq!(matching.op, BinaryOp::Add); + assert_eq!( + matching_labels(&matching.labels), + (false, Vec::new()), + "the default matching is not `ignoring` nothing, which matches on every label but the name" + ); + assert_eq!(matching_cardinality(&matching.cardinality).0, "one-to-one"); + assert_eq!( + matching.fill, + FillValues::default(), + "a query without a fill binds no fill value" + ); + assert!(!matching.return_bool, "`+` is not a comparison"); +} + +/// `a / on(job) b` matches on the one label it names. The default matches on every label but +/// `__name__`, so binding `on` as `ignoring` (or dropping it) would match series the query did not +/// ask to match. +#[test] +fn an_on_matching_binds_the_labels_it_names() { + let compiled = compile_selectors( + &eval_stmt("a / on(job) b"), + &one_schema(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 would compute 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"), + &one_schema(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`" + ); +} + +/// `fill_left` fills a sample of the left side, so it binds [`FillValues::lhs`] and leaves the right +/// one empty. The two fields are asserted apart because the kernel reads them apart, and a binding +/// that swapped them would compute the fill of the other side. +#[test] +fn fill_left_binds_the_left_fill_value() { + let compiled = compile_selectors( + &eval_stmt("a + fill_left(0) b"), + &one_schema(raw_schema()), + SeriesOrdering::KeyThenTime, + ) + .unwrap_or_else(|error| panic!("`a + fill_left(0) b` was refused: {error}")); + + let (_, _, matching) = binary_parts(compiled.tree.root()); + assert_eq!( + matching.fill.lhs, + Some(0.0), + "`fill_left(0)` did not bind the left fill value" + ); + assert_eq!( + matching.fill.rhs, None, + "`fill_left(0)` bound a right fill value the query did not write" + ); +} + +/// `fill_right` fills a sample of the right side, so it binds [`FillValues::rhs`]. The value is +/// asserted exactly, because a fill is a number the query wrote rather than one this compiler may +/// round. +#[test] +fn fill_right_binds_the_right_fill_value() { + let compiled = compile_selectors( + &eval_stmt("a + fill_right(1.5) b"), + &one_schema(raw_schema()), + SeriesOrdering::KeyThenTime, + ) + .unwrap_or_else(|error| panic!("`a + fill_right(1.5) b` was refused: {error}")); + + let (_, _, matching) = binary_parts(compiled.tree.root()); + assert_eq!( + matching.fill.rhs, + Some(1.5), + "`fill_right(1.5)` did not bind the right fill value" + ); + assert_eq!( + matching.fill.lhs, None, + "`fill_right(1.5)` bound a left fill value the query did not write" + ); +} + +/// `fill` stands for both sides, so both fields carry it. Binding one of them would fill one side +/// and drop the other's samples, which is a different query. +#[test] +fn fill_binds_both_fill_values() { + let compiled = compile_selectors( + &eval_stmt("a + fill(2) b"), + &one_schema(raw_schema()), + SeriesOrdering::KeyThenTime, + ) + .unwrap_or_else(|error| panic!("`a + fill(2) b` was refused: {error}")); + + let (_, _, matching) = binary_parts(compiled.tree.root()); + assert_eq!(matching.fill.lhs, Some(2.0), "`fill(2)` left the lhs empty"); + assert_eq!(matching.fill.rhs, Some(2.0), "`fill(2)` left the rhs empty"); +} + +/// Every selector is bound through the callback, so two selectors of one query may be fed +/// differently shaped samples: each input reports the layout its own selector asked for, and the +/// requirement beside it names the series and the matchers that selector wrote. +#[test] +fn each_selector_is_bound_to_the_layout_it_asked_for() { + let (left, right) = ( + raw_schema_of_field("left_value"), + raw_schema_of_field("right_value"), + ); + // One layout per metric name, so a selector bound to the wrong one is visible: a callback that + // answered the same schema for both would fail the assertions below. + let bindings = |selector: &VectorSelector| match selector.name.as_deref() { + Some("a") => Ok(Arc::clone(&left)), + Some("b") => Ok(Arc::clone(&right)), + other => panic!("the fixture has no layout for the selector `{other:?}`"), + }; + let compiled = compile_selectors( + &eval_stmt("a{job=\"left\"} + b{job=\"right\"}"), + &bindings, + SeriesOrdering::KeyThenTime, + ) + .unwrap_or_else(|error| { + panic!("`a{{job=\"left\"}} + b{{job=\"right\"}}` was refused: {error}") + }); + + assert_eq!(compiled.inputs.len(), 2); + // The binding is the one the callback answered for that selector, not a copy of the other's. + assert!( + Arc::ptr_eq(&compiled.inputs[0].schema, &left), + "the left selector was not bound to the layout it asked for" + ); + assert!( + Arc::ptr_eq(&compiled.inputs[1].schema, &right), + "the right selector was not bound to the layout it asked for" + ); + assert_eq!( + compiled.inputs[0].schema.fields[0].name.as_ref(), + "left_value" + ); + assert_eq!( + compiled.inputs[1].schema.fields[0].name.as_ref(), + "right_value" + ); + + // The requirement beside each binding is the selector's own: its metric and its matchers. + assert_eq!( + input_metrics(&compiled), + vec![Some("a".to_string()), Some("b".to_string())] + ); + for (input, value) in compiled.inputs.iter().zip(["left", "right"]) { + let matchers: Vec<&str> = input + .requirement + .matchers + .matchers + .iter() + .map(|matcher| matcher.value.as_str()) + .collect(); + assert_eq!( + matchers, + vec![value], + "the input did not record the matchers its selector wrote" + ); + } +} diff --git a/src/query/tests/native_multi_selector.rs b/src/query/tests/native_multi_selector.rs new file mode 100644 index 00000000000..0b73c8b77a7 --- /dev/null +++ b/src/query/tests/native_multi_selector.rs @@ -0,0 +1,573 @@ +// 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_parser::parser::VectorSelector; +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 { + 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 = |_selector: &VectorSelector| 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 = rows.iter().map(|&(time, _)| time).collect(); + let values: Vec = 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") +} + +/// 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 { + let pool: Arc = 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> { + let mut output: BTreeMap> = 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 = 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:?}" + ); +}