zhuqi-lucas commented on code in PR #27771:
URL: https://github.com/apache/datafusion/pull/27771#discussion_r4710846966


##########
datafusion/physical-optimizer/src/join_selection.rs:
##########
@@ -340,13 +346,90 @@ fn statistical_join_selection_subrule(
         None
     };
 
-    Ok(if let Some(transformed) = transformed {
-        Transformed::yes(transformed)
-    } else {
-        Transformed::no(plan)
+    Ok(match transformed {
+        Some(transformed) => match keep_satisfied_requirements(&plan, 
transformed)? {
+            Some(transformed) => Transformed::yes(transformed),
+            None => Transformed::no(plan),
+        },
+        None => Transformed::no(plan),
     })
 }
 
+/// Makes `new`, which replaces the join `old` over the same inputs, keep the
+/// order and distribution requirements that `old`'s inputs satisfy, because
+/// nothing restores them once `EnsureRequirements` has run.
+///
+/// A swap can make an input with several partitions the build side, which
+/// needs one partition, so that input gets a [`CoalescePartitionsExec`]. When
+/// `EnsureRequirements` runs later, it replaces this merge with the ones the
+/// plan needs. Returns `None`, so that the join is kept as it is, when the
+/// rewrite breaks any other requirement that held.
+///
+/// A hash join in [`PartitionMode::Auto`] has no requirement yet:
+/// `EnsureRequirements` resolves it and satisfies the requirements of the mode
+/// chosen for it.
+fn keep_satisfied_requirements(
+    old: &Arc<dyn ExecutionPlan>,
+    new: Arc<dyn ExecutionPlan>,
+) -> Result<Option<Arc<dyn ExecutionPlan>>> {
+    let mode_undecided = old
+        .downcast_ref::<HashJoinExec>()
+        .is_some_and(|join| join.partition_mode() == &PartitionMode::Auto);
+    if mode_undecided || check_input_requirements(old).is_err() {
+        return Ok(Some(new));
+    }
+    let inputs = old.children();
+    let is_input = |node: &Arc<dyn ExecutionPlan>| {
+        inputs.iter().any(|input| Arc::ptr_eq(input, node))
+    };
+    let merged = new
+        .transform_down(|node| {
+            if is_input(&node) {
+                return Ok(Transformed::new(node, false, 
TreeNodeRecursion::Jump));
+            }
+            let requirements = node.input_distribution_requirements();
+            let mut merged_any = false;
+            let children = node
+                .children()
+                .into_iter()
+                .enumerate()
+                .map(|(idx, child)| {
+                    let needs_one_partition = matches!(
+                        requirements.child_distribution(idx),
+                        Some(Distribution::SinglePartition)
+                    );
+                    if needs_one_partition
+                        && child.output_partitioning().partition_count() > 1
+                    {
+                        merged_any = true;
+                        
Arc::new(CoalescePartitionsExec::new(Arc::clone(child))) as _
+                    } else {
+                        Arc::clone(child)
+                    }
+                })
+                .collect();
+            Ok(if merged_any {
+                Transformed::yes(replace_children_if_necessary(node, 
children)?)
+            } else {
+                Transformed::no(node)
+            })
+        })?
+        .data;
+    let mut broken = false;

Review Comment:
   For `group_by.slt:3330`, the node relying on the order is the partial 
`AggregateExec` two levels above the join (a `ProjectionExec` in between), so a 
parent check wouldn't catch it. A whole-plan check like #27772 fixes it, but 
changes two default-order plans (`cte_materialized.slt`, 
`preserve_file_partitioning.slt`: `CollectLeft` becomes `Partitioned`), since 
before `EnsureRequirements` a simple plan can already satisfy its requirements.



##########
datafusion/physical-optimizer/src/join_selection.rs:
##########
@@ -340,13 +346,90 @@ fn statistical_join_selection_subrule(
         None
     };
 
-    Ok(if let Some(transformed) = transformed {
-        Transformed::yes(transformed)
-    } else {
-        Transformed::no(plan)
+    Ok(match transformed {
+        Some(transformed) => match keep_satisfied_requirements(&plan, 
transformed)? {
+            Some(transformed) => Transformed::yes(transformed),
+            None => Transformed::no(plan),
+        },
+        None => Transformed::no(plan),
     })
 }
 
+/// Makes `new`, which replaces the join `old` over the same inputs, keep the
+/// order and distribution requirements that `old`'s inputs satisfy, because
+/// nothing restores them once `EnsureRequirements` has run.
+///
+/// A swap can make an input with several partitions the build side, which
+/// needs one partition, so that input gets a [`CoalescePartitionsExec`]. When
+/// `EnsureRequirements` runs later, it replaces this merge with the ones the
+/// plan needs. Returns `None`, so that the join is kept as it is, when the
+/// rewrite breaks any other requirement that held.
+///
+/// A hash join in [`PartitionMode::Auto`] has no requirement yet:
+/// `EnsureRequirements` resolves it and satisfies the requirements of the mode
+/// chosen for it.
+fn keep_satisfied_requirements(
+    old: &Arc<dyn ExecutionPlan>,
+    new: Arc<dyn ExecutionPlan>,
+) -> Result<Option<Arc<dyn ExecutionPlan>>> {
+    let mode_undecided = old
+        .downcast_ref::<HashJoinExec>()
+        .is_some_and(|join| join.partition_mode() == &PartitionMode::Auto);
+    if mode_undecided || check_input_requirements(old).is_err() {
+        return Ok(Some(new));
+    }
+    let inputs = old.children();
+    let is_input = |node: &Arc<dyn ExecutionPlan>| {
+        inputs.iter().any(|input| Arc::ptr_eq(input, node))
+    };
+    let merged = new
+        .transform_down(|node| {
+            if is_input(&node) {
+                return Ok(Transformed::new(node, false, 
TreeNodeRecursion::Jump));
+            }
+            let requirements = node.input_distribution_requirements();
+            let mut merged_any = false;
+            let children = node
+                .children()
+                .into_iter()
+                .enumerate()
+                .map(|(idx, child)| {
+                    let needs_one_partition = matches!(
+                        requirements.child_distribution(idx),
+                        Some(Distribution::SinglePartition)
+                    );
+                    if needs_one_partition
+                        && child.output_partitioning().partition_count() > 1
+                    {
+                        merged_any = true;
+                        
Arc::new(CoalescePartitionsExec::new(Arc::clone(child))) as _

Review Comment:
   After a swap the old build side becomes the probe side but keeps its 
`CoalescePartitionsExec`, so with `JoinSelection` after `EnsureRequirements` 
the probe side runs in one partition. `SELECT big.column1, small.column1 FROM 
big, small` (two 2-file parquet tables, `target_partitions = 2`):
   ```
   CrossJoinExec
     CoalescePartitionsExec
       DataSourceExec  (small)
     CoalescePartitionsExec
       DataSourceExec  (big)
   ```
   Could the swap drop that merge when nothing else needs it?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to