Skip to main content

query/
planner.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::any::Any;
16use std::borrow::Cow;
17use std::collections::{HashMap, HashSet};
18use std::ops::ControlFlow;
19use std::str::FromStr;
20use std::sync::Arc;
21
22use arrow_schema::DataType;
23use async_trait::async_trait;
24use catalog::table_source::DfTableSourceProvider;
25use common_error::ext::BoxedError;
26use common_query::promql_annotations::promql_annotation_collector;
27use common_telemetry::tracing;
28use datafusion::common::{DFSchema, plan_err};
29use datafusion::execution::SessionStateBuilder;
30use datafusion::execution::context::SessionState;
31use datafusion::sql::planner::PlannerContext;
32use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
33use datafusion_common::{ScalarValue, ToDFSchema};
34use datafusion_expr::expr::{Exists, InSubquery};
35use datafusion_expr::{
36    Analyze, Explain, ExplainFormat, Expr as DfExpr, LogicalPlan, LogicalPlanBuilder, PlanType,
37    ToStringifiedPlan, col,
38};
39use datafusion_sql::parser::Statement as DfStatement;
40use datafusion_sql::planner::{IdentNormalizer, ParserOptions, SqlToRel};
41use log_query::LogQuery;
42use promql_parser::parser::EvalStmt;
43use session::context::QueryContextRef;
44use snafu::{ResultExt, ensure};
45use sql::CteContent;
46use sql::ast::Expr as SqlExpr;
47use sql::statements::explain::ExplainStatement;
48use sql::statements::query::Query;
49use sql::statements::statement::Statement;
50use sql::statements::tql::Tql;
51use sqlparser::ast::{AccessExpr, Value, visit_expressions_mut};
52use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME;
53
54use crate::dist_plan::DistPlannerOptions;
55use crate::dist_plan::region_local_node;
56use crate::error::{
57    CteColumnSchemaMismatchSnafu, PlanSqlSnafu, QueryPlanSnafu, Result, SqlSnafu,
58    UnimplementedSnafu,
59};
60use crate::log_query::planner::LogQueryPlanner;
61use crate::optimizer::expr_depth;
62use crate::options::{NativePromqlExtension, ScheduledTimeExtension};
63use crate::parser::{DEFAULT_LOOKBACK_STRING, PromQuery, QueryLanguageParser, QueryStatement};
64use crate::promql::planner::PromPlanner;
65use crate::query_engine::{DefaultPlanDecoder, QueryEngineState};
66use crate::range_select::plan_rewrite::RangePlanRewriter;
67use crate::{DfContextProviderAdapter, QueryEngineContext};
68
69#[async_trait]
70pub trait LogicalPlanner: Send + Sync {
71    async fn plan(&self, stmt: &QueryStatement, query_ctx: QueryContextRef) -> Result<LogicalPlan>;
72
73    /// Plans a statement whose output columns are read by SQL rather than returned to a client, such
74    /// as a flow's sink rows. A PromQL statement may still run on the native route, but publishes the
75    /// existing planner's columns on either route, as a TQL CTE does. A selector that names no metric
76    /// has no existing columns and publishes the native route's own.
77    async fn plan_relation(
78        &self,
79        stmt: &QueryStatement,
80        query_ctx: QueryContextRef,
81    ) -> Result<LogicalPlan>;
82
83    async fn plan_logs_query(
84        &self,
85        query: LogQuery,
86        query_ctx: QueryContextRef,
87    ) -> Result<LogicalPlan>;
88
89    fn optimize(&self, plan: LogicalPlan) -> Result<LogicalPlan>;
90
91    fn as_any(&self) -> &dyn Any;
92}
93
94/// A native plan a distributed planner splits over regions may place fused evaluation in one of two
95/// places: above one independent raw source per region, or inside the region whose own scan it
96/// reads.
97///
98/// The second placement is the analyzer's to give. It moves a node into a region only when it
99/// classifies the node as running where its scan is, and a bare scan is never shipped across a
100/// region boundary on its own: nothing below the boundary could read it. So a scan is admitted only
101/// under a node the analyzer would move, and every other input of the plan has to be a raw source
102/// that names the region it reads.
103///
104/// A fused node that reads no region is the one exception: it has nothing to place in a region, so
105/// the frontend evaluates it and the transport this gate protects is never used.
106fn remote_native_raw_plan_supported(plan: &LogicalPlan) -> bool {
107    /// `region_local` says the nearest enclosing node reads its scan where that scan is planned, so
108    /// the subtree below it travels inside the region's own plan.
109    fn walk(
110        plan: &LogicalPlan,
111        region_local: bool,
112        found_raw: &mut bool,
113        found_region_local: &mut bool,
114    ) -> bool {
115        match plan {
116            LogicalPlan::TableScan(_) => region_local,
117            LogicalPlan::Extension(extension) => {
118                if extension
119                    .node
120                    .as_any()
121                    .is::<promql::extension_plan::RawSeriesSource>()
122                {
123                    *found_raw = true;
124                    return matches!(
125                        extension.node.inputs().as_slice(),
126                        [LogicalPlan::TableScan(_)]
127                    );
128                }
129                let region_local = extension
130                    .node
131                    .as_any()
132                    .is::<promql::extension_plan::FusedSeries>()
133                    && region_local_node(extension.node.as_ref());
134                *found_region_local |= region_local;
135                extension
136                    .node
137                    .inputs()
138                    .iter()
139                    .all(|child| walk(child, region_local, found_raw, found_region_local))
140            }
141            _ => plan
142                .inputs()
143                .iter()
144                .all(|child| walk(child, region_local, found_raw, found_region_local)),
145        }
146    }
147    let mut found_raw = false;
148    let mut found_region_local = false;
149    walk(plan, false, &mut found_raw, &mut found_region_local)
150        && (found_raw || found_region_local || is_regionless_fused_plan(plan))
151}
152
153/// Whether `plan` is a native fused plan with no region below it.
154///
155/// Two shapes qualify, and both are already the finished plan: a statement that reads no data -
156/// `time()`, `vector(1)`, a label rewrite over one of them - is one node with no input at all,
157/// and a discovered selector that matched no metric table is planned over the typed empty frame
158/// [`is_empty_discovered_input`](crate::promql::planner::native::is_empty_discovered_input)
159/// builds. Neither has a scan to ship, so neither needs the remote transport.
160///
161/// The route stacks its own nodes above such an input: a split aggregate runs a `Final` half over
162/// the `Partial` half that reads it, and a segmented statement runs its parent over the segment's
163/// own node. So the inputs a node reads are followed through fused nodes only - never through
164/// another extension, and never through a scan - and every leaf that is not one of them rejects
165/// the shape.
166fn is_regionless_fused_plan(plan: &LogicalPlan) -> bool {
167    // `strip_tsid_column` publishes a statement's own columns over a node that reported the
168    // internal series id, which a data-free statement can synthesize with `label_replace`. That
169    // wrapper is this route's own, so it is read through when it drops exactly that one column.
170    if let LogicalPlan::Projection(projection) = plan {
171        return strips_only_tsid(plan, projection.input.as_ref())
172            && is_regionless_fused_chain(projection.input.as_ref());
173    }
174    is_regionless_fused_chain(plan)
175}
176
177/// Whether `plan` is a fused node whose inputs are fused nodes or the typed empty frame.
178fn is_regionless_fused_chain(plan: &LogicalPlan) -> bool {
179    let LogicalPlan::Extension(extension) = plan else {
180        return false;
181    };
182    let Some(fused) = extension
183        .node
184        .as_any()
185        .downcast_ref::<promql::extension_plan::FusedSeries>()
186    else {
187        return false;
188    };
189    fused.children().iter().all(|child| {
190        crate::promql::planner::native::is_empty_discovered_input(child)
191            || is_regionless_fused_chain(child)
192    })
193}
194
195/// Whether `plan` is the projection that drops exactly the internal series-id column of `inner`.
196///
197/// That is the projection `strip_tsid_column` builds: one plain column per field of its input,
198/// in order, except `__tsid__`. A computed expression, a reordering or a second dropped column is
199/// some other plan and is not read through.
200fn strips_only_tsid(plan: &LogicalPlan, inner: &LogicalPlan) -> bool {
201    let LogicalPlan::Projection(projection) = plan else {
202        return false;
203    };
204    if projection
205        .expr
206        .iter()
207        .any(|expr| !matches!(expr, DfExpr::Column(_)))
208    {
209        return false;
210    }
211    let stripped = inner
212        .schema()
213        .fields()
214        .iter()
215        .filter(|field| field.name() != DATA_SCHEMA_TSID_COLUMN_NAME)
216        .map(|field| field.name())
217        .collect::<Vec<_>>();
218    let projected = plan
219        .schema()
220        .fields()
221        .iter()
222        .map(|field| field.name())
223        .collect::<Vec<_>>();
224    projected == stripped && projected.len() + 1 == inner.schema().fields().len()
225}
226
227/// Whether `plan` runs on the native fused-series route.
228fn contains_native_fused(plan: &LogicalPlan) -> bool {
229    if let LogicalPlan::Extension(extension) = plan
230        && extension
231            .node
232            .as_any()
233            .is::<promql::extension_plan::FusedSeries>()
234    {
235        return true;
236    }
237    plan.inputs()
238        .iter()
239        .any(|input| contains_native_fused(input))
240}
241
242/// Whether `expr` holds a selector that names no metric and is answered by discovering metric
243/// tables. The label selector of `info` names no metric either, but it stands for the info table
244/// rather than a discovery.
245fn discovers_any_metric(expr: &promql_parser::parser::Expr) -> bool {
246    use promql_parser::parser::Expr as PromExpr;
247
248    #[derive(Default)]
249    struct Visitor {
250        discovers: bool,
251        /// Addresses of `info` label selectors, compared only.
252        info_label_selectors: Vec<usize>,
253    }
254
255    impl promql_parser::util::ExprVisitor for Visitor {
256        type Error = std::convert::Infallible;
257
258        fn pre_visit(&mut self, expr: &PromExpr) -> std::result::Result<bool, Self::Error> {
259            match expr {
260                PromExpr::Call(call) if call.func.name == "info" => {
261                    if let Some(PromExpr::VectorSelector(labels)) =
262                        call.args.args.get(1).map(|labels| labels.as_ref())
263                    {
264                        self.info_label_selectors
265                            .push(std::ptr::from_ref(labels) as usize);
266                    }
267                }
268                PromExpr::VectorSelector(selector)
269                    if !self
270                        .info_label_selectors
271                        .contains(&(std::ptr::from_ref(selector) as usize)) =>
272                {
273                    self.discovers |= crate::promql::planner::discovers_metric_name(selector);
274                }
275                PromExpr::MatrixSelector(selector) => {
276                    self.discovers |= crate::promql::planner::discovers_metric_name(&selector.vs);
277                }
278                _ => {}
279            }
280            Ok(!self.discovers)
281        }
282    }
283
284    let mut visitor = Visitor::default();
285    let _ = promql_parser::util::walk_expr(&mut visitor, expr);
286    visitor.discovers
287}
288
289/// Whether `schema` is a series frame's declaration, which describes the columns below it.
290fn publishes_series_frame(schema: &DFSchema) -> bool {
291    schema
292        .metadata()
293        .keys()
294        .any(|key| key.starts_with("greptime.series."))
295}
296
297/// Whether `published` publishes `wanted`'s columns: the same names, in the same order, with the
298/// same types, nullability, per-column metadata and schema metadata.
299///
300/// Qualifiers are not compared: a CTE's plan is read through the alias the CTE registers, which
301/// names every column after the CTE on both routes.
302fn publishes_columns(published: &DFSchema, wanted: &DFSchema) -> bool {
303    published.fields().len() == wanted.fields().len()
304        && published.metadata() == wanted.metadata()
305        && published
306            .iter()
307            .zip(wanted.iter())
308            .all(|((_, published), (_, wanted))| {
309                published.name() == wanted.name()
310                    && published.data_type() == wanted.data_type()
311                    && published.is_nullable() == wanted.is_nullable()
312                    && published.metadata() == wanted.metadata()
313            })
314}
315
316/// The type a column names once its dictionary encoding is taken off.
317///
318/// A label column is dictionary-encoded in the existing planner's plan and plain text in the fused
319/// plan's. That is the one difference between the two answers for the same column that an
320/// expression can carry: a cast reproduces the encoding, and the values stay the same strings.
321fn unwrap_dictionary(data_type: &DataType) -> &DataType {
322    let mut data_type = data_type;
323    while let DataType::Dictionary(_, inner) = data_type {
324        data_type = inner.as_ref();
325    }
326    data_type
327}
328
329/// The native plan, wrapped in the projection that publishes `legacy`'s columns over it.
330///
331/// A hybrid CTE registers the plan as a table the outer SQL query reads, so the columns this plan
332/// publishes *are* the CTE's columns: their names, their order, their types, their nullability and
333/// the metadata they carry are what the statement's SQL sees, and a column list the CTE declares is
334/// applied to them by position. The two routes do not agree on that schema - the fused node takes
335/// its names from the compiled tree and publishes the time index first, while the existing planner
336/// names each value column after the expression it planned and publishes the labels first - so a CTE
337/// answered natively would make one statement mean different things depending on which route planned
338/// it. This wraps the native plan in the projection that publishes the existing planner's answer for
339/// the same statement instead.
340///
341/// The per-row metric-name column a native rows answer declares is not published: the existing
342/// planner never publishes one, so a column list the CTE declares (`tql (ts, val)`) and every
343/// column the outer query reads stay the same on both routes. The name column serves the Prometheus
344/// HTTP response, which reads the plan's own output rather than a CTE.
345///
346/// The projection is made of expressions - an alias per column, and a cast where the two routes carry
347/// the same values in different Arrow types - because that is what survives analysis: the analyzer
348/// rebuilds a projection's schema from its expressions, so anything the projection declared but its
349/// expressions did not carry would be gone by the time the CTE's columns are read.
350///
351/// Columns are paired by the role they play in a rows answer rather than by type alone, because a
352/// series usually carries several labels of the same type:
353/// - the time index is the one column each plan marks as such, and is renamed if the routes name it
354///   differently;
355/// - a label is the native column of the same name, cast where only the dictionary encoding
356///   differs. Every native label has to be published, or the existing plan answers rows without a
357///   label the native answer keeps;
358/// - the value columns are what is left on each side, paired in order, of the same type.
359///
360/// `None` says the plans admit no such pairing - the value columns differ in number or in type, a
361/// label of one plan is missing from the other, or the result does not publish exactly the existing
362/// columns - and the caller then keeps the existing plan rather than publish a column it cannot fill
363/// faithfully.
364fn publish_legacy_schema(native: LogicalPlan, legacy: &LogicalPlan) -> Option<LogicalPlan> {
365    let native_schema = native.schema().clone();
366    let legacy_schema = legacy.schema();
367
368    // A frame's declaration is schema metadata describing the columns under it, and a projection
369    // that renames and reorders them cannot keep it. A statement that publishes one keeps the
370    // existing plan.
371    if publishes_series_frame(native_schema.as_ref()) {
372        return None;
373    }
374    if publishes_columns(native_schema.as_ref(), legacy_schema.as_ref()) {
375        return Some(native);
376    }
377
378    let is_time_index = |field: &arrow_schema::Field| {
379        field
380            .metadata()
381            .contains_key(datatypes::schema::TIME_INDEX_KEY)
382    };
383    let native_fields = native_schema
384        .iter()
385        .map(|(qualifier, field)| (qualifier.cloned(), field))
386        .collect::<Vec<_>>();
387    let mut native_time = None;
388    let mut native_tags = Vec::new();
389    let mut native_values = Vec::new();
390    // The native rows layout publishes every label as `Utf8` and every value as a float or a
391    // histogram (`segment::fused_output_schema`), so the type alone tells the two apart.
392    for (index, (_, field)) in native_fields.iter().enumerate() {
393        if is_time_index(field) {
394            if native_time.replace(index).is_some() {
395                return None;
396            }
397        } else if datatypes::schema::is_metric_name_field(field) {
398            // The per-row name serves the Prometheus response; the existing planner publishes none.
399        } else if field.data_type() == &DataType::Utf8 {
400            native_tags.push(index);
401        } else {
402            native_values.push(index);
403        }
404    }
405    let native_time = native_time?;
406
407    let mut source = vec![None; legacy_schema.fields().len()];
408    let mut legacy_values = Vec::new();
409    let mut paired_tags = 0;
410    let mut legacy_time = false;
411    for (legacy_index, (_, legacy_field)) in legacy_schema.iter().enumerate() {
412        if is_time_index(legacy_field) {
413            if legacy_time {
414                return None;
415            }
416            legacy_time = true;
417            source[legacy_index] = Some(native_time);
418        } else if let Some(&native_index) = native_tags
419            .iter()
420            .find(|&&index| native_fields[index].1.name() == legacy_field.name())
421        {
422            paired_tags += 1;
423            source[legacy_index] = Some(native_index);
424        } else {
425            legacy_values.push(legacy_index);
426        }
427    }
428    if !legacy_time
429        || paired_tags != native_tags.len()
430        || legacy_values.len() != native_values.len()
431    {
432        return None;
433    }
434    for (legacy_index, native_index) in legacy_values.into_iter().zip(native_values) {
435        source[legacy_index] = Some(native_index);
436    }
437
438    let mut exprs = Vec::with_capacity(source.len());
439    for ((_, legacy_field), native_index) in legacy_schema.iter().zip(source) {
440        let (native_qualifier, native_field) = &native_fields[native_index?];
441        if unwrap_dictionary(native_field.data_type())
442            != unwrap_dictionary(legacy_field.data_type())
443        {
444            return None;
445        }
446        let column = DfExpr::Column(datafusion_common::Column::new(
447            native_qualifier.clone(),
448            native_field.name().clone(),
449        ));
450        // A cast only adds or removes the dictionary encoding, so the values stay the same strings.
451        let value = if native_field.data_type() == legacy_field.data_type() {
452            column
453        } else {
454            DfExpr::Cast(datafusion_expr::Cast::new(
455                Box::new(column),
456                legacy_field.data_type().clone(),
457            ))
458        };
459        exprs.push(value.alias(legacy_field.name().clone()));
460    }
461    let plan = LogicalPlanBuilder::from(native)
462        .project(exprs)
463        .ok()?
464        .build()
465        .ok()?;
466    // The published columns are the ones this set out to publish, or the native plan is not used at
467    // all: what a CTE exposes may not change for a reason this did not predict.
468    publishes_columns(plan.schema().as_ref(), legacy_schema.as_ref()).then_some(plan)
469}
470
471pub struct DfLogicalPlanner {
472    engine_state: Arc<QueryEngineState>,
473    session_state: SessionState,
474}
475
476impl DfLogicalPlanner {
477    pub fn new(engine_state: Arc<QueryEngineState>) -> Self {
478        let session_state = engine_state.session_state();
479        Self {
480            engine_state,
481            session_state,
482        }
483    }
484
485    /// Derive a [`SessionState`] whose [`ExecutionProps`] includes
486    /// `query_execution_start_time` if a scheduled time extension is present
487    /// in the query context.
488    fn derive_session_state_with_scheduled_time(
489        &self,
490        query_ctx: QueryContextRef,
491    ) -> Result<QueryEngineContext> {
492        let extensions = query_ctx.extensions();
493        let mut state = match crate::options::parse_scheduled_time_datetime(&extensions)? {
494            Some(dt) => {
495                let execution_props = self
496                    .session_state
497                    .execution_props()
498                    .clone()
499                    .with_query_execution_start_time(dt);
500                SessionStateBuilder::new_from_existing(self.session_state.clone())
501                    .with_execution_props(execution_props)
502                    .build()
503            }
504            None => self.session_state.clone(),
505        };
506        let query_ctx = self
507            .engine_state
508            .apply_query_options(&mut state, query_ctx)?;
509        state.config_mut().set_extension(query_ctx.clone());
510        state.config_mut().set_extension(self.engine_state.clone());
511        state
512            .config_mut()
513            .options_mut()
514            .extensions
515            .insert(ScheduledTimeExtension {
516                scheduled_time: crate::options::scheduled_time_from_ctx(&query_ctx),
517            });
518        let config_options = state.config_options().clone();
519        let _ = state
520            .execution_props_mut()
521            .config_options
522            .insert(config_options);
523        Ok(QueryEngineContext::new(state, query_ctx))
524    }
525
526    /// Basically the same with `explain_to_plan` in DataFusion, but adapted to Greptime's
527    /// `plan_sql` to support Greptime Statements.
528    async fn explain_to_plan(
529        &self,
530        explain: &ExplainStatement,
531        query_ctx: QueryContextRef,
532    ) -> Result<LogicalPlan> {
533        let plan = self.plan_sql(&explain.statement, query_ctx).await?;
534        if matches!(plan, LogicalPlan::Explain(_)) {
535            return plan_err!("Nested EXPLAINs are not supported").context(PlanSqlSnafu);
536        }
537
538        let verbose = explain.verbose;
539        let analyze = explain.analyze;
540        let format = explain.format.map(|f| f.to_string());
541
542        let plan = Arc::new(plan);
543        let schema = LogicalPlan::explain_schema();
544        let schema = ToDFSchema::to_dfschema_ref(schema)?;
545
546        if verbose && format.is_some() {
547            return plan_err!("EXPLAIN VERBOSE with FORMAT is not supported").context(PlanSqlSnafu);
548        }
549
550        if analyze {
551            // notice format is already set in query context, so can be ignore here
552            Ok(LogicalPlan::Analyze(Analyze {
553                verbose,
554                format: ExplainFormat::Indent,
555                input: plan,
556                schema,
557                analyze_level: None,
558                analyze_categories: None,
559            }))
560        } else {
561            let stringified_plans = vec![plan.to_stringified(PlanType::InitialLogicalPlan)];
562
563            let options = self.session_state.config().options();
564            let format = format
565                .map(|x| ExplainFormat::from_str(&x))
566                .transpose()?
567                .unwrap_or_else(|| options.explain.format.clone());
568
569            Ok(LogicalPlan::Explain(Explain {
570                verbose,
571                explain_format: format,
572                plan,
573                stringified_plans,
574                schema,
575                logical_optimization_succeeded: false,
576                show_statistics: None,
577            }))
578        }
579    }
580
581    #[tracing::instrument(skip_all)]
582    #[async_recursion::async_recursion]
583    async fn plan_sql(&self, stmt: &Statement, query_ctx: QueryContextRef) -> Result<LogicalPlan> {
584        let mut planner_context = PlannerContext::new();
585        let mut stmt = Cow::Borrowed(stmt);
586        let mut is_tql_cte = false;
587
588        // handle explain before normal processing so we can explain Greptime Statements
589        if let Statement::Explain(explain) = stmt.as_ref() {
590            return self.explain_to_plan(explain, query_ctx).await;
591        }
592
593        // Check for hybrid CTEs before normal processing
594        if self.has_hybrid_ctes(stmt.as_ref()) {
595            let stmt_owned = stmt.into_owned();
596            let mut query = match stmt_owned {
597                Statement::Query(query) => query.as_ref().clone(),
598                _ => unreachable!("has_hybrid_ctes should only return true for Query statements"),
599            };
600            self.plan_query_with_hybrid_ctes(&query, query_ctx.clone(), &mut planner_context)
601                .await?;
602
603            // remove the processed TQL CTEs from the query
604            query.hybrid_cte = None;
605            stmt = Cow::Owned(Statement::Query(Box::new(query)));
606            is_tql_cte = true;
607        }
608
609        let mut df_stmt = stmt.as_ref().try_into().context(SqlSnafu)?;
610        normalize_field_access_after_subscript(
611            &mut df_stmt,
612            self.session_state
613                .config_options()
614                .sql_parser
615                .enable_ident_normalization,
616        );
617
618        // TODO(LFC): Remove this when Datafusion supports **both** the syntax and implementation of "explain with format".
619        if let datafusion::sql::parser::Statement::Statement(stmt) = &mut df_stmt
620            && matches!(
621                stmt.as_ref(),
622                datafusion::sql::sqlparser::ast::Statement::Explain { .. }
623            )
624        {
625            UnimplementedSnafu {
626                operation: "EXPLAIN with FORMAT using raw datafusion planner",
627            }
628            .fail()?;
629        }
630
631        let engine_context = self.derive_session_state_with_scheduled_time(query_ctx)?;
632        let scheduled_state = engine_context.state().clone();
633        let query_ctx = engine_context.query_ctx();
634        let table_provider = DfTableSourceProvider::new(
635            self.engine_state.catalog_manager().clone(),
636            self.engine_state.disallow_cross_catalog_query(),
637            query_ctx.clone(),
638            Arc::new(DefaultPlanDecoder::new(
639                scheduled_state.clone(),
640                &query_ctx,
641            )?),
642            scheduled_state
643                .config_options()
644                .sql_parser
645                .enable_ident_normalization,
646        );
647
648        let context_provider = DfContextProviderAdapter::try_new(
649            self.engine_state.clone(),
650            scheduled_state.clone(),
651            Some(&df_stmt),
652            query_ctx.clone(),
653        )
654        .await?;
655
656        let config_options = scheduled_state.config().options();
657        let parser_options = &config_options.sql_parser;
658        let parser_options = ParserOptions {
659            map_string_types_to_utf8view: false,
660            ..parser_options.into()
661        };
662
663        let sql_to_rel = SqlToRel::new_with_options(&context_provider, parser_options);
664
665        // this IF is to handle different version of ASTs
666        let result = if is_tql_cte {
667            let Statement::Query(query) = stmt.into_owned() else {
668                unreachable!("is_tql_cte should only be true for Query statements");
669            };
670            let sqlparser_stmt = sqlparser::ast::Statement::Query(Box::new(query.inner));
671            sql_to_rel
672                .sql_statement_to_plan_with_context(sqlparser_stmt, &mut planner_context)
673                .context(PlanSqlSnafu)?
674        } else {
675            sql_to_rel
676                .statement_to_plan(df_stmt)
677                .context(PlanSqlSnafu)?
678        };
679
680        expr_depth::validate_plan(&result)?;
681        common_telemetry::debug!("Logical planner, statement to plan result: {result}");
682        let plan = RangePlanRewriter::new(table_provider, query_ctx.clone())
683            .rewrite(result)
684            .await?;
685
686        // Optimize logical plan by extension rules
687        let plan = self
688            .engine_state
689            .optimize_by_extension_rules(plan, &engine_context)?;
690        common_telemetry::debug!("Logical planner, optimize result: {plan}");
691
692        Ok(plan)
693    }
694
695    /// Generate a relational expression from a SQL expression
696    #[tracing::instrument(skip_all)]
697    pub(crate) async fn sql_to_expr(
698        &self,
699        sql: SqlExpr,
700        schema: &DFSchema,
701        normalize_ident: bool,
702        query_ctx: QueryContextRef,
703    ) -> Result<DfExpr> {
704        let engine_context = self.derive_session_state_with_scheduled_time(query_ctx)?;
705        let query_ctx = engine_context.query_ctx();
706        let context_provider = DfContextProviderAdapter::try_new(
707            self.engine_state.clone(),
708            engine_context.state().clone(),
709            None,
710            query_ctx,
711        )
712        .await?;
713
714        let config_options = engine_context.state().config().options();
715        let parser_options = &config_options.sql_parser;
716        let parser_options: ParserOptions = ParserOptions {
717            map_string_types_to_utf8view: false,
718            enable_ident_normalization: normalize_ident,
719            ..parser_options.into()
720        };
721
722        let sql_to_rel = SqlToRel::new_with_options(&context_provider, parser_options);
723
724        Ok(sql_to_rel.sql_to_expr(sql, schema, &mut PlannerContext::new())?)
725    }
726
727    /// Plans a PromQL statement, offering it to the native fused-series route when the statement
728    /// may take it and the query options it is planned with ask for it.
729    ///
730    /// `native_route_allowed` states whether the statement may take the route at all: it is off
731    /// only when [`Self::plan_pql_relation`] plans the existing plan whose columns it publishes.
732    /// Everything else the route depends on is read from the query options snapshot the
733    /// statement is planned with, where every option is already resolved as request > session
734    /// `SET` > engine default.
735    #[tracing::instrument(skip_all)]
736    async fn plan_pql(
737        &self,
738        stmt: &EvalStmt,
739        query_ctx: QueryContextRef,
740        native_route_allowed: bool,
741    ) -> Result<LogicalPlan> {
742        let engine_context = self.derive_session_state_with_scheduled_time(query_ctx)?;
743        let query_ctx = engine_context.query_ctx();
744        let mut scheduled_state = engine_context.state().clone();
745        // Whether the distributed planner may fall back to the fallback plan rewriter. A fallback
746        // rewriter can wrap a native region scan in an unusable MergeScan, so the native route is
747        // only offered to a query that cannot fall back.
748        //
749        // `apply_query_options` above resolved the three sources this used to disjoin - the engine
750        // option, the session `allow_query_fallback` variable and the `query_fallback` hint - into
751        // this extension, so the read happens here instead. One mainline semantic is kept: a stated
752        // `false` overrides the engine default rather than leaving it on.
753        let allow_query_fallback = scheduled_state
754            .config_options()
755            .extensions
756            .get::<DistPlannerOptions>()
757            .is_some_and(|options| options.allow_query_fallback);
758        // Whether the statement is offered to the native fused-series compiler. This is the second,
759        // independent switch: it states what the query asks for, and no source of it is derived
760        // from the fallback option.
761        let native_promql = scheduled_state
762            .config_options()
763            .extensions
764            .get::<NativePromqlExtension>()
765            .is_some_and(|options| options.requested);
766        let promql_annotations = query_ctx.remote_query_id().map(promql_annotation_collector);
767        if let Some(collector) = &promql_annotations {
768            scheduled_state
769                .config_mut()
770                .options_mut()
771                .extensions
772                .insert(collector.clone());
773        }
774        let plan_decoder = Arc::new(DefaultPlanDecoder::new(
775            scheduled_state.clone(),
776            &query_ctx,
777        )?);
778        let table_provider = || {
779            DfTableSourceProvider::new(
780                self.engine_state.catalog_manager().clone(),
781                self.engine_state.disallow_cross_catalog_query(),
782                query_ctx.clone(),
783                plan_decoder.clone(),
784                scheduled_state
785                    .config_options()
786                    .sql_parser
787                    .enable_ident_normalization,
788            )
789        };
790        let native_requested = native_route_allowed && !allow_query_fallback && native_promql;
791        let plan = PromPlanner::stmt_to_plan_with_annotations(
792            table_provider(),
793            stmt,
794            &self.engine_state,
795            promql_annotations.clone(),
796            // A fallback rewriter can wrap a native region scan in an unusable MergeScan.
797            native_requested,
798        )
799        .await
800        .map_err(BoxedError::new)
801        .context(QueryPlanSnafu)?;
802
803        // A distributed planner plans a native statement over per-selector raw sources, and a
804        // statement that reads no table needs none. Anything else keeps the existing plan. Decide
805        // while the original statement is still available: physical planning cannot fall back
806        // safely. An engine with no distributed planner plans no region, so there is nothing to
807        // admit its plan against.
808        let plan = if native_requested
809            && self.engine_state.with_dist_planner()
810            && !remote_native_raw_plan_supported(&plan)
811        {
812            PromPlanner::stmt_to_plan_with_annotations(
813                table_provider(),
814                stmt,
815                &self.engine_state,
816                promql_annotations,
817                false,
818            )
819            .await
820            .map_err(BoxedError::new)
821            .context(QueryPlanSnafu)?
822        } else {
823            plan
824        };
825        let context = QueryEngineContext::new(scheduled_state, query_ctx);
826        Ok(self
827            .engine_state
828            .optimize_by_extension_rules(plan, &context)?)
829    }
830
831    #[tracing::instrument(skip_all)]
832    fn optimize_logical_plan(&self, plan: LogicalPlan) -> Result<LogicalPlan> {
833        Ok(self.engine_state.optimize_logical_plan(plan)?)
834    }
835
836    /// Check if a statement contains hybrid CTEs (mix of SQL and TQL)
837    fn has_hybrid_ctes(&self, stmt: &Statement) -> bool {
838        if let Statement::Query(query) = stmt {
839            query
840                .hybrid_cte
841                .as_ref()
842                .map(|hybrid_cte| !hybrid_cte.cte_tables.is_empty())
843                .unwrap_or(false)
844        } else {
845            false
846        }
847    }
848
849    /// Plan a query with hybrid CTEs using DataFusion's native PlannerContext
850    async fn plan_query_with_hybrid_ctes(
851        &self,
852        query: &Query,
853        query_ctx: QueryContextRef,
854        planner_context: &mut PlannerContext,
855    ) -> Result<()> {
856        let hybrid_cte = query.hybrid_cte.as_ref().unwrap();
857
858        for cte in &hybrid_cte.cte_tables {
859            match &cte.content {
860                CteContent::Tql(tql) => {
861                    // Plan TQL and register in PlannerContext
862                    let mut logical_plan = self.tql_to_logical_plan(tql, query_ctx.clone()).await?;
863                    if !cte.columns.is_empty() {
864                        let schema = logical_plan.schema();
865                        let schema_fields = schema.fields().to_vec();
866                        ensure!(
867                            schema_fields.len() == cte.columns.len(),
868                            CteColumnSchemaMismatchSnafu {
869                                cte_name: cte.name.value.clone(),
870                                original: schema_fields
871                                    .iter()
872                                    .map(|field| field.name().clone())
873                                    .collect::<Vec<_>>(),
874                                expected: cte
875                                    .columns
876                                    .iter()
877                                    .map(|column| column.to_string())
878                                    .collect::<Vec<_>>(),
879                            }
880                        );
881                        let aliases = cte
882                            .columns
883                            .iter()
884                            .zip(schema_fields.iter())
885                            .map(|(column, field)| col(field.name()).alias(column.to_string()));
886                        logical_plan = LogicalPlanBuilder::from(logical_plan)
887                            .project(aliases)
888                            .context(PlanSqlSnafu)?
889                            .build()
890                            .context(PlanSqlSnafu)?;
891                    }
892
893                    // Wrap in SubqueryAlias to ensure proper table qualification for CTE
894                    logical_plan = LogicalPlan::SubqueryAlias(
895                        datafusion_expr::SubqueryAlias::try_new(
896                            Arc::new(logical_plan),
897                            cte.name.value.clone(),
898                        )
899                        .context(PlanSqlSnafu)?,
900                    );
901
902                    planner_context.insert_cte(&cte.name.value, logical_plan);
903                }
904                CteContent::Sql(_) => {
905                    // SQL CTEs should have been moved to the main query's WITH clause
906                    // during parsing, so we shouldn't encounter them here
907                    unreachable!("SQL CTEs should not be in hybrid_cte.cte_tables");
908                }
909            }
910        }
911
912        Ok(())
913    }
914
915    /// Plans a PromQL statement whose output is read by SQL: a hybrid CTE or a flow's sink rows.
916    async fn plan_pql_relation(
917        &self,
918        eval: &EvalStmt,
919        query_ctx: QueryContextRef,
920    ) -> Result<LogicalPlan> {
921        let plan = self.plan_pql(eval, query_ctx.clone(), true).await?;
922        if !contains_native_fused(&plan) {
923            // The route was not taken - it is off for this query, or it declined this shape - so
924            // this is the existing plan, which already publishes the existing columns.
925            return Ok(plan);
926        }
927        // The existing planner refuses a selector that names no metric, so the native answer's own
928        // columns are the relation's. A series frame is not a table SQL reads, so it still goes to
929        // the existing planner, which refuses it.
930        if discovers_any_metric(&eval.expr) && !publishes_series_frame(plan.schema()) {
931            return Ok(plan);
932        }
933        // The relation's columns are SQL-visible, and this route names and orders its output its own
934        // way, so its own schema cannot stand in for the existing planner's: plan the statement for
935        // that schema and publish it over the native answer. A statement whose columns that
936        // projection cannot fill faithfully keeps the existing plan instead of changing the schema
937        // the relation exposes.
938        let existing = self.plan_pql(eval, query_ctx, false).await?;
939        Ok(publish_legacy_schema(plan, &existing).unwrap_or(existing))
940    }
941
942    /// Convert TQL to LogicalPlan directly
943    async fn tql_to_logical_plan(
944        &self,
945        tql: &Tql,
946        query_ctx: QueryContextRef,
947    ) -> Result<LogicalPlan> {
948        match tql {
949            Tql::Eval(eval) => {
950                // Convert TqlEval to PromQuery then to QueryStatement::Promql
951                let prom_query = PromQuery {
952                    query: eval.query.clone(),
953                    start: eval.start.clone(),
954                    end: eval.end.clone(),
955                    step: eval.step.clone(),
956                    lookback: eval
957                        .lookback
958                        .clone()
959                        .unwrap_or_else(|| DEFAULT_LOOKBACK_STRING.to_string()),
960                    alias: eval.alias.clone(),
961                };
962                let stmt = QueryLanguageParser::parse_promql(&prom_query, &query_ctx)?;
963                // A hybrid CTE registers this plan as a table the outer SQL query reads, so the
964                // `FusedSeries` node sits under a SQL alias and projection instead of at the plan
965                // root. Neither decides where a fused subtree runs: placement asks whether the
966                // node's own contract allows a region to run it, and the column requirements a
967                // node above makes are enforced by their lineage rather than by the shape of the
968                // subtree they travel through, so an alias or projection over the CTE does not
969                // block a multi-input fused subtree. The route is therefore offered here like it
970                // is for a top-level statement.
971                let QueryStatement::Promql(eval, _alias) = &stmt else {
972                    unreachable!("a TQL eval parses to a PromQL statement");
973                };
974                self.plan_pql_relation(eval, query_ctx).await
975            }
976            Tql::Explain(_) => UnimplementedSnafu {
977                operation: "TQL EXPLAIN in CTEs",
978            }
979            .fail(),
980            Tql::Analyze(_) => UnimplementedSnafu {
981                operation: "TQL ANALYZE in CTEs",
982            }
983            .fail(),
984        }
985    }
986
987    /// Extracts cast types for all placeholders in a logical plan.
988    /// Returns a map where each placeholder ID is mapped to:
989    /// - Some(DataType) if the placeholder is cast to a specific type
990    /// - None if the placeholder exists but has no cast
991    ///
992    /// Example: `$1::TEXT` returns `{"$1": Some(DataType::Utf8)}`
993    ///
994    /// This function walks through all expressions in the logical plan,
995    /// including subqueries, to identify placeholders and their cast types.
996    fn extract_placeholder_cast_types(
997        plan: &LogicalPlan,
998    ) -> Result<HashMap<String, Option<DataType>>> {
999        let mut placeholder_types = HashMap::new();
1000        let mut casted_placeholders = HashSet::new();
1001
1002        Self::extract_from_plan(plan, &mut placeholder_types, &mut casted_placeholders)?;
1003
1004        Ok(placeholder_types)
1005    }
1006
1007    fn extract_from_plan(
1008        plan: &LogicalPlan,
1009        placeholder_types: &mut HashMap<String, Option<DataType>>,
1010        casted_placeholders: &mut HashSet<String>,
1011    ) -> Result<()> {
1012        plan.apply(|node| {
1013            for expr in node.expressions() {
1014                let _ = expr.apply(|e| {
1015                    // Handle casted placeholders
1016                    if let DfExpr::Cast(cast) = e
1017                        && let DfExpr::Placeholder(ph) = &*cast.expr
1018                    {
1019                        placeholder_types
1020                            .insert(ph.id.clone(), Some(cast.field.data_type().clone()));
1021                        casted_placeholders.insert(ph.id.clone());
1022                    }
1023
1024                    // Handle arrow_cast(Placeholder, 'type_string') generated by SQL rewriter
1025                    if let DfExpr::ScalarFunction(scalar_func) = e
1026                        && scalar_func.name() == "arrow_cast"
1027                        && scalar_func.args.len() == 2
1028                        && let DfExpr::Placeholder(ph) = &scalar_func.args[0]
1029                        && let DfExpr::Literal(ScalarValue::Utf8(Some(type_str)), _) =
1030                            &scalar_func.args[1]
1031                        && let Ok(data_type) = type_str.parse::<DataType>()
1032                    {
1033                        placeholder_types.insert(ph.id.clone(), Some(data_type));
1034                        casted_placeholders.insert(ph.id.clone());
1035                    }
1036
1037                    // Handle bare (non-casted) placeholders
1038                    if let DfExpr::Placeholder(ph) = e
1039                        && !casted_placeholders.contains(&ph.id)
1040                        && !placeholder_types.contains_key(&ph.id)
1041                    {
1042                        placeholder_types.insert(ph.id.clone(), None);
1043                    }
1044
1045                    // Recurse into subquery plans embedded in expressions
1046                    match e {
1047                        DfExpr::Exists(Exists { subquery, .. })
1048                        | DfExpr::InSubquery(InSubquery { subquery, .. })
1049                        | DfExpr::ScalarSubquery(subquery) => {
1050                            Self::extract_from_plan(
1051                                &subquery.subquery,
1052                                placeholder_types,
1053                                casted_placeholders,
1054                            )?;
1055                        }
1056                        _ => {}
1057                    }
1058
1059                    Ok(TreeNodeRecursion::Continue)
1060                });
1061            }
1062            Ok(TreeNodeRecursion::Continue)
1063        })?;
1064        Ok(())
1065    }
1066
1067    fn infer_limit_placeholder_types(
1068        plan: &LogicalPlan,
1069        placeholder_types: &mut HashMap<String, Option<DataType>>,
1070    ) -> Result<()> {
1071        plan.apply(|node| {
1072            if let LogicalPlan::Limit(limit) = node {
1073                for expr in limit.skip.iter().chain(limit.fetch.iter()) {
1074                    expr.apply(|e| {
1075                        if let DfExpr::Placeholder(ph) = e {
1076                            placeholder_types
1077                                .entry(ph.id.clone())
1078                                .and_modify(|existing| {
1079                                    if existing.is_none() {
1080                                        *existing = Some(DataType::Int64);
1081                                    }
1082                                })
1083                                .or_insert(Some(DataType::Int64));
1084                        }
1085
1086                        Ok(TreeNodeRecursion::Continue)
1087                    })?;
1088                }
1089            }
1090
1091            Ok(TreeNodeRecursion::Continue)
1092        })?;
1093
1094        Ok(())
1095    }
1096
1097    /// Gets inferred parameter types from a logical plan.
1098    /// Returns a map where each parameter ID is mapped to:
1099    /// - Some(DataType) if the parameter type could be inferred
1100    /// - None if the parameter type could not be inferred
1101    ///
1102    /// This function first uses DataFusion's `get_parameter_types()` to infer types.
1103    /// If any parameters have `None` values (i.e., DataFusion couldn't infer their types),
1104    /// it falls back to using `extract_placeholder_cast_types()` to detect explicit casts
1105    /// and applies context-specific inference such as LIMIT/OFFSET placeholders.
1106    ///
1107    /// This is because datafusion can only infer types for a limited cases.
1108    ///
1109    /// Example: For query `WHERE $1::TEXT AND $2`, DataFusion may not infer `$2`'s type,
1110    /// but this function will return `{"$1": Some(DataType::Utf8), "$2": None}`.
1111    pub fn get_inferred_parameter_types(
1112        plan: &LogicalPlan,
1113    ) -> Result<HashMap<String, Option<DataType>>> {
1114        let mut param_types = plan.get_parameter_types().context(PlanSqlSnafu)?;
1115
1116        let has_none = param_types.values().any(|v| v.is_none());
1117
1118        if has_none {
1119            let cast_types = Self::extract_placeholder_cast_types(plan)?;
1120
1121            for (id, opt_type) in cast_types {
1122                param_types
1123                    .entry(id)
1124                    .and_modify(|existing| {
1125                        if existing.is_none() {
1126                            *existing = opt_type.clone();
1127                        }
1128                    })
1129                    .or_insert(opt_type);
1130            }
1131
1132            Self::infer_limit_placeholder_types(plan, &mut param_types)?;
1133        }
1134
1135        Ok(param_types)
1136    }
1137}
1138
1139/// Normalizes dot field accesses that follow a subscript for DataFusion.
1140///
1141/// sqlparser represents `j.o.l[1].inner.l[2]` as a compound field access with
1142/// the following access chain:
1143///
1144/// ```text
1145/// Dot(Identifier("o")),
1146/// Dot(Identifier("l")),
1147/// Subscript(1),
1148/// Dot(Identifier("inner")),
1149/// Dot(Identifier("l")),
1150/// Subscript(2)
1151/// ```
1152///
1153/// DataFusion first resolves the leading `j.o.l` through
1154/// `JsonExprPlanner::plan_compound_identifier`, which produces an untyped
1155/// `json_get` with path `$.o.l`. Before invoking `JsonExprPlanner::plan_field_access`,
1156/// however, DataFusion eagerly converts every remaining access into a
1157/// `GetFieldAccess`. It accepts string values but not [`SqlExpr::Identifier`]s
1158/// in [`AccessExpr::Dot`] after a subscript. Without this normalization, that
1159/// conversion fails at `.inner`, and `plan_field_access` is never called, even
1160/// for the preceding `[1]`.
1161///
1162/// This function converts dot identifiers after the first subscript into
1163/// `Dot(Value(SingleQuotedString(...)))`, applying DataFusion's identifier
1164/// normalization before discarding whether each identifier was quoted. It
1165/// changes neither the SQL text nor the dot accesses into subscript nodes: the
1166/// resulting AST is conceptually `j.o.l[1].'inner'.'l'[2]`. DataFusion converts
1167/// the string-valued dot accesses into named field accesses, which
1168/// `plan_field_access` safely encodes as dot members, quoting names when needed. It can then extend the
1169/// JSON path to `$.o.l[1].inner.l[2]`.
1170///
1171/// This behavior is unchanged in the latest upstream releases checked here:
1172/// DataFusion 55.0.0 and sqlparser 0.62.0.
1173///
1174/// TODO(LFC): Remove this workaround after upstream supports dot identifiers after subscripts.
1175fn normalize_field_access_after_subscript(stmt: &mut DfStatement, normalize_ident: bool) {
1176    let DfStatement::Statement(stmt) = stmt else {
1177        return;
1178    };
1179    let normalizer = IdentNormalizer::new(normalize_ident);
1180
1181    let _ = visit_expressions_mut(stmt.as_mut(), |expr| {
1182        let SqlExpr::CompoundFieldAccess { access_chain, .. } = expr else {
1183            return ControlFlow::<()>::Continue(());
1184        };
1185        let Some(index) = access_chain
1186            .iter()
1187            .position(|x| matches!(x, AccessExpr::Subscript(_)))
1188        else {
1189            return ControlFlow::Continue(());
1190        };
1191
1192        for access in &mut access_chain[index + 1..] {
1193            let AccessExpr::Dot(SqlExpr::Identifier(ident)) = access else {
1194                continue;
1195            };
1196            let value = normalizer.normalize(ident.clone());
1197            *access = AccessExpr::Dot(SqlExpr::Value(
1198                Value::SingleQuotedString(value).with_span(ident.span),
1199            ));
1200        }
1201        ControlFlow::Continue(())
1202    });
1203}
1204
1205#[async_trait]
1206impl LogicalPlanner for DfLogicalPlanner {
1207    #[tracing::instrument(skip_all)]
1208    async fn plan(&self, stmt: &QueryStatement, query_ctx: QueryContextRef) -> Result<LogicalPlan> {
1209        match stmt {
1210            QueryStatement::Sql(stmt) => self.plan_sql(stmt, query_ctx).await,
1211            // The statement's own plan is what a region receives, so the native route is offered.
1212            QueryStatement::Promql(stmt, _alias) => self.plan_pql(stmt, query_ctx, true).await,
1213        }
1214    }
1215
1216    async fn plan_relation(
1217        &self,
1218        stmt: &QueryStatement,
1219        query_ctx: QueryContextRef,
1220    ) -> Result<LogicalPlan> {
1221        match stmt {
1222            QueryStatement::Sql(stmt) => self.plan_sql(stmt, query_ctx).await,
1223            QueryStatement::Promql(stmt, _alias) => self.plan_pql_relation(stmt, query_ctx).await,
1224        }
1225    }
1226
1227    async fn plan_logs_query(
1228        &self,
1229        query: LogQuery,
1230        query_ctx: QueryContextRef,
1231    ) -> Result<LogicalPlan> {
1232        let engine_context = self.derive_session_state_with_scheduled_time(query_ctx)?;
1233        let query_ctx = engine_context.query_ctx();
1234        let state = engine_context.state().clone();
1235        let plan_decoder = Arc::new(DefaultPlanDecoder::new(state.clone(), &query_ctx)?);
1236        let table_provider = DfTableSourceProvider::new(
1237            self.engine_state.catalog_manager().clone(),
1238            self.engine_state.disallow_cross_catalog_query(),
1239            query_ctx,
1240            plan_decoder,
1241            state.config_options().sql_parser.enable_ident_normalization,
1242        );
1243
1244        let mut planner = LogQueryPlanner::new(table_provider, state);
1245        planner
1246            .query_to_plan(query)
1247            .await
1248            .map_err(BoxedError::new)
1249            .context(QueryPlanSnafu)
1250    }
1251
1252    fn optimize(&self, plan: LogicalPlan) -> Result<LogicalPlan> {
1253        self.optimize_logical_plan(plan)
1254    }
1255
1256    fn as_any(&self) -> &dyn Any {
1257        self
1258    }
1259}
1260
1261#[cfg(test)]
1262mod tests {
1263    use std::sync::Arc;
1264
1265    use arrow_schema::DataType;
1266    use catalog::RegisterTableRequest;
1267    use catalog::memory::MemoryCatalogManager;
1268    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
1269    use common_query::OutputData;
1270    use common_recordbatch::RecordBatch;
1271    use common_recordbatch::util::collect_batches;
1272    use common_time::Timezone;
1273    use datatypes::arrow::array::{Array, Float64Array, StringArray};
1274    use datatypes::prelude::ConcreteDataType;
1275    use datatypes::schema::{ColumnSchema, Schema};
1276    use session::context::{
1277        MetricDiscoveryScope, QueryContext, QueryContextBuilder, QueryContextRef,
1278    };
1279    use store_api::metric_engine_consts::{
1280        DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, LOGICAL_TABLE_METADATA_KEY,
1281        METRIC_ENGINE_NAME,
1282    };
1283    use table::metadata::{TableInfoBuilder, TableMetaBuilder};
1284    use table::test_util::EmptyTable;
1285
1286    use super::*;
1287    use crate::datafusion::QUERY_FALLBACK_HINT;
1288    use crate::parser::{PromQuery, QueryLanguageParser};
1289    use crate::promql::planner::NATIVE_PROMQL_EXTENSION_KEY;
1290    use crate::{QueryEngineFactory, QueryEngineRef};
1291
1292    async fn create_test_engine() -> QueryEngineRef {
1293        let columns = vec![
1294            ColumnSchema::new("id", ConcreteDataType::int32_datatype(), false),
1295            ColumnSchema::new("name", ConcreteDataType::string_datatype(), true),
1296        ];
1297        let schema = Arc::new(Schema::new(columns));
1298        let table_meta = TableMetaBuilder::empty()
1299            .schema(schema)
1300            .primary_key_indices(vec![0])
1301            .value_indices(vec![1])
1302            .next_column_id(1024)
1303            .build()
1304            .unwrap();
1305        let table_info = TableInfoBuilder::new("test", table_meta).build().unwrap();
1306        let table = EmptyTable::from_table_info(&table_info);
1307
1308        crate::tests::new_query_engine_with_table(table)
1309    }
1310
1311    async fn create_timestamp_test_engine() -> QueryEngineRef {
1312        let columns = vec![
1313            ColumnSchema::new(
1314                "ts",
1315                ConcreteDataType::timestamp_millisecond_datatype(),
1316                false,
1317            )
1318            .with_time_index(true),
1319            ColumnSchema::new(
1320                "st",
1321                ConcreteDataType::timestamp_millisecond_datatype(),
1322                false,
1323            ),
1324            ColumnSchema::new("note", ConcreteDataType::string_datatype(), true),
1325            ColumnSchema::new(
1326                "ts_ns",
1327                ConcreteDataType::timestamp_nanosecond_datatype(),
1328                true,
1329            ),
1330        ];
1331        let schema = Arc::new(Schema::new(columns));
1332        let table_meta = TableMetaBuilder::empty()
1333            .schema(schema)
1334            .primary_key_indices(vec![])
1335            .value_indices(vec![0, 1, 2, 3])
1336            .next_column_id(1024)
1337            .build()
1338            .unwrap();
1339        let table_info = TableInfoBuilder::new("timestamps", table_meta)
1340            .build()
1341            .unwrap();
1342        let table = EmptyTable::from_table_info(&table_info);
1343
1344        crate::tests::new_query_engine_with_table(table)
1345    }
1346
1347    fn create_promql_test_engine() -> QueryEngineRef {
1348        create_promql_test_engine_with(crate::options::QueryOptions::default(), false)
1349    }
1350
1351    /// The PromQL fixture, additionally stating the engine options and whether it plans distributed
1352    /// statements.
1353    fn create_promql_test_engine_with(
1354        query_options: crate::options::QueryOptions,
1355        with_dist_planner: bool,
1356    ) -> QueryEngineRef {
1357        let catalog_manager = MemoryCatalogManager::with_default_setup();
1358        let physical_table_name = "phy";
1359        let physical_table_id = 999u32;
1360
1361        let physical_schema = Arc::new(Schema::new(vec![
1362            ColumnSchema::new(
1363                DATA_SCHEMA_TABLE_ID_COLUMN_NAME.to_string(),
1364                ConcreteDataType::uint32_datatype(),
1365                false,
1366            ),
1367            ColumnSchema::new(
1368                DATA_SCHEMA_TSID_COLUMN_NAME.to_string(),
1369                ConcreteDataType::uint64_datatype(),
1370                false,
1371            ),
1372            ColumnSchema::new("tag_0", ConcreteDataType::string_datatype(), false),
1373            ColumnSchema::new("tag_1", ConcreteDataType::string_datatype(), false),
1374            ColumnSchema::new(
1375                "timestamp",
1376                ConcreteDataType::timestamp_millisecond_datatype(),
1377                false,
1378            )
1379            .with_time_index(true),
1380            ColumnSchema::new("field_0", ConcreteDataType::float64_datatype(), true),
1381        ]));
1382        let physical_meta = TableMetaBuilder::empty()
1383            .schema(physical_schema)
1384            .primary_key_indices(vec![0, 1, 2, 3])
1385            .value_indices(vec![4, 5])
1386            .engine(METRIC_ENGINE_NAME.to_string())
1387            .next_column_id(1024)
1388            .build()
1389            .unwrap();
1390        let physical_info = TableInfoBuilder::default()
1391            .table_id(physical_table_id)
1392            .name(physical_table_name)
1393            .meta(physical_meta)
1394            .build()
1395            .unwrap();
1396        catalog_manager
1397            .register_table_sync(RegisterTableRequest {
1398                catalog: DEFAULT_CATALOG_NAME.to_string(),
1399                schema: DEFAULT_SCHEMA_NAME.to_string(),
1400                table_name: physical_table_name.to_string(),
1401                table_id: physical_table_id,
1402                table: EmptyTable::from_table_info(&physical_info),
1403            })
1404            .unwrap();
1405
1406        let mut options = table::requests::TableOptions::default();
1407        options.extra_options.insert(
1408            LOGICAL_TABLE_METADATA_KEY.to_string(),
1409            physical_table_name.to_string(),
1410        );
1411        let logical_schema = Arc::new(Schema::new(vec![
1412            ColumnSchema::new("tag_0", ConcreteDataType::string_datatype(), false),
1413            ColumnSchema::new("tag_1", ConcreteDataType::string_datatype(), false),
1414            ColumnSchema::new(
1415                "timestamp",
1416                ConcreteDataType::timestamp_millisecond_datatype(),
1417                false,
1418            )
1419            .with_time_index(true),
1420            ColumnSchema::new("field_0", ConcreteDataType::float64_datatype(), true),
1421        ]));
1422        let logical_meta = TableMetaBuilder::empty()
1423            .schema(logical_schema)
1424            .primary_key_indices(vec![0, 1])
1425            .value_indices(vec![3])
1426            .engine(METRIC_ENGINE_NAME.to_string())
1427            .options(options)
1428            .next_column_id(1024)
1429            .build()
1430            .unwrap();
1431        let logical_info = TableInfoBuilder::default()
1432            .table_id(1024)
1433            .name("some_metric")
1434            .meta(logical_meta)
1435            .build()
1436            .unwrap();
1437        catalog_manager
1438            .register_table_sync(RegisterTableRequest {
1439                catalog: DEFAULT_CATALOG_NAME.to_string(),
1440                schema: DEFAULT_SCHEMA_NAME.to_string(),
1441                table_name: "some_metric".to_string(),
1442                table_id: 1024,
1443                table: EmptyTable::from_table_info(&logical_info),
1444            })
1445            .unwrap();
1446        let mut other_info = logical_info.clone();
1447        other_info.ident.table_id = 1025;
1448        other_info.name = "other_metric".to_string();
1449        catalog_manager
1450            .register_table_sync(RegisterTableRequest {
1451                catalog: DEFAULT_CATALOG_NAME.to_string(),
1452                schema: DEFAULT_SCHEMA_NAME.to_string(),
1453                table_name: other_info.name.clone(),
1454                table_id: other_info.ident.table_id,
1455                table: EmptyTable::from_table_info(&other_info),
1456            })
1457            .unwrap();
1458
1459        QueryEngineFactory::try_new_with_plugins(
1460            catalog_manager,
1461            None,
1462            None,
1463            None,
1464            None,
1465            None,
1466            with_dist_planner,
1467            Default::default(),
1468            query_options,
1469        )
1470        .unwrap()
1471        .query_engine()
1472    }
1473
1474    async fn parse_sql_to_plan(sql: &str) -> LogicalPlan {
1475        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
1476        let engine = create_test_engine().await;
1477        engine
1478            .planner()
1479            .plan(&stmt, QueryContext::arc())
1480            .await
1481            .unwrap()
1482    }
1483
1484    async fn parse_promql_to_plan(query: &str) -> LogicalPlan {
1485        let engine = create_promql_test_engine();
1486        let query_ctx = QueryContext::arc();
1487        let stmt = QueryLanguageParser::parse_promql(
1488            &PromQuery {
1489                query: query.to_string(),
1490                start: "0".to_string(),
1491                end: "10".to_string(),
1492                step: "5s".to_string(),
1493                lookback: "300s".to_string(),
1494                alias: None,
1495            },
1496            &query_ctx,
1497        )
1498        .unwrap();
1499
1500        engine.planner().plan(&stmt, query_ctx).await.unwrap()
1501    }
1502
1503    /// Plans `rate(some_metric[5m])`, which the in-process fixture plans natively, stating the
1504    /// query options the caller asks for: the engine-wide defaults, one session `SET` and one
1505    /// request extension. These are the sources the planning snapshot resolves, in that order.
1506    async fn plan_native_promql_with_query_options(
1507        engine_options: crate::options::QueryOptions,
1508        session: Option<(&str, &str)>,
1509        request: Option<(&str, &str)>,
1510    ) -> crate::error::Result<String> {
1511        let engine = create_promql_test_engine_with(
1512            engine_options,
1513            // The route a deployed frontend plans: a distributed planner over its regions.
1514            true,
1515        );
1516        let mut builder = QueryContextBuilder::default();
1517        if let Some((key, value)) = request {
1518            builder = builder.set_extension(key.to_string(), value.to_string());
1519        }
1520        // The session state a query is sent with, as `SET` leaves it.
1521        let query_ctx = builder.build();
1522        if let Some((key, value)) = session {
1523            query_ctx
1524                .configuration_parameter()
1525                .set_query_option(key, value)
1526                .unwrap();
1527        }
1528        let query_ctx = Arc::new(query_ctx);
1529        let stmt = QueryLanguageParser::parse_promql(
1530            &PromQuery {
1531                query: "rate(some_metric[5m])".to_string(),
1532                start: "0".to_string(),
1533                end: "10".to_string(),
1534                step: "5s".to_string(),
1535                lookback: "300s".to_string(),
1536                alias: None,
1537            },
1538            &query_ctx,
1539        )
1540        .unwrap();
1541
1542        engine
1543            .planner()
1544            .plan(&stmt, query_ctx)
1545            .await
1546            .map(|plan| plan.display_indent().to_string())
1547    }
1548
1549    /// The native route follows the query options the snapshot resolves: the request, then the
1550    /// session `SET`, then the engine-wide default. Only that one value decides, so a session that
1551    /// says `true` routes natively with no request hint and the engine default off, and a request
1552    /// that says `false` leaves the route however the other two are set.
1553    #[tokio::test]
1554    async fn test_plan_pql_native_route_follows_query_options() {
1555        // (engine default, session `SET`, request hint, native route admitted)
1556        for (engine_default, session, request, native) in [
1557            // Nothing states the option: the engine default decides.
1558            (false, None, None, false),
1559            (true, None, None, true),
1560            // A session `SET` alone enables the route while the engine default stays off.
1561            (false, Some("true"), None, true),
1562            // A request over the session value, in both directions.
1563            (false, Some("true"), Some("false"), false),
1564            (false, Some("false"), Some("true"), true),
1565            // Over the engine default too, in both directions.
1566            (true, Some("false"), None, false),
1567            (true, Some("true"), Some("false"), false),
1568            (false, None, Some("true"), true),
1569        ] {
1570            let plan = plan_native_promql_with_query_options(
1571                crate::options::QueryOptions {
1572                    experimental_native_promql: engine_default,
1573                    ..Default::default()
1574                },
1575                session.map(|value| (NATIVE_PROMQL_EXTENSION_KEY, value)),
1576                request.map(|value| (NATIVE_PROMQL_EXTENSION_KEY, value)),
1577            )
1578            .await
1579            .unwrap();
1580            assert_eq!(
1581                plan.contains("FusedSeries"),
1582                native,
1583                "engine default={engine_default}, session={session:?}, request={request:?}: {plan}"
1584            );
1585        }
1586    }
1587
1588    /// Plans `rate(some_metric[5m])` with the fallback option the caller states, while the native
1589    /// route is on and requested, so only the fallback option decides.
1590    async fn plan_native_promql_with_fallback(
1591        engine_fallback: bool,
1592        session_fallback: Option<bool>,
1593        request_fallback: Option<&str>,
1594    ) -> crate::error::Result<String> {
1595        plan_native_promql_with_query_options(
1596            crate::options::QueryOptions {
1597                allow_query_fallback: engine_fallback,
1598                experimental_native_promql: true,
1599                ..Default::default()
1600            },
1601            session_fallback.map(|value| {
1602                (
1603                    "query.allow_query_fallback",
1604                    if value { "true" } else { "false" },
1605                )
1606            }),
1607            request_fallback.map(|value| (QUERY_FALLBACK_HINT, value)),
1608        )
1609        .await
1610    }
1611
1612    /// The native route is admitted only when the query cannot fall back, and the fallback option
1613    /// resolves from the same snapshot, so a stated value overrides the engine default in both
1614    /// directions instead of only ever turning the fallback on.
1615    #[tokio::test]
1616    async fn test_plan_pql_declines_native_route_when_query_may_fall_back() {
1617        // (engine option, session variable, hint, native route admitted)
1618        for (engine, session, request, native) in [
1619            // Nothing asks for the fallback, so the route is planned as before.
1620            (false, None, None, true),
1621            (false, None, Some("false"), true),
1622            (false, Some(false), None, true),
1623            // A per-query source turns the fallback on, so the route is declined.
1624            (false, Some(true), None, false),
1625            (false, None, Some("true"), false),
1626            (false, None, Some("TRUE"), false),
1627            // The engine option is the default: a stated `false` overrides it.
1628            (true, None, None, false),
1629            (true, None, Some("false"), true),
1630            (true, Some(true), Some("false"), true),
1631            (true, Some(false), None, true),
1632        ] {
1633            let plan = plan_native_promql_with_fallback(engine, session, request)
1634                .await
1635                .unwrap();
1636            assert_eq!(
1637                plan.contains("FusedSeries"),
1638                native,
1639                "engine={engine}, session={session:?}, request={request:?}: {plan}"
1640            );
1641        }
1642    }
1643
1644    /// The engine-wide option is the default a request or a session overrides: it is not a gate
1645    /// the request also has to pass. A default deployment stays on the legacy route when nothing
1646    /// is stated, and a client that asks for the native route gets it - which is the case that
1647    /// matters when this branch is merged back, because a client can always state the option.
1648    #[tokio::test]
1649    async fn test_engine_option_is_the_default_a_request_or_session_overrides() {
1650        const KEY: &str = "query.experimental_native_promql";
1651        // (engine option, session `SET`, request hint, native route planned)
1652        for (engine, session, request, native) in [
1653            // Nothing states the option, so the engine default answers.
1654            (false, None, None, false),
1655            (true, None, None, true),
1656            // A request that asks for the route gets it on a default deployment.
1657            (false, None, Some((KEY, "true")), true),
1658            // ... and a request that states `false` keeps the legacy route on an enabled one.
1659            (true, None, Some((KEY, "false")), false),
1660            // A session `SET` states it too, and the request outranks it in both directions.
1661            (false, Some((KEY, "true")), None, true),
1662            (true, Some((KEY, "false")), None, false),
1663            (false, Some((KEY, "false")), Some((KEY, "true")), true),
1664            (true, Some((KEY, "true")), Some((KEY, "false")), false),
1665        ] {
1666            let plan = plan_native_promql_with_query_options(
1667                crate::options::QueryOptions {
1668                    experimental_native_promql: engine,
1669                    ..Default::default()
1670                },
1671                session,
1672                request,
1673            )
1674            .await
1675            .unwrap();
1676
1677            assert_eq!(
1678                plan.contains("FusedSeries"),
1679                native,
1680                "engine={engine}, session={session:?}, request={request:?}: {plan}"
1681            );
1682            assert_eq!(
1683                plan.contains("RawSeriesSource"),
1684                native,
1685                "engine={engine}, session={session:?}, request={request:?}: {plan}"
1686            );
1687        }
1688    }
1689
1690    /// The fallback hint names a query option, so a value that is not a boolean is rejected instead
1691    /// of silently leaving the fallback off.
1692    #[tokio::test]
1693    async fn test_plan_pql_rejects_a_fallback_hint_that_is_not_a_boolean() {
1694        let error = plan_native_promql_with_fallback(false, None, Some("yes"))
1695            .await
1696            .unwrap_err();
1697        let message = error.to_string();
1698        assert!(message.contains("query_fallback"), "{message}");
1699        assert!(message.contains("Expected true or false"), "{message}");
1700    }
1701
1702    /// One deployment, one topology: an engine that plans regions reads every selector through one
1703    /// source per region, so the admission gate admits the same shapes wherever those regions are.
1704    /// An engine with no distributed planner plans no region, so its plans keep the shapes a region
1705    /// runs itself and there is nothing for the gate to judge.
1706    #[tokio::test]
1707    async fn test_native_promql_admission_is_the_same_for_both_deployments() {
1708        for (with_dist_planner, query, sourced) in [
1709            (false, "some_metric + other_metric", true),
1710            (false, "rate(some_metric[5m])", false),
1711            (true, "some_metric + other_metric", true),
1712            (true, "rate(some_metric[5m])", true),
1713        ] {
1714            let engine = create_promql_test_engine_with(
1715                crate::options::QueryOptions {
1716                    experimental_native_promql: true,
1717                    ..Default::default()
1718                },
1719                with_dist_planner,
1720            );
1721            let query_ctx = Arc::new(
1722                QueryContextBuilder::default()
1723                    .set_extension(NATIVE_PROMQL_EXTENSION_KEY.to_string(), "true".to_string())
1724                    .build(),
1725            );
1726            let stmt = QueryLanguageParser::parse_promql(
1727                &PromQuery {
1728                    query: query.to_string(),
1729                    start: "0".to_string(),
1730                    end: "10".to_string(),
1731                    step: "5s".to_string(),
1732                    lookback: "300s".to_string(),
1733                    alias: None,
1734                },
1735                &query_ctx,
1736            )
1737            .unwrap();
1738            let plan = engine.planner().plan(&stmt, query_ctx).await.unwrap();
1739            let display = plan.display_indent().to_string();
1740            assert!(
1741                display.contains("FusedSeries"),
1742                "with_dist_planner={with_dist_planner}, query={query}: {display}"
1743            );
1744            if with_dist_planner {
1745                // The gate admits the plan instead of replanning it through the legacy route: one
1746                // source per region under a fused node.
1747                assert!(remote_native_raw_plan_supported(&plan), "{display}");
1748            }
1749            assert_eq!(
1750                display.contains("RawSeriesSource"),
1751                sourced,
1752                "with_dist_planner={with_dist_planner}, query={query}: {display}"
1753            );
1754        }
1755    }
1756
1757    /// Plans `query` on the fixture engine with the native route requested. The engine is one with
1758    /// no distributed planner, so its plans keep the shapes a region runs itself.
1759    async fn plan_remote_native_promql(
1760        engine: &QueryEngineRef,
1761        query_ctx: &QueryContextRef,
1762        query: &str,
1763    ) -> LogicalPlan {
1764        let stmt = QueryLanguageParser::parse_promql(
1765            &PromQuery {
1766                query: query.to_string(),
1767                start: "0".to_string(),
1768                end: "10".to_string(),
1769                step: "5s".to_string(),
1770                lookback: "300s".to_string(),
1771                alias: None,
1772            },
1773            query_ctx,
1774        )
1775        .unwrap();
1776        engine
1777            .planner()
1778            .plan(&stmt, query_ctx.clone())
1779            .await
1780            .unwrap()
1781    }
1782
1783    /// A query context that asks for the native route and states what a nameless selector may
1784    /// discover; the default context declines discovery altogether.
1785    fn native_query_ctx(scope: MetricDiscoveryScope) -> QueryContextRef {
1786        let mut ctx = (*QueryContext::arc()).clone();
1787        ctx.set_metric_discovery_scope(scope);
1788        ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY.to_string(), "true".to_string());
1789        Arc::new(ctx)
1790    }
1791
1792    fn native_discovery_query_ctx() -> QueryContextRef {
1793        native_query_ctx(MetricDiscoveryScope::Unrestricted)
1794    }
1795
1796    /// The engine's physical plan for `plan` and the batches it answers.
1797    async fn execute_plan(
1798        engine: &QueryEngineRef,
1799        plan: LogicalPlan,
1800        query_ctx: &QueryContextRef,
1801    ) -> (
1802        Arc<dyn datafusion::physical_plan::ExecutionPlan>,
1803        Vec<RecordBatch>,
1804    ) {
1805        let output = engine.execute(plan, query_ctx.clone()).await.unwrap();
1806        let physical = output
1807            .meta
1808            .plan
1809            .expect("the engine reports its physical plan");
1810        let batches = match output.data {
1811            OutputData::Stream(stream) => collect_batches(stream).await.unwrap(),
1812            OutputData::RecordBatches(batches) => batches,
1813            other => panic!("a PromQL query answers rows, not {other:?}"),
1814        }
1815        .take();
1816        (physical, batches)
1817    }
1818
1819    /// Every node name in the tree rooted at `root`, the root included.
1820    fn physical_plan_names(
1821        root: &Arc<dyn datafusion::physical_plan::ExecutionPlan>,
1822    ) -> Vec<String> {
1823        let mut names = Vec::new();
1824        let mut stack = vec![Arc::clone(root)];
1825        while let Some(node) = stack.pop() {
1826            names.push(node.name().to_string());
1827            stack.extend(node.children().into_iter().cloned());
1828        }
1829        names
1830    }
1831
1832    /// Every logical plan node below `root`, the root included.
1833    fn logical_plan_nodes(root: &LogicalPlan) -> Vec<&LogicalPlan> {
1834        let mut nodes = Vec::new();
1835        let mut stack = vec![root];
1836        while let Some(node) = stack.pop() {
1837            nodes.push(node);
1838            stack.extend(node.inputs());
1839        }
1840        nodes
1841    }
1842
1843    fn fused_series_nodes(plan: &LogicalPlan) -> Vec<&promql::extension_plan::FusedSeries> {
1844        logical_plan_nodes(plan)
1845            .into_iter()
1846            .filter_map(|node| match node {
1847                LogicalPlan::Extension(extension) => extension
1848                    .node
1849                    .as_any()
1850                    .downcast_ref::<promql::extension_plan::FusedSeries>(
1851                ),
1852                _ => None,
1853            })
1854            .collect()
1855    }
1856
1857    fn numeric_values(batches: &[RecordBatch], column: &str) -> Vec<f64> {
1858        batches
1859            .iter()
1860            .flat_map(|batch| {
1861                batch
1862                    .column_by_name(column)
1863                    .unwrap_or_else(|| panic!("no `{column}` column"))
1864                    .as_any()
1865                    .downcast_ref::<Float64Array>()
1866                    .unwrap()
1867                    .values()
1868                    .to_vec()
1869            })
1870            .collect()
1871    }
1872
1873    fn label_values(batches: &[RecordBatch], column: &str) -> Vec<String> {
1874        batches
1875            .iter()
1876            .flat_map(|batch| {
1877                let array = batch
1878                    .column_by_name(column)
1879                    .unwrap_or_else(|| panic!("no `{column}` column"))
1880                    .as_any()
1881                    .downcast_ref::<StringArray>()
1882                    .expect("a label column is Utf8");
1883                (0..array.len())
1884                    .map(|row| array.value(row).to_string())
1885                    .collect::<Vec<_>>()
1886            })
1887            .collect()
1888    }
1889
1890    /// Asserts `plan` is a native plan that reads no region, and that every fused node in it binds
1891    /// no metric: a data-free or zero-match statement has no table to name.
1892    fn assert_regionless_native_plan(plan: &LogicalPlan, query: &str) {
1893        let display = plan.display_indent().to_string();
1894        assert!(display.contains("FusedSeries"), "{query}: {display}");
1895        for absent in ["TableScan", "MergeScan", "RawSeriesSource"] {
1896            assert!(
1897                !display.contains(absent),
1898                "{query} contains {absent}: {display}"
1899            );
1900        }
1901        let fused = fused_series_nodes(plan);
1902        assert!(!fused.is_empty(), "{query}: {display}");
1903        for node in fused {
1904            assert_eq!(
1905                None,
1906                node.binding().metric_name,
1907                "{query} bound a metric to an input that reads no table: {display}"
1908            );
1909        }
1910    }
1911
1912    /// Asserts every empty input under `plan` declares the typed empty raw series frame: the
1913    /// planner's own definition of that input, and the frame a scan would have declared, so the
1914    /// physical planner reads it as a frame producer instead of looking for a scan below it.
1915    fn assert_typed_empty_inputs(plan: &LogicalPlan, query: &str) {
1916        let empty = logical_plan_nodes(plan)
1917            .into_iter()
1918            .filter(|node| matches!(node, LogicalPlan::EmptyRelation(_)))
1919            .collect::<Vec<_>>();
1920        assert!(!empty.is_empty(), "{query} has no empty input");
1921        for node in empty {
1922            assert!(
1923                crate::promql::planner::native::is_empty_discovered_input(node),
1924                "{query}: {node:?}"
1925            );
1926            let LogicalPlan::EmptyRelation(relation) = node else {
1927                unreachable!();
1928            };
1929            assert!(!relation.produce_one_row, "{query}: {relation:?}");
1930            let schema = relation.schema.as_arrow();
1931            for (key, expected) in [
1932                ("greptime.series.content", "raw"),
1933                ("greptime.series.labels", "explicit"),
1934                ("greptime.series.ordering", "contiguous"),
1935            ] {
1936                assert_eq!(
1937                    Some(expected),
1938                    schema.metadata().get(key).map(String::as_str),
1939                    "{query}: {key}"
1940                );
1941            }
1942            // The one value field the empty input is bound to, named as the route names a value.
1943            let fields = schema.field_with_name("fields").expect("a series frame");
1944            let arrow_schema::DataType::Struct(payloads) = fields.data_type() else {
1945                panic!("{query}: {fields:?}");
1946            };
1947            assert_eq!(
1948                vec!["value"],
1949                payloads
1950                    .iter()
1951                    .map(|field| field.name().as_str())
1952                    .collect::<Vec<_>>(),
1953                "{query}"
1954            );
1955        }
1956    }
1957
1958    /// Asserts the physical plan of a regionless native statement: the fused node runs on the
1959    /// frontend and no region read is planned.
1960    fn assert_regionless_physical_plan(
1961        physical: &Arc<dyn datafusion::physical_plan::ExecutionPlan>,
1962        query: &str,
1963    ) {
1964        let names = physical_plan_names(physical);
1965        assert!(
1966            names.iter().any(|name| name == "FusedSeriesExec"),
1967            "{query} is evaluated on the frontend by the fused node: {physical:?}"
1968        );
1969        assert!(
1970            !names.iter().any(|name| name == "MergeScanExec"),
1971            "{query} reads no region: {physical:?}"
1972        );
1973    }
1974
1975    /// A statement that reads no table plans natively over the wire, where there is no region to
1976    /// place anything in: the frontend evaluates the fused node with expression-named values.
1977    #[tokio::test]
1978    async fn test_remote_native_promql_plans_a_data_free_statement_natively() {
1979        let engine = create_promql_test_engine_with(
1980            crate::options::QueryOptions {
1981                experimental_native_promql: true,
1982                ..Default::default()
1983            },
1984            false,
1985        );
1986        let query_ctx = native_discovery_query_ctx();
1987        for (query, expected_values, expected_labels, name_column) in [
1988            // `time()` answers the evaluation grid in seconds. It is a scalar root: it publishes
1989            // one value and no series, so its rows layout declares no name column.
1990            ("time()", &[0.0, 5.0, 10.0][..], &[][..], false),
1991            // `vector(1)` is a samples root: its rows layout declares the per-row name column,
1992            // which names no row because the vector carries no series identity.
1993            ("vector(1)", &[1.0, 1.0, 1.0][..], &[][..], true),
1994            (
1995                r#"label_replace(vector(1), "host", "host1", "", "")"#,
1996                &[1.0, 1.0, 1.0][..],
1997                &[("host", "host1")][..],
1998                true,
1999            ),
2000            // A synthesized `__tsid` is published under the statement's own columns: the stripping
2001            // projection above the node is read through rather than mistaken for a remote plan.
2002            (
2003                r#"label_replace(vector(1), "__tsid", "x", "", "")"#,
2004                &[1.0, 1.0, 1.0][..],
2005                &[][..],
2006                true,
2007            ),
2008        ] {
2009            let plan = plan_remote_native_promql(&engine, &query_ctx, query).await;
2010            let display = plan.display_indent().to_string();
2011            assert_regionless_native_plan(&plan, query);
2012            assert!(
2013                !display.contains("greptime_value"),
2014                "{query} keeps the native value column: {display}"
2015            );
2016            // A data-free statement has no input at all, so nothing is scanned or left empty. The
2017            // value is named after the expression, and a samples root's rows keep the name column
2018            // last.
2019            let expression = promql_parser::parser::parse(query).unwrap().to_string();
2020            let mut expected_columns = vec!["time", expression.as_str()];
2021            expected_columns.extend(expected_labels.iter().map(|(name, _)| *name));
2022            if name_column {
2023                expected_columns.push("__name__");
2024            }
2025            assert_eq!(
2026                expected_columns,
2027                plan.schema()
2028                    .fields()
2029                    .iter()
2030                    .map(|field| field.name().as_str())
2031                    .collect::<Vec<_>>(),
2032                "{query}: {display}"
2033            );
2034            let (physical, batches) = execute_plan(&engine, plan, &query_ctx).await;
2035            assert_regionless_physical_plan(&physical, query);
2036            assert_eq!(
2037                expected_values,
2038                numeric_values(&batches, &expression).as_slice(),
2039                "{query}: {batches:?}"
2040            );
2041            for (label, value) in expected_labels {
2042                assert_eq!(
2043                    vec![value.to_string(); batches_row_count(&batches)],
2044                    label_values(&batches, label),
2045                    "{query}: label `{label}`: {batches:?}"
2046                );
2047            }
2048        }
2049    }
2050
2051    /// The rows every batch of `batches` holds.
2052    fn batches_row_count(batches: &[RecordBatch]) -> usize {
2053        batches.iter().map(|batch| batch.num_rows()).sum()
2054    }
2055
2056    /// A nameless selector that matches no metric table has no region to read either, so the typed
2057    /// empty input it is planned as stays that input and the node above it is evaluated on the
2058    /// frontend. Binding a metric to it is what used to turn this statement into an internal error.
2059    #[tokio::test]
2060    async fn test_remote_native_promql_plans_a_zero_match_selector_natively() {
2061        let engine = create_promql_test_engine_with(
2062            crate::options::QueryOptions {
2063                experimental_native_promql: true,
2064                ..Default::default()
2065            },
2066            false,
2067        );
2068        let query_ctx = native_discovery_query_ctx();
2069        for (query, expected_rows, expected_labels) in [
2070            // The selection itself, over the typed empty frame.
2071            (r#"{job="api"}"#, 0, &[][..]),
2072            // A whole-vector operation over it, which the route plans as a segment: its parent node
2073            // reads the segment's own fused node.
2074            (r#"sort({job="api"})"#, 0, &[][..]),
2075            // A fold splits into a `Final` half over the `Partial` half that reads the input.
2076            (r#"sum({job="api"})"#, 0, &[][..]),
2077            // `absent` answers one series per evaluation point over zero input, labelled by the
2078            // selector's matchers. The grid holds three points.
2079            (r#"absent({job="api"})"#, 3, &[("job", "api")][..]),
2080        ] {
2081            let plan = plan_remote_native_promql(&engine, &query_ctx, query).await;
2082            let display = plan.display_indent().to_string();
2083            assert_regionless_native_plan(&plan, query);
2084            assert!(
2085                display.contains("EmptyRelation"),
2086                "{query} keeps the typed empty input: {display}"
2087            );
2088            assert_typed_empty_inputs(&plan, query);
2089            let (physical, batches) = execute_plan(&engine, plan, &query_ctx).await;
2090            assert_regionless_physical_plan(&physical, query);
2091            // No table matched, so the answer is the empty vector, not an error.
2092            assert_eq!(
2093                expected_rows,
2094                batches_row_count(&batches),
2095                "{query} answered rows over a selector that matches no metric: {physical:?}"
2096            );
2097            for (label, value) in expected_labels {
2098                assert_eq!(
2099                    vec![value.to_string(); expected_rows],
2100                    label_values(&batches, label),
2101                    "{query}: label `{label}`: {batches:?}"
2102                );
2103            }
2104        }
2105
2106        // An allowlist that admits no metric at all reaches the same empty input: the answer comes
2107        // from the statement, not from whatever the catalog holds.
2108        let query_ctx = native_query_ctx(MetricDiscoveryScope::allowed(std::iter::empty()));
2109        let query = r#"{job="api"}"#;
2110        let plan = plan_remote_native_promql(&engine, &query_ctx, query).await;
2111        assert_regionless_native_plan(&plan, "denied discovery");
2112        assert_typed_empty_inputs(&plan, "denied discovery");
2113        let (physical, batches) = execute_plan(&engine, plan, &query_ctx).await;
2114        assert_regionless_physical_plan(&physical, "denied discovery");
2115        assert_eq!(
2116            0,
2117            batches_row_count(&batches),
2118            "denied discovery: {physical:?}"
2119        );
2120    }
2121
2122    /// Plans `sql` and runs the DataFusion analyzer, which is where
2123    /// `InsertAssignmentRule` sits. Planning alone stops short of it, so these
2124    /// assertions would not see the assignment rewrite at all.
2125    async fn analyze_insert(
2126        engine: &QueryEngineRef,
2127        sql: &str,
2128        query_ctx: &QueryContextRef,
2129    ) -> String {
2130        let stmt = QueryLanguageParser::parse_sql(sql, query_ctx).unwrap();
2131        let plan = engine
2132            .planner()
2133            .plan(&stmt, query_ctx.clone())
2134            .await
2135            .unwrap();
2136        let context = engine.engine_context(query_ctx.clone()).unwrap();
2137        let state = context.state();
2138        state
2139            .analyzer()
2140            .execute_and_check(plan, state.config_options(), |_, _| {})
2141            .unwrap()
2142            .display_indent_schema()
2143            .to_string()
2144    }
2145
2146    #[tokio::test]
2147    async fn test_insert_timestamp_literals_use_query_timezone() {
2148        let query_ctx = Arc::new(
2149            QueryContextBuilder::default()
2150                .timezone(Timezone::from_tz_string("Asia/Shanghai").unwrap())
2151                .build(),
2152        );
2153        let engine = create_timestamp_test_engine().await;
2154
2155        for (sql, expected_timestamps) in [
2156            (
2157                "INSERT INTO timestamps (ts, st) \
2158                 VALUES ('2026-08-02 12:00:00.001', now())",
2159                &[1_785_643_200_001_i64][..],
2160            ),
2161            (
2162                "INSERT INTO timestamps (ts, st) \
2163                 SELECT '2026-08-03 12:00:00.001', now()",
2164                &[1_785_729_600_001_i64][..],
2165            ),
2166            (
2167                "INSERT INTO timestamps (ts, st) \
2168                 SELECT '2026-08-04 12:00:00.001', now() LIMIT 1",
2169                &[1_785_816_000_001_i64][..],
2170            ),
2171            (
2172                "INSERT INTO timestamps (ts, st) \
2173                 SELECT * FROM (\
2174                     SELECT '2026-08-05 12:00:00.001', now()\
2175                 ) AS source",
2176                &[1_785_902_400_001_i64][..],
2177            ),
2178            (
2179                "INSERT INTO timestamps (ts, st) \
2180                 SELECT '2026-08-18 12:00:00.001', max(st) \
2181                 FROM timestamps GROUP BY note",
2182                &[1_787_025_600_001_i64][..],
2183            ),
2184            (
2185                "INSERT INTO timestamps (ts, st) \
2186                 SELECT c, s FROM (\
2187                     SELECT '2026-08-13 12:00:00.001' AS c, now() AS s\
2188                 ) AS t WHERE c > '2026-01-01'",
2189                &[1_786_593_600_001_i64][..],
2190            ),
2191            (
2192                "INSERT INTO timestamps (ts, st) \
2193                 SELECT c, s FROM (\
2194                     SELECT '2026-08-14 12:00:00.001' AS c, now() AS s\
2195                 ) AS t ORDER BY c",
2196                &[1_786_680_000_001_i64][..],
2197            ),
2198            (
2199                "INSERT INTO timestamps (ts, st) \
2200                 SELECT DISTINCT c, s FROM (\
2201                     SELECT '2026-08-15 12:00:00.001' AS c, now() AS s\
2202                 ) AS t",
2203                &[1_786_766_400_001_i64][..],
2204            ),
2205        ] {
2206            let plan = analyze_insert(&engine, sql, &query_ctx).await;
2207
2208            for expected_timestamp in expected_timestamps {
2209                assert!(
2210                    plan.contains(&format!("TimestampMillisecond({expected_timestamp}, None)")),
2211                    "{plan}"
2212                );
2213            }
2214        }
2215    }
2216
2217    #[tokio::test]
2218    async fn test_insert_explicit_timestamp_cast_keeps_datafusion_semantics() {
2219        let query_ctx = Arc::new(
2220            QueryContextBuilder::default()
2221                .timezone(Timezone::from_tz_string("Asia/Shanghai").unwrap())
2222                .build(),
2223        );
2224        let engine = create_timestamp_test_engine().await;
2225        let sql = "INSERT INTO timestamps (ts, st) \
2226                   VALUES (CAST('2026-08-08 12:00:00.001' AS TIMESTAMP), now())";
2227        let plan = analyze_insert(&engine, sql, &query_ctx).await;
2228
2229        // An explicit cast reaches the analyzer as an `arrow_cast` call rather
2230        // than an `Expr::Cast`, which is how it stays out of the rewrite.
2231        assert!(
2232            plan.contains("arrow_cast(Utf8(\"2026-08-08 12:00:00.001\")"),
2233            "{plan}"
2234        );
2235        // 12:00:00.001 read as Shanghai local time; the source query keeps UTC.
2236        assert!(
2237            !plan.contains("TimestampMillisecond(1786104000001, None)"),
2238            "{plan}"
2239        );
2240    }
2241
2242    #[tokio::test]
2243    async fn test_insert_converts_source_literal_shared_by_several_columns() {
2244        let query_ctx = Arc::new(
2245            QueryContextBuilder::default()
2246                .timezone(Timezone::from_tz_string("Asia/Shanghai").unwrap())
2247                .build(),
2248        );
2249        let engine = create_timestamp_test_engine().await;
2250
2251        // Rewriting `c` in place would also retype `note` and truncate `ts_ns`.
2252        for (sql, expected) in [
2253            (
2254                "INSERT INTO timestamps (ts, note) SELECT a, b FROM (\
2255                     SELECT c AS a, c AS b FROM (\
2256                         SELECT '2026-08-12 12:00:00.001' AS c\
2257                     ) AS t1\
2258                 ) AS t2",
2259                &[
2260                    "TimestampMillisecond(1786507200001, None)",
2261                    "[a:Utf8, b:Utf8]",
2262                ][..],
2263            ),
2264            (
2265                "INSERT INTO timestamps (ts, ts_ns) SELECT a, b FROM (\
2266                     SELECT c AS a, c AS b FROM (\
2267                         SELECT '2026-08-12 12:00:00.123456789' AS c\
2268                     ) AS t1\
2269                 ) AS t2",
2270                &[
2271                    "TimestampMillisecond(1786507200123, None)",
2272                    "TimestampNanosecond(1786507200123456789, None)",
2273                ][..],
2274            ),
2275        ] {
2276            let plan = analyze_insert(&engine, sql, &query_ctx).await;
2277
2278            for expected in expected {
2279                assert!(plan.contains(expected), "{plan}");
2280            }
2281        }
2282    }
2283
2284    #[tokio::test]
2285    async fn test_insert_union_converts_via_assignment_cast() {
2286        let query_ctx = Arc::new(
2287            QueryContextBuilder::default()
2288                .timezone(Timezone::from_tz_string("Asia/Shanghai").unwrap())
2289                .build(),
2290        );
2291        let engine = create_timestamp_test_engine().await;
2292        // Branches disagree, so the conversion stays as a cast on the
2293        // assignment instead of folding. One cast covers every branch, which is
2294        // why a NULL branch no longer cancels the conversion for the column and
2295        // why UNION's dedup keys stay on the original strings.
2296        for sql in [
2297            "INSERT INTO timestamps (ts, st) \
2298             SELECT '2026-08-06 12:00:00.001', now() \
2299             UNION ALL \
2300             SELECT '2026-08-07 12:00:00.001', NULL",
2301            "INSERT INTO timestamps (ts, st) \
2302             SELECT '2026-08-16 12:00:00.001', now() \
2303             UNION \
2304             SELECT '2026-08-17 12:00:00.001', now()",
2305        ] {
2306            let plan = analyze_insert(&engine, sql, &query_ctx).await;
2307
2308            assert!(
2309                plan.contains("AS Timestamp(ms, \"Asia/Shanghai\")"),
2310                "{plan}"
2311            );
2312            // The branches themselves are untouched.
2313            assert!(
2314                plan.contains("Utf8(\"2026-08-07 12:00:00.001\")")
2315                    || plan.contains("Utf8(\"2026-08-17 12:00:00.001\")"),
2316                "{plan}"
2317            );
2318        }
2319    }
2320
2321    #[tokio::test]
2322    async fn test_insert_mixed_union_keeps_source_coercion() {
2323        let query_ctx = Arc::new(
2324            QueryContextBuilder::default()
2325                .timezone(Timezone::from_tz_string("Asia/Shanghai").unwrap())
2326                .build(),
2327        );
2328        let engine = create_timestamp_test_engine().await;
2329        let sql = "INSERT INTO timestamps (ts, st) \
2330                   SELECT '2026-08-10 12:00:00.001', now() \
2331                   UNION ALL \
2332                   SELECT CAST('2026-08-11 12:00:00.001' AS TIMESTAMP), now()";
2333        let plan = analyze_insert(&engine, sql, &query_ctx).await;
2334
2335        assert!(
2336            !plan.contains("TimestampMillisecond(1786334400001, None)"),
2337            "{plan}"
2338        );
2339        assert!(
2340            plan.contains("arrow_cast(Utf8(\"2026-08-11 12:00:00.001\")"),
2341            "{plan}"
2342        );
2343        // TypeCoercion has already settled this union to timestamp, so the
2344        // assignment has nothing left to reinterpret. Retargeting the cast here
2345        // would leave a Timestamp(None) -> Timestamp(Some(tz)) step behind,
2346        // which shifts the value instead of relabelling it.
2347        assert!(!plan.contains("Asia/Shanghai"), "{plan}");
2348    }
2349
2350    #[tokio::test]
2351    async fn test_extract_placeholder_cast_types_multiple() {
2352        let plan = parse_sql_to_plan(
2353            "SELECT $1::INT, $2::TEXT, $3, $4::INTEGER FROM test WHERE $5::FLOAT > 0",
2354        )
2355        .await;
2356        let types = DfLogicalPlanner::extract_placeholder_cast_types(&plan).unwrap();
2357
2358        assert_eq!(types.len(), 5);
2359        assert_eq!(types.get("$1"), Some(&Some(DataType::Int32)));
2360        assert_eq!(types.get("$2"), Some(&Some(DataType::Utf8)));
2361        assert_eq!(types.get("$3"), Some(&None));
2362        assert_eq!(types.get("$4"), Some(&Some(DataType::Int32)));
2363        assert_eq!(types.get("$5"), Some(&Some(DataType::Float32)));
2364    }
2365
2366    #[tokio::test]
2367    async fn test_get_inferred_parameter_types_fallback_for_udf_args() {
2368        // datafusion is not able to infer type for scalar function arguments
2369        let plan = parse_sql_to_plan(
2370            "SELECT parse_ident($1), parse_ident($2::TEXT) FROM test WHERE id > $3",
2371        )
2372        .await;
2373        let types = DfLogicalPlanner::get_inferred_parameter_types(&plan).unwrap();
2374
2375        assert_eq!(types.len(), 3);
2376
2377        let type_1 = types.get("$1").unwrap();
2378        let type_2 = types.get("$2").unwrap();
2379        let type_3 = types.get("$3").unwrap();
2380
2381        assert!(type_1.is_none(), "Expected $1 to be None");
2382        assert_eq!(type_2, &Some(DataType::Utf8));
2383        assert_eq!(type_3, &Some(DataType::Int32));
2384    }
2385
2386    #[tokio::test]
2387    async fn test_get_inferred_parameter_types_limit_offset() {
2388        let plan = parse_sql_to_plan("SELECT id FROM test LIMIT $1 OFFSET $2").await;
2389        let types = DfLogicalPlanner::get_inferred_parameter_types(&plan).unwrap();
2390
2391        assert_eq!(types.get("$1"), Some(&Some(DataType::Int64)));
2392        assert_eq!(types.get("$2"), Some(&Some(DataType::Int64)));
2393    }
2394
2395    #[tokio::test]
2396    async fn test_plan_pql_applies_extension_rules() {
2397        for inner_agg in ["count", "sum", "avg", "min", "max", "stddev", "stdvar"] {
2398            let plan = parse_promql_to_plan(&format!(
2399                "sum(irate(some_metric[1h])) / scalar(count({inner_agg}(some_metric) by (tag_0)))"
2400            ))
2401            .await;
2402            let plan_str = plan.display_indent_schema().to_string();
2403            assert!(plan_str.contains("Distinct:"), "{inner_agg}: {plan_str}");
2404        }
2405    }
2406
2407    #[tokio::test]
2408    async fn test_plan_pql_filters_null_only_groups_for_non_count_inner_aggs() {
2409        let count_plan = parse_promql_to_plan("scalar(count(count(some_metric) by (tag_0)))").await;
2410        let count_plan_str = count_plan.display_indent_schema().to_string();
2411        assert!(
2412            !count_plan_str.contains("field_0 IS NOT NULL"),
2413            "{count_plan_str}"
2414        );
2415
2416        for inner_agg in ["sum", "avg", "min", "max", "stddev", "stdvar"] {
2417            let plan = parse_promql_to_plan(&format!(
2418                "scalar(count({inner_agg}(some_metric) by (tag_0)))"
2419            ))
2420            .await;
2421            let plan_str = plan.display_indent_schema().to_string();
2422            assert!(
2423                plan_str.contains("field_0 IS NOT NULL"),
2424                "{inner_agg}: {plan_str}"
2425            );
2426        }
2427    }
2428
2429    #[tokio::test]
2430    async fn test_plan_pql_skips_extension_rules_for_non_direct_or_unsupported_inner_agg() {
2431        for query in [
2432            "sum(irate(some_metric[1h])) / scalar(count(sum(irate(some_metric[1h])) by (tag_0)))",
2433            "sum(irate(some_metric[1h])) / scalar(count(group(some_metric) by (tag_0)))",
2434        ] {
2435            let plan = parse_promql_to_plan(query).await;
2436            let plan_str = plan.display_indent_schema().to_string();
2437            assert!(!plan_str.contains("Distinct:"), "{query}: {plan_str}");
2438        }
2439    }
2440
2441    #[tokio::test]
2442    async fn test_plan_sql_does_not_apply_nested_count_rule() {
2443        let plan = parse_sql_to_plan(
2444            "SELECT id, count(inner_count) \
2445             FROM ( \
2446                 SELECT id, count(name) AS inner_count \
2447                 FROM test \
2448                 GROUP BY id \
2449                 ORDER BY id \
2450                 LIMIT 1000000 \
2451             ) t \
2452             GROUP BY id \
2453             ORDER BY id",
2454        )
2455        .await;
2456
2457        let plan_str = plan.display_indent_schema().to_string();
2458        assert!(!plan_str.contains("Distinct:"), "{plan_str}");
2459    }
2460
2461    #[tokio::test]
2462    async fn test_get_inferred_parameter_types_subquery() {
2463        let plan = parse_sql_to_plan(
2464            r#"SELECT * FROM test WHERE id = (SELECT id FROM test CROSS JOIN (SELECT parse_ident($1::TEXT) AS parts) p LIMIT 1)"#,
2465        ).await;
2466        let types = DfLogicalPlanner::get_inferred_parameter_types(&plan).unwrap();
2467
2468        assert_eq!(types.len(), 1);
2469        let type_1 = types.get("$1").unwrap();
2470        assert_eq!(type_1, &Some(DataType::Utf8));
2471    }
2472
2473    #[tokio::test]
2474    async fn test_get_inferred_parameter_types_insert() {
2475        let plan = parse_sql_to_plan("INSERT INTO test (id, name) VALUES ($1, $2), ($3, $4)").await;
2476        let types = DfLogicalPlanner::get_inferred_parameter_types(&plan).unwrap();
2477
2478        assert_eq!(types.len(), 4);
2479        assert_eq!(types.get("$1"), Some(&Some(DataType::Int32)));
2480        assert_eq!(types.get("$2"), Some(&Some(DataType::Utf8)));
2481        assert_eq!(types.get("$3"), Some(&Some(DataType::Int32)));
2482        assert_eq!(types.get("$4"), Some(&Some(DataType::Utf8)));
2483    }
2484
2485    /// A plan that publishes `columns` as its output, one literal per column, named and typed as
2486    /// the column is.
2487    fn plan_publishing(columns: &[(&str, ScalarValue)]) -> LogicalPlan {
2488        let exprs = columns
2489            .iter()
2490            .map(|(name, value)| DfExpr::Literal(value.clone(), None).alias(*name))
2491            .collect::<Vec<_>>();
2492        LogicalPlanBuilder::empty(false)
2493            .project(exprs)
2494            .unwrap()
2495            .build()
2496            .unwrap()
2497    }
2498
2499    /// [`plan_publishing`], declaring what a plan of either route declares: the time index marked as
2500    /// one, and the schema version GreptimeDB's schemas carry.
2501    fn plan_publishing_marked(columns: &[(&str, ScalarValue)], time_index: &str) -> LogicalPlan {
2502        let plan = plan_publishing(columns);
2503        let LogicalPlan::Projection(projection) = plan else {
2504            unreachable!("plan_publishing builds a projection")
2505        };
2506        let fields = projection
2507            .schema
2508            .iter()
2509            .map(|(_, field)| {
2510                let field =
2511                    if field.name() == time_index {
2512                        Arc::new(field.as_ref().clone().with_metadata(
2513                            std::collections::HashMap::from([(
2514                                datatypes::schema::TIME_INDEX_KEY.to_string(),
2515                                "true".to_string(),
2516                            )]),
2517                        ))
2518                    } else if field.name() == "__name__" {
2519                        // The native rows layout marks the column that names each row.
2520                        Arc::new(field.as_ref().clone().with_metadata(
2521                            std::collections::HashMap::from([(
2522                                datatypes::schema::METRIC_NAME_KEY.to_string(),
2523                                "true".to_string(),
2524                            )]),
2525                        ))
2526                    } else {
2527                        Arc::clone(field)
2528                    };
2529                (None, field)
2530            })
2531            .collect::<Vec<_>>();
2532        let schema = Arc::new(
2533            DFSchema::new_with_metadata(
2534                fields,
2535                std::collections::HashMap::from([(
2536                    datatypes::schema::VERSION_KEY.to_string(),
2537                    datatypes::schema::Schema::INITIAL_VERSION.to_string(),
2538                )]),
2539            )
2540            .unwrap(),
2541        );
2542        LogicalPlan::Projection(
2543            datafusion_expr::Projection::try_new_with_schema(
2544                projection.expr.clone(),
2545                projection.input.clone(),
2546                schema,
2547            )
2548            .unwrap(),
2549        )
2550    }
2551
2552    /// The label column the existing planner publishes: dictionary-encoded text.
2553    fn dictionary_label(value: &str) -> ScalarValue {
2554        ScalarValue::Dictionary(
2555            Box::new(DataType::UInt32),
2556            Box::new(ScalarValue::Utf8(Some(value.to_string()))),
2557        )
2558    }
2559
2560    /// The names of a plan's output columns, in order.
2561    fn column_names(plan: &LogicalPlan) -> Vec<String> {
2562        plan.schema()
2563            .fields()
2564            .iter()
2565            .map(|field| field.name().clone())
2566            .collect()
2567    }
2568
2569    fn time_value() -> ScalarValue {
2570        ScalarValue::TimestampMillisecond(Some(0), None)
2571    }
2572
2573    /// The native answer for the statement these tests use: time index first, the value under the
2574    /// tree's own field name, the labels last.
2575    fn native_answer() -> LogicalPlan {
2576        plan_publishing_marked(
2577            &[
2578                ("ts", time_value()),
2579                ("val", ScalarValue::Float64(Some(2.0))),
2580                ("host", ScalarValue::Utf8(Some("a".to_string()))),
2581            ],
2582            "ts",
2583        )
2584    }
2585
2586    /// The existing planner's answer for the same statement: labels first, then the time index, then
2587    /// the value named after the expression it planned, with the label dictionary-encoded.
2588    fn existing_answer() -> LogicalPlan {
2589        plan_publishing_marked(
2590            &[
2591                ("host", dictionary_label("a")),
2592                ("ts", time_value()),
2593                ("lhs.val + rhs.val", ScalarValue::Float64(Some(2.0))),
2594            ],
2595            "ts",
2596        )
2597    }
2598
2599    /// A CTE publishes the existing planner's columns over a native plan as well.
2600    ///
2601    /// The fused plan publishes the time index first, the value under the tree's field name and the
2602    /// labels last, in plain text; the existing planner publishes the labels first, then the time
2603    /// index, then the value under the name of the expression it planned, in dictionary-encoded text.
2604    /// What a CTE exposes is the second one, whichever route answered the statement, because a CTE's
2605    /// columns are SQL-visible - and a column list the CTE declares is applied to them by position.
2606    #[test]
2607    fn a_cte_publishes_the_existing_planners_columns_over_a_native_plan() {
2608        let native = native_answer();
2609        let existing = existing_answer();
2610
2611        let published = publish_legacy_schema(native, &existing)
2612            .expect("every column has one answer in the other plan");
2613
2614        assert_eq!(
2615            column_names(&published),
2616            vec!["host", "ts", "lhs.val + rhs.val"],
2617            "the CTE publishes the existing planner's column order and names"
2618        );
2619        assert!(
2620            publishes_columns(published.schema().as_ref(), existing.schema().as_ref()),
2621            "and every column it publishes: name, order, type, nullability and metadata: {}",
2622            published.schema()
2623        );
2624        assert_eq!(
2625            published
2626                .schema()
2627                .field_with_name(None, "host")
2628                .unwrap()
2629                .data_type(),
2630            &DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
2631            "a label is published as the encoding the existing planner publishes"
2632        );
2633        let LogicalPlan::Projection(projection) = &published else {
2634            panic!("the native plan is wrapped in a projection: {published}");
2635        };
2636        assert_eq!(
2637            column_names(projection.input.as_ref()),
2638            vec!["ts", "val", "host"],
2639            "the native plan is kept as the projection's input"
2640        );
2641    }
2642
2643    /// A native answer's per-row name column is not published by the CTE.
2644    ///
2645    /// The existing planner publishes no such column, and a column list the CTE declares names
2646    /// exactly the existing planner's columns, so `tql (ts, val)` over one metric must still see two.
2647    #[test]
2648    fn a_cte_does_not_publish_the_native_name_column() {
2649        let native = plan_publishing_marked(
2650            &[
2651                ("ts", time_value()),
2652                ("val", ScalarValue::Float64(Some(2.0))),
2653                ("host", ScalarValue::Utf8(Some("a".to_string()))),
2654                (
2655                    "__name__",
2656                    ScalarValue::Utf8(Some("cte_native".to_string())),
2657                ),
2658            ],
2659            "ts",
2660        );
2661        let existing = existing_answer();
2662
2663        let published = publish_legacy_schema(native, &existing)
2664            .expect("the name column does not compete with a label");
2665
2666        assert!(
2667            publishes_columns(published.schema().as_ref(), existing.schema().as_ref()),
2668            "the CTE publishes exactly the existing planner's columns: {}",
2669            published.schema()
2670        );
2671    }
2672
2673    /// What the CTE publishes survives the analyzer, which rebuilds every projection from its
2674    /// expressions.
2675    ///
2676    /// The declared schema of a projection is not what analysis keeps: the analyzer calls
2677    /// `with_new_exprs`, which rebuilds the projection and derives its schema from the expressions
2678    /// and their input. So the columns have to be carried by the expressions themselves - an alias
2679    /// per column and a cast for the encoding - or they are gone by the time the CTE is read.
2680    #[test]
2681    fn what_a_cte_publishes_survives_the_analyzer_rebuilding_the_projection() {
2682        let existing = existing_answer();
2683        let published = publish_legacy_schema(native_answer(), &existing).unwrap();
2684
2685        // The rebuild `DistPlannerAnalyzer` performs on every projection it visits.
2686        let rebuilt = published
2687            .with_new_exprs(
2688                published.expressions(),
2689                published.inputs().into_iter().cloned().collect(),
2690            )
2691            .unwrap();
2692
2693        assert!(
2694            publishes_columns(rebuilt.schema().as_ref(), existing.schema().as_ref()),
2695            "the rebuilt projection publishes the same columns: {}",
2696            rebuilt.schema()
2697        );
2698        assert_eq!(
2699            rebuilt.to_string(),
2700            published.to_string(),
2701            "and the same expressions"
2702        );
2703    }
2704
2705    /// A statement whose columns do not pair keeps the existing plan.
2706    ///
2707    /// Publishing a column this cannot fill would change what the CTE means, so a shape it cannot
2708    /// map faithfully is refused instead: the caller keeps the existing plan and the CTE keeps the
2709    /// columns it has always published.
2710    #[test]
2711    fn a_shape_with_no_faithful_column_mapping_keeps_the_existing_plan() {
2712        // One native value column cannot fill two of the existing plan's value columns.
2713        let two_values = plan_publishing_marked(
2714            &[
2715                ("host", dictionary_label("a")),
2716                ("ts", time_value()),
2717                ("lhs.val + rhs.val", ScalarValue::Float64(Some(2.0))),
2718                ("lhs.val - rhs.val", ScalarValue::Float64(Some(0.0))),
2719            ],
2720            "ts",
2721        );
2722        assert!(publish_legacy_schema(native_answer(), &two_values).is_none());
2723
2724        // A label the native answer keeps and the existing answer does not publish has nothing to
2725        // be published under.
2726        let extra_label = plan_publishing_marked(
2727            &[
2728                ("ts", time_value()),
2729                ("val", ScalarValue::Float64(Some(2.0))),
2730                ("host", ScalarValue::Utf8(Some("a".to_string()))),
2731                ("dc", ScalarValue::Utf8(Some("x".to_string()))),
2732            ],
2733            "ts",
2734        );
2735        assert!(publish_legacy_schema(extra_label, &existing_answer()).is_none());
2736
2737        // A value the existing planner publishes as an integer is not the native float column.
2738        let integer_value = plan_publishing_marked(
2739            &[
2740                ("host", dictionary_label("a")),
2741                ("ts", time_value()),
2742                ("val", ScalarValue::Int64(Some(2))),
2743            ],
2744            "ts",
2745        );
2746        assert!(publish_legacy_schema(native_answer(), &integer_value).is_none());
2747    }
2748
2749    /// Labels are paired by name, so a series with several labels of the same type still pairs, and
2750    /// each label keeps its own values.
2751    #[test]
2752    fn labels_of_one_type_are_paired_by_name() {
2753        let native = plan_publishing_marked(
2754            &[
2755                ("ts", time_value()),
2756                ("rate(pf[2m])", ScalarValue::Float64(Some(2.0))),
2757                ("loc", ScalarValue::Utf8(Some("A".to_string()))),
2758                ("sensor", ScalarValue::Utf8(Some("s1".to_string()))),
2759                ("__name__", ScalarValue::Utf8(Some("pf".to_string()))),
2760            ],
2761            "ts",
2762        );
2763        let existing = plan_publishing_marked(
2764            &[
2765                ("sensor", dictionary_label("s1")),
2766                ("ts", time_value()),
2767                (
2768                    "prom_rate(ts_range,value,ts,Int64(120000))",
2769                    ScalarValue::Float64(Some(2.0)),
2770                ),
2771                ("loc", dictionary_label("A")),
2772            ],
2773            "ts",
2774        );
2775
2776        let published = publish_legacy_schema(native, &existing)
2777            .expect("each label has one native column of its name");
2778
2779        assert!(
2780            publishes_columns(published.schema().as_ref(), existing.schema().as_ref()),
2781            "{}",
2782            published.schema()
2783        );
2784        let LogicalPlan::Projection(projection) = &published else {
2785            panic!("the native plan is wrapped in a projection: {published}");
2786        };
2787        let sources = projection
2788            .expr
2789            .iter()
2790            .map(|expr| {
2791                let mut columns = expr.column_refs().into_iter();
2792                let column = columns.next().unwrap().name.clone();
2793                assert!(columns.next().is_none());
2794                column
2795            })
2796            .collect::<Vec<_>>();
2797        assert_eq!(sources, vec!["sensor", "ts", "rate(pf[2m])", "loc"]);
2798    }
2799
2800    /// The time index is paired by its marker, so a native answer that had to name its grid
2801    /// differently publishes it under the existing planner's name.
2802    #[test]
2803    fn the_time_index_is_paired_by_its_marker() {
2804        let renamed_time = plan_publishing_marked(
2805            &[
2806                ("native_time_0", time_value()),
2807                ("val", ScalarValue::Float64(Some(2.0))),
2808                ("host", ScalarValue::Utf8(Some("a".to_string()))),
2809            ],
2810            "native_time_0",
2811        );
2812        let existing = plan_publishing_marked(
2813            &[
2814                ("host", dictionary_label("a")),
2815                ("ts", time_value()),
2816                ("val", ScalarValue::Float64(Some(2.0))),
2817            ],
2818            "ts",
2819        );
2820        let published = publish_legacy_schema(renamed_time, &existing).unwrap();
2821        assert!(publishes_columns(
2822            published.schema().as_ref(),
2823            existing.schema().as_ref()
2824        ));
2825    }
2826
2827    #[tokio::test]
2828    async fn test_get_inferred_parameter_types_arrow_cast() {
2829        let plan = parse_sql_to_plan("SELECT $1::INT64, $2::FLOAT64, $3::INT16, $4::INT32, $5::UINT8, $6::UINT16, $7::UINT32").await;
2830        let types = DfLogicalPlanner::get_inferred_parameter_types(&plan).unwrap();
2831
2832        assert_eq!(types.get("$1"), Some(&Some(DataType::Int64)));
2833        assert_eq!(types.get("$2"), Some(&Some(DataType::Float64)));
2834        assert_eq!(types.get("$3"), Some(&Some(DataType::Int16)));
2835        assert_eq!(types.get("$4"), Some(&Some(DataType::Int32)));
2836        assert_eq!(types.get("$5"), Some(&Some(DataType::UInt8)));
2837        assert_eq!(types.get("$6"), Some(&Some(DataType::UInt16)));
2838        assert_eq!(types.get("$7"), Some(&Some(DataType::UInt32)));
2839
2840        let plan = parse_sql_to_plan("SELECT $1::INT8, $2::FLOAT8, $3::INT2, $4::INT8").await;
2841        let types = DfLogicalPlanner::get_inferred_parameter_types(&plan).unwrap();
2842
2843        assert_eq!(types.get("$1"), Some(&Some(DataType::Int64)));
2844        assert_eq!(types.get("$2"), Some(&Some(DataType::Float64)));
2845        assert_eq!(types.get("$3"), Some(&Some(DataType::Int16)));
2846    }
2847}