diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs index c9f8dc45e36de..0efcb88182904 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs @@ -164,9 +164,7 @@ impl AggregateHashTable { let timer = self.group_by_metrics.aggregate_arguments_time.timer(); // The evaluated args for each accumulator - let accumulator_args = self - .state - .building() + let accumulator_args = state .accumulators .iter() .map(|acc| acc.evaluate_acc_args(batch)) @@ -531,23 +529,16 @@ impl HashAggregateAccumulator { /// Evaluate aggregate arguments and filter for one input batch. /// - /// For example, `AVG(x + 1) FILTER (WHERE x > 0)` evaluates both `x + 1` - /// and `x > 0`. + /// For example, `AVG(2 / x) FILTER (WHERE x > 0)` evaluates `x > 0` + /// first, then evaluates `2 / x` only for selected rows. + /// Filtered rows will be evaluated to `NULL`, and won't trigger errors + /// such as divide by zero. /// /// These arrays can be passed directly to [`GroupsAccumulator`] next. pub(super) fn evaluate_acc_args( &self, batch: &RecordBatch, ) -> Result { - let arguments = self - .arguments - .iter() - .map(|expr| { - expr.evaluate(batch) - .and_then(|value| value.into_array(batch.num_rows())) - }) - .collect::>()?; - let filter = self .filter .as_ref() @@ -557,6 +548,19 @@ impl HashAggregateAccumulator { .and_then(|value| value.into_array(batch.num_rows())) }) .transpose()?; + let selection = filter.as_ref().map(|filter| filter.as_boolean()); + let arguments = self + .arguments + .iter() + .map(|expr| { + selection + .map_or_else( + || expr.evaluate(batch), + |selection| expr.evaluate_selection(batch, selection), + ) + .and_then(|value| value.into_array(batch.num_rows())) + }) + .collect::>()?; Ok(EvaluatedAccumulatorArgs { arguments, filter }) } diff --git a/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs b/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs index a1efbb41a264c..01bcfa0e14374 100644 --- a/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs +++ b/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs @@ -52,6 +52,7 @@ use datafusion_physical_expr::aggregate::AggregateFunctionExpr; use datafusion_physical_expr::expressions::Column; use datafusion_physical_expr::{GroupsAccumulatorAdapter, PhysicalSortExpr}; use datafusion_physical_expr_common::sort_expr::LexOrdering; +use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays; use crate::sorts::IncrementalSortIterator; use datafusion_common::instant::Instant; @@ -844,6 +845,12 @@ impl GroupedHashAggregateStream { evaluate_group_by(&self.group_by, batch)? }; + let filter_values = if self.spill_state.is_stream_merging { + vec![None; self.accumulators.len()] + } else { + evaluate_optional(&self.filter_expressions, batch)? + }; + // Only create the timer if there are actual aggregate arguments to evaluate let timer = match ( self.spill_state.is_stream_merging, @@ -860,18 +867,10 @@ impl GroupedHashAggregateStream { let input_values = if self.spill_state.is_stream_merging { evaluate_many(&self.spill_state.merging_aggregate_arguments, batch)? } else { - evaluate_many(&self.aggregate_arguments, batch)? + self.evaluate_aggregate_arguments(batch, &filter_values)? }; drop(timer); - // Evaluate the filter expressions, if any, against the inputs - let filter_values = if self.spill_state.is_stream_merging { - let filter_expressions = vec![None; self.accumulators.len()]; - evaluate_optional(&filter_expressions, batch)? - } else { - evaluate_optional(&self.filter_expressions, batch)? - }; - for group_values in &group_by_values { let groups_start_time = Instant::now(); @@ -1366,11 +1365,35 @@ impl GroupedHashAggregateStream { .is_some_and(|probe| probe.should_skip()) } + fn evaluate_aggregate_arguments( + &self, + batch: &RecordBatch, + filters: &[Option], + ) -> Result>> { + self.aggregate_arguments + .iter() + .zip(filters) + .map(|(arguments, filter)| { + let Some(filter) = filter else { + return evaluate_expressions_to_arrays(arguments, batch); + }; + let selection = filter.as_boolean(); + arguments + .iter() + .map(|expr| { + expr.evaluate_selection(batch, selection)? + .into_array(batch.num_rows()) + }) + .collect() + }) + .collect() + } + /// Transforms input batch to intermediate aggregate state, without grouping it fn transform_to_states(&self, batch: &RecordBatch) -> Result { let mut group_values = evaluate_group_by(&self.group_by, batch)?; - let input_values = evaluate_many(&self.aggregate_arguments, batch)?; let filter_values = evaluate_optional(&self.filter_expressions, batch)?; + let input_values = self.evaluate_aggregate_arguments(batch, &filter_values)?; assert_eq_or_internal_err!( group_values.len(), diff --git a/datafusion/sqllogictest/test_files/aggregate_filter_selection.slt b/datafusion/sqllogictest/test_files/aggregate_filter_selection.slt new file mode 100644 index 0000000000000..ca583785843c2 --- /dev/null +++ b/datafusion/sqllogictest/test_files/aggregate_filter_selection.slt @@ -0,0 +1,100 @@ +# 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. + +# Aggregate FILTER must select rows before evaluating fallible arguments. + +statement ok +CREATE TABLE aggregate_filter_selection (g INT, v BIGINT); + +statement ok +INSERT INTO aggregate_filter_selection VALUES + (1, 0), + (2, 2), + (3, 0), + (4, 5); + +statement ok +SET datafusion.execution.skip_partial_aggregation_probe_rows_threshold = 100000; + +statement ok +SET datafusion.execution.enable_migration_aggregate = true; + +query II +SELECT g, SUM(10 / v) FILTER (WHERE v <> 0) +FROM aggregate_filter_selection +GROUP BY g +ORDER BY g; +---- +1 NULL +2 5 +3 NULL +4 2 + +statement ok +SET datafusion.execution.target_partitions = 2; + +statement ok +SET datafusion.execution.batch_size = 1; + +statement ok +SET datafusion.execution.skip_partial_aggregation_probe_rows_threshold = 0; + +statement ok +SET datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.0; + +statement ok +CREATE TABLE aggregate_filter_selection_skip (g INT, v BIGINT); + +statement ok +INSERT INTO aggregate_filter_selection_skip VALUES + (1, 2), + (3, 5), + (2, 0); + +statement ok +SET datafusion.execution.enable_migration_aggregate = true; + +query II +SELECT g, SUM(10 / v) FILTER (WHERE v <> 0) +FROM aggregate_filter_selection_skip +GROUP BY g +ORDER BY g; +---- +1 5 +2 NULL +3 2 + +statement ok +RESET datafusion.execution.enable_migration_aggregate; + +statement ok +RESET datafusion.execution.skip_partial_aggregation_probe_ratio_threshold; + +statement ok +RESET datafusion.execution.skip_partial_aggregation_probe_rows_threshold; + +statement ok +RESET datafusion.execution.batch_size; + +statement ok +SET datafusion.execution.target_partitions = 4; + +statement ok +DROP TABLE aggregate_filter_selection_skip; + +statement ok +DROP TABLE aggregate_filter_selection;