use crate::aggregates::aggregate_argument::AggregateArgument;
use crate::aggregates::group_values::{
AccumulatorPhase, AggregateAccumulatorMetrics, AggregateArgumentMetrics,
aggregate_sub_metrics,
};
use crate::aggregates::{
AccumulatorItem, AggrDynFilter, AggregateInputMode, AggregateMode,
AggregateOutputMode, DynamicFilterAggregateType, aggregate_expressions,
aggregate_metric_label, create_accumulators_with_metrics,
};
use crate::metrics::{BaselineMetrics, RecordOutput};
use crate::stream::EmptyRecordBatchStream;
use crate::{RecordBatchStream, SendableRecordBatchStream};
use arrow::array::ArrayRef;
use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use datafusion_common::{Result, ScalarValue, internal_datafusion_err, internal_err};
use datafusion_execution::TaskContext;
use datafusion_expr::Operator;
use datafusion_physical_expr::PhysicalExpr;
use datafusion_physical_expr::expressions::{BinaryExpr, lit};
use futures::stream::BoxStream;
use itertools::Itertools;
use std::borrow::Cow;
use std::cmp::Ordering;
use std::sync::Arc;
use std::task::{Context, Poll};
use super::AggregateExec;
use crate::filter::batch_filter;
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};
use futures::stream::{Stream, StreamExt};
pub(crate) struct AggregateStream {
stream: BoxStream<'static, Result<RecordBatch>>,
schema: SchemaRef,
}
struct AggregateStreamInner {
schema: SchemaRef,
mode: AggregateMode,
input: SendableRecordBatchStream,
aggregate_arguments: Vec<Vec<AggregateArgument>>,
filter_expressions: Arc<[Option<Arc<dyn PhysicalExpr>>]>,
aggregate_argument_metrics: AggregateArgumentMetrics,
aggregate_accumulator_metrics: AggregateAccumulatorMetrics,
accumulators: Vec<AccumulatorItem>,
agg_dyn_filter_state: Option<Arc<AggrDynFilter>>,
finished: bool,
baseline_metrics: BaselineMetrics,
reservation: MemoryReservation,
}
impl AggregateStreamInner {
fn build_dynamic_filter_from_accumulator_bounds(
&self,
) -> Result<Arc<dyn PhysicalExpr>> {
let Some(filter_state) = self.agg_dyn_filter_state.as_ref() else {
return internal_err!(
"`build_dynamic_filter_from_accumulator_bounds()` is only called when dynamic filter is enabled"
);
};
let mut predicates: Vec<Arc<dyn PhysicalExpr>> =
Vec::with_capacity(filter_state.accumulator_dyn_filter_info.len());
for acc_info in &filter_state.accumulator_dyn_filter_info {
let bound = {
let guard = acc_info.shared_bound.lock();
if (*guard).is_null() {
return Ok(lit(true));
}
guard.clone()
};
let agg_args = self
.aggregate_arguments
.get(acc_info.aggr_index)
.ok_or_else(|| {
internal_datafusion_err!(
"Invalid aggregate expression index {} for dynamic filter",
acc_info.aggr_index
)
})?;
let column_expr = agg_args
.first()
.ok_or_else(|| {
internal_datafusion_err!(
"Aggregate expression at index {} expected a single argument",
acc_info.aggr_index
)
})?
.expr();
let literal = lit(bound);
let predicate: Arc<dyn PhysicalExpr> = match acc_info.aggr_type {
DynamicFilterAggregateType::Min => Arc::new(BinaryExpr::new(
Arc::clone(column_expr),
Operator::Lt,
literal,
)),
DynamicFilterAggregateType::Max => Arc::new(BinaryExpr::new(
Arc::clone(column_expr),
Operator::Gt,
literal,
)),
};
predicates.push(predicate);
}
let combined = predicates.into_iter().reduce(|acc, pred| {
Arc::new(BinaryExpr::new(acc, Operator::Or, pred)) as Arc<dyn PhysicalExpr>
});
Ok(combined.unwrap_or_else(|| lit(true)))
}
fn maybe_update_dyn_filter(&mut self) -> Result<()> {
let Some(filter_state) = self.agg_dyn_filter_state.as_ref() else {
return Ok(());
};
let mut bounds_changed = false;
for acc_info in &filter_state.accumulator_dyn_filter_info {
let acc =
self.accumulators
.get_mut(acc_info.aggr_index)
.ok_or_else(|| {
internal_datafusion_err!(
"Invalid accumulator index {} for dynamic filter",
acc_info.aggr_index
)
})?;
let current_bound = acc.evaluate()?;
{
let mut bound = acc_info.shared_bound.lock();
let new_bound = match acc_info.aggr_type {
DynamicFilterAggregateType::Max => {
scalar_max(&bound, ¤t_bound)?
}
DynamicFilterAggregateType::Min => {
scalar_min(&bound, ¤t_bound)?
}
};
if new_bound != *bound {
*bound = new_bound;
bounds_changed = true;
}
}
}
if bounds_changed {
let predicate = self.build_dynamic_filter_from_accumulator_bounds()?;
filter_state.filter.update(predicate)?;
}
Ok(())
}
}
fn scalar_min(v1: &ScalarValue, v2: &ScalarValue) -> Result<ScalarValue> {
if let Some(result) = scalar_cmp_null_short_circuit(v1, v2) {
return Ok(result);
}
match v1.partial_cmp(v2) {
Some(Ordering::Less | Ordering::Equal) => Ok(v1.clone()),
Some(Ordering::Greater) => Ok(v2.clone()),
None => datafusion_common::internal_err!(
"cannot compare values of different or incompatible types: {v1:?} vs {v2:?}"
),
}
}
fn scalar_max(v1: &ScalarValue, v2: &ScalarValue) -> Result<ScalarValue> {
if let Some(result) = scalar_cmp_null_short_circuit(v1, v2) {
return Ok(result);
}
match v1.partial_cmp(v2) {
Some(Ordering::Greater | Ordering::Equal) => Ok(v1.clone()),
Some(Ordering::Less) => Ok(v2.clone()),
None => datafusion_common::internal_err!(
"cannot compare values of different or incompatible types: {v1:?} vs {v2:?}"
),
}
}
fn scalar_cmp_null_short_circuit(
v1: &ScalarValue,
v2: &ScalarValue,
) -> Option<ScalarValue> {
match (v1.is_null(), v2.is_null()) {
(true, _) => Some(v2.clone()),
(_, true) => Some(v1.clone()),
_ => None,
}
}
fn prepend_grouping_id_column(
mut columns: Vec<Arc<dyn arrow::array::Array>>,
grouping_id: Option<&ScalarValue>,
) -> Result<Vec<Arc<dyn arrow::array::Array>>> {
if let Some(id) = grouping_id {
let num_rows = columns.first().map(|array| array.len()).unwrap_or(1);
let grouping_ids = id.to_array_of_size(num_rows)?;
columns.insert(0, grouping_ids);
}
Ok(columns)
}
impl AggregateStream {
pub fn new(
agg: &AggregateExec,
context: &Arc<TaskContext>,
partition: usize,
) -> Result<Self> {
let agg_schema = Arc::clone(&agg.schema);
let agg_filter_expr = agg.clone_filter_exprs();
let baseline_metrics = BaselineMetrics::new(&agg.metrics, partition);
let input = agg.input.execute(partition, Arc::clone(context))?;
let aggregate_arguments = aggregate_expressions(agg.aggr_expr(), &agg.mode, 0)?
.into_iter()
.map(|exprs| exprs.into_iter().map(AggregateArgument::new).collect())
.collect();
let filter_expressions = match agg.mode.input_mode() {
AggregateInputMode::Raw => agg_filter_expr,
AggregateInputMode::Partial => vec![None; agg.aggr_expr().len()].into(),
};
let aggregate_labels = agg
.aggr_expr()
.iter()
.map(|agg_expr| aggregate_metric_label(agg_expr))
.collect::<Vec<_>>();
let accumulators = create_accumulators_with_metrics(
agg.aggr_expr(),
&aggregate_sub_metrics(
&agg.metrics,
partition,
aggregate_labels.iter().cloned(),
),
)?;
let aggregate_argument_metrics = AggregateArgumentMetrics::new(
&agg.metrics,
partition,
aggregate_labels.clone(),
);
let aggregate_accumulator_metrics = AggregateAccumulatorMetrics::new(
&agg.metrics,
partition,
aggregate_labels,
accumulator_phases(&agg.mode),
);
let reservation = MemoryConsumer::new(format!("AggregateStream[{partition}]"))
.register(context.memory_pool());
reservation.try_grow(accumulators.iter().map(|accum| accum.size()).sum())?;
let mut maybe_dynamic_filter = match agg.dynamic_filter.as_ref() {
Some(filter) => Some(Arc::clone(filter)),
_ => None,
};
if !context
.session_config()
.options()
.optimizer
.enable_aggregate_dynamic_filter_pushdown
{
maybe_dynamic_filter = None;
}
let inner = AggregateStreamInner {
schema: Arc::clone(&agg.schema),
mode: agg.mode,
input,
baseline_metrics,
aggregate_arguments,
filter_expressions,
aggregate_argument_metrics,
aggregate_accumulator_metrics,
accumulators,
reservation,
finished: false,
agg_dyn_filter_state: maybe_dynamic_filter,
};
let stream = futures::stream::unfold(inner, |mut this| async move {
if this.finished {
return None;
}
loop {
let result = match this.input.next().await {
Some(Ok(batch)) => {
let result = {
let elapsed_compute = this.baseline_metrics.elapsed_compute();
let _timer = elapsed_compute.timer(); aggregate_batch(
&this.mode,
&batch,
&mut this.accumulators,
&mut this.aggregate_arguments,
&this.filter_expressions,
&this.aggregate_argument_metrics,
&this.aggregate_accumulator_metrics,
)
};
let result = result.and_then(|allocated| {
this.maybe_update_dyn_filter()?;
Ok(allocated)
});
match result
.and_then(|allocated| this.reservation.try_grow(allocated))
{
Ok(_) => continue,
Err(e) => Err(e),
}
}
Some(Err(e)) => Err(e),
None => {
this.finished = true;
let input_schema = this.input.schema();
this.input = Box::pin(EmptyRecordBatchStream::new(input_schema));
let timer = this.baseline_metrics.elapsed_compute().timer();
let result = finalize_aggregation_with_metrics(
&mut this.accumulators,
&this.mode,
&this.aggregate_accumulator_metrics,
)
.and_then(|columns| prepend_grouping_id_column(columns, None))
.and_then(|columns| {
RecordBatch::try_new(Arc::clone(&this.schema), columns)
.map_err(Into::into)
})
.record_output(&this.baseline_metrics);
timer.done();
result
}
};
this.finished = true;
return Some((result, this));
}
});
let stream = stream.fuse();
let stream = Box::pin(stream);
Ok(Self {
schema: agg_schema,
stream,
})
}
}
impl Stream for AggregateStream {
type Item = Result<RecordBatch>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let this = &mut *self;
this.stream.poll_next_unpin(cx)
}
}
impl RecordBatchStream for AggregateStream {
fn schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
}
fn aggregate_batch(
mode: &AggregateMode,
batch: &RecordBatch,
accumulators: &mut [AccumulatorItem],
arguments: &mut [Vec<AggregateArgument>],
filters: &[Option<Arc<dyn PhysicalExpr>>],
aggregate_argument_metrics: &AggregateArgumentMetrics,
aggregate_accumulator_metrics: &AggregateAccumulatorMetrics,
) -> Result<usize> {
let mut allocated = 0usize;
accumulators
.iter_mut()
.zip(arguments)
.zip(filters)
.enumerate()
.try_for_each(|(index, ((accum, arguments), filter))| {
let values = aggregate_argument_metrics.time(index, || {
let batch = match filter {
Some(filter) => Cow::Owned(batch_filter(batch, filter)?),
None => Cow::Borrowed(batch),
};
arguments
.iter_mut()
.map(|argument| argument.evaluate(batch.as_ref()))
.collect::<Result<Vec<_>>>()
})?;
let size_pre = accum.size();
let res = match mode.input_mode() {
AggregateInputMode::Raw => aggregate_accumulator_metrics.time(
index,
AccumulatorPhase::Update,
|| accum.update_batch(&values),
),
AggregateInputMode::Partial => aggregate_accumulator_metrics.time(
index,
AccumulatorPhase::Merge,
|| accum.merge_batch(&values),
),
};
let size_post = accum.size();
allocated += size_post.saturating_sub(size_pre);
res
})?;
Ok(allocated)
}
fn accumulator_phases(mode: &AggregateMode) -> &'static [AccumulatorPhase] {
match mode {
AggregateMode::Partial => &[AccumulatorPhase::Update, AccumulatorPhase::State],
AggregateMode::PartialReduce => {
&[AccumulatorPhase::Merge, AccumulatorPhase::State]
}
AggregateMode::Final | AggregateMode::FinalPartitioned => {
&[AccumulatorPhase::Merge, AccumulatorPhase::Evaluate]
}
AggregateMode::Single | AggregateMode::SinglePartitioned => {
&[AccumulatorPhase::Update, AccumulatorPhase::Evaluate]
}
}
}
fn finalize_aggregation_with_metrics(
accumulators: &mut [AccumulatorItem],
mode: &AggregateMode,
metrics: &AggregateAccumulatorMetrics,
) -> Result<Vec<ArrayRef>> {
match mode.output_mode() {
AggregateOutputMode::Final => accumulators
.iter_mut()
.enumerate()
.map(|(index, accumulator)| {
metrics
.time(index, AccumulatorPhase::Evaluate, || accumulator.evaluate())
.and_then(|value| value.to_array())
})
.collect(),
AggregateOutputMode::Partial => accumulators
.iter_mut()
.enumerate()
.map(|(index, accumulator)| {
metrics
.time(index, AccumulatorPhase::State, || accumulator.state())
.and_then(|values| {
values
.iter()
.map(|value| value.to_array())
.collect::<Result<Vec<_>>>()
})
})
.flatten_ok()
.collect(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aggregates::PhysicalGroupBy;
use crate::common::collect as collect_stream;
use crate::metrics::{MetricValue, MetricsSet};
use crate::test::TestMemoryExec;
use crate::{ExecutionPlan, collect};
use arrow::array::{Float64Array, Int32Array, UInt32Array};
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_functions_aggregate::{
array_agg::array_agg_udaf,
min_max::{max_udaf, min_udaf},
sum::sum_udaf,
};
use datafusion_physical_expr::aggregate::{
AggregateExprBuilder, AggregateFunctionExpr,
};
use datafusion_physical_expr::expressions::col;
fn sum_aggregate(
schema: &SchemaRef,
column: &str,
alias: &str,
) -> Result<Arc<AggregateFunctionExpr>> {
Ok(Arc::new(
AggregateExprBuilder::new(sum_udaf(), vec![col(column, schema)?])
.schema(Arc::clone(schema))
.alias(alias)
.build()?,
))
}
fn distinct_array_aggregate(
schema: &SchemaRef,
column: &str,
alias: &str,
) -> Result<Arc<AggregateFunctionExpr>> {
Ok(Arc::new(
AggregateExprBuilder::new(array_agg_udaf(), vec![col(column, schema)?])
.schema(Arc::clone(schema))
.distinct()
.alias(alias)
.build()?,
))
}
fn aggregate_metrics(metrics: &MetricsSet, phase: &str) -> Vec<(String, String)> {
let mut result = metrics
.iter()
.filter_map(|metric| match metric.value() {
MetricValue::Time { name, .. }
if name
.strip_prefix("agg_expr_")
.and_then(|name| name.split_once('_'))
.is_some_and(|(_, suffix)| suffix == format!("{phase}_time")) =>
{
Some((
name.to_string(),
metric
.labels()
.iter()
.find(|label| label.name() == "aggregate")?
.value()
.to_string(),
))
}
_ => None,
})
.collect::<Vec<_>>();
result.sort();
result
}
#[test]
fn accumulator_phases_match_aggregate_mode() {
let cases: [(AggregateMode, &[AccumulatorPhase]); 6] = [
(
AggregateMode::Partial,
&[AccumulatorPhase::Update, AccumulatorPhase::State],
),
(
AggregateMode::PartialReduce,
&[AccumulatorPhase::Merge, AccumulatorPhase::State],
),
(
AggregateMode::Final,
&[AccumulatorPhase::Merge, AccumulatorPhase::Evaluate],
),
(
AggregateMode::FinalPartitioned,
&[AccumulatorPhase::Merge, AccumulatorPhase::Evaluate],
),
(
AggregateMode::Single,
&[AccumulatorPhase::Update, AccumulatorPhase::Evaluate],
),
(
AggregateMode::SinglePartitioned,
&[AccumulatorPhase::Update, AccumulatorPhase::Evaluate],
),
];
for (mode, expected) in cases {
assert!(accumulator_phases(&mode) == expected, "{mode:?}");
}
}
#[tokio::test]
async fn aggregate_dynamic_filter_recovers_from_null_bounds() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Int32, false),
Field::new("b", DataType::Int32, true),
]));
let first = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(vec![1, 8])),
Arc::new(Int32Array::from(vec![None, None])),
],
)?;
let second = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(vec![2, 3])),
Arc::new(Int32Array::from(vec![5, 7])),
],
)?;
let input = TestMemoryExec::try_new_exec(
&[vec![first], vec![second]],
Arc::clone(&schema),
None,
)?;
let mut aggregates = Vec::new();
for column in ["a", "b"] {
for function in [min_udaf(), max_udaf()] {
let alias = format!("{}({column})", function.name());
aggregates.push(Arc::new(
AggregateExprBuilder::new(function, vec![col(column, &schema)?])
.schema(Arc::clone(&schema))
.alias(alias)
.build()?,
));
}
}
let aggregate = AggregateExec::try_new(
AggregateMode::Partial,
PhysicalGroupBy::default(),
aggregates,
vec![None; 4],
input,
schema,
)?;
let filter = &aggregate.dynamic_filter.as_ref().unwrap().filter;
let context = Arc::new(TaskContext::default());
collect_stream(aggregate.execute(0, Arc::clone(&context))?).await?;
assert_eq!(filter.current()?.to_string(), "true");
collect_stream(aggregate.execute(1, context)?).await?;
assert_eq!(
filter.current()?.to_string(),
"a@0 < 1 OR a@0 > 8 OR b@1 < 5 OR b@1 > 7"
);
Ok(())
}
#[tokio::test]
async fn aggregate_stream_reports_per_aggregate_metrics() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Float64, false),
Field::new("b", DataType::Float64, false),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0])),
Arc::new(Float64Array::from(vec![4.0, 5.0, 6.0])),
],
)?;
let input =
TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)?;
let aggregates = vec![
sum_aggregate(&schema, "a", "SUM(a)")?,
sum_aggregate(&schema, "b", "SUM(b)")?,
];
let aggregate = Arc::new(AggregateExec::try_new(
AggregateMode::Single,
PhysicalGroupBy::default(),
aggregates,
vec![None, None],
input,
schema,
)?);
let _ = collect(
Arc::clone(&aggregate) as Arc<dyn ExecutionPlan>,
Arc::new(TaskContext::default()),
)
.await?;
let metrics = aggregate.metrics().unwrap();
for phase in ["arguments", "update", "evaluate"] {
assert_eq!(
aggregate_metrics(&metrics, phase),
vec![
(format!("agg_expr_0_{phase}_time"), "SUM(a)".to_string()),
(format!("agg_expr_1_{phase}_time"), "SUM(b)".to_string()),
]
);
}
assert!(aggregate_metrics(&metrics, "merge").is_empty());
assert!(aggregate_metrics(&metrics, "state").is_empty());
assert!(metrics.sum_by_name("emitting_time").is_none());
Ok(())
}
#[tokio::test]
async fn aggregate_stream_reports_distinct_array_agg_submetrics() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::UInt32, false),
Field::new("b", DataType::UInt32, false),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from(vec![1, 1, 2])),
Arc::new(UInt32Array::from(vec![3, 3, 4])),
],
)?;
let input =
TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)?;
let aggregate = Arc::new(AggregateExec::try_new(
AggregateMode::Single,
PhysicalGroupBy::default(),
vec![
distinct_array_aggregate(&schema, "a", "first")?,
distinct_array_aggregate(&schema, "b", "second")?,
],
vec![None, None],
input,
schema,
)?);
let _ = collect(
Arc::clone(&aggregate) as Arc<dyn ExecutionPlan>,
Arc::new(TaskContext::default()),
)
.await?;
let metrics = aggregate.metrics().unwrap();
assert_eq!(
aggregate_metrics(&metrics, "internal_distinct"),
vec![
(
"agg_expr_0_internal_distinct_time".to_string(),
"first".to_string(),
),
(
"agg_expr_1_internal_distinct_time".to_string(),
"second".to_string(),
),
]
);
for index in 0..2 {
assert!(
metrics
.sum_by_name(&format!("agg_expr_{index}_internal_distinct_time"))
.expect("internal distinct time metric")
.as_usize()
> 0
);
}
assert_eq!(
aggregate_metrics(&aggregate.metrics().unwrap(), "update").len(),
2
);
assert_eq!(
aggregate_metrics(&aggregate.metrics().unwrap(), "evaluate").len(),
2
);
Ok(())
}
#[tokio::test]
async fn aggregate_stream_merges_submetrics_across_partitions() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::UInt32, false),
Field::new("b", DataType::UInt32, false),
Field::new("c", DataType::Float64, false),
]));
let batches = [
RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from(vec![1, 1, 2])),
Arc::new(UInt32Array::from(vec![3, 3, 4])),
Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0])),
],
)?,
RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from(vec![5, 5, 6])),
Arc::new(UInt32Array::from(vec![7, 7, 8])),
Arc::new(Float64Array::from(vec![4.0, 5.0, 6.0])),
],
)?,
];
let input = TestMemoryExec::try_new_exec(
&[vec![batches[0].clone()], vec![batches[1].clone()]],
Arc::clone(&schema),
None,
)?;
let aggregate = Arc::new(AggregateExec::try_new(
AggregateMode::Single,
PhysicalGroupBy::default(),
vec![
distinct_array_aggregate(&schema, "a", "first")?,
distinct_array_aggregate(&schema, "b", "second")?,
sum_aggregate(&schema, "c", "plain")?,
],
vec![None, None, None],
input,
schema,
)?);
let context = Arc::new(TaskContext::default());
for partition in 0..2 {
let _ = collect_stream(aggregate.execute(partition, Arc::clone(&context))?)
.await?;
}
let metrics = aggregate.metrics().unwrap();
assert_eq!(
aggregate_metrics(&metrics, "internal_distinct"),
vec![
(
"agg_expr_0_internal_distinct_time".to_string(),
"first".to_string(),
),
(
"agg_expr_0_internal_distinct_time".to_string(),
"first".to_string(),
),
(
"agg_expr_1_internal_distinct_time".to_string(),
"second".to_string(),
),
(
"agg_expr_1_internal_distinct_time".to_string(),
"second".to_string(),
),
]
);
let mut internal_partitions = metrics
.iter()
.filter(|metric| {
matches!(metric.value(), MetricValue::Time { name, .. } if name.ends_with("_internal_distinct_time"))
})
.map(|metric| metric.partition())
.collect::<Vec<_>>();
internal_partitions.sort_unstable();
assert_eq!(
internal_partitions,
vec![Some(0), Some(0), Some(1), Some(1)]
);
assert!(
metrics
.sum_by_name("agg_expr_0_internal_distinct_time")
.is_some_and(|metric| metric.as_usize() > 0)
);
assert!(!metrics.iter().any(|metric| {
matches!(metric.value(), MetricValue::Time { name, .. } if name.starts_with("agg_expr_2_internal_"))
}));
Ok(())
}
#[tokio::test]
async fn aggregate_stream_reports_partial_and_final_phases() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Float64, false),
Field::new("b", DataType::Float64, false),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0])),
Arc::new(Float64Array::from(vec![4.0, 5.0, 6.0])),
],
)?;
let input =
TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)?;
let aggregates = vec![
sum_aggregate(&schema, "a", "SUM(a)")?,
sum_aggregate(&schema, "b", "SUM(b)")?,
];
let group_by = PhysicalGroupBy::default();
let partial = Arc::new(AggregateExec::try_new(
AggregateMode::Partial,
group_by.clone(),
aggregates.clone(),
vec![None, None],
input,
Arc::clone(&schema),
)?);
let final_aggregate = Arc::new(AggregateExec::try_new(
AggregateMode::Final,
group_by.as_final(),
aggregates,
vec![None, None],
Arc::clone(&partial) as Arc<dyn ExecutionPlan>,
partial.schema(),
)?);
let _ = collect(
Arc::clone(&final_aggregate) as Arc<dyn ExecutionPlan>,
Arc::new(TaskContext::default()),
)
.await?;
let partial_metrics = partial.metrics().unwrap();
assert_eq!(aggregate_metrics(&partial_metrics, "update").len(), 2);
assert_eq!(aggregate_metrics(&partial_metrics, "state").len(), 2);
assert_eq!(aggregate_metrics(&partial_metrics, "arguments").len(), 2);
assert!(aggregate_metrics(&partial_metrics, "merge").is_empty());
assert!(aggregate_metrics(&partial_metrics, "evaluate").is_empty());
let final_metrics = final_aggregate.metrics().unwrap();
assert_eq!(aggregate_metrics(&final_metrics, "merge").len(), 2);
assert_eq!(aggregate_metrics(&final_metrics, "evaluate").len(), 2);
assert_eq!(aggregate_metrics(&final_metrics, "arguments").len(), 2);
assert!(aggregate_metrics(&final_metrics, "update").is_empty());
assert!(aggregate_metrics(&final_metrics, "state").is_empty());
Ok(())
}
}