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::DynArray;
17use crate::ExecutionCtx;
18use crate::IntoArray;
19use crate::aggregate_fn::AggregateFn;
20use crate::aggregate_fn::AggregateFnId;
21use crate::aggregate_fn::AggregateFnRef;
22use crate::arrays::ConstantArray;
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 /// Coerce the input type for this aggregate function.
64 ///
65 /// This is optionally used by Vortex users when performing type coercion over a Vortex
66 /// expression. The default implementation returns the input type unchanged.
67 fn coerce_args(&self, options: &Self::Options, input_dtype: &DType) -> VortexResult<DType> {
68 let _ = options;
69 Ok(input_dtype.clone())
70 }
71
72 /// The return [`DType`] of the aggregate.
73 ///
74 /// Returns `None` if the aggregate function cannot be applied to the input dtype.
75 fn return_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType>;
76
77 /// DType of the intermediate partial accumulator state.
78 ///
79 /// Use a struct dtype when multiple fields are needed
80 /// (e.g., Mean: `Struct { sum: f64, count: u64 }`).
81 ///
82 /// Returns `None` if the aggregate function cannot be applied to the input dtype.
83 fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType>;
84
85 /// Return the partial accumulator state for an empty group.
86 fn empty_partial(
87 &self,
88 options: &Self::Options,
89 input_dtype: &DType,
90 ) -> VortexResult<Self::Partial>;
91
92 /// Combine partial scalar state into the accumulator.
93 fn combine_partials(&self, partial: &mut Self::Partial, other: Scalar) -> VortexResult<()>;
94
95 /// Convert the partial state into a partial scalar.
96 ///
97 /// The returned scalar must have the same DType as specified by `partial_dtype` for the
98 /// options and input dtype used to construct the state.
99 fn to_scalar(&self, partial: &Self::Partial) -> VortexResult<Scalar>;
100
101 /// Reset the state of the accumulator to an empty group.
102 fn reset(&self, partial: &mut Self::Partial);
103
104 /// Is the partial accumulator state is "saturated", i.e. has it reached a state where the
105 /// final result is fully determined.
106 fn is_saturated(&self, state: &Self::Partial) -> bool;
107
108 /// Accumulate a new canonical array into the accumulator state.
109 fn accumulate(
110 &self,
111 state: &mut Self::Partial,
112 batch: &Columnar,
113 ctx: &mut ExecutionCtx,
114 ) -> VortexResult<()>;
115
116 /// Finalize an array of accumulator states into an array of aggregate results.
117 ///
118 /// The provides `states` array has dtype as specified by `state_dtype`, the result array
119 /// must have dtype as specified by `return_dtype`.
120 fn finalize(&self, states: ArrayRef) -> VortexResult<ArrayRef>;
121
122 /// Finalize a scalar accumulator state into an aggregate result.
123 ///
124 /// The provided `state` has dtype as specified by `state_dtype`, the result scalar must have
125 /// dtype as specified by `return_dtype`.
126 fn finalize_scalar(&self, partial: &Self::Partial) -> VortexResult<Scalar> {
127 let scalar = self.to_scalar(partial)?;
128 let array = ConstantArray::new(scalar, 1).into_array();
129 let result = self.finalize(array)?;
130 result.scalar_at(0)
131 }
132}
133
134#[derive(Clone, Debug, PartialEq, Eq, Hash)]
135pub struct EmptyOptions;
136impl Display for EmptyOptions {
137 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
138 write!(f, "")
139 }
140}
141
142/// Factory functions for aggregate vtables.
143pub trait AggregateFnVTableExt: AggregateFnVTable {
144 /// Bind this vtable with the given options into an [`AggregateFnRef`].
145 fn bind(&self, options: Self::Options) -> AggregateFnRef {
146 AggregateFn::new(self.clone(), options).erased()
147 }
148}
149impl<V: AggregateFnVTable> AggregateFnVTableExt for V {}