diff --git a/datafusion/core/tests/sql/aggregates/basic.rs b/datafusion/core/tests/sql/aggregates/basic.rs index 1a0a9e3420946..3fdf9a1c4b235 100644 --- a/datafusion/core/tests/sql/aggregates/basic.rs +++ b/datafusion/core/tests/sql/aggregates/basic.rs @@ -8,6 +8,162 @@ use datafusion_catalog::MemTable; use datafusion_common::ScalarValue; use insta::assert_snapshot; +#[tokio::test] +async fn aggregate_scalar_filter() -> Result<()> { + use arrow::array::BooleanArray; + use datafusion::logical_expr::{ColumnarValue, Volatility, create_udf}; + use datafusion_common::assert_batches_eq; + use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; + use datafusion_physical_plan::collect; + + let schema = Arc::new(Schema::new(vec![ + Field::new("key", DataType::Int32, false), + Field::new("value", DataType::Int32, true), + Field::new("keep", DataType::Boolean, true), + ])); + let mut offset = 0; + let batches = [ + (Some(true), 3), + (Some(false), 2), + (None, 1), + (Some(true), 4), + ] + .into_iter() + .map(|(keep, len)| { + let keys = Int32Array::from_iter_values(offset..offset + len); + offset += len; + RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(keys), + Arc::new(Int32Array::from_iter((0..len).map(|row| { + if keep == Some(true) { + (row != 0).then_some(2) + } else { + Some(0) + } + }))), + Arc::new(BooleanArray::from(vec![keep; len as usize])), + ], + ) + }) + .collect::, _>>()?; + + for partitions in [1, 2] { + for skip in [false, true] { + let config = SessionConfig::new() + .with_target_partitions(partitions) + .with_coalesce_batches(false) + .set_usize( + "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", + if skip { 0 } else { usize::MAX }, + ) + .set( + "datafusion.execution.skip_partial_aggregation_probe_ratio_threshold", + &ScalarValue::Float64(Some(if skip { 0.0 } else { 1.0 })), + ); + let ctx = SessionContext::new_with_config(config); + // A runtime scalar can change between batches. Volatility prevents + // the optimizer from folding away the FILTER before execution. + ctx.register_udf(create_udf( + "batch_filter", + vec![DataType::Boolean], + DataType::Boolean, + Volatility::Volatile, + Arc::new(|args| match &args[0] { + ColumnarValue::Array(array) => Ok(ColumnarValue::Scalar( + ScalarValue::try_from_array(array, 0)?, + )), + scalar => Ok(scalar.clone()), + }), + )); + ctx.register_table( + "scalar_filters", + Arc::new(MemTable::try_new( + Arc::clone(&schema), + vec![batches.clone(), batches.clone()], + )?), + )?; + for grouped in [false, true] { + let aggs = "count(*) FILTER (WHERE batch_filter(keep)) AS c, + sum(10 / value) FILTER (WHERE batch_filter(keep)) AS s, + sum(7) FILTER (WHERE batch_filter(keep)) AS l, + count(value) FILTER (WHERE batch_filter(keep)) AS v"; + let sql = if grouped { + format!( + "SELECT count(*) AS g, sum(c) AS c, sum(s) AS s, sum(l) AS l, sum(v) AS v + FROM (SELECT {aggs} FROM scalar_filters GROUP BY key)" + ) + } else { + format!("SELECT count(DISTINCT key) AS g, {aggs} FROM scalar_filters") + }; + let plan = ctx.sql(&sql).await?.create_physical_plan().await?; + let output = collect(Arc::clone(&plan), ctx.task_ctx()).await?; + assert_batches_eq!( + [ + "+----+----+----+----+----+", + "| g | c | s | l | v |", + "+----+----+----+----+----+", + "| 10 | 14 | 50 | 98 | 10 |", + "+----+----+----+----+----+" + ], + &output + ); + if grouped && partitions == 2 && skip { + let mut skipped_rows = 0; + plan.apply(|node| { + skipped_rows += node + .metrics() + .and_then(|m| m.sum_by_name("skipped_aggregation_rows")) + .map_or(0, |m| m.as_usize()); + Ok(TreeNodeRecursion::Continue) + })?; + assert!(skipped_rows > 0); + } + } + // `array_agg` keeps null arguments, so a group whose rows are all + // rejected is NULL only if the rejected rows are filtered out, also + // during skip-partial conversion. + let result = ctx + .sql( + "SELECT count(*) AS g, count(a) AS a FROM ( + SELECT array_agg(value) FILTER (WHERE batch_filter(keep)) AS a + FROM scalar_filters GROUP BY key)", + ) + .await? + .collect() + .await?; + assert_batches_eq!( + [ + "+----+---+", + "| g | a |", + "+----+---+", + "| 10 | 7 |", + "+----+---+" + ], + &result + ); + for predicate in ["false", "CAST(NULL AS BOOLEAN)"] { + let result = ctx.sql(&format!("SELECT + count(*) FILTER (WHERE batch_filter({predicate})) AS c, + sum(10 / (value - value)) FILTER (WHERE batch_filter({predicate})) AS s + FROM scalar_filters")).await?.collect().await?; + assert_batches_eq!( + [ + "+---+---+", + "| c | s |", + "+---+---+", + "| 0 | |", + "+---+---+" + ], + &result + ); + } + } + } + Ok(()) +} + #[tokio::test] async fn csv_query_array_agg_distinct() -> Result<()> { let ctx = SessionContext::new(); diff --git a/datafusion/physical-plan/src/aggregates/aggregate_argument.rs b/datafusion/physical-plan/src/aggregates/aggregate_argument.rs index 1b462ee071929..bad321a8c4c60 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_argument.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_argument.rs @@ -4,6 +4,7 @@ //! Evaluation of aggregate function arguments against input batches. +use std::borrow::Cow; use std::sync::Arc; use crate::PhysicalExpr; @@ -13,6 +14,7 @@ use arrow::datatypes::{DataType, Field, Fields, Schema, SchemaRef}; use arrow::record_batch::{RecordBatch, RecordBatchOptions}; use datafusion_common::cast::as_boolean_array; use datafusion_common::{Result, ScalarValue, internal_err}; +use datafusion_expr::ColumnarValue; use datafusion_physical_expr::expressions::Literal; use datafusion_physical_expr::utils::collect_columns; use datafusion_physical_expr_common::utils::scatter; @@ -151,6 +153,20 @@ pub(in crate::aggregates) struct AggregateFilter { selected_schema: Option<(SchemaRef, SchemaRef)>, } +/// The rows of a batch that an [`AggregateFilter`] selects. +/// +/// A filter often selects every row of a batch or none of them, for example +/// when its predicate is a literal or returns a scalar. Then neither a +/// [`BooleanArray`] nor a copy of the selected rows is needed. +pub(in crate::aggregates) enum AggregateSelection { + /// Every row is selected. + All, + /// No row is selected. + Empty, + /// The rows where the array is true: at least one row, but not all. + Rows(BooleanArray), +} + impl AggregateFilter { pub(in crate::aggregates) fn new( predicate: Arc, @@ -174,16 +190,53 @@ impl AggregateFilter { &self.predicate } - /// Evaluates the filter predicate for every row of `batch`. + /// Evaluates the filter predicate for `batch` and returns the rows it + /// selects. A null rejects its row, like `false`. + /// + /// The predicate is evaluated for every batch, even if it returns a + /// scalar: a runtime scalar, such as the result of a UDF, can change + /// between batches. pub(in crate::aggregates) fn evaluate( &self, batch: &RecordBatch, - ) -> Result { - let selection = self - .predicate - .evaluate(batch)? - .into_array(batch.num_rows())?; - Ok(as_boolean_array(&selection)?.clone()) + ) -> Result { + let selection = match self.predicate.evaluate(batch)? { + ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))) => { + return Ok(AggregateSelection::All); + } + ColumnarValue::Scalar(ScalarValue::Boolean(_)) => { + return Ok(AggregateSelection::Empty); + } + value => value.into_array(batch.num_rows())?, + }; + let selection = as_boolean_array(&selection)?; + // Nulls are counted neither by `has_true` nor by `has_false`. + Ok(if !selection.has_true() { + AggregateSelection::Empty + } else if selection.null_count() == 0 && !selection.has_false() { + AggregateSelection::All + } else { + AggregateSelection::Rows(selection.clone()) + }) + } + + /// Returns the rows of `batch` that `selection` selects, for evaluating + /// the arguments of the aggregate, or `None` if no row is selected. + /// + /// If every row is selected, `batch` itself is returned. Otherwise the + /// rows are copied by [`Self::select`]. + pub(in crate::aggregates) fn selected_batch<'a>( + &mut self, + batch: &'a RecordBatch, + selection: &AggregateSelection, + ) -> Result>> { + Ok(match selection { + AggregateSelection::All => Some(Cow::Borrowed(batch)), + AggregateSelection::Empty => None, + AggregateSelection::Rows(selection) => { + Some(Cow::Owned(self.select(batch, selection)?)) + } + }) } /// Returns the rows of `batch` where `selection` is true, for evaluating @@ -376,6 +429,72 @@ mod tests { Ok(()) } + #[test] + fn filter_selection_is_normalized() -> Result<()> { + let schema = + Arc::new(Schema::new(vec![Field::new("p", DataType::Boolean, true)])); + let batch = |values: Vec>| { + RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(BooleanArray::from(values))], + ) + }; + let argument = AggregateArgument::try_new(col("p", &schema)?, &schema)?; + let filter = + |predicate| AggregateFilter::new(predicate, std::slice::from_ref(&argument)); + let kind = |selection: &AggregateSelection| match selection { + AggregateSelection::All => "all", + AggregateSelection::Empty => "empty", + AggregateSelection::Rows(_) => "rows", + }; + + let null = lit(ScalarValue::Boolean(None)); + let column = col("p", &schema)?; + let cases = [ + // A scalar selects or rejects every row; a null rejects. + (lit(true), vec![Some(false), None], "all"), + (lit(false), vec![Some(true)], "empty"), + (null, vec![Some(true)], "empty"), + // So does an array that is all true, or has no true value. + (Arc::clone(&column), vec![Some(true), Some(true)], "all"), + (Arc::clone(&column), vec![Some(false), None], "empty"), + (Arc::clone(&column), vec![], "empty"), + // A null rejects its row. + (Arc::clone(&column), vec![Some(true), None], "rows"), + (Arc::clone(&column), vec![Some(false), Some(true)], "rows"), + ]; + for (predicate, values, expected) in cases { + let selection = filter(predicate).evaluate(&batch(values.clone())?)?; + assert_eq!(kind(&selection), expected, "{values:?}"); + } + + let batch = batch(vec![Some(true), None, Some(false)])?; + let mut filter = filter(column); + let selection = filter.evaluate(&batch)?; + let AggregateSelection::Rows(rows) = &selection else { + panic!("expected rows"); + }; + assert_eq!( + rows, + &BooleanArray::from(vec![Some(true), None, Some(false)]) + ); + let Some(Cow::Owned(selected)) = filter.selected_batch(&batch, &selection)? + else { + panic!("expected a copy of the selected rows"); + }; + assert_eq!(selected.num_rows(), 1); + assert!(matches!( + filter.selected_batch(&batch, &AggregateSelection::All)?, + Some(Cow::Borrowed(all)) if std::ptr::eq(all, &raw const batch) + )); + assert!( + filter + .selected_batch(&batch, &AggregateSelection::Empty)? + .is_none() + ); + Ok(()) + } + #[test] fn filter_selects_only_argument_columns() -> Result<()> { let schema = Arc::new(Schema::new(vec![ 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 fa7a134733194..9b9fd726618fe 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs @@ -8,6 +8,7 @@ use std::marker::PhantomData; use std::sync::Arc; use arrow::array::{Array, ArrayRef, AsArray, BooleanArray, new_null_array}; +use arrow::buffer::BooleanBuffer; use arrow::compute::prep_null_mask_filter; use arrow::datatypes::SchemaRef; use arrow::downcast_dictionary_array; @@ -21,7 +22,9 @@ use datafusion_physical_expr::aggregate::AggregateFunctionExpr; use log::debug; use crate::PhysicalExpr; -use crate::aggregates::aggregate_argument::{AggregateArgument, AggregateFilter}; +use crate::aggregates::aggregate_argument::{ + AggregateArgument, AggregateFilter, AggregateSelection, +}; use crate::aggregates::group_values::{ AccumulatorPhase, AggregateAccumulatorMetrics, AggregateArgumentMetrics, GroupByMetrics, GroupValues, new_group_values, @@ -486,7 +489,7 @@ impl AggregateHashTable { .iter() .map(|acc| CompactedAccumulatorArgs { arguments: acc.null_arguments(0), - selection: None, + selection: AggregateSelection::All, }) .collect::>(); group_by_metrics.time_aggregation(|| { @@ -538,7 +541,7 @@ pub(super) type AggregateAccumulator = HashAggregateAccumulator; /// /// Arguments: /// * accumulator to update. -/// * accumulator's compacted arguments and optional row-aligned selection. +/// * accumulator's compacted arguments and optional selection. /// * one group index per input row, mapping each row to its interned group. /// * total number of groups currently interned in that buffer, including newly /// interned groups. @@ -563,15 +566,17 @@ pub(super) struct CompactedAccumulatorArgs { /// Argument arrays containing only selected rows. Some aggregate functions take /// multiple arguments. pub(super) arguments: Vec, - /// Original row-aligned selection used only to compact the matching group IDs. - pub(super) selection: Option, + /// Selected rows, used only to compact the matching group IDs. Without a + /// filter, every row is selected. + pub(super) selection: AggregateSelection, } /// Evaluated aggregate arguments that preserve one output row per input row. pub(super) struct RowAlignedAccumulatorArgs { /// Row-aligned argument arrays. Rejected rows are represented as nulls. pub(super) arguments: Vec, - /// Original row-aligned filter passed through to state conversion. + /// Row-aligned filter passed through to state conversion, `None` if every + /// row is selected. pub(super) filter: Option, } @@ -785,17 +790,11 @@ impl HashAggregateAccumulator { batch: &RecordBatch, ) -> Result { let (selection, argument_batch) = match &mut self.filter { - None => (None, Some(Cow::Borrowed(batch))), + None => (AggregateSelection::All, Some(Cow::Borrowed(batch))), Some(filter) => { let selection = filter.evaluate(batch)?; - let argument_batch = match selection.true_count() { - 0 => None, - selected_rows if selected_rows == batch.num_rows() => { - Some(Cow::Borrowed(batch)) - } - _ => Some(Cow::Owned(filter.select(batch, &selection)?)), - }; - (Some(selection), argument_batch) + let argument_batch = filter.selected_batch(batch, &selection)?; + (selection, argument_batch) } }; let arguments = self @@ -826,36 +825,38 @@ impl HashAggregateAccumulator { batch: &RecordBatch, ) -> Result { let Some(filter) = &mut self.filter else { - let arguments = self - .arguments - .iter_mut() - .map(|argument| argument.evaluate(batch)) - .collect::>()?; return Ok(RowAlignedAccumulatorArgs { - arguments, + arguments: self.evaluate_arguments(batch)?, filter: None, }); }; - - let selection = filter.evaluate(batch)?; - if !selection.has_true() { - // No argument will be evaluated, so avoid constructing an empty - // selected batch (or slicing every unused input column). - return Ok(RowAlignedAccumulatorArgs { - arguments: self.null_arguments(batch.num_rows()), - filter: Some(selection), - }); - } - let selected = filter.select(batch, &selection)?; - let arguments = self - .arguments - .iter_mut() - .map(|argument| argument.evaluate_selection(batch, &selection, &selected)) - .collect::>()?; + let (arguments, selection) = match filter.evaluate(batch)? { + AggregateSelection::All => (self.evaluate_arguments(batch)?, None), + AggregateSelection::Empty => { + // No argument is evaluated, but state conversion still needs + // the filter to reject every row: aggregates such as + // `array_agg` keep null arguments. + let num_rows = batch.num_rows(); + let rejected = + BooleanArray::new(BooleanBuffer::new_unset(num_rows), None); + (self.null_arguments(num_rows), Some(rejected)) + } + AggregateSelection::Rows(selection) => { + let selected = filter.select(batch, &selection)?; + let arguments = self + .arguments + .iter_mut() + .map(|argument| { + argument.evaluate_selection(batch, &selection, &selected) + }) + .collect::>()?; + (arguments, Some(selection)) + } + }; Ok(RowAlignedAccumulatorArgs { arguments, - filter: Some(selection), + filter: selection, }) } @@ -874,11 +875,15 @@ impl HashAggregateAccumulator { group_indices: &[usize], total_num_groups: usize, ) -> Result<()> { - let filtered_group_indices = values - .selection - .as_ref() - .and_then(|selection| compact_group_indices(group_indices, selection)); - let group_indices = filtered_group_indices.as_deref().unwrap_or(group_indices); + let compacted; + let group_indices = match &values.selection { + AggregateSelection::All => group_indices, + AggregateSelection::Empty => &[], + AggregateSelection::Rows(selection) => { + compacted = compact_group_indices(group_indices, selection); + compacted.as_deref().unwrap_or(group_indices) + } + }; self.accumulator.update_batch( &values.arguments, group_indices, @@ -893,7 +898,7 @@ impl HashAggregateAccumulator { group_indices: &[usize], total_num_groups: usize, ) -> Result<()> { - debug_assert!(values.selection.is_none()); + debug_assert!(matches!(values.selection, AggregateSelection::All)); self.accumulator .merge_batch(&values.arguments, group_indices, total_num_groups) } @@ -928,6 +933,14 @@ impl HashAggregateAccumulator { .convert_to_state(&values.arguments, values.filter.as_ref()) } + /// Evaluates every argument for every row of `batch`. + fn evaluate_arguments(&mut self, batch: &RecordBatch) -> Result> { + self.arguments + .iter_mut() + .map(|argument| argument.evaluate(batch)) + .collect() + } + pub(super) fn null_arguments(&self, num_rows: usize) -> Vec { self.arguments .iter() diff --git a/datafusion/physical-plan/src/aggregates/aggregate_stream.rs b/datafusion/physical-plan/src/aggregates/aggregate_stream.rs index 9c29f39427805..4ee0468cbea8e 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_stream.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_stream.rs @@ -508,13 +508,16 @@ fn aggregate_batch( let batch = match filter { Some(filter) => { let selection = filter.evaluate(batch)?; - Cow::Owned(filter.select(batch, &selection)?) + filter.selected_batch(batch, &selection)? } - None => Cow::Borrowed(batch), + None => Some(Cow::Borrowed(batch)), }; arguments .iter_mut() - .map(|argument| argument.evaluate(batch.as_ref())) + .map(|argument| match &batch { + Some(batch) => argument.evaluate(batch.as_ref()), + None => Ok(argument.null_array(0)), + }) .collect::>>() })?; diff --git a/datafusion/sqllogictest/test_files/aggregate_filter_selection.slt b/datafusion/sqllogictest/test_files/aggregate_filter_selection.slt index 61cfe2b015c20..0140866c1a21e 100644 --- a/datafusion/sqllogictest/test_files/aggregate_filter_selection.slt +++ b/datafusion/sqllogictest/test_files/aggregate_filter_selection.slt @@ -186,3 +186,95 @@ DROP TABLE aggregate_filter_selection_skip; statement ok DROP TABLE aggregate_filter_selection; + +# Literal and constant-folded predicates, and prepared statement parameters, +# are evaluated as scalars that select or reject every row of a batch. Rejected +# rows must not evaluate arguments, and aggregates that keep NULL inputs, such +# as array_agg, must not see them. +query IIIII? +SELECT + count(*) FILTER (WHERE true), + sum(value) FILTER (WHERE true), + count(*) FILTER (WHERE 1 = 2), + sum(10 / (value - value)) FILTER (WHERE false), + count(value) FILTER (WHERE NULL), + array_agg(value) FILTER (WHERE CAST(NULL AS BOOLEAN)) +FROM range(16); +---- +16 120 0 NULL 0 NULL + +statement ok +PREPARE aggregate_filter_scalar(BOOLEAN) AS +SELECT count(*) FILTER (WHERE $1), sum(10 / (value - value)) FILTER (WHERE NOT $1) +FROM range(16); + +query II +EXECUTE aggregate_filter_scalar(true); +---- +16 NULL + +statement ok +DEALLOCATE aggregate_filter_scalar; + +statement ok +SET datafusion.execution.batch_size = 2; + +statement ok +SET datafusion.execution.target_partitions = 2; + +# Groups without selected rows must remain. +query IIIIII? +SELECT + value % 4 AS k, + count(*) FILTER (WHERE true), + sum(value) FILTER (WHERE true), + count(*) FILTER (WHERE 1 = 2), + sum(10 / (value - value)) FILTER (WHERE false), + count(value) FILTER (WHERE NULL), + array_agg(value) FILTER (WHERE CAST(NULL AS BOOLEAN)) +FROM range(16) +GROUP BY k +ORDER BY k; +---- +0 4 24 0 NULL 0 NULL +1 4 28 0 NULL 0 NULL +2 4 32 0 NULL 0 NULL +3 4 36 0 NULL 0 NULL + +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; + +# The same query with skip-partial conversion: every partition reads several +# batches, and all but the first are converted directly to partial states. +query IIIIII? +SELECT + value % 4 AS k, + count(*) FILTER (WHERE true), + sum(value) FILTER (WHERE true), + count(*) FILTER (WHERE 1 = 2), + sum(10 / (value - value)) FILTER (WHERE false), + count(value) FILTER (WHERE NULL), + array_agg(value) FILTER (WHERE CAST(NULL AS BOOLEAN)) +FROM range(16) +GROUP BY k +ORDER BY k; +---- +0 4 24 0 NULL 0 NULL +1 4 28 0 NULL 0 NULL +2 4 32 0 NULL 0 NULL +3 4 36 0 NULL 0 NULL + +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;