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
// 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::GroupValues;
use arrow::array::{
    Array, ArrayRef, FixedSizeListArray, LargeListArray, LargeListViewArray, ListArray,
    ListViewArray, MapArray, PrimitiveArray, RunArray, StructArray,
    downcast_run_end_index,
};
use arrow::compute::cast;
use arrow::datatypes::{DataType, SchemaRef};
use arrow::row::{RowConverter, Rows, SortField};
use datafusion_common::Result;
use datafusion_common::float_semantics::normalize_floats;
use datafusion_common::hash_utils::RandomState;
use datafusion_common::hash_utils::create_hashes;
use datafusion_execution::memory_pool::proxy::VecAllocExt;
use datafusion_expr::{EmitTo, GroupSelection};
use hashbrown::hash_table::HashTable;
use log::debug;
use std::sync::Arc;

/// A [`GroupValues`] making use of [`Rows`]
///
/// This is a general implementation of [`GroupValues`] that works for any
/// combination of data types and number of columns, including nested types such as
/// structs and lists.
///
/// It uses the arrow-rs [`Rows`] to store the group values, which is a row-wise
/// representation.
pub struct GroupValuesRows {
    /// The output schema
    schema: SchemaRef,

    /// Converter for the group values
    row_converter: RowConverter,

    /// Logically maps group values to a group_index in
    /// [`Self::group_values`] and in each accumulator
    ///
    /// Uses the raw API of hashbrown to avoid actually storing the
    /// keys (group values) in the table
    ///
    /// keys: u64 hashes of the GroupValue
    /// values: (hash, group_index)
    map: HashTable<(u64, usize)>,

    /// The actual group by values, stored in arrow [`Row`] format.
    /// `group_values[i]` holds the group value for group_index `i`.
    ///
    /// The row format is used to compare group keys quickly and store
    /// them efficiently in memory. Quick comparison is especially
    /// important for multi-column group keys.
    ///
    /// [`Row`]: arrow::row::Row
    group_values: Option<Rows>,

    /// reused buffer to store hashes
    hashes_buffer: Vec<u64>,

    /// reused buffer to store rows
    rows_buffer: Rows,

    /// The initial `rows_buffer` size, used to determine if it should be recreated in `clear_shrink`.
    initial_rows_buffer_size: usize,

    /// Random state for creating hashes
    random_state: RandomState,
}

impl GroupValuesRows {
    pub fn try_new(schema: SchemaRef) -> Result<Self> {
        // Print a debugging message, so it is clear when the (slower) fallback
        // GroupValuesRows is used.
        debug!("Creating GroupValuesRows for schema: {schema}");
        let row_converter = RowConverter::new(
            schema
                .fields()
                .iter()
                .map(|f| SortField::new(f.data_type().clone()))
                .collect(),
        )?;

        let map = HashTable::with_capacity(0);

        let rows_buffer = Self::new_rows_buffer(&row_converter);
        let initial_rows_buffer_size = rows_buffer.size();
        Ok(Self {
            schema,
            row_converter,
            map,
            group_values: None,
            hashes_buffer: Default::default(),
            rows_buffer,
            initial_rows_buffer_size,
            random_state: crate::aggregates::AGGREGATION_HASH_SEED,
        })
    }

    /// Create the reused `rows_buffer` with its initial capacities
    fn new_rows_buffer(row_converter: &RowConverter) -> Rows {
        let starting_rows_capacity = 1000;

        let starting_data_capacity = 64 * starting_rows_capacity;
        row_converter.empty_rows(starting_rows_capacity, starting_data_capacity)
    }
}

impl GroupValues for GroupValuesRows {
    fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec<usize>) -> Result<()> {
        // Normalize -0.0 → +0.0 so RowConverter (IEEE 754 totalOrder) and
        // primitive hashing both group ±0 together. No-op for non-float
        // columns.
        let normalized_cols: Vec<ArrayRef> = cols.iter().map(normalize_floats).collect();
        let cols = normalized_cols.as_slice();

        // Convert the group keys into the row format
        let group_rows = &mut self.rows_buffer;
        group_rows.clear();
        self.row_converter.append(group_rows, cols)?;
        let n_rows = group_rows.num_rows();

        let mut group_values = match self.group_values.take() {
            Some(group_values) => group_values,
            None => self.row_converter.empty_rows(0, 0),
        };

        // tracks to which group each of the input rows belongs
        groups.clear();

        // 1.1 Calculate the group keys for the group values
        let batch_hashes = &mut self.hashes_buffer;
        batch_hashes.clear();
        batch_hashes.resize(n_rows, 0);
        create_hashes(cols, &self.random_state, batch_hashes)?;

        for (row, &target_hash) in batch_hashes.iter().enumerate() {
            let entry = self.map.find_mut(target_hash, |(exist_hash, group_idx)| {
                // Somewhat surprisingly, this closure can be called even if the
                // hash doesn't match, so check the hash first with an integer
                // comparison first avoid the more expensive comparison with
                // group value. https://github.com/apache/datafusion/pull/11718
                target_hash == *exist_hash
                    // verify that the group that we are inserting with hash is
                    // actually the same key value as the group in
                    // existing_idx  (aka group_values @ row)
                    && group_rows.row(row) == group_values.row(*group_idx)
            });

            let group_idx = match entry {
                // Existing group_index for this group value
                Some((_hash, group_idx)) => *group_idx,
                //  1.2 Need to create new entry for the group
                None => {
                    // Add new entry to aggr_state and save newly created index
                    let group_idx = group_values.num_rows();
                    group_values.push(group_rows.row(row));

                    // for hasher function, use precomputed hash value
                    self.map.insert_unique(
                        target_hash,
                        (target_hash, group_idx),
                        |(hash, _group_index)| *hash,
                    );
                    group_idx
                }
            };
            groups.push(group_idx);
        }

        self.group_values = Some(group_values);

        Ok(())
    }

    fn size(&self) -> usize {
        let group_values_size = self
            .group_values
            .as_ref()
            .map(|values| values.size() - size_of::<Rows>())
            .unwrap_or_default();
        // `size_of::<Self>()` already accounts for inline row descriptors.
        // `HashTable::allocation_size` includes entries, control bytes, and group layout.
        size_of::<Self>() + self.row_converter.size() - size_of::<RowConverter>()
            + group_values_size
            + self.map.allocation_size()
            + self.rows_buffer.size()
            - size_of::<Rows>()
            + self.hashes_buffer.allocated_size()
    }

    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    fn len(&self) -> usize {
        self.group_values
            .as_ref()
            .map(|group_values| group_values.num_rows())
            .unwrap_or(0)
    }

    fn emit(&mut self, emit_to: EmitTo) -> Result<Vec<ArrayRef>> {
        let mut group_values = self
            .group_values
            .take()
            .expect("Can not emit from empty rows");

        let mut output = match emit_to {
            EmitTo::All => {
                let output = self.row_converter.convert_rows(&group_values)?;
                group_values.clear();
                self.map.clear();
                output
            }
            EmitTo::First(n) => {
                let groups_rows = group_values.iter().take(n);
                let output = self.row_converter.convert_rows(groups_rows)?;
                // Clear out first n group keys by copying them to a new Rows.
                // TODO file some ticket in arrow-rs to make this more efficient?
                let mut new_group_values = self.row_converter.empty_rows(0, 0);
                for row in group_values.iter().skip(n) {
                    new_group_values.push(row);
                }
                std::mem::swap(&mut new_group_values, &mut group_values);

                self.map.retain(|(_exists_hash, group_idx)| {
                    // Decrement group index by n
                    match group_idx.checked_sub(n) {
                        // Group index was >= n, shift value down
                        Some(sub) => {
                            *group_idx = sub;
                            true
                        }
                        // Group index was < n, so remove from table
                        None => false,
                    }
                });
                output
            }
        };

        // TODO: Materialize dictionaries in group keys
        // https://github.com/apache/datafusion/issues/7647
        for (field, array) in self.schema.fields.iter().zip(&mut output) {
            let expected = field.data_type();
            *array = encode_array_if_necessary(array, expected)?;
        }

        self.group_values = Some(group_values);
        Ok(output)
    }

    fn values_preserving(
        &mut self,
        selection: GroupSelection<'_>,
    ) -> Result<Vec<ArrayRef>> {
        let empty_rows;
        let group_values = if let Some(group_values) = self.group_values.as_ref() {
            group_values
        } else {
            empty_rows = self.row_converter.empty_rows(0, 0);
            &empty_rows
        };
        selection.validate_num_groups(group_values.num_rows())?;
        let rows = selection.iter().map(|index| group_values.row(index));
        let mut output = self.row_converter.convert_rows(rows)?;

        // TODO: Materialize dictionaries in group keys
        // https://github.com/apache/datafusion/issues/7647
        for (field, array) in self.schema.fields.iter().zip(&mut output) {
            *array = encode_array_if_necessary(array, field.data_type())?;
        }
        Ok(output)
    }

    fn supports_values_preserving(&self) -> bool {
        true
    }

    fn shrink_to_fit(&mut self) {
        self.map.shrink_to_fit(|(hash, _)| *hash);
        // Scratch for one `intern` call.
        self.hashes_buffer.clear();
        self.hashes_buffer.shrink_to_fit();
        if self.rows_buffer.size() > self.initial_rows_buffer_size {
            self.rows_buffer = Self::new_rows_buffer(&self.row_converter);
        }
    }

    fn clear_shrink(&mut self, num_rows: usize) {
        self.group_values = if num_rows == 0 {
            None
        } else {
            self.group_values.take().map(|mut rows| {
                // This only clear and do not shrink the capacity
                rows.clear();
                rows
            })
        };
        self.map.clear();
        self.map.shrink_to(num_rows, |_| 0); // hasher does not matter since the map is cleared
        self.hashes_buffer.clear();
        self.hashes_buffer.shrink_to(num_rows);

        if num_rows == 0 && self.rows_buffer.size() > self.initial_rows_buffer_size {
            // `rows_buffer` only gets cleared between batches, so it keeps any
            // capacity it grew to; recreate it to release that memory
            self.rows_buffer = Self::new_rows_buffer(&self.row_converter);
        }
    }
}

/// Re-apply dictionary / run-end encoding to `array` so it matches `expected`.
///
/// Arrow's [`RowConverter`] flattens dictionary and run-end-encoded values to
/// their plain value type during row encoding (at [`RowConverter::append`]),
/// so any group-value array produced from the row format is in that plain
/// type and must be re-encoded to match the schema's expected type before
/// being returned. Shared with the generic row-backed `GroupColumn`.
///
/// [`RowConverter`]: arrow::row::RowConverter
/// [`RowConverter::append`]: arrow::row::RowConverter::append
pub(crate) fn encode_array_if_necessary(
    array: &ArrayRef,
    expected: &DataType,
) -> Result<ArrayRef> {
    match (expected, array.data_type()) {
        (DataType::Struct(expected_fields), _) => {
            let struct_array = array.as_any().downcast_ref::<StructArray>().unwrap();
            let arrays = expected_fields
                .iter()
                .zip(struct_array.columns())
                .map(|(expected_field, column)| {
                    encode_array_if_necessary(column, expected_field.data_type())
                })
                .collect::<Result<Vec<_>>>()?;

            // A zero-field struct has no child to infer the length from.
            Ok(Arc::new(StructArray::try_new_with_length(
                expected_fields.clone(),
                arrays,
                struct_array.nulls().cloned(),
                struct_array.len(),
            )?))
        }
        (DataType::List(expected_field), &DataType::List(_)) => {
            let list = array.as_any().downcast_ref::<ListArray>().unwrap();

            Ok(Arc::new(ListArray::try_new(
                Arc::<arrow::datatypes::Field>::clone(expected_field),
                list.offsets().clone(),
                encode_array_if_necessary(list.values(), expected_field.data_type())?,
                list.nulls().cloned(),
            )?))
        }
        (DataType::LargeList(expected_field), &DataType::LargeList(_)) => {
            let list = array.as_any().downcast_ref::<LargeListArray>().unwrap();

            Ok(Arc::new(LargeListArray::try_new(
                Arc::<arrow::datatypes::Field>::clone(expected_field),
                list.offsets().clone(),
                encode_array_if_necessary(list.values(), expected_field.data_type())?,
                list.nulls().cloned(),
            )?))
        }
        (DataType::ListView(expected_field), &DataType::ListView(_)) => {
            // arrow-row's `decode_list_view` applies the dictionary-flatten
            // `corrected_type` to the child, so a `ListView<Dictionary<..>>`
            // decodes as `ListView<value type>` and the child must be
            // re-encoded here (same as `List` above, plus the `sizes`
            // buffer that view-lists carry).
            let list = array.as_any().downcast_ref::<ListViewArray>().unwrap();

            Ok(Arc::new(ListViewArray::try_new(
                Arc::<arrow::datatypes::Field>::clone(expected_field),
                list.offsets().clone(),
                list.sizes().clone(),
                encode_array_if_necessary(list.values(), expected_field.data_type())?,
                list.nulls().cloned(),
            )?))
        }
        (DataType::LargeListView(expected_field), &DataType::LargeListView(_)) => {
            let list = array.as_any().downcast_ref::<LargeListViewArray>().unwrap();

            Ok(Arc::new(LargeListViewArray::try_new(
                Arc::<arrow::datatypes::Field>::clone(expected_field),
                list.offsets().clone(),
                list.sizes().clone(),
                encode_array_if_necessary(list.values(), expected_field.data_type())?,
                list.nulls().cloned(),
            )?))
        }
        (
            DataType::FixedSizeList(expected_field, expected_size),
            &DataType::FixedSizeList(_, _),
        ) => {
            let list = array.as_any().downcast_ref::<FixedSizeListArray>().unwrap();

            Ok(Arc::new(FixedSizeListArray::try_new(
                Arc::<arrow::datatypes::Field>::clone(expected_field),
                *expected_size,
                encode_array_if_necessary(list.values(), expected_field.data_type())?,
                list.nulls().cloned(),
            )?))
        }
        (DataType::Map(expected_entries_field, ordered), &DataType::Map(_, _)) => {
            let map = array.as_any().downcast_ref::<MapArray>().unwrap();
            // Re-encode the entries `StructArray` (which holds key/value
            // columns) against the expected entries field's struct type.
            let entries_as_ref: ArrayRef = Arc::new(map.entries().clone());
            let entries = encode_array_if_necessary(
                &entries_as_ref,
                expected_entries_field.data_type(),
            )?;
            let entries = entries
                .as_any()
                .downcast_ref::<StructArray>()
                .expect("Map entries recurse must yield a StructArray")
                .clone();
            Ok(Arc::new(MapArray::try_new(
                Arc::<arrow::datatypes::Field>::clone(expected_entries_field),
                map.offsets().clone(),
                entries,
                map.nulls().cloned(),
                *ordered,
            )?))
        }
        (DataType::Dictionary(_, _), _) => Ok(cast(array.as_ref(), expected)?),
        (
            DataType::RunEndEncoded(run_ends_field, expected_values_field),
            &DataType::RunEndEncoded(_, _),
        ) => {
            macro_rules! reencode_ree {
                ($run_end_type:ty) => {{
                    let run_array = array
                        .as_any()
                        .downcast_ref::<RunArray<$run_end_type>>()
                        .unwrap();
                    let values = encode_array_if_necessary(
                        &(Arc::clone(run_array.values()) as ArrayRef),
                        expected_values_field.data_type(),
                    )?;
                    let run_ends = PrimitiveArray::<$run_end_type>::new(
                        run_array.run_ends().inner().clone(),
                        None,
                    );
                    Ok(Arc::new(RunArray::try_new(&run_ends, &values)?))
                }};
            }
            downcast_run_end_index! {
                run_ends_field.data_type() => (reencode_ree),
                _ => unreachable!("unsupported run end type: {}", run_ends_field.data_type()),
            }
        }
        (DataType::RunEndEncoded(_, _), _) => Ok(cast(array.as_ref(), expected)?),
        (_, _) => Ok(Arc::<dyn Array>::clone(array)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow::array::{AsArray, Int32Array, ListArray, StringArray};
    use arrow::datatypes::{Field, Int32Type, Schema};
    use std::mem::size_of;

    fn expected_size(group_values: &GroupValuesRows) -> usize {
        size_of::<GroupValuesRows>() + group_values.row_converter.size()
            - size_of::<RowConverter>()
            + group_values
                .group_values
                .as_ref()
                .map(|values| values.size() - size_of::<Rows>())
                .unwrap_or_default()
            + group_values.map.allocation_size()
            + group_values.rows_buffer.size()
            - size_of::<Rows>()
            + group_values.hashes_buffer.allocated_size()
    }

    fn int32_schema() -> SchemaRef {
        Arc::new(Schema::new(vec![Field::new(
            "group",
            DataType::Int32,
            true,
        )]))
    }

    #[test]
    fn size_retains_reusable_buffers_after_emit() -> Result<()> {
        let mut group_values = GroupValuesRows::try_new(int32_schema())?;
        let input: ArrayRef = Arc::new(Int32Array::from_iter_values(0..256));
        group_values.intern(&[input], &mut vec![])?;

        let rows_buffer_size = group_values.rows_buffer.size() - size_of::<Rows>();
        let hashes_buffer_size = group_values.hashes_buffer.allocated_size();

        let output = group_values.emit(EmitTo::First(1))?;
        assert_eq!(output[0].len(), 1);
        assert_eq!(group_values.len(), 255);
        let size_after_emit = group_values.size();
        assert_eq!(
            group_values.rows_buffer.size() - size_of::<Rows>(),
            rows_buffer_size
        );
        assert_eq!(
            group_values.hashes_buffer.allocated_size(),
            hashes_buffer_size
        );

        let input: ArrayRef = Arc::new(Int32Array::from_iter_values([256]));
        group_values.intern(&[input], &mut vec![])?;
        assert_eq!(group_values.len(), 256);
        assert!(group_values.size() >= size_after_emit);
        assert_eq!(
            group_values.rows_buffer.size() - size_of::<Rows>(),
            rows_buffer_size
        );
        assert_eq!(
            group_values.hashes_buffer.allocated_size(),
            hashes_buffer_size
        );
        Ok(())
    }

    #[test]
    fn preserving_nested_row_values() -> Result<()> {
        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
        let schema = Arc::new(Schema::new(vec![Field::new(
            "group",
            DataType::List(field),
            true,
        )]));
        let mut group_values = GroupValuesRows::try_new(schema)?;
        let input = Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
            Some(vec![Some(1), Some(2)]),
            None,
            Some(vec![Some(3)]),
            Some(vec![Some(1), Some(2)]),
        ])) as ArrayRef;
        let mut groups = vec![];
        group_values.intern(&[input], &mut groups)?;
        assert_eq!(groups, vec![0, 1, 2, 0]);

        let selection = GroupSelection::try_from_indices(&[2, 0, 1, 2], 3)?;
        let expected = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
            Some(vec![Some(3)]),
            Some(vec![Some(1), Some(2)]),
            None,
            Some(vec![Some(3)]),
        ]);
        for _ in 0..2 {
            let actual = group_values.values_preserving(selection)?;
            assert_eq!(actual[0].as_list::<i32>(), &expected);
        }

        let input = Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
            Some(vec![Some(4)]),
        ])) as ArrayRef;
        group_values.intern(&[input], &mut groups)?;
        assert_eq!(groups, vec![3]);
        Ok(())
    }

    #[test]
    fn test_exact_hash_table_allocation_accounting_multi_column() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, true),
            Field::new("b", DataType::Utf8, true),
        ]));
        let mut group_values = GroupValuesRows::try_new(schema)?;

        // 1. Initial state: map is unallocated
        assert_eq!(group_values.map.capacity(), 0);
        assert_eq!(group_values.map.allocation_size(), 0);
        assert_eq!(group_values.size(), expected_size(&group_values));

        // 2. Insert multi-column keys and observe table allocation growth
        let num_distinct = 500;
        let col_a = Arc::new(Int32Array::from_iter_values(0..num_distinct)) as ArrayRef;
        let col_b = Arc::new(StringArray::from_iter_values(
            (0..num_distinct).map(|i| format!("key_string_{i}")),
        )) as ArrayRef;

        let mut groups = vec![];
        group_values.intern(&[col_a, col_b], &mut groups)?;
        assert_eq!(groups.len(), num_distinct as usize);

        let table_bytes = group_values.map.allocation_size();
        assert!(group_values.map.capacity() >= num_distinct as usize);
        assert!(table_bytes > 0);

        // Hashbrown's layout contains entry slots, control bytes, and trailing group bytes.
        // It must strictly exceed the naive entry-only size: capacity * size_of::<(u64, usize)>().
        let entry_only_bytes = group_values.map.capacity() * size_of::<(u64, usize)>();
        assert!(
            table_bytes > entry_only_bytes,
            "allocation_size ({table_bytes}) must exceed entry-only capacity ({entry_only_bytes})"
        );

        // GroupValuesRows::size() should accurately account for the map's allocation_size
        assert_eq!(group_values.size(), expected_size(&group_values));

        // 3. Partial emit (EmitTo::First) - table retains entries and capacity
        let emit_count = 200;
        let emitted = group_values.emit(EmitTo::First(emit_count))?;
        assert_eq!(emitted[0].len(), emit_count);
        assert_eq!(group_values.len(), (num_distinct as usize) - emit_count);

        // Retained capacity is still charged until the table releases it.
        assert_eq!(group_values.map.allocation_size(), table_bytes);
        assert_eq!(group_values.size(), expected_size(&group_values));

        // 4. Emit all (EmitTo::All) - map is cleared but capacity remains allocated for reuse
        let remaining_count = group_values.len();
        let emitted_all = group_values.emit(EmitTo::All)?;
        assert_eq!(emitted_all[0].len(), remaining_count);
        assert_eq!(group_values.len(), 0);

        // Clear preserves table capacity
        assert_eq!(group_values.map.allocation_size(), table_bytes);

        // 5. clear_shrink: releases/shrinks map capacity
        group_values.clear_shrink(16);
        let shrunken_table_bytes = group_values.map.allocation_size();
        assert!(
            shrunken_table_bytes < table_bytes,
            "clear_shrink should shrink table from {table_bytes} to {shrunken_table_bytes}"
        );
        assert_eq!(group_values.size(), expected_size(&group_values));

        // 6. Reinsert new distinct values into the shrunken table
        let new_col_a =
            Arc::new(Int32Array::from_iter_values(num_distinct..num_distinct * 2))
                as ArrayRef;
        let new_col_b = Arc::new(StringArray::from_iter_values(
            (num_distinct..num_distinct * 2).map(|i| format!("key_string_{i}")),
        )) as ArrayRef;
        group_values.intern(&[new_col_a, new_col_b], &mut groups)?;
        assert_eq!(groups.len(), num_distinct as usize);
        assert!(group_values.map.allocation_size() > shrunken_table_bytes);
        assert_eq!(group_values.size(), expected_size(&group_values));

        Ok(())
    }

    #[test]
    fn test_exact_hash_table_allocation_accounting_nested_keys() -> Result<()> {
        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
        let schema = Arc::new(Schema::new(vec![Field::new(
            "nested",
            DataType::List(field),
            true,
        )]));
        let mut group_values = GroupValuesRows::try_new(schema)?;

        assert_eq!(group_values.map.capacity(), 0);
        assert_eq!(group_values.map.allocation_size(), 0);

        let input = Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(
            (0..256).map(|i| Some(vec![Some(i), Some(i * 2)])),
        )) as ArrayRef;
        let mut groups = vec![];
        group_values.intern(&[input], &mut groups)?;
        assert_eq!(groups.len(), 256);

        let table_bytes = group_values.map.allocation_size();
        assert!(table_bytes > 0);
        assert_eq!(group_values.size(), expected_size(&group_values));

        // Shrink to 0: table should completely deallocate
        group_values.clear_shrink(0);
        assert_eq!(group_values.map.capacity(), 0);
        assert_eq!(group_values.map.allocation_size(), 0);

        Ok(())
    }

    #[test]
    fn clear_shrink_0_after_intern_should_return_to_original_size() {
        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
        let schema = Arc::new(Schema::new(vec![Field::new(
            "group",
            DataType::List(field),
            true,
        )]));
        let mut group_values = GroupValuesRows::try_new(schema).unwrap();
        let initial_size = group_values.size();
        let input = Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
            Some(vec![Some(1), Some(2)]),
            None,
            Some(vec![Some(3)]),
            Some(vec![Some(1), Some(2)]),
        ])) as ArrayRef;
        let mut groups = vec![];
        group_values.intern(&[input], &mut groups).unwrap();
        assert_ne!(group_values.size(), initial_size, "should save some data");

        // A large batch so any reused buffers grow as well
        let input = Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(
            (0..10_000).map(|i| Some((0..20).map(move |j| Some(i * 20 + j)))),
        )) as ArrayRef;
        group_values.intern(&[input], &mut groups).unwrap();

        group_values.clear_shrink(0);
        assert_eq!(
            group_values.size(),
            initial_size,
            "should release memory back to original size"
        );
    }
}