Skip to main content

vortex_expr/stats/
expr.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Expression constructors for statistics backed by aggregate functions.
5
6use vortex_array::aggregate_fn::AggregateFnRef;
7use vortex_array::aggregate_fn::AggregateFnVTableExt;
8use vortex_array::aggregate_fn::EmptyOptions;
9use vortex_array::aggregate_fn::NumericalAggregateOpts;
10use vortex_array::aggregate_fn::fns::all_nan::AllNan;
11use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan;
12use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull;
13use vortex_array::aggregate_fn::fns::all_null::AllNull;
14use vortex_array::aggregate_fn::fns::min_max::MinMax;
15use vortex_array::aggregate_fn::fns::nan_count::NanCount;
16use vortex_array::aggregate_fn::fns::null_count::NullCount;
17use vortex_array::aggregate_fn::fns::sum::Sum;
18use vortex_error::VortexExpect;
19
20use crate::BoundExpression;
21use crate::Expression;
22use crate::ScalarFnExprExt;
23pub use crate::stats::stat_fn::StatFn;
24pub use crate::stats::stat_fn::StatOptions;
25
26/// Creates an expression that reads a stored aggregate statistic for `expr`.
27///
28/// If the statistic is not available in the current stats scope, evaluating the expression returns
29/// a nullable all-null array with the aggregate return type.
30pub fn stat(expr: Expression, aggregate_fn: AggregateFnRef) -> Expression {
31    StatFn.new_expr(StatOptions::new(aggregate_fn), [expr])
32}
33
34fn bound_stat(expr: BoundExpression, aggregate_fn: AggregateFnRef) -> BoundExpression {
35    StatFn
36        .try_new_bound_expr(StatOptions::new(aggregate_fn), [expr])
37        .vortex_expect("stat expressions must use an aggregate supported by the child dtype")
38}
39
40/// Creates `stat(expr, min_max)`, returning a nullable `{ min, max }` struct statistic.
41pub fn min_max(expr: Expression) -> Expression {
42    // Statistics follow NaN-skipping semantics; request it explicitly rather than via the default.
43    stat(expr, MinMax.bind(NumericalAggregateOpts::skip_nans()))
44}
45
46fn bound_min_max(expr: BoundExpression) -> BoundExpression {
47    bound_stat(expr, MinMax.bind(NumericalAggregateOpts::skip_nans()))
48}
49
50/// Creates `stat(expr, sum)`, returning a nullable sum statistic.
51pub fn sum(expr: Expression) -> Expression {
52    // Statistics follow NaN-skipping semantics; request it explicitly rather than via the default.
53    stat(expr, Sum.bind(NumericalAggregateOpts::skip_nans()))
54}
55
56fn bound_sum(expr: BoundExpression) -> BoundExpression {
57    bound_stat(expr, Sum.bind(NumericalAggregateOpts::skip_nans()))
58}
59
60/// Creates `stat(expr, null_count)`, returning a nullable null-count statistic.
61pub fn null_count(expr: Expression) -> Expression {
62    stat(expr, NullCount.bind(EmptyOptions))
63}
64
65fn bound_null_count(expr: BoundExpression) -> BoundExpression {
66    bound_stat(expr, NullCount.bind(EmptyOptions))
67}
68
69/// Creates `stat(expr, all_null)`, returning a nullable all-null statistic.
70pub fn all_null(expr: Expression) -> Expression {
71    stat(expr, AllNull.bind(EmptyOptions))
72}
73
74fn bound_all_null(expr: BoundExpression) -> BoundExpression {
75    bound_stat(expr, AllNull.bind(EmptyOptions))
76}
77
78/// Creates `stat(expr, all_nan)`, returning a nullable all-NaN statistic.
79pub fn all_nan(expr: Expression) -> Expression {
80    stat(expr, AllNan.bind(EmptyOptions))
81}
82
83fn bound_all_nan(expr: BoundExpression) -> BoundExpression {
84    bound_stat(expr, AllNan.bind(EmptyOptions))
85}
86
87/// Creates `stat(expr, all_non_null)`, returning a nullable all-non-null statistic.
88pub fn all_non_null(expr: Expression) -> Expression {
89    stat(expr, AllNonNull.bind(EmptyOptions))
90}
91
92fn bound_all_non_null(expr: BoundExpression) -> BoundExpression {
93    bound_stat(expr, AllNonNull.bind(EmptyOptions))
94}
95
96/// Creates `stat(expr, all_non_nan)`, returning a nullable all-non-NaN statistic.
97pub fn all_non_nan(expr: Expression) -> Expression {
98    stat(expr, AllNonNan.bind(EmptyOptions))
99}
100
101fn bound_all_non_nan(expr: BoundExpression) -> BoundExpression {
102    bound_stat(expr, AllNonNan.bind(EmptyOptions))
103}
104
105/// Creates `stat(expr, nan_count)`, returning a nullable NaN-count statistic.
106pub fn nan_count(expr: Expression) -> Expression {
107    stat(expr, NanCount.bind(EmptyOptions))
108}
109
110fn bound_nan_count(expr: BoundExpression) -> BoundExpression {
111    bound_stat(expr, NanCount.bind(EmptyOptions))
112}
113
114/// Constructors for statistic expressions whose input has already been bound.
115///
116/// These mirror the constructors in [`vortex_array::stats`] and panic when the aggregate does not support
117/// the input dtype.
118pub mod bound {
119    use vortex_array::aggregate_fn::AggregateFnRef;
120
121    use crate::BoundExpression;
122
123    /// Creates a bound expression that reads a stored aggregate statistic.
124    pub fn stat(expr: BoundExpression, aggregate_fn: AggregateFnRef) -> BoundExpression {
125        super::bound_stat(expr, aggregate_fn)
126    }
127
128    /// Creates a bound nullable `{ min, max }` statistic expression.
129    pub fn min_max(expr: BoundExpression) -> BoundExpression {
130        super::bound_min_max(expr)
131    }
132
133    /// Creates a bound nullable sum statistic expression.
134    pub fn sum(expr: BoundExpression) -> BoundExpression {
135        super::bound_sum(expr)
136    }
137
138    /// Creates a bound nullable null-count statistic expression.
139    pub fn null_count(expr: BoundExpression) -> BoundExpression {
140        super::bound_null_count(expr)
141    }
142
143    /// Creates a bound nullable all-null statistic expression.
144    pub fn all_null(expr: BoundExpression) -> BoundExpression {
145        super::bound_all_null(expr)
146    }
147
148    /// Creates a bound nullable all-NaN statistic expression.
149    pub fn all_nan(expr: BoundExpression) -> BoundExpression {
150        super::bound_all_nan(expr)
151    }
152
153    /// Creates a bound nullable all-non-null statistic expression.
154    pub fn all_non_null(expr: BoundExpression) -> BoundExpression {
155        super::bound_all_non_null(expr)
156    }
157
158    /// Creates a bound nullable all-non-NaN statistic expression.
159    pub fn all_non_nan(expr: BoundExpression) -> BoundExpression {
160        super::bound_all_non_nan(expr)
161    }
162
163    /// Creates a bound nullable NaN-count statistic expression.
164    pub fn nan_count(expr: BoundExpression) -> BoundExpression {
165        super::bound_nan_count(expr)
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use std::sync::LazyLock;
172
173    use vortex_array::Canonical;
174    use vortex_array::IntoArray;
175    use vortex_array::VortexSessionExecute;
176    use vortex_array::arrays::Chunked;
177    use vortex_array::arrays::ChunkedArray;
178    use vortex_array::arrays::ConstantArray;
179    use vortex_array::arrays::PrimitiveArray;
180    use vortex_array::arrays::chunked::ChunkedArrayExt;
181    use vortex_array::assert_arrays_eq;
182    use vortex_array::dtype::DType;
183    use vortex_array::dtype::Nullability;
184    use vortex_array::dtype::PType;
185    use vortex_array::optimizer::ArrayOptimizer;
186    use vortex_array::scalar::Scalar;
187    use vortex_array::scalar::ScalarValue;
188    use vortex_array::stats::Precision;
189    use vortex_array::stats::Stat;
190    use vortex_array::validity::Validity;
191    use vortex_buffer::buffer;
192    use vortex_error::VortexExpect;
193    use vortex_error::VortexResult;
194    use vortex_session::VortexSession;
195
196    use super::all_nan;
197    use super::all_non_nan;
198    use super::all_non_null;
199    use super::all_null;
200    use super::bound as bound_stats;
201    use super::null_count;
202    use super::stat;
203    use super::sum;
204    use crate::ArrayExprExt;
205    use crate::bound as bound_expr;
206    use crate::root;
207
208    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
209
210    #[test]
211    fn bound_stats_constructor_preserves_child_and_dtype() -> VortexResult<()> {
212        let input_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
213        let root = bound_expr::root(input_dtype.clone());
214        let bound = bound_stats::sum(root.clone());
215
216        assert_eq!(bound.children(), &[root]);
217        assert_eq!(
218            bound.dtype(),
219            &DType::Primitive(PType::I64, Nullability::Nullable)
220        );
221        assert_eq!(bound, sum(crate::root()).bind(&input_dtype)?);
222        Ok(())
223    }
224
225    #[test]
226    fn stat_expr_reads_cached_sum() -> VortexResult<()> {
227        let array = buffer![1i32, 2, 3].into_array();
228        let sum_scalar = Scalar::primitive(6i64, Nullability::Nullable);
229        array.statistics().set(
230            Stat::Sum,
231            Precision::exact(sum_scalar.into_value().vortex_expect("non-null sum")),
232        );
233
234        let result = array.apply(&sum(root()))?;
235
236        let expected =
237            ConstantArray::new(Scalar::primitive(6i64, Nullability::Nullable), 3).into_array();
238        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
239
240        Ok(())
241    }
242
243    #[test]
244    fn stat_expr_returns_null_when_sum_is_missing() -> VortexResult<()> {
245        let array = buffer![1i32, 2, 3].into_array();
246
247        let result = array.apply(&sum(root()))?;
248
249        let expected = ConstantArray::new(
250            Scalar::null(DType::Primitive(PType::I64, Nullability::Nullable)),
251            3,
252        )
253        .into_array();
254        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
255
256        Ok(())
257    }
258
259    #[test]
260    fn stat_expr_reads_cached_sum_per_chunk() -> VortexResult<()> {
261        let chunk0 = buffer![1i32, 2].into_array();
262        let sum_scalar = Scalar::primitive(3i64, Nullability::Nullable);
263        chunk0.statistics().set(
264            Stat::Sum,
265            Precision::exact(sum_scalar.into_value().vortex_expect("non-null sum")),
266        );
267        let chunk1 = buffer![4i32, 5, 6].into_array();
268        let chunked = ChunkedArray::try_new(
269            vec![chunk0, chunk1],
270            DType::Primitive(PType::I32, Nullability::NonNullable),
271        )?
272        .into_array();
273
274        let result = chunked.apply(&sum(root()))?.optimize_ctx(&SESSION)?;
275
276        let chunked_result = result
277            .as_opt::<Chunked>()
278            .vortex_expect("stat expression should preserve chunked alignment");
279        assert_eq!(chunked_result.nchunks(), 2);
280
281        let expected = PrimitiveArray::new(
282            buffer![3i64, 3, 0, 0, 0],
283            Validity::from_iter([true, true, false, false, false]),
284        )
285        .into_array();
286        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
287
288        Ok(())
289    }
290
291    #[test]
292    fn stat_expr_reads_cached_null_count() -> VortexResult<()> {
293        let array =
294            PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), None]).into_array();
295        let null_count_scalar = Scalar::primitive(2u64, Nullability::NonNullable);
296        array.statistics().set(
297            Stat::NullCount,
298            Precision::exact(
299                null_count_scalar
300                    .into_value()
301                    .vortex_expect("non-null null_count"),
302            ),
303        );
304
305        let result = array.apply(&null_count(root()))?;
306
307        let expected =
308            ConstantArray::new(Scalar::primitive(2u64, Nullability::Nullable), 4).into_array();
309        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
310
311        Ok(())
312    }
313
314    #[test]
315    fn stat_expr_reads_cached_all_null_from_null_count() -> VortexResult<()> {
316        let array = PrimitiveArray::from_option_iter::<i32, _>([None, None, None]).into_array();
317        array
318            .statistics()
319            .set(Stat::NullCount, Precision::exact(ScalarValue::from(3u64)));
320
321        let result = array.apply(&all_null(root()))?;
322
323        let expected =
324            ConstantArray::new(Scalar::bool(true, Nullability::Nullable), 3).into_array();
325        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
326
327        Ok(())
328    }
329
330    #[test]
331    fn stat_expr_reads_cached_all_null_false_from_inexact_low_null_count() -> VortexResult<()> {
332        let array = PrimitiveArray::from_option_iter::<i32, _>([None, Some(2), None]).into_array();
333        array
334            .statistics()
335            .set(Stat::NullCount, Precision::inexact(ScalarValue::from(2u64)));
336
337        let result = array.apply(&all_null(root()))?;
338
339        let expected =
340            ConstantArray::new(Scalar::bool(false, Nullability::Nullable), 3).into_array();
341        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
342
343        Ok(())
344    }
345
346    #[test]
347    fn stat_expr_returns_null_for_inexact_full_null_count_as_all_null() -> VortexResult<()> {
348        let array = PrimitiveArray::from_option_iter::<i32, _>([None, Some(2), None]).into_array();
349        array
350            .statistics()
351            .set(Stat::NullCount, Precision::inexact(ScalarValue::from(3u64)));
352
353        let result = array.apply(&all_null(root()))?;
354
355        let expected =
356            ConstantArray::new(Scalar::null(DType::Bool(Nullability::Nullable)), 3).into_array();
357        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
358
359        Ok(())
360    }
361
362    #[test]
363    fn stat_expr_reads_cached_all_non_null_from_null_count() -> VortexResult<()> {
364        let array = buffer![1i32, 2, 3].into_array();
365        array
366            .statistics()
367            .set(Stat::NullCount, Precision::exact(ScalarValue::from(0u64)));
368
369        let result = array.apply(&all_non_null(root()))?;
370
371        let expected =
372            ConstantArray::new(Scalar::bool(true, Nullability::Nullable), 3).into_array();
373        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
374
375        Ok(())
376    }
377
378    #[test]
379    fn stat_expr_reads_cached_all_non_null_true_from_inexact_zero_null_count() -> VortexResult<()> {
380        let array = buffer![1i32, 2, 3].into_array();
381        array
382            .statistics()
383            .set(Stat::NullCount, Precision::inexact(ScalarValue::from(0u64)));
384
385        let result = array.apply(&all_non_null(root()))?;
386
387        let expected =
388            ConstantArray::new(Scalar::bool(true, Nullability::Nullable), 3).into_array();
389        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
390
391        Ok(())
392    }
393
394    #[test]
395    fn stat_expr_returns_null_for_inexact_nonzero_null_count_as_all_non_null() -> VortexResult<()> {
396        let array =
397            PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), None]).into_array();
398        array
399            .statistics()
400            .set(Stat::NullCount, Precision::inexact(ScalarValue::from(2u64)));
401
402        let result = array.apply(&all_non_null(root()))?;
403
404        let expected =
405            ConstantArray::new(Scalar::null(DType::Bool(Nullability::Nullable)), 4).into_array();
406        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
407
408        Ok(())
409    }
410
411    #[test]
412    fn stat_expr_rejects_all_nan_for_non_float() -> VortexResult<()> {
413        let array = PrimitiveArray::empty::<i32>(Nullability::NonNullable).into_array();
414        let mut ctx = SESSION.create_execution_ctx();
415
416        let result = array
417            .apply(&all_nan(root()))
418            .and_then(|array| array.execute::<Canonical>(&mut ctx));
419
420        assert!(result.is_err());
421        Ok(())
422    }
423
424    #[test]
425    fn stat_expr_reads_cached_all_nan_from_nan_count() -> VortexResult<()> {
426        let array =
427            PrimitiveArray::from_option_iter([Some(f32::NAN), Some(f32::NAN), Some(f32::NAN)])
428                .into_array();
429        array
430            .statistics()
431            .set(Stat::NaNCount, Precision::exact(ScalarValue::from(3u64)));
432
433        let result = array.apply(&all_nan(root()))?;
434
435        let expected =
436            ConstantArray::new(Scalar::bool(true, Nullability::Nullable), 3).into_array();
437        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
438
439        Ok(())
440    }
441
442    #[test]
443    fn stat_expr_reads_cached_all_nan_false_from_inexact_low_nan_count() -> VortexResult<()> {
444        let array =
445            PrimitiveArray::from_option_iter([Some(f32::NAN), Some(1.0f32), Some(f32::NAN)])
446                .into_array();
447        array
448            .statistics()
449            .set(Stat::NaNCount, Precision::inexact(ScalarValue::from(2u64)));
450
451        let result = array.apply(&all_nan(root()))?;
452
453        let expected =
454            ConstantArray::new(Scalar::bool(false, Nullability::Nullable), 3).into_array();
455        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
456
457        Ok(())
458    }
459
460    #[test]
461    fn stat_expr_returns_null_for_inexact_full_nan_count_as_all_nan() -> VortexResult<()> {
462        let array =
463            PrimitiveArray::from_option_iter([Some(f32::NAN), Some(1.0f32), Some(f32::NAN)])
464                .into_array();
465        array
466            .statistics()
467            .set(Stat::NaNCount, Precision::inexact(ScalarValue::from(3u64)));
468
469        let result = array.apply(&all_nan(root()))?;
470
471        let expected =
472            ConstantArray::new(Scalar::null(DType::Bool(Nullability::Nullable)), 3).into_array();
473        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
474
475        Ok(())
476    }
477
478    #[test]
479    fn stat_expr_reads_cached_all_non_nan_true_from_inexact_zero_nan_count() -> VortexResult<()> {
480        let array = buffer![1.0f32, 2.0, 3.0].into_array();
481        array
482            .statistics()
483            .set(Stat::NaNCount, Precision::inexact(ScalarValue::from(0u64)));
484
485        let result = array.apply(&all_non_nan(root()))?;
486
487        let expected =
488            ConstantArray::new(Scalar::bool(true, Nullability::Nullable), 3).into_array();
489        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
490
491        Ok(())
492    }
493
494    #[test]
495    fn stat_expr_returns_null_for_inexact_nonzero_nan_count_as_all_non_nan() -> VortexResult<()> {
496        let array = PrimitiveArray::from_option_iter([Some(1.0f32), Some(f32::NAN), Some(3.0)])
497            .into_array();
498        array
499            .statistics()
500            .set(Stat::NaNCount, Precision::inexact(ScalarValue::from(1u64)));
501
502        let result = array.apply(&all_non_nan(root()))?;
503
504        let expected =
505            ConstantArray::new(Scalar::null(DType::Bool(Nullability::Nullable)), 3).into_array();
506        assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx());
507
508        Ok(())
509    }
510
511    #[test]
512    fn stat_expr_reads_cached_min_and_max() -> VortexResult<()> {
513        let array = buffer![3i32, 1, 2].into_array();
514        array
515            .statistics()
516            .set(Stat::Min, Precision::exact(ScalarValue::from(1i32)));
517        array
518            .statistics()
519            .set(Stat::Max, Precision::exact(ScalarValue::from(3i32)));
520
521        let min_result = array.clone().apply(&stat(
522            root(),
523            Stat::Min
524                .aggregate_fn()
525                .vortex_expect("min should have an aggregate function"),
526        ))?;
527        let expected_min =
528            ConstantArray::new(Scalar::primitive(1i32, Nullability::Nullable), 3).into_array();
529        assert_arrays_eq!(
530            min_result,
531            expected_min,
532            &mut SESSION.create_execution_ctx()
533        );
534
535        let max_result = array.apply(&stat(
536            root(),
537            Stat::Max
538                .aggregate_fn()
539                .vortex_expect("max should have an aggregate function"),
540        ))?;
541        let expected_max =
542            ConstantArray::new(Scalar::primitive(3i32, Nullability::Nullable), 3).into_array();
543        assert_arrays_eq!(
544            max_result,
545            expected_max,
546            &mut SESSION.create_execution_ctx()
547        );
548
549        Ok(())
550    }
551}