Repository navigation
fix: charge RepartitionExec coalescer buffers to the memory pool #26167
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pmoust
wants to merge
1
commit into
apache:main
Choose a base branch
from
pmoust:repartition-coalescer-reservation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -62,7 +62,7 @@ use datafusion_common::{ | |
| use datafusion_common::{Result, not_impl_err}; | ||
| use datafusion_common_runtime::SpawnedTask; | ||
| use datafusion_execution::TaskContext; | ||
| use datafusion_execution::memory_pool::MemoryConsumer; | ||
| use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation}; | ||
| use datafusion_expr::ColumnarValue; | ||
| use datafusion_physical_expr::{EquivalenceProperties, PhysicalExpr, RangePartitioning}; | ||
| use datafusion_physical_expr_common::physical_expr::PhysicalExprRef; | ||
|
|
@@ -215,7 +215,7 @@ impl PartitionSpillWriters { | |
| impl OutputChannel { | ||
| fn coalesce(&mut self, batch: RecordBatch) -> Result<Vec<RecordBatch>> { | ||
| match &self.shared_coalescer { | ||
| Some(shared) => Ok(shared.push_and_drain(batch)?), | ||
| Some(shared) => Ok(shared.push_and_drain(batch, &self.reservation)?), | ||
| None => Ok(vec![batch]), | ||
| } | ||
| } | ||
|
|
@@ -251,7 +251,7 @@ impl OutputChannel { | |
| let Some(shared) = self.shared_coalescer.take() else { | ||
| return Ok(()); | ||
| }; | ||
| for batch in shared.finalize()? { | ||
| for batch in shared.finalize(&self.reservation)? { | ||
| // If this errored, it means that nobody is listening on the other side, which is fine | ||
| // and can happen in certain cases, like when a LIMIT drops the stream that listens. | ||
| let _ = self.send(batch).await; | ||
|
|
@@ -268,51 +268,83 @@ impl OutputChannel { | |
| /// into it. The last task to call [`Self::finalize`] is the one that | ||
| /// finalizes the coalescer and ships the residual batch. | ||
| /// | ||
| /// The rows the coalescer buffers are charged to the output partition's | ||
| /// memory reservation until they are flushed into a completed batch, which | ||
| /// [`OutputChannel::send`] then charges on its own. | ||
| /// | ||
| /// Cheap to [`Clone`]: both fields are [`Arc`]s. | ||
| #[derive(Clone)] | ||
| struct SharedCoalescer { | ||
| inner: Arc<Mutex<LimitedBatchCoalescer>>, | ||
| inner: Arc<Mutex<BufferedCoalescer>>, | ||
| active_senders: Arc<AtomicUsize>, | ||
| } | ||
|
|
||
| /// A [`LimitedBatchCoalescer`] and the number of bytes of its buffered rows | ||
| /// currently charged to the output partition's memory reservation. | ||
| struct BufferedCoalescer { | ||
| coalescer: LimitedBatchCoalescer, | ||
| reserved: usize, | ||
| } | ||
|
|
||
| impl BufferedCoalescer { | ||
| /// Set the charge for the buffered rows to the coalescer's current size. | ||
| /// Completed batches must be drained first, so their bytes are not | ||
| /// counted here as well as in [`OutputChannel::send`]. | ||
| fn update_reservation(&mut self, reservation: &MemoryReservation) { | ||
| let buffered = self.coalescer.size(); | ||
| if buffered > self.reserved { | ||
| reservation.grow(buffered - self.reserved); | ||
| } else { | ||
| reservation.shrink(self.reserved - buffered); | ||
| } | ||
| self.reserved = buffered; | ||
| } | ||
| } | ||
|
|
||
| impl SharedCoalescer { | ||
| fn new(schema: SchemaRef, target_batch_size: usize, num_senders: usize) -> Self { | ||
| Self { | ||
| inner: Arc::new(Mutex::new(LimitedBatchCoalescer::new( | ||
| schema, | ||
| target_batch_size, | ||
| None, | ||
| ))), | ||
| inner: Arc::new(Mutex::new(BufferedCoalescer { | ||
| coalescer: LimitedBatchCoalescer::new(schema, target_batch_size, None), | ||
| reserved: 0, | ||
| })), | ||
| active_senders: Arc::new(AtomicUsize::new(num_senders)), | ||
| } | ||
| } | ||
|
|
||
| /// Push `batch` into the coalescer and drain any newly completed | ||
| /// batches. The mutex is held only briefly. | ||
| fn push_and_drain(&self, batch: RecordBatch) -> Result<Vec<RecordBatch>> { | ||
| fn push_and_drain( | ||
| &self, | ||
| batch: RecordBatch, | ||
| reservation: &MemoryReservation, | ||
| ) -> Result<Vec<RecordBatch>> { | ||
| let mut acc = Vec::new(); | ||
| let mut c = self.inner.lock(); | ||
| c.push_batch(batch)?; | ||
| while let Some(b) = c.next_completed_batch() { | ||
| c.coalescer.push_batch(batch)?; | ||
| while let Some(b) = c.coalescer.next_completed_batch() { | ||
| acc.push(b); | ||
| } | ||
| c.update_reservation(reservation); | ||
| Ok(acc) | ||
| } | ||
|
|
||
| /// 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)`. | ||
| fn finalize(&self) -> Result<Vec<RecordBatch>> { | ||
| fn finalize(&self, reservation: &MemoryReservation) -> Result<Vec<RecordBatch>> { | ||
| let was_last = self.active_senders.fetch_sub(1, AtomicOrdering::AcqRel) == 1; | ||
| if !was_last { | ||
| return Ok(vec![]); | ||
| } | ||
| let mut acc = Vec::new(); | ||
| let mut c = self.inner.lock(); | ||
| c.finish()?; | ||
| while let Some(b) = c.next_completed_batch() { | ||
| c.coalescer.finish()?; | ||
| while let Some(b) = c.coalescer.next_completed_batch() { | ||
| acc.push(b); | ||
| } | ||
| reservation.shrink(c.reserved); | ||
| c.reserved = 0; | ||
| Ok(acc) | ||
| } | ||
| } | ||
|
|
@@ -4531,6 +4563,88 @@ mod tests { | |
| Ok(()) | ||
| } | ||
|
|
||
| /// Rows held in the output coalescer are charged to the memory pool until | ||
| /// they are flushed, and each byte is charged only once. | ||
| #[tokio::test] | ||
| async fn repartition_reserves_coalescer_buffered_rows() -> Result<()> { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This covers one input, one output and a
The first two can be added by parameterizing this test over inputs and column type. |
||
| use datafusion_execution::memory_pool::{MemoryPool, UnboundedMemoryPool}; | ||
|
|
||
| let batch_size = 100; | ||
| let schema = test_schema(false); | ||
| let rows = |range: std::ops::Range<u32>| { | ||
| RecordBatch::try_new( | ||
| Arc::clone(&schema), | ||
| vec![Arc::new(UInt32Array::from_iter_values(range))], | ||
| ) | ||
| }; | ||
| // Four batches complete one output batch. The last one stays in the | ||
| // coalescer. All are small enough to be coalesced rather than passed | ||
| // through. | ||
| let batches = vec![ | ||
| rows(0..25)?, | ||
| rows(25..50)?, | ||
| rows(50..75)?, | ||
| rows(75..100)?, | ||
| rows(100..150)?, | ||
| ]; | ||
|
|
||
| // What the repartition coalescer should hold, and so have reserved, | ||
| // once it has taken all five batches and handed out the completed one. | ||
| let mut expected = | ||
| LimitedBatchCoalescer::new(Arc::clone(&schema), batch_size, None); | ||
| for batch in &batches { | ||
| expected.push_batch(batch.clone())?; | ||
| } | ||
| assert_eq!(expected.next_completed_batch().unwrap().num_rows(), 100); | ||
| assert!(expected.next_completed_batch().is_none()); | ||
| let expected_reserved = expected.size(); | ||
| assert!(expected_reserved >= 50 * size_of::<u32>()); | ||
|
|
||
| // Keep the input open after its last batch, so the coalescer holds | ||
| // the last 50 rows until the test releases it. | ||
| let input = Arc::new( | ||
| BarrierExec::new(vec![batches], Arc::clone(&schema)) | ||
| .without_start_barrier() | ||
| .with_finish_barrier() | ||
| .with_log(false), | ||
| ); | ||
|
|
||
| let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default()); | ||
| let runtime = RuntimeEnvBuilder::default() | ||
| .with_memory_pool(Arc::clone(&pool)) | ||
| .build_arc()?; | ||
| let task_ctx = TaskContext::default() | ||
| .with_session_config(SessionConfig::new().with_batch_size(batch_size)) | ||
| .with_runtime(runtime); | ||
|
|
||
| let exec = RepartitionExec::try_new( | ||
| Arc::clone(&input) as Arc<dyn ExecutionPlan>, | ||
| Partitioning::RoundRobinBatch(1), | ||
| )?; | ||
| let mut stream = exec.execute(0, Arc::new(task_ctx))?; | ||
|
|
||
| let batch = stream.next().await.expect("completed batch")?; | ||
| assert_eq!(batch.num_rows(), batch_size); | ||
|
|
||
| // The completed batch was released when it was received. The input | ||
| // task pushes the last batch in the background. | ||
| for _ in 0..100 { | ||
| if pool.reserved() == expected_reserved { | ||
| break; | ||
| } | ||
| tokio::task::yield_now().await; | ||
| } | ||
| assert_eq!(pool.reserved(), expected_reserved); | ||
|
|
||
| input.wait_finish().await; | ||
| let batch = stream.next().await.expect("residual batch")?; | ||
| assert_eq!(batch.num_rows(), 50); | ||
| assert_eq!(pool.reserved(), 0); | ||
| assert!(stream.next().await.is_none()); | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn repartition_without_spilling() -> Result<()> { | ||
| // Test that repartition does not spill when there's ample memory | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When
buffered == self.reservedthis takes theelsebranch and callsreservation.shrink(0). That is the common case for primitive columns, because the first write reserves a fullbatch_sizecapacity andsize()then stays constant.MemoryReservation::shrinkhas no zero check (freeandresizedo), so every push still reaches the pool: an atomic inGreedyMemoryPool, the state mutex inFairSpillPool, and an extraRwLockread inTrackConsumersPool. This runs per push per output partition with the coalescer mutex held. Unmeasured.MemoryReservation::resizealready does this delta logic and is a no-op when the size is unchanged. It cannot be used on the sharedArc<MemoryReservation>because its size is the sum over all input tasks and the receiver, which is whyreservedexists. A dedicated consumer owned byBufferedCoalescerwould remove the need for it. Precedent is{name}[Merge {partition}]at line 1882.With that:
update_reservationbecomesself.reservation.resize(self.coalescer.size()).reservedfield, the grow/shrink branch and thereservationargument threaded throughcoalesce,push_and_drainandfinalizego away.finalizebecomesfree().FairSpillPool.