Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
bacee66
add count distinct group benchmarks
coderfender Apr 12, 2026
c4461b7
add count distinct group benchmarks
coderfender Apr 12, 2026
45a19b0
add count distinct group benchmarks
coderfender Apr 12, 2026
659754f
count group benchmark check
coderfender Apr 14, 2026
5f2d9bb
count group benchmark check
coderfender Apr 14, 2026
72568bb
Merge branch 'main' into add_group_benchmarks_count_distinct
coderfender Apr 14, 2026
0617a7b
Merge branch 'main' into add_group_benchmarks_count_distinct
coderfender Apr 16, 2026
19dd479
Merge branch 'main' into add_group_benchmarks_count_distinct
coderfender Apr 16, 2026
17dd86b
Merge branch 'main' into add_group_benchmarks_count_distinct
coderfender Apr 16, 2026
a9cdec8
groups_acc
coderfender Apr 16, 2026
f982d8d
add count distinct group benchmarks
coderfender Apr 12, 2026
929e081
hashtable_with_count_vector_approach
coderfender Apr 16, 2026
72cea62
hashtable_with_count_vector_approach
coderfender Apr 16, 2026
ba140a0
groups_acc_more_robust_checks
coderfender Apr 16, 2026
12d314f
Merge branch 'main' into implement_groups_accumulator_count_distinct_…
coderfender Apr 16, 2026
c2bc9d3
fix_compilation_issues
coderfender Apr 17, 2026
47110a8
Merge branch 'main' into implement_groups_accumulator_count_distinct_…
coderfender Apr 17, 2026
066504d
Merge branch 'main' into implement_groups_accumulator_count_distinct_…
coderfender Apr 17, 2026
888f556
single_state_vec
coderfender Apr 17, 2026
617e790
slice_merge_batch
coderfender Apr 17, 2026
918036e
fix_pr_comments
coderfender Apr 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@

mod bytes;
mod dict;
mod groups;
mod native;

pub use bytes::BytesDistinctCountAccumulator;
pub use bytes::BytesViewDistinctCountAccumulator;
pub use dict::DictionaryCountAccumulator;
pub use groups::PrimitiveDistinctCountGroupsAccumulator;
pub use native::Bitmap65536DistinctCountAccumulator;
pub use native::Bitmap65536DistinctCountAccumulatorI16;
pub use native::BoolArray256DistinctCountAccumulator;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// 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 arrow::array::{
ArrayRef, AsArray, BooleanArray, Int64Array, ListArray, PrimitiveArray,
};
use arrow::buffer::{OffsetBuffer, ScalarBuffer};
use arrow::datatypes::{ArrowPrimitiveType, Field};
use datafusion_common::HashSet;
use datafusion_common::hash_utils::RandomState;
use datafusion_expr_common::groups_accumulator::{EmitTo, GroupsAccumulator};
use std::hash::Hash;
use std::mem::size_of;
use std::sync::Arc;

use crate::aggregate::groups_accumulator::accumulate::accumulate;

pub struct PrimitiveDistinctCountGroupsAccumulator<T: ArrowPrimitiveType>
where
T::Native: Eq + Hash,
{
seen: HashSet<(usize, T::Native), RandomState>,
counts: Vec<i64>,
}

impl<T: ArrowPrimitiveType> PrimitiveDistinctCountGroupsAccumulator<T>
where
T::Native: Eq + Hash,
{
pub fn new() -> Self {
Self {
seen: HashSet::default(),
counts: Vec::new(),
}
}
}

impl<T: ArrowPrimitiveType> Default for PrimitiveDistinctCountGroupsAccumulator<T>
where
T::Native: Eq + Hash,
{
fn default() -> Self {
Self::new()
}
}

impl<T: ArrowPrimitiveType + Send + std::fmt::Debug> GroupsAccumulator
for PrimitiveDistinctCountGroupsAccumulator<T>
where
T::Native: Eq + Hash,
{
fn update_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
opt_filter: Option<&BooleanArray>,
total_num_groups: usize,
) -> datafusion_common::Result<()> {
debug_assert_eq!(values.len(), 1);
self.counts.resize(total_num_groups, 0);
let arr = values[0].as_primitive::<T>();
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<ArrayRef> {
let counts = emit_to.take_needed(&mut self.counts);

match emit_to {
EmitTo::All => {
self.seen.clear();
}
EmitTo::First(n) => {
let mut remaining = HashSet::default();
for (group_idx, value) in self.seen.drain() {
if group_idx >= n {
remaining.insert((group_idx - n, value));
}
}
self.seen = remaining;
}
}

Ok(Arc::new(Int64Array::from(counts)))
}

fn state(&mut self, emit_to: EmitTo) -> datafusion_common::Result<Vec<ArrayRef>> {
let num_emitted = match emit_to {
EmitTo::All => self.counts.len(),
EmitTo::First(n) => n,
};

// Prefix-sum counts[..num_emitted] into offsets
let mut offsets = Vec::with_capacity(num_emitted + 1);
offsets.push(0i32);
let mut total = 0i32;
for &c in &self.counts[..num_emitted] {
total += c as i32;
offsets.push(total);
}

let mut all_values = vec![T::Native::default(); total as usize];
let mut cursors: Vec<i32> = offsets[..num_emitted].to_vec();

if matches!(emit_to, EmitTo::All) {
for (group_idx, value) in self.seen.drain() {
let pos = cursors[group_idx] as usize;
all_values[pos] = value;
cursors[group_idx] += 1;
}
self.counts.clear();
} else {
let mut remaining = HashSet::default();
for (group_idx, value) in self.seen.drain() {
if group_idx < num_emitted {
let pos = cursors[group_idx] as usize;
all_values[pos] = value;
cursors[group_idx] += 1;
} else {
remaining.insert((group_idx - num_emitted, value));
}
}
self.seen = remaining;
let _ = emit_to.take_needed(&mut self.counts);
}

let values_array = Arc::new(PrimitiveArray::<T>::new(
ScalarBuffer::from(all_values),
None,
));
let list_array = ListArray::new(
Arc::new(Field::new_list_field(T::DATA_TYPE, true)),
OffsetBuffer::new(offsets.into()),
values_array,
None,
);

Ok(vec![Arc::new(list_array)])
}

fn merge_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
_opt_filter: Option<&BooleanArray>,
total_num_groups: usize,
) -> datafusion_common::Result<()> {
debug_assert_eq!(values.len(), 1);
self.counts.resize(total_num_groups, 0);
let list_array = values[0].as_list::<i32>();
let inner = list_array.values().as_primitive::<T>();
let inner_values = inner.values();
let offsets = list_array.offsets();

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;
}
}
}

Ok(())
}

fn size(&self) -> usize {
size_of::<Self>()
+ self.seen.capacity() * (size_of::<(usize, T::Native)>() + size_of::<u64>())
+ self.counts.capacity() * size_of::<i64>()
}
}
132 changes: 129 additions & 3 deletions datafusion/functions-aggregate/benches/count_distinct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
use std::sync::Arc;

use arrow::array::{
ArrayRef, Int8Array, Int16Array, Int64Array, UInt8Array, UInt16Array,
Array, ArrayRef, Int8Array, Int16Array, Int64Array, UInt8Array, UInt16Array,
};
use arrow::datatypes::{DataType, Field, Schema};
use criterion::{Criterion, criterion_group, criterion_main};
use datafusion_expr::function::AccumulatorArgs;
use datafusion_expr::{Accumulator, AggregateUDFImpl};
use datafusion_expr::{Accumulator, AggregateUDFImpl, EmitTo};
use datafusion_functions_aggregate::count::Count;
use datafusion_physical_expr::expressions::col;
use rand::rngs::StdRng;
Expand Down Expand Up @@ -87,6 +87,30 @@ fn create_i16_array(n_distinct: usize) -> Int16Array {
.collect()
}

fn prepare_args(data_type: DataType) -> (Arc<Schema>, AccumulatorArgs<'static>) {
let schema = Arc::new(Schema::new(vec![Field::new("f", data_type, true)]));
let schema_leaked: &'static Schema = Box::leak(Box::new((*schema).clone()));
let expr = col("f", schema_leaked).unwrap();
let expr_leaked: &'static _ = Box::leak(Box::new(expr));
let return_field: Arc<Field> = Field::new("f", DataType::Int64, true).into();
let return_field_leaked: &'static _ = Box::leak(Box::new(return_field.clone()));
let expr_field = expr_leaked.return_field(schema_leaked).unwrap();
let expr_field_leaked: &'static _ = Box::leak(Box::new(expr_field));

let accumulator_args = AccumulatorArgs {
return_field: return_field_leaked.clone(),
schema: schema_leaked,
expr_fields: std::slice::from_ref(expr_field_leaked),
ignore_nulls: false,
order_bys: &[],
is_reversed: false,
name: "count(distinct f)",
is_distinct: true,
exprs: std::slice::from_ref(expr_leaked),
};
(schema, accumulator_args)
}

fn count_distinct_benchmark(c: &mut Criterion) {
for pct in [80, 99] {
let n_distinct = BATCH_SIZE * pct / 100;
Expand Down Expand Up @@ -150,5 +174,107 @@ fn count_distinct_benchmark(c: &mut Criterion) {
});
}

criterion_group!(benches, count_distinct_benchmark);
/// Create group indices with uniform distribution
fn create_uniform_groups(num_groups: usize) -> Vec<usize> {
let mut rng = StdRng::seed_from_u64(42);
(0..BATCH_SIZE)
.map(|_| rng.random_range(0..num_groups))
.collect()
}

/// Create group indices with skewed distribution (80% in 20% of groups)
fn create_skewed_groups(num_groups: usize) -> Vec<usize> {
let mut rng = StdRng::seed_from_u64(42);
let hot_groups = (num_groups / 5).max(1);
(0..BATCH_SIZE)
.map(|_| {
if rng.random_range(0..100) < 80 {
rng.random_range(0..hot_groups)
} else {
rng.random_range(0..num_groups)
}
})
.collect()
}

fn count_distinct_groups_benchmark(c: &mut Criterion) {
let count_fn = Count::new();

let group_counts = [100, 1000, 10000];
let cardinalities = [("low", 20), ("mid", 80), ("high", 99)];
let distributions = ["uniform", "skewed"];

for num_groups in group_counts {
for (card_name, distinct_pct) in cardinalities {
for dist in distributions {
let name = format!("g{num_groups}_{card_name}_{dist}");
let n_distinct = BATCH_SIZE * distinct_pct / 100;
let values = Arc::new(create_i64_array(n_distinct)) as ArrayRef;
let group_indices = if dist == "uniform" {
create_uniform_groups(num_groups)
} else {
create_skewed_groups(num_groups)
};

let (_schema, args) = prepare_args(DataType::Int64);

if count_fn.groups_accumulator_supported(args.clone()) {
c.bench_function(&format!("count_distinct_groups {name}"), |b| {
b.iter(|| {
let mut acc =
count_fn.create_groups_accumulator(args.clone()).unwrap();
acc.update_batch(
std::slice::from_ref(&values),
&group_indices,
None,
num_groups,
)
.unwrap();
acc.evaluate(EmitTo::All).unwrap()
})
});
} else {
let arr = values.as_any().downcast_ref::<Int64Array>().unwrap();
let mut group_rows: Vec<Vec<i64>> = vec![Vec::new(); num_groups];
for (idx, &group_idx) in group_indices.iter().enumerate() {
if arr.is_valid(idx) {
group_rows[group_idx].push(arr.value(idx));
}
}
let group_arrays: Vec<ArrayRef> = group_rows
.iter()
.map(|rows| Arc::new(Int64Array::from(rows.clone())) as ArrayRef)
.collect();

c.bench_function(&format!("count_distinct_groups {name}"), |b| {
b.iter(|| {
let mut accumulators: Vec<_> = (0..num_groups)
.map(|_| prepare_accumulator(DataType::Int64))
.collect();

for (group_idx, batch) in group_arrays.iter().enumerate() {
if !batch.is_empty() {
accumulators[group_idx]
.update_batch(std::slice::from_ref(batch))
.unwrap();
}
}

let _results: Vec<_> = accumulators
.iter_mut()
.map(|acc| acc.evaluate().unwrap())
.collect();
})
});
}
}
}
}
}

criterion_group!(
benches,
count_distinct_benchmark,
count_distinct_groups_benchmark
);
criterion_main!(benches);
Loading
Loading