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


##########
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, the merge stays: a node above 
may rely on that partitioning, and the swapped join's one-partition output 
still satisfies it.



##########
datafusion/core/tests/physical_optimizer/join_selection.rs:
##########
@@ -2264,3 +2269,103 @@ async fn 
test_join_selection_skips_real_dynamic_filter_pushdown() -> Result<()>
 
     Ok(())
 }
+
+/// A session whose physical optimizer runs [`JoinSelection`] right after
+/// [`EnsureRequirements`] instead of before it.
+fn session_with_join_selection_after_enforcement() -> SessionContext {
+    let mut rules = PhysicalOptimizer::new().rules;
+    let position = |rules: &[Arc<dyn PhysicalOptimizerRule + Send + Sync>],

Review Comment:
   `rules` is already the public way to change the list 
(`PhysicalOptimizer::with_rules` points to the contract for non-default lists), 
and the test in `output_requirements.rs` reads it the same way, so a method 
would be new public API with only this test as a caller. If a test harness for 
other rule orders lands later, it would have more callers and I'd add the 
method there. OK to keep it as is here?



-- 
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