diff --git a/datafusion/physical-plan/src/sorts/sort.rs b/datafusion/physical-plan/src/sorts/sort.rs index 23f46a5e15ffc..0ac75a6d0fe50 100644 --- a/datafusion/physical-plan/src/sorts/sort.rs +++ b/datafusion/physical-plan/src/sorts/sort.rs @@ -49,7 +49,7 @@ use crate::{ use arrow::array::{RecordBatch, RecordBatchOptions}; use arrow::compute::{concat_batches, lexsort_to_indices, take_arrays}; -use arrow::datatypes::{DataType, SchemaRef}; +use arrow::datatypes::{DataType, Schema, SchemaRef}; use datafusion_common::config::SpillCompression; use datafusion_common::tree_node::TreeNodeRecursion; use datafusion_common::utils::{ @@ -889,27 +889,14 @@ impl ExternalSorter { .acquire_owned() .await .map_err(|e| internal_datafusion_err!("Sort concurrency closed: {e}"))?; - let stream = SpawnedTask::spawn(async move { + SpawnedTask::spawn(async move { // Keep the permit until this job exits, even if its caller is cancelled. let _permit = permit; sort.await }) .join_unwind() .await - .map_err(|e| DataFusionError::ExecutionJoin(Box::new(e)))??; - Ok(Self::with_lookahead(stream)) - } - - /// [`Self::sort_run`] materializes all output and releases each batch's - /// reservation when that batch is pulled. Reading one batch ahead returns - /// extra spill workspace for the merge's current batch and cursor. - /// Each run can hold one prefetched batch whose reservation is already released. - fn with_lookahead(stream: SendableRecordBatchStream) -> SendableRecordBatchStream { - let schema = stream.schema(); - // Buffer the current batch and one ahead to return borrowed spill workspace - // before the merge processes the current batch. - let batches = stream.map(std::future::ready).buffered(2); - Box::pin(RecordBatchStreamAdapter::new(schema, batches)) + .map_err(|e| DataFusionError::ExecutionJoin(Box::new(e)))? } /// Concatenates `batches` into fewer, larger runs, each bounded by @@ -1091,6 +1078,7 @@ impl ExternalSorter { let elapsed_compute = self.metrics.baseline.elapsed_compute().clone(); // Set when `merge_run_batch_size` split this run let split = batch_size < self.batch_size; + let row_format = merges_in_row_format(&self.expr, &self.schema); Ok(async move { // Held until `batch` is sorted, when this block ends. The last run to @@ -1119,16 +1107,36 @@ impl ExternalSorter { .iter() .map(get_record_batch_memory_size) .sum(); + // A merge reserves its cursor over the keys when it takes the first + // batch. Keep headroom for it until then, out of the sorting + // reservation, so the cursor does not depend on memory that other + // consumers can take. The first batch bounds it from below, since + // the estimate leaves out the cursor's fixed costs. + let cursor_size = match sorted_batches.first() { + Some(first) => { + let keys = match row_format { + true => estimated_row_keys_size(&expressions, &schema, first)?, + false => None, + }; + keys.unwrap_or(0).max(get_record_batch_memory_size(first)) + } + None => 0, + }; + let mut cursor_allowance = + cursor_size.min(reservation.size().saturating_sub(total_sorted_size)); let mut workspace = merge_pool.borrow(total_sorted_size.saturating_sub(reservation.size())); reservation - .try_resize(total_sorted_size - workspace.size()) + .try_resize(total_sorted_size + cursor_allowance - workspace.size()) .map_err(Self::err_with_oom_context)?; - // Return borrowed workspace first so the merge's cursors can reuse - // it immediately. Both reservations also release on stream drop. + // Each batch stays reserved until its consumer takes it, which then + // reserves the batch itself. Return borrowed workspace first so the + // merge can reuse it immediately. Both reservations also release on + // stream drop. let batches = sorted_batches.into_iter().map(move |batch| { - let size = get_record_batch_memory_size(&batch); + let size = get_record_batch_memory_size(&batch) + + std::mem::take(&mut cursor_allowance); let borrowed = size.min(workspace.size()); workspace.shrink(borrowed); reservation.shrink(size - borrowed); @@ -1177,28 +1185,10 @@ impl ExternalSorter { /// computed key is sized from its type if that has a fixed width, and /// otherwise counts as larger, since sizing it would evaluate it again. fn encoded_keys_may_exceed(&self, run: &RecordBatch) -> Result { - // An 8-byte offset per row, then a null byte and the bytes of each key - let mut encoded = run.num_rows() * size_of::(); - for sort_expr in self.expr.iter() { - let key_bytes = match sort_expr.expr.downcast_ref::() { - Some(column) => run - .column(column.index()) - .to_data() - .get_slice_memory_size()?, - None => { - let width = sort_expr - .expr - .data_type(self.schema.as_ref()) - .ok() - .and_then(|data_type| data_type.primitive_width()); - let Some(width) = width else { - return Ok(true); - }; - run.num_rows() * width - } - }; - encoded += run.num_rows() + key_bytes; - } + let Some(encoded) = estimated_row_keys_size(&self.expr, &self.schema, run)? + else { + return Ok(true); + }; Ok(encoded > run.get_sliced_size()?) } @@ -1336,6 +1326,39 @@ fn get_reserved_bytes_for_next_record_batch( )) } +/// Estimates the row-format keys of `batch`: an 8-byte offset per row, then a +/// null byte and the bytes of each key. Returns `None` if a computed key has no +/// fixed width, since sizing it would evaluate it. +fn estimated_row_keys_size( + expressions: &LexOrdering, + schema: &Schema, + batch: &RecordBatch, +) -> Result> { + let rows = batch.num_rows(); + let mut size = rows * size_of::(); + for sort_expr in expressions.iter() { + let key_bytes = match sort_expr.expr.downcast_ref::() { + Some(column) => batch + .column(column.index()) + .to_data() + .get_slice_memory_size()?, + None => { + let width = sort_expr + .expr + .data_type(schema) + .ok() + .and_then(|data_type| data_type.primitive_width()); + let Some(width) = width else { + return Ok(None); + }; + rows * width + } + }; + size += rows + key_bytes; + } + Ok(Some(size)) +} + /// Returns whether the sorted copy of an array of `data_type` keeps /// referencing some of the array's buffers. /// diff --git a/datafusion/physical-plan/src/sorts/sort/spill_tests.rs b/datafusion/physical-plan/src/sorts/sort/spill_tests.rs index 53a0b4c0d8f00..87f5c31e75f40 100644 --- a/datafusion/physical-plan/src/sorts/sort/spill_tests.rs +++ b/datafusion/physical-plan/src/sorts/sort/spill_tests.rs @@ -540,8 +540,9 @@ async fn test_chunked_string_view_spill_can_use_workspace() -> Result<()> { check_chunked_string_view_workspace(true).await } -/// Prepared runs retain their workspace loans until merging starts. Looking -/// ahead during the merge returns enough workspace for its batch and cursors. +/// Prepared runs retain their workspace loans until merging starts. The loans +/// they return as the merge takes their batches cover the merge's batches, and +/// the cursors take nothing more, since the key column is part of each batch. async fn check_sort_preparation_workspace(consume_output: bool) -> Result<()> { let batch_size = 1024; let values: ArrayRef = Arc::new(StringViewArray::from_iter_values( @@ -623,7 +624,7 @@ async fn test_sort_preparation_retains_workspace_until_drop() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn test_sort_merge_lookahead_returns_cursor_workspace() -> Result<()> { +async fn test_sort_merge_fits_in_returned_workspace() -> Result<()> { check_sort_preparation_workspace(true).await } @@ -689,6 +690,86 @@ async fn test_sort_preparation_keeps_output_reserved() -> Result<()> { Ok(()) } +/// Runs that output several batches keep each batch reserved until the merge +/// reserves it, and keep room for the merge's cursors, so the merge can start +/// after another consumer takes the rest of the pool. The two `Int64` keys +/// merge in the row format, whose cursors hold memory of their own. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_sort_merge_keeps_run_batches_reserved() -> Result<()> { + let (rows, batch_size): (i64, usize) = (4096, 1024); + let batches = (0..4) + .map(|run| { + RecordBatch::try_from_iter([ + ( + "a", + Arc::new(Int64Array::from_iter_values( + (0..rows).map(|i| (i * 7 + run) % rows), + )) as ArrayRef, + ), + ( + "b", + Arc::new(Int64Array::from_iter_values((0..rows).rev())) as ArrayRef, + ), + ( + "c", + Arc::new(FixedSizeBinaryArray::try_from_iter( + (0..rows).map(|i| [i as u8; 64]), + )?) as ArrayRef, + ), + ]) + }) + .collect::, _>>()?; + let ordering: LexOrdering = [ + PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0))), + PhysicalSortExpr::new_default(Arc::new(Column::new("b", 1))), + ] + .into(); + let mut sorted_bytes = 0; + for batch in &batches { + for sorted in sort_batch_chunked(batch, &ordering, batch_size)? { + sorted_bytes += get_record_batch_memory_size(&sorted); + } + } + let capacity = 4 * sorted_bytes; + let runtime = RuntimeEnvBuilder::new() + .with_memory_pool(Arc::new(GreedyMemoryPool::new(capacity))) + .build_arc()?; + let mut sorter = ExternalSorter::new( + 0, + batches[0].schema(), + ordering.clone(), + batch_size, + 0, + 0, + SpillCompression::Uncompressed, + &ExecutionPlanMetricsSet::new(), + Arc::clone(&runtime), + )?; + for batch in &batches { + sorter.insert_batch(batch.clone()).await?; + } + let mut stream = sorter.sort().await?; + let other = MemoryConsumer::new("other").register(&runtime.memory_pool); + other.try_grow(capacity - runtime.memory_pool.reserved())?; + + let mut output = vec![stream.try_next().await?.expect("output")]; + // The merge holds the first batch of each run, and the runs hold the rest. + assert!(runtime.memory_pool.reserved() - other.size() >= sorted_bytes); + while let Some(batch) = stream.try_next().await? { + output.push(batch); + } + let input = concat_batches(&batches[0].schema(), &batches)?; + assert_eq!( + concat_batches(&input.schema(), &output)?, + sort_batch(&input, &ordering, None)? + ); + drop(stream); + drop(sorter); + drop(other); + assert_eq!(runtime.memory_pool.reserved(), 0); + Ok(()) +} + /// Merging sorted runs in the row format holds the keys of every run's current /// batch. Two `Int32` keys encode to 18 bytes per row against 8 bytes in the /// batches, and a single `FixedSizeBinary(16)` key and two long `Utf8View` keys diff --git a/datafusion/physical-plan/src/sorts/stream.rs b/datafusion/physical-plan/src/sorts/stream.rs index 246237fed85b1..fa0d269b82239 100644 --- a/datafusion/physical-plan/src/sorts/stream.rs +++ b/datafusion/physical-plan/src/sorts/stream.rs @@ -15,6 +15,7 @@ use arrow::row::{RowConverter, Rows, SortField}; use arrow_ord::sort::lexsort_to_indices; use datafusion_common::{Result, internal_datafusion_err}; use datafusion_execution::memory_pool::MemoryReservation; +use datafusion_physical_expr::expressions::Column; use datafusion_physical_expr_common::sort_expr::LexOrdering; use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays; use futures::stream::{Fuse, StreamExt}; @@ -292,7 +293,13 @@ impl FieldCursorStream { fn convert_batch(&mut self, batch: &RecordBatch) -> Result> { let value = self.sort.expr.evaluate(batch)?; let array = value.into_array(batch.num_rows())?; - let size_in_mem = array.get_buffer_memory_size(); + // A column key is part of `batch`, which the merge reserves for at least + // as long as this cursor lives, so only a computed key needs memory. + let size_in_mem = if self.sort.expr.downcast_ref::().is_some() { + 0 + } else { + array.get_buffer_memory_size() + }; let array = array.as_any().downcast_ref::().expect("field values"); let array_reservation = self.reservation.new_empty(); array_reservation.try_grow(size_in_mem)?;