From 7ce79aa265d977fbda8ba36caa8263131ef6b4d0 Mon Sep 17 00:00:00 2001 From: Yingwen Date: Thu, 3 Dec 2026 15:58:05 +0000 Subject: [PATCH] perf(query): push matching labels into native PromQL scans (#10834) * perf(query): push matching labels into native PromQL scans Port evenyag/greptimedb@e3a26033ab3d6900c6f8d72cd932fa08421812f8. Signed-off-by: evenyag * fix(query): guard PromQL matching-label propagation Signed-off-by: evenyag * test(query): cover native PromQL matching filter pushdown Signed-off-by: evenyag --------- Signed-off-by: evenyag --- src/query/src/promql/planner.rs | 23 +++ .../src/promql/planner/matching_filters.rs | 184 +++++++++++++++--- src/query/src/promql/planner/native.rs | 22 +++ src/query/src/promql/planner/test.rs | 67 ++++++- 4 files changed, 266 insertions(+), 30 deletions(-) diff --git a/src/query/src/promql/planner.rs b/src/query/src/promql/planner.rs index ee120818c09..c5aaa0abdef 100644 --- a/src/query/src/promql/planner.rs +++ b/src/query/src/promql/planner.rs @@ -1557,6 +1557,12 @@ impl PromPlanner { &right_context.tag_columns, &left_context.aggregation_field_labels, &right_context.aggregation_field_labels, + |label| { + [&left_input, &right_input].into_iter().all(|plan| { + Self::matcher_scan_schema(plan) + .is_some_and(|schema| Self::scan_label_is_string(schema, label)) + }) + }, ) { // A copied matcher belongs to the scan, not to the operand's identity: // `absent()` turns `selector_matcher` into the labels it reports, so the @@ -5775,6 +5781,23 @@ impl PromPlanner { native_histogram_value_type().as_arrow_type() } + /// Matcher rewrites cover selectors beneath unary plans with one scan. + fn matcher_scan_schema(plan: &LogicalPlan) -> Option<&DFSchemaRef> { + match plan { + LogicalPlan::TableScan(_) => Some(plan.schema()), + _ => match plan.inputs().as_slice() { + [input] => Self::matcher_scan_schema(input), + _ => None, + }, + } + } + + fn scan_label_is_string(schema: &DFSchemaRef, name: &str) -> bool { + Self::field_column_type(schema, name) + .and_then(Self::string_value_data_type) + .is_some() + } + fn field_column_type<'a>( schema: &'a DFSchemaRef, field_column: &str, diff --git a/src/query/src/promql/planner/matching_filters.rs b/src/query/src/promql/planner/matching_filters.rs index d70e1bc4192..d1ab2a940f6 100644 --- a/src/query/src/promql/planner/matching_filters.rs +++ b/src/query/src/promql/planner/matching_filters.rs @@ -68,7 +68,9 @@ const LABEL_PRESERVING_RANGE_FUNCTIONS: [&str; 20] = [ /// labels: filtering them before sample selection could replace the latest sample with an /// older one (#9242). /// -/// Whether a matcher reaches a scan is decided per receiving operand ([`preserves_filter`]), so +/// `is_string_tag` checks the column type on both scans. +/// +/// Whether a matcher reaches a scan is decided per receiving operand ([`preserves_label`]), so /// propagation is one-way when only one of the two can take the filter. pub(super) fn propagate( binary: &BinaryExpr, @@ -76,6 +78,7 @@ pub(super) fn propagate( right_tags: &[String], left_field_labels: &[String], right_field_labels: &[String], + is_string_tag: impl Fn(&str) -> bool, ) -> Option { match try_propagate( binary, @@ -83,6 +86,7 @@ pub(super) fn propagate( right_tags, left_field_labels, right_field_labels, + is_string_tag, ) { Ok(rewritten) => Some(rewritten), Err(reason) => { @@ -92,6 +96,90 @@ pub(super) fn propagate( } } +/// Finds scan-only matchers for a native tree with two selector occurrences. +/// The outer aggregations are unaffected because the binary result is unchanged. +pub(super) fn native_scan_matchers( + expr: &Expr, + left_source_tags: &[String], + right_source_tags: &[String], + is_string_tag: impl Fn(&str) -> bool, +) -> Option<[Vec; 2]> { + let binary = match expr { + Expr::Paren(paren) => { + return native_scan_matchers( + &paren.expr, + left_source_tags, + right_source_tags, + is_string_tag, + ); + } + Expr::Aggregate(aggregate) + if partitions_by_grouping_labels(aggregate) || ranks_by_grouping_labels(aggregate) => + { + return native_scan_matchers( + &aggregate.expr, + left_source_tags, + right_source_tags, + is_string_tag, + ); + } + Expr::Binary(binary) => binary, + _ => return None, + }; + let modifier = binary.modifier.as_ref()?; + let Some(LabelModifier::Include(on)) = modifier.matching.as_ref() else { + return None; + }; + let (tags, one_side) = match &modifier.card { + VectorMatchCardinality::OneToMany(_) => (left_source_tags, binary.lhs.as_ref()), + VectorMatchCardinality::ManyToOne(_) => (right_source_tags, binary.rhs.as_ref()), + _ => return None, + }; + let one_tags = explicit_unique_output_labels(one_side)?; + if one_tags + .iter() + .any(|tag| !tags.contains(tag) || !on.labels.contains(tag)) + || on.labels.iter().any(|tag| !one_tags.contains(tag)) + { + return None; + } + let (left_tags, right_tags) = match &modifier.card { + VectorMatchCardinality::OneToMany(_) => (one_tags, right_source_tags), + _ => (left_source_tags, one_tags), + }; + let mut original = binary.clone(); + let mut rewritten = propagate(binary, left_tags, right_tags, &[], &[], |label| { + preserves_label(&binary.lhs, label, false) + && preserves_label(&binary.rhs, label, false) + && is_string_tag(label) + })?; + let additions = |before: &mut Expr, after: &mut Expr| { + let before = selector_matchers(before)?; + let after = selector_matchers(after)?; + Some( + after + .matchers + .iter() + .filter(|matcher| !before.matchers.contains(matcher)) + .cloned() + .collect(), + ) + }; + Some([ + additions(&mut original.lhs, &mut rewritten.lhs)?, + additions(&mut original.rhs, &mut rewritten.rhs)?, + ]) +} + +/// Proves that a grouped operand's output labels are exactly its explicit grouping set. +fn explicit_unique_output_labels(expr: &Expr) -> Option<&[String]> { + let aggregate = unique_grouping_aggregate(expr)?; + let Some(LabelModifier::Include(labels)) = &aggregate.modifier else { + return None; + }; + Some(&labels.labels) +} + /// `Err` carries why the rewrite does not apply, for [`propagate`] to log. fn try_propagate( binary: &BinaryExpr, @@ -99,6 +187,7 @@ fn try_propagate( right_tags: &[String], left_field_labels: &[String], right_field_labels: &[String], + is_string_tag: impl Fn(&str) -> bool, ) -> Result { if !matches!( binary.op.id(), @@ -132,7 +221,7 @@ fn try_propagate( }; if let Some(modifier) = &binary.modifier { let unique_on_matching_labels = |expr: &Expr, tags: &[String]| { - has_unique_aggregate_output(expr) && tags.iter().all(&is_matching_label) + unique_grouping_aggregate(expr).is_some() && tags.iter().all(&is_matching_label) }; let supported_cardinality = match &modifier.card { VectorMatchCardinality::OneToOne => true, @@ -159,7 +248,11 @@ fn try_propagate( .matchers .iter() .chain(&right.matchers) - .filter(|matcher| is_matching_label(&matcher.name) && !matches_every_value(matcher)) + .filter(|matcher| { + is_matching_label(&matcher.name) + && !matches_every_value(matcher) + && is_string_tag(&matcher.name) + }) .cloned() .collect::>(); @@ -169,7 +262,7 @@ fn try_propagate( (&mut left.matchers, &binary.lhs), (&mut right.matchers, &binary.rhs), ] { - if !target.contains(&matcher) && preserves_filter(operand, &matcher.name) { + if !target.contains(&matcher) && preserves_label(operand, &matcher.name, true) { target.push(matcher.clone()); changed = true; } @@ -210,18 +303,17 @@ fn ranks_by_grouping_labels(aggregate: &AggregateExpr) -> bool { matches!(aggregate.op.id(), token::T_TOPK | token::T_BOTTOMK) } -/// Whether a partitioning aggregate proves the operand emits at most one series per combination -/// of its output labels; ranking narrows its input, so it inherits the proof. Uniqueness per -/// *match signature* additionally requires every output label to be a matching label, which the -/// caller checks. -fn has_unique_aggregate_output(expr: &Expr) -> bool { +/// Finds the aggregate that proves uniqueness per combination of output labels. Ranking narrows +/// its input, so it inherits the proof. The caller checks that every output label participates in +/// matching. +fn unique_grouping_aggregate(expr: &Expr) -> Option<&AggregateExpr> { match expr { - Expr::Paren(paren) => has_unique_aggregate_output(&paren.expr), - Expr::Aggregate(aggregate) if partitions_by_grouping_labels(aggregate) => true, + Expr::Paren(paren) => unique_grouping_aggregate(&paren.expr), + Expr::Aggregate(aggregate) if partitions_by_grouping_labels(aggregate) => Some(aggregate), Expr::Aggregate(aggregate) if ranks_by_grouping_labels(aggregate) => { - has_unique_aggregate_output(&aggregate.expr) + unique_grouping_aggregate(&aggregate.expr) } - _ => false, + _ => None, } } @@ -242,25 +334,29 @@ fn vector_operand_is_lhs(binary: &BinaryExpr) -> Option { } } -/// Whether adding a matcher on `label` to the scan [`selector_matchers`] finds leaves the -/// operand's output equal to the subset of its unfiltered output that satisfies the matcher. -/// A filter may cross an aggregate only when it removes whole groups: in particular, a label -/// retained by topk is not necessarily one of its partitioning labels. -fn preserves_filter(expr: &Expr, label: &str) -> bool { +/// Whether the selector's label reaches the join. When pushing a filter down through a +/// receiving operand, ranking must also partition by the label to keep the same candidates +/// within every surviving group. +fn preserves_label(expr: &Expr, label: &str, pushing_filter: bool) -> bool { match expr { Expr::VectorSelector(_) => true, - Expr::Paren(paren) => preserves_filter(&paren.expr, label), + Expr::Paren(paren) => preserves_label(&paren.expr, label, pushing_filter), Expr::Aggregate(aggregate) => { - let partition_label = match &aggregate.modifier { - Some(LabelModifier::Include(labels)) => labels.labels.iter().any(|x| x == label), - Some(LabelModifier::Exclude(labels)) => labels.labels.iter().all(|x| x != label), - None => false, - }; - partition_label && preserves_filter(&aggregate.expr, label) + let preserves = (ranks_by_grouping_labels(aggregate) && !pushing_filter) + || match &aggregate.modifier { + Some(LabelModifier::Include(labels)) => { + labels.labels.iter().any(|x| x == label) + } + Some(LabelModifier::Exclude(labels)) => { + labels.labels.iter().all(|x| x != label) + } + None => false, + }; + preserves && preserves_label(&aggregate.expr, label, pushing_filter) } Expr::Binary(binary) => match vector_operand_is_lhs(binary) { - Some(true) => preserves_filter(&binary.lhs, label), - Some(false) => preserves_filter(&binary.rhs, label), + Some(true) => preserves_label(&binary.lhs, label, pushing_filter), + Some(false) => preserves_label(&binary.rhs, label, pushing_filter), None => false, }, // A rollup emits at most one output series per input series and carries its labels. @@ -340,6 +436,7 @@ mod tests { &owned(right_tags), &owned(left_field_labels), &owned(right_field_labels), + |_| true, ) .map(Expr::Binary) } @@ -355,6 +452,39 @@ mod tests { assert!(rewrite(expected).is_none(), "{expected}"); } + #[test] + fn native_grouped_join_adds_only_missing_scan_matchers() { + let expr = parse( + r#"sum by (pod) ((8 * rate(a{cluster="qa",namespace=~"app"}[5m])) * on (cluster, namespace, pod) group_left() topk by (cluster, namespace, pod) (1, max by (cluster, namespace, pod) (b{host_network="false"})))"#, + ) + .unwrap(); + let names = |tags: &[&str]| tags.iter().map(|tag| tag.to_string()).collect::>(); + let left = names(&["cluster", "namespace", "pod", "container"]); + let right = names(&["cluster", "namespace", "pod", "host_network"]); + let [left_extra, right_extra] = + native_scan_matchers(&expr, &left, &right, |_| true).unwrap(); + assert!(left_extra.is_empty()); + assert_eq!( + vec!["cluster", "namespace"], + right_extra + .iter() + .map(|matcher| matcher.name.as_str()) + .collect::>(), + ); + assert!( + native_scan_matchers(&expr, &left, &names(&["cluster", "namespace"]), |_| true) + .is_none() + ); + } + + #[test] + fn native_does_not_copy_a_matcher_on_a_dropped_label() { + let expr = parse(r#"sum by (zone) (a{host="x"}) / on (host) group_left max by (host) (b)"#) + .unwrap(); + let tags = ["host".to_string(), "zone".to_string()]; + assert!(native_scan_matchers(&expr, &tags, &tags, |_| true).is_none()); + } + #[test] fn propagates_only_explicit_matching_labels() { assert_rewrite( diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 9c51b0942d8..931286aca87 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -1453,6 +1453,28 @@ impl PromPlanner { let Some((mut prepared, logical_ids_differ, statement_kind)) = preparation? else { return Ok(None); }; + // Selectors keep their original identity and labels for native compilation. + if selectors.len() == 2 + && matches!(prepared[0].0, LogicalPlan::TableScan(_)) + && matches!(prepared[1].0, LogicalPlan::TableScan(_)) + && let Some(matchers) = super::matching_filters::native_scan_matchers( + effective_expr, + &prepared[0].4, + &prepared[1].4, + |label| { + prepared + .iter() + .all(|(scan, ..)| Self::scan_label_is_string(scan.schema(), label)) + }, + ) + { + for ((scan, ..), matchers) in prepared.iter_mut().zip(matchers) { + let mut filters = Self::matchers_to_expr(Matchers::new(matchers), scan.schema())?; + if let LogicalPlan::TableScan(table_scan) = scan { + table_scan.filters.append(&mut filters); + } + } + } // `absent_over_time` keeps `__name__`, which a bare scan takes from the binding's metric. A // nameless input that is neither sourced nor empty has no name to bind. if reads_presence(prom_expr) diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index da68eb2445e..6d02a44e209 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -6974,13 +6974,18 @@ async fn native_colliding_tag_provider() -> DfTableSourceProvider { /// Single-region tables of `(name, tags, time index, field)`. fn native_tables_provider(tables: &[(&str, &[&str], &str, &str)]) -> DfTableSourceProvider { + native_tables_provider_with_tag_types(tables, |_, _| ConcreteDataType::string_datatype()) +} + +fn native_tables_provider_with_tag_types( + tables: &[(&str, &[&str], &str, &str)], + tag_type: impl Fn(&str, &str) -> ConcreteDataType, +) -> DfTableSourceProvider { let catalog_list = MemoryCatalogManager::with_default_setup(); for (table_id, &(name, tags, time_index, field)) in (1024..).zip(tables) { let mut columns = tags .iter() - .map(|tag| { - ColumnSchema::new(tag.to_string(), ConcreteDataType::string_datatype(), false) - }) + .map(|tag| ColumnSchema::new(tag.to_string(), tag_type(name, tag), false)) .collect::>(); columns.push( ColumnSchema::new( @@ -16519,6 +16524,62 @@ async fn binary_matching_label_filter_reaches_scalar_ranking_and_grouped_operand ); } +#[tokio::test] +async fn native_grouped_join_copies_regex_only_to_string_tag_scan() { + use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion}; + + let query = r#"a{host=~"[12][0-9]"} / on (host) group_left max by (host) (b)"#; + let tables: &[(&str, &[&str], &str, &str)] = &[ + ("a", &["host"], "timestamp", "field_0"), + ("b", &["host"], "timestamp", "field_0"), + ]; + for (right_type, expected_right_regexes) in [ + (ConcreteDataType::string_datatype(), 1), + (ConcreteDataType::int64_datatype(), 0), + ] { + let provider = native_tables_provider_with_tag_types(tables, |table, _| { + if table == "b" { + right_type.clone() + } else { + ConcreteDataType::string_datatype() + } + }); + let plan = build_native_fused_plan_with_provider(query, true, provider).await; + assert!(has_pair_node(&plan), "{right_type:?}: {plan}"); + + let mut scans = Vec::new(); + plan.apply(|node| { + if let LogicalPlan::TableScan(scan) = node { + let regexes = scan + .filters + .iter() + .filter(|filter| { + matches!( + filter, + DfExpr::BinaryExpr(binary) + if binary.op == Operator::RegexMatch + && binary.left.as_ref() == &col("host") + ) + }) + .count(); + scans.push((scan.table_name.table().to_string(), regexes)); + } + Ok(TreeNodeRecursion::Continue) + }) + .unwrap(); + scans.sort(); + assert_eq!( + scans, + [ + ("a".to_string(), 1), + ("b".to_string(), expected_right_regexes) + ], + "{right_type:?}: {}", + plan.display_indent() + ); + } +} + #[tokio::test] async fn binary_matching_label_filter_skips_selecting_aggregations() { // `topk` ranks its input, so filtering before it changes the candidate set.