From 54591d8b4ca324ad620c12b388f2e10aee179f2d Mon Sep 17 00:00:00 2001 From: discord9 Date: Fri, 23 Oct 2026 08:36:30 +0800 Subject: [PATCH] fix(query): decline the native route where it cannot reach a region Signed-off-by: discord9 --- src/query/src/dist_plan/commutativity.rs | 3 + src/query/src/planner.rs | 26 +++++++-- src/query/src/promql/planner.rs | 16 ++++++ src/query/src/promql/planner/native.rs | 35 ++++++++++++ src/query/src/promql/planner/test.rs | 71 +++++++++++++++++++++++- src/query/src/query_engine/state.rs | 9 +++ 6 files changed, 154 insertions(+), 6 deletions(-) diff --git a/src/query/src/dist_plan/commutativity.rs b/src/query/src/dist_plan/commutativity.rs index c8d56cc9a04..ce8466cd68f 100644 --- a/src/query/src/dist_plan/commutativity.rs +++ b/src/query/src/dist_plan/commutativity.rs @@ -400,6 +400,9 @@ fn reads_across_series(node: &NativeNode) -> bool { | NativeExpr::Window { input, .. } | NativeExpr::Map { input, .. } => reads_across_series(input), NativeExpr::Aggregate { .. } | NativeExpr::Binary { .. } => true, + // A vector operation reads the whole vector at each grid point (`topk`, `absent`, + // `histogram_quantile`, ...), so it is not a per-series node either. + NativeExpr::Vector { .. } => true, } } diff --git a/src/query/src/planner.rs b/src/query/src/planner.rs index c11517841e0..de45e55e8d8 100644 --- a/src/query/src/planner.rs +++ b/src/query/src/planner.rs @@ -316,7 +316,12 @@ impl DfLogicalPlanner { } #[tracing::instrument(skip_all)] - async fn plan_pql(&self, stmt: &EvalStmt, query_ctx: QueryContextRef) -> Result { + async fn plan_pql( + &self, + stmt: &EvalStmt, + query_ctx: QueryContextRef, + native_route_allowed: bool, + ) -> Result { let mut scheduled_state = self.derive_session_state_with_scheduled_time(&query_ctx)?; let promql_annotations = query_ctx.remote_query_id().map(promql_annotation_collector); if let Some(collector) = &promql_annotations { @@ -345,7 +350,9 @@ impl DfLogicalPlanner { stmt, &self.engine_state, promql_annotations, - self.engine_state.experimental_native_promql() + native_route_allowed + && self.engine_state.experimental_native_promql() + && self.engine_state.in_process_region_transport() && crate::promql::planner::native::native_promql_requested(&query_ctx), ) .await @@ -463,8 +470,16 @@ impl DfLogicalPlanner { alias: eval.alias.clone(), }; let stmt = QueryLanguageParser::parse_promql(&prom_query, &query_ctx)?; - - self.plan(&stmt, query_ctx).await + // A hybrid CTE registers this plan as a table the outer SQL query reads, so the + // `FusedSeries` node would sit under a SQL root. The in-process encodability + // exception is scoped to a plan whose root is the node, so here the node would be + // cut off and left in the frontend, where the physical planner cannot build it - + // a query that used to answer would fail instead. The route is therefore not + // offered for an embedded statement. + let QueryStatement::Promql(eval, _alias) = &stmt else { + unreachable!("a TQL eval parses to a PromQL statement"); + }; + self.plan_pql(eval, query_ctx, false).await } Tql::Explain(_) => UnimplementedSnafu { operation: "TQL EXPLAIN in CTEs", @@ -701,7 +716,8 @@ impl LogicalPlanner for DfLogicalPlanner { async fn plan(&self, stmt: &QueryStatement, query_ctx: QueryContextRef) -> Result { match stmt { QueryStatement::Sql(stmt) => self.plan_sql(stmt, query_ctx).await, - QueryStatement::Promql(stmt, _alias) => self.plan_pql(stmt, query_ctx).await, + // The statement's own plan is what a region receives, so the native route is offered. + QueryStatement::Promql(stmt, _alias) => self.plan_pql(stmt, query_ctx, true).await, } } diff --git a/src/query/src/promql/planner.rs b/src/query/src/promql/planner.rs index 7fba4db8816..2de6a87f241 100644 --- a/src/query/src/promql/planner.rs +++ b/src/query/src/promql/planner.rs @@ -5505,6 +5505,22 @@ impl PromPlanner { .map(|idx| schema.field(idx).data_type()) } + /// Whether every field column carries a type the region's raw series preflight serves. + /// + /// That preflight accepts numeric columns and native histograms only, so anything else - a + /// string, a boolean, a timestamp - has no raw framing. A route that offered it would fail + /// after the logical plan is fixed; declining keeps the existing plan. + fn field_columns_are_raw_series_servable( + schema: &DFSchemaRef, + field_columns: &[String], + ) -> bool { + field_columns.iter().all(|field| { + Self::field_column_type(schema, field).is_some_and(|data_type| { + data_type.is_numeric() || data_type == &Self::native_histogram_arrow_type() + }) + }) + } + fn field_column_is_native_histogram(schema: &DFSchemaRef, field_column: &str) -> bool { Self::field_column_type(schema, field_column) .is_some_and(|data_type| data_type == &Self::native_histogram_arrow_type()) diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 7dd6c85cd9d..31b083b08ea 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -224,6 +224,14 @@ impl PromPlanner { if Self::field_columns_contain_native_histogram(input.schema(), &fields) { return Ok(None); } + // The region's raw series preflight serves a field only when it is numeric or a native + // histogram, and the physical layer turns that refusal into a planning error because the + // logical plan is already fixed by then. A table whose selected fields are, say, a string + // and a boolean therefore has to be declined here, while the existing plan is still the + // fallback - `stringsfield` over such a table answered normally before this route existed. + if !Self::field_columns_are_raw_series_servable(input.schema(), &fields) { + return Ok(None); + } let Some(stmt) = self.native_statement(prom_expr) else { return Ok(None); }; @@ -250,6 +258,14 @@ impl PromPlanner { Err(DataFusionError::NotImplemented(_)) => return Ok(None), Err(error) => return Err(error).context(DataFusionPlanningSnafu), }; + // A vector operation (`sort`, `absent`, `topk`, `histogram_quantile`, ...) reads the whole + // vector at each grid point rather than one series at a time, so it cannot be evaluated by + // one executor per scan partition. Declining here is the only place that still works: once + // the `FusedSeries` node exists the logical plan is fixed, and the categorizer merely + // declining to push it down would leave a node the physical layer must build anyway. + if reads_across_series(tree.root()) { + return Ok(None); + } let binding = FusedSeriesBinding { series_schema, @@ -357,6 +373,25 @@ fn selector_range_millis(expr: &PromExpr) -> Option { } } +/// Whether any node of `tree` reads the whole input vector at a point rather than one series. +/// +/// Such a node folds or pairs across series (`Aggregate`, `Binary`) or reorders/reads a whole +/// vector (`Vector`: `sort`, `absent`, `topk`, `limitk`, `histogram_quantile`, ...). This node runs +/// one executor per scan partition, and a partition holds only part of a metric's series, so those +/// nodes would answer from a fragment. +fn reads_across_series(node: &promql::native::plan::NativeNode) -> bool { + use promql::native::plan::NativeExpr; + match &node.expr { + NativeExpr::Input(_) | NativeExpr::Scalar(_) => false, + NativeExpr::Instant { input, .. } + | NativeExpr::Window { input, .. } + | NativeExpr::Map { input, .. } => reads_across_series(input), + NativeExpr::Aggregate { .. } | NativeExpr::Binary { .. } | NativeExpr::Vector { .. } => { + true + } + } +} + fn single_selector(expr: &PromExpr) -> Option<&VectorSelector> { let mut selectors = Vec::new(); collect_selectors(expr, &mut selectors); diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index b9dd3f1de8e..c01d2d40f4f 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -916,6 +916,23 @@ async fn build_test_table_provider_with_partition_columns( partition_key_indices, ConcreteDataType::timestamp_millisecond_datatype(), false, + ConcreteDataType::float64_datatype(), + ) + .await +} + +/// A table whose single value field has the given type. +async fn build_test_table_provider_with_field_type( + field_type: ConcreteDataType, +) -> DfTableSourceProvider { + build_test_table_provider_with_options( + &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], + 1, + 1, + vec![], + ConcreteDataType::timestamp_millisecond_datatype(), + false, + field_type, ) .await } @@ -927,6 +944,7 @@ async fn build_test_table_provider_with_options( partition_key_indices: Vec, timestamp_type: ConcreteDataType, append_mode: bool, + field_type: ConcreteDataType, ) -> DfTableSourceProvider { let catalog_list = MemoryCatalogManager::with_default_setup(); for (schema_name, table_name) in table_name_tuples { @@ -945,7 +963,7 @@ async fn build_test_table_provider_with_options( for i in 0..num_field { columns.push(ColumnSchema::new( format!("field_{i}"), - ConcreteDataType::float64_datatype(), + field_type.clone(), true, )); } @@ -1749,6 +1767,7 @@ async fn native_fused_non_millisecond_time_index_falls_back() { vec![], ConcreteDataType::timestamp_microsecond_datatype(), false, + ConcreteDataType::float64_datatype(), ) .await; let native = @@ -1760,6 +1779,7 @@ async fn native_fused_non_millisecond_time_index_falls_back() { vec![], ConcreteDataType::timestamp_microsecond_datatype(), false, + ConcreteDataType::float64_datatype(), ) .await; let without_flag = @@ -1781,6 +1801,7 @@ async fn native_fused_append_mode_table_falls_back() { vec![], ConcreteDataType::timestamp_millisecond_datatype(), true, + ConcreteDataType::float64_datatype(), ) .await; let native = @@ -1792,6 +1813,7 @@ async fn native_fused_append_mode_table_falls_back() { vec![], ConcreteDataType::timestamp_millisecond_datatype(), true, + ConcreteDataType::float64_datatype(), ) .await; let without_flag = @@ -1819,6 +1841,53 @@ async fn native_fused_tag_partitioned_table_still_plans_fused_series() { } /// The flag on and a shape the compiler refuses: the existing planner plans it unchanged. +/// A value field the region's raw scan cannot serve keeps the existing plan. +/// +/// The preflight serves numeric columns and native histograms only, and the physical layer turns +/// its refusal into a planning error once the logical plan is fixed. A bare selector over a string +/// field answered normally before this route existed, so it must keep doing that. +#[tokio::test] +async fn native_fused_non_numeric_field_falls_back() { + for field_type in [ + ConcreteDataType::string_datatype(), + ConcreteDataType::boolean_datatype(), + ] { + let native = build_native_fused_plan_with_provider( + "some_metric", + true, + build_test_table_provider_with_field_type(field_type.clone()).await, + ) + .await; + let without_flag = build_native_fused_plan_with_provider( + "some_metric", + false, + build_test_table_provider_with_field_type(field_type.clone()).await, + ) + .await; + assert!( + find_fused_series(&native).is_none(), + "{field_type} must not reach the native route" + ); + assert_eq!( + native.display_indent().to_string(), + without_flag.display_indent().to_string(), + "{field_type} must keep the existing plan" + ); + } +} + +/// A whole-vector operation is not a per-series tree, so it stays on the existing plan. +#[tokio::test] +async fn native_fused_whole_vector_operation_falls_back() { + for query in ["sort(some_metric)", "absent(some_metric)"] { + let native = build_native_fused_plan(query, true).await; + assert!( + find_fused_series(&native).is_none(), + "`{query}` reads the whole vector and must not be placed region-side" + ); + } +} + #[tokio::test] async fn native_fused_unsupported_shape_falls_back() { let plan = build_native_fused_plan("sum(rate(some_metric[5m]))", true).await; diff --git a/src/query/src/query_engine/state.rs b/src/query/src/query_engine/state.rs index 80e7574bd13..0b37a9a4324 100644 --- a/src/query/src/query_engine/state.rs +++ b/src/query/src/query_engine/state.rs @@ -100,6 +100,9 @@ pub struct QueryEngineState { extension_rules: Vec>, plugins: Plugins, experimental_native_promql: bool, + /// Whether this engine's regions are reached in process, which is what lets a region take a + /// `LogicalPlan` instead of Substrait bytes. + in_process_region_transport: bool, } impl fmt::Debug for QueryEngineState { @@ -334,6 +337,7 @@ impl QueryEngineState { extension_rules, plugins, experimental_native_promql: options.experimental_native_promql, + in_process_region_transport, scalar_functions: Arc::new(RwLock::new(HashMap::new())), }) } @@ -486,6 +490,11 @@ impl QueryEngineState { self.experimental_native_promql } + /// Whether a region read is served in this process, so a region can take a `LogicalPlan`. + pub(crate) fn in_process_region_transport(&self) -> bool { + self.in_process_region_transport + } + pub fn catalog_manager(&self) -> &CatalogManagerRef { &self.catalog_manager }