From 312ca330b6d76ef93b2cbfec3fd1b6f48cea174f Mon Sep 17 00:00:00 2001 From: hushen <190065939+918154429@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:23:55 +0900 Subject: [PATCH 1/2] bench: cover small distinct sets and NULL-heavy groups --- .../grouped_count_distinct/README.md | 3 +++ .../benchmarks/q11.benchmark | 27 +++++++++++++++++++ .../benchmarks/q12.benchmark | 27 +++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q11.benchmark create mode 100644 benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q12.benchmark diff --git a/benchmarks/sql_benchmarks/grouped_count_distinct/README.md b/benchmarks/sql_benchmarks/grouped_count_distinct/README.md index 65fb2de2003c9..e95e04af60023 100644 --- a/benchmarks/sql_benchmarks/grouped_count_distinct/README.md +++ b/benchmarks/sql_benchmarks/grouped_count_distinct/README.md @@ -25,6 +25,9 @@ rows it has one million groups, each with four copies of the same value. Each native input row probes both the group table and the per-group distinct set; the rewrite's outer aggregate only sees the deduplicated pairs. +Q11 uses the same group count with at most two distinct values per group. Q12 +has 95% of groups containing only NULL arguments. + Every query checks its result against an explicit distinct-pairs-then-count query before timing. Keep the memory pool and limit the same on both sides. The combined correctness query needs more memory than the measured aggregate. diff --git a/benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q11.benchmark b/benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q11.benchmark new file mode 100644 index 0000000000000..ad763400d2129 --- /dev/null +++ b/benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q11.benchmark @@ -0,0 +1,27 @@ +name Q11 +group grouped_count_distinct + +load sql_benchmarks/grouped_count_distinct/init/load.sql + +assert I +WITH actual AS ( + SELECT many_g AS g, count(DISTINCT x % 2) AS n + FROM grouped_distinct GROUP BY many_g +), expected AS ( + SELECT g, count(x) AS n + FROM (SELECT DISTINCT many_g AS g, x % 2 AS x FROM grouped_distinct) + GROUP BY g +) +SELECT NOT EXISTS (SELECT * FROM actual EXCEPT SELECT * FROM expected) + AND NOT EXISTS (SELECT * FROM expected EXCEPT SELECT * FROM actual); +---- +true + +expect_plan AggregateExec + +run +-- Int64, 1M groups, at most two distinct values per group at 4M rows. +SELECT many_g, count(DISTINCT x % 2) +FROM grouped_distinct GROUP BY many_g; + +cleanup sql_benchmarks/grouped_count_distinct/init/cleanup.sql diff --git a/benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q12.benchmark b/benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q12.benchmark new file mode 100644 index 0000000000000..d57cb2b5b23db --- /dev/null +++ b/benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q12.benchmark @@ -0,0 +1,27 @@ +name Q12 +group grouped_count_distinct + +load sql_benchmarks/grouped_count_distinct/init/load.sql + +assert I +WITH actual AS ( + SELECT many_g AS g, count(DISTINCT CASE WHEN many_g % 20 < 19 THEN NULL ELSE dup_x END) AS n + FROM grouped_distinct GROUP BY many_g +), expected AS ( + SELECT g, count(x) AS n + FROM (SELECT DISTINCT many_g AS g, CASE WHEN many_g % 20 < 19 THEN NULL ELSE dup_x END AS x FROM grouped_distinct) + GROUP BY g +) +SELECT NOT EXISTS (SELECT * FROM actual EXCEPT SELECT * FROM expected) + AND NOT EXISTS (SELECT * FROM expected EXCEPT SELECT * FROM actual); +---- +true + +expect_plan AggregateExec + +run +-- Int64, 1M groups; 95% of groups contain only NULL arguments at 4M rows. +SELECT many_g, count(DISTINCT CASE WHEN many_g % 20 < 19 THEN NULL ELSE dup_x END) +FROM grouped_distinct GROUP BY many_g; + +cleanup sql_benchmarks/grouped_count_distinct/init/cleanup.sql From 643f16b5d8b9620d3c304fdbb18e219c962f5623 Mon Sep 17 00:00:00 2001 From: hushen <190065939+918154429@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:23:56 +0900 Subject: [PATCH 2/2] perf: inline the first value in grouped integer DISTINCT counts --- .../grouped_count_distinct/README.md | 23 +- .../benchmarks/q10.benchmark | 2 +- .../src/aggregate/count_distinct/groups.rs | 289 +++++++++++++++++- .../test_files/grouped_count_distinct.slt | 38 +++ 4 files changed, 337 insertions(+), 15 deletions(-) diff --git a/benchmarks/sql_benchmarks/grouped_count_distinct/README.md b/benchmarks/sql_benchmarks/grouped_count_distinct/README.md index e95e04af60023..782163bf45b5b 100644 --- a/benchmarks/sql_benchmarks/grouped_count_distinct/README.md +++ b/benchmarks/sql_benchmarks/grouped_count_distinct/README.md @@ -20,13 +20,26 @@ distributed rewrite, which remains selected with either flag value. The same environment variable works with `./bench.sh run grouped_count_distinct`. Q01-Q09 vary argument and grouping-key types, group count, distinct cardinality, -and skew. Q10 covers the unfavorable native shape: at the default four million -rows it has one million groups, each with four copies of the same value. Each -native input row probes both the group table and the per-group distinct set; -the rewrite's outer aggregate only sees the deduplicated pairs. +and skew. Q10 has one million groups, each with four copies of the same value, +at the default four million rows. It exercises the native accumulator's inline +first value, which lets repeated singleton values skip the distinct hash set. +The rewrite's outer aggregate only sees the deduplicated pairs. + +After each update or merge batch, the native accumulator checks the average +number of distinct values beyond the first per group. The denominator includes +all groups, even those with only NULL arguments. If the average exceeds eight, +the accumulator moves the inline values into the hash set and releases the +inline buffer. It stays in hash-only mode across partial emissions. +Emitting all groups with `EmitTo::All` resets it to inline mode. Q11 uses the same group count with at most two distinct values per group. Q12 -has 95% of groups containing only NULL arguments. +has 95% of groups containing only NULL arguments, exposing the memory cost of +allocating inline value slots for groups without a non-NULL value. Each +DISTINCT expression has its own buffer, so several sparse expressions can +raise peak memory reservations enough to trigger spilling. In a +[test with twelve sparse DISTINCT expressions](https://github.com/apache/datafusion/pull/27299#discussion_r4783027926), +the peak rose from 5.24 MB to 8.38 MB and the query began spilling with a 6M +memory limit. Every query checks its result against an explicit distinct-pairs-then-count query before timing. Keep the memory pool and limit the same on both sides. diff --git a/benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q10.benchmark b/benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q10.benchmark index be8dcb20c5b28..b9082e8623316 100644 --- a/benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q10.benchmark +++ b/benchmarks/sql_benchmarks/grouped_count_distinct/benchmarks/q10.benchmark @@ -20,7 +20,7 @@ expect_plan AggregateExec run -- Int64, 1M groups with four identical values per group at the default 4M rows. --- Native DISTINCT probes both the group table and its per-group set on each row. +-- Repeated singleton values exercise the native accumulator's inline first value. SELECT many_g, count(DISTINCT dup_x) FROM grouped_distinct GROUP BY many_g; cleanup sql_benchmarks/grouped_count_distinct/init/cleanup.sql diff --git a/datafusion/functions-aggregate-common/src/aggregate/count_distinct/groups.rs b/datafusion/functions-aggregate-common/src/aggregate/count_distinct/groups.rs index c30372d401b73..cfd349c990eb3 100644 --- a/datafusion/functions-aggregate-common/src/aggregate/count_distinct/groups.rs +++ b/datafusion/functions-aggregate-common/src/aggregate/count_distinct/groups.rs @@ -19,10 +19,16 @@ use std::sync::Arc; use crate::aggregate::groups_accumulator::accumulate::accumulate; +// Limit inline checks when the average number of additional distinct values grows. +const INLINE_AVERAGE_DISTINCT_LIMIT: usize = 8; + pub struct PrimitiveDistinctCountGroupsAccumulator where T::Native: Eq + Hash, { + // While present, this buffer keeps each group's first non-null value out of + // `seen`. None means all values have been promoted into the hash set. + first_values: Option>, seen: HashSet<(usize, T::Native), RandomState>, counts: Vec, } @@ -33,10 +39,46 @@ where { pub fn new() -> Self { Self { + first_values: Some(Vec::new()), seen: HashSet::default(), counts: Vec::new(), } } + + fn insert_inline( + first_value: &mut T::Native, + count: &mut i64, + seen: &mut HashSet<(usize, T::Native), RandomState>, + group_idx: usize, + value: T::Native, + ) { + if *count == 0 { + *first_value = value; + *count = 1; + } else if *first_value != value && seen.insert((group_idx, value)) { + *count += 1; + } + } + + fn promote_inline_values(&mut self) { + if self.seen.len() + > self + .counts + .len() + .saturating_mul(INLINE_AVERAGE_DISTINCT_LIMIT) + && let Some(first_values) = self.first_values.take() + { + // Pay for moving the first values once, then use the hash-only loop + // for subsequent batches with large distinct sets. + for (group_idx, (value, count)) in + first_values.into_iter().zip(&self.counts).enumerate() + { + if *count > 0 { + self.seen.insert((group_idx, value)); + } + } + } + } } impl Default for PrimitiveDistinctCountGroupsAccumulator @@ -63,16 +105,33 @@ where debug_assert_eq!(values.len(), 1); self.counts.resize(total_num_groups, 0); let arr = values[0].as_primitive::(); - accumulate(group_indices, arr, opt_filter, |group_idx, value| { - if self.seen.insert((group_idx, value)) { - self.counts[group_idx] += 1; - } - }); + if let Some(first_values) = &mut self.first_values { + first_values.resize(total_num_groups, T::Native::default()); + accumulate(group_indices, arr, opt_filter, |group_idx, value| { + Self::insert_inline( + &mut first_values[group_idx], + &mut self.counts[group_idx], + &mut self.seen, + group_idx, + value, + ); + }); + self.promote_inline_values(); + } else { + accumulate(group_indices, arr, opt_filter, |group_idx, value| { + if self.seen.insert((group_idx, value)) { + self.counts[group_idx] += 1; + } + }); + } Ok(()) } fn evaluate(&mut self, emit_to: EmitTo) -> datafusion_common::Result { let counts = emit_to.take_needed(&mut self.counts); + if let Some(first_values) = &mut self.first_values { + let _ = emit_to.take_needed(first_values); + } match emit_to { EmitTo::All => { @@ -80,6 +139,7 @@ where // capacity, and the aggregate streams rely on it dropping after // emitting everything. self.seen = HashSet::default(); + self.first_values = Some(Vec::new()); } EmitTo::First(n) => { let mut remaining = HashSet::default(); @@ -121,13 +181,29 @@ where let mut offsets = Vec::with_capacity(num_emitted + 1); offsets.push(0i32); let mut total = 0i32; + let mut seen_emitted = 0; for &c in &self.counts[..num_emitted] { total += c as i32; offsets.push(total); + seen_emitted += if self.first_values.is_some() { + (c as usize).saturating_sub(1) + } else { + c as usize + }; } let mut all_values = vec![T::Native::default(); total as usize]; let mut cursors: Vec = offsets[..num_emitted].to_vec(); + if let Some(first_values) = &mut self.first_values { + let first_values = emit_to.take_needed(first_values); + for (group_idx, value) in first_values.into_iter().enumerate() { + if self.counts[group_idx] > 0 { + let pos = cursors[group_idx] as usize; + all_values[pos] = value; + cursors[group_idx] += 1; + } + } + } if matches!(emit_to, EmitTo::All) { for (group_idx, value) in self.seen.drain() { @@ -138,9 +214,10 @@ where // Release the capacity, see `evaluate`. self.seen = HashSet::default(); self.counts = Vec::new(); + self.first_values = Some(Vec::new()); } else { let mut remaining = HashSet::with_capacity_and_hasher( - self.seen.len().saturating_sub(total as usize), + self.seen.len().saturating_sub(seen_emitted), RandomState::default(), ); for (group_idx, value) in self.seen.drain() { @@ -178,6 +255,9 @@ where ) -> datafusion_common::Result<()> { debug_assert_eq!(values.len(), 1); self.counts.resize(total_num_groups, 0); + if let Some(first_values) = &mut self.first_values { + first_values.resize(total_num_groups, T::Native::default()); + } let list_array = values[0].as_list::(); let inner = list_array.values().as_primitive::(); let inner_values = inner.values(); @@ -186,13 +266,26 @@ where for (row_idx, &group_idx) in group_indices.iter().enumerate() { let start = offsets[row_idx] as usize; let end = offsets[row_idx + 1] as usize; - for &value in &inner_values[start..end] { - if self.seen.insert((group_idx, value)) { - self.counts[group_idx] += 1; + if let Some(first_values) = &mut self.first_values { + for &value in &inner_values[start..end] { + Self::insert_inline( + &mut first_values[group_idx], + &mut self.counts[group_idx], + &mut self.seen, + group_idx, + value, + ); + } + } else { + for &value in &inner_values[start..end] { + if self.seen.insert((group_idx, value)) { + self.counts[group_idx] += 1; + } } } } + self.promote_inline_values(); Ok(()) } @@ -222,6 +315,10 @@ where } fn size(&self) -> usize { size_of::() + + self + .first_values + .as_ref() + .map_or(0, |values| values.capacity() * size_of::()) + self.seen.capacity() * (size_of::<(usize, T::Native)>() + size_of::()) + self.counts.capacity() * size_of::() } @@ -229,11 +326,185 @@ where #[cfg(test)] mod tests { + use std::mem::size_of_val; + use super::*; use arrow::array::Int32Array; use arrow::datatypes::Int32Type; use datafusion_common::Result; + #[test] + fn promoted_values_survive_partial_emission_and_merge() -> Result<()> { + let mut accumulator = PrimitiveDistinctCountGroupsAccumulator::::new(); + let values = Arc::new(Int32Array::from_iter( + (0..128).map(Some).chain([Some(7), None]), + )); + let groups = vec![0; 128].into_iter().chain([1, 2]).collect::>(); + accumulator.update_batch(&[values], &groups, None, 3)?; + assert!(accumulator.first_values.is_none()); + assert_eq!( + accumulator + .evaluate_preserving(GroupSelection::all(3))? + .as_primitive::(), + &Int64Array::from(vec![128, 1, 0]) + ); + + let states = accumulator.state(EmitTo::First(1))?; + let mut merged = PrimitiveDistinctCountGroupsAccumulator::::new(); + merged.merge_batch(&states, &[0], 1)?; + assert!(merged.first_values.is_none()); + merged.merge_batch(&states, &[0], 1)?; + merged.merge_batch(&states, &[1], 2)?; + assert_eq!( + merged + .evaluate(EmitTo::All)? + .as_primitive::(), + &Int64Array::from(vec![128, 128]) + ); + + // The promoted singleton and empty group now have indices 0 and 1. + let values = Arc::new(Int32Array::from(vec![Some(7), Some(9), None])); + accumulator.update_batch(&[values], &[0, 0, 1], None, 2)?; + assert_eq!( + accumulator + .evaluate(EmitTo::First(1))? + .as_primitive::(), + &Int64Array::from(vec![2]) + ); + let values = Arc::new(Int32Array::from(vec![7, 7])); + accumulator.update_batch(&[values], &[0, 0], None, 1)?; + let states = accumulator.state(EmitTo::All)?; + assert_eq!(accumulator.size(), size_of_val(&accumulator)); + merged.merge_batch(&states, &[0], 1)?; + assert_eq!( + merged + .evaluate(EmitTo::All)? + .as_primitive::(), + &Int64Array::from(vec![1]) + ); + + let values = Arc::new(Int32Array::from(vec![0, 0])); + accumulator.update_batch(&[values], &[0, 0], None, 1)?; + assert!(accumulator.first_values.is_some()); + assert_eq!( + accumulator + .evaluate(EmitTo::All)? + .as_primitive::(), + &Int64Array::from(vec![1]) + ); + Ok(()) + } + + #[test] + fn partial_evaluation_keeps_first_values_aligned() -> Result<()> { + let mut accumulator = PrimitiveDistinctCountGroupsAccumulator::::new(); + let values = Arc::new(Int32Array::from(vec![ + None, + Some(0), + Some(0), + Some(1), + Some(7), + Some(7), + Some(-1), + Some(0), + Some(2), + None, + ])); + accumulator.update_batch(&[values], &[0, 1, 1, 1, 2, 2, 3, 3, 3, 4], None, 5)?; + + assert_eq!( + accumulator + .evaluate(EmitTo::First(2))? + .as_primitive::(), + &Int64Array::from(vec![0, 2]) + ); + + // The former groups 2, 3 and 4 now have indices 0, 1 and 2. + let values = Arc::new(Int32Array::from(vec![7, 8, -1, 5, 0, 9, 9])); + accumulator.update_batch(&[values], &[0, 0, 1, 1, 2, 3, 3], None, 4)?; + assert_eq!( + accumulator + .evaluate(EmitTo::All)? + .as_primitive::(), + &Int64Array::from(vec![2, 4, 1, 1]) + ); + assert_eq!(accumulator.size(), size_of_val(&accumulator)); + + let values = Arc::new(Int32Array::from(vec![0, 0])); + accumulator.update_batch(&[values], &[0, 0], None, 1)?; + assert_eq!( + accumulator + .evaluate(EmitTo::All)? + .as_primitive::(), + &Int64Array::from(vec![1]) + ); + Ok(()) + } + + #[test] + fn partial_state_roundtrips_with_overlapping_values() -> Result<()> { + let mut accumulator = PrimitiveDistinctCountGroupsAccumulator::::new(); + let values = Arc::new(Int32Array::from(vec![ + None, + Some(0), + Some(1), + Some(7), + Some(8), + None, + ])); + accumulator.update_batch(&[values], &[0, 1, 1, 2, 2, 3], None, 4)?; + + // Emit both an empty state and a state with inline and hashed values. + let states = accumulator.state(EmitTo::First(2))?; + let mut merged = PrimitiveDistinctCountGroupsAccumulator::::new(); + let values = Arc::new(Int32Array::from(vec![1, 2])); + merged.update_batch(&[values], &[1, 1], None, 2)?; + merged.merge_batch(&states, &[0, 1], 2)?; + merged.merge_batch(&states, &[0, 1], 2)?; + assert_eq!( + merged + .evaluate(EmitTo::All)? + .as_primitive::(), + &Int64Array::from(vec![0, 3]) + ); + + // Update the shifted groups, preserving an all-NULL group's empty state. + let values = Arc::new(Int32Array::from(vec![Some(7), Some(9), None])); + accumulator.update_batch(&[values], &[0, 0, 1], None, 2)?; + let states = accumulator.state(EmitTo::All)?; + assert_eq!(accumulator.size(), size_of_val(&accumulator)); + merged.merge_batch(&states, &[0, 1], 2)?; + assert_eq!( + merged + .evaluate(EmitTo::All)? + .as_primitive::(), + &Int64Array::from(vec![3, 0]) + ); + Ok(()) + } + + #[test] + fn singleton_values_are_accounted_for() -> Result<()> { + let mut accumulator = PrimitiveDistinctCountGroupsAccumulator::::new(); + let values = Arc::new(Int32Array::from(vec![0; 64])); + let groups = (0..64).collect::>(); + accumulator.update_batch(&[values], &groups, None, 64)?; + assert!( + accumulator.size() + >= size_of_val(&accumulator) + 64 * (size_of::() + size_of::()) + ); + let states = accumulator.state(EmitTo::All)?; + assert_eq!(accumulator.size(), size_of_val(&accumulator)); + accumulator.merge_batch(&states, &groups, 64)?; + assert_eq!( + accumulator + .evaluate(EmitTo::All)? + .as_primitive::(), + &Int64Array::from(vec![1; 64]) + ); + Ok(()) + } + #[test] fn preserving_reads_keep_distinct_state() -> Result<()> { let mut accumulator = PrimitiveDistinctCountGroupsAccumulator::::new(); diff --git a/datafusion/sqllogictest/test_files/grouped_count_distinct.slt b/datafusion/sqllogictest/test_files/grouped_count_distinct.slt index 1490442ab383a..37065461bbac5 100644 --- a/datafusion/sqllogictest/test_files/grouped_count_distinct.slt +++ b/datafusion/sqllogictest/test_files/grouped_count_distinct.slt @@ -233,6 +233,44 @@ physical_plan statement ok SET datafusion.explain.physical_plan_only = false; +# Repeated singleton values, NULL-only groups and larger sets span small batches. +statement ok +SET datafusion.execution.batch_size = 2; + +statement ok +CREATE TABLE inline_counts AS +SELECT value % 4 AS g, + CASE WHEN value < 4 OR value % 4 = 0 THEN NULL + WHEN value % 4 = 1 THEN 0 + WHEN value % 4 = 2 THEN (value / 4) % 2 + ELSE value / 4 END AS x +FROM range(64); + +query II rowsort +SELECT g, count(DISTINCT x) FROM inline_counts GROUP BY g; +---- +0 0 +1 1 +2 2 +3 15 + +# Partial states overlap in both their first value and their additional values. +query II rowsort +SELECT g, count(DISTINCT x) +FROM (SELECT g, x FROM inline_counts UNION ALL SELECT g, x FROM inline_counts) +GROUP BY g; +---- +0 0 +1 1 +2 2 +3 15 + +statement ok +DROP TABLE inline_counts; + +statement ok +RESET datafusion.execution.batch_size; + # Turning the opt-in off in the same session restores the rewrite. statement ok SET datafusion.optimizer.single_distinct_prefer_native = false;