Skip to main content

vortex_expr/stats/
stat_fn.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Scalar function implementation for aggregate-backed stat expressions.
5
6use std::fmt::Display;
7use std::fmt::Formatter;
8
9use vortex_array::ArrayRef;
10use vortex_array::ExecutionCtx;
11use vortex_array::IntoArray;
12use vortex_array::aggregate_fn::AggregateFnRef;
13use vortex_array::aggregate_fn::fns::all_nan::AllNan;
14use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan;
15use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull;
16use vortex_array::aggregate_fn::fns::all_null::AllNull;
17use vortex_array::arrays::ConstantArray;
18use vortex_array::dtype::DType;
19use vortex_array::scalar::Scalar;
20use vortex_array::scalar::ScalarValue;
21use vortex_array::scalar_fn::Arity;
22use vortex_array::scalar_fn::ChildName;
23use vortex_array::scalar_fn::ExecutionArgs;
24use vortex_array::scalar_fn::ScalarFnId;
25use vortex_array::scalar_fn::ScalarFnVTable;
26use vortex_array::scalar_fn::display::ExprDisplay;
27use vortex_array::stats::Precision;
28use vortex_array::stats::Stat;
29use vortex_array::stats::StatsProvider;
30use vortex_array::stats::StatsProviderExt;
31use vortex_error::VortexResult;
32use vortex_error::vortex_bail;
33use vortex_session::registry::CachedId;
34
35/// Options for the `stat` scalar function.
36#[derive(Clone, Debug, PartialEq, Eq, Hash)]
37pub struct StatOptions {
38    aggregate_fn: AggregateFnRef,
39}
40
41impl StatOptions {
42    /// Creates options for the provided aggregate statistic.
43    pub fn new(aggregate_fn: AggregateFnRef) -> Self {
44        Self { aggregate_fn }
45    }
46
47    /// Returns the aggregate function backing this statistic lookup.
48    pub fn aggregate_fn(&self) -> &AggregateFnRef {
49        &self.aggregate_fn
50    }
51}
52
53impl Display for StatOptions {
54    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
55        Display::fmt(&self.aggregate_fn, f)
56    }
57}
58
59/// Scalar function that broadcasts a stored aggregate partial over the input rows.
60///
61/// The only current consumer is **row-wise pruning**: substituting `stat(col, agg)` into a
62/// predicate produces a cheap, row-aligned approximation whose constant runs let downstream
63/// filters drop entire stretches at once. For example, `value < 10` is prunable as
64/// `stat(value, max) < 10` (rows where the bound is false are guaranteed false) or
65/// `stat(value, min) >= 10` (rows where it is true are guaranteed true) — the zone-map /
66/// min-max-index pattern, expressed as an ordinary expression so the existing scalar
67/// machinery can rewrite, fold, and execute it.
68///
69/// The result is row-aligned with the input, at whatever granularity the input carries the
70/// stat at: e.g. a flat array yields a single broadcast `ConstantArray`; a chunked array
71/// yields a constant per chunk; a zone-mapped array would yield a run-end-encoded array,
72/// one run per zone. If the requested stat is not available, the result is a null constant.
73///
74/// Pruning only makes sense for aggregates that can prove something about every row in the scope
75/// — `min`, `max`, `all_null`, `all_non_null`, bloom filters, etc. Non-idempotent aggregates like
76/// `sum`, `count`, `mean`, `null_count`, and `nan_count` still produce a meaningful per-chunk
77/// value but do **not** bound any single row.
78#[derive(Clone)]
79pub struct StatFn;
80
81impl ScalarFnVTable for StatFn {
82    type Options = StatOptions;
83
84    fn id(&self) -> ScalarFnId {
85        static ID: CachedId = CachedId::new("vortex.stat");
86        *ID
87    }
88
89    fn arity(&self, _options: &Self::Options) -> Arity {
90        Arity::Exact(1)
91    }
92
93    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
94        match child_idx {
95            0 => ChildName::from("input"),
96            _ => unreachable!("Invalid child index {} for Stat expression", child_idx),
97        }
98    }
99
100    fn fmt_sql(
101        &self,
102        options: &Self::Options,
103        expr: &dyn ExprDisplay,
104        f: &mut Formatter<'_>,
105    ) -> std::fmt::Result {
106        write!(f, "stat(")?;
107        Display::fmt(expr.display_child(0), f)?;
108        write!(f, ", {})", options.aggregate_fn())
109    }
110
111    fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
112        stat_dtype(options.aggregate_fn(), &arg_dtypes[0])
113    }
114
115    fn execute(
116        &self,
117        options: &Self::Options,
118        args: &dyn ExecutionArgs,
119        _ctx: &mut ExecutionCtx,
120    ) -> VortexResult<ArrayRef> {
121        let input = args.get(0)?;
122        let dtype = stat_dtype(options.aggregate_fn(), input.dtype())?;
123        stat_array(&input, options.aggregate_fn(), dtype, args.row_count())
124    }
125
126    fn is_strict(&self, _options: &Self::Options) -> bool {
127        false
128    }
129}
130
131fn stat_dtype(aggregate_fn: &AggregateFnRef, input_dtype: &DType) -> VortexResult<DType> {
132    let Some(dtype) = aggregate_fn.state_dtype(input_dtype) else {
133        vortex_bail!(
134            "Aggregate function {} does not support input dtype {}",
135            aggregate_fn,
136            input_dtype
137        );
138    };
139    Ok(dtype.as_nullable())
140}
141
142fn stat_array(
143    array: &ArrayRef,
144    aggregate_fn: &AggregateFnRef,
145    dtype: DType,
146    len: usize,
147) -> VortexResult<ArrayRef> {
148    let value = if aggregate_fn.is::<AllNull>() {
149        let len = u64::try_from(len)?;
150        match array.statistics().get_as::<u64>(Stat::NullCount) {
151            Precision::Exact(count) => Some(count == len),
152            Precision::Inexact(count) => (count < len).then_some(false),
153            Precision::Absent => None,
154        }
155        .map(ScalarValue::Bool)
156    } else if aggregate_fn.is::<AllNonNull>() {
157        match array.statistics().get_as::<u64>(Stat::NullCount) {
158            Precision::Exact(count) => Some(count == 0),
159            Precision::Inexact(0) => Some(true),
160            Precision::Inexact(_) | Precision::Absent => None,
161        }
162        .map(ScalarValue::Bool)
163    } else if aggregate_fn.is::<AllNan>() {
164        let len = u64::try_from(len)?;
165        match array.statistics().get_as::<u64>(Stat::NaNCount) {
166            Precision::Exact(count) => Some(count == len),
167            Precision::Inexact(count) => (count < len).then_some(false),
168            Precision::Absent => None,
169        }
170        .map(ScalarValue::Bool)
171    } else if aggregate_fn.is::<AllNonNan>() {
172        match array.statistics().get_as::<u64>(Stat::NaNCount) {
173            Precision::Exact(count) => Some(count == 0),
174            Precision::Inexact(0) => Some(true),
175            Precision::Inexact(_) | Precision::Absent => None,
176        }
177        .map(ScalarValue::Bool)
178    } else if let Some(stat) = Stat::from_aggregate_fn(aggregate_fn) {
179        array
180            .statistics()
181            .with_typed_stats_set(|stats| stats.get(stat))
182            // We don't mind whether the stat is approxed or not, since these are row-wise bounds.
183            .into_inner()
184            .and_then(Scalar::into_value)
185    } else {
186        tracing::trace!(
187            "No legacy Stat slot for aggregate {}; stat expression will resolve to null",
188            aggregate_fn
189        );
190        None
191    };
192
193    let scalar = Scalar::try_new(dtype, value)?;
194    Ok(ConstantArray::new(scalar, len).into_array())
195}