use std::sync::Arc;
use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use datafusion_common::{DataFusionError, Result};
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};
use datafusion_execution::{TaskContext, TryEmitter, async_try_stream};
use futures::stream::StreamExt;
use super::AggregateExec;
use super::aggregate_hash_table::{OrderedAggregateTable, PartialMarker};
use crate::aggregates::AggregateMode;
use crate::aggregates::order::GroupOrdering;
use crate::metrics::{BaselineMetrics, MetricBuilder, SpillMetrics};
use crate::stream::{ObservedStream, RecordBatchStreamAdapter};
use crate::{InputOrderMode, SendableRecordBatchStream, metrics};
pub(crate) struct OrderedPartialAggregateStream {
reservation: MemoryReservation,
context: OrderedPartialAggregateContext,
stage: ExecutionStage,
}
enum ExecutionStage {
Aggregating(Aggregating),
Outputting(Outputting),
}
struct Aggregating {
input: SendableRecordBatchStream,
table: OrderedAggregateTable<PartialMarker>,
}
struct Outputting {
batch: RecordBatch,
resume: Option<Aggregating>,
}
struct OrderedPartialAggregateContext {
schema: SchemaRef,
batch_size: usize,
baseline_metrics: BaselineMetrics,
reduction_factor: metrics::RatioMetrics,
}
impl OrderedPartialAggregateStream {
pub fn new(
agg: &AggregateExec,
context: &Arc<TaskContext>,
partition: usize,
) -> Result<Self> {
debug_assert_eq!(agg.mode, AggregateMode::Partial);
debug_assert_ne!(agg.input_order_mode, InputOrderMode::Linear);
let schema = Arc::clone(&agg.schema);
let input = agg.input.execute(partition, Arc::clone(context))?;
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 reduction_factor = MetricBuilder::new(&agg.metrics)
.with_type(metrics::MetricType::Summary)
.ratio_metrics("reduction_factor", partition);
let table = OrderedAggregateTable::<PartialMarker>::new(
agg,
partition,
Arc::clone(&schema),
batch_size,
)?;
let reservation =
MemoryConsumer::new(format!("OrderedPartialAggregateStream[{partition}]"))
.with_can_spill(matches!(
table.group_ordering(),
GroupOrdering::Partial(_)
))
.register(context.memory_pool());
Ok(Self {
reservation,
context: OrderedPartialAggregateContext {
schema,
batch_size,
baseline_metrics,
reduction_factor,
},
stage: ExecutionStage::Aggregating(Aggregating { input, table }),
})
}
pub(crate) fn into_stream(self) -> SendableRecordBatchStream {
let Self {
reservation,
context,
stage,
} = self;
let schema = Arc::clone(&context.schema);
let metrics = context.baseline_metrics.clone();
let stream = async_try_stream(|mut emitter| async move {
let mut stage = Some(stage);
while let Some(current_stage) = stage {
stage = match current_stage {
ExecutionStage::Aggregating(aggregating) => {
aggregating.handle_stage(&context, &reservation).await?
}
ExecutionStage::Outputting(outputting) => {
outputting
.handle_stage(&context, &reservation, &mut emitter)
.await?
}
};
}
Ok(())
});
let stream = Box::pin(RecordBatchStreamAdapter::new(schema, stream));
Box::pin(ObservedStream::new(stream, metrics, None))
}
}
impl Aggregating {
async fn handle_stage(
mut self,
context: &OrderedPartialAggregateContext,
reservation: &MemoryReservation,
) -> Result<Option<ExecutionStage>> {
let elapsed_compute = context.baseline_metrics.elapsed_compute();
while let Some(batch) = self.input.next().await.transpose()? {
context.reduction_factor.add_total(batch.num_rows());
let timer = elapsed_compute.timer();
self.table.aggregate_batch(&batch)?;
let output = match reservation.try_resize(self.table.memory_size()) {
Ok(()) => self.table.take_completed_state_batch()?,
Err(oom @ DataFusionError::ResourcesExhausted(_)) => {
if matches!(self.table.group_ordering(), GroupOrdering::Full(_)) {
return Err(oom);
}
let Some(batch) = self.table.take_state_batch()? else {
return Err(oom);
};
Some(batch)
}
Err(e) => return Err(e),
};
let Some(batch) = output else {
continue;
};
timer.done();
return Ok(Some(ExecutionStage::Outputting(Outputting {
batch,
resume: Some(self),
})));
}
drop(self.input);
self.table.input_done();
let timer = elapsed_compute.timer();
let output = self.table.take_completed_state_batch()?;
drop(self.table);
timer.done();
let Some(batch) = output else {
reservation.try_resize(0)?;
return Ok(None);
};
Ok(Some(ExecutionStage::Outputting(Outputting {
batch,
resume: None,
})))
}
}
impl Outputting {
async fn handle_stage(
self,
context: &OrderedPartialAggregateContext,
reservation: &MemoryReservation,
emitter: &mut TryEmitter<RecordBatch, DataFusionError>,
) -> Result<Option<ExecutionStage>> {
let Self { mut batch, resume } = self;
let elapsed_compute = context.baseline_metrics.elapsed_compute();
let mut timer = elapsed_compute.timer();
let (table_memory, next_stage) = match resume {
Some(aggregating) => (
aggregating.table.memory_size(),
Some(ExecutionStage::Aggregating(aggregating)),
),
None => (0, None),
};
let batch_memory = batch.get_array_memory_size();
match reservation.try_resize(table_memory + batch_memory) {
Ok(()) => {}
Err(DataFusionError::ResourcesExhausted(_)) => {
reservation.try_resize(table_memory)?;
context.reduction_factor.add_part(batch.num_rows());
timer.done();
emitter.emit(batch).await;
return Ok(next_stage);
}
Err(e) => return Err(e),
}
while batch.num_rows() > context.batch_size {
let output = batch.slice(0, context.batch_size);
batch =
batch.slice(context.batch_size, batch.num_rows() - context.batch_size);
context.reduction_factor.add_part(output.num_rows());
timer.done();
emitter.emit(output).await;
timer = elapsed_compute.timer();
}
reservation.try_shrink(batch_memory)?;
context.reduction_factor.add_part(batch.num_rows());
timer.done();
emitter.emit(batch).await;
Ok(next_stage)
}
}