arrow-select 60.2.0

Selection kernels for arrow arrays
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
// 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

//! Dictionary utilities for Arrow arrays

use std::{collections::HashMap, sync::Arc};

use crate::filter::filter;
use crate::interleave::interleave;
use ahash::RandomState;
use arrow_array::builder::BooleanBufferBuilder;
use arrow_array::types::{
    ArrowDictionaryKeyType, ArrowPrimitiveType, BinaryType, ByteArrayType, LargeBinaryType,
    LargeUtf8Type, Utf8Type,
};
use arrow_array::{
    AnyDictionaryArray, Array, ArrayRef, ArrowNativeTypeOp, BooleanArray, DictionaryArray,
    GenericByteArray, PrimitiveArray, downcast_dictionary_array,
};
use arrow_array::{cast::AsArray, downcast_primitive};
use arrow_buffer::{ArrowNativeType, BooleanBuffer, ScalarBuffer, ToByteSlice};
use arrow_schema::{ArrowError, DataType};

/// Garbage collects a [DictionaryArray] by removing unreferenced values.
///
/// Returns a new [DictionaryArray] such that there are no values
/// that are not referenced by at least one key. There may still be duplicate
/// values.
///
/// See also [`garbage_collect_any_dictionary`] if you need to handle multiple dictionary types
pub fn garbage_collect_dictionary<K: ArrowDictionaryKeyType>(
    dictionary: &DictionaryArray<K>,
) -> Result<DictionaryArray<K>, ArrowError> {
    let keys = dictionary.keys();
    let values = dictionary.values();

    let mask = dictionary.occupancy();

    // If no work to do, return the original dictionary
    if mask.count_set_bits() == values.len() {
        return Ok(dictionary.clone());
    }

    // Create a mapping from the old keys to the new keys, use a Vec for easy indexing
    let mut key_remap = vec![K::Native::ZERO; values.len()];
    for (new_idx, old_idx) in mask.set_indices().enumerate() {
        key_remap[old_idx] =
            K::Native::from_usize(new_idx).ok_or(ArrowError::DictionaryKeyOverflowError)?;
    }

    // ... and then build the new keys array
    let new_keys = keys.unary(|key| {
        key_remap
            .get(key.as_usize())
            .copied()
            // nulls may be present in the keys, and they will have arbitrary value; we don't care
            // and can safely return zero
            .unwrap_or(K::Native::ZERO)
    });

    // Create a new values array by filtering using the mask
    let values = filter(dictionary.values(), &BooleanArray::new(mask, None))?;

    DictionaryArray::try_new(new_keys, values)
}

/// Equivalent to [`garbage_collect_dictionary`] but without requiring casting to a specific key type.
pub fn garbage_collect_any_dictionary(
    dictionary: &dyn AnyDictionaryArray,
) -> Result<ArrayRef, ArrowError> {
    let dictionary: &dyn Array = dictionary;
    downcast_dictionary_array!(
        dictionary => garbage_collect_dictionary(dictionary).map(|dict| Arc::new(dict) as ArrayRef),
        _ => unreachable!("have a dictionary array")
    )
}

/// A best effort interner that maintains a fixed number of buckets
/// and interns keys based on their hash value
///
/// Hash collisions will result in replacement
struct Interner<'a, V> {
    state: RandomState,
    buckets: Vec<Option<InternerBucket<'a, V>>>,
    shift: u32,
}

/// A single bucket in [`Interner`].
type InternerBucket<'a, V> = (Option<&'a [u8]>, V);

impl<'a, V> Interner<'a, V> {
    /// Capacity controls the number of unique buckets allocated within the Interner
    ///
    /// A larger capacity reduces the probability of hash collisions, and should be set
    /// based on an approximation of the upper bound of unique values
    fn new(capacity: usize) -> Self {
        // Add additional buckets to help reduce collisions
        let shift = (capacity as u64 + 128).leading_zeros();
        let num_buckets = (u64::MAX >> shift) as usize;
        let buckets = (0..num_buckets.saturating_add(1)).map(|_| None).collect();
        Self {
            // A fixed seed to ensure deterministic behaviour
            state: RandomState::with_seeds(0, 0, 0, 0),
            buckets,
            shift,
        }
    }

    fn intern<F: FnOnce() -> Result<V, E>, E>(
        &mut self,
        new: Option<&'a [u8]>,
        f: F,
    ) -> Result<&V, E> {
        let hash = self.state.hash_one(new);
        let bucket_idx = hash >> self.shift;
        Ok(match &mut self.buckets[bucket_idx as usize] {
            Some((current, v)) => {
                if *current != new {
                    *v = f()?;
                    *current = new;
                }
                v
            }
            slot => &slot.insert((new, f()?)).1,
        })
    }
}

// Sparse hashing pays off only when retained values greatly outnumber key lookups.
pub(crate) const MAX_DENSE_MAPPING_VALUES_PER_ROW: usize = 256;

pub(crate) enum KeyMapping<K: ArrowDictionaryKeyType> {
    Dense(Vec<K::Native>),
    Sparse(HashMap<usize, K::Native, RandomState>),
}

impl<K: ArrowDictionaryKeyType> KeyMapping<K> {
    fn new_dense(len: usize) -> Self {
        Self::Dense(vec![K::Native::ZERO; len])
    }

    fn new_sparse(capacity: usize) -> Self {
        Self::Sparse(HashMap::with_capacity_and_hasher(
            capacity,
            RandomState::with_seeds(0, 0, 0, 0),
        ))
    }

    fn insert(&mut self, old_key: usize, new_key: K::Native) {
        match self {
            Self::Dense(mapping) => mapping[old_key] = new_key,
            Self::Sparse(mapping) => {
                mapping.insert(old_key, new_key);
            }
        }
    }

    #[inline]
    pub fn get(&self, old_key: usize) -> Option<K::Native> {
        match self {
            Self::Dense(mapping) => mapping.get(old_key).copied(),
            Self::Sparse(mapping) => mapping.get(&old_key).copied(),
        }
    }
}

pub(crate) struct MergedDictionaries<K: ArrowDictionaryKeyType> {
    /// Maps each input dictionary key to its merged key.
    pub key_mappings: Vec<KeyMapping<K>>,
    /// The new values
    pub values: ArrayRef,
}

/// Performs a cheap, pointer-based comparison of two byte array
///
/// See [`ScalarBuffer::ptr_eq`]
fn bytes_ptr_eq<T: ByteArrayType>(a: &dyn Array, b: &dyn Array) -> bool {
    match (a.as_bytes_opt::<T>(), b.as_bytes_opt::<T>()) {
        (Some(a), Some(b)) => {
            let values_eq = a.values().ptr_eq(b.values()) && a.offsets().ptr_eq(b.offsets());
            match (a.nulls(), b.nulls()) {
                (Some(a), Some(b)) => values_eq && a.inner().ptr_eq(b.inner()),
                (None, None) => values_eq,
                _ => false,
            }
        }
        _ => false,
    }
}

/// Returns `true` if two child value arrays have the same layout and backing buffers.
///
/// This first checks whether the [`ArrayRef`]s point to the same allocation, then uses
/// direct buffer comparisons for byte arrays and [`arrow_data::ArrayData::ptr_eq`] for
/// other types.
///
/// This checks storage identity, not logical equality. Arrays with equal values in
/// different buffers return `false`. Arrays with no allocated storage, such as two empty
/// primitive arrays built from empty `Vec`s or two [`arrow_array::NullArray`]s of the same
/// length, return `true`.
pub(crate) fn child_values_ptr_eq(left: &ArrayRef, right: &ArrayRef) -> bool {
    if Arc::ptr_eq(left, right) {
        return true;
    }

    match left.data_type() {
        DataType::Utf8 => bytes_ptr_eq::<Utf8Type>(left.as_ref(), right.as_ref()),
        DataType::LargeUtf8 => bytes_ptr_eq::<LargeUtf8Type>(left.as_ref(), right.as_ref()),
        DataType::Binary => bytes_ptr_eq::<BinaryType>(left.as_ref(), right.as_ref()),
        DataType::LargeBinary => bytes_ptr_eq::<LargeBinaryType>(left.as_ref(), right.as_ref()),
        _ => left.to_data().ptr_eq(&right.to_data()),
    }
}

/// A type-erased function that compares two array for pointer equality
type PtrEq = fn(&dyn Array, &dyn Array) -> bool;

/// A weak heuristic of whether to merge dictionary values that aims to only
/// perform the expensive merge computation when it is likely to yield at least
/// some return over the naive approach used by MutableArrayData
///
/// `len` is the total length of the merged output
///
/// Returns `(should_merge, has_overflow)` where:
/// - `should_merge`: whether dictionary values should be merged
/// - `has_overflow`: whether the combined dictionary values would overflow the key type
pub(crate) fn should_merge_dictionary_values<K: ArrowDictionaryKeyType>(
    dictionaries: &[&DictionaryArray<K>],
    len: usize,
) -> (bool, bool) {
    use DataType::*;
    let first_values = dictionaries[0].values().as_ref();
    let ptr_eq: PtrEq = match first_values.data_type() {
        Utf8 => bytes_ptr_eq::<Utf8Type>,
        LargeUtf8 => bytes_ptr_eq::<LargeUtf8Type>,
        Binary => bytes_ptr_eq::<BinaryType>,
        LargeBinary => bytes_ptr_eq::<LargeBinaryType>,
        dt => {
            if !dt.is_primitive() {
                return (
                    false,
                    K::Native::from_usize(dictionaries.iter().map(|d| d.values().len()).sum())
                        .is_none(),
                );
            }
            |a, b| a.to_data().ptr_eq(&b.to_data())
        }
    };

    let mut single_dictionary = true;
    let mut total_values = first_values.len();
    for dict in dictionaries.iter().skip(1) {
        let values = dict.values().as_ref();
        total_values += values.len();
        if single_dictionary {
            single_dictionary = ptr_eq(first_values, values)
        }
    }

    let overflow = K::Native::from_usize(total_values).is_none();
    let values_exceed_length = total_values >= len;

    (
        !single_dictionary && (overflow || values_exceed_length),
        overflow,
    )
}

/// Given an array of dictionaries and an optional key mask compute a values array
/// containing referenced values, along with mappings from the [`DictionaryArray`]
/// keys to the new keys within this values array. Best-effort will be made to ensure
/// that the dictionary values are unique
///
/// This method is meant to be very fast and the output dictionary values
/// may not be unique, unlike `GenericByteDictionaryBuilder` which is slower
/// but produces unique values. `key_lookups` is the number of times each
/// input's keys will be remapped, and defaults to the input length.
pub(crate) fn merge_dictionary_values<K: ArrowDictionaryKeyType>(
    dictionaries: &[&DictionaryArray<K>],
    masks: Option<&[BooleanBuffer]>,
    key_lookups: Option<&[usize]>,
) -> Result<MergedDictionaries<K>, ArrowError> {
    let mut num_values = 0;

    let mut values_arrays = Vec::with_capacity(dictionaries.len());
    let mut value_slices = Vec::with_capacity(dictionaries.len());

    for (idx, dictionary) in dictionaries.iter().enumerate() {
        let mask = masks.and_then(|m| m.get(idx));
        let key_mask_owned;
        let key_mask = match (dictionary.nulls(), mask) {
            (Some(n), None) => Some(n.inner()),
            (None, Some(n)) => Some(n),
            (Some(n), Some(m)) => {
                key_mask_owned = n.inner() & m;
                Some(&key_mask_owned)
            }
            (None, None) => None,
        };
        let keys = dictionary.keys().values();
        let values = dictionary.values().as_ref();
        let lookups = key_lookups.map_or(keys.len(), |lookups| lookups[idx]);
        let use_sparse_mapping =
            values.len() > lookups.saturating_mul(MAX_DENSE_MAPPING_VALUES_PER_ROW);

        let selected_values = if use_sparse_mapping {
            let referenced_keys = compute_referenced_keys(keys, key_mask);
            let len = referenced_keys.len();
            get_selected_values(values, referenced_keys.into_iter(), len)
        } else {
            let values_mask = compute_values_mask(keys, key_mask, values.len());
            let len = values_mask.count_set_bits();
            get_selected_values(values, values_mask.set_indices(), len)
        };
        num_values += selected_values.len();
        value_slices.push((selected_values, use_sparse_mapping));
        values_arrays.push(values)
    }

    // Map from value to new index
    let mut interner = Interner::new(num_values);
    // Interleave indices for new values array
    let mut indices = Vec::with_capacity(num_values);

    // Compute the mapping for each dictionary
    let key_mappings = dictionaries
        .iter()
        .enumerate()
        .zip(value_slices)
        .map(
            |((dictionary_idx, dictionary), (values, use_sparse_mapping))| {
                let mut mapping = match use_sparse_mapping {
                    true => KeyMapping::new_sparse(values.len()),
                    false => KeyMapping::new_dense(dictionary.values().len()),
                };

                for (value_idx, value) in values {
                    let new_key =
                        *interner.intern(value, || match K::Native::from_usize(indices.len()) {
                            Some(idx) => {
                                indices.push((dictionary_idx, value_idx));
                                Ok(idx)
                            }
                            None => Err(ArrowError::DictionaryKeyOverflowError),
                        })?;
                    mapping.insert(value_idx, new_key);
                }
                Ok(mapping)
            },
        )
        .collect::<Result<Vec<_>, ArrowError>>()?;

    Ok(MergedDictionaries {
        key_mappings,
        values: interleave(&values_arrays, &indices)?,
    })
}

/// Merges referenced entries from multiple dictionary values arrays.
///
/// `values_masks[i]` corresponds to `values_arrays[i]`, with each set bit identifying a
/// value to retain. Returns the merged values and a mapping from each source value index
/// to its index in the merged array. Mapping entries for unreferenced values are zero and
/// must not be used.
///
/// Referenced values are gathered without hashing when their count fits in `K`'s key space,
/// preserving duplicates across sources. Otherwise, values are deduplicated on a best-effort
/// basis to avoid key overflow.
pub(crate) fn merge_dictionary_values_with_masks<K: ArrowDictionaryKeyType>(
    values_arrays: &[&dyn Array],
    values_masks: &[BooleanBuffer],
) -> Result<MergedDictionaries<K>, ArrowError> {
    assert_eq!(values_arrays.len(), values_masks.len());
    let num_values = values_masks.iter().map(BooleanBuffer::count_set_bits).sum();

    // Dictionary values need not be unique. Avoid hashing when the referenced value count
    // fits in `K`'s key space, and only deduplicate to avoid overflow.
    if num_values == 0 || K::Native::from_usize(num_values - 1).is_some() {
        let zero = K::Native::from_usize(0).unwrap();
        let mut indices = Vec::with_capacity(num_values);
        let key_mappings = values_arrays
            .iter()
            .zip(values_masks)
            .enumerate()
            .map(|(dictionary_idx, (values, mask))| {
                let mut mapping = vec![zero; values.len()];
                for value_idx in mask.set_indices() {
                    mapping[value_idx] = K::Native::from_usize(indices.len()).unwrap();
                    indices.push((dictionary_idx, value_idx));
                }
                KeyMapping::Dense(mapping)
            })
            .collect();
        return Ok(MergedDictionaries {
            key_mappings,
            values: interleave(values_arrays, &indices)?,
        });
    }

    let value_slices = values_arrays
        .iter()
        .zip(values_masks)
        .map(|(values, mask)| {
            let len = mask.count_set_bits();
            get_selected_values(*values, mask.set_indices(), len)
        })
        .collect::<Vec<_>>();
    let mut interner = Interner::new(num_values);
    let mut indices = Vec::with_capacity(num_values);

    let key_mappings = values_arrays
        .iter()
        .enumerate()
        .zip(value_slices)
        .map(|((dictionary_idx, value_array), values)| {
            let zero = K::Native::ZERO;
            let mut mapping = vec![zero; value_array.len()];

            for (value_idx, value) in values {
                mapping[value_idx] =
                    *interner.intern(value, || match K::Native::from_usize(indices.len()) {
                        Some(idx) => {
                            indices.push((dictionary_idx, value_idx));
                            Ok(idx)
                        }
                        None => Err(ArrowError::DictionaryKeyOverflowError),
                    })?;
            }
            Ok(KeyMapping::Dense(mapping))
        })
        .collect::<Result<Vec<_>, ArrowError>>()?;

    Ok(MergedDictionaries {
        key_mappings,
        values: interleave(values_arrays, &indices)?,
    })
}

/// Returns the unique dictionary keys referenced by the selected rows.
///
/// Sorting makes repeated keys adjacent for deduplication and preserves the
/// ascending dictionary-key order of the dense mask path. This keeps the sparse
/// and dense paths' merged values ordered consistently.
fn compute_referenced_keys<K: ArrowNativeType>(
    keys: &ScalarBuffer<K>,
    mask: Option<&BooleanBuffer>,
) -> Vec<usize> {
    let mut indices = match mask {
        Some(mask) => mask
            .set_indices()
            .map(|idx| keys[idx].as_usize())
            .collect::<Vec<_>>(),
        None => keys.iter().map(|key| key.as_usize()).collect(),
    };
    indices.sort_unstable();
    indices.dedup();
    indices
}

/// Return a mask identifying the values that are referenced by keys in `dictionary`
/// at the positions indicated by `selection`
fn compute_values_mask<K: ArrowNativeType>(
    keys: &ScalarBuffer<K>,
    mask: Option<&BooleanBuffer>,
    max_key: usize,
) -> BooleanBuffer {
    let mut builder = BooleanBufferBuilder::new(max_key);
    builder.advance(max_key);

    match mask {
        Some(n) => n
            .set_indices()
            .for_each(|idx| builder.set_bit(keys[idx].as_usize(), true)),
        None => keys
            .iter()
            .for_each(|k| builder.set_bit(k.as_usize(), true)),
    }
    builder.finish()
}

fn selected_primitives_to_bytes<T: ArrowPrimitiveType, I: Iterator<Item = usize>>(
    array: &PrimitiveArray<T>,
    indices: I,
    len: usize,
) -> Vec<(usize, Option<&[u8]>)>
where
    T::Native: ToByteSlice,
{
    let mut out = Vec::with_capacity(len);
    let values = array.values();
    for idx in indices {
        out.push((
            idx,
            array.is_valid(idx).then_some(values[idx].to_byte_slice()),
        ))
    }
    out
}

macro_rules! selected_primitive_to_bytes_helper {
    ($t:ty, $array:expr, $indices:expr, $len:expr) => {
        selected_primitives_to_bytes::<$t, _>($array.as_primitive(), $indices, $len)
    };
}

fn get_selected_values<I: Iterator<Item = usize>>(
    array: &dyn Array,
    indices: I,
    len: usize,
) -> Vec<(usize, Option<&[u8]>)> {
    downcast_primitive! {
        array.data_type() => (selected_primitive_to_bytes_helper, array, indices, len),
        DataType::Utf8 => selected_bytes(array.as_string::<i32>(), indices, len),
        DataType::LargeUtf8 => selected_bytes(array.as_string::<i64>(), indices, len),
        DataType::Binary => selected_bytes(array.as_binary::<i32>(), indices, len),
        DataType::LargeBinary => selected_bytes(array.as_binary::<i64>(), indices, len),
        _ => unimplemented!("Dictionary merging for type {} is not implemented", array.data_type()),
    }
}

fn selected_bytes<T: ByteArrayType, I: Iterator<Item = usize>>(
    array: &GenericByteArray<T>,
    indices: I,
    len: usize,
) -> Vec<(usize, Option<&[u8]>)> {
    let mut out = Vec::with_capacity(len);
    for idx in indices {
        out.push((
            idx,
            array.is_valid(idx).then_some(array.value(idx).as_ref()),
        ))
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    use arrow_array::cast::as_string_array;
    use arrow_array::types::{Int8Type, Int32Type, UInt8Type};
    use arrow_array::{
        ArrayRef, DictionaryArray, Int8Array, Int32Array, ListArray, NullArray, RunArray,
        StringArray, StringViewArray, UInt8Array,
    };
    use arrow_buffer::{BooleanBuffer, Buffer, NullBuffer, OffsetBuffer};
    use arrow_schema::Field;
    use std::sync::Arc;

    fn assert_mapping(mapping: &KeyMapping<Int32Type>, expected: &[i32]) {
        let KeyMapping::Dense(actual) = mapping else {
            panic!("expected a dense mapping");
        };
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_child_values_ptr_eq_accepts_reusable_value_mapping() {
        let dictionary = DictionaryArray::<Int8Type>::new(
            Int8Array::from(vec![0, 1]),
            Arc::new(StringArray::from(vec!["a", "b"])),
        );
        let same_values = Arc::clone(dictionary.values());

        assert!(Arc::ptr_eq(dictionary.values(), &same_values));
        assert!(child_values_ptr_eq(dictionary.values(), &same_values));

        let shared_values = StringArray::from(vec!["a", "b"]);
        let first_dictionary = DictionaryArray::<Int8Type>::new(
            Int8Array::from(vec![0, 1]),
            Arc::new(shared_values.clone()),
        );
        let cloned_dictionary =
            DictionaryArray::<Int8Type>::new(Int8Array::from(vec![0, 1]), Arc::new(shared_values));

        assert!(!Arc::ptr_eq(
            first_dictionary.values(),
            cloned_dictionary.values()
        ));
        assert!(child_values_ptr_eq(
            first_dictionary.values(),
            cloned_dictionary.values()
        ));

        // Run boundaries do not affect whether the child value mapping can be reused.
        let run_values = StringArray::from(vec!["a", "b"]);
        let first_runs =
            RunArray::<Int32Type>::try_new(&Int32Array::from(vec![1, 3]), &run_values).unwrap();
        let second_runs =
            RunArray::<Int32Type>::try_new(&Int32Array::from(vec![2, 3]), &run_values).unwrap();

        assert!(!Arc::ptr_eq(first_runs.values(), second_runs.values()));
        assert!(child_values_ptr_eq(
            first_runs.values(),
            second_runs.values()
        ));

        // Arrays without allocated buffers still have a reusable value mapping.
        let empty_left: ArrayRef = Arc::new(Int32Array::from(Vec::<i32>::new()));
        let empty_right: ArrayRef = Arc::new(Int32Array::from(Vec::<i32>::new()));
        assert!(child_values_ptr_eq(&empty_left, &empty_right));

        let null_left: ArrayRef = Arc::new(NullArray::new(3));
        let null_right: ArrayRef = Arc::new(NullArray::new(3));
        assert!(child_values_ptr_eq(&null_left, &null_right));
    }

    #[test]
    fn test_child_values_ptr_eq_rejects_different_storage_or_layout() {
        let independent_left: ArrayRef = Arc::new(StringArray::from(vec!["a", "b"]));
        let independent_right: ArrayRef = Arc::new(StringArray::from(vec!["a", "b"]));

        assert!(!child_values_ptr_eq(&independent_left, &independent_right));

        let storage = Int32Array::from(vec![1, 2, 3]);
        let prefix: ArrayRef = Arc::new(storage.slice(0, 2));
        let shifted: ArrayRef = Arc::new(storage.slice(1, 2));
        let shorter: ArrayRef = Arc::new(storage.slice(0, 1));

        assert!(!child_values_ptr_eq(&prefix, &shifted));
        assert!(!child_values_ptr_eq(&prefix, &shorter));
    }

    #[test]
    fn test_child_values_ptr_eq_rejects_different_nested_or_view_storage() {
        // Shared parent metadata is insufficient when child or payload storage differs.
        let list_field = Arc::new(Field::new_list_field(DataType::Int32, false));
        let shared_offsets = OffsetBuffer::new(vec![0_i32, 2].into());
        let first_list: ArrayRef = Arc::new(ListArray::new(
            Arc::clone(&list_field),
            shared_offsets.clone(),
            Arc::new(Int32Array::from(vec![1, 2])),
            None,
        ));
        let second_list: ArrayRef = Arc::new(ListArray::new(
            list_field,
            shared_offsets,
            Arc::new(Int32Array::from(vec![1, 3])),
            None,
        ));
        assert!(!child_values_ptr_eq(&first_list, &second_list));

        let first_payload: &[u8] = b"same payload one";
        let second_payload: &[u8] = b"same payload two";
        let view = arrow_data::ByteView::new(first_payload.len() as u32, &first_payload[..4]);
        let shared_views = ScalarBuffer::from(vec![view.into()]);
        let first_view: ArrayRef = Arc::new(StringViewArray::new(
            shared_views.clone(),
            vec![Buffer::from_slice_ref(first_payload)],
            None,
        ));
        let second_view: ArrayRef = Arc::new(StringViewArray::new(
            shared_views,
            vec![Buffer::from_slice_ref(second_payload)],
            None,
        ));
        assert!(!child_values_ptr_eq(&first_view, &second_view));
    }

    #[test]
    fn test_garbage_collect_i32_dictionary() {
        let values = StringArray::from_iter_values(["a", "b", "c", "d"]);
        let keys = Int32Array::from_iter_values([0, 1, 1, 3, 0, 0, 1]);
        let dict = DictionaryArray::<Int32Type>::new(keys, Arc::new(values));

        // Only "a", "b", "d" are referenced, "c" is not
        let gc = garbage_collect_dictionary(&dict).unwrap();

        let expected_values = StringArray::from_iter_values(["a", "b", "d"]);
        let expected_keys = Int32Array::from_iter_values([0, 1, 1, 2, 0, 0, 1]);
        let expected = DictionaryArray::<Int32Type>::new(expected_keys, Arc::new(expected_values));

        assert_eq!(gc, expected);
    }

    #[test]
    fn test_garbage_collect_any_dictionary() {
        let values = StringArray::from_iter_values(["a", "b", "c", "d"]);
        let keys = Int32Array::from_iter_values([0, 1, 1, 3, 0, 0, 1]);
        let dict = DictionaryArray::<Int32Type>::new(keys, Arc::new(values));

        let gc = garbage_collect_any_dictionary(&dict).unwrap();

        let expected_values = StringArray::from_iter_values(["a", "b", "d"]);
        let expected_keys = Int32Array::from_iter_values([0, 1, 1, 2, 0, 0, 1]);
        let expected = DictionaryArray::<Int32Type>::new(expected_keys, Arc::new(expected_values));

        assert_eq!(gc.as_ref(), &expected);
    }

    #[test]
    fn test_garbage_collect_with_nulls() {
        let values = StringArray::from_iter_values(["a", "b", "c"]);
        let keys = Int8Array::from(vec![Some(2), None, Some(0)]);
        let dict = DictionaryArray::<Int8Type>::new(keys, Arc::new(values));

        let gc = garbage_collect_dictionary(&dict).unwrap();

        let expected_values = StringArray::from_iter_values(["a", "c"]);
        let expected_keys = Int8Array::from(vec![Some(1), None, Some(0)]);
        let expected = DictionaryArray::<Int8Type>::new(expected_keys, Arc::new(expected_values));

        assert_eq!(gc, expected);
    }

    #[test]
    fn test_garbage_collect_empty_dictionary() {
        let values = StringArray::from_iter_values::<&str, _>([]);
        let keys = Int32Array::from_iter_values([]);
        let dict = DictionaryArray::<Int32Type>::new(keys, Arc::new(values));

        let gc = garbage_collect_dictionary(&dict).unwrap();

        assert_eq!(gc, dict);
    }

    #[test]
    fn test_garbage_collect_dictionary_all_unreferenced() {
        let values = StringArray::from_iter_values(["a", "b", "c"]);
        let keys = Int32Array::from(vec![None, None, None]);
        let dict = DictionaryArray::<Int32Type>::new(keys, Arc::new(values));

        let gc = garbage_collect_dictionary(&dict).unwrap();

        // All keys are null, so dictionary values can be empty
        let expected_values = StringArray::from_iter_values::<&str, _>([]);
        let expected_keys = Int32Array::from(vec![None, None, None]);
        let expected = DictionaryArray::<Int32Type>::new(expected_keys, Arc::new(expected_values));

        assert_eq!(gc, expected);
    }

    #[test]
    fn test_merge_strings() {
        let a = DictionaryArray::<Int32Type>::from_iter(["a", "b", "a", "b", "d", "c", "e"]);
        let b = DictionaryArray::<Int32Type>::from_iter(["c", "f", "c", "d", "a", "d"]);
        let merged = merge_dictionary_values(&[&a, &b], None, None).unwrap();

        let values = as_string_array(merged.values.as_ref());
        let actual: Vec<_> = values.iter().map(Option::unwrap).collect();
        assert_eq!(&actual, &["a", "b", "d", "c", "e", "f"]);

        assert_eq!(merged.key_mappings.len(), 2);
        assert_mapping(&merged.key_mappings[0], &[0, 1, 2, 3, 4]);
        assert_mapping(&merged.key_mappings[1], &[3, 5, 2, 0]);

        let a_slice = a.slice(1, 4);
        let merged = merge_dictionary_values(&[&a_slice, &b], None, None).unwrap();

        let values = as_string_array(merged.values.as_ref());
        let actual: Vec<_> = values.iter().map(Option::unwrap).collect();
        assert_eq!(&actual, &["a", "b", "d", "c", "f"]);

        assert_eq!(merged.key_mappings.len(), 2);
        assert_mapping(&merged.key_mappings[0], &[0, 1, 2, 0, 0]);
        assert_mapping(&merged.key_mappings[1], &[3, 4, 2, 0]);

        // Mask out only ["b", "b", "d"] from a
        let a_mask = BooleanBuffer::from_iter([false, true, false, true, true, false, false]);
        let b_mask = BooleanBuffer::new_set(b.len());
        let merged = merge_dictionary_values(&[&a, &b], Some(&[a_mask, b_mask]), None).unwrap();

        let values = as_string_array(merged.values.as_ref());
        let actual: Vec<_> = values.iter().map(Option::unwrap).collect();
        assert_eq!(&actual, &["b", "d", "c", "f", "a"]);

        assert_eq!(merged.key_mappings.len(), 2);
        assert_mapping(&merged.key_mappings[0], &[0, 0, 1, 0, 0]);
        assert_mapping(&merged.key_mappings[1], &[2, 3, 1, 4]);
    }

    #[test]
    fn test_merge_dictionary_values_with_masks() {
        let first = StringArray::from_iter_values(["a", "unused-a", "shared"]);
        let second = StringArray::from_iter_values(["shared", "b", "unused-b"]);
        let values = [&first as &dyn Array, &second as &dyn Array];
        let masks = [
            BooleanBuffer::from_iter([true, false, true]),
            BooleanBuffer::from_iter([true, true, false]),
        ];

        let merged = merge_dictionary_values_with_masks::<Int32Type>(&values, &masks).unwrap();

        let expected = StringArray::from_iter_values(["a", "shared", "shared", "b"]);
        assert_eq!(merged.values.as_ref(), &expected);
        assert_mapping(&merged.key_mappings[0], &[0, 0, 1]);
        assert_mapping(&merged.key_mappings[1], &[2, 3, 0]);
    }

    #[test]
    fn test_merge_nulls() {
        let buffer = Buffer::from(b"helloworldbingohelloworld");
        let offsets = OffsetBuffer::from_lengths([5, 5, 5, 5, 5]);
        let nulls = NullBuffer::from(vec![true, false, true, true, true]);
        let values = StringArray::new(offsets, buffer, Some(nulls));

        let key_values = vec![1, 2, 3, 1, 8, 2, 3];
        let key_nulls = NullBuffer::from(vec![true, true, false, true, false, true, true]);
        let keys = Int32Array::new(key_values.into(), Some(key_nulls));
        let a = DictionaryArray::new(keys, Arc::new(values));
        // [NULL, "bingo", NULL, NULL, NULL, "bingo", "hello"]

        let b = DictionaryArray::new(Int32Array::new_null(10), Arc::new(StringArray::new_null(0)));

        let merged = merge_dictionary_values(&[&a, &b], None, None).unwrap();
        let expected = StringArray::from(vec![None, Some("bingo"), Some("hello")]);
        assert_eq!(merged.values.as_ref(), &expected);
        assert_eq!(merged.key_mappings.len(), 2);
        assert_mapping(&merged.key_mappings[0], &[0, 0, 1, 2, 0]);
        assert_mapping(&merged.key_mappings[1], &[]);
    }

    #[test]
    fn test_merge_keys_smaller() {
        let values = StringArray::from_iter_values(["a", "b"]);
        let keys = Int32Array::from_iter_values([1]);
        let a = DictionaryArray::new(keys, Arc::new(values));

        let merged = merge_dictionary_values(&[&a], None, None).unwrap();
        let expected = StringArray::from(vec!["b"]);
        assert_eq!(merged.values.as_ref(), &expected);
    }

    #[test]
    fn test_compute_referenced_keys_preserves_dense_order() {
        let keys = Int32Array::from_iter_values([999, 1, 500, 1, 999]);

        let actual = compute_referenced_keys(keys.values(), None);

        assert_eq!(actual, vec![1, 500, 999]);
    }

    #[test]
    fn test_sparse_gate_counts_key_lookups() {
        let values: ArrayRef = Arc::new(StringArray::from_iter_values(
            (0..8 * MAX_DENSE_MAPPING_VALUES_PER_ROW).map(|idx| idx.to_string()),
        ));
        let is_sparse = |dictionary: &DictionaryArray<Int32Type>,
                         masks: Option<&[BooleanBuffer]>,
                         lookups: Option<&[usize]>| {
            let merged = merge_dictionary_values(&[dictionary], masks, lookups).unwrap();
            matches!(merged.key_mappings[0], KeyMapping::Sparse(_))
        };

        // One valid row of ten is over the gate by selected rows, but concat remaps all ten.
        let keys = Int32Array::from_iter((0..10).map(|idx| (idx == 0).then_some(999)));
        let mostly_null = DictionaryArray::new(keys, Arc::clone(&values));
        assert!(!is_sparse(&mostly_null, None, None));

        // Seven lookups stay under the gate, keeping the sparse path.
        let keys = Int32Array::from_iter_values([999; 7]);
        let short = DictionaryArray::new(keys, Arc::clone(&values));
        assert!(is_sparse(&short, None, None));

        // Interleave may look up the selected row more than once.
        let mask = BooleanBuffer::collect_bool(7, |idx| idx == 0);
        assert!(!is_sparse(
            &short,
            Some(std::slice::from_ref(&mask)),
            Some(&[10]),
        ));
        assert!(is_sparse(&short, Some(&[mask]), Some(&[7])));
    }

    #[test]
    fn test_merge_oversized_dictionary_slice() {
        let values_len = 4 * MAX_DENSE_MAPPING_VALUES_PER_ROW + 1;
        let values = StringArray::from_iter_values((0..values_len).map(|idx| idx.to_string()));
        let last = values_len as i32 - 1;
        let keys = Int32Array::from(vec![Some(last), None, Some(1), Some(last)]);
        let dictionary = DictionaryArray::new(keys, Arc::new(values));

        let merged = merge_dictionary_values(&[&dictionary], None, None).unwrap();
        let values = as_string_array(merged.values.as_ref());
        let actual = values.iter().collect::<Vec<_>>();
        let last_value = last.to_string();

        assert_eq!(actual, vec![Some("1"), Some(last_value.as_str())]);
        assert!(matches!(merged.key_mappings[0], KeyMapping::Sparse(_)));
        assert_eq!(merged.key_mappings[0].get(1), Some(0));
        assert_eq!(merged.key_mappings[0].get(last as usize), Some(1));
        assert_eq!(merged.key_mappings[0].get(500), None);
    }

    #[test]
    fn test_merge_sparse_dictionary_overflow() {
        const UNIQUE_VALUES: usize = u8::MAX as usize + 2;

        // One sparse value per dictionary exceeds the 256 values representable by UInt8.
        let dictionaries = (0..UNIQUE_VALUES)
            .map(|dictionary_idx| {
                let values = StringArray::from_iter_values(
                    (0..=MAX_DENSE_MAPPING_VALUES_PER_ROW)
                        .map(|value_idx| format!("{dictionary_idx}-{value_idx}")),
                );
                let keys = UInt8Array::from_iter_values([0]);
                DictionaryArray::<UInt8Type>::new(keys, Arc::new(values))
            })
            .collect::<Vec<_>>();
        let dictionaries = dictionaries.iter().collect::<Vec<_>>();

        let result = merge_dictionary_values(&dictionaries, None, None);

        assert!(matches!(
            result,
            Err(ArrowError::DictionaryKeyOverflowError)
        ));
    }
}