From fd53d5d0d3b891bdcfdb8c721696965928853431 Mon Sep 17 00:00:00 2001 From: Yongting You <2010youy01@gmail.com> Date: Mon, 16 Nov 2026 16:13:18 +0800 Subject: [PATCH 1/9] Separate regular hash join execution from the legacy stream --- datafusion/common/src/config.rs | 11 + .../joins/hash_join/batched_join_processor.rs | 512 ++++++++++++++++++ .../src/joins/hash_join/build.rs | 184 +++++++ .../physical-plan/src/joins/hash_join/exec.rs | 286 +++++++--- .../src/joins/hash_join/exec/prepared.rs | 24 +- .../physical-plan/src/joins/hash_join/mod.rs | 19 +- .../src/joins/hash_join/regular_join.rs | 179 ++++++ .../test_files/information_schema.slt | 2 + docs/source/user-guide/configs.md | 1 + 9 files changed, 1128 insertions(+), 90 deletions(-) create mode 100644 datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs create mode 100644 datafusion/physical-plan/src/joins/hash_join/build.rs create mode 100644 datafusion/physical-plan/src/joins/hash_join/regular_join.rs diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs index 4f2e4685c259a..23baad32481d3 100644 --- a/datafusion/common/src/config.rs +++ b/datafusion/common/src/config.rs @@ -977,6 +977,17 @@ config_namespace! { /// See for details. pub enable_migration_aggregate: bool, default = true + /// Whether inner, left outer, right outer, and full outer hash joins use + /// the refactored probe implementation. When set to `false`, these joins + /// use the previous probe implementation. + /// + /// The fallback exists only as a workaround for bugs in the new + /// implementation and will be removed, together with this option, once + /// the migration is complete. + /// + /// See for details. + pub enable_migration_hash_join: bool, default = true + /// Sets the compression codec used when spilling data to disk. /// /// Since datafusion writes spill files using the Arrow IPC Stream format, diff --git a/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs b/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs new file mode 100644 index 0000000000000..b1e7db5022490 --- /dev/null +++ b/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs @@ -0,0 +1,512 @@ +// 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 + +//! Bounded key lookup, residual filtering, and output for regular joins. +//! +//! [`BatchedJoinProcessor`] accepts probe batches and returns final output batches. +//! Its caller does not manage row indices, lookup cursors, match bitmaps, or +//! output buffering. See the type's example for the input/output contract. + +use std::sync::Arc; + +use arrow::array::{ArrayRef, UInt32Array, UInt64Array}; +use arrow::buffer::{BooleanBuffer, NullBuffer}; +use arrow::datatypes::SchemaRef; +use arrow::record_batch::RecordBatch; +use datafusion_common::hash_utils::RandomState; +use datafusion_common::{ + JoinSide, JoinType, NullEquality, Result, assert_or_internal_err, internal_err, +}; +use datafusion_physical_expr::PhysicalExprRef; +use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays; + +use super::build::RegularJoinLeftData; +use super::stream::lookup_join_hashmap; +use crate::coalesce::{LimitedBatchCoalescer, PushBatchStatus}; +use crate::hash_utils::create_hashes; +use crate::joins::Map; +use crate::joins::join_hash_map::ProbeOffset; +use crate::joins::utils::{ + BuildProbeJoinMetrics, ColumnIndex, JoinFilter, JoinKeyComparator, + adjust_indices_by_join_type, apply_join_filter_to_indices, + build_batch_empty_build_side, build_batch_from_indices, matchable_join_keys, +}; + +/// Join semantics and output settings for one probe partition. +pub(super) struct BatchedJoinProcessorConfig { + /// Join type, which determines whether to keep unmatched build or probe rows. + pub(super) kind: RegularJoinKind, + /// Output schema after projection. + pub(super) schema: SchemaRef, + /// Probe input schema, used for NULL columns in unmatched build output. + pub(super) probe_schema: SchemaRef, + /// For each output column, its source side and column index. + pub(super) column_indices: Vec, + /// Probe equality-key expressions, paired with the build keys by position. + pub(super) on_right: Vec, + /// Hash state shared with build-side insertion. + pub(super) random_state: RandomState, + /// Whether NULL equality keys can match. + pub(super) null_equality: NullEquality, + /// Extra `ON` condition checked after key equality, e.g. `l.x > r.y`. + /// Its input columns are independent of the output projection. + pub(super) filter: Option, + /// Target batch size for internal buffering, from configuration. + pub(super) batch_size: usize, + /// Preserve probe order when inserting unmatched rows for a right join. + pub(super) right_side_ordered: bool, + /// Maximum output rows from this processor; `None` means no limit. + pub(super) fetch: Option, +} + +/// Joins probe batches against the build map. +/// +/// See the [hash join overview](super) for architecture overview. This is the middle +/// layer that: +/// +/// 1. Looks up raw hash index for matches in chunks of at most `batch_size`. +/// 2. Applies residual filters and handles unmatched rows for outer joins. +/// 3. Materializes and coalesces output toward `batch_size`. +/// +/// # Example +/// +/// For a full join with one probe partition, build keys `[1, 2, 2]`, and +/// `batch_size = 1`: +/// +/// ```text +/// next_output_batch() -> NeedInput +/// push_batch([2]) +/// next_output_batch() -> Output([(2, 2)]) +/// next_output_batch() -> Output([(2, 2)]) +/// next_output_batch() -> NeedInput // This batch is done; the stream may have more. +/// +/// push_batch([3]) +/// next_output_batch() -> Output([(NULL, 3)]) +/// next_output_batch() -> NeedInput +/// +/// // The caller reads the probe stream and observes EOF. +/// finish_probe() +/// next_output_batch() -> Output([(1, NULL)]) +/// next_output_batch() -> Finished // All output from this processor is drained. +/// ``` +pub(super) struct BatchedJoinProcessor { + context: BatchedJoinProcessorConfig, + metrics: BuildProbeJoinMetrics, + build: Arc, + /// Input and residual-match state for the current probe batch. + probe: Option, + phase: Phase, + /// Lookup scratch and pair buffers are reused across input batches. + hashes_buffer: Vec, + probe_indices_buffer: Vec, + build_indices_buffer: Vec, + /// Coalescer for materialized output. Also handles the fetch/limit pushed into + /// the hash join for an early stop (e.g., for HashJoinExec(fetch=10), the whole + /// execution can stop early after 10 output rows are materialized). + output: LimitedBatchCoalescer, +} + +/// Input and lookup progress are separate from successful ON matches: rejecting +/// a chunk advances its offset, but does not make those probe rows joined. +struct ProbeBatch { + input: RecordBatch, + keys: Vec, + valid_keys: Option, + offset: ProbeOffset, + key_comparator: Option, + /// Count each probe row once, even when its equality matches span chunks. + last_probe_row_with_key_match: Option, + /// RIGHT/FULL joins retain this across chunks to avoid treating a previously + /// joined probe row as unmatched after later pairs fail the residual filter. + last_probe_row_with_on_match: Option, +} + +/// The next action for the caller of [`BatchedJoinProcessor::next_output_batch`]. +pub(super) enum JoinStep { + /// A joined output batch is ready. + Output(RecordBatch), + /// The caller should supply another probe batch or report EOF with + /// [`BatchedJoinProcessor::finish_probe`]. + NeedInput, + /// All output is drained, possibly before probe EOF. Stop reading input. + Finished, +} + +/// Join work remaining. The output coalescer outlives every phase. +enum Phase { + Probing, + /// Only the last probe partition receives this final match snapshot. + /// Scan it in chunks without holding the shared bitmap lock. + UnmatchedBuild { + visited: BooleanBuffer, + next_row: usize, + empty_probe: RecordBatch, + }, + /// No more rows will be produced; flush and drain buffered output. + DrainingOutput, + Finished, +} + +impl BatchedJoinProcessor { + pub(super) fn new( + build: Arc, + context: BatchedJoinProcessorConfig, + metrics: BuildProbeJoinMetrics, + ) -> Self { + // An empty map may still have build rows with NULL keys. Left/full + // joins must retain those rows for final null extension. + let join_type = context.kind.join_type(); + let can_skip_probe = (build.data.batch.num_rows() == 0 + && join_type.empty_build_side_produces_empty_result()) + || (build.data.map.is_empty() && join_type.empty_map_produces_empty_result()); + let phase = if can_skip_probe || context.fetch == Some(0) { + Phase::DrainingOutput + } else { + Phase::Probing + }; + Self { + build, + probe: None, + hashes_buffer: vec![], + probe_indices_buffer: vec![], + build_indices_buffer: vec![], + output: LimitedBatchCoalescer::new( + Arc::clone(&context.schema), + context.batch_size, + context.fetch, + ), + context, + metrics, + phase, + } + } + + /// Accept one probe batch after draining the previous input. + /// + /// Evaluate keys and hashes once; candidate lookup and output materialization + /// happen incrementally in [`Self::next_output_batch`]. + pub(super) fn push_batch(&mut self, batch: RecordBatch) -> Result<()> { + if !matches!(self.phase, Phase::Probing) { + return internal_err!( + "BatchedJoinProcessor: cannot push input after probing has finished" + ); + } + assert_or_internal_err!( + self.probe.is_none(), + "BatchedJoinProcessor: drain the current input before pushing another batch" + ); + let keys = evaluate_expressions_to_arrays(&self.context.on_right, &batch)?; + let valid_keys = if matches!(&**self.build.data.map, Map::HashMap(_)) { + let _timer = self.metrics.join_time.timer(); + self.hashes_buffer.clear(); + self.hashes_buffer.resize(batch.num_rows(), 0); + create_hashes(&keys, &self.context.random_state, &mut self.hashes_buffer)?; + matchable_join_keys(&keys, self.context.null_equality) + } else { + None + }; + self.probe = Some(ProbeBatch { + input: batch, + keys, + valid_keys, + offset: ProbeOffset::AtRow { row: 0 }, + key_comparator: None, + last_probe_row_with_key_match: None, + last_probe_row_with_on_match: None, + }); + Ok(()) + } + + /// Materialize the next joined batch. + /// + /// Handles incremental computation and output coalescing toward `batch_size` + /// internally. See the comments on [`BatchedJoinProcessor`] for details. + pub(super) fn next_output_batch(&mut self) -> Result { + let join_time = self.metrics.join_time.clone(); + loop { + if let Some(batch) = self.output.next_completed_batch() { + return Ok(JoinStep::Output(batch)); + } + let _timer = join_time.timer(); + + // Evaluate one final joined batch and put it into the output coalescer + // to combine potentially small batches. + let batch = match &mut self.phase { + Phase::Probing => { + let Some(batch) = self.probe_chunk()? else { + return Ok(JoinStep::NeedInput); + }; + batch + } + Phase::UnmatchedBuild { + visited, + next_row, + empty_probe, + } => { + let mut indices = Vec::with_capacity( + self.context.batch_size.min(visited.len() - *next_row), + ); + while *next_row < visited.len() + && indices.len() < self.context.batch_size + { + if !visited.value(*next_row) { + indices.push(*next_row as u64); + } + *next_row += 1; + } + self.metrics.input_rows.add(indices.len()); + if indices.is_empty() { + self.phase = Phase::DrainingOutput; + continue; + } + let probe_indices = UInt32Array::new_null(indices.len()); + build_batch_from_indices( + &self.context.schema, + &self.build.data.batch, + empty_probe, + &UInt64Array::from(indices), + &probe_indices, + &self.context.column_indices, + JoinSide::Left, + self.context.kind.join_type(), + None, + )? + } + Phase::DrainingOutput => { + self.output.finish()?; + self.phase = Phase::Finished; + continue; + } + Phase::Finished => return Ok(JoinStep::Finished), + }; + // Operator-level limit reached; stop probing. + // See the comments on `output` for details. + if self.output.push_batch(batch)? == PushBatchStatus::LimitReached { + self.release_probe(); + self.phase = Phase::DrainingOutput; + } + } + } + + /// Close this partition's probe input after all its batches have been + /// drained and the caller has exhausted all probe-side input batches. + pub(super) fn finish_probe(&mut self) -> Result<()> { + assert_or_internal_err!( + matches!(self.phase, Phase::Probing) && self.probe.is_none(), + "BatchedJoinProcessor: finish probing only after draining the current input" + ); + let join_time = self.metrics.join_time.clone(); + let _timer = join_time.timer(); + self.release_probe(); + self.phase = if let Some(visited) = self.build.finish_probe() { + self.metrics.input_batches.add(1); + Phase::UnmatchedBuild { + visited, + next_row: 0, + empty_probe: RecordBatch::new_empty(Arc::clone( + &self.context.probe_schema, + )), + } + } else { + Phase::DrainingOutput + }; + Ok(()) + } + + /// Join another portion of the current probe batch against the build batch. + /// + /// 1. Collect up to `batch_size` key-equal row-index pairs + /// in `build_indices` and `probe_indices`. + /// 2. Apply the join filter, record successful matches, + /// and add probe rows now known to be unmatched for right/full joins. + /// 3. Materialize those pairs into a batch. [`Self::next_output_batch`] + /// coalesces small batches of surviving pairs and unmatched rows. + /// + /// One call may cover part of one probe row's matches or several probe rows. + /// An empty batch means this chunk produced no output; `None` means the + /// current probe batch is drained. + fn probe_chunk(&mut self) -> Result> { + let Some(probe) = &mut self.probe else { + return Ok(None); + }; + let context = &self.context; + let build = &self.build; + let input = &probe.input; + + // NULL build keys can leave the map empty even when build rows exist. + // Such rows cannot match but are still emitted at build finalization + // for left/full joins. Right/full joins preserve this entire probe batch. + if build.data.map.is_empty() { + let batch = build_batch_empty_build_side( + &context.schema, + &build.data.batch, + input, + &context.column_indices, + context.kind.join_type(), + )?; + self.probe = None; + return Ok(Some(batch)); + } + + // Hash lookup reclaims its scratch internally. ArrayMap returns the + // scratch as Arrow arrays, so retain their buffers until materialization. + let mut array_map_buffers = None; + let (build_indices, probe_indices, next_offset) = match &**build.data.map { + Map::HashMap(map) => lookup_join_hashmap( + map.as_ref(), + &build.data.values, + &probe.keys, + context.null_equality, + &self.hashes_buffer, + probe.valid_keys.as_ref(), + context.batch_size, + probe.offset, + &mut self.probe_indices_buffer, + &mut self.build_indices_buffer, + &mut probe.key_comparator, + )?, + Map::ArrayMap(map) => { + let next_offset = map.get_matched_indices_with_limit_offset( + &probe.keys, + context.batch_size, + probe.offset, + &mut self.probe_indices_buffer, + &mut self.build_indices_buffer, + )?; + let build_indices: UInt64Array = + std::mem::take(&mut self.build_indices_buffer).into(); + let probe_indices: UInt32Array = + std::mem::take(&mut self.probe_indices_buffer).into(); + array_map_buffers = Some(( + build_indices.values().clone(), + probe_indices.values().clone(), + )); + (build_indices, probe_indices, next_offset) + } + }; + + // Equality pairs are ordered by probe row. A row continuing from the + // previous chunk contributes fanout, but not another probe hit. + let mut matched_probe_rows = 0; + for &row in probe_indices.values().iter() { + if probe.last_probe_row_with_key_match != Some(row) { + matched_probe_rows += 1; + probe.last_probe_row_with_key_match = Some(row); + } + } + self.metrics.probe_hit_rate.add_part(matched_probe_rows); + self.metrics.avg_fanout.add_part(build_indices.len()); + self.metrics.avg_fanout.add_total(matched_probe_rows); + + let (build_indices, probe_indices) = if let Some(filter) = &context.filter { + apply_join_filter_to_indices( + &build.data.batch, + input, + build_indices, + probe_indices, + filter, + JoinSide::Left, + None, + context.kind.join_type(), + )? + } else { + (build_indices, probe_indices) + }; + + // Only successful ON matches suppress unmatched build output. Rows + // rejected by the residual filter remain eligible for final output. + build.record_matches(&build_indices); + + let (build_indices, probe_indices) = if context.kind.preserves_probe() { + let last_joined_probe_row = probe_indices.values().last().copied(); + let start = probe + .last_probe_row_with_on_match + .map_or(0, |row| row as usize + 1); + let end = if next_offset.is_none() { + input.num_rows() + } else { + last_joined_probe_row.map_or(0, |row| row as usize + 1) + }; + if last_joined_probe_row.is_some() { + probe.last_probe_row_with_on_match = last_joined_probe_row; + } + adjust_indices_by_join_type( + build_indices, + probe_indices, + start..end, + context.kind.join_type(), + context.right_side_ordered, + )? + } else { + (build_indices, probe_indices) + }; + + let output = build_batch_from_indices( + &context.schema, + &build.data.batch, + input, + &build_indices, + &probe_indices, + &context.column_indices, + JoinSide::Left, + context.kind.join_type(), + None, + )?; + drop((build_indices, probe_indices)); + if let Some((build_buffer, probe_buffer)) = array_map_buffers { + self.build_indices_buffer = build_buffer.into(); + self.probe_indices_buffer = probe_buffer.into(); + } + if let Some(offset) = next_offset { + probe.offset = offset; + } else { + self.probe = None; + } + Ok(Some(output)) + } + + /// Release input and lookup storage on probe EOF or a fetch cutoff. + /// Output already materialized in the coalescer remains available. + fn release_probe(&mut self) { + self.probe = None; + self.hashes_buffer = Vec::new(); + self.probe_indices_buffer = Vec::new(); + self.build_indices_buffer = Vec::new(); + } +} + +/// The supported semantics of this execution path. Existence and mark joins +/// retain their own path rather than adding branches to regular probing. +#[derive(Clone, Copy)] +pub(super) enum RegularJoinKind { + Inner, + Left, + Right, + Full, +} + +impl RegularJoinKind { + pub(super) fn from_join_type(join_type: JoinType) -> Option { + match join_type { + JoinType::Inner => Some(Self::Inner), + JoinType::Left => Some(Self::Left), + JoinType::Right => Some(Self::Right), + JoinType::Full => Some(Self::Full), + _ => None, + } + } + + fn join_type(self) -> JoinType { + match self { + Self::Inner => JoinType::Inner, + Self::Left => JoinType::Left, + Self::Right => JoinType::Right, + Self::Full => JoinType::Full, + } + } + + fn preserves_probe(self) -> bool { + matches!(self, Self::Right | Self::Full) + } +} diff --git a/datafusion/physical-plan/src/joins/hash_join/build.rs b/datafusion/physical-plan/src/joins/hash_join/build.rs new file mode 100644 index 0000000000000..94f98a0692219 --- /dev/null +++ b/datafusion/physical-plan/src/joins/hash_join/build.rs @@ -0,0 +1,184 @@ +// 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 + +//! Build preparation and shared data for regular hash joins. +//! +//! Collection is shared across probe partitions in `CollectLeft` mode. Before +//! probing, each partition also waits for the join's dynamic filter to be ready. +//! The prepared result contains only the data and coordination regular joins need. + +use std::sync::Arc; + +use arrow::array::{BooleanBufferBuilder, UInt64Array}; +use arrow::buffer::BooleanBuffer; +use datafusion_common::Result; +use futures::future::poll_fn; +use parking_lot::Mutex; + +use super::exec::JoinBuildData; +use crate::joins::PartitionMode; +use crate::joins::hash_join::shared_bounds::{ + PartitionBounds, PartitionBuildData, SharedBuildAccumulator, +}; +use crate::joins::utils::{BuildProbeJoinMetrics, OnceFut}; + +/// Left-side data and mutable bookkeeping for one regular join execution. +/// Shares immutable [`JoinBuildData`] and coordinates unmatched build rows for +/// Left/Full joins, so only the last probe partition emits them. +pub(super) struct RegularJoinLeftData { + unmatched: Option>, + // Keep the build lease last: its reservation also covers the bitmap. + pub(super) data: Arc, +} + +struct UnmatchedRows { + visited: BooleanBufferBuilder, + remaining_probes: usize, +} + +impl RegularJoinLeftData { + pub(super) fn new( + data: Arc, + visited: Option, + probe_partitions: usize, + ) -> Self { + Self { + unmatched: visited.map(|visited| { + Mutex::new(UnmatchedRows { + visited, + remaining_probes: probe_partitions, + }) + }), + data, + } + } + + /// Record matches after the ON filter has accepted them. + pub(super) fn record_matches(&self, indices: &UInt64Array) { + if let Some(unmatched) = &self.unmatched { + let mut unmatched = unmatched.lock(); + for index in indices.iter().flatten() { + unmatched.visited.set_bit(index as usize, true); + } + } + } + + /// Report actual probe EOF; a fetch cutoff must not call this. + pub(super) fn finish_probe(&self) -> Option { + let mut unmatched = self.unmatched.as_ref()?.lock(); + // Counting and snapshotting under the same lock ensures the last probe + // sees every sibling's matches and is the only one to emit unmatched rows. + unmatched.remaining_probes -= 1; + (unmatched.remaining_probes == 0).then(|| unmatched.visited.finish_cloned()) + } +} + +/// Collecting the build-side data of a hash join. +/// +/// It handles coordination/synchronization among all parallel partitions for: +/// - Input batch collection +/// - Dynamic filter preparation +pub(super) struct HashJoinBuild { + partition: usize, + mode: PartitionMode, + + // --------------------------------------------------- + // Shared structures for coordination among partitions. + // --------------------------------------------------- + /// Coordination for the dynamic filter. + build_accumulator: Option>, + /// Shared future for collecting [`RegularJoinLeftData`]. + left_fut: OnceFut, + + metrics: BuildProbeJoinMetrics, +} + +impl HashJoinBuild { + pub(super) fn new( + partition: usize, + mode: PartitionMode, + left_fut: OnceFut, + build_accumulator: Option>, + metrics: BuildProbeJoinMetrics, + ) -> Self { + Self { + partition, + mode, + build_accumulator, + left_fut, + metrics, + } + } + + /// Prepare the build-side data and handle coordination. + /// + /// It handles coordination for build-side data preparation and dynamic filters. + /// + /// Example of coordination for build-side data (coordination for the dynamic + /// filter is similar; after all partitions are done, it can publish the dynamic + /// filter to pre-filter the probe side): + /// + /// ```text + /// With shared build-side configuration: + /// - partition0: call `prepare()`, and execute and cache all build-side data + /// - partition1~k: call `prepare()` for synchronization, wait for partition 0 to finish + /// and reuse the shared build-side data + /// ``` + pub(super) async fn prepare(mut self) -> Result> { + let build = poll_fn(|cx| { + // Count active polling time, excluding time suspended on input. + let _timer = self.metrics.build_time.timer(); + self.left_fut.get_shared(cx) + }) + .await?; + + if let Some(accumulator) = &self.build_accumulator { + let data = &build.data; + let pushdown = data.membership.clone(); + let bounds = data + .bounds + .clone() + .unwrap_or_else(|| PartitionBounds::new(vec![])); + // Dictionary keys can point at NULL values without physical NULL keys. + let keys_have_null = data + .values + .iter() + .any(|array| array.logical_null_count() > 0); + let report = match self.mode { + PartitionMode::Partitioned => PartitionBuildData::Partitioned { + partition_id: self.partition, + pushdown, + bounds, + keys_have_null, + }, + PartitionMode::CollectLeft => PartitionBuildData::CollectLeft { + pushdown, + bounds, + keys_have_null, + }, + PartitionMode::Auto => { + unreachable!("PartitionMode::Auto must be resolved before execution") + } + }; + + // Handle coordination for the dynamic filter. + accumulator.report_build_data(report).await?; + } + Ok(build) + } +} + +impl Drop for HashJoinBuild { + fn drop(&mut self) { + if self.mode == PartitionMode::Partitioned + && let Some(accumulator) = &self.build_accumulator + { + // A LIMIT may drop a stream before it reports. Unblock siblings, + // keeping that partition's filter permissive: unknown is not empty. + // The accumulator ignores cancellation after a report, including a + // report whose future was dropped while waiting for other partitions. + accumulator.report_canceled_partition(self.partition); + } + } +} diff --git a/datafusion/physical-plan/src/joins/hash_join/exec.rs b/datafusion/physical-plan/src/joins/hash_join/exec.rs index 51e0653e3d7da..69d69d88629be 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec.rs @@ -18,8 +18,13 @@ use crate::filter_pushdown::{ }; use crate::joins::Map; use crate::joins::array_map::ArrayMap; +use crate::joins::hash_join::batched_join_processor::{ + BatchedJoinProcessorConfig, RegularJoinKind, +}; +use crate::joins::hash_join::build::{HashJoinBuild, RegularJoinLeftData}; use crate::joins::hash_join::inlist_builder::build_struct_inlist_values; use crate::joins::hash_join::not_in::{NotIn, NotInBuild}; +use crate::joins::hash_join::regular_join::RegularHashJoinStream; use crate::joins::hash_join::shared_bounds::{ ColumnBounds, PartitionBounds, PushdownStrategy, SharedBuildAccumulator, }; @@ -236,27 +241,68 @@ fn array_map_key_range( } /// Immutable build buffers and their durable reservation. -struct JoinBuildData { +pub(super) struct JoinBuildData { /// Hash table with row indices into `batch`, charged to its own /// reservation because it is also shared with dynamic filters. - map: Arc, + pub(super) map: Arc, /// The input rows for the build side. - batch: RecordBatch, + pub(super) batch: RecordBatch, /// Evaluated build-side key expressions, with float `-0.0` rewritten to /// `+0.0` so probe batches can compare against them without scanning the /// build side again. The dynamic filters (`bounds`, `membership`) and /// the `NOT IN` NULL masks were computed from the original keys in /// `collect_left_input`. - values: Vec, + pub(super) values: Vec, /// Bounds computed from the build side; absent for an empty partition. - bounds: Option, - /// IN-list values or a hash-table reference used for filter pushdown. - membership: PushdownStrategy, + /// + /// For example, for the query `t1 JOIN t2 USING (c1, c2)`, the bounds can be: + /// - c1: `[0,100]` + /// - c2: `[10,20]` + /// + /// These represent each join key's range for this partition to pre-filter probing. + pub(super) bounds: Option, + /// Used for pre-filter probing, similar to [`Self::bounds`], but in different + /// representations: IN-list values or a hash-table reference. + pub(super) membership: PushdownStrategy, // Keep the reservation after the allocations it accounts for. reservation: MemoryReservation, } -/// A build lease and mutable bookkeeping for one join execution. +/// Collected left-side data shared by the regular and legacy implementations. +/// +/// This shared struct is temporary while the regular and existence join paths +/// are separated. +/// +/// See for details. +struct CollectedBuild { + not_in: Option, + visited: Option, + probe_partitions: usize, + // Its reservation also covers the mutable state above. + build: Arc, +} + +impl CollectedBuild { + /// Create [`RegularJoinLeftData`]; see [`CollectedBuild`] for the shared setup. + fn into_regular_left_data(self) -> RegularJoinLeftData { + RegularJoinLeftData::new(self.build, self.visited, self.probe_partitions) + } + + /// Create legacy [`JoinLeftData`]; see [`CollectedBuild`] for the shared setup. + fn into_legacy_left_data(self) -> JoinLeftData { + JoinLeftData { + not_in: self.not_in, + visited_indices_bitmap: Mutex::new( + self.visited.unwrap_or_else(|| BooleanBufferBuilder::new(0)), + ), + probe_completion: ProbeCompletion::new(self.probe_partitions), + build: self.build, + } + } +} + +/// Left-side data and mutable bookkeeping for one legacy join execution, +/// including regular joins when migration is disabled. pub(super) struct JoinLeftData { /// The `NOT IN` state of a null-aware join, see [`NotInBuild`]. not_in: Option, @@ -385,6 +431,7 @@ impl HashJoinExecBuilder { filter: None, join_type, left_fut: Default::default(), + regular_left_fut: Default::default(), prepared_build: None, random_state: HASH_JOIN_SEED, mode: PartitionMode::Auto, @@ -501,6 +548,7 @@ impl HashJoinExecBuilder { /// Reset task-local runtime state while retaining the immutable prepared build. pub fn reset_state(mut self) -> Self { self.exec.left_fut = Default::default(); + self.exec.regular_left_fut = Default::default(); if let Some(dynamic_filter) = &mut self.exec.dynamic_filter { dynamic_filter.filter.reset(); @@ -527,6 +575,7 @@ impl HashJoinExecBuilder { if let Some(prepared) = &exec.prepared_build { prepared.validate(&exec)?; exec.left_fut = Default::default(); + exec.regular_left_fut = Default::default(); exec.metrics = ExecutionPlanMetricsSet::new(); if let Some(filter) = &mut exec.dynamic_filter { filter.build_accumulator = OnceLock::new(); @@ -550,6 +599,7 @@ impl HashJoinExecBuilder { filter, join_type, left_fut, + regular_left_fut, prepared_build, random_state, mode, @@ -596,6 +646,7 @@ impl HashJoinExecBuilder { join_type, join_schema, left_fut, + regular_left_fut, prepared_build, random_state, mode, @@ -628,6 +679,7 @@ impl From<&HashJoinExec> for HashJoinExecBuilder { join_type: exec.join_type, join_schema: Arc::clone(&exec.join_schema), left_fut: Arc::clone(&exec.left_fut), + regular_left_fut: Arc::clone(&exec.regular_left_fut), prepared_build: exec.prepared_build.clone(), random_state: exec.random_state.clone(), mode: exec.mode, @@ -858,6 +910,9 @@ pub struct HashJoinExec { /// Each output stream waits on the `OnceAsync` to signal the completion of /// the hash table creation. left_fut: Arc>, + /// This is similar to [`Self::left_fut`], but specific to the regular join path. + /// See for details. + regular_left_fut: Arc>, /// Immutable build attached by an embedding executor. prepared_build: Option>, /// Shared the `SeededRandomState` for the hashing algorithm (seeds preserved for serialization) @@ -944,6 +999,7 @@ impl fmt::Debug for HashJoinExec { .field("join_type", &self.join_type) .field("join_schema", &self.join_schema) .field("left_fut", &self.left_fut) + .field("regular_left_fut", &self.regular_left_fut) .field("prepared_build", &self.prepared_build) .field("random_state", &self.random_state) .field("mode", &self.mode) @@ -1749,72 +1805,53 @@ impl ExecutionPlan for HashJoinExec { .flatten() .flatten(); - let left_fut = match (&self.prepared_build, self.mode) { - (Some(prepared), _) => { - // Public join fields can change after builder validation. - prepared.validate(self)?; - let prepared = Arc::clone(prepared); - self.left_fut.try_once(|| { - Ok(async move { Ok(prepared.probe_data(right_partitions)) }) - })? - } - (None, PartitionMode::CollectLeft) => self.left_fut.try_once(|| { - let left_stream = self.left.execute(0, Arc::clone(&context))?; - - let reservation = - MemoryConsumer::new("HashJoinInput").register(context.memory_pool()); - - Ok(collect_left_input( - self.random_state.random_state().clone(), - left_stream, - on_left.clone(), - join_metrics.clone(), - reservation, - need_produce_result_in_final(self.join_type), - right_partitions, - enable_dynamic_filter_pushdown, - Arc::clone(context.session_config().options()), - self.null_equality, - not_in, - array_map_created_count, - BuildMode::Ordinary, - )) - })?, - (None, PartitionMode::Partitioned) => { - let left_stream = self.left.execute(partition, Arc::clone(&context))?; - - let reservation = - MemoryConsumer::new(format!("HashJoinInput[{partition}]")) - .register(context.memory_pool()); - OnceFut::new(collect_left_input( - self.random_state.random_state().clone(), - left_stream, - on_left.clone(), - join_metrics.clone(), - reservation, - need_produce_result_in_final(self.join_type), - 1, - enable_dynamic_filter_pushdown, - Arc::clone(context.session_config().options()), - self.null_equality, - not_in, - array_map_created_count, - BuildMode::Ordinary, - )) - } - (None, PartitionMode::Auto) => { - return plan_err!( - "Invalid HashJoinExec, unsupported PartitionMode {:?} in execute()", - PartitionMode::Auto - ); - } + // See the comments on `enable_migration_hash_join` for details. + let use_regular = if let Some(prepared) = &self.prepared_build { + // Public join fields can change after builder validation. + prepared.validate(self)?; + prepared.is_regular() + } else { + context + .session_config() + .options() + .execution + .enable_migration_hash_join + }; + let regular_join = use_regular + .then(|| RegularJoinKind::from_join_type(self.join_type)) + .flatten(); + + // Both paths share collection, then create their own left-side data inside + // the once-only future before sibling probes can access it. + let collect = |build_partition, probe_partitions| { + let left_stream = self.left.execute(build_partition, Arc::clone(&context))?; + let name = match self.mode { + PartitionMode::CollectLeft => "HashJoinInput".to_string(), + _ => format!("HashJoinInput[{build_partition}]"), + }; + let reservation = MemoryConsumer::new(name).register(context.memory_pool()); + Ok::<_, datafusion_common::DataFusionError>(collect_left_input( + self.random_state.random_state().clone(), + left_stream, + on_left.clone(), + join_metrics.clone(), + reservation, + need_produce_result_in_final(self.join_type), + probe_partitions, + enable_dynamic_filter_pushdown, + Arc::clone(context.session_config().options()), + self.null_equality, + not_in, + array_map_created_count.clone(), + BuildMode::Ordinary, + )) }; let batch_size = context.session_config().batch_size(); - // we have the batches and the hash map with their keys. We can how create a stream - // over the right that uses this information to issue new batches. - let right_stream = self.right.execute(partition, context)?; + // The probe stream is not polled until build collection and dynamic + // filter preparation finish. + let right_stream = self.right.execute(partition, Arc::clone(&context))?; // update column indices to reflect the projection let column_indices_after_projection = match self.projection.as_ref() { @@ -1831,6 +1868,85 @@ impl ExecutionPlan for HashJoinExec { .map(|(_, right_expr)| Arc::clone(right_expr)) .collect::>(); + // For the `RegularHashJoinStream` path, prepare build-side data and construct + // the final stream. + if let Some(kind) = regular_join { + let left_fut = match (&self.prepared_build, self.mode) { + (Some(prepared), _) => { + let prepared = Arc::clone(prepared); + self.regular_left_fut.try_once(|| { + Ok(async move { Ok(prepared.regular_probe_data()) }) + })? + } + (None, PartitionMode::CollectLeft) => { + self.regular_left_fut.try_once(|| { + let future = collect(0, right_partitions)?; + Ok(async move { Ok(future.await?.into_regular_left_data()) }) + })? + } + (None, PartitionMode::Partitioned) => { + let future = collect(partition, 1)?; + OnceFut::new( + async move { Ok(future.await?.into_regular_left_data()) }, + ) + } + (None, PartitionMode::Auto) => { + return plan_err!( + "PartitionMode::Auto must be resolved before execution" + ); + } + }; + let build = HashJoinBuild::new( + partition, + self.mode, + left_fut, + build_accumulator, + join_metrics.clone(), + ); + let config = BatchedJoinProcessorConfig { + on_right, + random_state: self.random_state.random_state().clone(), + null_equality: self.null_equality, + filter: self.filter.clone(), + kind, + batch_size, + right_side_ordered: self.right.output_ordering().is_some(), + schema: self.schema(), + probe_schema: right_stream.schema(), + column_indices: column_indices_after_projection, + fetch: self.fetch, + }; + return Ok(RegularHashJoinStream::new( + build, + right_stream, + config, + join_metrics, + ) + .into_stream()); + } + + let left_fut = match (&self.prepared_build, self.mode) { + (Some(prepared), _) => { + let prepared = Arc::clone(prepared); + self.left_fut.try_once(|| { + Ok(async move { Ok(prepared.probe_data(right_partitions)) }) + })? + } + (None, PartitionMode::CollectLeft) => self.left_fut.try_once(|| { + let future = collect(0, right_partitions)?; + Ok(async move { Ok(future.await?.into_legacy_left_data()) }) + })?, + (None, PartitionMode::Partitioned) => { + let future = collect(partition, 1)?; + OnceFut::new(async move { Ok(future.await?.into_legacy_left_data()) }) + } + (None, PartitionMode::Auto) => { + return plan_err!( + "Invalid HashJoinExec, unsupported PartitionMode {:?} in execute()", + PartitionMode::Auto + ); + } + }; Ok(Box::pin(HashJoinStream::new( partition, self.schema(), @@ -2145,6 +2261,7 @@ impl ExecutionPlan for HashJoinExec { join_schema: _, // runtime build-side state, not part of the plan left_fut: _, + regular_left_fut: _, prepared_build, // the fixed `HASH_JOIN_SEED` constant, set identically by the // builder on decode @@ -3101,12 +3218,12 @@ fn concat_build_batches( /// # Dynamic Filter Coordination /// When `should_compute_dynamic_filters` is true, this function computes the min/max bounds /// for each join key column but does NOT update the dynamic filter. Instead, the -/// bounds are stored in the returned `JoinLeftData` and later coordinated by +/// bounds are stored in the returned build data and later coordinated by /// `SharedBuildAccumulator` to ensure all partitions contribute their bounds /// before updating the filter exactly once. /// /// # Returns -/// `JoinLeftData` containing the hash map, consolidated batch, join key values, +/// `CollectedBuild` containing the physical index, consolidated batch, join key values, /// visited indices bitmap, and computed bounds (if requested). #[expect(clippy::too_many_arguments)] async fn collect_left_input( @@ -3123,7 +3240,7 @@ async fn collect_left_input( not_in: Option, array_map_created_count: Count, mode: BuildMode, -) -> Result { +) -> Result { let schema = left_stream.schema(); let prepared = mode == BuildMode::Prepared; @@ -3247,7 +3364,7 @@ fn build_in_memory( not_in: Option, array_map_created_count: &Count, prepared: bool, -) -> Result { +) -> Result { let is_phj_candidate = is_perfect_hash_join_candidate(on_left, schema)?; // Bound before the map so error paths release the map before its charge. @@ -3366,11 +3483,9 @@ fn build_in_memory( }; // Reserve additional memory for visited indices bitmap and create shared builder - let visited_indices_bitmap = if with_visited_indices_bitmap { - allocate_bitmap()? - } else { - BooleanBufferBuilder::new(0) - }; + let visited = with_visited_indices_bitmap + .then(allocate_bitmap) + .transpose()?; let not_in = not_in .map(|not_in| { @@ -3460,7 +3575,7 @@ fn build_in_memory( )?; } - let data = JoinLeftData { + Ok(CollectedBuild { build: Arc::new(JoinBuildData { map, batch, @@ -3470,11 +3585,9 @@ fn build_in_memory( reservation, }), not_in, - visited_indices_bitmap: Mutex::new(visited_indices_bitmap), - probe_completion: ProbeCompletion::new(probe_threads_count), - }; - - Ok(data) + visited, + probe_partitions: probe_threads_count, + }) } #[cfg(test)] @@ -4547,7 +4660,8 @@ mod tests { Count::new(), BuildMode::Ordinary, ) - .await?; + .await? + .into_legacy_left_data(); Ok((left_data, metrics)) } diff --git a/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs b/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs index 70bdfdd0988b7..05ef3f92aef32 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs @@ -19,6 +19,9 @@ use datafusion_execution::memory_pool::MemoryPool; /// and non-spilling INNER joins. Residual conditions belong to each consuming /// join; null-aware joins remain unsupported. /// +/// Preparation chooses the executor. Every consumer uses that executor, even +/// if its migration setting differs from preparation. +/// /// Hash-join gathers copy supported build columns into output buffers, /// including contiguous selections. Output batches can therefore outlive this /// object without retaining unaccounted cached payload. View, dictionary and @@ -28,6 +31,7 @@ pub struct PreparedHashJoinBuild { build: Arc, keys: Vec, null_equality: NullEquality, + regular: bool, } impl fmt::Debug for PreparedHashJoinBuild { @@ -53,7 +57,11 @@ impl PreparedHashJoinBuild { self.build.batch.num_rows() } - /// Create independent mutable state for one consuming join. + pub(super) fn is_regular(&self) -> bool { + self.regular + } + + /// Create independent mutable state for one consuming legacy join. pub(super) fn probe_data(&self, probe_threads: usize) -> JoinLeftData { JoinLeftData { build: Arc::clone(&self.build), @@ -64,6 +72,12 @@ impl PreparedHashJoinBuild { } } + /// Create independent [`RegularJoinLeftData`] for one consuming regular join. + /// Prepared builds currently support INNER only, so no unmatched-row state is needed. + pub(super) fn regular_probe_data(&self) -> RegularJoinLeftData { + RegularJoinLeftData::new(Arc::clone(&self.build), None, 0) + } + /// Validate the build descriptor and current execution restrictions without /// consuming input or modifying either plan. Cache identity is caller-owned. pub(super) fn validate(&self, join: &HashJoinExec) -> Result<()> { @@ -105,8 +119,10 @@ impl HashJoinExec { /// embedding executor. This method does not provide a cache. /// /// Errors and cancellation release unfinished work. `config` controls - /// perfect-map and dynamic-filter choices. Byte keys use hash membership - /// to avoid copying payloads into range bounds and IN-list literals. + /// the executor, perfect-map and dynamic-filter choices. + /// The prepared build selects each consumer's executor independently of + /// the consumer's `enable_migration_hash_join` setting. Byte keys use hash + /// membership to avoid copying payloads into range bounds and IN-list literals. /// Consumer-local dynamic-filter allocations are outside this reservation. /// /// # Example @@ -169,6 +185,7 @@ impl HashJoinExec { let count = MetricBuilder::new(&metrics_set) .counter(ARRAY_MAP_CREATED_COUNT_METRIC_NAME, 0); let reservation = MemoryConsumer::new("PreparedHashJoinBuild").register(&pool); + let regular = config.execution.enable_migration_hash_join; let data = collect_left_input( self.random_state.random_state().clone(), input, @@ -189,6 +206,7 @@ impl HashJoinExec { build: data.build, keys, null_equality: self.null_equality, + regular, })) } } diff --git a/datafusion/physical-plan/src/joins/hash_join/mod.rs b/datafusion/physical-plan/src/joins/hash_join/mod.rs index 2254b38200242..e5a10cfd3e6cf 100644 --- a/datafusion/physical-plan/src/joins/hash_join/mod.rs +++ b/datafusion/physical-plan/src/joins/hash_join/mod.rs @@ -2,7 +2,21 @@ // 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 -//! [`HashJoinExec`] Partitioned Hash Join Operator +//! [`HashJoinExec`]: implementation for hash join. +//! +//! # Regular (inner/left/right/full) Hash Join implementation +//! +//! There are three major layers during execution: +//! +//! 1. [`RegularHashJoinStream::into_stream`]: the state machine entry point, +//! driving the build, probe, and final output stages. +//! 2. [`BatchedJoinProcessor`]: probes the raw index, evaluates the residual filter, +//! and coalesces output. Each lookup returns up to `batch_size` candidate pairs. +//! 3. [`Map`]: the raw build-side index (hash table or integer-key array map). +//! +//! [`RegularHashJoinStream::into_stream`]: regular_join::RegularHashJoinStream::into_stream +//! [`BatchedJoinProcessor`]: batched_join_processor::BatchedJoinProcessor +//! [`Map`]: crate::joins::Map pub use exec::{HashJoinExec, HashJoinExecBuilder, PreparedHashJoinBuild}; /// # Public Only for Internal Use: @@ -14,9 +28,12 @@ pub use exec::{HashJoinExec, HashJoinExecBuilder, PreparedHashJoinBuild}; pub use partitioned_hash_eval::HashTableLookupExpr; pub use partitioned_hash_eval::{HashExpr, SeededRandomState}; +mod batched_join_processor; +mod build; mod exec; mod inlist_builder; mod not_in; mod partitioned_hash_eval; +mod regular_join; mod shared_bounds; mod stream; diff --git a/datafusion/physical-plan/src/joins/hash_join/regular_join.rs b/datafusion/physical-plan/src/joins/hash_join/regular_join.rs new file mode 100644 index 0000000000000..07d5c838e2997 --- /dev/null +++ b/datafusion/physical-plan/src/joins/hash_join/regular_join.rs @@ -0,0 +1,179 @@ +// 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 + +//! State machine implementation for the regular hash join execution path. (Inner/ +//! Left/Right/Full join types are regular joins.) +//! +//! HashJoinExec is getting incrementally migrated to separate streams; see the issue +//! for details: +//! - + +use std::sync::Arc; + +use arrow::datatypes::SchemaRef; +use arrow::record_batch::RecordBatch; +use datafusion_common::{DataFusionError, Result, internal_err}; +use datafusion_execution::{TryEmitter, async_try_stream}; +use futures::TryStreamExt; + +use super::batched_join_processor::{ + BatchedJoinProcessor, BatchedJoinProcessorConfig, JoinStep, +}; +use super::build::HashJoinBuild; +use crate::SendableRecordBatchStream; +use crate::joins::utils::BuildProbeJoinMetrics; +use crate::metrics::BaselineMetrics; +use crate::stream::{ObservedStream, RecordBatchStreamAdapter}; + +/// Implementation for regular (Inner/Left/Right/Full) hash joins. +/// +/// See the [`super`] documentation for the high-level architecture. +/// [`Self::into_stream`] is the entry point for execution. +pub(super) struct RegularHashJoinStream { + schema: SchemaRef, + metrics: BaselineMetrics, + stage: ExecutionStage, +} + +/// Execution stages described in [`RegularHashJoinStream::into_stream`]. +enum ExecutionStage { + Building(Building), + Probing(Probing), + Outputting(BatchedJoinProcessor), +} + +struct Building { + build: HashJoinBuild, + probe: SendableRecordBatchStream, + config: BatchedJoinProcessorConfig, + metrics: BuildProbeJoinMetrics, +} + +struct Probing { + probe: SendableRecordBatchStream, + metrics: BuildProbeJoinMetrics, + processor: BatchedJoinProcessor, +} + +impl RegularHashJoinStream { + pub(super) fn new( + build: HashJoinBuild, + probe: SendableRecordBatchStream, + config: BatchedJoinProcessorConfig, + metrics: BuildProbeJoinMetrics, + ) -> Self { + Self { + schema: Arc::clone(&config.schema), + metrics: metrics.baseline.clone(), + stage: ExecutionStage::Building(Building { + build, + probe, + config, + metrics, + }), + } + } + + /// Entry point for the regular hash join execution stages. + /// + /// ```text + /// Building --> Probing --> Outputting --> end + /// ``` + /// + /// # Stages + /// + /// - Building: Load the build-side data, and handle cross-partition synchronization. + /// See [`HashJoinBuild`] for different physical strategies. + /// - Probing: Join probe batches with build data incrementally, until the + /// probe-side input is exhausted. + /// - Outputting: Drain buffered output, then emit unmatched build rows for + /// left/full joins. + /// + /// # Transition edges + /// + /// - `Building -> Probing`: The build data and its index are ready. + /// - `Probing -> Outputting`: Probe input reaches EOF. Release it and report + /// completion to the processor. + /// - `Outputting -> end`: Buffered output and any final unmatched build rows + /// have been emitted. + pub(super) fn into_stream(self) -> SendableRecordBatchStream { + let Self { + schema, + metrics, + stage, + } = self; + let stream = async_try_stream(|mut emitter| async move { + let mut stage = Some(stage); + while let Some(current_stage) = stage { + stage = match current_stage { + ExecutionStage::Building(building) => { + Some(building.handle_stage().await?) + } + ExecutionStage::Probing(probing) => { + probing.handle_stage(&mut emitter).await? + } + ExecutionStage::Outputting(mut processor) => { + loop { + match processor.next_output_batch()? { + JoinStep::Output(batch) => emitter.emit(batch).await, + JoinStep::Finished => break, + JoinStep::NeedInput => { + return internal_err!( + "BatchedJoinProcessor requested probe input after probe EOF" + ); + } + } + } + None + } + }; + } + Ok(()) + }); + let stream = Box::pin(RecordBatchStreamAdapter::new(schema, stream)); + Box::pin(ObservedStream::new(stream, metrics, None)) + } +} + +impl Building { + /// See the comments on [`RegularHashJoinStream::into_stream`] for details. + async fn handle_stage(self) -> Result { + let build = self.build.prepare().await?; + Ok(ExecutionStage::Probing(Probing { + probe: self.probe, + metrics: self.metrics.clone(), + processor: BatchedJoinProcessor::new(build, self.config, self.metrics), + })) + } +} + +impl Probing { + /// See the comments on [`RegularHashJoinStream::into_stream`] for details. + async fn handle_stage( + mut self, + emitter: &mut TryEmitter, + ) -> Result> { + loop { + match self.processor.next_output_batch()? { + JoinStep::Output(batch) => emitter.emit(batch).await, + JoinStep::NeedInput => match self.probe.try_next().await? { + Some(batch) => { + self.metrics.input_batches.add(1); + self.metrics.input_rows.add(batch.num_rows()); + self.metrics.probe_hit_rate.add_total(batch.num_rows()); + self.processor.push_batch(batch)?; + } + None => { + drop(self.probe); + self.processor.finish_probe()?; + return Ok(Some(ExecutionStage::Outputting(self.processor))); + } + }, + JoinStep::Finished => { + return Ok(None); + } + } + } + } +} diff --git a/datafusion/sqllogictest/test_files/information_schema.slt b/datafusion/sqllogictest/test_files/information_schema.slt index 7e8abe025e346..c2464b0b4f3ce 100644 --- a/datafusion/sqllogictest/test_files/information_schema.slt +++ b/datafusion/sqllogictest/test_files/information_schema.slt @@ -211,6 +211,7 @@ datafusion.execution.collect_statistics true datafusion.execution.enable_ansi_mode false datafusion.execution.enable_file_stream_work_stealing true datafusion.execution.enable_migration_aggregate true +datafusion.execution.enable_migration_hash_join true datafusion.execution.enable_nlj_coordinated_fallback true datafusion.execution.enable_recursive_ctes true datafusion.execution.enforce_batch_size_in_joins false @@ -381,6 +382,7 @@ datafusion.execution.collect_statistics true Should DataFusion collect statistic datafusion.execution.enable_ansi_mode false Whether to enable ANSI SQL mode. The flag is experimental and relevant only for DataFusion Spark built-in functions When `enable_ansi_mode` is set to `true`, the query engine follows ANSI SQL semantics for expressions, casting, and error handling. This means: - **Strict type coercion rules:** implicit casts between incompatible types are disallowed. - **Standard SQL arithmetic behavior:** operations such as division by zero, numeric overflow, or invalid casts raise runtime errors rather than returning `NULL` or adjusted values. - **Consistent ANSI behavior** for string concatenation, comparisons, and `NULL` handling. When `enable_ansi_mode` is `false` (the default), the engine uses a more permissive, non-ANSI mode designed for user convenience and backward compatibility. In this mode: - Implicit casts between types are allowed (e.g., string to integer when possible). - Arithmetic operations are more lenient — for example, `abs()` on the minimum representable integer value returns the input value instead of raising overflow. - Division by zero or invalid casts may return `NULL` instead of failing. # Default `false` — ANSI SQL mode is disabled by default. datafusion.execution.enable_file_stream_work_stealing true When `true` (the default), DataFusion's built-in file scans dynamically rebalance files across partitions at query execution time: a partition that goes idle reads files (or byte-range morsels) originally assigned to a sibling partition, which keeps all partitions busy in a single process. Executors that depend on the plan-time partition assignment — such as Ballista and datafusion-distributed, which run each partition as an isolated task and never poll the siblings — should set this to `false` so each partition reads only its own file group and no runtime reassignment occurs. datafusion.execution.enable_migration_aggregate true Whether aggregation uses the implementation from the major refactor completed in the 56.0.0 release. When set to `false`, aggregation falls back to the implementation used before 55.0.0. The fallback exists only as a workaround for bugs in the new implementation and will be removed, together with this option, after the 56.0.0 release. See for details. +datafusion.execution.enable_migration_hash_join true Whether inner, left outer, right outer, and full outer hash joins use the refactored probe implementation. When set to `false`, these joins use the previous probe implementation. The fallback exists only as a workaround for bugs in the new implementation and will be removed, together with this option, once the migration is complete. See for details. datafusion.execution.enable_nlj_coordinated_fallback true Enables the memory-limited fallback for `NestedLoopJoinExec` join types that emit unmatched left rows in the final output (LEFT, LEFT SEMI, LEFT ANTI, LEFT MARK, FULL) when the right side has multiple partitions. This fallback shares left-side state (the current left chunk, the visited bitmap and the probe-thread counter) across all right-side partitions, which assumes every partition runs in the same process. Distributed engines that execute each output partition as an independent task (e.g. Ballista, datafusion-distributed) give each task its own copy of this state and poll only one partition, so the cross-partition counter never reaches zero and the fallback would stall. Such engines should set this to `false`: the coordinated fallback is then disabled for left-emitting multi-partition joins, which instead fail with a resource-exhaustion error under memory pressure rather than deadlocking. Single-partition and non-left-emitting joins are unaffected and always keep the fallback. datafusion.execution.enable_recursive_ctes true Should DataFusion support recursive CTEs datafusion.execution.enforce_batch_size_in_joins false Should DataFusion enforce batch size in joins or not. By default, DataFusion will not enforce batch size in joins. Enforcing batch size in joins can reduce memory usage when joining large tables with a highly-selective join filter, but is also slightly slower. Note: this option currently only applies to the symmetric hash join. diff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.md index 0ebb23cf0be98..6e7ce42739aaf 100644 --- a/docs/source/user-guide/configs.md +++ b/docs/source/user-guide/configs.md @@ -114,6 +114,7 @@ The following configuration settings are available: | datafusion.execution.planning_concurrency | 0 | Fan-out during initial physical planning. This is mostly use to plan `UNION` children in parallel. Defaults to the number of CPU cores on the system | | datafusion.execution.skip_physical_aggregate_schema_check | false | When set to true, skips verifying that the schema produced by planning the input of `LogicalPlan::Aggregate` exactly matches the schema of the input plan. When set to false, if the schema does not match exactly (including nullability and metadata), a planning error will be raised. This is used to workaround bugs in the planner that are now caught by the new schema verification step. | | datafusion.execution.enable_migration_aggregate | true | Whether aggregation uses the implementation from the major refactor completed in the 56.0.0 release. When set to `false`, aggregation falls back to the implementation used before 55.0.0. The fallback exists only as a workaround for bugs in the new implementation and will be removed, together with this option, after the 56.0.0 release. See for details. | +| datafusion.execution.enable_migration_hash_join | true | Whether inner, left outer, right outer, and full outer hash joins use the refactored probe implementation. When set to `false`, these joins use the previous probe implementation. The fallback exists only as a workaround for bugs in the new implementation and will be removed, together with this option, once the migration is complete. See for details. | | datafusion.execution.spill_compression | uncompressed | Sets the compression codec used when spilling data to disk. Since datafusion writes spill files using the Arrow IPC Stream format, only codecs supported by the Arrow IPC Stream Writer are allowed. Valid values are: uncompressed, lz4_frame, zstd. Note: lz4_frame offers faster (de)compression, but typically results in larger spill files. In contrast, zstd achieves higher compression ratios at the cost of slower (de)compression speed. | | datafusion.execution.sort_spill_reservation_bytes | 10485760 | Specifies the reserved memory for each spillable sort operation to facilitate an in-memory merge. When a sort operation spills to disk, the in-memory data must be sorted and merged before being written to a file. This setting reserves a specific amount of memory for that in-memory sort/merge process. Note: This setting is irrelevant if the sort operation cannot spill (i.e., if there's no `DiskManager` configured). | | datafusion.execution.sort_in_place_threshold_bytes | 1048576 | When sorting, below what size should data be concatenated and sorted in a single RecordBatch rather than sorted in batches and merged. | From b93c3dda9ea46c4aa9c06f81a16be29ac765ae5a Mon Sep 17 00:00:00 2001 From: Yongting You <2010youy01@gmail.com> Date: Mon, 16 Nov 2026 16:13:21 +0800 Subject: [PATCH 2/9] Test both regular and legacy hash join paths --- datafusion/core/tests/fuzz_cases/join_fuzz.rs | 23 +++++++++++++------ .../join_disable_repartition_joins.slt | 2 ++ .../test_files/join_is_not_distinct_from.slt | 2 ++ .../test_files/join_limit_pushdown.slt | 2 ++ .../sqllogictest/test_files/join_only.slt | 2 ++ datafusion/sqllogictest/test_files/joins.slt | 2 ++ .../test_files/sort_merge_join_matrix.slt | 2 ++ 7 files changed, 28 insertions(+), 7 deletions(-) diff --git a/datafusion/core/tests/fuzz_cases/join_fuzz.rs b/datafusion/core/tests/fuzz_cases/join_fuzz.rs index c98e0b40dc7f9..77473c97e1e54 100644 --- a/datafusion/core/tests/fuzz_cases/join_fuzz.rs +++ b/datafusion/core/tests/fuzz_cases/join_fuzz.rs @@ -1028,8 +1028,15 @@ impl JoinFuzzTestCase { let mut nlj_formatted_sorted: Vec<&str> = nlj_formatted.trim().lines().collect(); nlj_formatted_sorted.sort_unstable(); - for batch_size in self.batch_sizes { - let session_config = SessionConfig::new().with_batch_size(*batch_size); + // Exercise both hash join implementations with the same inputs and batch sizes. + for (batch_size, enable_migration_hash_join) in + self.batch_sizes.iter().cartesian_product([true, false]) + { + let mut session_config = SessionConfig::new().with_batch_size(*batch_size); + session_config + .options_mut() + .execution + .enable_migration_hash_join = enable_migration_hash_join; let ctx = SessionContext::new_with_config(session_config); let task_ctx = ctx.task_ctx(); @@ -1063,7 +1070,9 @@ impl JoinFuzzTestCase { let fuzz_debug = "fuzz_test_debug"; std::fs::remove_dir_all(fuzz_debug).unwrap_or(()); std::fs::create_dir_all(fuzz_debug).unwrap(); - let out_dir_name = &format!("{fuzz_debug}/batch_size_{batch_size}"); + let out_dir_name = &format!( + "{fuzz_debug}/batch_size_{batch_size}_enable_migration_hash_join_{enable_migration_hash_join}" + ); println!( "Test result data mismatch found. HJ rows {hj_rows}, SMJ rows {smj_rows}, NLJ rows {nlj_rows}" ); @@ -1126,7 +1135,7 @@ impl JoinFuzzTestCase { if join_tests.contains(&NljHj) { let err_msg_rowcnt = format!( - "NestedLoopJoinExec and HashJoinExec produced different row counts, batch_size: {batch_size}" + "NestedLoopJoinExec and HashJoinExec produced different row counts, batch_size: {batch_size}, enable_migration_hash_join: {enable_migration_hash_join}" ); assert_eq!(nlj_rows, hj_rows, "{}", err_msg_rowcnt.as_str()); if nlj_rows == 0 && hj_rows == 0 { @@ -1135,7 +1144,7 @@ impl JoinFuzzTestCase { } let err_msg_contents = format!( - "NestedLoopJoinExec and HashJoinExec produced different results, batch_size: {batch_size}" + "NestedLoopJoinExec and HashJoinExec produced different results, batch_size: {batch_size}, enable_migration_hash_join: {enable_migration_hash_join}" ); // row level compare if any of joins returns the result // the reason is different formatting when there is no rows @@ -1155,12 +1164,12 @@ impl JoinFuzzTestCase { if join_tests.contains(&HjSmj) { let err_msg_row_cnt = format!( - "HashJoinExec and SortMergeJoinExec produced different row counts, batch_size: {batch_size}" + "HashJoinExec and SortMergeJoinExec produced different row counts, batch_size: {batch_size}, enable_migration_hash_join: {enable_migration_hash_join}" ); assert_eq!(hj_rows, smj_rows, "{}", err_msg_row_cnt.as_str()); let err_msg_contents = format!( - "SortMergeJoinExec and HashJoinExec produced different results, batch_size: {batch_size}" + "SortMergeJoinExec and HashJoinExec produced different results, batch_size: {batch_size}, enable_migration_hash_join: {enable_migration_hash_join}" ); // row level compare if any of joins returns the result // the reason is different formatting when there is no rows diff --git a/datafusion/sqllogictest/test_files/join_disable_repartition_joins.slt b/datafusion/sqllogictest/test_files/join_disable_repartition_joins.slt index d82c58a1abda7..2dbdc95af04e0 100644 --- a/datafusion/sqllogictest/test_files/join_disable_repartition_joins.slt +++ b/datafusion/sqllogictest/test_files/join_disable_repartition_joins.slt @@ -2,6 +2,8 @@ # 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 +# configMatrix: datafusion.execution.enable_migration_hash_join=true,false + ########## ## Join Tests ########## diff --git a/datafusion/sqllogictest/test_files/join_is_not_distinct_from.slt b/datafusion/sqllogictest/test_files/join_is_not_distinct_from.slt index c4660c0e41be5..e00cd07a080a9 100644 --- a/datafusion/sqllogictest/test_files/join_is_not_distinct_from.slt +++ b/datafusion/sqllogictest/test_files/join_is_not_distinct_from.slt @@ -2,6 +2,8 @@ # 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 +# configMatrix: datafusion.execution.enable_migration_hash_join=true,false + # Test IS NOT DISTINCT FROM join functionality # This tests the optimizer's ability to convert IS NOT DISTINCT FROM joins # to equijoins with proper null equality handling diff --git a/datafusion/sqllogictest/test_files/join_limit_pushdown.slt b/datafusion/sqllogictest/test_files/join_limit_pushdown.slt index 3530f5ae03106..d34f7d5b6ad21 100644 --- a/datafusion/sqllogictest/test_files/join_limit_pushdown.slt +++ b/datafusion/sqllogictest/test_files/join_limit_pushdown.slt @@ -2,6 +2,8 @@ # 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 +# configMatrix: datafusion.execution.enable_migration_hash_join=true,false + # Tests for limit pushdown into joins # need to use a single partition for deterministic results diff --git a/datafusion/sqllogictest/test_files/join_only.slt b/datafusion/sqllogictest/test_files/join_only.slt index f8974b7f07ea7..7fe78fdee947b 100644 --- a/datafusion/sqllogictest/test_files/join_only.slt +++ b/datafusion/sqllogictest/test_files/join_only.slt @@ -2,6 +2,8 @@ # 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 +# configMatrix: datafusion.execution.enable_migration_hash_join=true,false + include ./join.slt.part # Config reset diff --git a/datafusion/sqllogictest/test_files/joins.slt b/datafusion/sqllogictest/test_files/joins.slt index 23fef32e66070..b9c987cfd4f47 100644 --- a/datafusion/sqllogictest/test_files/joins.slt +++ b/datafusion/sqllogictest/test_files/joins.slt @@ -2,6 +2,8 @@ # 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 +# configMatrix: datafusion.execution.enable_migration_hash_join=true,false + #### # Configuration #### diff --git a/datafusion/sqllogictest/test_files/sort_merge_join_matrix.slt b/datafusion/sqllogictest/test_files/sort_merge_join_matrix.slt index 766aa7b3b031a..94b9690e668cb 100644 --- a/datafusion/sqllogictest/test_files/sort_merge_join_matrix.slt +++ b/datafusion/sqllogictest/test_files/sort_merge_join_matrix.slt @@ -5,6 +5,7 @@ # Sort-merge-join correctness across a config matrix. Every equijoin runs on # SortMergeJoin (prefer_hash_join=false) and HashJoin (true), so sweeping # {true,false} x batch_size {1,2,100,8192} requires them to agree row-for-row. +# Run both hash join implementations with enable_migration_hash_join=true,false. # batch_size=1 forces equal-key runs to span single-row batches (historically # bug-prone). SMJ needs target_partitions>1 and repartition_joins, set below (not # swept). Null-aware NOT IN always uses HashJoin, so it is out of scope (see @@ -13,6 +14,7 @@ # configMatrix: datafusion.optimizer.prefer_hash_join=true,false # configMatrix: datafusion.execution.batch_size=1,2,100,8192 +# configMatrix: datafusion.execution.enable_migration_hash_join=true,false statement ok set datafusion.execution.target_partitions = 4; From 282a10f16a88d368907073f8eeffbd5ffcb5f52d Mon Sep 17 00:00:00 2001 From: Yongting You <2010youy01@gmail.com> Date: Tue, 17 Nov 2026 20:40:54 +0800 Subject: [PATCH 3/9] review: speedup slow metrics update --- .../joins/hash_join/batched_join_processor.rs | 38 ++++++++++--------- .../src/joins/hash_join/stream.rs | 2 +- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs b/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs index b1e7db5022490..478f8d683c824 100644 --- a/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs +++ b/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs @@ -22,7 +22,7 @@ use datafusion_physical_expr::PhysicalExprRef; use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays; use super::build::RegularJoinLeftData; -use super::stream::lookup_join_hashmap; +use super::stream::{count_distinct_sorted_indices, lookup_join_hashmap}; use crate::coalesce::{LimitedBatchCoalescer, PushBatchStatus}; use crate::hash_utils::create_hashes; use crate::joins::Map; @@ -314,18 +314,18 @@ impl BatchedJoinProcessor { Ok(()) } - /// Join another portion of the current probe batch against the build batch. + /// Return a materialized joined batch in the output schema for one probe chunk. /// - /// 1. Collect up to `batch_size` key-equal row-index pairs - /// in `build_indices` and `probe_indices`. - /// 2. Apply the join filter, record successful matches, - /// and add probe rows now known to be unmatched for right/full joins. - /// 3. Materialize those pairs into a batch. [`Self::next_output_batch`] - /// coalesces small batches of surviving pairs and unmatched rows. + /// For an INNER JOIN on `t1.c1 = t2.c1 AND t1.c2 > t2.c2`, with + /// `batch_size = 8192`: /// - /// One call may cover part of one probe row's matches or several probe rows. - /// An empty batch means this chunk produced no output; `None` means the - /// current probe batch is drained. + /// 1. Use the index to look up at most 8192 key-equal row pairs (`t1.c1 = t2.c1`). + /// 2. Evaluate the residual filter `t1.c2 > t2.c2`; suppose only 100 pairs pass. + /// 3. Materialize those 100 pairs in the final output schema and return the batch. + /// + /// For non-inner joins, matched rows will be tracked for final output. + /// + /// For small output batches, the caller will coalesce them for final output. fn probe_chunk(&mut self) -> Result> { let Some(probe) = &mut self.probe else { return Ok(None); @@ -386,14 +386,16 @@ impl BatchedJoinProcessor { } }; - // Equality pairs are ordered by probe row. A row continuing from the - // previous chunk contributes fanout, but not another probe hit. - let mut matched_probe_rows = 0; - for &row in probe_indices.values().iter() { - if probe.last_probe_row_with_key_match != Some(row) { - matched_probe_rows += 1; - probe.last_probe_row_with_key_match = Some(row); + // Update metrics `probe_hit_rate` and `avg_fanout`` + let mut matched_probe_rows = count_distinct_sorted_indices(&probe_indices); + if let (Some(&first), Some(&last)) = ( + probe_indices.values().first(), + probe_indices.values().last(), + ) { + if Some(first) == probe.last_probe_row_with_key_match { + matched_probe_rows -= 1; } + probe.last_probe_row_with_key_match = Some(last); } self.metrics.probe_hit_rate.add_part(matched_probe_rows); self.metrics.avg_fanout.add_part(build_indices.len()); diff --git a/datafusion/physical-plan/src/joins/hash_join/stream.rs b/datafusion/physical-plan/src/joins/hash_join/stream.rs index c03354ccff979..80cc3251c651e 100644 --- a/datafusion/physical-plan/src/joins/hash_join/stream.rs +++ b/datafusion/physical-plan/src/joins/hash_join/stream.rs @@ -537,7 +537,7 @@ pub(super) fn lookup_join_hashmap( /// /// The input array must be sorted (e.g., `[0, 1, 1, 2, 2, ...]`) and contain no null values. #[inline] -fn count_distinct_sorted_indices(indices: &UInt32Array) -> usize { +pub(super) fn count_distinct_sorted_indices(indices: &UInt32Array) -> usize { if indices.is_empty() { return 0; } From d4c0a3fda32b6d55a7cc568791b79f61ec534d83 Mon Sep 17 00:00:00 2001 From: Yongting You <2010youy01@gmail.com> Date: Tue, 17 Nov 2026 20:55:53 +0800 Subject: [PATCH 4/9] review: improve err message --- datafusion/physical-plan/src/joins/hash_join/build.rs | 6 ++++-- datafusion/physical-plan/src/joins/hash_join/exec.rs | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/datafusion/physical-plan/src/joins/hash_join/build.rs b/datafusion/physical-plan/src/joins/hash_join/build.rs index 94f98a0692219..47a807fbc673a 100644 --- a/datafusion/physical-plan/src/joins/hash_join/build.rs +++ b/datafusion/physical-plan/src/joins/hash_join/build.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use arrow::array::{BooleanBufferBuilder, UInt64Array}; use arrow::buffer::BooleanBuffer; -use datafusion_common::Result; +use datafusion_common::{Result, internal_err}; use futures::future::poll_fn; use parking_lot::Mutex; @@ -158,7 +158,9 @@ impl HashJoinBuild { keys_have_null, }, PartitionMode::Auto => { - unreachable!("PartitionMode::Auto must be resolved before execution") + return internal_err!( + "PartitionMode::Auto must be resolved before execution" + ); } }; diff --git a/datafusion/physical-plan/src/joins/hash_join/exec.rs b/datafusion/physical-plan/src/joins/hash_join/exec.rs index 69d69d88629be..bd2c0fd254485 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec.rs @@ -1892,7 +1892,8 @@ impl ExecutionPlan for HashJoinExec { } (None, PartitionMode::Auto) => { return plan_err!( - "PartitionMode::Auto must be resolved before execution" + "Invalid HashJoinExec, unsupported PartitionMode {:?} in execute()", + PartitionMode::Auto ); } }; From ef96c9b538feaf05a3000d15d37e25b1d8ef1830 Mon Sep 17 00:00:00 2001 From: Yongting You <2010youy01@gmail.com> Date: Tue, 17 Nov 2026 21:03:37 +0800 Subject: [PATCH 5/9] fix: honor consumer config for prepared hash joins --- .../physical-plan/src/joins/hash_join/exec.rs | 18 +++-- .../src/joins/hash_join/exec/prepared.rs | 16 +---- .../joins/hash_join/exec/prepared/tests.rs | 65 ++++++++++++++++++- 3 files changed, 74 insertions(+), 25 deletions(-) diff --git a/datafusion/physical-plan/src/joins/hash_join/exec.rs b/datafusion/physical-plan/src/joins/hash_join/exec.rs index bd2c0fd254485..dd2f172b28c53 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec.rs @@ -1805,18 +1805,16 @@ impl ExecutionPlan for HashJoinExec { .flatten() .flatten(); - // See the comments on `enable_migration_hash_join` for details. - let use_regular = if let Some(prepared) = &self.prepared_build { + if let Some(prepared) = &self.prepared_build { // Public join fields can change after builder validation. prepared.validate(self)?; - prepared.is_regular() - } else { - context - .session_config() - .options() - .execution - .enable_migration_hash_join - }; + } + // See the comments on `enable_migration_hash_join` for details. + let use_regular = context + .session_config() + .options() + .execution + .enable_migration_hash_join; let regular_join = use_regular .then(|| RegularJoinKind::from_join_type(self.join_type)) .flatten(); diff --git a/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs b/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs index 05ef3f92aef32..7b580f09d3866 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs @@ -19,9 +19,6 @@ use datafusion_execution::memory_pool::MemoryPool; /// and non-spilling INNER joins. Residual conditions belong to each consuming /// join; null-aware joins remain unsupported. /// -/// Preparation chooses the executor. Every consumer uses that executor, even -/// if its migration setting differs from preparation. -/// /// Hash-join gathers copy supported build columns into output buffers, /// including contiguous selections. Output batches can therefore outlive this /// object without retaining unaccounted cached payload. View, dictionary and @@ -31,7 +28,6 @@ pub struct PreparedHashJoinBuild { build: Arc, keys: Vec, null_equality: NullEquality, - regular: bool, } impl fmt::Debug for PreparedHashJoinBuild { @@ -57,10 +53,6 @@ impl PreparedHashJoinBuild { self.build.batch.num_rows() } - pub(super) fn is_regular(&self) -> bool { - self.regular - } - /// Create independent mutable state for one consuming legacy join. pub(super) fn probe_data(&self, probe_threads: usize) -> JoinLeftData { JoinLeftData { @@ -119,10 +111,8 @@ impl HashJoinExec { /// embedding executor. This method does not provide a cache. /// /// Errors and cancellation release unfinished work. `config` controls - /// the executor, perfect-map and dynamic-filter choices. - /// The prepared build selects each consumer's executor independently of - /// the consumer's `enable_migration_hash_join` setting. Byte keys use hash - /// membership to avoid copying payloads into range bounds and IN-list literals. + /// perfect-map and dynamic-filter choices. Byte keys use hash membership + /// to avoid copying payloads into range bounds and IN-list literals. /// Consumer-local dynamic-filter allocations are outside this reservation. /// /// # Example @@ -185,7 +175,6 @@ impl HashJoinExec { let count = MetricBuilder::new(&metrics_set) .counter(ARRAY_MAP_CREATED_COUNT_METRIC_NAME, 0); let reservation = MemoryConsumer::new("PreparedHashJoinBuild").register(&pool); - let regular = config.execution.enable_migration_hash_join; let data = collect_left_input( self.random_state.random_state().clone(), input, @@ -206,7 +195,6 @@ impl HashJoinExec { build: data.build, keys, null_equality: self.null_equality, - regular, })) } } diff --git a/datafusion/physical-plan/src/joins/hash_join/exec/prepared/tests.rs b/datafusion/physical-plan/src/joins/hash_join/exec/prepared/tests.rs index 4f874f8c95af2..5d3bd9c5921d6 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec/prepared/tests.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec/prepared/tests.rs @@ -24,7 +24,7 @@ use arrow::buffer::Buffer; use arrow::compute::kernels::sort::SortOptions; use arrow_schema::Field; use datafusion_common::test_util::batches_to_sort_string; -use datafusion_common::{DataFusionError, assert_batches_eq}; +use datafusion_common::{DataFusionError, assert_batches_eq, assert_batches_sorted_eq}; use datafusion_common_runtime::SpawnedTask; use datafusion_execution::memory_pool::GreedyMemoryPool; use datafusion_expr::Operator; @@ -150,6 +150,69 @@ fn payload_filter(op: Operator) -> JoinFilter { ) } +// Construct a prepared build with `enable_migration_hash_join = X`, then use it +// with the opposite setting to verify compatibility. +// +// Temporary test for the refactor; see the comments on +// `enable_migration_hash_join` for details. +#[tokio::test] +async fn prepared_build_uses_consumer_executor_setting() -> Result<()> { + let build = batch(vec![Some(1), Some(1)]); + let base = join(build.schema(), batch(vec![Some(1)]))?; + for prepare_regular in [false, true] { + let mut config = ConfigOptions::default(); + config.execution.enable_migration_hash_join = prepare_regular; + let prepared = base + .prepare_build( + input(vec![build.clone()], build.schema()), + Arc::new(GreedyMemoryPool::new(1 << 20)), + Arc::new(config), + ) + .await?; + for consume_regular in [false, true] { + let task = base + .builder() + .with_prepared_build(Arc::clone(&prepared)) + .build()?; + let mut config = ConfigOptions::default(); + config.execution.enable_migration_hash_join = consume_regular; + let context = + Arc::new(TaskContext::default().with_session_config(config.into())); + let actual = common::collect(task.execute(0, context)?).await?; + assert_batches_sorted_eq!( + [ + "+-----+---------+-----+---------+", + "| key | payload | key | payload |", + "+-----+---------+-----+---------+", + "| 1 | 10 | 1 | 10 |", + "| 1 | 11 | 1 | 10 |", + "+-----+---------+-----+---------+", + ], + &actual + ); + + // Both executors return the same rows; check which one was initialized. + let mut initialized_by_check = false; + if consume_regular { + task.regular_left_fut.try_once(|| { + initialized_by_check = true; + Ok(std::future::pending()) + })?; + } else { + task.left_fut.try_once(|| { + initialized_by_check = true; + Ok(std::future::pending()) + })?; + } + assert!( + !initialized_by_check, + "prepare={prepare_regular}, consume={consume_regular}" + ); + } + } + Ok(()) +} + #[tokio::test] async fn prepared_build_placeholder_properties_and_reset() -> Result<()> { let ascending = |name, index| PhysicalSortExpr { From 835fcb1feaea6c15d04abcb96cd951ddc612b460 Mon Sep 17 00:00:00 2001 From: Yongting You <2010youy01@gmail.com> Date: Wed, 18 Nov 2026 16:15:52 +0800 Subject: [PATCH 6/9] Update datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs Co-authored-by: Matt Butrovich --- .../src/joins/hash_join/batched_join_processor.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs b/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs index 478f8d683c824..47fb902e63152 100644 --- a/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs +++ b/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs @@ -314,7 +314,7 @@ impl BatchedJoinProcessor { Ok(()) } - /// Return a materialized joined batch in the output schema for one probe chunk. + /// Look up, filter, and materialize the next chunk of the current probe batch. /// /// For an INNER JOIN on `t1.c1 = t2.c1 AND t1.c2 > t2.c2`, with /// `batch_size = 8192`: @@ -323,9 +323,12 @@ impl BatchedJoinProcessor { /// 2. Evaluate the residual filter `t1.c2 > t2.c2`; suppose only 100 pairs pass. /// 3. Materialize those 100 pairs in the final output schema and return the batch. /// - /// For non-inner joins, matched rows will be tracked for final output. + /// Left and full joins record the surviving build rows for the final unmatched + /// output. Right and full joins also emit the probe rows this chunk proves + /// unmatched. /// - /// For small output batches, the caller will coalesce them for final output. + /// Returns an empty batch when no row survives, and `None` once the current + /// probe batch is drained. The caller coalesces small batches. fn probe_chunk(&mut self) -> Result> { let Some(probe) = &mut self.probe else { return Ok(None); From 2f6a7979baeac8fe4c86dc2ce5497f136fcc78f3 Mon Sep 17 00:00:00 2001 From: Yongting You <2010youy01@gmail.com> Date: Wed, 18 Nov 2026 16:16:12 +0800 Subject: [PATCH 7/9] Update datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs Co-authored-by: Matt Butrovich --- .../src/joins/hash_join/batched_join_processor.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs b/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs index 47fb902e63152..e0e9b3836f1c5 100644 --- a/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs +++ b/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs @@ -389,7 +389,9 @@ impl BatchedJoinProcessor { } }; - // Update metrics `probe_hit_rate` and `avg_fanout`` + // Pairs are ordered by probe row. A probe row whose matches span a chunk + // boundary is the last row of the previous chunk and the first row of this + // one, so `probe_hit_rate` and `avg_fanout` count it only once. let mut matched_probe_rows = count_distinct_sorted_indices(&probe_indices); if let (Some(&first), Some(&last)) = ( probe_indices.values().first(), From 3f417b8349ef05b9e62b7f97fef616544361f2f9 Mon Sep 17 00:00:00 2001 From: Yongting You <2010youy01@gmail.com> Date: Wed, 18 Nov 2026 15:07:50 +0800 Subject: [PATCH 8/9] review: test for limit pushed in HJ --- .../test_files/join_limit_pushdown.slt | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/datafusion/sqllogictest/test_files/join_limit_pushdown.slt b/datafusion/sqllogictest/test_files/join_limit_pushdown.slt index d34f7d5b6ad21..33781b5c5727b 100644 --- a/datafusion/sqllogictest/test_files/join_limit_pushdown.slt +++ b/datafusion/sqllogictest/test_files/join_limit_pushdown.slt @@ -52,6 +52,29 @@ SELECT t1.a, t2.x FROM t1 INNER JOIN t2 ON t1.a = t2.x LIMIT 2; 1 1 2 2 +# Ensure limit pushed into HJ stops execution early +statement ok +set datafusion.execution.batch_size = 2; + +statement ok +set datafusion.explain.analyze_categories = 'rows'; + +# After probing the first input batch, HJ would satisfy the limit requirements. +# Ensure no further probing by checking `input_batches` metrics. +query TT +EXPLAIN ANALYZE SELECT t1.a, t2.x FROM t1 INNER JOIN t2 ON t1.a = t2.x LIMIT 2; +---- +Plan with Metrics +01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(a@0, x@0)], fetch=2, metrics=[input_batches=1, input_rows=2] +02)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] +03)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] + +statement ok +reset datafusion.execution.batch_size; + +statement ok +reset datafusion.explain.analyze_categories; + # Right join is converted to Left join with projection - fetch pushdown is supported query TT EXPLAIN SELECT t1.a, t2.x FROM t1 RIGHT JOIN t2 ON t1.a = t2.x LIMIT 3; From 804c9ed74a6e988e024fc195ede0b59a8c90eea1 Mon Sep 17 00:00:00 2001 From: Yongting You <2010youy01@gmail.com> Date: Wed, 18 Nov 2026 15:21:03 +0800 Subject: [PATCH 9/9] review: refactor status comment at stream.rs --- .../physical-plan/src/joins/hash_join/stream.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/datafusion/physical-plan/src/joins/hash_join/stream.rs b/datafusion/physical-plan/src/joins/hash_join/stream.rs index 80cc3251c651e..390492fc00bd7 100644 --- a/datafusion/physical-plan/src/joins/hash_join/stream.rs +++ b/datafusion/physical-plan/src/joins/hash_join/stream.rs @@ -6,6 +6,20 @@ //! //! This module implements [`HashJoinStream`], the streaming engine for //! [`super::HashJoinExec`]. See comments in [`HashJoinStream`] for more details. +//! +//! # Ongoing Hash Join refactor +//! +//! Hash join execution is being incrementally split into dedicated regular and +//! existence join streams; see [#26361](https://github.com/apache/datafusion/issues/26361). +//! +//! Inner, left, right, and full joins use this stream only when +//! `datafusion.execution.enable_migration_hash_join = false`. Implement changes +//! for these join types in [`BatchedJoinProcessor`], the default path, and keep +//! this legacy fallback consistent. +//! +//! Semi, anti, mark, and null-aware joins still use this stream by default. +//! +//! [`BatchedJoinProcessor`]: super::batched_join_processor::BatchedJoinProcessor use std::sync::Arc; use std::task::Poll;