kosiew commented on code in PR #27043:
URL: https://github.com/apache/datafusion/pull/27043#discussion_r4680298485


##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -552,6 +552,63 @@ impl ExternalSorter {
             "in_mem_batches must not be empty when attempting to sort and 
spill"
         );
 
+        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,

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



##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -552,6 +552,63 @@ impl ExternalSorter {
             "in_mem_batches must not be empty when attempting to sort and 
spill"
         );
 
+        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(());

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



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