Skip to main content

vortex_array/aggregate_fn/
proto.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexResult;
5use vortex_error::vortex_bail;
6use vortex_error::vortex_ensure_eq;
7use vortex_error::vortex_err;
8use vortex_session::VortexSession;
9
10use crate::aggregate_fn::AggregateFnId;
11use crate::aggregate_fn::AggregateFnRef;
12use crate::aggregate_fn::new_foreign_aggregate_fn;
13use crate::aggregate_fn::session::AggregateFnSessionExt;
14use crate::proto::expr as pb;
15
16impl AggregateFnRef {
17    /// Serialize this aggregate function's options, erroring if it is not serializable.
18    ///
19    /// The bytes are only meaningful alongside [`id`](Self::id); [`from_parts`](Self::from_parts)
20    /// is the inverse.
21    pub fn serialize_options(&self) -> VortexResult<Vec<u8>> {
22        self.options()
23            .serialize()?
24            .ok_or_else(|| vortex_err!("Aggregate function '{}' is not serializable", self.id()))
25    }
26
27    /// Resolve an aggregate function from its ID and serialized options.
28    ///
29    /// Returns `Ok(None)` when the session has no plugin registered for `id`; the caller decides
30    /// whether that is an error, a reason to skip the aggregate, or a foreign placeholder. Errors
31    /// if the plugin rejects `options`.
32    pub fn from_parts(
33        id: AggregateFnId,
34        options: &[u8],
35        session: &VortexSession,
36    ) -> VortexResult<Option<Self>> {
37        let Some(plugin) = session.aggregate_fns().find_plugin(&id) else {
38            return Ok(None);
39        };
40
41        let agg_fn = plugin.deserialize(options, session)?;
42        vortex_ensure_eq!(agg_fn.id(), id, "Aggregate function ID mismatch");
43        Ok(Some(agg_fn))
44    }
45
46    /// Serialize this aggregate function to its protobuf representation.
47    ///
48    /// The format is stable: it is persisted in zoned layout metadata. An aggregate function's
49    /// options encoding is part of that contract, so changing it requires a new ID.
50    pub fn serialize_proto(&self) -> VortexResult<pb::AggregateFn> {
51        Ok(pb::AggregateFn {
52            id: self.id().to_string(),
53            metadata: Some(self.serialize_options()?),
54        })
55    }
56
57    /// Deserialize an aggregate function from its protobuf representation.
58    ///
59    /// Absent `metadata` is read as empty options. An ID the session does not know deserializes
60    /// as a foreign placeholder if the session [allows unknown plugins], and errors otherwise.
61    ///
62    /// [allows unknown plugins]: VortexSession::allows_unknown
63    pub fn from_proto(proto: &pb::AggregateFn, session: &VortexSession) -> VortexResult<Self> {
64        #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
65        let agg_fn_id = AggregateFnId::new(proto.id.as_str());
66        if let Some(agg_fn) = Self::from_parts(agg_fn_id, proto.metadata(), session)? {
67            return Ok(agg_fn);
68        }
69        if session.allows_unknown() {
70            return Ok(new_foreign_aggregate_fn(
71                agg_fn_id,
72                proto.metadata().to_vec(),
73            ));
74        }
75        vortex_bail!("unknown aggregate function id: {}", proto.id)
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use std::sync::LazyLock;
82
83    use prost::Message;
84    use rstest::rstest;
85    use vortex_error::VortexResult;
86    use vortex_error::vortex_panic;
87    use vortex_session::VortexSession;
88
89    use crate::ArrayRef;
90    use crate::Columnar;
91    use crate::ExecutionCtx;
92    use crate::aggregate_fn::AggregateArgs;
93    use crate::aggregate_fn::AggregateFnId;
94    use crate::aggregate_fn::AggregateFnRef;
95    use crate::aggregate_fn::AggregateFnVTable;
96    use crate::aggregate_fn::AggregateFnVTableExt;
97    use crate::aggregate_fn::EmptyOptions;
98    use crate::aggregate_fn::NumericalAggregateOpts;
99    use crate::aggregate_fn::combined::PairOptions;
100    use crate::aggregate_fn::fns::count::Count;
101    use crate::aggregate_fn::fns::first::First;
102    use crate::aggregate_fn::fns::is_constant::IsConstant;
103    use crate::aggregate_fn::fns::is_sorted::IsSorted;
104    use crate::aggregate_fn::fns::is_sorted::IsSortedOptions;
105    use crate::aggregate_fn::fns::last::Last;
106    use crate::aggregate_fn::fns::max::Max;
107    use crate::aggregate_fn::fns::mean::Mean;
108    use crate::aggregate_fn::fns::min::Min;
109    use crate::aggregate_fn::fns::null_count::NullCount;
110    use crate::aggregate_fn::fns::sum::Sum;
111    use crate::aggregate_fn::session::AggregateFnSession;
112    use crate::aggregate_fn::session::AggregateFnSessionExt;
113    use crate::dtype::DType;
114    use crate::proto::expr as pb;
115    use crate::scalar::Scalar;
116
117    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
118        let session = VortexSession::empty();
119        session.aggregate_fns().register(TestAgg);
120        session
121    });
122
123    /// A minimal serializable aggregate function used solely to exercise the serde round-trip.
124    #[derive(Clone, Debug)]
125    struct TestAgg;
126
127    impl AggregateFnVTable for TestAgg {
128        type Options = EmptyOptions;
129        type Partial = ();
130
131        #[expect(clippy::disallowed_methods, reason = "test-only id")]
132        fn id(&self) -> AggregateFnId {
133            AggregateFnId::new("vortex.test.proto")
134        }
135
136        fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
137            Ok(Some(vec![]))
138        }
139
140        fn deserialize(
141            &self,
142            _metadata: &[u8],
143            _session: &VortexSession,
144        ) -> VortexResult<Self::Options> {
145            Ok(EmptyOptions)
146        }
147
148        fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option<DType> {
149            Some(input_dtype.clone())
150        }
151
152        fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType> {
153            self.return_dtype(options, input_dtype)
154        }
155
156        fn empty_partial(
157            &self,
158            _args: AggregateArgs<'_, Self::Options>,
159        ) -> VortexResult<Self::Partial> {
160            Ok(())
161        }
162
163        fn partial_from_scalar(
164            &self,
165            _args: AggregateArgs<'_, Self::Options>,
166            _scalar: &Scalar,
167        ) -> VortexResult<Self::Partial> {
168            Ok(())
169        }
170
171        fn merge_partials(
172            &self,
173            _args: AggregateArgs<'_, Self::Options>,
174            _first: Self::Partial,
175            _second: Self::Partial,
176        ) -> VortexResult<Self::Partial> {
177            Ok(())
178        }
179
180        fn to_scalar(
181            &self,
182            _args: AggregateArgs<'_, Self::Options>,
183            _partial: &Self::Partial,
184        ) -> VortexResult<Scalar> {
185            vortex_panic!("TestAgg is for serde tests only");
186        }
187
188        fn is_saturated(
189            &self,
190            _args: AggregateArgs<'_, Self::Options>,
191            _partial: &Self::Partial,
192        ) -> bool {
193            true
194        }
195
196        fn accumulate(
197            &self,
198            _args: AggregateArgs<'_, Self::Options>,
199            _state: &mut Self::Partial,
200            _batch: &Columnar,
201            _ctx: &mut ExecutionCtx,
202        ) -> VortexResult<()> {
203            Ok(())
204        }
205
206        fn finalize(
207            &self,
208            _args: AggregateArgs<'_, Self::Options>,
209            partials: ArrayRef,
210        ) -> VortexResult<ArrayRef> {
211            Ok(partials)
212        }
213
214        fn finalize_scalar(
215            &self,
216            _args: AggregateArgs<'_, Self::Options>,
217            _partial: &Self::Partial,
218        ) -> VortexResult<Scalar> {
219            vortex_panic!("TestAgg is for serde tests only");
220        }
221    }
222
223    #[test]
224    fn aggregate_fn_serde() {
225        let agg_fn = TestAgg.bind(EmptyOptions);
226
227        let serialized = agg_fn.serialize_proto().unwrap();
228        let buf = serialized.encode_to_vec();
229        let deserialized_proto = pb::AggregateFn::decode(buf.as_slice()).unwrap();
230        let deserialized = AggregateFnRef::from_proto(&deserialized_proto, &SESSION).unwrap();
231
232        assert_eq!(deserialized, agg_fn);
233    }
234
235    /// The `skip_nans` option must survive a protobuf serialize/deserialize round-trip for the
236    /// numeric aggregates, including the non-default NaN-including configuration.
237    #[rstest]
238    #[case(Sum.bind(NumericalAggregateOpts::skip_nans()))]
239    #[case(Sum.bind(NumericalAggregateOpts::include_nans()))]
240    #[case(Count.bind(NumericalAggregateOpts::skip_nans()))]
241    #[case(Count.bind(NumericalAggregateOpts::include_nans()))]
242    fn numeric_aggregate_options_round_trip(#[case] agg_fn: AggregateFnRef) -> VortexResult<()> {
243        assert_round_trip(agg_fn)
244    }
245
246    #[rstest]
247    #[case(First.bind(EmptyOptions))]
248    #[case(Last.bind(EmptyOptions))]
249    #[case(IsConstant.bind(EmptyOptions))]
250    #[case(IsSorted.bind(IsSortedOptions { strict: false }))]
251    #[case(IsSorted.bind(IsSortedOptions { strict: true }))]
252    fn aggregate_options_round_trip(#[case] agg_fn: AggregateFnRef) -> VortexResult<()> {
253        assert_round_trip(agg_fn)
254    }
255
256    #[rstest]
257    fn mean_options_round_trip(
258        #[values(false, true)] sum_skip_nans: bool,
259        #[values(false, true)] count_skip_nans: bool,
260    ) -> VortexResult<()> {
261        assert_round_trip(Mean::combined().bind(PairOptions(
262            NumericalAggregateOpts {
263                skip_nans: sum_skip_nans,
264            },
265            NumericalAggregateOpts {
266                skip_nans: count_skip_nans,
267            },
268        )))
269    }
270
271    #[rstest]
272    #[case(IsSorted.id(), vec![])]
273    #[case(IsSorted.id(), vec![2])]
274    #[case(IsSorted.id(), vec![0, 1])]
275    #[case(Mean::combined().id(), vec![])]
276    #[case(Mean::combined().id(), vec![0])]
277    #[case(Mean::combined().id(), vec![2, 0])]
278    #[case(Mean::combined().id(), vec![0, 2])]
279    #[case(Mean::combined().id(), vec![0, 1, 0])]
280    fn invalid_aggregate_options(#[case] id: AggregateFnId, #[case] metadata: Vec<u8>) {
281        let proto = pb::AggregateFn {
282            id: id.to_string(),
283            metadata: Some(metadata),
284        };
285        assert!(AggregateFnRef::from_proto(&proto, &VortexSession::empty()).is_err());
286    }
287
288    fn assert_round_trip(agg_fn: AggregateFnRef) -> VortexResult<()> {
289        let session = VortexSession::empty();
290
291        let proto = agg_fn.serialize_proto()?;
292        let buf = proto.encode_to_vec();
293        let decoded = pb::AggregateFn::decode(buf.as_slice())?;
294        let round_tripped = AggregateFnRef::from_proto(&decoded, &session)?;
295
296        assert_eq!(round_tripped, agg_fn);
297        Ok(())
298    }
299
300    #[test]
301    fn unknown_aggregate_fn_id_allow_unknown() {
302        let session = VortexSession::empty().with::<AggregateFnSession>();
303        session.allow_unknown();
304
305        let proto = pb::AggregateFn {
306            id: "vortex.test.foreign_aggregate".to_string(),
307            metadata: Some(vec![7, 8, 9]),
308        };
309
310        let agg_fn = AggregateFnRef::from_proto(&proto, &session).unwrap();
311        assert_eq!(agg_fn.id().as_ref(), "vortex.test.foreign_aggregate");
312
313        let roundtrip = agg_fn.serialize_proto().unwrap();
314        assert_eq!(roundtrip.id, proto.id);
315        assert_eq!(roundtrip.metadata(), proto.metadata());
316    }
317
318    /// Pins the persisted encoding: `serialize_proto` output is stored in zoned layout metadata,
319    /// so any change to these bytes breaks existing files.
320    #[rstest]
321    #[case::empty_options(IsConstant.bind(EmptyOptions), b"\x0a\x12vortex.is_constant\x12\x00".as_slice())]
322    #[case::numeric_options(Sum.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0avortex.sum\x12\x02\x08\x01".as_slice())]
323    #[case::numeric_default_options(Sum.bind(NumericalAggregateOpts::include_nans()), b"\x0a\x0avortex.sum\x12\x00".as_slice())]
324    #[case::count(Count.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0cvortex.count\x12\x02\x08\x01".as_slice())]
325    #[case::min(Min.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0avortex.min\x12\x02\x08\x01".as_slice())]
326    #[case::max(Max.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0avortex.max\x12\x02\x08\x01".as_slice())]
327    #[case::first(First.bind(EmptyOptions), b"\x0a\x0cvortex.first\x12\x00".as_slice())]
328    #[case::last(Last.bind(EmptyOptions), b"\x0a\x0bvortex.last\x12\x00".as_slice())]
329    #[case::null_count(NullCount.bind(EmptyOptions), b"\x0a\x11vortex.null_count\x12\x00".as_slice())]
330    #[case::is_sorted(IsSorted.bind(IsSortedOptions { strict: true }), b"\x0a\x10vortex.is_sorted\x12\x01\x01".as_slice())]
331    #[case::mean_options(
332        Mean::combined().bind(PairOptions(
333            NumericalAggregateOpts::skip_nans(),
334            NumericalAggregateOpts::include_nans(),
335        )),
336        b"\x0a\x0bvortex.mean\x12\x02\x01\x00".as_slice(),
337    )]
338    fn golden_encoding(#[case] agg_fn: AggregateFnRef, #[case] bytes: &[u8]) -> VortexResult<()> {
339        assert_eq!(agg_fn.serialize_proto()?.encode_to_vec(), bytes);
340        let decoded = pb::AggregateFn::decode(bytes)?;
341        assert_eq!(
342            AggregateFnRef::from_proto(&decoded, &VortexSession::empty())?,
343            agg_fn
344        );
345        Ok(())
346    }
347
348    /// Zoned layouts written before `vortex.expr.AggregateFn` replaced their private spec message
349    /// omit the options field when it is empty. Absent metadata must read as empty options.
350    #[rstest]
351    #[case::empty_options(b"\x0a\x12vortex.is_constant".as_slice(), IsConstant.bind(EmptyOptions))]
352    #[case::numeric_default_options(b"\x0a\x0avortex.sum".as_slice(), Sum.bind(NumericalAggregateOpts::include_nans()))]
353    fn decodes_absent_metadata(
354        #[case] bytes: &[u8],
355        #[case] expected: AggregateFnRef,
356    ) -> VortexResult<()> {
357        let decoded = pb::AggregateFn::decode(bytes)?;
358        assert!(decoded.metadata.is_none());
359        assert_eq!(
360            AggregateFnRef::from_proto(&decoded, &VortexSession::empty())?,
361            expected
362        );
363        Ok(())
364    }
365
366    #[test]
367    fn from_parts_unknown_id_is_none() -> VortexResult<()> {
368        let session = VortexSession::empty();
369        #[expect(clippy::disallowed_methods, reason = "test-only id")]
370        let id = AggregateFnId::new("vortex.test.unknown");
371        assert!(AggregateFnRef::from_parts(id, &[], &session)?.is_none());
372        Ok(())
373    }
374}