From 5d3e22ce937ff634722a101c60b49e346bfd7a08 Mon Sep 17 00:00:00 2001 From: discord9 Date: Tue, 1 Dec 2026 14:46:16 +0000 Subject: [PATCH] refactor(promql): report a declined shape instead of planning it the old way (#10701) * refactor(promql): refuse with the recorded cause A native decline fails the offer instead of silently planning the statement again with the existing planner. Preserve upstream statement, alias and time-index shapes. Signed-off-by: discord9 * refactor(promql): remove the dist-planner replan and the stale gates that fed it A statement the native route was asked for is planned once. The second planning pass with the route off, the gate that decided it, the histogram-aggregate refusal that cannot trigger, and the fallback option veto are gone; an unknown statement extension is refused by name. Signed-off-by: discord9 --------- Signed-off-by: discord9 --- src/query/src/dist_plan.rs | 1 - src/query/src/dist_plan/commutativity.rs | 14 - src/query/src/error.rs | 13 + src/query/src/metrics.rs | 9 +- src/query/src/planner.rs | 539 ++++++++------- src/query/src/promql/error.rs | 8 + src/query/src/promql/planner.rs | 22 +- src/query/src/promql/planner/native.rs | 121 ++-- src/query/src/promql/planner/test.rs | 652 ++++++++---------- .../src/tests/native_file_engine_test.rs | 12 +- tests-integration/src/tests/promql_test.rs | 338 ++++----- tests-integration/tests/http.rs | 50 +- 12 files changed, 817 insertions(+), 962 deletions(-) diff --git a/src/query/src/dist_plan.rs b/src/query/src/dist_plan.rs index df6fdd079bc..c67c340ffd8 100644 --- a/src/query/src/dist_plan.rs +++ b/src/query/src/dist_plan.rs @@ -25,7 +25,6 @@ mod remote_dyn_filter_receiver; mod remote_dyn_filter_registry; pub use analyzer::{DistPlannerAnalyzer, DistPlannerOptions}; -pub(crate) use commutativity::region_local_node; #[cfg(test)] pub(crate) use commutativity::{Categorizer, Commutativity}; pub use filter_id::{FilterFingerprint, FilterId, ParseFilterIdError, RemoteDynFilterProducerId}; diff --git a/src/query/src/dist_plan/commutativity.rs b/src/query/src/dist_plan/commutativity.rs index 2fda182a9c3..33389ff26c0 100644 --- a/src/query/src/dist_plan/commutativity.rs +++ b/src/query/src/dist_plan/commutativity.rs @@ -35,20 +35,6 @@ use crate::dist_plan::analyzer::AliasMapping; use crate::dist_plan::merge_sort::{MergeSortLogicalPlan, merge_sort_transformer}; use crate::promql::planner::native::{independent_scan_pair, pointwise_operand, same_table_scans}; -/// Whether `node` is a node the analyzer runs where the scan it reads is planned. -/// -/// A region only ever runs a fused node over its own scan, and the analyzer puts one there by -/// classifying it as commutative - which is also the only placement a node over a bare scan has, -/// because a bare scan is never shipped across a region boundary. A planner that has to commit to -/// a plan before the analyzer runs asks this to know whether that placement exists: `false` says -/// every input of this node has to be a source that names its region. -pub(crate) fn region_local_node(node: &dyn UserDefinedLogicalNode) -> bool { - matches!( - Categorizer::check_extension_plan(node, &AliasMapping::default()), - Commutativity::Commutative - ) -} - pub struct StepTransformAction { extra_parent_plans: Vec, new_child_plan: Option, diff --git a/src/query/src/error.rs b/src/query/src/error.rs index 919ef67b94f..de7fcbaec17 100644 --- a/src/query/src/error.rs +++ b/src/query/src/error.rs @@ -331,6 +331,18 @@ pub enum Error { location: Location, }, + #[snafu(display( + "Native PromQL columns cannot be published for this relation, native: {:?}, expected: {:?}", + native, + expected, + ))] + NativeColumnsNotPublishable { + native: Vec, + expected: Vec, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display( "Column schema mismatch in CTE {}, original: {:?}, expected: {:?}", cte_name, @@ -445,6 +457,7 @@ impl ErrorExt for Error { MissingTableMutationHandler { .. } => StatusCode::Unexpected, GetRegionMetadata { .. } => StatusCode::RegionNotReady, TableReadOnly { .. } => StatusCode::Unsupported, + NativeColumnsNotPublishable { .. } => StatusCode::Unsupported, GetFulltextOptions { source, .. } | GetSkippingIndexOptions { source, .. } diff --git a/src/query/src/metrics.rs b/src/query/src/metrics.rs index 41aa8d64fc5..7cc88bfea37 100644 --- a/src/query/src/metrics.rs +++ b/src/query/src/metrics.rs @@ -127,14 +127,13 @@ lazy_static! { ) .unwrap(); - /// Statements the native PromQL route handed to the existing planner, by the cause it recorded. + /// Statements the native PromQL route refused, by the cause it recorded. /// - /// A declined statement is not an error and not a different answer: the existing planner - /// computes the same rows, so a fallback is only visible as a slower query. This counter and - /// the log line beside it are what make its rate observable per cause. + /// A refused statement fails: no other route plans it, so the counter and the log line beside + /// it are what make its rate observable per cause. pub static ref NATIVE_PROMQL_DECLINED_TOTAL: IntCounterVec = register_int_counter_vec!( "greptime_query_native_promql_declined_total", - "native PromQL expressions planned by the existing planner, by cause", + "native PromQL expressions the route refused, by cause", &["reason"] ) .unwrap(); diff --git a/src/query/src/planner.rs b/src/query/src/planner.rs index 7786bb8c4a9..aef4c6e2297 100644 --- a/src/query/src/planner.rs +++ b/src/query/src/planner.rs @@ -49,13 +49,10 @@ use sql::statements::query::Query; use sql::statements::statement::Statement; use sql::statements::tql::Tql; use sqlparser::ast::{AccessExpr, Value, visit_expressions_mut}; -use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME; -use crate::dist_plan::DistPlannerOptions; -use crate::dist_plan::region_local_node; use crate::error::{ - CteColumnSchemaMismatchSnafu, PlanSqlSnafu, QueryPlanSnafu, Result, SqlSnafu, - UnimplementedSnafu, + CteColumnSchemaMismatchSnafu, NativeColumnsNotPublishableSnafu, PlanSqlSnafu, QueryPlanSnafu, + Result, SqlSnafu, UnimplementedSnafu, }; use crate::log_query::planner::LogQueryPlanner; use crate::optimizer::expr_depth; @@ -91,149 +88,6 @@ pub trait LogicalPlanner: Send + Sync { fn as_any(&self) -> &dyn Any; } -/// A native plan a distributed planner splits over regions may place fused evaluation in one of two -/// places: above one independent raw source per region, or inside the region whose own scan it -/// reads. -/// -/// The second placement is the analyzer's to give. It moves a node into a region only when it -/// classifies the node as running where its scan is, and a bare scan is never shipped across a -/// region boundary on its own: nothing below the boundary could read it. So a scan is admitted only -/// under a node the analyzer would move, and every other input of the plan has to be a raw source -/// that names the region it reads, or a row source that reads the regions' rows above them. -/// -/// A fused node that reads no region is the one exception: it has nothing to place in a region, so -/// the frontend evaluates it and the transport this gate protects is never used. -fn remote_native_raw_plan_supported(plan: &LogicalPlan) -> bool { - /// `region_local` says the nearest enclosing node reads its scan where that scan is planned, so - /// the subtree below it travels inside the region's own plan. - fn walk( - plan: &LogicalPlan, - region_local: bool, - found_raw: &mut bool, - found_region_local: &mut bool, - ) -> bool { - match plan { - LogicalPlan::TableScan(_) => region_local, - LogicalPlan::Extension(extension) => { - if extension - .node - .as_any() - .is::() - { - *found_raw = true; - return matches!( - extension.node.inputs().as_slice(), - [LogicalPlan::TableScan(_)] - ); - } - // A row source reads ordinary rows: the analyzer keeps it above the merge scan - // and ships only the scan below it, which every region answers as a plain query. - if extension - .node - .as_any() - .is::() - { - *found_raw = true; - return true; - } - let region_local = extension - .node - .as_any() - .is::() - && region_local_node(extension.node.as_ref()); - *found_region_local |= region_local; - extension - .node - .inputs() - .iter() - .all(|child| walk(child, region_local, found_raw, found_region_local)) - } - _ => plan - .inputs() - .iter() - .all(|child| walk(child, region_local, found_raw, found_region_local)), - } - } - let mut found_raw = false; - let mut found_region_local = false; - walk(plan, false, &mut found_raw, &mut found_region_local) - && (found_raw || found_region_local || is_regionless_fused_plan(plan)) -} - -/// Whether `plan` is a native fused plan with no region below it. -/// -/// Two shapes qualify, and both are already the finished plan: a statement that reads no data - -/// `time()`, `vector(1)`, a label rewrite over one of them - is one node with no input at all, -/// and a discovered selector that matched no metric table is planned over the typed empty frame -/// [`is_empty_discovered_input`](crate::promql::planner::native::is_empty_discovered_input) -/// builds. Neither has a scan to ship, so neither needs the remote transport. -/// -/// The route stacks its own nodes above such an input: a split aggregate runs a `Final` half over -/// the `Partial` half that reads it, and a segmented statement runs its parent over the segment's -/// own node. So the inputs a node reads are followed through fused nodes only - never through -/// another extension, and never through a scan - and every leaf that is not one of them rejects -/// the shape. -fn is_regionless_fused_plan(plan: &LogicalPlan) -> bool { - // `strip_tsid_column` publishes a statement's own columns over a node that reported the - // internal series id, which a data-free statement can synthesize with `label_replace`. That - // wrapper is this route's own, so it is read through when it drops exactly that one column. - if let LogicalPlan::Projection(projection) = plan { - return strips_only_tsid(plan, projection.input.as_ref()) - && is_regionless_fused_chain(projection.input.as_ref()); - } - is_regionless_fused_chain(plan) -} - -/// Whether `plan` is a fused node whose inputs are fused nodes or the typed empty frame. -fn is_regionless_fused_chain(plan: &LogicalPlan) -> bool { - let LogicalPlan::Extension(extension) = plan else { - return false; - }; - let Some(fused) = extension - .node - .as_any() - .downcast_ref::() - else { - return false; - }; - fused.children().iter().all(|child| { - crate::promql::planner::native::is_empty_discovered_input(child) - || is_regionless_fused_chain(child) - }) -} - -/// Whether `plan` is the projection that drops exactly the internal series-id column of `inner`. -/// -/// That is the projection `strip_tsid_column` builds: one plain column per field of its input, -/// in order, except `__tsid__`. A computed expression, a reordering or a second dropped column is -/// some other plan and is not read through. -fn strips_only_tsid(plan: &LogicalPlan, inner: &LogicalPlan) -> bool { - let LogicalPlan::Projection(projection) = plan else { - return false; - }; - if projection - .expr - .iter() - .any(|expr| !matches!(expr, DfExpr::Column(_))) - { - return false; - } - let stripped = inner - .schema() - .fields() - .iter() - .filter(|field| field.name() != DATA_SCHEMA_TSID_COLUMN_NAME) - .map(|field| field.name()) - .collect::>(); - let projected = plan - .schema() - .fields() - .iter() - .map(|field| field.name()) - .collect::>(); - projected == stripped && projected.len() + 1 == inner.schema().fields().len() -} - /// Whether `plan` runs on the native fused-series route. fn contains_native_fused(plan: &LogicalPlan) -> bool { if let LogicalPlan::Extension(extension) = plan @@ -369,7 +223,7 @@ fn unwrap_dictionary(data_type: &DataType) -> &DataType { /// /// `None` says the plans admit no such pairing - the value columns differ in number or in type, a /// label of one plan is missing from the other, or the result does not publish exactly the existing -/// columns - and the caller then keeps the existing plan rather than publish a column it cannot fill +/// columns - and the caller then refuses the statement rather than publish a column it cannot fill /// faithfully. fn publish_legacy_schema(native: LogicalPlan, legacy: &LogicalPlan) -> Option { let native_schema = native.schema().clone(); @@ -384,6 +238,12 @@ fn publish_legacy_schema(native: LogicalPlan, legacy: &LogicalPlan) -> Option Option bool { + let (native_fields, legacy_fields) = (native.fields(), legacy.fields()); + if native_fields.len() != 2 || legacy_fields.len() != 2 { + return false; + } + let millis = DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None); + let marks_time_index = |field: &Arc| { + field + .metadata() + .contains_key(datatypes::schema::TIME_INDEX_KEY) + }; + marks_time_index(&native_fields[0]) + && !marks_time_index(&legacy_fields[0]) + && native_fields[0].data_type() == &millis + && legacy_fields[0].data_type() == &millis + && !native_fields[0].is_nullable() + && !legacy_fields[0].is_nullable() + && native_fields[1].data_type() == &DataType::Float64 + && legacy_fields[1].data_type() == &DataType::Float64 +} + +/// The native plan, wrapped in the projection that publishes a no-input `time()` answer's columns. +/// +/// A statement that reads no data is one node without a scan: the native node marks its `time` as +/// the time index and names its value after the expression, while `EmptyMetric` publishes an +/// unmarked millisecond `time` and the expression it planned. Both carry the same two values - +/// `time` in milliseconds there, and `time()` as that count over a thousand in the kernel - so this +/// maps those columns by role. It maps that one shape and no other: the native plan must be the +/// no-input `EvalTime` node, and [`is_empty_time_pair`] must hold for the two schemas. +fn publish_empty_time_columns(native: &LogicalPlan, legacy: &LogicalPlan) -> Option { + let LogicalPlan::Extension(extension) = native else { + return None; + }; + let fused = extension + .node + .as_any() + .downcast_ref::()?; + if !native.inputs().is_empty() + || !matches!( + fused.tree().root().expr, + promql::native::plan::NativeExpr::EvalTime { date: None } + ) + { + return None; + } + let native_schema = native.schema(); + let legacy_schema = legacy.schema(); + if !is_empty_time_pair(native_schema.as_ref(), legacy_schema.as_ref()) { + return None; + } + let (native_fields, legacy_fields) = (native_schema.fields(), legacy_schema.fields()); + let columns = vec![ + col(native_fields[0].name().clone()).alias(legacy_fields[0].name().clone()), + col(native_fields[1].name().clone()).alias(legacy_fields[1].name().clone()), + ]; + // The published schema is the existing one, byte for byte: its columns and the schema metadata + // the empty node carries none of. + let published = Arc::new( + DFSchema::new_with_metadata( + legacy_schema + .iter() + .map(|(qualifier, field)| (qualifier.cloned(), Arc::clone(field))) + .collect(), + legacy_schema.metadata().clone(), + ) + .ok()?, + ); + Some(LogicalPlan::Projection( + datafusion_expr::Projection::try_new_with_schema( + columns, + Arc::new(native.clone()), + published, + ) + .ok()?, + )) +} + pub struct DfLogicalPlanner { engine_state: Arc, session_state: SessionState, @@ -752,22 +696,9 @@ impl DfLogicalPlanner { let engine_context = self.derive_session_state_with_scheduled_time(query_ctx)?; let query_ctx = engine_context.query_ctx(); let mut scheduled_state = engine_context.state().clone(); - // Whether the distributed planner may fall back to the fallback plan rewriter. A fallback - // rewriter can wrap a native region scan in an unusable MergeScan, so the native route is - // only offered to a query that cannot fall back. - // - // `apply_query_options` above resolved the three sources this used to disjoin - the engine - // option, the session `allow_query_fallback` variable and the `query_fallback` hint - into - // this extension, so the read happens here instead. One mainline semantic is kept: a stated - // `false` overrides the engine default rather than leaving it on. - let allow_query_fallback = scheduled_state - .config_options() - .extensions - .get::() - .is_some_and(|options| options.allow_query_fallback); - // Whether the statement is offered to the native fused-series compiler. This is the second, - // independent switch: it states what the query asks for, and no source of it is derived - // from the fallback option. + // Whether the statement is offered to the native fused-series compiler. This is the one + // switch the route reads: it states what the query asks for, and no source of it is derived + // from the fallback option, which answers a distributed plan that cannot be pushed down. let native_promql = scheduled_state .config_options() .extensions @@ -797,41 +728,18 @@ impl DfLogicalPlanner { .enable_ident_normalization, ) }; - let native_requested = native_route_allowed && !allow_query_fallback && native_promql; + let native_requested = native_route_allowed && native_promql; let plan = PromPlanner::stmt_to_plan_with_annotations( table_provider(), stmt, &self.engine_state, - promql_annotations.clone(), - // A fallback rewriter can wrap a native region scan in an unusable MergeScan. + promql_annotations, native_requested, ) .await .map_err(BoxedError::new) .context(QueryPlanSnafu)?; - // A distributed planner plans a native statement over per-selector raw sources, and a - // statement that reads no table needs none. Anything else keeps the existing plan. Decide - // while the original statement is still available: physical planning cannot fall back - // safely. An engine with no distributed planner plans no region, so there is nothing to - // admit its plan against. - let plan = if native_requested - && self.engine_state.with_dist_planner() - && !remote_native_raw_plan_supported(&plan) - { - PromPlanner::stmt_to_plan_with_annotations( - table_provider(), - stmt, - &self.engine_state, - promql_annotations, - false, - ) - .await - .map_err(BoxedError::new) - .context(QueryPlanSnafu)? - } else { - plan - }; let context = QueryEngineContext::new(scheduled_state, query_ctx); Ok(self .engine_state @@ -930,8 +838,8 @@ impl DfLogicalPlanner { ) -> Result { let plan = self.plan_pql(eval, query_ctx.clone(), true).await?; if !contains_native_fused(&plan) { - // The route was not taken - it is off for this query, or it declined this shape - so - // this is the existing plan, which already publishes the existing columns. + // The route was not taken - it is off for this query - so this is the existing plan, + // which already publishes the existing columns. return Ok(plan); } // The existing planner refuses a selector that names no metric, so the native answer's own @@ -943,10 +851,23 @@ impl DfLogicalPlanner { // The relation's columns are SQL-visible, and this route names and orders its output its own // way, so its own schema cannot stand in for the existing planner's: plan the statement for // that schema and publish it over the native answer. A statement whose columns that - // projection cannot fill faithfully keeps the existing plan instead of changing the schema - // the relation exposes. + // projection cannot fill faithfully is refused: publishing the existing plan instead would + // answer a statement this route was asked to plan. let existing = self.plan_pql(eval, query_ctx, false).await?; - Ok(publish_legacy_schema(plan, &existing).unwrap_or(existing)) + let native: Vec = plan + .schema() + .fields() + .iter() + .map(|field| field.name().clone()) + .collect(); + let expected: Vec = existing + .schema() + .fields() + .iter() + .map(|field| field.name().clone()) + .collect(); + publish_legacy_schema(plan, &existing) + .ok_or_else(|| NativeColumnsNotPublishableSnafu { native, expected }.build()) } /// Convert TQL to LogicalPlan directly @@ -1596,7 +1517,7 @@ mod tests { } /// Plans `rate(some_metric[5m])` with the fallback option the caller states, while the native - /// route is on and requested, so only the fallback option decides. + /// route is on and requested. async fn plan_native_promql_with_fallback( engine_fallback: bool, session_fallback: Option, @@ -1619,33 +1540,29 @@ mod tests { .await } - /// The native route is admitted only when the query cannot fall back, and the fallback option - /// resolves from the same snapshot, so a stated value overrides the engine default in both - /// directions instead of only ever turning the fallback on. + /// The fallback option answers a distributed plan that cannot be pushed down. It is no source + /// of the native route, so whatever it says the statement is planned natively. #[tokio::test] - async fn test_plan_pql_declines_native_route_when_query_may_fall_back() { - // (engine option, session variable, hint, native route admitted) - for (engine, session, request, native) in [ - // Nothing asks for the fallback, so the route is planned as before. - (false, None, None, true), - (false, None, Some("false"), true), - (false, Some(false), None, true), - // A per-query source turns the fallback on, so the route is declined. - (false, Some(true), None, false), - (false, None, Some("true"), false), - (false, None, Some("TRUE"), false), - // The engine option is the default: a stated `false` overrides it. - (true, None, None, false), - (true, None, Some("false"), true), - (true, Some(true), Some("false"), true), - (true, Some(false), None, true), + async fn test_plan_pql_offers_the_native_route_whatever_the_fallback_says() { + // (engine option, session variable, hint) + for (engine, session, request) in [ + (false, None, None), + (false, None, Some("false")), + (false, Some(false), None), + // A per-query source turns the fallback on. + (false, Some(true), None), + (false, None, Some("true")), + (false, None, Some("TRUE")), + (true, None, None), + (true, None, Some("false")), + (true, Some(true), Some("false")), + (true, Some(false), None), ] { let plan = plan_native_promql_with_fallback(engine, session, request) .await .unwrap(); - assert_eq!( + assert!( plan.contains("FusedSeries"), - native, "engine={engine}, session={session:?}, request={request:?}: {plan}" ); } @@ -1710,16 +1627,35 @@ mod tests { } /// One deployment, one topology: an engine that plans regions reads every selector through one - /// source per region, so the admission gate admits the same shapes wherever those regions are. - /// An engine with no distributed planner plans no region, so its plans keep the shapes a region - /// runs itself and there is nothing for the gate to judge. + /// source per region, and either deployment answers a statement it was offered for with the + /// route's own fused node - the wrappers a statement root can carry included. #[tokio::test] - async fn test_native_promql_admission_is_the_same_for_both_deployments() { - for (with_dist_planner, query, sourced) in [ - (false, "some_metric + other_metric", true), - (false, "rate(some_metric[5m])", false), - (true, "some_metric + other_metric", true), - (true, "rate(some_metric[5m])", true), + async fn test_native_promql_plans_the_same_for_both_deployments() { + for (with_dist_planner, query, alias, wrapper, sourced) in [ + (false, "some_metric + other_metric", None, None, true), + (false, "rate(some_metric[5m])", None, None, false), + (true, "some_metric + other_metric", None, None, true), + (true, "rate(some_metric[5m])", None, None, true), + // A statement that reads no table has no region to read, and a wrapper over it - the + // `EXPLAIN`/`ANALYZE` shell, or the `AS` alias's renamed projection - is planned + // natively as well. + (false, "time()", None, None, false), + (true, "time()", None, None, false), + (true, "time()", Some("v"), None, false), + ( + true, + "time()", + None, + Some(crate::parser::EXPLAIN_NODE_NAME), + false, + ), + ( + true, + "time()", + None, + Some(crate::parser::ANALYZE_NODE_NAME), + false, + ), ] { let engine = create_promql_test_engine_with( crate::options::QueryOptions { @@ -1740,26 +1676,36 @@ mod tests { end: "10".to_string(), step: "5s".to_string(), lookback: "300s".to_string(), - alias: None, + alias: alias.map(str::to_string), }, &query_ctx, ) .unwrap(); + let stmt = match wrapper { + Some(name) => stmt + .post_process(HashMap::from([("name".to_string(), name.to_string())])) + .unwrap(), + None => stmt, + }; let plan = engine.planner().plan(&stmt, query_ctx).await.unwrap(); let display = plan.display_indent().to_string(); assert!( - display.contains("FusedSeries"), - "with_dist_planner={with_dist_planner}, query={query}: {display}" + !fused_series_nodes(&plan).is_empty(), + "with_dist_planner={with_dist_planner}, query={query}, alias={alias:?}, \ + wrapper={wrapper:?}: {display}" + ); + assert!( + !logical_plan_nodes(&plan) + .iter() + .any(|node| matches!(node, LogicalPlan::Join(_))), + "with_dist_planner={with_dist_planner}, query={query}, alias={alias:?}, \ + wrapper={wrapper:?}: {display}" ); - if with_dist_planner { - // The gate admits the plan instead of replanning it through the legacy route: one - // source per region under a fused node. - assert!(remote_native_raw_plan_supported(&plan), "{display}"); - } assert_eq!( display.contains("RawSeriesSource"), sourced, - "with_dist_planner={with_dist_planner}, query={query}: {display}" + "with_dist_planner={with_dist_planner}, query={query}, alias={alias:?}, \ + wrapper={wrapper:?}: {display}" ); } } @@ -2712,13 +2658,126 @@ mod tests { ); } - /// A statement whose columns do not pair keeps the existing plan. + /// The no-input `time()` pair is the only one the narrow publication accepts. /// - /// Publishing a column this cannot fill would change what the CTE means, so a shape it cannot - /// map faithfully is refused instead: the caller keeps the existing plan and the CTE keeps the - /// columns it has always published. + /// The rule opens for exactly one shape: a marked millisecond grid column beside one float, on + /// the native side, against the same column unmarked beside one float on the existing side. + /// Every near miss - both sides marked, an integer value, a third column, a microsecond or a + /// nullable grid - stays unpublishable, which is what keeps it from publishing a relation whose + /// columns really do differ. #[test] - fn a_shape_with_no_faithful_column_mapping_keeps_the_existing_plan() { + fn only_the_no_input_time_pair_is_published_by_the_narrow_rule() { + use std::collections::HashMap; + + use arrow_schema::Field; + + let millis = || DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None); + let grid = |marked: bool| { + let field = Field::new("time", millis(), false); + let field = if marked { + field.with_metadata(HashMap::from([( + datatypes::schema::TIME_INDEX_KEY.to_string(), + "true".to_string(), + )])) + } else { + field + }; + (None, Arc::new(field)) + }; + let value = + |name: &str, data_type: DataType| (None, Arc::new(Field::new(name, data_type, true))); + let schema = |fields: Vec<(Option, Arc)>| { + Arc::new(DFSchema::new_with_metadata(fields, HashMap::new()).unwrap()) + }; + let native = schema(vec![grid(true), value("time()", DataType::Float64)]); + let legacy = schema(vec![ + grid(false), + value("time / Float64(1000)", DataType::Float64), + ]); + assert!( + is_empty_time_pair(native.as_ref(), legacy.as_ref()), + "the empty `time()` pair is published" + ); + + // Both sides marking their grid is already paired by role, and neither side marking one has + // no grid to publish. + assert!(!is_empty_time_pair( + native.as_ref(), + schema(vec![ + grid(true), + value("time / Float64(1000)", DataType::Float64), + ]) + .as_ref() + )); + assert!(!is_empty_time_pair( + schema(vec![grid(false), value("time()", DataType::Float64),]).as_ref(), + legacy.as_ref() + )); + // A value the two routes type differently is not the same answer. + assert!(!is_empty_time_pair( + native.as_ref(), + schema(vec![ + grid(false), + value("time / Float64(1000)", DataType::Int64) + ]) + .as_ref() + )); + // A third column is a different answer, whatever its type. + assert!(!is_empty_time_pair( + native.as_ref(), + schema(vec![ + grid(false), + value("time / Float64(1000)", DataType::Float64), + value("host", DataType::Utf8), + ]) + .as_ref() + )); + // The grid must be the millisecond one both routes compute on, and non-null. + assert!(!is_empty_time_pair( + native.as_ref(), + schema(vec![ + ( + None, + Arc::new(Field::new( + "time", + DataType::Timestamp(arrow_schema::TimeUnit::Microsecond, None), + false, + )), + ), + value("time / Float64(1000)", DataType::Float64), + ]) + .as_ref() + )); + assert!(!is_empty_time_pair( + Arc::new( + DFSchema::new_with_metadata( + vec![ + ( + None, + Arc::new(Field::new("time", millis(), true).with_metadata( + HashMap::from([( + datatypes::schema::TIME_INDEX_KEY.to_string(), + "true".to_string(), + )]), + )), + ), + value("time()", DataType::Float64), + ], + HashMap::new(), + ) + .unwrap(), + ) + .as_ref(), + legacy.as_ref() + )); + } + + /// A statement whose columns do not pair publishes no plan. + /// + /// Publishing a column this cannot fill would change what the CTE means, so such a shape maps + /// to `None` and the caller refuses the statement rather than publish another route's answer. + #[test] + fn a_shape_with_no_faithful_column_mapping_publishes_nothing() { // One native value column cannot fill two of the existing plan's value columns. let two_values = plan_publishing_marked( &[ diff --git a/src/query/src/promql/error.rs b/src/query/src/promql/error.rs index fb1ef3aef84..f8a5e8baa0d 100644 --- a/src/query/src/promql/error.rs +++ b/src/query/src/promql/error.rs @@ -261,6 +261,13 @@ pub enum Error { #[snafu(implicit)] location: Location, }, + + #[snafu(display("Native PromQL route declined this expression: {}", reason))] + NativeDeclined { + reason: String, + #[snafu(implicit)] + location: Location, + }, } impl ErrorExt for Error { @@ -302,6 +309,7 @@ impl ErrorExt for Error { MultipleMetricMatchers { .. } | NoMetricMatcher { .. } => StatusCode::InvalidSyntax, MultiFieldsNotSupported { .. } => StatusCode::Unsupported, + NativeDeclined { .. } => StatusCode::Unsupported, Catalog { source, .. } => source.status_code(), } } diff --git a/src/query/src/promql/planner.rs b/src/query/src/promql/planner.rs index 862c74e603b..b07990cbbc6 100644 --- a/src/query/src/promql/planner.rs +++ b/src/query/src/promql/planner.rs @@ -372,8 +372,8 @@ impl PromPlanner { /// Plans a PromQL statement and passes the optional collector to histogram UDFs. /// /// `native_fused` enables the native fused-series route: the statement is offered to - /// [`compile`](crate::promql::native_compile::compile) first, and whatever that compiler does - /// not accept is planned by the existing path, unchanged. See + /// [`compile`](crate::promql::native_compile::compile) first, and a statement that compiler + /// declines fails with the cause it recorded instead of being planned another way. See /// [`Self::try_plan_native_fused`]. pub async fn stmt_to_plan_with_annotations( table_provider: DfTableSourceProvider, @@ -395,13 +395,14 @@ impl PromPlanner { // The whole statement is offered to the native compiler first, because that compiler folds // a range function and the math functions over it into one tree: offered any later, the // expression has already been split into the nodes those functions would have shared. A - // shape it does not accept is planned by the existing path exactly as if it were not here. + // statement the route does not accept fails with the cause it recorded. if let Some(plan) = planner .try_plan_native_statement(&stmt.expr, query_engine_state) .await? { return planner.strip_tsid_column(plan); } + // Reached only when the route was never requested, or for a wrapper. let plan = planner .prom_root_expr_to_plan(&stmt.expr, query_engine_state) .await?; @@ -2603,6 +2604,20 @@ impl PromPlanner { // let promql_parser::parser::ast::Extension { expr } = ext_expr; let expr = &ext_expr.expr; let children = expr.children(); + if self.native_fused + && !matches!( + expr.name(), + ANALYZE_NODE_NAME + | ANALYZE_VERBOSE_NODE_NAME + | EXPLAIN_NODE_NAME + | EXPLAIN_VERBOSE_NODE_NAME + | ALIAS_NODE_NAME + ) + { + return Err(native::declined_statement( + "unsupported_statement_extension", + )); + } let native_plan = match expr.name() { ANALYZE_NODE_NAME | ANALYZE_VERBOSE_NODE_NAME @@ -2615,6 +2630,7 @@ impl PromPlanner { }; let plan = match native_plan { Some(plan) => plan, + // Only a route that was never requested answers `None` here; a refusal raised above. None => { self.prom_root_expr_to_plan(&children[0], query_engine_state) .await? diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index e9c898efb6c..824be6d5e83 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -18,7 +18,8 @@ //! when it is accepted, plans it as [`FusedSeries`] nodes over the selectors' table scans. //! For splittable aggregates, a `Partial` producer sends state through `SeriesRepartitionExec` //! to a `Final` consumer. Aggregates without mergeable state, such as `quantile`, can still be -//! planned over segments. If the native route declines the statement, the existing planner handles it. +//! planned over segments. A statement the native route declines is not planned at all: the offer +//! fails with the cause the route recorded. //! //! The row output schema is the time index, then the value fields, then the tags: the same shape a //! `SeriesNormalize` output has. A statement that reads no data is planned as one node without a @@ -53,7 +54,7 @@ use promql::extension_plan::{ matching_operands_drop_key, }; use promql::native::plan::{ - AggregateKind, BoundAggregate, BoundInput, NativeExpr, NativeNode, NativeTree, NativeType, + BoundAggregate, BoundInput, NativeExpr, NativeNode, NativeTree, NativeType, aggregate_state_binding, binary_output_field_kind, fused_output_tags, native_tree_supported, uniform_field_kind, }; @@ -81,7 +82,8 @@ use store_api::region_engine::RawLabelSource; use crate::parser::AliasExpr; use crate::promql::error::{ - DataFusionPlanningSnafu, Result, TimeIndexNotFoundSnafu, UnsupportedExprSnafu, + DataFusionPlanningSnafu, NativeDeclinedSnafu, Result, TimeIndexNotFoundSnafu, + UnsupportedExprSnafu, }; use crate::promql::native_compile::{ InfoInput, bind_evaluated_binary, compile_selectors_with_grid, compile_statement_with_grid, @@ -248,7 +250,7 @@ const NATIVE_DECLINE_UNRECORDED: &str = "cause_not_recorded"; /// another, which the drop merges into one label set. const UNPROVED_LABELSET_CHECK_NULLABLE_KEY: &str = "nullable_key"; -/// Returns `None` to hand the expression to the existing planner, recording `reason`. +/// Refuses the expression, recording `reason` as the cause the offer will fail with. fn declined(reason: &'static str) -> Option { NATIVE_DECLINE.with(|record| record.set(Some(reason))); None @@ -259,6 +261,20 @@ fn take_native_decline() -> Option<&'static str> { NATIVE_DECLINE.with(|record| record.replace(None)) } +/// The refusal of a statement the route was offered and cannot plan, reported with `reason`. +pub(super) fn declined_statement(reason: &'static str) -> crate::promql::error::Error { + debug!("Native PromQL route declined this expression ({reason})"); + crate::metrics::NATIVE_PROMQL_DECLINED_TOTAL + .with_label_values(&[reason]) + .inc(); + #[cfg(test)] + REPORTED_DECLINE.with(|reported| reported.set(Some(reason))); + NativeDeclinedSnafu { + reason: reason.to_string(), + } + .build() +} + /// Clears the attempt count and answers how many attempts this thread made since the last call. #[cfg(test)] pub(crate) fn take_native_attempts() -> usize { @@ -545,15 +561,16 @@ impl PromPlanner { prom_expr: &PromExpr, query_engine_state: &QueryEngineState, ) -> Result> { - let alias = match prom_expr { - PromExpr::Extension(extension) => extension.expr.as_any().downcast_ref::(), - _ => None, - }; - let Some(alias) = alias else { + let PromExpr::Extension(extension) = prom_expr else { return self .try_plan_native_fused(prom_expr, query_engine_state) .await; }; + let Some(alias) = extension.expr.as_any().downcast_ref::() else { + // A wrapper such as `EXPLAIN` is not a native expression: the existing planner plans it + // and offers what it wraps below. + return Ok(None); + }; let statement_ctx = self.ctx.clone(); let Some(plan) = self .try_plan_native_fused(&alias.expr, query_engine_state) @@ -593,20 +610,26 @@ impl PromPlanner { match aliased_rows(plan, &alias.alias, &labels, &time)? { Some(plan) => Ok(Some(plan)), None => { - // The existing plan reports a different label set, so only it can answer in its own - // layout. + // The existing plan reports a different label set, so this route cannot publish the + // alias in that layout, and a statement it was offered is not planned another way. self.ctx = statement_ctx; let reason = "alias_labels_differ_from_existing_plan"; + debug!("Native PromQL route declined this expression ({reason})"); crate::metrics::NATIVE_PROMQL_DECLINED_TOTAL .with_label_values(&[reason]) .inc(); #[cfg(test)] REPORTED_DECLINE.with(|reported| reported.set(Some(reason))); - Ok(None) + Err(NativeDeclinedSnafu { + reason: reason.to_string(), + } + .build()) } } } + /// Plans `prom_expr` natively, or fails with the cause it recorded; `Ok(None)` means the route + /// was never requested. pub(super) async fn try_plan_native_fused( &mut self, prom_expr: &PromExpr, @@ -616,6 +639,8 @@ impl PromPlanner { if !self.native_fused { return Ok(None); } + // A cause recorded before this offer cannot describe it. + let _ = take_native_decline(); let planned = self .try_plan_native(prom_expr, query_engine_state, FusedOutputFormat::PlainRows) .await?; @@ -635,16 +660,16 @@ impl PromPlanner { } _ => { let reason = take_native_decline().unwrap_or(NATIVE_DECLINE_UNRECORDED); - debug!( - "Native PromQL route declined this expression ({reason}); \ - the existing planner answers it" - ); + debug!("Native PromQL route declined this expression ({reason})"); crate::metrics::NATIVE_PROMQL_DECLINED_TOTAL .with_label_values(&[reason]) .inc(); #[cfg(test)] REPORTED_DECLINE.with(|reported| reported.set(Some(reason))); - Ok(None) + Err(NativeDeclinedSnafu { + reason: reason.to_string(), + } + .build()) } } } @@ -711,6 +736,7 @@ impl PromPlanner { return Ok(None); }; let saved = self.ctx.clone(); + let _ = take_native_decline(); let left = self .try_plan_native( &binary.lhs, @@ -718,10 +744,14 @@ impl PromPlanner { FusedOutputFormat::SeriesFrame, ) .await; + let left_cause = take_native_decline(); self.ctx = saved.clone(); let Some(NativePlanned::Frame(left)) = left? else { - return Ok(declined("left_operand_is_not_a_frame")); + 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, @@ -729,9 +759,12 @@ impl PromPlanner { FusedOutputFormat::SeriesFrame, ) .await; + let right_cause = take_native_decline(); self.ctx = saved; let Some(NativePlanned::Frame(right)) = right? else { - return Ok(declined("right_operand_is_not_a_frame")); + 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")); @@ -1653,14 +1686,6 @@ impl PromPlanner { } else { None }; - // A tree over several inputs folds every partition in one node above them, histograms - // included. The kind entering each aggregate decides, not the root's shape: `sum(h) * 2` has - // a binary root. - if let Some(kind @ FieldKind::Histogram) = statement_kind - && aggregate_reads_histogram(root, kind) - { - return Ok(declined("histogram_aggregate_needs_state_this_route_lacks")); - } // A tree over more than one input reads its inputs' partitions in the order they became // ready, which decides nothing: `limitk` picks its members by the hash of their labels, so // a group gathered in any order keeps the same ones. No other operation is left to that @@ -1783,7 +1808,7 @@ impl PromPlanner { }; // With only empty inputs, the time index is the synthetic `time` column // (`setup_context_for_empty_metric`); a value of the same name moves it to the first free - // `native_time_N`. A value colliding with a tag keeps the existing plan. + // `native_time_N`. A value colliding with a tag cannot be declared by this layout. let time = if named_by_a_real_input { time } else { @@ -1792,7 +1817,7 @@ impl PromPlanner { .iter() .any(|name| output_tags.iter().any(|tag| tag == name)) { - return Ok(None); + return Ok(declined("value_column_collides_with_a_tag")); } free_time_index(&time, &value_names, &output_tags) }; @@ -2406,30 +2431,6 @@ fn scan_time_filter( } } -/// Whether any aggregate in `node` consumes histogram samples, wherever it sits in the tree. -/// -/// Only `sum` and `avg` fold a histogram payload; they are admitted when they bind histogram state. -/// An input whose kind cannot be named (e.g. through a canonical merge or a set operation) counts -/// as a histogram. -fn aggregate_reads_histogram(node: &NativeNode, input_kind: FieldKind) -> bool { - // `count` and `group` count a histogram as one sample; `min`, `max`, `stddev`, `stdvar` and - // `quantile` skip it as Prometheus does (legacy: `create_native_histogram_aggregate_expr`). - // `sum` and `avg` fold the payload only when they bind histogram state. A kind the walk cannot - // name, such as a set operation whose sides disagree, is refused. - node.any(&|node| { - matches!( - &node.expr, - NativeExpr::Aggregate { input, op } - if matches!(op.kind, AggregateKind::Sum | AggregateKind::Avg) - && !matches!( - input.output_field_kind(Some(input_kind)), - Some(FieldKind::Float) - ) - && !binds_histogram_state(op) - ) - }) -} - /// Whether this aggregate's state carries a native histogram, per [`aggregate_state_binding`], the /// table the compiler and the split bind from. fn binds_histogram_state(op: &BoundAggregate) -> bool { @@ -2740,9 +2741,9 @@ mod tests { use super::{ ArrowDataType, FieldKind, METRIC_NAME, NATIVE_PROMQL_EXTENSION_KEY, NativeType, - PromPlanner, aggregate_reads_histogram, collect_selectors_with_set_operations, - fused_output_schema, independent_scan_pair, native_promql_requested, - native_promql_resolved, native_raw_plan_bounds_region_reads, scan_time_filter, + PromPlanner, collect_selectors_with_set_operations, fused_output_schema, + independent_scan_pair, native_promql_requested, native_promql_resolved, + native_raw_plan_bounds_region_reads, scan_time_filter, }; /// The switch resolves from the two sources planning reads: what the query states (a request @@ -2836,14 +2837,6 @@ mod tests { .tree } - #[test] - fn aggregate_histogram_walk_descends_through_scalar_vector_wrappers() { - let tree = compiled_test_tree("scalar(vector(scalar(sum(some_metric))))"); - assert_eq!(input_sources(tree.root()), vec![0]); - assert!(aggregate_reads_histogram(tree.root(), FieldKind::Histogram)); - assert!(!aggregate_reads_histogram(tree.root(), FieldKind::Float)); - } - fn input_sources(root: &NativeNode) -> Vec { root.inputs() .into_iter() diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index 6420103ea83..1b956d9e669 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -2611,56 +2611,28 @@ async fn native_empty_discovery_declares_the_field_its_matcher_names() { } } -/// A rule that drops every name the input can be given leaves no layout, so the selection keeps the -/// existing plan - including the refusal it raises when it has no table to bind. +/// A zero-match `__field__` operator this route cannot apply is refused, naming the layout it +/// cannot state. +/// +/// The field operators other than `=` keep or drop columns by a rule over every field a table +/// carries, and an input that reads no table has none: there is no layout to state, so the +/// selection is not one this route answers. #[tokio::test] -async fn native_empty_discovery_keeps_a_field_operator_it_cannot_apply() { +async fn native_empty_discovery_declines_a_field_operator_it_cannot_apply() { for query in [ r#"{__field__=~"field.*", job="api"}"#, r#"{__field__!="value", job="api"}"#, r#"{__field__!~"value", job="api"}"#, ] { - let native = PromPlanner::stmt_to_plan_with_annotations( - metric_discovery_provider(&["alpha_total", "beta_total"]).await, - &build_eval_stmt(query), - &build_query_engine_state(), - None, - true, - ) - .await; - let without_flag = PromPlanner::stmt_to_plan_with_annotations( - metric_discovery_provider(&["alpha_total", "beta_total"]).await, - &build_eval_stmt(query), - &build_query_engine_state(), - None, - false, - ) - .await; - match (native, without_flag) { - (Ok(native), Ok(without_flag)) => { - assert!( - find_fused_series(&native).is_none(), - "`{query}` claimed a field layout nothing decided: {}", - native.display_indent() - ); - assert_eq!( - without_flag.display_indent().to_string(), - native.display_indent().to_string(), - "`{query}` must keep the existing plan" - ); - } - // The existing planner has no table to bind, which is the answer this route leaves it. - (Err(native), Err(without_flag)) => assert_eq!( - without_flag.to_string(), - native.to_string(), - "`{query}` reports the existing planner's own refusal" - ), - (native, without_flag) => panic!( - "`{query}`: the route answered {} where the existing planner answered {}", - native.is_ok(), - without_flag.is_ok() - ), - } + assert_eq!( + "field_matcher_has_no_empty_layout", + native_decline_reason( + query, + metric_discovery_provider(&["alpha_total", "beta_total"]).await + ) + .await, + "`{query}` has no table whose fields the operator could rule over" + ); } } @@ -2865,18 +2837,16 @@ async fn native_named_selector_over_a_missing_table_plans_as_an_empty_input() { } } - // A `__field__` matcher still declines over a table this route can read: the matcher narrows the + // 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. let query = r#"x{__field__="field_0"}"#; - let plan = - build_native_fused_plan_with_provider(query, true, named_missing_table_provider().await) - .await; - assert!( - find_fused_series(&plan).is_none(), - "`{query}` claimed a field layout its scan does not report: {plan:?}" + 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" ); } @@ -3526,8 +3496,9 @@ fn fused_trees(plan: &LogicalPlan) -> Vec { trees } -async fn build_native_fused_plan(query: &str, native_fused: bool) -> LogicalPlan { - let table_provider = build_test_table_provider_with_options( +/// The fixture `build_native_fused_plan` plans against, for tests that state the outcome themselves. +async fn build_native_fused_table_provider() -> DfTableSourceProvider { + build_test_table_provider_with_options( &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], 1, 1, @@ -3537,7 +3508,11 @@ async fn build_native_fused_plan(query: &str, native_fused: bool) -> LogicalPlan ConcreteDataType::float64_datatype(), NATIVE_ENGINE, ) - .await; + .await +} + +async fn build_native_fused_plan(query: &str, native_fused: bool) -> LogicalPlan { + let table_provider = build_native_fused_table_provider().await; build_native_fused_plan_with_provider(query, native_fused, table_provider).await } @@ -4857,24 +4832,21 @@ 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; - let display = plan.display_indent().to_string(); - // The count below is only a bound if the matcher really crossed to the other operand. - assert!( - display.contains("some_metric.tag_0 = Utf8(\"x\")"), - "{query}: the matcher reached the other operand's scan: {display}" + 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" ); counts.push(take_native_attempts()); } - // Seven offers either way: the statement, its root's own retry under the legacy-only - // `__field__` matcher, the frame operands the composed attempts beside those two read, and the - // propagated operand itself. The four operators that make the deep statement deeper are inside + // 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. assert_eq!( - (7, 7), + (3, 3), (counts[0], counts[1]), - "a propagated operand is offered once whatever its depth: seven offers at both depths" + "a propagated operand is offered once whatever its depth: three offers at both depths" ); } @@ -4886,15 +4858,13 @@ 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`] plans: whether a native node answers the rewritten -/// operand, and whether the propagated matcher reached the other operand's scan. -async fn propagation_route(depth: usize) -> (bool, bool) { - let plan = build_native_fused_plan(&propagation_query(depth), true).await; - let display = plan.display_indent().to_string(); - ( - find_fused_series(&plan).is_some(), - display.contains("some_metric.tag_0 = Utf8(\"x\")"), +/// 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, ) + .await } /// A chain under a propagated matcher plans on the stack a query worker has, however deep it is. @@ -4930,51 +4900,29 @@ 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!( - (true, true), - route, - "the rewritten operand is native and the matcher reached the other operand's scan" + "field_selector_without_raw_series_equivalent", route, + "the propagated `__field__` operand narrows a field set at any depth" ); } -/// A metric table without logical-table metadata declines to the legacy plan. +/// A metric table without logical-table metadata is refused, naming the missing scanner. #[tokio::test] -async fn native_fused_metric_table_without_logical_metadata_falls_back() { - let native = build_native_fused_plan_with_provider( - "rate(some_metric[5m])", - true, - build_test_table_provider_with_options( - &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], - 1, - 1, - vec![], - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ConcreteDataType::float64_datatype(), - METRIC_ENGINE, - ) - .await, - ) - .await; - let legacy = build_native_fused_plan_with_provider( - "rate(some_metric[5m])", +async fn native_fused_metric_table_without_logical_metadata_is_declined() { + let table_provider = build_test_table_provider_with_options( + &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], + 1, + 1, + vec![], + ConcreteDataType::timestamp_millisecond_datatype(), false, - build_test_table_provider_with_options( - &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], - 1, - 1, - vec![], - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ConcreteDataType::float64_datatype(), - METRIC_ENGINE, - ) - .await, + ConcreteDataType::float64_datatype(), + METRIC_ENGINE, ) .await; - assert!(find_fused_series(&native).is_none()); assert_eq!( - native.display_indent().to_string(), - legacy.display_indent().to_string() + "engine_without_raw_series_scanner", + native_decline_reason("rate(some_metric[5m])", table_provider).await, + "a metric table with no logical table behind it has no raw series scanner" ); } @@ -5094,37 +5042,109 @@ async fn native_fused_file_engine_reads_through_a_row_source() { assert_eq!(scan.filters.len(), 1, "only the time range prunes the scan"); } -/// The plan `query` gets, or `None` when the planner refuses it. +/// The cause a declined offer reports. +fn decline_reason(error: &crate::promql::error::Error) -> &str { + match error { + crate::promql::error::Error::NativeDeclined { reason, .. } => reason, + other => panic!("expected a native decline, got {other:?}"), + } +} + +/// The cause the native route refuses `query` with, for a route the query asked for. /// -/// A field the raw series scan cannot read must not change what the statement answers, and some of -/// these statements the existing planner refuses outright: that refusal is its answer, so a test has -/// to be able to hold the route to it instead of unwrapping a plan. -async fn plan_or_refusal( - query: &str, - native_fused: bool, - table_provider: DfTableSourceProvider, -) -> Option { - PromPlanner::stmt_to_plan_with_annotations( +/// The offer answers a statement or fails with the cause it recorded, so a test holds the route to +/// that cause instead of to a plan some other route would have built. +async fn native_decline_reason(query: &str, table_provider: DfTableSourceProvider) -> String { + let error = PromPlanner::stmt_to_plan_with_annotations( table_provider, &build_eval_stmt(query), &build_query_engine_state(), None, - native_fused, + true, ) .await - .ok() + .expect_err("the native route answered this statement"); + decline_reason(&error).to_string() } -/// A value field the raw-series readers cannot serve keeps the existing plan. +/// A statement shell no parser builds, standing for an extension this planner does not know. +#[derive(Debug)] +struct ForeignExtension(parser::Expr); + +impl promql_parser::parser::ast::ExtensionExpr for ForeignExtension { + fn as_any(&self) -> &dyn std::any::Any { + self + } + + fn name(&self) -> &str { + "FOREIGN" + } + + fn value_type(&self) -> promql_parser::parser::value::ValueType { + self.0.value_type() + } + + fn children(&self) -> &[parser::Expr] { + std::slice::from_ref(&self.0) + } + + fn with_new_children( + &self, + children: Vec, + ) -> Arc { + Arc::new(Self( + children + .into_iter() + .next() + .unwrap_or_else(|| self.0.clone()), + )) + } +} + +/// A statement shell this planner does not know is refused by name when the route is asked for, +/// and keeps the plan the existing route builds when it is not. +#[tokio::test] +async fn native_fused_refuses_an_unknown_statement_extension() { + let mut stmt = build_eval_stmt("time()"); + let inner = stmt.expr.clone(); + stmt.expr = parser::Expr::Extension(promql_parser::parser::ast::Extension { + expr: Arc::new(ForeignExtension(inner)), + }); + let error = PromPlanner::stmt_to_plan_with_annotations( + native_mixed_kind_provider().await, + &stmt, + &build_query_engine_state(), + None, + true, + ) + .await + .expect_err("the native route answered an extension it does not know"); + assert_eq!("unsupported_statement_extension", decline_reason(&error)); + + let plan = PromPlanner::stmt_to_plan_with_annotations( + native_mixed_kind_provider().await, + &stmt, + &build_query_engine_state(), + None, + false, + ) + .await + .unwrap(); + assert!( + matches!(plan, LogicalPlan::EmptyRelation(_)), + "a route that was never asked for keeps the existing plan: {plan:?}" + ); +} + +/// A value field the raw-series readers cannot serve is refused, whatever the shape. /// /// The route admits two kinds: a `Float64`, which every reader serves, and the canonical native /// histogram struct, which the ordinary scan reads while the columnar samples - `Float64` only - /// are skipped for that selection. Everything else - a string, a boolean, a decimal - has no raw -/// representation and keeps the existing plan whatever the shape of the statement, including the -/// shapes that publish a `Float64` for a numeric field: `some_metric * 2` casts a string as readily -/// as an integer, and the route still refuses it because no raw frame can hold the values. +/// representation, including the shapes that publish a `Float64` for a numeric field: `some_metric +/// * 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_falls_back() { +async fn native_fused_unsupported_field_type_is_declined() { for field_type in [ ConcreteDataType::string_datatype(), ConcreteDataType::boolean_datatype(), @@ -5132,44 +5152,24 @@ async fn native_fused_unsupported_field_type_falls_back() { // the route's own numeric set leaves the decimals out; asking Arrow would let it through. ConcreteDataType::decimal128_datatype(10, 2), ] { - for query in [ - "some_metric", - "some_metric * 2", - "sum(some_metric)", - "min(some_metric)", - "rate(some_metric[5m])", + for (query, reason) in [ + ("some_metric", "mixed_field_kinds"), + // 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"), ] { - let native = plan_or_refusal( - query, - true, - build_test_table_provider_with_field_type(field_type.clone()).await, - ) - .await; - let without_flag = plan_or_refusal( - query, - false, - build_test_table_provider_with_field_type(field_type.clone()).await, - ) - .await; - match (&native, &without_flag) { - (Some(native_plan), Some(legacy_plan)) => { - assert!( - find_fused_series(native_plan).is_none(), - "{field_type} must not reach the native route: {query}" - ); - assert_eq!( - native_plan.display_indent().to_string(), - legacy_plan.display_indent().to_string(), - "{field_type} must keep the existing plan: {query}" - ); - } - _ => assert_eq!( - native.is_some(), - without_flag.is_some(), - "{field_type}: the route must answer what the existing planner answers for \ - {query}" - ), - } + assert_eq!( + reason, + native_decline_reason( + query, + build_test_table_provider_with_field_type(field_type.clone()).await + ) + .await, + "{field_type} has no raw series representation: {query}" + ); } } } @@ -5191,28 +5191,21 @@ async fn native_fused_float64_field_is_accepted() { ); } -/// Alternative (`or`) matchers keep the existing plan. +/// 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 fall back: what the existing plan answers for -/// them is its own question, not one this route claims to have fixed. +/// 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_fall_back() { +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])"#, ] { - let native = build_native_fused_plan(query, true).await; - let without_flag = build_native_fused_plan(query, false).await; - assert!( - find_fused_series(&native).is_none(), - "`{query}` names alternative matchers: {}", - native.display_indent() - ); assert_eq!( - native.display_indent().to_string(), - without_flag.display_indent().to_string(), - "`{query}` must keep the existing plan" + "or_matchers_have_no_single_raw_scan", + native_decline_reason(query, build_native_fused_table_provider().await).await, + "`{query}` names alternative matchers" ); } } @@ -5700,29 +5693,16 @@ async fn native_composed_binary_admits_fill() { // A filled left side meets the right side alone, and `float * float` is a float: with a // histogram on the right, one column would have to carry a histogram row and a float row. The - // kind walk refuses that shape, so the statement keeps the existing plan, which answers no fill - // at all - the two refusals are the type's, not a whitelist's. + // kind walk refuses that shape, so the route refuses the statement - the two refusals are the + // type's, not a whitelist's. for query in [ "hist * on(tag_0) fill_left(0) floats", "hist * on(tag_0) fill(0) floats", ] { - let stmt = build_eval_stmt(query); - let error = PromPlanner::stmt_to_plan_with_annotations( - native_mixed_kind_provider().await, - &stmt, - &build_query_engine_state(), - None, - true, - ) - .await - .unwrap_err(); - assert!( - matches!( - &error, - crate::promql::error::Error::UnsupportedExpr { name, .. } - if name == "PromQL fill modifiers" - ), - "{query}: {error}" + assert_eq!( + "no_output_kind_for_the_pair", + native_decline_reason(query, native_mixed_kind_provider().await).await, + "{query}: no single column carries a histogram row and a float row" ); } @@ -6141,19 +6121,13 @@ async fn native_composed_binary_admits_complex_operands() { assert!(!display.contains("Join:"), "{segmented_query}: {display}"); } -/// A composed binary that meets a shape its kernels refuse keeps the existing plan. +/// 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. None of these may turn into a planning error, -/// because the existing route answers them. +/// exactly as it would on the whole statement - and a declined offer is the statement's answer. #[tokio::test] -async fn native_composed_binary_declines_to_the_existing_plan() { - // An operand that is not a frame leaves the statement's own wrapper in place: the pair is - // refused, so the existing plan answers the statement. The offer is the statement's, and the - // binary that makes it spends it for the whole subtree below: the operand is planned by the - // existing path too, because a refused chain of n operators would otherwise compile its - // subtrees again at every operator. +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. @@ -6166,31 +6140,10 @@ async fn native_composed_binary_declines_to_the_existing_plan() { // `native_promql_kind_rules_match_legacy` (tests-integration) holds both routes' rows to // the same empty answer. ] { - let plan = - build_native_fused_plan_with_provider(query, true, native_mixed_kind_provider().await) - .await; - let display = plan.display_indent().to_string(); - assert!( - !is_fused_series(&plan), - "`{query}` has no composed answer: {display}" - ); - assert!( - find_fused_series(&plan).is_none(), - "`{query}` spends its one offer above the operand: {display}" - ); - let legacy = PromPlanner::stmt_to_plan_with_annotations( - native_mixed_kind_provider().await, - &build_eval_stmt(query), - &build_query_engine_state(), - None, - false, - ) - .await - .unwrap_or_else(|error| panic!("`{query}`: the existing route must answer it: {error}")); assert_eq!( - legacy.display_indent().to_string(), - display, - "`{query}` must keep the existing plan" + "frame_operand_is_not_evaluated", + native_decline_reason(query, native_mixed_kind_provider().await).await, + "`{query}`: the scalar operand has no evaluated frame" ); } } @@ -6341,61 +6294,19 @@ async fn native_histogram_binary_fill_declares_possible_payload_kind() { } } -/// A legacy-only outer function reaches a composed native binary, including statement anchors. +/// A pair of selectors that answer different kinds is refused, whatever the wrapper above it. #[tokio::test] -async fn native_fused_binary_inside_legacy_math_preserves_anchors() { +async fn native_fused_binary_inside_legacy_math_is_declined() { for query in [ "ceil(clamp(histogram_count(hist), 1, 2) + on(tag_0) floats)", "ceil((clamp(histogram_count(hist @ end() offset 1m), 1, 2) + on(tag_0) floats @ start()))", ] { - let plan = - build_native_fused_plan_with_provider(query, true, native_mixed_kind_provider().await) - .await; - let display = plan.display_indent().to_string(); - let fused = find_fused_series(&plan).unwrap_or_else(|| panic!("{query}: {display}")); - let NativeExpr::Binary { left, right, .. } = &fused.tree().root().expr else { - panic!("expected composed Binary for {query}: {display}"); - }; - assert!( - matches!(left.expr, NativeExpr::Input(_)) && matches!(right.expr, NativeExpr::Input(_)), - "{display}" + // The two selectors answer different kinds, so the statement is not one this route reads. + assert_eq!( + "selectors_disagree_on_field_kind", + native_decline_reason(query, native_mixed_kind_provider().await).await, + "{query}" ); - assert_eq!(2, fused.children().len(), "{display}"); - assert!(!display.contains("Join:"), "{display}"); - let expected_value = match query { - "ceil(clamp(histogram_count(hist), 1, 2) + on(tag_0) floats)" => { - "ceil(clamp(histogram_count(hist), 1, 2) + on (tag_0) floats)" - } - "ceil((clamp(histogram_count(hist @ end() offset 1m), 1, 2) + on(tag_0) floats @ start()))" => { - "ceil(clamp(histogram_count(hist @ end() offset 1m), 1, 2) + on (tag_0) floats @ start())" - } - _ => unreachable!("the test lists every query"), - }; - // The value is named after the statement, and the rows layout declares the per-row name - // column last. - let mut expected = vec![ - expected_value.to_string(), - "tag_0".to_string(), - "timestamp".to_string(), - "__name__".to_string(), - ]; - expected.sort(); - assert_eq!(expected, sorted_column_names(&plan), "{display}"); - if query.contains("@ end()") { - let left_tree = find_fused_series(&fused.children()[0]) - .unwrap() - .tree() - .to_string(); - let right_tree = find_fused_series(&fused.children()[1]) - .unwrap() - .tree() - .to_string(); - assert!( - left_tree.contains("@ 100000000ms") && left_tree.contains("offset 60000"), - "{left_tree}" - ); - assert!(right_tree.contains("@ 0ms"), "{right_tree}"); - } } } @@ -7044,7 +6955,7 @@ async fn native_fused_cross_table_union_with_a_colliding_column_stays_native() { } /// A value is named after the expression, so a bare selector whose metric shares the time index's or -/// a tag's name declines and the existing plan, which names the value after its field, answers it. +/// a tag's name is refused, naming the collision the row layout cannot state. #[tokio::test] async fn native_fused_declines_expression_names_that_collide_with_time_or_tag() { for (table, tags, time, field, query) in [ @@ -7052,9 +6963,11 @@ async fn native_fused_declines_expression_names_that_collide_with_time_or_tag() ("host", vec!["host"], "timestamp", "val", "host"), ] { let provider = native_tables_provider(&[(table, &tags, time, field)]); - take_reported_decline(); - let plan = build_native_fused_plan_with_provider(query, true, provider).await; - assert!(find_fused_series(&plan).is_none(), "`{query}`: {plan}"); + assert_eq!( + "output_column_names_collide", + native_decline_reason(query, provider).await, + "`{query}`" + ); assert_eq!( Some("output_column_names_collide"), take_reported_decline(), @@ -8534,24 +8447,12 @@ async fn native_fused_binary_inside_scalar_and_quantile() { /// `Complete` one is a node this runtime computes - the names in this list are the shapes even that /// node cannot answer. #[tokio::test] -async fn native_fused_unsplittable_aggregate_falls_back() { +async fn native_fused_unsplittable_aggregate_is_declined() { for query in ["sum by (field_0) (some_metric)"] { - let native = build_native_fused_plan(query, true).await; - let without_flag = build_native_fused_plan(query, false).await; - assert!( - find_fused_series(&native).is_none(), - "`{query}`: {}", - native.display_indent() - ); - assert!( - find_final_split(&native).is_none(), - "`{query}`: {}", - native.display_indent() - ); assert_eq!( - native.display_indent().to_string(), - without_flag.display_indent().to_string(), - "`{query}` must keep the existing plan" + "cross_series_consumer_over_one_scan", + native_decline_reason(query, build_native_fused_table_provider().await).await, + "`{query}` groups by a value field, which no state row names" ); } } @@ -9418,27 +9319,22 @@ async fn native_metric_discovery_name_rewrite_canonicalizes_by_name() { /// 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. #[tokio::test] -async fn native_fused_rewritten_scalar_operand_uses_rewritten_field_columns() { +async fn native_fused_rewritten_scalar_operand_is_refused_with_the_statement() { 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(); - assert!( - display.contains(r#"some_metric{tag_0="x"} * 2"#), - "the re-planned scalar operand publishes its rewritten expression name: {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" ); } #[tokio::test] -async fn native_fused_preparation_decline_preserves_legacy_plan() { +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 native = build_native_fused_plan(query, true).await; - let legacy = build_native_fused_plan(query, false).await; - - assert!(!native.display_indent().to_string().contains("FusedSeries")); assert_eq!( - native.display_indent_schema().to_string(), - legacy.display_indent_schema().to_string(), - "a native preparation decline must leave legacy planning context unchanged" + "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" ); } @@ -18277,10 +18173,11 @@ async fn native_composed_binary_restores_the_context_after_a_refused_operand() { let refused = planner .try_plan_native_fused(&stmt.expr, &state) .await - .unwrap(); - assert!( - refused.is_none(), - "a scalar operand is no frame, so the pair declines" + .expect_err("a scalar operand has no evaluated frame, so the pair declines"); + assert_eq!( + "frame_operand_is_not_evaluated", + decline_reason(&refused), + "a scalar operand has no evaluated frame, so the pair declines" ); assert_eq!( before, @@ -18473,55 +18370,36 @@ async fn a_float_tree_still_segments_next_to_the_histogram_gates() { } } -/// A statement named after the column its own layout publishes keeps the answer it owes. +/// A statement named after the column its own layout publishes takes a free grid name, or is +/// refused when the name it would need is one a tag already holds. /// /// A table that does not exist has no column of its own to name the grid after, so the planner /// fabricates the existing planner's synthetic `time` column for it. `time` is therefore both the -/// metric's name - which names the value column - and that grid, and `__name__` is both a metric -/// name and the row-name column every samples layout publishes. Prometheus answers both statements -/// with the empty vector: the first publishes its grid under a free synthetic name, and the second -/// is a layout the rows contract cannot name, so it keeps the existing plan, which answers empty. +/// metric's name - which names the value column - and that grid, so the grid moves to a free +/// synthetic name. `__name__` would have to publish the row-name column as its value column: no +/// layout here can declare that, so the route refuses the statement with that cause. #[tokio::test] -async fn native_missing_table_named_after_its_own_columns_answers_the_empty_vector() { - for (query, native) in [("time", true), ("__name__", false)] { - let plan = build_native_fused_plan_with_provider( - query, - true, - named_missing_table_provider().await, - ) - .await; - assert_eq!( - native, - find_fused_series(&plan).is_some(), - "`{query}`: {plan:?}" - ); - let columns = plan - .schema() - .fields() - .iter() - .map(|field| field.name().as_str()) - .collect::>(); - if native { - assert_eq!( - vec!["native_time_0", query, METRIC_NAME], - columns, - "`{query}`: the grid takes a free synthetic name" - ); - } - let stmt = build_eval_stmt(query); - let state = build_query_engine_state(); - let plan = PromPlanner::stmt_to_plan_with_annotations( - named_missing_table_provider().await, - &stmt, - &state, - None, - true, - ) - .await - .unwrap_or_else(|error| panic!("`{query}` is not planned at all: {error}")); - let (_, batches) = execute(plan, &state).await; - assert_eq!(0, batch_rows(&batches), "`{query}`: {batches:?}"); - } +async fn native_missing_table_named_after_its_own_columns_takes_a_free_grid_name() { + let plan = + build_native_fused_plan_with_provider("time", true, named_missing_table_provider().await) + .await; + assert!(find_fused_series(&plan).is_some(), "{plan:?}"); + let columns = plan + .schema() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>(); + assert_eq!( + vec!["native_time_0", "time", METRIC_NAME], + columns, + "the grid takes a free synthetic name" + ); + assert_eq!( + "value_column_collides_with_a_tag", + native_decline_reason("__name__", named_missing_table_provider().await).await, + "`__name__` names both the value column and a tag" + ); } /// A fold over a pairing of two histogram metrics runs natively. @@ -18584,26 +18462,36 @@ async fn count_values_with_an_empty_destination_is_rejected_on_both_routes() { .await } - for query in [ - "count_values(\"\", vector(1))", - "count_values(\"\", some_metric)", + for (query, reason) in [ + ( + "count_values(\"\", vector(1))", + "data_free_root_has_no_labels", + ), + ( + "count_values(\"\", some_metric)", + "root_has_no_output_labels", + ), ] { - for native in [true, false] { - let error = plan(query, native) - .await - .expect_err("an empty destination is not a label name"); - assert!( - matches!( - &error, - crate::promql::error::Error::InvalidLabelName { label_name, .. } - if label_name.is_empty() - ), - "`{query}` (native: {native}): {error}" - ); - assert!( - error.to_string().contains("invalid label name \"\""), - "`{query}` (native: {native}) names the empty destination: {error}" - ); - } + let error = plan(query, false) + .await + .expect_err("an empty destination is not a label name"); + assert!( + matches!( + &error, + crate::promql::error::Error::InvalidLabelName { label_name, .. } + if label_name.is_empty() + ), + "`{query}`: {error}" + ); + assert!( + error.to_string().contains("invalid label name \"\""), + "`{query}` names the empty destination: {error}" + ); + // The destination is what this route reads its output labels from, so an empty one is + // refused before the label name is read. + let native = plan(query, true) + .await + .expect_err("an empty destination leaves the route no output label"); + assert_eq!(reason, decline_reason(&native), "`{query}`: {native}"); } } diff --git a/tests-integration/src/tests/native_file_engine_test.rs b/tests-integration/src/tests/native_file_engine_test.rs index 495b1a8e4c5..63cd92ea832 100644 --- a/tests-integration/src/tests/native_file_engine_test.rs +++ b/tests-integration/src/tests/native_file_engine_test.rs @@ -599,8 +599,8 @@ async fn check_native_answers(instance: &Arc, observer: &PlanObserver) assert!(failures.is_empty(), "{}", failures.join("\n")); } -/// A tag column named `__name__` has no label to be read as, so the native route keeps the existing -/// plan rather than merging the two series it tells apart. +/// A tag column named `__name__` has no label to be read as, so the native route refuses the +/// statement rather than merging the two series it tells apart. async fn check_metric_name_tag_declines(instance: &Arc, observer: &PlanObserver) { let case = instant("fe_named", 0, vec![]); observer.take_node_names(); @@ -610,7 +610,13 @@ async fn check_metric_name_tag_declines(instance: &Arc, observer: &Pla !nodes.iter().any(|node| node == "RowSeriesSourceExec"), "a `__name__` tag column must not reach a row source: {nodes:?}" ); - assert!(answer.is_ok(), "{answer:?}"); + let Err(error) = answer else { + panic!("a `__name__` tag column is refused: {answer:?}"); + }; + assert!( + error.contains("declined this expression: row_source_tag_named_metric_name"), + "the refusal names the tag column it cannot read: {error}" + ); } fn observer_plugins() -> (Arc, Plugins) { diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index e8a9d730742..4d0cf1095cd 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -2147,6 +2147,29 @@ async fn collect_error(output: Output) -> String { } } +/// The error a statement reports, whether it was raised while planning or while its stream was read. +async fn native_tql_error(instance: &Arc, sql: &str, enabled: bool) -> String { + match instance + .do_query(sql, native_query_context(enabled, 4)) + .await + .remove(0) + { + Ok(output) => collect_error(output).await, + Err(error) => format!("{error:?}"), + } +} + +/// Asserts that the native route refuses `sql`, naming `reason` as the cause it recorded. +async fn assert_native_decline(instance: &Arc, sql: &str, reason: &str, context: &str) { + let error = native_tql_error(instance, sql, true).await; + assert!( + error.contains(&format!( + "Native PromQL route declined this expression: {reason}" + )), + "{context}: expected the route to decline with `{reason}`, got: {error}" + ); +} + /// Like [`native_result_rows`], with both label columns of the discovery fixture. async fn native_site_rows(output: Output) -> Vec<(i64, String, String, f64)> { let batches = match output.data { @@ -13386,14 +13409,15 @@ async fn native_promql_answers_mito_cross_table_grouping_by_metric_name() { ); } -/// `count_values` over a union reports one series per metric name, and per value it counted. +/// `count_values` over a union: a grouping by metric name answers, an outer fold over one refuses. /// /// `by (__name__)` folds the two inputs into two groups that differ only in their metric name; /// `by (val)` names a label no series carries, so both inputs fall into one group and the outer -/// `sum` folds what `count_values` wrote there. The full label sets of every row are what this -/// asserts: a plan that dropped the name would report one series where two metrics were counted. +/// `sum` folds what `count_values` wrote there - that fold over a two-input tree is the shape the +/// runtime does not execute, so the route refuses it and the existing planner's label set for it is +/// what this test pins. #[tokio::test(flavor = "multi_thread")] -async fn native_promql_answers_count_values_groupings_over_a_union() { +async fn native_promql_declines_count_values_groupings_over_a_union() { common_telemetry::init_default_ut_logging(); let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( "native_promql_count_values_groups", @@ -13435,36 +13459,40 @@ async fn native_promql_answers_count_values_groupings_over_a_union() { ("sample".to_string(), "1".to_string()), ]) }; - for (query, expected) in [ - ( - by_name, - vec![ - (0, counted("native_cv_demo"), 1.0), - (0, counted("native_cv_other"), 1.0), - ], - ), - (by_field, vec![(0, std::collections::BTreeMap::new(), 2.0)]), - ] { - let sql = format!("TQL EVAL (0, 0, '1s') {query}"); - observer.clear(); - let (_, native_rows) = - native_labelled_rows(native_tql_output(&instance, &sql, true).await).await; - let root = datafusion::physical_plan::displayable(observer.root_plan().as_ref()) - .indent(true) - .to_string(); - assert!( - observer.fused().is_some(), - "{query}: the union runs as one fused node: {root}" - ); - assert!( - !root.contains("JoinExec"), - "{query}: the union is not a legacy join: {root}" - ); - assert_eq!( - expected, native_rows, - "{query}: the full label sets of every row, not only the values" - ); - } + let by_name_expected = vec![ + (0, counted("native_cv_demo"), 1.0), + (0, counted("native_cv_other"), 1.0), + ]; + let sql = format!("TQL EVAL (0, 0, '1s') {by_name}"); + observer.clear(); + let (_, native_rows) = + native_labelled_rows(native_tql_output(&instance, &sql, true).await).await; + let root = datafusion::physical_plan::displayable(observer.root_plan().as_ref()) + .indent(true) + .to_string(); + assert!( + observer.fused().is_some(), + "{by_name}: the union runs as one fused node: {root}" + ); + assert!( + !root.contains("JoinExec"), + "{by_name}: the union is not a legacy join: {root}" + ); + assert_eq!( + by_name_expected, native_rows, + "{by_name}: the full label sets of every row, not only the values" + ); + + let sql = format!("TQL EVAL (0, 0, '1s') {by_field}"); + assert_native_decline(&instance, &sql, "runtime_refuses_the_tree", by_field).await; + // The existing planner answers the shape, and its label set is the one this test pins. + let (_, legacy_rows) = + native_labelled_rows(native_tql_output(&instance, &sql, false).await).await; + assert_eq!( + vec![(0, std::collections::BTreeMap::new(), 2.0)], + legacy_rows, + "{by_field}: the full label sets of every row, not only the values" + ); } /// `count_values` labels its result with the value it counted, and the native route has to name that @@ -13593,18 +13621,11 @@ async fn native_promql_rewrites_the_label_count_values_writes() { } /// `topk`/`bottomk` key their groups by series labels, and `by (val)` names no label a series -/// carries: `val` is the value field, not a label. Prometheus therefore puts every series of the -/// input into one empty group and answers only that group's winner, so the statement returns one -/// row rather than one per sample value. -/// -/// Both routes are about that grouping, but only the native one answers Prometheus here. The value -/// column is named after the expression, so a `by (val)` over it selects nothing and the one empty -/// group keeps the global winner. The existing plan still partitions its window by the `val` column -/// it publishes, one group per sample value; that divergence is known and is not pinned here. What -/// the native route must keep is the answer, with the union below it running as one native node -/// rather than a legacy join. +/// carries: `val` is the value field, not a label. A grouping by a value field needs a per-point +/// adapter the runtime does not have, so the route refuses the statement; a label grouping still +/// runs natively, which is what the second half of the test holds. #[tokio::test(flavor = "multi_thread")] -async fn native_promql_ranks_a_value_field_grouping_as_one_group() { +async fn native_promql_declines_a_value_field_ranking_grouping() { common_telemetry::init_default_ut_logging(); let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( "native_promql_ranking_value_field", @@ -13636,34 +13657,14 @@ async fn native_promql_ranks_a_value_field_grouping_as_one_group() { .await; let pair = r#"native_rank_demo{host="x"} or native_rank_other{host="y"}"#; - // No series carries a `val` label, so the grouping is empty: every series lands in that one - // group and the answer is its winner, `y` at 8 for `topk` and `x` at 2 for `bottomk`. - for (query, expected) in [ - ( - format!("topk by (val) (1, {pair})"), - vec![(0, "y".to_string(), 8.0)], - ), - ( - format!("bottomk by (val) (1, {pair})"), - vec![(0, "x".to_string(), 2.0)], - ), + // No series carries a `val` label, so the grouping names the value field: the route refuses the + // statement rather than answer one group per sample value. + for query in [ + format!("topk by (val) (1, {pair})"), + format!("bottomk by (val) (1, {pair})"), ] { let sql = format!("TQL EVAL (0, 0, '1s') {query}"); - observer.clear(); - let native_rows = native_result_rows(native_tql_output(&instance, &sql, true).await).await; - let root = datafusion::physical_plan::displayable(observer.root_plan().as_ref()) - .indent(true) - .to_string(); - // The union has to stay native rather than become the legacy join. - assert!( - observer.fused().is_some(), - "{query}: the union runs as one fused node: {root}" - ); - assert!( - !root.contains("JoinExec"), - "{query}: the union is not a legacy join: {root}" - ); - assert_eq!(native_rows, expected, "{query}: full rows"); + assert_native_decline(&instance, &sql, "runtime_refuses_the_tree", &query).await; } // A label grouping is what the native node does honor, so it still runs natively and keeps every @@ -13775,87 +13776,18 @@ async fn native_promql_answers_a_ranked_selection() { assert_eq!(rows, vec![(0, "a".to_string(), 8.0)], "{query}"); } -/// A `limitk` over more than one input answers natively, keeping `k` series the data holds. -/// -/// A node over more than one input reads its inputs in the order the gather finishes them, and -/// `limitk` picks its members by the hash of their labels, so that order does not change them. -/// Which two of the three hosts the hash ranks first is not asserted, and the answer is not -/// compared against the plan's: that choice is the engine's. -#[tokio::test(flavor = "multi_thread")] -async fn native_promql_answers_a_limitk_over_more_than_one_input() { - common_telemetry::init_default_ut_logging(); - let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( - "native_promql_limitk_multi_input", - )) - .await; - let instance = standalone.fe_instance().clone(); - execute_all( - &instance, - r#"CREATE TABLE native_limitk_phy ( - ts TIMESTAMP TIME INDEX, - val DOUBLE - ) ENGINE=metric WITH ("physical_metric_table" = "true"); - CREATE TABLE native_limitk_left ( - host STRING, - ts TIMESTAMP TIME INDEX, - val DOUBLE, - PRIMARY KEY (host) - ) ENGINE=metric WITH ("on_physical_table" = 'native_limitk_phy'); - CREATE TABLE native_limitk_right ( - host STRING, - ts TIMESTAMP TIME INDEX, - val DOUBLE, - PRIMARY KEY (host) - ) ENGINE=metric WITH ("on_physical_table" = 'native_limitk_phy'); - INSERT INTO native_limitk_left (host, ts, val) VALUES ('a', 0, 2), ('b', 0, 4), ('c', 0, 6); - INSERT INTO native_limitk_right (host, ts, val) VALUES ('a', 0, 8), ('b', 0, 8), ('c', 0, 8);"#, - QueryContext::arc(), - ) - .await; - - // The ranking reads the sum of two tables, so the tree holds two inputs and the `limitk` above - // them ranks the group they form. It answers natively: the existing planner has no kernel for - // `limitk`, so a refusal would be an error rather than a plan it already had. - let query = "limitk(2, native_limitk_left + on(host) native_limitk_right)"; - let sql = format!("TQL EVAL (0, 0, '1s') {query}"); - observer.clear(); - // Reading the answer is the "no error" assertion: `native_tql_output` unwraps the output. - let rows = native_result_rows(native_tql_output(&instance, &sql, true).await).await; - assert_eq!( - observer.take().name(), - "FusedSeriesExec", - "{query}: the route answers it natively" - ); - assert_eq!( - rows.len(), - 2, - "{query}: `limitk` keeps `k` series, not the whole input: {rows:?}" - ); - // Every series it answers is one the unranked sum holds, computed without the ranking over it. - let unranked = "TQL EVAL (0, 0, '1s') native_limitk_left + on(host) native_limitk_right"; - let all = native_result_rows(native_tql_output(&instance, unranked, true).await).await; - assert_eq!(all.len(), 3, "`{unranked}`: every host holds a sample"); - for row in &rows { - assert!( - all.contains(row), - "{query}: {row:?} is not a series the data holds: {all:?}" - ); - } -} - -/// A tree the native runtime cannot execute keeps the existing plan, rather than failing the -/// statement. +/// A tree the native runtime cannot execute is refused, naming that cause. /// /// The multi-input route skips the aggregate split, and the split is what refuses a tree the runtime -/// cannot run. The native node is chosen while planning the logical plan, so a refusal the physical -/// layer raises later is an error the statement reports, not a fall back - which would turn a query -/// the existing plan answers into a failure. A grouping by a value field needs a per-point adapter -/// the runtime does not have, so it is checked here on the shape that would otherwise reach the -/// node: two aggregates, one per logical table of one physical table, which is the multi-input case. +/// cannot run. The native node is chosen while planning the logical plan, so the refusal is decided +/// there and reported as the statement's cause rather than planned around. A grouping by a value +/// field needs a per-point adapter the runtime does not have, so it is checked here on the shape +/// that would otherwise reach the node: two aggregates, one per logical table of one physical +/// table, which is the multi-input case. The existing planner still answers the statement. #[tokio::test(flavor = "multi_thread")] async fn native_promql_declines_a_tree_the_runtime_cannot_execute() { common_telemetry::init_default_ut_logging(); - let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( + let (standalone, _observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( "native_promql_unexecutable_tree", )) .await; @@ -13892,20 +13824,10 @@ async fn native_promql_declines_a_tree_the_runtime_cannot_execute() { native_labelled_rows(native_tql_output(&instance, &sql, false).await).await; assert!( !legacy_rows.is_empty(), - "{query}: the existing plan must answer this, otherwise there is nothing to keep" + "{query}: the existing plan must answer this, otherwise the refusal is the only answer" ); - observer.clear(); - let (_, native_rows) = - native_labelled_rows(native_tql_output(&instance, &sql, true).await).await; - assert_eq!( - native_rows, legacy_rows, - "{query}: a tree the runtime cannot execute must keep the existing plan" - ); - assert!( - observer.fused().is_none(), - "{query}: the route must decline it instead of planning a node the runtime refuses" - ); + assert_native_decline(&instance, &sql, "runtime_refuses_the_tree", query).await; } /// A `quantile` over one logical table, divided by a `sum` over another, answers natively and the @@ -13977,7 +13899,7 @@ async fn native_promql_answers_a_quantile_over_a_multi_input_tree() { /// OTLP delta temporality on the public TQL route: a `delta`-marked series answers the raw sample /// sum (10 + 10 = 20) while a cumulative series with the same samples answers 0, on both routes. #[tokio::test(flavor = "multi_thread")] -async fn native_promql_delta_temporality_rate_and_increase_match_legacy() { +async fn native_promql_delta_temporality_rate_and_increase() { common_telemetry::init_default_ut_logging(); const TABLE: &str = "native_delta_temporality"; const CONTROL: &str = "native_delta_control"; @@ -14039,7 +13961,7 @@ async fn native_promql_delta_temporality_rate_and_increase_match_legacy() { (120_000, "cumulative", "cumulative", cumulative), (120_000, "delta", GREPTIME_TEMPORALITY_DELTA, delta), ]; - // Values before routes: a wrong number is the regression, a declined plan is not. + // Values before routes: a wrong number is the regression. let legacy_rows = native_marker_rows(native_tql_output(&instance, &sql, false).await).await; assert_delta_rows(&legacy_rows, &expected, &format!("native-off `{query}`")); observer.clear(); @@ -14132,7 +14054,7 @@ async fn native_promql_delta_temporality_rate_and_increase_match_legacy() { } // The control: a marker-free table (samples 10 and 30 here, unlike the table above) still fuses - // and agrees with the existing plan, so the decline is about the marker, not the table shape. + // and agrees with the existing plan. let control_sql = format!("TQL EVAL (120, 120, '1m') sum_over_time({CONTROL}[2m])"); observer.clear(); let control_native = @@ -14214,14 +14136,15 @@ async fn native_promql_binary_inside_scalar_and_quantile() { ); } -/// Enabling query fallback — by the engine option or by the per-request `query_fallback` hint — must -/// keep an otherwise fusible query on the existing plan without changing its answer. +/// Enabling query fallback — by the engine option or by the per-request `query_fallback` hint — +/// leaves an otherwise fusible query on the native route, and its answer unchanged. #[tokio::test(flavor = "multi_thread")] async fn native_promql_fallback_options_keep_expected_answer() { common_telemetry::init_default_ut_logging(); const TABLE: &str = "native_fallback_control"; - // One eligible selector, so only the fallback settings decide the route. `sum_over_time` is - // exact over the two samples in the window: 10 + 30 for `a`, 10 + 70 for `b`. + // One eligible selector, so the route this query takes is the one the request asks for. + // `sum_over_time` is exact over the two samples in the window: 10 + 30 for `a`, 10 + 70 for + // `b`. let query = format!("sum_over_time({TABLE}[2m])"); let expected = vec![ (120_000, "a".to_string(), 40.0), @@ -14262,20 +14185,11 @@ async fn native_promql_fallback_options_keep_expected_answer() { rows, expected, "{tag} {route}: the answer must not depend on the fallback settings" ); - if allow_query_fallback || route == "fallback-hint" { - // A fallback rewrites every table scan into `MergeScan`, which the fused node - // cannot read, so a query allowed to fall back keeps the existing plan. - assert!( - observer.fused().is_none(), - "{tag} {route}: enabling the fallback must keep the existing plan" - ); - } else { - assert_eq!( - observer.take().name(), - "FusedSeriesExec", - "{tag} {route}: with no fallback enabled this query must be fused" - ); - } + assert_eq!( + observer.take().name(), + "FusedSeriesExec", + "{tag} {route}: the fallback option does not decide the route" + ); } } } @@ -14615,14 +14529,11 @@ async fn native_promql_answers_an_aliased_statement_in_the_existing_layout() { assert_eq!(native, legacy); assert!(native.contains("alias on multi-value result"), "{native}"); - // Native names a value after the expression, here the time index's name, so it leaves these to - // the existing plan, which names the value after its field. + // Native names a value after the expression, here the time index's name, so it refuses a + // statement whose value it cannot name; the existing plan names the value after its field. for sql in ["TQL EVAL (0, 0, '1s') ts AS v", "TQL EVAL (0, 0, '1s') ts"] { - assert_eq!( - native_output_text(native_tql_output(&instance, sql, true).await).await, - native_output_text(native_tql_output(&instance, sql, false).await).await, - "{sql}" - ); + assert_native_decline(&instance, sql, "output_column_names_collide", sql).await; + let _ = native_output_text(native_tql_output(&instance, sql, false).await).await; } for query in [ @@ -16958,11 +16869,15 @@ async fn native_promql_real_query_q04_namespace_cpu_requests() { ); } -/// A multi-field `scalar()` input declines the native route and keeps the existing plan. +/// A multi-field `scalar()` input is refused, naming the tree the runtime does not execute. +/// +/// `scalar()` over a table with two value fields has no single value to report, and this route +/// decides that while planning: the statement reports the cause instead of being planned another +/// way, so the existing planner's own multi-field complaint never becomes the answer. #[tokio::test(flavor = "multi_thread")] -async fn native_promql_scalar_multi_field_falls_back() { +async fn native_promql_scalar_multi_field_is_declined() { common_telemetry::init_default_ut_logging(); - let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( + let (standalone, _observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( "native_promql_scalar_multi_field_fallback", )) .await; @@ -16975,19 +16890,7 @@ async fn native_promql_scalar_multi_field_falls_back() { ) .await; let sql = "TQL EVAL (0, 0, '1s') scalar(native_scalar_multi)"; - let error = instance - .do_query(sql, native_query_context(true, 4)) - .await - .remove(0) - .unwrap_err(); - assert!( - format!("{error:?}").contains("Multi fields calculation is not supported in scalar"), - "unexpected multi-field scalar error: {error:?}" - ); - assert!( - observer.fused().is_none(), - "multi-field scalar() must fall back" - ); + assert_native_decline(&instance, sql, "runtime_refuses_the_tree", sql).await; } /// A dynamic classic histogram quantile matches each equivalent constant-phi evaluation. @@ -19543,26 +19446,21 @@ async fn native_promql_matrix_root_matches_legacy() { assert!(!native.is_empty(), "{expr} produced no rows"); } + // A range query has no instant grid for a matrix root, so the offer declines before the + // existing planner's own range-vector check is reached. let range_query = "TQL EVAL (600, 1200, '1m') native_matrix_root[5m:1m]"; - let err = instance - .do_query(range_query, native_query_context(true, 4)) - .await - .remove(0) - .unwrap_err(); - assert!( - format!("{err:?}").contains("invalid expression type \"range vector\" for range query"), - "{err:?}" - ); + assert_native_decline( + &instance, + range_query, + "matrix_root_without_a_grid", + range_query, + ) + .await; - // This remains on the existing planner: a raw-sample matrix has no evaluation grid to bind. + // A raw-sample matrix has no evaluation grid to bind either, so the route refuses it instead of + // planning the existing plan for it. let sql = "TQL EVAL (600, 600, '1m') native_matrix_root[5m]"; - let native = run(&instance, &observer, sql, true).await; - assert!( - observer.fused().is_none(), - "raw matrix roots must use existing planning" - ); - let legacy = run(&instance, &observer, sql, false).await; - assert_eq!(native, legacy); + assert_native_decline(&instance, sql, "matrix_root_without_a_grid", sql).await; } /// Creates `split_a` and `split_b` in `db` on one physical metric table. With `narthex`, the diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index e7e0f3b0dd9..17d2a927170 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -6621,39 +6621,29 @@ pub async fn test_remote_write_v2_histogram_native_composition(store_type: Stora ); } - // The 121s end minus 1m reads the 61s histogram; @ start() reads the 61s float. - // Both are 2 after clamp, at both points. A 121s float of 9 exposes a lost @ start(). - // The `anchor` job also exposes a lost @ end() at the first point; both jobs expose a - // lost offset at the second point. Neither expected series carries its metric name. + // The two operands of this binary read different kinds - a histogram count and a float + // column - so no one tree composes them. The route was asked for and refuses the statement + // by name; it is not planned another way. let query = "ceil(clamp(histogram_count(native_comp_h @ end() offset 1m), 1, 2) + on(job) native_comp_f{job=~\"api|anchor\"} @ start())"; - let (status, body) = native_histogram_composition_query( - &client, - &observer, - &route, - query, - "query_range?start=61&end=121&step=60s", - ) - .await; - assert_eq!(status, StatusCode::OK, "{phase}: {query}: {body}"); - assert_eq!(body["status"], "success", "{phase}: {query}: {body}"); - assert_eq!( - body["data"]["resultType"], "matrix", + let response = client + .get(&format!( + "/v1/prometheus/api/v1/query_range?start=61&end=121&step=60s&query={}", + encode(query) + )) + .header("x-greptime-hints", "query.experimental_native_promql=true") + .send() + .await; + let status = response.status(); + let body: Value = response.json().await; + assert!(!status.is_success(), "{phase}: {query}: {body}"); + assert_eq!(body["status"], "error", "{phase}: {query}: {body}"); + let error = body["error"].as_str().expect("a named refusal"); + assert!( + error.contains( + "Native PromQL route declined this expression: selectors_disagree_on_field_kind" + ), "{phase}: {query}: {body}" ); - let results = body["data"]["result"].as_array().expect("range result"); - assert_eq!(results.len(), 2, "{phase}: {query}: {body}"); - for job in ["api", "anchor"] { - let expected = json!({ - "metric": {"job": job}, "values": [[61.0, "4.0"], [121.0, "4.0"]] - }); - assert_eq!( - results.iter().filter(|result| **result == expected).count(), - 1, - "{phase}: {query}: {body}" - ); - } - assert!(body.get("infos").is_none(), "{phase}: {query}: {body}"); - assert!(body.get("warnings").is_none(), "{phase}: {query}: {body}"); // The same two windows asked with the route explicitly off, so the legacy route answers // them and the observer proves it did. The engine option is a default here (this instance