@@ -49,8 +49,9 @@ use crate::enforce_sorting::sort_pushdown::{
4949} ;
5050use crate :: output_requirements:: OutputRequirementExec ;
5151use crate :: utils:: {
52- add_sort_above, add_sort_above_with_check, is_coalesce_partitions, is_limit,
53- is_repartition, is_sort, is_sort_preserving_merge, is_window,
52+ add_sort_above_with_check, add_sort_above_with_required_single,
53+ is_coalesce_partitions, is_limit, is_repartition, is_sort, is_sort_preserving_merge,
54+ is_window,
5455} ;
5556
5657use datafusion_common:: Result ;
@@ -489,6 +490,7 @@ pub fn ensure_sorting(
489490 } ;
490491
491492 let plan = & requirements. plan ;
493+ let required_distributions = plan. required_input_distribution ( ) ;
492494 let mut updated_children = vec ! [ ] ;
493495 for ( idx, ( required_ordering, mut child) ) in plan
494496 . required_input_ordering ( )
@@ -506,13 +508,14 @@ pub fn ensure_sorting(
506508 if physical_ordering. is_some ( ) {
507509 child = update_child_to_remove_unnecessary_sort ( idx, child, plan) ?;
508510 }
509- child = add_sort_above (
511+ child = add_sort_above_with_required_single (
510512 child,
511513 req,
512514 plan. as_any ( )
513515 . downcast_ref :: < OutputRequirementExec > ( )
514516 . map ( |output| output. fetch ( ) )
515517 . unwrap_or ( None ) ,
518+ matches ! ( required_distributions[ idx] , Distribution :: SinglePartition ) ,
516519 ) ;
517520 child = update_sort_ctx_children_data ( child, true ) ?;
518521 }
@@ -609,13 +612,15 @@ fn analyze_immediate_sort_removal(
609612fn adjust_window_sort_removal (
610613 mut window_tree : PlanWithCorrespondingSort ,
611614) -> Result < PlanWithCorrespondingSort > {
615+ let requires_single_partition = matches ! (
616+ window_tree. plan. required_input_distribution( ) [ 0 ] ,
617+ Distribution :: SinglePartition
618+ ) ;
619+
612620 // Window operators have a single child we need to adjust:
613621 let child_node = remove_corresponding_sort_from_sub_plan (
614622 window_tree. children . swap_remove ( 0 ) ,
615- matches ! (
616- window_tree. plan. required_input_distribution( ) [ 0 ] ,
617- Distribution :: SinglePartition
618- ) ,
623+ requires_single_partition,
619624 ) ?;
620625 window_tree. children . push ( child_node) ;
621626
@@ -647,7 +652,12 @@ fn adjust_window_sort_removal(
647652 // Satisfy the ordering requirement so that the window can run:
648653 let mut child_node = window_tree. children . swap_remove ( 0 ) ;
649654 if let Some ( reqs) = reqs {
650- child_node = add_sort_above ( child_node, reqs. into_single ( ) , None ) ;
655+ child_node = add_sort_above_with_required_single (
656+ child_node,
657+ reqs. into_single ( ) ,
658+ None ,
659+ requires_single_partition,
660+ ) ;
651661 }
652662 let child_plan = Arc :: clone ( & child_node. plan ) ;
653663 window_tree. children . push ( child_node) ;
0 commit comments