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 vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12use vortex_session::VortexSession;
13
14use crate::ArrayRef;
15use crate::Columnar;
16use crate::ExecutionCtx;
17use crate::aggregate_fn::AggregateFn;
18use crate::aggregate_fn::AggregateFnId;
19use crate::aggregate_fn::AggregateFnRef;
20use crate::dtype::DType;
21use crate::scalar::Scalar;
22
23/// Defines the interface for aggregate function vtables.
24///
25/// This trait is non-object-safe and allows the implementer to make use of associated types
26/// for improved type safety, while allowing Vortex to enforce runtime checks on the inputs and
27/// outputs of each function.
28///
29/// The [`AggregateFnVTable`] trait should be implemented for a struct that holds global data across
30/// all instances of the aggregate. In almost all cases, this struct will be an empty unit
31/// struct, since most aggregates do not require any global state.
32pub trait AggregateFnVTable: 'static + Sized + Clone + Send + Sync {
33 /// Options for this aggregate function.
34 type Options: 'static + Send + Sync + Clone + Debug + Display + PartialEq + Eq + Hash;
35
36 /// The partial accumulator state for a single group.
37 type Partial: 'static + Send;
38
39 /// Returns the ID of the aggregate function vtable.
40 fn id(&self) -> AggregateFnId;
41
42 /// Serialize the options for this aggregate function.
43 ///
44 /// Should return `Ok(None)` if the function is not serializable, and `Ok(vec![])` if it is
45 /// serializable but has no metadata.
46 fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
47 _ = options;
48 Ok(None)
49 }
50
51 /// Deserialize the options of this aggregate function.
52 fn deserialize(
53 &self,
54 _metadata: &[u8],
55 _session: &VortexSession,
56 ) -> VortexResult<Self::Options> {
57 vortex_bail!("Aggregate function {} is not deserializable", self.id());
58 }
59
60 /// The return [`DType`] of the aggregate.
61 ///
62 /// Returns `None` if the aggregate function cannot be applied to the input dtype.
63 fn return_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType>;
64
65 /// DType of the intermediate partial accumulator state.
66 ///
67 /// Use a struct dtype when multiple fields are needed
68 /// (e.g., Mean: `Struct { sum: f64, count: u64 }`).
69 ///
70 /// Returns `None` if the aggregate function cannot be applied to the input dtype.
71 fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType>;
72
73 /// Return the partial accumulator state for an empty group.
74 fn empty_partial(
75 &self,
76 options: &Self::Options,
77 input_dtype: &DType,
78 ) -> VortexResult<Self::Partial>;
79
80 /// Combine partial scalar state into the accumulator.
81 fn combine_partials(&self, partial: &mut Self::Partial, other: Scalar) -> VortexResult<()>;
82
83 /// Convert the partial state into a partial scalar.
84 ///
85 /// The returned scalar must have the same DType as specified by `partial_dtype` for the
86 /// options and input dtype used to construct the state.
87 fn to_scalar(&self, partial: &Self::Partial) -> VortexResult<Scalar>;
88
89 /// Reset the state of the accumulator to an empty group.
90 fn reset(&self, partial: &mut Self::Partial);
91
92 /// Is the partial accumulator state is "saturated", i.e. has it reached a state where the
93 /// final result is fully determined.
94 fn is_saturated(&self, state: &Self::Partial) -> bool;
95
96 /// Try to accumulate the raw array before decompression.
97 ///
98 /// Returns `true` if the array was handled, `false` to fall through to
99 /// the default kernel dispatch and canonicalization path.
100 ///
101 /// This is useful for aggregates that only depend on array metadata (e.g., validity)
102 /// rather than the encoded data, avoiding unnecessary decompression.
103 fn try_accumulate(
104 &self,
105 _state: &mut Self::Partial,
106 _batch: &ArrayRef,
107 _ctx: &mut ExecutionCtx,
108 ) -> VortexResult<bool> {
109 Ok(false)
110 }
111
112 /// Accumulate a new canonical array into the accumulator state.
113 fn accumulate(
114 &self,
115 state: &mut Self::Partial,
116 batch: &Columnar,
117 ctx: &mut ExecutionCtx,
118 ) -> VortexResult<()>;
119
120 /// Finalize an array of accumulator states into an array of aggregate results.
121 ///
122 /// The provides `states` array has dtype as specified by `state_dtype`, the result array
123 /// must have dtype as specified by `return_dtype`.
124 fn finalize(&self, states: ArrayRef) -> VortexResult<ArrayRef>;
125
126 /// Finalize a scalar accumulator state into an aggregate result.
127 ///
128 /// The provided `state` has dtype as specified by `state_dtype`, the result scalar must have
129 /// dtype as specified by `return_dtype`.
130 fn finalize_scalar(&self, partial: &Self::Partial) -> VortexResult<Scalar>;
131}
132
133#[derive(Clone, Debug, PartialEq, Eq, Hash)]
134pub struct EmptyOptions;
135impl Display for EmptyOptions {
136 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
137 write!(f, "")
138 }
139}
140
141/// Factory functions for aggregate vtables.
142pub trait AggregateFnVTableExt: AggregateFnVTable {
143 /// Bind this vtable with the given options into an [`AggregateFnRef`].
144 fn bind(&self, options: Self::Options) -> AggregateFnRef {
145 AggregateFn::new(self.clone(), options).erased()
146 }
147}
148impl<V: AggregateFnVTable> AggregateFnVTableExt for V {}