Skip to main content

vortex_array/stats/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Stats as they are stored on arrays.
5
6use std::sync::Arc;
7
8use parking_lot::RwLock;
9use vortex_error::VortexError;
10use vortex_error::VortexResult;
11use vortex_error::vortex_panic;
12
13use super::MutTypedStatsSetRef;
14use super::StatsSet;
15use super::StatsSetIntoIter;
16use super::TypedStatsSetRef;
17use crate::ArrayRef;
18use crate::LEGACY_SESSION;
19use crate::VortexSessionExecute;
20use crate::aggregate_fn::fns::is_constant::is_constant;
21use crate::aggregate_fn::fns::is_sorted::is_sorted;
22use crate::aggregate_fn::fns::is_sorted::is_strict_sorted;
23use crate::aggregate_fn::fns::min_max::MinMaxResult;
24use crate::aggregate_fn::fns::min_max::min_max;
25use crate::aggregate_fn::fns::nan_count::nan_count;
26use crate::aggregate_fn::fns::sum::sum;
27use crate::builders::builder_with_capacity;
28use crate::expr::stats::Precision;
29use crate::expr::stats::Stat;
30use crate::expr::stats::StatsProvider;
31use crate::scalar::Scalar;
32use crate::scalar::ScalarValue;
33
34/// A shared [`StatsSet`] stored in an array. Can be shared by copies of the array and can also be mutated in place.
35// TODO(adamg): This is a very bad name.
36#[derive(Clone, Default, Debug)]
37pub struct ArrayStats {
38    inner: Arc<RwLock<StatsSet>>,
39}
40
41/// Reference to an array's [`StatsSet`]. Can be used to get and mutate the underlying stats.
42///
43/// Constructed by calling [`ArrayStats::to_ref`].
44pub struct StatsSetRef<'a> {
45    // We need to reference back to the array
46    dyn_array_ref: &'a ArrayRef,
47    array_stats: &'a ArrayStats,
48}
49
50impl ArrayStats {
51    pub fn to_ref<'a>(&'a self, array: &'a ArrayRef) -> StatsSetRef<'a> {
52        StatsSetRef {
53            dyn_array_ref: array,
54            array_stats: self,
55        }
56    }
57
58    pub fn set(&self, stat: Stat, value: Precision<ScalarValue>) {
59        self.inner.write().set(stat, value);
60    }
61
62    pub fn clear(&self, stat: Stat) {
63        self.inner.write().clear(stat);
64    }
65
66    pub fn retain(&self, stats: &[Stat]) {
67        self.inner.write().retain_only(stats);
68    }
69}
70
71impl From<StatsSet> for ArrayStats {
72    fn from(value: StatsSet) -> Self {
73        Self {
74            inner: Arc::new(RwLock::new(value)),
75        }
76    }
77}
78
79impl From<ArrayStats> for StatsSet {
80    fn from(value: ArrayStats) -> Self {
81        value.inner.read().clone()
82    }
83}
84
85impl StatsSetRef<'_> {
86    pub(crate) fn replace(&self, stats: StatsSet) {
87        *self.array_stats.inner.write() = stats;
88    }
89
90    pub fn set_iter(&self, iter: StatsSetIntoIter) {
91        let mut guard = self.array_stats.inner.write();
92        for (stat, value) in iter {
93            guard.set(stat, value);
94        }
95    }
96
97    pub fn inherit_from(&self, stats: StatsSetRef<'_>) {
98        // Only inherit if the underlying stats are different
99        if !Arc::ptr_eq(&self.array_stats.inner, &stats.array_stats.inner) {
100            stats.with_iter(|iter| self.inherit(iter));
101        }
102    }
103
104    pub fn inherit<'a>(&self, iter: impl Iterator<Item = &'a (Stat, Precision<ScalarValue>)>) {
105        let mut guard = self.array_stats.inner.write();
106        for (stat, value) in iter {
107            if !value.is_exact() {
108                if !guard.get(*stat).is_some_and(|v| v.is_exact()) {
109                    guard.set(*stat, value.clone());
110                }
111            } else {
112                guard.set(*stat, value.clone());
113            }
114        }
115    }
116
117    pub fn with_typed_stats_set<U, F: FnOnce(TypedStatsSetRef) -> U>(&self, apply: F) -> U {
118        apply(
119            self.array_stats
120                .inner
121                .read()
122                .as_typed_ref(self.dyn_array_ref.dtype()),
123        )
124    }
125
126    pub fn with_mut_typed_stats_set<U, F: FnOnce(MutTypedStatsSetRef) -> U>(&self, apply: F) -> U {
127        apply(
128            self.array_stats
129                .inner
130                .write()
131                .as_mut_typed_ref(self.dyn_array_ref.dtype()),
132        )
133    }
134
135    pub fn to_owned(&self) -> StatsSet {
136        self.array_stats.inner.read().clone()
137    }
138
139    /// Returns a clone of the underlying [`ArrayStats`].
140    ///
141    /// Since [`ArrayStats`] uses `Arc` internally, this is a cheap reference-count increment.
142    pub fn to_array_stats(&self) -> ArrayStats {
143        self.array_stats.clone()
144    }
145
146    pub fn with_iter<
147        F: for<'a> FnOnce(&mut dyn Iterator<Item = &'a (Stat, Precision<ScalarValue>)>) -> R,
148        R,
149    >(
150        &self,
151        f: F,
152    ) -> R {
153        let lock = self.array_stats.inner.read();
154        f(&mut lock.iter())
155    }
156
157    pub fn compute_stat(&self, stat: Stat) -> VortexResult<Option<Scalar>> {
158        let mut ctx = LEGACY_SESSION.create_execution_ctx();
159
160        // If it's already computed and exact, we can return it.
161        if let Some(Precision::Exact(s)) = self.get(stat) {
162            return Ok(Some(s));
163        }
164
165        Ok(match stat {
166            Stat::Min => {
167                min_max(self.dyn_array_ref, &mut ctx)?.map(|MinMaxResult { min, max: _ }| min)
168            }
169            Stat::Max => {
170                min_max(self.dyn_array_ref, &mut ctx)?.map(|MinMaxResult { min: _, max }| max)
171            }
172            Stat::Sum => {
173                Stat::Sum
174                    .dtype(self.dyn_array_ref.dtype())
175                    .is_some()
176                    .then(|| {
177                        // Sum is supported for this dtype.
178                        sum(self.dyn_array_ref, &mut ctx)
179                    })
180                    .transpose()?
181            }
182            Stat::NullCount => self.dyn_array_ref.invalid_count().ok().map(Into::into),
183            Stat::IsConstant => {
184                if self.dyn_array_ref.is_empty() {
185                    None
186                } else {
187                    Some(is_constant(self.dyn_array_ref, &mut ctx)?.into())
188                }
189            }
190            Stat::IsSorted => Some(is_sorted(self.dyn_array_ref, &mut ctx)?.into()),
191            Stat::IsStrictSorted => Some(is_strict_sorted(self.dyn_array_ref, &mut ctx)?.into()),
192            Stat::UncompressedSizeInBytes => {
193                let mut builder =
194                    builder_with_capacity(self.dyn_array_ref.dtype(), self.dyn_array_ref.len());
195                unsafe {
196                    builder.extend_from_array_unchecked(self.dyn_array_ref);
197                }
198                let nbytes = builder.finish().nbytes();
199                self.set(stat, Precision::exact(nbytes));
200                Some(nbytes.into())
201            }
202            Stat::NaNCount => {
203                Stat::NaNCount
204                    .dtype(self.dyn_array_ref.dtype())
205                    .is_some()
206                    .then(|| {
207                        // NaNCount is supported for this dtype.
208                        nan_count(self.dyn_array_ref, &mut ctx)
209                    })
210                    .transpose()?
211                    .map(|s| s.into())
212            }
213        })
214    }
215
216    pub fn compute_all(&self, stats: &[Stat]) -> VortexResult<StatsSet> {
217        let mut stats_set = StatsSet::default();
218        for &stat in stats {
219            if let Some(s) = self.compute_stat(stat)?
220                && let Some(value) = s.into_value()
221            {
222                stats_set.set(stat, Precision::exact(value));
223            }
224        }
225        Ok(stats_set)
226    }
227}
228
229impl StatsSetRef<'_> {
230    pub fn compute_as<U: for<'a> TryFrom<&'a Scalar, Error = VortexError>>(
231        &self,
232        stat: Stat,
233    ) -> Option<U> {
234        self.compute_stat(stat)
235            .inspect_err(|e| tracing::warn!("Failed to compute stat {stat}: {e}"))
236            .ok()
237            .flatten()
238            .map(|s| U::try_from(&s))
239            .transpose()
240            .unwrap_or_else(|err| {
241                vortex_panic!(
242                    err,
243                    "Failed to compute stat {} as {}",
244                    stat,
245                    std::any::type_name::<U>()
246                )
247            })
248    }
249
250    pub fn set(&self, stat: Stat, value: Precision<ScalarValue>) {
251        self.array_stats.set(stat, value);
252    }
253
254    pub fn clear(&self, stat: Stat) {
255        self.array_stats.clear(stat);
256    }
257
258    pub fn compute_min<U: for<'a> TryFrom<&'a Scalar, Error = VortexError>>(&self) -> Option<U> {
259        self.compute_as(Stat::Min)
260    }
261
262    pub fn compute_max<U: for<'a> TryFrom<&'a Scalar, Error = VortexError>>(&self) -> Option<U> {
263        self.compute_as(Stat::Max)
264    }
265
266    pub fn compute_is_sorted(&self) -> Option<bool> {
267        self.compute_as(Stat::IsSorted)
268    }
269
270    pub fn compute_is_strict_sorted(&self) -> Option<bool> {
271        self.compute_as(Stat::IsStrictSorted)
272    }
273
274    pub fn compute_is_constant(&self) -> Option<bool> {
275        self.compute_as(Stat::IsConstant)
276    }
277
278    pub fn compute_null_count(&self) -> Option<usize> {
279        self.compute_as(Stat::NullCount)
280    }
281
282    pub fn compute_uncompressed_size_in_bytes(&self) -> Option<usize> {
283        self.compute_as(Stat::UncompressedSizeInBytes)
284    }
285}
286
287impl StatsProvider for StatsSetRef<'_> {
288    fn get(&self, stat: Stat) -> Option<Precision<Scalar>> {
289        self.array_stats
290            .inner
291            .read()
292            .as_typed_ref(self.dyn_array_ref.dtype())
293            .get(stat)
294    }
295
296    fn len(&self) -> usize {
297        self.array_stats.inner.read().len()
298    }
299}