perf: sort-merge join (SMJ) batch deferred filtering and move mark joins to bitwise stream. Near-unique LEFT and FULL SMJ 20-50x faster#21184
Conversation
|
run benchmarks sort_merge_join |
Note that the 2 queries I expect a speedup on in the |
|
🤖 Criterion benchmark running (GKE) | trigger File an issue against this benchmark runner |
|
Benchmark for this request failed. Last 20 lines of output: Click to expandFile an issue against this benchmark runner |
|
Also I'm now confused where I should add benchmarks. #20464 added Criterion SMJ benchmarks for sort-merge join , but it's missing scenarios from dfbench's |
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123. --> - Closes #. ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> Our SMJ benchmark queries finish too quickly to demonstrate improvements that aren't massive. For example, I am working on an optimization that introduces `DynComparator` (part of #20910) and it's about a 10% improvement, but only when you actually make the queries run long enough. The new queries for #21184 are scaled enough to see improvements, but we need to scale the older queries. I am also continuing to see SMJ issues with Comet when running joins with billions (sometimes trillions) of rows. We can't do that for microbenchmarks, but we can at least start hitting millions of rows to look at more than a handful of batches. ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> Bring our SMJ queries into alignment with some of the newer ones (Q21-23) to demonstrate further performance wins. ## Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> I ran the benchmark. On my M3 Max, here's how long it takes: | Query | Join Type | Rows | Keys | Filter | Median (ms) | |-------|-----------|------|------|--------|-------------| | Q1 | INNER | 1M×1M | 1:1 | — | 16.3 | | Q2 | INNER | 1M×10M | 1:10 | — | 117.4 | | Q3 | INNER | 1M×1M | 1:100 | — | 74.2 | | Q4 | INNER | 1M×10M | 1:10 | 1% | 17.1 | | Q5 | INNER | 1M×1M | 1:100 | 10% | 18.4 | | Q6 | LEFT | 1M×10M | 1:10 | — | 129.3 | | Q7 | LEFT | 1M×10M | 1:10 | 50% | 150.2 | | Q8 | FULL | 1M×1M | 1:10 | — | 16.6 | | Q9 | FULL | 1M×10M | 1:10 | 10% | 153.5 | | Q10 | LEFT SEMI | 1M×10M | 1:10 | — | 53.1 | | Q11 | LEFT SEMI | 1M×10M | 1:10 | 1% | 15.5 | | Q12 | LEFT SEMI | 1M×10M | 1:10 | 50% | 65.0 | | Q13 | LEFT SEMI | 1M×10M | 1:10 | 90% | 105.7 | | Q14 | LEFT ANTI | 1M×10M | 1:10 | — | 54.3 | | Q15 | LEFT ANTI | 1M×10M | 1:10 | partial | 51.5 | | Q16 | LEFT ANTI | 1M×1M | 1:1 | — | 10.3 | | Q17 | INNER | 1M×50M | 1:50 | 5% | 75.9 | | Q18 | LEFT SEMI | 1M×50M | 1:50 | 2% | 50.2 | | Q19 | LEFT ANTI | 1M×50M | 1:50 | partial | 336.4 | | Q20 | INNER | 1M×10M | 1:100 | GROUP BY | 763.7 | | Q21 | INNER | 10M×10M | 1:1 | 50% | 186.1 | | Q22 | LEFT | 10M×10M | 1:1 | 50% | 10,193.8 | | Q23 | FULL | 10M×10M | 1:1 | 50% | 10,194.7 | Note that Q22 and Q23 will be about 20x faster when #21184 merges, so taking 10 seconds to run is just a short-term issue. ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> <!-- If there are any breaking changes to public APIs, please add the `api change` label. --> No.
|
run benchmark smj |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing simplify_smj_full_opt (768529e) to 37c1b75 (merge-base) diff using: smj File an issue against this benchmark runner |
|
run benchmarks |
|
🤖 Benchmark completed (GKE) | trigger Instance: CPU Details (lscpu)Details
Resource Usagesmj — base (merge-base)
smj — branch
File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing simplify_smj_full_opt (768529e) to 37c1b75 (merge-base) diff using: clickbench_partitioned File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing simplify_smj_full_opt (768529e) to 37c1b75 (merge-base) diff using: tpcds File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing simplify_smj_full_opt (768529e) to 37c1b75 (merge-base) diff using: tpch File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: CPU Details (lscpu)Details
Resource Usagetpch — base (merge-base)
tpch — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: CPU Details (lscpu)Details
Resource Usageclickbench_partitioned — base (merge-base)
clickbench_partitioned — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: CPU Details (lscpu)Details
Resource Usagetpcds — base (merge-base)
tpcds — branch
File an issue against this benchmark runner |
| ), | ||
| ]; | ||
|
|
||
| for batch_size in [2, 49, 100] { |
There was a problem hiding this comment.
can we use already existing set of batch sizes like in other tests?
batch_sizes: &[1, 2, 7, 49, 50, 51, 100],
There was a problem hiding this comment.
The spill test is a bit slow already (it added about 20 seconds to what was already ~90 second test) because it's running with a memory limit and disk spilling across multiple join types and extra-column combos. The smaller set was chosen intentionally to keep the test run time reasonable. The spill test combinatorics (3 join types * 3 extra-column combos * N batch sizes) make the full set expensive, and these three cover small/medium/boundary cases. I can add them if we don't think these fuzz tests will become too expensive.
datafusion/physical-plan/src/joins/semi_anti_mark_sort_merge_join/stream.rs
Outdated
Show resolved
Hide resolved
datafusion/physical-plan/src/joins/semi_anti_mark_sort_merge_join/stream.rs
Outdated
Show resolved
Hide resolved
…emiAntiMark) into the same SMJ folder.
| /// Calculated as sum of peak memory values across partitions | ||
| peak_mem_used: Gauge, | ||
| /// Metrics related to spilling | ||
| spill_metrics: SpillMetrics, |
There was a problem hiding this comment.
Moved SpillMetrics construction from SortMergeJoinMetrics into exec.rs where the SpillManager is now built (shared across both streams). The metrics are still registered into the same ExecutionPlanMetricsSet and reported via metrics() — just constructed in a different place.
comphead
left a comment
There was a problem hiding this comment.
Thanks @mbutrovich numbers looks great, lets wait some time if anyone wants to take a look as well
Which issue does this PR close?
Partially addresses #20910. Fixes #21197.
Rationale for this change
Sort-merge join with a filter on outer joins (LEFT/RIGHT/FULL) runs
process_filtered_batches()on every key transition in the Init state. With near-unique keys (1:1 cardinality), this means running the full deferred filtering pipeline (concat +get_corrected_filter_mask+filter_record_batch_by_join_type) once per row — making filtered LEFT/RIGHT/FULL 55x slower than INNER for 10M unique keys.Additionally, mark join logic in
MaterializingSortMergeJoinStreammaterializes full(streamed, buffered)pairs only to discard most of them viaget_corrected_filter_mask(). Mark joins are structurally identical to semi joins (one output row per outer row with a boolean result) and belong inBitwiseSortMergeJoinStream, which avoids pair materialization entirely using a per-outer-batch bitset.What changes are included in this PR?
Three areas of improvement, building on the specialized semi/anti stream from #20806:
1. Move mark joins to
BitwiseSortMergeJoinStreamemit_outer_batch()emits all rows with the match bitset as a boolean column (vs semi's filter / anti's invert-and-filter)LeftMark/RightMarkfromSortMergeJoinExec::execute()to the bitwise streamMaterializingSortMergeJoinStream(mark_row_as_match,is_not_nullcolumn generation, mark arms in filter correction)2. Batch filter evaluation in
freeze_streamed()freeze_streamed()into null-joined classification +freeze_streamed_matched()for batched materializationslice→take→interleave)RecordBatchconstruction and singleexpression.evaluate()per freeze instead of per chunkappend_filter_metadata()using builderextend()instead of per-element loop3. Batch deferred filtering in Init state (this is the big win for Q22 and Q23)
process_filtered_batches()on accumulated rows >=batch_sizeinstead of running on every Init entryfreeze_dequeuing_buffered, one accumulating toward next freeze) — does not reintroduce unbounded buffering fixed by PR fix: SortMergeJoin don't wait for all input before emitting #20482Exhaustedstate flushes any remainderCleanup:
SortMergeJoinStream→MaterializingSortMergeJoinStream(materializes explicit row pairs for join output) andSemiAntiMarkSortMergeJoinStream→BitwiseSortMergeJoinStream(tracks matches via boolean bitset)semi_anti_mark_sort_merge_join/intosort_merge_join/asbitwise_stream.rs/bitwise_tests.rs; renamestream.rs→materializing_stream.rsandtests.rs→materializing_tests.rsSpillManagerconstruction intoSortMergeJoinExec::execute()(shared across both streams); movepeak_mem_usedgauge intoBitwiseSortMergeJoinStream::try_newMaterializingSortMergeJoinStreamnow handles only Inner/Left/Right/Full — all semi/anti/mark branching removedget_corrected_filter_mask(): merge identical Left/Right/Full branches; add null-metadata passthrough for already-null-joined rowsfilter_record_batch_by_join_type(): rewrite fromfilter(true) + filter(false) + concattozip()for in-place null-joining — preserves row ordering and removescreate_null_joined_batch()entirely; add early return for empty batchesfilter_record_batch_by_join_type(): usecompute::filter()directly onBooleanArrayinstead of wrapping in temporaryRecordBatchBenchmarks
cargo run --release --bin dfbench -- smjGeneral workload (Q1-Q20, various join types/cardinalities/selectivities): no regressions.
Are these changes tested?
In addition to existing unit and sqllogictests:
cargo test -p datafusion --features extended_tests --test fuzz -- join_fuzzLeftSemi) that use this streamAre there any user-facing changes?
No.