Repository navigation
Conversation
Spill independent sorted runs when a large multi-key sort has potentially expanding keys and less retained merge workspace than buffered reservation. Keep fixed-width keys and better-reserved merges on the existing preparation path. Hold shared input, per-run reservations, and merge workspace across asynchronous writes. Add an exact-output public SortExec regression and later-write lifetime coverage for success, failure, and cancellation. Amp-Thread-ID: https://ampcode.com/threads/T-92ab84e1-4bd7-42d2-9885-8e81c665fab6 Co-authored-by: Amp <amp@ampcode.com>
kosiew
left a comment
There was a problem hiding this comment.
@brancz, thanks for addressing the eager merge memory exhaustion. Independent spilling resolves the reproduced wide-dictionary failures while preserving ordering and memory accounting.
I'm requesting changes because the fallback also admits short UTF-8 keys, causing a previously successful sort to exceed its temporary disk quota. Please narrow the admission policy or otherwise prevent this regression.
| )), | ||
| ) | ||
| })?; | ||
| if has_expanding_keys |
There was a problem hiding this comment.
The gate also admits short Utf8 keys, where per-batch spill files can exhaust the temp-disk quota through repeated metadata and extra merge passes. A 4,096-row sort succeeded under a 300 KiB quota without this branch but now fails. Please narrow admission or avoid this disk overhead, and add a regression test.
| "in_mem_batches must not be empty when attempting to sort and spill" | ||
| ); | ||
|
|
||
| let has_expanding_keys = self.expr.iter().try_fold(false, |found, expr| { |
There was a problem hiding this comment.
Consider checking key count, batch count, and reservation thresholds before querying expression types. This avoids unnecessary data_type calls when independent spilling is already ruled out.
| }) | ||
| .collect::<std::result::Result<Vec<_>, _>>()?; | ||
| let actual = concat_batches(&decoded[0].schema(), &decoded)?; | ||
| let key_index = |
There was a problem hiding this comment.
Consider varying the second dictionary key independently among equal first keys across runs. The current test cannot detect a merge that ignores later dictionary keys. Verify ordering by (first_key, second_key, id).
Keep ordinary string keys on the merged spill path to avoid excessive spill files and disk-quota failures. Check cheap admission conditions before resolving sort-key types, and include run-end-encoded dictionary keys. Strengthen second-key ordering coverage, add a short-string disk-quota regression and REE dictionary cases, and preserve shared-input lifetime coverage under the narrowed gate. Amp-Thread-ID: https://ampcode.com/threads/T-92ab84e1-4bd7-42d2-9885-8e81c665fab6 Co-authored-by: Amp <amp@ampcode.com>
There was a problem hiding this comment.
Thanks for addressing the earlier findings. In reviewing the followup, I realized that my earlier recommendation overlooked nested dictionaries.
Before approval, please address the admission concerns below and share a reproducer case that fails on main during ingestion spilling but succeeds with this PR.
| found | ||
| || match expr.expr.data_type(&self.schema)? { | ||
| DataType::Dictionary(_, _) => true, | ||
| DataType::RunEndEncoded(_, values) => { | ||
| matches!(values.data_type(), DataType::Dictionary(_, _)) | ||
| } | ||
| _ => false, |
There was a problem hiding this comment.
Struct-wrapped dictionary keys bypass admission and exhaust memory in all eight tested configurations. Please cover nested dictionaries without admitting plain Utf8, and extend the existing regression matrix with struct-wrapped keys.
| if self.expr.len() > 1 | ||
| && self.in_mem_batches.len() > 1 | ||
| && self.reservation.size() >= self.sort_in_place_threshold_bytes | ||
| && self.merge_reservation.size() < self.reservation.size() | ||
| && self.expr.iter().try_fold(false, |found, expr| { | ||
| Ok::<_, DataFusionError>( | ||
| found | ||
| || match expr.expr.data_type(&self.schema)? { | ||
| DataType::Dictionary(_, _) => true, | ||
| DataType::RunEndEncoded(_, values) => { | ||
| matches!(values.data_type(), DataType::Dictionary(_, _)) | ||
| } | ||
| _ => false, | ||
| }, | ||
| ) | ||
| })? | ||
| { | ||
| // A row-format merge initializes keys for every buffered run before | ||
| // releasing any input. Dictionary keys, including run-end-encoded ones, | ||
| // can expand beyond the remaining pool capacity. Spill independent runs | ||
| // instead, retaining the input reservations and merge workspace while | ||
| // each run is written. | ||
| // Keep non-dictionary keys and better-reserved merges on the existing | ||
| // path: independent runs lose parallel preparation and add merge I/O, | ||
| // and even short strings can exceed disk quotas through file overhead. | ||
| // This workspace comparison is a heuristic, not a bound on encoded keys. | ||
| let batches = std::mem::take(&mut self.in_mem_batches); | ||
| let (sizes, shared_input_size) = self.sort_run_sizes(&batches)?; | ||
| let _shared_input = | ||
| shared_input_size.map(|size| self.reservation.split(size)); | ||
| self.in_mem_batches_counter = self.new_buffered_batches_counter(); | ||
| let elapsed_compute = self.metrics.baseline.elapsed_compute().clone(); | ||
|
|
||
| for (batch, size) in batches.into_iter().zip(sizes) { | ||
| let _reservation = self.reservation.split(size); | ||
| self.in_progress_spill_file = | ||
| Some((self.spill_manager.create_in_progress_file("Sorting")?, 0)); | ||
| let mut sorted_batches = IncrementalSortIterator::new( | ||
| batch, | ||
| self.expr.clone(), | ||
| self.batch_size, | ||
| ); | ||
| while let Some(batch) = { | ||
| let _timer = elapsed_compute.timer(); | ||
| sorted_batches.next() | ||
| } { | ||
| let batch = batch?; | ||
| let (file, max_record_batch_memory) = | ||
| self.in_progress_spill_file.as_mut().unwrap(); | ||
| let size = file.append_batch_async(&batch).await?; | ||
| *max_record_batch_memory = (*max_record_batch_memory).max(size); | ||
| } | ||
| self.spill_finish().await?; | ||
| } | ||
| return Ok(()); |
There was a problem hiding this comment.
Low-expansion dictionaries are 1.2-1.89x slower due to lost parallel preparation and additional merge I/O. Please restrict admission to cases where eager merging risks exhausting memory, or justify the measured slowdown, and include low-expansion dictionaries in the benchmarks.
|
Thanks for the thorough review, @kosiew. I think I want to give up on the heuristic. Instead, the spill should split into several files only when the memory pool actually refuses the merge, whatever the key type. I put together #27724 to try that. It converts the merge keys one run at a time and stops at the first run the pool refuses. If everything fits, the spill writes one file as before, so the short If that approach looks better to you, I'll close this one. |
Which issue does this PR close?
Related to #26940.
Rationale for this change
Multi-key sorts can run out of memory while trying to spill. Initializing merge cursors for all buffered batches can expand dictionary keys beyond the available memory before any data is written.
What changes are included in this PR?
Spill buffered batches as independent sorted runs for large multi-key sorts with potentially expanding keys when the buffered reservation exceeds reserved merge workspace. Keep the existing path otherwise.
The workspace comparison is a heuristic, not a bound on encoded key memory.
Related to #26953 and #26987. #26953 reduces merge input batch sizes; this avoids the ingestion-time merge for selected spills, including small batches that #26953 leaves unchanged. #26987 bounds the batches written to spill files for subsequent merging.
Also complementary to #27015, which reduces dictionary data written to disk.
What is the testing strategy for this PR?
Unit tests for wide dictionary keys and reservation lifetimes during async writes, including errors and cancellation. Extended workspace tests and Clippy pass.
Are there any user-facing changes?
No API changes, just an improvement to ingestion-time spilling. The tradeoff is more spill files and potentially more merge I/O for the selected path.
@alamb @Jefffrey