jayzhan211 commented on code in PR #27771:
URL: https://github.com/apache/datafusion/pull/27771#discussion_r4731274999


##########
datafusion/physical-optimizer/src/join_selection.rs:
##########
@@ -340,13 +346,117 @@ 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),
     })
 }
 
+/// Returns `new`, the rewrite of the join `old` over the same inputs, adjusted
+/// so that its inputs still satisfy the order and distribution requirements
+/// that `old`'s inputs satisfied, or `None` when that is not possible and 
`old`
+/// should be kept. Once `EnsureRequirements` has run, nothing repairs a
+/// requirement that stops holding.
+///
+/// When a swap makes an input with several partitions the build side, which
+/// needs one partition, that input gets a [`CoalescePartitionsExec`]. If
+/// `EnsureRequirements` runs later, it replaces this merge with the ones the
+/// plan needs. The merge the old build side had moves to the probe side, which
+/// needs none, and is dropped when `old`'s output had several partitions and 
no
+/// key, which nothing above the join can rely on.
+///
+/// Returns `new` unchanged when `old`'s inputs did not satisfy its 
requirements
+/// to begin with, usually because `EnsureRequirements` has not run yet, or 
when
+/// `old` is a hash join in [`PartitionMode::Auto`], whose mode and 
requirements
+/// `EnsureRequirements` chooses later.
+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 is_unchanged = |node: &Arc<dyn ExecutionPlan>| {
+        is_input(node)
+            || inputs.iter().any(|input| {
+                input
+                    .downcast_ref::<CoalescePartitionsExec>()
+                    .is_some_and(|merge| Arc::ptr_eq(merge.input(), node))
+            })
+    };
+    // Several partitions without a key satisfy only an unspecified 
distribution.
+    let output_has_no_key = matches!(

Review Comment:
   I went with a narrower check: `JoinSelection` keeps the join when the swap 
would lose the key its output was partitioned on, rather than whenever the 
output had a key. Is that OK for your pipeline? It leaves one case to a later 
`EnsureRequirements`, as on main: an `InterleaveExec` over a swapped 
partitioned join (the #21826 chain), because the interleave needs the same 
partitioning columns, not equal ones.
   
   Keeping the join whenever the output had a key would close that case, but 
the output of a partitioned join other than a full join always has a key, so 
those joins would never swap after `EnsureRequirements`. With `JoinSelection` 
after `EnsureRequirements` on the sqllogictest suite, 28 plans would keep the 
larger input as the build side, e.g. the fact table instead of the dimension 
table in `preserve_file_partitioning.slt:610`. With the narrower check those 
plans don't change. Your query is now a test.



##########
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:
   The swap now drops it when the old join's output had several partitions and 
no hash or range key, since nothing above the join can rely on such an output. 
When the output was hash or range partitioned, a node above may rely on that 
key, so the join is kept unless the swap keeps 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