Skip to main content

query/dist_plan/
commutativity.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::collections::HashSet;
16use std::sync::Arc;
17
18use common_function::aggrs::aggr_wrapper::{
19    StateMergeHelper, get_aggr_func, is_all_aggr_exprs_steppable,
20};
21use common_telemetry::debug;
22use datafusion::error::Result as DfResult;
23use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
24use datafusion_expr::expr::NullTreatment;
25use datafusion_expr::{Expr, LogicalPlan, UserDefinedLogicalNode};
26use promql::extension_plan::{
27    EmptyMetric, FusedSeries, InstantManipulate, RangeManipulate, RawSeriesSource, SeriesDivide,
28    SeriesNormalize,
29};
30use promql::native::plan::{AggregateStage, NativeExpr, reads_across_series};
31use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME;
32
33use crate::dist_plan::MergeScanLogicalPlan;
34use crate::dist_plan::analyzer::AliasMapping;
35use crate::dist_plan::merge_sort::{MergeSortLogicalPlan, merge_sort_transformer};
36use crate::promql::planner::native::{independent_scan_pair, pointwise_operand, same_table_scans};
37
38/// generate the upper aggregation plan that will execute on the frontend.
39/// Basically a logical plan resembling the following:
40/// Projection:
41///     Aggregate:
42///
43/// from Aggregate
44///
45/// The upper Projection exists sole to make sure parent plan can recognize the output
46/// of the upper aggregation plan.
47pub fn step_aggr_to_upper_aggr(
48    aggr_plan: &LogicalPlan,
49) -> datafusion_common::Result<TransformerAction> {
50    let LogicalPlan::Aggregate(input_aggr) = aggr_plan else {
51        return Err(datafusion_common::DataFusionError::Plan(
52            "step_aggr_to_upper_aggr only accepts Aggregate plan".to_string(),
53        ));
54    };
55    if !is_all_aggr_exprs_steppable(&input_aggr.aggr_expr) {
56        return Err(datafusion_common::DataFusionError::NotImplemented(format!(
57            "Some aggregate expressions are not steppable in [{}]",
58            input_aggr
59                .aggr_expr
60                .iter()
61                .map(|e| e.to_string())
62                .collect::<Vec<_>>()
63                .join(", ")
64        )));
65    }
66
67    let step_aggr_plan = StateMergeHelper::split_aggr_node(input_aggr.clone())?;
68
69    Ok(TransformerAction {
70        extra_parent_plans: vec![step_aggr_plan.upper_merge],
71        new_child_plan: Some(step_aggr_plan.lower_state),
72    })
73}
74
75pub enum Commutativity {
76    Commutative,
77    PartialCommutative,
78    ConditionalCommutative(Option<Transformer>),
79    TransformedCommutative {
80        /// Return plans from parent to child order
81        transformer: StageTransformer,
82    },
83    NonCommutative,
84    Unimplemented,
85    /// For unrelated plans like DDL
86    Unsupported,
87}
88
89pub struct Categorizer {}
90
91impl Categorizer {
92    pub fn check_plan(
93        plan: &LogicalPlan,
94        partition_cols: Option<AliasMapping>,
95    ) -> DfResult<Commutativity> {
96        // Subquery is treated separately in `inspect_plan_with_subquery`. To avoid rewrite the
97        // "maybe rewritten" plan, stop the check here.
98        if has_subquery(plan)? {
99            return Ok(Commutativity::Unimplemented);
100        }
101
102        let partition_cols = partition_cols.unwrap_or_default();
103
104        let comm = match plan {
105            LogicalPlan::Projection(proj) => {
106                for expr in &proj.expr {
107                    let commutativity = Self::check_expr(expr);
108                    if !matches!(commutativity, Commutativity::Commutative) {
109                        return Ok(commutativity);
110                    }
111                }
112                Commutativity::Commutative
113            }
114            LogicalPlan::Filter(filter) => Self::check_expr(&filter.predicate),
115            LogicalPlan::Window(_) => Commutativity::Unimplemented,
116            LogicalPlan::Aggregate(aggr) => {
117                // The pinned Substrait codec drops IGNORE NULLS, so keep these aggregates on the frontend.
118                if aggr.aggr_expr.iter().any(|expr| {
119                    get_aggr_func(expr).is_some_and(|func| {
120                        func.params.null_treatment == Some(NullTreatment::IgnoreNulls)
121                    })
122                }) {
123                    return Ok(Commutativity::NonCommutative);
124                }
125                // The state/merge split maps each group expression to one output column,
126                // which doesn't hold for grouping sets.
127                let has_grouping_set = aggr
128                    .group_expr
129                    .iter()
130                    .any(|expr| matches!(expr, Expr::GroupingSet(_)));
131                let is_all_steppable =
132                    !has_grouping_set && is_all_aggr_exprs_steppable(&aggr.aggr_expr);
133                let matches_partition = Self::check_partition(&aggr.group_expr, &partition_cols);
134                if !matches_partition && is_all_steppable {
135                    debug!("Plan is steppable: {plan}");
136                    return Ok(Commutativity::TransformedCommutative {
137                        transformer: Arc::new(|plan: &LogicalPlan| {
138                            debug!("Before Step optimize: {plan}");
139                            step_aggr_to_upper_aggr(plan).inspect_err(|err| {
140                                common_telemetry::error!("Failed to step aggregate plan: {err:?}");
141                            })
142                        }),
143                    });
144                }
145                if !matches_partition {
146                    return Ok(Commutativity::NonCommutative);
147                }
148                for expr in &aggr.aggr_expr {
149                    let commutativity = Self::check_expr(expr);
150                    if !matches!(commutativity, Commutativity::Commutative) {
151                        return Ok(commutativity);
152                    }
153                }
154                // all group by expressions are partition columns can push down, unless
155                // another push down(including `Limit` or `Sort`) is already in progress(which will then prevent next cond commutative node from being push down).
156                // TODO(discord9): This is a temporary solution(that works), a better description of
157                // commutativity is needed under this situation.
158                Commutativity::ConditionalCommutative(None)
159            }
160            LogicalPlan::Sort(_sort) => {
161                if partition_cols.is_empty() {
162                    return Ok(Commutativity::Commutative);
163                }
164
165                // sort plan needs to consider column priority
166                // Change Sort to MergeSort which assumes the input streams are already sorted hence can be more efficient.
167                Commutativity::ConditionalCommutative(Some(Arc::new(merge_sort_transformer)))
168            }
169            LogicalPlan::Join(_) => Commutativity::NonCommutative,
170            LogicalPlan::Repartition(_) => {
171                // unsupported? or non-commutative
172                Commutativity::Unimplemented
173            }
174            LogicalPlan::Union(_) => Commutativity::Unimplemented,
175            LogicalPlan::TableScan(_) => Commutativity::Commutative,
176            LogicalPlan::EmptyRelation(_) => Commutativity::NonCommutative,
177            LogicalPlan::Subquery(_) => Commutativity::Unimplemented,
178            LogicalPlan::SubqueryAlias(_) => Commutativity::Commutative,
179            LogicalPlan::Limit(limit) => {
180                // Only execute `fetch` on remote nodes.
181                // wait for https://github.com/apache/arrow-datafusion/pull/7669
182                if partition_cols.is_empty() && limit.fetch.is_some() {
183                    Commutativity::Commutative
184                } else if limit.skip.is_none() && limit.fetch.is_some() {
185                    Commutativity::PartialCommutative
186                } else {
187                    Commutativity::Unimplemented
188                }
189            }
190            LogicalPlan::Extension(extension) => {
191                Self::check_extension_plan(extension.node.as_ref() as _, &partition_cols)
192            }
193            LogicalPlan::Distinct(_) => {
194                if partition_cols.is_empty() {
195                    Commutativity::Commutative
196                } else {
197                    Commutativity::PartialCommutative
198                }
199            }
200            LogicalPlan::Unnest(_) => Commutativity::Commutative,
201            LogicalPlan::Statement(_) => Commutativity::Unsupported,
202            LogicalPlan::Values(_) => Commutativity::Unsupported,
203            LogicalPlan::Explain(_) => Commutativity::Unsupported,
204            LogicalPlan::Analyze(_) => Commutativity::Unsupported,
205            LogicalPlan::DescribeTable(_) => Commutativity::Unsupported,
206            LogicalPlan::Dml(_) => Commutativity::Unsupported,
207            LogicalPlan::Ddl(_) => Commutativity::Unsupported,
208            LogicalPlan::Copy(_) => Commutativity::Unsupported,
209            LogicalPlan::RecursiveQuery(_) => Commutativity::Unsupported,
210        };
211
212        Ok(comm)
213    }
214
215    pub fn check_extension_plan(
216        plan: &dyn UserDefinedLogicalNode,
217        partition_cols: &AliasMapping,
218    ) -> Commutativity {
219        match plan.name() {
220            name if name == SeriesDivide::name() => {
221                let series_divide = plan.as_any().downcast_ref::<SeriesDivide>().unwrap();
222                // Metric engine `__tsid` uniquely identifies a time-series. Treat a series divide
223                // that keys by `__tsid` as commutative across regions so it can be pushed down.
224                if series_divide
225                    .tags()
226                    .iter()
227                    .any(|tag| tag == DATA_SCHEMA_TSID_COLUMN_NAME)
228                {
229                    return Commutativity::Commutative;
230                }
231
232                let tags = series_divide.tags().iter().collect::<HashSet<_>>();
233
234                for all_alias in partition_cols.values() {
235                    let all_alias = all_alias.iter().map(|c| &c.name).collect::<HashSet<_>>();
236                    if tags.intersection(&all_alias).count() == 0 {
237                        return Commutativity::NonCommutative;
238                    }
239                }
240
241                Commutativity::Commutative
242            }
243            name if name == FusedSeries::name() => {
244                let fused = plan.as_any().downcast_ref::<FusedSeries>().unwrap();
245                if fused.is_canonical_producer() {
246                    // A canonical producer merges the pieces of one label set that its own input
247                    // partitions hold, and its physical canonical router collects those pieces from
248                    // exactly those partitions. A region holds only part of a label set, so a
249                    // producer there would answer a label set from one region's share whenever the
250                    // pieces are spread. Nothing below the node changes that: a canonical cut wraps
251                    // its inputs in sources independently of how the scan was chosen, so the shape
252                    // is not a placement proof. The per-series rules below are not consulted: they
253                    // describe what a node computes, not where the pieces of a label set are.
254                    return Commutativity::NonCommutative;
255                }
256                // The raw-series reader supports one scan, or the narrow same-table multi-scan
257                // one-to-one case. This classification is for region-local execution only.
258                let children = fused.children();
259                if children.len() == 1 {
260                    if !matches!(children[0], LogicalPlan::TableScan(_)) {
261                        return Commutativity::NonCommutative;
262                    }
263                } else if !(same_table_scans(children)
264                    && independent_scan_pair(fused.tree().root()))
265                {
266                    return Commutativity::NonCommutative;
267                }
268                let binding = fused.binding();
269                if binding.metric_name.is_none() {
270                    return Commutativity::NonCommutative;
271                }
272                let root = fused.tree().root();
273                // A `Partial` root is safe below the region boundary only when its prefix itself
274                // reads per-series work. Do not rely on split admission here: hand-built trees can
275                // put a whole-vector operation below the aggregate. The `Final` half above the
276                // exchange is not classified here because its input is the exchange, not a scan.
277                let partial = matches!(
278                    &root.expr,
279                    NativeExpr::Aggregate { input, op }
280                        if op.stage == AggregateStage::Partial && !reads_across_series(input)
281                );
282                let per_series = pointwise_operand(root) || independent_scan_pair(root);
283                // A gather of one raw scan does not establish region-global ownership. Cross-series
284                // consumers need their existing split or frontend placement.
285                if reads_across_series(root) && !per_series && !partial {
286                    return Commutativity::NonCommutative;
287                }
288
289                // The multi-scan exception describes only in-process, same-table region-local
290                // execution. It is not a claim that matching is globally commutative across regions.
291                Commutativity::Commutative
292            }
293            // A region answers its own series of one table, which is what the node above the merge
294            // scans reads from every region.
295            name if name == RawSeriesSource::name() => {
296                if matches!(plan.inputs().as_slice(), [LogicalPlan::TableScan(_)]) {
297                    Commutativity::Commutative
298                } else {
299                    Commutativity::NonCommutative
300                }
301            }
302            name if name == SeriesNormalize::name()
303                || name == InstantManipulate::name()
304                || name == RangeManipulate::name() =>
305            {
306                // They should always follows Series Divide.
307                // Either all commutative or all non-commutative (which will be blocked by SeriesDivide).
308                Commutativity::Commutative
309            }
310            name if name == EmptyMetric::name()
311                || name == MergeScanLogicalPlan::name()
312                || name == MergeSortLogicalPlan::name() =>
313            {
314                Commutativity::Unimplemented
315            }
316            _ => Commutativity::Unsupported,
317        }
318    }
319
320    pub fn check_expr(expr: &Expr) -> Commutativity {
321        #[allow(deprecated)]
322        match expr {
323            Expr::Column(_)
324            | Expr::ScalarVariable(_, _)
325            | Expr::Literal(_, _)
326            | Expr::BinaryExpr(_)
327            | Expr::Not(_)
328            | Expr::IsNotNull(_)
329            | Expr::IsNull(_)
330            | Expr::IsTrue(_)
331            | Expr::IsFalse(_)
332            | Expr::IsNotTrue(_)
333            | Expr::IsNotFalse(_)
334            | Expr::Negative(_)
335            | Expr::Between(_)
336            | Expr::Exists(_)
337            | Expr::InList(_)
338            | Expr::Like(_)
339            | Expr::Case(_) => Commutativity::Commutative,
340            // Annotation collection must not affect distribution. Keep scalar UDFs pushdownable;
341            // TODO: Preserve datanode PromQL annotations through plan decoding, return them in
342            // Flight stream metadata, and merge them on the frontend.
343            Expr::ScalarFunction(_) => Commutativity::Commutative,
344            Expr::AggregateFunction(_udaf) => Commutativity::Commutative,
345
346            Expr::SimilarTo(_)
347            | Expr::IsUnknown(_)
348            | Expr::IsNotUnknown(_)
349            | Expr::WindowFunction(_)
350            | Expr::InSubquery(_)
351            | Expr::ScalarSubquery(_)
352            | Expr::HigherOrderFunction(_)
353            | Expr::Lambda(_)
354            | Expr::LambdaVariable(_)
355            | Expr::Wildcard { .. } => Commutativity::Unimplemented,
356
357            Expr::Alias(alias) => Self::check_expr(&alias.expr),
358            Expr::Cast(cast) => Self::check_expr(&cast.expr),
359            Expr::TryCast(try_cast) => Self::check_expr(&try_cast.expr),
360
361            Expr::Unnest(_)
362            | Expr::GroupingSet(_)
363            | Expr::Placeholder(_)
364            | Expr::OuterReferenceColumn(_, _)
365            | Expr::SetComparison(_) => Commutativity::Unimplemented,
366        }
367    }
368
369    /// Return true if the given expr and partition cols satisfied the rule.
370    /// In this case the plan can be treated as fully commutative.
371    ///
372    /// So only if every partition column is itself one of `exprs`, return true.
373    /// Otherwise return false.
374    ///
375    /// An expression that only references a partition column, like `substr(host, 3, 1)`
376    /// or `k % 2`, doesn't count: it can put rows from different partitions into the same
377    /// group.
378    fn check_partition(exprs: &[Expr], partition_cols: &AliasMapping) -> bool {
379        let group_cols = exprs
380            .iter()
381            .filter_map(|expr| {
382                let mut expr = expr;
383                while let Expr::Alias(alias) = expr {
384                    expr = &alias.expr;
385                }
386                match expr {
387                    Expr::Column(column) => Some(column.name.clone()),
388                    _ => None,
389                }
390            })
391            .collect::<HashSet<_>>();
392        for all_alias in partition_cols.values() {
393            let all_alias = all_alias
394                .iter()
395                .map(|c| c.name.clone())
396                .collect::<HashSet<_>>();
397            // check if group columns intersect with all alias of partition columns
398            // is empty, if it's empty, not all partition columns show up in `exprs`
399            if group_cols.intersection(&all_alias).count() == 0 {
400                return false;
401            }
402        }
403
404        true
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use std::collections::{BTreeMap, BTreeSet};
411    use std::time::{Duration, UNIX_EPOCH};
412
413    use datafusion::arrow::datatypes::{
414        DataType as ArrowDataType, Field, TimeUnit as ArrowTimeUnit,
415    };
416    use datafusion::common::{DFSchema, DFSchemaRef};
417    use datafusion::datasource::DefaultTableSource;
418    use datafusion_common::Column;
419    use datafusion_common::config::ConfigOptions;
420    use datafusion_expr::LogicalPlanBuilder;
421    use datafusion_expr::expr::ScalarFunction;
422    use datafusion_expr::{Extension, LogicalPlan, UserDefinedLogicalNodeCore};
423    use datafusion_functions::core::coalesce;
424    use datafusion_optimizer::analyzer::AnalyzerRule;
425    use datatypes::series::SeriesOrdering;
426    use datatypes::series::aggregate_state::{AggregateStateKind, StateComponent};
427    use datatypes::series::samples::{FieldSpec, SeriesSchema};
428    use promql::extension_plan::FieldKind;
429    use promql::extension_plan::{FusedSeries, FusedSeriesBinding, RawSeriesSource};
430    use promql::functions::{
431        NativeHistogramDrop, NativeHistogramFraction, NativeHistogramQuantile,
432    };
433    use promql::native::plan::{
434        AggregateKind, AggregateStage, AggregateStateSchema, BoundAggregate, BoundInput, Grouping,
435        NativeExpr, NativeNode, NativeTree, NativeType,
436    };
437    use promql_parser::parser;
438    use store_api::storage::RegionId;
439    use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
440
441    use super::*;
442    use crate::dist_plan::DistPlannerAnalyzer;
443    use crate::optimizer::test_util::mock_table_provider;
444    use crate::promql::native_compile::{compile, compile_selectors, statement_grid};
445    use crate::query_engine::DefaultSerializer;
446
447    #[test]
448    fn series_divide_by_tsid_is_commutative() {
449        let input = LogicalPlanBuilder::empty(false).build().unwrap();
450        let series_divide = SeriesDivide::new(
451            vec![DATA_SCHEMA_TSID_COLUMN_NAME.to_string()],
452            "ts".to_string(),
453            input,
454        );
455
456        let partition_cols: AliasMapping = BTreeMap::from([(
457            "some_partition_col".to_string(),
458            BTreeSet::from([Column::from_name("some_partition_col")]),
459        )]);
460
461        let commutativity = Categorizer::check_extension_plan(&series_divide, &partition_cols);
462        assert!(matches!(commutativity, Commutativity::Commutative));
463    }
464
465    #[test]
466    fn annotated_histogram_helpers_do_not_block_pushdown() {
467        for udf in [
468            NativeHistogramQuantile::scalar_udf(),
469            NativeHistogramFraction::scalar_udf(),
470            NativeHistogramDrop::warning_bool_false_udf(String::new(), None),
471        ] {
472            let helper = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(udf), vec![]));
473            let expr = Expr::ScalarFunction(ScalarFunction::new_udf(coalesce(), vec![helper]));
474            assert!(matches!(
475                Categorizer::check_expr(&expr),
476                Commutativity::Commutative
477            ));
478        }
479    }
480
481    /// The statement one `FusedSeries` test node is bound to.
482    fn native_statement() -> promql_parser::parser::EvalStmt {
483        promql_parser::parser::EvalStmt {
484            expr: parser::parse("some_metric").unwrap(),
485            start: UNIX_EPOCH,
486            end: UNIX_EPOCH
487                .checked_add(Duration::from_secs(100_000))
488                .unwrap(),
489            interval: Duration::from_secs(5),
490            lookback_delta: Duration::from_secs(1),
491        }
492    }
493
494    /// A `FusedSeries` node over `input`, bound to the tree a bare selector compiles to.
495    ///
496    /// The tree is the simplest shape the compiler accepts, because what these tests change is
497    /// where the node may be placed, not what it computes.
498    fn fused_series_plan(input: LogicalPlan) -> LogicalPlan {
499        fused_series_plan_named(input, Some("some_metric"))
500    }
501
502    fn fused_pair_plan(left: LogicalPlan, right: LogicalPlan) -> LogicalPlan {
503        let mut stmt = native_statement();
504        stmt.expr =
505            parser::parse("some_metric{host=\"left\"} + on(host) some_metric{host=\"right\"}")
506                .unwrap();
507        let series_schema = Arc::new(SeriesSchema {
508            fields: Arc::from([FieldSpec { name: "v0".into() }]),
509            eval_grid: None,
510        });
511        let tree = compile_selectors(
512            &stmt,
513            &|_| Ok(Arc::clone(&series_schema)),
514            SeriesOrdering::Contiguous,
515            Some(FieldKind::Float),
516        )
517        .unwrap()
518        .tree;
519        let binding = FusedSeriesBinding {
520            grid: statement_grid(&stmt).unwrap(),
521            time_index: "ts".to_string(),
522            tags: vec!["host".to_string()],
523            metric_name: Some(Arc::from("some_metric")),
524        };
525        let output_schema: DFSchemaRef = Arc::new(
526            DFSchema::new_with_metadata(
527                vec![(
528                    None,
529                    Arc::new(Field::new("v0", ArrowDataType::Float64, true)),
530                )],
531                Default::default(),
532            )
533            .unwrap(),
534        );
535        LogicalPlan::Extension(Extension {
536            node: Arc::new(
537                FusedSeries::try_new(
538                    Arc::from("some_metric{host=\"left\"} + on(host) some_metric{host=\"right\"}"),
539                    tree,
540                    binding,
541                    vec![left, right],
542                    output_schema,
543                )
544                .unwrap(),
545            ),
546        })
547    }
548
549    /// The same node, with the metric name it binds chosen by the caller.
550    fn fused_series_plan_named(input: LogicalPlan, metric_name: Option<&str>) -> LogicalPlan {
551        let stmt = native_statement();
552        let series_schema = Arc::new(SeriesSchema {
553            fields: Arc::from([FieldSpec { name: "v0".into() }]),
554            eval_grid: None,
555        });
556        let tree = compile(
557            &stmt,
558            Arc::clone(&series_schema),
559            SeriesOrdering::KeyThenTime,
560        )
561        .unwrap();
562        let binding = FusedSeriesBinding {
563            grid: statement_grid(&stmt).unwrap(),
564            time_index: "ts".to_string(),
565            tags: Vec::new(),
566            metric_name: metric_name.map(Arc::from),
567        };
568        let output_schema: DFSchemaRef = Arc::new(
569            DFSchema::new_with_metadata(
570                vec![
571                    (
572                        None,
573                        Arc::new(Field::new("v0", ArrowDataType::Float64, true)),
574                    ),
575                    (
576                        None,
577                        Arc::new(Field::new(
578                            "ts",
579                            ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
580                            false,
581                        )),
582                    ),
583                ],
584                Default::default(),
585            )
586            .unwrap(),
587        );
588
589        LogicalPlan::Extension(Extension {
590            node: Arc::new(
591                FusedSeries::try_new(
592                    Arc::from("some_metric"),
593                    tree,
594                    binding,
595                    vec![input],
596                    output_schema,
597                )
598                .unwrap(),
599            ),
600        })
601    }
602
603    /// A canonical producer of `some_metric` over `input`.
604    ///
605    /// The tree says what the compiler says at a canonical boundary - one evaluated vector merged by
606    /// canonical label set - and the `Merge` root is what marks the node as the producer of that
607    /// collection. The children are exactly what the caller supplies, so a test can hand the node
608    /// the region's own scan and ask where such a node may run.
609    fn canonical_producer_plan(input: LogicalPlan) -> LogicalPlan {
610        let stmt = native_statement();
611        let grid = statement_grid(&stmt).unwrap();
612        let evaluated = NativeType::Samples(Arc::new(SeriesSchema {
613            fields: Arc::from([FieldSpec { name: "v0".into() }]),
614            eval_grid: Some(Arc::clone(&grid)),
615        }));
616        let merge = NativeNode {
617            expr: NativeExpr::Merge {
618                input: Box::new(NativeNode {
619                    expr: NativeExpr::Input(BoundInput {
620                        output: evaluated.clone(),
621                        source_index: 0,
622                        ordering: SeriesOrdering::KeyThenTime,
623                        time_unit: Default::default(),
624                    }),
625                    output: evaluated.clone(),
626                }),
627            },
628            output: evaluated,
629        };
630        let binding = FusedSeriesBinding {
631            grid,
632            time_index: "ts".to_string(),
633            tags: Vec::new(),
634            metric_name: Some(Arc::from("some_metric")),
635        };
636        let tree = NativeTree::try_new(merge).unwrap();
637        LogicalPlan::Extension(Extension {
638            node: Arc::new(
639                FusedSeries::try_new_canonical_producer(
640                    Arc::from("some_metric"),
641                    tree,
642                    binding,
643                    vec![input],
644                )
645                .unwrap(),
646            ),
647        })
648    }
649
650    /// The region's own view of the metric's table: a scan whose provider is the region provider.
651    fn table_scan_plan() -> LogicalPlan {
652        let provider = mock_table_provider(RegionId::new(1, 1));
653        LogicalPlanBuilder::scan(
654            "some_metric",
655            Arc::new(DefaultTableSource::new(Arc::new(provider))),
656            None,
657        )
658        .unwrap()
659        .build()
660        .unwrap()
661    }
662
663    fn table_scan_plan_with_filter(value: &str) -> LogicalPlan {
664        let LogicalPlan::TableScan(mut scan) = table_scan_plan() else {
665            unreachable!();
666        };
667        scan.filters
668            .push(datafusion_expr::col("k0").eq(datafusion_expr::lit(value)));
669        LogicalPlan::TableScan(scan)
670    }
671
672    fn holds_fused_series(plan: &LogicalPlan) -> bool {
673        if let LogicalPlan::Extension(extension) = plan
674            && extension.node.as_any().is::<FusedSeries>()
675        {
676            return true;
677        }
678        plan.inputs().into_iter().any(holds_fused_series)
679    }
680
681    /// An extension node with no `ExtensionSerializer` branch: neither one under its own name nor
682    /// one it shares, since the serializer lists names and not shapes. It stands in for the nodes
683    /// that cannot reach a region as bytes for their own reasons, which the encoding gate must keep
684    /// honouring. The categorizer refuses it, as it refuses every name it does not know.
685    #[derive(Debug, PartialEq, Eq, Hash)]
686    struct UnserializableNode {
687        input: LogicalPlan,
688        schema: DFSchemaRef,
689    }
690
691    impl PartialOrd for UnserializableNode {
692        fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
693            let ordering = self.input.partial_cmp(&other.input);
694            match ordering {
695                Some(std::cmp::Ordering::Equal) if self.schema != other.schema => None,
696                ordering => ordering,
697            }
698        }
699    }
700
701    impl UnserializableNode {
702        fn new(input: LogicalPlan) -> Self {
703            let schema = input.schema().clone();
704            Self { input, schema }
705        }
706    }
707
708    impl UserDefinedLogicalNodeCore for UnserializableNode {
709        fn name(&self) -> &str {
710            "UnserializableNode"
711        }
712
713        fn inputs(&self) -> Vec<&LogicalPlan> {
714            vec![&self.input]
715        }
716
717        fn schema(&self) -> &DFSchemaRef {
718            &self.schema
719        }
720
721        fn expressions(&self) -> Vec<Expr> {
722            vec![]
723        }
724
725        fn fmt_for_explain(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
726            write!(f, "UnserializableNode")
727        }
728
729        fn with_exprs_and_inputs(
730            &self,
731            _exprs: Vec<Expr>,
732            mut inputs: Vec<LogicalPlan>,
733        ) -> DfResult<Self> {
734            Ok(Self::new(inputs.swap_remove(0)))
735        }
736    }
737
738    /// The plan that node builds over `input`.
739    fn unserializable_plan(input: LogicalPlan) -> LogicalPlan {
740        LogicalPlan::Extension(Extension {
741            node: Arc::new(UnserializableNode::new(input)),
742        })
743    }
744
745    fn holds_unserializable_node(plan: &LogicalPlan) -> bool {
746        if let LogicalPlan::Extension(extension) = plan
747            && extension.node.as_any().is::<UnserializableNode>()
748        {
749            return true;
750        }
751        plan.inputs().into_iter().any(holds_unserializable_node)
752    }
753
754    fn holds_table_scan(plan: &LogicalPlan) -> bool {
755        if matches!(plan, LogicalPlan::TableScan(_)) {
756            return true;
757        }
758        plan.inputs().into_iter().any(holds_table_scan)
759    }
760
761    /// The merge scan `plan` is, if it is one.
762    fn as_merge_scan(plan: &LogicalPlan) -> Option<&MergeScanLogicalPlan> {
763        if let LogicalPlan::Extension(extension) = plan {
764            extension
765                .node
766                .as_any()
767                .downcast_ref::<MergeScanLogicalPlan>()
768        } else {
769            None
770        }
771    }
772
773    /// The first merge scan in `plan`'s visible tree. A merge scan's remote input is not one of its
774    /// children, so this does not look into one.
775    fn first_merge_scan(plan: &LogicalPlan) -> Option<&MergeScanLogicalPlan> {
776        if let Some(merge_scan) = as_merge_scan(plan) {
777            return Some(merge_scan);
778        }
779        plan.inputs().into_iter().find_map(first_merge_scan)
780    }
781
782    fn analyze(analyzer: DistPlannerAnalyzer, plan: LogicalPlan) -> LogicalPlan {
783        analyzer.analyze(plan, &ConfigOptions::default()).unwrap()
784    }
785
786    fn analyzed(analyzer: DistPlannerAnalyzer, plan: LogicalPlan) -> DfResult<LogicalPlan> {
787        analyzer.analyze(plan, &ConfigOptions::default())
788    }
789
790    /// Whether the remote input of any merge scan in `plan` holds a node `wanted` accepts.
791    fn any_remote_input_holds(plan: &LogicalPlan, wanted: fn(&LogicalPlan) -> bool) -> bool {
792        let mut holds = false;
793        plan.apply(|node| {
794            if let Some(merge_scan) = as_merge_scan(node) {
795                holds |= wanted(merge_scan.input());
796            }
797            Ok(TreeNodeRecursion::Continue)
798        })
799        .unwrap();
800        holds
801    }
802
803    #[test]
804    fn fused_series_over_its_scan_is_commutative() {
805        let plan = fused_series_plan(table_scan_plan());
806
807        assert!(matches!(
808            Categorizer::check_plan(&plan, None).unwrap(),
809            Commutativity::Commutative
810        ));
811    }
812
813    /// The region builds the node from the scan's own raw-series entrypoint, so an input that is
814    /// not that scan leaves the node with nothing to read where it would be placed.
815    #[test]
816    fn fused_series_over_anything_but_a_scan_is_not_commutative() {
817        let scan = table_scan_plan();
818        let input = LogicalPlanBuilder::from(scan)
819            .filter(datafusion_expr::col("k0").eq(datafusion_expr::lit("a")))
820            .unwrap()
821            .build()
822            .unwrap();
823        let plan = fused_series_plan(input);
824
825        assert!(matches!(
826            Categorizer::check_plan(&plan, None).unwrap(),
827            Commutativity::NonCommutative
828        ));
829    }
830
831    /// The region asks the scan for one named metric's series, so a node binding no name cannot
832    /// be built there.
833    #[test]
834    fn fused_series_that_binds_no_metric_name_is_not_commutative() {
835        let plan = fused_series_plan_named(table_scan_plan(), None);
836
837        assert!(matches!(
838            Categorizer::check_plan(&plan, None).unwrap(),
839            Commutativity::NonCommutative
840        ));
841    }
842
843    /// A canonical producer never runs in a region, whatever its children look like: its router
844    /// collects the pieces of one label set from exactly the partitions the producer runs on, and a
845    /// region holds only part of a label set. A bare scan underneath does not on its own admit the
846    /// producer, so the node stays above the regions with its router.
847    #[test]
848    fn a_canonical_producer_is_not_commutative_even_over_a_bare_scan() {
849        let plan = canonical_producer_plan(table_scan_plan());
850        let LogicalPlan::Extension(extension) = &plan else {
851            unreachable!();
852        };
853        assert!(matches!(
854            Categorizer::check_extension_plan(extension.node.as_ref(), &AliasMapping::default()),
855            Commutativity::NonCommutative
856        ));
857        assert!(matches!(
858            Categorizer::check_plan(&plan, None).unwrap(),
859            Commutativity::NonCommutative
860        ));
861    }
862
863    /// A tree built by something other than the compiler can hold a node that folds several
864    /// series. The check is a property of the tree, so it is exercised on the node itself: the
865    /// compiler emits no such node today, and nothing else would build a tree containing one.
866    #[test]
867    fn a_tree_that_folds_across_series_is_not_per_series() {
868        let raw = NativeType::Samples(Arc::new(SeriesSchema {
869            fields: Arc::from([FieldSpec { name: "v0".into() }]),
870            eval_grid: None,
871        }));
872        let input = NativeNode {
873            expr: NativeExpr::Input(BoundInput {
874                output: raw.clone(),
875                source_index: 0,
876                ordering: SeriesOrdering::KeyThenTime,
877                time_unit: Default::default(),
878            }),
879            output: raw,
880        };
881        let group = Grouping::By(Arc::from(["k0".into()]));
882        let aggregate = NativeNode {
883            expr: NativeExpr::Aggregate {
884                input: Box::new(input),
885                op: BoundAggregate {
886                    kind: AggregateKind::Sum,
887                    group: group.clone(),
888                    stage: AggregateStage::Partial,
889                    field_kind: FieldKind::Float,
890                },
891            },
892            output: NativeType::AggregateState(Arc::new(AggregateStateSchema {
893                group,
894                kind: AggregateStateKind::Sum,
895                components: Arc::from([StateComponent::Value, StateComponent::Compensation]),
896                accumulators: Arc::from([]),
897                grid: statement_grid(&native_statement()).unwrap(),
898            })),
899        };
900        assert!(reads_across_series(&aggregate));
901
902        // The same walk over what the compiler emits stays per-series.
903        let single_selector = compile(
904            &native_statement(),
905            Arc::new(SeriesSchema {
906                fields: Arc::from([FieldSpec { name: "v0".into() }]),
907                eval_grid: None,
908            }),
909            SeriesOrdering::KeyThenTime,
910        )
911        .unwrap();
912        assert!(!reads_across_series(single_selector.root()));
913    }
914
915    #[test]
916    fn same_table_two_scan_fused_pair_is_region_local_commutative() {
917        let pair = fused_pair_plan(table_scan_plan(), table_scan_plan());
918        let LogicalPlan::Extension(extension) = pair else {
919            unreachable!();
920        };
921        assert!(matches!(
922            Categorizer::check_extension_plan(extension.node.as_ref(), &AliasMapping::default()),
923            Commutativity::Commutative
924        ));
925
926        let other_table = LogicalPlanBuilder::scan(
927            "other_metric",
928            Arc::new(DefaultTableSource::new(Arc::new(mock_table_provider(
929                RegionId::new(1, 1),
930            )))),
931            None,
932        )
933        .unwrap()
934        .build()
935        .unwrap();
936        let pair = fused_pair_plan(table_scan_plan(), other_table);
937        let LogicalPlan::Extension(extension) = pair else {
938            unreachable!();
939        };
940        assert!(matches!(
941            Categorizer::check_extension_plan(extension.node.as_ref(), &AliasMapping::default()),
942            Commutativity::NonCommutative
943        ));
944    }
945
946    /// Two tables are two regions: the pair stays above them and each table's raw source rides
947    /// in a merge scan of its own.
948    #[test]
949    fn cross_table_pair_runs_above_one_merge_scan_per_table() {
950        let source = |scan: LogicalPlan, metric: &str| {
951            LogicalPlan::Extension(Extension {
952                node: Arc::new(
953                    RawSeriesSource::try_new(
954                        Arc::from(metric),
955                        vec!["host".to_string()],
956                        vec!["v0".to_string()],
957                        scan,
958                    )
959                    .unwrap(),
960                ),
961            })
962        };
963        let other_table = LogicalPlanBuilder::scan(
964            "other_metric",
965            Arc::new(DefaultTableSource::new(Arc::new(mock_table_provider(
966                RegionId::new(2, 1),
967            )))),
968            None,
969        )
970        .unwrap()
971        .build()
972        .unwrap();
973        let pair = fused_pair_plan(
974            source(table_scan_plan(), "some_metric"),
975            source(other_table, "other_metric"),
976        );
977
978        let analyzed_plan = analyze(DistPlannerAnalyzer::default(), pair);
979        let LogicalPlan::Extension(root) = &analyzed_plan else {
980            panic!("the pair stays the root: {analyzed_plan}");
981        };
982        assert!(root.node.as_any().is::<FusedSeries>(), "{analyzed_plan}");
983        let remote_tables = root
984            .node
985            .inputs()
986            .into_iter()
987            .map(|input| {
988                let merge_scan = first_merge_scan(input).expect("each input is a merge scan");
989                let LogicalPlan::Extension(remote) = merge_scan.input() else {
990                    panic!("expected a raw source: {}", merge_scan.input());
991                };
992                let source = remote
993                    .node
994                    .as_any()
995                    .downcast_ref::<RawSeriesSource>()
996                    .expect("the region runs the raw source");
997                let [LogicalPlan::TableScan(scan)] = remote.node.inputs()[..] else {
998                    panic!("the raw source reads its scan: {}", merge_scan.input());
999                };
1000                (
1001                    source.metric_name().to_string(),
1002                    scan.table_name.to_string(),
1003                )
1004            })
1005            .collect::<Vec<_>>();
1006        assert_eq!(
1007            vec![
1008                ("some_metric".to_string(), "some_metric".to_string()),
1009                ("other_metric".to_string(), "other_metric".to_string()),
1010            ],
1011            remote_tables
1012        );
1013    }
1014
1015    /// The number of merge scans in `plan`'s visible tree.
1016    fn merge_scan_count(plan: &LogicalPlan) -> usize {
1017        usize::from(as_merge_scan(plan).is_some())
1018            + plan
1019                .inputs()
1020                .into_iter()
1021                .map(merge_scan_count)
1022                .sum::<usize>()
1023    }
1024
1025    /// Asserts the same-table pair landed, whole, in one merge scan's region input.
1026    ///
1027    /// What the pair computes survives placement: both selectors still read their own scan, with
1028    /// the filter each selector was built from, and the tree still names them by source index, so
1029    /// the first selector reads the first child.
1030    fn assert_pair_lands_in_one_region(plan: &LogicalPlan, label: &str) {
1031        assert_eq!(1, merge_scan_count(plan), "{label}: {plan}");
1032        let merge_scan = first_merge_scan(plan)
1033            .unwrap_or_else(|| panic!("{label}: expected one merge scan in: {plan}"));
1034        let remote = merge_scan.input();
1035        let fused = first_fused_series(remote)
1036            .unwrap_or_else(|| panic!("{label}: expected the pair in the region input: {remote}"));
1037        let children = fused.children();
1038        assert_eq!(
1039            2,
1040            children.len(),
1041            "{label}: expected the pair over exactly its two scans, got: {remote}"
1042        );
1043        let [LogicalPlan::TableScan(left), LogicalPlan::TableScan(right)] = children else {
1044            panic!("{label}: expected the pair to read two scans: {remote}");
1045        };
1046        assert_ne!(
1047            left.filters, right.filters,
1048            "{label}: each selector keeps its own filter: {remote}"
1049        );
1050
1051        let NativeExpr::Binary { left, right, .. } = &fused.tree().root().expr else {
1052            panic!(
1053                "{label}: expected a binary root: {:?}",
1054                fused.tree().root().expr
1055            );
1056        };
1057        let NativeExpr::Instant { input: left, .. } = &left.expr else {
1058            panic!("{label}: expected a left selector: {:?}", left.expr);
1059        };
1060        let NativeExpr::Input(left) = &left.expr else {
1061            panic!("{label}: expected a left source: {:?}", left.expr);
1062        };
1063        let NativeExpr::Instant { input: right, .. } = &right.expr else {
1064            panic!("{label}: expected a right selector: {:?}", right.expr);
1065        };
1066        let NativeExpr::Input(right) = &right.expr else {
1067            panic!("{label}: expected a right source: {:?}", right.expr);
1068        };
1069        assert_eq!(
1070            (0, 1),
1071            (left.source_index, right.source_index),
1072            "{label}: the selectors keep their source indexes: {remote}"
1073        );
1074    }
1075
1076    /// The pair is placed by what the plan is.
1077    ///
1078    /// One same-table pair, one placement: the whole pair lands in one merge scan's region input, no
1079    /// matter which wrappers a plan puts above it. The wrappers decide what the pair's input looks
1080    /// like only in that each selector keeps its own filter and its own source index.
1081    #[test]
1082    fn a_same_table_pair_lands_whole_in_one_region() {
1083        let pair = || {
1084            fused_pair_plan(
1085                table_scan_plan_with_filter("left"),
1086                table_scan_plan_with_filter("right"),
1087            )
1088        };
1089        let projection_over = |input: LogicalPlan| {
1090            LogicalPlanBuilder::from(input)
1091                .project(vec![datafusion_expr::col("v0")])
1092                .unwrap()
1093                .build()
1094                .unwrap()
1095        };
1096        let filter_over = |input: LogicalPlan| {
1097            LogicalPlanBuilder::from(input)
1098                .filter(datafusion_expr::col("v0").gt(datafusion_expr::lit(0.0f64)))
1099                .unwrap()
1100                .build()
1101                .unwrap()
1102        };
1103        let alias_over = |input: LogicalPlan| {
1104            LogicalPlanBuilder::from(input)
1105                .alias(datafusion_common::TableReference::bare("some_metric"))
1106                .unwrap()
1107                .build()
1108                .unwrap()
1109        };
1110        // One way to put a node above the plan under test.
1111        type Wrapper = fn(LogicalPlan) -> LogicalPlan;
1112        let wrapped: [(&str, Wrapper); 4] = [
1113            ("at the root", |pair| pair),
1114            ("under a projection", projection_over),
1115            ("under a filter", filter_over),
1116            ("under an alias", alias_over),
1117        ];
1118
1119        for (label, wrap) in wrapped {
1120            let plan = wrap(pair());
1121            let analyzed_plan = analyzed(DistPlannerAnalyzer::default(), plan)
1122                .unwrap_or_else(|err| panic!("{label}: {err}"));
1123            assert_pair_lands_in_one_region(&analyzed_plan, label);
1124        }
1125
1126        // The same wrappers stacked are still one pair in one region.
1127        let stacked = projection_over(filter_over(alias_over(pair())));
1128        let analyzed_plan = analyzed(DistPlannerAnalyzer::default(), stacked)
1129            .unwrap_or_else(|err| panic!("stacked: {err}"));
1130        assert_pair_lands_in_one_region(&analyzed_plan, "stacked");
1131    }
1132
1133    /// Ordinary fused producers are serializable, and where they may run is a placement decision
1134    /// with no transport in it: the encoder carries the plan, the categorizer says if the region
1135    /// may have it.
1136    #[test]
1137    fn fused_series_encoding_and_placement_are_independent() {
1138        let plan = fused_series_plan(table_scan_plan());
1139        let encoded = DFLogicalSubstraitConvertor
1140            .encode(&plan, DefaultSerializer)
1141            .expect("FusedSeries uses its ordinary serializer");
1142        assert!(!encoded.is_empty());
1143
1144        let in_process = analyze(DistPlannerAnalyzer::default(), plan.clone());
1145        assert!(any_remote_input_holds(&in_process, holds_fused_series));
1146
1147        // A partial producer exports aggregate state, which the codec carries like any other
1148        // frame; whether it may be pushed below a region boundary is decided by the analyzer's
1149        // placement rules, not by the encoder.
1150        let split = split_aggregate_plan(table_scan_plan());
1151        let final_node = as_final_split(&split).expect("the split's final half");
1152        let [producer] = final_node.children() else {
1153            panic!("expected the final node to have one partial child: {split}")
1154        };
1155        assert!(
1156            DFLogicalSubstraitConvertor
1157                .encode(producer, DefaultSerializer)
1158                .is_ok(),
1159            "a state-exporting producer encodes like any other node"
1160        );
1161        let placed = analyze(DistPlannerAnalyzer::default(), split);
1162        assert!(as_final_split(&placed).is_some());
1163        let child = placed.inputs();
1164        let [child] = child.as_slice() else {
1165            panic!("expected the final node's input: {placed}")
1166        };
1167        let scan = first_merge_scan(child).expect("merge scan below the final node");
1168        let producer = first_fused_series(scan.input()).expect("partial producer in region input");
1169        assert!(matches!(
1170            &producer.tree().root().expr,
1171            NativeExpr::Aggregate { op, .. } if op.stage == AggregateStage::Partial
1172        ));
1173        assert!(matches!(
1174            &producer.tree().root().output,
1175            NativeType::AggregateState(_)
1176        ));
1177    }
1178
1179    /// A split aggregate over a scan and bound to `sum(some_metric)`.
1180    ///
1181    /// The compiler's tree is split into a `Partial` state-exporting node over the scan and a
1182    /// `Final` node above it, matching the two halves a query plans.
1183    fn split_aggregate_plan(input: LogicalPlan) -> LogicalPlan {
1184        let stmt = promql_parser::parser::EvalStmt {
1185            expr: parser::parse("sum(some_metric)").unwrap(),
1186            ..native_statement()
1187        };
1188        let series_schema = Arc::new(SeriesSchema {
1189            fields: Arc::from([FieldSpec { name: "v0".into() }]),
1190            eval_grid: None,
1191        });
1192        let tree = compile(
1193            &stmt,
1194            Arc::clone(&series_schema),
1195            SeriesOrdering::KeyThenTime,
1196        )
1197        .unwrap();
1198        let binding = FusedSeriesBinding {
1199            grid: statement_grid(&stmt).unwrap(),
1200            metric_name: Some(Arc::from("some_metric")),
1201            time_index: "ts".to_string(),
1202            tags: Vec::new(),
1203        };
1204        let output_schema: DFSchemaRef = Arc::new(
1205            DFSchema::new_with_metadata(
1206                vec![
1207                    (
1208                        None,
1209                        Arc::new(Field::new(
1210                            "ts",
1211                            ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
1212                            false,
1213                        )),
1214                    ),
1215                    (
1216                        None,
1217                        Arc::new(Field::new("sum(v0)", ArrowDataType::Float64, true)),
1218                    ),
1219                ],
1220                Default::default(),
1221            )
1222            .unwrap(),
1223        );
1224
1225        let (partial_tree, final_tree) =
1226            FusedSeries::split_aggregate(&tree, "ts").unwrap().unwrap();
1227        let partial = FusedSeries::try_new_state_export(
1228            Arc::from("sum(some_metric)"),
1229            partial_tree,
1230            binding.clone(),
1231            vec![input],
1232        )
1233        .unwrap();
1234        let final_node = FusedSeries::try_new(
1235            Arc::from("sum(some_metric)"),
1236            final_tree,
1237            binding,
1238            vec![LogicalPlan::Extension(Extension {
1239                node: Arc::new(partial),
1240            })],
1241            output_schema,
1242        )
1243        .unwrap();
1244        LogicalPlan::Extension(Extension {
1245            node: Arc::new(final_node),
1246        })
1247    }
1248
1249    fn as_final_split(plan: &LogicalPlan) -> Option<&FusedSeries> {
1250        if let LogicalPlan::Extension(extension) = plan {
1251            extension
1252                .node
1253                .as_any()
1254                .downcast_ref::<FusedSeries>()
1255                .filter(|fused| fused.reads_aggregate_state())
1256        } else {
1257            None
1258        }
1259    }
1260
1261    /// The first fused producer in `plan`'s visible tree.
1262    fn first_fused_series(plan: &LogicalPlan) -> Option<&FusedSeries> {
1263        if let LogicalPlan::Extension(extension) = plan
1264            && let Some(fused) = extension.node.as_any().downcast_ref::<FusedSeries>()
1265        {
1266            return Some(fused);
1267        }
1268        plan.inputs().into_iter().find_map(first_fused_series)
1269    }
1270
1271    /// The final half stays above the cut; only the partial half is commutative.
1272    #[test]
1273    fn a_split_aggregate_is_commutative_only_below_the_cut() {
1274        let plan = split_aggregate_plan(table_scan_plan());
1275        assert!(matches!(
1276            Categorizer::check_plan(&plan, None).unwrap(),
1277            Commutativity::NonCommutative
1278        ));
1279
1280        let final_node = as_final_split(&plan).unwrap();
1281        let [partial] = final_node.children() else {
1282            panic!("expected the final node to have one partial child: {plan}");
1283        };
1284        assert!(matches!(
1285            Categorizer::check_plan(partial, None).unwrap(),
1286            Commutativity::Commutative
1287        ));
1288    }
1289
1290    /// The final half stays on the frontend and the partial half rides inside the region scan, for
1291    /// every deployment: the split aggregate's two halves are decided by what the plan is, so a
1292    /// stand-alone deployment and a distributed frontend share the structure.
1293    #[test]
1294    fn a_split_aggregate_finalizes_above_the_region() {
1295        let plan = split_aggregate_plan(table_scan_plan());
1296        assert!(
1297            DFLogicalSubstraitConvertor
1298                .encode(&plan, DefaultSerializer)
1299                .is_ok(),
1300            "a split plan encodes like any other plan; where it may run is a placement decision"
1301        );
1302
1303        let analyzed_plan = analyze(DistPlannerAnalyzer::default(), plan);
1304        assert!(
1305            as_final_split(&analyzed_plan).is_some(),
1306            "the final node must stay on the frontend: {analyzed_plan}"
1307        );
1308        let final_node = as_final_split(&analyzed_plan).unwrap();
1309        let [child] = final_node.children() else {
1310            panic!("expected the final node to keep one input: {analyzed_plan}");
1311        };
1312        let merge_scan = first_merge_scan(child).unwrap_or_else(|| {
1313            panic!("expected a merge scan below the final node: {analyzed_plan}")
1314        });
1315        let partial = first_fused_series(merge_scan.input()).unwrap_or_else(|| {
1316            panic!("expected the partial node in the region input: {analyzed_plan}")
1317        });
1318        assert!(!partial.reads_aggregate_state());
1319        assert!(matches!(
1320            &partial.tree().root().expr,
1321            NativeExpr::Aggregate { op, .. } if op.stage == AggregateStage::Partial
1322        ));
1323        assert!(holds_table_scan(merge_scan.input()));
1324        // The analyzer, not the codec, decides placement: a split aggregate's partial producer is
1325        // region-local work and belongs below the boundary.
1326        assert!(
1327            any_remote_input_holds(&analyzed_plan, holds_fused_series),
1328            "the analyzer keeps the partial producer below the region boundary: {analyzed_plan}"
1329        );
1330    }
1331
1332    /// The final half of `plan`, with its partial input replaced by `producer`.
1333    fn final_over(plan: LogicalPlan, producer: LogicalPlan) -> LogicalPlan {
1334        let LogicalPlan::Extension(extension) = &plan else {
1335            panic!("a split aggregate is an extension node: {plan}");
1336        };
1337        let fused = extension
1338            .node
1339            .as_any()
1340            .downcast_ref::<FusedSeries>()
1341            .expect("a split aggregate's final half is a FusedSeries");
1342        // Qualified: both `UserDefinedLogicalNode` and `UserDefinedLogicalNodeCore` declare this
1343        // method, and only the latter's answer is the node itself.
1344        let rebuilt =
1345            UserDefinedLogicalNodeCore::with_exprs_and_inputs(fused, Vec::new(), vec![producer])
1346                .expect("the final node holds the one input it is given");
1347        LogicalPlan::Extension(Extension {
1348            node: Arc::new(rebuilt),
1349        })
1350    }
1351
1352    /// A state-exporting producer satisfies the node above it, and nothing else. An ordinary
1353    /// values-producing fused child over the same scan travels with the plan the region runs, while
1354    /// the final half still never crosses: the categorizer places each by its own shape, and the
1355    /// encoder is not part of the decision.
1356    #[test]
1357    fn an_ordinary_producer_is_placed_by_encodability() {
1358        let scan = table_scan_plan();
1359        let split = split_aggregate_plan(scan.clone());
1360        let producer_placed = analyze(DistPlannerAnalyzer::default(), split.clone());
1361        assert!(
1362            any_remote_input_holds(&producer_placed, holds_fused_series),
1363            "the split's partial producer rides inside the final node: {producer_placed}"
1364        );
1365
1366        let values = fused_series_plan(scan);
1367        let swapped = final_over(split, values);
1368        let analyzed = analyze(DistPlannerAnalyzer::default(), swapped);
1369        assert!(
1370            as_final_split(&analyzed).is_some(),
1371            "the final half never crosses the wire: {analyzed}"
1372        );
1373        assert!(
1374            any_remote_input_holds(&analyzed, holds_fused_series),
1375            "an ordinary fused node encodes, so the region may run it: {analyzed}"
1376        );
1377        assert!(
1378            any_remote_input_holds(&analyzed, holds_table_scan),
1379            "the region still reads the scan the producer reads: {analyzed}"
1380        );
1381    }
1382
1383    /// A node the categorizer refuses draws the boundary at itself, whatever the transport: being
1384    /// unencodable is one more reason the region cannot run it, not the reason it stays above.
1385    #[test]
1386    fn a_plan_that_does_not_encode_for_another_reason_still_expands_at_that_node() {
1387        let plan = unserializable_plan(table_scan_plan());
1388        assert!(
1389            DFLogicalSubstraitConvertor
1390                .encode(&plan, DefaultSerializer)
1391                .is_err(),
1392            "the stand-in node has a serializer branch now, so it no longer proves anything"
1393        );
1394
1395        let analyzed = analyze(DistPlannerAnalyzer::default(), plan);
1396
1397        assert!(
1398            !any_remote_input_holds(&analyzed, holds_unserializable_node),
1399            "the analyzer placed a node the categorizer refuses: {analyzed}"
1400        );
1401        let inputs = analyzed.inputs();
1402        let [input] = inputs.as_slice() else {
1403            panic!("expected the node to keep one input in: {analyzed}");
1404        };
1405        // `expand` keeps a projection over the merge scan to restore the schema of what it wrapped.
1406        let merge_scan = first_merge_scan(input)
1407            .unwrap_or_else(|| panic!("expected the boundary right below the node in: {analyzed}"));
1408        assert!(
1409            holds_table_scan(merge_scan.input()),
1410            "expected the scan under the node to be the region input in: {analyzed}"
1411        );
1412    }
1413}
1414
1415pub type Transformer = Arc<dyn Fn(&LogicalPlan) -> Option<LogicalPlan>>;
1416
1417/// Returns transformer action that need to be applied
1418pub type StageTransformer = Arc<dyn Fn(&LogicalPlan) -> DfResult<TransformerAction>>;
1419
1420/// The Action that a transformer should take on the plan.
1421pub struct TransformerAction {
1422    /// list of plans that need to be applied to parent plans, in the order of parent to child.
1423    /// i.e. if this returns `[Projection, Aggregate]`, then the parent plan should be transformed to
1424    /// ```ignore
1425    /// Original Parent Plan:
1426    ///     Projection:
1427    ///         Aggregate:
1428    ///             MergeScan: ...
1429    /// ```
1430    pub extra_parent_plans: Vec<LogicalPlan>,
1431    /// new child plan, if None, use the original plan.
1432    pub new_child_plan: Option<LogicalPlan>,
1433}
1434
1435fn has_subquery(plan: &LogicalPlan) -> DfResult<bool> {
1436    let mut found = false;
1437    plan.apply_expressions(|e| {
1438        e.apply(|x| {
1439            if matches!(
1440                x,
1441                Expr::Exists(_) | Expr::InSubquery(_) | Expr::ScalarSubquery(_)
1442            ) {
1443                found = true;
1444                Ok(TreeNodeRecursion::Stop)
1445            } else {
1446                Ok(TreeNodeRecursion::Continue)
1447            }
1448        })
1449    })?;
1450    Ok(found)
1451}
1452
1453#[cfg(test)]
1454mod test {
1455    use datafusion_expr::{LogicalPlanBuilder, Sort};
1456
1457    use super::*;
1458
1459    #[test]
1460    fn sort_on_empty_partition() {
1461        let plan = LogicalPlan::Sort(Sort {
1462            expr: vec![],
1463            input: Arc::new(LogicalPlanBuilder::empty(false).build().unwrap()),
1464            fetch: None,
1465        });
1466        assert!(matches!(
1467            Categorizer::check_plan(&plan, Some(Default::default())).unwrap(),
1468            Commutativity::Commutative
1469        ));
1470    }
1471}