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