Skip to main content

vortex_array/aggregate_fn/
session.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5use std::sync::Arc;
6
7use vortex_session::ArcSwapMap;
8use vortex_session::SessionExt;
9use vortex_session::SessionGuard;
10use vortex_session::SessionVar;
11use vortex_utils::aliases::hash_map::HashMap;
12
13use crate::aggregate_fn::AggregateFnId;
14use crate::aggregate_fn::AggregateFnPluginRef;
15use crate::aggregate_fn::AggregateFnRef;
16use crate::aggregate_fn::AggregateFnVTable;
17use crate::aggregate_fn::ExtensionStoragePushdown;
18use crate::aggregate_fn::fns::all_nan::AllNan;
19use crate::aggregate_fn::fns::all_non_distinct::AllNonDistinct;
20use crate::aggregate_fn::fns::all_non_nan::AllNonNan;
21use crate::aggregate_fn::fns::all_non_null::AllNonNull;
22use crate::aggregate_fn::fns::all_null::AllNull;
23use crate::aggregate_fn::fns::bounded_max::BoundedMax;
24use crate::aggregate_fn::fns::bounded_min::BoundedMin;
25use crate::aggregate_fn::fns::count::Count;
26use crate::aggregate_fn::fns::count::CountGroupedKernel;
27use crate::aggregate_fn::fns::first::First;
28use crate::aggregate_fn::fns::is_constant::IsConstant;
29use crate::aggregate_fn::fns::is_sorted::IsSorted;
30use crate::aggregate_fn::fns::last::Last;
31use crate::aggregate_fn::fns::max::Max;
32use crate::aggregate_fn::fns::mean::Mean;
33use crate::aggregate_fn::fns::min::Min;
34use crate::aggregate_fn::fns::min_max::MinMax;
35use crate::aggregate_fn::fns::nan_count::NanCount;
36use crate::aggregate_fn::fns::null_count::NullCount;
37use crate::aggregate_fn::fns::sum::PrimitiveGroupedSumEncodingKernel;
38use crate::aggregate_fn::fns::sum::Sum;
39use crate::aggregate_fn::fns::sum_v2::BoolGroupedSumV2EncodingKernel;
40use crate::aggregate_fn::fns::sum_v2::PrimitiveGroupedSumV2EncodingKernel;
41use crate::aggregate_fn::fns::sum_v2::SumV2;
42use crate::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes;
43use crate::aggregate_fn::kernels::DynAggregateKernel;
44use crate::aggregate_fn::kernels::DynGroupedAggregateKernel;
45use crate::array::ArrayId;
46use crate::array::VTable;
47use crate::arrays::Bool;
48use crate::arrays::Chunked;
49use crate::arrays::Dict;
50use crate::arrays::Primitive;
51use crate::arrays::RunEnd;
52use crate::arrays::Widen;
53use crate::arrays::chunked::compute::aggregate::ChunkedArrayAggregate;
54use crate::arrays::dict::compute::is_constant::DictIsConstantKernel;
55use crate::arrays::dict::compute::is_sorted::DictIsSortedKernel;
56use crate::arrays::dict::compute::min_max::DictMinMaxKernel;
57use crate::arrays::runend::compute::is_constant::RunEndIsConstantKernel;
58use crate::arrays::runend::compute::is_sorted::RunEndIsSortedKernel;
59use crate::arrays::runend::compute::min_max::RunEndMinMaxKernel;
60use crate::arrays::runend::compute::sum::RunEndSumKernel;
61use crate::arrays::widen::compute::aggregate::WidenArrayAggregate;
62use crate::dtype::DType;
63use crate::dtype::extension::ExtVTable;
64use crate::extension::datetime::Date;
65use crate::extension::datetime::Duration;
66use crate::extension::datetime::Time;
67use crate::extension::datetime::Timestamp;
68
69/// Session state for aggregate functions and encoding-specific aggregate kernels.
70///
71/// The default session registers the built-in aggregate functions and kernels. Additional
72/// aggregate functions and kernels may be registered by extensions when they are added to a
73/// [`VortexSession`](vortex_session::VortexSession).
74#[derive(Clone, Debug)]
75pub struct AggregateFnSession {
76    registry: AggregateFnRegistry,
77
78    kernels: AggregateKernelRegistry,
79    grouped_kernels: GroupedKernelRegistry,
80    grouped_encoding_kernels: GroupedEncodingKernelRegistry,
81}
82
83impl SessionVar for AggregateFnSession {
84    fn as_any(&self) -> &dyn Any {
85        self
86    }
87
88    fn as_any_mut(&mut self) -> &mut dyn Any {
89        self
90    }
91}
92
93type AggregateKernelKey = (ArrayId, Option<AggregateFnId>);
94type GroupedEncodingKernelKey = (ArrayId, AggregateFnId);
95
96/// Registry of aggregate function plugins, keyed by aggregate function id.
97type AggregateFnRegistry = ArcSwapMap<AggregateFnId, AggregateFnPluginRef>;
98/// Registry of aggregate kernels, keyed by encoding and optional aggregate function.
99type AggregateKernelRegistry = ArcSwapMap<AggregateKernelKey, &'static dyn DynAggregateKernel>;
100/// Registry of encoding-agnostic grouped aggregate kernels, keyed by aggregate function id.
101type GroupedKernelRegistry = ArcSwapMap<AggregateFnId, &'static dyn DynGroupedAggregateKernel>;
102/// Registry of grouped aggregate kernels, keyed by encoding and aggregate function.
103type GroupedEncodingKernelRegistry =
104    ArcSwapMap<GroupedEncodingKernelKey, &'static dyn DynGroupedAggregateKernel>;
105
106impl Default for AggregateFnSession {
107    fn default() -> Self {
108        let this = Self {
109            registry: AggregateFnRegistry::default(),
110            kernels: AggregateKernelRegistry::default(),
111            grouped_kernels: GroupedKernelRegistry::default(),
112            grouped_encoding_kernels: GroupedEncodingKernelRegistry::default(),
113        };
114
115        // Register the built-in aggregate functions
116        this.register(AllNonDistinct);
117        this.register(AllNonNan);
118        this.register(AllNonNull);
119        this.register(AllNan);
120        this.register(AllNull);
121        this.register(BoundedMax);
122        this.register(BoundedMin);
123        this.register(Count);
124        this.register(First);
125        this.register(IsConstant);
126        this.register(IsSorted);
127        this.register(Last);
128        this.register(Max);
129        this.register(Mean::combined());
130        this.register(Min);
131        this.register(MinMax);
132        this.register(NanCount);
133        this.register(NullCount);
134        this.register(Sum);
135        this.register(SumV2);
136        this.register(UncompressedSizeInBytes);
137
138        // Temporal extension types compare like their integer storage, so comparison-based
139        // aggregates are pushed down into it.
140        this.register_storage_ordered(Date);
141        this.register_storage_ordered(Duration);
142        this.register_storage_ordered(Time);
143        this.register_storage_ordered(Timestamp);
144
145        // Register the built-in aggregate kernels.
146        this.register_aggregate_kernel(Chunked.id(), None::<AggregateFnId>, &ChunkedArrayAggregate);
147        this.register_aggregate_kernel(Dict.id(), Some(MinMax.id()), &DictMinMaxKernel);
148        this.register_aggregate_kernel(Dict.id(), Some(IsConstant.id()), &DictIsConstantKernel);
149        this.register_aggregate_kernel(Dict.id(), Some(IsSorted.id()), &DictIsSortedKernel);
150        this.register_aggregate_kernel(RunEnd.id(), Some(MinMax.id()), &RunEndMinMaxKernel);
151        this.register_aggregate_kernel(RunEnd.id(), Some(IsConstant.id()), &RunEndIsConstantKernel);
152        this.register_aggregate_kernel(RunEnd.id(), Some(IsSorted.id()), &RunEndIsSortedKernel);
153        this.register_aggregate_kernel(RunEnd.id(), Some(Sum.id()), &RunEndSumKernel);
154        this.register_aggregate_kernel(RunEnd.id(), Some(SumV2.id()), &RunEndSumKernel);
155        this.register_aggregate_kernel(Widen.id(), Some(MinMax.id()), &WidenArrayAggregate);
156        this.register_aggregate_kernel(Widen.id(), Some(Min.id()), &WidenArrayAggregate);
157        this.register_aggregate_kernel(Widen.id(), Some(Max.id()), &WidenArrayAggregate);
158        this.register_aggregate_kernel(Widen.id(), Some(IsConstant.id()), &WidenArrayAggregate);
159        this.register_aggregate_kernel(Widen.id(), Some(IsSorted.id()), &WidenArrayAggregate);
160        this.register_aggregate_kernel(Widen.id(), Some(Sum.id()), &WidenArrayAggregate);
161
162        // Register the built-in grouped aggregate kernels.
163        this.register_grouped_kernel(Count.id(), &CountGroupedKernel);
164        this.register_grouped_encoding_kernel(
165            Primitive.id(),
166            Sum.id(),
167            &PrimitiveGroupedSumEncodingKernel,
168        );
169        this.register_grouped_encoding_kernel(
170            Primitive.id(),
171            SumV2.id(),
172            &PrimitiveGroupedSumV2EncodingKernel,
173        );
174        this.register_grouped_encoding_kernel(
175            Bool.id(),
176            SumV2.id(),
177            &BoolGroupedSumV2EncodingKernel,
178        );
179
180        this
181    }
182}
183
184impl AggregateFnSession {
185    /// Returns the aggregate function plugin registered for `id`, if any.
186    pub fn find_plugin(&self, id: &AggregateFnId) -> Option<AggregateFnPluginRef> {
187        self.registry.get(id)
188    }
189
190    /// Register an aggregate function vtable in the session, replacing any existing vtable with
191    /// the same ID.
192    pub fn register<V: AggregateFnVTable>(&self, vtable: V) {
193        let id = vtable.id();
194        let pluginref = Arc::new(vtable) as AggregateFnPluginRef;
195        self.registry.insert(id, pluginref);
196    }
197
198    /// Push the comparison-based aggregates `is_sorted` and `min_max` down into the storage of
199    /// extension type `ext`, through [`ExtensionStoragePushdown`].
200    ///
201    /// Only call this when comparing two values of `ext` is the same as comparing their storage,
202    /// as for the temporal types and for UUIDs, which are stored big-endian. See
203    /// [`ExtensionStoragePushdown`] for how to check.
204    pub fn register_storage_ordered<E: ExtVTable>(&self, ext: E) {
205        self.register(ExtensionStoragePushdown::new(IsSorted, ext.clone()));
206        self.register(ExtensionStoragePushdown::new(MinMax, ext));
207    }
208
209    /// The default per-chunk zone statistics for a column of `input_dtype`, collected from every
210    /// registered aggregate's `zone_stat_default`.
211    ///
212    /// Each call scans the whole plugin registry, so this is intended to be called once per
213    /// column when a zoned writer is opened, not per chunk or per row.
214    pub fn zone_stat_defaults(&self, input_dtype: &DType) -> Vec<AggregateFnRef> {
215        self.registry.read(|registry| {
216            let mut fns: Vec<AggregateFnRef> = registry
217                .values()
218                .filter_map(|plugin| plugin.zone_stat_default(input_dtype))
219                .collect();
220            fns.sort_by_key(|f| f.id());
221            fns
222        })
223    }
224
225    /// Returns the aggregate kernel registered for `array_id` and `agg_fn_id`, if any.
226    ///
227    /// Lookup first checks for a kernel registered for the exact aggregate function, then falls
228    /// back to a kernel registered for all aggregate functions on the same array encoding.
229    pub fn find_aggregate_kernel(
230        &self,
231        array_id: impl Into<ArrayId>,
232        agg_fn_id: impl Into<AggregateFnId>,
233    ) -> Option<&'static dyn DynAggregateKernel> {
234        let id = array_id.into();
235        let fn_id = agg_fn_id.into();
236        self.kernels
237            .read(|kernels| lookup_aggregate_kernel(kernels, id, fn_id))
238    }
239
240    /// Registers an aggregate kernel for an array encoding.
241    ///
242    /// When `agg_fn_id` is `Some`, the kernel is used only for that aggregate function. When
243    /// `agg_fn_id` is `None`, the kernel is used as the fallback for aggregate functions on the
244    /// array encoding that do not have a more specific kernel.
245    pub fn register_aggregate_kernel(
246        &self,
247        array_id: impl Into<ArrayId>,
248        agg_fn_id: Option<impl Into<AggregateFnId>>,
249        kernel: &'static dyn DynAggregateKernel,
250    ) {
251        let id = (array_id.into(), agg_fn_id.map(|id| id.into()));
252        self.kernels.insert(id, kernel);
253    }
254
255    /// Returns the grouped aggregate kernel registered for `agg_fn_id`, if any.
256    ///
257    /// These kernels are independent of the element encoding and are checked for each element
258    /// representation, after any kernel registered for the current element encoding.
259    pub fn find_grouped_kernel(
260        &self,
261        agg_fn_id: impl Into<AggregateFnId>,
262    ) -> Option<&'static dyn DynGroupedAggregateKernel> {
263        let fn_id = agg_fn_id.into();
264        self.grouped_kernels
265            .read(|kernels| kernels.get(&fn_id).copied())
266    }
267
268    /// Registers a grouped aggregate kernel for an aggregate function.
269    pub fn register_grouped_kernel(
270        &self,
271        agg_fn_id: impl Into<AggregateFnId>,
272        kernel: &'static dyn DynGroupedAggregateKernel,
273    ) {
274        let fn_id = agg_fn_id.into();
275        self.grouped_kernels.insert(fn_id, kernel)
276    }
277
278    /// Returns the grouped aggregate kernel registered for `array_id` and `agg_fn_id`, if any.
279    ///
280    /// These kernels are matched against each intermediate element encoding while the grouped
281    /// accumulator executes the element array.
282    pub fn find_grouped_encoding_kernel(
283        &self,
284        array_id: impl Into<ArrayId>,
285        agg_fn_id: impl Into<AggregateFnId>,
286    ) -> Option<&'static dyn DynGroupedAggregateKernel> {
287        let id = array_id.into();
288        let fn_id = agg_fn_id.into();
289        self.grouped_encoding_kernels
290            .read(|kernels| kernels.get(&(id, fn_id)).copied())
291    }
292
293    /// Registers a grouped aggregate kernel for a specific aggregate function and array encoding.
294    pub fn register_grouped_encoding_kernel(
295        &self,
296        array_id: impl Into<ArrayId>,
297        agg_fn_id: impl Into<AggregateFnId>,
298        kernel: &'static dyn DynGroupedAggregateKernel,
299    ) {
300        let id = array_id.into();
301        let fn_id = agg_fn_id.into();
302        self.grouped_encoding_kernels.insert((id, fn_id), kernel)
303    }
304
305    /// Captures the currently registered aggregate kernels, so repeated lookups skip the session
306    /// and registry loads.
307    pub(crate) fn kernels_snapshot(&self) -> AggregateKernels {
308        AggregateKernels {
309            kernels: self.kernels.snapshot(),
310            grouped_kernels: self.grouped_kernels.snapshot(),
311            grouped_encoding_kernels: self.grouped_encoding_kernels.snapshot(),
312        }
313    }
314}
315
316/// A point-in-time snapshot of the aggregate kernel registries of an [`AggregateFnSession`].
317///
318/// Lookups follow the same rules as the corresponding `find_*` methods on
319/// [`AggregateFnSession`].
320#[derive(Clone, Debug)]
321pub(crate) struct AggregateKernels {
322    kernels: Arc<HashMap<AggregateKernelKey, &'static dyn DynAggregateKernel>>,
323    grouped_kernels: Arc<HashMap<AggregateFnId, &'static dyn DynGroupedAggregateKernel>>,
324    grouped_encoding_kernels:
325        Arc<HashMap<GroupedEncodingKernelKey, &'static dyn DynGroupedAggregateKernel>>,
326}
327
328impl AggregateKernels {
329    /// See [`AggregateFnSession::find_aggregate_kernel`].
330    pub(crate) fn find_aggregate_kernel(
331        &self,
332        array_id: ArrayId,
333        agg_fn_id: AggregateFnId,
334    ) -> Option<&'static dyn DynAggregateKernel> {
335        lookup_aggregate_kernel(&self.kernels, array_id, agg_fn_id)
336    }
337
338    /// See [`AggregateFnSession::find_grouped_kernel`].
339    pub(crate) fn find_grouped_kernel(
340        &self,
341        agg_fn_id: AggregateFnId,
342    ) -> Option<&'static dyn DynGroupedAggregateKernel> {
343        self.grouped_kernels.get(&agg_fn_id).copied()
344    }
345
346    /// See [`AggregateFnSession::find_grouped_encoding_kernel`].
347    pub(crate) fn find_grouped_encoding_kernel(
348        &self,
349        array_id: ArrayId,
350        agg_fn_id: AggregateFnId,
351    ) -> Option<&'static dyn DynGroupedAggregateKernel> {
352        self.grouped_encoding_kernels
353            .get(&(array_id, agg_fn_id))
354            .copied()
355    }
356}
357
358fn lookup_aggregate_kernel(
359    kernels: &HashMap<AggregateKernelKey, &'static dyn DynAggregateKernel>,
360    array_id: ArrayId,
361    agg_fn_id: AggregateFnId,
362) -> Option<&'static dyn DynAggregateKernel> {
363    kernels
364        .get(&(array_id, Some(agg_fn_id)))
365        .or_else(|| kernels.get(&(array_id, None)))
366        .copied()
367}
368
369/// Extension trait for accessing aggregate function session data.
370pub trait AggregateFnSessionExt: SessionExt {
371    /// Returns the aggregate function session data.
372    fn aggregate_fns(&self) -> SessionGuard<'_, AggregateFnSession> {
373        self.get::<AggregateFnSession>()
374    }
375}
376impl<S: SessionExt> AggregateFnSessionExt for S {}