Skip to main content

vortex_expr/stats/rewrite/
helpers.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Building blocks for [`StatsRewriteRule`](crate::stats::rewrite::StatsRewriteRule)
5//! implementations: stat references over bound expressions and the NaN guards that keep
6//! min/max comparisons sound for floating-point values.
7
8use vortex_array::aggregate_fn::AggregateFnVTableExt;
9use vortex_array::aggregate_fn::EmptyOptions as AggregateEmptyOptions;
10use vortex_array::aggregate_fn::NumericalAggregateOpts;
11use vortex_array::aggregate_fn::fns::all_nan::AllNan;
12use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan;
13use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull;
14use vortex_array::aggregate_fn::fns::all_null::AllNull;
15use vortex_array::aggregate_fn::fns::max::Max;
16use vortex_array::aggregate_fn::fns::min::Min;
17use vortex_array::aggregate_fn::fns::nan_count::NanCount;
18use vortex_array::aggregate_fn::fns::null_count::NullCount;
19use vortex_array::dtype::DType;
20use vortex_array::scalar_fn::EmptyOptions;
21use vortex_array::scalar_fn::builtin::cast::Cast;
22use vortex_array::scalar_fn::builtin::literal::Literal;
23use vortex_error::VortexExpect;
24use vortex_error::VortexResult;
25use vortex_session::VortexSession;
26
27use crate::BoundExpression;
28use crate::ScalarFnExprExt;
29use crate::bound::and;
30use crate::bound::and_collect;
31use crate::bound::eq;
32use crate::bound::lit;
33use crate::lambda::row_count::RowCount;
34use crate::stats::derive::stat_expr;
35
36pub fn row_count() -> BoundExpression {
37    RowCount
38        .try_new_bound_expr(EmptyOptions, [])
39        .vortex_expect("row-count expressions are always well-typed")
40}
41
42// Statistics follow NaN-skipping semantics, so min and max request it explicitly.
43pub fn min(expr: &BoundExpression, session: &VortexSession) -> Option<BoundExpression> {
44    stat_expr(
45        expr,
46        &Min.bind(NumericalAggregateOpts::skip_nans()),
47        session,
48    )
49}
50
51pub fn max(expr: &BoundExpression, session: &VortexSession) -> Option<BoundExpression> {
52    stat_expr(
53        expr,
54        &Max.bind(NumericalAggregateOpts::skip_nans()),
55        session,
56    )
57}
58
59pub fn null_count(expr: &BoundExpression, session: &VortexSession) -> Option<BoundExpression> {
60    stat_expr(expr, &NullCount.bind(AggregateEmptyOptions), session)
61}
62
63pub fn nan_count(expr: &BoundExpression, session: &VortexSession) -> Option<BoundExpression> {
64    stat_expr(expr, &NanCount.bind(AggregateEmptyOptions), session)
65}
66
67pub fn all_null(expr: &BoundExpression, session: &VortexSession) -> Option<BoundExpression> {
68    stat_expr(expr, &AllNull.bind(AggregateEmptyOptions), session)
69}
70
71pub fn all_non_null(expr: &BoundExpression, session: &VortexSession) -> Option<BoundExpression> {
72    stat_expr(expr, &AllNonNull.bind(AggregateEmptyOptions), session)
73}
74
75pub fn all_nan(expr: &BoundExpression, session: &VortexSession) -> Option<BoundExpression> {
76    stat_expr(expr, &AllNan.bind(AggregateEmptyOptions), session)
77}
78
79pub fn all_non_nan(expr: &BoundExpression, session: &VortexSession) -> Option<BoundExpression> {
80    stat_expr(expr, &AllNonNan.bind(AggregateEmptyOptions), session)
81}
82
83pub enum NanCheck {
84    NotNeeded,
85    Check(BoundExpression),
86    Unavailable,
87}
88
89pub trait NonNanProof {
90    const EMIT_UNGUARDED_REWRITES: bool;
91
92    fn check(expr: &BoundExpression, session: &VortexSession) -> VortexResult<NanCheck>;
93}
94
95pub struct NanCountProof;
96
97impl NonNanProof for NanCountProof {
98    const EMIT_UNGUARDED_REWRITES: bool = true;
99
100    fn check(expr: &BoundExpression, session: &VortexSession) -> VortexResult<NanCheck> {
101        non_nan_check(expr, |expr| match nan_count(expr, session) {
102            Some(nan_count) => NanCheck::Check(eq(nan_count, lit(0u64))),
103            None => NanCheck::Unavailable,
104        })
105    }
106}
107
108pub struct AllNonNanProof;
109
110impl NonNanProof for AllNonNanProof {
111    const EMIT_UNGUARDED_REWRITES: bool = false;
112
113    fn check(expr: &BoundExpression, session: &VortexSession) -> VortexResult<NanCheck> {
114        non_nan_check(expr, |expr| match all_non_nan(expr, session) {
115            Some(all_non_nan) => NanCheck::Check(all_non_nan),
116            None => NanCheck::Unavailable,
117        })
118    }
119}
120
121// Min/max do not order NaN values, so comparison rewrites are only sound when every
122// candidate value is known to be non-NaN. Cast result dtypes are not enough: a cast
123// from float to non-float still needs a proof about the float source values.
124pub fn non_nan_check(
125    expr: &BoundExpression,
126    proof: impl FnOnce(&BoundExpression) -> NanCheck,
127) -> VortexResult<NanCheck> {
128    if let Some(scalar) = expr.as_opt::<Literal>() {
129        if !scalar.dtype().is_float() {
130            return Ok(NanCheck::NotNeeded);
131        }
132        return Ok(if scalar.as_primitive().is_nan() {
133            NanCheck::Check(lit(false))
134        } else {
135            NanCheck::NotNeeded
136        });
137    }
138
139    if expr.is::<Cast>() {
140        if !has_nans(expr.child(0).dtype()) {
141            return Ok(NanCheck::NotNeeded);
142        }
143
144        return non_nan_check(expr.child(0), proof);
145    }
146
147    if !has_nans(expr.dtype()) {
148        return Ok(NanCheck::NotNeeded);
149    }
150
151    Ok(proof(expr))
152}
153
154fn has_nans(dtype: &DType) -> bool {
155    dtype.is_float()
156}
157
158pub fn with_non_nan_guards<'a, P: NonNanProof>(
159    exprs: impl IntoIterator<Item = &'a BoundExpression>,
160    value_predicate: BoundExpression,
161    session: &VortexSession,
162) -> VortexResult<Option<BoundExpression>> {
163    let mut nan_checks = Vec::new();
164    for expr in exprs {
165        match P::check(expr, session)? {
166            NanCheck::NotNeeded => {}
167            NanCheck::Check(check) => nan_checks.push(check),
168            NanCheck::Unavailable => return Ok(None),
169        }
170    }
171    let nan_predicate = and_collect(nan_checks);
172
173    Ok(match nan_predicate {
174        Some(nan_check) => Some(and(nan_check, value_predicate)),
175        // No possible NaN-bearing expression remains, so the value predicate is
176        // already guarded. Only one registered rule emits this unguarded
177        // rewrite so non-float comparisons are not duplicated.
178        None if P::EMIT_UNGUARDED_REWRITES => Some(value_predicate),
179        None => None,
180    })
181}