datafusion-physical-plan 56.0.0

Physical (ExecutionPlan) implementations for DataFusion query engine
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
// 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

use crate::aggregates::group_values::multi_group_by::GroupColumn;
use arrow::array::{
    Array, ArrayRef, AsArray, BooleanBufferBuilder, DictionaryArray, Int64Array,
    PrimitiveArray,
};
use arrow::compute::take;
use arrow::datatypes::{ArrowDictionaryKeyType, ArrowNativeType, DataType, Field};
use arrow::error::ArrowError;
use datafusion_common::hash_utils::{RandomState, create_hashes};
use datafusion_common::{DataFusionError, Result, exec_err};
use datafusion_execution::memory_pool::proxy::HashTableAllocExt;
use datafusion_expr::GroupSelection;
use hashbrown::{HashMap, hash_table::HashTable};
use std::marker::PhantomData;
use std::mem::size_of;
use std::sync::{Arc, Weak};

use crate::aggregates::AGGREGATION_HASH_SEED;

/// [`GroupColumn`] for dictionary-encoded columns with key type `K`.
///
/// `inner` holds one slot per distinct value seen across all batches.
/// `group_to_inner[group_idx]` maps each group to its slot in `inner`,
/// so groups with the same value share a slot rather than duplicating data.
pub struct DictionaryGroupValuesColumn<K: ArrowDictionaryKeyType + Send + Sync> {
    /// Deduplicated store of distinct values.
    inner: Box<dyn GroupColumn>,
    /// Unary null array (length 1) reused for every null appended to `inner`.
    null_array: ArrayRef,
    /// Maps each group index to its slot in `inner`.
    group_to_inner: Vec<usize>,
    /// Lookup table mapping `(value_hash, inner_slot)` for each non-null distinct value.
    value_dedup: HashTable<(u64, usize)>,
    /// Tracked allocation size of `value_dedup` for memory accounting via `size()`.
    value_dedup_size: usize,
    /// Slot in `inner` for the null group; `None` until the first null is seen.
    null_inner_slot: Option<usize>,
    /// Hash seed — must match `create_hashes` so hashes are consistent across calls.
    random_state: RandomState,
    /// Maps `val_idx → inner_slot` for the values array in `cached_values`.
    ///
    /// Valid only while `cached_values` is `Some` and matches the incoming
    /// values array; `usize::MAX` means "not yet resolved". Entries are only
    /// ever filled in, never invalidated, because `inner` slots are stable
    /// under append. `take_n` remaps `inner` and therefore drops the cache.
    val_to_inner: Vec<usize>,
    /// Hashes of the values array in `cached_values`, one per `val_idx`.
    val_hashes: Vec<u64>,
    /// Weak reference to the values array that `val_hashes` and `val_to_inner`
    /// were built for. A matching live array reuses both caches without
    /// retaining an input dictionary after its batch is released.
    cached_values: Option<Weak<dyn Array>>,
    _phantom: PhantomData<K>,
}

impl<K: ArrowDictionaryKeyType + Send + Sync> DictionaryGroupValuesColumn<K> {
    pub fn new(inner: Box<dyn GroupColumn>, field: &Field) -> Self {
        let null_array = arrow::array::new_null_array(field.data_type(), 1);
        Self {
            inner,
            null_array,
            group_to_inner: Vec::new(),
            value_dedup: HashTable::new(),
            value_dedup_size: 0,
            null_inner_slot: None,
            random_state: AGGREGATION_HASH_SEED,
            val_to_inner: Vec::default(),
            val_hashes: Vec::default(),
            cached_values: None,
            _phantom: PhantomData,
        }
    }

    /// Build a `DictionaryArray` from `values` (all inner slots) and the
    /// per-group slot mapping.  The null inner slot, if any, is excluded from
    /// the values array and its groups emit a null key — so it never consumes
    /// a key index regardless of where it sits in `inner`.
    fn into_dict(
        values: ArrayRef,
        group_to_inner: &[usize],
        null_inner_slot: Option<usize>,
    ) -> ArrayRef {
        let Some(null_slot) = null_inner_slot else {
            // Fast path: no null group — raw slot indices are valid keys.
            let keys: PrimitiveArray<K> = group_to_inner
                .iter()
                .map(|&slot| Some(K::Native::usize_as(slot)))
                .collect();
            return Arc::new(DictionaryArray::<K>::new(keys, values));
        };

        // Build a compact remap: each non-null slot gets a contiguous key
        // starting from 0; the null slot is skipped entirely.
        let n = values.len();
        let mut remap = vec![0usize; n];
        let mut next = 0usize;
        for (i, mapped) in remap.iter_mut().enumerate() {
            if i != null_slot {
                *mapped = next;
                next += 1;
            }
        }

        let keys: PrimitiveArray<K> = group_to_inner
            .iter()
            .map(|&slot| {
                if slot == null_slot {
                    None
                } else {
                    Some(K::Native::usize_as(remap[slot]))
                }
            })
            .collect();

        // Compact values array: drop the null slot so key indices stay tight.
        let compact_indices: Int64Array = (0..n)
            .filter(|&i| i != null_slot)
            .map(|i| i as i64)
            .collect();
        let compact =
            take(&*values, &compact_indices, None).expect("compact values in into_dict");
        Arc::new(DictionaryArray::<K>::new(keys, compact))
    }

    // https://github.com/apache/datafusion/issues/23127
    // Null groups emit a null key (None), not a slot index, so the null inner
    // slot never consumes a key index regardless of its position in inner.
    fn check_key_overflow(&self) -> Result<()> {
        let non_null_count = self.inner.len() - self.null_inner_slot.is_some() as usize;
        if !Self::key_type_fits(non_null_count) {
            return exec_err!(
                "Dictionary key type {:?} cannot represent {} distinct values",
                K::DATA_TYPE,
                non_null_count
            );
        }
        Ok(())
    }

    fn key_type_fits(num_values: usize) -> bool {
        let max: usize = match K::DATA_TYPE {
            DataType::Int8 => i8::MAX as usize,
            DataType::Int16 => i16::MAX as usize,
            DataType::Int32 => i32::MAX as usize,
            DataType::Int64 => i64::MAX as usize,
            DataType::UInt8 => u8::MAX as usize,
            DataType::UInt16 => u16::MAX as usize,
            DataType::UInt32 => u32::MAX as usize,
            DataType::UInt64 => usize::MAX,
            _ => return false,
        };
        num_values == 0 || num_values - 1 <= max
    }

    fn hash_values(&mut self, values: &ArrayRef) {
        self.cached_values = None;
        self.val_hashes.clear();
        self.val_hashes.resize(values.len(), 0);
        create_hashes(
            std::slice::from_ref(values),
            &self.random_state,
            &mut self.val_hashes,
        )
        .unwrap();
    }

    fn is_cached(&self, values: &ArrayRef) -> bool {
        self.cached_values
            .as_ref()
            .is_some_and(|cached| std::ptr::addr_eq(cached.as_ptr(), Arc::as_ptr(values)))
    }

    /// Makes `val_hashes` and `val_to_inner` correspond to `dict_values`,
    /// reusing them when they were already built for this same values array.
    ///
    /// `take`, `filter` and repartitioning clone the values `Arc` and rewrite
    /// only the keys, so batches in a partition usually share one values
    /// array; without this the per-batch cost is O(dictionary cardinality)
    /// rather than O(rows). `take_n` remaps `inner` and clears
    /// `cached_values`, forcing a rebuild.
    fn sync_value_cache(&mut self, dict_values: &ArrayRef) {
        if self.is_cached(dict_values) {
            return;
        }
        self.hash_values(dict_values);
        self.val_to_inner.clear();
        self.val_to_inner.resize(dict_values.len(), usize::MAX);
        self.cached_values = Some(Arc::downgrade(dict_values));
    }

    fn find_or_insert_value(
        &mut self,
        dict_values: &ArrayRef,
        val_idx: usize,
        hash: u64,
    ) -> Result<usize> {
        let inner = &*self.inner;
        let existing = self
            .value_dedup
            .find(hash, |&(entry_hash, slot)| {
                entry_hash == hash && inner.equal_to(slot, dict_values, val_idx)
            })
            .map(|&(_, slot)| slot);

        match existing {
            Some(slot) => Ok(slot),
            None => {
                let slot = self.inner.len();
                self.inner.append_val(dict_values, val_idx)?;
                self.value_dedup.insert_accounted(
                    (hash, slot),
                    |&(entry_hash, _)| entry_hash,
                    &mut self.value_dedup_size,
                );
                Ok(slot)
            }
        }
    }

    /// Compares the value at `val_idx` against `inner[lhs_slot]` directly,
    /// memorizing `lhs_slot` in `val_to_inner` when they are equal.
    ///
    /// Each distinct value occupies exactly one slot in `inner`, so an equal
    /// comparison proves `lhs_slot` is the slot for `val_idx` without probing
    /// `value_dedup` or hashing. An unequal result is deliberately not
    /// memoized: it says which slot the value is *not* in, not which one it
    /// is. That is what keeps `val_to_inner` fill-only and never stale.
    ///
    /// Callers must have run [`Self::sync_value_cache`] for `dict_values`.
    ///
    /// Only called on a `val_to_inner` miss. It takes the fields it needs
    /// rather than `&mut self`, so the caller's hot loop can keep its slices
    /// of `val_to_inner` and `group_to_inner` in registers across the call.
    #[cold]
    #[inline(never)]
    fn equal_to_uncached(
        val_to_inner: &mut [usize],
        inner: &dyn GroupColumn,
        null_array: &ArrayRef,
        dict_values: &ArrayRef,
        val_idx: usize,
        lhs_slot: usize,
    ) -> bool {
        let equal = if dict_values.is_null(val_idx) {
            inner.equal_to(lhs_slot, null_array, 0)
        } else {
            inner.equal_to(lhs_slot, dict_values, val_idx)
        };

        if equal {
            val_to_inner[val_idx] = lhs_slot;
        }
        equal
    }

    fn find_or_insert_null(&mut self) -> Result<usize> {
        if let Some(slot) = self.null_inner_slot {
            return Ok(slot);
        }
        let slot = self.inner.len();
        self.inner.append_val(&self.null_array, 0)?;
        self.null_inner_slot = Some(slot);
        Ok(slot)
    }

    /// Per-row fallback for `vectorized_equal_to` used when the values array is
    /// not cached and the number of rows to check is smaller than the
    /// dictionary cardinality, making the O(D) hashing in `sync_value_cache`
    /// more expensive than direct value comparison.
    ///
    /// `#[cold]` + `#[inline(never)]` keeps this code out of the hot
    /// `val_to_inner` loops in `vectorized_equal_to` so LLVM can pipeline them.
    #[cold]
    #[inline(never)]
    fn equal_to_per_row(
        &self,
        lhs_rows: &[usize],
        dict_values: &ArrayRef,
        dict: &DictionaryArray<K>,
        rhs_rows: &[usize],
        equal_to_results: &mut BooleanBufferBuilder,
    ) {
        let group_to_inner = self.group_to_inner.as_slice();
        for (idx, (&lhs_row, &rhs_row)) in
            lhs_rows.iter().zip(rhs_rows.iter()).enumerate()
        {
            if !equal_to_results.get_bit(idx) {
                continue;
            }
            let lhs_slot = group_to_inner[lhs_row];
            let equal = match dict.key(rhs_row) {
                None => self.inner.equal_to(lhs_slot, &self.null_array, 0),
                Some(val_idx) if dict_values.is_null(val_idx) => {
                    self.inner.equal_to(lhs_slot, &self.null_array, 0)
                }
                Some(val_idx) => self.inner.equal_to(lhs_slot, dict_values, val_idx),
            };
            if !equal {
                equal_to_results.set_bit(idx, false);
            }
        }
    }
}

impl<K: ArrowDictionaryKeyType + Send + Sync> GroupColumn
    for DictionaryGroupValuesColumn<K>
{
    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> bool {
        let lhs_slot = self.group_to_inner[lhs_row];
        let dict = array.as_dictionary::<K>();
        match dict.key(rhs_row) {
            None => self.inner.equal_to(lhs_slot, &self.null_array, 0),
            Some(val_idx) if dict.values().is_null(val_idx) => {
                self.inner.equal_to(lhs_slot, &self.null_array, 0)
            }
            Some(val_idx) => self.inner.equal_to(lhs_slot, dict.values(), val_idx),
        }
    }

    fn append_val(&mut self, array: &ArrayRef, row: usize) -> Result<()> {
        let dict = array.as_dictionary::<K>();
        let inner_slot = match dict.key(row) {
            None => self.find_or_insert_null()?,
            Some(val_idx) if dict.values().is_null(val_idx) => {
                self.find_or_insert_null()?
            }
            Some(val_idx) => {
                let dict_values = dict.values();
                self.sync_value_cache(dict_values);
                self.find_or_insert_value(dict_values, val_idx, self.val_hashes[val_idx])?
            }
        };
        self.group_to_inner.push(inner_slot);
        self.check_key_overflow()
    }

    fn vectorized_equal_to(
        &mut self,
        lhs_rows: &[usize],
        array: &ArrayRef,
        rhs_rows: &[usize],
        equal_to_results: &mut BooleanBufferBuilder,
    ) {
        let dict = array.as_dictionary::<K>();
        let dict_keys = dict.keys();
        let dict_values = dict.values();

        let cached = self.is_cached(dict_values);
        if !cached && rhs_rows.len() < dict_values.len() {
            self.equal_to_per_row(
                lhs_rows,
                dict_values,
                dict,
                rhs_rows,
                equal_to_results,
            );
            return;
        }
        self.sync_value_cache(dict_values);

        let raw_keys = dict_keys.values();
        let group_to_inner = self.group_to_inner.as_slice();
        let val_to_inner = self.val_to_inner.as_mut_slice();
        let inner = &*self.inner;
        let null_array = &self.null_array;
        let null_inner_slot = self.null_inner_slot;
        if dict_keys.null_count() == 0 {
            // No null keys : skip the get_bit guard: we only ever write false,
            // so overwriting an already-false bit is a no-op.
            for (idx, (&lhs_row, &rhs_row)) in
                lhs_rows.iter().zip(rhs_rows.iter()).enumerate()
            {
                let val_idx = raw_keys[rhs_row].as_usize();
                let lhs_slot = group_to_inner[lhs_row];
                let equal = match val_to_inner[val_idx] {
                    usize::MAX => Self::equal_to_uncached(
                        val_to_inner,
                        inner,
                        null_array,
                        dict_values,
                        val_idx,
                        lhs_slot,
                    ),
                    slot => slot == lhs_slot,
                };
                if !equal {
                    equal_to_results.set_bit(idx, false);
                }
            }
        } else {
            let null_buf = dict_keys.nulls().unwrap();
            for (idx, (&lhs_row, &rhs_row)) in
                lhs_rows.iter().zip(rhs_rows.iter()).enumerate()
            {
                if equal_to_results.get_bit(idx) {
                    // A null key is not a position in the values array, so it
                    // resolves straight to the null slot instead of going
                    // through `val_to_inner`.
                    let lhs_slot = group_to_inner[lhs_row];
                    let equal = if null_buf.is_null(rhs_row) {
                        null_inner_slot == Some(lhs_slot)
                    } else {
                        let val_idx = raw_keys[rhs_row].as_usize();
                        match val_to_inner[val_idx] {
                            usize::MAX => Self::equal_to_uncached(
                                val_to_inner,
                                inner,
                                null_array,
                                dict_values,
                                val_idx,
                                lhs_slot,
                            ),
                            slot => slot == lhs_slot,
                        }
                    };
                    if !equal {
                        equal_to_results.set_bit(idx, false);
                    }
                }
            }
        }
    }

    fn vectorized_append(&mut self, array: &ArrayRef, rows: &[usize]) -> Result<()> {
        let dict = array.as_dictionary::<K>();
        let dict_keys = dict.keys();
        let dict_values = dict.values();

        // Reuses `val_hashes`/`val_to_inner` when this batch carries the same
        // values array as the last one, which is the common case downstream of
        // a repartition or filter. Previously this unconditionally re-hashed
        // and re-initialised both buffers, costing O(D) per batch.
        self.sync_value_cache(dict_values);

        self.group_to_inner.try_reserve(rows.len()).map_err(|e| {
            DataFusionError::ArrowError(
                Box::new(ArrowError::MemoryError(e.to_string())),
                None,
            )
        })?;

        let raw_keys = dict_keys.values();
        if dict_keys.null_count() == 0 {
            for &row in rows {
                let val_idx = raw_keys[row].as_usize();
                if self.val_to_inner[val_idx] == usize::MAX {
                    // A non-null key can still point to a null value in the values array.
                    self.val_to_inner[val_idx] = if dict_values.is_null(val_idx) {
                        self.find_or_insert_null()?
                    } else {
                        self.find_or_insert_value(
                            dict_values,
                            val_idx,
                            self.val_hashes[val_idx],
                        )?
                    };
                }
                self.group_to_inner.push(self.val_to_inner[val_idx]);
            }
        } else {
            let null_buf = dict_keys.nulls().unwrap();
            for &row in rows {
                let slot = if null_buf.is_null(row) {
                    self.find_or_insert_null()?
                } else {
                    let val_idx = raw_keys[row].as_usize();
                    if self.val_to_inner[val_idx] == usize::MAX {
                        self.val_to_inner[val_idx] = if dict_values.is_null(val_idx) {
                            self.find_or_insert_null()?
                        } else {
                            self.find_or_insert_value(
                                dict_values,
                                val_idx,
                                self.val_hashes[val_idx],
                            )?
                        };
                    }
                    self.val_to_inner[val_idx]
                };
                self.group_to_inner.push(slot);
            }
        }

        self.check_key_overflow()
    }

    fn len(&self) -> usize {
        self.group_to_inner.len()
    }

    fn size(&self) -> usize {
        self.inner.size()
            + self.value_dedup_size
            + self.group_to_inner.capacity() * size_of::<usize>()
            + self.val_to_inner.capacity() * size_of::<usize>()
            + self.val_hashes.capacity() * size_of::<u64>()
            + self.null_array.get_array_memory_size()
            + size_of::<Self>()
    }

    fn build(self: Box<Self>) -> ArrayRef {
        let null_inner_slot = self.null_inner_slot;
        let values = self.inner.build();
        Self::into_dict(values, &self.group_to_inner, null_inner_slot)
    }

    fn values_preserving(&self, selection: GroupSelection<'_>) -> Result<ArrayRef> {
        selection.validate_num_groups(self.group_to_inner.len())?;

        let mut old_to_new = HashMap::with_capacity(selection.len());
        let mut selected_inner = Vec::with_capacity(selection.len());
        let mut selected_groups = Vec::with_capacity(selection.len());
        for group_index in selection.iter() {
            let old_slot = self.group_to_inner[group_index];
            let new_slot = if let Some(&new_slot) = old_to_new.get(&old_slot) {
                new_slot
            } else {
                let new_slot = selected_inner.len();
                selected_inner.push(old_slot);
                old_to_new.insert(old_slot, new_slot);
                new_slot
            };
            selected_groups.push(new_slot);
        }

        let inner_selection =
            GroupSelection::try_from_indices(&selected_inner, self.inner.len())?;
        let values = self.inner.values_preserving(inner_selection)?;
        let null_inner_slot = self
            .null_inner_slot
            .and_then(|slot| old_to_new.get(&slot).copied());
        Ok(Self::into_dict(values, &selected_groups, null_inner_slot))
    }

    fn take_n(&mut self, n: usize) -> ArrayRef {
        let old_inner_len = self.inner.len();
        let all_inner_values = self.inner.take_n(old_inner_len);

        let mut emit_old_to_new = vec![usize::MAX; old_inner_len];
        let mut emit_new_to_old: Vec<usize> = Vec::new();
        for &old in &self.group_to_inner[..n] {
            // Null groups emit a null key (None) and need no slot in the
            // values array, so excluding them keeps key indices tight and
            // prevents overflow at key-type capacity.
            if all_inner_values.is_null(old) {
                continue;
            }
            if emit_old_to_new[old] == usize::MAX {
                emit_old_to_new[old] = emit_new_to_old.len();
                emit_new_to_old.push(old);
            }
        }
        let emit_indices =
            Int64Array::from_iter(emit_new_to_old.iter().map(|&i| i as i64));
        let compact_emit_values =
            take(&*all_inner_values, &emit_indices, None).expect("take emit values");
        let emitted_keys: PrimitiveArray<K> = self.group_to_inner[..n]
            .iter()
            .map(|&old| {
                if all_inner_values.is_null(old) {
                    None
                } else {
                    Some(K::Native::usize_as(emit_old_to_new[old]))
                }
            })
            .collect();
        let emitted: ArrayRef =
            Arc::new(DictionaryArray::<K>::new(emitted_keys, compact_emit_values));

        // Null deferred to last so null_inner_slot is always the highest index
        // and check_key_overflow can subtract it without a false overflow.
        let remaining = self.group_to_inner[n..].to_vec();
        let mut old_to_new = vec![usize::MAX; old_inner_len];
        let mut new_to_old: Vec<usize> = Vec::new();
        let mut null_old_slot: Option<usize> = None;
        for &old in &remaining {
            if all_inner_values.is_null(old) {
                if null_old_slot.is_none() {
                    null_old_slot = Some(old);
                }
                continue;
            }
            if old_to_new[old] == usize::MAX {
                old_to_new[old] = new_to_old.len();
                new_to_old.push(old);
            }
        }
        if let Some(old) = null_old_slot {
            old_to_new[old] = new_to_old.len();
            new_to_old.push(old);
        }

        self.value_dedup = HashTable::new();
        self.value_dedup_size = 0;
        self.null_inner_slot = None;

        self.hash_values(&all_inner_values);

        for (new_slot, &old_slot) in new_to_old.iter().enumerate() {
            if all_inner_values.is_null(old_slot) {
                self.inner
                    .append_val(&self.null_array, 0)
                    .expect("append null failed in take_n");
                self.null_inner_slot = Some(new_slot);
            } else {
                self.inner
                    .append_val(&all_inner_values, old_slot)
                    .expect("append value failed in take_n");
                self.value_dedup.insert_accounted(
                    (self.val_hashes[old_slot], new_slot),
                    |&(entry_hash, _)| entry_hash,
                    &mut self.value_dedup_size,
                );
            }
        }

        self.group_to_inner = remaining.iter().map(|&old| old_to_new[old]).collect();
        self.check_key_overflow().expect("key overflow in take_n");

        emitted
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::aggregates::group_values::multi_group_by::bytes::ByteGroupValueBuilder;
    use arrow::array::{
        Array, ArrayRef, BooleanBufferBuilder, DictionaryArray, Int32Array, StringArray,
        UInt8Array,
    };
    use arrow::compute::cast;
    use arrow::datatypes::{DataType, Int8Type, Int32Type, UInt8Type};
    use datafusion_physical_expr::binary_map::OutputType;
    use std::sync::Arc;

    fn utf8_col() -> DictionaryGroupValuesColumn<Int32Type> {
        let f = Field::new("", DataType::Utf8, true);
        DictionaryGroupValuesColumn::new(
            Box::new(ByteGroupValueBuilder::<i32>::new(OutputType::Utf8)),
            &f,
        )
    }

    fn int8_col() -> DictionaryGroupValuesColumn<Int8Type> {
        let f = Field::new("", DataType::Utf8, true);
        DictionaryGroupValuesColumn::new(
            Box::new(ByteGroupValueBuilder::<i32>::new(OutputType::Utf8)),
            &f,
        )
    }

    fn uint8_col() -> DictionaryGroupValuesColumn<UInt8Type> {
        let f = Field::new("", DataType::Utf8, true);
        DictionaryGroupValuesColumn::new(
            Box::new(ByteGroupValueBuilder::<i32>::new(OutputType::Utf8)),
            &f,
        )
    }

    fn i32_dict(keys: &[Option<i32>], values: &[Option<&str>]) -> ArrayRef {
        Arc::new(DictionaryArray::<Int32Type>::new(
            Int32Array::from(keys.to_vec()),
            Arc::new(StringArray::from(values.to_vec())),
        ))
    }

    fn i8_dict(keys: &[Option<i8>], values: &[Option<&str>]) -> ArrayRef {
        use arrow::array::Int8Array;
        Arc::new(DictionaryArray::<Int8Type>::new(
            Int8Array::from(keys.to_vec()),
            Arc::new(StringArray::from(values.to_vec())),
        ))
    }

    fn u8_dict(keys: &[Option<u8>], values: &[Option<&str>]) -> ArrayRef {
        Arc::new(DictionaryArray::<UInt8Type>::new(
            UInt8Array::from(keys.to_vec()),
            Arc::new(StringArray::from(values.to_vec())),
        ))
    }

    fn str_values(arr: &ArrayRef) -> Vec<Option<String>> {
        let plain = cast(arr.as_ref(), &DataType::Utf8).unwrap();
        plain
            .as_any()
            .downcast_ref::<StringArray>()
            .unwrap()
            .iter()
            .map(|v| v.map(|s| s.to_owned()))
            .collect()
    }

    fn bool_vec(buf: &BooleanBufferBuilder) -> Vec<bool> {
        (0..buf.len()).map(|i| buf.get_bit(i)).collect()
    }

    #[test]
    fn hash_cache_does_not_retain_dictionary_values() {
        let mut column = utf8_col();
        let input = i32_dict(&[Some(0)], &[Some("retained")]);
        let values = Arc::clone(input.as_dictionary::<Int32Type>().values());
        let weak_values = Arc::downgrade(&values);
        column.append_val(&input, 0).unwrap();
        assert!(
            column
                .cached_values
                .as_ref()
                .is_some_and(|cached| cached.ptr_eq(&weak_values))
        );
        let size_with_input = column.size();

        // The cache is only an identity hint: it must not keep an input
        // dictionary allocation alive after its batch is released.
        drop(values);
        drop(input);
        assert!(weak_values.upgrade().is_none());
        assert_eq!(column.size(), size_with_input);
    }

    fn all_true(len: usize) -> BooleanBufferBuilder {
        let mut buf = BooleanBufferBuilder::new(len);
        buf.append_n(len, true);
        buf
    }

    // Builds an Int8-keyed dict of `end-start` distinct strings "v{start}".."v{end-1}".
    fn distinct_i8_dict(start: usize, end: usize) -> ArrayRef {
        let strs: Vec<String> = (start..end).map(|i| format!("v{i}")).collect();
        let refs: Vec<Option<&str>> = strs.iter().map(|s| Some(s.as_str())).collect();
        i8_dict(
            &(0..strs.len()).map(|i| Some(i as i8)).collect::<Vec<_>>(),
            &refs,
        )
    }

    // Builds a UInt8-keyed dict of `count` distinct strings "u0".."u{count-1}".
    fn distinct_u8_dict(count: usize) -> ArrayRef {
        let strs: Vec<String> = (0..count).map(|i| format!("u{i}")).collect();
        let refs: Vec<Option<&str>> = strs.iter().map(|s| Some(s.as_str())).collect();
        u8_dict(
            &(0..count).map(|i| Some(i as u8)).collect::<Vec<_>>(),
            &refs,
        )
    }

    #[test]
    fn repeated_values_are_deduplicated_in_inner_store() {
        let mut col = utf8_col();
        let arr = i32_dict(
            &[Some(0), Some(1), Some(0), Some(1), Some(0)],
            &[Some("a"), Some("b")],
        );
        col.vectorized_append(&arr, &[0, 1, 2, 3, 4]).unwrap();
        let out = Box::new(col).build();
        assert_eq!(out.as_dictionary::<Int32Type>().values().len(), 2);
        assert_eq!(
            str_values(&out),
            vec![
                Some("a".into()),
                Some("b".into()),
                Some("a".into()),
                Some("b".into()),
                Some("a".into()),
            ]
        );
    }

    #[test]
    fn values_preserving_reorders_and_reuses_dictionary_values() {
        let mut col = utf8_col();
        let input = i32_dict(&[Some(0), None, Some(1), Some(0)], &[Some("a"), Some("b")]);
        col.vectorized_append(&input, &[0, 1, 2, 3]).unwrap();

        let selection = GroupSelection::try_from_indices(&[2, 1, 0, 2], 4).unwrap();
        for _ in 0..2 {
            let selected = col.values_preserving(selection).unwrap();
            assert_eq!(
                str_values(&selected),
                vec![Some("b".into()), None, Some("a".into()), Some("b".into())]
            );
            assert_eq!(selected.as_dictionary::<Int32Type>().values().len(), 2);
        }

        col.append_val(&i32_dict(&[Some(0)], &[Some("c")]), 0)
            .unwrap();
        let out = Box::new(col).build();
        assert_eq!(
            str_values(&out),
            vec![
                Some("a".into()),
                None,
                Some("b".into()),
                Some("a".into()),
                Some("c".into()),
            ]
        );
    }

    #[test]
    fn null_key_and_null_valued_entry_both_map_to_null_group() {
        let mut col = utf8_col();
        let input = i32_dict(&[None, Some(0), Some(1)], &[None, Some("b")]);
        for row in 0..3 {
            col.append_val(&input, row).unwrap();
        }
        assert!(col.equal_to(0, &input, 1));
        assert!(!col.equal_to(0, &input, 2));
        let out = Box::new(col).build();
        assert_eq!(out.as_dictionary::<Int32Type>().values().len(), 1);
        assert_eq!(str_values(&out), vec![None, None, Some("b".into())]);
    }

    #[test]
    fn take_n_compacts_emitted_values_and_remaps_remaining_slots() {
        let mut col = utf8_col();
        let b1 = i32_dict(
            &[Some(0), Some(1), None, Some(2)],
            &[Some("a"), Some("b"), Some("c")],
        );
        col.vectorized_append(&b1, &[0, 1, 2, 3]).unwrap();

        let emitted = col.take_n(2);
        assert_eq!(emitted.as_dictionary::<Int32Type>().values().len(), 2);
        assert_eq!(
            str_values(&emitted),
            vec![Some("a".into()), Some("b".into())]
        );

        let b2 = i32_dict(&[None, Some(0)], &[Some("z")]);
        col.vectorized_append(&b2, &[0, 1]).unwrap();

        let mut buf = all_true(2);
        col.vectorized_equal_to(&[0, 1], &b2, &[0, 1], &mut buf);
        assert_eq!(bool_vec(&buf), vec![true, false]);

        let out = Box::new(col).build();
        assert_eq!(
            str_values(&out),
            vec![None, Some("c".into()), None, Some("z".into())]
        );
    }

    #[test]
    fn vectorized_equal_to_does_not_use_stale_hashes_from_prior_append() {
        let mut col = utf8_col();
        col.vectorized_append(&i32_dict(&[Some(0)], &[Some("a"), Some("b")]), &[0])
            .unwrap();
        let batch2 = i32_dict(&[Some(1)], &[Some("z"), Some("a")]);
        let mut buf = all_true(1);
        col.vectorized_equal_to(&[0], &batch2, &[0], &mut buf);
        assert_eq!(bool_vec(&buf), vec![true]);
    }

    #[test]
    fn null_does_not_consume_a_key_slot_int8_null_first_mid_and_last() {
        let rows128 = (0..128).collect::<Vec<_>>();

        let mut col = int8_col(); // null-last: 128 non-null + null — ok
        col.vectorized_append(&distinct_i8_dict(0, 128), &rows128)
            .unwrap();
        col.append_val(&i8_dict(&[None], &[Some("x")]), 0).unwrap();

        let mut col = int8_col(); // null-first: null + 128 non-null — ok; 129th — error
        col.append_val(&i8_dict(&[None], &[Some("x")]), 0).unwrap();
        col.vectorized_append(&distinct_i8_dict(0, 128), &rows128)
            .unwrap();
        assert!(
            col.append_val(&i8_dict(&[Some(0)], &[Some("overflow")]), 0)
                .is_err()
        );

        let mut col = int8_col(); // null-mid: 100 + null + 28 = 128 total — ok; 129th — error
        col.vectorized_append(&distinct_i8_dict(0, 100), &(0..100).collect::<Vec<_>>())
            .unwrap();
        col.append_val(&i8_dict(&[None], &[Some("x")]), 0).unwrap();
        col.vectorized_append(&distinct_i8_dict(100, 128), &(0..28).collect::<Vec<_>>())
            .unwrap();
        assert!(
            col.append_val(&i8_dict(&[Some(0)], &[Some("v128")]), 0)
                .is_err()
        );

        let mut col = int8_col(); // build() null-first: 128 values (null excluded), null → None
        col.append_val(&i8_dict(&[None], &[Some("x")]), 0).unwrap();
        col.vectorized_append(&distinct_i8_dict(0, 128), &rows128)
            .unwrap();
        let out = Box::new(col).build();
        assert_eq!(out.as_dictionary::<Int8Type>().values().len(), 128);
        assert_eq!(str_values(&out)[0], None);
        assert_eq!(str_values(&out)[1], Some("v0".into()));
    }

    #[test]
    fn null_does_not_consume_a_key_slot_uint8_null_first_and_last() {
        let rows256 = (0..256).collect::<Vec<_>>();

        let mut col = uint8_col(); // null-first: null + 256 non-null — ok; 257th — error
        col.append_val(&u8_dict(&[None], &[Some("x")]), 0).unwrap();
        col.vectorized_append(&distinct_u8_dict(256), &rows256)
            .unwrap();
        assert!(
            col.append_val(&u8_dict(&[Some(0)], &[Some("overflow")]), 0)
                .is_err()
        );

        let mut col = uint8_col(); // build() null-first: 256 values (null excluded), last correct
        col.append_val(&u8_dict(&[None], &[Some("x")]), 0).unwrap();
        col.vectorized_append(&distinct_u8_dict(256), &rows256)
            .unwrap();
        let out = Box::new(col).build();
        assert_eq!(out.as_dictionary::<UInt8Type>().values().len(), 256);
        assert_eq!(str_values(&out)[0], None);
        assert_eq!(str_values(&out)[256], Some("u255".into()));
    }

    #[test]
    fn take_n_null_does_not_steal_key_slot_at_capacity() {
        let rows128 = (0..128).collect::<Vec<_>>();

        // Int8 null-first + 128 non-null; emit all 129 — no panic, null → None
        let mut col = int8_col();
        col.append_val(&i8_dict(&[None], &[Some("x")]), 0).unwrap();
        col.vectorized_append(&distinct_i8_dict(0, 128), &rows128)
            .unwrap();
        let emitted = col.take_n(129);
        assert!(emitted.as_dictionary::<Int8Type>().key(0).is_none());
        assert_eq!(str_values(&emitted)[1], Some("v0".into()));
        assert_eq!(str_values(&emitted)[128], Some("v127".into()));

        // UInt8 null-first + 256 non-null; emit all 257 — last must be "u255" not "u0" (wrap guard)
        let mut col = uint8_col();
        col.append_val(&u8_dict(&[None], &[Some("x")]), 0).unwrap();
        col.vectorized_append(&distinct_u8_dict(256), &(0..256).collect::<Vec<_>>())
            .unwrap();
        let emitted = col.take_n(257);
        assert!(emitted.as_dictionary::<UInt8Type>().key(0).is_none());
        assert_eq!(str_values(&emitted)[1], Some("u0".into()));
        assert_eq!(str_values(&emitted)[256], Some("u255".into()));
    }

    #[test]
    fn take_n_repeated_emissions_null_at_int8_capacity() {
        let rows128 = (0..128).collect::<Vec<_>>();
        let mut col = int8_col();
        col.vectorized_append(&distinct_i8_dict(0, 128), &rows128)
            .unwrap();
        col.append_val(&i8_dict(&[None], &[Some("x")]), 0).unwrap();
        col.vectorized_append(&distinct_i8_dict(0, 128), &rows128)
            .unwrap();

        let first_half = col.take_n(64);
        assert_eq!(str_values(&first_half)[0], Some("v0".into()));
        assert_eq!(str_values(&first_half)[63], Some("v63".into()));
        assert_eq!(first_half.as_dictionary::<Int8Type>().values().len(), 64);

        let second_half = col.take_n(64);
        assert_eq!(str_values(&second_half)[0], Some("v64".into()));
        assert_eq!(str_values(&second_half)[63], Some("v127".into()));

        let null_group = col.take_n(1);
        assert!(null_group.as_dictionary::<Int8Type>().key(0).is_none());

        let out = Box::new(col).build();
        assert_eq!(str_values(&out)[0], Some("v0".into()));
        assert_eq!(str_values(&out)[127], Some("v127".into()));
        assert_eq!(out.as_dictionary::<Int8Type>().values().len(), 128);
    }

    fn dict_with_values(keys: &[Option<i32>], values: &ArrayRef) -> ArrayRef {
        Arc::new(DictionaryArray::<Int32Type>::new(
            Int32Array::from(keys.to_vec()),
            Arc::clone(values),
        ))
    }

    /// A cache rebuild resets every `val_to_inner` entry to `usize::MAX`, so
    /// an entry resolved by an earlier batch surviving a later one proves the
    /// dictionary was not re-hashed in between.
    #[test]
    fn cache_survives_batches_sharing_a_values_array() {
        let values: ArrayRef =
            Arc::new(StringArray::from(vec![Some("a"), Some("b"), Some("c")]));
        let mut col = utf8_col();

        col.vectorized_append(&dict_with_values(&[Some(0)], &values), &[0])
            .unwrap();
        let slot_a = col.val_to_inner[0];
        assert_ne!(slot_a, usize::MAX);

        col.vectorized_append(&dict_with_values(&[Some(1)], &values), &[0])
            .unwrap();

        assert_eq!(col.val_to_inner[0], slot_a, "cache was rebuilt");
        assert_ne!(col.val_to_inner[1], usize::MAX);
        assert_eq!(
            col.val_to_inner[2],
            usize::MAX,
            "unreferenced value resolved"
        );
        assert!(col.is_cached(&values));
        assert_eq!(col.inner.len(), 2);
    }

    /// `take` clones the values `Arc` and rewrites only the keys, which is the
    /// property the `ptr_eq` check relies on. Pin that arrow behaviour.
    #[test]
    fn take_preserves_values_arc_so_cache_hits() {
        let values: ArrayRef = Arc::new(StringArray::from(vec![Some("a"), Some("b")]));
        let batch = dict_with_values(&[Some(0), Some(1), Some(0)], &values);
        let taken = take(&*batch, &Int32Array::from(vec![2, 0]), None).unwrap();
        assert!(
            Arc::ptr_eq(taken.as_dictionary::<Int32Type>().values(), &values),
            "take must not copy the values array"
        );

        let mut col = utf8_col();
        col.vectorized_append(&batch, &[0, 1, 2]).unwrap();
        let slot_b = col.val_to_inner[1];
        col.vectorized_append(&taken, &[0, 1]).unwrap();

        assert_eq!(col.val_to_inner[1], slot_b, "cache was rebuilt");
        assert_eq!(col.inner.len(), 2);
    }

    /// A genuinely different values array must rebuild the cache, and equal
    /// values across the two arrays must still dedup to one inner slot.
    #[test]
    fn distinct_values_arcs_rebuild_cache_but_still_dedup() {
        let mut col = utf8_col();
        let first = i32_dict(&[Some(0)], &[Some("a")]);
        let second = i32_dict(&[Some(0)], &[Some("a")]);
        col.vectorized_append(&first, &[0]).unwrap();
        col.vectorized_append(&second, &[0]).unwrap();

        assert!(
            col.is_cached(second.as_dictionary::<Int32Type>().values()),
            "cache should track the most recent values array"
        );
        assert_eq!(col.inner.len(), 1, "'a' must dedup across both arrays");
        assert_eq!(col.len(), 2);
    }

    /// `take_n` remaps inner slots, so the cached `val_idx → inner_slot` map
    /// must not survive it.
    #[test]
    fn take_n_invalidates_value_cache() {
        let values: ArrayRef = Arc::new(StringArray::from(vec![Some("a"), Some("b")]));
        let mut col = utf8_col();
        col.vectorized_append(&dict_with_values(&[Some(0), Some(1)], &values), &[0, 1])
            .unwrap();

        let _emitted = col.take_n(1);
        assert!(
            col.cached_values.is_none(),
            "take_n remaps inner slots and must drop the cache"
        );

        col.vectorized_append(&dict_with_values(&[Some(0), Some(1)], &values), &[0, 1])
            .unwrap();

        let out = Box::new(col).build();
        let d = out.as_dictionary::<Int32Type>();
        let vals = d.values().as_string::<i32>();
        let got: Vec<&str> = d
            .keys()
            .iter()
            .map(|k| vals.value(k.unwrap() as usize))
            .collect();
        assert_eq!(got, vec!["b", "a", "b"]);
    }

    /// `append_val` fills `val_hashes` but not `val_to_inner`; mixing it with
    /// `vectorized_append` must not duplicate a value or reuse a stale slot.
    #[test]
    fn scalar_and_vectorized_append_share_cache_consistently() {
        let values: ArrayRef = Arc::new(StringArray::from(vec![Some("a"), Some("b")]));
        let batch = dict_with_values(&[Some(0), Some(1)], &values);
        let mut col = utf8_col();

        col.append_val(&batch, 0).unwrap();
        assert!(col.is_cached(&values));

        col.vectorized_append(&batch, &[0, 1]).unwrap();
        assert_eq!(col.inner.len(), 2, "'a' must not be duplicated");
        assert_eq!(col.len(), 3);
    }

    /// On a cache miss `vectorized_equal_to` compares against the group's own
    /// slot: an equal result proves the slot and is cached, an unequal one
    /// only rules that slot out and must leave the entry unresolved.
    #[test]
    fn vectorized_equal_to_caches_only_equal_results() {
        let mut col = utf8_col();
        col.vectorized_append(
            &i32_dict(&[Some(0), Some(1)], &[Some("a"), Some("b")]),
            &[0, 1],
        )
        .unwrap();
        let (group_a, group_b) = (0, 1);
        let slot_a = col.group_to_inner[group_a];
        let slot_b = col.group_to_inner[group_b];

        // A new values array in the opposite order, so `val_idx` != slot.
        // Two rows for two values keeps the per-row fallback out of the way.
        let (idx_b, idx_a) = (0, 1);
        let values: ArrayRef = Arc::new(StringArray::from(vec![Some("b"), Some("a")]));
        let a_then_b =
            dict_with_values(&[Some(idx_a as i32), Some(idx_b as i32)], &values);

        // "a" vs group a is equal, "b" vs group a is not.
        let mut buf = all_true(2);
        col.vectorized_equal_to(&[group_a, group_a], &a_then_b, &[0, 1], &mut buf);
        assert_eq!(bool_vec(&buf), vec![true, false]);
        assert_eq!(col.val_to_inner[idx_a], slot_a);
        assert_eq!(
            col.val_to_inner[idx_b],
            usize::MAX,
            "unequal result was cached"
        );

        // Later, "b" vs group b fills the entry that was left unresolved.
        let only_b = dict_with_values(&[Some(idx_b as i32)], &values);
        let mut buf = all_true(1);
        col.vectorized_equal_to(&[group_b], &only_b, &[0], &mut buf);
        assert_eq!(bool_vec(&buf), vec![true]);
        assert_eq!(col.val_to_inner[idx_b], slot_b);
    }

    /// A non-null key pointing at a null value and a null key must both
    /// compare equal to the null group, and only the former goes through
    /// `val_to_inner`.
    #[test]
    fn vectorized_equal_to_matches_null_value_and_null_key_to_null_group() {
        let mut col = utf8_col();
        col.vectorized_append(&i32_dict(&[None, Some(0)], &[Some("a")]), &[0, 1])
            .unwrap();
        let (null_group, group_a) = (0, 1);
        let null_slot = col.null_inner_slot.unwrap();

        let idx_null = 0;
        let values: ArrayRef = Arc::new(StringArray::from(vec![None, Some("a")]));
        let batch = dict_with_values(
            &[Some(idx_null as i32), Some(idx_null as i32), None],
            &values,
        );

        // null value vs null group, null value vs group a, null key vs null group.
        let mut buf = all_true(3);
        col.vectorized_equal_to(
            &[null_group, group_a, null_group],
            &batch,
            &[0, 1, 2],
            &mut buf,
        );
        assert_eq!(bool_vec(&buf), vec![true, false, true]);
        assert_eq!(col.val_to_inner[idx_null], null_slot);
    }

    /// Fewer rows than values in an uncached values array takes the per-row
    /// fallback, which must not rebuild the cache for that array.
    #[test]
    fn vectorized_equal_to_small_batch_of_new_values_skips_cache_rebuild() {
        let old_values: ArrayRef = Arc::new(StringArray::from(vec![Some("a")]));
        let mut col = utf8_col();
        col.vectorized_append(&dict_with_values(&[Some(0)], &old_values), &[0])
            .unwrap();
        let group_a = 0;

        // One row against three values in an array the cache has not seen.
        let new_values: ArrayRef =
            Arc::new(StringArray::from(vec![Some("x"), Some("a"), Some("y")]));
        let idx_a = 1;
        let only_a = dict_with_values(&[Some(idx_a)], &new_values);
        let mut buf = all_true(1);
        col.vectorized_equal_to(&[group_a], &only_a, &[0], &mut buf);
        assert_eq!(bool_vec(&buf), vec![true]);
        assert!(
            col.is_cached(&old_values),
            "fallback must leave the cache on the previous values array"
        );
    }
}