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
// 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

//! A wrapper around `hashbrown::HashTable` that allows entries to be tracked by index

use crate::aggregates::group_values::HashValue;
use arrow::array::types::{IntervalDayTime, IntervalMonthDayNano};
use arrow::array::{
    Array, ArrayRef, ArrowNativeTypeOp, ArrowPrimitiveType, LargeStringArray,
    PrimitiveArray, StringArray, StringViewArray, builder::PrimitiveBuilder,
    cast::AsArray, downcast_primitive,
};
use arrow::array::{ArrayAccessor, StringArrayType};
use arrow::datatypes::{DataType, i256};
use datafusion_common::Result;
use datafusion_common::exec_datafusion_err;
use datafusion_common::hash_utils::RandomState;
use half::f16;
use hashbrown::hash_table::{Entry, HashTable};
use std::borrow::BorrowMut;
use std::fmt::Debug;
use std::hash::BuildHasher;
use std::sync::Arc;

/// `heap_idx` assigned to groups whose aggregate values are all NULL.
/// Such groups are tracked in the hash table only, without entering heap,
/// so they can be emitted with a NULL aggregate value at the end.
const NULL_HEAP_IDX: usize = usize::MAX - 1;

/// `heap_idx` needs to distinguish vacant slots from items that have a NULL key and value.
const VACANT_HEAP_IDX: usize = usize::MAX;

/// An entry in our hash table that:
/// 1. memoizes the hash
/// 2. contains the key (ID)
/// 3. contains the value (heap_idx - an index into the corresponding heap)
pub struct HashTableItem<ID> {
    hash: u64,
    pub id: Option<ID>,
    pub heap_idx: usize,
}

/// A custom wrapper around `hashbrown::HashTable` that:
/// 1. limits the number of entries to the top K
/// 2. Allocates a capacity greater than top K to maintain a low-fill factor and prevent resizing
/// 3. Tracks indexes to allow corresponding heap to refer to entries by index vs hash
struct TopKHashTable<ID> {
    map: HashTable<usize>,
    // Store the actual items separately to allow for index-based access
    store: Vec<HashTableItem<ID>>,
    // Free indexes in the store for reuse
    free_indices: Vec<usize>,
    // Pool of reusable value locations, usually Strings
    free_slots: Vec<ID>,
    // The maximum number of entries allowed
    limit: usize,
    // Number of entries registered as all-NULL (heap_idx == NULL_HEAP_IDX)
    null_count: usize,
}

/// Outcome of [`ArrowHashTable::find_or_insert`], letting the caller keep its
/// own all-NULL group accounting in sync without an extra lookup.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InsertKind {
    /// The group already existed as a valued group
    Existing,
    /// The group was newly inserted as a valued group
    New,
    /// The group was registered as all-NULL and has now been converted into a
    /// valued group
    ReplacedNull,
}

/// An interface to hide the generic type signature of TopKHashTable behind arrow arrays
pub trait ArrowHashTable {
    fn set_batch(&mut self, ids: ArrayRef);
    fn len(&self) -> usize;
    fn update_heap_idx(&mut self, mapper: &[(usize, usize)]);
    fn heap_idx_at(&self, map_idx: usize) -> usize;
    fn take_all(&mut self, indexes: Vec<usize>) -> ArrayRef;
    fn find_or_insert(
        &mut self,
        row_idx: usize,
        replace_idx: usize,
    ) -> (usize, InsertKind);
    /// Register the group at `row_idx` as all-NULL. Returns true if it was
    /// newly registered; false if the group is already tracked or the NULL
    /// group limit has been reached.
    fn insert_null(&mut self, row_idx: usize) -> bool;
    /// Remove the group at `row_idx` if it is registered as all-NULL. Returns
    /// true if a NULL registration was removed.
    fn remove_if_null(&mut self, row_idx: usize) -> bool;
    /// Store indexes of all groups registered as all-NULL. Returns null count.
    fn null_map_idxs(&self, out: &mut Vec<usize>) -> usize;
}

/// Returns true if the given data type can be used as a top-K aggregation hash key.
///
/// Supported types include Arrow primitives (integers, floats, decimals, intervals)
/// and UTF-8 strings (`Utf8`, `LargeUtf8`, `Utf8View`). This is used internally by
/// `PriorityMap::supports()` to validate grouping key type compatibility.
pub fn is_supported_hash_key_type(kt: &DataType) -> bool {
    kt.is_primitive()
        || matches!(
            kt,
            DataType::Utf8 | DataType::Utf8View | DataType::LargeUtf8
        )
}

// An implementation of ArrowHashTable for String keys
pub struct StringHashTable<S: Array>
where
    for<'a> &'a S: StringArrayType<'a>,
{
    owned: S,
    map: TopKHashTable<String>,
    rnd: RandomState,
}

// An implementation of ArrowHashTable for any `ArrowPrimitiveType` key
struct PrimitiveHashTable<VAL: ArrowPrimitiveType> {
    owned: PrimitiveArray<VAL>,
    map: TopKHashTable<VAL::Native>,
    rnd: RandomState,
    value_type: DataType,
}

impl<S> StringHashTable<S>
where
    S: Array + From<Vec<Option<String>>>,
    for<'a> &'a S: StringArrayType<'a>,
{
    pub fn new(limit: usize) -> Self {
        Self {
            owned: S::from(Vec::new()),
            map: TopKHashTable::new(limit, limit * 10),
            rnd: RandomState::default(),
        }
    }

    #[inline]
    fn eq_fn(id: Option<&str>) -> impl Fn(&Option<String>) -> bool {
        move |mi| id == mi.as_deref()
    }
}

impl<S> ArrowHashTable for StringHashTable<S>
where
    S: Array + Clone + From<Vec<Option<String>>> + 'static,
    for<'a> &'a S: StringArrayType<'a>,
{
    fn set_batch(&mut self, ids: ArrayRef) {
        self.owned = ids
            .as_any()
            .downcast_ref::<S>()
            .expect("Unsupported data type")
            .clone();
    }

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

    fn update_heap_idx(&mut self, mapper: &[(usize, usize)]) {
        self.map.update_heap_idx(mapper);
    }

    fn heap_idx_at(&self, map_idx: usize) -> usize {
        self.map.heap_idx_at(map_idx)
    }

    fn take_all(&mut self, indexes: Vec<usize>) -> ArrayRef {
        let ids = self.map.take_all(indexes);
        Arc::new(S::from(ids))
    }

    fn find_or_insert(
        &mut self,
        row_idx: usize,
        replace_idx: usize,
    ) -> (usize, InsertKind) {
        let id = some_value(&self.owned, row_idx);
        // Compute hash and create equality closure for hash table lookup.
        let hash = self.rnd.hash_one(id);

        // Use entry API to avoid double lookup
        self.map
            .find_or_insert(hash, id, replace_idx, Self::eq_fn(id))
    }

    fn insert_null(&mut self, row_idx: usize) -> bool {
        let id = some_value(&self.owned, row_idx);
        let hash = self.rnd.hash_one(id);
        self.map.insert_null(hash, id, Self::eq_fn(id))
    }

    fn remove_if_null(&mut self, row_idx: usize) -> bool {
        let id = some_value(&self.owned, row_idx);
        let hash = self.rnd.hash_one(id);
        self.map.remove_if_null(hash, Self::eq_fn(id))
    }

    fn null_map_idxs(&self, out: &mut Vec<usize>) -> usize {
        self.map.null_map_idxs(out)
    }
}

impl<VAL: ArrowPrimitiveType> PrimitiveHashTable<VAL>
where
    VAL::Native: HashValue,
    Option<VAL::Native>: HashValue,
{
    pub fn new(limit: usize, value_type: DataType) -> Self {
        Self {
            owned: PrimitiveArray::<VAL>::new_null(0).with_data_type(value_type.clone()),
            map: TopKHashTable::new(limit, limit * 10),
            rnd: RandomState::default(),
            value_type,
        }
    }

    /// Computes the id and its hash for the given row, for hash table lookups
    #[inline]
    fn id_and_hash(&self, row_idx: usize) -> (Option<VAL::Native>, u64) {
        let id = some_value(&self.owned, row_idx).map(HashValue::normalize_key);
        let hash: u64 = id.hash(&self.rnd);
        (id, hash)
    }

    #[inline]
    fn eq_fn(id: Option<VAL::Native>) -> impl Fn(&Option<VAL::Native>) -> bool {
        move |mi| match (id, *mi) {
            (Some(left), Some(right)) => left.is_eq(right),
            (None, None) => true,
            _ => false,
        }
    }
}

impl<VAL: ArrowPrimitiveType> ArrowHashTable for PrimitiveHashTable<VAL>
where
    VAL::Native: HashValue,
    Option<VAL::Native>: HashValue,
{
    fn set_batch(&mut self, ids: ArrayRef) {
        self.owned = ids.as_primitive().clone();
    }

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

    fn update_heap_idx(&mut self, mapper: &[(usize, usize)]) {
        self.map.update_heap_idx(mapper);
    }

    fn heap_idx_at(&self, map_idx: usize) -> usize {
        self.map.heap_idx_at(map_idx)
    }

    fn take_all(&mut self, indexes: Vec<usize>) -> ArrayRef {
        let ids = self.map.take_all(indexes);
        let mut builder: PrimitiveBuilder<VAL> =
            PrimitiveArray::builder(ids.len()).with_data_type(self.value_type.clone());
        for id in ids.into_iter() {
            builder.append_option(id);
        }
        let ids = builder.finish();
        Arc::new(ids)
    }

    fn find_or_insert(
        &mut self,
        row_idx: usize,
        replace_idx: usize,
    ) -> (usize, InsertKind) {
        let (id, hash) = self.id_and_hash(row_idx);
        // Use entry API to avoid double lookup
        self.map
            .find_or_insert(hash, id.as_ref(), replace_idx, Self::eq_fn(id))
    }

    fn insert_null(&mut self, row_idx: usize) -> bool {
        let (id, hash) = self.id_and_hash(row_idx);
        self.map.insert_null(hash, id.as_ref(), Self::eq_fn(id))
    }

    fn remove_if_null(&mut self, row_idx: usize) -> bool {
        let (id, hash) = self.id_and_hash(row_idx);
        self.map.remove_if_null(hash, Self::eq_fn(id))
    }

    fn null_map_idxs(&self, out: &mut Vec<usize>) -> usize {
        self.map.null_map_idxs(out)
    }
}

impl<ID> TopKHashTable<ID> {
    pub fn new(limit: usize, capacity: usize) -> Self {
        Self {
            map: HashTable::with_capacity(capacity),
            store: Vec::with_capacity(capacity),
            free_indices: Vec::new(),
            free_slots: Vec::new(),
            limit,
            null_count: 0,
        }
    }

    pub fn heap_idx_at(&self, map_idx: usize) -> usize {
        self.store[map_idx].heap_idx
    }

    /// Remove the entry stored at `map_idx`, freeing its store slot for reuse
    fn remove_at(&mut self, map_idx: usize) {
        let hash = self.store[map_idx].hash;
        let eq = |idx: &usize| *idx == map_idx;
        let hasher = |idx: &usize| self.store[*idx].hash;
        match self.map.entry(hash, eq, hasher) {
            Entry::Occupied(entry) => {
                let (removed_idx, _) = entry.remove();
                let mi = &mut self.store[removed_idx];
                debug_assert!(mi.is_occupied());
                mi.heap_idx = VACANT_HEAP_IDX;
                match mi.id.take() {
                    Some(slot) if Self::use_free_slots() => {
                        self.free_slots.push(slot);
                    }
                    _ => (),
                }
                self.free_indices.push(removed_idx);
            }
            Entry::Vacant(_) => unreachable!(),
        }
    }

    pub fn remove_if_full(&mut self, replace_idx: usize) -> usize {
        // All-NULL groups are tracked outside the heap, so only valued
        // groups count towards the limit here
        let valued_len = self.map.len() - self.null_count;
        if valued_len >= self.limit {
            self.remove_at(replace_idx);
            0 // if full, always replace top node
        } else {
            valued_len // if we're not full, always append to end
        }
    }

    fn update_heap_idx(&mut self, mapper: &[(usize, usize)]) {
        for (m, h) in mapper {
            self.store[*m].heap_idx = *h;
        }
    }

    /// Used to avoid pushing pointless copies of primitives to the `free_slots` pool.
    const fn use_free_slots() -> bool {
        std::mem::needs_drop::<ID>()
    }

    /// Find an existing entry or insert a new one, avoiding double hash table lookup.
    /// Returns (map_idx, kind) where kind describes whether the group already
    /// existed, was newly inserted, or was converted from an all-NULL group.
    /// If inserting a new entry and the table is full, replaces the entry at replace_idx.
    pub fn find_or_insert<Q>(
        &mut self,
        hash: u64,
        id: Option<&Q>,
        replace_idx: usize,
        mut eq: impl FnMut(&Option<ID>) -> bool,
    ) -> (usize, InsertKind)
    where
        Q: ToOwned<Owned = ID> + ?Sized,
    {
        // Check if entry exists - this is the only hash table lookup
        let mut replaced_null = false;

        let eq_fn = |idx: &usize| eq(&self.store[*idx].id);
        if let Some(&map_idx) = self.map.find(hash, eq_fn) {
            if self.store[map_idx].is_null() {
                // This group was registered as all-NULL but now produced a
                // value: unregister it so it is inserted as a valued group
                self.remove_at(map_idx);
                self.null_count -= 1;
                replaced_null = true;
            } else {
                return (map_idx, InsertKind::Existing);
            }
        }

        // Entry doesn't exist - compute heap_idx and prepare item
        let heap_idx = self.remove_if_full(replace_idx);
        let store_idx = self.push_store_item(hash, id, heap_idx);
        let kind = if replaced_null {
            InsertKind::ReplacedNull
        } else {
            InsertKind::New
        };
        (store_idx, kind)
    }

    fn push_store_item<Q>(&mut self, hash: u64, id: Option<&Q>, heap_idx: usize) -> usize
    where
        Q: ToOwned<Owned = ID> + ?Sized,
    {
        let id = if Self::use_free_slots() {
            id.map(|id| match self.free_slots.pop() {
                Some(mut slot) => {
                    id.clone_into(&mut slot);
                    slot
                }
                _ => id.to_owned(),
            })
        } else {
            debug_assert!(self.free_slots.is_empty(), "primitives should not pool");
            id.map(ToOwned::to_owned)
        };
        let mi = HashTableItem::new(hash, id, heap_idx);
        let store_idx = if let Some(idx) = self.free_indices.pop() {
            debug_assert!(self.store[idx].is_vacant(), "slot should be empty");
            self.store[idx] = mi;
            idx
        } else {
            self.store.push(mi);
            self.store.len() - 1
        };

        // Reserve space if needed
        let hasher = |idx: &usize| self.store[*idx].hash;
        if self.map.len() == self.map.capacity() {
            self.map.reserve(self.limit, hasher);
        }

        // Insert without checking again since we already confirmed it doesn't exist
        self.map.insert_unique(hash, store_idx, hasher);
        store_idx
    }

    /// Register a group whose aggregate values are all NULL, unless it is
    /// already tracked. NULL groups are stored with a sentinel `heap_idx` and
    /// never enter the heap. At most `limit` NULL groups are tracked: they all
    /// tie on the sort key, so any `limit` of them is a valid top-k superset.
    /// Returns true if the group was newly registered.
    pub fn insert_null<Q>(
        &mut self,
        hash: u64,
        id: Option<&Q>,
        mut eq: impl FnMut(&Option<ID>) -> bool,
    ) -> bool
    where
        Q: ToOwned<Owned = ID> + ?Sized,
        ID: BorrowMut<Q::Owned>,
    {
        let eq_fn = |idx: &usize| eq(&self.store[*idx].id);
        if self.map.find(hash, eq_fn).is_some() {
            return false;
        }

        if self.null_count >= self.limit {
            return false;
        }

        _ = self.push_store_item(hash, id, NULL_HEAP_IDX);
        self.null_count += 1;
        true
    }

    /// Remove the given group if it is registered as all-NULL. Used when an
    /// all-NULL group produces a value that loses to the current top-k: the
    /// group can no longer reach the top-k, but it must not be emitted with a
    /// NULL value either. Returns true if a NULL registration was removed.
    pub fn remove_if_null(
        &mut self,
        hash: u64,
        mut eq: impl FnMut(&Option<ID>) -> bool,
    ) -> bool {
        let eq_fn = |idx: &usize| eq(&self.store[*idx].id);
        if let Some(&map_idx) = self.map.find(hash, eq_fn)
            && self.store[map_idx].is_null()
        {
            self.remove_at(map_idx);
            self.null_count -= 1;
            return true;
        }
        false
    }

    /// Store indexes of all groups registered as all-NULL
    pub fn null_map_idxs(&self, out: &mut Vec<usize>) -> usize {
        let iter = self
            .store
            .iter()
            .enumerate()
            .filter_map(|(idx, item)| item.is_null().then_some(idx));

        let prev_len = out.len();
        out.extend(iter);

        debug_assert_eq!(out.len(), self.null_count + prev_len);
        self.null_count
    }

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

    pub fn take_all(&mut self, idxs: Vec<usize>) -> Vec<Option<ID>> {
        let ids = idxs
            .into_iter()
            .map(|idx| self.store[idx].id.take())
            .collect();
        self.map.clear();
        self.store.clear();
        self.free_indices.clear();
        // No need to clear free_slots.
        self.null_count = 0;
        ids
    }
}

impl<ID> HashTableItem<ID> {
    pub fn new(hash: u64, id: Option<ID>, heap_idx: usize) -> Self {
        Self { hash, id, heap_idx }
    }

    #[inline]
    pub fn is_null(&self) -> bool {
        self.heap_idx == NULL_HEAP_IDX
    }

    #[inline]
    pub fn is_vacant(&self) -> bool {
        self.heap_idx == VACANT_HEAP_IDX
    }

    #[inline]
    pub fn is_occupied(&self) -> bool {
        self.heap_idx != VACANT_HEAP_IDX
    }
}

impl HashValue for Option<String> {
    fn hash(&self, state: &RandomState) -> u64 {
        state.hash_one(self)
    }
}

macro_rules! hash_float {
    ($($t:ty),+) => {
        $(impl HashValue for Option<$t> {
            fn hash(&self, state: &RandomState) -> u64 {
                self.map(|me| me.hash(state)).unwrap_or(0)
            }
        })+
    };
}

macro_rules! has_integer {
    ($($t:ty),+) => {
        $(impl HashValue for Option<$t> {
            fn hash(&self, state: &RandomState) -> u64 {
                self.map(|me| me.hash(state)).unwrap_or(0)
            }
        })+
    };
}

has_integer!(i8, i16, i32, i64, i128, i256);
has_integer!(u8, u16, u32, u64);
has_integer!(IntervalDayTime, IntervalMonthDayNano);
hash_float!(f16, f32, f64);

#[inline]
fn some_value<'a, A>(array: &'a A, index: usize) -> Option<<&'a A as ArrayAccessor>::Item>
where
    &'a A: ArrayAccessor,
{
    if array.is_null(index) {
        None
    } else {
        Some(array.value(index))
    }
}

pub fn new_hash_table(
    limit: usize,
    kt: DataType,
) -> Result<Box<dyn ArrowHashTable + Send>> {
    macro_rules! downcast_helper {
        ($kt:ty, $d:ident) => {
            return Ok(Box::new(PrimitiveHashTable::<$kt>::new(limit, kt)))
        };
    }

    downcast_primitive! {
        kt => (downcast_helper, kt),
        DataType::Utf8 => return Ok(Box::new(StringHashTable::<StringArray>::new(limit))),
        DataType::LargeUtf8 => return Ok(Box::new(StringHashTable::<LargeStringArray>::new(limit))),
        DataType::Utf8View => return Ok(Box::new(StringHashTable::<StringViewArray>::new(limit))),
        _ => {}
    }

    Err(exec_datafusion_err!(
        "Can't create HashTable for type: {kt:?}"
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow::array::TimestampMillisecondArray;
    use arrow::datatypes::{Float16Type, Float32Type, Float64Type};
    use arrow_schema::TimeUnit;
    use std::collections::BTreeMap;

    fn assert_nulls<ID>(map: &TopKHashTable<ID>, expected: &[usize]) {
        assert_eq!(map.null_count, expected.len());
        let mut actual = Vec::new();
        assert_eq!(map.null_map_idxs(&mut actual), expected.len());
        assert_eq!(actual, expected);
    }

    fn check_float_keys<T: ArrowPrimitiveType>(
        nan: T::Native,
        other_nan: T::Native,
        negative_zero: T::Native,
    ) -> Result<()> {
        let ids: ArrayRef = Arc::new(PrimitiveArray::<T>::from_iter_values([
            nan,
            nan,
            other_nan,
            negative_zero,
            T::Native::default(),
        ]));
        let data_type = ids.data_type().clone();
        let mut ht = new_hash_table(3, data_type.clone())?;
        ht.set_batch(Arc::clone(&ids));

        let (nan_idx, kind) = ht.find_or_insert(0, 0);
        assert_eq!(kind, InsertKind::New);
        assert_eq!(ht.find_or_insert(1, 0), (nan_idx, InsertKind::Existing));
        let (_, kind) = ht.find_or_insert(2, 0);
        assert_eq!(kind, InsertKind::New);
        let (zero_idx, kind) = ht.find_or_insert(3, 0);
        assert_eq!(kind, InsertKind::New);
        assert_eq!(ht.find_or_insert(4, 0), (zero_idx, InsertKind::Existing));
        assert_eq!(ht.len(), 3);
        let keys = ht.take_all(vec![zero_idx]);
        assert!(
            keys.as_primitive::<T>()
                .value(0)
                .is_eq(T::Native::default())
        );

        // A NaN key must also survive NULL aggregate value transitions.
        assert!(ht.insert_null(0));
        assert!(!ht.insert_null(1));
        let (nan_idx, kind) = ht.find_or_insert(1, 0);
        assert_eq!(kind, InsertKind::ReplacedNull);
        ht.take_all(vec![nan_idx]);
        assert!(ht.insert_null(0));
        assert!(ht.remove_if_null(1));
        assert_eq!(ht.len(), 0);

        let mut ht = new_hash_table(1, data_type)?;
        ht.set_batch(ids);
        ht.find_or_insert(0, 0);
        let (zero_idx, kind) = ht.find_or_insert(3, 0);
        assert_eq!(kind, InsertKind::New);
        assert_eq!(ht.len(), 1);
        let keys = ht.take_all(vec![zero_idx]);
        assert!(
            keys.as_primitive::<T>()
                .value(0)
                .is_eq(T::Native::default())
        );
        Ok(())
    }

    #[test]
    fn should_handle_float_keys() -> Result<()> {
        check_float_keys::<Float16Type>(
            f16::from_bits(0x7e00),
            f16::from_bits(0x7e01),
            f16::from_bits(0x8000),
        )?;
        check_float_keys::<Float32Type>(
            f32::NAN,
            f32::from_bits(f32::NAN.to_bits() + 1),
            -0.0,
        )?;
        check_float_keys::<Float64Type>(
            f64::NAN,
            f64::from_bits(f64::NAN.to_bits() + 1),
            -0.0,
        )
    }

    #[test]
    fn should_emit_correct_type() -> Result<()> {
        let ids =
            TimestampMillisecondArray::from(vec![1000]).with_timezone("UTC".to_string());
        let dt = DataType::Timestamp(TimeUnit::Millisecond, Some("UTC".into()));
        let mut ht = new_hash_table(1, dt.clone())?;
        ht.set_batch(Arc::new(ids));
        ht.find_or_insert(0, 0);
        let ids = ht.take_all(vec![0]);
        assert_eq!(ids.data_type(), &dt);

        Ok(())
    }

    #[test]
    fn should_resize_properly() -> Result<()> {
        let mut heap_to_map = BTreeMap::<usize, usize>::new();
        // Create TopKHashTable with limit=5 and capacity=3 to force resizing
        let mut map = TopKHashTable::<String>::new(5, 3);

        // Insert 5 entries, tracking the heap-to-map index mapping
        for (heap_idx, id) in ["1", "2", "3", "4", "5"].iter().enumerate() {
            let value = Some(id.to_string());
            let hash = heap_idx as u64;
            let (map_idx, kind) =
                map.find_or_insert(hash, value.as_ref(), heap_idx, |v| *v == value);
            assert_eq!(kind, InsertKind::New, "Entry should be new");
            heap_to_map.insert(heap_idx, map_idx);
        }

        // Verify all 5 entries are present
        assert_eq!(map.len(), 5);

        // Verify that the hash table resized properly (capacity should have grown beyond 3)
        // This is implicit - if it didn't resize, insertions would have failed or been slow

        // Drain all values in heap order
        let (_heap_idxs, map_idxs): (Vec<_>, Vec<_>) = heap_to_map.into_iter().unzip();
        let ids = map.take_all(map_idxs);

        assert_eq!(
            format!("{ids:?}"),
            r#"[Some("1"), Some("2"), Some("3"), Some("4"), Some("5")]"#
        );
        assert_eq!(map.len(), 0, "Map should have been cleared!");

        Ok(())
    }

    #[test]
    fn should_track_null_groups() -> Result<()> {
        let mut map = TopKHashTable::<String>::new(2, 10);

        let a = Some("a".to_string());
        let b = Some("b".to_string());
        let c = Some("c".to_string());

        // register two all-NULL groups; the third exceeds the NULL group limit
        assert!(map.insert_null(100, a.as_ref(), |v| *v == a));
        assert!(map.insert_null(200, b.as_ref(), |v| *v == b));
        assert!(!map.insert_null(300, c.as_ref(), |v| *v == c));
        // re-registering an existing NULL group is a no-op
        assert!(!map.insert_null(100, a.as_ref(), |v| *v == a));
        assert_nulls(&map, &[0, 1]);

        // a valued insert for a NULL group converts it to a valued group
        let (map_idx, kind) = map.find_or_insert(200, b.as_ref(), 0, |v| *v == b);
        assert_eq!(kind, InsertKind::ReplacedNull, "NULL group should convert");
        assert_eq!(map.heap_idx_at(map_idx), 0, "Heap should append at 0");
        assert_nulls(&map, &[0]);

        // remove the remaining NULL group; removing twice is a no-op
        map.remove_if_null(100, |v| *v == a);
        assert_nulls(&map, &[]);
        map.remove_if_null(100, |v| *v == a);
        // removing a valued group via remove_if_null is a no-op
        map.remove_if_null(200, |v| *v == b);
        assert_eq!(map.len(), 1);

        Ok(())
    }

    #[test]
    fn should_track_null_id() {
        let mut map = TopKHashTable::<String>::new(2, 10);

        let hash = 0;
        let none = Option::<&str>::None;

        assert!(map.insert_null(hash, none, Option::is_none));
        assert_nulls(&map, &[0]);

        assert!(!map.insert_null(hash, none, Option::is_none));
        assert_nulls(&map, &[0]);

        assert!(map.remove_if_null(hash, Option::is_none));
        assert_nulls(&map, &[]);
    }

    #[test]
    fn should_reuse_all_freed_store_slots() -> Result<()> {
        let mut map = TopKHashTable::<String>::new(1, 10);

        let a = Some("a".to_string());
        let b = Some("b".to_string());
        let c = Some("c".to_string());

        let (b_idx, kind) = map.find_or_insert(100, b.as_ref(), 0, |v| *v == b);
        assert_eq!(kind, InsertKind::New);
        assert!(map.insert_null(200, a.as_ref(), |v| *v == a));

        // Converting a NULL group while the valued heap is full frees two
        // slots: the NULL registration and the evicted valued group.
        let (_, kind) = map.find_or_insert(200, a.as_ref(), b_idx, |v| *v == a);
        assert_eq!(kind, InsertKind::ReplacedNull);

        // Both freed slots must remain reusable. Otherwise repeated
        // conversions make the backing store grow without bound.
        assert!(map.insert_null(300, c.as_ref(), |v| *v == c));
        assert_eq!(map.store.len(), 2);

        Ok(())
    }
}