andygrove opened a new pull request, #7057:
URL: https://github.com/apache/datafusion-comet/pull/7057

   ## Which issue does this PR close?
   
   Part of #2545. This is a research draft for discussion, not a change to 
merge as it stands.
   
   ## Rationale for this change
   
   Comet's native shuffled hash join is DataFusion's `HashJoinExec`, whose 
build side has to fit in the task's share
   of the memory pool. When it does not, the task fails. That is why 
`spark.comet.exec.forceShuffledHashJoin` is off by
   default and has a build-size guard (#6384), even though a hash join is 
faster than a sort-merge join when it fits.
   
   DataFusion has an open design for spilling hash joins 
(apache/datafusion#24768), but no agreed approach yet. The
   sort-merge fallback (apache/datafusion#25217) is waiting on review, and a 
refactor of the hash join stream is in
   flight. Comet's case is much simpler than DataFusion's general one. Every 
native shuffled hash join runs in
   `Partitioned` mode, on one partition per task, and the output order contract 
lives on the Spark side, not in
   DataFusion's optimizer. This draft explores a Comet-only design for that 
case, to find out what it costs and what
   breaks. Parts of it could be offered upstream later.
   
   ## What changes are included in this PR?
   
   The design is written up in 
`docs/source/contributor-guide/spilling-hash-join-design.md`. In short:
   
   - `SpillingHashJoinExec` (`native/operators/src/spilling_hash_join/`) wraps 
the `HashJoinExec` that Comet already
     plans. An equi-join splits exactly by a hash of its keys, for every join 
type, so each bucket is joined by a stock
     `HashJoinExec`, and the operator implements no join semantics of its own.
     - While the build side fits, it runs that join unchanged.
     - When the memory pool refuses, it routes both sides to 16 buckets, 
destages the largest buckets to disk, joins
       the buckets left in memory with the probe input, and then joins each 
spilled bucket from its files. A bucket
       that does not fit is split on the next bits of the hash. A bucket that 
splitting cannot shrink, because most of
       its rows share one key or have a null key, is joined in chunks, with a 
replay of its probe rows for each chunk.
     - Spill files hold full batches. Routing splits every input batch 16 ways, 
so a file's writer holds its parts,
       reserved, until they make a batch of the session's batch size or 256 KiB.
     - Each spilled bucket has a Bloom filter of its build keys. A probe row 
that the filter rejects matches nothing
       anywhere, so it goes to the join of the buckets left in memory instead 
of to disk.
     - Everything the operator and its inner joins hold is reserved under one 
memory consumer. That includes what
       `HashJoinExec` allocates without reserving it: its concatenated copy of 
the build batches, and its chain of row
       indices. A spilled bucket's build side is read back into one batch, 
which its inner join keeps without a
       copy, so that the bucket needs about its own size in memory. A build 
side with nested, dictionary or view
       columns is read back compacted instead.
   - An inner join whose probe rows match many build rows each switches to a 
DataFusion `SortMergeJoinExec` for the
     rest of its probe input. Such a join loses to a sort-merge join whether or 
not it spills, as TPC-DS q72 shows
     below.
     - At a probe batch boundary with probe input left, it switches when its 
probe rows have matched at least 16
       build rows each, at 20 ns or more a match, and its probe has taken at 
least 4 times as long as its build. It
       reads all three from the inner `HashJoinExec`'s metrics.
     - The operator sorts the build batch's row order by the join keys, in the 
memory that the dropped hash table
       had reserved, and switches only once it has reserved what the sort needs 
beyond that. A `SortExec` sorts the
       rest of the probe input, and spilled pairs after a switch are joined by 
sort-merge joins too.
     - Only inner joins switch, because the other join types keep a record of 
which rows matched.
   - With `spark.comet.exec.forceShuffledHashJoin`, the rewrite now keeps a 
sort-merge join whose sorted output an
     operator above reads, when that operator is not converted itself, instead 
of sorting the hash join's output for
     it. In TPC-DS q95 that sort, of about a billion rows, made the query 45% 
slower than with the sort-merge join.
   - Three configs. `spark.comet.exec.hashJoin.spill.enabled` is on by default, 
so that CI runs the new join.
     `spark.comet.exec.hashJoin.spill.maxBuildBufferBytes` forces spilling, for 
tests.
     `spark.comet.exec.hashJoin.spill.sortMergeFallback.enabled` turns the 
sort-merge fallback off. It applies to the
     key types that `CometSortMergeJoinExec` supports, and an internal config 
makes every join switch, for tests. The
     serde enables spilling only
     for shuffled hash joins that are not null-aware, do not use the join 
runtime filter, and whose output order no
     operator above relies on. `CometExecRule` walks up the plan from each 
shuffled hash join to find that out, and a
     spilling join reports no output order.
   - The Spark plan keeps `CometHashJoinExec`, and the native operator displays 
as the `HashJoinExec` it runs, so plans
     and golden files do not change. New metrics: `spilled_buckets`, 
`split_buckets`, `chunked_buckets`,
     `bloom_filtered_rows`, `budget_overflow_bytes` and `sort_merge_joins`, 
plus the spill metrics.
   - `CometHashJoinMemoryBenchmark` compares Spark's sort-merge join with 
Comet's sort-merge join, its hash join with
     spilling disabled, and its hash join with spilling, across native memory 
budgets. A native benchmark,
     `cargo bench --bench spilling_hash_join`, runs one task's join over 
in-memory batches.
   - User docs for the join and its metrics.
   
   It reviews best commit by commit. The first four commits are the first 
version, the next ones are a second round
   that made spilling cheaper and let more joins spill, and the commits since 
add the sort-merge fallback, merge main,
   lower the fallback's threshold after measuring it at scale factor 100, and 
keep the sort-merge joins that q95's
   semi joins read.
   
   ## Findings so far
   
   `CometHashJoinMemoryBenchmark` joins 4M build rows with 20M probe rows on 
`local[4]`, with a native pool per task
   from 1024 MiB down to 64 MiB. These runs were on an otherwise idle AMD 
7950X3D, pinned to its eight V-cache cores,
   median of three. Before is the first version, after is the second round.
   
   | Inner join, median ms / CPU s | Comet sort-merge join | Hash join, no 
spilling | Before    | After     |
   | ----------------------------- | --------------------- | 
---------------------- | --------- | --------- |
   | 1024 MiB                      | 1051 / 4.4            | 641 / 2.7          
    | 626 / 2.5 | 637 / 2.6 |
   | 192 MiB                       | 1152 / 5.1            | 617 / 2.4          
    | 730 / 3.2 | 707 / 3.2 |
   | 128 MiB                       | 1161 / 5.1            | fails              
    | 864 / 3.8 | 825 / 3.4 |
   | 64 MiB                        | 1152 / 5.2            | fails              
    | 889 / 3.9 | 787 / 3.2 |
   
   - The spilling join completes for every join shape at every budget, 
including where the join without spilling
     fails. The shapes are inner, left, right and full outer, left anti, and an 
inner join with a hot key.
   - When it spills, it is faster than Comet's sort-merge join in both wall 
time and CPU time, at every budget and
     for every join shape. At 64 MiB the second round is 5 to 19% faster than 
the first and spills 38 to 50% fewer
     bytes.
     The first draft's numbers, which showed it no faster, came from a machine 
that another benchmark was also using.
   - While the build side fits, it costs the same as the join without spilling.
   - Reserving honestly moves the spill point. At 192 MiB the join without 
spilling fits, but the spilling join
     spills, mostly because it counts the concatenated copy of the build side 
that `HashJoinExec` makes without
     reserving it.
   - In the native benchmark, a join under a 20 MiB pool takes 24% less time 
than in the first version, mostly from
     writing full batches: spill files held slivers of 512 rows, or 32 once 
split, and every one cost an IPC message
     and an lz4 frame per buffer. Under 10 MiB the first version split every 
bucket again, and the join now takes 84%
     less time, because a spilled bucket's inner join gets one build batch and 
needs half the memory, so no bucket is
     split.
   - The Bloom filters keep 1.4 to 2.3 million of the native benchmark's 5 
million probe rows off disk, where half of
     the probe rows match. A first version with Parquet's split block filter 
cost about 9 ns a lookup and lost
     overall. The one here sets four bits in one 64-bit word.
   - On spill compression: in `CometHashJoinMemoryBenchmark`'s inner join at 64 
MiB, zstd makes the spilling join 14%
     slower than lz4 and spills 39% fewer bytes, and uncompressed files make it 
4% faster and spill twice as many. The
     join uses `spark.comet.exec.spill.compression.codec`, the setting it 
shares with sorts and aggregates, and which
     is best depends on the disks.
   - Two DataFusion facts came up along the way. A batch read back from a spill 
file can hold up to twice the memory
     it held when written: DataFusion 55.2 reads spill files in chunks of 128 
KiB, and arrow assembles a message that
     spans chunks in a buffer that grows by doubling. apache/datafusion#24592 
fixed that on main after 55.2 (it closed
     apache/datafusion#17340) and was not backported, so this PR reads a 
spilled build side back compacted. The
     backport to branch-55 is proposed in apache/datafusion#26435. And
     `HashJoinExec` counts its final pass over the build rows as probe input in 
`input_rows`.
   
   ### TPC-H at scale factor 100
   
   On the same machine, as a Spark 4.1.1 standalone cluster of two executors 
with 8 cores each, AQE on, one run of
   each query. The hash join arms force it with 
`spark.comet.exec.forceShuffledHashJoin` and `maxBuildSize=-1`. Total
   time of the 22 queries:
   
   | Off-heap pool per executor, shuffle partitions | Comet sort-merge join     
| Spilling hash join      | Hash join, no spilling |
   | ---------------------------------------------- | ------------------------- 
| ----------------------- | ---------------------- |
   | 16 GiB, 200                                    | 255.5 s                   
| 232.8 s                 | 232.5 s                |
   | 2 GiB, 32                                      | 268.0 s, 12 tasks retried 
| 242.2 s, 1 task retried | q21 fails              |
   | 1 GiB, 16                                      | 272.1 s, 11 tasks retried 
| q21 fails               | q9, q21 and q22 fail   |
   
   - Every query that completed returned the same rows as with the sort-merge 
join, by row count and a hash of its
     sorted rows. That includes every query that spilled.
   - With 16 GiB nothing spills, and the spilling join costs nothing over the 
join without spilling.
   - With 2 GiB, q21 spills 384 buckets, 3.84 GB, and takes 33.5 s, against 
36.7 s with the sort-merge join. Without
     spilling it fails. Its `NOT EXISTS` anti join probes the output of the 
sort-merge join of `EXISTS`, so Spark
     reports an order for it, and until `CometExecRule` looked at the operators 
above, it could not spill.
   - With 1 GiB, q9, q10, q17 and q22 spill. Every query but q21 completes, the 
21 of them in 208.0 s, against
     235.6 s with the sort-merge join.
   - With 1 GiB, q21 fails with spilling too. The anti join takes 124 MB of the 
task's 130 MB share for its build
     side, and then a sort below its probe side, for the sort-merge join of 
`EXISTS`, cannot get the 10 MiB it needs
     to merge. The join takes whatever the pool grants, and nothing makes it 
give memory back.
     Capping the join's build buffer at 64 MiB with `maxBuildBufferBytes` lets 
q21 complete in 33.9 s. Making
     Comet's fair pool divide the task's share instead of the executor's pool, 
with
     `spark.comet.exec.memoryPool.fraction=0.125`, lets it complete in 34.9 s, 
but then consumers that cannot spill
     hit their smaller limits: q16's broadcast hash join fails in both arms, 
and so does a sort's merge in q2 with
     the sort-merge join.
   - A prototype pool that limits only the consumers that can spill, as 
DataFusion's `FairSpillPool` does, over
     the task's share, fixes both. Every TPC-H query completes in both arms at 
1, 2 and 16 GiB with no task
     retried, in up to 3% more total time, and the spilling join completes all 
22 at 1 GiB in 248.1 s. It is not
     part of this PR, because it changes when every Comet operator spills, and 
is tracked in #7088.
   - The sort-merge join arm's retried tasks were the same kind of failure: a 
sort refused memory for its merge while
     another sort of its task held most of the task's share. Those retries 
succeed, because a sort's need is
     bounded and a retry finds a larger share. A retried spilling join takes 
the larger share as well.
   
   ### TPC-DS at scale factor 100
   
   On the same cluster, with 2 GiB and 32 shuffle partitions:
   
   | TPC-DS, 2 GiB, 32 partitions  | Comet sort-merge join     | Spilling hash 
join        | Hash join, no spilling |
   | ----------------------------- | ------------------------- | 
------------------------- | ---------------------- |
   | All 99 queries                | 974.8 s, 15 tasks retried | 2174.7 s, 3 
tasks retried | q72 runs past 40 min   |
   | The 98 queries other than q72 | 596.8 s                   | 564.3 s        
           | 564.5 s                |
   
   - Only q72 spills, and every query returned the same rows in every arm, 
except q39, whose floating point results
     differ in their last digits from run to run: every row agrees within a 
relative 4e-16, and two runs of the
     sort-merge join differ from each other the same way.
   - q72 is slow with either hash join, not because of spilling. Its join of 
`catalog_sales` with `inventory`, on the
     item alone with a residual filter, produces 16.8 billion rows, and the 
tasks of that stage take 179 s on average
     with the sort-merge join, 678 s with the spilling join and over 1,000 s 
without spilling. Forcing the hash join by
     default would need a guard on fan-out, not only on build size. The 
sort-merge fallback below is that guard.
     DataFusion tracks the cost in
     apache/datafusion#17494, and a DataFusion reproduction of q72's join is 
about 5 times slower with the hash join
     than with the sort-merge join on 55.2 and on main.
   
   ### Sort-merge fallback at scale factor 100
   
   On the same cluster, with 2 GiB and 32 shuffle partitions, every TPC-H and 
TPC-DS query ran with the fallback on and
   off, alternating per query, and then with the fallback on and its threshold 
lowered from 30 to 20 ns a match:
   
   | 2 GiB, 32 partitions                  | Fallback off | Fallback on, 30 ns 
| Fallback on, 20 ns |
   | ------------------------------------- | ------------ | ------------------ 
| ------------------ |
   | TPC-H, 22 queries                     | 244.3 s      | 244.1 s            
| 244.0 s            |
   | TPC-DS, the 98 queries other than q72 | 564.0 s      | 567.0 s            
| 565.8 s            |
   | TPC-DS q72                            | 1610 s       | 383.7 to 452 s     
| 384.8 s, 380.6 s   |
   
   q72 took 375.2 s with the sort-merge join on the same day. Its time without 
the fallback is the earlier run above.
   
   - Only q72 switches. With 20 ns, all 32 of its joins of the buckets left in 
memory switch, after at most 2.4 s of
     hashing, and its 162 spilled pairs are joined by sort-merge joins. No join 
of any other query reaches 16 matches
     per probe row: the most among the 2,028 inner joins with at least 16K 
probe rows is 12.6.
   - Every query returned the same rows in every arm, q72 included, except q39, 
as before.
   - With 30 ns, the threshold sat at the edge of q72's join. In some tasks the 
join of the buckets left in memory
     measured 28 ns a match, at about 870 matches per probe row. It then did 
not switch, or switched only after
     minutes, and its task took up to 254 s, against 174 to 191 s for the tasks 
that switched. A spilled pair whose
     build side fits in the cache takes about 10 ns a match, so 20 ns sits 
between the two. With 20 ns, the slowest task
     of the join's stage took 192 and 188 s in two runs, against 187 s with the 
sort-merge join.
   - No other query got slower. The short TPC-DS queries that differed by more 
than 6% in one run, q41, q43, q90 and
     q96, at 2 to 3 s, were within run-to-run noise when rerun three times, 
alternating.
   
   ### Forced hash join against the sort-merge join
   
   TPC-DS ran again on the same day with Comet's sort-merge join and with the 
forced spilling hash join and the
   fallback, alternating per query, on the same cluster with 2 GiB and 32 
shuffle partitions:
   
   | TPC-DS, 2 GiB, 32 partitions  | Sort-merge join | Forced hash join |
   | ----------------------------- | --------------- | ---------------- |
   | All 99 queries                | 975.1 s         | 945.7 s          |
   | The 98 queries other than q72 | 597.9 s         | 561.1 s          |
   | TPC-DS q72                    | 377.1 s         | 384.6 s          |
   
   - Every query returned the same rows in both arms.
   - 19 queries are more than 5% faster with the hash join, among them q80 at 
10.5 s against 16.4 s, q4 at 20.3 s
     against 30.8 s, q78 at 16.0 s against 21.5 s and q40 at 5.4 s against 7.2 
s. In q4 and q78 the sort-merge join's
     sorts were also refused memory for their merge, in 5 and 3 tasks that 
Spark retried.
   - Only q96 and q99, at 2.4 to 3.5 s, are more than 5% slower, by 0.2 s each, 
and were within 2% in the first run.
   - In the first run, q95 took 11.6 s with the hash join against 8.0 s. Its 
two left semi joins, which the rewrite
     cannot convert (#2667), need their input sorted by the order number, and 
the rewrite had sorted the output of
     the hash joins below them, about a billion rows, at 72 s of task time 
against 7 s for the sort-merge joins'
     input sorts. With the rewrite keeping those joins, q95 takes 8.0 s. The 
table is from the run after that change.
   
   ## Open questions
   
   - Is the honest reservation of the concatenated copy worth the earlier spill 
point, or should the build side be
     concatenated as it arrives, so the copy is smaller? A spilled bucket now 
avoids the copy by handing its inner
     join one build batch, but the join that fits in memory still makes it.
   - Spilling is on by default so that CI runs it. Now that it beats the 
sort-merge join when it spills, can
     `forceShuffledHashJoin` be on by default, after measuring TPC-H and TPC-DS 
at realistic memory sizes?
   - How does this fit with #6785, which plans the forced shuffled hash join at 
planning time, and with
     `forceShuffledHashJoin.maxBuildSize` once joins can spill?
   - How should a spilling join share the task's memory with the operators that 
run after its build, such as a sort
     below its probe side? Comet's `fair_unified` pool divides the executor's 
whole pool among a task's consumers,
     so its limit does not bind while Spark gives each task an even share. 
Limiting only the consumers that can
     spill, to a share of what the task's share leaves after the ones that 
cannot, as DataFusion's `FairSpillPool`
     does, helps every operator, the sort-merge join included, as the prototype 
above shows, but changes when all
     of them spill (#7088). Or the join could keep resident only part of what 
the pool grants when its probe side
     has operators that need memory.
   - A join whose output order an operator above relies on cannot spill. With 
`forceShuffledHashJoin`, there are none
     among the 611 native shuffled hash joins in the TPC-DS plans at scale 
factor 1. Before `CometExecRule` looked at
     the operators above, there were 10, in six queries, for which Spark 
reported an order that nothing used. Should a join whose order is used keep
     the sort-merge join?
   - Is 16 buckets per level the right fan-out?
   
   The remaining work, in priority order, and how to pick it up are in the 
design doc's Remaining work and
   Working on it sections.
   
   ## How are these changes tested?
   
   - Rust tests compare the operator with a plain `HashJoinExec`, row for row, 
for all 10 DataFusion join types, with
     and without a residual filter. They cover each path: in memory, bucketed, 
split again, chunked for a hot key and
     for null keys, real pool refusals, every bucket spilled, and empty sides, 
each with uncompressed and lz4 spill
     files. They also check that no inner join reserves beyond its estimate, 
that the operator's row counts are right,
     that a failed acquire fails the join instead of spilling, and that 
dropping the join deletes its spill files.
     Four deliberate breakages of the operator were each caught.
   - Further differential tests join keys of decimal, date, timestamp, string 
view, binary and dictionary type, carry
     list, struct, string view, dictionary, wide decimal, fixed-size binary and 
boolean payloads, and write rows wide
     enough that spilled batches span DataFusion's read chunks. The payload 
test is what showed that a dictionary's
     values have to be copied when a build side is read back. A unit test 
checks the one-batch build against
     `concat_batches`.
   - A planner test checks that the join is wrapped, that it keeps the 
projection `swap_inputs` adds, and that a join
     with the runtime filter is left alone.
   - Rust tests of the sort-merge fallback check that an inner join switches 
and still matches, in memory and when it
     spills, with one and two keys, string keys and a residual filter. One 
covers a join swapped for `BuildRight`,
     whose filter DataFusion 55's `SortMergeJoinExec` reads with its columns in 
the wrong places unless they are
     reordered (fixed upstream in apache/datafusion#25489). Others check that 
no other join type switches, that a
     join with few matches per probe row does not, and that a join switches 
only once it has reserved the memory to
     sort its build side.
   - `CometSpillingHashJoinSuite` checks that under a native pool too small for 
the build side the join fails without
     spilling, and completes and matches Spark with it. It also checks that 
every Spark join type matches Spark while
     spilling, and which joins are eligible.
   - `CometJoinSuite` checks that the rewrite keeps a sort-merge join whose 
order a kept sort-merge join, existence
     join, left semi join or window reads, and that it undoes a chain of 
rewrites on the same key, as in q95, but
     sorts above a hash join it did not make.
   - `CometSpillingHashJoinGreedyPoolSuite` checks that under the 
`greedy_unified` pool, with a small off-heap pool,
     the join spills when Spark refuses it memory, and matches Spark.
   - `CometJoinSpillingSuite` runs all of `CometJoinSuite` with every native 
shuffled hash join spilling all of its
     build side.
   - `CometSpillingHashJoinSuite` checks that inner joins that switch match 
Spark, building on the left and, with a
     residual filter, on the right, in memory and spilling. 
`CometJoinSortMergeFallbackSuite` runs all of
     `CometJoinSuite` with every inner join that can spill switching after its 
first probe batch, which 34 of its
     joins do.
   - These suites are now listed in the PR workflows. 
`CometSpillingHashJoinSuite` was not, which failed preflight, so
     no PR build ran for the first version.
   - Locally, `CometJoinSuite`, `CometJoinSpillingSuite`, 
`CometJoinSortMergeFallbackSuite` and both spilling suites
     pass on Spark 4.1, and every Spark profile, 3.4, 3.5 with strict warnings, 
4.0, 4.1 and 4.2, compiles with its
     tests.
   - TPC-H and TPC-DS at scale factor 1 match the golden answers of 
`CometTPCHQuerySuite` and `CometTPCDSQuerySuite`,
     all 22 and all 134 queries, with the suites' shuffled hash join 
configuration also setting
     `spark.comet.exec.hashJoin.spill.maxBuildBufferBytes`, to 1 MiB and 256 
KiB, so that every larger build side
     spills.
   - TPC-H at scale factor 100, under three sizes of the off-heap pool, and 
TPC-DS at scale factor 100, under one,
     return the same rows with the spilling join as with the sort-merge join 
for every query that completed, but for
     floating point noise in TPC-DS q39, see the findings above. So do all of 
them under 2 GiB with the sort-merge
     fallback on and off.
   - The Spark SQL suites pass on Spark 4.1, in CI with the 
`run-spark-4.1-tests` label. They run Comet on-heap,
     where the native pool is unbounded and nothing spills, so they show that 
the wrapper is transparent. Not yet
     run: the Spark SQL suites on the other Spark versions, and the Iceberg 
suites.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to