use std::mem::size_of;
use std::sync::Arc;
use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use datafusion_common::{
DataFusionError, Result, assert_ne_or_internal_err, internal_datafusion_err,
};
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};
use datafusion_execution::{TaskContext, TryEmitter, async_try_stream};
use futures::stream::{Stream, StreamExt};
use super::AggregateExec;
use super::aggregate_hash_table::{
AggregateHashTable, ClusteredAggregateTableMetrics, FinalMarker, PartialMarker,
PartialSkipMarker,
};
use super::order::GroupClusteringMode;
use super::skip_partial::SkipAggregationProbe;
use super::spill::AggregateSpill;
use crate::metrics::{
BaselineMetrics, MetricBuilder, MetricCategory, RecordOutput, SpillMetrics,
};
use crate::stream::{EmptyRecordBatchStream, RecordBatchStreamAdapter};
use crate::{SendableRecordBatchStream, metrics};
pub(crate) struct PartialHashAggregateStream {
schema: SchemaRef,
input: SendableRecordBatchStream,
batch_size: usize,
reservation: MemoryReservation,
baseline_metrics: BaselineMetrics,
reduction_factor: metrics::RatioMetrics,
early_emit_count: metrics::Count,
skip_aggregation_probe: Option<SkipAggregationProbe>,
group_values_soft_limit: Option<usize>,
hash_table: Option<AggregateHashTable<PartialMarker>>,
}
pub(crate) struct FinalHashAggregateStream {
schema: SchemaRef,
input: SendableRecordBatchStream,
baseline_metrics: BaselineMetrics,
reservation: MemoryReservation,
group_values_soft_limit: Option<usize>,
hash_table: Option<AggregateHashTable<FinalMarker>>,
spill_context: Option<Box<AggregateSpill>>,
}
#[derive(PartialEq)]
enum HandleInputResult {
ProcessNext,
ReachedLimit,
#[expect(clippy::upper_case_acronyms)]
OOM,
SwitchToSkipAggregation,
}
impl PartialHashAggregateStream {
pub fn new(
agg: &AggregateExec,
context: &Arc<TaskContext>,
partition: usize,
) -> Result<Self> {
debug_assert_eq!(agg.mode, super::AggregateMode::Partial);
debug_assert_eq!(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 early_emit_count =
MetricBuilder::new(&agg.metrics).counter("early_emit_count", partition);
let hash_table = AggregateHashTable::<PartialMarker>::new(
agg,
partition,
Arc::clone(&schema),
batch_size,
)?;
let skip_aggregation_probe = if agg.group_by().is_single() {
let options = &context.session_config().options().execution;
let probe_ratio_threshold =
options.skip_partial_aggregation_probe_ratio_threshold;
if probe_ratio_threshold >= 1.0 {
None
} else {
let skipped_aggregation_rows = MetricBuilder::new(&agg.metrics)
.with_category(MetricCategory::Rows)
.counter("skipped_aggregation_rows", partition);
Some(SkipAggregationProbe::new(
options.skip_partial_aggregation_probe_rows_threshold,
probe_ratio_threshold,
skipped_aggregation_rows,
))
}
} else {
None
};
let reservation =
MemoryConsumer::new(format!("PartialHashAggregateStream[{partition}]"))
.with_can_spill(true)
.register(context.memory_pool());
reservation.try_grow(hash_table.memory_size())?;
Ok(Self {
schema,
input,
batch_size,
baseline_metrics,
reservation,
reduction_factor,
early_emit_count,
skip_aggregation_probe,
group_values_soft_limit: agg.limit_options().map(|config| config.limit()),
hash_table: Some(hash_table),
})
}
pub(crate) fn into_stream(self) -> SendableRecordBatchStream {
let schema = Arc::clone(&self.schema);
Box::pin(RecordBatchStreamAdapter::new(schema, self.create_stream()))
}
fn create_stream(mut self) -> impl Stream<Item = Result<RecordBatch>> {
async_try_stream(|mut emitter| async move {
let mut hash_table = self
.hash_table
.take()
.expect("hash_table should not be None");
debug_assert!(hash_table.is_building());
let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
let mut last_state = HandleInputResult::ProcessNext;
while let Some(batch) = self.input.next().await.transpose()? {
let timer = elapsed_compute.timer();
last_state = self.handle_input_batch(&batch, &mut hash_table)?;
match last_state {
HandleInputResult::ProcessNext => {}
HandleInputResult::ReachedLimit
| HandleInputResult::SwitchToSkipAggregation => {
break;
}
HandleInputResult::OOM => {
let materialized_group_states = hash_table.take_state_batch()?.ok_or_else(|| {
internal_datafusion_err!(
"Partial hash aggregate ran out of memory with no aggregated groups"
)
})?;
self.early_emit_count.add(1);
timer.done();
self.emit_on_memory_pressure(
materialized_group_states,
&mut emitter,
hash_table.memory_size(),
)
.await?;
}
}
}
let timer = elapsed_compute.timer();
let skip_hash_table =
if last_state == HandleInputResult::SwitchToSkipAggregation {
Some(hash_table.partial_skip_table()?)
} else {
self.close_input();
None
};
hash_table.start_output()?;
timer.done();
self.produce_output(hash_table, &mut emitter).await?;
if let Some(hash_table) = skip_hash_table {
self.skip_rest_of_aggregation(hash_table, emitter).await?;
}
Ok(())
})
}
fn hit_soft_group_limit(
&self,
hash_table: &AggregateHashTable<PartialMarker>,
) -> bool {
self.group_values_soft_limit
.is_some_and(|limit| limit <= hash_table.building_group_count())
}
fn update_skip_aggregation_probe(&mut self, input_rows: usize, num_groups: usize) {
if let Some(probe) = self.skip_aggregation_probe.as_mut() {
probe.update_state(input_rows, num_groups);
}
}
fn should_skip_aggregation(&self) -> bool {
self.skip_aggregation_probe
.as_ref()
.is_some_and(|probe| probe.should_skip())
}
fn close_input(&mut self) {
let input_schema = self.input.schema();
self.input = Box::pin(EmptyRecordBatchStream::new(input_schema));
}
fn handle_input_batch(
&mut self,
batch: &RecordBatch,
hash_table: &mut AggregateHashTable<PartialMarker>,
) -> Result<HandleInputResult> {
let input_rows = batch.num_rows();
self.reduction_factor.add_total(input_rows);
hash_table.aggregate_batch(batch)?;
if self.hit_soft_group_limit(hash_table) {
return Ok(HandleInputResult::ReachedLimit);
}
self.update_skip_aggregation_probe(input_rows, hash_table.building_group_count());
if self.should_skip_aggregation() {
return Ok(HandleInputResult::SwitchToSkipAggregation);
}
let resize_result = self.reservation.try_resize(hash_table.memory_size());
match resize_result {
Ok(()) => Ok(HandleInputResult::ProcessNext),
Err(DataFusionError::ResourcesExhausted(_)) => Ok(HandleInputResult::OOM),
Err(e) => Err(e),
}
}
async fn emit_on_memory_pressure(
&mut self,
mut remaining_groups: RecordBatch,
emitter: &mut TryEmitter<RecordBatch, DataFusionError>,
hash_table_mem_size: usize,
) -> Result<()> {
let remaining_groups_memory = remaining_groups.get_array_memory_size();
match self
.reservation
.try_resize(hash_table_mem_size + remaining_groups_memory)
{
Ok(()) => {}
Err(DataFusionError::ResourcesExhausted(_)) => {
self.reservation.try_resize(hash_table_mem_size)?;
self.reduction_factor.add_part(remaining_groups.num_rows());
emitter
.emit(remaining_groups.record_output(&self.baseline_metrics))
.await;
return Ok(());
}
Err(error) => return Err(error),
}
while remaining_groups.num_rows() > self.batch_size {
let output = remaining_groups.slice(0, self.batch_size);
remaining_groups = remaining_groups.slice(
self.batch_size,
remaining_groups.num_rows() - self.batch_size,
);
self.reduction_factor.add_part(output.num_rows());
emitter
.emit(output.record_output(&self.baseline_metrics))
.await;
}
self.reduction_factor.add_part(remaining_groups.num_rows());
self.reservation.try_shrink(remaining_groups_memory)?;
emitter
.emit(remaining_groups.record_output(&self.baseline_metrics))
.await;
Ok(())
}
async fn produce_output(
&mut self,
mut hash_table: AggregateHashTable<PartialMarker>,
emitter: &mut TryEmitter<RecordBatch, DataFusionError>,
) -> Result<()> {
debug_assert!(!hash_table.is_building());
let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
let mut timer = elapsed_compute.timer();
loop {
let Some(batch) = hash_table.next_output_batch()? else {
self.reservation.try_resize(0)?;
return Ok(());
};
debug_assert!(batch.num_rows() > 0);
let _ = self.reservation.try_resize(hash_table.memory_size());
self.reduction_factor.add_part(batch.num_rows());
timer.done();
emitter
.emit(batch.record_output(&self.baseline_metrics))
.await;
timer = elapsed_compute.timer();
}
}
async fn skip_rest_of_aggregation(
&mut self,
mut hash_table: AggregateHashTable<PartialSkipMarker>,
mut emitter: TryEmitter<RecordBatch, DataFusionError>,
) -> Result<()> {
let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
while let Some(batch) = self.input.next().await.transpose()? {
if let Some(probe) = self.skip_aggregation_probe.as_mut() {
probe.record_skipped(&batch);
}
let result = {
let _timer = elapsed_compute.timer();
hash_table.convert_batch_to_state(&batch)?
};
emitter
.emit(result.record_output(&self.baseline_metrics))
.await;
}
self.close_input();
Ok(())
}
}
impl FinalHashAggregateStream {
pub fn new(
agg: &AggregateExec,
context: &Arc<TaskContext>,
partition: usize,
) -> Result<Self> {
debug_assert!(matches!(
agg.mode,
super::AggregateMode::Final | super::AggregateMode::FinalPartitioned
));
debug_assert_eq!(agg.group_clustering_mode, GroupClusteringMode::None);
let input = agg.input.execute(partition, Arc::clone(context))?;
Self::new_with_input(agg, context, partition, input)
}
pub(in crate::aggregates) fn new_with_input(
agg: &AggregateExec,
context: &Arc<TaskContext>,
partition: usize,
input: SendableRecordBatchStream,
) -> Result<Self> {
let schema = Arc::clone(&agg.schema);
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 hash_table = AggregateHashTable::<FinalMarker>::new(
agg,
partition,
Arc::clone(&schema),
batch_size,
)?;
let can_spill = context.runtime_env().disk_manager.tmp_files_enabled();
let spill_context = if can_spill {
Some(Box::new(AggregateSpill::try_new(
"FinalHashAggregateSpill",
agg,
context,
partition,
batch_size,
&GroupClusteringMode::None,
&input_schema,
spill_metrics,
)?))
} else {
None
};
let reservation =
MemoryConsumer::new(format!("FinalHashAggregateStream[{partition}]"))
.with_can_spill(can_spill)
.register(context.memory_pool());
reservation.try_grow(hash_table.memory_size())?;
Ok(Self {
schema,
input,
baseline_metrics,
reservation,
group_values_soft_limit: agg.limit_options().map(|config| config.limit()),
hash_table: Some(hash_table),
spill_context,
})
}
pub(crate) fn into_stream(self) -> SendableRecordBatchStream {
let schema = Arc::clone(&self.schema);
Box::pin(RecordBatchStreamAdapter::new(schema, self.create_stream()))
}
fn create_stream(mut self) -> impl Stream<Item = Result<RecordBatch>> {
async_try_stream(|emitter| async move {
let mut hash_table = self
.hash_table
.take()
.expect("hash_table should not be None");
let mut spill_context = self.spill_context.take();
self.consume_input(&mut hash_table, &mut spill_context)
.await?;
self.close_input();
match spill_context {
Some(spill_context) if spill_context.has_spills() => {
self.produce_output_from_spills(hash_table, spill_context, emitter)
.await?
}
spill_context => {
self.produce_output_from_memory(hash_table, spill_context, emitter)
.await?
}
}
Ok(())
})
}
fn close_input(&mut self) {
let input_schema = self.input.schema();
self.input = Box::pin(EmptyRecordBatchStream::new(input_schema));
}
fn hit_soft_group_limit(&self, hash_table: &AggregateHashTable<FinalMarker>) -> bool {
self.group_values_soft_limit
.is_some_and(|limit| limit <= hash_table.building_group_count())
}
fn reservation_size_for_table(
hash_table: &AggregateHashTable<FinalMarker>,
spill_context: Option<&AggregateSpill>,
) -> usize {
let table_size = hash_table.memory_size();
if spill_context.is_some() {
table_size.saturating_add(
hash_table
.building_group_count()
.saturating_mul(size_of::<u32>()),
)
} else {
table_size
}
}
async fn consume_input(
&mut self,
hash_table: &mut AggregateHashTable<FinalMarker>,
spill_context: &mut Option<Box<AggregateSpill>>,
) -> Result<()> {
let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
while let Some(batch) = self.input.next().await.transpose()? {
let _timer = elapsed_compute.timer();
hash_table.aggregate_batch(&batch)?;
let spilled = spill_context
.as_ref()
.is_some_and(|context| context.has_spills());
if self.hit_soft_group_limit(hash_table) && !spilled {
break;
}
let resize_result =
self.reservation
.try_resize(Self::reservation_size_for_table(
hash_table,
spill_context.as_deref(),
));
match resize_result {
Ok(()) => {}
Err(e @ DataFusionError::ResourcesExhausted(_)) => {
let spill_context = spill_context.as_mut().ok_or_else(|| e.context(
"Final hash aggregate cannot spill because temporary files are not enabled in the DiskManager",
))?;
assert_ne_or_internal_err!(
hash_table.building_group_count(),
0,
"Final hash aggregate ran out of memory with no aggregated groups"
);
let result = hash_table
.take_state_batch()
.and_then(|batch| spill_context.sort_and_spill(batch));
self.reservation
.try_resize(hash_table.memory_size())
.map_err(|e| {
e.context(
"Decreasing allocation after spilling should succeed",
)
})?;
result?;
}
Err(e) => return Err(e),
}
}
Ok(())
}
async fn produce_output_from_spills(
&mut self,
mut hash_table: AggregateHashTable<FinalMarker>,
mut spill_context: Box<AggregateSpill>,
mut emitter: TryEmitter<RecordBatch, DataFusionError>,
) -> Result<()> {
let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
let timer = elapsed_compute.timer();
hash_table
.take_state_batch()
.and_then(|batch| spill_context.sort_and_spill(batch))?;
let mut output_stream =
self.switch_to_clustered_final_stream(hash_table, spill_context)?;
timer.done();
while let Some(batch) = output_stream.next().await.transpose()? {
emitter.emit(batch).await;
}
Ok(())
}
fn switch_to_clustered_final_stream(
&mut self,
hash_table: AggregateHashTable<FinalMarker>,
spill_context: Box<AggregateSpill>,
) -> Result<SendableRecordBatchStream> {
let metrics = ClusteredAggregateTableMetrics::from_hash_table(&hash_table);
drop(hash_table);
self.reservation.try_resize(0)?;
spill_context.into_replay_stream(
&self.baseline_metrics,
metrics,
self.reservation.new_empty(),
)
}
async fn produce_output_from_memory(
&mut self,
mut hash_table: AggregateHashTable<FinalMarker>,
spill_context: Option<Box<AggregateSpill>>,
mut emitter: TryEmitter<RecordBatch, DataFusionError>,
) -> Result<()> {
let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
let mut timer = elapsed_compute.timer();
hash_table.start_output()?;
loop {
let Some(batch) = hash_table.next_output_batch()? else {
self.reservation.try_resize(0)?;
return Ok(());
};
match self.reservation.try_resize(hash_table.memory_size()) {
Ok(()) => {}
Err(e @ DataFusionError::ResourcesExhausted(_)) => {
let spill_context = spill_context.ok_or_else(|| e.context(
"Final hash aggregate cannot spill its output because temporary files are not enabled in the DiskManager",
))?;
let remaining =
std::iter::from_fn(|| hash_table.next_output_batch().transpose());
let mut output = spill_context.spill_output(
Arc::clone(&self.schema),
std::iter::once(Ok(batch)).chain(remaining),
)?;
drop(hash_table);
self.reservation.try_resize(0)?;
timer.done();
while let Some(batch) = output.next().await.transpose()? {
emitter
.emit(batch.record_output(&self.baseline_metrics))
.await;
}
return Ok(());
}
Err(e) => return Err(e),
}
timer.done();
emitter
.emit(batch.record_output(&self.baseline_metrics))
.await;
timer = elapsed_compute.timer();
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;
use super::*;
use crate::aggregates::GroupClusteringMode;
use crate::aggregates::clustered_test_util::collect_under_limit;
use crate::aggregates::{AggregateMode, PhysicalGroupBy};
use crate::common::collect;
use crate::execution_plan::ExecutionPlan;
use crate::test::TestMemoryExec;
use crate::test::exec::BarrierExec;
use arrow::array::{ArrayRef, AsArray, Int32Array, Int64Array, StringViewArray};
use arrow::datatypes::{DataType, Field, Int32Type, Schema};
use datafusion_common::Result;
use datafusion_execution::config::SessionConfig;
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryPool, UnboundedMemoryPool,
};
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
use datafusion_functions_aggregate::approx_distinct::approx_distinct_udaf;
use datafusion_functions_aggregate::count::count_udaf;
use datafusion_functions_aggregate::{min_max::min_udaf, sum::sum_udaf};
use datafusion_physical_expr::aggregate::AggregateExprBuilder;
use datafusion_physical_expr::expressions::col;
use futures::channel::mpsc;
use futures::{FutureExt, StreamExt};
use std::collections::BTreeMap;
#[tokio::test]
async fn test_partial_hash_stream_double_emission_race_condition_bug() -> Result<()> {
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; let num_groups = batch_size + 100;
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]];
let runtime = RuntimeEnvBuilder::default()
.with_memory_limit(5 * 1024, 1.0) .build_arc()?;
let mut task_ctx = TaskContext::default().with_runtime(runtime);
let mut session_config = task_ctx.session_config().clone();
session_config = session_config.set(
"datafusion.execution.batch_size",
&datafusion_common::ScalarValue::UInt64(Some(1024)),
);
session_config = session_config.set(
"datafusion.execution.skip_partial_aggregation_probe_rows_threshold",
&datafusion_common::ScalarValue::UInt64(Some(50)),
);
session_config = session_config.set(
"datafusion.execution.skip_partial_aggregation_probe_ratio_threshold",
&datafusion_common::ScalarValue::Float64(Some(0.8)),
);
task_ctx = task_ctx.with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
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, &Arc::clone(&task_ctx), 0)?
.into_stream();
let mut results = Vec::new();
while let Some(result) = stream.next().await {
let batch = result?;
results.push(batch);
}
let mut total_output_groups = 0;
for batch in &results {
total_output_groups += batch.num_rows();
}
assert_eq!(
total_output_groups, num_groups,
"Unexpected number of groups",
);
assert_eq!(
aggregate_exec
.metrics()
.unwrap()
.sum_by_name("early_emit_count")
.unwrap()
.as_usize(),
0
);
let runtime = RuntimeEnvBuilder::default()
.with_memory_limit(5 * 1024, 1.0)
.build_arc()?;
let session_config = task_ctx.session_config().clone().set(
"datafusion.execution.skip_partial_aggregation_probe_ratio_threshold",
&datafusion_common::ScalarValue::Float64(Some(2.0)),
);
let no_skip_task_ctx = Arc::new(
TaskContext::default()
.with_runtime(runtime)
.with_session_config(session_config),
);
let mut stream =
PartialHashAggregateStream::new(&aggregate_exec, &no_skip_task_ctx, 0)?
.into_stream();
while let Some(result) = stream.next().await {
result?;
}
assert_eq!(
aggregate_exec
.metrics()
.unwrap()
.sum_by_name("early_emit_count")
.unwrap()
.as_usize(),
1
);
Ok(())
}
#[tokio::test]
async fn test_partial_hash_stream_skip_aggregation_probe_not_locked_until_skip()
-> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("group_col", DataType::Int32, false),
Field::new("value_col", DataType::Int32, false),
]));
let probe_rows_threshold = 100;
let probe_ratio_threshold = 0.8;
let batch1_rows = 100;
let batch1_groups = 10;
let mut group_ids_batch1 = Vec::new();
for i in 0..batch1_rows {
group_ids_batch1.push((i % batch1_groups) as i32);
}
let values_batch1: Vec<i32> = vec![1; batch1_rows];
let batch1 = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(group_ids_batch1)),
Arc::new(Int32Array::from(values_batch1)),
],
)?;
let batch2_rows = 360;
let batch2_groups = 360;
let group_ids_batch2: Vec<i32> = (batch1_groups..(batch1_groups + batch2_groups))
.map(|x| x as i32)
.collect();
let values_batch2: Vec<i32> = vec![1; batch2_rows];
let batch2 = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(group_ids_batch2)),
Arc::new(Int32Array::from(values_batch2)),
],
)?;
let batch3_rows = 100;
let batch3_groups = 100;
let batch3_start_group = batch1_groups + batch2_groups;
let group_ids_batch3: Vec<i32> = (batch3_start_group
..(batch3_start_group + batch3_groups))
.map(|x| x as i32)
.collect();
let values_batch3: Vec<i32> = vec![1; batch3_rows];
let batch3 = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(group_ids_batch3)),
Arc::new(Int32Array::from(values_batch3)),
],
)?;
let input_partitions = vec![vec![batch1, batch2, batch3]];
let runtime = RuntimeEnvBuilder::default().build_arc()?;
let mut task_ctx = TaskContext::default().with_runtime(runtime);
let mut session_config = task_ctx.session_config().clone();
session_config = session_config.set(
"datafusion.execution.skip_partial_aggregation_probe_rows_threshold",
&datafusion_common::ScalarValue::UInt64(Some(probe_rows_threshold)),
);
session_config = session_config.set(
"datafusion.execution.skip_partial_aggregation_probe_ratio_threshold",
&datafusion_common::ScalarValue::Float64(Some(probe_ratio_threshold)),
);
task_ctx = task_ctx.with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
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, &Arc::clone(&task_ctx), 0)?
.into_stream();
let mut results = Vec::new();
while let Some(result) = stream.next().await {
let batch = result?;
results.push(batch);
}
let metrics = aggregate_exec.metrics().unwrap();
let skipped_rows = metrics
.sum_by_name("skipped_aggregation_rows")
.map(|m| m.as_usize())
.unwrap_or(0);
assert_eq!(
skipped_rows, batch3_rows,
"Expected batch 3's rows ({batch3_rows}) to be skipped",
);
Ok(())
}
fn partial_stream_under_memory_limit(
memory_limit: usize,
batch_size: usize,
num_groups: usize,
) -> Result<(
SendableRecordBatchStream,
Arc<BarrierExec>,
Arc<datafusion_execution::runtime_env::RuntimeEnv>,
)> {
let schema = Arc::new(Schema::new(vec![
Field::new("group_col", DataType::Int32, false),
Field::new("value_col", DataType::Int64, false),
]));
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]];
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)),
)
.set(
"datafusion.execution.skip_partial_aggregation_probe_ratio_threshold",
&datafusion_common::ScalarValue::Float64(Some(1.0)),
);
task_ctx = task_ctx.with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
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 input = Arc::new(
BarrierExec::new(input_partitions, Arc::clone(&schema))
.without_start_barrier()
.with_finish_barrier()
.with_log(false),
);
let aggregate_exec = AggregateExec::try_new(
AggregateMode::Partial,
PhysicalGroupBy::new_single(group_expr),
aggr_expr,
vec![None],
Arc::clone(&input) as Arc<dyn ExecutionPlan>,
Arc::clone(&schema),
)?;
let stream =
PartialHashAggregateStream::new(&aggregate_exec, &task_ctx, 0)?.into_stream();
Ok((stream, input, runtime))
}
#[tokio::test]
async fn test_partial_hash_stream_accounts_held_batch_on_memory_pressure_while_slicing()
-> Result<()> {
let batch_size = 1024;
let num_groups = 4 * batch_size;
let memory_limit = 100 * 1024;
let (mut stream, input, runtime) =
partial_stream_under_memory_limit(memory_limit, batch_size, num_groups)?;
let first = tokio::time::timeout(Duration::from_secs(5), stream.next())
.await
.expect("early emit should occur")
.expect("stream ended early")?;
assert_eq!(first.num_rows(), batch_size);
let held_size = first.get_array_memory_size();
assert!(runtime.memory_pool.reserved() >= held_size);
let second = stream.next().await.expect("stream ended early")?;
assert_eq!(second.num_rows(), batch_size);
assert_eq!(
first
.column(0)
.as_primitive::<Int32Type>()
.values()
.inner()
.data_ptr(),
second
.column(0)
.as_primitive::<Int32Type>()
.values()
.inner()
.data_ptr(),
"batches should slice one materialized state batch"
);
input.wait_finish().await;
let mut total_rows = first.num_rows() + second.num_rows();
while let Some(batch) = stream.next().await {
total_rows += batch?.num_rows();
}
assert_eq!(total_rows, num_groups);
Ok(())
}
#[tokio::test]
async fn test_partial_hash_stream_emits_whole_batch_when_held_batch_does_not_fit()
-> Result<()> {
let batch_size = 1024;
let num_groups = 4 * batch_size;
let memory_limit = 32 * 1024;
let (mut stream, input, runtime) =
partial_stream_under_memory_limit(memory_limit, batch_size, num_groups)?;
let first = tokio::time::timeout(Duration::from_secs(5), stream.next())
.await
.expect("early emit should occur")
.expect("stream ended early")?;
assert_eq!(first.num_rows(), num_groups);
assert!(first.get_array_memory_size() > memory_limit);
assert!(runtime.memory_pool.reserved() < first.get_array_memory_size());
input.wait_finish().await;
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(())
}
#[tokio::test]
async fn test_partial_hash_stream_releases_held_batch_after_last_slice() -> Result<()>
{
let batch_size = 1024;
let num_slices = 4;
let num_groups = num_slices * batch_size;
let memory_limit = 100 * 1024;
let (mut stream, input, runtime) =
partial_stream_under_memory_limit(memory_limit, batch_size, num_groups)?;
let mut held_size = 0;
for slice_idx in 0..num_slices {
let slice = if slice_idx == 0 {
tokio::time::timeout(Duration::from_secs(5), stream.next())
.await
.expect("early emit should occur")
.expect("stream ended early")?
} else {
stream.next().await.expect("stream ended early")?
};
assert_eq!(slice.num_rows(), batch_size);
held_size = slice.get_array_memory_size();
if slice_idx + 1 < num_slices {
assert!(runtime.memory_pool.reserved() >= held_size);
} else {
assert!(runtime.memory_pool.reserved() < held_size);
}
}
assert!(held_size > 0);
input.wait_finish().await;
let mut total_rows = num_groups;
while let Some(batch) = stream.next().await {
total_rows += batch?.num_rows();
}
assert_eq!(total_rows, num_groups);
Ok(())
}
#[derive(Clone, Copy)]
enum Finish {
Collect,
DropDuringReplay,
InputError,
}
#[tokio::test]
async fn final_hash_spill_replay_with_other_partitions_holding_state() -> Result<()> {
for spills in [1, 2, 3] {
run_shared_pool_case(spills, Some(1024 * 1024), Finish::Collect).await?;
}
run_shared_pool_case(0, None, Finish::Collect).await
}
#[tokio::test]
async fn final_hash_spill_replay_releases_memory_on_drop() -> Result<()> {
run_shared_pool_case(1, Some(1024 * 1024), Finish::DropDuringReplay).await
}
#[tokio::test]
async fn final_hash_spill_releases_memory_on_input_error() -> Result<()> {
run_shared_pool_case(1, Some(1024 * 1024), Finish::InputError).await
}
async fn run_shared_pool_case(
spills: usize,
limit: Option<usize>,
finish: Finish,
) -> Result<()> {
const PARTITIONS: usize = 4;
const HELD_BYTES: usize = 512 * 1024;
const MAX_BATCHES: i64 = 1000;
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),
Field::new("s", DataType::Utf8View, false),
]));
let groups = PhysicalGroupBy::new_single(vec![
(col("a", &schema)?, "a".into()),
(col("b", &schema)?, "b".into()),
]);
let expressions = vec![
Arc::new(
AggregateExprBuilder::new(sum_udaf(), vec![col("v", &schema)?])
.schema(Arc::clone(&schema))
.alias("sum")
.build()?,
),
Arc::new(
AggregateExprBuilder::new(min_udaf(), vec![col("s", &schema)?])
.schema(Arc::clone(&schema))
.alias("min")
.build()?,
),
];
let empty = TestMemoryExec::try_new_exec(&[vec![]], Arc::clone(&schema), None)?;
let partial = AggregateExec::try_new(
AggregateMode::Partial,
groups.clone(),
expressions.clone(),
vec![None; 2],
empty,
Arc::clone(&schema),
)?;
let partial_schema = partial.schema();
let input = TestMemoryExec::try_new_exec(
&vec![vec![]; PARTITIONS],
Arc::clone(&partial_schema),
None,
)?;
let aggregate = AggregateExec::try_new(
AggregateMode::FinalPartitioned,
groups.as_final(),
expressions,
vec![None; 2],
input,
schema,
)?;
assert_eq!(
aggregate.group_clustering_mode(),
&GroupClusteringMode::None
);
let pool: Arc<dyn MemoryPool> = match limit {
Some(limit) => Arc::new(GreedyMemoryPool::new(limit)),
None => Arc::new(UnboundedMemoryPool::default()),
};
let context = Arc::new(
TaskContext::default()
.with_session_config(SessionConfig::new().with_batch_size(128))
.with_runtime(
RuntimeEnvBuilder::new()
.with_memory_pool(Arc::clone(&pool))
.build_arc()?,
),
);
let make_stream = |partition| -> Result<_> {
let (sender, receiver) = mpsc::unbounded();
let input = Box::pin(RecordBatchStreamAdapter::new(
Arc::clone(&partial_schema),
receiver,
));
let stream = FinalHashAggregateStream::new_with_input(
&aggregate, &context, partition, input,
)?
.into_stream();
Ok((sender, stream))
};
let mut streams = vec![];
let mut senders = vec![];
for partition in 1..PARTITIONS {
let (sender, stream) = make_stream(partition)?;
senders.push(sender);
streams.push(stream);
}
let mut expected = BTreeMap::new();
let mut make_batch = |partition: i64, start: i64| {
for value in start..start + 128 {
let entry = expected
.entry((
partition,
if partition == 0 && value % 128 == 0 {
0
} else {
value
},
))
.or_insert_with(|| (0, (value % 2).to_string()));
entry.0 += value * 2;
}
RecordBatch::try_new(
Arc::clone(&partial_schema),
vec![
Arc::new(Int64Array::from(vec![partition; 128])),
Arc::new(Int64Array::from_iter_values((start..start + 128).map(
|value| {
if partition == 0 && value % 128 == 0 {
0
} else {
value
}
},
))),
Arc::new(Int64Array::from_iter_values(
(start..start + 128).map(|v| v * 2),
)),
Arc::new(StringViewArray::from_iter_values(
(start..start + 128).map(|v| if v % 2 == 0 { "0" } else { "1" }),
)),
],
)
.unwrap()
};
let mut held_batches = 0;
while pool.reserved() < HELD_BYTES {
assert!(held_batches < MAX_BATCHES, "held state stays small");
for (partition, (sender, stream)) in
senders.iter().zip(streams.iter_mut()).enumerate()
{
let partition = partition + 1;
sender
.unbounded_send(Ok(make_batch(partition as i64, held_batches * 128)))
.unwrap();
assert!(stream.next().now_or_never().is_none());
}
held_batches += 1;
}
let held = pool.reserved();
let spill_count = || aggregate.metrics().unwrap().spill_count().unwrap();
assert_eq!(spill_count(), 0);
let (partition_zero_sender, mut first) = make_stream(0)?;
let mut batches = 0;
loop {
let done = if spills == 0 {
batches == 70
} else {
spill_count() >= spills
};
if done {
break;
}
assert!(batches < MAX_BATCHES, "partition 0 did not spill");
partition_zero_sender
.unbounded_send(Ok(make_batch(0, batches * 128)))
.unwrap();
assert!(first.next().now_or_never().is_none());
batches += 1;
}
for _ in 0..8 {
partition_zero_sender
.unbounded_send(Ok(make_batch(0, batches * 128)))
.unwrap();
assert!(first.next().now_or_never().is_none());
batches += 1;
}
assert!(spill_count() >= spills);
assert_eq!(spill_count() == 0, spills == 0);
match finish {
Finish::Collect => {
partition_zero_sender.close_channel();
let mut output = collect(first).await?;
assert_eq!(pool.reserved(), held);
for sender in &senders {
sender.close_channel();
}
for stream in streams.drain(..) {
output.extend(collect(stream).await?);
}
let mut actual = BTreeMap::new();
for batch in output {
let a = batch
.column(0)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
let b = batch
.column(1)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
let sum = batch
.column(2)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
let min = batch
.column(3)
.as_any()
.downcast_ref::<StringViewArray>()
.unwrap();
for row in 0..batch.num_rows() {
assert!(
actual
.insert(
(a.value(row), b.value(row)),
(sum.value(row), min.value(row).to_string())
)
.is_none()
);
}
}
assert_eq!(actual, expected);
assert_eq!(spill_count() == 0, spills == 0);
}
Finish::DropDuringReplay => {
partition_zero_sender.close_channel();
first.next().await.unwrap()?;
assert!(pool.reserved() > held);
drop(first);
assert_eq!(pool.reserved(), held);
}
Finish::InputError => {
partition_zero_sender
.unbounded_send(datafusion_common::exec_err!(
"injected input failure"
))
.unwrap();
let error = first.next().await.unwrap().unwrap_err();
assert!(error.to_string().contains("injected input failure"));
assert_eq!(pool.reserved(), held);
drop(first);
}
}
drop(streams);
assert_eq!(pool.reserved(), 0);
Ok(())
}
#[tokio::test]
async fn emitted_states_release_accumulator_scratch() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("k", DataType::Int64, false),
Field::new("v", DataType::Int64, false),
]));
let batches = [0..8192, 8192..16384, 16384..24576]
.into_iter()
.map(|range| {
let values: ArrayRef = Arc::new(Int64Array::from_iter_values(range));
RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::clone(&values), values],
)
})
.collect::<Result<Vec<_>, _>>()?;
let input = TestMemoryExec::try_new_exec(&[batches], Arc::clone(&schema), None)?;
let aggregate = AggregateExec::try_new(
AggregateMode::Partial,
PhysicalGroupBy::new_single(vec![(col("k", &schema)?, "k".into())]),
vec![Arc::new(
AggregateExprBuilder::new(
approx_distinct_udaf(),
vec![col("v", &schema)?],
)
.schema(Arc::clone(&schema))
.alias("approx_distinct")
.build()?,
)],
vec![None],
input,
schema,
)?;
assert_eq!(
aggregate.group_clustering_mode(),
&GroupClusteringMode::None
);
let output = collect_under_limit(&aggregate, 64 * 1024).await?;
assert_eq!(output.iter().map(|b| b.num_rows()).sum::<usize>(), 24576);
assert!(
aggregate
.metrics()
.unwrap()
.sum_by_name("early_emit_count")
.unwrap()
.as_usize()
> 0
);
Ok(())
}
}