Skip to main content

datafusion_functions_aggregate_common/aggregate/groups_accumulator/
accumulate.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//! [`GroupsAccumulator`] helpers: [`NullState`] and [`accumulate_indices`]
6//!
7//! [`GroupsAccumulator`]: datafusion_expr_common::groups_accumulator::GroupsAccumulator
8
9use arrow::array::{Array, BooleanArray, BooleanBufferBuilder, PrimitiveArray};
10use arrow::buffer::NullBuffer;
11use arrow::datatypes::ArrowPrimitiveType;
12
13use crate::aggregate::groups_accumulator::nulls::filter_to_validity;
14use datafusion_common::Result;
15use datafusion_expr_common::groups_accumulator::{EmitTo, GroupSelection};
16
17/// If the input has nulls, then the accumulator must potentially
18/// handle each input null value specially (e.g. for `SUM` to mark the
19/// corresponding sum as null)
20///
21/// `NullState` tracks if it has seen *any* value for each group when filters or
22/// sparse group indices may omit input for a registered group.
23#[derive(Debug)]
24pub enum SeenValues {
25    /// All groups seen so far have seen at least one non-null value
26    All {
27        num_values: usize,
28    },
29    // Some groups have not yet seen a non-null value
30    Some {
31        values: BooleanBufferBuilder,
32    },
33}
34
35impl Default for SeenValues {
36    fn default() -> Self {
37        SeenValues::All { num_values: 0 }
38    }
39}
40
41impl SeenValues {
42    /// Return a mutable reference to the `BooleanBufferBuilder` in `SeenValues::Some`.
43    ///
44    /// If `self` is `SeenValues::All`, it is transitioned to `SeenValues::Some`
45    /// by creating a new `BooleanBufferBuilder` where the first `num_values` are true.
46    ///
47    /// The builder is then ensured to have at least `total_num_groups` length,
48    /// with any new entries initialized to false.
49    fn get_builder(&mut self, total_num_groups: usize) -> &mut BooleanBufferBuilder {
50        match self {
51            SeenValues::All { num_values } => {
52                let mut builder = BooleanBufferBuilder::new(total_num_groups);
53                builder.append_n(*num_values, true);
54                if total_num_groups > *num_values {
55                    builder.append_n(total_num_groups - *num_values, false);
56                }
57                *self = SeenValues::Some { values: builder };
58                match self {
59                    SeenValues::Some { values } => values,
60                    _ => unreachable!(),
61                }
62            }
63            SeenValues::Some { values } => {
64                if values.len() < total_num_groups {
65                    values.append_n(total_num_groups - values.len(), false);
66                }
67                values
68            }
69        }
70    }
71}
72
73/// Returns true when all newly registered groups are present in `group_indices`.
74///
75/// Group indices are assigned in first-seen order, so an unfiltered batch visits
76/// new groups in ascending order. Pre-filtered input can omit a new group, making
77/// the indices sparse even though the accumulator no longer receives a filter.
78fn new_groups_are_dense(
79    group_indices: &[usize],
80    first_new_group: usize,
81    total_num_groups: usize,
82) -> bool {
83    if first_new_group == total_num_groups {
84        return true;
85    }
86
87    let mut next_new_group = first_new_group;
88    for &group_index in group_indices {
89        if group_index == next_new_group {
90            next_new_group += 1;
91        } else if group_index > next_new_group {
92            return false;
93        }
94    }
95    next_new_group == total_num_groups
96}
97
98/// Track the accumulator null state per row: if any values for that
99/// group were null and if any values have been seen at all for that group.
100///
101/// This is part of the inner loop for many [`GroupsAccumulator`]s,
102/// and thus the performance is critical and so there are multiple
103/// specialized implementations, invoked depending on the specific
104/// combinations of the input.
105///
106/// Typically there are 4 potential combinations of inputs must be
107/// special cased for performance:
108///
109/// * With / Without filter
110/// * With / Without nulls in the input
111///
112/// If the input has nulls, then the accumulator must potentially
113/// handle each input null value specially (e.g. for `SUM` to mark the
114/// corresponding sum as null)
115///
116/// `NullState` tracks if it has seen *any* value for each group when filters or
117/// sparse group indices may omit input for a registered group.
118///
119/// [`GroupsAccumulator`]: datafusion_expr_common::groups_accumulator::GroupsAccumulator
120#[derive(Debug)]
121pub struct NullState {
122    /// Have we seen any non-filtered input values for `group_index`?
123    ///
124    /// If `seen_values` is `SeenValues::Some(buffer)` and buffer\[i\] is true, have seen at least one non null
125    /// value for group `i`
126    ///
127    /// If `seen_values` is `SeenValues::Some(buffer)` and buffer\[i\] is false, have not seen any values that
128    /// pass the filter yet for group `i`
129    ///
130    /// If `seen_values` is `SeenValues::All`, all groups have seen at least one non null value
131    seen_values: SeenValues,
132}
133
134impl Default for NullState {
135    fn default() -> Self {
136        Self::new()
137    }
138}
139
140impl NullState {
141    pub fn new() -> Self {
142        Self {
143            seen_values: SeenValues::All { num_values: 0 },
144        }
145    }
146
147    /// return the size of all buffers allocated by this null state, not including self
148    pub fn size(&self) -> usize {
149        match &self.seen_values {
150            SeenValues::All { .. } => 0,
151            SeenValues::Some { values } => values.capacity() / 8,
152        }
153    }
154
155    /// Invokes `value_fn(group_index, value)` for each non null, non
156    /// filtered value of `value`, while tracking which groups have
157    /// seen null inputs and which groups have seen any inputs if necessary
158    //
159    /// # Arguments:
160    ///
161    /// * `values`: the input arguments to the accumulator
162    /// * `group_indices`:  To which groups do the rows in `values` belong, (aka group_index)
163    /// * `opt_filter`: if present, only rows for which is Some(true) are included
164    /// * `value_fn`: function invoked for  (group_index, value) where value is non null
165    ///
166    /// See [`accumulate`], for more details on how value_fn is called
167    ///
168    /// When value_fn is called it also sets
169    ///
170    /// 1. `self.seen_values[group_index]` to true for all rows that had a non null value
171    pub fn accumulate<T, F>(
172        &mut self,
173        group_indices: &[usize],
174        values: &PrimitiveArray<T>,
175        opt_filter: Option<&BooleanArray>,
176        total_num_groups: usize,
177        mut value_fn: F,
178    ) where
179        T: ArrowPrimitiveType + Send,
180        F: FnMut(usize, T::Native) + Send,
181    {
182        // Skip per-value null handling when every input value is valid and all
183        // newly registered groups are represented. Pre-filtered inputs can have
184        // sparse group indices despite not passing a filter to the accumulator.
185        if opt_filter.is_none()
186            && values.null_count() == 0
187            && let SeenValues::All { num_values } = &mut self.seen_values
188            && new_groups_are_dense(group_indices, *num_values, total_num_groups)
189        {
190            accumulate(group_indices, values, None, value_fn);
191            *num_values = total_num_groups;
192            return;
193        }
194
195        let seen_values = self.seen_values.get_builder(total_num_groups);
196        accumulate(group_indices, values, opt_filter, |group_index, value| {
197            seen_values.set_bit(group_index, true);
198            value_fn(group_index, value);
199        });
200    }
201
202    /// Invokes `value_fn(group_index, value)` for each non null, non
203    /// filtered value in `values`, while tracking which groups have
204    /// seen null inputs and which groups have seen any inputs, for
205    /// [`BooleanArray`]s.
206    ///
207    /// Since `BooleanArray` is not a [`PrimitiveArray`] it must be
208    /// handled specially.
209    ///
210    /// See [`Self::accumulate`], which handles `PrimitiveArray`s, for
211    /// more details on other arguments.
212    pub fn accumulate_boolean<F>(
213        &mut self,
214        group_indices: &[usize],
215        values: &BooleanArray,
216        opt_filter: Option<&BooleanArray>,
217        total_num_groups: usize,
218        mut value_fn: F,
219    ) where
220        F: FnMut(usize, bool) + Send,
221    {
222        let data = values.values();
223        assert_eq!(data.len(), group_indices.len());
224
225        // Skip per-value null handling when every input value is valid and all
226        // newly registered groups are represented. Pre-filtered inputs can have
227        // sparse group indices despite not passing a filter to the accumulator.
228        if opt_filter.is_none()
229            && values.null_count() == 0
230            && let SeenValues::All { num_values } = &mut self.seen_values
231            && new_groups_are_dense(group_indices, *num_values, total_num_groups)
232        {
233            group_indices
234                .iter()
235                .zip(data.iter())
236                .for_each(|(&group_index, new_value)| value_fn(group_index, new_value));
237            *num_values = total_num_groups;
238
239            return;
240        }
241
242        let seen_values = self.seen_values.get_builder(total_num_groups);
243
244        // These could be made more performant by iterating in chunks of 64 bits at a time
245        match (values.null_count() > 0, opt_filter) {
246            // no nulls, no filter,
247            (false, None) => {
248                // if we have previously seen nulls, ensure the null
249                // buffer is big enough (start everything at valid)
250                group_indices.iter().zip(data.iter()).for_each(
251                    |(&group_index, new_value)| {
252                        seen_values.set_bit(group_index, true);
253                        value_fn(group_index, new_value)
254                    },
255                )
256            }
257            // nulls, no filter
258            (true, None) => {
259                let nulls = values.nulls().unwrap();
260                group_indices
261                    .iter()
262                    .zip(data.iter())
263                    .zip(nulls.iter())
264                    .for_each(|((&group_index, new_value), is_valid)| {
265                        if is_valid {
266                            seen_values.set_bit(group_index, true);
267                            value_fn(group_index, new_value);
268                        }
269                    })
270            }
271            // no nulls, but a filter
272            (false, Some(filter)) => {
273                assert_eq!(filter.len(), group_indices.len());
274
275                group_indices
276                    .iter()
277                    .zip(data.iter())
278                    .zip(filter.iter())
279                    .for_each(|((&group_index, new_value), filter_value)| {
280                        if filter_value == Some(true) {
281                            seen_values.set_bit(group_index, true);
282                            value_fn(group_index, new_value);
283                        }
284                    })
285            }
286            // both null values and filters
287            (true, Some(filter)) => {
288                assert_eq!(filter.len(), group_indices.len());
289                filter
290                    .iter()
291                    .zip(group_indices.iter())
292                    .zip(values.iter())
293                    .for_each(|((filter_value, &group_index), new_value)| {
294                        if filter_value == Some(true)
295                            && let Some(new_value) = new_value
296                        {
297                            seen_values.set_bit(group_index, true);
298                            value_fn(group_index, new_value)
299                        }
300                    })
301            }
302        }
303    }
304
305    /// Creates a [`NullBuffer`] for `selection` without changing this state.
306    pub fn build_preserving(
307        &self,
308        selection: GroupSelection<'_>,
309    ) -> Result<Option<NullBuffer>> {
310        let selected_len = selection.len();
311        match &self.seen_values {
312            SeenValues::All { num_values } => {
313                selection.validate_num_groups(*num_values)?;
314                Ok(None)
315            }
316            SeenValues::Some { values } => {
317                selection.validate_num_groups(values.len())?;
318                let mut selected = BooleanBufferBuilder::new(selected_len);
319                for index in selection.iter() {
320                    selected.append(values.get_bit(index));
321                }
322                Ok(Some(NullBuffer::new(selected.finish())))
323            }
324        }
325    }
326
327    /// Creates the a [`NullBuffer`] representing which group_indices
328    /// should have null values (because they never saw any values)
329    /// for the `emit_to` rows.
330    ///
331    /// resets the internal state appropriately
332    pub fn build(&mut self, emit_to: EmitTo) -> Option<NullBuffer> {
333        match emit_to {
334            EmitTo::All => {
335                let old_seen = std::mem::take(&mut self.seen_values);
336                match old_seen {
337                    SeenValues::All { .. } => None,
338                    SeenValues::Some { mut values } => {
339                        Some(NullBuffer::new(values.finish()))
340                    }
341                }
342            }
343            EmitTo::First(n) => match &mut self.seen_values {
344                SeenValues::All { num_values } => {
345                    *num_values = num_values.saturating_sub(n);
346                    None
347                }
348                SeenValues::Some { .. } => {
349                    let SeenValues::Some {
350                        values: mut old_values,
351                    } = std::mem::take(&mut self.seen_values)
352                    else {
353                        unreachable!()
354                    };
355                    let nulls = old_values.finish();
356                    let first_n_null = nulls.slice(0, n);
357                    let remainder = nulls.slice(n, nulls.len() - n);
358                    let mut new_builder = BooleanBufferBuilder::new(remainder.len());
359                    new_builder.append_buffer(&remainder);
360                    self.seen_values = SeenValues::Some {
361                        values: new_builder,
362                    };
363                    Some(NullBuffer::new(first_n_null))
364                }
365            },
366        }
367    }
368}
369
370/// Invokes `value_fn(group_index, value)` for each non null, non
371/// filtered value of `value`,
372///
373/// # Arguments:
374///
375/// * `group_indices`:  To which groups do the rows in `values` belong, (aka group_index)
376/// * `values`: the input arguments to the accumulator
377/// * `opt_filter`: if present, only rows for which is Some(true) are included
378/// * `value_fn`: function invoked for  (group_index, value) where value is non null
379///
380/// # Example
381///
382/// ```text
383///  ┌─────────┐   ┌─────────┐   ┌ ─ ─ ─ ─ ┐
384///  │ ┌─────┐ │   │ ┌─────┐ │     ┌─────┐
385///  │ │  2  │ │   │ │ 200 │ │   │ │  t  │ │
386///  │ ├─────┤ │   │ ├─────┤ │     ├─────┤
387///  │ │  2  │ │   │ │ 100 │ │   │ │  f  │ │
388///  │ ├─────┤ │   │ ├─────┤ │     ├─────┤
389///  │ │  0  │ │   │ │ 200 │ │   │ │  t  │ │
390///  │ ├─────┤ │   │ ├─────┤ │     ├─────┤
391///  │ │  1  │ │   │ │ 200 │ │   │ │NULL │ │
392///  │ ├─────┤ │   │ ├─────┤ │     ├─────┤
393///  │ │  0  │ │   │ │ 300 │ │   │ │  t  │ │
394///  │ └─────┘ │   │ └─────┘ │     └─────┘
395///  └─────────┘   └─────────┘   └ ─ ─ ─ ─ ┘
396///
397/// group_indices   values        opt_filter
398/// ```
399///
400/// In the example above, `value_fn` is invoked for each (group_index,
401/// value) pair where `opt_filter[i]` is true and values is non null
402///
403/// ```text
404/// value_fn(2, 200)
405/// value_fn(0, 200)
406/// value_fn(0, 300)
407/// ```
408pub fn accumulate<T, F>(
409    group_indices: &[usize],
410    values: &PrimitiveArray<T>,
411    opt_filter: Option<&BooleanArray>,
412    mut value_fn: F,
413) where
414    T: ArrowPrimitiveType + Send,
415    F: FnMut(usize, T::Native) + Send,
416{
417    let data: &[T::Native] = values.values();
418    assert_eq!(data.len(), group_indices.len());
419
420    match (values.null_count() > 0, opt_filter) {
421        // no nulls, no filter,
422        (false, None) => {
423            let iter = group_indices.iter().zip(data.iter());
424            for (&group_index, &new_value) in iter {
425                value_fn(group_index, new_value);
426            }
427        }
428        // nulls, no filter
429        (true, None) => {
430            let nulls = values.nulls().unwrap();
431            // This is based on (ahem, COPY/PASTE) arrow::compute::aggregate::sum
432            // iterate over in chunks of 64 bits for more efficient null checking
433            let (group_indices_chunks, group_indices_remainder) =
434                group_indices.as_chunks::<64>();
435            let (data_chunks, data_remainder) = data.as_chunks::<64>();
436            let bit_chunks = nulls.inner().bit_chunks();
437
438            group_indices_chunks
439                .iter()
440                .zip(data_chunks)
441                .zip(bit_chunks.iter())
442                .for_each(|((group_index_chunk, data_chunk), mask)| {
443                    // index_mask has value 1 << i in the loop
444                    let mut index_mask = 1;
445                    group_index_chunk.iter().zip(data_chunk.iter()).for_each(
446                        |(&group_index, &new_value)| {
447                            // valid bit was set, real value
448                            let is_valid = (mask & index_mask) != 0;
449                            if is_valid {
450                                value_fn(group_index, new_value);
451                            }
452                            index_mask <<= 1;
453                        },
454                    )
455                });
456
457            // handle any remaining bits (after the initial 64)
458            let remainder_bits = bit_chunks.remainder_bits();
459            group_indices_remainder
460                .iter()
461                .zip(data_remainder.iter())
462                .enumerate()
463                .for_each(|(i, (&group_index, &new_value))| {
464                    let is_valid = remainder_bits & (1 << i) != 0;
465                    if is_valid {
466                        value_fn(group_index, new_value);
467                    }
468                });
469        }
470        // no nulls, but a filter
471        (false, Some(filter)) => {
472            assert_eq!(filter.len(), group_indices.len());
473            // The performance with a filter could be improved by
474            // iterating over the filter in chunks, rather than a single
475            // iterator. TODO file a ticket
476            group_indices
477                .iter()
478                .zip(data.iter())
479                .zip(filter.iter())
480                .for_each(|((&group_index, &new_value), filter_value)| {
481                    if filter_value == Some(true) {
482                        value_fn(group_index, new_value);
483                    }
484                })
485        }
486        // both null values and filters
487        (true, Some(filter)) => {
488            assert_eq!(filter.len(), group_indices.len());
489            // The performance with a filter could be improved by
490            // iterating over the filter in chunks, rather than using
491            // iterators. TODO file a ticket
492            filter
493                .iter()
494                .zip(group_indices.iter())
495                .zip(values.iter())
496                .for_each(|((filter_value, &group_index), new_value)| {
497                    if filter_value == Some(true)
498                        && let Some(new_value) = new_value
499                    {
500                        value_fn(group_index, new_value)
501                    }
502                })
503        }
504    }
505}
506
507/// Accumulates with multiple accumulate(value) columns. (e.g. `corr(c1, c2)`)
508///
509/// This method assumes that for any input record index, if any of the value column
510/// is null, or it's filtered out by `opt_filter`, then the record would be ignored.
511/// (Won't be accumulated by `value_fn`)
512///
513/// # Arguments
514///
515/// * `group_indices` - To which groups do the rows in `value_columns` belong
516/// * `value_columns` - The input arrays to accumulate
517/// * `opt_filter` - Optional filter array. If present, only rows where filter is `Some(true)` are included
518/// * `value_fn` - Callback function for each valid row, with parameters:
519///     * `group_idx`: The group index for the current row
520///     * `batch_idx`: The index of the current row in the input arrays
521///     * `columns`: Reference to all input arrays for accessing values
522pub fn accumulate_multiple<T, F>(
523    group_indices: &[usize],
524    value_columns: &[&PrimitiveArray<T>],
525    opt_filter: Option<&BooleanArray>,
526    mut value_fn: F,
527) where
528    T: ArrowPrimitiveType + Send,
529    F: FnMut(usize, usize, &[&PrimitiveArray<T>]) + Send,
530{
531    for col in value_columns.iter() {
532        debug_assert_eq!(col.len(), group_indices.len());
533    }
534
535    // Start with rows where all value columns are non-null.
536    let mut valid_indices =
537        NullBuffer::union_many(value_columns.iter().map(|arr| arr.nulls()))
538            .map(NullBuffer::into_inner);
539
540    // Restrict to rows where the optional filter is Some(true). Keep the filter
541    // as a raw BooleanBuffer to avoid computing a NullBuffer null_count just to
542    // test row validity below.
543    if let Some(filter) = opt_filter {
544        debug_assert_eq!(filter.len(), group_indices.len());
545        let filter_validity = filter_to_validity(filter);
546        if let Some(valid_indices) = valid_indices.as_mut() {
547            *valid_indices &= &filter_validity;
548        } else {
549            valid_indices = Some(filter_validity);
550        }
551    }
552
553    match valid_indices {
554        None => {
555            for (batch_idx, &group_idx) in group_indices.iter().enumerate() {
556                value_fn(group_idx, batch_idx, value_columns);
557            }
558        }
559        Some(valid_indices) => {
560            for (batch_idx, &group_idx) in group_indices.iter().enumerate() {
561                if valid_indices.value(batch_idx) {
562                    value_fn(group_idx, batch_idx, value_columns);
563                }
564            }
565        }
566    }
567}
568
569/// This function is called to update the accumulator state per row
570/// when the value is not needed (e.g. COUNT)
571///
572/// `F`: Invoked like `value_fn(group_index) for all non null values
573/// passing the filter. Note that no tracking is done for null inputs
574/// or which groups have seen any values
575///
576/// See [`NullState::accumulate`], for more details on other
577/// arguments.
578pub fn accumulate_indices<F>(
579    group_indices: &[usize],
580    nulls: Option<&NullBuffer>,
581    opt_filter: Option<&BooleanArray>,
582    mut index_fn: F,
583) where
584    F: FnMut(usize) + Send,
585{
586    match (nulls, opt_filter) {
587        (None, None) => {
588            for &group_index in group_indices.iter() {
589                index_fn(group_index)
590            }
591        }
592        (None, Some(filter)) => {
593            debug_assert_eq!(filter.len(), group_indices.len());
594            let (group_indices_chunks, group_indices_remainder) =
595                group_indices.as_chunks::<64>();
596            let filter_validity = filter_to_validity(filter);
597            let bit_chunks = filter_validity.bit_chunks();
598
599            group_indices_chunks.iter().zip(bit_chunks.iter()).for_each(
600                |(group_index_chunk, mask)| {
601                    // index_mask has value 1 << i in the loop
602                    let mut index_mask = 1;
603                    for &group_index in group_index_chunk {
604                        // valid bit was set, real vale
605                        let is_valid = (mask & index_mask) != 0;
606                        if is_valid {
607                            index_fn(group_index);
608                        }
609                        index_mask <<= 1;
610                    }
611                },
612            );
613
614            // handle any remaining bits (after the initial 64)
615            let remainder_bits = bit_chunks.remainder_bits();
616            group_indices_remainder
617                .iter()
618                .enumerate()
619                .for_each(|(i, &group_index)| {
620                    let is_valid = remainder_bits & (1 << i) != 0;
621                    if is_valid {
622                        index_fn(group_index)
623                    }
624                });
625        }
626        (Some(valids), None) => {
627            debug_assert_eq!(valids.len(), group_indices.len());
628            // This is based on (ahem, COPY/PASTA) arrow::compute::aggregate::sum
629            // iterate over in chunks of 64 bits for more efficient null checking
630            let (group_indices_chunks, group_indices_remainder) =
631                group_indices.as_chunks::<64>();
632            let bit_chunks = valids.inner().bit_chunks();
633
634            group_indices_chunks.iter().zip(bit_chunks.iter()).for_each(
635                |(group_index_chunk, mask)| {
636                    // index_mask has value 1 << i in the loop
637                    let mut index_mask = 1;
638                    for &group_index in group_index_chunk {
639                        // valid bit was set, real vale
640                        let is_valid = (mask & index_mask) != 0;
641                        if is_valid {
642                            index_fn(group_index);
643                        }
644                        index_mask <<= 1;
645                    }
646                },
647            );
648
649            // handle any remaining bits (after the initial 64)
650            let remainder_bits = bit_chunks.remainder_bits();
651            group_indices_remainder
652                .iter()
653                .enumerate()
654                .for_each(|(i, &group_index)| {
655                    let is_valid = remainder_bits & (1 << i) != 0;
656                    if is_valid {
657                        index_fn(group_index)
658                    }
659                });
660        }
661
662        (Some(valids), Some(filter)) => {
663            debug_assert_eq!(filter.len(), group_indices.len());
664            debug_assert_eq!(valids.len(), group_indices.len());
665
666            let (group_indices_chunks, group_indices_remainder) =
667                group_indices.as_chunks::<64>();
668            let valid_bit_chunks = valids.inner().bit_chunks();
669            let filter_validity = filter_to_validity(filter);
670            let filter_bit_chunks = filter_validity.bit_chunks();
671
672            group_indices_chunks
673                .iter()
674                .zip(valid_bit_chunks.iter())
675                .zip(filter_bit_chunks.iter())
676                .for_each(|((group_index_chunk, valid_mask), filter_mask)| {
677                    // index_mask has value 1 << i in the loop
678                    let mut index_mask = 1;
679                    for &group_index in group_index_chunk {
680                        // valid bit was set, real vale
681                        let is_valid = (valid_mask & filter_mask & index_mask) != 0;
682                        if is_valid {
683                            index_fn(group_index);
684                        }
685                        index_mask <<= 1;
686                    }
687                });
688
689            // handle any remaining bits (after the initial 64)
690            let remainder_valid_bits = valid_bit_chunks.remainder_bits();
691            let remainder_filter_bits = filter_bit_chunks.remainder_bits();
692            group_indices_remainder
693                .iter()
694                .enumerate()
695                .for_each(|(i, &group_index)| {
696                    let is_valid =
697                        remainder_valid_bits & remainder_filter_bits & (1 << i) != 0;
698                    if is_valid {
699                        index_fn(group_index)
700                    }
701                });
702        }
703    }
704}
705
706#[cfg(test)]
707mod test {
708    use super::*;
709
710    use arrow::{
711        array::{Int32Array, UInt32Array},
712        buffer::BooleanBuffer,
713    };
714    use rand::{Rng, rngs::ThreadRng};
715    use std::collections::HashSet;
716
717    #[test]
718    fn accumulate() {
719        let group_indices = (0..100).collect();
720        let values = (0..100).map(|i| (i + 1) * 10).collect();
721        let values_with_nulls = (0..100)
722            .map(|i| if i % 3 == 0 { None } else { Some((i + 1) * 10) })
723            .collect();
724
725        // default to every fifth value being false, every even
726        // being null
727        let filter: BooleanArray = (0..100)
728            .map(|i| {
729                let is_even = i % 2 == 0;
730                let is_fifth = i % 5 == 0;
731                if is_even {
732                    None
733                } else if is_fifth {
734                    Some(false)
735                } else {
736                    Some(true)
737                }
738            })
739            .collect();
740
741        Fixture {
742            group_indices,
743            values,
744            values_with_nulls,
745            filter,
746        }
747        .run()
748    }
749
750    #[test]
751    fn accumulate_fuzz() {
752        let mut rng = rand::rng();
753        for _ in 0..100 {
754            Fixture::new_random(&mut rng).run();
755        }
756    }
757
758    /// Values for testing (there are enough values to exercise the 64 bit chunks
759    struct Fixture {
760        /// 100..0
761        group_indices: Vec<usize>,
762
763        /// 10, 20, ... 1010
764        values: Vec<u32>,
765
766        /// same as values, but every third is null:
767        /// None, Some(20), Some(30), None ...
768        values_with_nulls: Vec<Option<u32>>,
769
770        /// filter (defaults to None)
771        filter: BooleanArray,
772    }
773
774    impl Fixture {
775        fn new_random(rng: &mut ThreadRng) -> Self {
776            // Number of input values in a batch
777            let num_values: usize = rng.random_range(1..200);
778            // number of distinct groups
779            let num_groups: usize = rng.random_range(2..1000);
780            let max_group = num_groups - 1;
781
782            let group_indices: Vec<usize> = (0..num_values)
783                .map(|_| rng.random_range(0..max_group))
784                .collect();
785
786            let values: Vec<u32> = (0..num_values).map(|_| rng.random()).collect();
787
788            // 10% chance of false
789            // 10% change of null
790            // 80% chance of true
791            let filter: BooleanArray = (0..num_values)
792                .map(|_| {
793                    let filter_value = rng.random_range(0.0..1.0);
794                    if filter_value < 0.1 {
795                        Some(false)
796                    } else if filter_value < 0.2 {
797                        None
798                    } else {
799                        Some(true)
800                    }
801                })
802                .collect();
803
804            // random values with random number and location of nulls
805            // random null percentage
806            let null_pct: f32 = rng.random_range(0.0..1.0);
807            let values_with_nulls: Vec<Option<u32>> = (0..num_values)
808                .map(|_| {
809                    let is_null = null_pct < rng.random_range(0.0..1.0);
810                    if is_null { None } else { Some(rng.random()) }
811                })
812                .collect();
813
814            Self {
815                group_indices,
816                values,
817                values_with_nulls,
818                filter,
819            }
820        }
821
822        /// returns `Self::values` an Array
823        fn values_array(&self) -> UInt32Array {
824            UInt32Array::from(self.values.clone())
825        }
826
827        /// returns `Self::values_with_nulls` as an Array
828        fn values_with_nulls_array(&self) -> UInt32Array {
829            UInt32Array::from(self.values_with_nulls.clone())
830        }
831
832        /// Calls `NullState::accumulate` and `accumulate_indices`
833        /// with all combinations of nulls and filter values
834        fn run(&self) {
835            let total_num_groups = *self.group_indices.iter().max().unwrap() + 1;
836
837            let group_indices = &self.group_indices;
838            let values_array = self.values_array();
839            let values_with_nulls_array = self.values_with_nulls_array();
840            let filter = &self.filter;
841
842            // no null, no filters
843            Self::accumulate_test(group_indices, &values_array, None, total_num_groups);
844
845            // nulls, no filters
846            Self::accumulate_test(
847                group_indices,
848                &values_with_nulls_array,
849                None,
850                total_num_groups,
851            );
852
853            // no nulls, filters
854            Self::accumulate_test(
855                group_indices,
856                &values_array,
857                Some(filter),
858                total_num_groups,
859            );
860
861            // nulls, filters
862            Self::accumulate_test(
863                group_indices,
864                &values_with_nulls_array,
865                Some(filter),
866                total_num_groups,
867            );
868        }
869
870        /// Calls `NullState::accumulate` and `accumulate_indices` to
871        /// ensure it generates the correct values.
872        fn accumulate_test(
873            group_indices: &[usize],
874            values: &UInt32Array,
875            opt_filter: Option<&BooleanArray>,
876            total_num_groups: usize,
877        ) {
878            Self::accumulate_values_test(
879                group_indices,
880                values,
881                opt_filter,
882                total_num_groups,
883            );
884            Self::accumulate_indices_test(group_indices, values.nulls(), opt_filter);
885
886            // Convert values into a boolean array (anything above the
887            // average is true, otherwise false)
888            let avg: usize = values.iter().filter_map(|v| v.map(|v| v as usize)).sum();
889            let boolean_values: BooleanArray =
890                values.iter().map(|v| v.map(|v| v as usize > avg)).collect();
891            Self::accumulate_boolean_test(
892                group_indices,
893                &boolean_values,
894                opt_filter,
895                total_num_groups,
896            );
897        }
898
899        /// This is effectively a different implementation of
900        /// accumulate that we compare with the above implementation
901        fn accumulate_values_test(
902            group_indices: &[usize],
903            values: &UInt32Array,
904            opt_filter: Option<&BooleanArray>,
905            total_num_groups: usize,
906        ) {
907            let mut accumulated_values = vec![];
908            let mut null_state = NullState::new();
909
910            null_state.accumulate(
911                group_indices,
912                values,
913                opt_filter,
914                total_num_groups,
915                |group_index, value| {
916                    accumulated_values.push((group_index, value));
917                },
918            );
919
920            // Figure out the expected values
921            let mut expected_values = vec![];
922            let mut mock = MockNullState::new();
923
924            match opt_filter {
925                None => group_indices.iter().zip(values.iter()).for_each(
926                    |(&group_index, value)| {
927                        if let Some(value) = value {
928                            mock.saw_value(group_index);
929                            expected_values.push((group_index, value));
930                        }
931                    },
932                ),
933                Some(filter) => {
934                    group_indices
935                        .iter()
936                        .zip(values.iter())
937                        .zip(filter.iter())
938                        .for_each(|((&group_index, value), is_included)| {
939                            // if value passed filter
940                            if is_included == Some(true)
941                                && let Some(value) = value
942                            {
943                                mock.saw_value(group_index);
944                                expected_values.push((group_index, value));
945                            }
946                        });
947                }
948            }
949
950            assert_eq!(
951                accumulated_values, expected_values,
952                "\n\naccumulated_values:{accumulated_values:#?}\n\nexpected_values:{expected_values:#?}"
953            );
954
955            match &null_state.seen_values {
956                SeenValues::All { num_values } => {
957                    assert_eq!(*num_values, total_num_groups);
958                }
959                SeenValues::Some { values } => {
960                    let seen_values = values.finish_cloned();
961                    mock.validate_seen_values(&seen_values);
962                }
963            }
964
965            // Validate the final buffer (one value per group)
966            let expected_null_buffer = mock.expected_null_buffer(total_num_groups);
967
968            let null_buffer = null_state.build(EmitTo::All);
969            if let Some(nulls) = &null_buffer {
970                assert_eq!(*nulls, expected_null_buffer);
971            }
972        }
973
974        // Calls `accumulate_indices`
975        // and opt_filter and ensures it calls the right values
976        fn accumulate_indices_test(
977            group_indices: &[usize],
978            nulls: Option<&NullBuffer>,
979            opt_filter: Option<&BooleanArray>,
980        ) {
981            let mut accumulated_values = vec![];
982
983            accumulate_indices(group_indices, nulls, opt_filter, |group_index| {
984                accumulated_values.push(group_index);
985            });
986
987            // Figure out the expected values
988            let mut expected_values = vec![];
989
990            match (nulls, opt_filter) {
991                (None, None) => group_indices.iter().for_each(|&group_index| {
992                    expected_values.push(group_index);
993                }),
994                (Some(nulls), None) => group_indices.iter().zip(nulls.iter()).for_each(
995                    |(&group_index, is_valid)| {
996                        if is_valid {
997                            expected_values.push(group_index);
998                        }
999                    },
1000                ),
1001                (None, Some(filter)) => group_indices.iter().zip(filter.iter()).for_each(
1002                    |(&group_index, is_included)| {
1003                        if is_included == Some(true) {
1004                            expected_values.push(group_index);
1005                        }
1006                    },
1007                ),
1008                (Some(nulls), Some(filter)) => {
1009                    group_indices
1010                        .iter()
1011                        .zip(nulls.iter())
1012                        .zip(filter.iter())
1013                        .for_each(|((&group_index, is_valid), is_included)| {
1014                            // if value passed filter
1015                            if is_valid && is_included == Some(true) {
1016                                expected_values.push(group_index);
1017                            }
1018                        });
1019                }
1020            }
1021
1022            assert_eq!(
1023                accumulated_values, expected_values,
1024                "\n\naccumulated_values:{accumulated_values:#?}\n\nexpected_values:{expected_values:#?}"
1025            );
1026        }
1027
1028        /// This is effectively a different implementation of
1029        /// accumulate_boolean that we compare with the above implementation
1030        fn accumulate_boolean_test(
1031            group_indices: &[usize],
1032            values: &BooleanArray,
1033            opt_filter: Option<&BooleanArray>,
1034            total_num_groups: usize,
1035        ) {
1036            let mut accumulated_values = vec![];
1037            let mut null_state = NullState::new();
1038
1039            null_state.accumulate_boolean(
1040                group_indices,
1041                values,
1042                opt_filter,
1043                total_num_groups,
1044                |group_index, value| {
1045                    accumulated_values.push((group_index, value));
1046                },
1047            );
1048
1049            // Figure out the expected values
1050            let mut expected_values = vec![];
1051            let mut mock = MockNullState::new();
1052
1053            match opt_filter {
1054                None => group_indices.iter().zip(values.iter()).for_each(
1055                    |(&group_index, value)| {
1056                        if let Some(value) = value {
1057                            mock.saw_value(group_index);
1058                            expected_values.push((group_index, value));
1059                        }
1060                    },
1061                ),
1062                Some(filter) => {
1063                    group_indices
1064                        .iter()
1065                        .zip(values.iter())
1066                        .zip(filter.iter())
1067                        .for_each(|((&group_index, value), is_included)| {
1068                            // if value passed filter
1069                            if is_included == Some(true)
1070                                && let Some(value) = value
1071                            {
1072                                mock.saw_value(group_index);
1073                                expected_values.push((group_index, value));
1074                            }
1075                        });
1076                }
1077            }
1078
1079            assert_eq!(
1080                accumulated_values, expected_values,
1081                "\n\naccumulated_values:{accumulated_values:#?}\n\nexpected_values:{expected_values:#?}"
1082            );
1083
1084            match &null_state.seen_values {
1085                SeenValues::All { num_values } => {
1086                    assert_eq!(*num_values, total_num_groups);
1087                }
1088                SeenValues::Some { values } => {
1089                    let seen_values = values.finish_cloned();
1090                    mock.validate_seen_values(&seen_values);
1091                }
1092            }
1093
1094            // Validate the final buffer (one value per group)
1095            let expected_null_buffer = Some(mock.expected_null_buffer(total_num_groups));
1096
1097            let is_all_seen = matches!(null_state.seen_values, SeenValues::All { .. });
1098            let null_buffer = null_state.build(EmitTo::All);
1099
1100            if !is_all_seen {
1101                assert_eq!(null_buffer, expected_null_buffer);
1102            }
1103        }
1104    }
1105
1106    /// Parallel implementation of NullState to check expected values
1107    #[derive(Debug, Default)]
1108    struct MockNullState {
1109        /// group indices that had values that passed the filter
1110        seen_values: HashSet<usize>,
1111    }
1112
1113    impl MockNullState {
1114        fn new() -> Self {
1115            Default::default()
1116        }
1117
1118        fn saw_value(&mut self, group_index: usize) {
1119            self.seen_values.insert(group_index);
1120        }
1121
1122        /// did this group index see any input?
1123        fn expected_seen(&self, group_index: usize) -> bool {
1124            self.seen_values.contains(&group_index)
1125        }
1126
1127        /// Validate that the seen_values matches self.seen_values
1128        fn validate_seen_values(&self, seen_values: &BooleanBuffer) {
1129            for (group_index, is_seen) in seen_values.iter().enumerate() {
1130                let expected_seen = self.expected_seen(group_index);
1131                assert_eq!(
1132                    expected_seen, is_seen,
1133                    "mismatch at for group {group_index}"
1134                );
1135            }
1136        }
1137
1138        /// Create the expected null buffer based on if the input had nulls and a filter
1139        fn expected_null_buffer(&self, total_num_groups: usize) -> NullBuffer {
1140            (0..total_num_groups)
1141                .map(|group_index| self.expected_seen(group_index))
1142                .collect()
1143        }
1144    }
1145
1146    #[test]
1147    fn test_accumulate_multiple_no_nulls_no_filter() {
1148        let group_indices = vec![0, 1, 0, 1];
1149        let values1 = Int32Array::from(vec![1, 2, 3, 4]);
1150        let values2 = Int32Array::from(vec![10, 20, 30, 40]);
1151        let value_columns = [values1, values2];
1152
1153        let mut accumulated = vec![];
1154        accumulate_multiple(
1155            &group_indices,
1156            &value_columns.iter().collect::<Vec<_>>(),
1157            None,
1158            |group_idx, batch_idx, columns| {
1159                let values = columns.iter().map(|col| col.value(batch_idx)).collect();
1160                accumulated.push((group_idx, values));
1161            },
1162        );
1163
1164        let expected = vec![
1165            (0, vec![1, 10]),
1166            (1, vec![2, 20]),
1167            (0, vec![3, 30]),
1168            (1, vec![4, 40]),
1169        ];
1170        assert_eq!(accumulated, expected);
1171    }
1172
1173    #[test]
1174    fn test_accumulate_multiple_with_nulls() {
1175        let group_indices = vec![0, 1, 0, 1];
1176        let values1 = Int32Array::from(vec![Some(1), None, Some(3), Some(4)]);
1177        let values2 = Int32Array::from(vec![Some(10), Some(20), None, Some(40)]);
1178        let value_columns = [values1, values2];
1179
1180        let mut accumulated = vec![];
1181        accumulate_multiple(
1182            &group_indices,
1183            &value_columns.iter().collect::<Vec<_>>(),
1184            None,
1185            |group_idx, batch_idx, columns| {
1186                let values = columns.iter().map(|col| col.value(batch_idx)).collect();
1187                accumulated.push((group_idx, values));
1188            },
1189        );
1190
1191        // Only rows where both columns are non-null should be accumulated
1192        let expected = vec![(0, vec![1, 10]), (1, vec![4, 40])];
1193        assert_eq!(accumulated, expected);
1194    }
1195
1196    #[test]
1197    fn test_accumulate_multiple_with_filter() {
1198        let group_indices = vec![0, 1, 0, 1];
1199        let values1 = Int32Array::from(vec![1, 2, 3, 4]);
1200        let values2 = Int32Array::from(vec![10, 20, 30, 40]);
1201        let value_columns = [values1, values2];
1202
1203        let filter = BooleanArray::from(vec![true, false, true, false]);
1204
1205        let mut accumulated = vec![];
1206        accumulate_multiple(
1207            &group_indices,
1208            &value_columns.iter().collect::<Vec<_>>(),
1209            Some(&filter),
1210            |group_idx, batch_idx, columns| {
1211                let values = columns.iter().map(|col| col.value(batch_idx)).collect();
1212                accumulated.push((group_idx, values));
1213            },
1214        );
1215
1216        // Only rows where filter is true should be accumulated
1217        let expected = vec![(0, vec![1, 10]), (0, vec![3, 30])];
1218        assert_eq!(accumulated, expected);
1219    }
1220
1221    #[test]
1222    fn test_accumulate_indices_with_null_filter() {
1223        let group_indices = vec![0, 1, 0, 1];
1224        let filter = BooleanArray::new(
1225            BooleanBuffer::from(vec![true, true, true, false]),
1226            Some(NullBuffer::from(vec![true, false, true, true])),
1227        );
1228
1229        let mut accumulated = vec![];
1230        accumulate_indices(&group_indices, None, Some(&filter), |group_idx| {
1231            accumulated.push(group_idx);
1232        });
1233
1234        // A NULL filter value should be treated the same as false, even if the
1235        // underlying BooleanBuffer value is true.
1236        let expected = vec![0, 0];
1237        assert_eq!(accumulated, expected);
1238
1239        let value_validity = NullBuffer::from(vec![true, true, false, true]);
1240        let mut accumulated = vec![];
1241        accumulate_indices(
1242            &group_indices,
1243            Some(&value_validity),
1244            Some(&filter),
1245            |group_idx| {
1246                accumulated.push(group_idx);
1247            },
1248        );
1249
1250        let expected = vec![0];
1251        assert_eq!(accumulated, expected);
1252    }
1253
1254    #[test]
1255    fn test_accumulate_multiple_with_null_filter() {
1256        let group_indices = vec![0, 1, 0, 1];
1257        let values1 = Int32Array::from(vec![1, 2, 3, 4]);
1258        let values2 = Int32Array::from(vec![10, 20, 30, 40]);
1259        let value_columns = [values1, values2];
1260
1261        let filter = BooleanArray::new(
1262            BooleanBuffer::from(vec![true, true, true, false]),
1263            Some(NullBuffer::from(vec![true, false, true, true])),
1264        );
1265
1266        let mut accumulated = vec![];
1267        accumulate_multiple(
1268            &group_indices,
1269            &value_columns.iter().collect::<Vec<_>>(),
1270            Some(&filter),
1271            |group_idx, batch_idx, columns| {
1272                let values = columns.iter().map(|col| col.value(batch_idx)).collect();
1273                accumulated.push((group_idx, values));
1274            },
1275        );
1276
1277        // A NULL filter value should be treated the same as false, even if the
1278        // underlying BooleanBuffer value is true.
1279        let expected = vec![(0, vec![1, 10]), (0, vec![3, 30])];
1280        assert_eq!(accumulated, expected);
1281    }
1282
1283    #[test]
1284    fn test_accumulate_multiple_with_nulls_and_filter() {
1285        let group_indices = vec![0, 1, 0, 1];
1286        let values1 = Int32Array::from(vec![Some(1), None, Some(3), Some(4)]);
1287        let values2 = Int32Array::from(vec![Some(10), Some(20), None, Some(40)]);
1288        let value_columns = [values1, values2];
1289
1290        let filter = BooleanArray::from(vec![true, true, true, false]);
1291
1292        let mut accumulated = vec![];
1293        accumulate_multiple(
1294            &group_indices,
1295            &value_columns.iter().collect::<Vec<_>>(),
1296            Some(&filter),
1297            |group_idx, batch_idx, columns| {
1298                let values = columns.iter().map(|col| col.value(batch_idx)).collect();
1299                accumulated.push((group_idx, values));
1300            },
1301        );
1302
1303        // Only rows where both:
1304        // 1. Filter is true
1305        // 2. Both columns are non-null
1306        // should be accumulated
1307        let expected = [(0, vec![1, 10])];
1308        assert_eq!(accumulated, expected);
1309    }
1310}