vortex_array/aggregate_fn/vtable.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt;
5use std::fmt::Debug;
6use std::fmt::Display;
7use std::fmt::Formatter;
8use std::hash::Hash;
9
10use prost::Message;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_proto::expr as pb;
14use vortex_session::VortexSession;
15
16use crate::ArrayRef;
17use crate::Columnar;
18use crate::ExecutionCtx;
19use crate::aggregate_fn::AggregateFn;
20use crate::aggregate_fn::AggregateFnId;
21use crate::aggregate_fn::AggregateFnRef;
22use crate::aggregate_fn::AggregateFnSatisfaction;
23use crate::dtype::DType;
24use crate::scalar::Scalar;
25
26/// Defines the interface for aggregate function vtables.
27///
28/// This trait is non-object-safe and allows the implementer to make use of associated types
29/// for improved type safety, while allowing Vortex to enforce runtime checks on the inputs and
30/// outputs of each function.
31///
32/// The [`AggregateFnVTable`] trait should be implemented for a struct that holds global data across
33/// all instances of the aggregate. In almost all cases, this struct will be an empty unit
34/// struct, since most aggregates do not require any global state.
35pub trait AggregateFnVTable: 'static + Sized + Clone + Send + Sync {
36 /// Options for this aggregate function.
37 type Options: 'static + Send + Sync + Clone + Debug + Display + PartialEq + Eq + Hash;
38
39 /// The partial accumulator state for a single group.
40 type Partial: 'static + Send;
41
42 /// Returns the ID of the aggregate function vtable.
43 fn id(&self) -> AggregateFnId;
44
45 /// Serialize the options for this aggregate function.
46 ///
47 /// Should return `Ok(None)` if the function is not serializable, and `Ok(vec![])` if it is
48 /// serializable but has no metadata.
49 fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
50 _ = options;
51 Ok(None)
52 }
53
54 /// Deserialize the options of this aggregate function.
55 fn deserialize(
56 &self,
57 _metadata: &[u8],
58 _session: &VortexSession,
59 ) -> VortexResult<Self::Options> {
60 vortex_bail!("Aggregate function {} is not deserializable", self.id());
61 }
62
63 /// Return whether this stored aggregate can satisfy `requested`.
64 ///
65 /// The default implementation only treats exactly equal aggregate functions as satisfying the
66 /// request. Approximate pruning aggregates can override this to expose looser-but-sound bounds.
67 fn can_satisfy(
68 &self,
69 options: &Self::Options,
70 requested: &AggregateFnRef,
71 ) -> AggregateFnSatisfaction {
72 if requested
73 .as_opt::<Self>()
74 .is_some_and(|other| other == options)
75 {
76 AggregateFnSatisfaction::Exact
77 } else {
78 AggregateFnSatisfaction::No
79 }
80 }
81
82 /// The return [`DType`] of the aggregate.
83 ///
84 /// Returns `None` if the aggregate function cannot be applied to the input dtype.
85 fn return_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType>;
86
87 /// If this aggregate should be computed as a default zone statistic for `input_dtype`, return
88 /// the bound aggregate to store. Default: not a zone-map default.
89 fn zone_stat_default(&self, _input_dtype: &DType) -> Option<AggregateFnRef> {
90 None
91 }
92
93 /// DType of the intermediate partial accumulator state.
94 ///
95 /// Use a struct dtype when multiple fields are needed
96 /// (e.g., Mean: `Struct { sum: f64, count: u64 }`).
97 ///
98 /// Returns `None` if the aggregate function cannot be applied to the input dtype.
99 fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType>;
100
101 /// Return the partial accumulator state for an empty group.
102 fn empty_partial(
103 &self,
104 options: &Self::Options,
105 input_dtype: &DType,
106 ) -> VortexResult<Self::Partial>;
107
108 /// Combine partial scalar state into the accumulator.
109 fn combine_partials(&self, partial: &mut Self::Partial, other: Scalar) -> VortexResult<()>;
110
111 /// Convert the partial state into a partial scalar.
112 ///
113 /// The returned scalar must have the same DType as specified by `partial_dtype` for the
114 /// options and input dtype used to construct the state.
115 fn to_scalar(&self, partial: &Self::Partial) -> VortexResult<Scalar>;
116
117 /// Reset the state of the accumulator to an empty group.
118 fn reset(&self, partial: &mut Self::Partial);
119
120 /// Is the partial accumulator state is "saturated", i.e. has it reached a state where the
121 /// final result is fully determined.
122 fn is_saturated(&self, state: &Self::Partial) -> bool;
123
124 /// Try to accumulate the raw array before decompression.
125 ///
126 /// Returns `true` if the array was handled, `false` to fall through to
127 /// the default kernel dispatch and canonicalization path.
128 ///
129 /// This is useful for aggregates that only depend on array metadata (e.g., validity)
130 /// rather than the encoded data, avoiding unnecessary decompression.
131 fn try_accumulate(
132 &self,
133 _state: &mut Self::Partial,
134 _batch: &ArrayRef,
135 _ctx: &mut ExecutionCtx,
136 ) -> VortexResult<bool> {
137 Ok(false)
138 }
139
140 /// Accumulate a new canonical array into the accumulator state.
141 fn accumulate(
142 &self,
143 state: &mut Self::Partial,
144 batch: &Columnar,
145 ctx: &mut ExecutionCtx,
146 ) -> VortexResult<()>;
147
148 /// Finalize an array of accumulator states into an array of aggregate results.
149 ///
150 /// The provides `states` array has dtype as specified by `state_dtype`, the result array
151 /// must have dtype as specified by `return_dtype`.
152 fn finalize(&self, states: ArrayRef) -> VortexResult<ArrayRef>;
153
154 /// Finalize a scalar accumulator state into an aggregate result.
155 ///
156 /// The provided `state` has dtype as specified by `state_dtype`, the result scalar must have
157 /// dtype as specified by `return_dtype`.
158 fn finalize_scalar(&self, partial: &Self::Partial) -> VortexResult<Scalar>;
159}
160
161#[derive(Clone, Debug, PartialEq, Eq, Hash)]
162pub struct EmptyOptions;
163impl Display for EmptyOptions {
164 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
165 write!(f, "")
166 }
167}
168
169/// Options for aggregate functions over primitive numeric inputs, controlling how NaN values in
170/// floating-point arrays are handled.
171///
172/// When `skip_nans` is `true` (the default), NaN values are treated as missing: they contribute
173/// nothing to `sum`/`min`/`max`/`mean` and are excluded from `count`.
174///
175/// When `skip_nans` is `false`, NaN values participate in the aggregate: `count` includes them,
176/// while any NaN value poisons the result of `sum`/`min`/`max`/`mean` to NaN.
177///
178/// The option has no effect on non-float inputs.
179#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
180pub struct NumericalAggregateOpts {
181 /// Whether NaN values are skipped (treated as missing) during aggregation.
182 pub skip_nans: bool,
183}
184
185impl NumericalAggregateOpts {
186 /// Options that skip NaN values, treating them as missing during aggregation.
187 ///
188 /// This is the default configuration; see [`NumericalAggregateOpts::include_nans`] for the
189 /// NaN-including variant.
190 pub const fn skip_nans() -> Self {
191 Self { skip_nans: true }
192 }
193
194 /// Options that include NaN values in the aggregate: `count` counts them, while any NaN
195 /// poisons the result of `sum`/`min`/`max`/`mean` to NaN.
196 ///
197 /// See [`NumericalAggregateOpts::skip_nans`] for the default NaN-skipping variant.
198 pub const fn include_nans() -> Self {
199 Self { skip_nans: false }
200 }
201
202 /// Serialize these options to protobuf-encoded metadata bytes.
203 pub fn serialize(&self) -> Vec<u8> {
204 pb::NumericalAggregateOpts {
205 skip_nans: self.skip_nans,
206 }
207 .encode_to_vec()
208 }
209
210 /// Deserialize these options from protobuf-encoded metadata bytes.
211 pub fn deserialize(metadata: &[u8]) -> VortexResult<Self> {
212 let opts = pb::NumericalAggregateOpts::decode(metadata)?;
213 Ok(Self {
214 skip_nans: opts.skip_nans,
215 })
216 }
217}
218
219impl Default for NumericalAggregateOpts {
220 fn default() -> Self {
221 Self::skip_nans()
222 }
223}
224
225impl Display for NumericalAggregateOpts {
226 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
227 // Only the non-default configuration is displayed, so that aggregates with default
228 // options render identically to their pre-options form, e.g. `vortex.sum()`.
229 if !self.skip_nans {
230 write!(f, "skip_nans=false")?;
231 }
232 Ok(())
233 }
234}
235
236/// Factory functions for aggregate vtables.
237pub trait AggregateFnVTableExt: AggregateFnVTable {
238 /// Bind this vtable with the given options into an [`AggregateFnRef`].
239 fn bind(&self, options: Self::Options) -> AggregateFnRef {
240 AggregateFn::new(self.clone(), options).erased()
241 }
242}
243impl<V: AggregateFnVTable> AggregateFnVTableExt for V {}