From 328e087c0e3ffe9133c45176bbd46a0dfaf6ecb0 Mon Sep 17 00:00:00 2001 From: Yongting You <2010youy01@gmail.com> Date: Mon, 30 Nov 2026 17:14:29 +0800 Subject: [PATCH 1/2] refactor: separate hash join swapping from partition selection --- .../physical_optimizer/join_selection.rs | 2 +- .../physical-optimizer/src/join_selection.rs | 253 ++++-------------- .../physical-plan/src/joins/hash_join/exec.rs | 177 ++++++++++-- .../src/joins/hash_join/exec/optimizations.rs | 147 ++++++++++ .../src/joins/hash_join/not_in.rs | 8 +- .../src/operator_statistics/mod.rs | 2 +- datafusion/sqllogictest/test_files/cte.slt | 7 + .../sqllogictest/test_files/explain_tree.slt | 19 +- datafusion/sqllogictest/test_files/joins.slt | 7 + 9 files changed, 392 insertions(+), 230 deletions(-) create mode 100644 datafusion/physical-plan/src/joins/hash_join/exec/optimizations.rs diff --git a/datafusion/core/tests/physical_optimizer/join_selection.rs b/datafusion/core/tests/physical_optimizer/join_selection.rs index 3ab64d77ae15e..745f49460b394 100644 --- a/datafusion/core/tests/physical_optimizer/join_selection.rs +++ b/datafusion/core/tests/physical_optimizer/join_selection.rs @@ -1065,7 +1065,7 @@ async fn test_hash_join_swap_on_joins_with_projections( )?); let swapped = join - .swap_inputs(PartitionMode::Partitioned) + .swap_inputs() .expect("swap_hash_join must support joins with projections"); let swapped_join = swapped .downcast_ref::() diff --git a/datafusion/physical-optimizer/src/join_selection.rs b/datafusion/physical-optimizer/src/join_selection.rs index 8740cddc45f7a..5ac2944776b52 100644 --- a/datafusion/physical-optimizer/src/join_selection.rs +++ b/datafusion/physical-optimizer/src/join_selection.rs @@ -8,10 +8,16 @@ //! tries to transform a non-runnable query (with the given infinite sources) //! into a runnable query by replacing pipeline-breaking join operations with //! pipeline-friendly ones. To achieve the second goal, it selects the proper -//! `PartitionMode` and the build side using the available statistics for hash joins. +//! build side and partition mode using the available statistics for hash joins. +//! +//! After normalizing joins with unbounded inputs, two bottom-up passes make +//! independent decisions: first fix the build side, then choose the partition +//! mode for that build side. The mode pass never swaps inputs. use crate::PhysicalOptimizerRule; -use crate::optimizer::{ConfigOnlyContext, PhysicalOptimizerContext}; +use crate::optimizer::{ + ConfigOnlyContext, PhysicalOptimizerContext, with_statistics_context, +}; use datafusion_common::Statistics; use datafusion_common::config::ConfigOptions; use datafusion_common::error::Result; @@ -23,10 +29,10 @@ use datafusion_physical_expr::expressions::Column; use datafusion_physical_plan::execution_plan::EmissionType; use datafusion_physical_plan::joins::utils::ColumnIndex; use datafusion_physical_plan::joins::{ - CrossJoinExec, HashJoinExec, NestedLoopJoinExec, PartitionMode, - StreamJoinPartitionMode, SymmetricHashJoinExec, + CrossJoinExec, HashJoinExec, NestedLoopJoinExec, StreamJoinPartitionMode, + SymmetricHashJoinExec, }; -use datafusion_physical_plan::statistics::StatisticsArgs; +use datafusion_physical_plan::statistics::{StatisticsArgs, StatisticsContext}; use datafusion_physical_plan::{ExecutionPlan, ExecutionPlanProperties}; use std::sync::Arc; @@ -97,24 +103,6 @@ pub(crate) fn should_swap_join_order( } } -fn supports_collect_by_thresholds( - plan: &Arc, - threshold_byte_size: usize, - threshold_num_rows: usize, - context: &dyn PhysicalOptimizerContext, -) -> bool { - let Ok(stats) = get_stats(plan, context) else { - return false; - }; - - // Stats use `Precision` to represent stats, where `Absent` means unknown. - // `Exact(0)` and `Inexact(0)` are both valid stats, and we should not treat - // them as unknown, `Absent` will return None (this is in regards to why - // `!=0` is not checked) - below_collect_thresholds(&stats, threshold_byte_size, threshold_num_rows) - .unwrap_or(false) -} - /// Whether `stats` is below the `CollectLeft` thresholds, comparing bytes when /// known and rows otherwise. `None` when the size is unknown. pub(crate) fn below_collect_thresholds( @@ -153,9 +141,18 @@ impl PhysicalOptimizerRule for JoinSelection { let new_plan = plan .transform_up(|p| apply_subrules(p, &subrules, context.config_options())) .data()?; - new_plan - .transform_up(|plan| statistical_join_selection_subrule(plan, context)) - .data() + with_statistics_context(context, |statistics| { + let new_plan = new_plan + .transform_up(|plan| { + statistical_join_swap_subrule(plan, context, statistics) + }) + .data()?; + new_plan + .transform_up(|plan| { + statistical_join_partition_mode_subrule(plan, context, statistics) + }) + .data() + }) } fn name(&self) -> &str { @@ -167,169 +164,14 @@ impl PhysicalOptimizerRule for JoinSelection { } } -/// Determines whether it is possible to swap inputs of a hash join. Of the -/// null-aware joins only a `LeftAnti` can be swapped: the resulting `RightAnti` -/// decides `NOT IN` per probe row, including multi-column and correlated -/// (scope keys or a join filter) shapes. A null-aware `LeftMark` has no -/// null-aware `RightMark` counterpart. -fn can_swap_hash_join(hash_join: &HashJoinExec) -> bool { - hash_join.join_type().supports_swap() - && (!hash_join.null_aware || *hash_join.join_type() == JoinType::LeftAnti) -} - -/// Tries to create a [`HashJoinExec`] in [`PartitionMode::CollectLeft`] when possible. -/// -/// This function will first consider the given join type and check whether the -/// `CollectLeft` mode is applicable. Otherwise, it will try to swap the join sides. -/// When the `ignore_threshold` is false, this function will also check left -/// and right sizes in bytes or rows. -/// -/// Used configurations -/// - `optimizer.hash_join_single_partition_threshold`: byte threshold for `CollectLeft` -/// - `optimizer.hash_join_single_partition_threshold_rows`: row threshold for `CollectLeft` -/// - `optimizer.join_reordering`: allows or forbids input swapping -pub(crate) fn try_collect_left( - hash_join: &HashJoinExec, - ignore_threshold: bool, - context: &dyn PhysicalOptimizerContext, -) -> Result>> { - let left = hash_join.left(); - let right = hash_join.right(); - let optimizer_config = &context.config_options().optimizer; - - let left_can_collect = ignore_threshold - || supports_collect_by_thresholds( - left, - optimizer_config.hash_join_single_partition_threshold, - optimizer_config.hash_join_single_partition_threshold_rows, - context, - ); - let right_can_collect = ignore_threshold - || supports_collect_by_thresholds( - right, - optimizer_config.hash_join_single_partition_threshold, - optimizer_config.hash_join_single_partition_threshold_rows, - context, - ); - - match (left_can_collect, right_can_collect) { - (true, true) => { - // For null-aware joins, we only swap `LeftAnti` joins where the left side is > right side - if can_swap_hash_join(hash_join) - && should_swap_join_order(left, right, context)? - { - Ok(Some(hash_join.swap_inputs(PartitionMode::CollectLeft)?)) - } else { - Ok(Some(Arc::new( - hash_join - .builder() - .with_partition_mode(PartitionMode::CollectLeft) - .build()?, - ))) - } - } - (true, false) => Ok(Some(Arc::new( - hash_join - .builder() - .with_partition_mode(PartitionMode::CollectLeft) - .build()?, - ))), - (false, true) => { - if optimizer_config.join_reordering && can_swap_hash_join(hash_join) { - hash_join.swap_inputs(PartitionMode::CollectLeft).map(Some) - } else { - Ok(None) - } - } - (false, false) => Ok(None), - } -} - -/// Creates a partitioned hash join execution plan, swapping inputs if beneficial. -/// -/// Checks if the join order should be swapped based on the join type and input statistics. -/// If swapping is optimal and supported, creates a swapped partitioned hash join; otherwise, -/// creates a standard partitioned hash join. -/// -/// Used configurations -/// - `optimizer.join_reordering`: allows or forbids statistics-driven join swapping -pub(crate) fn partitioned_hash_join( - hash_join: &HashJoinExec, - context: &dyn PhysicalOptimizerContext, -) -> Result> { - let left = hash_join.left(); - let right = hash_join.right(); - let partition_mode = if hash_join.null_aware { - PartitionMode::CollectLeft - } else { - PartitionMode::Partitioned - }; - if can_swap_hash_join(hash_join) && should_swap_join_order(left, right, context)? { - hash_join.swap_inputs(partition_mode) - } else { - // Null-aware anti joins must use CollectLeft mode because they track probe-side state - // (probe_side_non_empty, probe_side_has_null) per-partition, but need global knowledge - // for correct null handling. With partitioning, a partition might not see probe rows - // even if the probe side is globally non-empty, leading to incorrect NULL row handling. - - Ok(Arc::new( - hash_join - .builder() - .with_partition_mode(partition_mode) - .build()?, - )) - } -} - -/// This subrule tries to modify a given plan so that it can -/// optimize hash and cross joins in the plan according to available statistical -/// information. -/// -/// Used configurations -/// - `optimizer.hash_join_single_partition_threshold`: byte threshold for `CollectLeft` -/// - `optimizer.hash_join_single_partition_threshold_rows`: row threshold for `CollectLeft` -/// - `optimizer.join_reordering`: allows or forbids input swapping -fn statistical_join_selection_subrule( +/// Chooses build sides without changing partition modes. +fn statistical_join_swap_subrule( plan: Arc, context: &dyn PhysicalOptimizerContext, + statistics: &StatisticsContext, ) -> Result>> { let transformed = if let Some(hash_join) = plan.downcast_ref::() { - if !hash_join.dynamic_expressions_produced().is_empty() { - // Once a HashJoinExec carries a dynamic filter, its build side - // has already been determined and the dynamic filter has been wired - // to the probe side. Reordering inputs would invalidate the dynamic - // filter, so skip this join and leave it unchanged. - None - } else { - match hash_join.partition_mode() { - PartitionMode::Auto => try_collect_left(hash_join, false, context)? - .map_or_else( - || partitioned_hash_join(hash_join, context).map(Some), - |v| Ok(Some(v)), - )?, - PartitionMode::CollectLeft => try_collect_left(hash_join, true, context)? - .map_or_else( - || partitioned_hash_join(hash_join, context).map(Some), - |v| Ok(Some(v)), - )?, - PartitionMode::Partitioned => { - let left = hash_join.left(); - let right = hash_join.right(); - if can_swap_hash_join(hash_join) - && should_swap_join_order(left, right, context)? - { - // A null-aware join is never in `Partitioned` mode - // (`NotIn::try_new` rejects it), so the swap - // keeps the mode this arm matched on. - hash_join - .swap_inputs(PartitionMode::Partitioned) - .map(Some)? - } else { - None - } - } - } - } + hash_join.swap_inputs_if_beneficial(context.config_options(), statistics)? } else if let Some(cross_join) = plan.downcast_ref::() { let left = cross_join.left(); let right = cross_join.right(); @@ -359,6 +201,23 @@ fn statistical_join_selection_subrule( }) } +/// Chooses the `partition_mode` for [`HashJoinExec`]. +/// [`EnsureRequirements`](crate::ensure_requirements::EnsureRequirements) later +/// inserts operators to satisfy the resulting input distribution requirements. +fn statistical_join_partition_mode_subrule( + plan: Arc, + context: &dyn PhysicalOptimizerContext, + statistics: &StatisticsContext, +) -> Result>> { + let Some(join) = plan.downcast_ref::() else { + return Ok(Transformed::no(plan)); + }; + match join.choose_partition_mode(context.config_options(), statistics)? { + Some(join) => Ok(Transformed::yes(Arc::new(join) as _)), + None => Ok(Transformed::no(plan)), + } +} + /// Pipeline-fixing join selection subrule. pub type PipelineFixerSubrule = dyn Fn(Arc, &ConfigOptions) -> Result>; @@ -559,28 +418,18 @@ pub fn hash_join_swap_subrule( pub(crate) fn swap_join_according_to_unboundedness( hash_join: &HashJoinExec, ) -> Result> { - let partition_mode = hash_join.partition_mode(); let join_type = hash_join.join_type(); - match (*partition_mode, *join_type) { - ( - _, - JoinType::Right + if matches!( + join_type, + JoinType::Right | JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark - | JoinType::Full, - ) => internal_err!("{join_type} join cannot be swapped for unbounded input."), - (PartitionMode::Partitioned, _) => { - hash_join.swap_inputs(PartitionMode::Partitioned) - } - (PartitionMode::CollectLeft, _) => { - hash_join.swap_inputs(PartitionMode::CollectLeft) - } - (PartitionMode::Auto, _) => { - // Use `PartitionMode::Partitioned` as default if `Auto` is selected. - hash_join.swap_inputs(PartitionMode::Partitioned) - } + | JoinType::Full + ) { + return internal_err!("{join_type} join cannot be swapped for unbounded input."); } + hash_join.swap_inputs() } /// Apply given `PipelineFixerSubrule`s to a given plan. This plan, along with diff --git a/datafusion/physical-plan/src/joins/hash_join/exec.rs b/datafusion/physical-plan/src/joins/hash_join/exec.rs index dd2f172b28c53..009b7b7a2a3de 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec.rs @@ -100,6 +100,7 @@ use parking_lot::Mutex; use super::partitioned_hash_eval::SeededRandomState; +mod optimizations; mod prepared; pub use prepared::PreparedHashJoinBuild; @@ -1246,6 +1247,20 @@ impl HashJoinExec { self.null_equality } + 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 the dynamic filter expression produced by this hash join, if set. #[deprecated( since = "55.0.0", @@ -1416,8 +1431,7 @@ impl HashJoinExec { } /// Returns a new `ExecutionPlan` that computes the same join as this one, - /// with the left and right inputs swapped using the specified - /// `partition_mode`. + /// with the left and right inputs swapped, preserving the partition mode. /// /// # Notes: /// @@ -1451,10 +1465,7 @@ impl HashJoinExec { /// /// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis #[doc(hidden)] - pub fn swap_inputs( - &self, - partition_mode: PartitionMode, - ) -> Result> { + pub fn swap_inputs(&self) -> Result> { assert_or_internal_err!( self.dynamic_filter.is_none(), "Cannot swap HashJoinExec inputs after dynamic filters have been constructed. \ @@ -1480,7 +1491,6 @@ impl HashJoinExec { self.projection.as_deref(), self.join_type(), )) - .with_partition_mode(partition_mode) .build()?; // Semi / anti / mark joins output columns from one side only, so // swapping does not reorder them; an embedded projection already fixes @@ -1626,15 +1636,7 @@ impl ExecutionPlan for HashJoinExec { fn input_distribution_requirements(&self) -> InputDistributionRequirements { match self.mode { PartitionMode::Partitioned => { - 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), - ]) + self.partitioned_input_distribution_requirements() } PartitionMode::CollectLeft => InputDistributionRequirements::new(vec![ Distribution::SinglePartition, @@ -12040,7 +12042,7 @@ mod tests { fn swap_for_separate_execution( left_anti: &HashJoinExec, ) -> Result> { - let swapped = left_anti.swap_inputs(PartitionMode::CollectLeft)?; + let swapped = left_anti.swap_inputs()?; let swapped = swapped.downcast_ref::().unwrap(); Ok(Arc::new(swapped.builder().reset_state().build()?)) } @@ -12302,7 +12304,7 @@ mod tests { )? .set_dynamic_filter(dynamic_filter)?; - let err = join.swap_inputs(PartitionMode::CollectLeft).unwrap_err(); + let err = join.swap_inputs().unwrap_err(); assert_contains!( err.to_string(), "Cannot swap HashJoinExec inputs after dynamic filters have been constructed" @@ -12665,4 +12667,143 @@ mod tests { assert_contains!(error.to_string(), "Resources exhausted"); Ok(()) } + + #[rstest] + #[case::small_left(Some(1), Some(1), 1000, true)] + #[case::large_left(Some(1000), Some(1), 1, false)] + #[case::byte_threshold(Some(100), Some(1), 1, false)] + #[case::row_fallback(None, Some(1), 1000, true)] + #[case::row_threshold(None, Some(10), 1, false)] + #[case::unknown(None, None, 1, false)] + #[case::zero(Some(0), Some(0), 1000, true)] + fn choose_partition_mode_keeps_build_side( + #[case] left_bytes: Option, + #[case] left_rows: Option, + #[case] right_bytes: usize, + #[case] collect_left: bool, + ) -> Result<()> { + let (left_schema, right_schema, on) = build_schema_and_on()?; + let mut left_stats = Statistics::new_unknown(&left_schema); + left_stats.total_byte_size = left_bytes + .map(Precision::Exact) + .unwrap_or(Precision::Absent); + left_stats.num_rows = + left_rows.map(Precision::Exact).unwrap_or(Precision::Absent); + let mut right_stats = Statistics::new_unknown(&right_schema); + right_stats.total_byte_size = Precision::Exact(right_bytes); + let left: Arc = Arc::new(StatisticsExec::new( + left_stats, + left_schema.as_ref().clone(), + )); + let right: Arc = Arc::new(StatisticsExec::new( + right_stats, + right_schema.as_ref().clone(), + )); + let join = HashJoinExecBuilder::new( + Arc::clone(&left), + Arc::clone(&right), + on, + JoinType::Inner, + ) + .with_partition_mode(PartitionMode::Auto) + .build()?; + let mut config = ConfigOptions::new(); + config.execution.target_partitions = 4; + config.optimizer.hash_join_single_partition_threshold = 100; + config.optimizer.hash_join_single_partition_threshold_rows = 10; + + let selected = join + .choose_partition_mode(&config, &StatisticsContext::new())? + .expect("Auto must resolve to a concrete mode"); + + let children = selected.children(); + assert!(Arc::ptr_eq(children[0], &left)); + assert!(Arc::ptr_eq(children[1], &right)); + let expected_mode = if collect_left { + PartitionMode::CollectLeft + } else { + PartitionMode::Partitioned + }; + assert_eq!(*selected.partition_mode(), expected_mode); + assert!( + selected + .choose_partition_mode(&config, &StatisticsContext::new())? + .is_none() + ); + Ok(()) + } + + #[rstest] + #[case::one_partition(true, 1, false)] + #[case::repartition_disabled(false, 4, false)] + #[case::null_aware(true, 4, true)] + fn choose_partition_mode_respects_collect_constraints( + #[case] repartition_joins: bool, + #[case] target_partitions: usize, + #[case] null_aware: bool, + ) -> Result<()> { + let (left_schema, right_schema, on) = build_schema_and_on()?; + let left: Arc = Arc::new(StatisticsExec::new( + Statistics::new_unknown(&left_schema), + left_schema.as_ref().clone(), + )); + let right: Arc = Arc::new(StatisticsExec::new( + Statistics::new_unknown(&right_schema), + right_schema.as_ref().clone(), + )); + let join = HashJoinExecBuilder::new( + Arc::clone(&left), + Arc::clone(&right), + on, + JoinType::LeftAnti, + ) + .with_partition_mode(PartitionMode::Auto) + .with_null_aware(null_aware) + .build()?; + let mut config = ConfigOptions::new(); + config.execution.target_partitions = target_partitions; + config.optimizer.repartition_joins = repartition_joins; + config.optimizer.hash_join_single_partition_threshold = 0; + config.optimizer.hash_join_single_partition_threshold_rows = 0; + + let selected = join + .choose_partition_mode(&config, &StatisticsContext::new())? + .expect("Auto must resolve to a concrete mode"); + + let children = selected.children(); + assert!(Arc::ptr_eq(children[0], &left)); + assert!(Arc::ptr_eq(children[1], &right)); + assert_eq!(*selected.partition_mode(), PartitionMode::CollectLeft); + Ok(()) + } + + #[rstest] + #[case(PartitionMode::CollectLeft)] + #[case(PartitionMode::Partitioned)] + fn choose_partition_mode_preserves_explicit_mode( + #[case] mode: PartitionMode, + ) -> Result<()> { + let (left_schema, right_schema, on) = build_schema_and_on()?; + let left = Arc::new(StatisticsExec::new( + Statistics::new_unknown(&left_schema), + left_schema.as_ref().clone(), + )); + let right = Arc::new(StatisticsExec::new( + Statistics::new_unknown(&right_schema), + right_schema.as_ref().clone(), + )); + let join = HashJoinExecBuilder::new(left, right, on, JoinType::Inner) + .with_partition_mode(mode) + .build()?; + let mut config = ConfigOptions::new(); + config.execution.target_partitions = 1; + config.optimizer.hash_join_single_partition_threshold = 0; + config.optimizer.hash_join_single_partition_threshold_rows = 0; + + assert!( + join.choose_partition_mode(&config, &StatisticsContext::new())? + .is_none() + ); + Ok(()) + } } diff --git a/datafusion/physical-plan/src/joins/hash_join/exec/optimizations.rs b/datafusion/physical-plan/src/joins/hash_join/exec/optimizations.rs new file mode 100644 index 0000000000000..4a01ead209b58 --- /dev/null +++ b/datafusion/physical-plan/src/joins/hash_join/exec/optimizations.rs @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Optimizer hooks for [`HashJoinExec`]. + +use super::*; +use crate::statistics::StatisticsContext; +use datafusion_common::config::OptimizerOptions; + +impl HashJoinExec { + /// Uses statistics to choose the smaller input as the build side. + /// + /// Returns `Some` with the swapped plan if swapping is allowed and beneficial, + /// or `None` otherwise. + /// + /// # Implementation + /// + /// Compare sizes first. If one side is known-small, another side has unknown + /// stat, put the known-small to the left side. + /// + /// ## Example + /// + /// Both sizes are known, swap since right side is smaller: + /// + /// ```text + /// left: 10 MB + /// right: 5 MB + /// result: swap + /// ``` + /// + /// Only the right size is known, swap since it's below threshold: + /// + /// ```text + /// left: unknown size + /// right: 1 MB, below the configured broadcast threshold + /// result: swap + /// ``` + /// + /// # 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 swap_inputs_if_beneficial( + &self, + config: &ConfigOptions, + statistics: &StatisticsContext, + ) -> Result>> { + if !config.optimizer.join_reordering + || !self.join_type.supports_swap() + || (self.null_aware && self.join_type != JoinType::LeftAnti) + || self.dynamic_filter.is_some() + || self.prepared_build.is_some() + || self.left.boundedness().is_unbounded() + || self.right.boundedness().is_unbounded() + { + return Ok(None); + } + + let left = statistics.compute_arc(&self.left, &StatisticsArgs::new())?; + let right = statistics.compute_arc(&self.right, &StatisticsArgs::new())?; + + // See the `Implementation` section above. + let should_swap = left_is_larger(&left, &right).unwrap_or_else(|| { + !can_collect(&left, &config.optimizer) + && can_collect(&right, &config.optimizer) + }); + + should_swap.then(|| self.swap_inputs()).transpose() + } + + /// Resolves [`PartitionMode::Auto`] partition mode. + /// + /// Assumes the input order is final and will not be swapped afterward. + /// [JoinSelection] first traverses the plan only to swap inputs, then runs + /// a second traversal to choose partition modes with this method. + /// + /// The implementation follows: + /// 1. Choose `CollectLeft` if + /// - Required (e.g. from configuration) + /// - Left side statistics is below configured size threshold + /// 2. Otherwise use `Partitioned` + /// + /// # Public Only for Internal Use: + /// + /// This is not a public API and is for internal use only; see [API policy] for details. + /// + /// [JoinSelection]: https://docs.rs/datafusion-physical-optimizer/latest/datafusion_physical_optimizer/join_selection/index.html + /// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis + #[doc(hidden)] + pub fn choose_partition_mode( + &self, + config: &ConfigOptions, + statistics: &StatisticsContext, + ) -> Result> { + if self.mode != PartitionMode::Auto { + return Ok(None); + } + + let builder = self.builder(); + if config.execution.target_partitions <= 1 + || !config.optimizer.repartition_joins + || self.null_aware + { + return builder + .with_partition_mode(PartitionMode::CollectLeft) + .build() + .map(Some); + } + + let collect_left = statistics + .compute_arc(&self.left, &StatisticsArgs::new()) + .is_ok_and(|stats| can_collect(&stats, &config.optimizer)); + let mode = if collect_left { + PartitionMode::CollectLeft + } else { + PartitionMode::Partitioned + }; + builder.with_partition_mode(mode).build().map(Some) + } +} + +fn can_collect(stats: &Statistics, config: &OptimizerOptions) -> bool { + if let Some(bytes) = stats.total_byte_size.get_value() { + *bytes < config.hash_join_single_partition_threshold + } else { + stats + .num_rows + .get_value() + .is_some_and(|rows| *rows < config.hash_join_single_partition_threshold_rows) + } +} + +fn left_is_larger(left: &Statistics, right: &Statistics) -> Option { + match ( + left.total_byte_size.get_value(), + right.total_byte_size.get_value(), + ) { + (Some(left), Some(right)) => Some(left > right), + _ => match (left.num_rows.get_value(), right.num_rows.get_value()) { + (Some(left), Some(right)) => Some(left > right), + _ => None, + }, + } +} diff --git a/datafusion/physical-plan/src/joins/hash_join/not_in.rs b/datafusion/physical-plan/src/joins/hash_join/not_in.rs index 3e0574a5a7607..7672e12d8abed 100644 --- a/datafusion/physical-plan/src/joins/hash_join/not_in.rs +++ b/datafusion/physical-plan/src/joins/hash_join/not_in.rs @@ -107,9 +107,11 @@ impl NotIn { let output = match (join_type, partition_mode) { (JoinType::LeftAnti, _) => Some(NotInOutput::Rows), (JoinType::LeftMark, _) => Some(NotInOutput::Mark), - // `PartitionMode::CollectLeft` is safe because `RightAnti` is - // probe-driven: every probe row sees the whole build side. - (JoinType::RightAnti, PartitionMode::CollectLeft) => None, + // `Auto` is allowed while choosing the build side; mode selection + // must resolve it to `CollectLeft` before execution. + (JoinType::RightAnti, PartitionMode::CollectLeft | PartitionMode::Auto) => { + None + } _ => { return plan_err!( "null_aware can only be true for LeftAnti joins and RightAnti joins with `CollectLeft` `PartitionMode`, or LeftMark joins, got {join_type} with {partition_mode}" diff --git a/datafusion/physical-plan/src/operator_statistics/mod.rs b/datafusion/physical-plan/src/operator_statistics/mod.rs index 513b9d698735b..c19c49da3423d 100644 --- a/datafusion/physical-plan/src/operator_statistics/mod.rs +++ b/datafusion/physical-plan/src/operator_statistics/mod.rs @@ -2575,7 +2575,7 @@ mod tests { )?; // Swapping the inputs turns the join into a right join with the same // output columns. - let swapped = join.swap_inputs(PartitionMode::CollectLeft)?; + let swapped = join.swap_inputs()?; let registry = StatisticsRegistry::with_providers(vec![Arc::new(JoinStatisticsProvider)]); // The preserved key keeps its 20 NULLs only as an estimate, since diff --git a/datafusion/sqllogictest/test_files/cte.slt b/datafusion/sqllogictest/test_files/cte.slt index 303c0101bdbed..69a735acd9665 100644 --- a/datafusion/sqllogictest/test_files/cte.slt +++ b/datafusion/sqllogictest/test_files/cte.slt @@ -1925,6 +1925,10 @@ DROP TABLE dynamic_filter_recursive; # recursive iterations (#26641). Each iteration looks up a different key; the # EXPLAIN ANALYZE below checks that the filter is reset and republished, so the # probe scan prunes rows on every iteration. +# Keep the work table on the build side so the parquet scan receives the filter. +statement ok +SET datafusion.optimizer.join_reordering = false; + statement ok SET datafusion.execution.target_partitions = 1; @@ -1986,6 +1990,9 @@ Plan with Metrics statement ok DROP TABLE hash_join_dynamic_filter; +statement ok +RESET datafusion.optimizer.join_reordering; + statement ok RESET datafusion.explain.analyze_categories; diff --git a/datafusion/sqllogictest/test_files/explain_tree.slt b/datafusion/sqllogictest/test_files/explain_tree.slt index f9a6cfe06e4fd..a63b11acc9bee 100644 --- a/datafusion/sqllogictest/test_files/explain_tree.slt +++ b/datafusion/sqllogictest/test_files/explain_tree.slt @@ -1095,7 +1095,7 @@ physical_plan 01)┌───────────────────────────┐ 02)│ HashJoinExec │ 03)│ -------------------- │ -04)│ join_type: LeftAnti │ +04)│ join_type: RightAnti │ 05)│ │ 06)│ null_aware ├──────────────┐ 07)│ │ │ @@ -1103,11 +1103,20 @@ physical_plan 09)│ (int_col = int_col) │ │ 10)└─────────────┬─────────────┘ │ 11)┌─────────────┴─────────────┐┌─────────────┴─────────────┐ -12)│ DataSourceExec ││ DataSourceExec │ +12)│ DataSourceExec ││ RepartitionExec │ 13)│ -------------------- ││ -------------------- │ -14)│ files: 1 ││ files: 1 │ -15)│ format: csv ││ format: parquet │ -16)└───────────────────────────┘└───────────────────────────┘ +14)│ files: 1 ││ partition_count(in->out): │ +15)│ format: parquet ││ 1 -> 4 │ +16)│ ││ │ +17)│ ││ partitioning_scheme: │ +18)│ ││ RoundRobinBatch(4) │ +19)└───────────────────────────┘└─────────────┬─────────────┘ +20)-----------------------------┌─────────────┴─────────────┐ +21)-----------------------------│ DataSourceExec │ +22)-----------------------------│ -------------------- │ +23)-----------------------------│ files: 1 │ +24)-----------------------------│ format: csv │ +25)-----------------------------└───────────────────────────┘ # Query with nested loop join. query TT diff --git a/datafusion/sqllogictest/test_files/joins.slt b/datafusion/sqllogictest/test_files/joins.slt index b690e2a489f5f..063376e407f30 100644 --- a/datafusion/sqllogictest/test_files/joins.slt +++ b/datafusion/sqllogictest/test_files/joins.slt @@ -4489,6 +4489,10 @@ physical_plan ## RIGHT JOIN w/ LIMIT ###### +# Keep a physical right join to exercise its limit pushdown. +statement ok +set datafusion.optimizer.join_reordering = false; + query II select * from t1 RIGHT JOIN t2 ON t1.a = t2.b LIMIT 2; ---- @@ -4518,6 +4522,9 @@ physical_plan 02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/joins/t1.csv]]}, projection=[a], file_type=csv, has_header=true 03)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/joins/t2.csv]]}, projection=[b], limit=2, file_type=csv, has_header=true +statement ok +reset datafusion.optimizer.join_reordering; + ###### ## FULL JOIN w/ LIMIT ###### From d8d10c6e1ea2c025dea9e96ec72adf151230b447 Mon Sep 17 00:00:00 2001 From: Yongting You <2010youy01@gmail.com> Date: Thu, 3 Dec 2026 11:07:35 +0800 Subject: [PATCH 2/2] remove unnecessary UTs --- .../physical-plan/src/joins/hash_join/exec.rs | 139 ------------------ 1 file changed, 139 deletions(-) diff --git a/datafusion/physical-plan/src/joins/hash_join/exec.rs b/datafusion/physical-plan/src/joins/hash_join/exec.rs index 009b7b7a2a3de..7e43755e6c4c1 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec.rs @@ -12667,143 +12667,4 @@ mod tests { assert_contains!(error.to_string(), "Resources exhausted"); Ok(()) } - - #[rstest] - #[case::small_left(Some(1), Some(1), 1000, true)] - #[case::large_left(Some(1000), Some(1), 1, false)] - #[case::byte_threshold(Some(100), Some(1), 1, false)] - #[case::row_fallback(None, Some(1), 1000, true)] - #[case::row_threshold(None, Some(10), 1, false)] - #[case::unknown(None, None, 1, false)] - #[case::zero(Some(0), Some(0), 1000, true)] - fn choose_partition_mode_keeps_build_side( - #[case] left_bytes: Option, - #[case] left_rows: Option, - #[case] right_bytes: usize, - #[case] collect_left: bool, - ) -> Result<()> { - let (left_schema, right_schema, on) = build_schema_and_on()?; - let mut left_stats = Statistics::new_unknown(&left_schema); - left_stats.total_byte_size = left_bytes - .map(Precision::Exact) - .unwrap_or(Precision::Absent); - left_stats.num_rows = - left_rows.map(Precision::Exact).unwrap_or(Precision::Absent); - let mut right_stats = Statistics::new_unknown(&right_schema); - right_stats.total_byte_size = Precision::Exact(right_bytes); - let left: Arc = Arc::new(StatisticsExec::new( - left_stats, - left_schema.as_ref().clone(), - )); - let right: Arc = Arc::new(StatisticsExec::new( - right_stats, - right_schema.as_ref().clone(), - )); - let join = HashJoinExecBuilder::new( - Arc::clone(&left), - Arc::clone(&right), - on, - JoinType::Inner, - ) - .with_partition_mode(PartitionMode::Auto) - .build()?; - let mut config = ConfigOptions::new(); - config.execution.target_partitions = 4; - config.optimizer.hash_join_single_partition_threshold = 100; - config.optimizer.hash_join_single_partition_threshold_rows = 10; - - let selected = join - .choose_partition_mode(&config, &StatisticsContext::new())? - .expect("Auto must resolve to a concrete mode"); - - let children = selected.children(); - assert!(Arc::ptr_eq(children[0], &left)); - assert!(Arc::ptr_eq(children[1], &right)); - let expected_mode = if collect_left { - PartitionMode::CollectLeft - } else { - PartitionMode::Partitioned - }; - assert_eq!(*selected.partition_mode(), expected_mode); - assert!( - selected - .choose_partition_mode(&config, &StatisticsContext::new())? - .is_none() - ); - Ok(()) - } - - #[rstest] - #[case::one_partition(true, 1, false)] - #[case::repartition_disabled(false, 4, false)] - #[case::null_aware(true, 4, true)] - fn choose_partition_mode_respects_collect_constraints( - #[case] repartition_joins: bool, - #[case] target_partitions: usize, - #[case] null_aware: bool, - ) -> Result<()> { - let (left_schema, right_schema, on) = build_schema_and_on()?; - let left: Arc = Arc::new(StatisticsExec::new( - Statistics::new_unknown(&left_schema), - left_schema.as_ref().clone(), - )); - let right: Arc = Arc::new(StatisticsExec::new( - Statistics::new_unknown(&right_schema), - right_schema.as_ref().clone(), - )); - let join = HashJoinExecBuilder::new( - Arc::clone(&left), - Arc::clone(&right), - on, - JoinType::LeftAnti, - ) - .with_partition_mode(PartitionMode::Auto) - .with_null_aware(null_aware) - .build()?; - let mut config = ConfigOptions::new(); - config.execution.target_partitions = target_partitions; - config.optimizer.repartition_joins = repartition_joins; - config.optimizer.hash_join_single_partition_threshold = 0; - config.optimizer.hash_join_single_partition_threshold_rows = 0; - - let selected = join - .choose_partition_mode(&config, &StatisticsContext::new())? - .expect("Auto must resolve to a concrete mode"); - - let children = selected.children(); - assert!(Arc::ptr_eq(children[0], &left)); - assert!(Arc::ptr_eq(children[1], &right)); - assert_eq!(*selected.partition_mode(), PartitionMode::CollectLeft); - Ok(()) - } - - #[rstest] - #[case(PartitionMode::CollectLeft)] - #[case(PartitionMode::Partitioned)] - fn choose_partition_mode_preserves_explicit_mode( - #[case] mode: PartitionMode, - ) -> Result<()> { - let (left_schema, right_schema, on) = build_schema_and_on()?; - let left = Arc::new(StatisticsExec::new( - Statistics::new_unknown(&left_schema), - left_schema.as_ref().clone(), - )); - let right = Arc::new(StatisticsExec::new( - Statistics::new_unknown(&right_schema), - right_schema.as_ref().clone(), - )); - let join = HashJoinExecBuilder::new(left, right, on, JoinType::Inner) - .with_partition_mode(mode) - .build()?; - let mut config = ConfigOptions::new(); - config.execution.target_partitions = 1; - config.optimizer.hash_join_single_partition_threshold = 0; - config.optimizer.hash_join_single_partition_threshold_rows = 0; - - assert!( - join.choose_partition_mode(&config, &StatisticsContext::new())? - .is_none() - ); - Ok(()) - } }