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


##########
datafusion/physical-plan/src/joins/hash_join/exec.rs:
##########
@@ -1246,6 +1246,45 @@ impl HashJoinExec {
         self.null_equality
     }
 
+    /// Return the [`InputDistributionRequirements`] that this hash join would
+    /// require if executed in [`PartitionMode::Partitioned`].
+    pub fn partitioned_input_distribution_requirements(

Review Comment:
   Optional cleanup: this is only called inside `HashJoinExec`, and keeping it 
private keeps it out of the public API, so its signature can change later 
without a breaking change.
   
   ```suggestion
       fn partitioned_input_distribution_requirements(
   ```



##########
datafusion/physical-optimizer/src/join_selection.rs:
##########
@@ -181,6 +186,10 @@ pub(crate) fn try_collect_left(
     ignore_threshold: bool,
     context: &dyn PhysicalOptimizerContext,
 ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
+    if hash_join.inputs_satisfy_partitioned_requirements()? {
+        return Ok(None);
+    }

Review Comment:
   @stuhood thanks for this! When the co-partitioned inputs have fewer 
partitions than `target_partitions` and `preserve_file_partitions` is off, 
`EnsureRequirements` hash-repartitions both inputs of the now-`Partitioned` 
join. So the large probe side gets shuffled where `CollectLeft` only coalesced 
the small side, which made my probe about 1.35x slower at 
`target_partitions=8`. It also adds those repartitions under 
`repartition_joins=false`, where the physical planner chose `CollectLeft`. 
Could we keep `Partitioned` only when the existing partitioning will survive?
   
   ```suggestion
       if keeps_input_partitioning(hash_join, context.config_options())
           && hash_join.inputs_satisfy_partitioned_requirements()?
       {
           return Ok(None);
       }
   ```
   
   with this helper next to `try_collect_left`. It mirrors 
`ChildPolicy::needs_hash_repartition` in `enforce_distribution.rs`; sharing one 
`pub(crate)` function there would also work:
   
   ```rs
   /// Whether `EnsureRequirements` keeps the join inputs' existing partitioning
   /// once the join is [`PartitionMode::Partitioned`]. Below 
`target_partitions`,
   /// and without `preserve_file_partitions`, it hash-repartitions both inputs 
to
   /// gain parallelism, shuffling the probe side that `CollectLeft` leaves in 
place.
   fn keeps_input_partitioning(hash_join: &HashJoinExec, config: 
&ConfigOptions) -> bool {
       let partition_count = 
hash_join.left().output_partitioning().partition_count();
       let preserve_file_partitions = config.optimizer.preserve_file_partitions;
       partition_count >= config.execution.target_partitions
           || (preserve_file_partitions > 0 && partition_count >= 
preserve_file_partitions)
   }
   ```
   
   <details>
   <summary>Timings, and a test that runs the full optimizer (fails on this PR, 
passes with the change)</summary>
   
   Two `ListingTable`s declared Range-partitioned into 3 partitions (12M-row 
fact, 300-row dim), `SELECT count(*), sum(f.v) FROM fact f JOIN dim d ON f.k = 
d.k`, release build, median of 7 runs over 3 rounds:
   
   | | target_partitions=3 | target_partitions=8 |
   |---|---|---|
   | main | 100-108 ms | 102-104 ms (`CollectLeft` + `RoundRobinBatch(8)` on 
the probe side) |
   | this PR | 94-108 ms | 136-145 ms (`Hash([k], 8)` on both sides) |
   
   The existing co-partitioned tests then need 
`config.execution.target_partitions = 2` in `check_hash_join_mode`, because 
their inputs have 2 partitions. The test also needs `use 
datafusion_physical_optimizer::optimizer::PhysicalOptimizer;`.
   
   ```rs
   #[rstest]
   #[case::fewer_than_target(4, 0, PartitionMode::CollectLeft)]
   #[case::equal_to_target(2, 0, PartitionMode::Partitioned)]
   #[case::preserved_file_partitions(4, 2, PartitionMode::Partitioned)]
   #[case::below_preserve_threshold(4, 3, PartitionMode::CollectLeft)]
   fn test_join_selection_co_partitioned_target_partitions(
       #[case] target_partitions: usize,
       #[case] preserve_file_partitions: usize,
       #[case] expected_mode: PartitionMode,
   ) -> Result<()> {
       let inputs = create_partitioned_test_inputs(
           PartitionCase::CoPartitionedHash,
           small_statistics(),
           big_statistics(),
       )?;
       let join = Arc::new(HashJoinExec::try_new(
           inputs.left,
           inputs.right,
           inputs.on,
           None,
           &JoinType::Inner,
           None,
           PartitionMode::Auto,
           NullEquality::NullEqualsNothing,
           false,
       )?);
       let mut config = ConfigOptions::new();
       config.execution.target_partitions = target_partitions;
       config.optimizer.preserve_file_partitions = preserve_file_partitions;
       // Run every default rule: `EnsureRequirements` must not hash-repartition
       // the inputs that `JoinSelection` kept `Partitioned` for.
       let mut plan: Arc<dyn ExecutionPlan> = join;
       for rule in PhysicalOptimizer::new().rules {
           plan = rule.optimize(plan, &config)?;
       }
       let hash_join = plan
           .downcast_ref::<HashJoinExec>()
           .expect("The type of the plan should not be changed");
       assert_eq!(*hash_join.partition_mode(), expected_mode);
       let plan_string = displayable(plan.as_ref()).indent(true).to_string();
       assert!(
           !plan_string.contains("partitioning=Hash"),
           "unexpected hash repartition:\n{plan_string}"
       );
       Ok(())
   }
   ```
   </details>



##########
datafusion/physical-plan/src/joins/hash_join/exec.rs:
##########
@@ -1246,6 +1246,45 @@ impl HashJoinExec {
         self.null_equality
     }
 
+    /// Return the [`InputDistributionRequirements`] that this hash join would
+    /// require if executed in [`PartitionMode::Partitioned`].
+    pub fn partitioned_input_distribution_requirements(
+        &self,
+    ) -> InputDistributionRequirements {
+        let (left_expr, right_expr) = self
+            .on
+            .iter()
+            .map(|(l, r)| (Arc::clone(l), Arc::clone(r)))
+            .unzip();
+        InputDistributionRequirements::co_partitioned(vec![
+            Distribution::KeyPartitioned(left_expr),
+            Distribution::KeyPartitioned(right_expr),
+        ])
+    }
+
+    /// Returns `true` if both inputs have more than 1 partition and already
+    /// satisfy the distribution and co-partitioning requirements for
+    /// [`PartitionMode::Partitioned`].
+    ///
+    /// Null-aware joins cannot use [`PartitionMode::Partitioned`] and return 
`false`.
+    pub fn inputs_satisfy_partitioned_requirements(&self) -> Result<bool> {

Review Comment:
   Optional cleanup: this needs to be `pub` only for `JoinSelection` in 
`datafusion-physical-optimizer`. Marking it as an [internal public 
API](https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis)
 lets us change it later without a deprecation.
   
   ```suggestion
       /// Null-aware joins cannot use [`PartitionMode::Partitioned`] and 
return `false`.
       ///
       /// # Public Only for Internal Use:
       ///
       /// This is not a public API and is for internal use only; see [API 
policy] for details.
       ///
       /// [API policy]: 
https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis
       #[doc(hidden)]
       pub fn inputs_satisfy_partitioned_requirements(&self) -> Result<bool> {
   ```



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