Apache DataFusion SQL Query Engine
Add aggregate-internal submetrics (#25051)
kosiew790c46383084
diff --git a/benchmarks/bench.sh b/benchmarks/bench.shindex 082651656e..7cd0141b4b 100755--- a/benchmarks/bench.sh+++ b/benchmarks/bench.sh@@ -165,6 +165,7 @@ nlj: Benchmark for simple nested loop joins, testing varioushj: Benchmark for simple hash joins, testing various join scenariossmj: Benchmark for simple sort merge joins, testing various join scenariosdict: Benchmark for dictionary-encoded group-by scenarios+array_agg_distinct: 1000K-group, two-row-per-group array_agg(DISTINCT) benchmarkcompile_profile: Compile and execute TPC-H across selected Cargo profiles, reporting timing and binary size@@ -660,6 +661,9 @@ main() {dict)run_dict;;+ array_agg_distinct)+ run_array_agg_distinct+ ;;compile_profile)run_compile_profile "${PROFILE_ARGS[@]}";;@@ -1719,6 +1723,14 @@ run_dict() {debug_run $CARGO_COMMAND --bin dfbench -- dict --iterations 5 -o "${RESULTS_FILE}" ${QUERY_ARG} ${LATENCY_ARG}}+# Runs the data-free high-cardinality array_agg(DISTINCT) SQL benchmark.+run_array_agg_distinct() {+ echo "Running array_agg_distinct benchmark..."+ debug_run env BENCH_NAME=array_agg_distinct \+ ${QUERY:+BENCH_QUERY="${QUERY}"} \+ bash -c "$SQL_CARGO_COMMAND"+}+compare_benchmarks() {BASE_RESULTS_DIR="${SCRIPT_DIR}/results"diff --git a/benchmarks/sql_benchmarks/array_agg_distinct/array_agg_distinct.suite b/benchmarks/sql_benchmarks/array_agg_distinct/array_agg_distinct.suitenew file mode 100644index 0000000000..b114854f14--- /dev/null+++ b/benchmarks/sql_benchmarks/array_agg_distinct/array_agg_distinct.suite@@ -0,0 +1,11 @@+description = "High-cardinality array_agg(DISTINCT) SQL benchmarks"++query_pattern = "q{QUERY_ID_PADDED}.benchmark"++[[examples]]+command = "cargo run --release --bin benchmark_runner -- array_agg_distinct"+description = "Run the high-cardinality array_agg(DISTINCT) benchmark."++[[examples]]+command = "cargo run --release --bin benchmark_runner -- array_agg_distinct --query 1 --iterations 5 --output /tmp/array_agg_distinct.json"+description = "Run five iterations and write comparable JSON results."diff --git a/benchmarks/sql_benchmarks/array_agg_distinct/benchmarks/q01.benchmark b/benchmarks/sql_benchmarks/array_agg_distinct/benchmarks/q01.benchmarknew file mode 100644index 0000000000..b1987a1465--- /dev/null+++ b/benchmarks/sql_benchmarks/array_agg_distinct/benchmarks/q01.benchmark@@ -0,0 +1,11 @@+name Q01+group array_agg_distinct++expect_plan AggregateExec++run+-- 1M groups, 2 rows/group, and 2 distinct values/group. `range` is end-exclusive.+-- This is data-free so comparisons isolate grouped array_agg(DISTINCT) execution.+SELECT value / 2 AS k, array_agg(DISTINCT value % 2) AS distinct_values+FROM range(2000000)+GROUP BY value / 2;diff --git a/datafusion/expr-common/src/accumulator.rs b/datafusion/expr-common/src/accumulator.rsindex 7e9a4ae525..95cee870e2 100644--- a/datafusion/expr-common/src/accumulator.rs+++ b/datafusion/expr-common/src/accumulator.rs@@ -18,8 +18,79 @@//! Accumulator module contains the trait definition for aggregation function's accumulators.use arrow::array::ArrayRef;-use datafusion_common::{Result, ScalarValue, internal_err};+use datafusion_common::{Result, ScalarValue, instant::Instant, internal_err};use std::fmt::Debug;+use std::sync::Arc;+use std::time::Duration;++/// A metric owned by one aggregate implementation.+///+/// Aggregate implementations use this interface for optional internal+/// subphases. The execution engine owns metric registration and aggregation.+pub trait AggregateMetric: Debug + Send + Sync + std::panic::RefUnwindSafe {+ /// Adds elapsed time to this metric.+ fn add_duration(&self, duration: Duration);+}++/// Factory for optional metrics owned by one aggregate expression.+///+/// `subphase` must be a stable static identifier. Repeated requests for the+/// same subphase must return handles that update the same metric identity. An+/// implementation may request no metrics. The execution engine assigns the+/// aggregate expression identity.+pub trait AggregateMetrics: Debug + Send + Sync {+ /// Returns the metric for an aggregate-owned internal subphase.+ fn metric(&self, subphase: &'static str) -> Arc<dyn AggregateMetric>;+}++/// Publishes aggregate-owned timing when dropped.+///+/// Create this before the operation that may return an error, and scope each+/// [`Self::timer`] to only the aggregate-owned work. All timed intervals are+/// combined into one metric update when the recorder is dropped.+pub struct AggregateMetricRecorder {+ metric: Option<Arc<dyn AggregateMetric>>,+ duration: Duration,+}++impl AggregateMetricRecorder {+ /// Creates a recorder for an optional aggregate-owned metric.+ pub fn new(metric: Option<Arc<dyn AggregateMetric>>) -> Self {+ Self {+ metric,+ duration: Duration::ZERO,+ }+ }++ /// Starts timing one aggregate-owned interval.+ pub fn timer(&mut self) -> Option<AggregateMetricTimer<'_>> {+ self.metric.as_ref()?;+ Some(AggregateMetricTimer {+ duration: &mut self.duration,+ start: Instant::now(),+ })+ }+}++impl Drop for AggregateMetricRecorder {+ fn drop(&mut self) {+ if let Some(metric) = &self.metric {+ metric.add_duration(self.duration);+ }+ }+}++/// One aggregate-owned interval recorded by [`AggregateMetricRecorder`].+pub struct AggregateMetricTimer<'a> {+ duration: &'a mut Duration,+ start: Instant,+}++impl Drop for AggregateMetricTimer<'_> {+ fn drop(&mut self) {+ *self.duration += self.start.elapsed();+ }+}/// Tracks an aggregate function's state.///@@ -49,6 +120,15 @@ use std::fmt::Debug;/// [`merge_batch`]: Self::merge_batch/// [window function]: https://en.wikipedia.org/wiki/Window_function_(SQL)pub trait Accumulator: Send + Sync + Debug + std::any::Any {+ /// Supplies optional metrics owned by this aggregate expression.+ ///+ /// The grouped accumulator adapter supplies these metrics to every+ /// accumulator it creates. Call this immediately after construction and+ /// before the accumulator is used; replacing metrics after use is+ /// unsupported. The default preserves compatibility for accumulators+ /// without internal submetrics.+ fn set_metrics(&mut self, _metrics: Arc<dyn AggregateMetrics>) {}+/// Updates the accumulator's state from its input.////// `values` contains the arguments to this aggregate function.@@ -58,6 +138,33 @@ pub trait Accumulator: Send + Sync + Debug + std::any::Any {/// running sum.fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()>;+ /// Returns an optional metric timed once per grouped adapter input batch.+ ///+ /// A grouped accumulator adapter uses this for aggregate-owned work it+ /// dispatches to one accumulator per group. The default preserves the+ /// usual per-accumulator update path.+ fn grouped_update_batch_metric(&self) -> Option<Arc<dyn AggregateMetric>> {+ None+ }++ /// Updates state when called by a grouped accumulator adapter.+ ///+ /// The default delegates to [`Self::update_batch`]. Implementations that+ /// return a [`Self::grouped_update_batch_metric`] can avoid timing every+ /// per-group call; the adapter records one interval for the full batch.+ fn update_batch_grouped(&mut self, values: &[ArrayRef]) -> Result<()> {+ self.update_batch(values)+ }++ /// Merges state when called by a grouped accumulator adapter.+ ///+ /// The default delegates to [`Self::merge_batch`]. Implementations that+ /// return a [`Self::grouped_update_batch_metric`] can avoid timing every+ /// per-group merge; the adapter records one interval for the full batch.+ fn merge_batch_grouped(&mut self, states: &[ArrayRef]) -> Result<()> {+ self.merge_batch(states)+ }+/// Returns the final aggregate value.////// For example, the `SUM` accumulator maintains a running sum,diff --git a/datafusion/expr-common/src/groups_accumulator.rs b/datafusion/expr-common/src/groups_accumulator.rsindex c682d7caf1..1c004cb70b 100644--- a/datafusion/expr-common/src/groups_accumulator.rs+++ b/datafusion/expr-common/src/groups_accumulator.rs@@ -19,6 +19,9 @@use arrow::array::{ArrayRef, BooleanArray};use datafusion_common::{Result, exec_err, not_impl_err, utils::split_vec_min_alloc};+use std::sync::Arc;++use crate::accumulator::AggregateMetrics;/// Describes how many rows should be emitted during grouping.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -188,6 +191,13 @@ impl<'a> GroupSelection<'a> {/// [`Accumulator`]: crate::accumulator::Accumulator/// [Aggregating Millions of Groups Fast blog]: https://arrow.apache.org/blog/2023/08/05/datafusion_fast_grouping/pub trait GroupsAccumulator: Send + std::any::Any {+ /// Supplies optional metrics owned by this aggregate expression.+ ///+ /// Call this immediately after construction and before the accumulator is+ /// used; replacing metrics after use is unsupported. The default preserves+ /// compatibility for accumulators without internal submetrics.+ fn set_metrics(&mut self, _metrics: Arc<dyn AggregateMetrics>) {}+/// Updates the accumulator's state from its arguments, encoded as/// a vector of [`ArrayRef`]s.///diff --git a/datafusion/expr/src/lib.rs b/datafusion/expr/src/lib.rsindex 649f3de252..ed9b4df4ce 100644--- a/datafusion/expr/src/lib.rs+++ b/datafusion/expr/src/lib.rs@@ -101,7 +101,9 @@ pub use datafusion_doc::{DocSection, Documentation, DocumentationBuilder, aggregate_doc_sections,scalar_doc_sections, window_doc_sections,};-pub use datafusion_expr_common::accumulator::Accumulator;+pub use datafusion_expr_common::accumulator::{+ Accumulator, AggregateMetric, AggregateMetricRecorder, AggregateMetrics,+};pub use datafusion_expr_common::columnar_value::ColumnarValue;pub use datafusion_expr_common::groups_accumulator::{EmitTo, GroupSelection, GroupsAccumulator,diff --git a/datafusion/functions-aggregate-common/Cargo.toml b/datafusion/functions-aggregate-common/Cargo.tomlindex 0898e6b4c5..463034d4d6 100644--- a/datafusion/functions-aggregate-common/Cargo.toml+++ b/datafusion/functions-aggregate-common/Cargo.toml@@ -57,3 +57,7 @@ rand = { workspace = true }[[bench]]harness = falsename = "accumulate"++[[bench]]+harness = false+name = "groups_accumulator_adapter"diff --git a/datafusion/functions-aggregate-common/benches/groups_accumulator_adapter.rs b/datafusion/functions-aggregate-common/benches/groups_accumulator_adapter.rsnew file mode 100644index 0000000000..30fd4c0e16--- /dev/null+++ b/datafusion/functions-aggregate-common/benches/groups_accumulator_adapter.rs@@ -0,0 +1,62 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++//! Benchmarks the uninstrumented `GroupsAccumulatorAdapter` update path.++use std::hint::black_box;+use std::sync::Arc;++use arrow::array::{ArrayRef, Int64Array};+use arrow::datatypes::DataType;+use criterion::{BatchSize, Criterion, criterion_group, criterion_main};+use datafusion_expr_common::accumulator::Accumulator;+use datafusion_expr_common::groups_accumulator::GroupsAccumulator;+use datafusion_functions_aggregate_common::aggregate::groups_accumulator::GroupsAccumulatorAdapter;+use datafusion_functions_aggregate_common::min_max::MaxAccumulator;++const NUM_GROUPS: usize = 8_192;++fn groups_accumulator_adapter(c: &mut Criterion) {+ let values: ArrayRef = Arc::new(Int64Array::from_iter_values(0..NUM_GROUPS as i64));+ let group_indices: Vec<_> = (0..NUM_GROUPS).collect();++ c.bench_function("groups_accumulator_adapter/update_batch/8192_groups", |b| {+ b.iter_batched(+ || {+ GroupsAccumulatorAdapter::new(|| {+ Ok(Box::new(MaxAccumulator::try_new(&DataType::Int64)?)+ as Box<dyn Accumulator>)+ })+ },+ |mut accumulator| {+ accumulator+ .update_batch(+ &[Arc::clone(&values)],+ &group_indices,+ None,+ NUM_GROUPS,+ )+ .unwrap();+ black_box(accumulator);+ },+ BatchSize::SmallInput,+ );+ });+}++criterion_group!(benches, groups_accumulator_adapter);+criterion_main!(benches);diff --git a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator.rs b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator.rsindex ad01fbce5b..41917329b2 100644--- a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator.rs+++ b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator.rs@@ -24,6 +24,7 @@ pub mod nulls;pub mod prim_op;use std::mem::{size_of, size_of_val};+use std::sync::{Arc, OnceLock};use arrow::array::new_empty_array;use arrow::{@@ -33,7 +34,9 @@ use arrow::{datatypes::UInt32Type,};use datafusion_common::{Result, ScalarValue, arrow_datafusion_err};-use datafusion_expr_common::accumulator::Accumulator;+use datafusion_expr_common::accumulator::{+ Accumulator, AggregateMetric, AggregateMetricRecorder, AggregateMetrics,+};use datafusion_expr_common::groups_accumulator::{EmitTo, GroupSelection, GroupsAccumulator,};@@ -103,11 +106,17 @@ pub struct GroupsAccumulatorAdapter {/// distinct groups.allocation_bytes: usize,- /// The portion of [`Self::allocation_bytes`] that is the scratch- /// [`AccumulatorState::indices`] capacity held by [`Self::states`].- indices_allocation_bytes: usize,+ /// Metrics supplied by the aggregate execution operator.+ metrics: Option<Arc<dyn AggregateMetrics>>,++ /// Optional aggregate-owned metric timed once for a grouped update batch.+ grouped_update_metric: OnceLock<Option<Arc<dyn AggregateMetric>>>,}+/// Maximum number of prepared group inputs retained while timing an+/// aggregate-owned grouped subphase.+const GROUPED_METRIC_PREPARATION_CHUNK_SIZE: usize = 64;+struct AccumulatorState {/// [`Accumulator`] that stores the per-group stateaccumulator: Box<dyn Accumulator>,@@ -143,10 +152,31 @@ impl GroupsAccumulatorAdapter {factory: Box::new(factory),states: vec![],allocation_bytes: 0,- indices_allocation_bytes: 0,+ metrics: None,+ grouped_update_metric: OnceLock::new(),}}+ /// Creates an accumulator with this adapter's optional metrics.+ fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {+ let mut accumulator = (self.factory)()?;+ if let Some(metrics) = &self.metrics {+ accumulator.set_metrics(Arc::clone(metrics));+ }+ self.grouped_update_metric+ .get_or_init(|| accumulator.grouped_update_batch_metric());+ Ok(accumulator)+ }++ /// Returns the aggregate-owned grouped-update metric, if the first+ /// accumulator this adapter created exposed one.+ ///+ /// The cell is seeded by [`Self::create_accumulator`], so this returns+ /// `None` until at least one accumulator has been built.+ fn grouped_metric(&self) -> Option<Arc<dyn AggregateMetric>> {+ self.grouped_update_metric.get().and_then(Clone::clone)+ }+/// Ensure that self.accumulators has total_num_groupsfn make_accumulators_if_needed(&mut self, total_num_groups: usize) -> Result<()> {// can't shrink@@ -156,7 +186,7 @@ impl GroupsAccumulatorAdapter {// instantiate new accumulatorslet new_accumulators = total_num_groups - self.states.len();for _ in 0..new_accumulators {- let accumulator = (self.factory)()?;+ let accumulator = self.create_accumulator()?;let state = AccumulatorState::new(accumulator);self.add_allocation(state.size());self.states.push(state);@@ -208,9 +238,20 @@ impl GroupsAccumulatorAdapter {// figure out which input rows correspond to which groups.// Note that self.state.indices starts empty for all groups// (it is cleared out below)+ // Charge retained scratch capacity only when a push grows a vector,+ // avoiding another pass over every group after indexing.+ let mut indices_allocation_delta = 0;for (idx, group_index) in group_indices.iter().enumerate() {- self.states[*group_index].indices.push(idx as u32);+ let indices = &mut self.states[*group_index].indices;+ if indices.len() < indices.capacity() {+ indices.push(idx as u32);+ } else {+ let size_pre = indices.allocated_size();+ indices.push(idx as u32);+ indices_allocation_delta += indices.allocated_size() - size_pre;+ }}+ self.add_allocation(indices_allocation_delta);// groups_with_rows holds a list of group indexes that have// any rows that need to be accumulated, stored in order of@@ -226,12 +267,8 @@ impl GroupsAccumulatorAdapter {let mut offsets = vec![0];let mut offset_so_far = 0;- let mut indices_allocation_bytes = 0;for (group_index, state) in self.states.iter_mut().enumerate() {let indices = &state.indices;- // this pass already visits every group, so totalling the scratch- // capacity here costs a field read rather than a `size()` call- indices_allocation_bytes += indices.allocated_size();if indices.is_empty() {continue;}@@ -243,45 +280,107 @@ impl GroupsAccumulatorAdapter {}let batch_indices = batch_indices.into();- // The push loop above is the only place `indices` grows. Charge the- // growth since the previous batch here: the pre/post deltas below- // observe the identical capacity on both sides, because `f` does not- // touch `indices` and the `clear()` after it retains the capacity.- self.adjust_allocation(self.indices_allocation_bytes, indices_allocation_bytes);- self.indices_allocation_bytes = indices_allocation_bytes;-// reorder the values and opt_filter by batch_indices so that// all values for each group are contiguous, then invoke the// accumulator once per group with valueslet values = take_arrays(values, &batch_indices, None)?;let opt_filter = get_filter_at_indices(opt_filter, &batch_indices)?;- // invoke each accumulator with the appropriate rows, first- // pulling the input arguments for this group into their own- // RecordBatch(es)- let iter = groups_with_rows.iter().zip(offsets.windows(2));+ let grouped_update_metric = self.grouped_metric();let mut sizes_pre = 0;let mut sizes_post = 0;- for (&group_idx, offsets) in iter {- let state = &mut self.states[group_idx];- sizes_pre += state.size();-- let values_to_accumulate = slice_and_maybe_filter(- &values,- opt_filter.as_ref().map(|f| f.as_boolean()),- offsets,- )?;- f(state.accumulator.as_mut(), &values_to_accumulate)?;+ let has_grouped_update_metric = grouped_update_metric.is_some();+ let mut metric_recorder = AggregateMetricRecorder::new(grouped_update_metric);+ let result: Result<()> = (|| {+ if !has_grouped_update_metric {+ // Keep the pre-metrics single-pass path for accumulators that+ // do not expose an aggregate-owned submetric.+ for (&group_idx, offsets) in+ groups_with_rows.iter().zip(offsets.windows(2))+ {+ sizes_pre += self.states[group_idx].size();+ let values_to_accumulate = match slice_and_maybe_filter(+ &values,+ opt_filter.as_ref().map(|f| f.as_boolean()),+ offsets,+ ) {+ Ok(values) => values,+ Err(error) => {+ sizes_post += self.states[group_idx].size();+ return Err(error);+ }+ };+ let update_result = f(+ self.states[group_idx].accumulator.as_mut(),+ &values_to_accumulate,+ );+ let state = &mut self.states[group_idx];+ if update_result.is_ok() {+ state.indices.clear();+ }+ sizes_post += state.size();+ update_result?;+ }+ return Ok(());+ }- // clear out the state so they are empty for next- // iteration- state.indices.clear();- sizes_post += state.size();- }+ // Keep preparation bounded to avoid retaining one filtered array per+ // group. Time only accumulator invocation: slicing and filtering+ // are adapter work, not aggregate-owned subphase work.+ for (chunk_index, groups) in groups_with_rows+ .chunks(GROUPED_METRIC_PREPARATION_CHUNK_SIZE)+ .enumerate()+ {+ let first_offset = chunk_index * GROUPED_METRIC_PREPARATION_CHUNK_SIZE;+ let values_to_accumulate = groups+ .iter()+ .enumerate()+ .map(|(index, &group_idx)| {+ let values = slice_and_maybe_filter(+ &values,+ opt_filter.as_ref().map(|f| f.as_boolean()),+ &offsets[first_offset + index..first_offset + index + 2],+ )?;+ Ok((group_idx, values))+ })+ .collect::<Result<Vec<_>>>()?;++ // Size accounting is adapter work: keep it out of the timer.+ for (group_idx, _) in &values_to_accumulate {+ sizes_pre += self.states[*group_idx].size();+ }++ let (successful_groups, chunk_result) = {+ let _timer = metric_recorder.timer();+ let mut successful_groups = 0;+ let mut chunk_result = Ok(());+ for (group_idx, values) in &values_to_accumulate {+ chunk_result =+ f(self.states[*group_idx].accumulator.as_mut(), values);+ if chunk_result.is_err() {+ break;+ }+ successful_groups += 1;+ }+ (successful_groups, chunk_result)+ };+ for (index, (group_idx, _)) in values_to_accumulate.iter().enumerate() {+ let state = &mut self.states[*group_idx];+ if index < successful_groups {+ // Clear every successfully applied group before+ // propagating an error from a later group.+ state.indices.clear();+ }+ sizes_post += state.size();+ }+ chunk_result?;+ }+ Ok(())+ })();self.adjust_allocation(sizes_pre, sizes_post);- Ok(())+ result}/// Increment the allocation by `n`@@ -301,15 +400,8 @@ impl GroupsAccumulatorAdapter {}/// Release the allocation held by a state that is being emitted.- ///- /// [`AccumulatorState::size`] covers the scratch `indices` capacity, so- /// this also drops it from [`Self::indices_allocation_bytes`] to keep that- /// running total equal to the capacity still held by [`Self::states`].fn free_state_allocation(&mut self, state: &AccumulatorState) {self.free_allocation(state.size());- self.indices_allocation_bytes = self- .indices_allocation_bytes- .saturating_sub(state.indices.allocated_size());}/// Adjusts the allocation for something that started with@@ -326,6 +418,10 @@ impl GroupsAccumulatorAdapter {}impl GroupsAccumulator for GroupsAccumulatorAdapter {+ fn set_metrics(&mut self, metrics: Arc<dyn AggregateMetrics>) {+ self.metrics = Some(metrics);+ }+fn update_batch(&mut self,values: &[ArrayRef],@@ -339,7 +435,7 @@ impl GroupsAccumulator for GroupsAccumulatorAdapter {opt_filter,total_num_groups,|accumulator, values_to_accumulate| {- accumulator.update_batch(values_to_accumulate)+ accumulator.update_batch_grouped(values_to_accumulate)},)?;Ok(())@@ -371,7 +467,7 @@ impl GroupsAccumulator for GroupsAccumulatorAdapter {if selected_len == 0 {// ScalarValue::iter_to_array needs at least one value to infer the// output type, so evaluate a temporary empty accumulator.- let mut accumulator = (self.factory)()?;+ let mut accumulator = self.create_accumulator()?;return Ok(ScalarValue::iter_to_array([accumulator.evaluate()?])?.slice(0, 0));}@@ -441,8 +537,7 @@ impl GroupsAccumulator for GroupsAccumulatorAdapter {None,total_num_groups,|accumulator, values_to_accumulate| {- accumulator.merge_batch(values_to_accumulate)?;- Ok(())+ accumulator.merge_batch_grouped(values_to_accumulate)},)?;Ok(())@@ -462,7 +557,7 @@ impl GroupsAccumulator for GroupsAccumulatorAdapter {// If there are no rows, return empty arraysif num_rows == 0 {// create empty accumulator to get the state types- let empty_state = (self.factory)()?.state()?;+ let empty_state = self.create_accumulator()?.state()?;let empty_arrays = empty_state.into_iter().map(|state_val| new_empty_array(&state_val.data_type()))@@ -473,22 +568,49 @@ impl GroupsAccumulator for GroupsAccumulatorAdapter {// Each row has its respective grouplet mut results = vec![];- for row_idx in 0..num_rows {- // Create the empty accumulator for converting- let mut converted_accumulator = (self.factory)()?;+ let mut metric_recorder = None;+ for chunk_start in (0..num_rows).step_by(GROUPED_METRIC_PREPARATION_CHUNK_SIZE) {+ let chunk_end =+ (chunk_start + GROUPED_METRIC_PREPARATION_CHUNK_SIZE).min(num_rows);+ let mut prepared = Vec::with_capacity(chunk_end - chunk_start);++ for row_idx in chunk_start..chunk_end {+ // Create the empty accumulator and prepare adapter-owned input+ // outside the aggregate submetric.+ let accumulator = self.create_accumulator()?;+ // `create_accumulator` resolves the metric, so the recorder can+ // only be built once the first accumulator exists.+ metric_recorder.get_or_insert_with(|| {+ AggregateMetricRecorder::new(self.grouped_metric())+ });+ let values_to_accumulate =+ slice_and_maybe_filter(values, opt_filter, &[row_idx, row_idx + 1])?;+ prepared.push((accumulator, values_to_accumulate));+ }- // Convert row to states- let values_to_accumulate =- slice_and_maybe_filter(values, opt_filter, &[row_idx, row_idx + 1])?;- converted_accumulator.update_batch(&values_to_accumulate)?;- let states = converted_accumulator.state()?;+ // Time only aggregate-owned deduplication, once per bounded chunk.+ let update_result: Result<()> = {+ let _timer = metric_recorder+ .as_mut()+ .and_then(AggregateMetricRecorder::timer);+ prepared+ .iter_mut()+ .try_for_each(|(accumulator, values_to_accumulate)| {+ accumulator.update_batch_grouped(values_to_accumulate)+ })+ };+ update_result?;- // Resize results to have enough columns according to the converted states- results.resize_with(states.len(), || Vec::with_capacity(num_rows));+ for (mut accumulator, _) in prepared {+ let states = accumulator.state()?;- // Add the states to results- for (idx, state_val) in states.into_iter().enumerate() {- results[idx].push(state_val);+ // Resize results to have enough columns according to the converted states+ results.resize_with(states.len(), || Vec::with_capacity(num_rows));++ // Add the states to results+ for (idx, state_val) in states.into_iter().enumerate() {+ results[idx].push(state_val);+ }}}@@ -561,12 +683,482 @@ pub(crate) fn slice_and_maybe_filter(#[cfg(test)]mod tests {use std::sync::Arc;+ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};+ use std::time::Duration;use super::*;use crate::min_max::MaxAccumulator;- use arrow::array::{AsArray, Int64Array};+ use arrow::array::{AsArray, BooleanArray, Int64Array};use arrow::datatypes::{DataType, Int64Type};+ #[derive(Debug)]+ struct CountingMetric(Arc<AtomicUsize>);++ impl AggregateMetric for CountingMetric {+ fn add_duration(&self, _duration: Duration) {+ self.0.fetch_add(1, Ordering::Relaxed);+ }+ }++ #[derive(Debug)]+ struct CountingMetrics(Arc<AtomicUsize>);++ impl AggregateMetrics for CountingMetrics {+ fn metric(&self, _subphase: &'static str) -> Arc<dyn AggregateMetric> {+ Arc::new(CountingMetric(Arc::clone(&self.0)))+ }+ }++ #[derive(Debug)]+ struct DurationMetric(Arc<AtomicU64>);++ impl AggregateMetric for DurationMetric {+ fn add_duration(&self, duration: Duration) {+ self.0+ .fetch_add(duration.as_nanos() as u64, Ordering::Relaxed);+ }+ }++ #[derive(Debug)]+ struct TimedAccumulator {+ metric: Arc<dyn AggregateMetric>,+ }++ impl Accumulator for TimedAccumulator {+ fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {+ self.metric.add_duration(Duration::ZERO);+ Ok(())+ }++ fn grouped_update_batch_metric(&self) -> Option<Arc<dyn AggregateMetric>> {+ Some(Arc::clone(&self.metric))+ }++ fn update_batch_grouped(&mut self, _values: &[ArrayRef]) -> Result<()> {+ Ok(())+ }++ fn evaluate(&mut self) -> Result<ScalarValue> {+ Ok(ScalarValue::Int64(None))+ }++ fn size(&self) -> usize {+ size_of_val(self)+ }++ fn state(&mut self) -> Result<Vec<ScalarValue>> {+ Ok(vec![ScalarValue::Int64(None)])+ }++ fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {+ Ok(())+ }+ }++ #[derive(Debug)]+ struct MetricsAwareAccumulator {+ metric: Option<Arc<dyn AggregateMetric>>,+ }++ impl Accumulator for MetricsAwareAccumulator {+ fn set_metrics(&mut self, metrics: Arc<dyn AggregateMetrics>) {+ self.metric = Some(metrics.metric("update"));+ }++ fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {+ self.metric+ .as_ref()+ .expect("adapter must supply metrics to every group")+ .add_duration(Duration::ZERO);+ Ok(())+ }++ fn evaluate(&mut self) -> Result<ScalarValue> {+ Ok(ScalarValue::Int64(None))+ }++ fn size(&self) -> usize {+ size_of_val(self)+ }++ fn state(&mut self) -> Result<Vec<ScalarValue>> {+ Ok(vec![ScalarValue::Int64(None)])+ }++ fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {+ Ok(())+ }+ }++ #[test]+ fn adapter_supplies_metrics_to_every_group() -> Result<()> {+ let metric_updates = Arc::new(AtomicUsize::new(0));+ let mut adapter = GroupsAccumulatorAdapter::new(|| {+ Ok(Box::new(MetricsAwareAccumulator { metric: None })+ as Box<dyn Accumulator>)+ });+ adapter.set_metrics(Arc::new(CountingMetrics(Arc::clone(&metric_updates))));++ let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));+ adapter.update_batch(&[values], &[0, 1], None, 2)?;++ assert_eq!(metric_updates.load(Ordering::Relaxed), 2);+ Ok(())+ }++ #[test]+ fn adapter_charges_retained_indices_once_and_releases_them() -> Result<()> {+ let mut adapter = GroupsAccumulatorAdapter::new(|| {+ Ok(Box::new(TimedAccumulator {+ metric: Arc::new(CountingMetric(Arc::new(AtomicUsize::new(0)))),+ }) as Box<dyn Accumulator>)+ });+ adapter.make_accumulators_if_needed(1)?;+ let allocation_before_update = adapter.size();+ let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 3, 4]));++ adapter.update_batch(&[Arc::clone(&values)], &[0, 0, 0, 0], None, 1)?;+ let retained_indices = adapter.states[0].indices.allocated_size();+ assert!(retained_indices > 0);+ assert!(adapter.states[0].indices.is_empty());+ assert_eq!(adapter.size(), allocation_before_update + retained_indices);++ let allocation_after_first_update = adapter.size();+ adapter.update_batch(&[values], &[0, 0, 0, 0], None, 1)?;+ assert_eq!(adapter.size(), allocation_after_first_update);++ adapter.evaluate(EmitTo::All)?;+ assert_eq!(adapter.size(), 0);+ Ok(())+ }++ #[test]+ fn adapter_grouped_update_records_one_metric_after_filtering() -> Result<()> {+ let metric_updates = Arc::new(AtomicUsize::new(0));+ let mut accumulator = GroupsAccumulatorAdapter::new({+ let metric_updates = Arc::clone(&metric_updates);+ move || {+ Ok(Box::new(TimedAccumulator {+ metric: Arc::new(CountingMetric(Arc::clone(&metric_updates))),+ }) as Box<dyn Accumulator>)+ }+ });++ let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 3, 4]));+ let filter = BooleanArray::from(vec![true, false, true, false]);+ accumulator.update_batch(&[values], &[0, 0, 1, 1], Some(&filter), 2)?;++ assert_eq!(metric_updates.load(Ordering::Relaxed), 1);+ Ok(())+ }++ #[test]+ fn adapter_grouped_update_records_zero_duration_for_empty_batch() -> Result<()> {+ let metric_updates = Arc::new(AtomicUsize::new(0));+ let mut accumulator = GroupsAccumulatorAdapter::new({+ let metric_updates = Arc::clone(&metric_updates);+ move || {+ Ok(Box::new(TimedAccumulator {+ metric: Arc::new(CountingMetric(Arc::clone(&metric_updates))),+ }) as Box<dyn Accumulator>)+ }+ });++ let values: ArrayRef = Arc::new(Int64Array::from(vec![1]));+ accumulator.update_batch(&[values], &[0], None, 1)?;+ metric_updates.store(0, Ordering::Relaxed);++ let empty_values: ArrayRef = Arc::new(Int64Array::from(Vec::<i64>::new()));+ accumulator.update_batch(&[empty_values], &[], None, 1)?;++ assert_eq!(metric_updates.load(Ordering::Relaxed), 1);+ Ok(())+ }++ #[test]+ fn adapter_convert_to_state_records_metric_once() -> Result<()> {+ let metric_updates = Arc::new(AtomicUsize::new(0));+ let accumulator = GroupsAccumulatorAdapter::new({+ let metric_updates = Arc::clone(&metric_updates);+ move || {+ Ok(Box::new(TimedAccumulator {+ metric: Arc::new(CountingMetric(Arc::clone(&metric_updates))),+ }) as Box<dyn Accumulator>)+ }+ });++ let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 3]));+ accumulator.convert_to_state(&[values], None)?;++ assert_eq!(metric_updates.load(Ordering::Relaxed), 1);+ Ok(())+ }++ #[derive(Debug)]+ struct SlowStateAccumulator {+ metric: Arc<dyn AggregateMetric>,+ }++ impl Accumulator for SlowStateAccumulator {+ fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {+ Ok(())+ }++ fn grouped_update_batch_metric(&self) -> Option<Arc<dyn AggregateMetric>> {+ Some(Arc::clone(&self.metric))+ }++ fn evaluate(&mut self) -> Result<ScalarValue> {+ Ok(ScalarValue::Int64(None))+ }++ fn size(&self) -> usize {+ size_of_val(self)+ }++ fn state(&mut self) -> Result<Vec<ScalarValue>> {+ std::thread::sleep(Duration::from_millis(50));+ Ok(vec![ScalarValue::Int64(None)])+ }++ fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {+ Ok(())+ }+ }++ #[test]+ fn adapter_convert_to_state_excludes_state_materialization_from_metric() -> Result<()>+ {+ let recorded_nanos = Arc::new(AtomicU64::new(0));+ let accumulator = GroupsAccumulatorAdapter::new({+ let recorded_nanos = Arc::clone(&recorded_nanos);+ move || {+ Ok(Box::new(SlowStateAccumulator {+ metric: Arc::new(DurationMetric(Arc::clone(&recorded_nanos))),+ }) as Box<dyn Accumulator>)+ }+ });++ let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));+ let filter = BooleanArray::from(vec![true, false]);+ accumulator.convert_to_state(&[values], Some(&filter))?;++ assert!(+ recorded_nanos.load(Ordering::Relaxed)+ < Duration::from_millis(25).as_nanos() as u64,+ "internal metric must exclude state materialization"+ );+ Ok(())+ }++ #[derive(Debug)]+ struct SlowSizeAccumulator {+ metric: Arc<dyn AggregateMetric>,+ }++ impl Accumulator for SlowSizeAccumulator {+ fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {+ Ok(())+ }++ fn grouped_update_batch_metric(&self) -> Option<Arc<dyn AggregateMetric>> {+ Some(Arc::clone(&self.metric))+ }++ fn update_batch_grouped(&mut self, _values: &[ArrayRef]) -> Result<()> {+ Ok(())+ }++ fn evaluate(&mut self) -> Result<ScalarValue> {+ Ok(ScalarValue::Int64(None))+ }++ fn size(&self) -> usize {+ std::thread::sleep(Duration::from_millis(50));+ size_of_val(self)+ }++ fn state(&mut self) -> Result<Vec<ScalarValue>> {+ Ok(vec![ScalarValue::Int64(None)])+ }++ fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {+ Ok(())+ }+ }++ #[test]+ fn adapter_grouped_update_excludes_size_accounting_from_metric() -> Result<()> {+ let recorded_nanos = Arc::new(AtomicU64::new(0));+ let mut accumulator = GroupsAccumulatorAdapter::new({+ let recorded_nanos = Arc::clone(&recorded_nanos);+ move || {+ Ok(Box::new(SlowSizeAccumulator {+ metric: Arc::new(DurationMetric(Arc::clone(&recorded_nanos))),+ }) as Box<dyn Accumulator>)+ }+ });++ let values: ArrayRef = Arc::new(Int64Array::from(vec![1]));+ accumulator.update_batch(&[values], &[0], None, 1)?;++ assert!(+ recorded_nanos.load(Ordering::Relaxed)+ < Duration::from_millis(25).as_nanos() as u64,+ "grouped-update metric must exclude size accounting"+ );+ Ok(())+ }++ #[derive(Debug)]+ struct FailOnceAccumulator {+ fail_first_update: bool,+ successful_group_rows: Option<Arc<AtomicUsize>>,+ allocation_bytes: usize,+ metric: Option<Arc<dyn AggregateMetric>>,+ }++ impl Accumulator for FailOnceAccumulator {+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {+ if self.fail_first_update {+ self.fail_first_update = false;+ return datafusion_common::internal_err!("injected update failure");+ }+ if let Some(rows) = &self.successful_group_rows {+ rows.fetch_add(values[0].len(), Ordering::Relaxed);+ self.allocation_bytes = 1024;+ }+ Ok(())+ }++ fn grouped_update_batch_metric(&self) -> Option<Arc<dyn AggregateMetric>> {+ self.metric.clone()+ }++ fn evaluate(&mut self) -> Result<ScalarValue> {+ Ok(ScalarValue::Int64(None))+ }++ fn size(&self) -> usize {+ size_of_val(self) + self.allocation_bytes+ }++ fn state(&mut self) -> Result<Vec<ScalarValue>> {+ Ok(vec![ScalarValue::Int64(None)])+ }++ fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {+ Ok(())+ }+ }++ #[test]+ fn adapter_clears_successful_group_indices_after_later_error() -> Result<()> {+ let created = Arc::new(AtomicUsize::new(0));+ let successful_group_rows = Arc::new(AtomicUsize::new(0));+ let mut accumulator = GroupsAccumulatorAdapter::new({+ let created = Arc::clone(&created);+ let successful_group_rows = Arc::clone(&successful_group_rows);+ move || {+ let group = created.fetch_add(1, Ordering::Relaxed);+ Ok(Box::new(FailOnceAccumulator {+ fail_first_update: group == 1,+ successful_group_rows: (group == 0)+ .then(|| Arc::clone(&successful_group_rows)),+ allocation_bytes: 0,+ metric: None,+ }) as Box<dyn Accumulator>)+ }+ });++ accumulator.make_accumulators_if_needed(2)?;+ let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));+ assert!(+ accumulator+ .update_batch(&[Arc::clone(&values)], &[0, 1], None, 2)+ .is_err()+ );+ assert_eq!(+ accumulator.size(),+ accumulator.states.allocated_size()+ + accumulator+ .states+ .iter()+ .map(AccumulatorState::size)+ .sum::<usize>()+ );+ accumulator.update_batch(&[values], &[0, 1], None, 2)?;++ assert_eq!(successful_group_rows.load(Ordering::Relaxed), 2);+ Ok(())+ }++ #[test]+ fn adapter_reconciles_allocation_after_later_error_with_grouped_metric() -> Result<()>+ {+ let created = Arc::new(AtomicUsize::new(0));+ let successful_group_rows = Arc::new(AtomicUsize::new(0));+ let metric: Arc<dyn AggregateMetric> =+ Arc::new(CountingMetric(Arc::new(AtomicUsize::new(0))));+ let mut accumulator = GroupsAccumulatorAdapter::new({+ let created = Arc::clone(&created);+ let successful_group_rows = Arc::clone(&successful_group_rows);+ move || {+ let group = created.fetch_add(1, Ordering::Relaxed);+ Ok(Box::new(FailOnceAccumulator {+ fail_first_update: group == 1,+ successful_group_rows: (group == 0)+ .then(|| Arc::clone(&successful_group_rows)),+ allocation_bytes: 0,+ metric: Some(Arc::clone(&metric)),+ }) as Box<dyn Accumulator>)+ }+ });++ accumulator.make_accumulators_if_needed(2)?;+ let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));+ assert!(+ accumulator+ .update_batch(&[values], &[0, 1], None, 2)+ .is_err()+ );+ assert_eq!(+ accumulator.size(),+ accumulator.states.allocated_size()+ + accumulator+ .states+ .iter()+ .map(AccumulatorState::size)+ .sum::<usize>()+ );+ Ok(())+ }++ #[test]+ fn adapter_convert_to_state_records_metric_on_update_error() -> Result<()> {+ let created = Arc::new(AtomicUsize::new(0));+ let metric_updates = Arc::new(AtomicUsize::new(0));+ let metric: Arc<dyn AggregateMetric> =+ Arc::new(CountingMetric(Arc::clone(&metric_updates)));+ let accumulator = GroupsAccumulatorAdapter::new({+ let created = Arc::clone(&created);+ move || {+ let group = created.fetch_add(1, Ordering::Relaxed);+ Ok(Box::new(FailOnceAccumulator {+ fail_first_update: group == 1,+ successful_group_rows: None,+ allocation_bytes: 0,+ metric: Some(Arc::clone(&metric)),+ }) as Box<dyn Accumulator>)+ }+ });++ let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));+ assert!(accumulator.convert_to_state(&[values], None).is_err());+ assert_eq!(metric_updates.load(Ordering::Relaxed), 1);+ Ok(())+ }+#[test]fn adapter_preserving_evaluation_uses_accumulator_contract() -> Result<()> {let mut accumulator = GroupsAccumulatorAdapter::new(|| {diff --git a/datafusion/functions-aggregate/benches/nth_value.rs b/datafusion/functions-aggregate/benches/nth_value.rsindex a0cff5397b..78942c2a66 100644--- a/datafusion/functions-aggregate/benches/nth_value.rs+++ b/datafusion/functions-aggregate/benches/nth_value.rs@@ -23,15 +23,18 @@ use arrow::compute::SortOptions;use arrow::datatypes::DataType;use criterion::{BatchSize, BenchmarkId, Criterion, criterion_group, criterion_main};use datafusion_expr::Accumulator;+use datafusion_expr::groups_accumulator::GroupsAccumulator;use datafusion_functions_aggregate::nth_value::{NthValueAccumulator, TrivialNthValueAccumulator,};+use datafusion_functions_aggregate_common::aggregate::groups_accumulator::GroupsAccumulatorAdapter;use datafusion_physical_expr::expressions::Column;use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr};const N_VALUES: [i64; 6] = [-100, -10, -1, 1, 10, 100];const BATCH_LEN: usize = 8192;const UPDATES_PER_ITER: usize = 10;+const ADAPTER_GROUPS: usize = 8192;fn int64_array(values: impl IntoIterator<Item = i64>) -> ArrayRef {Arc::new(Int64Array::from_iter_values(values))@@ -51,6 +54,34 @@ fn ordered_accumulator(n: i64) -> NthValueAccumulator {.unwrap()}+fn grouped_adapter_benchmark(c: &mut Criterion) {+ let values = int64_array(0..ADAPTER_GROUPS as i64);+ let n_values = int64_array(std::iter::repeat_n(1, ADAPTER_GROUPS));+ let ordering_values = int64_array(0..ADAPTER_GROUPS as i64);+ let group_indices: Vec<_> = (0..ADAPTER_GROUPS).collect();+ let batch = vec![values, n_values, ordering_values];++ c.bench_function(+ "nth_value/ordered_groups_accumulator_adapter/8192_groups",+ |b| {+ b.iter_batched(+ || {+ GroupsAccumulatorAdapter::new(|| {+ Ok(Box::new(ordered_accumulator(1)) as Box<dyn Accumulator>)+ })+ },+ |mut accumulator| {+ accumulator+ .update_batch(&batch, &group_indices, None, ADAPTER_GROUPS)+ .unwrap();+ black_box(accumulator);+ },+ BatchSize::SmallInput,+ );+ },+ );+}+fn nth_value_benchmark(c: &mut Criterion) {let values = int64_array(0..BATCH_LEN as i64);let mut group = c.benchmark_group("nth_value");@@ -98,5 +129,5 @@ fn nth_value_benchmark(c: &mut Criterion) {group.finish();}-criterion_group!(benches, nth_value_benchmark);+criterion_group!(benches, nth_value_benchmark, grouped_adapter_benchmark);criterion_main!(benches);diff --git a/datafusion/functions-aggregate/benches/percentile_cont.rs b/datafusion/functions-aggregate/benches/percentile_cont.rsindex 05119441e1..17723ac1c2 100644--- a/datafusion/functions-aggregate/benches/percentile_cont.rs+++ b/datafusion/functions-aggregate/benches/percentile_cont.rs@@ -22,13 +22,17 @@ use arrow::array::{ArrayRef, Float64Array};use arrow::datatypes::{DataType, Field, Schema};use criterion::{BatchSize, Criterion, criterion_group, criterion_main};use datafusion_expr::function::AccumulatorArgs;+use datafusion_expr::groups_accumulator::GroupsAccumulator;use datafusion_expr::{Accumulator, AggregateUDFImpl};+use datafusion_functions_aggregate::approx_percentile_cont::ApproxPercentileAccumulator;use datafusion_functions_aggregate::percentile_cont::PercentileCont;+use datafusion_functions_aggregate_common::aggregate::groups_accumulator::GroupsAccumulatorAdapter;use datafusion_physical_expr::expressions::{col, lit};const STEP_SIZE: usize = 128;const SLIDES_PER_ITER: usize = 32;const WINDOW_SIZES: [usize; 3] = [256, 4096, 16384];+const ADAPTER_GROUPS: usize = 8192;fn prepare_accumulator() -> Box<dyn Accumulator> {let schema = Arc::new(Schema::new(vec![Field::new("f", DataType::Float64, true)]));@@ -99,6 +103,39 @@ fn sliding_window_bench(});}+fn grouped_adapter_benchmark(c: &mut Criterion) {+ let values = stream_array(ADAPTER_GROUPS, None);+ let group_indices: Vec<_> = (0..ADAPTER_GROUPS).collect();++ c.bench_function(+ "approx_percentile_cont/groups_accumulator_adapter/8192_groups",+ |b| {+ b.iter_batched(+ || {+ GroupsAccumulatorAdapter::new(|| {+ Ok(Box::new(ApproxPercentileAccumulator::new(+ 0.5,+ DataType::Float64,+ )) as Box<dyn Accumulator>)+ })+ },+ |mut accumulator| {+ accumulator+ .update_batch(+ std::slice::from_ref(&values),+ &group_indices,+ None,+ ADAPTER_GROUPS,+ )+ .unwrap();+ black_box(accumulator);+ },+ BatchSize::SmallInput,+ );+ },+ );+}+fn percentile_cont_benchmark(c: &mut Criterion) {for window_size in WINDOW_SIZES {let stream_len = window_size + STEP_SIZE * SLIDES_PER_ITER;@@ -125,5 +162,9 @@ fn percentile_cont_benchmark(c: &mut Criterion) {}}-criterion_group!(benches, percentile_cont_benchmark);+criterion_group!(+ benches,+ percentile_cont_benchmark,+ grouped_adapter_benchmark+);criterion_main!(benches);diff --git a/datafusion/functions-aggregate/src/array_agg.rs b/datafusion/functions-aggregate/src/array_agg.rsindex 8ea30a09f7..00c637ac3c 100644--- a/datafusion/functions-aggregate/src/array_agg.rs+++ b/datafusion/functions-aggregate/src/array_agg.rs@@ -43,8 +43,8 @@ use datafusion_common::{use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};use datafusion_expr::utils::format_state_name;use datafusion_expr::{- Accumulator, AggregateUDFImpl, Documentation, EmitTo, GroupsAccumulator, Signature,- Volatility,+ Accumulator, AggregateMetric, AggregateMetricRecorder, AggregateMetrics,+ AggregateUDFImpl, Documentation, EmitTo, GroupsAccumulator, Signature, Volatility,};use datafusion_functions_aggregate_common::aggregate::groups_accumulator::nulls::filter_to_nulls;use datafusion_functions_aggregate_common::order::AggregateOrderSensitivity;@@ -853,6 +853,7 @@ pub struct DistinctArrayAggAccumulator {datatype: DataType,sort_options: Option<SortOptions>,ignore_nulls: bool,+ distinct_metric: Option<Arc<dyn AggregateMetric>>,}/// Returns `true` if `dt` is, or recursively contains, a `Dictionary` type.@@ -888,6 +889,7 @@ impl DistinctArrayAggAccumulator {datatype: datatype.clone(),sort_options,ignore_nulls,+ distinct_metric: None,})}@@ -911,14 +913,12 @@ impl DistinctArrayAggAccumulator {}Ok(())}-}--impl Accumulator for DistinctArrayAggAccumulator {- fn state(&mut self) -> Result<Vec<ScalarValue>> {- Ok(vec![self.evaluate()?])- }- fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {+ fn update_batch_impl(+ &mut self,+ values: &[ArrayRef],+ record_metric: bool,+ ) -> Result<()> {if values.is_empty() {return Ok(());}@@ -948,68 +948,119 @@ impl Accumulator for DistinctArrayAggAccumulator {return Ok(());}- self.ensure_state(col.data_type())?;-- // Encode the entire incoming batch into rows_buffer in one pass.- let DistinctState {- converter,- group_rows,- counts,- row_hashes,- rows_buffer,- } = self.state.as_mut().unwrap();- rows_buffer.clear();- converter.append(rows_buffer, std::slice::from_ref(col))?;+ let distinct_metric = record_metric+ .then(|| self.distinct_metric.clone())+ .flatten();+ let mut metric_recorder = AggregateMetricRecorder::new(distinct_metric);+ {+ let _timer = metric_recorder.timer();+ self.ensure_state(col.data_type())?;- // Pre-compute all hashes for the batch in one SIMD-friendly pass.- self.hashes_buffer.clear();- self.hashes_buffer.resize(col.len(), 0);- create_hashes(- std::slice::from_ref(col),- &self.random_state,- &mut self.hashes_buffer,- )?;+ // Encode the entire incoming batch into rows_buffer in one pass.+ let DistinctState {+ converter,+ group_rows,+ counts,+ row_hashes,+ rows_buffer,+ } = self.state.as_mut().unwrap();+ rows_buffer.clear();+ converter.append(rows_buffer, std::slice::from_ref(col))?;++ // Pre-compute all hashes for the batch in one SIMD-friendly pass.+ self.hashes_buffer.clear();+ self.hashes_buffer.resize(col.len(), 0);+ create_hashes(+ std::slice::from_ref(col),+ &self.random_state,+ &mut self.hashes_buffer,+ )?;- for (row_idx, &hash) in self.hashes_buffer.iter().enumerate() {- let row = rows_buffer.row(row_idx);- let entry = self.map.find_mut(hash, |&(h, group_idx)| {- h == hash && group_rows[group_idx].row() == row- });- match entry {- Some((_, group_idx)) => {- // Already known: just increment the live refcount.- counts[*group_idx] += 1;- }- None => {- // New distinct value: own the encoded row, record it.- let new_group_idx = group_rows.len();- group_rows.push(row.owned());- counts.push(1);- row_hashes.push(hash);- self.map.insert_accounted(- (hash, new_group_idx),- |&(h, _)| h,- &mut self.map_size,- );+ for (row_idx, &hash) in self.hashes_buffer.iter().enumerate() {+ let row = rows_buffer.row(row_idx);+ let entry = self.map.find_mut(hash, |&(h, group_idx)| {+ h == hash && group_rows[group_idx].row() == row+ });+ match entry {+ Some((_, group_idx)) => {+ // Already known: just increment the live refcount.+ counts[*group_idx] += 1;+ }+ None => {+ // New distinct value: own the encoded row, record it.+ let new_group_idx = group_rows.len();+ group_rows.push(row.owned());+ counts.push(1);+ row_hashes.push(hash);+ self.map.insert_accounted(+ (hash, new_group_idx),+ |&(h, _)| h,+ &mut self.map_size,+ );+ }}}+ Ok(())}- Ok(())}- fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {+ fn merge_batch_impl(+ &mut self,+ states: &[ArrayRef],+ record_metric: bool,+ ) -> Result<()> {if states.is_empty() {return Ok(());}assert_eq_or_internal_err!(states.len(), 1, "expects single state");- // The DISTINCT state is `List<value>`.- states[0]- .as_list::<i32>()- .iter()- .flatten()- .try_for_each(|val| self.update_batch(&[val]))+ let distinct_metric = record_metric+ .then(|| self.distinct_metric.clone())+ .flatten();+ let mut metric_recorder = AggregateMetricRecorder::new(distinct_metric);++ // The DISTINCT state is `List<value>`. This calls the update+ // implementation once per state row, so record the submetric once for+ // the entire merge rather than once per row.+ {+ let _timer = metric_recorder.timer();+ states[0]+ .as_list::<i32>()+ .iter()+ .flatten()+ .try_for_each(|val| self.update_batch_impl(&[val], false))+ }+ }+}++impl Accumulator for DistinctArrayAggAccumulator {+ fn set_metrics(&mut self, metrics: Arc<dyn AggregateMetrics>) {+ self.distinct_metric = Some(metrics.metric("distinct"));+ }++ fn grouped_update_batch_metric(&self) -> Option<Arc<dyn AggregateMetric>> {+ self.distinct_metric.clone()+ }++ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {+ self.update_batch_impl(values, true)+ }++ fn update_batch_grouped(&mut self, values: &[ArrayRef]) -> Result<()> {+ self.update_batch_impl(values, false)+ }++ fn state(&mut self) -> Result<Vec<ScalarValue>> {+ Ok(vec![self.evaluate()?])+ }++ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {+ self.merge_batch_impl(states, true)+ }++ fn merge_batch_grouped(&mut self, states: &[ArrayRef]) -> Result<()> {+ self.merge_batch_impl(states, false)}fn evaluate(&mut self) -> Result<ScalarValue> {@@ -1650,13 +1701,113 @@ impl Accumulator for OrderSensitiveArrayAggAccumulator {#[cfg(test)]mod tests {use super::*;- use arrow::array::{ListBuilder, StringBuilder};+ use arrow::array::{Int32Builder, ListBuilder, StringBuilder};use arrow::datatypes::Schema;use datafusion_common::cast::as_generic_string_array;use datafusion_common::internal_err;use datafusion_physical_expr::PhysicalExpr;use datafusion_physical_expr::expressions::Column;use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;+ use std::sync::atomic::{AtomicUsize, Ordering};++ #[derive(Debug)]+ struct CountingMetric(Arc<AtomicUsize>);++ impl AggregateMetric for CountingMetric {+ fn add_duration(&self, _duration: std::time::Duration) {+ self.0.fetch_add(1, Ordering::Relaxed);+ }+ }++ #[derive(Debug)]+ struct CountingMetrics(Arc<AtomicUsize>);++ impl AggregateMetrics for CountingMetrics {+ fn metric(&self, _subphase: &'static str) -> Arc<dyn AggregateMetric> {+ Arc::new(CountingMetric(Arc::clone(&self.0)))+ }+ }++ #[test]+ fn distinct_accumulator_records_metric_for_small_batches() -> Result<()> {+ let metric_updates = Arc::new(AtomicUsize::new(0));+ let mut accumulator =+ DistinctArrayAggAccumulator::try_new(&DataType::Int32, None, false)?;+ accumulator.set_metrics(Arc::new(CountingMetrics(Arc::clone(&metric_updates))));++ accumulator.update_batch(&[Arc::new(Int32Array::from(vec![1]))])?;++ assert_eq!(metric_updates.load(Ordering::Relaxed), 1);+ Ok(())+ }++ #[test]+ fn distinct_accumulator_records_metric_on_update_error() -> Result<()> {+ use arrow::array::StringArray;++ let metric_updates = Arc::new(AtomicUsize::new(0));+ let mut accumulator =+ DistinctArrayAggAccumulator::try_new(&DataType::Int32, None, false)?;+ accumulator.set_metrics(Arc::new(CountingMetrics(Arc::clone(&metric_updates))));++ accumulator.update_batch(&[Arc::new(Int32Array::from(vec![1]))])?;+ metric_updates.store(0, Ordering::Relaxed);++ let result =+ accumulator.update_batch(&[Arc::new(StringArray::from(vec!["bad"]))]);++ assert!(result.is_err());+ assert_eq!(metric_updates.load(Ordering::Relaxed), 1);+ Ok(())+ }++ #[test]+ fn distinct_accumulator_records_metric_for_large_batches() -> Result<()> {+ let metric_updates = Arc::new(AtomicUsize::new(0));+ let mut accumulator =+ DistinctArrayAggAccumulator::try_new(&DataType::Int32, None, false)?;+ accumulator.set_metrics(Arc::new(CountingMetrics(Arc::clone(&metric_updates))));++ accumulator.update_batch(&[Arc::new(Int32Array::from(vec![1; 16]))])?;++ assert_eq!(metric_updates.load(Ordering::Relaxed), 1);+ Ok(())+ }++ #[test]+ fn distinct_accumulator_records_merge_metric_once() -> Result<()> {+ let mut builder = ListBuilder::new(Int32Builder::new());+ for value in [1, 2, 3] {+ builder.append_value([Some(value)]);+ }+ let state: ArrayRef = Arc::new(builder.finish());++ let metric_updates = Arc::new(AtomicUsize::new(0));+ let mut target =+ DistinctArrayAggAccumulator::try_new(&DataType::Int32, None, false)?;+ target.set_metrics(Arc::new(CountingMetrics(Arc::clone(&metric_updates))));+ target.merge_batch(&[state])?;++ assert_eq!(metric_updates.load(Ordering::Relaxed), 1);+ Ok(())+ }++ #[test]+ fn distinct_accumulator_preserves_unwind_auto_traits() {+ fn assert_unwind_traits<T: std::panic::UnwindSafe + std::panic::RefUnwindSafe>() {+ }++ assert_unwind_traits::<DistinctArrayAggAccumulator>();+ }++ #[test]+ fn distinct_accumulator_size_includes_metric_handle() -> Result<()> {+ let accumulator =+ DistinctArrayAggAccumulator::try_new(&DataType::Int32, None, false)?;++ assert_eq!(accumulator.size(), size_of_val(&accumulator));+ Ok(())+ }#[test]fn no_duplicates_no_distinct() -> Result<()> {@@ -1944,7 +2095,7 @@ mod tests {acc2.update_batch(&[string_list_data([vec!["e", "f", "g"]])])?;acc1 = merge(acc1, acc2)?;- assert_eq!(acc1.size(), 2274);+ assert_eq!(acc1.size(), 2290);Ok(())}diff --git a/datafusion/physical-expr-common/src/metrics/value.rs b/datafusion/physical-expr-common/src/metrics/value.rsindex 64416b0104..cd0ac1d6d1 100644--- a/datafusion/physical-expr-common/src/metrics/value.rs+++ b/datafusion/physical-expr-common/src/metrics/value.rs@@ -203,6 +203,15 @@ impl Time {self.nanos.fetch_add(more_nanos.max(1), Ordering::Relaxed);}+ /// Adds a duration without rounding it up to one nanosecond.+ ///+ /// Use only for metrics that record many independent operations, where a+ /// minimum per recording would materially inflate the total.+ pub fn add_duration_exact(&self, duration: Duration) {+ self.nanos+ .fetch_add(duration.as_nanos() as usize, Ordering::Relaxed);+ }+/// Add the number of nanoseconds of other `Time` to selfpub fn add(&self, other: &Time) {self.add_duration(Duration::from_nanos(other.value() as u64))@@ -1276,6 +1285,14 @@ mod tests {}}+ #[test]+ fn test_time_merge_marks_a_zero_duration_measurement_as_recorded() {+ let merged = Time::new();+ merged.add(&Time::new());++ assert_eq!(merged.value(), 1);+ }+#[test]fn test_display_ratio() {let ratio_metrics = RatioMetrics::new();diff --git a/datafusion/physical-expr/src/aggregate.rs b/datafusion/physical-expr/src/aggregate.rsindex df22bc69d8..a660a272b9 100644--- a/datafusion/physical-expr/src/aggregate.rs+++ b/datafusion/physical-expr/src/aggregate.rs@@ -53,7 +53,7 @@ use datafusion_expr::expr::{};use datafusion_expr::physical_planning_context::PhysicalPlanningContext;use datafusion_expr::{AggregateUDF, Expr, ReversedUDAF, SetMonotonicity};-use datafusion_expr_common::accumulator::Accumulator;+use datafusion_expr_common::accumulator::{Accumulator, AggregateMetrics};use datafusion_expr_common::groups_accumulator::GroupsAccumulator;use datafusion_expr_common::type_coercion::aggregates::check_arg_count;use datafusion_functions_aggregate_common::accumulator::{@@ -747,6 +747,16 @@ impl AggregateFunctionExpr {self.fun.accumulator(acc_args)}+ /// Creates an accumulator and supplies optional aggregate-owned metrics.+ pub fn create_accumulator_with_metrics(+ &self,+ metrics: Arc<dyn AggregateMetrics>,+ ) -> Result<Box<dyn Accumulator>> {+ let mut accumulator = self.create_accumulator()?;+ accumulator.set_metrics(metrics);+ Ok(accumulator)+ }+/// the field of the final result of this aggregation.pub fn state_fields(&self) -> Result<Vec<FieldRef>> {let args = StateFieldsArgs {@@ -928,6 +938,16 @@ impl AggregateFunctionExpr {self.fun.create_groups_accumulator(args)}+ /// Creates a groups accumulator and supplies optional aggregate-owned metrics.+ pub fn create_groups_accumulator_with_metrics(+ &self,+ metrics: Arc<dyn AggregateMetrics>,+ ) -> Result<Box<dyn GroupsAccumulator>> {+ let mut accumulator = self.create_groups_accumulator()?;+ accumulator.set_metrics(metrics);+ Ok(accumulator)+ }+/// Construct an expression that calculates the aggregate in reverse./// Typically the "reverse" expression is itself (e.g. SUM, COUNT)./// For aggregates that do not support calculation in reverse,diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rsindex 5f10195087..f517f6a998 100644--- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs+++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs@@ -28,7 +28,7 @@ use arrow::datatypes::SchemaRef;use arrow::record_batch::RecordBatch;use datafusion_common::{Result, internal_err};use datafusion_execution::memory_pool::proxy::VecAllocExt;-use datafusion_expr::{EmitTo, GroupsAccumulator};+use datafusion_expr::{AggregateMetrics, EmitTo, GroupsAccumulator};use datafusion_physical_expr::aggregate::AggregateFunctionExpr;use crate::PhysicalExpr;@@ -92,6 +92,9 @@ pub(in crate::aggregates) struct AggregateHashTable<AggrMode> {/// Per-aggregate timing metrics for accumulator operations.pub(super) aggregate_accumulator_metrics: Arc<AggregateAccumulatorMetrics>,+ /// Optional internal metrics owned by each aggregate expression.+ pub(super) aggregate_submetrics: Vec<Arc<dyn AggregateMetrics>>,+/// Raw input schema, used to evaluate expressions and synthesize empty/// grouping-set rows.pub(super) input_schema: SchemaRef,@@ -127,6 +130,7 @@ impl<AggrMode> AggregateHashTable<AggrMode> {}let input_schema = agg.input().schema();+ let metrics = AggregateTableMetrics::new(agg, partition);let aggregate_arguments = aggregate_expressions(&agg.aggr_expr,&agg.mode,@@ -137,13 +141,16 @@ impl<AggrMode> AggregateHashTable<AggrMode> {.iter().zip(aggregate_arguments).zip(filters)- .map(|((agg_expr, arguments), filter)| {- let accumulator = create_group_accumulator(agg_expr)?;+ .zip(metrics.submetrics.iter())+ .map(|(((agg_expr, arguments), filter), submetrics)| {+ let accumulator =+ create_group_accumulator(agg_expr, Arc::clone(submetrics))?;Ok(HashAggregateAccumulator::new(Arc::clone(agg_expr),arguments,filter,accumulator,+ Arc::clone(submetrics),))}).collect::<Result<_>>()?;@@ -151,12 +158,11 @@ impl<AggrMode> AggregateHashTable<AggrMode> {let group_schema = agg.group_by.group_schema(&input_schema)?;let group_values = new_group_values(group_schema, &GroupOrdering::None)?;- let metrics = AggregateTableMetrics::new(agg, partition);-Ok(Self {group_by_metrics: metrics.group_by,aggregate_argument_metrics: metrics.aggregate_arguments,aggregate_accumulator_metrics: metrics.accumulator,+ aggregate_submetrics: metrics.submetrics,input_schema,output_schema,state_schema,@@ -506,6 +512,9 @@ pub(super) struct HashAggregateAccumulator {/// Accumulator state for all groups for one aggregate expression.accumulator: Box<dyn GroupsAccumulator>,++ /// Optional internal metrics owned by this aggregate expression.+ submetrics: Arc<dyn AggregateMetrics>,}pub(super) type AggregateAccumulator = HashAggregateAccumulator;@@ -683,24 +692,28 @@ impl HashAggregateAccumulator {arguments: Vec<Arc<dyn PhysicalExpr>>,filter: Option<Arc<dyn PhysicalExpr>>,accumulator: Box<dyn GroupsAccumulator>,+ submetrics: Arc<dyn AggregateMetrics>,) -> Self {Self {aggregate_expr,arguments,filter,accumulator,+ submetrics,}}/// Construct a new accumulator with the same definition, but with empty internal/// state buffers (empty [`GroupsAccumulator`]).pub(super) fn empty_like(&self) -> Result<Self> {- let accumulator = create_group_accumulator(&self.aggregate_expr)?;+ let accumulator =+ create_group_accumulator(&self.aggregate_expr, Arc::clone(&self.submetrics))?;Ok(Self::new(Arc::clone(&self.aggregate_expr),self.arguments.clone(),self.filter.clone(),accumulator,+ Arc::clone(&self.submetrics),))}@@ -897,6 +910,7 @@ mod tests {use datafusion_physical_expr::expressions::Column;use super::*;+ use crate::aggregates::group_values::aggregate_sub_metrics;use crate::metrics::ExecutionPlanMetricsSet;#[test]@@ -955,8 +969,11 @@ mod tests {Arc::new(BooleanArray::from(vec![true, false, true, false])),],)?;- let accumulator = sum_accumulator(&schema, "include", 1)?;let metrics = ExecutionPlanMetricsSet::new();+ let submetrics = aggregate_sub_metrics(&metrics, 0, ["SUM(value)"])+ .pop()+ .expect("one aggregate submetric factory");+ let accumulator = sum_accumulator(&schema, "include", 1, submetrics)?;let group_by_metrics = GroupByMetrics::new(&metrics, 0);let argument_metrics = AggregateArgumentMetrics::new(&metrics, 0, ["SUM(value)"]);let accumulator_metrics = AggregateAccumulatorMetrics::new(@@ -998,6 +1015,7 @@ mod tests {schema: &SchemaRef,filter_name: &str,filter_index: usize,+ submetrics: Arc<dyn AggregateMetrics>,) -> Result<HashAggregateAccumulator> {let argument: Arc<dyn PhysicalExpr> = Arc::new(Column::new("value", 0));let aggregate_expr = Arc::new(@@ -1006,12 +1024,14 @@ mod tests {.alias("SUM(value)").build()?,);- let accumulator = create_group_accumulator(&aggregate_expr)?;+ let accumulator =+ create_group_accumulator(&aggregate_expr, Arc::clone(&submetrics))?;Ok(HashAggregateAccumulator::new(aggregate_expr,vec![argument],Some(Arc::new(Column::new(filter_name, filter_index))),accumulator,+ submetrics,))}diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_ordered.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_ordered.rsindex 97ef898b51..6446c2ecc1 100644--- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_ordered.rs+++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_ordered.rs@@ -26,7 +26,7 @@ use arrow::record_batch::RecordBatch;use datafusion_common::Result;use datafusion_common::assert_or_internal_err;use datafusion_execution::memory_pool::proxy::VecAllocExt;-use datafusion_expr::EmitTo;+use datafusion_expr::{AggregateMetrics, EmitTo};use crate::InputOrderMode;use crate::PhysicalExpr;@@ -52,6 +52,7 @@ pub(in crate::aggregates) struct OrderedAggregateTableMetrics {pub(super) group_by: GroupByMetrics,pub(super) aggregate_arguments: AggregateArgumentMetrics,pub(super) accumulator: Arc<AggregateAccumulatorMetrics>,+ pub(super) submetrics: Vec<Arc<dyn AggregateMetrics>>,}impl OrderedAggregateTableMetrics {@@ -61,6 +62,7 @@ impl OrderedAggregateTableMetrics {group_by: metrics.group_by,aggregate_arguments: metrics.aggregate_arguments,accumulator: metrics.accumulator,+ submetrics: metrics.submetrics,}}@@ -71,6 +73,7 @@ impl OrderedAggregateTableMetrics {group_by: table.group_by_metrics.clone(),aggregate_arguments: table.aggregate_argument_metrics.clone(),accumulator: Arc::clone(&table.aggregate_accumulator_metrics),+ submetrics: table.aggregate_submetrics.clone(),}}}@@ -138,6 +141,9 @@ pub(in crate::aggregates) struct OrderedAggregateTable<OrderedAggrMode> {/// Per-aggregate timing metrics for accumulator operations.pub(super) aggregate_accumulator_metrics: Arc<AggregateAccumulatorMetrics>,+ /// Optional internal metrics owned by each aggregate expression.+ pub(super) aggregate_submetrics: Vec<Arc<dyn AggregateMetrics>>,+/// Group keys, ordering state, and accumulator states.pub(super) buffer: OrderedAggregateTableBuffer,@@ -207,13 +213,16 @@ impl<AggrMode> OrderedAggregateTable<AggrMode> {.iter().zip(aggregate_arguments).zip(filters)- .map(|((agg_expr, arguments), filter)| {- let accumulator = create_group_accumulator(agg_expr)?;+ .zip(metrics.submetrics.iter())+ .map(|(((agg_expr, arguments), filter), submetrics)| {+ let accumulator =+ create_group_accumulator(agg_expr, Arc::clone(submetrics))?;Ok(AggregateAccumulator::new(Arc::clone(agg_expr),arguments,filter,accumulator,+ Arc::clone(submetrics),))}).collect::<Result<_>>()?;@@ -225,6 +234,7 @@ impl<AggrMode> OrderedAggregateTable<AggrMode> {group_by_metrics: metrics.group_by,aggregate_argument_metrics: metrics.aggregate_arguments,aggregate_accumulator_metrics: metrics.accumulator,+ aggregate_submetrics: metrics.submetrics,buffer: OrderedAggregateTableBuffer {group_by: Arc::clone(&agg.group_by),group_ordering,@@ -308,6 +318,7 @@ impl<AggrMode> OrderedAggregateTable<AggrMode> {group_by: self.group_by_metrics.clone(),aggregate_arguments: self.aggregate_argument_metrics.clone(),accumulator: Arc::clone(&self.aggregate_accumulator_metrics),+ submetrics: self.aggregate_submetrics.clone(),}}diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rsindex 902a859bac..29ef4a662f 100644--- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs+++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs@@ -29,9 +29,10 @@ use std::sync::Arc;use crate::aggregates::group_values::{AccumulatorPhase, AggregateAccumulatorMetrics, AggregateArgumentMetrics,- GroupByMetrics,+ GroupByMetrics, aggregate_sub_metrics,};use crate::aggregates::{AggregateExec, AggregateMode, aggregate_metric_label};+use datafusion_expr::AggregateMetrics;pub(super) fn accumulator_phases(mode: &AggregateMode) -> &'static [AccumulatorPhase] {match mode {@@ -63,6 +64,7 @@ pub(super) struct AggregateTableMetrics {pub(super) group_by: GroupByMetrics,pub(super) aggregate_arguments: AggregateArgumentMetrics,pub(super) accumulator: Arc<AggregateAccumulatorMetrics>,+ pub(super) submetrics: Vec<Arc<dyn AggregateMetrics>>,}impl AggregateTableMetrics {@@ -75,6 +77,11 @@ impl AggregateTableMetrics {Self {group_by: GroupByMetrics::new(&agg.metrics, partition),+ submetrics: aggregate_sub_metrics(+ &agg.metrics,+ partition,+ aggregate_labels.iter().cloned(),+ ),aggregate_arguments: AggregateArgumentMetrics::new(&agg.metrics,partition,diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rsindex 377abdae71..90f8193034 100644--- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs+++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs@@ -91,6 +91,7 @@ impl AggregateHashTable<PartialMarker> {aggregate_accumulator_metrics: Arc::clone(&self.aggregate_accumulator_metrics,),+ aggregate_submetrics: self.aggregate_submetrics.clone(),input_schema: Arc::clone(&self.input_schema),output_schema: Arc::clone(&self.output_schema),state_schema: Arc::clone(&self.state_schema),diff --git a/datafusion/physical-plan/src/aggregates/aggregate_stream.rs b/datafusion/physical-plan/src/aggregates/aggregate_stream.rsindex 862a44cb20..3ce7915806 100644--- a/datafusion/physical-plan/src/aggregates/aggregate_stream.rs+++ b/datafusion/physical-plan/src/aggregates/aggregate_stream.rs@@ -19,11 +19,12 @@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,+ aggregate_metric_label, create_accumulators_with_metrics,};use crate::metrics::{BaselineMetrics, RecordOutput};use crate::stream::EmptyRecordBatchStream;@@ -304,12 +305,19 @@ impl AggregateStream {AggregateInputMode::Raw => agg_filter_expr,AggregateInputMode::Partial => vec![None; agg.aggr_expr.len()].into(),};- let accumulators = create_accumulators(&agg.aggr_expr)?;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,@@ -573,9 +581,9 @@ mod tests {use crate::metrics::{MetricValue, MetricsSet};use crate::test::TestMemoryExec;use crate::{ExecutionPlan, collect};- use arrow::array::Float64Array;+ use arrow::array::{Float64Array, UInt32Array};use arrow::datatypes::{DataType, Field, Schema};- use datafusion_functions_aggregate::sum::sum_udaf;+ use datafusion_functions_aggregate::{array_agg::array_agg_udaf, sum::sum_udaf};use datafusion_physical_expr::aggregate::{AggregateExprBuilder, AggregateFunctionExpr,};@@ -594,6 +602,20 @@ mod tests {))}+ 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()@@ -706,6 +728,171 @@ mod tests {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 _ = crate::common::collect(+ 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![diff --git a/datafusion/physical-plan/src/aggregates/group_values/metrics.rs b/datafusion/physical-plan/src/aggregates/group_values/metrics.rsindex 5e66fe496e..97f9e050c9 100644--- a/datafusion/physical-plan/src/aggregates/group_values/metrics.rs+++ b/datafusion/physical-plan/src/aggregates/group_values/metrics.rs@@ -18,6 +18,105 @@//! Metrics for the various group-by implementations.use crate::metrics::{ExecutionPlanMetricsSet, MetricBuilder, Time};+use datafusion_expr::{AggregateMetric, AggregateMetrics};+use parking_lot::Mutex;+use std::collections::HashMap;+use std::sync::{Arc, OnceLock};+use std::time::Duration;++/// Lazily registers optional internal metrics for one aggregate expression.+///+/// The physical aggregate operator owns the expression index and label. Aggregate+/// implementations can only supply stable subphase identifiers through+/// [`AggregateMetrics`].+#[derive(Debug)]+struct AggregateSubMetrics {+ metrics: ExecutionPlanMetricsSet,+ partition: usize,+ index: usize,+ aggregate_label: String,+ /// The first subphase is the common case. Keep it lock-free because an+ /// accumulator adapter creates one accumulator per group.+ first_subphase_metric: OnceLock<(&'static str, Arc<dyn AggregateMetric>)>,+ additional_subphase_metrics: Mutex<HashMap<&'static str, Arc<dyn AggregateMetric>>>,+}++impl AggregateSubMetrics {+ fn new(+ metrics: &ExecutionPlanMetricsSet,+ partition: usize,+ index: usize,+ aggregate_label: impl Into<String>,+ ) -> Self {+ Self {+ metrics: metrics.clone(),+ partition,+ index,+ aggregate_label: aggregate_label.into(),+ first_subphase_metric: OnceLock::new(),+ additional_subphase_metrics: Mutex::new(HashMap::new()),+ }+ }++ fn new_metric(&self, subphase: &'static str) -> Arc<dyn AggregateMetric> {+ let time = MetricBuilder::new(&self.metrics)+ .with_new_label("aggregate", self.aggregate_label.clone())+ .subset_time(+ format!("agg_expr_{}_internal_{}_time", self.index, subphase),+ self.partition,+ );+ Arc::new(AggregateSubMetric { time })+ }+}++#[derive(Debug)]+struct AggregateSubMetric {+ time: Time,+}++impl AggregateMetric for AggregateSubMetric {+ fn add_duration(&self, duration: Duration) {+ self.time.add_duration_exact(duration);+ }+}++impl AggregateMetrics for AggregateSubMetrics {+ fn metric(&self, subphase: &'static str) -> Arc<dyn AggregateMetric> {+ // `get_or_init` already takes a lock-free fast path when the cell is+ // initialized, so the common repeat lookup never allocates or locks.+ let (registered_subphase, metric) = self+ .first_subphase_metric+ .get_or_init(|| (subphase, self.new_metric(subphase)));+ if *registered_subphase == subphase {+ return Arc::clone(metric);+ }++ let mut additional_subphase_metrics = self.additional_subphase_metrics.lock();+ Arc::clone(+ additional_subphase_metrics+ .entry(subphase)+ .or_insert_with(|| self.new_metric(subphase)),+ )+ }+}++pub(crate) fn aggregate_sub_metrics<T>(+ metrics: &ExecutionPlanMetricsSet,+ partition: usize,+ aggregate_labels: impl IntoIterator<Item = T>,+) -> Vec<Arc<dyn AggregateMetrics>>+where+ T: Into<String>,+{+ aggregate_labels+ .into_iter()+ .enumerate()+ .map(|(index, label)| {+ Arc::new(AggregateSubMetrics::new(metrics, partition, index, label))+ as Arc<dyn AggregateMetrics>+ })+ .collect()+}#[derive(Clone)]pub(crate) struct AggregateArgumentMetrics {@@ -221,7 +320,7 @@ impl GroupByMetrics {#[cfg(test)]mod tests {- use super::GroupByMetrics;+ use super::{AggregateSubMetrics, GroupByMetrics, aggregate_sub_metrics};use crate::aggregates::{AggregateExec, AggregateMode, PhysicalGroupBy};use crate::metrics::{ExecutionPlanMetricsSet, MetricValue, MetricsSet};use crate::test::TestMemoryExec;@@ -233,6 +332,7 @@ mod tests {use datafusion_execution::TaskContext;use datafusion_execution::config::SessionConfig;use datafusion_execution::runtime_env::RuntimeEnvBuilder;+ use datafusion_expr::AggregateMetrics;use datafusion_functions_aggregate::count::count_udaf;use datafusion_functions_aggregate::sum::sum_udaf;use datafusion_physical_expr::aggregate::{@@ -240,6 +340,123 @@ mod tests {};use datafusion_physical_expr::expressions::col;use std::sync::Arc;+ use std::time::Duration;++ #[test]+ fn aggregate_submetrics_cache_first_subphase() {+ let metric_set = ExecutionPlanMetricsSet::new();+ let metrics =+ AggregateSubMetrics::new(&metric_set, 0, 0, "array_agg(DISTINCT a)");++ metrics.metric("distinct");++ assert_eq!(+ metrics+ .first_subphase_metric+ .get()+ .map(|(subphase, _)| *subphase),+ Some("distinct")+ );+ }++ #[test]+ fn aggregate_submetrics_reuse_metric_identity_for_one_subphase() {+ let metrics = ExecutionPlanMetricsSet::new();+ let submetrics = aggregate_sub_metrics(&metrics, 0, ["array_agg(DISTINCT a)"]);++ let first = submetrics[0].metric("distinct");+ let second = submetrics[0].metric("distinct");+ first.add_duration(Duration::from_nanos(1));+ second.add_duration(Duration::from_nanos(2));++ let metrics = metrics.clone_inner();+ let matching_metrics = metrics+ .iter()+ .filter(|metric| metric.value().name() == "agg_expr_0_internal_distinct_time")+ .collect::<Vec<_>>();+ assert_eq!(matching_metrics.len(), 1);+ assert_eq!(matching_metrics[0].value().as_usize(), 3);+ }++ #[test]+ fn aggregate_submetrics_preserve_zero_duration_per_recording() {+ let metrics = ExecutionPlanMetricsSet::new();+ let submetrics = aggregate_sub_metrics(&metrics, 0, ["array_agg(DISTINCT a)"]);++ submetrics[0]+ .metric("distinct")+ .add_duration(Duration::ZERO);++ assert_eq!(+ metrics+ .clone_inner()+ .iter()+ .find(|metric| {+ metric.value().name() == "agg_expr_0_internal_distinct_time"+ })+ .unwrap()+ .value()+ .as_usize(),+ 0+ );+ }++ #[test]+ fn aggregate_submetrics_support_multiple_subphases() {+ let metrics = ExecutionPlanMetricsSet::new();+ let submetrics = aggregate_sub_metrics(&metrics, 0, ["array_agg(DISTINCT a)"]);++ submetrics[0]+ .metric("distinct")+ .add_duration(Duration::from_nanos(1));+ submetrics[0]+ .metric("sort")+ .add_duration(Duration::from_nanos(2));++ let metrics = metrics.clone_inner();+ assert_eq!(+ metrics+ .sum_by_name("agg_expr_0_internal_distinct_time")+ .unwrap()+ .as_usize(),+ 1+ );+ assert_eq!(+ metrics+ .sum_by_name("agg_expr_0_internal_sort_time")+ .unwrap()+ .as_usize(),+ 2+ );+ }++ #[test]+ fn aggregate_submetrics_merge_across_partitions() {+ let metrics = ExecutionPlanMetricsSet::new();+ let partition_0 = aggregate_sub_metrics(&metrics, 0, ["array_agg(DISTINCT a)"]);+ let partition_1 = aggregate_sub_metrics(&metrics, 1, ["array_agg(DISTINCT a)"]);++ partition_0[0]+ .metric("distinct")+ .add_duration(Duration::from_nanos(1));+ partition_0[0]+ .metric("distinct")+ .add_duration(Duration::from_nanos(2));+ partition_1[0]+ .metric("distinct")+ .add_duration(Duration::from_nanos(3));++ let metrics = metrics.clone_inner();+ let metric_name = "agg_expr_0_internal_distinct_time";+ assert_eq!(metrics.sum_by_name(metric_name).unwrap().as_usize(), 6);+ assert!(metrics.iter().all(|metric| {+ metric.value().name() == metric_name+ && metric.labels().iter().any(|label| {+ label.name() == "aggregate"+ && label.value() == "array_agg(DISTINCT a)"+ })+ }));+ }/// Helper function to verify all three GroupBy metrics exist and have non-zero valuesfn assert_groupby_metrics(metrics: &MetricsSet) {diff --git a/datafusion/physical-plan/src/aggregates/group_values/mod.rs b/datafusion/physical-plan/src/aggregates/group_values/mod.rsindex b764fd7792..80e6b335e3 100644--- a/datafusion/physical-plan/src/aggregates/group_values/mod.rs+++ b/datafusion/physical-plan/src/aggregates/group_values/mod.rs@@ -51,7 +51,7 @@ mod null_builder;pub(crate) use metrics::{AccumulatorPhase, AggregateAccumulatorMetrics, AggregateArgumentMetrics,- GroupByMetrics,+ GroupByMetrics, aggregate_sub_metrics,};/// Stores the group values during hash aggregation.diff --git a/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs b/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rsindex d8f2543996..f8d427f207 100644--- a/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs+++ b/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs@@ -40,7 +40,7 @@ use super::skip_partial::SkipAggregationProbe;use super::{AggregateExec, format_human_display};use crate::aggregates::group_values::{AccumulatorPhase, AggregateAccumulatorMetrics, AggregateArgumentMetrics,- GroupByMetrics, GroupValues, new_group_values,+ GroupByMetrics, GroupValues, aggregate_sub_metrics, new_group_values,};use crate::aggregates::order::GroupOrderingFull;use crate::aggregates::{@@ -64,7 +64,7 @@ use datafusion_common::{use datafusion_execution::TaskContext;use datafusion_execution::memory_pool::proxy::VecAllocExt;use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};-use datafusion_expr::{EmitTo, GroupsAccumulator};+use datafusion_expr::{AggregateMetrics, EmitTo, GroupsAccumulator};use datafusion_physical_expr::aggregate::AggregateFunctionExpr;use datafusion_physical_expr::expressions::Column;use datafusion_physical_expr::{GroupsAccumulatorAdapter, PhysicalSortExpr};@@ -418,6 +418,11 @@ impl GroupedHashAggregateStream {partition,aggregate_labels.iter().cloned(),);+ let aggregate_submetrics = aggregate_sub_metrics(+ &agg.metrics,+ partition,+ aggregate_labels.iter().cloned(),+ );let aggregate_accumulator_metrics = AggregateAccumulatorMetrics::new(&agg.metrics,partition,@@ -451,7 +456,8 @@ impl GroupedHashAggregateStream {// Instantiate the accumulatorslet accumulators: Vec<_> = aggregate_exprs.iter()- .map(create_group_accumulator)+ .zip(aggregate_submetrics)+ .map(|(agg_expr, metrics)| create_group_accumulator(agg_expr, metrics)).collect::<Result<_>>()?;let group_schema = agg_group_by.group_schema(&agg.input().schema())?;@@ -651,18 +657,21 @@ impl GroupedHashAggregateStream {/// [`GroupsAccumulatorAdapter`] if not.pub(crate) fn create_group_accumulator(agg_expr: &Arc<AggregateFunctionExpr>,+ metrics: Arc<dyn AggregateMetrics>,) -> Result<Box<dyn GroupsAccumulator>> {if agg_expr.groups_accumulator_supported() {- agg_expr.create_groups_accumulator()+ agg_expr.create_groups_accumulator_with_metrics(metrics)} else {// Note in the log when the slow path is useddebug!("Creating GroupsAccumulatorAdapter for {}: {agg_expr:?}",agg_expr.name());- let agg_expr_captured = Arc::clone(agg_expr);- let factory = move || agg_expr_captured.create_accumulator();- Ok(Box::new(GroupsAccumulatorAdapter::new(factory)))+ let agg_expr = Arc::clone(agg_expr);+ let mut adapter =+ GroupsAccumulatorAdapter::new(move || agg_expr.create_accumulator());+ adapter.set_metrics(metrics);+ Ok(Box::new(adapter))}}@@ -1496,12 +1505,172 @@ mod tests {use crate::ExecutionPlan;use crate::InputOrderMode;use crate::test::TestMemoryExec;- use arrow::array::{Int32Array, Int64Array};+ use arrow::array::{Int32Array, Int64Array, UInt32Array};use arrow::datatypes::{DataType, Field, Schema};use datafusion_execution::runtime_env::RuntimeEnvBuilder;- use datafusion_functions_aggregate::count::count_udaf;+ use datafusion_expr::AggregateMetric;+ use datafusion_functions_aggregate::{array_agg::array_agg_udaf, count::count_udaf};use datafusion_physical_expr::aggregate::AggregateExprBuilder;use datafusion_physical_expr::expressions::col;+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::time::Duration;++ #[derive(Debug)]+ struct CountingMetric(Arc<AtomicUsize>);++ impl AggregateMetric for CountingMetric {+ fn add_duration(&self, _duration: Duration) {+ self.0.fetch_add(1, Ordering::Relaxed);+ }+ }++ #[derive(Debug)]+ struct CountingMetrics {+ resolutions: Arc<AtomicUsize>,+ durations: Arc<AtomicUsize>,+ }++ impl AggregateMetrics for CountingMetrics {+ fn metric(&self, _subphase: &'static str) -> Arc<dyn AggregateMetric> {+ self.resolutions.fetch_add(1, Ordering::Relaxed);+ Arc::new(CountingMetric(Arc::clone(&self.durations)))+ }+ }++ #[test]+ fn legacy_grouped_distinct_installs_metrics_for_conversion_and_update() -> Result<()>+ {+ let schema = Arc::new(Schema::new(vec![Field::new(+ "value",+ DataType::UInt32,+ false,+ )]));+ let aggregate_expr = Arc::new(+ AggregateExprBuilder::new(array_agg_udaf(), vec![col("value", &schema)?])+ .schema(Arc::clone(&schema))+ .distinct()+ .alias("distinct_values")+ .build()?,+ );+ let metric_resolutions = Arc::new(AtomicUsize::new(0));+ let metric_durations = Arc::new(AtomicUsize::new(0));+ let mut accumulator = create_group_accumulator(+ &aggregate_expr,+ Arc::new(CountingMetrics {+ resolutions: Arc::clone(&metric_resolutions),+ durations: Arc::clone(&metric_durations),+ }),+ )?;+ let values: ArrayRef = Arc::new(UInt32Array::from(vec![1, 2, 3]));++ accumulator.convert_to_state(&[Arc::clone(&values)], None)?;+ accumulator.update_batch(&[values], &[0, 1, 2], None, 3)?;++ // Three temporary conversion accumulators and three grouped accumulators+ // each receive the aggregate expression's metrics.+ assert_eq!(metric_resolutions.load(Ordering::Relaxed), 6);+ assert_eq!(metric_durations.load(Ordering::Relaxed), 2);+ Ok(())+ }++ #[test]+ fn legacy_grouped_distinct_merge_records_metric_once() -> Result<()> {+ let schema = Arc::new(Schema::new(vec![Field::new(+ "value",+ DataType::UInt32,+ false,+ )]));+ let aggregate_expr = Arc::new(+ AggregateExprBuilder::new(array_agg_udaf(), vec![col("value", &schema)?])+ .schema(Arc::clone(&schema))+ .distinct()+ .alias("distinct_values")+ .build()?,+ );+ let metric_resolutions = Arc::new(AtomicUsize::new(0));+ let metric_durations = Arc::new(AtomicUsize::new(0));+ let mut accumulator = create_group_accumulator(+ &aggregate_expr,+ Arc::new(CountingMetrics {+ resolutions: Arc::clone(&metric_resolutions),+ durations: Arc::clone(&metric_durations),+ }),+ )?;++ let mut state = ListBuilder::new(UInt32Builder::new());+ for value in [1, 2, 3] {+ state.append_value([Some(value)]);+ }+ accumulator.merge_batch(&[Arc::new(state.finish())], &[1, 2, 3], 4)?;++ // Four group accumulators each receive the aggregate expression's metrics.+ assert_eq!(metric_resolutions.load(Ordering::Relaxed), 4);+ assert_eq!(metric_durations.load(Ordering::Relaxed), 1);+ Ok(())+ }++ #[tokio::test]+ async fn grouped_hash_stream_reports_distinct_array_agg_submetric() -> Result<()> {+ let schema = Arc::new(Schema::new(vec![+ Field::new("group", DataType::Int32, false),+ Field::new("value", DataType::UInt32, false),+ ]));+ let batch = RecordBatch::try_new(+ Arc::clone(&schema),+ vec![+ Arc::new(Int32Array::from(vec![1, 1, 2, 2])),+ Arc::new(UInt32Array::from(vec![3, 3, 4, 4])),+ ],+ )?;+ let input = Arc::new(TestMemoryExec::try_new(+ &[vec![batch]],+ Arc::clone(&schema),+ None,+ )?);+ let group_by = PhysicalGroupBy::new_single(vec![(+ col("group", &schema)?,+ "group".to_string(),+ )]);+ let aggregate_expr = Arc::new(+ AggregateExprBuilder::new(array_agg_udaf(), vec![col("value", &schema)?])+ .schema(Arc::clone(&schema))+ .distinct()+ .alias("distinct_values")+ .build()?,+ );+ let output_schema = Arc::new(create_schema(+ &schema,+ &group_by,+ std::slice::from_ref(&aggregate_expr),+ AggregateMode::Single,+ )?);+ let aggregate_exec = AggregateExec::try_new(+ AggregateMode::Single,+ group_by,+ vec![aggregate_expr],+ vec![None],+ input,+ output_schema,+ )?;++ let mut stream = GroupedHashAggregateStream::new(+ &aggregate_exec,+ &Arc::new(TaskContext::default()),+ 0,+ )?;+ while let Some(batch) = stream.next().await {+ batch?;+ }++ let metrics = aggregate_exec.metrics().unwrap();+ let distinct_time = metrics+ .iter()+ .find(|metric| metric.value().name() == "agg_expr_0_internal_distinct_time")+ .expect("internal distinct time metric");+ assert!(distinct_time.value().as_usize() > 0);++ Ok(())+ }// Migrated to PartialHashAggregateStream coverage in hash_stream.rs;// kept here for the legacy GroupedHashAggregateStream implementation.diff --git a/datafusion/physical-plan/src/aggregates/mod.rs b/datafusion/physical-plan/src/aggregates/mod.rsindex f2afe6e754..ffa93a387d 100644--- a/datafusion/physical-plan/src/aggregates/mod.rs+++ b/datafusion/physical-plan/src/aggregates/mod.rs@@ -191,7 +191,7 @@ use datafusion_common::{assert_eq_or_internal_err, internal_err, not_impl_err,};use datafusion_execution::TaskContext;-use datafusion_expr::{Accumulator, Aggregate};+use datafusion_expr::{Accumulator, Aggregate, AggregateMetrics};use datafusion_physical_expr::aggregate::AggregateFunctionExpr;use datafusion_physical_expr::equivalence::ProjectionMapping;use datafusion_physical_expr::expressions::{Column, DynamicFilterPhysicalExpr, lit};@@ -3013,6 +3013,18 @@ pub fn create_accumulators(.collect()}+pub(crate) fn create_accumulators_with_metrics(+ aggr_expr: &[Arc<AggregateFunctionExpr>],+ aggregate_metrics: &[Arc<dyn AggregateMetrics>],+) -> Result<Vec<AccumulatorItem>> {+ debug_assert_eq!(aggr_expr.len(), aggregate_metrics.len());+ aggr_expr+ .iter()+ .zip(aggregate_metrics)+ .map(|(expr, metrics)| expr.create_accumulator_with_metrics(Arc::clone(metrics)))+ .collect()+}+/// returns a vector of ArrayRefs, where each entry corresponds to either the/// final value (mode = Final, FinalPartitioned and Single) or states (mode = Partial)pub fn finalize_aggregation(diff --git a/docs/source/user-guide/metrics.md b/docs/source/user-guide/metrics.mdindex 5bb4895a3d..111df66ccc 100644--- a/docs/source/user-guide/metrics.md+++ b/docs/source/user-guide/metrics.md@@ -154,6 +154,25 @@ when it is evaluated per aggregate. The legacy grouped hash path evaluatesfilters collectively, so its per-aggregate `arguments` timers cover argumentexpressions only; their sum need not equal `aggregate_arguments_time`.+Aggregate implementations can also expose optional internal submetrics. These+use the `agg_expr_{index}_internal_{subphase}_time` naming and `aggregate`+label. The `internal` segment keeps them separate from call-boundary timers;+`subphase` is a stable identifier owned and documented by the aggregate+implementation. They are registered lazily only when an aggregate requests+them, so aggregates without internal submetrics add no metrics. Registration+is per `(aggregate expression index, subphase, partition)`: replacement+accumulators in that partition share the same time, and normal metric display+combines that time across partitions. An aggregate may request its submetric+during accumulator construction, so it can appear even when its input is empty.+For example, `array_agg(DISTINCT ...)` records the time spent deduplicating+input values as `agg_expr_{index}_internal_distinct_time`. Grouped accumulation+records this once per input batch, rather than once per group, to avoid making+metric collection proportional to group cardinality. These submetrics complement+the `update`, `merge`, `state`, and `evaluate` timers rather than subdividing or+replacing them. An internal submetric may therefore overlap its enclosing phase+timer; it is a supplementary diagnostic and must not be added to phase timings+as a breakdown.+Except for the `Summary` metric `reduction_factor`, these operator-level andper-aggregate metrics are `Dev` metrics. They appear in `EXPLAIN ANALYZE` when`datafusion.explain.analyze_level` includes `Dev` (the default), but are omitted