From 47f526e9bf68c2aae2e971efc91ddfda0534a961 Mon Sep 17 00:00:00 2001 From: discord9 Date: Wed, 2 Dec 2026 18:27:50 +0000 Subject: [PATCH] feat(promql): narrow a __field__ scan, and declare the kind a broadcast answers (#10655) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(promql): answer __field__ selectors and same-metric `or` groups natively Let the native route plan three shapes it used to hand back: - `__field__` selection (`m{__field__="f"}`) on mito raw scans, metric logical scans and file-engine row sources: the scan is narrowed to the selected fields (`field_first_projection`) so `RawSeriesSource` still sees exactly the canonical frame, text columns are refused as value kinds, and a matcher naming a column the selection drops is refused (`row_matchers_need_a_dropped_column`) instead of degrading to a literal `"" = …` that silently answers nothing. - `or` groups within one metric (`m{host="a" or host="b"}`) as one scan with one `Filter`: `AlternativeFilters` merges the groups' conjuncts, groups that select different fields or tables are refused, and `discovers_metric_name` learns the alternative groups so the authorization layer and the planner agree on what a selector discovers. - A scalar operand in a composed binary (`(hist * on(job) floats) * 2`): `native_scalar_operand` binds a scalar side that the composed path previously required to be a frame. `field_columns_selected_by` is extracted in `planner.rs` so the legacy and native routes select the same columns; as a side effect the legacy route's value-column order for a multi-field `__field__` selection goes from HashSet order to table order. Signed-off-by: discord9 * refactor(promql): share the scalar-binary binder and refuse a histogram over a dynamic scalar - Fold the composed path's `bind_evaluated_broadcast` into a single `bind_scalar_binary` shared with `binary_operation`'s scalar tail; both carry the same modifier refusal and `broadcast(...)` call. - In `try_plan_native_composed_binary`, decline a histogram frame met by a *dynamic* scalar (`(hist * on(job) floats) / time()`) with `histogram_over_a_dynamic_scalar`: the runtime refuses non-float samples on that branch instead of dropping them. A constant scalar (`* 2`) keeps planning natively. The refusal can go once the histogram-aware dynamic kernel lands separately. - Adapt the tests to the rebased base (#10701): a decline is now an error carrying its cause, so the `plan_or_refusal` sites assert `native_decline_reason(..)` and the integration rows that used to unwrap a declined output assert the cause. Signed-off-by: discord9 * refactor(promql): say a refusal is an error and drop the dead pre-or matcher loop Review follow-ups: - `histogram_over_a_dynamic_scalar` refused because the dynamic-scalar kernel on main errors on a non-float sample (#10812), not because Prometheus lacks a per-point histogram scale — it has one (`h / time()`). Comment and the three test docs now say so and reference #10812. - Since #10701 a decline is a planning error with its cause; nothing falls back to the existing plan. Reword the doc comments and test docs that still described a fallback. - `native_promql_or_matchers_narrow_the_scan` asserted the existing plan's rows for `{host="a" or host="b"}`, which answers `c`: the parser moves the pre-`or` matchers into the first group and `matchers_to_expr` reads `matchers.matchers` only, so the existing plan applies none of them. That is the existing plan's bug, filed separately; the test no longer states it as an expectation and keeps only the route check. - `AlternativeFilters::of_selector` looped over `selector.matchers.matchers` before the group loop; with any `or` that list is empty, and if it were not the loop would silently drop every non-selection matcher. Removed. Signed-off-by: discord9 --------- Signed-off-by: discord9 --- src/query/src/promql/native_compile.rs | 53 +- src/query/src/promql/planner.rs | 136 +-- src/query/src/promql/planner/native.rs | 611 +++++++++--- src/query/src/promql/planner/test.rs | 905 ++++++++++++++++-- .../src/tests/native_aggregate_test.rs | 4 +- tests-integration/src/tests/promql_test.rs | 492 +++++++++- 6 files changed, 1892 insertions(+), 309 deletions(-) diff --git a/src/query/src/promql/native_compile.rs b/src/query/src/promql/native_compile.rs index 86a0985dda2..4d36bb36587 100644 --- a/src/query/src/promql/native_compile.rs +++ b/src/query/src/promql/native_compile.rs @@ -484,15 +484,6 @@ fn binary_operation(context: &Context, binary: &BinaryExpr) -> Result Result Result { + if refuses_modifier(binary.modifier.as_ref()) { + return Err(not_implemented(&format!( + "the vector matching in `{binary}`, which a constant operand has nothing to match: \ + `on`, `ignoring`, `group_left` and `group_right` name labels of a vector, and a fill \ + value fills in a match group that could miss" + ))); + } + Ok(broadcast(left, right, op, binary.return_bool())) +} + /// Uses the ordinary binary binder for two evaluated frame inputs. pub(crate) fn bind_evaluated_binary( binary: &BinaryExpr, @@ -551,6 +561,23 @@ pub(crate) fn bind_evaluated_binary( NativeTree::try_new(bind_vector_binary(binary, left, right, op)?) } +/// Uses the ordinary broadcast binder for one evaluated frame and one scalar operand: Prometheus +/// broadcasts a scalar over the vector it meets rather than matching series, so such a pair carries +/// no `on`, `ignoring`, `group_left`, `group_right` or fill value. +pub(crate) fn bind_evaluated_broadcast( + binary: &BinaryExpr, + left: NativeNode, + right: NativeNode, +) -> Result { + let op = binary_op(&binary.op).ok_or_else(|| { + not_implemented(&format!( + "the binary operator `{}` in `{binary}`", + binary.op + )) + })?; + NativeTree::try_new(bind_scalar_binary(binary, left, right, op)?) +} + /// Compiles `and`, `or` or `unless` between two vectors, matched by the labels the query wrote. /// /// The parser already refuses a scalar operand, `bool` and `group_left` / `group_right` on a set diff --git a/src/query/src/promql/planner.rs b/src/query/src/promql/planner.rs index 5c5fb7b75ae..ee120818c09 100644 --- a/src/query/src/promql/planner.rs +++ b/src/query/src/promql/planner.rs @@ -2751,6 +2751,73 @@ impl PromPlanner { Ok(Matchers::new(matchers)) } + /// The field columns `field_matchers` select from `field_columns`, in the order `field_columns` + /// lists them, for both planner paths. + /// + /// `=` and `!=` must name a column the table carries, while `=~` and `!~` keep or drop what they + /// match; a selection without an `=` or `=~` starts from every column, so `!=` and `!~` only drop. + fn field_columns_selected_by( + field_matchers: &[Matcher], + field_columns: &[String], + ) -> Result> { + let col_set = field_columns.iter().collect::>(); + // opt-in set + let mut result_set = HashSet::new(); + // opt-out set + let mut reverse_set = HashSet::new(); + for matcher in field_matchers { + match &matcher.op { + MatchOp::Equal => { + if col_set.contains(&matcher.value) { + let _ = result_set.insert(matcher.value.clone()); + } else { + return Err(ColumnNotFoundSnafu { + col: matcher.value.clone(), + } + .build()); + } + } + MatchOp::NotEqual => { + if col_set.contains(&matcher.value) { + let _ = reverse_set.insert(matcher.value.clone()); + } else { + return Err(ColumnNotFoundSnafu { + col: matcher.value.clone(), + } + .build()); + } + } + MatchOp::Re(regex) => { + for col in field_columns { + if regex.is_match(col) { + let _ = result_set.insert(col.clone()); + } + } + } + MatchOp::NotRe(regex) => { + for col in field_columns { + if regex.is_match(col) { + let _ = reverse_set.insert(col.clone()); + } + } + } + } + } + // merge two set + if result_set.is_empty() { + result_set = col_set.into_iter().cloned().collect(); + } + for col in reverse_set { + let _ = result_set.remove(&col); + } + + Ok(field_columns + .iter() + .filter(|col| result_set.contains(*col)) + .cloned() + .collect()) + } + async fn selector_to_series_normalize_plan( &mut self, offset_duration: Millisecond, @@ -2779,68 +2846,12 @@ impl PromPlanner { // make a projection plan if there is any `__field__` matcher if let Some(field_matchers) = &self.ctx.field_column_matcher { - let col_set = self.ctx.field_columns.iter().collect::>(); - // opt-in set - let mut result_set = HashSet::new(); - // opt-out set - let mut reverse_set = HashSet::new(); - for matcher in field_matchers { - match &matcher.op { - MatchOp::Equal => { - if col_set.contains(&matcher.value) { - let _ = result_set.insert(matcher.value.clone()); - } else { - return Err(ColumnNotFoundSnafu { - col: matcher.value.clone(), - } - .build()); - } - } - MatchOp::NotEqual => { - if col_set.contains(&matcher.value) { - let _ = reverse_set.insert(matcher.value.clone()); - } else { - return Err(ColumnNotFoundSnafu { - col: matcher.value.clone(), - } - .build()); - } - } - MatchOp::Re(regex) => { - for col in &self.ctx.field_columns { - if regex.is_match(col) { - let _ = result_set.insert(col.clone()); - } - } - } - MatchOp::NotRe(regex) => { - for col in &self.ctx.field_columns { - if regex.is_match(col) { - let _ = reverse_set.insert(col.clone()); - } - } - } - } - } - // merge two set - if result_set.is_empty() { - result_set = col_set.into_iter().cloned().collect(); - } - for col in reverse_set { - let _ = result_set.remove(&col); - } + let field_columns = + Self::field_columns_selected_by(field_matchers, &self.ctx.field_columns)?; - // mask the field columns in context using computed result set - self.ctx.field_columns = self - .ctx - .field_columns - .drain(..) - .filter(|col| result_set.contains(col)) - .collect(); - - let exprs = result_set - .into_iter() - .map(|col| DfExpr::Column(Column::new_unqualified(col))) + let exprs = field_columns + .iter() + .map(|col| DfExpr::Column(Column::new_unqualified(col.as_str()))) .chain(self.create_tag_column_exprs()?) .chain( self.ctx @@ -2858,6 +2869,9 @@ impl PromPlanner { .context(DataFusionPlanningSnafu)? .build() .context(DataFusionPlanningSnafu)?; + + // mask the field columns in context using the computed selection + self.ctx.field_columns = field_columns; } // make sort plan diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index a89c5b66882..135c3b7881c 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -86,11 +86,12 @@ use crate::promql::error::{ UnsupportedExprSnafu, }; use crate::promql::native_compile::{ - InfoInput, bind_evaluated_binary, compile_selectors_with_grid, compile_statement_with_grid, - info_input, statement_grid, subquery_child_grid, + InfoInput, bind_evaluated_binary, bind_evaluated_broadcast, compile_selectors_with_grid, + compile_statement_with_grid, constant_value, info_input, statement_grid, subquery_child_grid, }; use crate::promql::planner::{ - DEFAULT_FIELD_COLUMN, DEFAULT_TIME_INDEX_COLUMN, GrownStack, PromPlanner, + DB_COLUMN_MATCHER, DEFAULT_FIELD_COLUMN, DEFAULT_TIME_INDEX_COLUMN, FIELD_COLUMN_MATCHER, + GrownStack, PromPlanner, SCHEMA_COLUMN_MATCHER, }; use crate::query_engine::QueryEngineState; @@ -299,6 +300,7 @@ impl PromPlanner { async fn prepare_one_scan( &mut self, matchers: Matchers, + alternative_groups: &[AlternativeGroup], logical_scan_id: &mut Option, logical_ids_differ: &mut bool, statement_kind: &mut Option, @@ -310,14 +312,56 @@ impl PromPlanner { return Ok(declined("selector_without_table_or_time_index")); }; let tags = self.ctx.tag_columns.clone(); - let fields = self.ctx.field_columns.clone(); - // The raw series scan has no equivalent of the `__field__` projection. - if self.ctx.field_column_matcher.is_some() || fields.is_empty() { - return Ok(declined("field_selector_without_raw_series_equivalent")); - } + // A `__field__` matcher selects among the table's field columns, resolved as the existing + // plan resolves it; one naming a column the table lacks refuses the statement. + let reads_a_field_selection = self.ctx.field_column_matcher.is_some(); + let selected_fields = match &self.ctx.field_column_matcher { + Some(field_matchers) => { + let Ok(fields) = + Self::field_columns_selected_by(field_matchers, &self.ctx.field_columns) + else { + return Ok(declined("field_selector_names_a_column_the_table_lacks")); + }; + fields + } + None => self.ctx.field_columns.clone(), + }; // Built by the existing path's method so both paths read the same columns. let table_ref = self.table_ref()?; let mut input = self.create_table_scan_plan(table_ref).await?; + // This route declares no text value and one value column per field kind, so a text column + // is read only where the table keys by it, as a label; otherwise it has no place here. + let mut fields = Vec::with_capacity(selected_fields.len()); + let mut reads_a_text_column = false; + for name in &selected_fields { + let Some(data_type) = Self::field_column_type(input.schema(), name) else { + return Ok(declined("field_missing_from_source_schema")); + }; + if Self::string_value_data_type(data_type).is_some() { + reads_a_text_column = true; + } else { + fields.push(name.clone()); + } + } + if reads_a_text_column { + return Ok(declined(if reads_a_field_selection { + "field_selector_names_a_text_column" + } else { + "text_field_is_not_a_table_key" + })); + } + if fields.is_empty() { + return Ok(declined("selector_reads_no_field")); + } + let mut read: Vec<&str> = tags.iter().map(String::as_str).collect(); + read.push(time.as_str()); + read.extend(fields.iter().map(String::as_str)); + if row_matchers_need_a_dropped_column(&matchers, alternative_groups, input.schema(), &read) + { + return Ok(declined( + "field_selector_and_row_matcher_need_different_columns", + )); + } let logical_scan = metric_scan_and_table_id(&input); let has_verified_metric_rewrite = logical_scan.is_some(); // Two logical tables over one physical table scan the same table; only their ids tell the @@ -331,31 +375,14 @@ impl PromPlanner { } let scan = match logical_scan { Some((mut scan, predicate, _)) => { - // Preserve logical field order and the table restriction on the direct - // physical scan. - let source_schema = scan.source.schema(); - let Some(mut ordered_projection) = fields - .iter() - .map(|field| source_schema.index_of(field).ok()) - .collect::>>() + let Some(projection) = + field_first_projection(&scan, &selected_fields, &self.ctx.field_columns) else { return Ok(declined("field_missing_from_source_schema")); }; - let original_projection = scan.projection.as_ref(); - let selected_indices = original_projection - .cloned() - .unwrap_or_else(|| (0..source_schema.fields().len()).collect()); - for index in selected_indices { - let is_field = fields - .iter() - .any(|field| field == source_schema.field(index).name()); - if !is_field && !ordered_projection.contains(&index) { - ordered_projection.push(index); - } - } scan.filters.push(predicate); scan = TableScanBuilder::from(scan) - .with_projection(Some(ordered_projection)) + .with_projection(Some(projection)) .build() .context(DataFusionPlanningSnafu)?; input = LogicalPlan::TableScan(scan.clone()); @@ -371,7 +398,29 @@ impl PromPlanner { input = LogicalPlan::TableScan(scan.clone()); } match &input { - LogicalPlan::TableScan(scan) => scan.clone(), + LogicalPlan::TableScan(plain) => { + let plain = plain.clone(); + // A plain scan reads every column; narrowing it means projecting the + // selection, since the raw series scan reports one field per field column it + // is handed. + if !reads_a_field_selection { + plain + } else { + let Some(projection) = field_first_projection( + &plain, + &selected_fields, + &self.ctx.field_columns, + ) else { + return Ok(declined("field_missing_from_source_schema")); + }; + let scan = TableScanBuilder::from(plain) + .with_projection(Some(projection)) + .build() + .context(DataFusionPlanningSnafu)?; + input = LogicalPlan::TableScan(scan.clone()); + scan + } + } _ => return Ok(declined("selector_plan_is_not_a_table_scan")), } } @@ -435,7 +484,7 @@ impl PromPlanner { .partition_column_names() .all(|column| tags.iter().any(|tag| tag == column)); // Every field must read as one kind: `Float64` or the native histogram struct; any other - // type, or a statement whose fields disagree, keeps the existing plan. The raw scan casts + // type, or a statement whose fields disagree, refuses the statement. The raw scan casts // numeric fields to `Float64`, and the answer publishes `Float64` even where the existing // plan keeps the field's own type, as in the Prometheus data model. let read_types = fields @@ -471,7 +520,7 @@ impl PromPlanner { return Ok(declined("selector_plan_is_not_a_table_scan")); } if reads_rows { - input = row_source_input(input, &tags, &time, &fields, matchers)?; + input = row_source_input(input, &tags, &time, &fields, matchers, alternative_groups)?; input = LogicalPlan::Extension(Extension { node: Arc::new( RowSeriesSource::try_new( @@ -486,6 +535,7 @@ impl PromPlanner { }); } else { let mut filters = Self::matchers_to_expr(matchers, input.schema())?; + filters.extend(alternative_conjuncts(alternative_groups, input.schema())?); if let LogicalPlan::TableScan(table_scan) = &mut input { table_scan.filters.append(&mut filters); } @@ -698,8 +748,8 @@ impl PromPlanner { /// Combines two native operands without a legacy join. /// - /// Each operand of a binary expression is planned as an evaluated series frame. Declines when - /// the grids differ or the kernels cannot answer the matching or output kind. + /// A scalar operand enters the node as the compiled scalar rather than as an input; a shape the + /// kernels refuse declines with the cause the route records, never to the existing plan. async fn try_plan_native_composed_binary( &mut self, expr: &PromExpr, @@ -721,55 +771,34 @@ impl PromPlanner { return Ok(None); }; let saved = self.ctx.clone(); - let _ = take_native_decline(); - let left = self - .try_plan_native( - &binary.lhs, - query_engine_state, - FusedOutputFormat::SeriesFrame, - ) - .await; - let left_cause = take_native_decline(); - self.ctx = saved.clone(); - let Some(NativePlanned::Frame(left)) = left? else { - return Ok(declined( - left_cause.unwrap_or("left_operand_is_not_a_frame"), - )); - }; - let _ = take_native_decline(); - let right = self - .try_plan_native( - &binary.rhs, - query_engine_state, - FusedOutputFormat::SeriesFrame, - ) - .await; - let right_cause = take_native_decline(); - self.ctx = saved; - let Some(NativePlanned::Frame(right)) = right? else { - return Ok(declined( - right_cause.unwrap_or("right_operand_is_not_a_frame"), - )); - }; - if left.grid.spec() != right.grid.spec() { - return Ok(declined("operand_grids_differ")); + // Only vector sides are offered as frames below: a scalar is bound afterwards, against the + // grid the frame it meets answers on. + let is_scalar = |operand: &PromExpr| operand.value_type() == ValueType::Scalar; + let (left_scalar, right_scalar) = (is_scalar(&binary.lhs), is_scalar(&binary.rhs)); + if left_scalar && right_scalar { + return Ok(None); } - let NativeFramePlan { - plan: left_plan, - output: left_output, - tags: left_tags, - kind: left_kind, - time: left_time, - grid: left_grid, - } = left; - let NativeFramePlan { - plan: right_plan, - output: right_output, - tags: right_tags, - kind: right_kind, - .. - } = right; - let source_tags = [left_tags, right_tags]; + let mut frames: [Option; 2] = [None, None]; + for (index, operand) in [&binary.lhs, &binary.rhs].into_iter().enumerate() { + if is_scalar(operand) { + continue; + } + let _ = take_native_decline(); + let planned = self + .try_plan_native(operand, query_engine_state, FusedOutputFormat::SeriesFrame) + .await; + let cause = take_native_decline(); + self.ctx = saved.clone(); + let Some(NativePlanned::Frame(frame)) = planned? else { + return Ok(declined(cause.unwrap_or(if index == 0 { + "left_operand_is_not_a_frame" + } else { + "right_operand_is_not_a_frame" + }))); + }; + frames[index] = Some(frame); + } + self.ctx = saved; let evaluated = |source_index, output: &NativeType| NativeNode { expr: NativeExpr::Input(BoundInput { source_index, @@ -779,23 +808,162 @@ impl PromPlanner { }), output: output.clone(), }; - let tree = match bind_evaluated_binary( - binary, - evaluated(0, &left_output), - evaluated(1, &right_output), - ) { + let [left_frame, right_frame] = frames; + let (tree, children, source_tags, time, grid, kinds) = match (left_frame, right_frame) { + (Some(left), Some(right)) => { + if left.grid.spec() != right.grid.spec() { + return Ok(declined("operand_grids_differ")); + } + let NativeFramePlan { + plan: left_plan, + output: left_output, + tags: left_tags, + kind: left_kind, + time: left_time, + grid: left_grid, + } = left; + let NativeFramePlan { + plan: right_plan, + output: right_output, + tags: right_tags, + kind: right_kind, + .. + } = right; + let tree = match bind_evaluated_binary( + binary, + evaluated(0, &left_output), + evaluated(1, &right_output), + ) { + Ok(tree) => tree, + Err(DataFusionError::NotImplemented(_)) => { + return Ok(declined("no_kernel_for_the_operator_pair")); + } + Err(error) => return Err(error).context(DataFusionPlanningSnafu), + }; + ( + tree, + vec![left_plan, right_plan], + vec![left_tags, right_tags], + left_time, + left_grid, + (left_kind, right_kind), + ) + } + // One side is a scalar: a broadcast over the frame side, which is then the node's only + // input, while the scalar enters as the compiled node beside it. + (left, right) => { + let Some(frame) = left.or(right) else { + return Ok(declined("composition_has_no_frame_operand")); + }; + let scalar_expr = if left_scalar { + &binary.lhs + } else { + &binary.rhs + }; + let Some(scalar) = self.native_scalar_operand(scalar_expr, &frame.grid)? else { + return Ok(None); + }; + // Prometheus does define a per-point scale of a histogram (`h / time()`), but the + // dynamic-scalar kernel errors on a non-float sample instead of scaling it + // (`#10812`), so the pair is refused until that kernel answers histograms. + if frame.kind == FieldKind::Histogram && constant_value(scalar_expr).is_none() { + return Ok(declined("histogram_over_a_dynamic_scalar")); + } + let NativeFramePlan { + plan, + output, + tags, + kind, + time, + grid, + } = frame; + let vector = evaluated(0, &output); + let (left, right) = if left_scalar { + (scalar, vector) + } else { + (vector, scalar) + }; + let kinds = if left_scalar { + (FieldKind::Float, kind) + } else { + (kind, FieldKind::Float) + }; + let tree = match bind_evaluated_broadcast(binary, left, right) { + Ok(tree) => tree, + Err(DataFusionError::NotImplemented(_)) => { + return Ok(declined("no_kernel_for_the_operator_pair")); + } + Err(error) => return Err(error).context(DataFusionPlanningSnafu), + }; + (tree, vec![plan], vec![tags], time, grid, kinds) + } + }; + Self::publish_native_composition( + expr, + format, + tree, + &source_tags, + children, + time, + grid, + kinds, + ) + } + + /// The scalar node a composition broadcasts over its vector side, or `None` when this route + /// does not bind one. + fn native_scalar_operand( + &self, + expr: &PromExpr, + grid: &Arc, + ) -> Result> { + let Some(stmt) = self.native_statement(expr) else { + return Ok(declined("scalar_operand_has_no_evaluation_grid")); + }; + let Ok(statement) = statement_grid(&stmt) else { + return Ok(declined("statement_grid_unavailable")); + }; + if statement.spec() != grid.spec() { + return Ok(declined("operand_grids_differ")); + } + let tree = match compile_statement_with_grid(&stmt, statement) { Ok(tree) => tree, Err(DataFusionError::NotImplemented(_)) => { - return Ok(declined("no_kernel_for_the_operator_pair")); + return Ok(declined("scalar_operand_has_no_kernel")); } Err(error) => return Err(error).context(DataFusionPlanningSnafu), }; + let evaluated = matches!( + &tree.root().output, + NativeType::Scalar(scalar) if scalar.spec() == grid.spec() + ); + if !evaluated { + return Ok(declined("scalar_operand_is_not_a_scalar")); + } + Ok(Some(tree.root().clone())) + } + + /// Publishes a bound composition as one node over `children`. + /// + /// `kinds` are the pair's kinds in the order the operands were written, a scalar side being a + /// float; `source_tags` names each child's labels. + #[allow(clippy::too_many_arguments)] + fn publish_native_composition( + expr: &PromExpr, + format: FusedOutputFormat, + tree: NativeTree, + source_tags: &[Vec], + children: Vec, + time: String, + grid: Arc, + kinds: (FieldKind, FieldKind), + ) -> Result> { let NativeExpr::Binary { matching, .. } = &tree.root().expr else { return Ok(declined("bound_root_is_not_the_binary")); }; let Some(root_kind) = binary_output_field_kind( - left_kind, - right_kind, + kinds.0, + kinds.1, matching.op, matching.return_bool, matching.fill, @@ -809,7 +977,7 @@ impl PromPlanner { let metadata = match format { FusedOutputFormat::PlainRows => None, FusedOutputFormat::SeriesFrame => { - let Some(tags) = fused_output_tags(tree.root(), &source_tags) else { + let Some(tags) = fused_output_tags(tree.root(), source_tags) else { return Ok(declined("composition_has_no_output_labels")); }; Some((tree.root().output.clone(), tags)) @@ -817,13 +985,8 @@ impl PromPlanner { }; let output_schema = match format { FusedOutputFormat::PlainRows => { - let Some(schema) = Self::fused_root_schema( - &expression, - &tree, - &source_tags, - &left_time, - root_kind, - )? + let Some(schema) = + Self::fused_root_schema(&expression, &tree, source_tags, &time, root_kind)? else { return Ok(declined("composition_has_no_value_columns")); }; @@ -846,12 +1009,12 @@ impl PromPlanner { Arc::from(expression.as_str()), tree, FusedSeriesBinding { - grid: Arc::clone(&left_grid), - time_index: left_time.clone(), + grid: Arc::clone(&grid), + time_index: time.clone(), tags: Vec::new(), metric_name: None, }, - vec![left_plan, right_plan], + children, output_schema, format, ) else { @@ -860,12 +1023,10 @@ impl PromPlanner { let plan = LogicalPlan::Extension(Extension { node: Arc::new(node), }); - Ok(Some(native_planned( - plan, metadata, root_kind, left_time, left_grid, - ))) + Ok(Some(native_planned(plan, metadata, root_kind, time, grid))) } - /// Plans `prom_expr` as one native node, or returns `None` to keep the existing plan. + /// Plans `prom_expr` as one native node, or returns `None` with the cause the route recorded. /// /// The expression text names the value columns. Table, time index, tag and field columns come /// from the planner's resolved selector context. @@ -961,7 +1122,8 @@ impl PromPlanner { } Err(error) => return Err(error).context(DataFusionPlanningSnafu), }; - // A scalar root has no labels to match, so it cannot be a frame operand. + // A frame consumer decodes series, and a composition binds a scalar side as the scalar + // it is, so a scalar published as a frame could not be read. let evaluated = matches!( &tree.root().output, NativeType::Samples(schema) if schema.eval_grid.is_some() @@ -1042,14 +1204,17 @@ impl PromPlanner { let mut statement_kind: Option = None; for selector in &selectors { self.ctx = original_context.clone(); - if !selector.matchers.or_matchers.is_empty() { - return Ok(declined("or_matchers_have_no_single_raw_scan")); + let Some(alternatives) = AlternativeFilters::of_selector(selector) else { + return Ok(declined("or_matchers_name_different_tables")); + }; + if let Some(reason) = alternatives.merge_refusal() { + return Ok(declined(reason)); } // A nameless selector enumerates the schema's logical metric tables, one scan each, // unioned into one input. if discovers_metric_name(selector) { - let name_matchers = selector.matchers.find_matchers(METRIC_NAME); - let mut ordinary_matchers = selector.matchers.clone(); + let name_matchers = alternatives.shared.find_matchers(METRIC_NAME); + let mut ordinary_matchers = alternatives.shared.clone(); ordinary_matchers .matchers .retain(|matcher| matcher.name != METRIC_NAME); @@ -1111,10 +1276,19 @@ impl PromPlanner { // rows, so a matcher that rejects the empty string cannot match anything there. metrics.retain(|table| { let schema = table.schema(); - matchers.matchers.iter().all(|matcher| { - matcher.is_match("") - || schema.column_schema_by_name(&matcher.name).is_some() - }) + let keeps = |matchers: &Matchers| { + matchers.matchers.iter().all(|matcher| { + matcher.is_match("") + || schema.column_schema_by_name(&matcher.name).is_some() + }) + }; + keeps(&matchers) + && (alternatives.groups.is_empty() + || alternatives + .groups + .iter() + .map(|group| &group.rows) + .any(keeps)) }); metrics.sort_by_key(|table| table.table_info().name.clone()); if metrics.len() > MAX_DISCOVERED_METRICS { @@ -1164,6 +1338,7 @@ impl PromPlanner { )) = self .prepare_one_scan( matchers.clone(), + &alternatives.groups, &mut logical_scan_id, &mut logical_ids_differ, &mut statement_kind, @@ -1258,7 +1433,7 @@ impl PromPlanner { continue; } let matchers = - match self.preprocess_label_matchers(&selector.matchers, &selector.name) { + match self.preprocess_label_matchers(&alternatives.shared, &selector.name) { Ok(m) => m, Err(_) => return Ok(declined("selector_matchers_cannot_be_preprocessed")), }; @@ -1278,6 +1453,7 @@ impl PromPlanner { let Some(one) = self .prepare_one_scan( matchers, + &alternatives.groups, &mut logical_scan_id, &mut logical_ids_differ, &mut statement_kind, @@ -2110,6 +2286,7 @@ fn row_source_input( time: &str, fields: &[String], matchers: Matchers, + alternative_groups: &[AlternativeGroup], ) -> Result { let column = |name: &str| DfExpr::Column(datafusion::common::Column::from_name(name)); let mut exprs = tags @@ -2129,7 +2306,11 @@ fn row_source_input( .context(DataFusionPlanningSnafu)? .build() .context(DataFusionPlanningSnafu)?; - let filters = PromPlanner::matchers_to_expr(matchers, projected.schema())?; + let mut filters = PromPlanner::matchers_to_expr(matchers, projected.schema())?; + filters.extend(alternative_conjuncts( + alternative_groups, + projected.schema(), + )?); let Some(predicate) = datafusion_expr::utils::conjunction(filters) else { return Ok(projected); }; @@ -2552,8 +2733,163 @@ pub(crate) fn same_table_scans<'a>(plans: impl IntoIterator, + alternative_names_a_table: bool, +} + +#[derive(Debug, Clone, PartialEq)] +struct AlternativeGroup { + rows: Matchers, + /// The `__field__` matchers this group states; `None` reads every field. + fields: Option>, +} + +fn names_what_is_read(matcher: &Matcher) -> bool { + matches!( + matcher.name.as_str(), + FIELD_COLUMN_MATCHER | METRIC_NAME | SCHEMA_COLUMN_MATCHER | DB_COLUMN_MATCHER + ) +} + +/// The selection plus `matcher`'s column, or `None` when it disagrees about the table. +fn merge_into_selection(selection: &mut Vec, matcher: &Matcher) -> Option<()> { + match matcher.name.as_str() { + FIELD_COLUMN_MATCHER => { + if !selection.contains(matcher) { + selection.push(matcher.clone()); + } + } + _ => match selection.iter().find(|held| held.name == matcher.name) { + Some(held) if held != matcher => return None, + Some(_) => {} + None => selection.push(matcher.clone()), + }, + } + Some(()) +} + +impl AlternativeFilters { + /// Splits `selector`'s matchers into what it reads and the rows each group keeps. + fn of_selector(selector: &VectorSelector) -> Option { + if selector.matchers.or_matchers.is_empty() { + return Some(Self { + shared: selector.matchers.clone(), + groups: Vec::new(), + alternative_names_a_table: false, + }); + } + // promql-parser moves the matchers before the first `or` into that `or`'s own group, so + // `selector.matchers.matchers` is empty here and every matcher arrives through a group. + let mut selection = Vec::new(); + let mut alternative_names_a_table = false; + let mut groups: Vec = + Vec::with_capacity(selector.matchers.or_matchers.len()); + for group in &selector.matchers.or_matchers { + let mut rows = Vec::new(); + let mut fields = Vec::new(); + for matcher in group { + if matcher.name == FIELD_COLUMN_MATCHER { + merge_into_selection(&mut selection, matcher)?; + fields.push(matcher.clone()); + } else if names_what_is_read(matcher) { + merge_into_selection(&mut selection, matcher)?; + alternative_names_a_table = true; + } else { + rows.push(matcher.clone()); + } + } + let group = AlternativeGroup { + rows: Matchers::new(rows), + fields: (!fields.is_empty()).then_some(fields), + }; + if !groups.contains(&group) { + groups.push(group); + } + } + Some(Self { + shared: Matchers::new(selection), + groups, + alternative_names_a_table, + }) + } + + fn merge_refusal(&self) -> Option<&'static str> { + if self.alternative_names_a_table { + return Some("or_alternatives_name_a_table"); + } + if !self + .groups + .windows(2) + .all(|pair| pair[0].fields == pair[1].fields) + { + return Some("or_alternatives_select_different_fields"); + } + None + } +} + +/// The conjuncts a selector's alternatives add to its scan. +/// +/// A group with no row filter keeps every row the shared matchers keep, so nothing narrows the scan. +fn alternative_conjuncts(groups: &[AlternativeGroup], schema: &DFSchemaRef) -> Result> { + let conjunctions = groups + .iter() + .map(|group| { + Ok(PromPlanner::matchers_to_expr(group.rows.clone(), schema)? + .into_iter() + .reduce(|left, right| left.and(right))) + }) + .collect::>>>()?; + match conjunctions.len() { + 0 => Ok(Vec::new()), + 1 => Ok(conjunctions.into_iter().flatten().collect()), + _ => { + if conjunctions.iter().any(Option::is_none) { + return Ok(Vec::new()); + } + Ok(conjunctions + .into_iter() + .flatten() + .reduce(|left, right| left.or(right)) + .into_iter() + .collect()) + } + } +} + +/// Whether a row matcher names a column the selector's own projection drops: `read` is what the +/// projection keeps, and a column the table lacks stays the empty label Prometheus compares against. +fn row_matchers_need_a_dropped_column( + matchers: &Matchers, + groups: &[AlternativeGroup], + schema: &DFSchemaRef, + read: &[&str], +) -> bool { + let named = matchers + .matchers + .iter() + .chain(groups.iter().flat_map(|group| group.rows.matchers.iter())) + .filter(|matcher| !names_what_is_read(matcher)) + .filter_map(|matcher| PromPlanner::find_case_sensitive_column(schema, &matcher.name)); + named + .into_iter() + .any(|column| !read.contains(&column.as_str())) +} + /// Whether a selector names no single table and has to enumerate the schema's metric tables. /// +/// The matchers inside a selector's `or` alternatives are row filters, so it still needs discovery. +/// /// Public so the authorization layer gives the same answer as the planner. pub fn discovers_metric_name(selector: &VectorSelector) -> bool { let name_matchers = selector.matchers.find_matchers(METRIC_NAME); @@ -2563,13 +2899,22 @@ pub fn discovers_metric_name(selector: &VectorSelector) -> bool { let has_exact_name_matcher = name_matchers.len() == 1 && !has_non_equal_name_matcher; selector.name.is_none() && !has_exact_name_matcher - && selector.matchers.or_matchers.is_empty() && (name_matchers.len() > 1 || has_non_equal_name_matcher - || selector.matchers.matchers.iter().any(|matcher| { - !["__schema__", "__database__", "__field__", METRIC_NAME] + || selector + .matchers + .matchers + .iter() + .chain(selector.matchers.or_matchers.iter().flatten()) + .any(|matcher| { + ![ + SCHEMA_COLUMN_MATCHER, + DB_COLUMN_MATCHER, + FIELD_COLUMN_MATCHER, + METRIC_NAME, + ] .contains(&matcher.name.as_str()) - })) + })) } /// One side of a set operation, as the slice of the pre-order selector list it reads. @@ -2814,6 +3159,34 @@ fn metric_scan_and_table_id( Some((scan.clone(), filter.predicate.clone(), *table_id)) } +/// The scan projection that reads `fields` followed by the scan's non-field columns: the region scan +/// requires the requested field sequence to match its projection exactly, so a field column `fields` +/// does not name is dropped rather than read beside the selection. +fn field_first_projection( + scan: &datafusion::logical_expr::TableScan, + fields: &[String], + table_fields: &[String], +) -> Option> { + let source_schema = scan.source.schema(); + let mut projection = fields + .iter() + .map(|field| source_schema.index_of(field).ok()) + .collect::>>()?; + let read_indices = scan + .projection + .clone() + .unwrap_or_else(|| (0..source_schema.fields().len()).collect()); + for index in read_indices { + let is_field = table_fields + .iter() + .any(|field| field == source_schema.field(index).name()); + if !is_field && !projection.contains(&index) { + projection.push(index); + } + } + Some(projection) +} + #[cfg(test)] mod tests { use std::sync::Arc; diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index be918883fde..3bf05514d9b 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -56,7 +56,7 @@ use promql::native::plan::{ AggregateKind, AggregateStage, BoundVectorOp, Grouping, NativeExpr, NativeNode, NativeType, ParameterizedOp, unifies_its_own_contributions, }; -use promql::vector_match::{Cardinality, MatchingLabels}; +use promql::vector_match::{Cardinality, FillValues, MatchingLabels}; use promql_parser::label::{Labels, METRIC_NAME}; use promql_parser::parser; use session::context::{MetricDiscoveryScope, QueryContext, QueryContextRef}; @@ -1520,6 +1520,194 @@ async fn build_test_table_provider_with_options( ) } +/// `some_metric` with two tag columns - `tag_0` and `tag_1` - and one `Float64` field. +async fn native_two_tag_provider() -> DfTableSourceProvider { + build_test_table_provider_with_options( + &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], + 2, + 1, + vec![], + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ConcreteDataType::float64_datatype(), + NATIVE_ENGINE, + ) + .await +} + +/// `some_metric` with three `Float64` fields - `field_0` to `field_2` - in the order listed. +async fn native_field_selector_provider() -> DfTableSourceProvider { + build_test_table_provider_with_options( + &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], + 1, + 3, + vec![], + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ConcreteDataType::float64_datatype(), + NATIVE_ENGINE, + ) + .await +} + +/// `some_metric` with a `Float64` value column and a text column in the key when `keyed`. +async fn build_test_text_field_table_provider(keyed: bool) -> DfTableSourceProvider { + let catalog_list = MemoryCatalogManager::with_default_setup(); + let mut columns = vec![ColumnSchema::new( + "tag_0".to_string(), + ConcreteDataType::string_datatype(), + false, + )]; + if keyed { + columns.push(ColumnSchema::new( + "text_field".to_string(), + ConcreteDataType::string_datatype(), + false, + )); + } + columns.push( + ColumnSchema::new( + "timestamp".to_string(), + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ) + .with_time_index(true), + ); + if !keyed { + columns.push(ColumnSchema::new( + "text_field".to_string(), + ConcreteDataType::string_datatype(), + true, + )); + } + let mut value_indices = Vec::new(); + if !keyed { + value_indices.push(columns.len() - 1); + } + columns.push(ColumnSchema::new( + "field_0".to_string(), + ConcreteDataType::float64_datatype(), + true, + )); + value_indices.push(columns.len() - 1); + let primary_key_indices = (0..columns.len()) + .filter(|index| columns[*index].name != "timestamp" && !value_indices.contains(index)) + .collect::>(); + build_one_native_table( + catalog_list, + columns, + primary_key_indices, + value_indices, + NATIVE_ENGINE, + ) +} + +/// `some_metric` with a `Float64` column `val` and a text column `status` outside the key. +/// +/// `row_source` states the file engine and a second-precision time index, which the scan casts +/// through the projection the row source reads. +async fn build_test_unread_text_column_table_provider(row_source: bool) -> DfTableSourceProvider { + let timestamp_type = if row_source { + ConcreteDataType::timestamp_second_datatype() + } else { + ConcreteDataType::timestamp_millisecond_datatype() + }; + let columns = vec![ + ColumnSchema::new( + "tag_0".to_string(), + ConcreteDataType::string_datatype(), + false, + ), + ColumnSchema::new("timestamp".to_string(), timestamp_type, false).with_time_index(true), + ColumnSchema::new( + "val".to_string(), + ConcreteDataType::float64_datatype(), + true, + ), + ColumnSchema::new( + "status".to_string(), + ConcreteDataType::string_datatype(), + true, + ), + ]; + build_one_native_table( + MemoryCatalogManager::with_default_setup(), + columns, + vec![0], + vec![2, 3], + if row_source { + FILE_ENGINE + } else { + NATIVE_ENGINE + }, + ) +} + +/// `some_metric` whose only value column is text, so the table has no value column to read. +async fn build_test_text_only_table_provider() -> DfTableSourceProvider { + let catalog_list = MemoryCatalogManager::with_default_setup(); + let columns = vec![ + ColumnSchema::new( + "tag_0".to_string(), + ConcreteDataType::string_datatype(), + false, + ), + ColumnSchema::new( + "timestamp".to_string(), + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ) + .with_time_index(true), + ColumnSchema::new( + "text_field".to_string(), + ConcreteDataType::string_datatype(), + true, + ), + ]; + build_one_native_table(catalog_list, columns, vec![0], vec![2], NATIVE_ENGINE) +} + +fn build_one_native_table( + catalog_list: Arc, + columns: Vec, + primary_key_indices: Vec, + value_indices: Vec, + engine: &str, +) -> DfTableSourceProvider { + let table_meta = TableMetaBuilder::empty() + .schema(Arc::new(Schema::new(columns))) + .engine(engine.to_string()) + .primary_key_indices(primary_key_indices) + .value_indices(value_indices) + .next_column_id(1024) + .build() + .unwrap(); + let table_info = TableInfoBuilder::default() + .name("some_metric".to_string()) + .meta(table_meta) + .build() + .unwrap(); + let table = EmptyTable::from_table_info(&table_info); + assert!( + catalog_list + .register_table_sync(RegisterTableRequest { + catalog: DEFAULT_CATALOG_NAME.to_string(), + schema: DEFAULT_SCHEMA_NAME.to_string(), + table_name: "some_metric".to_string(), + table_id: 1024, + table, + }) + .is_ok() + ); + DfTableSourceProvider::new( + catalog_list, + false, + QueryContext::arc(), + DummyDecoder::arc(), + false, + ) +} + async fn build_test_native_histogram_table_provider(table_name: &str) -> DfTableSourceProvider { build_test_native_histogram_table_provider_with_marker(table_name, false).await } @@ -2837,16 +3025,15 @@ async fn native_named_selector_over_a_missing_table_plans_as_an_empty_input() { } } - // A `__field__` matcher is refused over a table this route can read: the matcher narrows the - // field set of the scan below the node, and the raw series scan reports every field the scan - // carries. That refusal is about the scan, not about the table existing - a missing table has no - // field set to narrow and is admitted as the empty input, which - // `native_missing_table_with_a_field_matcher_answers_the_empty_vector` asserts beside its rows. + // A `__field__` matcher narrows the scan to the fields it names, so a table that exists is + // admitted with that projection rather than refused for its scan's field set. let query = r#"x{__field__="field_0"}"#; - assert_eq!( - "field_selector_without_raw_series_equivalent", - native_decline_reason(query, named_missing_table_provider().await).await, - "`{query}` narrows a field set the raw series scan reports in full" + let plan = + build_native_fused_plan_with_provider(query, true, named_missing_table_provider().await) + .await; + assert!( + find_fused_series(&plan).is_some(), + "`{query}` narrows the scan to the field it names: {plan:?}" ); } @@ -3566,6 +3753,46 @@ fn find_fused_series(plan: &LogicalPlan) -> Option<&FusedSeries> { plan.inputs().into_iter().find_map(find_fused_series) } +/// Whether `field` holds sample values: the native route declares one output column per field. +fn is_value_column(field: &Field) -> bool { + field.data_type() == &ArrowDataType::Float64 + || field.data_type() + == &common_query::native_histogram::native_histogram_value_type().as_arrow_type() +} + +/// The field columns the narrowed scan of the plan projects, in the order it reads them. +fn scan_projected_field_names(plan: &LogicalPlan) -> Option> { + fn visit<'a>(plan: &'a LogicalPlan, selection: &mut Option>) { + if let LogicalPlan::TableScan(scan) = plan + && scan.projection.is_some() + { + let fields = scan + .projected_schema + .fields() + .iter() + .filter(|field| is_value_column(field)) + .map(|field| field.name().as_str()) + .collect::>(); + selection.get_or_insert(fields); + } + for input in plan.inputs() { + visit(input, selection); + } + } + + let mut selection = None; + visit(plan, &mut selection); + selection +} + +fn value_field_count(plan: &LogicalPlan) -> usize { + plan.schema() + .fields() + .iter() + .filter(|field| is_value_column(field)) + .count() +} + /// The value column of a native producer's output. /// /// The native route names a value column after the expression that produced it, not after the @@ -4812,19 +5039,40 @@ async fn native_offer_is_counted_once_per_statement() { ); } -/// A propagated matcher is offered once for the operand it rewrote, and nothing below it. -/// -/// `matching_filters::propagate` writes a matcher into an operand's scan, which makes that operand -/// an expression the offer spent at its parent never compiled: that offer read the statement as it -/// was written, and the matcher reached the scan afterwards. The rewrite is therefore offered of -/// its own, and the offer it is handed is spent again by the rewritten operand's own subtree, -/// exactly as this one was. So `N` operators below the rewrite buy one offer - not `N`, and not the -/// `N` positions times `N` subtrees an unconditional re-offer would compile. +/// Every table scan the plan carries, in the order the plan lists them. +fn table_scans(plan: &LogicalPlan) -> Vec { + fn visit(plan: &LogicalPlan, scans: &mut Vec) { + if let LogicalPlan::TableScan(scan) = plan { + scans.push(scan.clone()); + } + for input in plan.inputs() { + visit(input, scans); + } + } + + let mut scans = Vec::new(); + visit(plan, &mut scans); + scans +} + +/// The `name = value` matcher a statement states, as the predicate a scan carries for it: asserting +/// on the predicate says the matcher reached the scan, not that a rendering contains it. +fn tag_is(name: &str, value: &str) -> DfExpr { + let value = DfExpr::Literal(ScalarValue::Utf8(Some(value.to_string())), None); + DfExpr::Column(Column::from_name(name)).eq(value) +} + +/// The `tag_0 = "x"` matcher the propagation fixtures state. +fn tag_0_is_x() -> DfExpr { + tag_is("tag_0", "x") +} + +/// A statement is offered to the native route once, whatever the depth of the operand below it: the +/// offer compiles the whole tree, so `N` operators under a binary buy one offer. #[tokio::test] async fn native_offer_counts_a_propagated_operand_once() { - // The same match with the rewritten operand two operators deep and six deep: the matcher - // crosses in both, and the four extra operators are the operand's subtree rather than more - // expressions to offer. + // The same match with the operand under it two operators deep and six deep: the four extra + // operators are that operand's subtree rather than more expressions to offer. let shallow = "((some_metric * 2) * 2) / on(tag_0) \ some_metric{tag_0=\"x\",__field__=\"field_0\"}"; let deep = "((((((some_metric * 2) * 2) * 2) * 2) * 2) * 2) / on(tag_0) \ @@ -4832,25 +5080,35 @@ async fn native_offer_counts_a_propagated_operand_once() { let mut counts = Vec::new(); for query in [shallow, deep] { let _ = take_native_attempts(); + let plan = build_native_fused_plan(query, true).await; + // One scan per operand, and the matcher is a filter of the one that states it. + let scans = table_scans(&plan); assert_eq!( - "field_selector_without_raw_series_equivalent", - native_decline_reason(query, build_native_fused_table_provider().await).await, - "{query}: the propagated `__field__` operand narrows a field set the raw scan reports" + 2, + scans.len(), + "`{query}` reads one scan per operand: {}", + plan.display_indent() + ); + assert_eq!( + 1, + scans + .iter() + .filter(|scan| scan.filters.contains(&tag_0_is_x())) + .count(), + "`{query}`: the stated matcher filters its own scan and no other: {}", + plan.display_indent() ); counts.push(take_native_attempts()); } - // Three offers either way: the statement, the frame operand the whole attempt reads, and the - // composition's own retry. The four operators that make the deep statement deeper are inside - // that operand's subtree, so they buy no offer of their own - an offer that was not spent again - // by the rewrite would compile each of them, and the deep statement would cost four more. + // One offer either way: a per-operator re-offer would make the deep answer five rather than one. assert_eq!( - (3, 3), + (1, 1), (counts[0], counts[1]), - "a propagated operand is offered once whatever its depth: three offers at both depths" + "a statement is offered once, whatever the depth of the operand below it" ); } -/// The same matcher-propagating match, with its rewritten operand `depth` operators deep. +/// The same matcher-carrying match, with the operand beside it `depth` operators deep. fn propagation_query(depth: usize) -> String { let operand = (0..depth).fold("some_metric".to_string(), |inner, _| { format!("({inner} * 2)") @@ -4858,16 +5116,21 @@ fn propagation_query(depth: usize) -> String { format!("{operand} / on(tag_0) some_metric{{tag_0=\"x\",__field__=\"field_0\"}}") } -/// How a statement of [`propagation_query`] is answered: with the cause the route refuses it for. -async fn propagation_route(depth: usize) -> String { - native_decline_reason( - &propagation_query(depth), - build_native_fused_table_provider().await, +/// How a statement of [`propagation_query`] plans: whether a native node answers it, and whether +/// the matcher the statement states became a filter of the scan it binds. +async fn propagation_route(depth: usize) -> (bool, bool) { + let plan = build_native_fused_plan(&propagation_query(depth), true).await; + ( + find_fused_series(&plan).is_some(), + table_scans(&plan) + .iter() + .filter(|scan| scan.filters.contains(&tag_0_is_x())) + .count() + == 1, ) - .await } -/// A chain under a propagated matcher plans on the stack a query worker has, however deep it is. +/// A chain beside a matcher-carrying operand plans on the stack a query worker has. /// /// The planner recurses once per operator and charges every level's frame to the stack of the level /// above it, so a chain of constant multiplications deep enough - eight operators was enough on a @@ -4900,8 +5163,9 @@ fn a_deep_propagated_operand_plans_within_a_worker_stack() { .join() .expect("operands 2, 8, 10 and 12 operators deep plan on a two-megabyte stack"); assert_eq!( - "field_selector_without_raw_series_equivalent", route, - "the propagated `__field__` operand narrows a field set at any depth" + (true, true), + route, + "the statement is native and the matcher it states filters the scan it binds" ); } @@ -5145,21 +5409,28 @@ async fn native_fused_refuses_an_unknown_statement_extension() { /// * 2` casts a string as readily as an integer, and no raw frame can hold the values. #[tokio::test] async fn native_fused_unsupported_field_type_is_declined() { - for field_type in [ - ConcreteDataType::string_datatype(), - ConcreteDataType::boolean_datatype(), + for (field_type, reason) in [ + // A text column is no value kind of this route's at all, so it is named as such. + ( + ConcreteDataType::string_datatype(), + "text_field_is_not_a_table_key", + ), + (ConcreteDataType::boolean_datatype(), "mixed_field_kinds"), // Arrow's `is_numeric` includes the decimals, so a decimal field only stays out because // the route's own numeric set leaves the decimals out; asking Arrow would let it through. - ConcreteDataType::decimal128_datatype(10, 2), + ( + ConcreteDataType::decimal128_datatype(10, 2), + "mixed_field_kinds", + ), ] { - for (query, reason) in [ - ("some_metric", "mixed_field_kinds"), + for query in [ + "some_metric", // The scalar operand has no raw kind at all, so the pair is refused before the kinds // are compared. - ("some_metric * 2", "mixed_field_kinds"), - ("sum(some_metric)", "mixed_field_kinds"), - ("min(some_metric)", "mixed_field_kinds"), - ("rate(some_metric[5m])", "mixed_field_kinds"), + "some_metric * 2", + "sum(some_metric)", + "min(some_metric)", + "rate(some_metric[5m])", ] { assert_eq!( reason, @@ -5191,25 +5462,6 @@ async fn native_fused_float64_field_is_accepted() { ); } -/// Alternative (`or`) matchers are refused, naming the one scan they cannot share. -/// -/// `a{x="1" or x="2"}` names alternative matchers, which the one scan below the node cannot -/// represent. These queries are only asserted to be refused: what another planner answers for them -/// is its own question, not one this route claims to have fixed. -#[tokio::test] -async fn native_fused_or_matchers_are_declined() { - for query in [ - r#"some_metric{tag_0="a" or tag_0="b"}"#, - r#"rate(some_metric{tag_0="a" or tag_0="b"}[5m])"#, - ] { - assert_eq!( - "or_matchers_have_no_single_raw_scan", - native_decline_reason(query, build_native_fused_table_provider().await).await, - "`{query}` names alternative matchers" - ); - } -} - /// `rate` and `increase` over a table carrying the OTLP temporality marker run natively, also /// through a subquery: the window picks the delta math per series from the labels that reach it, /// as the existing planner does. @@ -6124,16 +6376,14 @@ async fn native_composed_binary_admits_complex_operands() { /// A composed binary that meets a shape its kernels refuse is refused with that cause. /// /// Admission is the composition's own: an operand the native compiler cannot bind, a value that is -/// not a frame, or a pair whose output column cannot carry both operands' kinds declines here -/// exactly as it would on the whole statement - and a declined offer is the statement's answer. +/// not a frame, nor a scalar it can bind, or a pair whose output column cannot carry both +/// operands' kinds, declines here with that cause rather than planning the statement another way. #[tokio::test] async fn native_composed_binary_declines_with_its_cause() { for query in [ - // A scalar root is not a frame: composing it by vector matching would broadcast it as if it - // were a one-series vector, which is not what the query asked for. - "(hist * on(tag_0) floats) * 2", - // Neither is a scalar function, however it is written. - "(hist * on(tag_0) floats) / time()", + // A scalar that reads data is a tree over a scan, not a value bound on the statement's grid. + "(hist * on(tag_0) floats) / scalar(sum(floats))", + "(hist * on(tag_0) floats) * scalar(floats)", // A comparison between a histogram and a float is not a refusal: its two sides pair no // sample, so the column is the empty float layout and the statement composes. // `native_fused_mixed_comparison_answers_the_empty_float_layout` states that shape, and @@ -6141,9 +6391,9 @@ async fn native_composed_binary_declines_with_its_cause() { // the same empty answer. ] { assert_eq!( - "frame_operand_is_not_evaluated", + "scalar_operand_has_no_kernel", native_decline_reason(query, native_mixed_kind_provider().await).await, - "`{query}`: the scalar operand has no evaluated frame" + "`{query}`: the scalar operand reads data rather than answering one value" ); } } @@ -9317,26 +9567,378 @@ async fn native_metric_discovery_name_rewrite_canonicalizes_by_name() { ); } -/// A propagated matcher re-plans a scalar operand of the other side natively, and the native -/// output name includes the matcher it now carries. The outer legacy binary must read the field -/// columns the re-planned operand publishes, not the ones captured before propagation. +/// A `__field__` operand beside a scalar-multiplied one keeps the matcher it was written with, and +/// the scan it binds projects the field it names. +/// +/// The matcher is not propagated into the operand beside it (see `matching_filters::propagate`). #[tokio::test] -async fn native_fused_rewritten_scalar_operand_is_refused_with_the_statement() { +async fn native_fused_rewritten_scalar_operand_uses_rewritten_field_columns() { let query = r#"(some_metric * 2) / on(tag_0) some_metric{tag_0="x",__field__="field_0"}"#; + let plan = build_native_fused_plan(query, true).await; + let display = plan.display_indent().to_string(); + let scans = table_scans(&plan); + assert_eq!(2, scans.len(), "one scan per operand: {display}"); assert_eq!( - "field_selector_without_raw_series_equivalent", - native_decline_reason(query, build_native_fused_table_provider().await).await, - "the propagated `__field__` operand narrows a field set the raw scan reports" + 1, + scans + .iter() + .filter(|scan| scan.filters.contains(&tag_0_is_x())) + .count(), + "the matcher filters the scan of the operand that states it and no other: {display}" ); + assert_eq!( + Some(vec!["field_0"]), + scan_projected_field_names(&plan), + "the narrowed scan reads the selected field: {display}" + ); +} + +/// A `__field__` operand of a composition plans natively: the selection is the scan's projection. +#[tokio::test] +async fn native_field_selector_operand_of_a_composition_plans_natively() { + for query in [ + r#"(some_metric * 2) / on(tag_0) some_metric{tag_0="x",__field__="field_0"}"#, + r#"absent(vector(1)) + on(tag_0) some_metric{tag_0="x",__field__="field_0"}"#, + ] { + let provider = native_field_selector_provider().await; + let native = build_native_fused_plan_with_provider(query, true, provider).await; + let display = native.display_indent().to_string(); + assert!( + count_fused_nodes(&native) > 0, + "`{query}` keeps the existing plan instead of running natively: {display}" + ); + assert!( + !display.contains("PromSeriesNormalize"), + "`{query}` reads through a native node and not the existing normalization: {display}" + ); + assert_eq!( + Some(vec!["field_0"]), + scan_projected_field_names(&native), + "`{query}`: {display}" + ); + + let legacy = build_native_fused_plan_with_provider( + query, + false, + native_field_selector_provider().await, + ) + .await; + assert_eq!( + value_field_count(&native), + value_field_count(&legacy), + "`{query}` publishes the fields the existing plan publishes: {}", + legacy.display_indent() + ); + } +} + +/// A `__field__` matcher selects what a native selector reads, under every operator the existing +/// plan supports, and in the same field order. +#[tokio::test] +async fn native_field_selector_reads_the_fields_it_names() { + for (query, expected) in [ + (r#"some_metric{__field__="field_1"}"#, vec!["field_1"]), + ( + r#"some_metric{__field__!="field_1"}"#, + vec!["field_0", "field_2"], + ), + ( + r#"some_metric{__field__=~"field_(0|2)"}"#, + vec!["field_0", "field_2"], + ), + (r#"some_metric{__field__!~"field_(0|2)"}"#, vec!["field_1"]), + // The fields keep the table's order, whatever order the matchers are stated in. + ( + r#"some_metric{__field__="field_2", __field__="field_0"}"#, + vec!["field_0", "field_2"], + ), + // A `=~` that matches no field keeps every field, as the existing plan does. + ( + r#"some_metric{__field__=~"nope.*"}"#, + vec!["field_0", "field_1", "field_2"], + ), + ] { + let native = build_native_fused_plan_with_provider( + query, + true, + native_field_selector_provider().await, + ) + .await; + let display = native.display_indent().to_string(); + assert_eq!( + Some(expected), + scan_projected_field_names(&native), + "`{query}`: {display}" + ); + let legacy = build_native_fused_plan_with_provider( + query, + false, + native_field_selector_provider().await, + ) + .await; + assert_eq!( + value_field_count(&native), + value_field_count(&legacy), + "`{query}` publishes the fields the existing plan publishes: {}", + legacy.display_indent() + ); + } + + // A matcher naming a column the table does not carry is an error in the existing plan, and a + // selection that keeps no field has no value to read: both refuse the statement with the cause + // they name. + for (query, refusal) in [ + ( + r#"some_metric{__field__="nonexistent"}"#, + "field_selector_names_a_column_the_table_lacks", + ), + ( + r#"some_metric{__field__!="nonexistent"}"#, + "field_selector_names_a_column_the_table_lacks", + ), + ( + r#"some_metric{__field__="field_0", __field__!="field_0"}"#, + "selector_reads_no_field", + ), + ] { + assert_eq!( + refusal, + native_decline_reason(query, native_field_selector_provider().await).await, + "`{query}` has no field selection this route can state" + ); + } +} + +/// A selector's `or` alternatives are one predicate on the one scan below the node, so a series both +/// groups keep is read once. +#[tokio::test] +async fn native_alternatives_read_as_one_scan() { + for (statement, expected) in [ + ( + r#"some_metric{tag_1="a", tag_0="x" or tag_0="y"}"#, + tag_is("tag_1", "a") + .and(tag_is("tag_0", "x")) + .or(tag_is("tag_0", "y")), + ), + ( + r#"some_metric{tag_1="a", tag_0="x" or tag_1="a", tag_0="y"}"#, + tag_is("tag_1", "a") + .and(tag_is("tag_0", "x")) + .or(tag_is("tag_1", "a").and(tag_is("tag_0", "y"))), + ), + ( + r#"rate(some_metric{tag_1="a", tag_0="x" or tag_0="y"}[5m])"#, + tag_is("tag_1", "a") + .and(tag_is("tag_0", "x")) + .or(tag_is("tag_0", "y")), + ), + ] { + let native = + build_native_fused_plan_with_provider(statement, true, native_two_tag_provider().await) + .await; + let display = native.display_indent().to_string(); + assert!( + find_fused_series(&native).is_some(), + "`{statement}` keeps the existing plan: {display}" + ); + let scans = table_scans(&native); + assert_eq!( + 1, + scans.len(), + "`{statement}` reads one scan, not one per alternative: {display}" + ); + assert!( + scans[0].filters.contains(&expected), + "`{statement}`: the alternatives are one disjunction: {display} / {:?}", + scans[0].filters + ); + } + + // Alternatives that read the same field are one selection, whatever rows each keeps. + let native = build_native_fused_plan_with_provider( + r#"some_metric{__field__="field_0", tag_0="x" or __field__="field_0", tag_0="y"}"#, + true, + native_field_selector_provider().await, + ) + .await; + assert_eq!( + Some(vec!["field_0"]), + scan_projected_field_names(&native), + "`__field__` alternatives that agree read the field they name: {}", + native.display_indent() + ); + + // Alternatives that name different tables read two tables, which one scan cannot state. + let provider = build_test_table_provider_with_options( + &[ + (DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string()), + (DEFAULT_SCHEMA_NAME.to_string(), "other_metric".to_string()), + ], + 1, + 1, + vec![], + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ConcreteDataType::float64_datatype(), + NATIVE_ENGINE, + ) + .await; + assert_eq!( + "or_matchers_name_different_tables", + native_decline_reason( + r#"{__name__="some_metric" or __name__="other_metric"}"#, + provider + ) + .await, + "a cross-table alternative has no one scan to read" + ); +} + +/// Alternatives one scan cannot answer as they are written are refused: a single scan reads one +/// field list, and one table, for every alternative. +#[tokio::test] +async fn native_alternatives_one_scan_cannot_answer_are_refused() { + for (statement, refusal) in [ + // Alternatives that read different fields: one projection cannot keep them apart. + ( + r#"some_metric{__field__="field_0", tag_0="x" or __field__="field_1", tag_0="y"}"#, + "or_alternatives_select_different_fields", + ), + ( + r#"some_metric{__field__="field_0", tag_0="x" or __field__="field_1"}"#, + "or_alternatives_select_different_fields", + ), + // An alternative that names no field reads the whole table's. + ( + r#"some_metric{__field__="field_0", tag_0="x" or tag_0="y"}"#, + "or_alternatives_select_different_fields", + ), + ( + r#"some_metric{__field__="field_0" or __field__="field_2"}"#, + "or_alternatives_select_different_fields", + ), + // An alternative that names a table would have one scan read it for its siblings too. + ( + r#"some_metric{__schema__="secret", tag_0="x" or tag_0="y"}"#, + "or_alternatives_name_a_table", + ), + ( + r#"some_metric{__database__="secret", tag_0="x" or tag_0="y"}"#, + "or_alternatives_name_a_table", + ), + ( + r#"{__name__="some_metric", tag_0="x" or tag_0="y"}"#, + "or_alternatives_name_a_table", + ), + ] { + assert_eq!( + refusal, + native_decline_reason(statement, native_field_selector_provider().await).await, + "`{statement}` is refused: one scan cannot state it" + ); + } +} + +/// A text column is not a value kind: it reaches the route as a label the raw scan binds from the +/// primary key, or as a column that has no place here at all. +#[tokio::test] +async fn native_text_columns_are_not_value_kinds() { + // A table that keys by its text column reads a value field of its own. + let keyed = r#"some_metric{tag_0="x"}"#; + take_reported_decline(); + let native = build_native_fused_plan_with_provider( + keyed, + true, + build_test_text_field_table_provider(true).await, + ) + .await; + assert_eq!( + None, + take_reported_decline(), + "a text column the table keys by is a label, not a value kind: {}", + native.display_indent() + ); + assert!( + find_fused_series(&native).is_some(), + "the keyed text column is a label and the value column beside it is read: {}", + native.display_indent() + ); + + // Nothing binds an unkeyed text column as a label, and no raw frame carries it. + for (query, refusal) in [ + ("some_metric", "text_field_is_not_a_table_key"), + ( + r#"some_metric{__field__="text_field"}"#, + "field_selector_names_a_text_column", + ), + ] { + assert_eq!( + refusal, + native_decline_reason(query, build_test_text_field_table_provider(false).await).await, + "`{query}` has no value column this route reads" + ); + } + + // A table whose only field column is text reads no value, and says which column it cannot read. + assert_eq!( + "text_field_is_not_a_table_key", + native_decline_reason("some_metric", build_test_text_only_table_provider().await).await, + "a text-only table has no value column this route reads" + ); +} + +/// A row matcher over a column the selection does not read is refused. +/// +/// The route projects the fields first, so the column the matcher names is not there to compare: it +/// would read as the empty label instead. +#[tokio::test] +async fn native_row_matcher_over_a_column_outside_the_selection_is_refused() { + for row_source in [false, true] { + for query in [ + r#"some_metric{__field__="val", status="ready"}"#, + r#"some_metric{__field__="val", status="ready" or __field__="val", status="pending"}"#, + ] { + assert_eq!( + "field_selector_and_row_matcher_need_different_columns", + native_decline_reason( + query, + build_test_unread_text_column_table_provider(row_source).await + ) + .await, + "`{query}` (row_source={row_source}) needs a column its selection drops" + ); + } + + // A label the table does not carry is the empty label Prometheus compares against. + let query = r#"some_metric{__field__="val", status_missing="ready"}"#; + take_reported_decline(); + let native = build_native_fused_plan_with_provider( + query, + true, + build_test_unread_text_column_table_provider(row_source).await, + ) + .await; + assert_eq!( + None, + take_reported_decline(), + "`{query}` (row_source={row_source}): {}", + native.display_indent() + ); + assert!( + find_fused_series(&native).is_some(), + "`{query}` runs natively: {}", + native.display_indent() + ); + } } #[tokio::test] async fn native_fused_preparation_decline_is_an_error() { - let query = "absent(vector(1)) + on(tag_0) some_metric{tag_0=\"x\",__field__=\"field_0\"}"; + let query = "absent(vector(1)) + on(tag_0) some_metric"; assert_eq!( - "field_selector_without_raw_series_equivalent", - native_decline_reason(query, build_native_fused_table_provider().await).await, - "the `__field__` operand narrows a field set the raw scan reports" + "text_field_is_not_a_table_key", + native_decline_reason(query, build_test_text_field_table_provider(false).await).await, + "a `Utf8` field is no value column of the node, so the operand refuses the statement" ); } @@ -18055,11 +18657,122 @@ async fn native_composed_binary_admits_a_source_free_frame_operand() { ); } +/// A scalar operand is broadcast over the vector it meets, not matched as a second frame. +/// +/// `(hist * on(tag_0) floats) * 2` composes because its two selectors carry different field kinds, +/// and its scalar right side enters the node as the compiled scalar rather than as a second frame: +/// the pair keeps the vector's labels, reads its one input, and answers a histogram. +#[tokio::test] +async fn native_composed_binary_broadcasts_a_scalar_operand() { + for (query, scalar_on_the_left, histogram) in [ + ("(hist * on(tag_0) floats) * 2", false, true), + ("(hist > on(tag_0) floats) / time()", false, false), + ("2 * (hist * on(tag_0) floats)", true, true), + ] { + let plan = + build_native_fused_plan_with_provider(query, true, native_mixed_kind_provider().await) + .await; + let display = plan.display_indent().to_string(); + assert!(!display.contains("Join:"), "{query}: {display}"); + let fused = find_fused_series(&plan).unwrap_or_else(|| panic!("{query}: {display}")); + let NativeExpr::Binary { + left, + right, + matching, + } = &fused.tree().root().expr + else { + panic!("{query}: the statement root is the broadcast: {display}"); + }; + // The scalar side carries no labels, so the pair matches nothing and fills nothing. + assert!( + matches!(matching.labels, MatchingLabels::Ignoring(ref names) if names.is_empty()) + && matching.cardinality == Cardinality::OneToOne + && matching.fill == FillValues::default(), + "{query}: a broadcast pairs no series: {display}" + ); + let (vector, scalar) = if scalar_on_the_left { + (right, left) + } else { + (left, right) + }; + assert!( + matches!(vector.expr, NativeExpr::Input(_)), + "{query}: the frame side is the node's one input: {display}" + ); + assert!( + matches!( + scalar.expr, + NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } + ), + "{query}: the scalar side is the compiled scalar: {display}" + ); + // The scalar is not a child: only the frame side reads an input. + assert_eq!(1, fused.children().len(), "{query}: {display}"); + assert_eq!( + &if histogram { + native_histogram_value_type().as_arrow_type() + } else { + ArrowDataType::Float64 + }, + native_value_field(fused, query).data_type(), + "{query}: the pair answers the vector's kind: {display}" + ); + } +} + +/// A statement whose scalar side is read from data is refused: `scalar(sum(floats))` is a tree over +/// a scan rather than a value this composition can bind. +#[tokio::test] +async fn native_composed_binary_refuses_a_scalar_operand_that_reads_data() { + for query in [ + "(hist * on(tag_0) floats) / scalar(sum(floats))", + "(hist * on(tag_0) floats) * scalar(floats)", + ] { + assert_eq!( + "scalar_operand_has_no_kernel", + native_decline_reason(query, native_mixed_kind_provider().await).await, + "`{query}`: the scalar side reads data rather than answering one value" + ); + } +} + +/// A histogram meets only a constant scalar natively. +/// +/// Prometheus does define a per-point scale of a histogram, but the dynamic-scalar kernel errors on +/// a non-float sample rather than scaling it (`#10812`), so the pair is refused with that cause. A +/// constant still scales a histogram: that is the literal kernel, which answers a histogram. +#[tokio::test] +async fn native_composed_binary_declines_a_histogram_over_a_dynamic_scalar() { + for query in [ + "(hist * on(tag_0) floats) / time()", + "(hist * on(tag_0) floats) * time()", + ] { + assert_eq!( + "histogram_over_a_dynamic_scalar", + native_decline_reason(query, native_mixed_kind_provider().await).await, + "`{query}`: the dynamic-scalar kernel does not scale a histogram" + ); + } + + for query in ["(hist * on(tag_0) floats) * 2", "hist * 2"] { + take_reported_decline(); + let plan = + build_native_fused_plan_with_provider(query, true, native_mixed_kind_provider().await) + .await; + let display = plan.display_indent().to_string(); + assert!( + find_fused_series(&plan).is_some(), + "`{query}` scales a histogram by a constant: {display}" + ); + assert_eq!(None, take_reported_decline(), "`{query}`: {display}"); + } +} + /// A composition descends a parsed expression, so a deep one ends. /// /// Every operand offered below is a strict part of the expression it came from, which is what bounds /// the descent. A left-deep chain of matches over two field kinds plans as a nested tree here, and a -/// shape that did not would decline to the existing plan; neither may re-offer the same expression. +/// shape that did not would decline with a cause; neither may re-offer the same expression. #[tokio::test] async fn native_composed_binary_recursion_terminates_on_a_deep_expression() { let depth = 32; @@ -18158,12 +18871,12 @@ fn a_deep_native_composition_plans_within_a_worker_stack() { /// A refused operand leaves the planner's selector state where it found it. /// /// The composed attempt writes the context while it prepares each operand's scan, so a refusal - here -/// the left operand plans and the scalar `2` is no frame - must restore it before the refusal is -/// returned. The same planner then plans another expression natively, from the same context. +/// the left operand plans and the right one reads data, which this binding does not take - must +/// restore it before the refusal is returned. #[tokio::test] async fn native_composed_binary_restores_the_context_after_a_refused_operand() { let state = build_query_engine_state(); - let stmt = build_eval_stmt("(hist * on(tag_0) floats) / 2"); + let stmt = build_eval_stmt("(hist * on(tag_0) floats) / scalar(sum(floats))"); let mut planner = PromPlanner { table_provider: native_mixed_kind_provider().await, ctx: PromPlannerContext::from_eval_stmt(&stmt).unwrap(), @@ -18175,11 +18888,11 @@ async fn native_composed_binary_restores_the_context_after_a_refused_operand() { let refused = planner .try_plan_native_fused(&stmt.expr, &state) .await - .expect_err("a scalar operand has no evaluated frame, so the pair declines"); + .expect_err("a scalar operand that reads data is no value this pair can bind"); assert_eq!( - "frame_operand_is_not_evaluated", + "scalar_operand_has_no_kernel", decline_reason(&refused), - "a scalar operand has no evaluated frame, so the pair declines" + "a scalar that reads data has no kernel this route can bind" ); assert_eq!( before, diff --git a/tests-integration/src/tests/native_aggregate_test.rs b/tests-integration/src/tests/native_aggregate_test.rs index 262efab1c88..d2854b03cd8 100644 --- a/tests-integration/src/tests/native_aggregate_test.rs +++ b/tests-integration/src/tests/native_aggregate_test.rs @@ -2651,8 +2651,8 @@ async fn native_aggregate_complete_over_four_nonempty_mito_partitions() { const GROUP_B: &[(&str, &str)] = &[("job", "b")]; [(GROUP_A, a), (GROUP_B, b)] } - // Both tables have exactly one value field (`v`), so a bare table selector reads it. A - // `__field__` matcher would narrow the field set, and the native route declines such a query. + // Both tables have exactly one value field (`v`), so a bare table selector reads it, and a + // `__field__` matcher naming it would select the same field. let cases = [ case(format!("sum by (job) ({GAUGE_TABLE})"), &by_job(18.0, 12.0)), // The gauge's groups average to 6 and 6, and the producer's plan line has to name the diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index 9e84ce71ba8..474c92d650d 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -2752,6 +2752,194 @@ async fn native_tql_discovers_metrics_like_the_prometheus_handler() { assert_eq!(2, rows); } +/// A selector's `or` alternatives narrow the one scan below the node. +/// +/// The groups are row filters over one table, so a series both groups keep is read once. The existing +/// plan pushes none of them down: promql-parser moves the matchers before the first `or` into that +/// `or`'s own group, and `matchers_to_expr` reads only `matchers.matchers`, so for this query it +/// applies no matcher at all and answers every series of the table - hence `native_or_pair`'s third +/// series, which the fixture states rather than hides. +#[tokio::test(flavor = "multi_thread")] +async fn native_promql_or_matchers_narrow_the_scan() { + common_telemetry::init_default_ut_logging(); + let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( + "native_promql_or_matchers", + )) + .await; + let instance = standalone.fe_instance().clone(); + execute_all( + &instance, + "CREATE TABLE native_or_phy (ts TIMESTAMP TIME INDEX, v DOUBLE) \ + ENGINE=metric WITH (\"physical_metric_table\" = \"\"); \ + CREATE TABLE native_or_pair (host STRING NULL, ts TIMESTAMP NOT NULL, v DOUBLE NULL, \ + TIME INDEX (ts), PRIMARY KEY (host)) \ + ENGINE=metric WITH (on_physical_table = 'native_or_phy'); \ + CREATE TABLE native_or_overlap (host STRING NULL, ts TIMESTAMP NOT NULL, v DOUBLE NULL, \ + TIME INDEX (ts), PRIMARY KEY (host)) \ + ENGINE=metric WITH (on_physical_table = 'native_or_phy'); \ + INSERT INTO native_or_pair (host, ts, v) VALUES ('a', 0, 2), ('b', 0, 4), ('c', 0, 8); \ + INSERT INTO native_or_overlap (host, ts, v) VALUES ('a', 0, 6)", + QueryContext::arc(), + ) + .await; + + // A repeated alternative is one filter, not a second reading of the same rows. + for (query, expected) in [ + ( + r#"native_or_pair{host="a" or host="b"}"#, + vec![(0, "a".to_string(), 2.0), (0, "b".to_string(), 4.0)], + ), + ( + r#"native_or_pair{host="a" or host="b" or host="a"}"#, + vec![(0, "a".to_string(), 2.0), (0, "b".to_string(), 4.0)], + ), + ] { + let sql = format!("TQL EVAL (0, 0, '1s') {query}"); + observer.clear(); + let native = native_result_rows(native_tql_output(&instance, &sql, true).await).await; + assert_native_rows_plan(&observer); + assert_eq!(expected, native, "{query}"); + observer.clear(); + // Only the route is pinned here: the existing plan applies no alternative, so its rows are + // not an expectation this test states. + let _ = native_result_rows(native_tql_output(&instance, &sql, false).await).await; + assert!( + observer.fused().is_none(), + "{query} must keep the existing plan when the native route is off" + ); + } + + // The one series both alternatives keep is read once, not once per alternative. + let query = r#"native_or_overlap{host=~"a" or host="a"}"#; + let sql = format!("TQL EVAL (0, 0, '1s') {query}"); + observer.clear(); + let native = native_result_rows(native_tql_output(&instance, &sql, true).await).await; + assert_native_rows_plan(&observer); + assert_eq!(vec![(0, "a".to_string(), 6.0)], native, "{query}"); + observer.clear(); + let legacy = native_result_rows(native_tql_output(&instance, &sql, false).await).await; + assert_eq!(native, legacy, "{query}"); + + // A `__field__` alternative names a column rather than a row, so the groups' selections are one + // selection and the scan reads the field it names. + let query = r#"native_or_pair{__field__="v" or __field__="v"}"#; + let sql = format!("TQL EVAL (0, 0, '1s') {query}"); + observer.clear(); + let native = native_result_rows(native_tql_output(&instance, &sql, true).await).await; + assert_native_rows_plan(&observer); + assert_eq!( + vec![ + (0, "a".to_string(), 2.0), + (0, "b".to_string(), 4.0), + (0, "c".to_string(), 8.0), + ], + native, + "{query}: a selection of the field column keeps every series reading it" + ); +} + +/// Every sample a statement answers, as the host and the value of its one value column. +/// +/// A statement that publishes one value column names it after the query rather than after the field, +/// so the sample's field is the one the statement selected, not the column's name. +async fn native_host_value_rows(output: Output) -> Vec<(String, f64)> { + let batches = match output.data { + OutputData::Stream(stream) => collect_batches(stream).await.unwrap(), + OutputData::RecordBatches(batches) => batches, + _ => unreachable!("TQL EVAL returns record batches"), + }; + let mut rows = Vec::new(); + for batch in batches.iter() { + let values = batch + .columns() + .iter() + .filter(|column| column.data_type() == &DataType::Float64) + .collect::>(); + assert_eq!(1, values.len(), "expected one value column"); + let values = values[0] + .as_any() + .downcast_ref::() + .expect("a value column is a float"); + let hosts = cast( + batch.column_by_name("host").unwrap().as_ref(), + &DataType::Utf8, + ) + .unwrap(); + let hosts = hosts.as_any().downcast_ref::().unwrap(); + for row in 0..batch.num_rows() { + if !values.is_null(row) { + rows.push((hosts.value(row).to_string(), values.value(row))); + } + } + } + rows.sort_by(|left, right| left.0.cmp(&right.0)); + rows +} + +/// Alternatives that read their own field or name their own table are refused by the native route: +/// a single scan carries one field list, and reads one table, for all of them. +#[tokio::test(flavor = "multi_thread")] +async fn native_promql_or_alternatives_with_their_own_field_or_table_are_refused() { + common_telemetry::init_default_ut_logging(); + let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( + "native_promql_or_field_alternatives", + )) + .await; + let instance = standalone.fe_instance().clone(); + execute_all( + &instance, + "CREATE TABLE native_or_field (host STRING NULL, ts TIMESTAMP NOT NULL, v DOUBLE NULL, \ + w DOUBLE NULL, PRIMARY KEY (host), TIME INDEX (ts)); \ + INSERT INTO native_or_field (host, ts, v, w) VALUES ('a', 0, 2, 6), ('c', 0, 4, 8)", + QueryContext::arc(), + ) + .await; + + for (query, refusal) in [ + ( + r#"native_or_field{__field__="v", host="a" or __field__="w", host="c"}"#, + "or_alternatives_select_different_fields", + ), + ( + r#"native_or_field{__field__="v", host="a" or __field__="w"}"#, + "or_alternatives_select_different_fields", + ), + // A schema named by one alternative is that alternative's own: one scan would read it for + // the other, which never asked for it. + ( + r#"native_or_field{__schema__="public", host="a" or host="b"}"#, + "or_alternatives_name_a_table", + ), + ] { + let sql = format!("TQL EVAL (0, 0, '1s') {query}"); + observer.clear(); + assert_native_decline(&instance, &sql, refusal, query).await; + assert!( + observer.fused().is_none(), + "{query}: one scan cannot answer these alternatives as they are written" + ); + } + + // One alternative on its own reads its own field of its own rows: the row of `host="a"` carries + // `v=2` and `w=6`, and the selection answers `2` only. + for (query, expected) in [ + ( + r#"native_or_field{__field__="v", host="a"}"#, + vec![("a".to_string(), 2.0)], + ), + ( + r#"native_or_field{__field__="w", host="c"}"#, + vec![("c".to_string(), 8.0)], + ), + ] { + let sql = format!("TQL EVAL (0, 0, '1s') {query}"); + observer.clear(); + let native = native_host_value_rows(native_tql_output(&instance, &sql, true).await).await; + assert_native_rows_plan(&observer); + assert_eq!(expected, native, "{query}"); + } +} + /// A native rows result names each row after the metric it came from. /// /// The name is part of what the statement answers, not of how a result is displayed: `sum by @@ -5640,6 +5828,227 @@ async fn native_promql_kind_rules_match_legacy() { ); } +/// A scalar operand broadcasts over the vector it meets on both routes, row for row. +/// +/// `(scalar_hist * on(job) scalar_float) * 2` composes because its selectors carry different field +/// kinds, and its scalar right side broadcasts over the vector it meets: a histogram times a float +/// stays a histogram, and the existing plan's rows say so. Prometheus also defines a per-point scale +/// of a histogram, but the dynamic-scalar kernel errors on a non-float sample instead of scaling it +/// (`#10812`), so the same pair under `time()` is refused and only the existing plan answers it. +#[tokio::test(flavor = "multi_thread")] +async fn native_promql_composed_scalar_operand_matches_legacy() { + use api::greptime_proto::io::prometheus::write::v2::histogram::{Count, ZeroCount}; + use api::greptime_proto::io::prometheus::write::v2::{Histogram, Sample}; + use axum::body::{Body, to_bytes}; + use http::Request; + use prost::Message; + use servers::prom_remote_write::v2::test_util as remote_write_v2; + use servers::prom_store::snappy_compress; + use tower::ServiceExt; + + common_telemetry::init_default_ut_logging(); + let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( + "native_promql_composed_scalar", + )) + .await; + let instance = standalone.fe_instance().clone(); + let server = crate::test_util::build_test_prom_server(instance.clone(), false, None).build(); + let router = server.build(server.make_app()).unwrap(); + // One histogram metric and one float metric, written through the remote-write endpoint so both + // tables carry one layout: a difference in the answers is then not a difference in the fixture. + for request in [ + remote_write_v2::request_with_labels_and_histograms( + vec![("__name__", "scalar_hist"), ("job", "api"), ("host", "a")], + [600_000, 1_200_000] + .into_iter() + .map(|timestamp| Histogram { + timestamp, + count: Some(Count::CountInt(4)), + zero_count: Some(ZeroCount::ZeroCountInt(4)), + sum: 8.0, + ..Default::default() + }) + .collect(), + ), + remote_write_v2::request_with_labels_and_samples( + vec![("__name__", "scalar_float"), ("job", "api"), ("host", "a")], + [(600_000, 2.0), (1_200_000, 3.0)] + .into_iter() + .map(|(timestamp, value)| Sample { + timestamp, + value, + ..Default::default() + }) + .collect(), + ), + ] { + let response = router + .clone() + .oneshot( + Request::post("/v1/prometheus/write") + .header("Content-Encoding", "snappy") + .header( + "Content-Type", + "application/x-protobuf;proto=io.prometheus.write.v2.Request", + ) + .body(Body::from( + snappy_compress(&request.encode_to_vec()).unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status(), + 204, + "{:?}", + to_bytes(response.into_body(), usize::MAX).await.unwrap() + ); + } + + // The histogram side is `count = 4, sum = 8` and the float side `2` then `3`, so the match answers + // `8/16` then `12/24`, labelled by `job` alone. A constant scalar scales the histogram it is + // broadcast over, so the pair runs natively and the existing plan answers it row for row. + let expression = "(scalar_hist * on(job) scalar_float) * 2"; + let expected = vec![ + (600_000, vec!["job=api".to_string()], 16.0, 32.0), + (1_200_000, vec!["job=api".to_string()], 24.0, 48.0), + ]; + let sql = format!("TQL EVAL (600, 1200, '600s') {expression}"); + observer.clear(); + let native = native_tql_output(&instance, &sql, true).await; + assert!( + observer.fused().is_some(), + "{expression} did not run natively: {:#?}", + observer.root_plan() + ); + let native_rows = histogram_label_rows(native).await; + assert_eq!(expected, native_rows, "{expression}"); + observer.clear(); + let legacy = native_tql_output(&instance, &sql, false).await; + assert!( + observer.fused().is_none(), + "{expression} must keep the existing plan when the native route is off" + ); + assert_eq!( + histogram_label_rows(legacy).await, + native_rows, + "{expression} must answer the existing plan's rows row for row" + ); + + // `time()` is the step in seconds - `600` and `1200` here - so the divisor meets the histogram's + // samples one point at a time. That per-point scale is what Prometheus defines, but the + // dynamic-scalar kernel errors on a non-float sample instead of scaling it (`#10812`), so the + // native route refuses the pair and the rows read through `native = false` are the expectations + // below. + let expression = "(scalar_hist * on(job) scalar_float) / time()"; + let expected = vec![ + ( + 600_000, + vec!["job=api".to_string()], + 8.0 / 600.0, + 16.0 / 600.0, + ), + ( + 1_200_000, + vec!["job=api".to_string()], + 12.0 / 1200.0, + 24.0 / 1200.0, + ), + ]; + let sql = format!("TQL EVAL (600, 1200, '600s') {expression}"); + assert_native_decline( + &instance, + &sql, + "histogram_over_a_dynamic_scalar", + expression, + ) + .await; + observer.clear(); + let rows = histogram_label_rows(native_tql_output(&instance, &sql, false).await).await; + assert_eq!(expected, rows, "{expression}"); + assert!( + observer.fused().is_none(), + "{expression} must keep the existing plan when the native route is off" + ); + + // A scalar over a float metric still runs natively, and a composed operand of one keeps its node. + let float_expression = "(scalar_float * 2) * 2"; + let sql = format!("TQL EVAL (600, 1200, '600s') {float_expression}"); + observer.clear(); + let native = native_tql_output(&instance, &sql, true).await; + assert!( + observer.fused().is_some(), + "{float_expression} did not run natively: {:#?}", + observer.root_plan() + ); + let native_rows = native_rows_value(native).await; + observer.clear(); + let legacy = native_tql_output(&instance, &sql, false).await; + assert!( + observer.fused().is_none(), + "{float_expression} must keep the existing plan when the native route is off" + ); + assert_eq!( + vec![ + (600_000, "api".to_string(), 8.0), + (1_200_000, "api".to_string(), 12.0) + ], + native_rows, + "{float_expression}" + ); + assert_eq!( + native_rows_value(legacy).await, + native_rows, + "{float_expression} must answer the existing plan's rows row for row" + ); +} + +/// The `(time, job, value)` rows of a labelled float answer, matched by values rather than names. +async fn native_rows_value(output: Output) -> Vec<(i64, String, f64)> { + let batches = match output.data { + OutputData::Stream(stream) => collect_batches(stream).await.unwrap(), + OutputData::RecordBatches(batches) => batches, + _ => unreachable!("TQL EVAL returns record batches"), + }; + let mut rows = Vec::new(); + for batch in batches.iter() { + let time = batch + .columns() + .iter() + .find(|column| { + matches!( + column.data_type(), + DataType::Timestamp(TimeUnit::Millisecond, _) + ) + }) + .expect("a PromQL result carries its time index"); + let time = cast(time.as_ref(), &DataType::Int64).unwrap(); + let time = time.as_any().downcast_ref::().unwrap(); + let job = batch + .column_by_name("job") + .expect("the answer carries the label it matched on"); + let job = cast(job.as_ref(), &DataType::Utf8).unwrap(); + let job = job.as_any().downcast_ref::().unwrap(); + let values = batch + .columns() + .iter() + .filter(|column| column.data_type() == &DataType::Float64) + .collect::>(); + assert_eq!(values.len(), 1, "expected one Float64 value column"); + let values = values[0].as_any().downcast_ref::().unwrap(); + for row in 0..batch.num_rows() { + rows.push(( + time.value(row), + job.value(row).to_string(), + values.value(row), + )); + } + } + rows.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1))); + rows +} + /// A float function above a split `sum` over native histograms runs natively and answers what the /// existing plan and Prometheus answer. /// @@ -14507,6 +14916,35 @@ async fn native_promql_answers_numeric_fields_as_float64() { ); } + // A `__field__` matcher narrows what the scan reads: the selection is the scan's projection, so + // the statement publishes one value column. + for (query, fused) in [ + (format!(r#"{TABLE}{{__field__="f"}}"#), true), + // Every numeric field is answered as a `Float64`, the integer one included. + (format!(r#"{TABLE}{{__field__="i"}}"#), true), + ] { + let sql = format!("TQL EVAL (2, 2, '1s') {query}"); + observer.clear(); + let native = native_answer(native_tql_output(&instance, &sql, true).await).await; + assert_eq!( + fused, + observer.fused().is_some(), + "`{query}`: {}", + observer.answering_node().unwrap_or_default() + ); + assert_eq!( + vec![DataType::Float64], + native.value_types, + "`{query}`: only the selected field is a value column" + ); + let legacy = native_answer(native_tql_output(&instance, &sql, false).await).await; + assert_eq!( + numeric_rows(&native), + numeric_rows(&legacy), + "`{query}`: the selected field's rows" + ); + } + // A field the raw series preflight refuses has no float to publish, whatever the shape is. These // keep the existing plan, which is where their answer comes from - for some of them an error // (`sum` of a string has no fold), and that error is the answer the route must not replace. @@ -14524,34 +14962,52 @@ async fn native_promql_answers_numeric_fields_as_float64() { for query in [ TEXT_TABLE.to_string(), format!("sum({TEXT_TABLE})"), - format!("{TEXT_TABLE} * 2"), format!("rate({TEXT_TABLE}[2s])"), ] { let sql = format!("TQL EVAL (2, 2, '1s') {query}"); observer.clear(); - native_run_ignoring_the_answer(&instance, &sql, true).await; + assert_native_decline(&instance, &sql, "text_field_is_not_a_table_key", &query).await; assert!( observer.fused().is_none(), "`{query}`: a string field has no raw representation" ); } -} -/// Runs a TQL statement and drops whatever it answered. -/// -/// A statement the existing planner refuses is answered by that refusal - `sum` of a string has no -/// fold - and the route must not replace it with an answer of its own, so a test that only means to -/// hold the route to the existing plan must not unwrap the answer. -async fn native_run_ignoring_the_answer(instance: &Arc, sql: &str, enabled: bool) { - let Ok(output) = instance - .do_query(sql, native_query_context(enabled, 4)) - .await - .remove(0) - else { - return; - }; - if let OutputData::Stream(stream) = output.data { - let _ = collect_batches(stream).await; + // A text column beside a numeric one is the same answer: no frame carries a text value. + const MIXED_TABLE: &str = "native_numeric_shape_mixed"; + execute_all( + &instance, + &format!( + "CREATE TABLE {MIXED_TABLE} (host STRING, ts TIMESTAMP(3) TIME INDEX, l STRING, v DOUBLE, PRIMARY KEY (host)); \ + INSERT INTO {MIXED_TABLE} (host, ts, l, v) VALUES ('a', 0, 'x', 1), ('a', 1000, 'y', 2); \ + ADMIN FLUSH_TABLE('{MIXED_TABLE}');" + ), + QueryContext::arc(), + ) + .await; + for (query, refusal) in [ + (MIXED_TABLE.to_string(), "text_field_is_not_a_table_key"), + ( + format!("sum({MIXED_TABLE})"), + "text_field_is_not_a_table_key", + ), + ( + format!("rate({MIXED_TABLE}[2s])"), + "text_field_is_not_a_table_key", + ), + ( + format!(r#"{MIXED_TABLE}{{__field__="l"}}"#), + "field_selector_names_a_text_column", + ), + ] { + let sql = format!("TQL EVAL (2, 2, '1s') {query}"); + observer.clear(); + assert_native_decline(&instance, &sql, refusal, &query).await; + assert!( + observer.fused().is_none(), + "`{query}`: a text column is a value column of the existing plan, and no raw frame \ + carries one" + ); } }