1use 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
38pub 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 transformer: StageTransformer,
82 },
83 NonCommutative,
84 Unimplemented,
85 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 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 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 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 Commutativity::ConditionalCommutative(None)
159 }
160 LogicalPlan::Sort(_sort) => {
161 if partition_cols.is_empty() {
162 return Ok(Commutativity::Commutative);
163 }
164
165 Commutativity::ConditionalCommutative(Some(Arc::new(merge_sort_transformer)))
168 }
169 LogicalPlan::Join(_) => Commutativity::NonCommutative,
170 LogicalPlan::Repartition(_) => {
171 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 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 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 return Commutativity::NonCommutative;
255 }
256 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 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 if reads_across_series(root) && !per_series && !partial {
286 return Commutativity::NonCommutative;
287 }
288
289 Commutativity::Commutative
292 }
293 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 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 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 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 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 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 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 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 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 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 #[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 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 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 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 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 #[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 #[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 #[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 #[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 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 #[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 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 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 #[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 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 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 #[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 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 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 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 #[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 #[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 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 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 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 #[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 #[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 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
1417pub type StageTransformer = Arc<dyn Fn(&LogicalPlan) -> DfResult<TransformerAction>>;
1419
1420pub struct TransformerAction {
1422 pub extra_parent_plans: Vec<LogicalPlan>,
1431 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}