Skip to main content

vortex_array/aggregate_fn/fns/min_max/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod bool;
5mod decimal;
6pub use decimal::valid_range;
7mod extension;
8mod fixed_size_list;
9mod primitive;
10mod varbinview;
11
12use std::sync::LazyLock;
13
14use vortex_error::VortexExpect;
15use vortex_error::VortexResult;
16use vortex_error::vortex_bail;
17use vortex_error::vortex_panic;
18use vortex_session::registry::CachedId;
19
20use self::bool::accumulate_bool;
21use self::decimal::accumulate_decimal;
22use self::extension::accumulate_extension;
23use self::fixed_size_list::accumulate_fixed_size_bytes;
24use self::primitive::accumulate_primitive;
25use self::varbinview::accumulate_varbinview;
26use crate::ArrayRef;
27use crate::Canonical;
28use crate::Columnar;
29use crate::ExecutionCtx;
30use crate::aggregate_fn::Accumulator;
31use crate::aggregate_fn::AggregateArgs;
32use crate::aggregate_fn::AggregateDTypes;
33use crate::aggregate_fn::AggregateFnId;
34use crate::aggregate_fn::AggregateFnVTable;
35use crate::aggregate_fn::DynAccumulator;
36use crate::aggregate_fn::NumericalAggregateOpts;
37use crate::aggregate_fn::fns::fixed_size_bytes::is_fixed_size_bytes;
38use crate::dtype::DType;
39use crate::dtype::FieldNames;
40use crate::dtype::Nullability;
41use crate::dtype::PType;
42use crate::dtype::StructFields;
43use crate::dtype::half::f16;
44use crate::partial_ord::partial_max;
45use crate::partial_ord::partial_min;
46use crate::scalar::Scalar;
47use crate::stats::Precision;
48use crate::stats::Stat;
49use crate::stats::StatsProvider;
50use crate::stats::StatsProviderExt;
51
52static NAMES: LazyLock<FieldNames> = LazyLock::new(|| FieldNames::from(["min", "max"]));
53
54/// The minimum and maximum non-null values of an array, or `None` if there are no non-null values.
55///
56/// NaN handling for float inputs is controlled by [`NumericalAggregateOpts`]: with `skip_nans` (the
57/// default) NaN values are ignored and the cached `Stat::Min`/`Stat::Max` statistics are consulted
58/// and updated. With `skip_nans=false`, any NaN value in a float array poisons both extrema to
59/// NaN; an exact `Stat::NaNCount` statistic shortcircuits the NaN scan in either direction. The
60/// same applies to extension arrays stored as floats.
61///
62/// The result scalars have the non-nullable version of the array dtype.
63/// This will update the stats set of the array as a side effect.
64pub fn min_max(
65    array: &ArrayRef,
66    ctx: &mut ExecutionCtx,
67    options: NumericalAggregateOpts,
68) -> VortexResult<Option<MinMaxResult>> {
69    if !options.skip_nans && has_nan_values(array.dtype()) {
70        match array.statistics().get_as::<u64>(Stat::NaNCount) {
71            // NaN-free: identical to the NaN-skipping path below, including its stat caching.
72            Precision::Exact(0) => {}
73            // At least one NaN value poisons both extrema.
74            Precision::Exact(_) => return Ok(Some(nan_minmax_result(array.dtype())?)),
75            _ => {
76                if array.is_empty() || array.valid_count(ctx)? == 0 {
77                    return Ok(None);
78                }
79                // Compute with NaN-including options; the NaN-skipping `Stat::Min`/`Stat::Max`
80                // caches are neither read nor written.
81                let mut acc = Accumulator::try_new(MinMax, options, array.dtype().clone())?;
82                acc.accumulate(array, ctx)?;
83                return MinMaxResult::from_scalar(&acc.finish()?);
84            }
85        }
86    }
87
88    // NaN-skipping path. Also reached for NaN-free not-skipping float arrays and all non-float
89    // arrays, where `skip_nans` has no effect.
90
91    // Short-circuit using cached array statistics.
92    let cached_min = array.statistics().get(Stat::Min).as_exact();
93    let cached_max = array.statistics().get(Stat::Max).as_exact();
94    if let Some((min, max)) = cached_min.zip(cached_max) {
95        let non_nullable_dtype = array.dtype().as_nonnullable();
96        return Ok(Some(MinMaxResult {
97            min: min.cast(&non_nullable_dtype)?,
98            max: max.cast(&non_nullable_dtype)?,
99        }));
100    }
101
102    // Short-circuit for empty arrays or all-null arrays.
103    if array.is_empty() || array.valid_count(ctx)? == 0 {
104        return Ok(None);
105    }
106
107    // Short-circuit for dtypes this helper cannot currently compute.
108    if !minmax_compute_supported_dtype(array.dtype()) {
109        return Ok(None);
110    }
111
112    // Compute using Accumulator<MinMax>.
113    let mut acc = Accumulator::try_new(
114        MinMax,
115        NumericalAggregateOpts::default(),
116        array.dtype().clone(),
117    )?;
118    acc.accumulate(array, ctx)?;
119    let result_scalar = acc.finish()?;
120    let result = MinMaxResult::from_scalar(&result_scalar)?;
121
122    // Cache the computed min/max as statistics.
123    if let Some(r) = &result {
124        if let Some(min_value) = r.min.value() {
125            array
126                .statistics()
127                .set(Stat::Min, Precision::Exact(min_value.clone()));
128        }
129        if let Some(max_value) = r.max.value() {
130            array
131                .statistics()
132                .set(Stat::Max, Precision::Exact(max_value.clone()));
133        }
134    }
135
136    Ok(result)
137}
138
139/// Compute the min and max of an already-executed batch without touching any statistics.
140///
141/// Aggregates that delegate to [`MinMax`] use this on the columnar form of their input, so that
142/// results are only ever cached on the array the aggregate was requested for, never on a
143/// temporary canonical array.
144pub(crate) fn columnar_min_max(
145    batch: &Columnar,
146    options: NumericalAggregateOpts,
147    ctx: &mut ExecutionCtx,
148) -> VortexResult<Option<MinMaxResult>> {
149    if !minmax_compute_supported_dtype(batch.dtype()) {
150        return Ok(None);
151    }
152
153    let dtypes = AggregateDTypes::try_new(&MinMax, &options, batch.dtype().clone())?;
154    let args = dtypes.args(&options);
155    let mut partial = MinMax.empty_partial(args)?;
156    MinMax.accumulate(args, &mut partial, batch, ctx)?;
157    MinMaxResult::from_scalar(&MinMax.to_scalar(args, &partial)?)
158}
159
160/// A `{min: NaN, max: NaN}` result for a poisoned NaN-including min/max over `dtype`.
161fn nan_minmax_result(dtype: &DType) -> VortexResult<MinMaxResult> {
162    let nan = nan_scalar(dtype)?;
163
164    Ok(MinMaxResult {
165        min: nan.clone(),
166        max: nan,
167    })
168}
169
170/// Whether `dtype` can hold NaN values: floats, and extension types stored as floats.
171pub(crate) fn has_nan_values(dtype: &DType) -> bool {
172    match dtype {
173        DType::Extension(ext_dtype) => has_nan_values(ext_dtype.storage_dtype()),
174        _ => dtype.is_float(),
175    }
176}
177
178/// A non-nullable NaN scalar of `dtype`, a float or an extension type stored as a float.
179///
180/// Returns an error if an extension dtype rejects NaN.
181pub(crate) fn nan_scalar(dtype: &DType) -> VortexResult<Scalar> {
182    if let DType::Extension(ext_dtype) = dtype {
183        return Scalar::try_extension_ref(
184            ext_dtype.with_nullability(Nullability::NonNullable),
185            nan_scalar(ext_dtype.storage_dtype())?,
186        );
187    }
188
189    Ok(match dtype.as_ptype() {
190        PType::F16 => Scalar::primitive(f16::NAN, Nullability::NonNullable),
191        PType::F32 => Scalar::primitive(f32::NAN, Nullability::NonNullable),
192        PType::F64 => Scalar::primitive(f64::NAN, Nullability::NonNullable),
193        _ => vortex_panic!("NaN scalar requested for non-float dtype {dtype}"),
194    })
195}
196
197/// Whether a scalar holds a float NaN value, directly or as the storage of an extension scalar.
198pub(crate) fn scalar_is_nan(scalar: &Scalar) -> bool {
199    if let Some(ext) = scalar.as_extension_opt() {
200        return scalar_is_nan(&ext.to_storage_scalar());
201    }
202    if !scalar.dtype().is_float() {
203        return false;
204    }
205
206    scalar.as_primitive_opt().is_some_and(|p| p.is_nan())
207}
208
209/// The minimum and maximum non-null values of an array.
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct MinMaxResult {
212    pub min: Scalar,
213    pub max: Scalar,
214}
215
216impl MinMaxResult {
217    /// Extract a `MinMaxResult` from a struct scalar with `{min, max}` fields.
218    pub fn from_scalar(scalar: &Scalar) -> VortexResult<Option<Self>> {
219        if scalar.is_null() {
220            Ok(None)
221        } else {
222            let min = scalar
223                .as_struct()
224                .field_by_idx(0)
225                .vortex_expect("missing min field");
226            let max = scalar
227                .as_struct()
228                .field_by_idx(1)
229                .vortex_expect("missing max field");
230            Ok(Some(MinMaxResult { min, max }))
231        }
232    }
233}
234
235/// Compute the min and max of an array.
236///
237/// Returns a nullable struct scalar `{min: T, max: T}` where `T` is the non-nullable input dtype.
238/// The struct is null when the array is empty or all-null.
239///
240/// NaN handling for float inputs is controlled by [`NumericalAggregateOpts`]: with `skip_nans` (the
241/// default) NaN values are ignored, otherwise any NaN value poisons both extrema to NaN.
242#[derive(Clone, Debug)]
243pub struct MinMax;
244
245/// Partial accumulator state for min/max.
246pub struct MinMaxPartial {
247    min: Option<Scalar>,
248    max: Option<Scalar>,
249}
250
251impl MinMaxPartial {
252    /// Merge a local `MinMaxResult` into this partial state.
253    fn merge(
254        &mut self,
255        args: AggregateArgs<'_, NumericalAggregateOpts>,
256        local: Option<MinMaxResult>,
257    ) -> VortexResult<()> {
258        let Some(MinMaxResult { min, max }) = local else {
259            return Ok(());
260        };
261
262        // NaN scalars are incomparable under `partial_min`/`partial_max`, so they are handled
263        // explicitly: a NaN extremum poisons the partial state when NaNs participate, and is
264        // dropped when they are skipped.
265        if scalar_is_nan(&min) || scalar_is_nan(&max) || self.is_poisoned() {
266            if !args.options.skip_nans {
267                self.poison(args)?;
268            }
269            return Ok(());
270        }
271
272        self.min = Some(match self.min.take() {
273            Some(current) => partial_min(min, current).vortex_expect("incomparable min scalars"),
274            None => min,
275        });
276
277        self.max = Some(match self.max.take() {
278            Some(current) => partial_max(max, current).vortex_expect("incomparable max scalars"),
279            None => max,
280        });
281
282        Ok(())
283    }
284
285    /// Poison the partial state to `{min: NaN, max: NaN}`.
286    fn poison(&mut self, args: AggregateArgs<'_, NumericalAggregateOpts>) -> VortexResult<()> {
287        let nan = nan_scalar(args.dtype)?;
288        self.min = Some(nan.clone());
289        self.max = Some(nan);
290
291        Ok(())
292    }
293
294    /// Whether the partial state is poisoned to NaN.
295    fn is_poisoned(&self) -> bool {
296        self.min.as_ref().is_some_and(scalar_is_nan)
297    }
298}
299
300/// Creates the struct dtype `{min: T, max: T}` (nullable) used for min/max aggregate results.
301pub fn make_minmax_dtype(element_dtype: &DType) -> DType {
302    DType::Struct(
303        StructFields::new(
304            NAMES.clone(),
305            vec![
306                element_dtype.as_nonnullable(),
307                element_dtype.as_nonnullable(),
308            ],
309        ),
310        Nullability::Nullable,
311    )
312}
313
314fn minmax_supported_dtype(input_dtype: &DType) -> bool {
315    match input_dtype {
316        DType::Bool(_)
317        | DType::Primitive(..)
318        | DType::Decimal(..)
319        | DType::Utf8(..)
320        | DType::Binary(..)
321        | DType::Extension(..) => true,
322        DType::List(element_dtype, _) => minmax_supported_dtype(element_dtype),
323        DType::FixedSizeList(element_dtype, ..) => minmax_supported_dtype(element_dtype),
324        _ => false,
325    }
326}
327
328/// Returns whether [`min_max`] can currently compute extrema for this logical dtype.
329///
330/// This is intentionally narrower than [`minmax_supported_dtype`]. List and fixed-size-list
331/// extrema have a defined output dtype for aggregate expression lowering, but the accumulator does
332/// not yet implement lexicographic list comparison. Fixed-size lists of non-nullable `u8` are the
333/// exception: they compare by byte.
334fn minmax_compute_supported_dtype(input_dtype: &DType) -> bool {
335    matches!(
336        input_dtype,
337        DType::Bool(_)
338            | DType::Primitive(..)
339            | DType::Decimal(..)
340            | DType::Utf8(..)
341            | DType::Binary(..)
342            | DType::Extension(..)
343    ) || is_fixed_size_bytes(input_dtype)
344}
345
346impl AggregateFnVTable for MinMax {
347    type Options = NumericalAggregateOpts;
348    type Partial = MinMaxPartial;
349
350    fn id(&self) -> AggregateFnId {
351        static ID: CachedId = CachedId::new("vortex.min_max");
352        *ID
353    }
354
355    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
356        Ok(None)
357    }
358
359    fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option<DType> {
360        minmax_supported_dtype(input_dtype).then(|| make_minmax_dtype(input_dtype))
361    }
362
363    fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType> {
364        self.return_dtype(options, input_dtype)
365    }
366
367    fn empty_partial(
368        &self,
369        _args: AggregateArgs<'_, Self::Options>,
370    ) -> VortexResult<Self::Partial> {
371        Ok(MinMaxPartial {
372            min: None,
373            max: None,
374        })
375    }
376
377    fn partial_from_scalar(
378        &self,
379        args: AggregateArgs<'_, Self::Options>,
380        scalar: &Scalar,
381    ) -> VortexResult<Self::Partial> {
382        let mut partial = MinMaxPartial {
383            min: None,
384            max: None,
385        };
386        // `merge` normalizes the parsed extrema: nulls stay empty and NaNs poison or drop.
387        partial.merge(args, MinMaxResult::from_scalar(scalar)?)?;
388        Ok(partial)
389    }
390
391    fn merge_partials(
392        &self,
393        args: AggregateArgs<'_, Self::Options>,
394        mut first: Self::Partial,
395        second: Self::Partial,
396    ) -> VortexResult<Self::Partial> {
397        if let (Some(min), Some(max)) = (second.min, second.max) {
398            first.merge(args, Some(MinMaxResult { min, max }))?;
399        }
400        Ok(first)
401    }
402
403    fn to_scalar(
404        &self,
405        args: AggregateArgs<'_, Self::Options>,
406        partial: &Self::Partial,
407    ) -> VortexResult<Scalar> {
408        let dtype = args.partial_dtype.clone();
409        Ok(match (&partial.min, &partial.max) {
410            (Some(min), Some(max)) => Scalar::struct_(dtype, vec![min.clone(), max.clone()]),
411            _ => Scalar::null(dtype),
412        })
413    }
414
415    #[inline]
416    fn is_saturated(
417        &self,
418        _args: AggregateArgs<'_, Self::Options>,
419        partial: &Self::Partial,
420    ) -> bool {
421        // A poisoned NaN-including min/max is fully determined.
422        partial.is_poisoned()
423    }
424
425    fn try_accumulate(
426        &self,
427        args: AggregateArgs<'_, Self::Options>,
428        partial: &mut Self::Partial,
429        batch: &ArrayRef,
430        _ctx: &mut ExecutionCtx,
431    ) -> VortexResult<bool> {
432        // NaN-aware shortcircuits only apply to NaN-including float min/max; everything else
433        // takes the default dispatch path.
434        if args.options.skip_nans || !args.dtype.is_float() {
435            return Ok(false);
436        }
437        match batch.statistics().get_as::<u64>(Stat::NaNCount) {
438            Precision::Exact(0) => {
439                // NaN-free batch: the cached NaN-skipping extrema (if any) are valid.
440                let cached_min = batch.statistics().get(Stat::Min).as_exact();
441                let cached_max = batch.statistics().get(Stat::Max).as_exact();
442                if let Some((min, max)) = cached_min.zip(cached_max) {
443                    // Cached float stats carry the (possibly nullable) array dtype; `to_scalar`
444                    // builds a struct with non-nullable fields, so normalise here.
445                    let non_nullable_dtype = args.dtype.as_nonnullable();
446                    partial.merge(
447                        args,
448                        Some(MinMaxResult {
449                            min: min.cast(&non_nullable_dtype)?,
450                            max: max.cast(&non_nullable_dtype)?,
451                        }),
452                    )?;
453                    return Ok(true);
454                }
455                Ok(false)
456            }
457            Precision::Exact(_) => {
458                // At least one NaN value poisons both extrema without scanning the batch.
459                partial.poison(args)?;
460                Ok(true)
461            }
462            _ => Ok(false),
463        }
464    }
465
466    fn accumulate(
467        &self,
468        args: AggregateArgs<'_, Self::Options>,
469        partial: &mut Self::Partial,
470        batch: &Columnar,
471        ctx: &mut ExecutionCtx,
472    ) -> VortexResult<()> {
473        match batch {
474            Columnar::Constant(c) => {
475                if c.is_empty() {
476                    return Ok(());
477                }
478
479                let scalar = c.scalar();
480                if scalar.is_null() {
481                    return Ok(());
482                }
483                // NaN float constants are skipped or poison the extrema, per the options.
484                if scalar_is_nan(scalar) {
485                    if !args.options.skip_nans {
486                        partial.poison(args)?;
487                    }
488                    return Ok(());
489                }
490                let non_nullable_dtype = scalar.dtype().as_nonnullable();
491                let cast = scalar.cast(&non_nullable_dtype)?;
492                partial.merge(
493                    args,
494                    Some(MinMaxResult {
495                        min: cast.clone(),
496                        max: cast,
497                    }),
498                )
499            }
500            Columnar::Canonical(c) => match c {
501                Canonical::Primitive(p) => accumulate_primitive(args, partial, p, ctx),
502                Canonical::Bool(b) => accumulate_bool(args, partial, b, ctx),
503                Canonical::VarBinView(v) => accumulate_varbinview(args, partial, v, ctx),
504                Canonical::Decimal(d) => accumulate_decimal(args, partial, d, ctx),
505                Canonical::Extension(e) => accumulate_extension(args, partial, e, ctx),
506                Canonical::FixedSizeList(f) if is_fixed_size_bytes(f.dtype()) => {
507                    accumulate_fixed_size_bytes(args, partial, f, ctx)
508                }
509                Canonical::Null(_) => Ok(()),
510                Canonical::Union(_) => {
511                    vortex_bail!("TODO(connor)[Union]: implement min_max for Union arrays")
512                }
513                Canonical::Struct(_)
514                | Canonical::List(_)
515                | Canonical::Map(_)
516                | Canonical::FixedSizeList(_)
517                | Canonical::Variant(_) => {
518                    vortex_bail!("Unsupported canonical type for min_max: {}", batch.dtype())
519                }
520            },
521        }
522    }
523
524    fn finalize(
525        &self,
526        _args: AggregateArgs<'_, Self::Options>,
527        partials: ArrayRef,
528    ) -> VortexResult<ArrayRef> {
529        Ok(partials)
530    }
531
532    fn finalize_scalar(
533        &self,
534        args: AggregateArgs<'_, Self::Options>,
535        partial: &Self::Partial,
536    ) -> VortexResult<Scalar> {
537        self.to_scalar(args, partial)
538    }
539}
540
541#[cfg(test)]
542mod tests {
543    use std::sync::Arc;
544    use std::sync::LazyLock;
545
546    use rstest::rstest;
547    use vortex_buffer::BitBuffer;
548    use vortex_buffer::Buffer;
549    use vortex_buffer::buffer;
550    use vortex_error::VortexExpect;
551    use vortex_error::VortexResult;
552    use vortex_session::VortexSession;
553
554    use crate::ArrayRef;
555    use crate::EmptyMetadata;
556    use crate::IntoArray as _;
557    use crate::VortexSessionExecute;
558    use crate::aggregate_fn::Accumulator;
559    use crate::aggregate_fn::AggregateDTypes;
560    use crate::aggregate_fn::AggregateFnVTable;
561    use crate::aggregate_fn::DynAccumulator;
562    use crate::aggregate_fn::NumericalAggregateOpts;
563    use crate::aggregate_fn::fns::min_max::MinMax;
564    use crate::aggregate_fn::fns::min_max::MinMaxPartial;
565    use crate::aggregate_fn::fns::min_max::MinMaxResult;
566    use crate::aggregate_fn::fns::min_max::make_minmax_dtype;
567    use crate::aggregate_fn::fns::min_max::min_max;
568    use crate::arrays::BoolArray;
569    use crate::arrays::ChunkedArray;
570    use crate::arrays::ConstantArray;
571    use crate::arrays::DecimalArray;
572    use crate::arrays::ExtensionArray;
573    use crate::arrays::FixedSizeListArray;
574    use crate::arrays::ListArray;
575    use crate::arrays::NullArray;
576    use crate::arrays::PrimitiveArray;
577    use crate::arrays::TemporalArray;
578    use crate::arrays::VarBinArray;
579    use crate::dtype::BigCast;
580    use crate::dtype::DType;
581    use crate::dtype::DecimalDType;
582    use crate::dtype::Nullability;
583    use crate::dtype::PType;
584    use crate::dtype::extension::ExtDType;
585    use crate::dtype::extension::ExtId;
586    use crate::dtype::extension::ExtVTable;
587    use crate::extension::datetime::TimeUnit;
588    use crate::match_each_decimal_value_type;
589    use crate::scalar::DecimalValue;
590    use crate::scalar::Scalar;
591    use crate::scalar::ScalarValue;
592    use crate::stats::Precision;
593    use crate::stats::Stat;
594    use crate::stats::StatsProvider;
595    use crate::validity::Validity;
596
597    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
598
599    #[test]
600    fn test_prim_min_max() -> VortexResult<()> {
601        let p = PrimitiveArray::new(buffer![1, 2, 3], Validity::NonNullable).into_array();
602        let mut ctx = SESSION.create_execution_ctx();
603        assert_eq!(
604            min_max(&p, &mut ctx, NumericalAggregateOpts::default())?,
605            Some(MinMaxResult {
606                min: 1.into(),
607                max: 3.into()
608            })
609        );
610        Ok(())
611    }
612
613    #[test]
614    fn test_timestamp_min_max_beyond_jiff_range() -> VortexResult<()> {
615        // Midnight on 9999-12-31 UTC.
616        const END_OF_9999_US: i64 = 253_402_214_400_000_000;
617        let timestamps = TemporalArray::new_timestamp(
618            PrimitiveArray::from_iter([0i64, END_OF_9999_US]).into_array(),
619            TimeUnit::Microseconds,
620            None,
621        )
622        .into_array();
623        let mut ctx = SESSION.create_execution_ctx();
624        let MinMaxResult { min, max } =
625            min_max(&timestamps, &mut ctx, NumericalAggregateOpts::default())?
626                .vortex_expect("two non-null timestamps have min and max");
627
628        assert_eq!(min.as_extension().to_storage_scalar(), 0i64.into());
629        assert_eq!(
630            max.as_extension().to_storage_scalar(),
631            END_OF_9999_US.into()
632        );
633
634        Ok(())
635    }
636
637    #[test]
638    fn test_prim_min_max_multiple_null_runs() -> VortexResult<()> {
639        // Several disjoint valid runs separated by nulls exercise the per-run fold; the extrema
640        // (min 1, max 9) fall in different runs.
641        let p = PrimitiveArray::from_option_iter([
642            Some(5i32),
643            Some(3),
644            None,
645            None,
646            Some(9),
647            None,
648            Some(1),
649            Some(7),
650        ])
651        .into_array();
652        let mut ctx = SESSION.create_execution_ctx();
653        assert_eq!(
654            min_max(&p, &mut ctx, NumericalAggregateOpts::default())?,
655            Some(MinMaxResult {
656                min: 1.into(),
657                max: 9.into()
658            })
659        );
660        Ok(())
661    }
662
663    #[test]
664    fn test_bool_min_max() -> VortexResult<()> {
665        let mut ctx = SESSION.create_execution_ctx();
666
667        let all_true = BoolArray::new(
668            BitBuffer::from([true, true, true].as_slice()),
669            Validity::NonNullable,
670        )
671        .into_array();
672        assert_eq!(
673            min_max(&all_true, &mut ctx, NumericalAggregateOpts::default())?,
674            Some(MinMaxResult {
675                min: true.into(),
676                max: true.into()
677            })
678        );
679
680        let all_false = BoolArray::new(
681            BitBuffer::from([false, false, false].as_slice()),
682            Validity::NonNullable,
683        )
684        .into_array();
685        assert_eq!(
686            min_max(&all_false, &mut ctx, NumericalAggregateOpts::default())?,
687            Some(MinMaxResult {
688                min: false.into(),
689                max: false.into()
690            })
691        );
692
693        let mixed = BoolArray::new(
694            BitBuffer::from([false, true, false].as_slice()),
695            Validity::NonNullable,
696        )
697        .into_array();
698        assert_eq!(
699            min_max(&mixed, &mut ctx, NumericalAggregateOpts::default())?,
700            Some(MinMaxResult {
701                min: false.into(),
702                max: true.into()
703            })
704        );
705        Ok(())
706    }
707
708    #[test]
709    fn test_null_array() -> VortexResult<()> {
710        let p = NullArray::new(1).into_array();
711        let mut ctx = SESSION.create_execution_ctx();
712        assert_eq!(
713            min_max(&p, &mut ctx, NumericalAggregateOpts::default())?,
714            None
715        );
716        Ok(())
717    }
718
719    #[test]
720    fn test_prim_nan() -> VortexResult<()> {
721        let array = PrimitiveArray::new(
722            buffer![f32::NAN, -f32::NAN, -1.0, 1.0],
723            Validity::NonNullable,
724        );
725        let mut ctx = SESSION.create_execution_ctx();
726        let result = min_max(
727            &array.into_array(),
728            &mut ctx,
729            NumericalAggregateOpts::default(),
730        )?
731        .vortex_expect("should have result");
732        assert_eq!(f32::try_from(&result.min)?, -1.0);
733        assert_eq!(f32::try_from(&result.max)?, 1.0);
734        Ok(())
735    }
736
737    #[test]
738    fn test_prim_inf() -> VortexResult<()> {
739        let array = PrimitiveArray::new(
740            buffer![f32::INFINITY, f32::NEG_INFINITY, -1.0, 1.0],
741            Validity::NonNullable,
742        );
743        let mut ctx = SESSION.create_execution_ctx();
744        let result = min_max(
745            &array.into_array(),
746            &mut ctx,
747            NumericalAggregateOpts::default(),
748        )?
749        .vortex_expect("should have result");
750        assert_eq!(f32::try_from(&result.min)?, f32::NEG_INFINITY);
751        assert_eq!(f32::try_from(&result.max)?, f32::INFINITY);
752        Ok(())
753    }
754
755    #[test]
756    fn test_multi_batch() -> VortexResult<()> {
757        let mut ctx = SESSION.create_execution_ctx();
758        let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
759        let mut acc = Accumulator::try_new(MinMax, NumericalAggregateOpts::default(), dtype)?;
760
761        let batch1 = PrimitiveArray::new(buffer![10i32, 20, 5], Validity::NonNullable).into_array();
762        acc.accumulate(&batch1, &mut ctx)?;
763
764        let batch2 = PrimitiveArray::new(buffer![3i32, 25], Validity::NonNullable).into_array();
765        acc.accumulate(&batch2, &mut ctx)?;
766
767        let result = MinMaxResult::from_scalar(&acc.finish()?)?.vortex_expect("should have result");
768        assert_eq!(result.min, Scalar::from(3i32));
769        assert_eq!(result.max, Scalar::from(25i32));
770        Ok(())
771    }
772
773    #[test]
774    fn test_finish_resets_state() -> VortexResult<()> {
775        let mut ctx = SESSION.create_execution_ctx();
776        let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
777        let mut acc = Accumulator::try_new(MinMax, NumericalAggregateOpts::default(), dtype)?;
778
779        let batch1 = PrimitiveArray::new(buffer![10i32, 20], Validity::NonNullable).into_array();
780        acc.accumulate(&batch1, &mut ctx)?;
781        let result1 =
782            MinMaxResult::from_scalar(&acc.finish()?)?.vortex_expect("should have result");
783        assert_eq!(result1.min, Scalar::from(10i32));
784        assert_eq!(result1.max, Scalar::from(20i32));
785
786        let batch2 = PrimitiveArray::new(buffer![3i32, 6, 9], Validity::NonNullable).into_array();
787        acc.accumulate(&batch2, &mut ctx)?;
788        let result2 =
789            MinMaxResult::from_scalar(&acc.finish()?)?.vortex_expect("should have result");
790        assert_eq!(result2.min, Scalar::from(3i32));
791        assert_eq!(result2.max, Scalar::from(9i32));
792        Ok(())
793    }
794
795    #[test]
796    fn test_state_merge() -> VortexResult<()> {
797        let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
798        let options = NumericalAggregateOpts::default();
799        let owned = AggregateDTypes::try_new(&MinMax, &options, dtype)?;
800        let args = owned.args(&options);
801        let partial_of = |min: i32, max: i32| MinMaxPartial {
802            min: Some(Scalar::from(min)),
803            max: Some(Scalar::from(max)),
804        };
805
806        let state = MinMax.merge_partials(args, partial_of(5, 15), partial_of(2, 10))?;
807
808        let result = MinMaxResult::from_scalar(&MinMax.to_scalar(args, &state)?)?
809            .vortex_expect("should have result");
810        assert_eq!(result.min, Scalar::from(2i32));
811        assert_eq!(result.max, Scalar::from(15i32));
812        Ok(())
813    }
814
815    #[test]
816    fn test_constant_nan() -> VortexResult<()> {
817        let scalar = Scalar::primitive(f16::NAN, Nullability::NonNullable);
818        let array = ConstantArray::new(scalar, 2).into_array();
819        let mut ctx = SESSION.create_execution_ctx();
820        assert_eq!(
821            min_max(&array, &mut ctx, NumericalAggregateOpts::default())?,
822            None
823        );
824        Ok(())
825    }
826
827    const KEEP_NANS: NumericalAggregateOpts = NumericalAggregateOpts::include_nans();
828
829    fn assert_poisoned(result: Option<MinMaxResult>) -> VortexResult<()> {
830        let result = result.vortex_expect("should have result");
831        assert!(f64::try_from(&result.min.cast(&result.min.dtype().as_nullable())?)?.is_nan());
832        assert!(f64::try_from(&result.max.cast(&result.max.dtype().as_nullable())?)?.is_nan());
833        Ok(())
834    }
835
836    #[test]
837    fn test_prim_nan_not_skipping() -> VortexResult<()> {
838        let array = PrimitiveArray::new(
839            buffer![f32::NAN, -f32::NAN, -1.0, 1.0],
840            Validity::NonNullable,
841        )
842        .into_array();
843        let mut ctx = SESSION.create_execution_ctx();
844        assert_poisoned(min_max(&array, &mut ctx, KEEP_NANS)?)
845    }
846
847    #[test]
848    fn test_prim_no_nan_not_skipping() -> VortexResult<()> {
849        let array =
850            PrimitiveArray::new(buffer![3.0f32, -1.0, 1.0], Validity::NonNullable).into_array();
851        let mut ctx = SESSION.create_execution_ctx();
852        let result = min_max(&array, &mut ctx, KEEP_NANS)?.vortex_expect("should have result");
853        assert_eq!(f32::try_from(&result.min)?, -1.0);
854        assert_eq!(f32::try_from(&result.max)?, 3.0);
855        Ok(())
856    }
857
858    #[test]
859    fn test_constant_nan_not_skipping() -> VortexResult<()> {
860        let scalar = Scalar::primitive(f64::NAN, Nullability::NonNullable);
861        let array = ConstantArray::new(scalar, 2).into_array();
862        let mut ctx = SESSION.create_execution_ctx();
863        assert_poisoned(min_max(&array, &mut ctx, KEEP_NANS)?)
864    }
865
866    #[test]
867    fn test_not_skipping_with_exact_nan_count_stat() -> VortexResult<()> {
868        // The exact NaN count agrees with the batch; including NaNs must poison both extrema.
869        let array = PrimitiveArray::new(
870            buffer![1.0f64, 2.0, 3.0, f64::NAN, f64::NAN],
871            Validity::NonNullable,
872        )
873        .into_array();
874        array
875            .statistics()
876            .set(Stat::NaNCount, Precision::Exact(ScalarValue::from(2u64)));
877        let mut ctx = SESSION.create_execution_ctx();
878        assert_poisoned(min_max(&array, &mut ctx, KEEP_NANS)?)
879    }
880
881    #[test]
882    fn test_not_skipping_with_exact_stats_when_nan_free() -> VortexResult<()> {
883        // With an exact NaNCount of zero, the exact Min/Max stats are usable as-is.
884        let array =
885            PrimitiveArray::new(buffer![1.0f64, 2.0, 3.0], Validity::NonNullable).into_array();
886        array
887            .statistics()
888            .set(Stat::NaNCount, Precision::Exact(ScalarValue::from(0u64)));
889        array
890            .statistics()
891            .set(Stat::Min, Precision::Exact(ScalarValue::from(1.0f64)));
892        array
893            .statistics()
894            .set(Stat::Max, Precision::Exact(ScalarValue::from(3.0f64)));
895        let mut ctx = SESSION.create_execution_ctx();
896        let result = min_max(&array, &mut ctx, KEEP_NANS)?.vortex_expect("should have result");
897        assert_eq!(f64::try_from(&result.min)?, 1.0);
898        assert_eq!(f64::try_from(&result.max)?, 3.0);
899        Ok(())
900    }
901
902    #[test]
903    fn test_accumulator_nan_including_nullable_cached_stats() -> VortexResult<()> {
904        // A nullable float array's cached Min/Max stats are reconstructed as nullable scalars.
905        // The NaN-including accumulator shortcircuit must normalise them to the non-nullable
906        // struct field dtype before building the result scalar.
907        let mut ctx = SESSION.create_execution_ctx();
908        let array =
909            PrimitiveArray::from_option_iter([Some(1.0f64), Some(2.0), Some(3.0)]).into_array();
910        array
911            .statistics()
912            .set(Stat::NaNCount, Precision::Exact(ScalarValue::from(0u64)));
913        array
914            .statistics()
915            .set(Stat::Min, Precision::Exact(ScalarValue::from(1.0f64)));
916        array
917            .statistics()
918            .set(Stat::Max, Precision::Exact(ScalarValue::from(3.0f64)));
919
920        let mut acc = Accumulator::try_new(MinMax, KEEP_NANS, array.dtype().clone())?;
921        acc.accumulate(&array, &mut ctx)?;
922        let result = MinMaxResult::from_scalar(&acc.finish()?)?.vortex_expect("should have result");
923        assert_eq!(f64::try_from(&result.min)?, 1.0);
924        assert_eq!(f64::try_from(&result.max)?, 3.0);
925        Ok(())
926    }
927
928    #[test]
929    fn test_multi_batch_nan_poisoning() -> VortexResult<()> {
930        let mut ctx = SESSION.create_execution_ctx();
931        let dtype = DType::Primitive(PType::F64, Nullability::NonNullable);
932        let mut acc = Accumulator::try_new(MinMax, KEEP_NANS, dtype)?;
933
934        let batch1 = PrimitiveArray::new(buffer![1.0f64, 2.0], Validity::NonNullable).into_array();
935        acc.accumulate(&batch1, &mut ctx)?;
936        assert!(!acc.is_saturated());
937
938        let batch2 = PrimitiveArray::new(buffer![f64::NAN], Validity::NonNullable).into_array();
939        acc.accumulate(&batch2, &mut ctx)?;
940        assert!(acc.is_saturated());
941
942        assert_poisoned(MinMaxResult::from_scalar(&acc.finish()?)?)
943    }
944
945    #[test]
946    fn test_chunked() -> VortexResult<()> {
947        let chunk1 = PrimitiveArray::from_option_iter([Some(5i32), None, Some(1)]);
948        let chunk2 = PrimitiveArray::from_option_iter([Some(10i32), Some(3), None]);
949        let dtype = chunk1.dtype().clone();
950        let chunked = ChunkedArray::try_new(vec![chunk1.into_array(), chunk2.into_array()], dtype)?;
951        let mut ctx = SESSION.create_execution_ctx();
952        let result = min_max(
953            &chunked.into_array(),
954            &mut ctx,
955            NumericalAggregateOpts::default(),
956        )?
957        .vortex_expect("should have result");
958        assert_eq!(result.min, Scalar::from(1i32));
959        assert_eq!(result.max, Scalar::from(10i32));
960        Ok(())
961    }
962
963    #[test]
964    fn test_all_null() -> VortexResult<()> {
965        let p = PrimitiveArray::from_option_iter::<i32, _>([None, None, None]);
966        let mut ctx = SESSION.create_execution_ctx();
967        assert_eq!(
968            min_max(&p.into_array(), &mut ctx, NumericalAggregateOpts::default())?,
969            None
970        );
971        Ok(())
972    }
973
974    #[test]
975    fn test_varbin() -> VortexResult<()> {
976        let array = VarBinArray::from_iter(
977            vec![
978                Some("hello world"),
979                None,
980                Some("hello world this is a long string"),
981                None,
982            ],
983            DType::Utf8(Nullability::Nullable),
984        );
985        let mut ctx = SESSION.create_execution_ctx();
986        let result = min_max(
987            &array.into_array(),
988            &mut ctx,
989            NumericalAggregateOpts::default(),
990        )?
991        .vortex_expect("should have result");
992        assert_eq!(
993            result.min,
994            Scalar::utf8("hello world", Nullability::NonNullable)
995        );
996        assert_eq!(
997            result.max,
998            Scalar::utf8(
999                "hello world this is a long string",
1000                Nullability::NonNullable
1001            )
1002        );
1003        Ok(())
1004    }
1005
1006    #[test]
1007    fn test_decimal() -> VortexResult<()> {
1008        let mut ctx = SESSION.create_execution_ctx();
1009        let decimal = DecimalArray::new(
1010            buffer![100i16, 2000, 200],
1011            DecimalDType::new(4, 2),
1012            Validity::from_iter([true, false, true]),
1013            &mut ctx,
1014        );
1015        let result = min_max(
1016            &decimal.into_array(),
1017            &mut ctx,
1018            NumericalAggregateOpts::default(),
1019        )?
1020        .vortex_expect("should have result");
1021
1022        let non_nullable_dtype = DType::Decimal(DecimalDType::new(4, 2), Nullability::NonNullable);
1023        let expected_min = Scalar::try_new(
1024            non_nullable_dtype.clone(),
1025            Some(ScalarValue::from(DecimalValue::from(100i32))),
1026        )?;
1027        let expected_max = Scalar::try_new(
1028            non_nullable_dtype,
1029            Some(ScalarValue::from(DecimalValue::from(200i32))),
1030        )?;
1031        assert_eq!(result.min, expected_min);
1032        assert_eq!(result.max, expected_max);
1033        Ok(())
1034    }
1035
1036    #[rstest]
1037    #[case::non_nullable(vec![Some(-3), Some(7), Some(5)], false, Some((-3, 7)))]
1038    #[case::all_valid(vec![Some(-3), Some(7), Some(5)], true, Some((-3, 7)))]
1039    #[case::null_extremes(vec![None, Some(-3), Some(7), None], true, Some((-3, 7)))]
1040    #[case::single_valid(vec![None, Some(5), None], true, Some((5, 5)))]
1041    #[case::single_row(vec![Some(5)], false, Some((5, 5)))]
1042    #[case::equal_values(vec![Some(5), Some(5)], true, Some((5, 5)))]
1043    #[case::all_null(vec![None, None], true, None)]
1044    #[case::empty_non_nullable(vec![], false, None)]
1045    #[case::empty_nullable(vec![], true, None)]
1046    fn test_decimal_valid_range(
1047        #[case] values: Vec<Option<i8>>,
1048        #[case] nullable: bool,
1049        #[case] expected: Option<(i8, i8)>,
1050        #[values(2, 4, 9, 18, 38, 76)] precision: u8,
1051    ) -> VortexResult<()> {
1052        let mut ctx = SESSION.create_execution_ctx();
1053        let decimal_dtype = DecimalDType::new(precision, 2);
1054        let validity = if nullable {
1055            Validity::from_iter(values.iter().map(Option::is_some))
1056        } else {
1057            Validity::NonNullable
1058        };
1059        let expected = expected.map(|(min, max)| MinMaxResult {
1060            min: Scalar::decimal(min.into(), decimal_dtype, Nullability::NonNullable),
1061            max: Scalar::decimal(max.into(), decimal_dtype, Nullability::NonNullable),
1062        });
1063
1064        match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |T| {
1065            let buffer: Buffer<T> = values
1066                .iter()
1067                .enumerate()
1068                .map(|(row, value)| match value {
1069                    Some(value) => <T as BigCast>::from(*value)
1070                        .vortex_expect("i8 fixture values fit every decimal storage type"),
1071                    None if row % 2 == 0 => T::MIN,
1072                    None => T::MAX,
1073                })
1074                .collect();
1075            let array = DecimalArray::new(buffer, decimal_dtype, validity, &mut ctx).into_array();
1076            let actual = min_max(&array, &mut ctx, NumericalAggregateOpts::default())?;
1077            assert_eq!(actual, expected);
1078            if let Some(actual) = actual {
1079                let dtype = DType::Decimal(decimal_dtype, Nullability::NonNullable);
1080                assert_eq!(actual.min.dtype(), &dtype);
1081                assert_eq!(actual.max.dtype(), &dtype);
1082            }
1083
1084            Ok(())
1085        })
1086    }
1087
1088    #[test]
1089    fn test_decimal_value_outside_precision_in_null_slot() -> VortexResult<()> {
1090        let mut ctx = SESSION.create_execution_ctx();
1091        // The out-of-range value sits in a null slot, so it must be ignored.
1092        let decimal = DecimalArray::new(
1093            buffer![5i8, 100i8],
1094            DecimalDType::new(2, 0),
1095            Validity::from_iter([true, false]),
1096            &mut ctx,
1097        );
1098        let result = min_max(
1099            &decimal.into_array(),
1100            &mut ctx,
1101            NumericalAggregateOpts::default(),
1102        )?
1103        .vortex_expect("should have result");
1104
1105        let expected = Scalar::decimal(
1106            DecimalValue::I8(5),
1107            DecimalDType::new(2, 0),
1108            Nullability::NonNullable,
1109        );
1110        assert_eq!(result.min, expected);
1111        assert_eq!(result.max, expected);
1112        Ok(())
1113    }
1114
1115    #[test]
1116    fn list_and_fixed_size_list_return_dtype() {
1117        let element_dtype = DType::Primitive(PType::I32, Nullability::Nullable);
1118        let list_dtype = DType::List(Arc::new(element_dtype.clone()), Nullability::Nullable);
1119        let fixed_size_list_dtype =
1120            DType::FixedSizeList(Arc::new(element_dtype), 1, Nullability::Nullable);
1121
1122        assert_eq!(
1123            MinMax.return_dtype(&NumericalAggregateOpts::default(), &list_dtype),
1124            Some(make_minmax_dtype(&list_dtype))
1125        );
1126        assert_eq!(
1127            MinMax.return_dtype(&NumericalAggregateOpts::default(), &fixed_size_list_dtype),
1128            Some(make_minmax_dtype(&fixed_size_list_dtype))
1129        );
1130    }
1131
1132    #[test]
1133    fn list_and_fixed_size_list_min_max_returns_none() -> VortexResult<()> {
1134        let mut ctx = SESSION.create_execution_ctx();
1135
1136        let list_array = ListArray::try_new(
1137            buffer![1i32, 2, 3].into_array(),
1138            buffer![0u32, 2, 3].into_array(),
1139            Validity::NonNullable,
1140            &mut ctx,
1141        )?
1142        .into_array();
1143        assert_eq!(
1144            min_max(&list_array, &mut ctx, NumericalAggregateOpts::default())?,
1145            None
1146        );
1147
1148        let fixed_size_list_array = FixedSizeListArray::try_new(
1149            buffer![1i32, 2, 3, 4].into_array(),
1150            2,
1151            Validity::NonNullable,
1152            2,
1153        )?
1154        .into_array();
1155        assert_eq!(
1156            min_max(
1157                &fixed_size_list_array,
1158                &mut ctx,
1159                NumericalAggregateOpts::default()
1160            )?,
1161            None
1162        );
1163
1164        Ok(())
1165    }
1166
1167    use crate::dtype::half::f16;
1168
1169    #[test]
1170    fn test_bool_with_nulls() -> VortexResult<()> {
1171        let mut ctx = SESSION.create_execution_ctx();
1172
1173        let result = min_max(
1174            &BoolArray::from_iter(vec![Some(true), Some(true), None, None]).into_array(),
1175            &mut ctx,
1176            NumericalAggregateOpts::default(),
1177        )?;
1178        assert_eq!(
1179            result,
1180            Some(MinMaxResult {
1181                min: Scalar::bool(true, Nullability::NonNullable),
1182                max: Scalar::bool(true, Nullability::NonNullable),
1183            })
1184        );
1185
1186        let result = min_max(
1187            &BoolArray::from_iter(vec![None, Some(true), Some(true)]).into_array(),
1188            &mut ctx,
1189            NumericalAggregateOpts::default(),
1190        )?;
1191        assert_eq!(
1192            result,
1193            Some(MinMaxResult {
1194                min: Scalar::bool(true, Nullability::NonNullable),
1195                max: Scalar::bool(true, Nullability::NonNullable),
1196            })
1197        );
1198
1199        let result = min_max(
1200            &BoolArray::from_iter(vec![None, Some(true), Some(true), None]).into_array(),
1201            &mut ctx,
1202            NumericalAggregateOpts::default(),
1203        )?;
1204        assert_eq!(
1205            result,
1206            Some(MinMaxResult {
1207                min: Scalar::bool(true, Nullability::NonNullable),
1208                max: Scalar::bool(true, Nullability::NonNullable),
1209            })
1210        );
1211
1212        let result = min_max(
1213            &BoolArray::from_iter(vec![Some(false), Some(false), None, None]).into_array(),
1214            &mut ctx,
1215            NumericalAggregateOpts::default(),
1216        )?;
1217        assert_eq!(
1218            result,
1219            Some(MinMaxResult {
1220                min: Scalar::bool(false, Nullability::NonNullable),
1221                max: Scalar::bool(false, Nullability::NonNullable),
1222            })
1223        );
1224        Ok(())
1225    }
1226
1227    /// Regression test for <https://github.com/vortex-data/vortex/issues/7074>.
1228    ///
1229    /// A chunked all-true bool array with an empty first chunk returned min=false because
1230    /// `accumulate_bool` on the empty chunk incorrectly merged min=false,max=false into the
1231    /// partial state.
1232    #[test]
1233    fn test_bool_chunked_with_empty_chunk() -> VortexResult<()> {
1234        let mut ctx = SESSION.create_execution_ctx();
1235
1236        let empty = BoolArray::new(BitBuffer::from([].as_slice()), Validity::NonNullable);
1237        let chunk1 = BoolArray::new(
1238            BitBuffer::from([true, true].as_slice()),
1239            Validity::NonNullable,
1240        );
1241        let chunk2 = BoolArray::new(
1242            BitBuffer::from([true, true, true].as_slice()),
1243            Validity::NonNullable,
1244        );
1245        let chunked = ChunkedArray::try_new(
1246            vec![empty.into_array(), chunk1.into_array(), chunk2.into_array()],
1247            DType::Bool(Nullability::NonNullable),
1248        )?;
1249
1250        let result = min_max(
1251            &chunked.into_array(),
1252            &mut ctx,
1253            NumericalAggregateOpts::default(),
1254        )?;
1255        assert_eq!(
1256            result,
1257            Some(MinMaxResult {
1258                min: Scalar::bool(true, Nullability::NonNullable),
1259                max: Scalar::bool(true, Nullability::NonNullable),
1260            })
1261        );
1262        Ok(())
1263    }
1264
1265    #[test]
1266    fn empty_constant_leaves_partial_empty() -> VortexResult<()> {
1267        let mut ctx = SESSION.create_execution_ctx();
1268        let array = ConstantArray::new(Scalar::from(99i32), 0).into_array();
1269        let options = NumericalAggregateOpts::default();
1270        let mut acc = Accumulator::try_new(MinMax, options, array.dtype().clone())?;
1271
1272        acc.accumulate(&array, &mut ctx)?;
1273
1274        assert!(acc.partial_scalar()?.is_null());
1275        Ok(())
1276    }
1277
1278    /// Regression test for <https://github.com/vortex-data/vortex/issues/8145>.
1279    ///
1280    /// A chunked array whose first chunk is an *empty* constant array — as produced by
1281    /// `fill_null` on an empty all-null chunk — returned `max = u32::MAX` because
1282    /// `ChunkedArrayAggregate` accumulated the empty chunk, folding its fill scalar into the
1283    /// running min/max. Empty chunks are now skipped during chunked aggregation.
1284    #[test]
1285    fn test_chunked_with_empty_constant_chunk() -> VortexResult<()> {
1286        let mut ctx = SESSION.create_execution_ctx();
1287
1288        let empty = ConstantArray::new(Scalar::primitive(u32::MAX, Nullability::NonNullable), 0)
1289            .into_array();
1290        let chunk1 = PrimitiveArray::new(buffer![7631471u32], Validity::NonNullable).into_array();
1291        let chunk2 = PrimitiveArray::new(buffer![0u32], Validity::NonNullable).into_array();
1292        let chunked = ChunkedArray::try_new(
1293            vec![empty, chunk1, chunk2],
1294            DType::Primitive(PType::U32, Nullability::NonNullable),
1295        )?;
1296
1297        assert_eq!(
1298            min_max(
1299                &chunked.into_array(),
1300                &mut ctx,
1301                NumericalAggregateOpts::default()
1302            )?,
1303            Some(MinMaxResult {
1304                min: Scalar::primitive(0u32, Nullability::NonNullable),
1305                max: Scalar::primitive(7631471u32, Nullability::NonNullable),
1306            })
1307        );
1308        Ok(())
1309    }
1310
1311    #[test]
1312    fn test_varbin_all_nulls() -> VortexResult<()> {
1313        let array = VarBinArray::from_iter(
1314            vec![Option::<&str>::None, None, None],
1315            DType::Utf8(Nullability::Nullable),
1316        );
1317        let mut ctx = SESSION.create_execution_ctx();
1318        assert_eq!(
1319            min_max(
1320                &array.into_array(),
1321                &mut ctx,
1322                NumericalAggregateOpts::default()
1323            )?,
1324            None
1325        );
1326        Ok(())
1327    }
1328
1329    #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
1330    struct F64Ext;
1331
1332    impl ExtVTable for F64Ext {
1333        type Metadata = EmptyMetadata;
1334        type StoredMetadata = Self::Metadata;
1335        type NativeValue<'a> = &'a ScalarValue;
1336
1337        #[expect(clippy::disallowed_methods, reason = "test-only id")]
1338        fn id(&self) -> ExtId {
1339            ExtId::new("test.f64_ext")
1340        }
1341
1342        fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
1343            Ok(vec![])
1344        }
1345
1346        fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult<Self::StoredMetadata> {
1347            Ok(EmptyMetadata)
1348        }
1349
1350        fn metadata_from_storage(
1351            &self,
1352            stored_metadata: Self::StoredMetadata,
1353            _storage_dtype: &DType,
1354        ) -> VortexResult<Self::Metadata> {
1355            Ok(stored_metadata)
1356        }
1357
1358        fn storage_dtype(_metadata: &Self::Metadata) -> DType {
1359            DType::Primitive(PType::F64, Nullability::NonNullable)
1360        }
1361
1362        fn unpack_native<'a>(
1363            _extension_dtype: &'a ExtDType<Self>,
1364            storage_value: &'a ScalarValue,
1365        ) -> VortexResult<Self::NativeValue<'a>> {
1366            Ok(storage_value)
1367        }
1368    }
1369
1370    fn f64_ext_array(values: Buffer<f64>) -> VortexResult<ArrayRef> {
1371        let ext_dtype =
1372            ExtDType::<F64Ext>::try_new(EmptyMetadata, Nullability::NonNullable)?.erased();
1373        Ok(ExtensionArray::new(ext_dtype, values.into_array()).into_array())
1374    }
1375
1376    fn ext_storage_f64(scalar: &Scalar) -> VortexResult<f64> {
1377        f64::try_from(&scalar.as_extension().to_storage_scalar())
1378    }
1379
1380    #[test]
1381    fn test_extension_nan_not_skipping() -> VortexResult<()> {
1382        let array = f64_ext_array(buffer![1.0f64, f64::NAN, 3.0])?;
1383        let mut ctx = SESSION.create_execution_ctx();
1384        let result = min_max(&array, &mut ctx, KEEP_NANS)?.vortex_expect("should have result");
1385        assert_eq!(result.min.dtype(), &array.dtype().as_nonnullable());
1386        assert!(ext_storage_f64(&result.min)?.is_nan());
1387        assert!(ext_storage_f64(&result.max)?.is_nan());
1388        // A NaN-including result is not a NaN-skipping statistic.
1389        assert!(array.statistics().get(Stat::Min).as_exact().is_none());
1390        Ok(())
1391    }
1392
1393    #[test]
1394    fn test_extension_nan_skipping() -> VortexResult<()> {
1395        let array = f64_ext_array(buffer![1.0f64, f64::NAN, 3.0])?;
1396        let mut ctx = SESSION.create_execution_ctx();
1397        let result = min_max(&array, &mut ctx, NumericalAggregateOpts::default())?
1398            .vortex_expect("should have result");
1399        assert_eq!(ext_storage_f64(&result.min)?, 1.0);
1400        assert_eq!(ext_storage_f64(&result.max)?, 3.0);
1401        Ok(())
1402    }
1403
1404    #[test]
1405    fn test_extension_nan_free_not_skipping() -> VortexResult<()> {
1406        let array = f64_ext_array(buffer![2.0f64, 1.0, 3.0])?;
1407        let mut ctx = SESSION.create_execution_ctx();
1408        let result = min_max(&array, &mut ctx, KEEP_NANS)?.vortex_expect("should have result");
1409        assert_eq!(ext_storage_f64(&result.min)?, 1.0);
1410        assert_eq!(ext_storage_f64(&result.max)?, 3.0);
1411        Ok(())
1412    }
1413}