Skip to content

fix: don't double count column join keys in SortMergeJoinExec buffered batch reservation - #27346

Open
Kristofferjoha wants to merge 3 commits into
apache:mainfrom
Kristofferjoha:27322-fix-join-key-double
Open

Kristofferjoha wants to merge 3 commits into
apache:mainfrom
Kristofferjoha:27322-fix-join-key-double

Conversation

@Kristofferjoha

@Kristofferjoha Kristofferjoha commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

BufferedBatch::try_new reserves batch.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_new counts the join keys and then the batch with one RecordBatchMemoryCounter, so each buffer is charged once, the way HashJoinExec charges its build side. A column used in two key pairs is also charged once. The estimate no longer includes the per-array struct size that get_array_memory_size added.
  • When a spilled batch is read back, column keys are pointed at the restored batch's columns and the cached key comparators are dropped, so the pre-spill key buffers are released. The reservation is recomputed from the restored batch.

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_key checks that a computed key's peak_mem_used is exactly the computed key array's buffer size above a column key's.
  • spill_two_join_keys_share_buffered_column checks that a buffered column used in two key pairs is charged once after a spill.
  • spill_read_back_releases_original_column_key_buffer uses Buffer::strong_count to check that the pre-spill key buffer is released after read-back.
  • Updated the expected peak_mem_used in explain_analyze.slt (432 B -> 80 B). The existing spill tests take their expected size, and three of them their memory limit, from a new column_key_batch_size helper, so they still spill with the smaller estimate.

Are there any user-facing changes?

No.

@vinycalves vinycalves left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two logic questions; no code suggestions.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@github-actions github-actions Bot added sqllogictest SQL Logic Tests (.slt) physical-plan Changes to the physical-plan crate labels Nov 12, 2026
@Kristofferjoha

Copy link
Copy Markdown
Contributor Author

@adriangb Can you take a look at this one

@comphead

comphead commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Thanks @Kristofferjoha I'm checking the PR

@comphead comphead left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 on Kristofferjoha/datafusion for 8898d1e2f, so the new tests have not run in CI yet. Enabling Actions on the fork and rebasing onto main (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_estimation formula, so a small helper in tests.rs would turn the next change into one edit.
  • Follow-ups, not for this PR: PiecewiseMergeJoinExec double counts a column key the same way (get_record_batch_memory_size(&single_batch) + buffered_values.get_array_memory_size() in piecewise_merge_join/exec.rs). A per-stream RecordBatchMemoryTracker, 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.

Comment on lines 296 to 308
// 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>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +1122 to +1123
// Release the pre-spill key buffers the restored batch replaced.
bb.join_arrays = join_arrays(&batch, &self.on_buffered)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +4032 to +4034
/// 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<()> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Kristofferjoha
Kristofferjoha force-pushed the 27322-fix-join-key-double branch from 8898d1e to 2f5e58f Compare December 5, 2026 09:09
@Kristofferjoha

Copy link
Copy Markdown
Contributor Author

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 size_estimation from the restored batch, adjusting the reservation with resize instead of reusing the cached value. I added spill_two_join_keys_share_buffered_column to cover a column used in two key pairs. Three tests that hard-coded a 500 byte memory limit now take it from column_key_batch_size, so they still spill with the smaller estimate.

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

Labels

physical-plan Changes to the physical-plan crate sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SortMergeJoinExec double counts join key columns in the buffered batch reservation

3 participants