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