Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion datafusion/core/tests/physical_optimizer/join_selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<HashJoinExec>()
Expand Down
253 changes: 51 additions & 202 deletions datafusion/physical-optimizer/src/join_selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -97,24 +103,6 @@ pub(crate) fn should_swap_join_order(
}
}

fn supports_collect_by_thresholds(
plan: &Arc<dyn ExecutionPlan>,
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<T>` 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(
Expand Down Expand Up @@ -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 {
Expand All @@ -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<Option<Arc<dyn ExecutionPlan>>> {
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<Arc<dyn ExecutionPlan>> {
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<dyn ExecutionPlan>,
context: &dyn PhysicalOptimizerContext,
statistics: &StatisticsContext,
) -> Result<Transformed<Arc<dyn ExecutionPlan>>> {
let transformed = if let Some(hash_join) = plan.downcast_ref::<HashJoinExec>() {
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::<CrossJoinExec>() {
let left = cross_join.left();
let right = cross_join.right();
Expand Down Expand Up @@ -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<dyn ExecutionPlan>,
context: &dyn PhysicalOptimizerContext,
statistics: &StatisticsContext,
) -> Result<Transformed<Arc<dyn ExecutionPlan>>> {
let Some(join) = plan.downcast_ref::<HashJoinExec>() 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<dyn ExecutionPlan>, &ConfigOptions) -> Result<Arc<dyn ExecutionPlan>>;
Expand Down Expand Up @@ -559,28 +418,18 @@ pub fn hash_join_swap_subrule(
pub(crate) fn swap_join_according_to_unboundedness(
hash_join: &HashJoinExec,
) -> Result<Arc<dyn ExecutionPlan>> {
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
Expand Down
Loading
Loading