use arrow::array::{ArrayRef, OffsetSizeTrait};
use datafusion_common::ScalarValue;
use datafusion_common::cast::as_list_array;
use datafusion_common::utils::SingleRowListArrayBuilder;
use datafusion_expr_common::accumulator::Accumulator;
use datafusion_physical_expr_common::binary_map::{ArrowBytesSet, OutputType};
use datafusion_physical_expr_common::binary_view_map::ArrowBytesViewSet;
use std::fmt::Debug;
use std::mem::size_of_val;
#[derive(Debug)]
pub struct BytesDistinctCountAccumulator<O: OffsetSizeTrait>(ArrowBytesSet<O>);
impl<O: OffsetSizeTrait> BytesDistinctCountAccumulator<O> {
pub fn new(output_type: OutputType) -> Self {
Self(ArrowBytesSet::new(output_type))
}
}
impl<O: OffsetSizeTrait> Accumulator for BytesDistinctCountAccumulator<O> {
fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
let set = self.0.take();
let arr = set.into_state();
Ok(vec![
SingleRowListArrayBuilder::new(arr).build_list_scalar(),
])
}
fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
if values.is_empty() {
return Ok(());
}
self.0.insert(&values[0]);
Ok(())
}
fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
if states.is_empty() {
return Ok(());
}
assert_eq!(
states.len(),
1,
"count_distinct states must be single array"
);
let arr = as_list_array(&states[0])?;
arr.iter().try_for_each(|maybe_list| {
if let Some(list) = maybe_list {
self.0.insert(&list);
}
Ok(())
})
}
fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
Ok(ScalarValue::Int64(Some(self.0.non_null_len() as i64)))
}
fn size(&self) -> usize {
size_of_val(self) + self.0.size()
}
}
#[derive(Debug)]
pub struct BytesViewDistinctCountAccumulator(ArrowBytesViewSet);
impl BytesViewDistinctCountAccumulator {
pub fn new(output_type: OutputType) -> Self {
Self(ArrowBytesViewSet::new(output_type))
}
}
impl Accumulator for BytesViewDistinctCountAccumulator {
fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
let set = self.0.take();
let arr = set.into_state();
Ok(vec![
SingleRowListArrayBuilder::new(arr).build_list_scalar(),
])
}
fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
if values.is_empty() {
return Ok(());
}
self.0.insert(&values[0]);
Ok(())
}
fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
if states.is_empty() {
return Ok(());
}
assert_eq!(
states.len(),
1,
"count_distinct states must be single array"
);
let arr = as_list_array(&states[0])?;
arr.iter().try_for_each(|maybe_list| {
if let Some(list) = maybe_list {
self.0.insert(&list);
}
Ok(())
})
}
fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
Ok(ScalarValue::Int64(Some(self.0.non_null_len() as i64)))
}
fn size(&self) -> usize {
size_of_val(self) + self.0.size()
}
}
#[cfg(all(test, not(feature = "force_hash_collisions")))]
mod tests {
use super::*;
use arrow::array::{StringArray, StringViewArray};
use datafusion_physical_expr_common::binary_map::INITIAL_MAP_CAPACITY;
use datafusion_physical_expr_common::binary_view_map::INITIAL_MAP_CAPACITY as INITIAL_VIEW_MAP_CAPACITY;
use std::sync::Arc;
const BATCH_SIZE: usize = 8192;
const CARDINALITIES: [usize; 7] = [0, 1, 100, 1_000, 10_000, 100_000, 500_000];
const PER_GROUP_SCALE: usize = 100;
const UNGROUPED_SCALE: usize = 10_000;
fn distinct_value(i: usize) -> String {
format!("distinct value number {i}")
}
fn batches(distinct_values: usize, view: bool) -> Vec<ArrayRef> {
(0..distinct_values)
.step_by(BATCH_SIZE)
.map(|start| {
let values = (start..(start + BATCH_SIZE).min(distinct_values))
.map(distinct_value);
if view {
Arc::new(StringViewArray::from_iter_values(values)) as ArrayRef
} else {
Arc::new(StringArray::from_iter_values(values)) as ArrayRef
}
})
.collect()
}
fn assert_lazy_is_not_worse(
distinct_values: usize,
lazy_size: usize,
pre_allocated_size: usize,
) {
assert!(
lazy_size <= pre_allocated_size,
"at {distinct_values} distinct values the lazy set reported \
{lazy_size} bytes against the {pre_allocated_size} bytes the \
pre-allocated one reported"
);
if distinct_values <= PER_GROUP_SCALE {
assert!(
lazy_size < pre_allocated_size,
"at {distinct_values} distinct values the lazy set should be \
strictly cheaper, but reported {lazy_size} bytes against \
{pre_allocated_size}"
);
}
if distinct_values >= UNGROUPED_SCALE {
assert_eq!(
lazy_size, pre_allocated_size,
"at {distinct_values} distinct values the lazy and pre-allocated \
sets should have converged"
);
}
}
#[test]
fn ungrouped_utf8_accumulator_is_never_worse_than_a_pre_allocated_set() {
for distinct_values in CARDINALITIES {
let mut accumulator =
BytesDistinctCountAccumulator::<i32>::new(OutputType::Utf8);
let mut pre_allocated = ArrowBytesSet::<i32>::with_capacity(
OutputType::Utf8,
INITIAL_MAP_CAPACITY,
);
for batch in batches(distinct_values, false) {
accumulator.update_batch(&[Arc::clone(&batch)]).unwrap();
pre_allocated.insert(&batch);
}
assert_eq!(accumulator.0.non_null_len(), distinct_values);
assert_lazy_is_not_worse(
distinct_values,
accumulator.0.size(),
pre_allocated.size(),
);
}
}
#[test]
fn ungrouped_utf8_view_accumulator_is_never_worse_than_a_pre_allocated_set() {
for distinct_values in CARDINALITIES {
let mut accumulator =
BytesViewDistinctCountAccumulator::new(OutputType::Utf8View);
let mut pre_allocated = ArrowBytesViewSet::with_capacity(
OutputType::Utf8View,
INITIAL_VIEW_MAP_CAPACITY,
);
for batch in batches(distinct_values, true) {
accumulator.update_batch(&[Arc::clone(&batch)]).unwrap();
pre_allocated.insert(&batch);
}
assert_eq!(accumulator.0.non_null_len(), distinct_values);
assert_lazy_is_not_worse(
distinct_values,
accumulator.0.size(),
pre_allocated.size(),
);
}
}
}