Repository navigation
Expand file tree
/
Copy patharray_agg.rs
More file actions
5082 lines (4361 loc) · 178 KB
/
Copy patharray_agg.rs
File metadata and controls
5082 lines (4361 loc) · 178 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
//! `ARRAY_AGG` aggregate implementation: [`ArrayAgg`]
use std::collections::VecDeque;
use std::hash::BuildHasher;
use std::mem::{size_of, size_of_val, take};
use std::ops::Range;
use std::sync::Arc;
use arrow::array::{
Array, ArrayRef, AsArray, BooleanArray, ListArray, NullBufferBuilder, StructArray,
UInt32Array, make_array, new_empty_array,
};
use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
use arrow::compute::{SortOptions, cast, filter, take as take_array};
use arrow::datatypes::{DataType, Field, FieldRef, Fields};
use arrow::row::{OwnedRow, Row, RowConverter, Rows, SortField};
use arrow_select::dictionary::garbage_collect_any_dictionary;
use datafusion_common::cast::as_list_array;
use datafusion_common::hash_utils::{RandomState, create_hashes};
use datafusion_common::scalar::copy_array_data;
use datafusion_common::utils::map_dictionary_values;
use datafusion_common::utils::memory::estimate_memory_size;
use datafusion_common::utils::proxy::HashTableAllocExt;
use datafusion_common::utils::{SingleRowListArrayBuilder, offset_span};
use datafusion_common::{
HashMap, HashSet, Result, ScalarValue, assert_eq_or_internal_err, exec_err,
internal_datafusion_err, internal_err,
};
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::utils::format_state_name;
use datafusion_expr::{
Accumulator, AggregateMetric, AggregateMetricRecorder, AggregateMetrics,
AggregateUDFImpl, Documentation, EmitTo, GroupsAccumulator, Signature, Volatility,
};
use datafusion_functions_aggregate_common::aggregate::groups_accumulator::nulls::filter_to_nulls;
use datafusion_functions_aggregate_common::order::AggregateOrderSensitivity;
use datafusion_functions_aggregate_common::utils::ordering_fields;
use datafusion_macros::user_doc;
use datafusion_physical_expr_common::sort_expr::LexOrdering;
use hashbrown::hash_table::HashTable;
use itertools::{Either, Itertools};
make_udaf_expr_and_func!(
ArrayAgg,
array_agg,
expression,
"input values, including nulls, concatenated into an array",
array_agg_udaf
);
#[user_doc(
doc_section(label = "General Functions"),
description = r#"Returns an array created from the expression elements. If ordering is required, elements are inserted in the specified order.
This aggregation function can only mix DISTINCT and ORDER BY if the ordering expression is exactly the same as the argument expression."#,
syntax_example = "array_agg(expression [ORDER BY expression])",
sql_example = r#"
```sql
> SELECT array_agg(column_name ORDER BY other_column) FROM table_name;
+-----------------------------------------------+
| array_agg(column_name ORDER BY other_column) |
+-----------------------------------------------+
| [element1, element2, element3] |
+-----------------------------------------------+
> SELECT array_agg(DISTINCT column_name ORDER BY column_name) FROM table_name;
+--------------------------------------------------------+
| array_agg(DISTINCT column_name ORDER BY column_name) |
+--------------------------------------------------------+
| [element1, element2, element3] |
+--------------------------------------------------------+
```
"#,
standard_argument(name = "expression",)
)]
#[derive(Debug, PartialEq, Eq, Hash)]
/// ARRAY_AGG aggregate expression
pub struct ArrayAgg {
signature: Signature,
is_input_pre_ordered: bool,
}
impl Default for ArrayAgg {
fn default() -> Self {
Self {
signature: Signature::any(1, Volatility::Immutable),
is_input_pre_ordered: false,
}
}
}
impl AggregateUDFImpl for ArrayAgg {
fn name(&self) -> &str {
"array_agg"
}
fn signature(&self) -> &Signature {
&self.signature
}
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
Ok(DataType::List(Arc::new(Field::new_list_field(
arg_types[0].clone(),
true,
))))
}
fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
if args.is_distinct {
return Ok(vec![
Field::new_list(
format_state_name(args.name, "distinct_array_agg"),
// See COMMENTS.md to understand why nullable is set to true
Field::new_list_field(args.input_fields[0].data_type().clone(), true),
true,
)
.into(),
]);
}
let mut fields = vec![
Field::new_list(
format_state_name(args.name, "array_agg"),
// See COMMENTS.md to understand why nullable is set to true
Field::new_list_field(args.input_fields[0].data_type().clone(), true),
true,
)
.into(),
];
if args.ordering_fields.is_empty() {
return Ok(fields);
}
let orderings = args.ordering_fields.to_vec();
fields.push(
Field::new_list(
format_state_name(args.name, "array_agg_orderings"),
Field::new_list_field(DataType::Struct(Fields::from(orderings)), true),
false,
)
.into(),
);
Ok(fields)
}
fn order_sensitivity(&self) -> AggregateOrderSensitivity {
AggregateOrderSensitivity::SoftRequirement
}
fn with_beneficial_ordering(
self: Arc<Self>,
beneficial_ordering: bool,
) -> Result<Option<Arc<dyn AggregateUDFImpl>>> {
Ok(Some(Arc::new(Self {
signature: self.signature.clone(),
is_input_pre_ordered: beneficial_ordering,
})))
}
fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
let field = &acc_args.expr_fields[0];
let data_type = field.data_type();
let ignore_nulls = acc_args.ignore_nulls && field.is_nullable();
if acc_args.is_distinct {
return Ok(Box::new(DistinctArrayAggAccumulator::try_new(
data_type,
distinct_sort_options(&acc_args)?,
ignore_nulls,
)?));
}
let Some(ordering) = LexOrdering::new(acc_args.order_bys.to_vec()) else {
return Ok(Box::new(ArrayAggAccumulator::try_new(
data_type,
ignore_nulls,
)?));
};
let ordering_dtypes = ordering
.iter()
.map(|e| e.expr.data_type(acc_args.schema))
.collect::<Result<Vec<_>>>()?;
OrderSensitiveArrayAggAccumulator::try_new(
data_type,
&ordering_dtypes,
&ordering,
self.is_input_pre_ordered,
acc_args.is_reversed,
ignore_nulls,
)
.map(|acc| Box::new(acc) as _)
}
fn reverse_expr(&self) -> datafusion_expr::ReversedUDAF {
datafusion_expr::ReversedUDAF::Reversed(array_agg_udaf())
}
fn groups_accumulator_supported(&self, args: AccumulatorArgs) -> bool {
if args.is_distinct {
distinct_sort_options(&args).is_ok()
} else {
args.order_bys.is_empty()
}
}
fn create_groups_accumulator(
&self,
args: AccumulatorArgs,
) -> Result<Box<dyn GroupsAccumulator>> {
let field = &args.expr_fields[0];
let data_type = field.data_type().clone();
let ignore_nulls = args.ignore_nulls && field.is_nullable();
if args.is_distinct {
return Ok(Box::new(DistinctArrayAggGroupsAccumulator::new(
data_type,
distinct_sort_options(&args)?,
ignore_nulls,
)));
}
Ok(Box::new(ArrayAggGroupsAccumulator::new(
data_type,
ignore_nulls,
)))
}
fn supports_null_handling_clause(&self) -> bool {
true
}
fn documentation(&self) -> Option<&Documentation> {
self.doc()
}
}
#[derive(Debug)]
pub struct ArrayAggAccumulator {
values: VecDeque<ArrayRef>,
datatype: DataType,
ignore_nulls: bool,
/// Number of elements already consumed (retracted) from the front array.
/// Used by sliding window frames to avoid copying on partial retract.
front_offset: usize,
}
impl ArrayAggAccumulator {
/// new array_agg accumulator based on given item data type
pub fn try_new(datatype: &DataType, ignore_nulls: bool) -> Result<Self> {
Ok(Self {
values: VecDeque::new(),
datatype: datatype.clone(),
ignore_nulls,
front_offset: 0,
})
}
/// This function will return the underlying list array values if all valid values are consecutive without gaps (i.e. no null value point to a non-empty list)
/// If there are gaps but only in the end of the list array, the function will return the values without the null values in the end
fn get_optional_values_to_merge_as_is(list_array: &ListArray) -> Option<ArrayRef> {
let offsets = list_array.offsets();
let null_count = list_array.null_count();
// If no nulls than just use the fast path
// This is ok as the state is a ListArray rather than a ListViewArray so all the values are consecutive
if null_count == 0 {
// According to Arrow specification, the first offset can be non-zero
let (start, len) = offset_span(offsets);
let list_values = list_array.values().slice(start, len);
return Some(list_values);
}
// If all the values are null than just return an empty values array
if list_array.null_count() == list_array.len() {
return Some(list_array.values().slice(0, 0));
}
// According to the Arrow spec, null values can point to non-empty lists
// So this will check if all null values starting from the first valid value to the last one point to a 0 length list so we can just slice the underlying value
// Unwrapping is safe as we just checked if there is a null value
let nulls = list_array.nulls().unwrap();
let mut valid_slices_iter = nulls.valid_slices();
// This is safe as we validated that there is at least 1 valid value in the array
let (start, end) = valid_slices_iter.next().unwrap();
let start_offset = offsets[start];
// End is exclusive, so it already point to the last offset value
// This is valid as the length of the array is always 1 less than the length of the offsets
let mut end_offset_of_last_valid_value = offsets[end];
for (start, end) in valid_slices_iter {
// If there is a null value that point to a non-empty list than the start offset of the valid value
// will be different that the end offset of the last valid value
if offsets[start] != end_offset_of_last_valid_value {
return None;
}
// End is exclusive, so it already point to the last offset value
// This is valid as the length of the array is always 1 less than the length of the offsets
end_offset_of_last_valid_value = offsets[end];
}
let consecutive_valid_values = list_array.values().slice(
start_offset as usize,
(end_offset_of_last_valid_value - start_offset) as usize,
);
Some(consecutive_valid_values)
}
}
/// Returns the sort options for `ARRAY_AGG(DISTINCT ...)`, or an error if the
/// ORDER BY cannot be combined with DISTINCT.
///
/// Limitation similar to Postgres. The aggregation function can only mix
/// DISTINCT and ORDER BY if all the expressions in the ORDER BY appear
/// also in the arguments of the function. This implies that if the
/// aggregation function only accepts one argument, only one argument
/// can be used in the ORDER BY, For example:
///
/// ARRAY_AGG(DISTINCT col)
///
/// can only be mixed with an ORDER BY if the order expression is "col".
///
/// ARRAY_AGG(DISTINCT col ORDER BY col) <- Valid
/// ARRAY_AGG(DISTINCT concat(col, '') ORDER BY concat(col, '')) <- Valid
/// ARRAY_AGG(DISTINCT col ORDER BY other_col) <- Invalid
/// ARRAY_AGG(DISTINCT col ORDER BY concat(col, '')) <- Invalid
///
/// The DISTINCT accumulators sort the values themselves, so a reversed
/// aggregate must still sort them in the requested order.
fn distinct_sort_options(acc_args: &AccumulatorArgs) -> Result<Option<SortOptions>> {
match acc_args.order_bys {
[single] if single.expr.eq(&acc_args.exprs[0]) => {
Ok(Some(if acc_args.is_reversed {
!single.options
} else {
single.options
}))
}
[] => Ok(None),
_ => exec_err!(
"In an aggregate with DISTINCT, ORDER BY expressions must appear in argument list"
),
}
}
/// Returns the mask of non-null rows in `values` when `ignore_nulls` is set
/// and some row is null.
fn non_null_mask(values: &dyn Array, ignore_nulls: bool) -> Option<BooleanArray> {
if !ignore_nulls {
return None;
}
let nulls = values.logical_nulls()?;
if nulls.null_count() == 0 {
return None;
}
// The validity bitmap is the keep mask: a row is kept when it is valid.
Some(BooleanArray::new(nulls.into_inner(), None))
}
impl Accumulator for ArrayAggAccumulator {
fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
// Append value like Int64Array(1,2,3)
if values.is_empty() {
return Ok(());
}
assert_eq_or_internal_err!(values.len(), 1, "expects single batch");
let val = &values[0];
let nulls = if self.ignore_nulls {
val.logical_nulls()
} else {
None
};
let val = match nulls {
Some(nulls) if nulls.null_count() >= val.len() => return Ok(()),
Some(nulls) => filter(val, &BooleanArray::new(nulls.inner().clone(), None))?,
None => Arc::clone(val),
};
if !val.is_empty() {
self.values.push_back(val)
}
Ok(())
}
fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
// Append value like ListArray(Int64Array(1,2,3), Int64Array(4,5,6))
if states.is_empty() {
return Ok(());
}
assert_eq_or_internal_err!(states.len(), 1, "expects single state");
let list_arr = as_list_array(&states[0])?;
match Self::get_optional_values_to_merge_as_is(list_arr) {
Some(values) => {
// Make sure we don't insert empty lists
if !values.is_empty() {
self.values.push_back(values);
}
}
None => {
for arr in list_arr.iter().flatten() {
self.values.push_back(arr);
}
}
}
Ok(())
}
fn state(&mut self) -> Result<Vec<ScalarValue>> {
Ok(vec![self.evaluate()?])
}
fn evaluate(&mut self) -> Result<ScalarValue> {
if self.values.is_empty() {
return Ok(ScalarValue::new_null_list(self.datatype.clone(), true, 1));
}
let element_arrays: Vec<ArrayRef> = self
.values
.iter()
.enumerate()
.map(|(i, a)| {
if i == 0 && self.front_offset > 0 {
a.slice(self.front_offset, a.len() - self.front_offset)
} else {
Arc::clone(a)
}
})
.collect();
let element_refs: Vec<&dyn Array> =
element_arrays.iter().map(|a| a.as_ref()).collect();
if element_refs.iter().all(|a| a.is_empty()) {
return Ok(ScalarValue::new_null_list(self.datatype.clone(), true, 1));
}
let concated_array = arrow::compute::concat(&element_refs)?;
Ok(SingleRowListArrayBuilder::new(concated_array).build_list_scalar())
}
fn retract_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
if values.is_empty() {
return Ok(());
}
assert_eq_or_internal_err!(values.len(), 1, "expects single batch");
let val = &values[0];
let mut to_retract = if self.ignore_nulls {
val.len() - val.logical_null_count()
} else {
val.len()
};
while to_retract > 0 {
let Some(front) = self.values.front() else {
break;
};
let available = front.len() - self.front_offset;
if to_retract >= available {
self.values.pop_front();
to_retract -= available;
self.front_offset = 0;
} else {
self.front_offset += to_retract;
to_retract = 0;
}
}
Ok(())
}
fn supports_retract_batch(&self) -> bool {
true
}
fn size(&self) -> usize {
size_of_val(self)
+ (size_of::<ArrayRef>() * self.values.capacity())
+ self
.values
.iter()
// Each ArrayRef might be just a reference to a bigger array, and many
// ArrayRefs here might be referencing exactly the same array, so if we
// were to call `arr.get_array_memory_size()`, we would be double-counting
// the same underlying data many times.
//
// Instead, we do an approximation by estimating how much memory each
// ArrayRef would occupy if its underlying data was fully owned by this
// accumulator.
//
// Note that this is just an estimation, but the reality is that this
// accumulator might not own any data.
.map(|arr| arr.to_data().get_slice_memory_size().unwrap_or_default())
.sum::<usize>()
+ self.datatype.size()
- size_of_val(&self.datatype)
}
}
#[derive(Debug)]
struct ArrayAggGroupsAccumulator {
datatype: DataType,
ignore_nulls: bool,
/// Source arrays — input arrays (from update_batch) or list backing
/// arrays (from merge_batch).
batches: Vec<ArrayRef>,
/// Per-batch list of (group_idx, row_idx) pairs.
batch_entries: Vec<Vec<(u32, u32)>>,
/// Total number of groups tracked.
num_groups: usize,
}
impl ArrayAggGroupsAccumulator {
fn new(datatype: DataType, ignore_nulls: bool) -> Self {
Self {
datatype,
ignore_nulls,
batches: Vec::new(),
batch_entries: Vec::new(),
num_groups: 0,
}
}
fn clear_state(&mut self) {
// `size()` measures Vec capacity rather than len, so allocate new
// buffers instead of using `clear()`.
self.batches = Vec::new();
self.batch_entries = Vec::new();
self.num_groups = 0;
}
fn compact_retained_state(&mut self, emit_groups: usize) -> Result<()> {
// EmitTo::First is used to recover from memory pressure. Simply
// removing emitted entries in place is not enough because mixed batches
// would continue to pin their original Array arrays, even if only a few
// retained rows remain.
//
// Rebuild the retained state from scratch so fully emitted batches are
// dropped, mixed batches are compacted to arrays containing only the
// surviving rows, and retained metadata is right-sized.
let emit_groups = emit_groups as u32;
let old_batches = take(&mut self.batches);
let old_batch_entries = take(&mut self.batch_entries);
let mut batches = Vec::new();
let mut batch_entries = Vec::new();
for (batch, entries) in old_batches.into_iter().zip(old_batch_entries) {
let retained_len = entries.iter().filter(|(g, _)| *g >= emit_groups).count();
if retained_len == 0 {
continue;
}
if retained_len == entries.len() {
// Nothing was emitted from this batch, so we keep the existing
// array and only renumber the remaining group IDs so that they
// start from 0.
let mut retained_entries = entries;
for (g, _) in &mut retained_entries {
*g -= emit_groups;
}
retained_entries.shrink_to_fit();
batches.push(batch);
batch_entries.push(retained_entries);
continue;
}
let mut retained_entries = Vec::with_capacity(retained_len);
let mut retained_rows = Vec::with_capacity(retained_len);
for (g, r) in entries {
if g >= emit_groups {
// Compute the new `(group_idx, row_idx)` pair for a
// retained row. `group_idx` is renumbered to start from
// 0, and `row_idx` points into the new dense batch we are
// building.
retained_entries.push((g - emit_groups, retained_rows.len() as u32));
retained_rows.push(r);
}
}
debug_assert_eq!(retained_entries.len(), retained_len);
debug_assert_eq!(retained_rows.len(), retained_len);
let batch = if retained_len == batch.len() {
batch
} else {
// Compact mixed batches so retained rows no longer pin the
// original array.
let retained_rows = UInt32Array::from(retained_rows);
arrow::compute::take(batch.as_ref(), &retained_rows, None)?
};
batches.push(batch);
batch_entries.push(retained_entries);
}
self.batches = batches;
self.batch_entries = batch_entries;
self.num_groups -= emit_groups as usize;
Ok(())
}
}
impl GroupsAccumulator for ArrayAggGroupsAccumulator {
/// Store a reference to the input batch, plus a `(group_idx, row_idx)` pair
/// for every row.
fn update_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
opt_filter: Option<&BooleanArray>,
total_num_groups: usize,
) -> Result<()> {
assert_eq!(values.len(), 1, "single argument to update_batch");
let input = &values[0];
self.num_groups = self.num_groups.max(total_num_groups);
let nulls = if self.ignore_nulls {
input.logical_nulls()
} else {
None
};
// Without a filter or nulls to skip, every row becomes an entry
let mut entries = if opt_filter.is_none() && nulls.is_none() {
Vec::with_capacity(group_indices.len())
} else {
Vec::new()
};
for (row_idx, &group_idx) in group_indices.iter().enumerate() {
// Skip filtered rows
if let Some(filter) = opt_filter
&& (filter.is_null(row_idx) || !filter.value(row_idx))
{
continue;
}
// Skip null values when ignore_nulls is set
if let Some(ref nulls) = nulls
&& nulls.is_null(row_idx)
{
continue;
}
entries.push((group_idx as u32, row_idx as u32));
}
// We only need to record the batch if it was non-empty.
if !entries.is_empty() {
self.batches.push(Arc::clone(input));
self.batch_entries.push(entries);
}
Ok(())
}
/// Produce a `ListArray` ordered by group index: the list at
/// position N contains the aggregated values for group N.
///
/// Uses a counting sort to rearrange the stored `(group, row)`
/// entries into group order, then calls `interleave` to gather
/// the values into a flat array that backs the output `ListArray`.
fn evaluate(&mut self, emit_to: EmitTo) -> Result<ArrayRef> {
let emit_groups = match emit_to {
EmitTo::All => self.num_groups,
EmitTo::First(n) => n,
};
// Step 1: Count entries per group. For EmitTo::First(n), only groups
// 0..n are counted; the rest are retained to be emitted in the future.
let mut counts = vec![0u32; emit_groups];
for entries in &self.batch_entries {
for &(g, _) in entries {
let g = g as usize;
if g < emit_groups {
counts[g] += 1;
}
}
}
// Step 2: Do a prefix sum over the counts and use it to build ListArray
// offsets, null buffer, and write positions for the counting sort.
let mut offsets = Vec::<i32>::with_capacity(emit_groups + 1);
offsets.push(0);
let mut nulls_builder = NullBufferBuilder::new(emit_groups);
let mut write_positions = Vec::with_capacity(emit_groups);
let mut cur_offset = 0u32;
for &count in &counts {
if count == 0 {
nulls_builder.append_null();
} else {
nulls_builder.append_non_null();
}
write_positions.push(cur_offset);
cur_offset += count;
offsets.push(cur_offset as i32);
}
let total_rows = cur_offset as usize;
// Step 3: Scatter entries into group order using the counting sort. The
// batch index is implicit from the outer loop position.
let flat_values = if total_rows == 0 {
new_empty_array(&self.datatype)
} else {
let mut interleave_indices = vec![(0usize, 0usize); total_rows];
for (batch_idx, entries) in self.batch_entries.iter().enumerate() {
for &(g, r) in entries {
let g = g as usize;
if g < emit_groups {
let wp = write_positions[g] as usize;
interleave_indices[wp] = (batch_idx, r as usize);
write_positions[g] += 1;
}
}
}
let sources: Vec<&dyn Array> =
self.batches.iter().map(|b| b.as_ref()).collect();
arrow::compute::interleave(&sources, &interleave_indices)?
};
// Step 4: Release state for emitted groups.
match emit_to {
EmitTo::All => self.clear_state(),
EmitTo::First(_) => self.compact_retained_state(emit_groups)?,
}
let offsets = OffsetBuffer::new(ScalarBuffer::from(offsets));
let field = Arc::new(Field::new_list_field(self.datatype.clone(), true));
let result = ListArray::new(field, offsets, flat_values, nulls_builder.finish());
Ok(Arc::new(result))
}
fn state(&mut self, emit_to: EmitTo) -> Result<Vec<ArrayRef>> {
Ok(vec![self.evaluate(emit_to)?])
}
fn merge_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
total_num_groups: usize,
) -> Result<()> {
assert_eq!(values.len(), 1, "one argument to merge_batch");
let input_list = values[0].as_list::<i32>();
self.num_groups = self.num_groups.max(total_num_groups);
// Push the ListArray's backing values array as a single batch.
let list_values = input_list.values();
let list_offsets = input_list.offsets();
// Without null rows, every value in the offset span becomes an entry
let mut entries = if input_list.null_count() == 0 {
Vec::with_capacity(offset_span(list_offsets).1)
} else {
Vec::new()
};
for (row_idx, &group_idx) in group_indices.iter().enumerate() {
if input_list.is_null(row_idx) {
continue;
}
let start = list_offsets[row_idx] as u32;
let end = list_offsets[row_idx + 1] as u32;
for pos in start..end {
entries.push((group_idx as u32, pos));
}
}
if !entries.is_empty() {
self.batches.push(Arc::clone(list_values));
self.batch_entries.push(entries);
}
Ok(())
}
fn convert_to_state(
&self,
values: &[ArrayRef],
opt_filter: Option<&BooleanArray>,
) -> Result<Vec<ArrayRef>> {
assert_eq!(values.len(), 1, "one argument to convert_to_state");
Ok(vec![single_value_lists(
&values[0],
opt_filter,
self.ignore_nulls,
&self.datatype,
)])
}
fn size(&self) -> usize {
self.batches
.iter()
.map(|arr| arr.to_data().get_slice_memory_size().unwrap_or_default())
.sum::<usize>()
+ self.batches.capacity() * size_of::<ArrayRef>()
+ self
.batch_entries
.iter()
.map(|e| e.capacity() * size_of::<(u32, u32)>())
.sum::<usize>()
+ self.batch_entries.capacity() * size_of::<Vec<(u32, u32)>>()
}
}
/// Converts each input row into a one-element list, the state shape of
/// `ARRAY_AGG`.
///
/// Filtered rows become null list entries, which `merge_batch` skips. With
/// `ignore_nulls`, null values also become null list entries; without it they
/// stay as `[NULL]` so `merge_batch` retains them.
fn single_value_lists(
input: &ArrayRef,
opt_filter: Option<&BooleanArray>,
ignore_nulls: bool,
datatype: &DataType,
) -> ArrayRef {
// Offsets are [0, 1, 2, ..., n].
let offsets = OffsetBuffer::from_repeated_length(1, input.len());
let filter_nulls = opt_filter.map(filter_to_nulls);
let nulls = if ignore_nulls {
let logical = input.logical_nulls();
NullBuffer::union(filter_nulls.as_ref(), logical.as_ref())
} else {
filter_nulls
};
let field = Arc::new(Field::new_list_field(datatype.clone(), true));
Arc::new(ListArray::new(field, offsets, Arc::clone(input), nulls))
}
/// [`GroupsAccumulator`] for `ARRAY_AGG(DISTINCT x)`, optionally with
/// `ORDER BY x`.
///
/// Distinct values are encoded once with a [`RowConverter`] and stored in a
/// single [`Rows`] buffer shared by all groups, so a value that appears in many
/// groups is held once. Each group records the values it has seen as
/// `(group_index, value_index)` pairs, deduplicated in one hash set rather than
/// one set per group.
#[derive(Debug)]
struct DistinctArrayAggGroupsAccumulator {
datatype: DataType,
sort_options: Option<SortOptions>,
ignore_nulls: bool,
/// Encodes values to rows. Created on the first non-empty input, once the
/// runtime type is known.
converter: Option<RowConverter>,
/// Every distinct value seen so far, indexed by value index.
values: Option<Rows>,
/// `(hash, value_index)` for every row in `values`.
value_map: HashTable<(u64, u32)>,
/// Heap size of `value_map` in bytes.
value_map_size: usize,
/// Distinct `(group_index, value_index)` pairs, in first-seen order.
pairs: Vec<(u32, u32)>,
/// Deduplicates `pairs`.
pair_set: HashSet<(u32, u32), RandomState>,
/// Total number of groups tracked.
num_groups: usize,
random_state: RandomState,
/// Time spent deduplicating values, reported as the DISTINCT submetric.
distinct_metric: Option<Arc<dyn AggregateMetric>>,
}
impl DistinctArrayAggGroupsAccumulator {
fn new(
datatype: DataType,
sort_options: Option<SortOptions>,
ignore_nulls: bool,
) -> Self {
Self {
datatype,
sort_options,
ignore_nulls,
converter: None,
values: None,
value_map: HashTable::new(),
value_map_size: 0,
pairs: Vec::new(),
pair_set: HashSet::default(),
num_groups: 0,
random_state: RandomState::default(),
distinct_metric: None,
}
}
fn converter(&mut self, data_type: &DataType) -> Result<&RowConverter> {
if self.converter.is_none() {
let sort_field = match self.sort_options {
Some(opts) => SortField::new_with_options(data_type.clone(), opts),
None => SortField::new(data_type.clone()),
};
let converter = RowConverter::new(vec![sort_field])?;
self.values = Some(converter.empty_rows(0, 0));
self.converter = Some(converter);
}
self.converter
.as_ref()
.ok_or_else(|| internal_datafusion_err!("row converter must be set"))
}
/// Like [`Self::insert`], but first gathers the selected rows when they
/// are only part of `input`, so rejected values are never encoded.
fn insert_selected(
&mut self,
input: &ArrayRef,
rows: Vec<(usize, usize)>,
) -> Result<()> {
if rows.len() == input.len() {
return self.insert(input, rows);
}
let indices = UInt32Array::from_iter_values(
rows.iter().map(|&(_, row_index)| row_index as u32),
);
let selected = take_array(input.as_ref(), &indices, None)?;
self.insert(
&selected,
rows.into_iter()
.enumerate()
.map(|(position, (group_index, _))| (group_index, position)),
)
}
/// Records that `group_index` contains each value of `input` selected by
/// `rows`, given as `(group_index, row_in_input)` pairs.
fn insert(
&mut self,
input: &ArrayRef,
rows: impl IntoIterator<Item = (usize, usize)>,
) -> Result<()> {
let encoded = self
.converter(input.data_type())?
.convert_columns(std::slice::from_ref(input))?;
let Self {
values,
value_map,
value_map_size,
pairs,
pair_set,
random_state,
..
} = self;
let values = values
.as_mut()
.ok_or_else(|| internal_datafusion_err!("value rows must be set"))?;
for (group_index, row_index) in rows {
let row = encoded.row(row_index);
let hash = random_state.hash_one(row.as_ref());
let value_index = match value_map.find(hash, |&(h, index)| {
h == hash && values.row(index as usize) == row
}) {
Some(&(_, index)) => index,
None => {
let index = values.num_rows() as u32;
values.push(row);
value_map.insert_accounted(
(hash, index),
|&(h, _)| h,
value_map_size,
);
index
}
};
let pair = (group_index as u32, value_index);
if pair_set.insert(pair) {
pairs.push(pair);
}
}
Ok(())
}