From b8ad0f64b45a075b6b6f886a3ae5560606cfb22c Mon Sep 17 00:00:00 2001 From: "xudong.w" Date: Wed, 11 Nov 2026 11:56:48 +0800 Subject: [PATCH 1/4] perf: specialize scalar aggregate FILTER evaluation --- datafusion/core/tests/sql/aggregates/basic.rs | 134 ++++++++++++++++++ .../physical-plan/benches/aggregate_filter.rs | 98 ++++++++++++- .../src/aggregates/aggregate_argument.rs | 25 +++- .../aggregates/aggregate_hash_table/common.rs | 84 +++++++---- .../src/aggregates/aggregate_stream.rs | 22 ++- 5 files changed, 324 insertions(+), 39 deletions(-) diff --git a/datafusion/core/tests/sql/aggregates/basic.rs b/datafusion/core/tests/sql/aggregates/basic.rs index 1a0a9e3420946..d18675ba0c1ab 100644 --- a/datafusion/core/tests/sql/aggregates/basic.rs +++ b/datafusion/core/tests/sql/aggregates/basic.rs @@ -8,6 +8,140 @@ 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); + } + } + 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/benches/aggregate_filter.rs b/datafusion/physical-plan/benches/aggregate_filter.rs index f0665cab6f21e..f967a8a23efc7 100644 --- a/datafusion/physical-plan/benches/aggregate_filter.rs +++ b/datafusion/physical-plan/benches/aggregate_filter.rs @@ -15,13 +15,15 @@ use arrow::array::{BooleanArray, Float64Array, UInt32Array}; use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; use arrow::record_batch::RecordBatch; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; +use datafusion_common::ScalarValue; use datafusion_execution::TaskContext; -use datafusion_expr::{AggregateUDF, Operator}; +use datafusion_execution::config::SessionConfig; +use datafusion_expr::{AggregateUDF, ColumnarValue, Operator, Volatility, create_udf}; use datafusion_functions_aggregate::count::count_udaf; use datafusion_functions_aggregate::sum::sum_udaf; -use datafusion_physical_expr::PhysicalExpr; use datafusion_physical_expr::aggregate::{AggregateExprBuilder, AggregateFunctionExpr}; use datafusion_physical_expr::expressions::{BinaryExpr, col, lit}; +use datafusion_physical_expr::{PhysicalExpr, ScalarFunctionExpr}; use datafusion_physical_plan::aggregates::{ AggregateExec, AggregateMode, PhysicalGroupBy, }; @@ -260,8 +262,100 @@ fn benchmark_case( } } +fn benchmark_scalar_filters(c: &mut Criterion, runtime: &Runtime) { + let schema = schema(); + let batch_filter = Arc::new(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()), + }), + )); + let varying: Arc = Arc::new( + ScalarFunctionExpr::try_new( + batch_filter, + vec![col("include_a", &schema).unwrap()], + &schema, + Arc::default(), + ) + .unwrap(), + ); + let filters = [ + ("true", Some(lit(true))), + ("false", Some(lit(false))), + ("null", Some(lit(ScalarValue::Boolean(None)))), + ("varying", Some(varying)), + ("array_50_percent", Some(col("include_a", &schema).unwrap())), + ("unfiltered", None), + ]; + let config = SessionConfig::new() + .set_usize( + "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", + 0, + ) + .set( + "datafusion.execution.skip_partial_aggregation_probe_ratio_threshold", + &ScalarValue::Float64(Some(0.0)), + ); + let task_ctx = Arc::new(TaskContext::default().with_session_config(config)); + for (name, mode, grouped) in [ + ("ungrouped", AggregateMode::Single, false), + ("grouped", AggregateMode::Single, true), + ("skip_partial", AggregateMode::Partial, true), + ] { + let batches = make_batches( + Some(50), + if mode == AggregateMode::Partial { + NUM_ROWS + } else { + 16 + }, + ); + let input: Arc = + TestMemoryExec::try_new_exec(&[batches], Arc::clone(&schema), None).unwrap(); + let mut group = c.benchmark_group(format!("scalar_aggregate_filter/{name}")); + for (filter_name, filter) in &filters { + let group_by = if grouped { + PhysicalGroupBy::new_single(vec![( + col("group_key", &schema).unwrap(), + "group_key".to_string(), + )]) + } else { + PhysicalGroupBy::default() + }; + let plan: Arc = Arc::new( + AggregateExec::try_new( + mode, + group_by, + vec![aggregate_expr(&schema, 0, ArgumentKind::Column)], + vec![filter.clone()], + Arc::clone(&input), + Arc::clone(&schema), + ) + .unwrap(), + ); + group.bench_function(*filter_name, |b| { + b.iter(|| { + black_box( + runtime + .block_on(collect(Arc::clone(&plan), Arc::clone(&task_ctx))) + .unwrap(), + ); + }); + }); + } + group.finish(); + } +} + fn aggregate_filter_benchmark(c: &mut Criterion) { let runtime = Runtime::new().unwrap(); + benchmark_scalar_filters(c, &runtime); benchmark_case( c, diff --git a/datafusion/physical-plan/src/aggregates/aggregate_argument.rs b/datafusion/physical-plan/src/aggregates/aggregate_argument.rs index 1b462ee071929..2f061fb72fe29 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_argument.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_argument.rs @@ -13,6 +13,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 +152,12 @@ pub(in crate::aggregates) struct AggregateFilter { selected_schema: Option<(SchemaRef, SchemaRef)>, } +/// An aggregate filter result, retaining predicates that select or reject a whole batch. +pub(in crate::aggregates) enum AggregateFilterValue { + Scalar(bool), + Array(BooleanArray), +} + impl AggregateFilter { pub(in crate::aggregates) fn new( predicate: Arc, @@ -178,12 +185,18 @@ impl AggregateFilter { 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 { + match self.predicate.evaluate(batch)? { + ColumnarValue::Scalar(ScalarValue::Boolean(value)) => { + Ok(AggregateFilterValue::Scalar(value.unwrap_or(false))) + } + value => { + let selection = value.into_array(batch.num_rows())?; + Ok(AggregateFilterValue::Array( + as_boolean_array(&selection)?.clone(), + )) + } + } } /// Returns the rows of `batch` where `selection` is true, for evaluating 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..c610815e70d7d 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, AggregateFilterValue, +}; use crate::aggregates::group_values::{ AccumulatorPhase, AggregateAccumulatorMetrics, AggregateArgumentMetrics, GroupByMetrics, GroupValues, new_group_values, @@ -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,8 +566,8 @@ 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, + /// Selection used only to compact the matching group IDs. + pub(super) selection: Option, } /// Evaluated aggregate arguments that preserve one output row per input row. @@ -788,12 +791,20 @@ impl HashAggregateAccumulator { None => (None, 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() => { + let argument_batch = match &selection { + AggregateFilterValue::Scalar(true) if batch.num_rows() > 0 => { Some(Cow::Borrowed(batch)) } - _ => Some(Cow::Owned(filter.select(batch, &selection)?)), + AggregateFilterValue::Scalar(_) => None, + AggregateFilterValue::Array(selection) => { + 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) } @@ -825,19 +836,37 @@ impl HashAggregateAccumulator { &mut self, 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, - filter: None, - }); + let selection = self + .filter + .as_ref() + .map(|filter| filter.evaluate(batch)) + .transpose()?; + let selection = match selection { + None | Some(AggregateFilterValue::Scalar(true)) => { + let arguments = self + .arguments + .iter_mut() + .map(|argument| argument.evaluate(batch)) + .collect::>()?; + return Ok(RowAlignedAccumulatorArgs { + arguments, + filter: None, + }); + } + Some(AggregateFilterValue::Scalar(false)) => { + // State conversion must retain rejected rows, and its interface + // requires an array filter even for a scalar predicate. + return Ok(RowAlignedAccumulatorArgs { + arguments: self.null_arguments(batch.num_rows()), + filter: Some(BooleanArray::new( + BooleanBuffer::new_unset(batch.num_rows()), + None, + )), + }); + } + Some(AggregateFilterValue::Array(selection)) => selection, }; - 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). @@ -846,7 +875,7 @@ impl HashAggregateAccumulator { filter: Some(selection), }); } - let selected = filter.select(batch, &selection)?; + let selected = self.filter.as_mut().unwrap().select(batch, &selection)?; let arguments = self .arguments .iter_mut() @@ -874,10 +903,17 @@ 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 filtered_group_indices = + values + .selection + .as_ref() + .and_then(|selection| match selection { + AggregateFilterValue::Scalar(true) => None, + AggregateFilterValue::Scalar(false) => Some(vec![]), + AggregateFilterValue::Array(selection) => { + compact_group_indices(group_indices, selection) + } + }); let group_indices = filtered_group_indices.as_deref().unwrap_or(group_indices); self.accumulator.update_batch( &values.arguments, diff --git a/datafusion/physical-plan/src/aggregates/aggregate_stream.rs b/datafusion/physical-plan/src/aggregates/aggregate_stream.rs index 9c29f39427805..c84b7ae664a66 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_stream.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_stream.rs @@ -4,7 +4,9 @@ //! Aggregate without grouping columns -use crate::aggregates::aggregate_argument::{AggregateArgument, AggregateFilter}; +use crate::aggregates::aggregate_argument::{ + AggregateArgument, AggregateFilter, AggregateFilterValue, +}; use crate::aggregates::group_values::{ AccumulatorPhase, AggregateAccumulatorMetrics, AggregateArgumentMetrics, aggregate_sub_metrics, @@ -506,15 +508,21 @@ fn aggregate_batch( // 1.2 and 1.3 let values = aggregate_argument_metrics.time(index, || { let batch = match filter { - Some(filter) => { - let selection = filter.evaluate(batch)?; - Cow::Owned(filter.select(batch, &selection)?) - } - None => Cow::Borrowed(batch), + Some(filter) => match filter.evaluate(batch)? { + AggregateFilterValue::Scalar(true) => Some(Cow::Borrowed(batch)), + AggregateFilterValue::Scalar(false) => None, + AggregateFilterValue::Array(selection) => { + Some(Cow::Owned(filter.select(batch, &selection)?)) + } + }, + 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::>>() })?; From 8cd7f91ecc7cf837d64c34ba3ad3975719e2f03c Mon Sep 17 00:00:00 2001 From: "xudong.w" Date: Thu, 12 Nov 2026 09:24:51 +0800 Subject: [PATCH 2/4] docs: move scalar aggregate filter benchmark into README --- datafusion/physical-plan/benches/README.md | 180 ++++++++++++++++++ .../physical-plan/benches/aggregate_filter.rs | 98 +--------- 2 files changed, 182 insertions(+), 96 deletions(-) create mode 100644 datafusion/physical-plan/benches/README.md diff --git a/datafusion/physical-plan/benches/README.md b/datafusion/physical-plan/benches/README.md new file mode 100644 index 0000000000000..0511ca46469c9 --- /dev/null +++ b/datafusion/physical-plan/benches/README.md @@ -0,0 +1,180 @@ + + +# Physical plan benchmarks + +## Reproducing the scalar aggregate FILTER measurements + +The following optional benchmark exercises scalar `true`, `false`, `NULL`, and +batch-varying predicates in ungrouped, grouped, and skip-partial aggregation. +A shuffled 50%-selective array predicate and an unfiltered aggregate serve as +controls. It uses the existing in-memory `AggregateExec` benchmark helpers to +exclude SQL planning and file I/O. + +To run it locally, paste the function below into +[`aggregate_filter.rs`](aggregate_filter.rs), immediately before +`aggregate_filter_benchmark`. In `aggregate_filter_benchmark`, add this call +immediately after `let runtime = Runtime::new().unwrap();`: + +```rust +benchmark_scalar_filters(c, &runtime); +``` + +
+Benchmark code + +```rust +fn benchmark_scalar_filters(c: &mut Criterion, runtime: &Runtime) { + use datafusion_common::ScalarValue; + use datafusion_execution::config::SessionConfig; + use datafusion_expr::{ColumnarValue, Volatility, create_udf}; + use datafusion_physical_expr::ScalarFunctionExpr; + + let schema = schema(); + let batch_filter = Arc::new(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()), + }), + )); + let varying: Arc = Arc::new( + ScalarFunctionExpr::try_new( + batch_filter, + vec![col("include_a", &schema).unwrap()], + &schema, + Arc::default(), + ) + .unwrap(), + ); + let filters = [ + ("true", Some(lit(true))), + ("false", Some(lit(false))), + ("null", Some(lit(ScalarValue::Boolean(None)))), + ("varying", Some(varying)), + ("array_50_percent", Some(col("include_a", &schema).unwrap())), + ("unfiltered", None), + ]; + let config = SessionConfig::new() + .set_usize( + "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", + 0, + ) + .set( + "datafusion.execution.skip_partial_aggregation_probe_ratio_threshold", + &ScalarValue::Float64(Some(0.0)), + ); + let task_ctx = Arc::new(TaskContext::default().with_session_config(config)); + for (name, mode, grouped) in [ + ("ungrouped", AggregateMode::Single, false), + ("grouped", AggregateMode::Single, true), + ("skip_partial", AggregateMode::Partial, true), + ] { + let batches = make_batches( + Some(50), + if mode == AggregateMode::Partial { + NUM_ROWS + } else { + 16 + }, + ); + let input: Arc = + TestMemoryExec::try_new_exec(&[batches], Arc::clone(&schema), None).unwrap(); + let mut group = c.benchmark_group(format!("scalar_aggregate_filter/{name}")); + for (filter_name, filter) in &filters { + let group_by = if grouped { + PhysicalGroupBy::new_single(vec![( + col("group_key", &schema).unwrap(), + "group_key".to_string(), + )]) + } else { + PhysicalGroupBy::default() + }; + let plan: Arc = Arc::new( + AggregateExec::try_new( + mode, + group_by, + vec![aggregate_expr(&schema, 0, ArgumentKind::Column)], + vec![filter.clone()], + Arc::clone(&input), + Arc::clone(&schema), + ) + .unwrap(), + ); + group.bench_function(*filter_name, |b| { + b.iter(|| { + black_box( + runtime + .block_on(collect(Arc::clone(&plan), Arc::clone(&task_ctx))) + .unwrap(), + ); + }); + }); + } + group.finish(); + } +} +``` + +
+ +Run from the repository root: + +```bash +cargo bench --profile release-nonlto -p datafusion-physical-plan \ + --features test_utils --bench aggregate_filter -- \ + scalar_aggregate_filter --warm-up-time 0.5 --measurement-time 1 \ + --sample-size 30 --noplot +``` + +For comparisons, apply the same snippet and registration call to both revisions, +use separate `CARGO_TARGET_DIR` directories, and alternate the run order. The +benchmark uses 65,536 rows in batches of 8,192, with 16 groups for grouped +aggregation and one group per row for skip-partial aggregation. The latter sets +both skip-partial probe thresholds to zero. The varying predicate returns the +first shuffled filter value in each batch as a scalar. + +### Recorded measurements + +The scalar FILTER change was compared with main at `34eb6dc5b`, using the same +benchmark source and `release-nonlto` builds. Times below are medians of three +per-run medians, with 30 Criterion samples, 0.5 s warm-up, and 1 s measurement per +case. The two revisions were run in alternating order. + +| Ungrouped FILTER | main median | Scalar path median | Change | +| ------------------------------ | ----------: | -----------------: | -----: | +| Scalar true | 13.54 us | 12.28 us | -9.3% | +| Scalar false | 5.75 us | 3.93 us | -31.7% | +| Scalar NULL | 7.21 us | 4.06 us | -43.7% | +| Scalar varying between batches | 7.45 us | 5.74 us | -23.0% | + +An initial short run suggested a 6.2% slowdown in the skip-partial array-filter +control. Three longer runs per build, alternating the run order, did not reproduce +it. To repeat those control measurements, use: + +```bash +cargo bench --profile release-nonlto -p datafusion-physical-plan \ + --features test_utils --bench aggregate_filter -- \ + 'scalar_aggregate_filter/(grouped|skip_partial)/(array_50_percent|unfiltered|true)$' \ + --warm-up-time 1 --measurement-time 3 --sample-size 60 --noplot +``` + +| Control | main median | Scalar path median | Change | +| ------------------------- | ----------: | -----------------: | -----: | +| Grouped array filter | 211.42 us | 210.88 us | -0.3% | +| Grouped unfiltered | 162.90 us | 162.12 us | -0.5% | +| Grouped scalar true | 162.36 us | 162.13 us | -0.1% | +| Skip-partial array filter | 196.14 us | 193.73 us | -1.2% | +| Skip-partial unfiltered | 134.08 us | 133.83 us | -0.2% | +| Skip-partial scalar true | 134.70 us | 134.04 us | -0.5% | + +These local microbenchmarks ran on a shared macOS machine. They measure aggregate +execution overhead and do not establish an end-to-end query speedup. diff --git a/datafusion/physical-plan/benches/aggregate_filter.rs b/datafusion/physical-plan/benches/aggregate_filter.rs index f967a8a23efc7..f0665cab6f21e 100644 --- a/datafusion/physical-plan/benches/aggregate_filter.rs +++ b/datafusion/physical-plan/benches/aggregate_filter.rs @@ -15,15 +15,13 @@ use arrow::array::{BooleanArray, Float64Array, UInt32Array}; use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; use arrow::record_batch::RecordBatch; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; -use datafusion_common::ScalarValue; use datafusion_execution::TaskContext; -use datafusion_execution::config::SessionConfig; -use datafusion_expr::{AggregateUDF, ColumnarValue, Operator, Volatility, create_udf}; +use datafusion_expr::{AggregateUDF, Operator}; use datafusion_functions_aggregate::count::count_udaf; use datafusion_functions_aggregate::sum::sum_udaf; +use datafusion_physical_expr::PhysicalExpr; use datafusion_physical_expr::aggregate::{AggregateExprBuilder, AggregateFunctionExpr}; use datafusion_physical_expr::expressions::{BinaryExpr, col, lit}; -use datafusion_physical_expr::{PhysicalExpr, ScalarFunctionExpr}; use datafusion_physical_plan::aggregates::{ AggregateExec, AggregateMode, PhysicalGroupBy, }; @@ -262,100 +260,8 @@ fn benchmark_case( } } -fn benchmark_scalar_filters(c: &mut Criterion, runtime: &Runtime) { - let schema = schema(); - let batch_filter = Arc::new(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()), - }), - )); - let varying: Arc = Arc::new( - ScalarFunctionExpr::try_new( - batch_filter, - vec![col("include_a", &schema).unwrap()], - &schema, - Arc::default(), - ) - .unwrap(), - ); - let filters = [ - ("true", Some(lit(true))), - ("false", Some(lit(false))), - ("null", Some(lit(ScalarValue::Boolean(None)))), - ("varying", Some(varying)), - ("array_50_percent", Some(col("include_a", &schema).unwrap())), - ("unfiltered", None), - ]; - let config = SessionConfig::new() - .set_usize( - "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", - 0, - ) - .set( - "datafusion.execution.skip_partial_aggregation_probe_ratio_threshold", - &ScalarValue::Float64(Some(0.0)), - ); - let task_ctx = Arc::new(TaskContext::default().with_session_config(config)); - for (name, mode, grouped) in [ - ("ungrouped", AggregateMode::Single, false), - ("grouped", AggregateMode::Single, true), - ("skip_partial", AggregateMode::Partial, true), - ] { - let batches = make_batches( - Some(50), - if mode == AggregateMode::Partial { - NUM_ROWS - } else { - 16 - }, - ); - let input: Arc = - TestMemoryExec::try_new_exec(&[batches], Arc::clone(&schema), None).unwrap(); - let mut group = c.benchmark_group(format!("scalar_aggregate_filter/{name}")); - for (filter_name, filter) in &filters { - let group_by = if grouped { - PhysicalGroupBy::new_single(vec![( - col("group_key", &schema).unwrap(), - "group_key".to_string(), - )]) - } else { - PhysicalGroupBy::default() - }; - let plan: Arc = Arc::new( - AggregateExec::try_new( - mode, - group_by, - vec![aggregate_expr(&schema, 0, ArgumentKind::Column)], - vec![filter.clone()], - Arc::clone(&input), - Arc::clone(&schema), - ) - .unwrap(), - ); - group.bench_function(*filter_name, |b| { - b.iter(|| { - black_box( - runtime - .block_on(collect(Arc::clone(&plan), Arc::clone(&task_ctx))) - .unwrap(), - ); - }); - }); - } - group.finish(); - } -} - fn aggregate_filter_benchmark(c: &mut Criterion) { let runtime = Runtime::new().unwrap(); - benchmark_scalar_filters(c, &runtime); benchmark_case( c, From 4b6ab334e479c7258c5f8a8965e68d20fef1dc71 Mon Sep 17 00:00:00 2001 From: "xudong.w" Date: Thu, 12 Nov 2026 10:24:17 +0800 Subject: [PATCH 3/4] docs: keep scalar filter benchmark in PR description --- datafusion/physical-plan/benches/README.md | 180 --------------------- 1 file changed, 180 deletions(-) delete mode 100644 datafusion/physical-plan/benches/README.md diff --git a/datafusion/physical-plan/benches/README.md b/datafusion/physical-plan/benches/README.md deleted file mode 100644 index 0511ca46469c9..0000000000000 --- a/datafusion/physical-plan/benches/README.md +++ /dev/null @@ -1,180 +0,0 @@ - - -# Physical plan benchmarks - -## Reproducing the scalar aggregate FILTER measurements - -The following optional benchmark exercises scalar `true`, `false`, `NULL`, and -batch-varying predicates in ungrouped, grouped, and skip-partial aggregation. -A shuffled 50%-selective array predicate and an unfiltered aggregate serve as -controls. It uses the existing in-memory `AggregateExec` benchmark helpers to -exclude SQL planning and file I/O. - -To run it locally, paste the function below into -[`aggregate_filter.rs`](aggregate_filter.rs), immediately before -`aggregate_filter_benchmark`. In `aggregate_filter_benchmark`, add this call -immediately after `let runtime = Runtime::new().unwrap();`: - -```rust -benchmark_scalar_filters(c, &runtime); -``` - -
-Benchmark code - -```rust -fn benchmark_scalar_filters(c: &mut Criterion, runtime: &Runtime) { - use datafusion_common::ScalarValue; - use datafusion_execution::config::SessionConfig; - use datafusion_expr::{ColumnarValue, Volatility, create_udf}; - use datafusion_physical_expr::ScalarFunctionExpr; - - let schema = schema(); - let batch_filter = Arc::new(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()), - }), - )); - let varying: Arc = Arc::new( - ScalarFunctionExpr::try_new( - batch_filter, - vec![col("include_a", &schema).unwrap()], - &schema, - Arc::default(), - ) - .unwrap(), - ); - let filters = [ - ("true", Some(lit(true))), - ("false", Some(lit(false))), - ("null", Some(lit(ScalarValue::Boolean(None)))), - ("varying", Some(varying)), - ("array_50_percent", Some(col("include_a", &schema).unwrap())), - ("unfiltered", None), - ]; - let config = SessionConfig::new() - .set_usize( - "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", - 0, - ) - .set( - "datafusion.execution.skip_partial_aggregation_probe_ratio_threshold", - &ScalarValue::Float64(Some(0.0)), - ); - let task_ctx = Arc::new(TaskContext::default().with_session_config(config)); - for (name, mode, grouped) in [ - ("ungrouped", AggregateMode::Single, false), - ("grouped", AggregateMode::Single, true), - ("skip_partial", AggregateMode::Partial, true), - ] { - let batches = make_batches( - Some(50), - if mode == AggregateMode::Partial { - NUM_ROWS - } else { - 16 - }, - ); - let input: Arc = - TestMemoryExec::try_new_exec(&[batches], Arc::clone(&schema), None).unwrap(); - let mut group = c.benchmark_group(format!("scalar_aggregate_filter/{name}")); - for (filter_name, filter) in &filters { - let group_by = if grouped { - PhysicalGroupBy::new_single(vec![( - col("group_key", &schema).unwrap(), - "group_key".to_string(), - )]) - } else { - PhysicalGroupBy::default() - }; - let plan: Arc = Arc::new( - AggregateExec::try_new( - mode, - group_by, - vec![aggregate_expr(&schema, 0, ArgumentKind::Column)], - vec![filter.clone()], - Arc::clone(&input), - Arc::clone(&schema), - ) - .unwrap(), - ); - group.bench_function(*filter_name, |b| { - b.iter(|| { - black_box( - runtime - .block_on(collect(Arc::clone(&plan), Arc::clone(&task_ctx))) - .unwrap(), - ); - }); - }); - } - group.finish(); - } -} -``` - -
- -Run from the repository root: - -```bash -cargo bench --profile release-nonlto -p datafusion-physical-plan \ - --features test_utils --bench aggregate_filter -- \ - scalar_aggregate_filter --warm-up-time 0.5 --measurement-time 1 \ - --sample-size 30 --noplot -``` - -For comparisons, apply the same snippet and registration call to both revisions, -use separate `CARGO_TARGET_DIR` directories, and alternate the run order. The -benchmark uses 65,536 rows in batches of 8,192, with 16 groups for grouped -aggregation and one group per row for skip-partial aggregation. The latter sets -both skip-partial probe thresholds to zero. The varying predicate returns the -first shuffled filter value in each batch as a scalar. - -### Recorded measurements - -The scalar FILTER change was compared with main at `34eb6dc5b`, using the same -benchmark source and `release-nonlto` builds. Times below are medians of three -per-run medians, with 30 Criterion samples, 0.5 s warm-up, and 1 s measurement per -case. The two revisions were run in alternating order. - -| Ungrouped FILTER | main median | Scalar path median | Change | -| ------------------------------ | ----------: | -----------------: | -----: | -| Scalar true | 13.54 us | 12.28 us | -9.3% | -| Scalar false | 5.75 us | 3.93 us | -31.7% | -| Scalar NULL | 7.21 us | 4.06 us | -43.7% | -| Scalar varying between batches | 7.45 us | 5.74 us | -23.0% | - -An initial short run suggested a 6.2% slowdown in the skip-partial array-filter -control. Three longer runs per build, alternating the run order, did not reproduce -it. To repeat those control measurements, use: - -```bash -cargo bench --profile release-nonlto -p datafusion-physical-plan \ - --features test_utils --bench aggregate_filter -- \ - 'scalar_aggregate_filter/(grouped|skip_partial)/(array_50_percent|unfiltered|true)$' \ - --warm-up-time 1 --measurement-time 3 --sample-size 60 --noplot -``` - -| Control | main median | Scalar path median | Change | -| ------------------------- | ----------: | -----------------: | -----: | -| Grouped array filter | 211.42 us | 210.88 us | -0.3% | -| Grouped unfiltered | 162.90 us | 162.12 us | -0.5% | -| Grouped scalar true | 162.36 us | 162.13 us | -0.1% | -| Skip-partial array filter | 196.14 us | 193.73 us | -1.2% | -| Skip-partial unfiltered | 134.08 us | 133.83 us | -0.2% | -| Skip-partial scalar true | 134.70 us | 134.04 us | -0.5% | - -These local microbenchmarks ran on a shared macOS machine. They measure aggregate -execution overhead and do not establish an end-to-end query speedup. From 60007e4752b5adcd103ddeb2f04973ad17273ba4 Mon Sep 17 00:00:00 2001 From: "xudong.w" Date: Thu, 26 Nov 2026 10:51:52 +0800 Subject: [PATCH 4/4] refactor: normalize aggregate FILTER selections Evaluate an aggregate FILTER to All, Empty, or Rows, folding arrays that select every row or none into the same cases as scalar predicates. The ungrouped, compacting, and skip-partial paths share this representation, and the ungrouped path now also skips argument evaluation for arrays that reject every row. Cover literal, constant-folded, and prepared statement predicates in SQLLogicTest. Check array_agg, which keeps NULL arguments, so skip-partial conversion must still pass a rejecting filter when no row is selected. --- datafusion/core/tests/sql/aggregates/basic.rs | 22 +++ .../src/aggregates/aggregate_argument.rs | 136 ++++++++++++++++-- .../aggregates/aggregate_hash_table/common.rs | 127 +++++++--------- .../src/aggregates/aggregate_stream.rs | 15 +- .../test_files/aggregate_filter_selection.slt | 92 ++++++++++++ 5 files changed, 292 insertions(+), 100 deletions(-) diff --git a/datafusion/core/tests/sql/aggregates/basic.rs b/datafusion/core/tests/sql/aggregates/basic.rs index d18675ba0c1ab..3fdf9a1c4b235 100644 --- a/datafusion/core/tests/sql/aggregates/basic.rs +++ b/datafusion/core/tests/sql/aggregates/basic.rs @@ -121,6 +121,28 @@ async fn aggregate_scalar_filter() -> Result<()> { 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, diff --git a/datafusion/physical-plan/src/aggregates/aggregate_argument.rs b/datafusion/physical-plan/src/aggregates/aggregate_argument.rs index 2f061fb72fe29..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; @@ -152,10 +153,18 @@ pub(in crate::aggregates) struct AggregateFilter { selected_schema: Option<(SchemaRef, SchemaRef)>, } -/// An aggregate filter result, retaining predicates that select or reject a whole batch. -pub(in crate::aggregates) enum AggregateFilterValue { - Scalar(bool), - Array(BooleanArray), +/// 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 { @@ -181,22 +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 { - match self.predicate.evaluate(batch)? { - ColumnarValue::Scalar(ScalarValue::Boolean(value)) => { - Ok(AggregateFilterValue::Scalar(value.unwrap_or(false))) + ) -> Result { + let selection = match self.predicate.evaluate(batch)? { + ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))) => { + return Ok(AggregateSelection::All); } - value => { - let selection = value.into_array(batch.num_rows())?; - Ok(AggregateFilterValue::Array( - as_boolean_array(&selection)?.clone(), - )) + 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 @@ -389,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 c610815e70d7d..9b9fd726618fe 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs @@ -23,7 +23,7 @@ use log::debug; use crate::PhysicalExpr; use crate::aggregates::aggregate_argument::{ - AggregateArgument, AggregateFilter, AggregateFilterValue, + AggregateArgument, AggregateFilter, AggregateSelection, }; use crate::aggregates::group_values::{ AccumulatorPhase, AggregateAccumulatorMetrics, AggregateArgumentMetrics, @@ -489,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(|| { @@ -566,15 +566,17 @@ pub(super) struct CompactedAccumulatorArgs { /// Argument arrays containing only selected rows. Some aggregate functions take /// multiple arguments. pub(super) arguments: Vec, - /// 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, } @@ -788,25 +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 { - AggregateFilterValue::Scalar(true) if batch.num_rows() > 0 => { - Some(Cow::Borrowed(batch)) - } - AggregateFilterValue::Scalar(_) => None, - AggregateFilterValue::Array(selection) => { - 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 @@ -836,55 +824,39 @@ impl HashAggregateAccumulator { &mut self, batch: &RecordBatch, ) -> Result { - let selection = self - .filter - .as_ref() - .map(|filter| filter.evaluate(batch)) - .transpose()?; - let selection = match selection { - None | Some(AggregateFilterValue::Scalar(true)) => { + let Some(filter) = &mut self.filter else { + return Ok(RowAlignedAccumulatorArgs { + arguments: self.evaluate_arguments(batch)?, + filter: None, + }); + }; + 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(batch)) + .map(|argument| { + argument.evaluate_selection(batch, &selection, &selected) + }) .collect::>()?; - return Ok(RowAlignedAccumulatorArgs { - arguments, - filter: None, - }); + (arguments, Some(selection)) } - Some(AggregateFilterValue::Scalar(false)) => { - // State conversion must retain rejected rows, and its interface - // requires an array filter even for a scalar predicate. - return Ok(RowAlignedAccumulatorArgs { - arguments: self.null_arguments(batch.num_rows()), - filter: Some(BooleanArray::new( - BooleanBuffer::new_unset(batch.num_rows()), - None, - )), - }); - } - Some(AggregateFilterValue::Array(selection)) => selection, }; - 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 = self.filter.as_mut().unwrap().select(batch, &selection)?; - let arguments = self - .arguments - .iter_mut() - .map(|argument| argument.evaluate_selection(batch, &selection, &selected)) - .collect::>()?; - Ok(RowAlignedAccumulatorArgs { arguments, - filter: Some(selection), + filter: selection, }) } @@ -903,18 +875,15 @@ impl HashAggregateAccumulator { group_indices: &[usize], total_num_groups: usize, ) -> Result<()> { - let filtered_group_indices = - values - .selection - .as_ref() - .and_then(|selection| match selection { - AggregateFilterValue::Scalar(true) => None, - AggregateFilterValue::Scalar(false) => Some(vec![]), - AggregateFilterValue::Array(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, @@ -929,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) } @@ -964,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 c84b7ae664a66..4ee0468cbea8e 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_stream.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_stream.rs @@ -4,9 +4,7 @@ //! Aggregate without grouping columns -use crate::aggregates::aggregate_argument::{ - AggregateArgument, AggregateFilter, AggregateFilterValue, -}; +use crate::aggregates::aggregate_argument::{AggregateArgument, AggregateFilter}; use crate::aggregates::group_values::{ AccumulatorPhase, AggregateAccumulatorMetrics, AggregateArgumentMetrics, aggregate_sub_metrics, @@ -508,13 +506,10 @@ fn aggregate_batch( // 1.2 and 1.3 let values = aggregate_argument_metrics.time(index, || { let batch = match filter { - Some(filter) => match filter.evaluate(batch)? { - AggregateFilterValue::Scalar(true) => Some(Cow::Borrowed(batch)), - AggregateFilterValue::Scalar(false) => None, - AggregateFilterValue::Array(selection) => { - Some(Cow::Owned(filter.select(batch, &selection)?)) - } - }, + Some(filter) => { + let selection = filter.evaluate(batch)?; + filter.selected_batch(batch, &selection)? + } None => Some(Cow::Borrowed(batch)), }; arguments 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;