From e6abd885f722852617d620e16c776079eb0bc559 Mon Sep 17 00:00:00 2001 From: QinXi <3624951962@qq.com> Date: Thu, 1 Oct 2026 11:03:04 +0000 Subject: [PATCH 1/5] perf(aggregate): specialize fully ordered group keys without hashing (#25150) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #14574 for supported fully ordered multi-column keys. Single-column specializations and additional key types remain on their existing paths. When input is already sorted by all grouping expressions, DataFusion can emit completed groups early, but its multi-column group-key mapping still hashes each row and maintains a hash table. This adds CPU and retained state even though equal keys must be consecutive. - Add an internal columnar `GroupValuesOrdered` selected only for `GroupOrdering::Full` and supported multi-column schemas. Arrow's partition kernel identifies adjacent runs; existing column builders retain representatives and compare the boundary key across batches. Dense IDs, partial emission, preserving selections, and reset behavior follow the existing contracts. - Support boolean, integer, string, and binary keys, including their large/view variants. Keep single-column, float, nested, dictionary, partially ordered, and unordered inputs on established paths. - Add differential correctness tests and a reproducible benchmark covering two key schemas, batch sizes 127/8192, and run lengths 1/8/128/8192. Include both grouping with emission and complete ordered `AggregateExec` execution. - Include two small Windows lint compatibility fixes needed to run the repository's full Clippy command: remove a redundant semicolon in rounding and add a Windows-only `unused_async` expectation to the unsupported FIFO example's uniform async entry point. This builds on the problem and review in #9662, particularly its single-column regression and requests for repeatable measurements and cross-batch tests. It is distinct from #23986's consecutive-key cache for clustered input, which retains the general hash path. This PR optimizes existing streaming aggregation; it does not introduce streaming aggregation or change whole-query asymptotic complexity. `ordered_keys_match_hash_grouping_across_batches_and_emits` compares group IDs and emitted/preserved keys with `GroupValuesColumn` for 15 key types, ascending/descending runs, NULLs, long strings, six batch sizes, and four emission limits. It also exercises empty batches and reset/reuse. A schema gate test covers excluded types. `ordered_single_and_partial_final_match_unordered_execution` compares actual `AggregateExec` results with unordered execution for Single and Partial→Final with FILTER, using four batch sizes and asserted sorted execution. Validation after the September 26 conflict-resolution rebase onto `main` at `6a792c6` (Windows, Rust 1.98.1): `cargo fmt --all -- --check`, `git diff --check`, `cargo test --offline --locked -p datafusion-physical-plan --lib` (**2,323 passed, 0 failed**), focused physical-plan library Clippy with `-D warnings`, and `cargo check --offline --locked -p datafusion-physical-plan --bench ordered_group_values` passed. Full `cargo clippy --all-targets --all-features -- -D warnings` was attempted but stopped while linking `protobuf-src`'s `protoc` on this Windows machine (`LNK2019`/`LNK1120`); it is not a passing full lint result. Fresh Linux CI remains to be seen for the rebased head. Earlier local validation on Windows, before this rebase: - Rust 1.97.0: full `cargo clippy --all-targets --all-features -- -D warnings` and formatting checks pass. - Rust 1.98.1, CI profile, extended workspace features: 11,333 tests passed across recorded runs, including all 2,050 physical-plan tests, 120 fuzz tests, and the two 5M-row SMJ low-memory runners. Eight tests are ignored, with no pending test programs. Seven baseline-reproduced failures remain, so this is not a full-workspace pass. - Seven failures reproduce with the same assertion differences on unmodified baseline `423df6f4`: two datasource path tests, four floating-point interval/statistics tests, and the xtask CI command snapshot. These remain recorded failures. - Windows library backtrace capture was disabled for the extended run because it made error-path tests exceptionally slow. The common crate's 650 tests, including backtrace behavior, pass separately with capture enabled. A CRLF checkout of the Q15 fixture was normalized to its original LF contents so the existing multi-statement skip works as intended; no test assertion was changed. - An external process interruption required resuming missing tests from Cargo's compiled artifact list. Completed suite summaries and unique individual test results were retained; this does not represent one successful full-workspace Cargo invocation. Linux CI passed on the pre-rebase head `a62b640`. The following benchmark measurements predate the September 26 rebase and have not been rerun against `6a792c6`. They were collected on an Intel Core Ultra 7 258V / Windows, Rust 1.98.1, `release-nonlto`, pinned to logical CPU 0, with no concurrent task builds/tests. Baseline and candidate were built from separate source directories with identical lockfiles. The run order was baseline, candidate, candidate, baseline; each case used 250 ms warmup, 10 samples, and at least 1 second of measurement. The complete ordered `AggregateExec` benchmark uses 8,192-row batches. Speedup ranges below are `min(baseline) / max(candidate)` through `max(baseline) / min(candidate)` across the two repetitions; they are not confidence intervals for the ratio. | Keys / rows per group | Baseline ms (two runs) | Candidate ms (two runs) | Speedup range | |---|---:|---:|---:| | int / 1 | 6.086, 5.269 | 1.609, 1.857 | 2.84–3.78x | | int / 8 | 2.434, 2.296 | 0.480, 0.609 | 3.77–5.07x | | int / 128 | 2.112, 1.949 | 0.549, 0.598 | 3.26–3.85x | | int / 8192 | 2.162, 2.059 | 0.545, 0.553 | 3.73–3.97x | | string / 1 | 9.616, 9.665 | 4.793, 5.521 | 1.74–2.02x | | string / 8 | 4.333, 4.422 | 1.697, 1.660 | 2.55–2.66x | | string / 128 | 3.723, 3.464 | 1.747, 1.638 | 1.98–2.27x | | string / 8192 | 3.907, 3.745 | 1.613, 1.607 | 2.32–2.43x | All 16 selected grouping microbenchmark cases also have faster point estimates in both repetitions; the weakest cross-repetition ratio is approximately 1.06x for long strings in 127-row batches. Small differences on one machine should not be generalized across platforms. At batch size 8192 / run length 1, peak retained group state drops from 425,792 to 196,608 bytes for integer keys and from 950,080 to 720,896 bytes for integer/long-string keys. The benchmark pre-generates 131,072 rows and excludes input generation, sorting, SQL planning, and I/O. The grouping benchmark includes partial/final emission; the execution benchmark includes SUM and output collection on already ordered input. `group_state_bytes` reports peak retained `GroupValues::size()`, excluding shared inputs and transient kernel allocations; it is not process RSS. Eligible fully ordered multi-column aggregations use less grouping state and avoid hashing. No SQL syntax, result semantics, configuration, or public API changes. This contribution is AI-assisted. --------- Co-authored-by: hushen <190065939+918154429@users.noreply.github.com> Co-authored-by: kosiew (cherry picked from commit 5635e5c1965fcb8b52201ebdfc6b3748f25ff139) Environment: Datadog workspace Co-authored-by: Codex GPT-6.2 Astra --- .../file_stream_provider.rs | 7 + datafusion/common/src/rounding.rs | 2 +- datafusion/physical-plan/Cargo.toml | 4 + .../benches/ordered_group_values.rs | 265 ++++++++++ .../src/aggregates/group_values/mod.rs | 10 +- .../group_values/multi_group_by/mod.rs | 2 + .../group_values/multi_group_by/ordered.rs | 491 ++++++++++++++++++ 7 files changed, 779 insertions(+), 2 deletions(-) create mode 100644 datafusion/physical-plan/benches/ordered_group_values.rs create mode 100644 datafusion/physical-plan/src/aggregates/group_values/multi_group_by/ordered.rs diff --git a/datafusion-examples/examples/custom_data_source/file_stream_provider.rs b/datafusion-examples/examples/custom_data_source/file_stream_provider.rs index 5b43072d43f80..49be4469c3947 100644 --- a/datafusion-examples/examples/custom_data_source/file_stream_provider.rs +++ b/datafusion-examples/examples/custom_data_source/file_stream_provider.rs @@ -28,6 +28,13 @@ /// with DataFusion without needing to reload the entire dataset each time. /// /// This example does not work on Windows. +#[cfg_attr( + target_os = "windows", + expect( + clippy::unused_async, + reason = "keep the same async entry point on all platforms" + ) +)] pub async fn file_stream_provider() -> datafusion::error::Result<()> { #[cfg(target_os = "windows")] { diff --git a/datafusion/common/src/rounding.rs b/datafusion/common/src/rounding.rs index 1796143d7cf1a..b3b514e8631c8 100644 --- a/datafusion/common/src/rounding.rs +++ b/datafusion/common/src/rounding.rs @@ -254,7 +254,7 @@ where } } _ => {} - }; + } Ok(result) } diff --git a/datafusion/physical-plan/Cargo.toml b/datafusion/physical-plan/Cargo.toml index 552b979c785a4..356b8d83fdcf5 100644 --- a/datafusion/physical-plan/Cargo.toml +++ b/datafusion/physical-plan/Cargo.toml @@ -151,3 +151,7 @@ required-features = ["test_utils"] [[bench]] harness = false name = "bounded_window" + +[[bench]] +harness = false +name = "ordered_group_values" diff --git a/datafusion/physical-plan/benches/ordered_group_values.rs b/datafusion/physical-plan/benches/ordered_group_values.rs new file mode 100644 index 0000000000000..ae0e44a859d5e --- /dev/null +++ b/datafusion/physical-plan/benches/ordered_group_values.rs @@ -0,0 +1,265 @@ +// 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. + +//! Fully ordered grouping: compare the selected implementation with the +//! existing streaming hash table on identical batches. Include emission and +//! cross-batch continuation, not just lookup. Input preparation is untimed. +//! The physical-plan benchmark includes aggregation but excludes SQL planning, +//! sorting and I/O; the data already has a proven ordering. + +use std::hint::black_box; +use std::sync::Arc; +use std::time::Duration; + +use arrow::array::{ArrayRef, Int32Array, Int64Array, StringArray}; +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use arrow::record_batch::RecordBatch; +use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; +use datafusion_execution::TaskContext; +use datafusion_expr::EmitTo; +use datafusion_functions_aggregate::sum::sum_udaf; +use datafusion_physical_expr::aggregate::AggregateExprBuilder; +use datafusion_physical_expr::expressions::col; +use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr}; +use datafusion_physical_plan::aggregates::group_values::multi_group_by::GroupValuesColumn; +use datafusion_physical_plan::aggregates::group_values::{GroupValues, new_group_values}; +use datafusion_physical_plan::aggregates::order::GroupOrdering; +use datafusion_physical_plan::aggregates::{ + AggregateExec, AggregateMode, PhysicalGroupBy, +}; +use datafusion_physical_plan::test::TestMemoryExec; +use datafusion_physical_plan::{ExecutionPlan, InputOrderMode, collect}; +use tokio::runtime::Runtime; + +const ROWS: usize = 131_072; + +fn inputs( + run_length: usize, + batch_size: usize, + strings: bool, +) -> (SchemaRef, Vec>) { + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, false), + Field::new( + "b", + if strings { + DataType::Utf8 + } else { + DataType::Int32 + }, + false, + ), + ])); + let batches = (0..ROWS) + .step_by(batch_size) + .map(|start| { + let end = (start + batch_size).min(ROWS); + let first: ArrayRef = Arc::new(Int32Array::from_iter_values( + (start..end).map(|row| ((row / run_length) / 4) as i32), + )); + let second: ArrayRef = if strings { + Arc::new(StringArray::from_iter_values((start..end).map(|row| { + format!("key-{}-a-longer-than-inline-string", (row / run_length) % 4) + }))) + } else { + Arc::new(Int32Array::from_iter_values( + (start..end).map(|row| ((row / run_length) % 4) as i32), + )) + }; + vec![first, second] + }) + .collect(); + (schema, batches) +} + +fn grouping(c: &mut Criterion) { + let mut group = c.benchmark_group("fully_ordered_grouping"); + group.sample_size(10); + group.warm_up_time(Duration::from_millis(250)); + group.measurement_time(Duration::from_secs(1)); + for strings in [false, true] { + for batch_size in [127, 8192] { + for run_length in [1, 8, 128, 8192] { + let (schema, batches) = inputs(run_length, batch_size, strings); + let case = format!( + "{}_batch{batch_size}_run{run_length}", + if strings { "string" } else { "int" } + ); + let (hashed_bytes, selected_bytes) = check_case(&schema, &batches); + eprintln!( + "group_state_bytes {case} hashed={hashed_bytes} selected={selected_bytes}" + ); + for selected in [false, true] { + let name = if selected { "selected" } else { "hashed" }; + group.bench_function(BenchmarkId::new(name, &case), |b| { + b.iter_batched_ref( + || { + let values: Box = if selected { + new_group_values( + Arc::clone(&schema), + &GroupOrdering::try_new(&InputOrderMode::Sorted) + .unwrap(), + ) + .unwrap() + } else { + Box::new( + GroupValuesColumn::::try_new(Arc::clone( + &schema, + )) + .unwrap(), + ) + }; + (values, Vec::new()) + }, + |(values, ids)| { + for batch in &batches { + values.intern(batch, ids).unwrap(); + black_box(&*ids); + let completed = values.len().saturating_sub(1); + if completed > 0 { + black_box( + values + .emit(EmitTo::First(completed)) + .unwrap(), + ); + } + } + black_box(values.emit(EmitTo::All).unwrap()); + }, + criterion::BatchSize::LargeInput, + ); + }); + } + } + } + } + group.finish(); +} + +// Validate the benchmark input and report retained grouping-state memory. +// These counters exclude the shared input and transient kernel allocations; +// they are not process RSS measurements. Neither validation nor reporting is timed. +fn check_case(schema: &SchemaRef, batches: &[Vec]) -> (usize, usize) { + let mut hashed = GroupValuesColumn::::try_new(Arc::clone(schema)).unwrap(); + let mut selected = new_group_values( + Arc::clone(schema), + &GroupOrdering::try_new(&InputOrderMode::Sorted).unwrap(), + ) + .unwrap(); + let mut expected = Vec::new(); + let mut actual = Vec::new(); + let mut hashed_peak = 0; + let mut selected_peak = 0; + for batch in batches { + hashed.intern(batch, &mut expected).unwrap(); + selected.intern(batch, &mut actual).unwrap(); + assert_eq!(actual, expected); + hashed_peak = hashed_peak.max(hashed.size()); + selected_peak = selected_peak.max(selected.size()); + let completed = hashed.len().saturating_sub(1); + assert_eq!( + selected.emit(EmitTo::First(completed)).unwrap(), + hashed.emit(EmitTo::First(completed)).unwrap() + ); + } + assert_eq!( + selected.emit(EmitTo::All).unwrap(), + hashed.emit(EmitTo::All).unwrap() + ); + (hashed_peak, selected_peak) +} + +fn aggregate_plan( + schema: &SchemaRef, + keys: Vec>, +) -> Arc { + let mut fields = schema.fields().to_vec(); + fields.push(Arc::new(Field::new("v", DataType::Int64, false))); + let schema = Arc::new(Schema::new(fields)); + let batches = keys + .into_iter() + .map(|mut cols| { + cols.push(Arc::new(Int64Array::from(vec![1; cols[0].len()]))); + RecordBatch::try_new(Arc::clone(&schema), cols).unwrap() + }) + .collect::>(); + let ordering = LexOrdering::new(vec![ + PhysicalSortExpr::new_default(col("a", &schema).unwrap()), + PhysicalSortExpr::new_default(col("b", &schema).unwrap()), + ]) + .unwrap(); + let input = + TestMemoryExec::try_new_exec(&[batches], Arc::clone(&schema), None).unwrap(); + let input = Arc::new( + input + .as_ref() + .clone() + .try_with_sort_information(vec![ordering]) + .unwrap(), + ); + let expr = AggregateExprBuilder::new(sum_udaf(), vec![col("v", &schema).unwrap()]) + .schema(Arc::clone(&schema)) + .alias("sum_v") + .build() + .unwrap(); + let plan = AggregateExec::try_new( + AggregateMode::Single, + PhysicalGroupBy::new_single(vec![ + (col("a", &schema).unwrap(), "a".into()), + (col("b", &schema).unwrap(), "b".into()), + ]), + vec![Arc::new(expr)], + vec![None], + input, + schema, + ) + .unwrap(); + assert_eq!(plan.input_order_mode(), &InputOrderMode::Sorted); + Arc::new(plan) +} + +fn aggregation(c: &mut Criterion) { + let runtime = Runtime::new().unwrap(); + let mut group = c.benchmark_group("fully_ordered_aggregate_exec"); + group.sample_size(10); + group.warm_up_time(Duration::from_millis(250)); + group.measurement_time(Duration::from_secs(1)); + for strings in [false, true] { + for run_length in [1, 8, 128, 8192] { + let (schema, keys) = inputs(run_length, 8192, strings); + let plan = aggregate_plan(&schema, keys); + let name = + format!("{}_run{run_length}", if strings { "string" } else { "int" }); + group.bench_function(name, |b| { + b.iter(|| { + black_box( + runtime + .block_on(collect( + Arc::clone(&plan), + Arc::new(TaskContext::default()), + )) + .unwrap(), + ) + }); + }); + } + } + group.finish(); +} + +criterion_group!(benches, grouping, aggregation); +criterion_main!(benches); diff --git a/datafusion/physical-plan/src/aggregates/group_values/mod.rs b/datafusion/physical-plan/src/aggregates/group_values/mod.rs index 92880dad291a6..70405cfd9da18 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/mod.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/mod.rs @@ -34,7 +34,7 @@ mod row; pub use row::GroupValuesRows; mod single_group_by; use datafusion_physical_expr::binary_map::OutputType; -use multi_group_by::GroupValuesColumn; +use multi_group_by::{GroupValuesColumn, GroupValuesOrdered}; pub(crate) use single_group_by::primitive::HashValue; @@ -121,6 +121,9 @@ pub trait GroupValues: Send { /// /// [`GroupValues`] implementations choosing logic: /// +/// - Fully ordered multi-column keys with supported scalar types use adjacent +/// comparisons and column builders, without a hash table. +/// /// - If group by single column, and type of this column has /// the specific [`GroupValues`] implementation, such implementation /// will be chosen. @@ -137,6 +140,11 @@ pub fn new_group_values( schema: SchemaRef, group_clustering: &GroupClustering, ) -> Result> { + if matches!(group_ordering, GroupOrdering::Full(_)) + && GroupValuesOrdered::supports_schema(&schema) + { + return Ok(Box::new(GroupValuesOrdered::try_new(schema)?)); + } if schema.fields.len() == 1 { let d = schema.fields[0].data_type(); diff --git a/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs index 409e159216df6..7cbc9182a8948 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs @@ -22,6 +22,8 @@ mod bytes; pub mod bytes_view; mod dictionary; mod fixed_size_binary; +mod ordered; +pub(super) use ordered::GroupValuesOrdered; pub mod primitive; pub mod row_backed; diff --git a/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/ordered.rs b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/ordered.rs new file mode 100644 index 0000000000000..9e34ac7aeac17 --- /dev/null +++ b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/ordered.rs @@ -0,0 +1,491 @@ +// 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. + +use std::mem; + +use arrow::array::ArrayRef; +use arrow::datatypes::{DataType, Schema, SchemaRef}; +use arrow_ord::partition::partition; +use datafusion_common::{Result, not_impl_err}; +use datafusion_execution::memory_pool::proxy::VecAllocExt; +use datafusion_expr::{EmitTo, GroupSelection}; + +use super::{GroupColumn, GroupValuesColumn}; +use crate::aggregates::group_values::GroupValues; + +/// Columnar group keys for input fully ordered by all grouping expressions. +/// +/// Equal keys must be contiguous across input batches. Within a batch Arrow's +/// partition kernel finds those runs. Only the first run can continue the last +/// buffered group; compare it with the stored columns, without retaining the +/// input batch. New group representatives use the existing column builders. +/// +/// This removes hashing and hash-table storage, but does not change the dense +/// group-id or emission contracts. In particular, `First(n)` shifts the remaining +/// keys and their ids together. Partially ordered inputs must use a hash table. +pub(crate) struct GroupValuesOrdered { + schema: SchemaRef, + columns: Vec>, + new_groups: Vec, +} + +impl GroupValuesOrdered { + /// Types for which adjacent Arrow equality agrees with GROUP BY equality. + /// Keep single-column specializations and floats/nested/encoded keys on the + /// established path until their semantics and performance are validated. + pub(crate) fn supports_schema(schema: &Schema) -> bool { + schema.fields().len() > 1 + && schema.fields().iter().all(|field| { + matches!( + field.data_type(), + DataType::Boolean + | DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Utf8View + | DataType::Binary + | DataType::LargeBinary + | DataType::BinaryView + ) + }) + } + + pub(crate) fn try_new(schema: SchemaRef) -> Result { + if !Self::supports_schema(&schema) { + return not_impl_err!( + "Unsupported schema for fully ordered group values: {schema}" + ); + } + let columns = GroupValuesColumn::::build_group_columns(&schema)?; + Ok(Self { + schema, + columns, + new_groups: Vec::new(), + }) + } +} + +impl GroupValues for GroupValuesOrdered { + fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec) -> Result<()> { + groups.clear(); + let ranges = partition(cols)?.ranges(); + if ranges.is_empty() { + return Ok(()); + } + + let old_len = self.len(); + let continues = old_len > 0 + && self + .columns + .iter() + .zip(cols) + .all(|(stored, input)| stored.equal_to(old_len - 1, input, 0)); + + self.new_groups.clear(); + self.new_groups.extend( + ranges + .iter() + .skip(usize::from(continues)) + .map(|range| range.start), + ); + for (stored, input) in self.columns.iter_mut().zip(cols) { + stored.vectorized_append(input, &self.new_groups)?; + } + + let first_group = old_len - usize::from(continues); + for (index, range) in ranges.iter().enumerate() { + groups.resize(range.end, first_group + index); + } + Ok(()) + } + + fn size(&self) -> usize { + self.columns + .iter() + .map(|column| column.size()) + .sum::() + + self.new_groups.allocated_size() + } + + fn is_empty(&self) -> bool { + self.len() == 0 + } + + fn len(&self) -> usize { + self.columns[0].len() + } + + fn emit(&mut self, emit_to: EmitTo) -> Result> { + Ok(match emit_to { + EmitTo::All => { + let fresh = GroupValuesColumn::::build_group_columns(&self.schema)?; + mem::replace(&mut self.columns, fresh) + .into_iter() + .map(|column| column.build()) + .collect() + } + EmitTo::First(n) => self + .columns + .iter_mut() + .map(|column| column.take_n(n)) + .collect(), + }) + } + + fn values_preserving( + &mut self, + selection: GroupSelection<'_>, + ) -> Result> { + selection.validate_num_groups(self.len())?; + self.columns + .iter() + .map(|column| column.values_preserving(selection)) + .collect() + } + + fn supports_values_preserving(&self) -> bool { + true + } + + fn clear_shrink(&mut self, num_rows: usize) { + self.columns = GroupValuesColumn::::build_group_columns(&self.schema) + .expect("schema validated by GroupValuesOrdered::try_new"); + self.new_groups.clear(); + self.new_groups.shrink_to(num_rows); + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow::array::UInt32Array; + use arrow::array::{Array, BooleanArray, Int32Array, Int64Array, StringArray}; + use arrow::compute::{cast, take}; + use arrow::datatypes::Field; + use datafusion_expr::GroupSelection; + + use super::*; + + // Compare with the existing hash implementation, changing actual input + // boundaries and removing completed groups between batches. This checks the + // semantic contract rather than duplicating the adjacent-run algorithm. + #[test] + fn ordered_keys_match_hash_grouping_across_batches_and_emits() -> Result<()> { + for key_type in [ + DataType::Boolean, + DataType::Int8, + DataType::Int16, + DataType::Int32, + DataType::Int64, + DataType::UInt8, + DataType::UInt16, + DataType::UInt32, + DataType::UInt64, + DataType::Utf8, + DataType::LargeUtf8, + DataType::Utf8View, + DataType::Binary, + DataType::LargeBinary, + DataType::BinaryView, + ] { + let rows = 1025; + let first: ArrayRef = Arc::new(Int32Array::from_iter((0..rows).map(|row| { + let group = row / 7; + (group >= 4).then_some(group / 4) + }))); + let second: ArrayRef = match key_type { + DataType::Boolean => { + Arc::new(BooleanArray::from_iter((0..rows).map(|row| { + let key = (row / 7) % 4; + (key != 0).then_some(key >= 2) + }))) + } + DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Utf8View + | DataType::Binary + | DataType::LargeBinary + | DataType::BinaryView => { + let strings = StringArray::from_iter((0..rows).map(|row| { + let key = (row / 7) % 4; + (key != 0).then(|| { + format!( + "key-{key}-{}", + "x".repeat(if key == 3 { 128 } else { 0 }) + ) + }) + })); + cast(&strings, &key_type)? + } + _ => { + let values = Int32Array::from_iter((0..rows).map(|row| { + let key = (row / 7) % 4; + (key != 0).then_some(key) + })); + cast(&values, &key_type)? + } + }; + for descending in [false, true] { + let mut input = vec![Arc::clone(&first), Arc::clone(&second)]; + if descending { + let reverse = UInt32Array::from_iter_values((0..rows as u32).rev()); + input = input + .iter() + .map(|array| take(array, &reverse, None)) + .collect::>()?; + } + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", key_type.clone(), true), + ])); + for batch_size in [1, 2, 7, 8, 63, 1024] { + for emit_limit in [0, 1, 17, usize::MAX] { + let mut ordered = + GroupValuesOrdered::try_new(Arc::clone(&schema))?; + let mut hashed = + GroupValuesColumn::::try_new(Arc::clone(&schema))?; + let mut actual = Vec::new(); + let mut expected = Vec::new(); + for offset in (0..rows as usize).step_by(batch_size) { + let length = batch_size.min(rows as usize - offset); + let batch = input + .iter() + .map(|array| array.slice(offset, length)) + .collect::>(); + ordered.intern(&batch, &mut actual)?; + hashed.intern(&batch, &mut expected)?; + assert_eq!( + actual, expected, + "{key_type:?}, batch={batch_size}, offset={offset}, descending={descending}" + ); + assert_eq!(ordered.len(), hashed.len()); + let selection = GroupSelection::all(ordered.len()); + assert_eq!( + ordered.values_preserving(selection)?, + hashed.values_preserving(selection)? + ); + // A zero-row batch must neither forget the boundary + // key nor leave stale group ids in the output buffer. + let empty = batch + .iter() + .map(|array| array.slice(0, 0)) + .collect::>(); + ordered.intern(&empty, &mut actual)?; + assert!(actual.is_empty()); + let emit = emit_limit.min(ordered.len().saturating_sub(1)); + assert_eq!( + ordered.emit(EmitTo::First(emit))?, + hashed.emit(EmitTo::First(emit))? + ); + } + assert_eq!(ordered.emit(EmitTo::All)?, hashed.emit(EmitTo::All)?); + assert!(ordered.is_empty()); + // All and clear_shrink reset the cross-batch state. + ordered.clear_shrink(0); + hashed.clear_shrink(0); + ordered.intern(&input, &mut actual)?; + hashed.intern(&input, &mut expected)?; + assert_eq!(actual, expected); + assert_eq!(ordered.emit(EmitTo::All)?, hashed.emit(EmitTo::All)?); + } + } + } + } + Ok(()) + } + + #[test] + fn ordered_schema_gate_keeps_unvalidated_types_on_existing_paths() { + for data_type in [ + DataType::Float32, + DataType::Float64, + DataType::Null, + DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)), + DataType::List(Arc::new(Field::new("item", DataType::Int32, true))), + ] { + let schema = Schema::new(vec![ + Field::new("a", DataType::Int32, false), + Field::new("b", data_type, true), + ]); + assert!(!GroupValuesOrdered::supports_schema(&schema)); + } + assert!(!GroupValuesOrdered::supports_schema(&Schema::new(vec![ + Field::new("a", DataType::Int32, false) + ]))); + } + + #[tokio::test] + async fn ordered_single_and_partial_final_match_unordered_execution() -> Result<()> { + use crate::aggregates::{AggregateExec, AggregateMode, PhysicalGroupBy}; + use crate::test::TestMemoryExec; + use crate::{ExecutionPlan, InputOrderMode, collect}; + use arrow::compute::{SortOptions, take_record_batch}; + use arrow::record_batch::RecordBatch; + use arrow::row::{RowConverter, SortField}; + use datafusion_execution::TaskContext; + use datafusion_functions_aggregate::sum::sum_udaf; + use datafusion_physical_expr::aggregate::AggregateExprBuilder; + use datafusion_physical_expr::expressions::col; + use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr}; + + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Utf8, false), + Field::new("v", DataType::Int64, false), + Field::new("include", DataType::Boolean, false), + ])); + let source = RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int32Array::from_iter( + (0..257).map(|row| (row >= 28).then_some(row / 28)), + )), + Arc::new(StringArray::from_iter_values( + (0..257).map(|row| format!("key-{}", (row / 7) % 4)), + )), + Arc::new(Int64Array::from_iter_values(0..257)), + Arc::new(BooleanArray::from_iter( + (0..257).map(|row| Some(row % 3 != 0)), + )), + ], + )?; + let aggregate = Arc::new( + AggregateExprBuilder::new(sum_udaf(), vec![col("v", &schema)?]) + .schema(Arc::clone(&schema)) + .alias("sum_v") + .build()?, + ); + + for descending in [false, true] { + let source = if descending { + let reverse = UInt32Array::from_iter_values((0..257).rev()); + take_record_batch(&source, &reverse)? + } else { + source.clone() + }; + for input_batch_size in [1, 7, 31, 128] { + let batches = (0..257) + .step_by(input_batch_size) + .map(|offset| { + source.slice(offset, input_batch_size.min(257 - offset)) + }) + .collect::>(); + for two_stage in [false, true] { + let mut results = Vec::new(); + for sorted in [false, true] { + let input = TestMemoryExec::try_new_exec( + std::slice::from_ref(&batches), + Arc::clone(&schema), + None, + )?; + let input: Arc = if sorted { + let options = if descending { + SortOptions::default().desc().nulls_last() + } else { + SortOptions::default() + }; + let ordering = LexOrdering::new(vec![ + PhysicalSortExpr::new(col("a", &schema)?, options), + PhysicalSortExpr::new(col("b", &schema)?, options), + ]) + .unwrap(); + Arc::new( + input + .as_ref() + .clone() + .try_with_sort_information(vec![ordering])?, + ) + } else { + input + }; + let group_by = PhysicalGroupBy::new_single(vec![ + (col("a", &schema)?, "a".into()), + (col("b", &schema)?, "b".into()), + ]); + let plan = AggregateExec::try_new( + if two_stage { + AggregateMode::Partial + } else { + AggregateMode::Single + }, + group_by.clone(), + vec![Arc::clone(&aggregate)], + vec![Some(col("include", &schema)?)], + input, + Arc::clone(&schema), + )?; + if sorted { + assert_eq!(plan.input_order_mode(), &InputOrderMode::Sorted); + } + let plan: Arc = if two_stage { + let plan = AggregateExec::try_new( + AggregateMode::Final, + group_by, + vec![Arc::clone(&aggregate)], + vec![None], + Arc::new(plan), + Arc::clone(&schema), + )?; + if sorted { + assert_eq!( + plan.input_order_mode(), + &InputOrderMode::Sorted + ); + } + Arc::new(plan) + } else { + Arc::new(plan) + }; + let converter = RowConverter::new( + plan.schema() + .fields() + .iter() + .map(|field| SortField::new(field.data_type().clone())) + .collect(), + )?; + let output = + collect(plan, Arc::new(TaskContext::default())).await?; + let mut rows = Vec::new(); + for batch in output { + rows.extend( + converter + .convert_columns(batch.columns())? + .iter() + .map(|row| row.as_ref().to_vec()), + ); + } + rows.sort(); + results.push(rows); + } + assert_eq!( + results[0], results[1], + "batch_size={input_batch_size}, two_stage={two_stage}, descending={descending}" + ); + } + } + } + Ok(()) + } +} From cd5fdadb13db9275837dc21c0877cd0c6c00977e Mon Sep 17 00:00:00 2001 From: Geoffrey Claude Date: Wed, 21 Oct 2026 06:47:51 +0000 Subject: [PATCH 2/5] perf: extend fully ordered aggregation to more scalar types (#26370) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #26369. Follow-up to #25150. Fully ordered multi-column `GROUP BY` still hashes temporal, decimal, and fixed-size binary keys. These types can use the existing adjacent-run grouping path because Arrow's adjacent equality agrees with the grouping builders. In our production usecases, we are especially interested in #26369's optimization extending to `Timestamp`s (timeseries data) and `FixedSizeBinary(16)` (for UUIDs). - **Only production code change is 12 new types** added to the `match` under `supports_schema`: the rest are tests and benches. - Enable timestamps with all units and timezone metadata, dates, valid time units, durations, intervals, Decimal32/64/128/256, and every valid fixed-size binary width. - Preserve type metadata and the existing selection of single-column specializations. - Add a `fully_ordered` group to the existing SQL aggregation Criterion benchmark, with integer/string controls, timestamp run-length variants, and a timestamp `SUM(v)` case. The first two commits contain only benchmarks, followed by the type expansion and regression tests, including the UUID coverage. Differential tests compare ordered and hash grouping across nulls, units/timezones, decimal metadata, sliced batches, and group emission. Dedicated tests cover zero-width binary and 16-byte binary keys that share their first 15 bytes, including cross-batch continuation and keys that differ only in the last byte. SQL regression tests cover single-stage and partial/final aggregation, mixed sort directions, null ordering, and aggregate filters. The benchmarks check input types, row and group counts, and fully clustered aggregation without sorting or repartitioning in the measured query. The timestamp `SUM(v)` case also checks every group's sum before timing.
SQL benchmark results [Latest benchmark bot report](https://github.com/apache/datafusion/pull/26370#issuecomment-6266981812), comparing the benchmark-only baseline `dc6a10cf3c8` with `a398f8768ca`. Both refs contain the same 17 benchmark cases. The table shows rounded speedups from the report. The controls are roughly unchanged; the small differences may be benchmark noise. Values below 1× mean slower. | Second grouping key / query | Rows per group | Approx. speedup | | --- | ---: | ---: | | Int64 (control) | 31 | ~0.95× | | Utf8View (control) | 31 | ~0.99× | | Timestamp (ns) | 31 | ~7.0× | | Timestamp (µs, UTC) | 31 | ~6.9× | | Date32 | 31 | ~7.5× | | Time32 (ms) | 31 | ~7.5× | | Time64 (ns) | 31 | ~7.0× | | Duration (ns) | 31 | ~7.0× | | Interval (day/time) | 31 | ~6.4× | | Interval (month/day/ns) | 31 | ~5.3× | | Decimal128(30, 4) | 31 | ~6.1× | | Decimal256(60, 4) | 31 | ~5.2× | | FixedSizeBinary(16) | 31 | ~4.6× | | FixedSizeBinary(7) | 31 | ~4.4× | | Timestamp (ns), singleton groups | 1 | ~2.9× | | Timestamp (ns), long groups | 512 | ~7.7× | | Timestamp (ns), `SUM(v)` | 31 | ~4.0× | The 16 key-only cases use the same two-key deduplication query: ```sql SELECT k1, k2 FROM ordered_input GROUP BY k1, k2 ``` The additional timestamp case includes accumulator work: ```sql SELECT k1, k2, SUM(v) FROM ordered_input GROUP BY k1, k2 ``` Here `v` is the nonconstant source row number. The timestamp `SUM(v)` case improved from approximately 43.9 ms to 11.0 ms (~4.0×). - **Input:** about 2.1 million rows. `k1` is an Int32 prefix that advances every 32 groups; nullable `k2` cycles through 32 values, including one null, using the type listed above. Both keys vary. - **Group sizes:** normally 31 rows per key pair, so runs cross the 8,192-row batch boundaries. The additional timestamp cases use one or 512 rows per group to vary cardinality. - **Before timing:** generate the data, sort by both keys, and materialize it into one in-memory partition with its ordering declared to the planner. - **Measured work:** SQL planning, query execution, and collection of all results. The key-only cases focus on grouping the keys; the timestamp `SUM(v)` case also updates an accumulator. - **Setup checks:** verify input type, row count, and output group count; require fully clustered aggregation and fail if the measured plan adds sorting or repartitioning. The `SUM(v)` case verifies every group's result, including null timestamp keys and the final short group, before timing.
Already-sorted multi-column aggregations can use lower-overhead key storage for these types. Query results stay the same. Developed with AI assistance. (cherry picked from commit 6c1727fcd9230dda428f8c3a2397fce235544bd5) Environment: Datadog workspace Co-authored-by: Codex GPT-6.2 Astra --- .../core/benches/aggregate_query_sql.rs | 236 +++++++- .../group_values/multi_group_by/ordered.rs | 507 ++++++++++++++---- .../ordered_aggregate_key_types.slt | 172 ++++++ 3 files changed, 798 insertions(+), 117 deletions(-) create mode 100644 datafusion/sqllogictest/test_files/ordered_aggregate_key_types.slt diff --git a/datafusion/core/benches/aggregate_query_sql.rs b/datafusion/core/benches/aggregate_query_sql.rs index d7e24aceba170..2ea81cccc84e2 100644 --- a/datafusion/core/benches/aggregate_query_sql.rs +++ b/datafusion/core/benches/aggregate_query_sql.rs @@ -17,10 +17,17 @@ mod data_utils; +use arrow::array::{Array, AsArray}; +use arrow::datatypes::{ + DataType, Int32Type, Int64Type, IntervalUnit, TimeUnit, TimestampNanosecondType, +}; use criterion::{Criterion, criterion_group, criterion_main}; use data_utils::create_table_provider; +use datafusion::datasource::MemTable; use datafusion::error::Result; -use datafusion::execution::context::SessionContext; +use datafusion::execution::context::{SessionConfig, SessionContext}; +use datafusion::physical_plan::{collect, displayable}; +use datafusion_expr::col; use parking_lot::Mutex; use std::hint::black_box; use std::sync::Arc; @@ -330,5 +337,230 @@ fn criterion_benchmark(c: &mut Criterion) { }); } -criterion_group!(benches, criterion_benchmark); +/// Measure the multi-column fully ordered grouping path, with data generation +/// and sorting outside timing. Both keys vary, and the nullable second key +/// changes type while the shape of the input stays the same. +fn fully_ordered(c: &mut Criterion) { + use DataType::*; + use IntervalUnit::{DayTime, MonthDayNano}; + use TimeUnit::{Microsecond, Millisecond, Nanosecond}; + + let cases = [ + ("int64", "signed_key", Int64, 31), + ( + "utf8_view", + "arrow_cast(lpad(CAST(key_value AS VARCHAR), 4, '0'), 'Utf8View')", + Utf8View, + 31, + ), + ( + "timestamp_ns", + "arrow_cast(signed_key, 'Timestamp(Nanosecond)')", + Timestamp(Nanosecond, None), + 31, + ), + ( + "timestamp_us_utc", + "arrow_cast(signed_key, 'Timestamp(Microsecond, Some(\"UTC\"))')", + Timestamp(Microsecond, Some("UTC".into())), + 31, + ), + ( + "date32", + "arrow_cast(CAST(signed_key AS INTEGER), 'Date32')", + Date32, + 31, + ), + ( + "time32_ms", + "arrow_cast(CAST(key_value AS INTEGER), 'Time32(Millisecond)')", + Time32(Millisecond), + 31, + ), + ( + "time64_ns", + "arrow_cast(key_value, 'Time64(Nanosecond)')", + Time64(Nanosecond), + 31, + ), + ( + "duration_ns", + "arrow_cast(signed_key, 'Duration(Nanosecond)')", + Duration(Nanosecond), + 31, + ), + ( + "interval_day_time", + "arrow_cast(concat(CAST(signed_key AS VARCHAR), ' days'), 'Interval(DayTime)')", + Interval(DayTime), + 31, + ), + ( + "interval_month_day_nano", + "arrow_cast(arrow_cast(signed_key, 'Duration(Nanosecond)'), 'Interval(MonthDayNano)')", + Interval(MonthDayNano), + 31, + ), + ( + "decimal128", + "arrow_cast(concat('123456789012345678901', lpad(CAST(key_value AS VARCHAR), 4, '0'), '.1250'), 'Decimal128(30, 4)')", + Decimal128(30, 4), + 31, + ), + ( + "decimal256", + "arrow_cast(concat('123456789012345678901234567890123456789012345678901', lpad(CAST(key_value AS VARCHAR), 4, '0'), '.1250'), 'Decimal256(60, 4)')", + Decimal256(60, 4), + 31, + ), + ( + "fixed_binary16", + "arrow_cast(decode(lpad(to_hex(key_value), 32, '0'), 'hex'), 'FixedSizeBinary(16)')", + FixedSizeBinary(16), + 31, + ), + ( + "fixed_binary7", + "arrow_cast(decode(lpad(to_hex(key_value), 14, '0'), 'hex'), 'FixedSizeBinary(7)')", + FixedSizeBinary(7), + 31, + ), + ( + "timestamp_ns_singleton", + "arrow_cast(signed_key, 'Timestamp(Nanosecond)')", + Timestamp(Nanosecond, None), + 1, + ), + ( + "timestamp_ns_long_runs", + "arrow_cast(signed_key, 'Timestamp(Nanosecond)')", + Timestamp(Nanosecond, None), + 512, + ), + ]; + + let rt = Runtime::new().unwrap(); + let mut group = c.benchmark_group("fully_ordered"); + for (name, key_expr, key_type, run_length) in cases { + let ctx = rt + .block_on(fully_ordered_context( + key_expr, &key_type, run_length, false, + )) + .unwrap(); + group.bench_function(name, |b| { + b.iter(|| query(ctx.clone(), &rt, FULLY_ORDERED_QUERY)) + }); + } + // Add accumulator work for one representative timestamp case without + // multiplying every key type and run length by the aggregate expression. + let ctx = rt + .block_on(fully_ordered_context( + "arrow_cast(signed_key, 'Timestamp(Nanosecond)')", + &Timestamp(Nanosecond, None), + 31, + true, + )) + .unwrap(); + group.bench_function("timestamp_ns_sum", |b| { + b.iter(|| query(ctx.clone(), &rt, FULLY_ORDERED_SUM_QUERY)) + }); + group.finish(); +} + +const FULLY_ORDERED_QUERY: &str = "SELECT k1, k2 FROM ordered_input GROUP BY k1, k2"; +const FULLY_ORDERED_SUM_QUERY: &str = + "SELECT k1, k2, SUM(v) FROM ordered_input GROUP BY k1, k2"; + +async fn fully_ordered_context( + key_expr: &str, + key_type: &DataType, + run_length: usize, + with_sum: bool, +) -> Result>> { + const ROWS: usize = 2_097_152; + // Use source row numbers as nonconstant values for the aggregate case. + let (value_projection, input_value, sql) = if with_sum { + (", v", ", value AS v", FULLY_ORDERED_SUM_QUERY) + } else { + ("", "", FULLY_ORDERED_QUERY) + }; + let config = SessionConfig::new() + .with_target_partitions(1) + .with_batch_size(8192) + .with_prefer_existing_sort(true); + let ctx = SessionContext::new_with_config(config); + // Runs of 31 cross batch boundaries; singleton and long-run cases vary + // cardinality without multiplying every type by every input shape. + let input = ctx + .sql(&format!( + "SELECT CAST(group_id / 32 AS INTEGER) AS k1, \ + CASE WHEN key_value = 0 THEN NULL ELSE {key_expr} END AS k2{value_projection} \ + FROM (SELECT value / {run_length} AS group_id, \ + value / {run_length} % 32 AS key_value, \ + value / {run_length} % 32 - 16 AS signed_key{input_value} \ + FROM range({ROWS})) \ + ORDER BY k1 ASC NULLS FIRST, k2 ASC NULLS FIRST" + )) + .await? + .create_physical_plan() + .await?; + let schema = input.schema(); + assert_eq!(schema.field(1).data_type(), key_type); + let batches = collect(input, ctx.task_ctx()).await?; + assert_eq!( + batches.iter().map(|batch| batch.num_rows()).sum::(), + ROWS + ); + // The setup query sorts both keys before materialization. Retain that + // known ordering explicitly when registering its results as a table. + let table = MemTable::try_new(schema, vec![batches])?.with_sort_order(vec![vec![ + col("k1").sort(true, true), + col("k2").sort(true, true), + ]]); + ctx.register_table("ordered_input", Arc::new(table))?; + + let plan = ctx.sql(sql).await?.create_physical_plan().await?; + let description = displayable(plan.as_ref()).indent(true).to_string(); + assert!( + description.contains("group_clustering_mode=Full"), + "{description}" + ); + // Input is already sorted in one partition. Fail if the planner adds + // sorting or repartitioning to the measured query. + assert!(!description.contains("SortExec"), "{description}"); + assert!(!description.contains("RepartitionExec"), "{description}"); + let result = collect(plan, ctx.task_ctx()).await?; + assert_eq!( + result.iter().map(|batch| batch.num_rows()).sum::(), + ROWS.div_ceil(run_length) + ); + if with_sum { + let rows = i64::try_from(ROWS).unwrap(); + let run_length = i64::try_from(run_length).unwrap(); + for batch in &result { + let k1 = batch.column(0).as_primitive::(); + let k2 = batch.column(1).as_primitive::(); + let sums = batch.column(2).as_primitive::(); + assert_eq!(sums.null_count(), 0); + for row in 0..batch.num_rows() { + // Each input group covers a contiguous range of source row + // numbers. Recover it from the keys, independently of output + // order, and check the arithmetic-series sum, including the + // final short group and groups with a NULL timestamp key. + let key_offset = if k2.is_null(row) { + 0 + } else { + k2.value(row) + 16 + }; + let group_id = i64::from(k1.value(row)) * 32 + key_offset; + let start = group_id * run_length; + let end = (start + run_length).min(rows); + assert_eq!(sums.value(row), (start + end - 1) * (end - start) / 2); + } + } + } + Ok(Arc::new(Mutex::new(ctx))) +} + +criterion_group!(benches, criterion_benchmark, fully_ordered); criterion_main!(benches); diff --git a/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/ordered.rs b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/ordered.rs index 9e34ac7aeac17..d331c510163cc 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/ordered.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/ordered.rs @@ -18,7 +18,7 @@ use std::mem; use arrow::array::ArrayRef; -use arrow::datatypes::{DataType, Schema, SchemaRef}; +use arrow::datatypes::{DataType, Schema, SchemaRef, TimeUnit}; use arrow_ord::partition::partition; use datafusion_common::{Result, not_impl_err}; use datafusion_execution::memory_pool::proxy::VecAllocExt; @@ -27,7 +27,7 @@ use datafusion_expr::{EmitTo, GroupSelection}; use super::{GroupColumn, GroupValuesColumn}; use crate::aggregates::group_values::GroupValues; -/// Columnar group keys for input fully ordered by all grouping expressions. +/// Columnar group keys for input clustered by the complete grouping tuple. /// /// Equal keys must be contiguous across input batches. Within a batch Arrow's /// partition kernel finds those runs. Only the first run can continue the last @@ -36,14 +36,15 @@ use crate::aggregates::group_values::GroupValues; /// /// This removes hashing and hash-table storage, but does not change the dense /// group-id or emission contracts. In particular, `First(n)` shifts the remaining -/// keys and their ids together. Partially ordered inputs must use a hash table. -pub(crate) struct GroupValuesOrdered { +/// keys and their ids together. Inputs clustered by only a subset of the keys +/// must use a hash table. +pub(crate) struct GroupValuesClustered { schema: SchemaRef, columns: Vec>, new_groups: Vec, } -impl GroupValuesOrdered { +impl GroupValuesClustered { /// Types for which adjacent Arrow equality agrees with GROUP BY equality. /// Keep single-column specializations and floats/nested/encoded keys on the /// established path until their semantics and performance are validated. @@ -61,12 +62,24 @@ impl GroupValuesOrdered { | DataType::UInt16 | DataType::UInt32 | DataType::UInt64 + | DataType::Timestamp(_, _) + | DataType::Date32 + | DataType::Date64 + | DataType::Time32(TimeUnit::Second | TimeUnit::Millisecond) + | DataType::Time64(TimeUnit::Microsecond | TimeUnit::Nanosecond) + | DataType::Duration(_) + | DataType::Interval(_) + | DataType::Decimal32(_, _) + | DataType::Decimal64(_, _) + | DataType::Decimal128(_, _) + | DataType::Decimal256(_, _) | DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View | DataType::Binary | DataType::LargeBinary | DataType::BinaryView + | DataType::FixedSizeBinary(0..) ) }) } @@ -74,7 +87,7 @@ impl GroupValuesOrdered { pub(crate) fn try_new(schema: SchemaRef) -> Result { if !Self::supports_schema(&schema) { return not_impl_err!( - "Unsupported schema for fully ordered group values: {schema}" + "Unsupported schema for fully clustered group values: {schema}" ); } let columns = GroupValuesColumn::::build_group_columns(&schema)?; @@ -86,7 +99,7 @@ impl GroupValuesOrdered { } } -impl GroupValues for GroupValuesOrdered { +impl GroupValues for GroupValuesClustered { fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec) -> Result<()> { groups.clear(); let ranges = partition(cols)?.ranges(); @@ -170,7 +183,7 @@ impl GroupValues for GroupValuesOrdered { fn clear_shrink(&mut self, num_rows: usize) { self.columns = GroupValuesColumn::::build_group_columns(&self.schema) - .expect("schema validated by GroupValuesOrdered::try_new"); + .expect("schema validated by GroupValuesClustered::try_new"); self.new_groups.clear(); self.new_groups.shrink_to(num_rows); } @@ -181,19 +194,167 @@ mod tests { use std::sync::Arc; use arrow::array::UInt32Array; - use arrow::array::{Array, BooleanArray, Int32Array, Int64Array, StringArray}; + use arrow::array::{ + Array, AsArray, BooleanArray, Decimal32Array, Decimal64Array, Decimal128Array, + Decimal256Array, FixedSizeBinaryArray, Int32Array, Int64Array, + IntervalDayTimeArray, IntervalMonthDayNanoArray, IntervalYearMonthArray, + StringArray, + }; + use arrow::buffer::{Buffer, NullBuffer}; use arrow::compute::{cast, take}; - use arrow::datatypes::Field; + use arrow::datatypes::{ + Field, IntervalDayTime, IntervalMonthDayNano, IntervalUnit, i256, + }; use datafusion_expr::GroupSelection; use super::*; + // The values repeat in seven-row runs, with four keys per value of the + // first column. Construct logical types directly where casting would + // rescale decimals or cannot represent all interval components. + fn clustered_key_array( + key_type: &DataType, + rows: usize, + nullable: bool, + ) -> Result { + let keys = (0..rows) + .map(|row| { + let key = ((row / 7) % 4) as i32; + (!nullable || key != 0).then_some(key) + }) + .collect::>(); + Ok(match key_type { + DataType::Boolean => Arc::new(BooleanArray::from_iter( + keys.iter().map(|key| key.map(|key| key >= 2)), + )), + DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Utf8View + | DataType::Binary + | DataType::LargeBinary + | DataType::BinaryView => { + let strings = StringArray::from_iter(keys.iter().map(|key| { + key.map(|key| { + format!( + "key-{key}-{}", + "x".repeat(if key == 3 { 128 } else { 0 }) + ) + }) + })); + cast(&strings, key_type)? + } + DataType::Decimal32(precision, scale) => Arc::new( + Decimal32Array::from_iter(keys.iter().map(|key| key.map(|key| key - 2))) + .with_precision_and_scale(*precision, *scale)?, + ), + DataType::Decimal64(precision, scale) => Arc::new( + Decimal64Array::from_iter( + keys.iter().map(|key| key.map(|key| i64::from(key - 2))), + ) + .with_precision_and_scale(*precision, *scale)?, + ), + DataType::Decimal128(precision, scale) => { + // Equal low 64 bits must not hide differences in the high bits. + let values = [ + -(1_i128 << 100), + 0, + 1_i128 << 100, + (1_i128 << 100) + (1_i128 << 64), + ]; + let array = Decimal128Array::from_iter( + keys.iter().map(|key| key.map(|key| values[key as usize])), + ); + array.validate_decimal_precision(*precision)?; + Arc::new(array.with_precision_and_scale(*precision, *scale)?) + } + DataType::Decimal256(precision, scale) => { + // These values share their low 128 bits but exceed i128's range. + let values = [ + i256::from_parts(0, -(1_i128 << 100)), + i256::from_i128(0), + i256::from_parts(0, 1_i128 << 100), + i256::from_parts(0, (1_i128 << 100) + 1), + ]; + let array = Decimal256Array::from_iter( + keys.iter().map(|key| key.map(|key| values[key as usize])), + ); + array.validate_decimal_precision(*precision)?; + Arc::new(array.with_precision_and_scale(*precision, *scale)?) + } + DataType::Interval(IntervalUnit::YearMonth) => { + let values = [-13, 0, 1, 13]; + Arc::new(IntervalYearMonthArray::from_iter( + keys.iter().map(|key| key.map(|key| values[key as usize])), + )) + } + DataType::Interval(IntervalUnit::DayTime) => { + let values = [ + IntervalDayTime::new(-1, 0), + IntervalDayTime::new(0, 0), + IntervalDayTime::new(0, 1), + IntervalDayTime::new(1, 1), + ]; + Arc::new(IntervalDayTimeArray::from_iter( + keys.iter().map(|key| key.map(|key| values[key as usize])), + )) + } + DataType::Interval(IntervalUnit::MonthDayNano) => { + let values = [ + IntervalMonthDayNano::new(0, 0, 0), + IntervalMonthDayNano::new(0, 0, 1), + IntervalMonthDayNano::new(0, 1, 1), + IntervalMonthDayNano::new(1, 1, 1), + ]; + Arc::new(IntervalMonthDayNanoArray::from_iter( + keys.iter().map(|key| key.map(|key| values[key as usize])), + )) + } + DataType::FixedSizeBinary(width) => { + let bytes = keys + .iter() + .flat_map(|key| { + std::iter::repeat_n( + key.unwrap_or_default() as u8, + *width as usize, + ) + }) + .collect::>(); + let nulls = nullable.then(|| { + NullBuffer::from(keys.iter().map(Option::is_some).collect::>()) + }); + Arc::new(FixedSizeBinaryArray::try_new_with_len( + *width, + Buffer::from(bytes), + nulls, + rows, + )?) + } + DataType::Date64 => { + let values = Int64Array::from_iter( + keys.iter() + .map(|key| key.map(|key| i64::from(key) * 86_400_000)), + ); + cast(&values, key_type)? + } + DataType::Timestamp(_, _) | DataType::Time64(_) | DataType::Duration(_) => { + let values = + Int64Array::from_iter(keys.iter().map(|key| key.map(i64::from))); + cast(&values, key_type)? + } + _ => cast(&Int32Array::from(keys), key_type)?, + }) + } + // Compare with the existing hash implementation, changing actual input // boundaries and removing completed groups between batches. This checks the // semantic contract rather than duplicating the adjacent-run algorithm. - #[test] - fn ordered_keys_match_hash_grouping_across_batches_and_emits() -> Result<()> { - for key_type in [ + #[rstest::rstest] + #[case::sorted(false)] + #[case::unsorted(true)] + fn clustered_keys_match_hash_grouping_across_batches_and_emits( + #[case] unsorted: bool, + ) -> Result<()> { + let mut key_types = vec![ DataType::Boolean, DataType::Int8, DataType::Int16, @@ -209,106 +370,135 @@ mod tests { DataType::Binary, DataType::LargeBinary, DataType::BinaryView, + DataType::Date32, + DataType::Date64, + DataType::Time32(TimeUnit::Second), + DataType::Time32(TimeUnit::Millisecond), + DataType::Time64(TimeUnit::Microsecond), + DataType::Time64(TimeUnit::Nanosecond), + DataType::Interval(IntervalUnit::YearMonth), + DataType::Interval(IntervalUnit::DayTime), + DataType::Interval(IntervalUnit::MonthDayNano), + DataType::Decimal32(9, 2), + DataType::Decimal32(9, -2), + DataType::Decimal64(18, 2), + DataType::Decimal64(18, -2), + DataType::Decimal128(38, 2), + DataType::Decimal128(38, -2), + DataType::Decimal256(76, 2), + DataType::Decimal256(76, -2), + DataType::FixedSizeBinary(3), + DataType::FixedSizeBinary(16), + ]; + for unit in [ + TimeUnit::Second, + TimeUnit::Millisecond, + TimeUnit::Microsecond, + TimeUnit::Nanosecond, ] { - let rows = 1025; - let first: ArrayRef = Arc::new(Int32Array::from_iter((0..rows).map(|row| { - let group = row / 7; - (group >= 4).then_some(group / 4) - }))); - let second: ArrayRef = match key_type { - DataType::Boolean => { - Arc::new(BooleanArray::from_iter((0..rows).map(|row| { - let key = (row / 7) % 4; - (key != 0).then_some(key >= 2) - }))) - } - DataType::Utf8 - | DataType::LargeUtf8 - | DataType::Utf8View - | DataType::Binary - | DataType::LargeBinary - | DataType::BinaryView => { - let strings = StringArray::from_iter((0..rows).map(|row| { - let key = (row / 7) % 4; - (key != 0).then(|| { - format!( - "key-{key}-{}", - "x".repeat(if key == 3 { 128 } else { 0 }) - ) + key_types.push(DataType::Duration(unit)); + for timezone in [None, Some("UTC"), Some("Europe/Paris"), Some("+05:30")] { + key_types.push(DataType::Timestamp(unit, timezone.map(Into::into))); + } + } + for key_type in key_types { + for nullable in [false, true] { + let rows = 1025; + let first: ArrayRef = + Arc::new(Int32Array::from_iter((0..rows).map(|row| { + let group = (row / 7) as i32; + let key = group / 4; + // Swap neighboring key values while keeping each run contiguous. + (!nullable || group >= 4).then_some(if unsorted { + key ^ 1 + } else { + key }) - })); - cast(&strings, &key_type)? - } - _ => { - let values = Int32Array::from_iter((0..rows).map(|row| { - let key = (row / 7) % 4; - (key != 0).then_some(key) - })); - cast(&values, &key_type)? - } - }; - for descending in [false, true] { - let mut input = vec![Arc::clone(&first), Arc::clone(&second)]; - if descending { - let reverse = UInt32Array::from_iter_values((0..rows as u32).rev()); - input = input - .iter() - .map(|array| take(array, &reverse, None)) - .collect::>()?; - } - let schema = Arc::new(Schema::new(vec![ - Field::new("a", DataType::Int32, true), - Field::new("b", key_type.clone(), true), - ])); - for batch_size in [1, 2, 7, 8, 63, 1024] { - for emit_limit in [0, 1, 17, usize::MAX] { - let mut ordered = - GroupValuesOrdered::try_new(Arc::clone(&schema))?; - let mut hashed = - GroupValuesColumn::::try_new(Arc::clone(&schema))?; - let mut actual = Vec::new(); - let mut expected = Vec::new(); - for offset in (0..rows as usize).step_by(batch_size) { - let length = batch_size.min(rows as usize - offset); - let batch = input - .iter() - .map(|array| array.slice(offset, length)) - .collect::>(); - ordered.intern(&batch, &mut actual)?; - hashed.intern(&batch, &mut expected)?; - assert_eq!( - actual, expected, - "{key_type:?}, batch={batch_size}, offset={offset}, descending={descending}" - ); - assert_eq!(ordered.len(), hashed.len()); - let selection = GroupSelection::all(ordered.len()); + }))); + let second = clustered_key_array(&key_type, rows, nullable)?; + for descending in [false, true] { + let mut input = vec![Arc::clone(&first), Arc::clone(&second)]; + if descending { + let reverse = + UInt32Array::from_iter_values((0..rows as u32).rev()); + input = input + .iter() + .map(|array| take(array, &reverse, None)) + .collect::>()?; + } + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, nullable), + Field::new("b", key_type.clone(), nullable), + ])); + assert!(GroupValuesClustered::supports_schema(&schema), "{key_type}"); + for batch_size in [1, 2, 7, 8, 63, 1024] { + for emit_limit in [0, 1, 17, usize::MAX] { + let mut clustered = + GroupValuesClustered::try_new(Arc::clone(&schema))?; + let mut hashed = + GroupValuesColumn::::try_new(Arc::clone(&schema))?; + let mut actual = Vec::new(); + let mut expected = Vec::new(); + for offset in (0..rows).step_by(batch_size) { + let length = batch_size.min(rows - offset); + let batch = input + .iter() + .map(|array| array.slice(offset, length)) + .collect::>(); + clustered.intern(&batch, &mut actual)?; + hashed.intern(&batch, &mut expected)?; + assert_eq!( + actual, expected, + "{key_type:?}, nullable={nullable}, unsorted={unsorted}, batch={batch_size}, offset={offset}, descending={descending}" + ); + assert_eq!(clustered.len(), hashed.len()); + let selection = GroupSelection::all(clustered.len()); + let values = clustered.values_preserving(selection)?; + assert_eq!(values, hashed.values_preserving(selection)?); + assert_eq!(values[1].data_type(), &key_type); + // A zero-row batch must neither forget the boundary + // key nor leave stale group ids in the output buffer. + let empty = batch + .iter() + .map(|array| array.slice(0, 0)) + .collect::>(); + clustered.intern(&empty, &mut actual)?; + assert!(actual.is_empty()); + let emit = + emit_limit.min(clustered.len().saturating_sub(1)); + let values = clustered.emit(EmitTo::First(emit))?; + assert_eq!(values, hashed.emit(EmitTo::First(emit))?); + assert_eq!(values[1].data_type(), &key_type); + } + let indices = [clustered.len() - 1, 0, clustered.len() - 1]; + let selection = GroupSelection::try_from_indices( + &indices, + clustered.len(), + )?; assert_eq!( - ordered.values_preserving(selection)?, + clustered.values_preserving(selection)?, hashed.values_preserving(selection)? ); - // A zero-row batch must neither forget the boundary - // key nor leave stale group ids in the output buffer. - let empty = batch - .iter() - .map(|array| array.slice(0, 0)) - .collect::>(); - ordered.intern(&empty, &mut actual)?; - assert!(actual.is_empty()); - let emit = emit_limit.min(ordered.len().saturating_sub(1)); - assert_eq!( - ordered.emit(EmitTo::First(emit))?, - hashed.emit(EmitTo::First(emit))? - ); + let values = clustered.emit(EmitTo::All)?; + assert_eq!(values, hashed.emit(EmitTo::All)?); + assert_eq!(values[1].data_type(), &key_type); + assert!(clustered.is_empty()); + // All resets the clustered boundary state. The hash reference + // also needs its lookup table cleared after draining keys. + hashed.clear_shrink(0); + clustered.intern(&input, &mut actual)?; + hashed.intern(&input, &mut expected)?; + assert_eq!(actual, expected); + // Clearing populated storage must reset it as well. + clustered.clear_shrink(0); + hashed.clear_shrink(0); + clustered.intern(&input, &mut actual)?; + hashed.intern(&input, &mut expected)?; + assert_eq!(actual, expected); + let values = clustered.emit(EmitTo::All)?; + assert_eq!(values, hashed.emit(EmitTo::All)?); + assert_eq!(values[1].data_type(), &key_type); } - assert_eq!(ordered.emit(EmitTo::All)?, hashed.emit(EmitTo::All)?); - assert!(ordered.is_empty()); - // All and clear_shrink reset the cross-batch state. - ordered.clear_shrink(0); - hashed.clear_shrink(0); - ordered.intern(&input, &mut actual)?; - hashed.intern(&input, &mut expected)?; - assert_eq!(actual, expected); - assert_eq!(ordered.emit(EmitTo::All)?, hashed.emit(EmitTo::All)?); } } } @@ -317,11 +507,92 @@ mod tests { } #[test] - fn ordered_schema_gate_keeps_unvalidated_types_on_existing_paths() { + fn fixed_size_binary_16_common_prefix() -> Result<()> { + let first = [0xa5_u8; 16]; + let mut second = first; + second[15] = 0xa6; + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, false), + Field::new("b", DataType::FixedSizeBinary(16), false), + ])); + let mut clustered = GroupValuesClustered::try_new(Arc::clone(&schema))?; + let mut hashed = GroupValuesColumn::::try_new(schema)?; + let mut actual = Vec::new(); + let mut expected = Vec::new(); + // Continue the first group, then distinguish a key only by its last byte. + for (key, group_id) in [(first, 0), (first, 0), (second, 1)] { + let batch: [ArrayRef; 2] = [ + Arc::new(Int32Array::from(vec![7])), + Arc::new(FixedSizeBinaryArray::try_from_iter([key].into_iter())?), + ]; + clustered.intern(&batch, &mut actual)?; + hashed.intern(&batch, &mut expected)?; + assert_eq!(actual, [group_id]); + assert_eq!(actual, expected); + } + let values = clustered.emit(EmitTo::All)?; + assert_eq!(values, hashed.emit(EmitTo::All)?); + assert_eq!( + values[1].as_fixed_size_binary().value_data(), + [first, second].concat() + ); + Ok(()) + } + + #[test] + fn zero_width_binary_preserves_emitted_lengths_and_nulls() -> Result<()> { + for nullable in [false, true] { + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, false), + Field::new("b", DataType::FixedSizeBinary(0), nullable), + ])); + let first: ArrayRef = Arc::new(Int32Array::from(vec![7; 6])); + let second: ArrayRef = Arc::new(FixedSizeBinaryArray::try_new_with_len( + 0, + Buffer::default(), + nullable.then(|| { + NullBuffer::from(vec![true, false, false, true, true, true]) + }), + 6, + )?); + let input = [first.slice(1, 4), second.slice(1, 4)]; + let mut clustered = GroupValuesClustered::try_new(schema)?; + let mut groups = Vec::new(); + for offset in [0, 2] { + let batch = input + .iter() + .map(|array| array.slice(offset, 2)) + .collect::>(); + clustered.intern(&batch, &mut groups)?; + assert_eq!(groups, vec![usize::from(nullable && offset == 2); 2]); + } + let values = + clustered.values_preserving(GroupSelection::all(clustered.len()))?; + assert_eq!(values[1].len(), if nullable { 2 } else { 1 }); + assert_eq!(values[1].null_count(), usize::from(nullable)); + let values = clustered.emit(EmitTo::First(1))?; + assert_eq!(values[1].len(), 1); + assert_eq!(values[1].null_count(), usize::from(nullable)); + let values = clustered.emit(EmitTo::All)?; + assert_eq!(values[1].len(), usize::from(nullable)); + assert_eq!(values[1].null_count(), 0); + assert_eq!(values[1].data_type(), &DataType::FixedSizeBinary(0)); + } + Ok(()) + } + + #[test] + fn clustered_schema_gate_keeps_unvalidated_types_on_existing_paths() { for data_type in [ + DataType::Float16, DataType::Float32, DataType::Float64, DataType::Null, + DataType::Time32(TimeUnit::Microsecond), + DataType::Time32(TimeUnit::Nanosecond), + DataType::Time64(TimeUnit::Second), + DataType::Time64(TimeUnit::Millisecond), + DataType::FixedSizeBinary(-1), DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)), DataType::List(Arc::new(Field::new("item", DataType::Int32, true))), ] { @@ -329,18 +600,21 @@ mod tests { Field::new("a", DataType::Int32, false), Field::new("b", data_type, true), ]); - assert!(!GroupValuesOrdered::supports_schema(&schema)); + assert!(!GroupValuesClustered::supports_schema(&schema)); + assert!(GroupValuesClustered::try_new(Arc::new(schema)).is_err()); } - assert!(!GroupValuesOrdered::supports_schema(&Schema::new(vec![ + assert!(!GroupValuesClustered::supports_schema(&Schema::new(vec![ Field::new("a", DataType::Int32, false) ]))); } #[tokio::test] async fn ordered_single_and_partial_final_match_unordered_execution() -> Result<()> { - use crate::aggregates::{AggregateExec, AggregateMode, PhysicalGroupBy}; + use crate::aggregates::{ + AggregateExec, AggregateMode, GroupClusteringMode, PhysicalGroupBy, + }; use crate::test::TestMemoryExec; - use crate::{ExecutionPlan, InputOrderMode, collect}; + use crate::{ExecutionPlan, collect}; use arrow::compute::{SortOptions, take_record_batch}; use arrow::record_batch::RecordBatch; use arrow::row::{RowConverter, SortField}; @@ -437,7 +711,10 @@ mod tests { Arc::clone(&schema), )?; if sorted { - assert_eq!(plan.input_order_mode(), &InputOrderMode::Sorted); + assert_eq!( + plan.group_clustering_mode(), + &GroupClusteringMode::Full + ); } let plan: Arc = if two_stage { let plan = AggregateExec::try_new( @@ -450,8 +727,8 @@ mod tests { )?; if sorted { assert_eq!( - plan.input_order_mode(), - &InputOrderMode::Sorted + plan.group_clustering_mode(), + &GroupClusteringMode::Full ); } Arc::new(plan) diff --git a/datafusion/sqllogictest/test_files/ordered_aggregate_key_types.slt b/datafusion/sqllogictest/test_files/ordered_aggregate_key_types.slt new file mode 100644 index 0000000000000..cd47847420417 --- /dev/null +++ b/datafusion/sqllogictest/test_files/ordered_aggregate_key_types.slt @@ -0,0 +1,172 @@ +# 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. + +# Fully ordered multi-column aggregation agrees with unordered aggregation for +# parameterized key types. Two-row batches split both null and non-null groups. +statement ok +SET datafusion.execution.batch_size = 2; + +statement ok +SET datafusion.execution.target_partitions = 1; + +statement ok +SET datafusion.execution.enable_migration_aggregate = true; + +statement ok +SET datafusion.optimizer.enable_round_robin_repartition = false; + +statement ok +SET datafusion.optimizer.prefer_existing_sort = true; + +statement ok +SET datafusion.explain.physical_plan_only = true; + +statement ok +CREATE TABLE ordered_key_types AS +SELECT + arrow_cast(t, 'Timestamp(Nanosecond, Some("Europe/Paris"))') AS ts_ns, + arrow_cast(t, 'Timestamp(Millisecond)') AS ts_ms, + arrow_cast(n, 'Decimal32(9, 2)') AS d32, + arrow_cast(n, 'Decimal64(18, 4)') AS d64, + arrow_cast(n, 'Decimal128(20, 3)') AS d128, + arrow_cast(n, 'Decimal256(50, 7)') AS d256, + arrow_cast(b, 'FixedSizeBinary(5)') AS b, + arrow_cast(CAST(t AS INT), 'Date32') AS date32, + arrow_cast(t * 86400000, 'Date64') AS date64, + arrow_cast(CAST(t AS INT), 'Time32(Millisecond)') AS time32, + arrow_cast(t, 'Time64(Microsecond)') AS time64, + arrow_cast(t, 'Duration(Nanosecond)') AS duration, + arrow_cast(CAST(t AS VARCHAR) || ' months', 'Interval(YearMonth)') AS iym, + arrow_cast(CAST(t AS VARCHAR) || ' days', 'Interval(DayTime)') AS idt, + arrow_cast(CAST(t AS VARCHAR) || ' nanoseconds', 'Interval(MonthDayNano)') AS imdn, + v +FROM (VALUES + (0, -1.25, X'00000000ff', 10), + (0, -1.25, X'00000000ff', 0), + (0, -1.25, X'00000000ff', 20), + (0, -1.25, X'00000000ff', NULL), + (0, -1.25, X'0000000001', 4), + (1, NULL, NULL, 0), + (1, NULL, NULL, 8), + (NULL, 2.5, X'ff00000000', 12), + (NULL, 2.5, X'ff00000000', 4), + (NULL, NULL, NULL, 0) +) AS input(t, n, b, v); + +# LIMIT preserves the subquery's ordering. It exceeds the fixture's row count. +# Mixed directions and explicit null ordering must not change group equality. +statement ok +CREATE VIEW ordered_key_types_sorted AS +SELECT * FROM ordered_key_types +ORDER BY ts_ns DESC NULLS FIRST, ts_ms, d32 DESC NULLS LAST, + d64, d128, d256, b DESC NULLS FIRST, date32, date64, + time32, time64, duration, iym, idt, imdn +LIMIT 1000; + +query TT +EXPLAIN SELECT ts_ns, ts_ms, d32, d64, d128, d256, b, + date32, date64, time32, time64, duration, iym, idt, imdn, SUM(v) +FROM ordered_key_types_sorted +GROUP BY ts_ns, ts_ms, d32, d64, d128, d256, b, + date32, date64, time32, time64, duration, iym, idt, imdn; +---- +physical_plan +01)AggregateExec: mode=Single,group_clustering_mode=Full + + +# Unordered reference. FILTER must also prevent division by zero. +query IR?IIII rowsort ordered-key-types +SELECT CAST(ts_ns AS BIGINT), d128, b, MIN(v), SUM(10 / v) FILTER (WHERE v <> 0), + COUNT(v) FILTER (WHERE v <> 0), COUNT(*) +FROM ordered_key_types +GROUP BY ts_ns, ts_ms, d32, d64, d128, d256, b, + date32, date64, time32, time64, duration, iym, idt, imdn; +---- +0 -1.250 0000000001 4 2 1 1 +0 -1.250 00000000ff 0 1 2 4 +1 NULL NULL 0 1 1 2 +NULL 2.500 ff00000000 4 2 2 2 +NULL NULL NULL 0 NULL 0 1 + +# The same keys and aggregates through fully ordered Single aggregation. +query IR?IIII rowsort ordered-key-types +SELECT CAST(ts_ns AS BIGINT), d128, b, MIN(v), SUM(10 / v) FILTER (WHERE v <> 0), + COUNT(v) FILTER (WHERE v <> 0), COUNT(*) +FROM ordered_key_types_sorted +GROUP BY ts_ns, ts_ms, d32, d64, d128, d256, b, + date32, date64, time32, time64, duration, iym, idt, imdn; +---- +0 -1.250 0000000001 4 2 1 1 +0 -1.250 00000000ff 0 1 2 4 +1 NULL NULL 0 1 1 2 +NULL 2.500 ff00000000 4 2 2 2 +NULL NULL NULL 0 NULL 0 1 + +statement ok +SET datafusion.execution.target_partitions = 2; + +# Partial and final stages must both retain complete group-key ordering. +query TT +EXPLAIN SELECT ts_ns, ts_ms, d32, d64, d128, d256, b, + date32, date64, time32, time64, duration, iym, idt, imdn, SUM(v) +FROM ordered_key_types_sorted +GROUP BY ts_ns, ts_ms, d32, d64, d128, d256, b, + date32, date64, time32, time64, duration, iym, idt, imdn; +---- +physical_plan +01)AggregateExec: mode=FinalPartitioned,group_clustering_mode=Full +02)--RepartitionExec:maintains_sort_order=true +03)----AggregateExec: mode=Partial,group_clustering_mode=Full + + +query IR?IIII rowsort ordered-key-types +SELECT CAST(ts_ns AS BIGINT), d128, b, MIN(v), SUM(10 / v) FILTER (WHERE v <> 0), + COUNT(v) FILTER (WHERE v <> 0), COUNT(*) +FROM ordered_key_types_sorted +GROUP BY ts_ns, ts_ms, d32, d64, d128, d256, b, + date32, date64, time32, time64, duration, iym, idt, imdn; +---- +0 -1.250 0000000001 4 2 1 1 +0 -1.250 00000000ff 0 1 2 4 +1 NULL NULL 0 1 1 2 +NULL 2.500 ff00000000 4 2 2 2 +NULL NULL NULL 0 NULL 0 1 + +statement ok +DROP VIEW ordered_key_types_sorted; + +statement ok +DROP TABLE ordered_key_types; + +# Restore the sqllogictest runner's settings. +statement ok +RESET datafusion.execution.batch_size; + +statement ok +SET datafusion.execution.target_partitions = 4; + +statement ok +RESET datafusion.execution.enable_migration_aggregate; + +statement ok +RESET datafusion.optimizer.enable_round_robin_repartition; + +statement ok +RESET datafusion.optimizer.prefer_existing_sort; + +statement ok +RESET datafusion.explain.physical_plan_only; From 3764d0ad28dcb36ca60c8d295be4bfc4f0062542 Mon Sep 17 00:00:00 2001 From: "xavier.lee" Date: Thu, 26 Nov 2026 22:08:38 +0000 Subject: [PATCH 3/5] fix(aggregate): adapt clustered group values to the DF55 interfaces Use the fork's full-clustering guarantee for the adjacent-key path. DF55 exposes destructive emission and has column builders for the wide decimal types. Keep narrow decimals on their existing fallback and exercise the supported emit, reset and cross-batch contracts. Environment: Datadog workspace Co-Authored-By: Codex GPT-6.2 Astra --- .../benches/ordered_group_values.rs | 16 ++--- .../src/aggregates/group_values/mod.rs | 10 +-- .../{ordered.rs => clustered.rs} | 62 +++---------------- .../group_values/multi_group_by/mod.rs | 4 +- 4 files changed, 24 insertions(+), 68 deletions(-) rename datafusion/physical-plan/src/aggregates/group_values/multi_group_by/{ordered.rs => clustered.rs} (92%) diff --git a/datafusion/physical-plan/benches/ordered_group_values.rs b/datafusion/physical-plan/benches/ordered_group_values.rs index ae0e44a859d5e..c2aa27c72aa95 100644 --- a/datafusion/physical-plan/benches/ordered_group_values.rs +++ b/datafusion/physical-plan/benches/ordered_group_values.rs @@ -37,12 +37,12 @@ use datafusion_physical_expr::expressions::col; use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr}; use datafusion_physical_plan::aggregates::group_values::multi_group_by::GroupValuesColumn; use datafusion_physical_plan::aggregates::group_values::{GroupValues, new_group_values}; -use datafusion_physical_plan::aggregates::order::GroupOrdering; +use datafusion_physical_plan::aggregates::order::GroupClustering; use datafusion_physical_plan::aggregates::{ - AggregateExec, AggregateMode, PhysicalGroupBy, + AggregateExec, AggregateMode, GroupClusteringMode, PhysicalGroupBy, }; use datafusion_physical_plan::test::TestMemoryExec; -use datafusion_physical_plan::{ExecutionPlan, InputOrderMode, collect}; +use datafusion_physical_plan::{ExecutionPlan, collect}; use tokio::runtime::Runtime; const ROWS: usize = 131_072; @@ -111,8 +111,10 @@ fn grouping(c: &mut Criterion) { let values: Box = if selected { new_group_values( Arc::clone(&schema), - &GroupOrdering::try_new(&InputOrderMode::Sorted) - .unwrap(), + &GroupClustering::try_new( + &GroupClusteringMode::Full, + ) + .unwrap(), ) .unwrap() } else { @@ -157,7 +159,7 @@ fn check_case(schema: &SchemaRef, batches: &[Vec]) -> (usize, usize) { let mut hashed = GroupValuesColumn::::try_new(Arc::clone(schema)).unwrap(); let mut selected = new_group_values( Arc::clone(schema), - &GroupOrdering::try_new(&InputOrderMode::Sorted).unwrap(), + &GroupClustering::try_new(&GroupClusteringMode::Full).unwrap(), ) .unwrap(); let mut expected = Vec::new(); @@ -228,7 +230,7 @@ fn aggregate_plan( schema, ) .unwrap(); - assert_eq!(plan.input_order_mode(), &InputOrderMode::Sorted); + assert_eq!(plan.group_clustering_mode(), &GroupClusteringMode::Full); Arc::new(plan) } diff --git a/datafusion/physical-plan/src/aggregates/group_values/mod.rs b/datafusion/physical-plan/src/aggregates/group_values/mod.rs index 70405cfd9da18..10a4aad5f5863 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/mod.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/mod.rs @@ -34,7 +34,7 @@ mod row; pub use row::GroupValuesRows; mod single_group_by; use datafusion_physical_expr::binary_map::OutputType; -use multi_group_by::{GroupValuesColumn, GroupValuesOrdered}; +use multi_group_by::{GroupValuesClustered, GroupValuesColumn}; pub(crate) use single_group_by::primitive::HashValue; @@ -121,7 +121,7 @@ pub trait GroupValues: Send { /// /// [`GroupValues`] implementations choosing logic: /// -/// - Fully ordered multi-column keys with supported scalar types use adjacent +/// - Fully clustered multi-column keys with supported scalar types use adjacent /// comparisons and column builders, without a hash table. /// /// - If group by single column, and type of this column has @@ -140,10 +140,10 @@ pub fn new_group_values( schema: SchemaRef, group_clustering: &GroupClustering, ) -> Result> { - if matches!(group_ordering, GroupOrdering::Full(_)) - && GroupValuesOrdered::supports_schema(&schema) + if matches!(group_clustering, GroupClustering::Full(_)) + && GroupValuesClustered::supports_schema(&schema) { - return Ok(Box::new(GroupValuesOrdered::try_new(schema)?)); + return Ok(Box::new(GroupValuesClustered::try_new(schema)?)); } if schema.fields.len() == 1 { let d = schema.fields[0].data_type(); diff --git a/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/ordered.rs b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/clustered.rs similarity index 92% rename from datafusion/physical-plan/src/aggregates/group_values/multi_group_by/ordered.rs rename to datafusion/physical-plan/src/aggregates/group_values/multi_group_by/clustered.rs index d331c510163cc..fad85fb18d82d 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/ordered.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/clustered.rs @@ -22,7 +22,7 @@ use arrow::datatypes::{DataType, Schema, SchemaRef, TimeUnit}; use arrow_ord::partition::partition; use datafusion_common::{Result, not_impl_err}; use datafusion_execution::memory_pool::proxy::VecAllocExt; -use datafusion_expr::{EmitTo, GroupSelection}; +use datafusion_expr::EmitTo; use super::{GroupColumn, GroupValuesColumn}; use crate::aggregates::group_values::GroupValues; @@ -69,8 +69,6 @@ impl GroupValuesClustered { | DataType::Time64(TimeUnit::Microsecond | TimeUnit::Nanosecond) | DataType::Duration(_) | DataType::Interval(_) - | DataType::Decimal32(_, _) - | DataType::Decimal64(_, _) | DataType::Decimal128(_, _) | DataType::Decimal256(_, _) | DataType::Utf8 @@ -166,21 +164,6 @@ impl GroupValues for GroupValuesClustered { }) } - fn values_preserving( - &mut self, - selection: GroupSelection<'_>, - ) -> Result> { - selection.validate_num_groups(self.len())?; - self.columns - .iter() - .map(|column| column.values_preserving(selection)) - .collect() - } - - fn supports_values_preserving(&self) -> bool { - true - } - fn clear_shrink(&mut self, num_rows: usize) { self.columns = GroupValuesColumn::::build_group_columns(&self.schema) .expect("schema validated by GroupValuesClustered::try_new"); @@ -195,17 +178,15 @@ mod tests { use arrow::array::UInt32Array; use arrow::array::{ - Array, AsArray, BooleanArray, Decimal32Array, Decimal64Array, Decimal128Array, - Decimal256Array, FixedSizeBinaryArray, Int32Array, Int64Array, - IntervalDayTimeArray, IntervalMonthDayNanoArray, IntervalYearMonthArray, - StringArray, + Array, AsArray, BooleanArray, Decimal128Array, Decimal256Array, + FixedSizeBinaryArray, Int32Array, Int64Array, IntervalDayTimeArray, + IntervalMonthDayNanoArray, IntervalYearMonthArray, StringArray, }; use arrow::buffer::{Buffer, NullBuffer}; use arrow::compute::{cast, take}; use arrow::datatypes::{ Field, IntervalDayTime, IntervalMonthDayNano, IntervalUnit, i256, }; - use datafusion_expr::GroupSelection; use super::*; @@ -243,16 +224,6 @@ mod tests { })); cast(&strings, key_type)? } - DataType::Decimal32(precision, scale) => Arc::new( - Decimal32Array::from_iter(keys.iter().map(|key| key.map(|key| key - 2))) - .with_precision_and_scale(*precision, *scale)?, - ), - DataType::Decimal64(precision, scale) => Arc::new( - Decimal64Array::from_iter( - keys.iter().map(|key| key.map(|key| i64::from(key - 2))), - ) - .with_precision_and_scale(*precision, *scale)?, - ), DataType::Decimal128(precision, scale) => { // Equal low 64 bits must not hide differences in the high bits. let values = [ @@ -379,10 +350,6 @@ mod tests { DataType::Interval(IntervalUnit::YearMonth), DataType::Interval(IntervalUnit::DayTime), DataType::Interval(IntervalUnit::MonthDayNano), - DataType::Decimal32(9, 2), - DataType::Decimal32(9, -2), - DataType::Decimal64(18, 2), - DataType::Decimal64(18, -2), DataType::Decimal128(38, 2), DataType::Decimal128(38, -2), DataType::Decimal256(76, 2), @@ -452,10 +419,6 @@ mod tests { "{key_type:?}, nullable={nullable}, unsorted={unsorted}, batch={batch_size}, offset={offset}, descending={descending}" ); assert_eq!(clustered.len(), hashed.len()); - let selection = GroupSelection::all(clustered.len()); - let values = clustered.values_preserving(selection)?; - assert_eq!(values, hashed.values_preserving(selection)?); - assert_eq!(values[1].data_type(), &key_type); // A zero-row batch must neither forget the boundary // key nor leave stale group ids in the output buffer. let empty = batch @@ -470,15 +433,6 @@ mod tests { assert_eq!(values, hashed.emit(EmitTo::First(emit))?); assert_eq!(values[1].data_type(), &key_type); } - let indices = [clustered.len() - 1, 0, clustered.len() - 1]; - let selection = GroupSelection::try_from_indices( - &indices, - clustered.len(), - )?; - assert_eq!( - clustered.values_preserving(selection)?, - hashed.values_preserving(selection)? - ); let values = clustered.emit(EmitTo::All)?; assert_eq!(values, hashed.emit(EmitTo::All)?); assert_eq!(values[1].data_type(), &key_type); @@ -566,10 +520,6 @@ mod tests { clustered.intern(&batch, &mut groups)?; assert_eq!(groups, vec![usize::from(nullable && offset == 2); 2]); } - let values = - clustered.values_preserving(GroupSelection::all(clustered.len()))?; - assert_eq!(values[1].len(), if nullable { 2 } else { 1 }); - assert_eq!(values[1].null_count(), usize::from(nullable)); let values = clustered.emit(EmitTo::First(1))?; assert_eq!(values[1].len(), 1); assert_eq!(values[1].null_count(), usize::from(nullable)); @@ -584,6 +534,10 @@ mod tests { #[test] fn clustered_schema_gate_keeps_unvalidated_types_on_existing_paths() { for data_type in [ + DataType::Decimal32(9, 2), + DataType::Decimal32(9, -2), + DataType::Decimal64(18, 2), + DataType::Decimal64(18, -2), DataType::Float16, DataType::Float32, DataType::Float64, diff --git a/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs index 7cbc9182a8948..fc1158ac849de 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs @@ -20,10 +20,10 @@ mod boolean; mod bytes; pub mod bytes_view; +mod clustered; +pub(super) use clustered::GroupValuesClustered; mod dictionary; mod fixed_size_binary; -mod ordered; -pub(super) use ordered::GroupValuesOrdered; pub mod primitive; pub mod row_backed; From 101e2cb63e2c9203b516837afb60621ac16b6211 Mon Sep 17 00:00:00 2001 From: linfeng <33561138+lyne7-sc@users.noreply.github.com> Date: Fri, 21 Aug 2026 05:41:09 +0000 Subject: [PATCH 4/5] fix: evaluate grouped aggregate arguments after FILTER (#24444) ## Which issue does this PR close? - Closes #24443. ## Rationale for this change Grouped aggregates evaluate their arguments before applying `FILTER`, which can cause errors on rows that should not participate in the aggregate. ## What changes are included in this PR? Evaluate aggregate filters first and use the resulting filters as selections when evaluating arguments. This covers migrated hash and ordered aggregation, legacy grouped hash aggregation, and both skip-partial paths. ## Are these changes tested? Yes. slts and unit tests cover migrated, legacy, ordered, and skip-partial execution. ## Are there any user-facing changes? No public APIs are changed. Grouped aggregate arguments are no longer evaluated for rows rejected by `FILTER`. (cherry picked from commit 5610e58b916373ee0d036231a9a3df2c1709aa1c) Environment: Datadog workspace Co-authored-by: Codex GPT-6.2 Astra --- .../aggregates/aggregate_hash_table/common.rs | 32 +++--- .../test_files/aggregate_filter_selection.slt | 100 ++++++++++++++++++ 2 files changed, 118 insertions(+), 14 deletions(-) create mode 100644 datafusion/sqllogictest/test_files/aggregate_filter_selection.slt 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/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; From 47997bf664c401960abfe68dce7f309ce2fce4ca Mon Sep 17 00:00:00 2001 From: "xavier.lee" Date: Thu, 26 Nov 2026 23:07:36 +0000 Subject: [PATCH 5/5] fix(aggregate): honor FILTER in the DF55 legacy grouped stream DF55 still dispatches fully clustered Single aggregates to the legacy stream. Apply the per-aggregate filter before evaluating fallible arguments there and when converting input rows to partial states. Spill replay continues to evaluate the saved unfiltered states. Environment: Datadog workspace Co-Authored-By: Codex GPT-6.2 Astra --- .../src/aggregates/grouped_hash_stream.rs | 43 ++++++++++++++----- 1 file changed, 33 insertions(+), 10 deletions(-) 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(),