-
Notifications
You must be signed in to change notification settings - Fork 2.4k
fix: account for memory that we still hold on when splitting batch #24852
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
rluvaton
wants to merge
2
commits into
apache:main
Choose a base branch
from
rluvaton:add-unaccounted-memory
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
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -182,6 +182,9 @@ enum PartialHashAggregateState { | |
| // After each incremental emitting step, the `remaining_groups` will be updated | ||
| // with batch slicing. | ||
| remaining_groups: RecordBatch, | ||
|
|
||
| // The size of remaining_groups in case we need to hold on it while slicing | ||
| batch_memory_size: usize, | ||
| }, | ||
| ProducingOutput { | ||
| hash_table: AggregateHashTable<PartialMarker>, | ||
|
|
@@ -652,10 +655,19 @@ impl PartialHashAggregateStream { | |
| let _timer = elapsed_compute.timer(); | ||
| let state_batch_result = hash_table.take_state_batch(); | ||
|
|
||
| // If we are holding on the memory due to slicing account for that | ||
| let state_batch_size = match &state_batch_result { | ||
| Ok(Some(batch)) if batch.num_rows() > self.batch_size => { | ||
| batch.get_array_memory_size() | ||
| } | ||
| _ => 0, | ||
| }; | ||
|
|
||
| // Emitting clears the aggregate table and releases its | ||
| // accumulated memory. Update the reservation accordingly. | ||
| let resize_result = | ||
| self.reservation.try_resize(hash_table.memory_size()); | ||
| let resize_result = self | ||
| .reservation | ||
| .try_resize(hash_table.memory_size() + state_batch_size); | ||
|
|
||
| if let Err(e) = resize_result { | ||
| return Self::break_with_err(e); | ||
|
|
@@ -675,6 +687,7 @@ impl PartialHashAggregateStream { | |
| PartialHashAggregateState::EmittingOnMemoryPressure { | ||
| hash_table, | ||
| remaining_groups: materialized_group_states, | ||
| batch_memory_size: state_batch_size, | ||
|
Member
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.
|
||
| }, | ||
| ); | ||
| } | ||
|
|
@@ -718,6 +731,7 @@ impl PartialHashAggregateStream { | |
| let PartialHashAggregateState::EmittingOnMemoryPressure { | ||
| hash_table, | ||
| remaining_groups: batch, | ||
| batch_memory_size: size, | ||
| } = original_state | ||
| else { | ||
| return Self::break_with_internal_err( | ||
|
|
@@ -741,11 +755,18 @@ impl PartialHashAggregateStream { | |
| PartialHashAggregateState::EmittingOnMemoryPressure { | ||
| hash_table, | ||
| remaining_groups: remaining, | ||
| batch_memory_size: size, | ||
| }, | ||
| ) | ||
| }; | ||
|
|
||
| self.reduction_factor.add_part(output_batch.num_rows()); | ||
| if matches!(next_state, PartialHashAggregateState::ReadingInput { .. }) | ||
| && size > 0 | ||
| { | ||
| self.reservation.shrink(size); | ||
| } | ||
|
|
||
| debug_assert!(output_batch.num_rows() > 0); | ||
| ControlFlow::Break(( | ||
| Poll::Ready(Some(Ok(output_batch.record_output(&self.baseline_metrics)))), | ||
|
|
@@ -1833,4 +1854,105 @@ mod tests { | |
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_partial_hash_stream_accounts_held_batch_on_memory_pressure() | ||
| -> Result<()> { | ||
| // When memory pressure triggers early emission, the materialized state | ||
| // batch is held in `EmittingOnMemoryPressure::remaining_groups` while it | ||
| // is sliced into `batch_size` outputs. The stream must keep that held | ||
| // batch accounted for in its memory reservation until the last slice is | ||
| // emitted; before the fix the reservation was resized down to just the | ||
| // (emptied) hash table size, leaving the held batch unaccounted. | ||
|
|
||
| let schema = Arc::new(Schema::new(vec![ | ||
| Field::new("group_col", DataType::Int32, false), | ||
| Field::new("value_col", DataType::Int64, false), | ||
| ])); | ||
|
|
||
| let batch_size = 1024; | ||
| // One row per group so the state batch is emitted in 4 slices | ||
| let num_groups = 4 * batch_size; | ||
| let group_ids: Vec<i32> = (0..num_groups as i32).collect(); | ||
| let values: Vec<i64> = vec![1; num_groups]; | ||
|
|
||
| let batch = RecordBatch::try_new( | ||
| Arc::clone(&schema), | ||
| vec![ | ||
| Arc::new(Int32Array::from(group_ids)), | ||
| Arc::new(Int64Array::from(values)), | ||
| ], | ||
| )?; | ||
| let input_partitions = vec![vec![batch]]; | ||
|
|
||
| // Smaller than the building hash table (so pressure triggers) but large | ||
| // enough to hold the materialized state batch (so emission can proceed) | ||
| let memory_limit = 100 * 1024; | ||
| let runtime = RuntimeEnvBuilder::default() | ||
| .with_memory_limit(memory_limit, 1.0) | ||
| .build_arc()?; | ||
|
|
||
| let mut task_ctx = TaskContext::default().with_runtime(Arc::clone(&runtime)); | ||
| let session_config = task_ctx.session_config().clone().set( | ||
| "datafusion.execution.batch_size", | ||
| &datafusion_common::ScalarValue::UInt64(Some(batch_size as u64)), | ||
| ); | ||
| task_ctx = task_ctx.with_session_config(session_config); | ||
| let task_ctx = Arc::new(task_ctx); | ||
|
|
||
| // Create aggregate: COUNT(*) GROUP BY group_col | ||
| let group_expr = vec![(col("group_col", &schema)?, "group_col".to_string())]; | ||
| let aggr_expr = vec![Arc::new( | ||
| AggregateExprBuilder::new(count_udaf(), vec![col("value_col", &schema)?]) | ||
| .schema(Arc::clone(&schema)) | ||
| .alias("count_value") | ||
| .build()?, | ||
| )]; | ||
|
|
||
| let exec = TestMemoryExec::try_new(&input_partitions, Arc::clone(&schema), None)?; | ||
| let exec = Arc::new(TestMemoryExec::update_cache(&Arc::new(exec))); | ||
|
|
||
| let aggregate_exec = AggregateExec::try_new( | ||
| AggregateMode::Partial, | ||
| PhysicalGroupBy::new_single(group_expr), | ||
| aggr_expr, | ||
| vec![None], | ||
| exec, | ||
| Arc::clone(&schema), | ||
| )?; | ||
|
|
||
| let mut stream = PartialHashAggregateStream::new(&aggregate_exec, &task_ctx, 0)?; | ||
|
|
||
| // The first output batch must be a pressure-emitted slice, with the rest | ||
| // of the materialized state batch still held by the stream | ||
| let first = stream.next().await.expect("stream ended early")?; | ||
| assert_eq!(first.num_rows(), batch_size); | ||
| assert!( | ||
| matches!( | ||
| stream.state, | ||
| Some(PartialHashAggregateState::EmittingOnMemoryPressure { .. }) | ||
| ), | ||
| "expected the stream to still be emitting under memory pressure \ | ||
| (if this fails the test setup no longer triggers early emission)" | ||
| ); | ||
|
|
||
| // The emitted slice shares buffers with the held state batch, so its | ||
| // array memory size reflects the full held allocation | ||
| let held_size = first.get_array_memory_size(); | ||
| let reserved = runtime.memory_pool.reserved(); | ||
| assert!( | ||
| reserved >= held_size, | ||
| "memory pool has {reserved} bytes reserved but the stream is \ | ||
| holding a materialized state batch of {held_size} bytes" | ||
| ); | ||
|
|
||
| // Drain the stream: no groups lost and the reservation is released | ||
| let mut total_rows = first.num_rows(); | ||
| while let Some(batch) = stream.next().await { | ||
| total_rows += batch?.num_rows(); | ||
| } | ||
| assert_eq!(total_rows, num_groups); | ||
|
|
||
| Ok(()) | ||
| } | ||
| } | ||
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.
This follows a failed resize, so charging the retained batch can make early emission fail with OOM after the batch is already allocated. If it cannot be retained, preserve progress (for example, yield it whole).