From 337d23202329dc9baf7b8b9f28557f50fe31f8c4 Mon Sep 17 00:00:00 2001 From: Richard Baah Date: Wed, 2 Dec 2026 11:01:41 -0500 Subject: [PATCH] perf(repartition): coalesce hash output from indices --- .../physical-plan/src/repartition/mod.rs | 225 +++++++++++++++++- 1 file changed, 212 insertions(+), 13 deletions(-) diff --git a/datafusion/physical-plan/src/repartition/mod.rs b/datafusion/physical-plan/src/repartition/mod.rs index 99571f3c0c168..03cc7590ea029 100644 --- a/datafusion/physical-plan/src/repartition/mod.rs +++ b/datafusion/physical-plan/src/repartition/mod.rs @@ -35,7 +35,9 @@ use crate::{ PlanProperties, ReplaceChildrenOptions, Statistics, validate_child_count, }; -use arrow::array::{PrimitiveArray, RecordBatch, RecordBatchOptions, UInt64Array}; +use arrow::array::{ + PrimitiveArray, RecordBatch, RecordBatchOptions, UInt32Array, UInt64Array, +}; use arrow::compute::{take_arrays, take_record_batch}; use arrow::datatypes::{DataType, Schema, SchemaRef, UInt32Type}; use arrow_schema::SortOptions; @@ -171,6 +173,51 @@ struct OutputChannel { shared_coalescer: Option, } +/// A batch routed to one output partition, either already materialized or as +/// a selection over the original input batch. +/// +/// Keeping the selection as indices lets a shared output coalescer copy each +/// row once into its final batch instead of materializing an intermediate batch. +enum PartitionedBatch { + /// A batch whose rows already belong to the output partition. + Batch(RecordBatch), + /// Rows selected from `batch` by an owned, reusable index buffer. + Indexed { + batch: RecordBatch, + indices: Vec, + }, +} + +impl PartitionedBatch { + /// Materializes an indexed selection and returns its index allocation for + /// reuse. An already materialized batch has no allocation to return. + fn materialize(self) -> Result<(RecordBatch, Option>)> { + match self { + Self::Batch(batch) => Ok((batch, None)), + Self::Indexed { batch, indices } => { + let indices = UInt32Array::from(indices); + let columns = take_arrays(batch.columns(), &indices, None)?; + let options = + RecordBatchOptions::new().with_row_count(Some(indices.len())); + let batch = + RecordBatch::try_new_with_options(batch.schema(), columns, &options)?; + Ok((batch, Some(Self::recycle_indices(indices)?))) + } + } + } + + /// Recovers the uniquely owned `Vec` backing an index array. + /// + /// This fails if the array no longer owns a complete, unshared allocation. + fn recycle_indices(indices: UInt32Array) -> Result> { + let (_, values, nulls) = indices.into_parts(); + debug_assert!(nulls.is_none()); + values.into_inner().into_vec::().map_err(|_| { + internal_datafusion_err!("Failed to recover repartition index buffer") + }) + } +} + /// The set of spill-pool writers for a single output partition, before they are handed to the /// per-input tasks. The variant encodes the repartition mode so the wrong writer topology cannot /// be constructed for a given mode. @@ -203,12 +250,27 @@ impl PartitionSpillWriters { impl OutputChannel { /// Appends the batches that are ready to send to `out`. - fn coalesce(&mut self, batch: RecordBatch, out: &mut Vec) -> Result<()> { - match &self.shared_coalescer { - Some(shared) => shared.push_and_drain(batch, out), - None => { + fn coalesce( + &mut self, + batch: PartitionedBatch, + out: &mut Vec, + ) -> Result>> { + match (&self.shared_coalescer, batch) { + (Some(shared), PartitionedBatch::Batch(batch)) => { + shared.push_and_drain(batch, out)?; + Ok(None) + } + (Some(shared), PartitionedBatch::Indexed { batch, indices }) => { + let indices = UInt32Array::from(indices); + let result = shared.push_indices_and_drain(batch, &indices, out); + let indices = PartitionedBatch::recycle_indices(indices)?; + result?; + Ok(Some(indices)) + } + (None, batch) => { + let (batch, indices) = batch.materialize()?; out.push(batch); - Ok(()) + Ok(indices) } } } @@ -295,6 +357,22 @@ impl SharedCoalescer { Ok(()) } + /// Push indexed rows into the coalescer and drain any completed batches + /// into `out` without materializing an intermediate batch. + fn push_indices_and_drain( + &self, + batch: RecordBatch, + indices: &UInt32Array, + out: &mut Vec, + ) -> Result<()> { + let mut c = self.inner.lock(); + c.push_batch_with_indices(batch, indices)?; + while let Some(b) = c.next_completed_batch() { + out.push(b); + } + Ok(()) + } + /// Decrement the active-senders counter. If this caller was the last /// sender, finalize the coalescer and return its residual batches; if /// other senders are still active, return `Ok(None)`. @@ -979,6 +1057,7 @@ impl StrengthReducedU64 { } } + /// Appends each row position to the output selected by its hash. fn partition_indices(self, hash_buffer: &[u64], indices: &mut [Vec]) { match self { Self::PowerOfTwo { mask } => { @@ -1375,6 +1454,83 @@ impl BatchPartitioner { Ok(it) } + /// Returns hash-partitioned batches as index selections for the output + /// coalescer. + fn partition_for_output( + &mut self, + batch: RecordBatch, + ) -> Result> { + match &mut self.state { + BatchPartitionerState::Hash { + exprs, + partition_reducer, + hash_buffer, + indices, + } => { + let timer = self.timer.timer(); + + let arrays = evaluate_expressions_to_arrays(exprs.as_slice(), &batch)?; + + hash_buffer.clear(); + hash_buffer.resize(batch.num_rows(), 0); + + create_hashes( + &arrays, + REPARTITION_RANDOM_STATE.random_state(), + hash_buffer, + )?; + + for v in indices.iter_mut() { + v.clear(); + } + + partition_reducer.partition_indices(hash_buffer, indices); + for &partition in &self.closed_outputs { + indices[partition].clear(); + } + timer.done(); + + Ok(indices + .iter_mut() + .enumerate() + .filter_map(|(partition, indices)| { + (!indices.is_empty()).then(|| { + ( + partition, + PartitionedBatch::Indexed { + batch: batch.clone(), + indices: std::mem::take(indices), + }, + ) + }) + }) + .collect()) + } + _ => { + let batches = self.partition_iter(batch)?.collect::>>()?; + Ok(batches + .into_iter() + .map(|(partition, batch)| (partition, PartitionedBatch::Batch(batch))) + .collect()) + } + } + } + + /// Restores an index allocation after the output coalescer has consumed it. + fn recycle_indices(&mut self, partition: usize, mut recycled: Vec) { + recycled.clear(); + match &mut self.state { + BatchPartitionerState::Hash { indices, .. } => { + debug_assert!(indices[partition].is_empty()); + indices[partition] = recycled; + } + BatchPartitionerState::RoundRobin { .. } + | BatchPartitionerState::Range { .. } => { + debug_assert!(false, "only hash partitioning recycles index buffers"); + } + } + } + // return the number of output partitions fn num_partitions(&self) -> usize { match &self.state { @@ -1481,11 +1637,11 @@ impl BatchPartitioner { let batches = { let _timer = timer.timer(); - let indices_array: PrimitiveArray = reordered_indices.into(); + let indices_array = UInt32Array::from(reordered_indices); let columns = take_arrays(batch.columns(), &indices_array, None)?; - let mut options = RecordBatchOptions::new(); - options = options.with_row_count(Some(indices_array.len())); + let options = + RecordBatchOptions::new().with_row_count(Some(indices_array.len())); let reordered_batch = RecordBatch::try_new_with_options(batch.schema(), columns, &options)?; @@ -2446,13 +2602,17 @@ impl RepartitionExec { } let mut closed = vec![]; - for res in partitioner.partition_iter(batch)? { - let (partition, batch) = res?; - + for (partition, batch) in partitioner.partition_for_output(batch)? { let timer = metrics.send_time[partition].timer(); // if there is still a receiver, send to it if let Some(output_channel) = output_channels.get_mut(&partition) { - output_channel.coalesce(batch, &mut coalesced)?; + if let Some(indices) = + output_channel.coalesce(batch, &mut coalesced)? + { + // The coalescer borrows the indices synchronously, so restore the + // values allocation before any channel send can yield. + partitioner.recycle_indices(partition, indices); + } for batch in coalesced.drain(..) { if output_channel.send(batch).await.is_err() { // If the other end has hung up, it was an early shutdown (e.g. LIMIT) @@ -2462,6 +2622,8 @@ impl RepartitionExec { break; } } + } else if let PartitionedBatch::Indexed { indices, .. } = batch { + partitioner.recycle_indices(partition, indices); } timer.done(); } @@ -3118,6 +3280,43 @@ mod tests { Ok(()) } + #[test] + fn partition_index_buffer_is_reused() -> Result<()> { + let schema = test_schema(false); + let mut partitioner = BatchPartitioner::new_hash_partitioner( + vec![col("c0", &schema)?], + 1, + metrics::Time::default(), + )?; + let batch = create_batch(); + + let (partition, PartitionedBatch::Indexed { indices, .. }) = + partitioner.partition_for_output(batch.clone())?.remove(0) + else { + panic!("expected indexed batch") + }; + assert_eq!(partition, 0); + let expected = indices.clone(); + let pointer = indices.as_ptr(); + let capacity = indices.capacity(); + + let indices = PartitionedBatch::recycle_indices(UInt32Array::from(indices))?; + assert_eq!(indices.as_ptr(), pointer); + assert_eq!(indices.capacity(), capacity); + partitioner.recycle_indices(0, indices); + + let (partition, PartitionedBatch::Indexed { indices, .. }) = + partitioner.partition_for_output(batch)?.remove(0) + else { + panic!("expected indexed batch") + }; + assert_eq!(partition, 0); + assert_eq!(indices, expected); + assert_eq!(indices.as_ptr(), pointer); + assert_eq!(indices.capacity(), capacity); + Ok(()) + } + #[tokio::test] async fn one_to_many_round_robin() -> Result<()> { // define input partitions