Skip to main content

datafusion_functions_nested/
utils.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! array function utils
6
7use std::sync::Arc;
8
9use arrow::datatypes::{DataType, Field, FieldRef, Fields};
10
11use arrow::array::{
12    Array, ArrayRef, BooleanArray, BooleanBufferBuilder, Float64Array, GenericListArray,
13    NullBufferBuilder, OffsetSizeTrait, Scalar, new_empty_array,
14};
15use arrow::buffer::{BooleanBuffer, NullBuffer, OffsetBuffer};
16use datafusion_common::cast::{
17    as_fixed_size_list_array, as_float64_array, as_generic_list_array,
18    as_large_list_array, as_large_list_view_array, as_list_array, as_list_view_array,
19};
20use datafusion_common::utils::{offset_span, offset_span_len};
21use datafusion_common::{Result, ScalarValue, exec_err, internal_err, plan_err};
22
23use datafusion_expr::ColumnarValue;
24use itertools::Itertools as _;
25
26/// Empty every valid list row, preserving parent nulls and the given child field.
27pub(crate) fn empty_list_values<O: OffsetSizeTrait>(
28    list: &GenericListArray<O>,
29    field: FieldRef,
30) -> ArrayRef {
31    let values = new_empty_array(field.data_type());
32    Arc::new(GenericListArray::<O>::new(
33        field,
34        OffsetBuffer::new_zeroed(list.len()),
35        values,
36        list.nulls().cloned(),
37    ))
38}
39
40/// Build result row offsets and exclude elements stored under NULL list rows.
41///
42/// `keep` is a bitmap identifying which elements in the list's visible span
43/// should be preserved. The returned bitmap uses the same indexing, with bits
44/// for NULL list rows cleared. Selected elements may themselves be NULL; their
45/// validity is the caller's responsibility when copying values.
46pub(crate) fn prepare_list_filter<O: OffsetSizeTrait>(
47    list: &GenericListArray<O>,
48    keep: &BooleanBuffer,
49) -> (OffsetBuffer<O>, BooleanBuffer) {
50    let list_offsets = list.offsets();
51    let (first_offset, span_len) = offset_span(list_offsets);
52    debug_assert_eq!(keep.len(), span_len);
53    let mut offsets = Vec::with_capacity(list.len() + 1);
54    offsets.push(O::zero());
55    // Count the set bits before each row end in one pass over `keep`, which
56    // stays cheap for short rows.
57    let keep_mask = if list.null_count() == 0 {
58        // Without NULL rows, every set bit is kept.
59        let mut set_bits = SetBitCounter::new(keep.bit_chunks().iter_padded());
60        offsets.extend(list_offsets[1..].iter().map(|end| {
61            O::usize_as(set_bits.count_before(end.as_usize() - first_offset))
62        }));
63        keep.clone()
64    } else {
65        let mut set_bits = SetBitCounter::new(keep.bit_chunks().iter_padded());
66        let mut kept_count = 0;
67        // Set bits stored under NULL rows, which the result does not keep.
68        let mut hidden_count = 0;
69        // NULL list rows are usually empty, so reuse `keep` until a NULL row
70        // stores elements. Copy the bits of the preceding rows when that first
71        // happens.
72        let mut keep_mask: Option<BooleanBufferBuilder> = None;
73        for (row, window) in list_offsets.windows(2).enumerate() {
74            let start = window[0].as_usize() - first_offset;
75            let end = window[1].as_usize() - first_offset;
76            let len = end - start;
77            let bit_start = keep.offset() + start;
78            if list.is_valid(row) {
79                kept_count = set_bits.count_before(end) - hidden_count;
80                if let Some(keep_mask) = &mut keep_mask {
81                    keep_mask
82                        .append_packed_range(bit_start..bit_start + len, keep.values());
83                }
84            } else if len != 0 {
85                let set_before_row = set_bits.count_before(start);
86                hidden_count += set_bits.count_before(end) - set_before_row;
87                keep_mask
88                    .get_or_insert_with(|| {
89                        let mut builder = BooleanBufferBuilder::new(keep.len());
90                        builder
91                            .append_packed_range(keep.offset()..bit_start, keep.values());
92                        builder
93                    })
94                    .append_n(len, false);
95            }
96            offsets.push(O::usize_as(kept_count));
97        }
98        keep_mask
99            .map(BooleanBufferBuilder::build)
100            .unwrap_or_else(|| keep.clone())
101    };
102    debug_assert_eq!(keep_mask.len(), keep.len());
103    // SAFETY: offsets start at zero and never decrease, since each one counts
104    // the kept elements up to a row's end. A count cannot exceed the input's
105    // element span, which fits in `O`, so converting it to `O` cannot overflow.
106    let offsets = unsafe { OffsetBuffer::new_unchecked(offsets.into()) };
107    (offsets, keep_mask)
108}
109
110/// Counts the set bits that precede a sequence of non-decreasing positions in a
111/// bitmap, reading each 64-bit word of the bitmap once.
112struct SetBitCounter<I> {
113    /// The bitmap's remaining words, with the final word padded with zeros.
114    words: I,
115    /// The word containing the most recent position.
116    word: u64,
117    /// Position of the first bit of `word`.
118    word_start: usize,
119    /// Set bits before `word_start`.
120    count_before_word: usize,
121}
122
123impl<I: Iterator<Item = u64>> SetBitCounter<I> {
124    fn new(mut words: I) -> Self {
125        let word = words.next().unwrap_or(0);
126        Self {
127            words,
128            word,
129            word_start: 0,
130            count_before_word: 0,
131        }
132    }
133
134    /// Returns the number of set bits before `end`. `end` must be no less than
135    /// in the previous call, and no greater than the bitmap's length.
136    #[inline]
137    fn count_before(&mut self, end: usize) -> usize {
138        debug_assert!(end >= self.word_start);
139        while end - self.word_start >= 64 {
140            self.count_before_word += self.word.count_ones() as usize;
141            self.word = self.words.next().unwrap_or(0);
142            self.word_start += 64;
143        }
144        let mask = (1u64 << (end - self.word_start)) - 1;
145        self.count_before_word + (self.word & mask).count_ones() as usize
146    }
147}
148
149/// Computes the return type of a function that produces a list with the same
150/// inner field as `array_type`, plus an element that may be null when
151/// `element_nullable` is set.
152///
153/// The inner field is carried over from `array_type` verbatim — name, metadata
154/// and all — so that the type promised at planning time is the one the kernel
155/// can actually build. Its nullability is widened when `element_nullable` is
156/// set, because a nullable new element may introduce nulls into a list whose
157/// elements were previously declared non-nullable.
158///
159/// Types other than `List`/`LargeList` are returned unchanged; callers handle
160/// `Null` themselves and the kernels reject anything else at execution time.
161pub(crate) fn list_type_with_element(
162    array_type: &DataType,
163    element_nullable: bool,
164) -> DataType {
165    match array_type {
166        DataType::List(field) => {
167            DataType::List(widen_nullability(field, element_nullable))
168        }
169        DataType::LargeList(field) => {
170            DataType::LargeList(widen_nullability(field, element_nullable))
171        }
172        other => other.clone(),
173    }
174}
175
176fn widen_nullability(field: &FieldRef, nullable: bool) -> FieldRef {
177    if nullable && !field.is_nullable() {
178        Arc::new(field.as_ref().clone().with_nullable(true))
179    } else {
180        Arc::clone(field)
181    }
182}
183
184/// Extracts the inner field of a `List`/`LargeList` type, so that a kernel can
185/// build a list array carrying exactly that field.
186///
187/// Used both on an input's type and on the type promised by
188/// [`ScalarUDFImpl::return_field_from_args`]. Anything else is a bug in the
189/// caller's dispatch, hence the internal error; `context` names the kernel so
190/// that error identifies where the bad dispatch happened.
191///
192/// [`ScalarUDFImpl::return_field_from_args`]: datafusion_expr::ScalarUDFImpl::return_field_from_args
193pub(crate) fn list_inner_field(context: &str, data_type: &DataType) -> Result<FieldRef> {
194    match data_type {
195        DataType::List(field) | DataType::LargeList(field) => Ok(Arc::clone(field)),
196        other => internal_err!("{context} got unexpected data type: {other}"),
197    }
198}
199
200pub(crate) fn check_datatypes(name: &str, args: &[&ArrayRef]) -> Result<()> {
201    let data_type = args[0].data_type();
202    if !args.iter().all(|arg| {
203        arg.data_type().equals_datatype(data_type)
204            || arg.data_type().equals_datatype(&DataType::Null)
205    }) {
206        let types = args.iter().map(|arg| arg.data_type()).collect::<Vec<_>>();
207        return plan_err!(
208            "{name} received incompatible types: {}",
209            types.iter().join(", ")
210        );
211    }
212
213    Ok(())
214}
215
216/// array function wrapper that differentiates between scalar (length 1) and array.
217pub(crate) fn make_scalar_function<F>(
218    inner: F,
219) -> impl Fn(&[ColumnarValue]) -> Result<ColumnarValue>
220where
221    F: Fn(&[ArrayRef]) -> Result<ArrayRef>,
222{
223    move |args: &[ColumnarValue]| {
224        // first, identify if any of the arguments is an Array. If yes, store its `len`,
225        // as any scalar will need to be converted to an array of len `len`.
226        let len = args
227            .iter()
228            .fold(Option::<usize>::None, |acc, arg| match arg {
229                ColumnarValue::Scalar(_) => acc,
230                ColumnarValue::Array(a) => Some(a.len()),
231            });
232
233        let is_scalar = len.is_none();
234
235        let args = ColumnarValue::values_to_arrays(args)?;
236
237        let result = (inner)(&args);
238
239        if is_scalar {
240            // If all inputs are scalar, keeps output as scalar
241            let result = result.and_then(|arr| ScalarValue::try_from_array(&arr, 0));
242            result.map(ColumnarValue::Scalar)
243        } else {
244            result.map(ColumnarValue::Array)
245        }
246    }
247}
248
249pub(crate) fn align_array_dimensions<O: OffsetSizeTrait>(
250    args: Vec<ArrayRef>,
251) -> Result<Vec<ArrayRef>> {
252    let args_ndim = args
253        .iter()
254        .map(|arg| datafusion_common::utils::list_ndims(arg.data_type()))
255        .collect::<Vec<_>>();
256    let max_ndim = args_ndim.iter().max().unwrap_or(&0);
257
258    // Align the dimensions of the arrays
259    let aligned_args: Result<Vec<ArrayRef>> = args
260        .into_iter()
261        .zip(args_ndim.iter())
262        .map(|(array, ndim)| {
263            if ndim < max_ndim {
264                let mut aligned_array = Arc::clone(&array);
265                for _ in 0..(max_ndim - ndim) {
266                    let data_type = aligned_array.data_type().to_owned();
267                    let array_lengths = std::iter::repeat_n(1, aligned_array.len());
268                    let offsets = OffsetBuffer::<O>::from_lengths(array_lengths);
269
270                    aligned_array = Arc::new(GenericListArray::<O>::try_new(
271                        Arc::new(Field::new_list_field(data_type, true)),
272                        offsets,
273                        aligned_array,
274                        None,
275                    )?)
276                }
277                Ok(aligned_array)
278            } else {
279                Ok(Arc::clone(&array))
280            }
281        })
282        .collect();
283
284    aligned_args
285}
286
287/// Computes a BooleanArray indicating equality or inequality between elements in a list array and a specified element array.
288///
289/// # Arguments
290///
291/// * `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.
292///
293/// * `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.
294///
295/// * `row_index` - The index of the row in the `element_array` and `list_array` to use for the comparison.
296///
297/// * `eq` - A boolean flag. If `true`, the function computes equality; if `false`, it computes inequality.
298///
299/// # Returns
300///
301/// Returns a `Result<BooleanArray>` representing the comparison results. The result may contain an error if there are issues with the computation.
302///
303/// # Example
304///
305/// ```text
306/// compare_element_to_list(
307///     [1, 2, 3], [1, 2, 3], 0, true => [true, false, false]
308///     [1, 2, 3, 3, 2, 1], [1, 2, 3], 1, true => [false, true, false, false, true, false]
309///
310///     [[1, 2, 3], [2, 3, 4], [3, 4, 5]], [[1, 2, 3], [2, 3, 4], [3, 4, 5]], 0, true => [true, false, false]
311///     [[1, 2, 3], [2, 3, 4], [2, 3, 4]], [[1, 2, 3], [2, 3, 4], [3, 4, 5]], 1, false => [true, false, false]
312/// )
313/// ```
314pub(crate) fn compare_element_to_list(
315    list_array_row: &dyn Array,
316    element_array: &dyn Array,
317    row_index: usize,
318    eq: bool,
319) -> Result<BooleanArray> {
320    if list_array_row.data_type() != element_array.data_type() {
321        return exec_err!(
322            "compare_element_to_list received incompatible types: '{:?}' and '{:?}'.",
323            list_array_row.data_type(),
324            element_array.data_type()
325        );
326    }
327
328    let element_array_row = element_array.slice(row_index, 1);
329
330    // Compute all positions in list_row_array (that is itself an
331    // array) that are equal to `from_array_row`
332    let res = match element_array_row.data_type() {
333        // arrow_ord::cmp::eq does not support ListArray, so we need to compare it by loop
334        DataType::List(_) => {
335            // compare each element of the from array
336            let element_array_row_inner = as_list_array(&element_array_row)?.value(0);
337            let list_array_row_inner = as_list_array(list_array_row)?;
338
339            list_array_row_inner
340                .iter()
341                // compare element by element the current row of list_array
342                .map(|row| {
343                    row.map(|row| {
344                        if eq {
345                            row.eq(&element_array_row_inner)
346                        } else {
347                            row.ne(&element_array_row_inner)
348                        }
349                    })
350                })
351                .collect::<BooleanArray>()
352        }
353        DataType::LargeList(_) => {
354            // compare each element of the from array
355            let element_array_row_inner =
356                as_large_list_array(&element_array_row)?.value(0);
357            let list_array_row_inner = as_large_list_array(list_array_row)?;
358
359            list_array_row_inner
360                .iter()
361                // compare element by element the current row of list_array
362                .map(|row| {
363                    row.map(|row| {
364                        if eq {
365                            row.eq(&element_array_row_inner)
366                        } else {
367                            row.ne(&element_array_row_inner)
368                        }
369                    })
370                })
371                .collect::<BooleanArray>()
372        }
373        _ => {
374            let element_arr = Scalar::new(element_array_row);
375            // use not_distinct so we can compare NULL
376            if eq {
377                arrow_ord::cmp::not_distinct(&list_array_row, &element_arr)?
378            } else {
379                arrow_ord::cmp::distinct(&list_array_row, &element_arr)?
380            }
381        }
382    };
383
384    Ok(res)
385}
386
387/// Returns the length of each array dimension
388pub(crate) fn compute_array_dims(
389    arr: Option<ArrayRef>,
390) -> Result<Option<Vec<Option<u64>>>> {
391    let Some(mut value) = arr else {
392        return Ok(None);
393    };
394    if value.is_empty() {
395        return Ok(None);
396    }
397    let mut res = vec![Some(value.len() as u64)];
398
399    loop {
400        match value.data_type() {
401            DataType::List(_) => {
402                value = as_list_array(&value)?.value(0);
403                res.push(Some(value.len() as u64));
404            }
405            DataType::LargeList(_) => {
406                value = as_large_list_array(&value)?.value(0);
407                res.push(Some(value.len() as u64));
408            }
409            DataType::ListView(_) => {
410                value = as_list_view_array(&value)?.value(0);
411                res.push(Some(value.len() as u64));
412            }
413            DataType::LargeListView(_) => {
414                value = as_large_list_view_array(&value)?.value(0);
415                res.push(Some(value.len() as u64));
416            }
417            DataType::FixedSizeList(..) => {
418                value = as_fixed_size_list_array(&value)?.value(0);
419                res.push(Some(value.len() as u64));
420            }
421            _ => return Ok(Some(res)),
422        }
423    }
424}
425
426pub(crate) fn get_map_entry_field(data_type: &DataType) -> Result<&Fields> {
427    match data_type {
428        DataType::Map(field, _) => {
429            let field_data_type = field.data_type();
430            match field_data_type {
431                DataType::Struct(fields) => Ok(fields),
432                _ => {
433                    internal_err!("Expected a Struct type, got {}", field_data_type)
434                }
435            }
436        }
437        _ => plan_err!("Expected a Map type, got {data_type}"),
438    }
439}
440
441/// Shared `coerce_types` impl for array-math UDFs whose kernels expect
442/// `List<Float64>` / `LargeList<Float64>` (e.g. `array_add`, `cosine_distance`,
443/// `inner_product`, `array_normalize`).
444///
445/// Each input must be `Null`, `List`, `LargeList`, or `FixedSizeList`; otherwise
446/// returns a plan error naming `name`. `FixedSizeList` is widened to `List`,
447/// `Null` is coerced to a list of `Float64`, and if any input is `LargeList`
448/// the rest are widened to `LargeList` so the runtime sees a homogeneous pair.
449pub(crate) fn coerce_array_math_arg_types(
450    name: &str,
451    arg_types: &[DataType],
452) -> Result<Vec<DataType>> {
453    use DataType::{FixedSizeList, LargeList, List, Null};
454    use datafusion_common::utils::{ListCoercion, coerced_type_with_base_type_only};
455
456    let coercion = Some(&ListCoercion::FixedSizedListToList);
457
458    for arg_type in arg_types {
459        if !matches!(arg_type, Null | List(_) | LargeList(_) | FixedSizeList(..)) {
460            return plan_err!("{name} does not support type {arg_type}");
461        }
462    }
463
464    // If any input is `LargeList`, both sides must be widened to `LargeList`
465    // so the runtime dispatch in `inner_product_inner` sees a homogeneous
466    // pair. Follows the pattern in `ArrayConcat::coerce_types`.
467    let any_large_list = arg_types.iter().any(|t| matches!(t, LargeList(_)));
468
469    let coerced = arg_types
470        .iter()
471        .map(|arg_type| {
472            if matches!(arg_type, Null) {
473                let field = Arc::new(Field::new_list_field(DataType::Float64, true));
474                return if any_large_list {
475                    LargeList(field)
476                } else {
477                    List(field)
478                };
479            }
480            let coerced =
481                coerced_type_with_base_type_only(arg_type, &DataType::Float64, coercion);
482            match coerced {
483                List(field) if any_large_list => LargeList(field),
484                other => other,
485            }
486        })
487        .collect();
488
489    Ok(coerced)
490}
491
492/// Element-wise binary operation kernel for two `Float64` lists of equal per-row
493/// length. The caller is responsible for type-dispatching on `O` (`i32` for
494/// `List`, `i64` for `LargeList`).
495///
496/// Semantics:
497/// - whole-row NULL on either side → NULL output row, length 0
498/// - per-element NULL on either side → NULL at that output position
499/// - per-row length mismatch → exec error tagged with `op_name`
500///
501/// `op_name` flows into the error message; `op` is the per-element scalar op
502/// (e.g. `|a, b| a + b` for `array_add`, `|a, b| a - b` for `array_subtract`).
503pub(crate) fn array_math_binary_op<O, F>(
504    op_name: &str,
505    lhs: &ArrayRef,
506    rhs: &ArrayRef,
507    op: F,
508) -> Result<ArrayRef>
509where
510    O: OffsetSizeTrait,
511    F: Fn(f64, f64) -> f64,
512{
513    let lhs = as_generic_list_array::<O>(lhs)?;
514    let rhs = as_generic_list_array::<O>(rhs)?;
515
516    let lhs_values = as_float64_array(lhs.values())?;
517    let rhs_values = as_float64_array(rhs.values())?;
518    let lhs_offsets = lhs.value_offsets();
519    let rhs_offsets = rhs.value_offsets();
520
521    let row_nulls = NullBuffer::union(lhs.nulls(), rhs.nulls());
522
523    let capacity = offset_span_len(lhs.offsets());
524    let mut out_values: Vec<f64> = Vec::with_capacity(capacity);
525    let mut out_inner_nulls = NullBufferBuilder::new(capacity);
526    let mut out_offsets = Vec::<O>::with_capacity(lhs.len() + 1);
527    out_offsets.push(O::zero());
528
529    for row in 0..lhs.len() {
530        if row_nulls.as_ref().is_some_and(|nb| nb.is_null(row)) {
531            out_offsets.push(out_offsets[row]);
532            continue;
533        }
534
535        let start1 = lhs_offsets[row].as_usize();
536        let len1 = lhs.value_length(row).as_usize();
537        let start2 = rhs_offsets[row].as_usize();
538        let len2 = rhs.value_length(row).as_usize();
539
540        if len1 != len2 {
541            return exec_err!(
542                "{op_name} requires both list inputs to have the same length per row, got {len1} and {len2} at row {row}"
543            );
544        }
545
546        let l_slice = lhs_values.slice(start1, len1);
547        let r_slice = rhs_values.slice(start2, len2);
548
549        let l_vals = l_slice.values();
550        let r_vals = r_slice.values();
551
552        for i in 0..len1 {
553            out_values.push(op(l_vals[i], r_vals[i]));
554        }
555
556        match NullBuffer::union(l_slice.nulls(), r_slice.nulls()) {
557            Some(nb) => out_inner_nulls.append_buffer(&nb),
558            None => out_inner_nulls.append_n_non_nulls(len1),
559        }
560
561        out_offsets.push(out_offsets[row] + O::usize_as(len1));
562    }
563
564    let values_array = Arc::new(Float64Array::new(
565        out_values.into(),
566        out_inner_nulls.finish(),
567    ));
568    let field = Arc::new(Field::new_list_field(DataType::Float64, true));
569
570    Ok(Arc::new(GenericListArray::<O>::try_new(
571        field,
572        OffsetBuffer::new(out_offsets.into()),
573        values_array,
574        row_nulls,
575    )?))
576}
577
578/// Returns a power of two that brings the largest magnitude in `values` close
579/// to 1, so that squaring the scaled values neither overflows nor underflows.
580///
581/// Squaring a large finite value overflows (`1e200 * 1e200` is infinity) and
582/// squaring a small one underflows (`1e-200 * 1e-200` is zero), even when the
583/// norm itself is representable. The factor is a power of two, so scaling is
584/// exact whenever the scaled value is normal. A value that becomes subnormal is
585/// rounded, so an `array_normalize` element that is itself subnormal can differ
586/// from the unscaled result in its last bit.
587///
588/// Returns `None` when `values` is empty, all zero, or contains an infinity.
589/// The unscaled computation already gives the expected result for those inputs.
590/// NaN values are ignored, and the scaled computation still produces NaN.
591pub(crate) fn norm_scale(values: impl IntoIterator<Item = f64>) -> Option<f64> {
592    // No early return inside the loop, so that it vectorizes. `f64::max` skips
593    // NaN, so only an infinity can make `max` non-finite.
594    let mut max = 0.0_f64;
595    for value in values {
596        max = max.max(value.abs());
597    }
598    if max == 0.0 || !max.is_finite() {
599        return None;
600    }
601    // Unbiased exponent of `max`. Subnormal values store a biased exponent of 0,
602    // so clamp them to the smallest normal exponent.
603    let exponent = ((max.to_bits() >> 52) as i32 - 1023).max(-1022);
604    Some(2.0_f64.powi(-exponent))
605}
606
607/// Returns whether a sum of `len` squares computed without scaling may be
608/// wrong because a square overflowed or underflowed, in which case it should be
609/// recomputed with the factor from [`norm_scale`].
610///
611/// An overflowing square makes the sum infinite. An underflowing square is off
612/// by at most half the smallest subnormal value, so `len` of them move the sum
613/// by at most `len * 2^-1075`. A sum of at least `len * 2^-1012` is therefore
614/// off by less than `2^-63` of itself, far below its rounding precision.
615pub(crate) fn needs_norm_scale(sum_of_squares: f64, len: usize) -> bool {
616    // 2^-1012 = 2^10 * f64::MIN_POSITIVE
617    let min_unscaled = 1024.0 * len as f64 * f64::MIN_POSITIVE;
618    !(min_unscaled..f64::INFINITY).contains(&sum_of_squares)
619}
620
621#[cfg(test)]
622pub(crate) mod tests {
623    use super::*;
624    use arrow::array::ListArray;
625    use arrow::datatypes::Int64Type;
626    use datafusion_common::utils::SingleRowListArrayBuilder;
627    use rand::{Rng, SeedableRng, rngs::StdRng};
628
629    /// Compare `prepare_list_filter` with a per-row reference, returning the
630    /// output bitmap so callers can check whether `keep` was reused.
631    fn assert_list_filter_matches_reference<O: OffsetSizeTrait>(
632        list: &GenericListArray<O>,
633        keep: &BooleanBuffer,
634    ) -> BooleanBuffer {
635        let first = list.offsets()[0].as_usize();
636        let mut expected = keep.iter().collect::<Vec<_>>();
637        let mut expected_offsets = vec![0];
638        for (row, window) in list.offsets().windows(2).enumerate() {
639            let start = window[0].as_usize() - first;
640            let end = window[1].as_usize() - first;
641            if list.is_null(row) {
642                expected[start..end].fill(false);
643            }
644            expected_offsets.push(expected[..end].iter().filter(|&&v| v).count());
645        }
646        let (offsets, mask) = prepare_list_filter(list, keep);
647        assert_eq!(mask.iter().collect::<Vec<_>>(), expected);
648        assert_eq!(
649            offsets.iter().map(|o| o.as_usize()).collect::<Vec<_>>(),
650            expected_offsets
651        );
652        mask
653    }
654
655    /// A list of NULL elements with the given row lengths and row validity,
656    /// sliced to `len` rows starting at row `offset`.
657    fn null_element_list<O: OffsetSizeTrait>(
658        lengths: &[usize],
659        nulls: Option<NullBuffer>,
660        offset: usize,
661        len: usize,
662    ) -> GenericListArray<O> {
663        GenericListArray::<O>::new(
664            Arc::new(Field::new_list_field(DataType::Int32, true)),
665            OffsetBuffer::from_lengths(lengths.iter().copied()),
666            // `prepare_list_filter` must permit selecting NULL elements.
667            arrow::array::new_null_array(&DataType::Int32, lengths.iter().sum()),
668            nulls,
669        )
670        .slice(offset, len)
671    }
672
673    /// Check a list sliced to its last seven rows, returning the input and output
674    /// bitmaps so callers can check whether the input was reused.
675    fn check_list_filter<O: OffsetSizeTrait>(
676        lengths: [usize; 8],
677        valid: [bool; 8],
678    ) -> (BooleanBuffer, BooleanBuffer) {
679        let nulls = Some(NullBuffer::from(valid.to_vec()));
680        let list = null_element_list::<O>(&lengths, nulls, 1, 7);
681        let len = offset_span(list.offsets()).1;
682        // Use an offset that is not a multiple of the bitmap's three-bit period.
683        let keep = BooleanBuffer::collect_bool(len + 1, |i| i % 3 != 0).slice(1, len);
684        let mask = assert_list_filter_matches_reference(&list, &keep);
685        (keep, mask)
686    }
687
688    #[test]
689    fn list_filter_mask_handles_slices_and_hidden_elements() {
690        let valid = [true, false, true, false, false, true, true, false];
691        // After slicing off the first row, the first lengths of each pair give an
692        // empty NULL row, a NULL row storing elements after a valid row,
693        // consecutive NULL rows, and a trailing one. The second lengths store no
694        // elements under NULL rows, which leaves the bitmap untouched.
695        for (hidden, empty) in [
696            ([2, 0, 2, 1, 2, 0, 3, 2], [2, 0, 2, 0, 0, 3, 3, 0]),
697            // Rows long enough that counting and copying bits spans 64-bit words.
698            ([2, 0, 63, 65, 64, 0, 65, 2], [2, 0, 63, 0, 0, 65, 65, 0]),
699        ] {
700            let (keep, mask) = check_list_filter::<i32>(hidden, valid);
701            assert!(!mask.inner().ptr_eq(keep.inner()));
702            let (keep, mask) = check_list_filter::<i32>(empty, valid);
703            assert!(mask.inner().ptr_eq(keep.inner()));
704            check_list_filter::<i64>(hidden, valid);
705            check_list_filter::<i64>(empty, valid);
706        }
707    }
708
709    #[test]
710    fn list_filter_matches_reference_on_random_lists() {
711        let mut rng = StdRng::seed_from_u64(42);
712        for _ in 0..500 {
713            let rows = rng.random_range(0..=24);
714            // Mostly short rows, plus some long enough to span 64-bit words.
715            let lengths = (0..rows)
716                .map(|_| {
717                    let max_len = if rng.random_bool(0.2) { 130 } else { 4 };
718                    rng.random_range(0..=max_len)
719                })
720                .collect::<Vec<_>>();
721            // Either no NULL buffer, or rows that are NULL with this probability.
722            let null_rows = [0.0, 0.3, 0.9][rng.random_range(0..3)];
723            let valid = (0..rows)
724                .map(|_| !rng.random_bool(null_rows))
725                .collect::<Vec<_>>();
726            let nulls = (null_rows > 0.0).then(|| NullBuffer::from(valid.clone()));
727            let offset = rng.random_range(0..=rows);
728            let len = rng.random_range(0..=rows - offset);
729            let span = lengths[offset..offset + len].iter().sum::<usize>();
730            let density = [0.0, 0.1, 0.5, 0.9, 1.0][rng.random_range(0..5)];
731            let keep_offset = rng.random_range(0..130);
732            let keep = BooleanBuffer::collect_bool(keep_offset + span, |_| {
733                rng.random_bool(density)
734            })
735            .slice(keep_offset, span);
736
737            let list = null_element_list::<i32>(&lengths, nulls.clone(), offset, len);
738            let mask = assert_list_filter_matches_reference(&list, &keep);
739            // `keep` is copied only when a visible NULL row stores elements.
740            let hides_elements =
741                (offset..offset + len).any(|row| !valid[row] && lengths[row] != 0);
742            assert_eq!(mask.inner().ptr_eq(keep.inner()), !hides_elements);
743            let list = null_element_list::<i64>(&lengths, nulls, offset, len);
744            assert_list_filter_matches_reference(&list, &keep);
745        }
746    }
747
748    #[test]
749    fn set_bit_counter_matches_per_position_counts() {
750        // A sliced bitmap whose length is a whole number of 64-bit words.
751        let bits =
752            BooleanBuffer::collect_bool(200, |i| i % 3 != 0 && i % 7 != 0).slice(5, 192);
753        let mut counter = SetBitCounter::new(bits.bit_chunks().iter_padded());
754        let mut expected = 0;
755        for end in 0..=bits.len() {
756            assert_eq!(counter.count_before(end), expected, "end {end}");
757            if end < bits.len() {
758                expected += usize::from(bits.value(end));
759            }
760        }
761    }
762
763    /// Only test internal functions, array-related sql functions will be tested in sqllogictest `array.slt`
764    #[test]
765    fn test_align_array_dimensions() {
766        let array1d_1: ArrayRef =
767            Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>(vec![
768                Some(vec![Some(1), Some(2), Some(3)]),
769                Some(vec![Some(4), Some(5)]),
770            ]));
771        let array1d_2: ArrayRef =
772            Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>(vec![
773                Some(vec![Some(6), Some(7), Some(8)]),
774            ]));
775
776        let array2d_1: ArrayRef = Arc::new(
777            SingleRowListArrayBuilder::new(Arc::clone(&array1d_1)).build_list_array(),
778        );
779        let array2d_2 = Arc::new(
780            SingleRowListArrayBuilder::new(Arc::clone(&array1d_2)).build_list_array(),
781        );
782
783        let res = align_array_dimensions::<i32>(vec![
784            array1d_1.to_owned(),
785            array2d_2.to_owned(),
786        ])
787        .unwrap();
788
789        let expected = as_list_array(&array2d_1).unwrap();
790        let expected_dim = datafusion_common::utils::list_ndims(array2d_1.data_type());
791        assert_ne!(as_list_array(&res[0]).unwrap(), expected);
792        assert_eq!(
793            datafusion_common::utils::list_ndims(res[0].data_type()),
794            expected_dim
795        );
796
797        let array3d_1: ArrayRef =
798            Arc::new(SingleRowListArrayBuilder::new(array2d_1).build_list_array());
799        let array3d_2: ArrayRef =
800            Arc::new(SingleRowListArrayBuilder::new(array2d_2).build_list_array());
801        let res = align_array_dimensions::<i32>(vec![array1d_1, array3d_2]).unwrap();
802
803        let expected = as_list_array(&array3d_1).unwrap();
804        let expected_dim = datafusion_common::utils::list_ndims(array3d_1.data_type());
805        assert_ne!(as_list_array(&res[0]).unwrap(), expected);
806        assert_eq!(
807            datafusion_common::utils::list_ndims(res[0].data_type()),
808            expected_dim
809        );
810    }
811
812    #[test]
813    fn norm_scale_brings_largest_magnitude_close_to_one() {
814        assert_eq!(norm_scale([3e200, -4e200]), Some(2.0_f64.powi(-666)));
815        assert_eq!(norm_scale([3.0, 4.0]), Some(0.25));
816        // 2^-1023 and 2^1022, pinned by bit pattern rather than computed
817        assert_eq!(norm_scale([f64::MAX]), Some(f64::from_bits(1 << 51)));
818        assert_eq!(
819            norm_scale([f64::MIN_POSITIVE / 4.0]),
820            Some(f64::from_bits(2045 << 52))
821        );
822        // NaN is ignored; the scaled computation still produces NaN
823        assert_eq!(norm_scale([f64::NAN, 3.0, 4.0]), Some(0.25));
824    }
825
826    #[test]
827    fn norm_scale_skips_inputs_the_unscaled_computation_handles() {
828        assert_eq!(norm_scale([]), None);
829        assert_eq!(norm_scale([0.0, -0.0]), None);
830        assert_eq!(norm_scale([f64::NAN, 0.0]), None);
831        assert_eq!(norm_scale([f64::INFINITY, 1.0]), None);
832        assert_eq!(norm_scale([1.0, f64::NAN, f64::NEG_INFINITY]), None);
833    }
834
835    #[test]
836    fn needs_norm_scale_only_for_sums_that_may_have_overflowed_or_underflowed() {
837        assert!(!needs_norm_scale(1.0, 1));
838        assert!(!needs_norm_scale(f64::MAX, 1));
839        // The square of 1e-100 is 1e-200, which is far from underflowing.
840        assert!(!needs_norm_scale(1e-200, 1));
841        assert!(!needs_norm_scale(1e-200, 1536));
842
843        let min_unscaled = 1024.0 * f64::MIN_POSITIVE;
844        assert!(!needs_norm_scale(min_unscaled, 1));
845        assert!(needs_norm_scale(min_unscaled, 2));
846        assert!(needs_norm_scale(min_unscaled / 2.0, 1));
847
848        assert!(needs_norm_scale(0.0, 1));
849        assert!(needs_norm_scale(f64::INFINITY, 1));
850        assert!(needs_norm_scale(f64::NAN, 1));
851    }
852
853    /// Tests the array function supplied via `run` on small slices of a large
854    /// list, checking two independent properties:
855    ///
856    /// 1. Correctness: results match those from equivalent inputs with compact
857    ///    child storage.
858    /// 2. Capacity: newly created outputs retain little memory, catching
859    ///    reservations based on the full child rather than the visible slice.
860    ///    Returning the original input is allowed for no-op cases.
861    pub(crate) fn check_sliced_list_behavior(
862        run: impl Fn(&ArrayRef) -> Result<ArrayRef>,
863    ) -> Result<()> {
864        let padding = 8192;
865        let visible = vec![Some(3.0), None, Some(4.0), Some(9.0), Some(9.0)];
866        let values = Float64Array::from_iter(
867            std::iter::repeat_n(Some(1.0), padding)
868                .chain(visible.iter().copied())
869                .chain(std::iter::repeat_n(Some(1.0), padding)),
870        );
871        let field = Arc::new(Field::new_list_field(DataType::Float64, true));
872        let input = ListArray::new(
873            Arc::clone(&field),
874            OffsetBuffer::from_lengths([padding, 3, 0, 2, padding]),
875            Arc::new(values),
876            Some(NullBuffer::from(vec![true, true, true, false, true])),
877        );
878        let compact = ListArray::new(
879            Arc::clone(&field),
880            OffsetBuffer::from_lengths([3, 0, 2]),
881            Arc::new(Float64Array::from(visible)),
882            Some(NullBuffer::from(vec![true, true, false])),
883        );
884        for data_type in [input.data_type().clone(), DataType::LargeList(field)] {
885            let input = arrow::compute::cast(&input, &data_type)?;
886            let compact = arrow::compute::cast(&compact, &data_type)?;
887            // Middle slice, empty slice, empty row, and null row with child data.
888            for (offset, len) in [(0, 3), (0, 0), (1, 1), (2, 1)] {
889                let sliced = input.slice(1 + offset, len);
890                let result = run(&sliced)?;
891                let expected = run(&compact.slice(offset, len))?;
892                assert_eq!(result.as_ref(), expected.as_ref());
893                // Compare buffers, since evaluating through a plan re-wraps arrays.
894                assert!(
895                    result.to_data().ptr_eq(&sliced.to_data())
896                        || result.get_buffer_memory_size() < 1024,
897                    "{data_type}: {} bytes for {len} rows",
898                    result.get_buffer_memory_size()
899                );
900            }
901        }
902        Ok(())
903    }
904}