From 4c63d150be949b0eadec52d27f72ad3d863ffb7e Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:43:58 +0800 Subject: [PATCH] feat(query): add native PromQL gate and local raw-series admission Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- src/query/src/datafusion.rs | 423 ++++++++- src/query/src/datafusion/native_promql.rs | 328 +++++++ .../datafusion/raw_series_admission_tests.rs | 831 ++++++++++++++++++ src/query/src/dummy_catalog.rs | 39 + src/query/src/query_engine/state.rs | 7 + 5 files changed, 1615 insertions(+), 13 deletions(-) create mode 100644 src/query/src/datafusion/native_promql.rs create mode 100644 src/query/src/datafusion/raw_series_admission_tests.rs diff --git a/src/query/src/datafusion.rs b/src/query/src/datafusion.rs index 72788461836..b8f6b2a7c48 100644 --- a/src/query/src/datafusion.rs +++ b/src/query/src/datafusion.rs @@ -16,41 +16,58 @@ mod error; mod json_expr_planner; +pub(crate) mod native_promql; mod pg_oid_alias_expr_planner; mod planner; +#[cfg(test)] +#[path = "datafusion/raw_series_admission_tests.rs"] +mod raw_series_admission_tests; + use std::any::Any; use std::collections::HashMap; use std::sync::Arc; +use api::v1::SemanticType; use async_trait::async_trait; use common_base::Plugins; use common_catalog::consts::is_readonly_table; use common_error::ext::BoxedError; use common_function::function::FunctionContext; use common_function::function_factory::ScalarFunctionFactory; +use common_query::request::{ + INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY, PreparedNamedRawSeries, RawSeriesRequest, +}; use common_query::{Output, OutputData, OutputMeta}; -use common_recordbatch::adapter::{RecordBatchStreamAdapter, RegionQueryStatCounters}; +use common_recordbatch::adapter::{ + RecordBatchStreamAdapter, RegionQueryStatCounters, SERIES_SCAN_EXEC_NAME, +}; use common_recordbatch::{EmptyRecordBatchStream, SendableRecordBatchStream}; use common_telemetry::tracing; use datafusion::catalog::TableFunction; use datafusion::dataframe::DataFrame; -use datafusion::physical_plan::ExecutionPlan; +use datafusion::datasource::DefaultTableSource; use datafusion::physical_plan::analyze::AnalyzeExec; use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec; +use datafusion::physical_plan::coop::CooperativeExec; +use datafusion::physical_plan::{ChildrenPropertiesMode, ExecutionPlan, ReplaceChildrenOptions}; use datafusion_common::ResolvedTableReference; +use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; use datafusion_expr::{ - AggregateUDF, DmlStatement, LogicalPlan as DfLogicalPlan, LogicalPlan, WindowUDF, WriteOp, + AggregateUDF, DmlStatement, Expr, LogicalPlan as DfLogicalPlan, LogicalPlan, Volatility, + WindowUDF, WriteOp, }; use datatypes::prelude::VectorRef; use datatypes::schema::Schema; +use datatypes::series::SeriesOrdering; use futures_util::StreamExt; use session::context::QueryContextRef; use snafu::{OptionExt, ResultExt, ensure}; use sqlparser::ast::AnalyzeFormat; +use store_api::metadata::RegionMetadata; use table::TableRef; use table::requests::{DeleteRequest, InsertRequest}; -use table::table::scan::{REGION_SCAN_EXEC_NAME, RegionScanExec}; +use table::table::scan::{REGION_SCAN_EXEC_NAME, RegionScanExec, SeriesScanExec}; use tracing::Span; use crate::analyze::DistAnalyzeExec; @@ -58,10 +75,11 @@ pub use crate::datafusion::planner::DfContextProviderAdapter; use crate::dist_plan::{ DistPlannerOptions, MergeScanLogicalPlan, RemoteDynFilterReceiverInjectorRef, }; +use crate::dummy_catalog::DummyTableProvider; use crate::error::{ CatalogSnafu, CreateRecordBatchSnafu, MissingTableMutationHandlerSnafu, MissingTimestampColumnSnafu, QueryExecutionSnafu, Result, TableMutationSnafu, - TableNotFoundSnafu, TableReadOnlySnafu, UnsupportedExprSnafu, + TableNotFoundSnafu, TableReadOnlySnafu, UnimplementedSnafu, UnsupportedExprSnafu, }; use crate::executor::QueryExecutor; use crate::metrics::{ @@ -82,15 +100,57 @@ pub const QUERY_PARALLELISM_HINT: &str = "query_parallelism"; /// Whether to fallback to the original plan when failed to push down. pub const QUERY_FALLBACK_HINT: &str = "query_fallback"; +pub(crate) fn raw_expr_supported(expr: &Expr) -> bool { + let mut supported = true; + let _ = expr.apply(|node| { + match node { + Expr::Column(_) | Expr::Literal(_, _) => {} + Expr::ScalarFunction(function) + if function.func.signature().volatility == Volatility::Immutable => {} + Expr::BinaryExpr(_) + | Expr::Like(_) + | Expr::SimilarTo(_) + | Expr::Not(_) + | Expr::IsNotNull(_) + | Expr::IsNull(_) + | Expr::IsTrue(_) + | Expr::IsFalse(_) + | Expr::IsUnknown(_) + | Expr::IsNotTrue(_) + | Expr::IsNotFalse(_) + | Expr::IsNotUnknown(_) + | Expr::Negative(_) + | Expr::Between(_) + | Expr::Case(_) + | Expr::Cast(_) + | Expr::TryCast(_) + | Expr::InList(_) => {} + _ => supported = false, + } + Ok(if supported { + TreeNodeRecursion::Continue + } else { + TreeNodeRecursion::Stop + }) + }); + supported +} + fn query_load_region_id(plan: &Arc) -> Option { let mut region_id = None; let mut stack = vec![plan.clone()]; while let Some(plan) = stack.pop() { - if plan.name() == REGION_SCAN_EXEC_NAME - && let Some(scan) = plan.downcast_ref::() - && let Some(scan_region_id) = scan.query_load_region_id() - { + let scan_region_id = if plan.name() == REGION_SCAN_EXEC_NAME { + plan.downcast_ref::() + .and_then(RegionScanExec::query_load_region_id) + } else if plan.name() == SERIES_SCAN_EXEC_NAME { + plan.downcast_ref::() + .and_then(SeriesScanExec::query_load_region_id) + } else { + None + }; + if let Some(scan_region_id) = scan_region_id { match region_id { Some(region_id) if region_id != scan_region_id => return None, Some(_) => {} @@ -116,10 +176,16 @@ fn query_stat_counters(plan: &Arc) -> Option() - && let Some(scan_counters) = scan.query_stat_counters() - { + let scan_counters = if plan.name() == REGION_SCAN_EXEC_NAME { + plan.downcast_ref::() + .and_then(RegionScanExec::query_stat_counters) + } else if plan.name() == SERIES_SCAN_EXEC_NAME { + plan.downcast_ref::() + .and_then(SeriesScanExec::query_stat_counters) + } else { + None + }; + if let Some(scan_counters) = scan_counters { match &counters { Some(counters) if !Arc::ptr_eq(&counters.query_cpu_time, &scan_counters.query_cpu_time) @@ -145,7 +211,208 @@ pub struct DatafusionQueryEngine { plugins: Plugins, } +struct PreparedRawSeries { + context: QueryEngineContext, + plan: Arc, + /// The binding this plan's native leaf was validated against. Bound preparation keeps the + /// caller's expectation; named preparation reports the binding derived from the actual scan. + binding: RawSeriesRequest, + ordering: SeriesOrdering, +} + +/// Derives the authorized logical label and field names of one discovered table scan. +/// +/// The names come from the scan's own output schema paired with the source metadata it resolved +/// against, so they describe exactly the authorized output. Internal and reserved columns are not +/// logical labels or fields. `None` means the output cannot be named, so no mapping is invented. +fn authorized_logical_names( + scan: &datafusion_expr::logical_plan::TableScan, + metadata: &RegionMetadata, +) -> Option<(Vec, Vec)> { + let mut logical_tags = Vec::new(); + let mut field_names = Vec::new(); + for field in scan.projected_schema.fields() { + let column = metadata.column_by_name(field.name())?; + if store_api::storage::consts::ReservedColumnId::is_reserved(column.column_id) { + continue; + } + match column.semantic_type { + SemanticType::Tag + if !store_api::metric_engine_consts::is_metric_engine_internal_column( + field.name(), + ) && !store_api::storage::consts::is_internal_column(field.name()) => + { + logical_tags.push(field.name().clone()); + } + SemanticType::Field + if !store_api::storage::consts::is_internal_column(field.name()) => + { + field_names.push(field.name().clone()); + } + SemanticType::Tag | SemanticType::Timestamp | SemanticType::Field => {} + } + } + Some((logical_tags, field_names)) +} + impl DatafusionQueryEngine { + /// Prepares a native raw-series leaf for one safely wrapped table scan. + /// + /// `binding` is the caller's expectation for bound preparation. `None` derives the actual + /// binding from the authorized scanner instead. Both modes share this body, so they admit the + /// same plan shapes and reject the same residuals. + async fn prepare_raw_series_plan( + &self, + plan: LogicalPlan, + query_ctx: QueryContextRef, + binding: Option, + ) -> Result> { + // A positive hint describes the caller's own parallelism, which the private context below + // reduces to one partition; only hints that cannot be honoured at all decline the plan. + if let Some(hint) = query_ctx.extension(QUERY_PARALLELISM_HINT) + && !matches!(hint.parse::(), Ok(partitions) if partitions > 0) + { + return Ok(None); + } + if query_ctx + .extension(INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY) + .is_some() + { + return Ok(None); + } + // The discovered tree is preserved as a whole: only the captured scan has its source + // substituted, and any operator the physical planner keeps above that scan rejects the + // plan instead of being unwrapped. + let Some(logical_scan) = native_promql::table_scan_through_safe_nodes(&plan) else { + return Ok(None); + }; + // A missing projection means the scan reads its entire authorized schema: every visible + // tag, timestamp, and field is approved as-is, so no subset is ever selected here. + if logical_scan.fetch.is_some() + || !logical_scan.statistics_requests.is_empty() + || logical_scan.filters.iter().any(|e| !raw_expr_supported(e)) + { + return Ok(None); + } + let Some(source) = logical_scan.source.downcast_ref::() else { + return Ok(None); + }; + let Some(provider) = source.table_provider.downcast_ref::() else { + return Ok(None); + }; + let Some(provider) = provider.clone_for_raw_series() else { + return Ok(None); + }; + // The metric name and the logical names come from this authorized scan: its table name, + // its output schema, and the source metadata it resolved against. + let metadata = provider.region_metadata(); + let metric_name = logical_scan.table_name.table().to_string(); + let authorized_schema = logical_scan.projected_schema.inner().clone(); + let Some((logical_tags, field_names)) = authorized_logical_names(logical_scan, &metadata) + else { + return Ok(None); + }; + let new_source = Arc::new(DefaultTableSource::new(Arc::new(provider))); + let plan = plan + .transform_down(|node| match node { + LogicalPlan::TableScan(mut scan) => { + scan.source = new_source.clone(); + Ok(Transformed::yes(LogicalPlan::TableScan(scan))) + } + node => Ok(Transformed::no(node)), + })? + .data; + + let normal_ctx = self.engine_context(query_ctx.clone()); + let mut state = normal_ctx.state().clone(); + let config = state.config().clone().with_target_partitions(1); + *state.config_mut() = config; + let mut ctx = QueryEngineContext::new(state, query_ctx.clone()); + let physical = self.create_physical_plan(&mut ctx, &plan).await?; + let physical = self.optimize_physical_plan(&mut ctx, physical)?; + let cooperative = (physical.as_ref() as &dyn Any).downcast_ref::(); + let scan_candidate = cooperative.map_or(&physical, |plan| plan.input()); + if scan_candidate.name() != REGION_SCAN_EXEC_NAME { + common_telemetry::debug!( + "Raw series physical plan rejected: root={}, scan candidate={}", + physical.name(), + scan_candidate.name(), + ); + return Ok(None); + } + let Some(scan) = (scan_candidate.as_ref() as &dyn Any).downcast_ref::() + else { + return Ok(None); + }; + let ranges = scan.get_partition_ranges(); + let prepared = Arc::new( + scan.with_new_partitions(vec![ranges], 1) + .map_err(BoxedError::new) + .context(QueryExecutionSnafu)?, + ); + // The prepared executor must still produce exactly the authorized output, so that the + // binding resolved below describes the plan that will run. + let physical_output = prepared.schema(); + if authorized_schema.fields().len() != physical_output.fields().len() + || authorized_schema + .fields() + .iter() + .zip(physical_output.fields()) + .any(|(authorized, physical)| { + authorized.name() != physical.name() + || authorized.data_type() != physical.data_type() + }) + { + return Ok(None); + } + let (binding, native) = match binding { + Some(binding) => { + let Some(native) = prepared.clone().try_to_bound_series_scan(&binding)? else { + return Ok(None); + }; + (binding, native) + } + None => { + let Some((binding, native)) = prepared.clone().try_to_named_series_binding( + &metric_name, + &logical_tags, + &field_names, + )? + else { + return Ok(None); + }; + (binding, native) + } + }; + let ordering = native.raw_series_ordering(); + let native_plan: Arc = native; + let native_plan = if cooperative.is_some() { + physical.replace_children( + vec![native_plan], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )? + } else { + native_plan + }; + let wrapped = if let Some(wrapper) = self.plugins.get::() { + wrapper.wrap(native_plan.clone(), query_ctx) + } else { + native_plan.clone() + }; + if !Arc::ptr_eq(&native_plan, &wrapped) + || native_plan.schema() != wrapped.schema() + || wrapped.properties().output_partitioning().partition_count() != 1 + { + return Ok(None); + } + Ok(Some(PreparedRawSeries { + context: ctx, + plan: wrapped, + binding, + ordering, + })) + } + pub fn new(state: Arc, plugins: Plugins) -> Self { Self { state, plugins } } @@ -435,6 +702,26 @@ impl DatafusionQueryEngine { .query_planner() .create_physical_plan(&optimized_plan, state) .await?; + let physical_plan = if self.state.experimental_native_promql() { + if let DfLogicalPlan::Analyze(analyze) = &optimized_plan + && let Some(exec) = physical_plan.downcast_ref::() + { + let selected = + native_promql::try_select(&analyze.input, Arc::clone(exec.input())).await?; + if Arc::ptr_eq(&selected, exec.input()) { + physical_plan + } else { + physical_plan.replace_children( + vec![selected], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )? + } + } else { + native_promql::try_select(&optimized_plan, physical_plan).await? + } + } else { + physical_plan + }; logger.phy_plan = Some(physical_plan.clone()); drop(logger); @@ -523,6 +810,54 @@ impl QueryEngine for DatafusionQueryEngine { } } + async fn prepare_raw_series( + &self, + plan: LogicalPlan, + query_ctx: QueryContextRef, + binding: RawSeriesRequest, + ) -> Result> { + Ok(self + .prepare_raw_series_plan(plan, query_ctx, Some(binding)) + .await? + .map(|prepared| prepared.ordering)) + } + + async fn prepare_named_raw_series( + &self, + plan: LogicalPlan, + query_ctx: QueryContextRef, + ) -> Result> { + Ok(self + .prepare_raw_series_plan(plan, query_ctx, None) + .await? + .map(|prepared| PreparedNamedRawSeries { + binding: prepared.binding, + ordering: prepared.ordering, + })) + } + + async fn execute_raw_series( + &self, + plan: LogicalPlan, + query_ctx: QueryContextRef, + binding: RawSeriesRequest, + ) -> Result { + let Some(prepared) = self + .prepare_raw_series_plan(plan, query_ctx, Some(binding)) + .await? + else { + return Err(UnimplementedSnafu { + operation: "unsupported native raw-series plan".to_string(), + } + .build()); + }; + let stream = self.execute_stream(&prepared.context, &prepared.plan)?; + Ok(Output::new( + OutputData::Stream(stream), + OutputMeta::new_with_plan(prepared.plan), + )) + } + /// Note in SQL queries, aggregate names are looked up using /// lowercase unless the query uses quotes. For example, /// @@ -764,6 +1099,7 @@ mod tests { use datafusion::prelude::{col, lit}; use datafusion_common::{JoinType, NullEquality, ScalarValue}; use datafusion_physical_expr::expressions::Column; + use datatypes::arrow::datatypes::{DataType, Field}; use datatypes::prelude::ConcreteDataType; use datatypes::schema::{ColumnSchema, SchemaRef}; use datatypes::vectors::{Helper, UInt32Vector, VectorRef}; @@ -1042,6 +1378,67 @@ mod tests { .query_engine() } + #[tokio::test] + async fn raw_series_entrypoint_rejects_unsupported_parents_and_invalid_parallel_hints() { + let engine = create_test_engine().await; + let provider = crate::optimizer::test_util::mock_table_provider(RegionId::new(1, 1)); + let metadata = provider.region_metadata(); + let source = Arc::new(DefaultTableSource::new(Arc::new(provider))); + let scan = datafusion_expr::LogicalPlanBuilder::scan("raw", source, Some(vec![2])) + .unwrap() + .build() + .unwrap(); + let binding = RawSeriesRequest { + version: 1, + physical_metadata: metadata.as_ref().clone(), + metric_name: "m".to_string(), + logical_tags: vec![], + field_ids: vec![3], + }; + for hint in ["invalid", "0"] { + let ctx = Arc::new( + QueryContextBuilder::default() + .set_extension(QUERY_PARALLELISM_HINT.to_string(), hint.to_string()) + .build(), + ); + let error = match engine + .execute_raw_series(scan.clone(), ctx, binding.clone()) + .await + { + Err(error) => error, + Ok(_) => panic!("invalid parallelism hint was accepted"), + }; + assert!(matches!( + error, + crate::error::Error::Unimplemented { operation, .. } + if operation == "unsupported native raw-series plan" + )); + } + assert!(raw_expr_supported(&lit(1_i64).eq(lit(2_i64)))); + assert!(!raw_expr_supported(&Expr::ScalarVariable( + Arc::new(Field::new("v", DataType::Int64, true)), + vec!["v".into()], + ))); + + let parent = datafusion_expr::LogicalPlanBuilder::from(scan.clone()) + .limit(0, Some(1)) + .unwrap() + .build() + .unwrap(); + let error = match engine + .execute_raw_series(parent, QueryContext::arc(), binding) + .await + { + Err(error) => error, + Ok(_) => panic!("an unsupported parent logical plan was accepted"), + }; + assert!(matches!( + error, + crate::error::Error::Unimplemented { operation, .. } + if operation == "unsupported native raw-series plan" + )); + } + #[tokio::test] async fn test_sql_to_plan() { let engine = create_test_engine().await; diff --git a/src/query/src/datafusion/native_promql.rs b/src/query/src/datafusion/native_promql.rs new file mode 100644 index 00000000000..4cb5083cafa --- /dev/null +++ b/src/query/src/datafusion/native_promql.rs @@ -0,0 +1,328 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::Arc; + +use api::v1::SemanticType; +use datafusion::arrow::datatypes::{DataType, SchemaRef, TimeUnit}; +use datafusion::datasource::DefaultTableSource; +use datafusion::physical_plan::ExecutionPlan; +use datafusion_expr::{Extension, LogicalPlan}; +use datatypes::data_type::ConcreteDataType; +use promql::extension_plan::{InstantManipulate, InstantManipulateExec, SeriesDivideExec}; +use store_api::metric_engine_consts::is_metric_engine_internal_column; +use table::table::scan::RegionScanExec; + +use crate::datafusion::raw_expr_supported; +use crate::dummy_catalog::DummyTableProvider; + +/// Selects native execution for the bounded, unmodified instant-over-divide shape. +/// +/// Returns the original plan unchanged for any shape that does not match the local pattern. +pub(crate) async fn try_select( + logical: &LogicalPlan, + original: Arc, +) -> datafusion::error::Result> { + if let Some(local) = try_select_local(logical, &original)? { + return Ok(local); + } + Ok(original) +} + +/// Selects native execution only for the bounded, unmodified local instant-over-divide shape. +fn try_select_local( + logical: &LogicalPlan, + original: &Arc, +) -> datafusion::error::Result>> { + let Some((instant, divide, scan_node)) = logical_shape(logical) else { + return Ok(None); + }; + let Some((instant_exec_schema, scan_exec, root_cooperative, scan_cooperative)) = + physical_shape(original) + else { + return Ok(None); + }; + if scan_node.fetch.is_some() + || !scan_node.statistics_requests.is_empty() + || scan_node + .filters + .iter() + .any(|filter| !raw_expr_supported(filter)) + { + return Ok(None); + } + let Some(source) = scan_node.source.downcast_ref::() else { + return Ok(None); + }; + let Some(provider) = source.table_provider.downcast_ref::() else { + return Ok(None); + }; + + let metadata = provider.region_metadata(); + let table_name = scan_node.table_name.table().to_string(); + let logical_tags = metadata + .column_metadatas + .iter() + .filter(|column| { + column.semantic_type == SemanticType::Tag + && !is_metric_engine_internal_column(&column.column_schema.name) + }) + .map(|column| column.column_schema.name.clone()) + .collect::>(); + let logical_output = scan_node.projected_schema.as_ref(); + let physical_output = scan_exec.schema(); + if logical_output.fields().len() != physical_output.fields().len() + || logical_output + .fields() + .iter() + .zip(physical_output.fields()) + .any(|(logical, physical)| { + logical.name() != physical.name() || logical.data_type() != physical.data_type() + }) + { + return Ok(None); + } + let mut fields = Vec::new(); + let mut tags_found = std::collections::HashSet::new(); + let mut time_found = false; + for field in logical_output.fields() { + let Some(column) = metadata.column_by_name(field.name()) else { + return Ok(None); + }; + match column.semantic_type { + SemanticType::Tag if logical_tags.iter().any(|tag| tag == field.name()) => { + tags_found.insert(field.name().clone()); + } + SemanticType::Timestamp + if field.data_type() == &DataType::Timestamp(TimeUnit::Millisecond, None) => + { + time_found = true; + } + SemanticType::Field + if column.column_schema.data_type == ConcreteDataType::float64_datatype() + && field.data_type() == &DataType::Float64 => + { + fields.push(field.name().clone()); + } + _ => return Ok(None), + } + } + // The declared Float64 fields are mapped in declared order; only the configured staleness + // columns are checked, exactly like the ordinary selector. + if !time_found + || logical_output.fields().len() != logical_tags.len() + fields.len() + 1 + || tags_found.len() != logical_tags.len() + || fields.is_empty() + || (!divide.tags().is_empty() && divide.tags() != logical_tags) + { + return Ok(None); + } + + let Some(native_scan) = + scan_exec + .clone() + .try_to_named_series_scan(&table_name, &logical_tags, &fields)? + else { + return Ok(None); + }; + let label_source = native_scan.label_source().clone(); + let series_schema = Arc::clone(native_scan.series_schema()); + let mut native_child: Arc = native_scan; + if scan_cooperative { + native_child = Arc::new(datafusion::physical_plan::coop::CooperativeExec::new( + native_child, + )); + } + let native = instant.try_to_native_execution_plan( + native_child, + instant_exec_schema, + label_source, + series_schema, + &logical_tags, + )?; + let Some(native) = native else { + return Ok(None); + }; + if root_cooperative { + Arc::clone(original) + .replace_children( + vec![native], + datafusion::physical_plan::ReplaceChildrenOptions::new( + datafusion::physical_plan::ChildrenPropertiesMode::Recompute, + ), + ) + .map(Some) + } else { + Ok(Some(native)) + } +} + +fn logical_shape( + plan: &LogicalPlan, +) -> Option<( + &InstantManipulate, + &promql::extension_plan::SeriesDivide, + &datafusion_expr::logical_plan::TableScan, +)> { + let LogicalPlan::Extension(Extension { node }) = plan else { + return None; + }; + let instant = node.as_any().downcast_ref::()?; + if instant.is_single_evaluation() { + return None; + } + let instant_inputs = node.inputs(); + let [input] = instant_inputs.as_slice() else { + return None; + }; + let LogicalPlan::Extension(Extension { node: divide_node }) = input else { + return None; + }; + let divide = divide_node + .as_any() + .downcast_ref::()?; + let divide_inputs = divide_node.inputs(); + let [input] = divide_inputs.as_slice() else { + return None; + }; + let scan = table_scan_through_safe_nodes(input)?; + Some((instant, divide, scan)) +} + +/// Returns the single table scan a plan reaches through safe nodes: a sort without a fetch, a +/// filter whose predicate the raw path supports, or a positional identity projection. +/// +/// The scan is a discovery result only: callers must preserve every node of the discovered tree +/// instead of treating the wrappers around the scan as removable. +pub(crate) fn table_scan_through_safe_nodes( + plan: &LogicalPlan, +) -> Option<&datafusion_expr::logical_plan::TableScan> { + match plan { + LogicalPlan::TableScan(scan) => Some(scan), + LogicalPlan::Sort(sort) if sort.fetch.is_none() => { + table_scan_through_safe_nodes(&sort.input) + } + LogicalPlan::Filter(filter) if raw_expr_supported(&filter.predicate) => { + table_scan_through_safe_nodes(&filter.input) + } + LogicalPlan::Projection(projection) + if projection.expr.len() == projection.input.schema().fields().len() + && projection.expr.iter().enumerate().all(|(index, expr)| { + matches!(expr, datafusion_expr::Expr::Column(column) + if column.name.as_str() == projection.input.schema().field(index).name()) + }) => + { + table_scan_through_safe_nodes(&projection.input) + } + _ => None, + } +} + +fn physical_shape( + plan: &Arc, +) -> Option<(SchemaRef, Arc, bool, bool)> { + let (plan, root_cooperative) = if let Some(wrapper) = + plan.downcast_ref::() + { + (wrapper.input(), true) + } else { + (plan, false) + }; + let instant = plan.downcast_ref::()?; + let output_schema = instant.schema(); + let instant_children = instant.children(); + let [divide] = instant_children.as_slice() else { + return None; + }; + let divide = divide.downcast_ref::()?; + let divide_children = divide.children(); + let [scan] = divide_children.as_slice() else { + return None; + }; + let (scan, scan_cooperative) = if let Some(wrapper) = + scan.downcast_ref::() + { + (wrapper.input(), true) + } else { + (*scan, false) + }; + let scan = scan.downcast_ref::()?; + if scan.properties().output_partitioning().partition_count() != 1 { + return None; + } + Some(( + output_schema, + Arc::new(scan.clone()), + root_cooperative, + scan_cooperative, + )) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use datafusion::datasource::DefaultTableSource; + use datafusion_expr::{Extension, LogicalPlan, LogicalPlanBuilder}; + use promql::extension_plan::{InstantManipulate, SeriesDivide}; + use store_api::storage::RegionId; + + use super::{logical_shape, table_scan_through_safe_nodes}; + + #[test] + fn native_instant_admission_rejects_non_instant_root() { + let plan = LogicalPlanBuilder::empty(false).build().unwrap(); + assert!(logical_shape(&plan).is_none()); + } + + #[test] + fn native_instant_admission_accepts_one_bounded_instant_scan() { + let provider = Arc::new(crate::optimizer::test_util::mock_table_provider( + RegionId::new(1, 1), + )); + let source = Arc::new(DefaultTableSource::new(provider)); + let scan = LogicalPlanBuilder::scan("metric", source, None) + .unwrap() + .build() + .unwrap(); + let divide = LogicalPlan::Extension(Extension { + node: Arc::new(SeriesDivide::new(vec!["k0".into()], "ts".into(), scan)), + }); + let instant = LogicalPlan::Extension(Extension { + node: Arc::new(InstantManipulate::new( + 1000, + 2000, + 30000, + 1000, + 0, + "ts".into(), + vec!["k0".into()], + Some("v0".into()), + divide, + )), + }); + assert!(logical_shape(&instant).is_some()); + } + + #[test] + fn native_instant_scan_path_rejects_uncontrolled_operators() { + let plan = LogicalPlanBuilder::empty(false) + .limit(0, Some(1)) + .unwrap() + .build() + .unwrap(); + assert!(table_scan_through_safe_nodes(&plan).is_none()); + assert!(matches!(plan, LogicalPlan::Limit(_))); + } +} diff --git a/src/query/src/datafusion/raw_series_admission_tests.rs b/src/query/src/datafusion/raw_series_admission_tests.rs new file mode 100644 index 00000000000..45176cb524b --- /dev/null +++ b/src/query/src/datafusion/raw_series_admission_tests.rs @@ -0,0 +1,831 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::any::Any; +use std::fmt; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; + +use api::region::RegionResponse; +use api::v1::SemanticType; +use async_trait::async_trait; +use common_error::ext::BoxedError; +use common_query::OutputData; +use common_query::request::{ + INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY, RawSeriesRequest, RawSeriesTag, +}; +use common_recordbatch::{SendableRecordBatchStream, util}; +use datafusion::datasource::{DefaultTableSource, MemTable}; +use datafusion::physical_plan::PhysicalExpr; +use datafusion::physical_plan::display::{DisplayAs, DisplayFormatType}; +use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet; +use datafusion_common::ScalarValue; +use datafusion_expr::{LogicalPlan, LogicalPlanBuilder, SortExpr, col, lit}; +use datatypes::arrow::array::{AsArray, BinaryArray, Float64Array, Int64Array, ListArray}; +use datatypes::arrow::buffer::Buffer; +use datatypes::schema::SchemaRef; +use datatypes::series::SeriesOrdering; +use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; +use datatypes::series::samples::{FieldSpec, Samples, SeriesFields, SeriesSchema}; +use futures::Stream; +use session::context::{QueryContext, QueryContextBuilder}; +use store_api::metadata::RegionMetadataRef; +use store_api::region_engine::{ + PrepareRequest, QueryScanContext, RawLabelSource, RawSeriesStream, RegionEngine, + RegionEngineRef, RegionRole, RegionScanner, RegionScannerRef, RegionStatistic, + RemapManifestsRequest, RemapManifestsResponse, ScannerProperties, SendableRawSeriesStream, + SetRegionRoleStateResponse, SettableRegionRoleState, SyncRegionFromRequest, + SyncRegionFromResponse, +}; +use store_api::region_request::RegionRequest; +use store_api::storage::{RegionId, ScanRequest, SequenceNumber, TimeSeriesRowSelector}; + +use crate::QueryEngineRef; +use crate::datafusion::QUERY_PARALLELISM_HINT; +use crate::dummy_catalog::DummyTableProvider; +use crate::options::QueryOptions; +use crate::query_engine::QueryEngineFactory; + +async fn engine() -> QueryEngineRef { + QueryEngineFactory::new( + catalog::memory::new_memory_catalog_manager().unwrap(), + None, + None, + None, + None, + false, + QueryOptions::default(), + ) + .query_engine() +} + +fn mock_scan() -> (LogicalPlan, RawSeriesRequest) { + let provider = crate::optimizer::test_util::mock_table_provider(RegionId::new(1, 1)); + let metadata = provider.region_metadata(); + let source = Arc::new(DefaultTableSource::new(Arc::new(provider))); + let scan = LogicalPlanBuilder::scan("raw", source, Some(vec![2])) + .unwrap() + .build() + .unwrap(); + let binding = RawSeriesRequest { + version: 1, + physical_metadata: metadata.as_ref().clone(), + metric_name: "m".to_string(), + logical_tags: vec![], + field_ids: vec![3], + }; + (scan, binding) +} + +async fn assert_rejected( + engine: &QueryEngineRef, + plan: LogicalPlan, + ctx: Arc, + binding: RawSeriesRequest, +) { + assert!( + engine + .prepare_raw_series(plan.clone(), ctx.clone(), binding.clone()) + .await + .unwrap() + .is_none() + ); + let error = match engine.execute_raw_series(plan, ctx, binding).await { + Err(error) => error, + Ok(_) => panic!("unsupported raw-series plan was accepted"), + }; + assert!(matches!( + error, + crate::error::Error::Unimplemented { operation, .. } + if operation == "unsupported native raw-series plan" + )); +} + +#[tokio::test] +async fn raw_series_admission_rejects_invalid_parallelism_hints() { + let engine = engine().await; + let (scan, binding) = mock_scan(); + // Positive hints are no longer a hint-level rejection: the private preparation context + // pins the scan to one partition, so a positive hint reaches the plan-shape gates instead. + for hint in ["invalid", "0"] { + let ctx = Arc::new( + QueryContextBuilder::default() + .set_extension(QUERY_PARALLELISM_HINT.to_string(), hint.to_string()) + .build(), + ); + assert_rejected(&engine, scan.clone(), ctx, binding.clone()).await; + } +} + +#[tokio::test] +async fn raw_series_admission_rejects_initial_dynamic_filter_intent() { + let engine = engine().await; + let (scan, binding) = mock_scan(); + let ctx = Arc::new( + QueryContextBuilder::default() + .set_extension( + INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY.to_string(), + "malformed marker".to_string(), + ) + .build(), + ); + assert_rejected(&engine, scan.clone(), ctx, binding.clone()).await; +} + +/// A region engine that serves one region with a non-executing raw-series scanner. +struct RawSeriesEngine { + metadata: RegionMetadataRef, + raw_capable: bool, +} + +#[async_trait] +impl RegionEngine for RawSeriesEngine { + fn name(&self) -> &str { + "RawSeriesEngine" + } + + async fn handle_request( + &self, + _region_id: RegionId, + _request: RegionRequest, + ) -> std::result::Result { + unimplemented!("raw-series admission never writes") + } + + async fn handle_query( + &self, + region_id: RegionId, + _request: ScanRequest, + ) -> std::result::Result { + assert_eq!(region_id, self.metadata.region_id); + Ok(Box::new(RawSeriesScanner { + properties: ScannerProperties::default(), + metadata: self.metadata.clone(), + raw_capable: self.raw_capable, + })) + } + + async fn get_metadata( + &self, + region_id: RegionId, + ) -> std::result::Result { + assert_eq!(region_id, self.metadata.region_id); + Ok(self.metadata.clone()) + } + + fn region_statistic(&self, _region_id: RegionId) -> Option { + None + } + + async fn get_committed_sequence( + &self, + _region_id: RegionId, + ) -> std::result::Result { + Ok(SequenceNumber::default()) + } + + async fn stop(&self) -> std::result::Result<(), BoxedError> { + Ok(()) + } + + fn set_region_role( + &self, + _region_id: RegionId, + _role: RegionRole, + ) -> std::result::Result<(), BoxedError> { + unimplemented!("raw-series admission never changes the region role") + } + + async fn set_region_role_state_gracefully( + &self, + _region_id: RegionId, + _region_role_state: SettableRegionRoleState, + ) -> std::result::Result { + unimplemented!("raw-series admission never changes the region role") + } + + async fn sync_region( + &self, + _region_id: RegionId, + _request: SyncRegionFromRequest, + ) -> std::result::Result { + unimplemented!("raw-series admission never syncs a region") + } + + async fn remap_manifests( + &self, + _request: RemapManifestsRequest, + ) -> std::result::Result { + unimplemented!("raw-series admission never remaps manifests") + } + + fn role(&self, _region_id: RegionId) -> Option { + None + } + + fn as_any(&self) -> &dyn Any { + self + } +} + +/// The single sample every raw execution of this scanner emits: one series, one timestamp, and +/// one float value per declared field. +const RAW_SAMPLE_KEY: &[u8] = b"complete-key"; +const RAW_SAMPLE_TIMESTAMP: i64 = 10; +const RAW_SAMPLE_VALUE: f64 = 1.5; + +/// A scanner that reports raw-series capability without polluting any execution state. +#[derive(Debug)] +struct RawSeriesScanner { + properties: ScannerProperties, + metadata: RegionMetadataRef, + raw_capable: bool, +} + +impl RawSeriesScanner { + /// The complete raw-series schema this scanner declares for its own metadata. + fn declared_raw_schema(&self) -> Arc { + let fields = self + .metadata + .column_metadatas + .iter() + .filter(|column| column.semantic_type == SemanticType::Field) + .map(|column| FieldSpec { + name: Arc::from(column.column_schema.name.as_str()), + }) + .collect::>(); + Arc::new(SeriesSchema { + fields: fields.into(), + eval_grid: None, + }) + } +} + +/// One planned raw-series chunk, yielded once and finished afterwards. +#[derive(Debug)] +struct RawSeriesSampleStream { + schema: Arc, + label_source: RawLabelSource, + chunk: Option, +} + +impl Stream for RawSeriesSampleStream { + type Item = std::result::Result; + + fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(self.chunk.take().map(Ok)) + } +} + +impl RawSeriesStream for RawSeriesSampleStream { + fn schema(&self) -> &Arc { + &self.schema + } + + fn label_source(&self) -> &RawLabelSource { + &self.label_source + } + + fn ordering(&self) -> SeriesOrdering { + SeriesOrdering::KeyThenTime + } +} + +impl DisplayAs for RawSeriesScanner { + fn fmt_as(&self, _format: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("RawSeriesScanner") + } +} + +impl RegionScanner for RawSeriesScanner { + fn name(&self) -> &str { + "RawSeriesScanner" + } + + fn properties(&self) -> &ScannerProperties { + &self.properties + } + + fn schema(&self) -> SchemaRef { + self.metadata.schema.clone() + } + + fn metadata(&self) -> RegionMetadataRef { + self.metadata.clone() + } + + fn prepare(&mut self, request: PrepareRequest) -> std::result::Result<(), BoxedError> { + self.properties.prepare(request); + Ok(()) + } + + fn scan_partition( + &self, + _ctx: &QueryScanContext, + _metrics: &ExecutionPlanMetricsSet, + _partition: usize, + ) -> std::result::Result { + unimplemented!("raw-series admission never executes an ordinary scan") + } + + fn raw_series_schema( + &self, + _source: &RawLabelSource, + ) -> std::result::Result>, BoxedError> { + if !self.raw_capable { + return Ok(None); + } + Ok(Some(self.declared_raw_schema())) + } + + /// Executes the raw path for the focused admission case without changing scanner state: one + /// series with one sample per declared field, so a prepared plan's visible output can be + /// observed directly. + fn scan_series_partition( + &self, + _ctx: &QueryScanContext, + _metrics: &ExecutionPlanMetricsSet, + _partition: usize, + label_source: &RawLabelSource, + ) -> std::result::Result, BoxedError> { + if !self.raw_capable { + return Ok(None); + } + let schema = self.declared_raw_schema(); + let fields = SeriesFields::try_from_vec( + schema + .fields + .iter() + .map(|_| Samples::from_float(Float64Array::from(vec![Some(RAW_SAMPLE_VALUE)]))) + .collect(), + ) + .expect("the declared raw schema must accept one sample per field"); + let chunk = RawSeriesChunk::try_new( + &schema, + Buffer::from(RAW_SAMPLE_KEY), + None, + RawTimestamps::try_new(vec![RAW_SAMPLE_TIMESTAMP].into()) + .expect("the sample timestamp must be strictly increasing"), + fields, + true, + ) + .expect("the sample chunk must match the declared raw schema"); + Ok(Some(Box::pin(RawSeriesSampleStream { + schema, + label_source: label_source.clone(), + chunk: Some(chunk), + }))) + } + + fn raw_series_ordering(&self) -> SeriesOrdering { + SeriesOrdering::KeyThenTime + } + + fn has_predicate_without_region(&self) -> bool { + false + } + + fn add_dyn_filter_to_predicate( + &mut self, + filter_exprs: Vec>, + ) -> Vec { + filter_exprs.iter().map(|_| false).collect() + } + + fn set_logical_region(&mut self, logical_region: bool) { + self.properties.set_logical_region(logical_region); + } + + fn set_query_load_region_id(&mut self, region_id: RegionId) { + self.properties.set_query_load_region_id(region_id); + } +} + +/// One authorized region scan over the mock metadata `k0: string tag, ts: timestamp, v0: f64 field`. +struct RawSeriesFixture { + scan: LogicalPlan, + provider: DummyTableProvider, + metadata: RegionMetadataRef, + region_id: RegionId, +} + +fn raw_series_fixture(raw_capable: bool) -> RawSeriesFixture { + let region_id = RegionId::new(1, 1); + let metadata = crate::optimizer::test_util::mock_table_provider(region_id).region_metadata(); + let engine: RegionEngineRef = Arc::new(RawSeriesEngine { + metadata: metadata.clone(), + raw_capable, + }); + let provider = DummyTableProvider::new(region_id, engine, metadata.clone()); + let source = Arc::new(DefaultTableSource::new(Arc::new(provider.clone()))); + let scan = LogicalPlanBuilder::scan("cpu", source, None) + .unwrap() + .build() + .unwrap(); + RawSeriesFixture { + scan, + provider, + metadata, + region_id, + } +} + +impl RawSeriesFixture { + /// The frozen remote shape: sort over a timestamp filter over a full-schema scan. + fn wrapped(&self) -> LogicalPlan { + let lower = lit(ScalarValue::TimestampMillisecond(Some(-298_999), None)); + let upper = lit(ScalarValue::TimestampMillisecond(Some(3_000), None)); + LogicalPlanBuilder::from(self.scan.clone()) + .filter(col("ts").gt_eq(lower).and(col("ts").lt_eq(upper))) + .unwrap() + .sort(vec![ + SortExpr::new(col("k0"), true, true), + SortExpr::new(col("ts"), true, true), + ]) + .unwrap() + .build() + .unwrap() + } + + /// The expectation a bound caller derives from the same authorized scan. + fn binding(&self) -> RawSeriesRequest { + RawSeriesRequest { + version: 1, + physical_metadata: self.metadata.as_ref().clone(), + metric_name: "cpu".to_string(), + logical_tags: vec![RawSeriesTag { + column_id: 1, + name: "k0".to_string(), + }], + field_ids: vec![3], + } + } +} + +#[tokio::test] +async fn named_raw_series_preparation_derives_the_actual_binding() { + let fixture = raw_series_fixture(true); + let engine = engine().await; + let ctx = Arc::new( + QueryContextBuilder::default() + .set_extension(QUERY_PARALLELISM_HINT.to_string(), "4".to_string()) + .set_extension("unrelated.extension".to_string(), "kept".to_string()) + .build(), + ); + + for plan in [fixture.scan.clone(), fixture.wrapped()] { + let rendered = plan.to_string(); + let prepared = engine + .prepare_named_raw_series(plan.clone(), ctx.clone()) + .await + .unwrap() + .expect("the authorized wrapped shape must be approved"); + assert_eq!(prepared.ordering, SeriesOrdering::KeyThenTime); + assert_eq!(prepared.binding.version, 1); + assert_eq!(prepared.binding.metric_name, "cpu"); + assert_eq!( + prepared.binding.physical_metadata.region_id, + fixture.region_id + ); + assert_eq!(prepared.binding.logical_tags.len(), 1); + assert_eq!(prepared.binding.logical_tags[0].column_id, 1); + assert_eq!(prepared.binding.logical_tags[0].name, "k0"); + assert_eq!(prepared.binding.field_ids, [3]); + assert_eq!( + engine + .prepare_raw_series(plan.clone(), ctx.clone(), fixture.binding()) + .await + .unwrap(), + Some(SeriesOrdering::KeyThenTime), + "bound preparation must share the approved shape" + ); + assert_eq!(plan.to_string(), rendered); + } + + assert_eq!(ctx.extension(QUERY_PARALLELISM_HINT), Some("4")); + assert_eq!(ctx.extension("unrelated.extension"), Some("kept")); + assert!(fixture.provider.scan_request().distribution.is_none()); + assert!( + fixture + .provider + .scan_request() + .series_row_selector + .is_none() + ); +} + +#[tokio::test] +async fn named_raw_series_preparation_approves_the_entire_unprojected_schema() { + let fixture = raw_series_fixture(true); + let engine = engine().await; + let ctx = Arc::new( + QueryContextBuilder::default() + .set_extension(QUERY_PARALLELISM_HINT.to_string(), "2".to_string()) + .build(), + ); + // The authorized region schema is the complete visible tag and field set of this scan. + let expected_tags = fixture + .metadata + .column_metadatas + .iter() + .filter(|column| column.semantic_type == SemanticType::Tag) + .map(|column| (column.column_id, column.column_schema.name.clone())) + .collect::>(); + let expected_fields = fixture + .metadata + .column_metadatas + .iter() + .filter(|column| column.semantic_type == SemanticType::Field) + .map(|column| column.column_schema.name.clone()) + .collect::>(); + assert!(!expected_tags.is_empty()); + assert!(!expected_fields.is_empty()); + + // A scan without a projection reads its whole region, so the approval and the reported + // binding must cover every visible tag and field instead of a convenient subset. + let plan = fixture.wrapped(); + let prepared = engine + .prepare_named_raw_series(plan.clone(), ctx.clone()) + .await + .unwrap() + .expect("an unprojected authorized scan must be approved as a whole"); + assert_eq!(prepared.ordering, SeriesOrdering::KeyThenTime); + assert_eq!(prepared.binding.version, 1); + assert_eq!(prepared.binding.metric_name, "cpu"); + assert_eq!( + prepared.binding.physical_metadata.region_id, + fixture.region_id + ); + assert_eq!( + prepared + .binding + .logical_tags + .iter() + .map(|tag| (tag.column_id, tag.name.clone())) + .collect::>(), + expected_tags, + "the approved binding must keep every authorized tag in schema order" + ); + assert_eq!( + prepared + .binding + .field_ids + .iter() + .map(|id| { + fixture + .metadata + .column_by_id(*id) + .expect("approved fields must exist in the actual metadata") + .column_schema + .name + .clone() + }) + .collect::>(), + expected_fields, + "the approved binding must keep every authorized field in schema order" + ); + + // The bound path approves the same plan, and executing it emits exactly that visible data. + let binding = prepared.binding.clone(); + assert_eq!( + engine + .prepare_raw_series(plan.clone(), ctx.clone(), binding.clone()) + .await + .unwrap(), + Some(SeriesOrdering::KeyThenTime) + ); + let OutputData::Stream(stream) = engine + .execute_raw_series(plan, ctx, binding) + .await + .unwrap() + .data + else { + panic!("a prepared raw-series plan must stream record batches"); + }; + let batches = util::collect(stream).await.unwrap(); + assert_eq!(batches.len(), 1); + let batch = batches.first().unwrap(); + assert_eq!(batch.num_rows(), 1); + + // The emitted frame keeps the whole authorized schema: the identity, the time axis, and every + // authorized field, in order. + let frame = batch.df_record_batch(); + assert_eq!( + frame + .schema() + .fields() + .iter() + .map(|field| field.name().clone()) + .collect::>(), + ["read_key", "is_last", "time", "fields"] + ); + assert_eq!( + common_query::series_frame::raw_series_frame_ordering(&frame.schema()).unwrap(), + SeriesOrdering::KeyThenTime + ); + assert_eq!( + frame + .column_by_name("read_key") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + RAW_SAMPLE_KEY + ); + assert_eq!( + frame + .column_by_name("time") + .unwrap() + .as_struct() + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec(), + vec![RAW_SAMPLE_TIMESTAMP] + ); + let payload = frame.column_by_name("fields").unwrap().as_struct(); + assert_eq!( + payload + .fields() + .iter() + .map(|field| field.name().clone()) + .collect::>(), + expected_fields, + "an unprojected approval must emit every authorized field" + ); + for (index, name) in expected_fields.iter().enumerate() { + assert_eq!( + payload + .column(index) + .as_struct() + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec(), + vec![RAW_SAMPLE_VALUE], + "field {name} must be visible in the emitted frame" + ); + } + + assert_eq!(fixture.provider.scan_request().distribution, None); +} + +#[tokio::test] +async fn raw_series_preparation_declines_residual_and_unknown_wrapper_shapes() { + let fixture = raw_series_fixture(true); + let engine = engine().await; + let ctx = Arc::new( + QueryContextBuilder::default() + .set_extension(QUERY_PARALLELISM_HINT.to_string(), "1".to_string()) + .build(), + ); + + // A sort on a field column and an inexact field filter both survive physical planning above + // the scan, so they must reject the plan instead of being unwrapped. + let residual_sort = LogicalPlanBuilder::from(fixture.scan.clone()) + .sort(vec![SortExpr::new(col("v0"), false, true)]) + .unwrap() + .build() + .unwrap(); + let residual_filter = LogicalPlanBuilder::from(fixture.scan.clone()) + .filter(col("v0").gt(lit(0.0))) + .unwrap() + .build() + .unwrap(); + // Unsupported operators, a non-identity projection, and a partial projection are not safe. + let limited = LogicalPlanBuilder::from(fixture.scan.clone()) + .limit(0, Some(1)) + .unwrap() + .build() + .unwrap(); + let non_identity = LogicalPlanBuilder::from(fixture.scan.clone()) + .project(vec![col("k0"), col("ts"), col("v0") + lit(1.0)]) + .unwrap() + .build() + .unwrap(); + let partial_projection = LogicalPlanBuilder::scan( + "cpu", + Arc::new(DefaultTableSource::new(Arc::new(fixture.provider.clone()))), + Some(vec![2]), + ) + .unwrap() + .build() + .unwrap(); + // A table source that is not the authorized region provider is not a raw-series candidate. + let foreign_source = { + let schema = fixture.metadata.schema.arrow_schema(); + let table = MemTable::try_new(Arc::clone(schema), vec![vec![]]).unwrap(); + LogicalPlanBuilder::scan( + "cpu", + Arc::new(DefaultTableSource::new(Arc::new(table))), + None, + ) + .unwrap() + .build() + .unwrap() + }; + + for plan in [ + residual_sort, + residual_filter, + limited, + non_identity, + partial_projection, + foreign_source, + ] { + assert!( + engine + .prepare_named_raw_series(plan.clone(), ctx.clone()) + .await + .unwrap() + .is_none(), + "an unsupported shape must not be approved: {plan}" + ); + assert!( + engine + .prepare_raw_series(plan, ctx.clone(), fixture.binding()) + .await + .unwrap() + .is_none() + ); + } + + // A selector changes the requested rows, so the provider cannot be cloned for raw series. + let selector_fixture = raw_series_fixture(true); + selector_fixture + .provider + .with_time_series_selector_hint(TimeSeriesRowSelector::LastRow { after_merge: false }); + assert!( + engine + .prepare_named_raw_series(selector_fixture.wrapped(), ctx.clone()) + .await + .unwrap() + .is_none() + ); + + // A scanner without raw-series capability declines instead of falling back to an ordinary scan. + let incapable = raw_series_fixture(false); + assert!( + engine + .prepare_named_raw_series(incapable.wrapped(), ctx.clone()) + .await + .unwrap() + .is_none() + ); + + // Initial remote dynamic-filter intent and unusable hints decline before planning. + let dynamic = Arc::new( + QueryContextBuilder::default() + .set_extension( + INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY.to_string(), + "malformed marker".to_string(), + ) + .build(), + ); + assert!( + engine + .prepare_named_raw_series(fixture.wrapped(), dynamic) + .await + .unwrap() + .is_none() + ); + for hint in ["invalid", "0"] { + let ctx = Arc::new( + QueryContextBuilder::default() + .set_extension(QUERY_PARALLELISM_HINT.to_string(), hint.to_string()) + .build(), + ); + assert!( + engine + .prepare_named_raw_series(fixture.wrapped(), ctx) + .await + .unwrap() + .is_none() + ); + } +} diff --git a/src/query/src/dummy_catalog.rs b/src/query/src/dummy_catalog.rs index 8f0a2c7ac60..a78d5de138c 100644 --- a/src/query/src/dummy_catalog.rs +++ b/src/query/src/dummy_catalog.rs @@ -286,6 +286,19 @@ impl DummyTableProvider { } } + /// Clones this provider for a trusted raw-series scan, unless it carries a + /// row selector which changes the requested rows. + pub(crate) fn clone_for_raw_series(&self) -> Option { + let provider = self.clone_for_scan(); + let mut request = provider.scan_request.lock().unwrap(); + if request.series_row_selector.is_some() { + return None; + } + request.distribution = Some(TimeSeriesDistribution::PerSeries); + drop(request); + Some(provider) + } + pub fn with_sequence(&self, sequence: u64) { self.scan_request.lock().unwrap().memtable_max_sequence = Some(sequence); } @@ -653,6 +666,32 @@ mod tests { FLOW_RETURN_REGION_SEQ, FLOW_SINK_TABLE_ID, }; + #[test] + fn raw_provider_clone_sets_per_series_without_mutating_shared_request() { + let provider = crate::optimizer::test_util::mock_table_provider(RegionId::new(1, 1)); + let original = provider.scan_request(); + let raw = provider.clone_for_raw_series().unwrap(); + assert_eq!( + raw.scan_request().distribution, + Some(TimeSeriesDistribution::PerSeries) + ); + assert_eq!(provider.scan_request(), original); + } + + #[test] + fn raw_provider_clone_rejects_selector_and_preserves_snapshot_intent() { + let provider = crate::optimizer::test_util::mock_table_provider(RegionId::new(1, 1)); + provider + .with_time_series_selector_hint(TimeSeriesRowSelector::LastRow { after_merge: false }); + assert!(provider.clone_for_raw_series().is_none()); + + let provider = crate::optimizer::test_util::mock_table_provider(RegionId::new(1, 1)); + provider.with_sequence(42); + let raw = provider.clone_for_raw_series().unwrap(); + assert_eq!(raw.scan_request().memtable_max_sequence, Some(42)); + assert_eq!(provider.scan_request().distribution, None); + } + #[test] fn test_nullable_label_filter_pushdown() { use datafusion_expr::{Cast, col, lit}; diff --git a/src/query/src/query_engine/state.rs b/src/query/src/query_engine/state.rs index e2095c33530..bc190c7eea7 100644 --- a/src/query/src/query_engine/state.rs +++ b/src/query/src/query_engine/state.rs @@ -91,6 +91,7 @@ use crate::region_query::RegionQueryHandlerRef; #[derive(Clone)] pub struct QueryEngineState { df_context: SessionContext, + experimental_native_promql: bool, catalog_manager: CatalogManagerRef, dyn_filter_registry_manager: Arc, function_state: Arc, @@ -285,6 +286,7 @@ impl QueryEngineState { Ok(Self { df_context, + experimental_native_promql: options.experimental_native_promql, catalog_manager: catalog_list, dyn_filter_registry_manager: Arc::new(DynFilterRegistryManager::default()), function_state: Arc::new(FunctionState { @@ -485,6 +487,11 @@ impl QueryEngineState { .unwrap_or(false) } + /// Whether the experimental native PromQL execution path is enabled. + pub(crate) fn experimental_native_promql(&self) -> bool { + self.experimental_native_promql + } + pub fn session_state(&self) -> SessionState { self.df_context.state() }