Repository navigation
refactor: Rewrite Hash Join's regular (inner/left/right/full) join path - #27399
Conversation
|
|
||
| /// Immutable build buffers and their durable reservation. | ||
| struct JoinBuildData { | ||
| pub(super) struct JoinBuildData { |
There was a problem hiding this comment.
Some notes about structs related to build-side data, as this PR introduces extra complexity on this part:
The final shape split left-side data into RegularJoinLeftData and ExistenceJoinLeftData, with JoinBuildData as the common inner part. (better to split since some fields are only specific to one path)
This PR only migrates regular joins, requiring temporary indirection:
CollectedBuild → RegularJoinLeftData / JoinLeftData
After migration, we can remove CollectedBuild and replace legacy JoinLeftData with ExistenceJoinLeftData to keep it simple.
| /// completion to the processor. | ||
| /// - `Outputting -> end`: Buffered output and any final unmatched build rows | ||
| /// have been emitted. | ||
| pub(super) fn into_stream(self) -> SendableRecordBatchStream { |
There was a problem hiding this comment.
This is the execution entry point.
| /// next_output_batch() -> Output([(1, NULL)]) | ||
| /// next_output_batch() -> Finished // All output from this processor is drained. | ||
| /// ``` | ||
| pub(super) struct BatchedJoinProcessor { |
There was a problem hiding this comment.
This is the key struct that establishes a layer inside HJ.
7c30bde to
b93c3dd
Compare
|
This PR replaces #26227. The main difference is that it is now step 1 toward a concrete optimization, rather than just preparing for future optimizations (see rationale for details). I hope this can make the review easier. CC reviewers in the origin PR: @jayzhan211 @mbutrovich @andygrove |
jayzhan211
left a comment
There was a problem hiding this comment.
@2010YOUY01 thanks for splitting this out! The new path returned the same rows as the legacy one on everything I tried: the join fuzz tests, the join .slt files under both flag values, and about 1,300 extra queries covering all four join types, residual filters, IS NOT DISTINCT FROM, dictionary keys, empty inputs, both partition modes, batch sizes 1/2/8192 and LIMIT.
The one change I'd ask for before merging is the probe-hit counting loop (inline), which makes hj Q24 and Q26 6-12% slower. The other comments are optional.
| // 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); | ||
| } | ||
| } |
There was a problem hiding this comment.
This loop makes the new path slower than the legacy one on hj (sf1, same binary, toggling enable_migration_hash_join): Q24 is 1.06x and Q26 is 1.12x, while Q17, which the flag doesn't touch, stays at 1.01x. A profile puts the extra time here: the field is read and written through &mut on every row. The legacy path's count_distinct_sorted_indices plus a first/last boundary fix brings Q24 to 1.00x and Q26 to 1.04x, and join_probe_metrics_count_each_probe_row_once still passes. This also needs count_distinct_sorted_indices in stream.rs made pub(super) and imported here.
| // 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); | |
| } | |
| } | |
| // 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 = 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); | |
| } |
Per-query numbers (new/legacy, median of 60 runs)
| query | PR | with this change |
|---|---|---|
| Q24 single hot bucket, string key | 1.063 | 1.000 |
| Q26 Partitioned, dense keys | 1.119 | 1.040 |
| Q9 | 0.995 | 1.019 |
| Q13 | 0.964 | 0.953 |
| Q17 RightSemi (control) | 1.007 | 1.021 |
There was a problem hiding this comment.
Good catch, addressed in 282a10f
I'll validate the full benchmark result later.
| if self.output.push_batch(batch)? == PushBatchStatus::LimitReached { | ||
| self.release_probe(); | ||
| self.phase = Phase::DrainingOutput; | ||
| } |
There was a problem hiding this comment.
Optional: no test covers this early stop. If release_probe() and the move to DrainingOutput are removed, every test still passes, but the join reads the whole probe input after fetch rows. The test below makes the second probe batch an error, so it fails without the early stop for all four join types.
Test for exec.rs tests module
/// Reaching `fetch` stops reading the probe side: the second probe batch
/// is an error that must never be polled.
#[rstest]
#[tokio::test]
async fn join_fetch_stops_reading_probe(
#[values(JoinType::Inner, JoinType::Left, JoinType::Right, JoinType::Full)]
join_type: JoinType,
) -> Result<()> {
let left = build_table(
("a1", &vec![1, 2, 3]),
("b1", &vec![1, 2, 3]),
("c1", &vec![7, 8, 9]),
);
let right_batch = build_table_i32(
("a2", &vec![1, 2, 3]),
("b1", &vec![1, 2, 3]),
("c2", &vec![4, 5, 6]),
);
let right_schema = right_batch.schema();
let on = vec![(
Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
Arc::new(Column::new_with_schema("b1", &right_schema)?) as _,
)];
let right: Arc<dyn ExecutionPlan> = Arc::new(
MockExec::new(
vec![Ok(right_batch), exec_err!("probe read after fetch")],
right_schema,
)
.with_use_task(false)
.with_unknown_statistics(),
);
let join = HashJoinExecBuilder::new(left, right, on, join_type)
.with_partition_mode(PartitionMode::CollectLeft)
.with_fetch(Some(2))
.build()?;
let batches =
common::collect(join.execute(0, prepare_task_ctx(8192, false))?).await?;
assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 2);
Ok(())
}There was a problem hiding this comment.
This is a mutation testing failure: removing two lines of execution code should cause a test to fail, but all tests still pass.
I feel that adding a test specifically for this case would be a bit overfitted and hard to maintain, so I'd prefer to skip it. Perhaps we could improve our fuzzers to make similar cases covered instead 🤔
There was a problem hiding this comment.
Perhaps we could improve our fuzzers to make similar cases covered instead
A fuzzer that compares outputs can't catch this one. Without the early stop, the join still returns exactly fetch rows, because LimitedBatchCoalescer::push_batch drops everything pushed after the limit. The only difference is that the probe input keeps getting read to the end, and that doesn't show up in any output. join_fuzz.rs also never sets fetch.
The test @jayzhan211 posted checks the operator's contract through its public API: once fetch rows are out, the probe input is never polled again. It doesn't touch BatchedJoinProcessor internals, so it should survive #27401 unchanged. Could we add it? Without it, losing the early stop in a later refactor would make every LIMIT over a hash join read its whole probe side, and no test would notice.
There was a problem hiding this comment.
You're right, I was thinking of it as something else.
In 3f417b8, I've implemented the same test goal with slt -- removing those two lines will fail the added slt test case
| 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 | ||
| }; |
There was a problem hiding this comment.
Optional cleanup: if this uses the consumer's config for prepared builds too, enable_migration_hash_join = false also works as the bug workaround for prepared consumers. Today a long-lived prepared build keeps whichever path was set at preparation. Both left-data constructors only borrow the same Arc<JoinBuildData>, so nothing depends on the choice being made at preparation. This removes PreparedHashJoinBuild::regular, is_regular, and the doc lines about it, and all join tests pass with the flag's default set to either value.
- 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
- };
+ }
+ let use_regular = context
+ .session_config()
+ .options()
+ .execution
+ .enable_migration_hash_join;There was a problem hiding this comment.
Today a long-lived prepared build keeps whichever path was set at preparation.
This choice is also written into public docs. The PreparedHashJoinBuild docs and the prepare_build rustdoc now say that preparation picks the executor for every consumer, whatever the consumer's enable_migration_hash_join is. That makes a temporary option part of the contract of a public type and method, and both paragraphs have to change again when the option is removed. Reading the flag in execute keeps the option out of the prepared-build API, so I'd make this change in this PR.
There was a problem hiding this comment.
Good point, fixed in ef96c9b
It ensured prepared build is compatible regardless of enable_migration_hash_join is true/false, and added a unit test for it.
| return plan_err!( | ||
| "PartitionMode::Auto must be resolved before execution" | ||
| ); |
There was a problem hiding this comment.
Optional: the legacy branch below reports this case as "Invalid HashJoinExec, unsupported PartitionMode Auto in execute()". Using the same message keeps the error independent of the migration flag.
| return plan_err!( | |
| "PartitionMode::Auto must be resolved before execution" | |
| ); | |
| return plan_err!( | |
| "Invalid HashJoinExec, unsupported PartitionMode {:?} in execute()", | |
| PartitionMode::Auto | |
| ); |
mbutrovich
left a comment
There was a problem hiding this comment.
@2010YOUY01 thanks for reworking this as step 1 of #27398. I traced the new path against the legacy HashJoinStream (unmatched build emission, right/full alignment across chunks, the dynamic filter report, and the empty-map cases) and found it equivalent. Breaking the last-partition check in RegularJoinLeftData::finish_probe or the last_probe_row_with_on_match update makes existing exec.rs tests fail, so those paths are covered.
| /// the migration is complete. | ||
| /// | ||
| /// See <https://github.com/apache/datafusion/issues/26361> for details. | ||
| pub enable_migration_hash_join: bool, default = true |
There was a problem hiding this comment.
This adds a user-facing config option, datafusion.execution.enable_migration_hash_join, which shows up in information_schema.df_settings, SHOW ALL, and configs.md. The PR description answers "Are there any user-facing changes?" with "No". Could you list the option there, with its default and the plan to remove it? The description becomes the squash commit message, so that's where users will look for it.
There was a problem hiding this comment.
👍🏼 Updated the PR description.
| PartitionMode::Auto => { | ||
| unreachable!("PartitionMode::Auto must be resolved before execution") | ||
| } |
There was a problem hiding this comment.
prepare already returns Result, so this invariant violation can be an internal error instead of a panic. execute rejects Auto before it builds a HashJoinBuild today, and an error keeps a future caller that skips that check from bringing down the process. This also needs internal_err added to the datafusion_common import on line 15.
| PartitionMode::Auto => { | |
| unreachable!("PartitionMode::Auto must be resolved before execution") | |
| } | |
| PartitionMode::Auto => { | |
| return internal_err!( | |
| "PartitionMode::Auto must be resolved before execution" | |
| ); | |
| } |
|
run benchmark tpch10 hj tpcds |
|
@jayzhan211 and @mbutrovich Thank you for the review! I've addressed all the existing comments. Next, I'll rerun and verify the benchmark. |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing refactor-hj-regular-stream (ef96c9b) to 1200494 (merge-base) diff Run configurationrun benchmark tpch10Results will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing refactor-hj-regular-stream (ef96c9b) to 1200494 (merge-base) diff Run configurationrun benchmark hjResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing refactor-hj-regular-stream (ef96c9b) to 1200494 (merge-base) diff Run configurationrun benchmark tpcdsResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing refactor-hj-regular-stream (ef96c9b) to 1200494 (merge-base) diff Run configurationrun benchmark tpch10CPU Details (lscpu)Details
Resource Usagetpch10 — base (merge-base)
tpch10 — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing refactor-hj-regular-stream (ef96c9b) to 1200494 (merge-base) diff Run configurationrun benchmark hjCPU Details (lscpu)Details
Resource Usagehj — base (merge-base)
hj — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing refactor-hj-regular-stream (ef96c9b) to 1200494 (merge-base) diff Run configurationrun benchmark tpcdsCPU Details (lscpu)Details
Resource Usagetpcds — base (merge-base)
tpcds — branch
File an issue against this benchmark runner |
mbutrovich
left a comment
There was a problem hiding this comment.
@2010YOUY01 thanks for the quick turnaround on the earlier comments.
Could we add a notice to the stream.rs module doc? It should say that inner, left, right, and full joins reach HashJoinStream only with enable_migration_hash_join = false, and that changes for those join types belong in BatchedJoinProcessor. Semi, anti, mark, and null-aware joins still run there by default, so the notice can't cover the whole stream the way the # Deprecation section in grouped_hash_stream.rs does for aggregates. #27228 shows the risk. It adds the Left and Right single-join check to HashJoinStream, so after this PR that check would run only with the flag off, and the default path would return duplicate rows instead of the error. Whichever of the two lands second has to add the check to the new path or route single joins to the legacy stream.
|
I ran property-based tests from arrow-pbt (mbutrovich/arrow-pbt#5) against this PR at dbc4514, with arrow-rs That test runs the same The cases cover every join type, both The comparison with the nested loop join also discarded 175 cases on three open arrow-rs bugs that the joins' non-key columns reach: apache/arrow-rs#11607, apache/arrow-rs#10925, and apache/arrow-rs#11835. In the To rerun it, check out the ARROW_PBT_SEEDS=1-6 ARROW_PBT_CASES=1000 cargo test -p arrow-pbt-datafusion --test joins |
…essor.rs Co-authored-by: Matt Butrovich <mbutrovich@users.noreply.github.com>
…essor.rs Co-authored-by: Matt Butrovich <mbutrovich@users.noreply.github.com>
I've updated the comments in 804c9ed |
mbutrovich
left a comment
There was a problem hiding this comment.
@2010YOUY01 thanks for working through both rounds. This LGTM!
|
@jayzhan211 @mbutrovich Thanks again |
Which issue does this PR close?
Step 1 toward:
Part of:
HashJoinExecby splitting regular/existence join into dedicated streams #26361Rationale for this change
This PR is step 1 of #27398, a structural cleanup of Hash Join to prepare for #27401 (physical HT redesign, with 8 queries in the
hjbenchmark achieving >3x speedups).The goal is to make Hash Join easier to understand, review, and optimize. This PR focuses on the execution structure without changing the physical hash table representation.
Why the cleanup?
The existing Hash Join implementation has two major architectural issues:
Regular and existence joins share the same execution path. It's better to split them to support logic/optimizations specific to each.
Everything is mixed into one layer. Low-level physical operations are mixed with high-level execution control flow. This makes PRs hard to review: even a change that only touches one layer can appear to be a deep architectural change.
The ideal design has three layers (see #27398):
This PR establishes the first two layers. The
JoinIndexMapabstraction and physical redesign are deferred to #27401.For deeper rationale, see:
What changes are included in this PR?
There are only two key points to understand this PR:
Split out the regular Hash Join execution path (Inner/Left/Right/Full joins).
Establish
BatchedJoinProcessoras the main execution layer.Suggested review order
It's easier to read the diff in this order:
Migration configuration:
enable_migration_hash_join. Whentrue, regular joins use the new path; otherwise, they use the existing implementation. Existence joins always use the existing path. The option defaults totrue, since the new path covers the existing regular-join functionality.It's planned to keep it for just one release to guard against major bugs, as we did in #22710.
Execution state machine:
datafusion/physical-plan/src/joins/hash_join/regular_join.rs. Start withRegularHashJoinStream::into_stream, which is the entry point for the entire execution.Main execution layer:
datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs. Start with the documentation onBatchedJoinProcessor, which explains its responsibilities and input/output contract with a concrete example....and follow along.
What is the testing strategy for this PR?
Existing tests are reused. Major join fuzz tests are exercised with both
enable_migration_hash_join=trueandenable_migration_hash_join=falseto cover the new and legacy implementations during migration.Are there any user-facing changes?
This PR adds
datafusion.execution.enable_migration_hash_join(default:true). It enables the refactored implementation for inner, left, right, and full hash joins. Setting it tofalserestores the legacy implementation as a temporary workaround for bugs.See issue for details: #26361
The option and legacy fallback will be removed once the migration is complete; the current plan is to retain them for one release.