Skip to content

Add opt-in runtime build-side selection to partitioned HashJoinExec - #232

Draft
aman-ddog wants to merge 2 commits into
den-55from
aman/adaptive-hash-join-build-side
Draft

aman-ddog wants to merge 2 commits into
den-55from
aman/adaptive-hash-join-build-side

Conversation

@aman-ddog

@aman-ddog aman-ddog commented Dec 1, 2026 •

Copy link
Copy Markdown

Why

A hash join loads one input (the build side) fully into memory and streams the other (the probe side) through it. JoinSelection picks the build side at planning time from input statistics. Those statistics are row counts from before filters run. A heavily filtered join can therefore choose a very large input as the build side, while the other input yields only a small amount of data at runtime. The build side then exhausts the memory pool and the query fails with an out-of-memory error on HashJoinInput. More planner rules that pattern-match these query shapes would be fragile, because the planner still cannot see post-filter sizes.

After this change, an opt-in setting lets an eligible partitioned hash join measure both inputs at runtime before building. If the planned build side is too large and the planned probe side turns out small, the join swaps roles in-stream and builds the small side. Query results and the output schema are unchanged. With the setting off, hash joins behave exactly as before.

What changed

  • One new execution setting.

    • datafusion.execution.hash_join_adaptive_build_side_threshold_bytes (default 0, which turns the feature off). It is the byte budget for each side's sample, summed across all partitions of the join. It is session-level and can be changed with SET.
  • Only a narrow, safe set of joins is eligible.

    • The join must use PartitionMode::Partitioned and have dynamic filter pushdown enabled. This guarantees a shared build accumulator exists (the object that collects every partition's build result into one dynamic filter).
    • Both inputs must be bounded. The join must have no fetch limit, no required output ordering, no null-aware anti semantics (NOT IN), and no probe-side buffering (hash_join_buffering_capacity = 0). join_reordering must be enabled.
    • Supported join types are Inner, Left, LeftSemi, RightSemi, and LeftAnti. Every other join takes the existing path and reports no adaptive metrics.
  • All partitions of a join decide together.

    • A per-join coordinator (AdaptiveBuildCoordinator) moves through four phases: SampleLeft → ReleasingFilter → SampleRight → Decided.
    • SampleLeft: every partition buffers the planned left (build) side. The right side is not read. If the whole left side fits within the threshold, the join builds it as usual (left_small).
    • SampleRight: if the left side crosses the threshold, every partition samples the right side. The join swaps only when every partition's right side ends within the threshold. If the right side also crosses the threshold (right_crossed), errors (right_error), or a partition is dropped (abandoned), the join keeps the left side.
    • Besides bytes, each side's sample is capped at 64 batches and 64 × batch_size rows per partition (summed join-wide), so tiny or zero-byte batches cannot hold the decision open.
    • Sampled batches are charged to the memory pool as they are buffered. When a buffered prefix is replayed, its full reservation is held until the last buffered batch is emitted, because sliced batches can share buffers.
  • The dynamic filter is released before the right side is read.

    • The right side can itself be waiting on this join's dynamic filter (for example, a scan or nested join that blocks on wait_complete()). Reading it before that filter exists could deadlock.
    • So when the left side first crosses the threshold, the coordinator enters ReleasingFilter. One partition marks every pending accumulator slot as canceled and waits until this join's dynamic filter is final as a pass-through true. Only then is SampleRight published.
    • While the filter is being released, the other partitions park. They stop polling and buffering the left side, so they cannot use up a tight memory pool.
    • Partitions that start after the release run the stock path, detached from the accumulator, so nothing competes to finalize the filter again.
    • This makes the deadlock impossible by construction, with no timer and no dependence on scheduling.
  • Fix a lost-wakeup race in DynamicFilterPhysicalExpr.

    • wait_complete() checked is_complete, then subscribed to the watch channel. A mark_complete() call between those two steps was missed, and the waiter could hang. It now re-checks is_complete after subscribing.
    • update() and mark_complete() now publish with send_replace while holding the write lock. The channel always keeps the latest state, even with zero receivers, and a later update() cannot move a completed filter back to in-progress.
  • The swap happens inside the join stream.

    • The sampled right side becomes the hash table. The buffered left prefix, followed by the rest of the left input, becomes the probe stream.
    • The stream swaps the join type (for example Left becomes Right) and the join filter. It also flips the side recorded for each output column, so output columns keep their planned order and no ProjectionExec is added.
    • When the left side fits, nothing is swapped. The dynamic filter is built and pushed to the right-side scan exactly as today, before that scan is first polled.
  • New metrics (shown in EXPLAIN ANALYZE).

    • Per partition: adaptive_build_swapped, adaptive_right_sampled, adaptive_sampled_left_bytes, adaptive_sampled_right_bytes, and adaptive_sample_poll_time (time spent polling the sampler, excluding time parked between polls).
    • Per join, recorded once: adaptive_decision_wall_time (from the first partition starting to the decision) and adaptive_decision_reason_* with reasons swap_right, left_small, right_crossed, right_error, abandoned, and duplicate (the same partition was executed twice).
  • Tests.

    • DynamicFilterPhysicalExpr: completion with zero receivers is kept in the watch channel, and a two-thread race between mark_complete() and wait_complete() never hangs.
    • Coordinator unit tests: each phase transition, the batch and row caps, every slot discharged before SampleRight is published, waiting for a competing finalizer, and an abandon during the release not being overwritten.
    • End-to-end tests compare results with the stock join for all five supported join types. They cover slow right sides, right sides that wait on this join's dynamic filter, projections, residual filters, empty and all-NULL inputs, and perfect-hash (array map) builds.
    • Adversarial tests cover a 62-partition join that runs out of memory without this change and succeeds with it, a skewed hot partition, peers parking under a tight memory pool, a peer dropped during the release, synchronous child execute() errors, errors in each phase, the decision wall-time metric being recorded once, and every ineligible configuration.
  • Diff breakdown (~74% tests).

    • Production code: +1,632 / -152 lines (25.9% of additions).
    • Tests and snapshots: +4,669 / -1 lines (74.1% of additions).
    • Docs: +1 line.

Scope, rollout & caveats

  • Off by default.
    • With the threshold at 0, merging this changes nothing until a session enables it.
  • When both sides exceed the threshold, this join loses its own filter pushdown.
    • The filter is released before the right side is sampled. If the right side also crosses the threshold, the join keeps the planned left side, but the rest of the probe scan runs with this join's dynamic filter set to true, not the exact hash-table filter it would build today. Results are identical; only the pruning is lost.
    • Joins whose left side fits never release the filter and keep today's pushdown unchanged.
    • A possible follow-up is to split "don't wait on me" from "final forever" in DynamicFilterPhysicalExpr. Waiters could then be unblocked during sampling, and the real filter could still be pushed later.
  • Inputs must be independent.
    • The left and right inputs must not block on each other through anything other than this join's dynamic filter. Standard relational SQL plans meet this.
  • Bounded extra cost.
    • The join can buffer up to the threshold from each side before building.
  • Out of scope.
    • Right, RightAnti, Full, LeftMark, and RightMark joins, and CollectLeft joins.
    • Distributed execution: each worker decides from the partitions it runs. This needs validation before the feature is turned on by default.
Verification
  • cargo fmt --all -- --check: passed (0 diffs).
  • cargo clippy -p datafusion-common -p datafusion-physical-expr -p datafusion-physical-plan --all-targets -- -D warnings: passed (0 warnings).
  • cargo test -p datafusion-common --lib config::: 14/14 passed.
  • cargo test -p datafusion-physical-expr --lib dynamic_filters: 24/24 passed.
  • cargo test -p datafusion-physical-plan --lib joins::: 1,071/1,071 passed, including all 38 adaptive tests.
  • datafusion-sqllogictest (information_schema.slt) and the extended workspace / full-feature clippy suites: CI only (not run locally).

@codecov-commenter

codecov-commenter commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.21669% with 79 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.34%. Comparing base (ce3d32c) to head (fa7abd8).

Files with missing lines Patch % Lines
...fusion/physical-plan/src/joins/hash_join/stream.rs 89.02% 16 Missing and 11 partials ⚠️
...sion/physical-plan/src/joins/hash_join/adaptive.rs 96.68% 8 Missing and 17 partials ⚠️
...tafusion/physical-plan/src/joins/hash_join/exec.rs 93.60% 5 Missing and 9 partials ⚠️
...physical-plan/src/joins/hash_join/shared_bounds.rs 85.71% 4 Missing and 8 partials ⚠️
...ysical-expr/src/expressions/dynamic_filters/mod.rs 98.38% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           den-55     #232      +/-   ##
==========================================
+ Coverage   81.28%   81.34%   +0.05%     
==========================================
  Files        1111     1112       +1     
  Lines      390523   391774    +1251     
  Branches   390523   391774    +1251     
==========================================
+ Hits       317453   318677    +1224     
+ Misses      54448    54445       -3     
- Partials    18622    18652      +30     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants