From 5001e40a2af4ba379491784f255ac0693d8b2dd6 Mon Sep 17 00:00:00 2001 From: Geoffrey Claude Date: Fri, 30 Oct 2026 11:44:06 +0100 Subject: [PATCH 1/2] refactor: use iterator lookahead for materialized sort runs --- datafusion/physical-plan/src/sorts/sort.rs | 82 ++++----- datafusion/physical-plan/src/stream.rs | 188 --------------------- 2 files changed, 42 insertions(+), 228 deletions(-) diff --git a/datafusion/physical-plan/src/sorts/sort.rs b/datafusion/physical-plan/src/sorts/sort.rs index 53c2929d4aca9..fbc4c09fc2bed 100644 --- a/datafusion/physical-plan/src/sorts/sort.rs +++ b/datafusion/physical-plan/src/sorts/sort.rs @@ -35,7 +35,6 @@ use crate::spill::get_record_batch_memory_size; use crate::spill::in_progress_spill_file::InProgressSpillFile; use crate::spill::spill_manager::{GetSlicedSize, SpillManager}; use crate::statistics::{ChildStats, StatisticsArgs, with_per_partition_fetch}; -use crate::stream::ReservationStream; use crate::stream::{ObservedStream, RecordBatchStreamAdapter}; use crate::topk::TopK; use crate::topk::TopKDynamicFilters; @@ -787,7 +786,8 @@ impl ExternalSorter { .enumerate() .map(move |(index, (batch, size))| { let reservation = self.reservation.split(size); - let sort = self.sort_run(batch, reservation, shared_input.clone())?; + let sort = + self.sort_run(batch, reservation, shared_input.clone(), true)?; let permits = Arc::clone(&concurrency.permits); Ok::<_, DataFusionError>(async move { let stream = Self::prepare_sort_run(sort, permits).await?; @@ -837,19 +837,7 @@ impl ExternalSorter { .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)) + Ok(stream) } /// Concatenates `batches` into fewer, larger runs, each bounded by @@ -998,14 +986,19 @@ impl ExternalSorter { shared_input: Option>, ) -> Result { let schema = batch.schema(); - let stream = - futures::stream::once(self.sort_run(batch, reservation, shared_input)?) - .try_flatten(); + let stream = futures::stream::once(self.sort_run( + batch, + reservation, + shared_input, + false, + )?) + .try_flatten(); Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) } /// Sorts a batch and reserves its complete output before returning a stream. - /// The stream releases reservations as its consumer takes each output batch. + /// Reservations release as output is read; parallel preparation reads one + /// batch ahead to return spill workspace before the merge builds its cursor. /// If present, `shared_input` covers the runs' shared buffers and is held /// until sorting finishes; `reservation` covers this run's sorting and output. fn sort_run( @@ -1013,6 +1006,7 @@ impl ExternalSorter { batch: RecordBatch, reservation: MemoryReservation, shared_input: Option>, + read_ahead: bool, ) -> Result> + Send + use<>> { let reserved_bytes = get_reserved_bytes_for_record_batch(&batch)?; @@ -1045,31 +1039,39 @@ impl ExternalSorter { .iter() .map(get_record_batch_memory_size) .sum(); - let mut workspace = + let workspace = merge_pool.borrow(total_sorted_size.saturating_sub(reservation.size())); reservation .try_resize(total_sorted_size - workspace.size()) .map_err(Self::err_with_oom_context)?; - if workspace.size() == 0 { - return Ok(Box::pin(ReservationStream::new( - Arc::clone(&schema), - Box::pin(RecordBatchStreamAdapter::new( - Arc::clone(&schema), - futures::stream::iter(sorted_batches.into_iter().map(Ok)), - )), - reservation, - )) as SendableRecordBatchStream); - } - - // Return borrowed workspace first so the merge's cursors 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 borrowed = size.min(workspace.size()); - workspace.shrink(borrowed); - reservation.shrink(size - borrowed); - Ok(batch) + // An empty loan must not keep unused merge workspace alive. + let mut workspace = (workspace.size() != 0).then_some(workspace); + let mut batches = Some( + sorted_batches + .into_iter() + .inspect(move |batch| { + let size = get_record_batch_memory_size(batch); + let borrowed = workspace.as_mut().map_or(0, |workspace| { + let borrowed = size.min(workspace.size()); + workspace.shrink(borrowed); + borrowed + }); + reservation.shrink(size - borrowed); + }) + .peekable(), + ); + // Output is already in memory. Peeking releases the next batch's + // reservation before the merge allocates its current cursor. + let batches = std::iter::from_fn(move || { + let iter = batches.as_mut()?; + let batch = iter.next()?; + if read_ahead && iter.peek().is_none() { + // Release the exhausted iterator's workspace loan now, so it + // cannot keep unused merge memory reserved until another poll. + drop(batches.take()); + } + Some(Ok(batch)) }); Result::<_, DataFusionError>::Ok(Box::pin(RecordBatchStreamAdapter::new( Arc::clone(&schema), @@ -2557,7 +2559,7 @@ mod tests { let reservation = sorter.reservation.new_empty(); reservation.try_grow(get_reserved_bytes_for_record_batch(&batch)?)?; let before = elapsed_compute.value(); - let sort = sorter.sort_run(batch.clone(), reservation, None)?; + let sort = sorter.sort_run(batch.clone(), reservation, None, spawned)?; assert_eq!(elapsed_compute.value(), before); let stream = if spawned { diff --git a/datafusion/physical-plan/src/stream.rs b/datafusion/physical-plan/src/stream.rs index 28870c4ef359e..87f5feaaa9d06 100644 --- a/datafusion/physical-plan/src/stream.rs +++ b/datafusion/physical-plan/src/stream.rs @@ -14,13 +14,11 @@ use super::metrics::ExecutionPlanMetricsSet; use super::metrics::{BaselineMetrics, SplitMetrics}; use super::{ExecutionPlan, RecordBatchStream, SendableRecordBatchStream}; use crate::displayable; -use crate::spill::get_record_batch_memory_size; use arrow::{datatypes::SchemaRef, record_batch::RecordBatch}; use datafusion_common::{Result, exec_err}; use datafusion_common_runtime::JoinSet; use datafusion_execution::TaskContext; -use datafusion_execution::memory_pool::MemoryReservation; use futures::ready; use futures::stream::BoxStream; @@ -729,73 +727,6 @@ impl RecordBatchStream for BatchSplitStream { } } -/// A stream that holds a memory reservation for its lifetime, -/// shrinking the reservation as batches are consumed. -/// The original reservation must have its batch sizes calculated using [`get_record_batch_memory_size`] -/// On error, the reservation is *NOT* freed, until the stream is dropped. -pub(crate) struct ReservationStream { - schema: SchemaRef, - inner: SendableRecordBatchStream, - reservation: MemoryReservation, -} - -impl ReservationStream { - pub(crate) fn new( - schema: SchemaRef, - inner: SendableRecordBatchStream, - reservation: MemoryReservation, - ) -> Self { - Self { - schema, - inner, - reservation, - } - } -} - -impl Stream for ReservationStream { - type Item = Result; - - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { - let res = self.inner.poll_next_unpin(cx); - - match res { - Poll::Ready(res) => { - match res { - Some(Ok(batch)) => { - self.reservation - .shrink(get_record_batch_memory_size(&batch)); - Poll::Ready(Some(Ok(batch))) - } - Some(Err(err)) => Poll::Ready(Some(Err(err))), - None => { - // Stream is done so free the reservation completely - self.reservation.free(); - // Release the input pipeline's resources. - let inner_schema = self.inner.schema(); - self.inner = Box::pin(EmptyRecordBatchStream::new(inner_schema)); - Poll::Ready(None) - } - } - } - Poll::Pending => Poll::Pending, - } - } - - fn size_hint(&self) -> (usize, Option) { - self.inner.size_hint() - } -} - -impl RecordBatchStream for ReservationStream { - fn schema(&self) -> SchemaRef { - Arc::clone(&self.schema) - } -} - #[cfg(test)] mod test { use super::*; @@ -1023,123 +954,4 @@ mod test { "Should have received exactly two empty batches" ); } - - #[tokio::test] - async fn test_reservation_stream_shrinks_on_poll() { - use arrow::array::Int32Array; - use datafusion_execution::memory_pool::MemoryConsumer; - use datafusion_execution::runtime_env::RuntimeEnvBuilder; - - let runtime = RuntimeEnvBuilder::new() - .with_memory_limit(10 * 1024 * 1024, 1.0) - .build_arc() - .unwrap(); - - let reservation = MemoryConsumer::new("test").register(&runtime.memory_pool); - - let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); - - // Create batches - let batch1 = RecordBatch::try_new( - Arc::clone(&schema), - vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5]))], - ) - .unwrap(); - let batch2 = RecordBatch::try_new( - Arc::clone(&schema), - vec![Arc::new(Int32Array::from(vec![6, 7, 8, 9, 10]))], - ) - .unwrap(); - - let batch1_size = get_record_batch_memory_size(&batch1); - let batch2_size = get_record_batch_memory_size(&batch2); - - // Reserve memory upfront - reservation.try_grow(batch1_size + batch2_size).unwrap(); - let initial_reserved = runtime.memory_pool.reserved(); - assert_eq!(initial_reserved, batch1_size + batch2_size); - - // Create stream with batches - let stream = futures::stream::iter(vec![Ok(batch1), Ok(batch2)]); - let inner = Box::pin(RecordBatchStreamAdapter::new(Arc::clone(&schema), stream)) - as SendableRecordBatchStream; - - let mut res_stream = - ReservationStream::new(Arc::clone(&schema), inner, reservation); - - // Poll first batch - let result1 = res_stream.next().await; - assert!(result1.is_some()); - - // Memory should be reduced by batch1_size - let after_first = runtime.memory_pool.reserved(); - assert_eq!(after_first, batch2_size); - - // Poll second batch - let result2 = res_stream.next().await; - assert!(result2.is_some()); - - // Memory should be reduced by batch2_size - let after_second = runtime.memory_pool.reserved(); - assert_eq!(after_second, 0); - - // Poll None (end of stream) - let result3 = res_stream.next().await; - assert!(result3.is_none()); - - // Memory should still be 0 - assert_eq!(runtime.memory_pool.reserved(), 0); - } - - #[tokio::test] - async fn test_reservation_stream_error_handling() { - use datafusion_execution::memory_pool::MemoryConsumer; - use datafusion_execution::runtime_env::RuntimeEnvBuilder; - - let runtime = RuntimeEnvBuilder::new() - .with_memory_limit(10 * 1024 * 1024, 1.0) - .build_arc() - .unwrap(); - - let reservation = MemoryConsumer::new("test").register(&runtime.memory_pool); - - let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); - - reservation.try_grow(1000).unwrap(); - let initial = runtime.memory_pool.reserved(); - assert_eq!(initial, 1000); - - // Create a stream that errors - let stream = futures::stream::iter(vec![exec_err!("Test error")]); - let inner = Box::pin(RecordBatchStreamAdapter::new(Arc::clone(&schema), stream)) - as SendableRecordBatchStream; - - let mut res_stream = - ReservationStream::new(Arc::clone(&schema), inner, reservation); - - // Get the error - let result = res_stream.next().await; - assert!(result.is_some()); - assert!(result.unwrap().is_err()); - - // Verify reservation is NOT automatically freed on error - // The reservation is only freed when poll_next returns Poll::Ready(None) - // After an error, the stream may continue to hold the reservation - // until it's explicitly dropped or polled to None - let after_error = runtime.memory_pool.reserved(); - assert_eq!( - after_error, 1000, - "Reservation should still be held after error" - ); - - // Drop the stream to free the reservation - drop(res_stream); - - // Now memory should be freed - assert_eq!( - runtime.memory_pool.reserved(), - 0, - "Memory should be freed when stream is dropped" - ); - } } From 9ec4391ee50fe81a283b31e883e4822512f8a44b Mon Sep 17 00:00:00 2001 From: Geoffrey Claude Date: Fri, 6 Nov 2026 15:44:17 +0100 Subject: [PATCH 2/2] refactor: keep existing lookahead for sort runs --- datafusion/physical-plan/src/sorts/sort.rs | 70 +++++++++------------- 1 file changed, 28 insertions(+), 42 deletions(-) diff --git a/datafusion/physical-plan/src/sorts/sort.rs b/datafusion/physical-plan/src/sorts/sort.rs index fbc4c09fc2bed..1a87ea745ce45 100644 --- a/datafusion/physical-plan/src/sorts/sort.rs +++ b/datafusion/physical-plan/src/sorts/sort.rs @@ -786,8 +786,7 @@ impl ExternalSorter { .enumerate() .map(move |(index, (batch, size))| { let reservation = self.reservation.split(size); - let sort = - self.sort_run(batch, reservation, shared_input.clone(), true)?; + let sort = self.sort_run(batch, reservation, shared_input.clone())?; let permits = Arc::clone(&concurrency.permits); Ok::<_, DataFusionError>(async move { let stream = Self::prepare_sort_run(sort, permits).await?; @@ -837,7 +836,19 @@ impl ExternalSorter { .join_unwind() .await .map_err(|e| DataFusionError::ExecutionJoin(Box::new(e)))??; - Ok(stream) + 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)) } /// Concatenates `batches` into fewer, larger runs, each bounded by @@ -986,19 +997,14 @@ impl ExternalSorter { shared_input: Option>, ) -> Result { let schema = batch.schema(); - let stream = futures::stream::once(self.sort_run( - batch, - reservation, - shared_input, - false, - )?) - .try_flatten(); + let stream = + futures::stream::once(self.sort_run(batch, reservation, shared_input)?) + .try_flatten(); Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) } /// Sorts a batch and reserves its complete output before returning a stream. - /// Reservations release as output is read; parallel preparation reads one - /// batch ahead to return spill workspace before the merge builds its cursor. + /// The stream releases reservations as its consumer takes each output batch. /// If present, `shared_input` covers the runs' shared buffers and is held /// until sorting finishes; `reservation` covers this run's sorting and output. fn sort_run( @@ -1006,7 +1012,6 @@ impl ExternalSorter { batch: RecordBatch, reservation: MemoryReservation, shared_input: Option>, - read_ahead: bool, ) -> Result> + Send + use<>> { let reserved_bytes = get_reserved_bytes_for_record_batch(&batch)?; @@ -1039,39 +1044,20 @@ impl ExternalSorter { .iter() .map(get_record_batch_memory_size) .sum(); - let workspace = + let mut workspace = merge_pool.borrow(total_sorted_size.saturating_sub(reservation.size())); reservation .try_resize(total_sorted_size - workspace.size()) .map_err(Self::err_with_oom_context)?; - // An empty loan must not keep unused merge workspace alive. - let mut workspace = (workspace.size() != 0).then_some(workspace); - let mut batches = Some( - sorted_batches - .into_iter() - .inspect(move |batch| { - let size = get_record_batch_memory_size(batch); - let borrowed = workspace.as_mut().map_or(0, |workspace| { - let borrowed = size.min(workspace.size()); - workspace.shrink(borrowed); - borrowed - }); - reservation.shrink(size - borrowed); - }) - .peekable(), - ); - // Output is already in memory. Peeking releases the next batch's - // reservation before the merge allocates its current cursor. - let batches = std::iter::from_fn(move || { - let iter = batches.as_mut()?; - let batch = iter.next()?; - if read_ahead && iter.peek().is_none() { - // Release the exhausted iterator's workspace loan now, so it - // cannot keep unused merge memory reserved until another poll. - drop(batches.take()); - } - Some(Ok(batch)) + // Return borrowed workspace first so the merge's cursors 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 borrowed = size.min(workspace.size()); + workspace.shrink(borrowed); + reservation.shrink(size - borrowed); + Ok(batch) }); Result::<_, DataFusionError>::Ok(Box::pin(RecordBatchStreamAdapter::new( Arc::clone(&schema), @@ -2559,7 +2545,7 @@ mod tests { let reservation = sorter.reservation.new_empty(); reservation.try_grow(get_reserved_bytes_for_record_batch(&batch)?)?; let before = elapsed_compute.value(); - let sort = sorter.sort_run(batch.clone(), reservation, None, spawned)?; + let sort = sorter.sort_run(batch.clone(), reservation, None)?; assert_eq!(elapsed_compute.value(), before); let stream = if spawned {