Repository navigation
fix: don't double count column join keys in SortMergeJoinExec buffered batch reservation - #27346
Kristofferjoha wants to merge 3 commits into
Conversation
vinycalves
left a comment
There was a problem hiding this comment.
Two logic questions; no code suggestions.
There was a problem hiding this comment.
Does the new test cover a computed join key and the spill/read-back path, where the key array is actually unshared? When a batch spills, does the reservation still avoid double-counting buffers shared with the key arrays?
There was a problem hiding this comment.
Thanks, added a test which covers a computed key and the spill/read-back path. On spill the batch is dropped, so only the key arrays stay in memory and they’re counted once.
There was a problem hiding this comment.
The size_estimation / 2 runs in buffered_batch_reservation_column_and_computed_key don't reach the read-back change. restore_spilled_batches sets the reservation from the cached size_estimation, so those runs pass with the re-evaluation removed and repeat the unlimited runs. No reservation metric can see that line, because it changes which buffers the keys point at, not how much is reserved. A test would have to look at retained buffers instead, for example Buffer::strong_count on the pre-spill key buffer (an untested idea).
|
@adriangb Can you take a look at this one |
|
Thanks @Kristofferjoha I'm checking the PR |
comphead
left a comment
There was a problem hiding this comment.
The fix follows how HashJoinExec charges its build keys (count_batch on the batch, then count_array per key). Re-evaluating the keys on read-back is needed too: a spilled batch keeps its key arrays in memory, so without it the restored batch would sit next to the pre-spill key buffers while size_estimation assumes they are shared.
Rust (fork)found no run onKristofferjoha/datafusionfor8898d1e2f, so the new tests have not run in CI yet. Enabling Actions on the fork and rebasing ontomain(the branch predates the SMJ changes in #27278) would give a signal before the merge queue. See https://datafusion.apache.org/contributor-guide/#pull-requests-from-forks.- The three spill tests now repeat the
size_estimationformula, so a small helper intests.rswould turn the next change into one edit. - Follow-ups, not for this PR:
PiecewiseMergeJoinExecdouble counts a column key the same way (get_record_batch_memory_size(&single_batch) + buffered_values.get_array_memory_size()inpiecewise_merge_join/exec.rs). A per-streamRecordBatchMemoryTracker, whose docs already name sort-merge join, would also dedup buffers that several buffered batches share. - FYI, my draft #27928 drops unused buffered columns before a batch spills. Once both land, the read-back re-evaluation needs the keys bound to the projected schema. I'll handle that on my side.
| // A key that is a plain column is the batch's own array. | ||
| let mut counter = RecordBatchMemoryCounter::new(); | ||
| counter.count_batch(&batch); | ||
| let unshared_join_arrays_mem: usize = join_arrays | ||
| .iter() | ||
| .map(|arr| counter.count_array(arr.as_ref())) | ||
| .sum(); | ||
|
|
||
| let size_estimation = batch.get_array_memory_size() | ||
| + join_arrays_mem | ||
| + unshared_join_arrays_mem | ||
| + batch.num_rows().next_power_of_two() * size_of::<usize>() | ||
| + size_of::<Range<usize>>() | ||
| + size_of::<usize>(); |
There was a problem hiding this comment.
count_batch already walks the batch, but its result is dropped and get_array_memory_size() walks it again. The keys are walked twice as well (lines 291-294 and 299-302). One counter gives both numbers if the keys go first:
let mut counter = RecordBatchMemoryCounter::new();
let join_arrays_mem: usize = join_arrays
.iter()
.map(|arr| counter.count_array(arr.as_ref()))
.sum();
let size_estimation = join_arrays_mem
+ counter.count_batch(&batch)
+ batch.num_rows().next_power_of_two() * size_of::<usize>()
+ size_of::<Range<usize>>()
+ size_of::<usize>();count_batch then returns only the batch buffers the keys don't already hold. That drops unshared_join_arrays_mem, charges the batch the way HashJoinExec does (get_record_batch_memory_size), and stops join_arrays_mem from charging a column twice when it appears in two key pairs. The totals lose the per-array size_of::<Self>() that get_array_memory_size adds, so the test formulas and the .slt value would move.
There was a problem hiding this comment.
Done in BufferedBatch::memory_sizes: one counter, keys first. join_arrays_mem is deduplicated as well, so a column in two key pairs is charged once (covered by spill_two_join_keys_share_buffered_column). The slt value moved to 80 B. great point on the helper.
| // Release the pre-spill key buffers the restored batch replaced. | ||
| bb.join_arrays = join_arrays(&batch, &self.on_buffered)?; |
There was a problem hiding this comment.
The comment promises a bit more than happens here. The cached streamed_buffered_cmp and buffered_equality_cmp still hold the old head and tail key arrays (arrow's comparators clone the key values), so those buffers are only released when the comparators are rebuilt. No test can see this line either (see my reply in the computed-key thread). I'd make the comment state the invariant the line keeps, for example // size_estimation charges column keys as part of the batch, so point them at the restored buffers.
There was a problem hiding this comment.
Updated the read-back path to point column keys at the restored batch and clear both cached comparators. I also added spill_read_back_releases_original_column_key_buffer, which checks the old buffer’s reference count while the join still has rows to emit.
| /// Only a computed join key is charged on top of the batch, in memory and after spill read-back. | ||
| #[tokio::test] | ||
| async fn buffered_batch_reservation_column_and_computed_key() -> Result<()> { |
There was a problem hiding this comment.
The explain_analyze.slt change already pins the column key end to end (432 B to 288 B), so column_join_key_not_double_counted repeats it and could go. Here I'd compare the two keys instead of rebuilding size_estimation term by term: assert that the computed key's peak exceeds the column key's by exactly that key array's get_buffer_memory_size(). That catches both a double-counted column key and an uncharged computed key, and it survives changes to the estimate like the one suggested in try_new. The spill runs can go, see my reply in the computed-key thread.
There was a problem hiding this comment.
Done, tests now asserts that computed keys peak equals column keys peak + the computed key array's get_buffer_memory_size(). I removed the spill runs and column_join_key_not_double_counted.
8898d1e to
2f5e58f
Compare
|
Got fork actions working https://github.com/Kristofferjoha/datafusion/actions/runs/47503138202 and added your suggestions. I made a few changes you didnt ask for. On read-back, only column keys are pointed at the restored batch. Computed keys stay in memory while the batch is spilled, so they aren't re-evaluated. Read-back also clears both cached comparators and recomputes |
Which issue does this PR close?
Rationale for this change
BufferedBatch::try_newreservesbatch.get_array_memory_size()plus the size of each evaluated join key array. For a column key, the key array is the batch's own column, so that column is counted twice. Joins on wide string keys reserve about twice what they hold, and spill or fail under a memory limit earlier than they should.What changes are included in this PR?
BufferedBatch::try_newcounts the join keys and then the batch with oneRecordBatchMemoryCounter, so each buffer is charged once, the wayHashJoinExeccharges its build side. A column used in two key pairs is also charged once. The estimate no longer includes the per-array struct size thatget_array_memory_sizeadded.With the repro from the issue both queries now report 19.5 MB (was 38.8 MB and 19.7 MB).
What is the testing strategy for this PR?
buffered_batch_reservation_column_and_computed_keychecks that a computed key'speak_mem_usedis exactly the computed key array's buffer size above a column key's.spill_two_join_keys_share_buffered_columnchecks that a buffered column used in two key pairs is charged once after a spill.spill_read_back_releases_original_column_key_bufferusesBuffer::strong_countto check that the pre-spill key buffer is released after read-back.peak_mem_usedinexplain_analyze.slt(432 B -> 80 B). The existing spill tests take their expected size, and three of them their memory limit, from a newcolumn_key_batch_sizehelper, so they still spill with the smaller estimate.Are there any user-facing changes?
No.