-
Notifications
You must be signed in to change notification settings - Fork 1.5k
refactor: Use SpillManager for all spilling scenarios #15405
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 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 |
---|---|---|
|
@@ -30,7 +30,7 @@ use crate::aggregates::{ | |
use crate::metrics::{BaselineMetrics, MetricBuilder, RecordOutput}; | ||
use crate::sorts::sort::sort_batch; | ||
use crate::sorts::streaming_merge::StreamingMergeBuilder; | ||
use crate::spill::{read_spill_as_stream, spill_record_batch_by_size}; | ||
use crate::spill::spill_manager::SpillManager; | ||
use crate::stream::RecordBatchStreamAdapter; | ||
use crate::{aggregates, metrics, ExecutionPlan, PhysicalExpr}; | ||
use crate::{RecordBatchStream, SendableRecordBatchStream}; | ||
|
@@ -42,7 +42,6 @@ use datafusion_common::{internal_err, DataFusionError, Result}; | |
use datafusion_execution::disk_manager::RefCountedTempFile; | ||
use datafusion_execution::memory_pool::proxy::VecAllocExt; | ||
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation}; | ||
use datafusion_execution::runtime_env::RuntimeEnv; | ||
use datafusion_execution::TaskContext; | ||
use datafusion_expr::{EmitTo, GroupsAccumulator}; | ||
use datafusion_physical_expr::expressions::Column; | ||
|
@@ -91,6 +90,9 @@ struct SpillState { | |
/// GROUP BY expressions for merging spilled data | ||
merging_group_by: PhysicalGroupBy, | ||
|
||
/// Manages the process of spilling and reading back intermediate data | ||
spill_manager: SpillManager, | ||
|
||
// ======================================================================== | ||
// STATES: | ||
// Fields changes during execution. Can be buffer, or state flags that | ||
|
@@ -109,12 +111,7 @@ struct SpillState { | |
/// Peak memory used for buffered data. | ||
/// Calculated as sum of peak memory values across partitions | ||
peak_mem_used: metrics::Gauge, | ||
/// count of spill files during the execution of the operator | ||
spill_count: metrics::Count, | ||
/// total spilled bytes during the execution of the operator | ||
spilled_bytes: metrics::Count, | ||
/// total spilled rows during the execution of the operator | ||
spilled_rows: metrics::Count, | ||
// Metrics related to spilling are managed inside `spill_manager` | ||
} | ||
|
||
/// Tracks if the aggregate should skip partial aggregations | ||
|
@@ -435,9 +432,6 @@ pub(crate) struct GroupedHashAggregateStream { | |
|
||
/// Execution metrics | ||
baseline_metrics: BaselineMetrics, | ||
|
||
/// The [`RuntimeEnv`] associated with the [`TaskContext`] argument | ||
runtime: Arc<RuntimeEnv>, | ||
} | ||
|
||
impl GroupedHashAggregateStream { | ||
|
@@ -544,6 +538,12 @@ impl GroupedHashAggregateStream { | |
|
||
let exec_state = ExecutionState::ReadingInput; | ||
|
||
let spill_manager = SpillManager::new( | ||
context.runtime_env(), | ||
metrics::SpillMetrics::new(&agg.metrics, partition), | ||
Arc::clone(&partial_agg_schema), | ||
); | ||
|
||
let spill_state = SpillState { | ||
spills: vec![], | ||
spill_expr, | ||
|
@@ -553,9 +553,7 @@ impl GroupedHashAggregateStream { | |
merging_group_by: PhysicalGroupBy::new_single(agg_group_by.expr.clone()), | ||
peak_mem_used: MetricBuilder::new(&agg.metrics) | ||
.gauge("peak_mem_used", partition), | ||
spill_count: MetricBuilder::new(&agg.metrics).spill_count(partition), | ||
spilled_bytes: MetricBuilder::new(&agg.metrics).spilled_bytes(partition), | ||
spilled_rows: MetricBuilder::new(&agg.metrics).spilled_rows(partition), | ||
spill_manager, | ||
}; | ||
|
||
// Skip aggregation is supported if: | ||
|
@@ -604,7 +602,6 @@ impl GroupedHashAggregateStream { | |
batch_size, | ||
group_ordering, | ||
input_done: false, | ||
runtime: context.runtime_env(), | ||
spill_state, | ||
group_values_soft_limit: agg.limit, | ||
skip_aggregation_probe, | ||
|
@@ -981,28 +978,30 @@ impl GroupedHashAggregateStream { | |
Ok(()) | ||
} | ||
|
||
/// Emit all rows, sort them, and store them on disk. | ||
/// Emit all intermediate aggregation states, sort them, and store them on disk. | ||
/// This process helps in reducing memory pressure by allowing the data to be | ||
/// read back with streaming merge. | ||
fn spill(&mut self) -> Result<()> { | ||
// Emit and sort intermediate aggregation state | ||
let Some(emit) = self.emit(EmitTo::All, true)? else { | ||
return Ok(()); | ||
}; | ||
let sorted = sort_batch(&emit, self.spill_state.spill_expr.as_ref(), None)?; | ||
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. eventually it might make sense to have the spill manager handle sorting the runs too (so it could potentially merge multiple files into a single run to reduce fanout, etc |
||
let spillfile = self.runtime.disk_manager.create_tmp_file("HashAggSpill")?; | ||
// TODO: slice large `sorted` and write to multiple files in parallel | ||
spill_record_batch_by_size( | ||
|
||
// Spill sorted state to disk | ||
let spillfile = self.spill_state.spill_manager.spill_record_batch_by_size( | ||
&sorted, | ||
spillfile.path().into(), | ||
sorted.schema(), | ||
"HashAggSpill", | ||
self.batch_size, | ||
)?; | ||
self.spill_state.spills.push(spillfile); | ||
|
||
// Update metrics | ||
self.spill_state.spill_count.add(1); | ||
self.spill_state | ||
.spilled_bytes | ||
.add(sorted.get_array_memory_size()); | ||
self.spill_state.spilled_rows.add(sorted.num_rows()); | ||
match spillfile { | ||
Some(spillfile) => self.spill_state.spills.push(spillfile), | ||
None => { | ||
return internal_err!( | ||
"Calling spill with no intermediate batch to spill" | ||
); | ||
} | ||
} | ||
|
||
Ok(()) | ||
} | ||
|
@@ -1058,7 +1057,7 @@ impl GroupedHashAggregateStream { | |
})), | ||
))); | ||
for spill in self.spill_state.spills.drain(..) { | ||
let stream = read_spill_as_stream(spill, Arc::clone(&schema), 2)?; | ||
let stream = self.spill_state.spill_manager.read_spill_as_stream(spill)?; | ||
streams.push(stream); | ||
} | ||
self.spill_state.is_stream_merging = true; | ||
|
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
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.
❤️