use std::ops::ControlFlow;
use std::sync::Arc;
use std::task::{Context, Poll};
use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use datafusion_common::{DataFusionError, Result, internal_datafusion_err};
use datafusion_execution::TaskContext;
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};
use futures::stream::{Stream, StreamExt};
use super::aggregate_hash_table::{ClusteredAggregateTable, SingleMarker};
use super::order::GroupClusteringMode;
use super::spill::AggregateSpill;
use super::{AggregateExec, create_schema};
use crate::aggregates::AggregateMode;
use crate::metrics::{BaselineMetrics, RecordOutput, SpillMetrics};
use crate::stream::EmptyRecordBatchStream;
use crate::{RecordBatchStream, SendableRecordBatchStream};
pub(crate) struct ClusteredSingleAggregateStream {
schema: SchemaRef,
input: SendableRecordBatchStream,
reservation: MemoryReservation,
baseline_metrics: BaselineMetrics,
batch_size: usize,
state: Option<ClusteredSingleAggregateState>,
}
enum ClusteredSingleAggregateState {
ReadingInput {
table: ClusteredAggregateTable<SingleMarker>,
spill_context: Option<Box<AggregateSpill>>,
},
Spilling {
table: ClusteredAggregateTable<SingleMarker>,
spill_context: Box<AggregateSpill>,
},
Outputting {
batch: RecordBatch,
batch_memory: usize,
next_state: Box<ClusteredSingleAggregateState>,
},
PreparingMergeInput {
table: ClusteredAggregateTable<SingleMarker>,
spill_context: Box<AggregateSpill>,
},
MergingSpills {
stream: SendableRecordBatchStream,
},
Done,
Error,
}
type ClusteredSingleAggregatePoll = Poll<Option<Result<RecordBatch>>>;
type ClusteredSingleAggregateStateTransition = ControlFlow<
(ClusteredSingleAggregatePoll, ClusteredSingleAggregateState),
ClusteredSingleAggregateState,
>;
impl ClusteredSingleAggregateStream {
pub fn new(
agg: &AggregateExec,
context: &Arc<TaskContext>,
partition: usize,
) -> Result<Self> {
debug_assert!(matches!(
agg.mode,
AggregateMode::Single | AggregateMode::SinglePartitioned
));
debug_assert_ne!(agg.group_clustering_mode, GroupClusteringMode::None);
let schema = Arc::clone(&agg.schema);
let input = agg.input.execute(partition, Arc::clone(context))?;
let input_schema = input.schema();
let batch_size = context.session_config().batch_size();
let baseline_metrics = BaselineMetrics::new(&agg.metrics, partition);
let spill_metrics = SpillMetrics::new(&agg.metrics, partition);
let state_schema = Arc::new(create_schema(
input_schema.as_ref(),
agg.group_by(),
agg.aggr_expr(),
AggregateMode::Partial,
)?);
let table = ClusteredAggregateTable::<SingleMarker>::new(
agg,
partition,
Arc::clone(&schema),
Arc::clone(&state_schema),
)?;
let can_spill =
matches!(agg.group_clustering_mode, GroupClusteringMode::Partial(_))
&& context.runtime_env().disk_manager.tmp_files_enabled();
let spill_context = if can_spill {
Some(Box::new(AggregateSpill::try_new(
"ClusteredSingleAggregateSpill",
agg,
context,
partition,
batch_size,
&agg.group_clustering_mode,
&state_schema,
spill_metrics,
)?))
} else {
None
};
let reservation =
MemoryConsumer::new(format!("ClusteredSingleAggregateStream[{partition}]"))
.with_can_spill(can_spill)
.register(context.memory_pool());
reservation.try_grow(table.memory_size())?;
Ok(Self {
schema,
input,
reservation,
baseline_metrics,
batch_size,
state: Some(ClusteredSingleAggregateState::ReadingInput {
table,
spill_context,
}),
})
}
fn close_input(&mut self) {
let input_schema = self.input.schema();
self.input = Box::pin(EmptyRecordBatchStream::new(input_schema));
}
fn break_with_err(error: DataFusionError) -> ClusteredSingleAggregateStateTransition {
ControlFlow::Break((
Poll::Ready(Some(Err(error))),
ClusteredSingleAggregateState::Error,
))
}
fn break_with_internal_err(message: &str) -> ClusteredSingleAggregateStateTransition {
Self::break_with_err(internal_datafusion_err!("{message}"))
}
fn reservation_size_for_table(
table: &ClusteredAggregateTable<SingleMarker>,
spill_context: Option<&AggregateSpill>,
) -> usize {
let table_size = table.memory_size();
if spill_context.is_some() {
table_size.saturating_add(table.num_groups().saturating_mul(size_of::<u32>()))
} else {
table_size
}
}
fn start_outputting(
&mut self,
batch: RecordBatch,
table_memory: usize,
next_state: ClusteredSingleAggregateState,
) -> ClusteredSingleAggregateStateTransition {
let batch_memory = batch.get_array_memory_size();
match self.reservation.try_resize(table_memory + batch_memory) {
Ok(()) => ControlFlow::Continue(ClusteredSingleAggregateState::Outputting {
batch,
batch_memory,
next_state: Box::new(next_state),
}),
Err(DataFusionError::ResourcesExhausted(_)) => {
if let Err(e) = self.reservation.try_resize(table_memory) {
return Self::break_with_err(e);
}
ControlFlow::Break((
Poll::Ready(Some(Ok(batch.record_output(&self.baseline_metrics)))),
next_state,
))
}
Err(e) => Self::break_with_err(e),
}
}
fn handle_reading_input(
&mut self,
cx: &mut Context<'_>,
original_state: ClusteredSingleAggregateState,
) -> ClusteredSingleAggregateStateTransition {
let ClusteredSingleAggregateState::ReadingInput {
mut table,
spill_context,
} = original_state
else {
return Self::break_with_internal_err(
"Clustered single aggregate stream expected ReadingInput state",
);
};
match self.input.poll_next_unpin(cx) {
Poll::Pending => ControlFlow::Break((
Poll::Pending,
ClusteredSingleAggregateState::ReadingInput {
table,
spill_context,
},
)),
Poll::Ready(Some(Ok(batch))) => {
let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
let timer = elapsed_compute.timer();
let result = table.aggregate_batch(&batch);
timer.done();
if let Err(e) = result {
return Self::break_with_err(e);
}
let timer = elapsed_compute.timer();
let resize_result =
self.reservation
.try_resize(Self::reservation_size_for_table(
&table,
spill_context.as_deref(),
));
timer.done();
let oom = match resize_result {
Ok(()) => None,
Err(e @ DataFusionError::ResourcesExhausted(_)) => {
match spill_context {
Some(spill_context) => {
if table.is_empty() {
return Self::break_with_internal_err(
"Clustered single aggregate ran out of memory with no aggregated groups",
);
}
return ControlFlow::Continue(
ClusteredSingleAggregateState::Spilling {
table,
spill_context,
},
);
}
None => Some(e),
}
}
Err(e) => {
return Self::break_with_err(e);
}
};
let result = if spill_context
.as_ref()
.is_some_and(|spill_context| spill_context.has_spills())
{
Ok(None)
} else {
let timer = elapsed_compute.timer();
let result = table.take_completed_result_batch();
timer.done();
result
};
match (result, oom) {
(Ok(Some(batch)), oom) => {
if oom.is_some() {
table.shrink_to_fit();
}
let table_memory = Self::reservation_size_for_table(
&table,
spill_context.as_deref(),
);
self.start_outputting(
batch,
table_memory,
ClusteredSingleAggregateState::ReadingInput {
table,
spill_context,
},
)
}
(Ok(None), Some(oom)) => Self::break_with_err(oom),
(Ok(None), None) => ControlFlow::Continue(
ClusteredSingleAggregateState::ReadingInput {
table,
spill_context,
},
),
(Err(e), _) => Self::break_with_err(e),
}
}
Poll::Ready(Some(Err(e))) => Self::break_with_err(e),
Poll::Ready(None) => {
self.close_input();
match spill_context {
Some(spill_context) if spill_context.has_spills() => {
ControlFlow::Continue(
ClusteredSingleAggregateState::PreparingMergeInput {
table,
spill_context,
},
)
}
_ => {
table.input_done();
let elapsed_compute =
self.baseline_metrics.elapsed_compute().clone();
let timer = elapsed_compute.timer();
let result = table.take_completed_result_batch();
drop(table);
timer.done();
match result {
Ok(Some(batch)) => self.start_outputting(
batch,
0,
ClusteredSingleAggregateState::Done,
),
Ok(None) => {
ControlFlow::Continue(ClusteredSingleAggregateState::Done)
}
Err(e) => Self::break_with_err(e),
}
}
}
}
}
}
fn handle_spilling(
&mut self,
original_state: ClusteredSingleAggregateState,
) -> ClusteredSingleAggregateStateTransition {
let ClusteredSingleAggregateState::Spilling {
mut table,
mut spill_context,
} = original_state
else {
return Self::break_with_internal_err(
"Clustered single aggregate stream expected Spilling state",
);
};
if table.is_empty() {
return Self::break_with_internal_err(
"Clustered single aggregation entered Spilling with an empty table",
);
}
let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
let timer = elapsed_compute.timer();
let mut result = table
.take_state_batch()
.and_then(|batch| spill_context.sort_and_spill(batch));
if let Err(e) = self.reservation.try_resize(table.memory_size()) {
result = Err(e);
}
timer.done();
match result {
Ok(()) => {
ControlFlow::Continue(ClusteredSingleAggregateState::ReadingInput {
table,
spill_context: Some(spill_context),
})
}
Err(e) => Self::break_with_err(e),
}
}
fn handle_preparing_merge_input(
&mut self,
original_state: ClusteredSingleAggregateState,
) -> ClusteredSingleAggregateStateTransition {
let ClusteredSingleAggregateState::PreparingMergeInput {
mut table,
mut spill_context,
} = original_state
else {
return Self::break_with_internal_err(
"Clustered single aggregate stream expected PreparingMergeInput state",
);
};
let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
let timer = elapsed_compute.timer();
let replay = match table
.take_state_batch()
.and_then(|batch| spill_context.sort_and_spill(batch))
{
Ok(()) => {
let metrics = table.metrics();
drop(table);
match self.reservation.try_resize(0) {
Ok(()) => (*spill_context).into_replay_stream(
&self.baseline_metrics,
metrics,
self.reservation.new_empty(),
),
Err(e) => Err(e),
}
}
Err(e) => Err(e),
};
timer.done();
match replay {
Ok(stream) => {
ControlFlow::Continue(ClusteredSingleAggregateState::MergingSpills {
stream,
})
}
Err(e) => Self::break_with_err(e),
}
}
fn handle_merging_spills(
&mut self,
cx: &mut Context<'_>,
original_state: ClusteredSingleAggregateState,
) -> ClusteredSingleAggregateStateTransition {
let ClusteredSingleAggregateState::MergingSpills { mut stream } = original_state
else {
return Self::break_with_internal_err(
"Clustered single aggregate stream expected MergingSpills state",
);
};
match stream.poll_next_unpin(cx) {
Poll::Pending => ControlFlow::Break((
Poll::Pending,
ClusteredSingleAggregateState::MergingSpills { stream },
)),
Poll::Ready(Some(Ok(batch))) => ControlFlow::Break((
Poll::Ready(Some(Ok(batch))),
ClusteredSingleAggregateState::MergingSpills { stream },
)),
Poll::Ready(Some(Err(e))) => Self::break_with_err(e),
Poll::Ready(None) => {
ControlFlow::Continue(ClusteredSingleAggregateState::Done)
}
}
}
fn handle_outputting(
&mut self,
original_state: ClusteredSingleAggregateState,
) -> ClusteredSingleAggregateStateTransition {
let ClusteredSingleAggregateState::Outputting {
batch,
batch_memory,
next_state,
} = original_state
else {
return Self::break_with_internal_err(
"Clustered single aggregate stream expected Outputting state",
);
};
if batch.num_rows() > self.batch_size {
let output = batch.slice(0, self.batch_size);
let batch = batch.slice(self.batch_size, batch.num_rows() - self.batch_size);
return ControlFlow::Break((
Poll::Ready(Some(Ok(output.record_output(&self.baseline_metrics)))),
ClusteredSingleAggregateState::Outputting {
batch,
batch_memory,
next_state,
},
));
}
if let Err(e) = self.reservation.try_shrink(batch_memory) {
return Self::break_with_err(e);
}
ControlFlow::Break((
Poll::Ready(Some(Ok(batch.record_output(&self.baseline_metrics)))),
*next_state,
))
}
}
impl Stream for ClusteredSingleAggregateStream {
type Item = Result<RecordBatch>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
loop {
let cur_state = self
.state
.take()
.expect("ClusteredSingleAggregateStream state should not be None");
let next_state = match cur_state {
state @ ClusteredSingleAggregateState::ReadingInput { .. } => {
self.handle_reading_input(cx, state)
}
state @ ClusteredSingleAggregateState::Spilling { .. } => {
self.handle_spilling(state)
}
state @ ClusteredSingleAggregateState::PreparingMergeInput { .. } => {
self.handle_preparing_merge_input(state)
}
state @ ClusteredSingleAggregateState::MergingSpills { .. } => {
self.handle_merging_spills(cx, state)
}
state @ ClusteredSingleAggregateState::Outputting { .. } => {
self.handle_outputting(state)
}
state @ ClusteredSingleAggregateState::Error => {
self.close_input();
self.reservation.free();
self.state = Some(state);
return Poll::Ready(None);
}
state @ ClusteredSingleAggregateState::Done => {
let _ = self.reservation.try_resize(0);
self.state = Some(state);
return Poll::Ready(None);
}
};
match next_state {
ControlFlow::Continue(next_state) => {
self.state = Some(next_state);
}
ControlFlow::Break((Poll::Ready(Some(Err(e))), next_state)) => {
debug_assert!(matches!(
next_state,
ClusteredSingleAggregateState::Error
));
self.close_input();
self.reservation.free();
self.state = Some(ClusteredSingleAggregateState::Error);
return Poll::Ready(Some(Err(e)));
}
ControlFlow::Break((poll, next_state)) => {
self.state = Some(next_state);
return poll;
}
}
}
}
}
impl RecordBatchStream for ClusteredSingleAggregateStream {
fn schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aggregates::PhysicalGroupBy;
use crate::aggregates::clustered_test_util::{
assert_completed_groups_emitted_under_limit, assert_output_unchanged_under_limit,
assert_resources_exhausted_under_limit, distinct_key_batches, full_batches,
held_memory, single_key_batches, sum_over_sorted_input,
};
use crate::collect;
use crate::test::TestMemoryExec;
use arrow::array::Int64Array;
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_common::test_util::batches_to_sort_string;
use datafusion_execution::config::SessionConfig;
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryPool, PeakRecordingPool,
};
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
use datafusion_functions_aggregate::sum::sum_udaf;
use datafusion_physical_expr::PhysicalSortExpr;
use datafusion_physical_expr::aggregate::AggregateExprBuilder;
use datafusion_physical_expr::expressions::col;
use datafusion_physical_expr_common::sort_expr::LexOrdering;
async fn run(pool: Arc<dyn MemoryPool>) -> Result<Vec<RecordBatch>> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Int64, false),
Field::new("b", DataType::Int64, false),
Field::new("v", DataType::Int64, false),
]));
let batches = [0, 0, 1, 1, 2, 2]
.map(|a| {
RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int64Array::from(vec![a; 43])),
Arc::new(Int64Array::from_iter_values(0..43)),
Arc::new(Int64Array::from_iter_values(0..43)),
],
)
.unwrap()
})
.to_vec();
let input = TestMemoryExec::try_new(&[batches], Arc::clone(&schema), None)?
.try_with_sort_information(vec![
LexOrdering::new([PhysicalSortExpr::new_default(col("a", &schema)?)])
.unwrap(),
])?;
let aggregate = AggregateExec::try_new(
AggregateMode::Single,
PhysicalGroupBy::new_single(vec![
(col("a", &schema)?, "a".into()),
(col("b", &schema)?, "b".into()),
]),
vec![Arc::new(
AggregateExprBuilder::new(sum_udaf(), vec![col("v", &schema)?])
.schema(Arc::clone(&schema))
.alias("sum")
.build()?,
)],
vec![None],
Arc::new(TestMemoryExec::update_cache(&Arc::new(input))),
Arc::clone(&schema),
)?;
let context = TaskContext::default()
.with_session_config(
SessionConfig::new()
.with_batch_size(4)
.set_bool("datafusion.execution.enable_migration_aggregate", true),
)
.with_runtime(
RuntimeEnvBuilder::new()
.with_memory_pool(pool)
.build_arc()?,
);
collect(Arc::new(aggregate), Arc::new(context)).await
}
#[tokio::test]
async fn completed_groups_under_memory_pressure() -> Result<()> {
let pool = Arc::new(PeakRecordingPool::new(Arc::new(GreedyMemoryPool::new(
usize::MAX,
))));
let expected = run(Arc::clone(&pool) as _).await?;
let limit = pool.peak_reserved() - 1;
let actual = run(Arc::new(GreedyMemoryPool::new(limit))).await?;
assert_eq!(
batches_to_sort_string(&actual),
batches_to_sort_string(&expected)
);
Ok(())
}
#[tokio::test]
async fn fully_clustered_completed_groups_under_memory_pressure() -> Result<()> {
let plan = sum_over_sorted_input(AggregateMode::Single, &["k"], full_batches())?;
assert_eq!(plan.group_clustering_mode(), &GroupClusteringMode::Full);
assert_completed_groups_emitted_under_limit(&plan).await
}
#[tokio::test]
async fn completed_groups_release_batch_capacity() -> Result<()> {
let plan =
sum_over_sorted_input(AggregateMode::Single, &["k"], distinct_key_batches())?;
assert_eq!(plan.group_clustering_mode(), &GroupClusteringMode::Full);
assert_output_unchanged_under_limit(&plan, 100 * 1024).await
}
#[tokio::test]
async fn memory_pressure_without_completed_groups() -> Result<()> {
let plan =
sum_over_sorted_input(AggregateMode::Single, &["k"], single_key_batches())?;
let limit = held_memory(&plan).await?;
assert_resources_exhausted_under_limit(&plan, limit).await
}
}