Skip to main content

query/dist_plan/
merge_sort.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
15//! Merge sort logical plan for distributed query execution, roughly corresponding to the
16//! `SortPreservingMergeExec` operator in datafusion
17//!
18
19use std::fmt;
20use std::sync::Arc;
21
22use datafusion::execution::TaskContext;
23use datafusion::physical_plan::execution_plan::CardinalityEffect;
24use datafusion::physical_plan::metrics::MetricsSet;
25use datafusion::physical_plan::projection::{ProjectionExec, make_with_child, update_ordering};
26use datafusion::physical_plan::sorts::sort::SortExec;
27use datafusion::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
28use datafusion::physical_plan::{
29    ChildStats, ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan,
30    InputDistributionRequirements, PlanProperties, ReplaceChildrenOptions,
31    SendableRecordBatchStream, Statistics, StatisticsArgs, apply_expression_roots,
32};
33use datafusion_common::tree_node::TreeNodeRecursion;
34use datafusion_common::{DataFusionError, Result};
35use datafusion_expr::{Extension, LogicalPlan, SortExpr, UserDefinedLogicalNodeCore};
36use datafusion_physical_expr::{LexOrdering, OrderingRequirements, PhysicalExpr};
37
38/// MergeSort Logical Plan, have same field as `Sort`, but indicate it is a merge sort,
39/// which assume each input partition is a sorted stream, and will use `SortPreserveingMergeExec`
40/// to merge them into a single sorted stream.
41#[derive(Hash, PartialOrd, PartialEq, Eq, Clone)]
42pub struct MergeSortLogicalPlan {
43    pub expr: Vec<SortExpr>,
44    pub input: Arc<LogicalPlan>,
45    pub fetch: Option<usize>,
46}
47
48impl fmt::Debug for MergeSortLogicalPlan {
49    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50        UserDefinedLogicalNodeCore::fmt_for_explain(self, f)
51    }
52}
53
54impl MergeSortLogicalPlan {
55    pub fn new(input: Arc<LogicalPlan>, expr: Vec<SortExpr>, fetch: Option<usize>) -> Self {
56        Self { input, expr, fetch }
57    }
58
59    pub fn name() -> &'static str {
60        "MergeSort"
61    }
62
63    /// Create a [`LogicalPlan::Extension`] node from this merge sort plan
64    pub fn into_logical_plan(self) -> LogicalPlan {
65        LogicalPlan::Extension(Extension {
66            node: Arc::new(self),
67        })
68    }
69}
70
71/// An opaque physical execution node for [`MergeSortLogicalPlan`].
72///
73/// It delegates execution and physical properties to DataFusion's
74/// [`SortPreservingMergeExec`], but intentionally does not expose itself as a
75/// `SortPreservingMergeExec`. `EnforceSorting` is allowed to replace a bare
76/// `SortPreservingMergeExec` with `CoalescePartitionsExec` when the parent does
77/// not require ordering. `MergeSortExec` represents the distributed TopK merge
78/// stage itself, so later physical optimizer rules must not rewrite it into an
79/// unordered fetch: for `ORDER BY ts DESC LIMIT 1` that would return the first
80/// row of one region instead of the global TopK.
81#[derive(Debug, Clone)]
82pub(crate) struct MergeSortExec {
83    inner: SortPreservingMergeExec,
84}
85
86impl MergeSortExec {
87    pub(crate) fn new(
88        ordering: LexOrdering,
89        input: Arc<dyn ExecutionPlan>,
90        fetch: Option<usize>,
91    ) -> Self {
92        Self {
93            inner: SortPreservingMergeExec::new(ordering, input).with_fetch(fetch),
94        }
95    }
96
97    fn input_with_fetch(&self, fetch: Option<usize>) -> Arc<dyn ExecutionPlan> {
98        let input = Arc::clone(self.inner.input());
99        if let Some(sort) = input.downcast_ref::<SortExec>()
100            && sort.preserve_partitioning()
101            && sort.expr() == self.inner.expr()
102        {
103            // Mirror DataFusion's bare SPM plan quality for distributed TopK:
104            // keep the parent `MergeSortExec(fetch)` as the global merge, and
105            // bound the partition-preserving child sort to the same local TopK.
106            // Local top-K is safe because every global top-K row must be within
107            // the top-K rows of its own input partition.
108            Arc::new(sort.with_fetch(fetch))
109        } else {
110            input
111        }
112    }
113}
114
115impl DisplayAs for MergeSortExec {
116    fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
117        match t {
118            DisplayFormatType::Default | DisplayFormatType::Verbose => {
119                write!(f, "MergeSortExec: [{}]", self.inner.expr())?;
120                if let Some(fetch) = self.inner.fetch() {
121                    write!(f, ", fetch={fetch}")?;
122                }
123                Ok(())
124            }
125            DisplayFormatType::TreeRender => {
126                if let Some(fetch) = self.inner.fetch() {
127                    writeln!(f, "limit={fetch}")?;
128                }
129
130                for (i, expr) in self.inner.expr().iter().enumerate() {
131                    expr.fmt_sql(f)?;
132                    if i != self.inner.expr().len() - 1 {
133                        write!(f, ", ")?;
134                    }
135                }
136
137                Ok(())
138            }
139        }
140    }
141}
142
143impl ExecutionPlan for MergeSortExec {
144    fn name(&self) -> &str {
145        "MergeSortExec"
146    }
147
148    fn properties(&self) -> &Arc<PlanProperties> {
149        self.inner.properties()
150    }
151
152    /// Forwards DataFusion's order-preserving scan hint through this wrapper.
153    ///
154    /// This mirrors `SortPreservingMergeExec::with_preserve_order()`: if the
155    /// child can produce an order-preserving variant, rebuild the same merge
156    /// stage on top of that child. The result must stay a `MergeSortExec`, not a
157    /// bare SPM; see the struct docs.
158    fn with_preserve_order(&self, preserve_order: bool) -> Option<Arc<dyn ExecutionPlan>> {
159        self.inner
160            .input()
161            .with_preserve_order(preserve_order)
162            .map(|new_input| {
163                Arc::new(Self::new(
164                    self.inner.expr().clone(),
165                    new_input,
166                    self.inner.fetch(),
167                )) as Arc<dyn ExecutionPlan>
168            })
169    }
170
171    fn input_distribution_requirements(&self) -> InputDistributionRequirements {
172        self.inner.input_distribution_requirements()
173    }
174
175    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
176        self.inner.benefits_from_input_partitioning()
177    }
178
179    /// Tells DataFusion that `MergeSortExec` requires each input partition to be
180    /// ordered. This is the contract that makes `EnforceSorting` insert a
181    /// `SortExec` below `MergeSortExec` when the input cannot preserve ordering.
182    fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
183        vec![Some(OrderingRequirements::from(self.inner.expr().clone()))]
184    }
185
186    fn maintains_input_order(&self) -> Vec<bool> {
187        self.inner.maintains_input_order()
188    }
189
190    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
191        self.inner.children()
192    }
193
194    fn apply_expressions(
195        &self,
196        f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
197    ) -> Result<TreeNodeRecursion> {
198        apply_expression_roots(self.inner.expr().iter().map(|sort_expr| &sort_expr.expr), f)
199    }
200
201    fn replace_children(
202        self: Arc<Self>,
203        mut children: Vec<Arc<dyn ExecutionPlan>>,
204        options: ReplaceChildrenOptions,
205    ) -> Result<Arc<dyn ExecutionPlan>> {
206        if children.len() != 1 {
207            return Err(DataFusionError::Internal(format!(
208                "MergeSortExec expects exactly one child, got {}",
209                children.len()
210            )));
211        }
212
213        match options.children_properties {
214            ChildrenPropertiesMode::Keep => Ok(Arc::new(Self {
215                inner: SortPreservingMergeExec::new(
216                    self.inner.expr().clone(),
217                    children.swap_remove(0),
218                )
219                .with_fetch(self.inner.fetch()),
220            })),
221            ChildrenPropertiesMode::Recompute => Ok(Arc::new(Self::new(
222                self.inner.expr().clone(),
223                children.swap_remove(0),
224                self.inner.fetch(),
225            ))),
226        }
227    }
228
229    #[allow(deprecated)]
230    fn with_new_children(
231        self: Arc<Self>,
232        children: Vec<Arc<dyn ExecutionPlan>>,
233    ) -> Result<Arc<dyn ExecutionPlan>> {
234        self.replace_children(
235            children,
236            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
237        )
238    }
239
240    fn execute(
241        &self,
242        partition: usize,
243        context: Arc<TaskContext>,
244    ) -> Result<SendableRecordBatchStream> {
245        self.inner.execute(partition, context)
246    }
247
248    fn metrics(&self) -> Option<MetricsSet> {
249        self.inner.metrics()
250    }
251
252    fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
253        self.inner.child_stats_requests(partition)
254    }
255
256    fn statistics_from_inputs(
257        &self,
258        input_stats: &[Arc<Statistics>],
259        args: &StatisticsArgs,
260    ) -> Result<Arc<Statistics>> {
261        self.inner.statistics_from_inputs(input_stats, args)
262    }
263
264    fn cardinality_effect(&self) -> CardinalityEffect {
265        self.inner.cardinality_effect()
266    }
267
268    /// Intentionally keeps DataFusion's generic limit pushdown disabled.
269    ///
270    /// `MergeSortExec` still supports its own global fetch through
271    /// `with_fetch()`. What we must not allow is pushing an external limit below
272    /// this required distributed TopK merge. DataFusion's limit pushdown rules
273    /// know how to treat a bare `SortPreservingMergeExec` as a
274    /// partition-combining node, but not this wrapper. Enabling generic limit
275    /// pushdown here could return partition-local rows instead of the global TopK.
276    fn supports_limit_pushdown(&self) -> bool {
277        false
278    }
279
280    fn fetch(&self) -> Option<usize> {
281        self.inner.fetch()
282    }
283
284    fn with_fetch(&self, limit: Option<usize>) -> Option<Arc<dyn ExecutionPlan>> {
285        Some(Arc::new(Self::new(
286            self.inner.expr().clone(),
287            self.input_with_fetch(limit),
288            limit,
289        )))
290    }
291
292    /// Lets DataFusion push a projection below this merge when it can rewrite
293    /// the ordering expressions safely.
294    ///
295    /// This mirrors `SortPreservingMergeExec::try_swapping_with_projection()`
296    /// for plan quality, but re-wraps the result as `MergeSortExec` so the
297    /// distributed merge stage keeps its type identity and opacity.
298    fn try_swapping_with_projection(
299        &self,
300        projection: &ProjectionExec,
301    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
302        if projection.expr().len() >= projection.input().schema().fields().len() {
303            return Ok(None);
304        }
305
306        let Some(updated_exprs) = update_ordering(self.inner.expr().clone(), projection.expr())?
307        else {
308            return Ok(None);
309        };
310
311        Ok(Some(Arc::new(Self::new(
312            updated_exprs,
313            make_with_child(projection, self.inner.input())?,
314            self.inner.fetch(),
315        ))))
316    }
317}
318
319impl UserDefinedLogicalNodeCore for MergeSortLogicalPlan {
320    fn name(&self) -> &str {
321        Self::name()
322    }
323
324    // Allow optimization here
325    fn inputs(&self) -> Vec<&LogicalPlan> {
326        vec![self.input.as_ref()]
327    }
328
329    fn schema(&self) -> &datafusion_common::DFSchemaRef {
330        self.input.schema()
331    }
332
333    // Allow further optimization
334    fn expressions(&self) -> Vec<datafusion_expr::Expr> {
335        self.expr.iter().map(|sort| sort.expr.clone()).collect()
336    }
337
338    fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {
339        write!(f, "MergeSort: ")?;
340        for (i, expr_item) in self.expr.iter().enumerate() {
341            if i > 0 {
342                write!(f, ", ")?;
343            }
344            write!(f, "{expr_item}")?;
345        }
346        if let Some(a) = self.fetch {
347            write!(f, ", fetch={a}")?;
348        }
349        Ok(())
350    }
351
352    fn with_exprs_and_inputs(
353        &self,
354        exprs: Vec<datafusion::prelude::Expr>,
355        mut inputs: Vec<LogicalPlan>,
356    ) -> Result<Self> {
357        let mut zelf = self.clone();
358        zelf.expr = zelf
359            .expr
360            .into_iter()
361            .zip(exprs)
362            .map(|(sort, expr)| sort.with_expr(expr))
363            .collect();
364        zelf.input = Arc::new(inputs.pop().ok_or_else(|| {
365            DataFusionError::Internal("Expected exactly one input with MergeSort".to_string())
366        })?);
367        Ok(zelf)
368    }
369}
370
371/// Turn `Sort` into `MergeSort` if possible
372pub fn merge_sort_transformer(plan: &LogicalPlan) -> Option<LogicalPlan> {
373    if let LogicalPlan::Sort(sort) = plan {
374        Some(
375            MergeSortLogicalPlan::new(sort.input.clone(), sort.expr.clone(), sort.fetch)
376                .into_logical_plan(),
377        )
378    } else {
379        None
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use arrow_schema::{DataType, Field, Schema, SortOptions};
386    use datafusion::physical_optimizer::enforce_sorting::replace_with_order_preserving_variants::{
387        OrderPreservationContext, plan_with_order_breaking_variants,
388    };
389    use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
390    use datafusion::physical_plan::displayable;
391    use datafusion::physical_plan::empty::EmptyExec;
392    use datafusion_physical_expr::PhysicalSortExpr;
393    use datafusion_physical_expr::expressions::col as physical_col;
394
395    use super::*;
396
397    /// Test double that records DataFusion's preserve-order signal while
398    /// otherwise behaving like a transparent wrapper around its child.
399    #[derive(Debug, Clone)]
400    struct PreserveOrderProbeExec {
401        inner: Arc<dyn ExecutionPlan>,
402        preserve_order: bool,
403    }
404
405    impl PreserveOrderProbeExec {
406        fn new(inner: Arc<dyn ExecutionPlan>) -> Self {
407            Self {
408                inner,
409                preserve_order: false,
410            }
411        }
412    }
413
414    impl DisplayAs for PreserveOrderProbeExec {
415        fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
416            write!(
417                f,
418                "PreserveOrderProbeExec: preserve_order={}",
419                self.preserve_order
420            )
421        }
422    }
423
424    impl ExecutionPlan for PreserveOrderProbeExec {
425        fn name(&self) -> &str {
426            "PreserveOrderProbeExec"
427        }
428
429        fn properties(&self) -> &Arc<PlanProperties> {
430            self.inner.properties()
431        }
432
433        fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
434            vec![&self.inner]
435        }
436
437        fn apply_expressions(
438            &self,
439            _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
440        ) -> Result<TreeNodeRecursion> {
441            Ok(TreeNodeRecursion::Continue)
442        }
443
444        fn with_new_children(
445            self: Arc<Self>,
446            mut children: Vec<Arc<dyn ExecutionPlan>>,
447        ) -> Result<Arc<dyn ExecutionPlan>> {
448            if children.len() != 1 {
449                return Err(DataFusionError::Internal(format!(
450                    "PreserveOrderProbeExec expects exactly one child, got {}",
451                    children.len()
452                )));
453            }
454
455            Ok(Arc::new(Self {
456                inner: children.swap_remove(0),
457                preserve_order: self.preserve_order,
458            }))
459        }
460
461        fn execute(
462            &self,
463            partition: usize,
464            context: Arc<TaskContext>,
465        ) -> Result<SendableRecordBatchStream> {
466            self.inner.execute(partition, context)
467        }
468
469        fn with_preserve_order(&self, preserve_order: bool) -> Option<Arc<dyn ExecutionPlan>> {
470            Some(Arc::new(Self {
471                inner: Arc::clone(&self.inner),
472                preserve_order,
473            }))
474        }
475    }
476
477    fn test_ordering(schema: &Schema) -> LexOrdering {
478        LexOrdering::new([PhysicalSortExpr::new(
479            physical_col("ts", schema).unwrap(),
480            SortOptions {
481                descending: true,
482                nulls_first: false,
483            },
484        )])
485        .unwrap()
486    }
487
488    #[test]
489    fn merge_sort_exec_is_opaque_and_preserves_topk_requirements() {
490        let schema = Arc::new(Schema::new(vec![Field::new("ts", DataType::Int64, false)]));
491        let input = Arc::new(EmptyExec::new(schema.clone()).with_partitions(2)) as _;
492        let ordering = test_ordering(schema.as_ref());
493
494        let merge_sort =
495            Arc::new(MergeSortExec::new(ordering, input, Some(1))) as Arc<dyn ExecutionPlan>;
496
497        assert_eq!(merge_sort.name(), "MergeSortExec");
498        assert!(
499            merge_sort
500                .downcast_ref::<SortPreservingMergeExec>()
501                .is_none(),
502            "MergeSortExec must stay opaque to EnforceSorting's bare SortPreservingMerge rewrite"
503        );
504        assert_eq!(merge_sort.fetch(), Some(1));
505        assert!(!merge_sort.supports_limit_pushdown());
506        assert!(merge_sort.required_input_ordering()[0].is_some());
507
508        let tree = displayable(merge_sort.as_ref()).tree_render().to_string();
509        assert!(tree.contains("MergeSortExec"));
510        assert!(!tree.contains("SortPreservingMergeExec"));
511
512        let fetched = merge_sort.with_fetch(Some(2)).unwrap();
513        assert!(fetched.downcast_ref::<MergeSortExec>().is_some());
514        assert_eq!(fetched.fetch(), Some(2));
515    }
516
517    #[test]
518    fn merge_sort_exec_required_input_ordering_matches_spm() {
519        let schema = Arc::new(Schema::new(vec![Field::new("ts", DataType::Int64, false)]));
520        let input = Arc::new(EmptyExec::new(schema.clone()).with_partitions(2)) as _;
521        let ordering = test_ordering(schema.as_ref());
522
523        let merge_sort = MergeSortExec::new(ordering.clone(), Arc::clone(&input), Some(1));
524        let bare_spm =
525            SortPreservingMergeExec::new(ordering.clone(), Arc::clone(&input)).with_fetch(Some(1));
526
527        assert_eq!(
528            merge_sort.required_input_ordering(),
529            vec![Some(OrderingRequirements::from(ordering))],
530            "MergeSortExec must require locally sorted input partitions for the merge key"
531        );
532        assert_eq!(
533            merge_sort.required_input_ordering(),
534            bare_spm.required_input_ordering(),
535            "MergeSortExec's child ordering contract should mirror SortPreservingMergeExec"
536        );
537        assert_eq!(
538            merge_sort.maintains_input_order(),
539            bare_spm.maintains_input_order()
540        );
541    }
542
543    #[test]
544    fn merge_sort_exec_with_fetch_pushes_fetch_to_child_sort() {
545        let schema = Arc::new(Schema::new(vec![Field::new("ts", DataType::Int64, false)]));
546        let input = Arc::new(EmptyExec::new(schema.clone()).with_partitions(2)) as _;
547        let ordering = test_ordering(schema.as_ref());
548        let child_sort =
549            Arc::new(SortExec::new(ordering.clone(), input).with_preserve_partitioning(true))
550                as Arc<dyn ExecutionPlan>;
551        let merge_sort = MergeSortExec::new(ordering, child_sort, None);
552
553        let fetched = merge_sort.with_fetch(Some(2)).unwrap();
554
555        assert!(fetched.downcast_ref::<MergeSortExec>().is_some());
556        assert_eq!(fetched.fetch(), Some(2));
557        let child_sort = fetched.children()[0].downcast_ref::<SortExec>().unwrap();
558        assert_eq!(child_sort.fetch(), Some(2));
559        assert!(child_sort.preserve_partitioning());
560    }
561
562    #[test]
563    fn merge_sort_exec_with_preserve_order_matches_spm_but_keeps_wrapper() {
564        let schema = Arc::new(Schema::new(vec![Field::new("ts", DataType::Int64, false)]));
565        let input = Arc::new(PreserveOrderProbeExec::new(Arc::new(
566            EmptyExec::new(schema.clone()).with_partitions(2),
567        ))) as _;
568        let ordering = test_ordering(schema.as_ref());
569
570        let bare_spm =
571            SortPreservingMergeExec::new(ordering.clone(), Arc::clone(&input)).with_fetch(Some(1));
572        let preserved_spm = bare_spm.with_preserve_order(true).unwrap();
573        assert!(
574            preserved_spm
575                .downcast_ref::<SortPreservingMergeExec>()
576                .is_some(),
577            "bare SPM should rebuild as bare SPM"
578        );
579        assert!(
580            preserved_spm.children()[0]
581                .downcast_ref::<PreserveOrderProbeExec>()
582                .unwrap()
583                .preserve_order
584        );
585
586        let merge_sort = MergeSortExec::new(ordering, input, Some(1));
587        let preserved_merge_sort = merge_sort.with_preserve_order(true).unwrap();
588        assert!(
589            preserved_merge_sort
590                .downcast_ref::<MergeSortExec>()
591                .is_some(),
592            "MergeSortExec must rewrap the preserve-order child as MergeSortExec"
593        );
594        assert!(
595            preserved_merge_sort
596                .downcast_ref::<SortPreservingMergeExec>()
597                .is_none(),
598            "MergeSortExec must not expose a bare SPM after with_preserve_order"
599        );
600        assert_eq!(preserved_merge_sort.fetch(), Some(1));
601        assert_eq!(
602            preserved_merge_sort.required_input_ordering(),
603            preserved_spm.required_input_ordering(),
604            "preserve-order rewrite should keep the same SPM child-ordering contract"
605        );
606        assert!(
607            preserved_merge_sort.children()[0]
608                .downcast_ref::<PreserveOrderProbeExec>()
609                .unwrap()
610                .preserve_order
611        );
612    }
613
614    #[test]
615    fn merge_sort_exec_projection_swap_matches_spm_but_keeps_wrapper() -> Result<()> {
616        let schema = Arc::new(Schema::new(vec![
617            Field::new("value", DataType::Int64, false),
618            Field::new("ts", DataType::Int64, false),
619            Field::new("tag", DataType::Utf8, false),
620        ]));
621        let input = Arc::new(EmptyExec::new(schema.clone()).with_partitions(2)) as _;
622        let ordering = test_ordering(schema.as_ref());
623
624        let bare_spm = Arc::new(
625            SortPreservingMergeExec::new(ordering.clone(), Arc::clone(&input)).with_fetch(Some(1)),
626        ) as Arc<dyn ExecutionPlan>;
627        let spm_projection = ProjectionExec::try_new(
628            vec![
629                (physical_col("ts", schema.as_ref())?, "ts".to_string()),
630                (physical_col("tag", schema.as_ref())?, "tag".to_string()),
631            ],
632            Arc::clone(&bare_spm),
633        )?;
634        let swapped_spm = bare_spm
635            .try_swapping_with_projection(&spm_projection)?
636            .expect("SPM should accept a narrowing projection that preserves the sort key");
637        assert!(
638            swapped_spm
639                .downcast_ref::<SortPreservingMergeExec>()
640                .is_some(),
641            "bare SPM should rebuild as bare SPM"
642        );
643
644        let merge_sort =
645            Arc::new(MergeSortExec::new(ordering, input, Some(1))) as Arc<dyn ExecutionPlan>;
646        let merge_projection = ProjectionExec::try_new(
647            vec![
648                (physical_col("ts", schema.as_ref())?, "ts".to_string()),
649                (physical_col("tag", schema.as_ref())?, "tag".to_string()),
650            ],
651            Arc::clone(&merge_sort),
652        )?;
653        let swapped_merge_sort = merge_sort
654            .try_swapping_with_projection(&merge_projection)?
655            .expect("MergeSortExec should accept the same projection swap as SPM");
656
657        assert!(
658            swapped_merge_sort.downcast_ref::<MergeSortExec>().is_some(),
659            "MergeSortExec must rewrap projection swaps as MergeSortExec"
660        );
661        assert!(
662            swapped_merge_sort
663                .downcast_ref::<SortPreservingMergeExec>()
664                .is_none(),
665            "MergeSortExec must not expose a bare SPM after projection swap"
666        );
667        assert_eq!(swapped_merge_sort.fetch(), Some(1));
668        assert!(
669            swapped_merge_sort.children()[0]
670                .downcast_ref::<ProjectionExec>()
671                .is_some(),
672            "the projection should move below MergeSortExec"
673        );
674        let swapped_schema = swapped_merge_sort.schema();
675        assert_eq!(
676            swapped_schema
677                .fields()
678                .iter()
679                .map(|field| field.name().as_str())
680                .collect::<Vec<_>>(),
681            vec!["ts", "tag"],
682            "swapped MergeSortExec should expose the projected schema"
683        );
684
685        let projected_ordering = LexOrdering::new([PhysicalSortExpr::new(
686            physical_col("ts", swapped_merge_sort.children()[0].schema().as_ref())?,
687            SortOptions {
688                descending: true,
689                nulls_first: false,
690            },
691        )])
692        .unwrap();
693        assert_eq!(
694            swapped_merge_sort.required_input_ordering(),
695            vec![Some(OrderingRequirements::from(projected_ordering))],
696            "projection swap must rewrite the ordering to the child projection's schema"
697        );
698        assert_eq!(
699            swapped_merge_sort.required_input_ordering(),
700            swapped_spm.required_input_ordering(),
701            "MergeSortExec projection swap should mirror SPM's ordering rewrite"
702        );
703
704        let spm_projection_without_sort_key = ProjectionExec::try_new(
705            vec![(physical_col("tag", schema.as_ref())?, "tag".to_string())],
706            Arc::clone(&bare_spm),
707        )?;
708        let merge_projection_without_sort_key = ProjectionExec::try_new(
709            vec![(physical_col("tag", schema.as_ref())?, "tag".to_string())],
710            Arc::clone(&merge_sort),
711        )?;
712        assert!(
713            bare_spm
714                .try_swapping_with_projection(&spm_projection_without_sort_key)?
715                .is_none(),
716            "SPM must reject projection swaps that drop the sort key"
717        );
718        assert!(
719            merge_sort
720                .try_swapping_with_projection(&merge_projection_without_sort_key)?
721                .is_none(),
722            "MergeSortExec should reject the same projection swap as SPM"
723        );
724
725        Ok(())
726    }
727
728    #[test]
729    fn enforce_sorting_rewrite_keeps_merge_sort_exec_opaque() {
730        let schema = Arc::new(Schema::new(vec![Field::new("ts", DataType::Int64, false)]));
731        let input = Arc::new(EmptyExec::new(schema.clone()).with_partitions(2)) as _;
732        let ordering = test_ordering(schema.as_ref());
733
734        let bare_spm = Arc::new(
735            SortPreservingMergeExec::new(ordering.clone(), Arc::clone(&input)).with_fetch(Some(1)),
736        ) as Arc<dyn ExecutionPlan>;
737        let optimized_spm = plan_with_order_breaking_variants(OrderPreservationContext::new(
738            bare_spm,
739            false,
740            vec![OrderPreservationContext::new(
741                Arc::clone(&input),
742                false,
743                vec![],
744            )],
745        ))
746        .unwrap()
747        .plan;
748        assert!(
749            optimized_spm
750                .downcast_ref::<CoalescePartitionsExec>()
751                .is_some(),
752            "this regression test must exercise EnforceSorting's bare SPM -> CoalescePartitionsExec rewrite"
753        );
754
755        let merge_sort =
756            Arc::new(MergeSortExec::new(ordering, input, Some(1))) as Arc<dyn ExecutionPlan>;
757        let optimized_merge_sort =
758            plan_with_order_breaking_variants(OrderPreservationContext::new(
759                Arc::clone(&merge_sort),
760                false,
761                vec![OrderPreservationContext::new(
762                    Arc::clone(merge_sort.children()[0]),
763                    false,
764                    vec![],
765                )],
766            ))
767            .unwrap()
768            .plan;
769        assert!(
770            optimized_merge_sort
771                .downcast_ref::<MergeSortExec>()
772                .is_some(),
773            "MergeSortExec must stay opaque to the bare SPM rewrite"
774        );
775        assert!(
776            optimized_merge_sort
777                .downcast_ref::<CoalescePartitionsExec>()
778                .is_none(),
779            "MergeSortExec(fetch) is the required distributed TopK merge stage, not an unordered coalesce"
780        );
781        assert_eq!(optimized_merge_sort.fetch(), Some(1));
782    }
783}