From 8ea60a155c9c06ae83e4898fc92025d47542672e Mon Sep 17 00:00:00 2001 From: dennis zhuang Date: Wed, 2 Dec 2026 05:44:11 +0000 Subject: [PATCH] fix(promql): keep NULL rows of native instant selectors (#10762) * fix(promql): keep NULL rows of native instant selectors A selector at the statement root dropped a selected row whose fields are all NULL, so native TQL answered nothing where the existing planner answers a NULL row, and an all-NULL series disappeared. The root selection now reports stored rows (InstantValue::Row); selections that feed functions, aggregations and binary operands keep dropping them. Signed-off-by: Dennis Zhuang * style: format the merge and document root selection precedence Signed-off-by: Dennis Zhuang --------- Signed-off-by: Dennis Zhuang --- src/promql/src/native/display.rs | 1 + src/promql/src/native/execute.rs | 16 ++-- src/promql/src/native/plan.rs | 19 +++-- src/query/src/promql/planner/native.rs | 23 ++++++ tests-integration/src/tests/promql_test.rs | 90 ++++++++++------------ 5 files changed, 86 insertions(+), 63 deletions(-) diff --git a/src/promql/src/native/display.rs b/src/promql/src/native/display.rs index 5b4a24c4e05..9cf1f17ab3a 100644 --- a/src/promql/src/native/display.rs +++ b/src/promql/src/native/display.rs @@ -160,6 +160,7 @@ fn describe(node: &NativeNode) -> String { } match op.value { InstantValue::Sample => {} + InstantValue::Row => text.push_str(" stored rows"), InstantValue::MatrixRows => text.push_str(" matrix rows"), InstantValue::Timestamp => text.push_str(" timestamp"), InstantValue::InfoTimestamp => text.push_str(" info timestamp"), diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 77f2a073add..74d657acb95 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -902,9 +902,12 @@ impl InstantRuntime { } /// Pushes the selected `row` at grid `position`. A selection of samples drops a row whose - /// fields are all empty; matrix rows keep it as a row of nulls. + /// fields are all empty; stored rows and matrix rows keep it as a row of nulls. fn push_row(&mut self, position: usize, row: &[Option]) -> Result<()> { - if self.selection.value == InstantValue::MatrixRows { + if matches!( + self.selection.value, + InstantValue::Row | InstantValue::MatrixRows + ) { self.output.push_stored_row(position, row) } else { self.output.push_samples(position, row) @@ -915,9 +918,10 @@ impl InstantRuntime { fn output_metric(&self, metric: &SeriesLabels) -> Result { match self.selection.value { InstantValue::Timestamp => drop_metric_name(metric), - InstantValue::Sample | InstantValue::MatrixRows | InstantValue::InfoTimestamp => { - Ok(metric.clone()) - } + InstantValue::Sample + | InstantValue::Row + | InstantValue::MatrixRows + | InstantValue::InfoTimestamp => Ok(metric.clone()), } } @@ -937,7 +941,7 @@ impl InstantRuntime { InstantValue::InfoTimestamp => { info_sample_times(&self.answer, metric, time, fields, indices, timestamps)? } - InstantValue::Sample | InstantValue::MatrixRows => { + InstantValue::Sample | InstantValue::Row | InstantValue::MatrixRows => { return Err(DataFusionError::Internal( "an instant selection of samples has no sample times to project".to_string(), )); diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index cafa54cfa38..094311b9cb6 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -76,9 +76,10 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti let tags = fused_output_tags(input, source_tags)?; Some(match op.value { InstantValue::Timestamp => without_metadata_labels(tags), - InstantValue::Sample | InstantValue::MatrixRows | InstantValue::InfoTimestamp => { - tags - } + InstantValue::Sample + | InstantValue::Row + | InstantValue::MatrixRows + | InstantValue::InfoTimestamp => tags, }) } NativeExpr::Window { input, op } => { @@ -506,7 +507,9 @@ impl NativeNode { .or(Some(inner)) } NativeExpr::Instant { input, op } => match op.value { - InstantValue::Sample | InstantValue::MatrixRows => kind_of(input), + InstantValue::Sample | InstantValue::Row | InstantValue::MatrixRows => { + kind_of(input) + } InstantValue::Timestamp | InstantValue::InfoTimestamp => Some(FieldKind::Float), }, NativeExpr::Map { input, op } => { @@ -695,16 +698,20 @@ pub enum InstantValue { /// The info series `info()` reads: the sample's own time in milliseconds, under all of its /// labels, as Prometheus' `evalSeries` records it for `info`. InfoTimestamp, + /// The selected row as stored: its samples, or a row of nulls where every field is null. A + /// selector at the statement root reports its rows this way, as the existing planner does. + Row, /// A range selector root's window, as the existing planner reports it: a row of nulls where /// every field is null is kept, and a row with a stale marker in any field is dropped - /// (`SeriesNormalize`). [`InstantValue::Sample`] reads the marker from the first field only. + /// (`SeriesNormalize`). [`InstantValue::Sample`] and [`InstantValue::Row`] read the marker + /// from the first field only. MatrixRows, } impl InstantValue { /// Whether the selection reports the selected samples rather than their times. pub fn reports_samples(self) -> bool { - matches!(self, Self::Sample | Self::MatrixRows) + matches!(self, Self::Sample | Self::Row | Self::MatrixRows) } } diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 94feed47c0c..1c443009e9f 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -1411,8 +1411,14 @@ impl PromPlanner { } Err(e) => return Err(e).context(DataFusionPlanningSnafu), }; + // A range selector root drops rows stale in any field, so it does not also become stored + // rows. Rows answer the statement; a frame is a binary operand and keeps reading samples. if sample_window.is_some() { compiled.tree = matrix_rows(&compiled.tree).context(DataFusionPlanningSnafu)?; + } else if format == FusedOutputFormat::PlainRows + && let Some(tree) = stored_rows(&compiled.tree).context(DataFusionPlanningSnafu)? + { + compiled.tree = tree; } if compiled.inputs.len() != prepared.len() { return Err(DataFusionError::Internal( @@ -2195,6 +2201,23 @@ fn epoch_millis(millis: i64) -> Option { } } +/// `tree` with its root instant selection reporting the selected rows as stored, `None` when the +/// root is not a selection of samples. The existing planner answers a selected row whose fields +/// are all null with that row; a selection of samples drops it. +fn stored_rows(tree: &NativeTree) -> std::result::Result, DataFusionError> { + if !matches!( + &tree.root().expr, + NativeExpr::Instant { op, .. } if op.value == InstantValue::Sample + ) { + return Ok(None); + } + let mut root = tree.root().clone(); + if let NativeExpr::Instant { op, .. } = &mut root.expr { + op.value = InstantValue::Row; + } + NativeTree::try_new(root).map(Some) +} + /// `tree`, a range selector root's instant selection, reporting the window's rows as the existing /// planner does; see [`InstantValue::MatrixRows`]. fn matrix_rows(tree: &NativeTree) -> std::result::Result { diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index 7c12fbfac64..9ed36eb03ef 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -3977,6 +3977,44 @@ fn assert_native_rows_plan(observer: &NativePlanObserver) { assert!(display.contains("FusedSeriesExec"), "{display}"); } +/// A selected row whose fields are all null is answered as a row of nulls, as the existing route +/// answers it, and a series of only such rows is reported too. +#[tokio::test(flavor = "multi_thread")] +async fn native_promql_instant_selector_keeps_null_rows() { + let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( + "native_promql_instant_selector_null_rows", + )) + .await; + let instance = standalone.fe_instance().clone(); + execute_all( + &instance, + "CREATE TABLE null_rows (ts TIMESTAMP(3) TIME INDEX, val DOUBLE, host STRING PRIMARY KEY); \ + INSERT INTO null_rows VALUES (0, 1.0, 'a'), (10000, 2.0, 'a'), (20000, NULL, 'a'), \ + (30000, 4.0, 'a'), (20000, NULL, 'b'); \ + CREATE TABLE null_rows_wide (ts TIMESTAMP(3) TIME INDEX, v1 DOUBLE, v2 DOUBLE, \ + host STRING PRIMARY KEY); \ + INSERT INTO null_rows_wide VALUES (0, 1.0, NULL, 'a'), (10000, NULL, NULL, 'a'), \ + (20000, NULL, 2.0, 'a')", + QueryContext::arc(), + ) + .await; + for (metric, sql) in [ + ("null_rows", "TQL EVAL (20, 20, '1s') null_rows"), + ("null_rows", "TQL EVAL (0, 40, '5s') null_rows"), + ("null_rows", "TQL EVAL (0, 40, '10s') null_rows @ 20"), + ("null_rows", "TQL EVAL (0, 40, '10s') (null_rows offset 5s)"), + ("null_rows", "TQL EVAL (30, 30, '1s') null_rows[20s:10s]"), + ("null_rows_wide", "TQL EVAL (0, 30, '10s') null_rows_wide"), + ] { + observer.clear(); + let output = native_tql_output(&instance, sql, true).await; + let native = eval_text_rows(collected(output).await, ReportedName::Metric(metric)); + assert_native_rows_plan(&observer); + let legacy = eval_text(collected(native_tql_output(&instance, sql, false).await).await); + assert_eq!(legacy, native, "{sql}"); + } +} + /// [`native_result_rows`] for a statement whose output carries no series labels, such as the /// data-free `vector(time())`: the evaluation timestamp and the one value, sorted by time. /// @@ -9053,14 +9091,6 @@ async fn native_promql_instant_at_uses_sample_time_and_anchor() { ("native_at{host=\"b\"}", 499, 499, 2_000, "b", vec![9.]), ("native_at{host=\"b\"}", 500, 500, 2_000, "b", vec![]), ("native_at{host=\"b\"} @ -1.5", 0, 0, 0, "b", vec![9.]), - ( - "native_at{host=\"missing\"}", - 2_000, - 2_000, - 5_000, - "missing", - vec![], - ), ( "timestamp(native_at{host=\"missing\"})", 2_000, @@ -9245,49 +9275,7 @@ async fn native_promql_instant_at_uses_sample_time_and_anchor() { ) .await .unwrap(); - if expr == "native_at{host=\"missing\"}" { - // Legacy preserves the selected NULL sample row; native selectors drop all-missing rows. - let batches = match legacy.data { - OutputData::Stream(stream) => collect_batches(stream).await.unwrap(), - OutputData::RecordBatches(batches) => batches, - _ => unreachable!("TQL EVAL returns record batches"), - }; - assert_eq!( - batches.iter().map(|batch| batch.num_rows()).sum::(), - 1, - "legacy missing selector must retain exactly the selected NULL row" - ); - for batch in batches.iter().filter(|batch| batch.num_rows() > 0) { - assert_eq!(batch.num_rows(), 1); - let timestamps = batch - .column_by_name("ts") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - let hosts = cast( - batch.column_by_name("host").unwrap().as_ref(), - &DataType::Utf8, - ) - .unwrap(); - let hosts = hosts.as_any().downcast_ref::().unwrap(); - let value_columns = batch - .columns() - .iter() - .filter(|column| column.data_type() == &DataType::Float64) - .collect::>(); - assert_eq!(value_columns.len(), 1, "expected one Float64 value column"); - let values = value_columns[0] - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(timestamps.null_count(), 0); - assert_eq!(hosts.null_count(), 0); - assert_eq!(values.null_count(), 1); - assert_eq!(timestamps.value(0), 2_000); - assert_eq!(hosts.value(0), "missing"); - } - } else if expr == "timestamp(native_at{host=\"neg\"} @ 11 offset -2s)" { + if expr == "timestamp(native_at{host=\"neg\"} @ 11 offset -2s)" { // Legacy uses the shifted instant for its lookback window and selects 11.5s; the // anchored native selection intersects that window with the unshifted anchor. assert_eq!(