From b948fb78b193da4b438c23a3e3e74c5276694c19 Mon Sep 17 00:00:00 2001 From: discord9 Date: Mon, 23 Nov 2026 08:59:55 +0000 Subject: [PATCH] fix(promql): plan absent_over_time over a nameless multi-metric selector (#10512) `absent_over_time({job="x"}[20m])` was declined by the native route, and the plan it fell back to answers with an error, so the shape produced no answer at all: the existing planner needs one `__name__` equality matcher to read a table from (`Expect a metric matcher, but not found`). The guard that declined it assumed that a nameless selector's tree declares `__name__` while binding no metric name, and that the fused node refuses such a tree. That is not the shape: a discovered selector's prepared input is the `Union` of one `RawSeriesSource` per metric, so the node is handed explicit-label frames, and only its bare-region-scan arm reads the binding's name - an arm a nameless selector never reaches, because a successful scan always binds one metric. A statement such as `sum by (__name__) ({tag_0="x"})` over discovered metrics already builds and runs exactly this combination. The guard now declines only a nameless input that is not already sourced, which keeps the bare-scan arm closed if that invariant ever regresses. The presence fold keeps the metric name, so two metrics sharing ordinary labels stay two series and `absent` answers the empty vector, as Prometheus does; a fold that dropped the name would have folded them into one series and answered wrongly. `is_sourced_plan` is the existing predicate factored out of the child mapping, so the guard and the mapping ask the same question. `FusedSeriesBinding::metric_name`'s doc no longer claims the logical node requires a name whenever `tags` declares `__name__`; the requirement belongs to the bare-scan arm of the physical planner. A statement that mixes a multi-metric discovery with a single-metric selector was admitted and then failed at physical planning: `build_inner_segment`'s multi-source arm wrapped every prepared plan in a new `RawSeriesSource`, including plans that were already sources, and built `RawSeriesSource(RawSeriesSource(TableScan))`, which the physical planner refuses after the statement has been committed to this route. The arm now hands an already-sourced plan to the segment as it is and wraps only real table scans (`is_sourced_plan`). Regression: `absent_over_time({job="api"}[5m]) or ({probe_label="y"} + on(job) absent_a)` was unanswerable before that fix and now runs a `FusedSeriesExec` and answers `(120000, {job="api"}, 7.0)` and `(400000, {job="api"}, 1.0)`. Not changed: a statement whose discovered table is partitioned still declines, because `remote_raw_boundary` skips this builder and the alternative does not recognise a `Union`. Signed-off-by: discord9 --- src/promql/src/extension_plan/fused_series.rs | 9 +- src/promql/src/extension_plan/planner.rs | 187 +++++++++++++++++- src/promql/src/native/segment.rs | 28 ++- src/query/src/promql/planner/native.rs | 50 +++-- src/query/src/promql/planner/test.rs | 79 ++++++-- tests-integration/src/tests/promql_test.rs | 149 +++++++++++--- 6 files changed, 435 insertions(+), 67 deletions(-) diff --git a/src/promql/src/extension_plan/fused_series.rs b/src/promql/src/extension_plan/fused_series.rs index db71f3b3c98..e92d8a05f24 100644 --- a/src/promql/src/extension_plan/fused_series.rs +++ b/src/promql/src/extension_plan/fused_series.rs @@ -150,9 +150,12 @@ pub struct FusedSeriesBinding { pub grid: Arc, /// The metric name every input series is bound to, when the input reads one named metric. /// - /// The logical node requires it when [`tags`](Self::tags) declares [`METRIC_NAME`]: a reader of - /// the output has to be able to tell that a range function dropped the name, which needs a name - /// to drop. The physical node takes the names from the frames, which carry each series' own. + /// The requirement that a binding naming [`METRIC_NAME`] among [`tags`](Self::tags) also declares + /// this name belongs to the bare-scan arm of `plan_fused_series`, not to this node: a child that + /// is a region scan is asked for the series of this one metric, while a child that already + /// produces raw frames - a discovered selector's `RawSeriesSource`, or the union of them - names + /// each series in its own labels and is accepted with `None` here. A reader of the output still + /// sees which range functions dropped the name, which needs no binding. pub metric_name: Option>, /// The output column holding the grid timestamps. pub time_index: String, diff --git a/src/promql/src/extension_plan/planner.rs b/src/promql/src/extension_plan/planner.rs index 4a5ec7b20f7..d31b6c3dddc 100644 --- a/src/promql/src/extension_plan/planner.rs +++ b/src/promql/src/extension_plan/planner.rs @@ -327,18 +327,36 @@ fn explicit_label_frame_ordering(schema: &Schema) -> Option { #[cfg(test)] mod tests { + use std::fmt::{self, Formatter}; use std::sync::Arc; + use common_error::ext::BoxedError; use common_query::series_frame::{ raw_series_frame_schema_with_ordering, series_frame_ordering, }; + use common_recordbatch::{EmptyRecordBatchStream, SendableRecordBatchStream}; + use datafusion::common::DFSchema; + use datafusion::logical_expr::{EmptyRelation, LogicalPlan}; use datafusion::physical_plan::ExecutionPlan; use datafusion::physical_plan::empty::EmptyExec; + use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet; use datafusion::physical_plan::union::UnionExec; + use datafusion::physical_plan::{DisplayAs, DisplayFormatType}; + use datatypes::prelude::ConcreteDataType; + use datatypes::schema::{ColumnSchema, SchemaRef as DatatypesSchemaRef}; use datatypes::series::SeriesOrdering; use datatypes::series::samples::{FieldSpec, SeriesSchema}; + use datatypes::series::time::{EvalGrid, GridSpec}; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef}; + use store_api::region_engine::{ + PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties, + }; + use store_api::storage::{RegionId, ScanRequest}; + use table::table::scan::RegionScanExec; - use super::normalize_raw_union; + use super::{METRIC_NAME, normalize_raw_union, plan_fused_series}; + use crate::extension_plan::{FusedSeries, FusedSeriesBinding}; + use crate::native::plan::{BoundInput, NativeExpr, NativeNode, NativeTree, NativeType}; fn raw_frame(ordering: SeriesOrdering) -> Arc { let series = SeriesSchema { @@ -399,4 +417,171 @@ mod tests { "nothing is lowered when every member is complete" ); } + + /// A region whose only column is the time index: the scan below publishes an ordinary region + /// schema, not a series frame. + fn region_metadata() -> RegionMetadataRef { + let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 1)); + builder + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ) + .with_time_index(true), + semantic_type: api::v1::SemanticType::Timestamp, + column_id: 1, + }) + .primary_key(vec![]); + Arc::new(builder.build().expect("the fixture metadata is valid")) + } + + /// The scanner of [`bare_region_scan`], which never answers a chunk here. + #[derive(Debug)] + struct BareScanner { + metadata: RegionMetadataRef, + properties: ScannerProperties, + } + + impl DisplayAs for BareScanner { + fn fmt_as(&self, _format: DisplayFormatType, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "BareScanner") + } + } + + impl RegionScanner for BareScanner { + fn name(&self) -> &str { + "BareScanner" + } + + fn properties(&self) -> &ScannerProperties { + &self.properties + } + + fn schema(&self) -> DatatypesSchemaRef { + Arc::clone(&self.metadata.schema) + } + + fn metadata(&self) -> RegionMetadataRef { + Arc::clone(&self.metadata) + } + + fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> { + self.properties.prepare(request); + Ok(()) + } + + fn scan_partition( + &self, + _ctx: &QueryScanContext, + _metrics: &ExecutionPlanMetricsSet, + _partition: usize, + ) -> Result { + Ok(Box::pin(EmptyRecordBatchStream::new(Arc::clone( + &self.metadata.schema, + )))) + } + + fn set_logical_region(&mut self, logical_region: bool) { + self.properties.set_logical_region(logical_region); + } + + fn set_query_load_region_id(&mut self, region_id: RegionId) { + self.properties.set_query_load_region_id(region_id); + } + + fn has_predicate_without_region(&self) -> bool { + true + } + + fn add_dyn_filter_to_predicate( + &mut self, + filter_exprs: Vec>, + ) -> Vec { + vec![false; filter_exprs.len()] + } + } + + /// A bare region scan: the input of a node that runs inside the region it reads. + fn bare_region_scan() -> Arc { + let scanner = BareScanner { + metadata: region_metadata(), + properties: ScannerProperties::default(), + }; + Arc::new( + RegionScanExec::new(Box::new(scanner), ScanRequest::default(), None) + .expect("the fixture scanner scans"), + ) + } + + /// The compiled tree a region-local node runs: one source, evaluated on the statement grid. + fn one_source_tree() -> (NativeTree, Arc) { + let grid = Arc::new( + EvalGrid::try_new(GridSpec::try_new(0, 60_000, 2).expect("the grid spec is legal")) + .expect("the grid is legal"), + ); + let samples = NativeType::Samples(Arc::new(SeriesSchema { + fields: vec![FieldSpec { + name: Arc::from("val"), + }] + .into(), + eval_grid: Some(Arc::clone(&grid)), + })); + let tree = NativeTree::try_new(NativeNode { + expr: NativeExpr::Input(BoundInput { + output: samples.clone(), + source_index: 0, + ordering: SeriesOrdering::Contiguous, + }), + output: samples, + }) + .expect("the fixture tree is legal"); + (tree, grid) + } + + /// The narrowed admission guard's premise: the bare-scan arm still needs the binding's own + /// metric name, because it asks a region scan for the series of that one metric. + /// + /// A discovered selector never reaches that arm - its prepared input is a `Union` of raw sources + /// that each name the metric they read - so this refusal only has to hold for a scan. + #[test] + fn a_bare_region_scan_without_a_bound_metric_name_is_refused() { + let (tree, grid) = one_source_tree(); + let node = FusedSeries::try_new( + Arc::from(r#"absent_over_time({job="api"}[5m])"#), + tree, + FusedSeriesBinding { + grid, + metric_name: None, + time_index: "time".to_string(), + tags: vec![METRIC_NAME.to_string()], + }, + vec![LogicalPlan::EmptyRelation(EmptyRelation { + produce_one_row: false, + schema: Arc::new( + DFSchema::try_from(raw_frame(SeriesOrdering::Contiguous).as_ref().clone()) + .expect("the frame is a legal schema"), + ), + })], + Arc::new( + DFSchema::try_from(datafusion::arrow::datatypes::Schema::new(vec![ + datafusion::arrow::datatypes::Field::new( + "val", + datafusion::arrow::datatypes::DataType::Float64, + true, + ), + ])) + .expect("the output is a legal schema"), + ), + ) + .expect("one source binds one child"); + assert_eq!(1, node.children().len(), "the node has its one input"); + let error = plan_fused_series(&node, &[bare_region_scan()], 4) + .expect_err("a region scan has no series to answer without the bound name"); + assert!( + error.to_string().contains("binds no metric name"), + "the refusal names what is missing: {error}" + ); + } } diff --git a/src/promql/src/native/segment.rs b/src/promql/src/native/segment.rs index d3dd151ad19..fd3aa799b82 100644 --- a/src/promql/src/native/segment.rs +++ b/src/promql/src/native/segment.rs @@ -730,6 +730,19 @@ fn is_raw_series_source(plan: &LogicalPlan) -> bool { } } +/// Whether `plan` already answers raw series frames of its own. +/// +/// A selector naming no metric is prepared as one [`RawSeriesSource`] per discovered metric, or as +/// the `Union` of them when it discovered several, and each source names the metric it reads. So +/// such a plan is a frame producer in its own right: a segment hands it to the node it builds +/// instead of binding it again. Binding it again nests a source in a source, and the physical +/// planner reads a source's child as the region scan that source binds - a union is no such child +/// either - so the nested input is refused after the statement has already been committed to this +/// route. +fn is_sourced_plan(plan: &LogicalPlan) -> bool { + matches!(plan, LogicalPlan::Union(_)) || is_raw_series_source(plan) +} + fn find_input_node(node: &NativeNode, source_index: usize) -> Option<&BoundInput> { node.inputs() .into_iter() @@ -918,11 +931,16 @@ fn build_inner_segment( let source_fields = tree_source_fields(&tree).ok()?; let mut children = Vec::with_capacity(sources.len()); for (local_index, &source_index) in sources.iter().enumerate() { - let (Some((Some(metric), _, source_tags)), Some(fields), Some(scan)) = ( - per_source.get(source_index), - source_fields.get(local_index), - scans.get(local_index), - ) else { + let scan = scans.get(local_index)?; + // A scan that is already a source - one metric of a discovery, or the union of several - + // is the frame producer this segment reads, so it stays as it is; see [`is_sourced_plan`]. + if is_sourced_plan(scan) { + children.push(scan.clone()); + continue; + } + let (Some((Some(metric), _, source_tags)), Some(fields)) = + (per_source.get(source_index), source_fields.get(local_index)) + else { return None; }; children.push(LogicalPlan::Extension(Extension { diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index ad0043bf5d2..eaf1123fa95 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -1070,17 +1070,20 @@ impl PromPlanner { let Some((mut prepared, logical_ids_differ, statement_kind)) = preparation? else { return Ok(None); }; - // `absent_over_time` reads its window through a fold that keeps the metric name, so the segment that - // runs it reports names across a boundary. A nameless selector that discovery expands into more - // than one metric binds no single name for that boundary, and the fused node refuses a tree - // declaring `__name__` without one. A fold that dropped the name would plan, but it would read two - // metrics sharing their ordinary labels as one series, so the route declines. + // `absent_over_time` reads its window through a fold that keeps the metric name, which the fused + // node hands over in a frame's labels. Only the bare-scan arm of that node needs the binding's own + // name: it asks a region scan for the series of one metric, and that is exactly the shape with a + // name to ask for. A nameless selector that discovery expands into several metric tables never + // reaches that arm, because its prepared input is the `Union` of one `RawSeriesSource` per + // discovered metric, and each source names its own metric, so the node is handed explicit-label + // frames instead. So the case declined here is a nameless input that is *not* sourced, which is the + // one shape where a tree keeping `__name__` would meet a scan that has no name to bind. // - // A selector that matched no table is not that shape: its typed empty input holds no series. + // A selector that matched no table is not that shape either: its typed empty input holds no series. if reads_presence(prom_expr) - && prepared - .iter() - .any(|(scan, _, metric, ..)| !is_empty_discovered_input(scan) && metric.is_none()) + && prepared.iter().any(|(scan, _, metric, ..)| { + !is_empty_discovered_input(scan) && metric.is_none() && !is_sourced_plan(scan) + }) { return Ok(None); } @@ -1386,15 +1389,6 @@ impl PromPlanner { let children = prepared .into_iter() .map(|(scan, schema, metric, _, tags, _, split_series)| { - // A discovered selector already carries its own sources: a single metric is one - // `RawSeriesSource`, several are a `Union` of them, and each names the metric it - // reads. Wrapping either again would nest a source in a source. - let already_sourced = matches!(&scan, LogicalPlan::Union(_)) - || matches!( - &scan, - LogicalPlan::Extension(extension) - if extension.node.as_any().is::() - ); // The typed empty frame of a selector that matched no table is already the input: it reads // no region and has no metric to bind, so it stays itself on both routes. if is_empty_discovered_input(&scan) { @@ -1404,8 +1398,9 @@ impl PromPlanner { // reads every input through a raw source: the source names each region's half and // reconciles the fragments of a series several regions hold. A partition that splits one // series across regions has to be read through a raw source even where no split is - // planned, since a bare scan would hand a region only its own fragment. - if (!per_source_inputs && !split_series) || already_sourced { + // planned, since a bare scan would hand a region only its own fragment. A selector that + // already carries its own sources stays as it is; see [`is_sourced_plan`]. + if (!per_source_inputs && !split_series) || is_sourced_plan(&scan) { return Ok(scan); } let Some(metric) = metric else { @@ -1862,6 +1857,21 @@ fn reads_presence(expr: &PromExpr) -> bool { presence.0 } +/// Whether a prepared selector already carries its own raw sources, and so hands the fused node +/// explicit-label frames rather than a bare region scan. +/// +/// A discovered selector is that shape: a single metric is one [`RawSeriesSource`], several are a +/// `Union` of them, and each names the metric it reads. Wrapping either again would nest a source in +/// a source. +fn is_sourced_plan(plan: &LogicalPlan) -> bool { + matches!(plan, LogicalPlan::Union(_)) + || matches!( + plan, + LogicalPlan::Extension(extension) + if extension.node.as_any().is::() + ) +} + /// The moment `millis` milliseconds from the Unix epoch, on whichever side of it that lands. /// /// A pre-epoch statement reaches the planner as a negative millisecond. `None` means the bound is diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index 1fba23601f2..c067ad9412d 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -2582,7 +2582,7 @@ async fn native_zero_match_takes_the_layout_of_its_set_operand() { async fn native_absent_over_time_plans_over_discovered_metrics() { // Only one of the two metrics carries `no_such_label`, so the matcher that wants a value of it // narrows the discovery to that one metric and the route plans. A selector that narrowed to - // both would decline: its presence read keeps the names, and one segment could not bind them. + // both - checked below - plans as well, since each discovered metric answers for itself. let specs = ["alpha_total", "beta_total"] .into_iter() .map(|name| ((DEFAULT_SCHEMA_NAME.to_string(), name.to_string()), 2, 1)) @@ -2656,9 +2656,9 @@ async fn native_absent_over_time_plans_over_discovered_metrics() { "a selector that matched no table still answers its matchers: {tree}" ); - // The same selector over metrics that all carry the label narrows to several: the presence - // read keeps their names and one segment cannot bind them, so the route declines rather than - // planning a tree that cannot be built or one that would read two metrics as one series. + // The same selector over metrics that all carry the label narrows to several, and it plans: each + // discovered metric is read through its own raw source, so the presence read keeps every name + // and the fused node is handed the union of those sources rather than a scan to bind. let specs = ["alpha_total", "beta_total"] .into_iter() .map(|name| ((DEFAULT_SCHEMA_NAME.to_string(), name.to_string()), 2, 1)) @@ -2668,19 +2668,72 @@ async fn native_absent_over_time_plans_over_discovered_metrics() { vec!["tag_0".to_string(), "no_such_label".to_string()], ]; let provider = build_test_table_provider_with_tsid_tag_names(&specs, &tags, None).await; - let error = PromPlanner::stmt_to_plan_with_annotations( - provider, - &build_eval_stmt(r#"absent_over_time({no_such_label="x", tag_0="api"}[5m])"#), - &build_query_engine_state(), - None, + let plan = build_native_fused_plan_with_provider( + r#"absent_over_time({no_such_label="x", tag_0="api"}[5m])"#, true, + provider, ) - .await - .expect_err("a nameless selector over several metrics must decline"); + .await; + let display = plan.display_indent().to_string(); + assert!(display.contains("FusedSeries"), "{display}"); assert!( - error.to_string().contains("metric matcher"), - "the decline keeps the existing plan's answer: {error}" + !display.contains("prom_absent_over_time"), + "the answer must not be the existing per-series UDF: {display}" ); + let fused = find_fused_series(&plan).expect("fused plan"); + // One input holds the whole discovery: the two metrics are the union's sources, not two inputs. + assert_eq!(1, fused.inputs().len(), "{plan:?}"); + // Each discovered metric is read through its own source, and that source names the metric it + // reads: this is why the binding below needs no name of its own. + fn source_metrics(plan: &LogicalPlan, out: &mut Vec) { + if let LogicalPlan::Extension(extension) = plan + && let Some(source) = extension.node.as_any().downcast_ref::() + { + out.push(source.metric_name().to_string()); + } + for input in plan.inputs() { + source_metrics(input, out); + } + } + let mut sources = Vec::new(); + for input in fused.inputs() { + source_metrics(input, &mut sources); + } + sources.sort(); + assert_eq!(vec!["alpha_total", "beta_total"], sources, "{plan:?}"); + // The tree reads presence through a fold that keeps the name, which is what tells two metrics + // apart at runtime; a fold that dropped it would read them as one series. + let trees = fused_trees(&plan).join("\n"); + assert!( + trees.contains(r#"Vector: absent {no_such_label="x", tag_0="api"}"#), + "the labels are the selector's matchers: {trees}" + ); + assert!( + trees.contains("Window: last_over_time [300000ms]"), + "the presence read folds the window: {trees}" + ); + assert!( + !trees.contains("present_over_time"), + "the fold keeps the name rather than dropping it: {trees}" + ); + // The layout still declares the per-row name column, and an `absent` answer names no row: the + // column is the nullable one every row leaves empty. + let names = plan.schema().fields(); + let last = names.last().expect("the plan publishes a name column"); + assert_eq!(METRIC_NAME, last.name().as_str(), "{names:?}"); + assert_eq!(&ArrowDataType::Utf8, last.data_type(), "{names:?}"); + assert!(last.is_nullable(), "{names:?}"); + assert_eq!( + 1, + names + .iter() + .filter(|field| field.name() == METRIC_NAME) + .count(), + "the name column is declared once: {names:?}" + ); + // The binding below the node names no metric: the frames it reads name their own, so the lifted + // assumption - that such a tree does not need the binding's name - is what is being pinned here. + assert!(fused.binding().metric_name.is_none(), "{plan:?}"); // A selector that names its metric answers with that metric's other equality matchers alone. let plan = diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index 01e9c26b5c5..1548ea55ec0 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -6635,10 +6635,11 @@ async fn promql_output( /// `absent_over_time` answers with the labels its selector's matchers fix at every point no series /// of the selector has a sample at, and with nothing at the points one does. Three metric tables /// make the shapes reachable: `absent_probe` carries `probe_label`, which no row's value matches, so -/// a nameless selector narrows to it; `absent_a` and `absent_b` carry the same ordinary labels, so a -/// nameless selector over them is one discovery expands into several metrics; and no table carries -/// `no_such_label`, which is the reported query - the one whose selector matches no metric table and -/// whose labels therefore have to come from the matchers alone. +/// a nameless selector narrows to it; `absent_a` and `absent_b` carry the same ordinary labels, so +/// a nameless selector covers both and is one discovery expanding into several metrics, each +/// answering through its own raw source; and no table carries `no_such_label`, which is the reported +/// query - the one whose selector matches no metric table and whose labels therefore have to come +/// from the matchers alone. /// /// The existing plan answers the call per series with a UDF, which needs a metric name to read a /// table from: such a selector writes none, and the labels still have to reach the answer at every @@ -6748,33 +6749,131 @@ async fn native_promql_absent_over_time_answers_like_prometheus() { ); } - // A nameless selector that discovery expands into more than one metric declines. The presence - // read keeps the metric name, and no single name is bound for the segment that hands it over; a - // fold that dropped the name would plan, and would read two metrics sharing their ordinary - // labels as one series. Neither tree is planned, so the query keeps the existing plan's answer - // for a selector that names no metric - an error - rather than answering wrongly. + // A nameless selector that discovery expands into more than one metric answers. `absent_a`, + // `absent_b` and `absent_probe` all carry `job`, and the first two carry the same ordinary + // labels, so `{job="api"}` is one discovery expanding into several metrics whose series would + // collapse into one if the presence read dropped the metric name. It does not, so the node + // reads a frame per metric - its child is the union of their raw sources - rather than one scan + // bound to one name. + // + // Both metrics holding samples in the window answer nothing: neither may be read as the other. observer.clear(); - let declined = servers::prometheus_handler::PrometheusHandler::do_query( - instance.as_ref(), - &PromQuery { - query: r#"absent_over_time({job="api"}[5m])"#.to_string(), - start: "120".to_string(), - end: "120".to_string(), - step: "1s".to_string(), - ..PromQuery::default() - }, - native_query_context(true, 4), + let (columns, rows) = native_labelled_rows( + promql_output( + &instance, + r#"absent_over_time({job="api"}[5m])"#, + "120", + "120", + "1s", + ) + .await, ) .await; assert!( - declined.is_err(), - "a nameless selector over several metrics must not be answered natively yet" - ); - assert!( - !observed_physical_nodes(&observer) + observed_physical_nodes(&observer) .iter() .any(|node| node.name() == "FusedSeriesExec"), - "the declining shape must not run a fused node" + "a nameless selector over several metrics must run a fused node: {columns:?}" + ); + assert!( + rows.is_empty(), + "two metrics with equal labels holding samples in the window: {columns:?} {rows:?}" + ); + + // The same selector where the window holds no sample of any of them answers once, with the + // selector's equality labels alone: the name the presence read kept is not a label of the + // answer, and neither is `probe_label`, which no matcher fixes. + let (columns, rows) = native_labelled_rows( + promql_output( + &instance, + r#"absent_over_time({job="api"}[5m])"#, + "400", + "400", + "1s", + ) + .await, + ) + .await; + assert_eq!( + vec![(400000, labels(&[("job", "api")]), 1.0)], + rows, + "{columns:?}" + ); + + // A range answers every step whose window holds nothing. + let (columns, rows) = native_labelled_rows( + promql_output( + &instance, + r#"absent_over_time({job="api"}[5m])"#, + "400", + "470", + "70s", + ) + .await, + ) + .await; + assert_eq!( + vec![ + (400000, labels(&[("job", "api")]), 1.0), + (470000, labels(&[("job", "api")]), 1.0), + ], + rows, + "{columns:?}" + ); + + // A statement that compares a discovery over several metrics with one over a single metric cuts + // both occurrences into one segment. `{job="api"}` is a union of one raw source per discovered + // metric and `{probe_label="y"}` is a single raw source, and each is already the frame producer + // it reads through, so the segment hands them on rather than binding them again: a second + // binding nests a source in a source, and the physical planner refuses that, because a source's + // child has to be the region scan it binds. + // + // Both metrics hold a sample in the window at 120s, so the absent side reports nothing, and the + // addition answers alone. One-to-one matching under `on(job)` narrows the result to the labels + // the two operands are matched by, as Prometheus does: the probe's `probe_label` is not one of + // them, so it leaves the result. The value is the sum of the matched samples, 5 + 2. + observer.clear(); + let (columns, rows) = native_labelled_rows( + promql_output( + &instance, + r#"absent_over_time({job="api"}[5m]) or ({probe_label="y"} + on(job) absent_a)"#, + "120", + "120", + "1s", + ) + .await, + ) + .await; + assert!( + observed_physical_nodes(&observer) + .iter() + .any(|node| node.name() == "FusedSeriesExec"), + "the mixed discovery statement must run a fused node: {columns:?}" + ); + assert_eq!( + vec![(120000, labels(&[("job", "api")]), 7.0)], + rows, + "{columns:?}" + ); + + // At 400s the window holds no sample of either metric and both right-hand operands are older + // than the lookback, so the absent side answers alone: one series, labelled by the matcher it + // fixes, and nothing here supplies `probe_label`. + let (columns, rows) = native_labelled_rows( + promql_output( + &instance, + r#"absent_over_time({job="api"}[5m]) or ({probe_label="y"} + on(job) absent_a)"#, + "400", + "400", + "1s", + ) + .await, + ) + .await; + assert_eq!( + vec![(400000, labels(&[("job", "api")]), 1.0)], + rows, + "{columns:?}" ); }