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::{ClusteredAggregateTable, PartialMarker};
use crate::aggregates::AggregateMode;
use crate::aggregates::order::{GroupClustering, GroupClusteringMode};
use crate::metrics::{BaselineMetrics, MetricBuilder, SpillMetrics};
use crate::stream::{ObservedStream, RecordBatchStreamAdapter};
use crate::{SendableRecordBatchStream, metrics};
pub(crate) struct ClusteredPartialAggregateStream {
reservation: MemoryReservation,
context: ClusteredPartialAggregateContext,
stage: ExecutionStage,
}
enum ExecutionStage {
Aggregating(Aggregating),
Outputting(Outputting),
}
struct Aggregating {
input: SendableRecordBatchStream,
table: ClusteredAggregateTable<PartialMarker>,
}
struct Outputting {
batch: RecordBatch,
resume: Option<Aggregating>,
}
struct ClusteredPartialAggregateContext {
schema: SchemaRef,
batch_size: usize,
baseline_metrics: BaselineMetrics,
reduction_factor: metrics::RatioMetrics,
}
impl ClusteredPartialAggregateStream {
pub fn new(
agg: &AggregateExec,
context: &Arc<TaskContext>,
partition: usize,
) -> Result<Self> {
debug_assert_eq!(agg.mode, AggregateMode::Partial);
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 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 = ClusteredAggregateTable::<PartialMarker>::new(
agg,
partition,
Arc::clone(&schema),
)?;
let reservation =
MemoryConsumer::new(format!("ClusteredPartialAggregateStream[{partition}]"))
.with_can_spill(matches!(
table.group_clustering(),
GroupClustering::Partial(_)
))
.register(context.memory_pool());
reservation.try_grow(table.memory_size())?;
Ok(Self {
reservation,
context: ClusteredPartialAggregateContext {
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: &ClusteredPartialAggregateContext,
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_clustering(), GroupClustering::Full(_)) {
let batch =
self.table.take_completed_state_batch()?.ok_or(oom)?;
self.table.shrink_to_fit();
Some(batch)
} else {
Some(self.table.take_state_batch()?.ok_or(oom)?)
}
}
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: &ClusteredPartialAggregateContext,
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)
}
}
#[cfg(test)]
mod tests {
use std::ops::Range;
use super::*;
use crate::aggregates::GroupClusteringMode;
use crate::aggregates::PhysicalGroupBy;
use crate::aggregates::clustered_test_util::{
aggregate_expr_over_sorted_input, aggregate_over_sorted_input,
assert_completed_groups_emitted_under_limit, assert_output_unchanged_under_limit,
collect_under_limit, distinct_key_batches, full_batches, sum_over_sorted_input,
};
use crate::test::TestMemoryExec;
use arrow::array::{ArrayRef, Float64Array, Int64Array, ListArray};
use arrow::datatypes::{DataType, Field, Int64Type, Schema};
use datafusion_common::test_util::batches_to_string;
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryPool, UnboundedMemoryPool,
};
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
use datafusion_functions_aggregate::any_value::any_value_udaf;
use datafusion_functions_aggregate::approx_distinct::approx_distinct_udaf;
use datafusion_functions_aggregate::first_last::first_value_udaf;
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;
fn batches(
key_types: &[DataType],
ranges: &[Range<i64>],
) -> Result<Vec<RecordBatch>> {
let mut fields: Vec<_> = key_types
.iter()
.enumerate()
.map(|(i, data_type)| Field::new(format!("k{i}"), data_type.clone(), false))
.collect();
fields.push(Field::new("v", DataType::Int64, false));
let schema = Arc::new(Schema::new(fields));
ranges
.iter()
.map(|range| {
let int64: ArrayRef =
Arc::new(Int64Array::from_iter_values(range.clone()));
let mut columns = key_types
.iter()
.map(|data_type| match data_type {
DataType::Int64 => Arc::clone(&int64),
DataType::Float64 => Arc::new(Float64Array::from_iter_values(
range.clone().map(|v| v as f64),
)),
DataType::List(_) => {
Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>(
range.clone().map(|v| Some([Some(v)])),
))
}
_ => unreachable!("unsupported key type {data_type}"),
})
.collect::<Vec<_>>();
columns.push(int64);
Ok(RecordBatch::try_new(Arc::clone(&schema), columns)?)
})
.collect()
}
async fn run(
batches: Vec<RecordBatch>,
pool: Arc<dyn MemoryPool>,
) -> Result<Vec<RecordBatch>> {
let schema = batches[0].schema();
let keys = (0..schema.fields().len() - 1)
.map(|i| Ok((col(&format!("k{i}"), &schema)?, format!("k{i}"))))
.collect::<Result<Vec<_>>>()?;
let ordering = LexOrdering::new(
keys.iter()
.map(|(expr, _)| PhysicalSortExpr::new_default(Arc::clone(expr))),
)
.unwrap();
let input = TestMemoryExec::try_new(&[batches], Arc::clone(&schema), None)?
.try_with_sort_information(vec![ordering])?;
let aggregate = AggregateExec::try_new(
AggregateMode::Partial,
PhysicalGroupBy::new_single(keys),
vec![Arc::new(
AggregateExprBuilder::new(sum_udaf(), vec![col("v", &schema)?])
.schema(Arc::clone(&schema))
.alias("sum")
.build()?,
)],
vec![None],
Arc::new(input),
Arc::clone(&schema),
)?;
assert_eq!(aggregate.group_clustering_mode, GroupClusteringMode::Full);
let context = Arc::new(
TaskContext::default().with_runtime(
RuntimeEnvBuilder::new()
.with_memory_pool(pool)
.build_arc()?,
),
);
let stream =
ClusteredPartialAggregateStream::new(&aggregate, &context, 0)?.into_stream();
crate::common::collect(stream).await
}
#[tokio::test]
async fn completed_groups_under_memory_pressure() -> Result<()> {
let list = DataType::List(Arc::new(Field::new_list_field(DataType::Int64, true)));
for key_types in [
vec![DataType::Int64],
vec![DataType::Int64, DataType::Int64],
vec![DataType::Float64, DataType::Float64],
vec![DataType::Int64, list],
] {
let input = || batches(&key_types, &[0..8193, 8192..16385, 16384..24576]);
let expected =
run(input()?, Arc::new(UnboundedMemoryPool::default())).await?;
let actual = run(input()?, Arc::new(GreedyMemoryPool::new(100 * 1024)))
.await
.map_err(|e| e.context(format!("key types {key_types:?}")))?;
assert_eq!(batches_to_string(&actual), batches_to_string(&expected));
}
Ok(())
}
#[tokio::test]
async fn fully_clustered_completed_groups_under_memory_pressure() -> Result<()> {
let plan = sum_over_sorted_input(AggregateMode::Partial, &["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_accumulator_scratch() -> Result<()> {
for udaf in [approx_distinct_udaf(), any_value_udaf()] {
let plan = aggregate_over_sorted_input(
AggregateMode::Partial,
&["k"],
distinct_key_batches(),
udaf,
)?;
assert_eq!(plan.group_clustering_mode(), &GroupClusteringMode::Full);
assert_output_unchanged_under_limit(&plan, 64 * 1024).await?;
}
Ok(())
}
#[tokio::test]
async fn active_group_releases_adapter_indices() -> Result<()> {
let keys = std::iter::once(0)
.chain(std::iter::repeat_n(1, 8191))
.collect();
let plan = aggregate_over_sorted_input(
AggregateMode::Partial,
&["k"],
vec![vec![keys]],
any_value_udaf(),
)?;
assert_eq!(plan.group_clustering_mode(), &GroupClusteringMode::Full);
assert_output_unchanged_under_limit(&plan, 16 * 1024).await
}
#[tokio::test]
async fn completed_groups_release_first_value_bitmap() -> Result<()> {
let plan = aggregate_expr_over_sorted_input(
AggregateMode::Partial,
&["k"],
vec![vec![(0..131072).collect()]],
first_value_udaf(),
|builder, schema| {
Ok(builder
.order_by(vec![PhysicalSortExpr::new_default(col("v", schema)?)]))
},
)?;
assert_eq!(plan.group_clustering_mode(), &GroupClusteringMode::Full);
assert_output_unchanged_under_limit(&plan, 16 * 1024).await
}
#[tokio::test]
async fn emitted_states_release_accumulator_scratch() -> Result<()> {
let batches = [0..8193, 8192..16385, 16384..24576]
.into_iter()
.map(|range| vec![range.clone().collect(), range.collect()])
.collect();
let plan = aggregate_over_sorted_input(
AggregateMode::Partial,
&["k", "k2"],
batches,
approx_distinct_udaf(),
)?;
assert!(matches!(
plan.group_clustering_mode(),
GroupClusteringMode::Partial(_)
));
collect_under_limit(&plan, 64 * 1024).await?;
Ok(())
}
}