Skip to main content

vortex_expr/stats/
bind.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Bind abstract `vortex.stat` expressions to a concrete stats representation.
5//!
6//! Stats rewrite rules describe pruning in terms of `vortex.stat(input, aggregate_fn)` placeholders
7//! so the rewrite is independent of where statistics are stored. These stat placeholders are
8//! abstract because they name the statistic needed for a proof, but not how that statistic is
9//! represented by a specific layout or reader.
10//!
11//! Binding is the later pass that replaces each abstract placeholder with the representation used
12//! by a caller: zone-map field references, file-level stat literals, or typed nulls for missing
13//! stats. This lets all callers share the same falsification rules while keeping layout-specific
14//! stat storage behind [`StatBinder`].
15
16use vortex_array::aggregate_fn::AggregateFnRef;
17use vortex_array::dtype::DType;
18use vortex_array::expr::BoundExpression;
19use vortex_array::expr::bound::lit;
20use vortex_array::expr::traversal::NodeExt;
21use vortex_array::expr::traversal::Transformed;
22use vortex_array::scalar::Scalar;
23use vortex_array::scalar_fn::fns::stat::StatFn;
24use vortex_error::VortexResult;
25
26/// A target that can bind abstract statistics to concrete expressions.
27///
28/// Implementations define how a pruning proof should read stats from a specific backing
29/// representation. For example, a zone-map binder can translate a `max(col)` placeholder into a
30/// field reference in the per-zone stats table, while a file-stats binder can translate the same
31/// placeholder into a literal value from the file footer.
32pub trait StatBinder {
33    /// Bind `aggregate_fn(input)` to a concrete expression.
34    ///
35    /// Implementations should return `Ok(None)` when the requested aggregate
36    /// statistic is unavailable in their backing representation.
37    fn bind_aggregate(
38        &self,
39        input: &BoundExpression,
40        aggregate_fn: &AggregateFnRef,
41        stat_dtype: &DType,
42    ) -> VortexResult<Option<BoundExpression>>;
43
44    /// Expression to use when a stat is unavailable.
45    ///
46    /// The default is a nullable null literal, which preserves three-valued
47    /// pruning semantics for stats-table execution.
48    fn missing_stat(&self, dtype: DType) -> VortexResult<BoundExpression> {
49        null_expr(dtype)
50    }
51}
52
53/// Bind all `vortex.stat` expressions in `predicate`.
54///
55/// The predicate is usually the output of a stats rewrite rule. Rewrite rules
56/// are responsible for expressing stat semantics; binding maps aggregate-backed
57/// stat requests to the concrete stats representation supported by the binder.
58pub fn bind_stats<B: StatBinder + ?Sized>(
59    predicate: BoundExpression,
60    binder: &B,
61) -> VortexResult<BoundExpression> {
62    Ok(predicate
63        .transform_down(|expr| {
64            if !expr.is::<StatFn>() {
65                return Ok(Transformed::no(expr));
66            }
67
68            match bind_stat_fn(&expr, binder)? {
69                Some(bound) => Ok(Transformed::yes(bound)),
70                None => Ok(Transformed::yes(binder.missing_stat(expr.dtype().clone())?)),
71            }
72        })?
73        .into_inner())
74}
75
76fn bind_stat_fn(
77    expr: &BoundExpression,
78    binder: &(impl StatBinder + ?Sized),
79) -> VortexResult<Option<BoundExpression>> {
80    let options = expr.as_::<StatFn>();
81    let aggregate_fn = options.aggregate_fn();
82    // `StatFn` has exactly one child: the expression the aggregate statistic is computed over.
83    let input = expr.child(0);
84
85    binder.bind_aggregate(input, aggregate_fn, expr.dtype())
86}
87
88fn null_expr(dtype: DType) -> VortexResult<BoundExpression> {
89    Ok(lit(Scalar::null(dtype.as_nullable())))
90}
91
92#[cfg(test)]
93mod tests {
94    use vortex_array::dtype::Nullability;
95    use vortex_array::dtype::PType;
96    use vortex_array::dtype::StructFields;
97    use vortex_array::expr::and;
98    use vortex_array::expr::col;
99    use vortex_array::expr::get_item;
100    use vortex_array::expr::is_null;
101    use vortex_array::expr::lit;
102    use vortex_array::expr::or;
103    use vortex_array::expr::root;
104    use vortex_array::expr::stats::Stat;
105    use vortex_error::VortexResult;
106
107    use super::*;
108    use crate::stats::all_non_nan;
109    use crate::stats::nan_count;
110
111    struct TestBinder {
112        input_scope: DType,
113        stats_scope: DType,
114        bind_nan_count: bool,
115    }
116
117    impl TestBinder {
118        fn new(bind_nan_count: bool) -> Self {
119            Self {
120                input_scope: DType::Struct(
121                    StructFields::from_iter([(
122                        "f",
123                        DType::Primitive(PType::F32, Nullability::NonNullable),
124                    )]),
125                    Nullability::NonNullable,
126                ),
127                stats_scope: DType::Struct(
128                    StructFields::from_iter([(
129                        "f_nan_count",
130                        DType::Primitive(PType::U64, Nullability::NonNullable),
131                    )]),
132                    Nullability::NonNullable,
133                ),
134                bind_nan_count,
135            }
136        }
137    }
138
139    impl StatBinder for TestBinder {
140        fn bind_aggregate(
141            &self,
142            _input: &BoundExpression,
143            aggregate_fn: &AggregateFnRef,
144            _stat_dtype: &DType,
145        ) -> VortexResult<Option<BoundExpression>> {
146            let Some(stat) = Stat::from_aggregate_fn(aggregate_fn) else {
147                return Ok(None);
148            };
149
150            if stat == Stat::NaNCount && self.bind_nan_count {
151                Ok(Some(
152                    get_item("f_nan_count", root()).bind(&self.stats_scope)?,
153                ))
154            } else {
155                Ok(None)
156            }
157        }
158    }
159
160    #[test]
161    fn nan_count_binds_to_direct_stat_slot() -> VortexResult<()> {
162        let binder = TestBinder::new(true);
163
164        let bound = bind_stats(nan_count(col("f")).bind(&binder.input_scope)?, &binder)?;
165
166        assert_eq!(bound, col("f_nan_count").bind(&binder.stats_scope)?);
167        Ok(())
168    }
169
170    #[test]
171    fn all_non_nan_does_not_derive_from_nan_count() -> VortexResult<()> {
172        let binder = TestBinder::new(true);
173
174        let bound = bind_stats(all_non_nan(col("f")).bind(&binder.input_scope)?, &binder)?;
175
176        assert_eq!(
177            bound,
178            lit(Scalar::null(DType::Bool(Nullability::Nullable))).bind(&binder.stats_scope)?
179        );
180        Ok(())
181    }
182
183    #[test]
184    fn missing_stats_bind_to_null_without_reducing() -> VortexResult<()> {
185        let binder = TestBinder::new(false);
186        let null_bool = lit(Scalar::null(DType::Bool(Nullability::Nullable)));
187
188        let bound = bind_stats(
189            and(lit(false), all_non_nan(col("f"))).bind(&binder.input_scope)?,
190            &binder,
191        )?;
192
193        assert_eq!(
194            bound,
195            and(lit(false), null_bool.clone()).bind(&binder.stats_scope)?
196        );
197
198        let bound = bind_stats(
199            or(lit(true), all_non_nan(col("f"))).bind(&binder.input_scope)?,
200            &binder,
201        )?;
202
203        assert_eq!(bound, or(lit(true), null_bool).bind(&binder.stats_scope)?);
204        Ok(())
205    }
206
207    #[test]
208    fn unrelated_expressions_are_preserved() -> VortexResult<()> {
209        let binder = TestBinder::new(false);
210
211        let bound = bind_stats(is_null(col("f")).bind(&binder.input_scope)?, &binder)?;
212
213        assert_eq!(bound, is_null(col("f")).bind(&binder.input_scope)?);
214        Ok(())
215    }
216}