datafusion-functions-nested 56.0.0

Nested Type Function packages for the DataFusion query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

//! array function utils

use std::sync::Arc;

use arrow::datatypes::{DataType, Field, FieldRef, Fields};

use arrow::array::{
    Array, ArrayRef, BooleanArray, BooleanBufferBuilder, Float64Array, GenericListArray,
    NullBufferBuilder, OffsetSizeTrait, Scalar, new_empty_array,
};
use arrow::buffer::{BooleanBuffer, NullBuffer, OffsetBuffer};
use datafusion_common::cast::{
    as_fixed_size_list_array, as_float64_array, as_generic_list_array,
    as_large_list_array, as_large_list_view_array, as_list_array, as_list_view_array,
};
use datafusion_common::utils::{offset_span, offset_span_len};
use datafusion_common::{Result, ScalarValue, exec_err, internal_err, plan_err};

use datafusion_expr::ColumnarValue;
use itertools::Itertools as _;

/// Empty every valid list row, preserving parent nulls and the given child field.
pub(crate) fn empty_list_values<O: OffsetSizeTrait>(
    list: &GenericListArray<O>,
    field: FieldRef,
) -> ArrayRef {
    let values = new_empty_array(field.data_type());
    Arc::new(GenericListArray::<O>::new(
        field,
        OffsetBuffer::new_zeroed(list.len()),
        values,
        list.nulls().cloned(),
    ))
}

/// Build result row offsets and exclude elements stored under NULL list rows.
///
/// `keep` is a bitmap identifying which elements in the list's visible span
/// should be preserved. The returned bitmap uses the same indexing, with bits
/// for NULL list rows cleared. Selected elements may themselves be NULL; their
/// validity is the caller's responsibility when copying values.
pub(crate) fn prepare_list_filter<O: OffsetSizeTrait>(
    list: &GenericListArray<O>,
    keep: &BooleanBuffer,
) -> (OffsetBuffer<O>, BooleanBuffer) {
    let list_offsets = list.offsets();
    let (first_offset, span_len) = offset_span(list_offsets);
    debug_assert_eq!(keep.len(), span_len);
    let mut offsets = Vec::with_capacity(list.len() + 1);
    offsets.push(O::zero());
    // Count the set bits before each row end in one pass over `keep`, which
    // stays cheap for short rows.
    let keep_mask = if list.null_count() == 0 {
        // Without NULL rows, every set bit is kept.
        let mut set_bits = SetBitCounter::new(keep.bit_chunks().iter_padded());
        offsets.extend(list_offsets[1..].iter().map(|end| {
            O::usize_as(set_bits.count_before(end.as_usize() - first_offset))
        }));
        keep.clone()
    } else {
        let mut set_bits = SetBitCounter::new(keep.bit_chunks().iter_padded());
        let mut kept_count = 0;
        // Set bits stored under NULL rows, which the result does not keep.
        let mut hidden_count = 0;
        // NULL list rows are usually empty, so reuse `keep` until a NULL row
        // stores elements. Copy the bits of the preceding rows when that first
        // happens.
        let mut keep_mask: Option<BooleanBufferBuilder> = None;
        for (row, window) in list_offsets.windows(2).enumerate() {
            let start = window[0].as_usize() - first_offset;
            let end = window[1].as_usize() - first_offset;
            let len = end - start;
            let bit_start = keep.offset() + start;
            if list.is_valid(row) {
                kept_count = set_bits.count_before(end) - hidden_count;
                if let Some(keep_mask) = &mut keep_mask {
                    keep_mask
                        .append_packed_range(bit_start..bit_start + len, keep.values());
                }
            } else if len != 0 {
                let set_before_row = set_bits.count_before(start);
                hidden_count += set_bits.count_before(end) - set_before_row;
                keep_mask
                    .get_or_insert_with(|| {
                        let mut builder = BooleanBufferBuilder::new(keep.len());
                        builder
                            .append_packed_range(keep.offset()..bit_start, keep.values());
                        builder
                    })
                    .append_n(len, false);
            }
            offsets.push(O::usize_as(kept_count));
        }
        keep_mask
            .map(BooleanBufferBuilder::build)
            .unwrap_or_else(|| keep.clone())
    };
    debug_assert_eq!(keep_mask.len(), keep.len());
    // SAFETY: offsets start at zero and never decrease, since each one counts
    // the kept elements up to a row's end. A count cannot exceed the input's
    // element span, which fits in `O`, so converting it to `O` cannot overflow.
    let offsets = unsafe { OffsetBuffer::new_unchecked(offsets.into()) };
    (offsets, keep_mask)
}

/// Counts the set bits that precede a sequence of non-decreasing positions in a
/// bitmap, reading each 64-bit word of the bitmap once.
struct SetBitCounter<I> {
    /// The bitmap's remaining words, with the final word padded with zeros.
    words: I,
    /// The word containing the most recent position.
    word: u64,
    /// Position of the first bit of `word`.
    word_start: usize,
    /// Set bits before `word_start`.
    count_before_word: usize,
}

impl<I: Iterator<Item = u64>> SetBitCounter<I> {
    fn new(mut words: I) -> Self {
        let word = words.next().unwrap_or(0);
        Self {
            words,
            word,
            word_start: 0,
            count_before_word: 0,
        }
    }

    /// Returns the number of set bits before `end`. `end` must be no less than
    /// in the previous call, and no greater than the bitmap's length.
    #[inline]
    fn count_before(&mut self, end: usize) -> usize {
        debug_assert!(end >= self.word_start);
        while end - self.word_start >= 64 {
            self.count_before_word += self.word.count_ones() as usize;
            self.word = self.words.next().unwrap_or(0);
            self.word_start += 64;
        }
        let mask = (1u64 << (end - self.word_start)) - 1;
        self.count_before_word + (self.word & mask).count_ones() as usize
    }
}

/// Computes the return type of a function that produces a list with the same
/// inner field as `array_type`, plus an element that may be null when
/// `element_nullable` is set.
///
/// The inner field is carried over from `array_type` verbatim — name, metadata
/// and all — so that the type promised at planning time is the one the kernel
/// can actually build. Its nullability is widened when `element_nullable` is
/// set, because a nullable new element may introduce nulls into a list whose
/// elements were previously declared non-nullable.
///
/// Types other than `List`/`LargeList` are returned unchanged; callers handle
/// `Null` themselves and the kernels reject anything else at execution time.
pub(crate) fn list_type_with_element(
    array_type: &DataType,
    element_nullable: bool,
) -> DataType {
    match array_type {
        DataType::List(field) => {
            DataType::List(widen_nullability(field, element_nullable))
        }
        DataType::LargeList(field) => {
            DataType::LargeList(widen_nullability(field, element_nullable))
        }
        other => other.clone(),
    }
}

fn widen_nullability(field: &FieldRef, nullable: bool) -> FieldRef {
    if nullable && !field.is_nullable() {
        Arc::new(field.as_ref().clone().with_nullable(true))
    } else {
        Arc::clone(field)
    }
}

/// Extracts the inner field of a `List`/`LargeList` type, so that a kernel can
/// build a list array carrying exactly that field.
///
/// Used both on an input's type and on the type promised by
/// [`ScalarUDFImpl::return_field_from_args`]. Anything else is a bug in the
/// caller's dispatch, hence the internal error; `context` names the kernel so
/// that error identifies where the bad dispatch happened.
///
/// [`ScalarUDFImpl::return_field_from_args`]: datafusion_expr::ScalarUDFImpl::return_field_from_args
pub(crate) fn list_inner_field(context: &str, data_type: &DataType) -> Result<FieldRef> {
    match data_type {
        DataType::List(field) | DataType::LargeList(field) => Ok(Arc::clone(field)),
        other => internal_err!("{context} got unexpected data type: {other}"),
    }
}

pub(crate) fn check_datatypes(name: &str, args: &[&ArrayRef]) -> Result<()> {
    let data_type = args[0].data_type();
    if !args.iter().all(|arg| {
        arg.data_type().equals_datatype(data_type)
            || arg.data_type().equals_datatype(&DataType::Null)
    }) {
        let types = args.iter().map(|arg| arg.data_type()).collect::<Vec<_>>();
        return plan_err!(
            "{name} received incompatible types: {}",
            types.iter().join(", ")
        );
    }

    Ok(())
}

/// array function wrapper that differentiates between scalar (length 1) and array.
pub(crate) fn make_scalar_function<F>(
    inner: F,
) -> impl Fn(&[ColumnarValue]) -> Result<ColumnarValue>
where
    F: Fn(&[ArrayRef]) -> Result<ArrayRef>,
{
    move |args: &[ColumnarValue]| {
        // first, identify if any of the arguments is an Array. If yes, store its `len`,
        // as any scalar will need to be converted to an array of len `len`.
        let len = args
            .iter()
            .fold(Option::<usize>::None, |acc, arg| match arg {
                ColumnarValue::Scalar(_) => acc,
                ColumnarValue::Array(a) => Some(a.len()),
            });

        let is_scalar = len.is_none();

        let args = ColumnarValue::values_to_arrays(args)?;

        let result = (inner)(&args);

        if is_scalar {
            // If all inputs are scalar, keeps output as scalar
            let result = result.and_then(|arr| ScalarValue::try_from_array(&arr, 0));
            result.map(ColumnarValue::Scalar)
        } else {
            result.map(ColumnarValue::Array)
        }
    }
}

pub(crate) fn align_array_dimensions<O: OffsetSizeTrait>(
    args: Vec<ArrayRef>,
) -> Result<Vec<ArrayRef>> {
    let args_ndim = args
        .iter()
        .map(|arg| datafusion_common::utils::list_ndims(arg.data_type()))
        .collect::<Vec<_>>();
    let max_ndim = args_ndim.iter().max().unwrap_or(&0);

    // Align the dimensions of the arrays
    let aligned_args: Result<Vec<ArrayRef>> = args
        .into_iter()
        .zip(args_ndim.iter())
        .map(|(array, ndim)| {
            if ndim < max_ndim {
                let mut aligned_array = Arc::clone(&array);
                for _ in 0..(max_ndim - ndim) {
                    let data_type = aligned_array.data_type().to_owned();
                    let array_lengths = std::iter::repeat_n(1, aligned_array.len());
                    let offsets = OffsetBuffer::<O>::from_lengths(array_lengths);

                    aligned_array = Arc::new(GenericListArray::<O>::try_new(
                        Arc::new(Field::new_list_field(data_type, true)),
                        offsets,
                        aligned_array,
                        None,
                    )?)
                }
                Ok(aligned_array)
            } else {
                Ok(Arc::clone(&array))
            }
        })
        .collect();

    aligned_args
}

/// Computes a BooleanArray indicating equality or inequality between elements in a list array and a specified element array.
///
/// # Arguments
///
/// * `list_array_row` - A reference to a trait object implementing the Arrow `Array` trait. It represents the list array for which the equality or inequality will be compared.
///
/// * `element_array` - A reference to a trait object implementing the Arrow `Array` trait. It represents the array with which each element in the `list_array_row` will be compared.
///
/// * `row_index` - The index of the row in the `element_array` and `list_array` to use for the comparison.
///
/// * `eq` - A boolean flag. If `true`, the function computes equality; if `false`, it computes inequality.
///
/// # Returns
///
/// Returns a `Result<BooleanArray>` representing the comparison results. The result may contain an error if there are issues with the computation.
///
/// # Example
///
/// ```text
/// compare_element_to_list(
///     [1, 2, 3], [1, 2, 3], 0, true => [true, false, false]
///     [1, 2, 3, 3, 2, 1], [1, 2, 3], 1, true => [false, true, false, false, true, false]
///
///     [[1, 2, 3], [2, 3, 4], [3, 4, 5]], [[1, 2, 3], [2, 3, 4], [3, 4, 5]], 0, true => [true, false, false]
///     [[1, 2, 3], [2, 3, 4], [2, 3, 4]], [[1, 2, 3], [2, 3, 4], [3, 4, 5]], 1, false => [true, false, false]
/// )
/// ```
pub(crate) fn compare_element_to_list(
    list_array_row: &dyn Array,
    element_array: &dyn Array,
    row_index: usize,
    eq: bool,
) -> Result<BooleanArray> {
    if list_array_row.data_type() != element_array.data_type() {
        return exec_err!(
            "compare_element_to_list received incompatible types: '{:?}' and '{:?}'.",
            list_array_row.data_type(),
            element_array.data_type()
        );
    }

    let element_array_row = element_array.slice(row_index, 1);

    // Compute all positions in list_row_array (that is itself an
    // array) that are equal to `from_array_row`
    let res = match element_array_row.data_type() {
        // arrow_ord::cmp::eq does not support ListArray, so we need to compare it by loop
        DataType::List(_) => {
            // compare each element of the from array
            let element_array_row_inner = as_list_array(&element_array_row)?.value(0);
            let list_array_row_inner = as_list_array(list_array_row)?;

            list_array_row_inner
                .iter()
                // compare element by element the current row of list_array
                .map(|row| {
                    row.map(|row| {
                        if eq {
                            row.eq(&element_array_row_inner)
                        } else {
                            row.ne(&element_array_row_inner)
                        }
                    })
                })
                .collect::<BooleanArray>()
        }
        DataType::LargeList(_) => {
            // compare each element of the from array
            let element_array_row_inner =
                as_large_list_array(&element_array_row)?.value(0);
            let list_array_row_inner = as_large_list_array(list_array_row)?;

            list_array_row_inner
                .iter()
                // compare element by element the current row of list_array
                .map(|row| {
                    row.map(|row| {
                        if eq {
                            row.eq(&element_array_row_inner)
                        } else {
                            row.ne(&element_array_row_inner)
                        }
                    })
                })
                .collect::<BooleanArray>()
        }
        _ => {
            let element_arr = Scalar::new(element_array_row);
            // use not_distinct so we can compare NULL
            if eq {
                arrow_ord::cmp::not_distinct(&list_array_row, &element_arr)?
            } else {
                arrow_ord::cmp::distinct(&list_array_row, &element_arr)?
            }
        }
    };

    Ok(res)
}

/// Returns the length of each array dimension
pub(crate) fn compute_array_dims(
    arr: Option<ArrayRef>,
) -> Result<Option<Vec<Option<u64>>>> {
    let Some(mut value) = arr else {
        return Ok(None);
    };
    if value.is_empty() {
        return Ok(None);
    }
    let mut res = vec![Some(value.len() as u64)];

    loop {
        match value.data_type() {
            DataType::List(_) => {
                value = as_list_array(&value)?.value(0);
                res.push(Some(value.len() as u64));
            }
            DataType::LargeList(_) => {
                value = as_large_list_array(&value)?.value(0);
                res.push(Some(value.len() as u64));
            }
            DataType::ListView(_) => {
                value = as_list_view_array(&value)?.value(0);
                res.push(Some(value.len() as u64));
            }
            DataType::LargeListView(_) => {
                value = as_large_list_view_array(&value)?.value(0);
                res.push(Some(value.len() as u64));
            }
            DataType::FixedSizeList(..) => {
                value = as_fixed_size_list_array(&value)?.value(0);
                res.push(Some(value.len() as u64));
            }
            _ => return Ok(Some(res)),
        }
    }
}

pub(crate) fn get_map_entry_field(data_type: &DataType) -> Result<&Fields> {
    match data_type {
        DataType::Map(field, _) => {
            let field_data_type = field.data_type();
            match field_data_type {
                DataType::Struct(fields) => Ok(fields),
                _ => {
                    internal_err!("Expected a Struct type, got {}", field_data_type)
                }
            }
        }
        _ => plan_err!("Expected a Map type, got {data_type}"),
    }
}

/// Shared `coerce_types` impl for array-math UDFs whose kernels expect
/// `List<Float64>` / `LargeList<Float64>` (e.g. `array_add`, `cosine_distance`,
/// `inner_product`, `array_normalize`).
///
/// Each input must be `Null`, `List`, `LargeList`, or `FixedSizeList`; otherwise
/// returns a plan error naming `name`. `FixedSizeList` is widened to `List`,
/// `Null` is coerced to a list of `Float64`, and if any input is `LargeList`
/// the rest are widened to `LargeList` so the runtime sees a homogeneous pair.
pub(crate) fn coerce_array_math_arg_types(
    name: &str,
    arg_types: &[DataType],
) -> Result<Vec<DataType>> {
    use DataType::{FixedSizeList, LargeList, List, Null};
    use datafusion_common::utils::{ListCoercion, coerced_type_with_base_type_only};

    let coercion = Some(&ListCoercion::FixedSizedListToList);

    for arg_type in arg_types {
        if !matches!(arg_type, Null | List(_) | LargeList(_) | FixedSizeList(..)) {
            return plan_err!("{name} does not support type {arg_type}");
        }
    }

    // If any input is `LargeList`, both sides must be widened to `LargeList`
    // so the runtime dispatch in `inner_product_inner` sees a homogeneous
    // pair. Follows the pattern in `ArrayConcat::coerce_types`.
    let any_large_list = arg_types.iter().any(|t| matches!(t, LargeList(_)));

    let coerced = arg_types
        .iter()
        .map(|arg_type| {
            if matches!(arg_type, Null) {
                let field = Arc::new(Field::new_list_field(DataType::Float64, true));
                return if any_large_list {
                    LargeList(field)
                } else {
                    List(field)
                };
            }
            let coerced =
                coerced_type_with_base_type_only(arg_type, &DataType::Float64, coercion);
            match coerced {
                List(field) if any_large_list => LargeList(field),
                other => other,
            }
        })
        .collect();

    Ok(coerced)
}

/// Element-wise binary operation kernel for two `Float64` lists of equal per-row
/// length. The caller is responsible for type-dispatching on `O` (`i32` for
/// `List`, `i64` for `LargeList`).
///
/// Semantics:
/// - whole-row NULL on either side → NULL output row, length 0
/// - per-element NULL on either side → NULL at that output position
/// - per-row length mismatch → exec error tagged with `op_name`
///
/// `op_name` flows into the error message; `op` is the per-element scalar op
/// (e.g. `|a, b| a + b` for `array_add`, `|a, b| a - b` for `array_subtract`).
pub(crate) fn array_math_binary_op<O, F>(
    op_name: &str,
    lhs: &ArrayRef,
    rhs: &ArrayRef,
    op: F,
) -> Result<ArrayRef>
where
    O: OffsetSizeTrait,
    F: Fn(f64, f64) -> f64,
{
    let lhs = as_generic_list_array::<O>(lhs)?;
    let rhs = as_generic_list_array::<O>(rhs)?;

    let lhs_values = as_float64_array(lhs.values())?;
    let rhs_values = as_float64_array(rhs.values())?;
    let lhs_offsets = lhs.value_offsets();
    let rhs_offsets = rhs.value_offsets();

    let row_nulls = NullBuffer::union(lhs.nulls(), rhs.nulls());

    let capacity = offset_span_len(lhs.offsets());
    let mut out_values: Vec<f64> = Vec::with_capacity(capacity);
    let mut out_inner_nulls = NullBufferBuilder::new(capacity);
    let mut out_offsets = Vec::<O>::with_capacity(lhs.len() + 1);
    out_offsets.push(O::zero());

    for row in 0..lhs.len() {
        if row_nulls.as_ref().is_some_and(|nb| nb.is_null(row)) {
            out_offsets.push(out_offsets[row]);
            continue;
        }

        let start1 = lhs_offsets[row].as_usize();
        let len1 = lhs.value_length(row).as_usize();
        let start2 = rhs_offsets[row].as_usize();
        let len2 = rhs.value_length(row).as_usize();

        if len1 != len2 {
            return exec_err!(
                "{op_name} requires both list inputs to have the same length per row, got {len1} and {len2} at row {row}"
            );
        }

        let l_slice = lhs_values.slice(start1, len1);
        let r_slice = rhs_values.slice(start2, len2);

        let l_vals = l_slice.values();
        let r_vals = r_slice.values();

        for i in 0..len1 {
            out_values.push(op(l_vals[i], r_vals[i]));
        }

        match NullBuffer::union(l_slice.nulls(), r_slice.nulls()) {
            Some(nb) => out_inner_nulls.append_buffer(&nb),
            None => out_inner_nulls.append_n_non_nulls(len1),
        }

        out_offsets.push(out_offsets[row] + O::usize_as(len1));
    }

    let values_array = Arc::new(Float64Array::new(
        out_values.into(),
        out_inner_nulls.finish(),
    ));
    let field = Arc::new(Field::new_list_field(DataType::Float64, true));

    Ok(Arc::new(GenericListArray::<O>::try_new(
        field,
        OffsetBuffer::new(out_offsets.into()),
        values_array,
        row_nulls,
    )?))
}

/// Returns a power of two that brings the largest magnitude in `values` close
/// to 1, so that squaring the scaled values neither overflows nor underflows.
///
/// Squaring a large finite value overflows (`1e200 * 1e200` is infinity) and
/// squaring a small one underflows (`1e-200 * 1e-200` is zero), even when the
/// norm itself is representable. The factor is a power of two, so scaling is
/// exact whenever the scaled value is normal. A value that becomes subnormal is
/// rounded, so an `array_normalize` element that is itself subnormal can differ
/// from the unscaled result in its last bit.
///
/// Returns `None` when `values` is empty, all zero, or contains an infinity.
/// The unscaled computation already gives the expected result for those inputs.
/// NaN values are ignored, and the scaled computation still produces NaN.
pub(crate) fn norm_scale(values: impl IntoIterator<Item = f64>) -> Option<f64> {
    // No early return inside the loop, so that it vectorizes. `f64::max` skips
    // NaN, so only an infinity can make `max` non-finite.
    let mut max = 0.0_f64;
    for value in values {
        max = max.max(value.abs());
    }
    if max == 0.0 || !max.is_finite() {
        return None;
    }
    // Unbiased exponent of `max`. Subnormal values store a biased exponent of 0,
    // so clamp them to the smallest normal exponent.
    let exponent = ((max.to_bits() >> 52) as i32 - 1023).max(-1022);
    Some(2.0_f64.powi(-exponent))
}

/// Returns whether a sum of `len` squares computed without scaling may be
/// wrong because a square overflowed or underflowed, in which case it should be
/// recomputed with the factor from [`norm_scale`].
///
/// An overflowing square makes the sum infinite. An underflowing square is off
/// by at most half the smallest subnormal value, so `len` of them move the sum
/// by at most `len * 2^-1075`. A sum of at least `len * 2^-1012` is therefore
/// off by less than `2^-63` of itself, far below its rounding precision.
pub(crate) fn needs_norm_scale(sum_of_squares: f64, len: usize) -> bool {
    // 2^-1012 = 2^10 * f64::MIN_POSITIVE
    let min_unscaled = 1024.0 * len as f64 * f64::MIN_POSITIVE;
    !(min_unscaled..f64::INFINITY).contains(&sum_of_squares)
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use arrow::array::ListArray;
    use arrow::datatypes::Int64Type;
    use datafusion_common::utils::SingleRowListArrayBuilder;
    use rand::{Rng, SeedableRng, rngs::StdRng};

    /// Compare `prepare_list_filter` with a per-row reference, returning the
    /// output bitmap so callers can check whether `keep` was reused.
    fn assert_list_filter_matches_reference<O: OffsetSizeTrait>(
        list: &GenericListArray<O>,
        keep: &BooleanBuffer,
    ) -> BooleanBuffer {
        let first = list.offsets()[0].as_usize();
        let mut expected = keep.iter().collect::<Vec<_>>();
        let mut expected_offsets = vec![0];
        for (row, window) in list.offsets().windows(2).enumerate() {
            let start = window[0].as_usize() - first;
            let end = window[1].as_usize() - first;
            if list.is_null(row) {
                expected[start..end].fill(false);
            }
            expected_offsets.push(expected[..end].iter().filter(|&&v| v).count());
        }
        let (offsets, mask) = prepare_list_filter(list, keep);
        assert_eq!(mask.iter().collect::<Vec<_>>(), expected);
        assert_eq!(
            offsets.iter().map(|o| o.as_usize()).collect::<Vec<_>>(),
            expected_offsets
        );
        mask
    }

    /// A list of NULL elements with the given row lengths and row validity,
    /// sliced to `len` rows starting at row `offset`.
    fn null_element_list<O: OffsetSizeTrait>(
        lengths: &[usize],
        nulls: Option<NullBuffer>,
        offset: usize,
        len: usize,
    ) -> GenericListArray<O> {
        GenericListArray::<O>::new(
            Arc::new(Field::new_list_field(DataType::Int32, true)),
            OffsetBuffer::from_lengths(lengths.iter().copied()),
            // `prepare_list_filter` must permit selecting NULL elements.
            arrow::array::new_null_array(&DataType::Int32, lengths.iter().sum()),
            nulls,
        )
        .slice(offset, len)
    }

    /// Check a list sliced to its last seven rows, returning the input and output
    /// bitmaps so callers can check whether the input was reused.
    fn check_list_filter<O: OffsetSizeTrait>(
        lengths: [usize; 8],
        valid: [bool; 8],
    ) -> (BooleanBuffer, BooleanBuffer) {
        let nulls = Some(NullBuffer::from(valid.to_vec()));
        let list = null_element_list::<O>(&lengths, nulls, 1, 7);
        let len = offset_span(list.offsets()).1;
        // Use an offset that is not a multiple of the bitmap's three-bit period.
        let keep = BooleanBuffer::collect_bool(len + 1, |i| i % 3 != 0).slice(1, len);
        let mask = assert_list_filter_matches_reference(&list, &keep);
        (keep, mask)
    }

    #[test]
    fn list_filter_mask_handles_slices_and_hidden_elements() {
        let valid = [true, false, true, false, false, true, true, false];
        // After slicing off the first row, the first lengths of each pair give an
        // empty NULL row, a NULL row storing elements after a valid row,
        // consecutive NULL rows, and a trailing one. The second lengths store no
        // elements under NULL rows, which leaves the bitmap untouched.
        for (hidden, empty) in [
            ([2, 0, 2, 1, 2, 0, 3, 2], [2, 0, 2, 0, 0, 3, 3, 0]),
            // Rows long enough that counting and copying bits spans 64-bit words.
            ([2, 0, 63, 65, 64, 0, 65, 2], [2, 0, 63, 0, 0, 65, 65, 0]),
        ] {
            let (keep, mask) = check_list_filter::<i32>(hidden, valid);
            assert!(!mask.inner().ptr_eq(keep.inner()));
            let (keep, mask) = check_list_filter::<i32>(empty, valid);
            assert!(mask.inner().ptr_eq(keep.inner()));
            check_list_filter::<i64>(hidden, valid);
            check_list_filter::<i64>(empty, valid);
        }
    }

    #[test]
    fn list_filter_matches_reference_on_random_lists() {
        let mut rng = StdRng::seed_from_u64(42);
        for _ in 0..500 {
            let rows = rng.random_range(0..=24);
            // Mostly short rows, plus some long enough to span 64-bit words.
            let lengths = (0..rows)
                .map(|_| {
                    let max_len = if rng.random_bool(0.2) { 130 } else { 4 };
                    rng.random_range(0..=max_len)
                })
                .collect::<Vec<_>>();
            // Either no NULL buffer, or rows that are NULL with this probability.
            let null_rows = [0.0, 0.3, 0.9][rng.random_range(0..3)];
            let valid = (0..rows)
                .map(|_| !rng.random_bool(null_rows))
                .collect::<Vec<_>>();
            let nulls = (null_rows > 0.0).then(|| NullBuffer::from(valid.clone()));
            let offset = rng.random_range(0..=rows);
            let len = rng.random_range(0..=rows - offset);
            let span = lengths[offset..offset + len].iter().sum::<usize>();
            let density = [0.0, 0.1, 0.5, 0.9, 1.0][rng.random_range(0..5)];
            let keep_offset = rng.random_range(0..130);
            let keep = BooleanBuffer::collect_bool(keep_offset + span, |_| {
                rng.random_bool(density)
            })
            .slice(keep_offset, span);

            let list = null_element_list::<i32>(&lengths, nulls.clone(), offset, len);
            let mask = assert_list_filter_matches_reference(&list, &keep);
            // `keep` is copied only when a visible NULL row stores elements.
            let hides_elements =
                (offset..offset + len).any(|row| !valid[row] && lengths[row] != 0);
            assert_eq!(mask.inner().ptr_eq(keep.inner()), !hides_elements);
            let list = null_element_list::<i64>(&lengths, nulls, offset, len);
            assert_list_filter_matches_reference(&list, &keep);
        }
    }

    #[test]
    fn set_bit_counter_matches_per_position_counts() {
        // A sliced bitmap whose length is a whole number of 64-bit words.
        let bits =
            BooleanBuffer::collect_bool(200, |i| i % 3 != 0 && i % 7 != 0).slice(5, 192);
        let mut counter = SetBitCounter::new(bits.bit_chunks().iter_padded());
        let mut expected = 0;
        for end in 0..=bits.len() {
            assert_eq!(counter.count_before(end), expected, "end {end}");
            if end < bits.len() {
                expected += usize::from(bits.value(end));
            }
        }
    }

    /// Only test internal functions, array-related sql functions will be tested in sqllogictest `array.slt`
    #[test]
    fn test_align_array_dimensions() {
        let array1d_1: ArrayRef =
            Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>(vec![
                Some(vec![Some(1), Some(2), Some(3)]),
                Some(vec![Some(4), Some(5)]),
            ]));
        let array1d_2: ArrayRef =
            Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>(vec![
                Some(vec![Some(6), Some(7), Some(8)]),
            ]));

        let array2d_1: ArrayRef = Arc::new(
            SingleRowListArrayBuilder::new(Arc::clone(&array1d_1)).build_list_array(),
        );
        let array2d_2 = Arc::new(
            SingleRowListArrayBuilder::new(Arc::clone(&array1d_2)).build_list_array(),
        );

        let res = align_array_dimensions::<i32>(vec![
            array1d_1.to_owned(),
            array2d_2.to_owned(),
        ])
        .unwrap();

        let expected = as_list_array(&array2d_1).unwrap();
        let expected_dim = datafusion_common::utils::list_ndims(array2d_1.data_type());
        assert_ne!(as_list_array(&res[0]).unwrap(), expected);
        assert_eq!(
            datafusion_common::utils::list_ndims(res[0].data_type()),
            expected_dim
        );

        let array3d_1: ArrayRef =
            Arc::new(SingleRowListArrayBuilder::new(array2d_1).build_list_array());
        let array3d_2: ArrayRef =
            Arc::new(SingleRowListArrayBuilder::new(array2d_2).build_list_array());
        let res = align_array_dimensions::<i32>(vec![array1d_1, array3d_2]).unwrap();

        let expected = as_list_array(&array3d_1).unwrap();
        let expected_dim = datafusion_common::utils::list_ndims(array3d_1.data_type());
        assert_ne!(as_list_array(&res[0]).unwrap(), expected);
        assert_eq!(
            datafusion_common::utils::list_ndims(res[0].data_type()),
            expected_dim
        );
    }

    #[test]
    fn norm_scale_brings_largest_magnitude_close_to_one() {
        assert_eq!(norm_scale([3e200, -4e200]), Some(2.0_f64.powi(-666)));
        assert_eq!(norm_scale([3.0, 4.0]), Some(0.25));
        // 2^-1023 and 2^1022, pinned by bit pattern rather than computed
        assert_eq!(norm_scale([f64::MAX]), Some(f64::from_bits(1 << 51)));
        assert_eq!(
            norm_scale([f64::MIN_POSITIVE / 4.0]),
            Some(f64::from_bits(2045 << 52))
        );
        // NaN is ignored; the scaled computation still produces NaN
        assert_eq!(norm_scale([f64::NAN, 3.0, 4.0]), Some(0.25));
    }

    #[test]
    fn norm_scale_skips_inputs_the_unscaled_computation_handles() {
        assert_eq!(norm_scale([]), None);
        assert_eq!(norm_scale([0.0, -0.0]), None);
        assert_eq!(norm_scale([f64::NAN, 0.0]), None);
        assert_eq!(norm_scale([f64::INFINITY, 1.0]), None);
        assert_eq!(norm_scale([1.0, f64::NAN, f64::NEG_INFINITY]), None);
    }

    #[test]
    fn needs_norm_scale_only_for_sums_that_may_have_overflowed_or_underflowed() {
        assert!(!needs_norm_scale(1.0, 1));
        assert!(!needs_norm_scale(f64::MAX, 1));
        // The square of 1e-100 is 1e-200, which is far from underflowing.
        assert!(!needs_norm_scale(1e-200, 1));
        assert!(!needs_norm_scale(1e-200, 1536));

        let min_unscaled = 1024.0 * f64::MIN_POSITIVE;
        assert!(!needs_norm_scale(min_unscaled, 1));
        assert!(needs_norm_scale(min_unscaled, 2));
        assert!(needs_norm_scale(min_unscaled / 2.0, 1));

        assert!(needs_norm_scale(0.0, 1));
        assert!(needs_norm_scale(f64::INFINITY, 1));
        assert!(needs_norm_scale(f64::NAN, 1));
    }

    /// Tests the array function supplied via `run` on small slices of a large
    /// list, checking two independent properties:
    ///
    /// 1. Correctness: results match those from equivalent inputs with compact
    ///    child storage.
    /// 2. Capacity: newly created outputs retain little memory, catching
    ///    reservations based on the full child rather than the visible slice.
    ///    Returning the original input is allowed for no-op cases.
    pub(crate) fn check_sliced_list_behavior(
        run: impl Fn(&ArrayRef) -> Result<ArrayRef>,
    ) -> Result<()> {
        let padding = 8192;
        let visible = vec![Some(3.0), None, Some(4.0), Some(9.0), Some(9.0)];
        let values = Float64Array::from_iter(
            std::iter::repeat_n(Some(1.0), padding)
                .chain(visible.iter().copied())
                .chain(std::iter::repeat_n(Some(1.0), padding)),
        );
        let field = Arc::new(Field::new_list_field(DataType::Float64, true));
        let input = ListArray::new(
            Arc::clone(&field),
            OffsetBuffer::from_lengths([padding, 3, 0, 2, padding]),
            Arc::new(values),
            Some(NullBuffer::from(vec![true, true, true, false, true])),
        );
        let compact = ListArray::new(
            Arc::clone(&field),
            OffsetBuffer::from_lengths([3, 0, 2]),
            Arc::new(Float64Array::from(visible)),
            Some(NullBuffer::from(vec![true, true, false])),
        );
        for data_type in [input.data_type().clone(), DataType::LargeList(field)] {
            let input = arrow::compute::cast(&input, &data_type)?;
            let compact = arrow::compute::cast(&compact, &data_type)?;
            // Middle slice, empty slice, empty row, and null row with child data.
            for (offset, len) in [(0, 3), (0, 0), (1, 1), (2, 1)] {
                let sliced = input.slice(1 + offset, len);
                let result = run(&sliced)?;
                let expected = run(&compact.slice(offset, len))?;
                assert_eq!(result.as_ref(), expected.as_ref());
                // Compare buffers, since evaluating through a plan re-wraps arrays.
                assert!(
                    result.to_data().ptr_eq(&sliced.to_data())
                        || result.get_buffer_memory_size() < 1024,
                    "{data_type}: {} bytes for {len} rows",
                    result.get_buffer_memory_size()
                );
            }
        }
        Ok(())
    }
}