Skip to main content

datafusion_functions_aggregate_common/aggregate/count_distinct/
bytes.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`BytesDistinctCountAccumulator`] for Utf8/LargeUtf8/Binary/LargeBinary values
6
7use arrow::array::{ArrayRef, OffsetSizeTrait};
8use datafusion_common::ScalarValue;
9use datafusion_common::cast::as_list_array;
10use datafusion_common::utils::SingleRowListArrayBuilder;
11use datafusion_expr_common::accumulator::Accumulator;
12use datafusion_physical_expr_common::binary_map::{ArrowBytesSet, OutputType};
13use datafusion_physical_expr_common::binary_view_map::ArrowBytesViewSet;
14use std::fmt::Debug;
15use std::mem::size_of_val;
16
17/// Specialized implementation of
18/// `COUNT DISTINCT` for [`StringArray`] [`LargeStringArray`],
19/// [`BinaryArray`] and [`LargeBinaryArray`].
20///
21/// [`StringArray`]: arrow::array::StringArray
22/// [`LargeStringArray`]: arrow::array::LargeStringArray
23/// [`BinaryArray`]: arrow::array::BinaryArray
24/// [`LargeBinaryArray`]: arrow::array::LargeBinaryArray
25#[derive(Debug)]
26pub struct BytesDistinctCountAccumulator<O: OffsetSizeTrait>(ArrowBytesSet<O>);
27
28impl<O: OffsetSizeTrait> BytesDistinctCountAccumulator<O> {
29    /// The set deliberately does not pre-allocate. `GroupsAccumulatorAdapter`
30    /// creates one accumulator per group, so a grouped `COUNT(DISTINCT)` over a
31    /// high cardinality key holds hundreds of thousands of these at once and
32    /// most of them see only a handful of values.
33    ///
34    /// The ungrouped path builds one of these and grows it to hold every
35    /// distinct value in the input, so it is the caller that had a use for the
36    /// warm up. It loses nothing here: the set grows into exactly the
37    /// capacities a pre-allocated one reaches, which
38    /// `ungrouped_utf8_accumulator_is_never_worse_than_a_pre_allocated_set`
39    /// pins. That is why this constructor needs no signal distinguishing the
40    /// two callers.
41    pub fn new(output_type: OutputType) -> Self {
42        Self(ArrowBytesSet::new(output_type))
43    }
44}
45
46impl<O: OffsetSizeTrait> Accumulator for BytesDistinctCountAccumulator<O> {
47    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
48        let set = self.0.take();
49        let arr = set.into_state();
50        Ok(vec![
51            SingleRowListArrayBuilder::new(arr).build_list_scalar(),
52        ])
53    }
54
55    fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
56        if values.is_empty() {
57            return Ok(());
58        }
59
60        self.0.insert(&values[0]);
61
62        Ok(())
63    }
64
65    fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
66        if states.is_empty() {
67            return Ok(());
68        }
69        assert_eq!(
70            states.len(),
71            1,
72            "count_distinct states must be single array"
73        );
74
75        let arr = as_list_array(&states[0])?;
76        arr.iter().try_for_each(|maybe_list| {
77            if let Some(list) = maybe_list {
78                self.0.insert(&list);
79            }
80            Ok(())
81        })
82    }
83
84    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
85        Ok(ScalarValue::Int64(Some(self.0.non_null_len() as i64)))
86    }
87
88    fn size(&self) -> usize {
89        size_of_val(self) + self.0.size()
90    }
91}
92
93/// Specialized implementation of
94/// `COUNT DISTINCT` for [`StringViewArray`] and [`BinaryViewArray`].
95///
96/// [`StringViewArray`]: arrow::array::StringViewArray
97/// [`BinaryViewArray`]: arrow::array::BinaryViewArray
98#[derive(Debug)]
99pub struct BytesViewDistinctCountAccumulator(ArrowBytesViewSet);
100
101impl BytesViewDistinctCountAccumulator {
102    /// See [`BytesDistinctCountAccumulator::new`] for why the set does not
103    /// pre-allocate.
104    pub fn new(output_type: OutputType) -> Self {
105        Self(ArrowBytesViewSet::new(output_type))
106    }
107}
108
109impl Accumulator for BytesViewDistinctCountAccumulator {
110    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
111        let set = self.0.take();
112        let arr = set.into_state();
113        Ok(vec![
114            SingleRowListArrayBuilder::new(arr).build_list_scalar(),
115        ])
116    }
117
118    fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
119        if values.is_empty() {
120            return Ok(());
121        }
122
123        self.0.insert(&values[0]);
124
125        Ok(())
126    }
127
128    fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
129        if states.is_empty() {
130            return Ok(());
131        }
132        assert_eq!(
133            states.len(),
134            1,
135            "count_distinct states must be single array"
136        );
137
138        let arr = as_list_array(&states[0])?;
139        arr.iter().try_for_each(|maybe_list| {
140            if let Some(list) = maybe_list {
141                self.0.insert(&list);
142            }
143            Ok(())
144        })
145    }
146
147    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
148        Ok(ScalarValue::Int64(Some(self.0.non_null_len() as i64)))
149    }
150
151    fn size(&self) -> usize {
152        size_of_val(self) + self.0.size()
153    }
154}
155
156/// With `force_hash_collisions` every distinct value collides into the same
157/// hash bucket, so both `ArrowBytesSet`/`ArrowBytesViewSet` degrade to a
158/// linear scan per insert. These tests insert up to 500,000 distinct values
159/// per accumulator (twice, once lazily constructed and once pre-allocated),
160/// which is O(n) under a real hash and O(n^2) under a forced collision,
161/// turning a sub-second run into a multi-hour one and hanging CI (see
162/// apache/datafusion#25011). Skipped under that feature, matching the
163/// `count_distinct_spill` precedent in
164/// `datafusion/core/tests/memory_limit/mod.rs`.
165#[cfg(all(test, not(feature = "force_hash_collisions")))]
166mod tests {
167    use super::*;
168    use arrow::array::{StringArray, StringViewArray};
169    use datafusion_physical_expr_common::binary_map::INITIAL_MAP_CAPACITY;
170    use datafusion_physical_expr_common::binary_view_map::INITIAL_MAP_CAPACITY as INITIAL_VIEW_MAP_CAPACITY;
171    use std::sync::Arc;
172
173    /// The batch size the aggregate stream drives an ungrouped accumulator with.
174    const BATCH_SIZE: usize = 8192;
175
176    /// Distinct value counts spanning both sides of the warm up capacity, up to
177    /// ones where the two constructors have converged.
178    const CARDINALITIES: [usize; 7] = [0, 1, 100, 1_000, 10_000, 100_000, 500_000];
179
180    /// Cardinalities small enough that the warm up dominates what the set
181    /// holds. This is the per group population, where `GroupsAccumulatorAdapter`
182    /// holds one accumulator per group and most see a handful of values.
183    const PER_GROUP_SCALE: usize = 100;
184
185    /// Cardinalities at which a lazily built set has grown into exactly the
186    /// capacities a pre-allocated one reaches. This is the ungrouped
187    /// population, one set holding every distinct value in the input.
188    const UNGROUPED_SCALE: usize = 10_000;
189
190    /// Longer than the map's inline value length, so the value lands in the
191    /// value buffer rather than inside the hash table entry.
192    fn distinct_value(i: usize) -> String {
193        format!("distinct value number {i}")
194    }
195
196    fn batches(distinct_values: usize, view: bool) -> Vec<ArrayRef> {
197        (0..distinct_values)
198            .step_by(BATCH_SIZE)
199            .map(|start| {
200                let values = (start..(start + BATCH_SIZE).min(distinct_values))
201                    .map(distinct_value);
202                if view {
203                    Arc::new(StringViewArray::from_iter_values(values)) as ArrayRef
204                } else {
205                    Arc::new(StringArray::from_iter_values(values)) as ArrayRef
206                }
207            })
208            .collect()
209    }
210
211    /// The property that decides whether the ungrouped path can afford to share
212    /// the lazy constructor with the per group path.
213    fn assert_lazy_is_not_worse(
214        distinct_values: usize,
215        lazy_size: usize,
216        pre_allocated_size: usize,
217    ) {
218        // The guarantee that lets both paths share one lazy constructor.
219        assert!(
220            lazy_size <= pre_allocated_size,
221            "at {distinct_values} distinct values the lazy set reported \
222             {lazy_size} bytes against the {pre_allocated_size} bytes the \
223             pre-allocated one reported"
224        );
225
226        if distinct_values <= PER_GROUP_SCALE {
227            // The warm up is pure overhead here, and removing it is the whole
228            // point of the change.
229            assert!(
230                lazy_size < pre_allocated_size,
231                "at {distinct_values} distinct values the lazy set should be \
232                 strictly cheaper, but reported {lazy_size} bytes against \
233                 {pre_allocated_size}"
234            );
235        }
236
237        if distinct_values >= UNGROUPED_SCALE {
238            // The hash table's bucket count is a power of two fixed by the
239            // number of entries, and the value buffer grows on a power of two
240            // ladder, so a set that starts empty lands on exactly the
241            // capacities a pre-allocated one reaches. The ungrouped path gives
242            // up nothing by starting empty, which is why these accumulators
243            // need no signal telling them apart from the per group ones.
244            assert_eq!(
245                lazy_size, pre_allocated_size,
246                "at {distinct_values} distinct values the lazy and pre-allocated \
247                 sets should have converged"
248            );
249        }
250    }
251
252    /// An ungrouped `COUNT(DISTINCT <string>)` builds a single accumulator that
253    /// grows to hold every distinct value in its input, which is the population
254    /// the warm up existed for. It must be no more expensive without one.
255    #[test]
256    fn ungrouped_utf8_accumulator_is_never_worse_than_a_pre_allocated_set() {
257        for distinct_values in CARDINALITIES {
258            let mut accumulator =
259                BytesDistinctCountAccumulator::<i32>::new(OutputType::Utf8);
260            let mut pre_allocated = ArrowBytesSet::<i32>::with_capacity(
261                OutputType::Utf8,
262                INITIAL_MAP_CAPACITY,
263            );
264
265            for batch in batches(distinct_values, false) {
266                accumulator.update_batch(&[Arc::clone(&batch)]).unwrap();
267                pre_allocated.insert(&batch);
268            }
269
270            assert_eq!(accumulator.0.non_null_len(), distinct_values);
271            assert_lazy_is_not_worse(
272                distinct_values,
273                accumulator.0.size(),
274                pre_allocated.size(),
275            );
276        }
277    }
278
279    /// The `Utf8View` counterpart of
280    /// [`ungrouped_utf8_accumulator_is_never_worse_than_a_pre_allocated_set`].
281    #[test]
282    fn ungrouped_utf8_view_accumulator_is_never_worse_than_a_pre_allocated_set() {
283        for distinct_values in CARDINALITIES {
284            let mut accumulator =
285                BytesViewDistinctCountAccumulator::new(OutputType::Utf8View);
286            let mut pre_allocated = ArrowBytesViewSet::with_capacity(
287                OutputType::Utf8View,
288                INITIAL_VIEW_MAP_CAPACITY,
289            );
290
291            for batch in batches(distinct_values, true) {
292                accumulator.update_batch(&[Arc::clone(&batch)]).unwrap();
293                pre_allocated.insert(&batch);
294            }
295
296            assert_eq!(accumulator.0.non_null_len(), distinct_values);
297            assert_lazy_is_not_worse(
298                distinct_values,
299                accumulator.0.size(),
300                pre_allocated.size(),
301            );
302        }
303    }
304}