• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vortex-data / vortex / 16728097825

04 Aug 2025 04:00PM UTC coverage: 48.355% (-35.1%) from 83.429%
16728097825

Pull #4108

github

web-flow
Merge 1b2d27fd8 into 649ba9576
Pull Request #4108: perf[vortex-array]: use all_valid instead of `invalid_count() == 0`

1 of 1 new or added line in 1 file covered. (100.0%)

11596 existing lines in 378 files now uncovered.

18635 of 38538 relevant lines covered (48.35%)

151786.4 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.38
/vortex-array/src/compute/min_max.rs
1
// SPDX-License-Identifier: Apache-2.0
2
// SPDX-FileCopyrightText: Copyright the Vortex contributors
3

4
use std::sync::LazyLock;
5

6
use arcref::ArcRef;
7
use vortex_dtype::{DType, Nullability, StructFields};
8
use vortex_error::{VortexExpect, VortexResult, vortex_bail};
9
use vortex_scalar::Scalar;
10

11
use crate::Array;
12
use crate::arrays::ConstantVTable;
13
use crate::compute::{ComputeFn, ComputeFnVTable, InvocationArgs, Kernel, Output, UnaryArgs};
14
use crate::stats::{Precision, Stat, StatsProviderExt};
15
use crate::vtable::VTable;
16

17
static MIN_MAX_FN: LazyLock<ComputeFn> = LazyLock::new(|| {
2✔
18
    let compute = ComputeFn::new("min_max".into(), ArcRef::new_ref(&MinMax));
2✔
19
    for kernel in inventory::iter::<MinMaxKernelRef> {
28✔
20
        compute.register_kernel(kernel.0.clone());
26✔
21
    }
26✔
22
    compute
2✔
23
});
2✔
24

25
/// The minimum and maximum non-null values of an array, or None if there are no non-null values.
26
///
27
/// The return value dtype is the non-nullable version of the array dtype.
28
///
29
/// This will update the stats set of this array (as a side effect).
30
pub fn min_max(array: &dyn Array) -> VortexResult<Option<MinMaxResult>> {
12,186✔
31
    let scalar = MIN_MAX_FN
12,186✔
32
        .invoke(&InvocationArgs {
12,186✔
33
            inputs: &[array.into()],
12,186✔
34
            options: &(),
12,186✔
35
        })?
12,186✔
36
        .unwrap_scalar()?;
12,186✔
37
    MinMaxResult::from_scalar(scalar)
12,186✔
38
}
12,186✔
39

40
#[derive(Debug, Clone, PartialEq, Eq)]
41
pub struct MinMaxResult {
42
    pub min: Scalar,
43
    pub max: Scalar,
44
}
45

46
impl MinMaxResult {
47
    pub fn from_scalar(scalar: Scalar) -> VortexResult<Option<Self>> {
24,222✔
48
        if scalar.is_null() {
24,222✔
49
            Ok(None)
488✔
50
        } else {
51
            let min = scalar
23,734✔
52
                .as_struct()
23,734✔
53
                .field_by_idx(0)
23,734✔
54
                .vortex_expect("missing min field");
23,734✔
55
            let max = scalar
23,734✔
56
                .as_struct()
23,734✔
57
                .field_by_idx(1)
23,734✔
58
                .vortex_expect("missing max field");
23,734✔
59
            Ok(Some(MinMaxResult { min, max }))
23,734✔
60
        }
61
    }
24,222✔
62
}
63

64
pub struct MinMax;
65

66
impl ComputeFnVTable for MinMax {
67
    fn invoke(
12,186✔
68
        &self,
12,186✔
69
        args: &InvocationArgs,
12,186✔
70
        kernels: &[ArcRef<dyn Kernel>],
12,186✔
71
    ) -> VortexResult<Output> {
12,186✔
72
        let UnaryArgs { array, .. } = UnaryArgs::<()>::try_from(args)?;
12,186✔
73

74
        let return_dtype = self.return_dtype(args)?;
12,186✔
75

76
        match min_max_impl(array, kernels)? {
12,186✔
77
            None => Ok(Scalar::null(return_dtype).into()),
244✔
78
            Some(MinMaxResult { min, max }) => {
11,942✔
79
                assert!(
11,942✔
80
                    min <= max,
11,942✔
81
                    "min > max: min={} max={} encoding={}",
×
82
                    min,
83
                    max,
84
                    array.encoding_id()
×
85
                );
86

87
                // Update the stats set with the computed min/max
88
                array
11,942✔
89
                    .statistics()
11,942✔
90
                    .set(Stat::Min, Precision::Exact(min.value().clone()));
11,942✔
91
                array
11,942✔
92
                    .statistics()
11,942✔
93
                    .set(Stat::Max, Precision::Exact(max.value().clone()));
11,942✔
94

95
                // Return the min/max as a struct scalar
96
                Ok(Scalar::struct_(return_dtype, vec![min, max]).into())
11,942✔
97
            }
98
        }
99
    }
12,186✔
100

101
    fn return_dtype(&self, args: &InvocationArgs) -> VortexResult<DType> {
24,372✔
102
        let UnaryArgs { array, .. } = UnaryArgs::<()>::try_from(args)?;
24,372✔
103

104
        // We return a min/max struct scalar, where the overall struct is nullable in the case
105
        // that the array is all null or empty.
106
        Ok(DType::Struct(
24,372✔
107
            StructFields::new(
24,372✔
108
                ["min", "max"].into(),
24,372✔
109
                vec![array.dtype().clone(), array.dtype().clone()],
24,372✔
110
            ),
24,372✔
111
            Nullability::Nullable,
24,372✔
112
        ))
24,372✔
113
    }
24,372✔
114

115
    fn return_len(&self, _args: &InvocationArgs) -> VortexResult<usize> {
12,186✔
116
        Ok(1)
12,186✔
117
    }
12,186✔
118

119
    fn is_elementwise(&self) -> bool {
12,186✔
120
        false
12,186✔
121
    }
12,186✔
122
}
123

124
fn min_max_impl(
12,186✔
125
    array: &dyn Array,
12,186✔
126
    kernels: &[ArcRef<dyn Kernel>],
12,186✔
127
) -> VortexResult<Option<MinMaxResult>> {
12,186✔
128
    if array.is_empty() || array.valid_count()? == 0 {
12,186✔
UNCOV
129
        return Ok(None);
×
130
    }
12,186✔
131

132
    if let Some(array) = array.as_opt::<ConstantVTable>() {
12,186✔
UNCOV
133
        if !array.scalar().is_null() {
×
UNCOV
134
            return Ok(Some(MinMaxResult {
×
UNCOV
135
                min: array.scalar().clone(),
×
UNCOV
136
                max: array.scalar().clone(),
×
UNCOV
137
            }));
×
138
        }
×
139
    }
12,186✔
140

141
    let min = array
12,186✔
142
        .statistics()
12,186✔
143
        .get_scalar(Stat::Min, array.dtype())
12,186✔
144
        .and_then(Precision::as_exact);
12,186✔
145
    let max = array
12,186✔
146
        .statistics()
12,186✔
147
        .get_scalar(Stat::Max, array.dtype())
12,186✔
148
        .and_then(Precision::as_exact);
12,186✔
149

150
    if let Some((min, max)) = min.zip(max) {
12,186✔
151
        return Ok(Some(MinMaxResult { min, max }));
150✔
152
    }
12,036✔
153

154
    let args = InvocationArgs {
12,036✔
155
        inputs: &[array.into()],
12,036✔
156
        options: &(),
12,036✔
157
    };
12,036✔
158
    for kernel in kernels {
61,126✔
159
        if let Some(output) = kernel.invoke(&args)? {
61,126✔
160
            return MinMaxResult::from_scalar(output.unwrap_scalar()?);
12,036✔
161
        }
49,090✔
162
    }
UNCOV
163
    if let Some(output) = array.invoke(&MIN_MAX_FN, &args)? {
×
164
        return MinMaxResult::from_scalar(output.unwrap_scalar()?);
×
UNCOV
165
    }
×
166

UNCOV
167
    if !array.is_canonical() {
×
UNCOV
168
        let array = array.to_canonical()?;
×
UNCOV
169
        return min_max(array.as_ref());
×
170
    }
×
171

172
    vortex_bail!(NotImplemented: "min_max", array.encoding_id());
×
173
}
12,186✔
174

175
/// The minimum and maximum non-null values of an array, or None if there are no non-null values.
176
pub trait MinMaxKernel: VTable {
177
    fn min_max(&self, array: &Self::Array) -> VortexResult<Option<MinMaxResult>>;
178
}
179

180
pub struct MinMaxKernelRef(ArcRef<dyn Kernel>);
181
inventory::collect!(MinMaxKernelRef);
182

183
#[derive(Debug)]
184
pub struct MinMaxKernelAdapter<V: VTable>(pub V);
185

186
impl<V: VTable + MinMaxKernel> MinMaxKernelAdapter<V> {
187
    pub const fn lift(&'static self) -> MinMaxKernelRef {
×
188
        MinMaxKernelRef(ArcRef::new_ref(self))
×
189
    }
×
190
}
191

192
impl<V: VTable + MinMaxKernel> Kernel for MinMaxKernelAdapter<V> {
193
    fn invoke(&self, args: &InvocationArgs) -> VortexResult<Option<Output>> {
61,126✔
194
        let inputs = UnaryArgs::<()>::try_from(args)?;
61,126✔
195
        let Some(array) = inputs.array.as_opt::<V>() else {
61,126✔
196
            return Ok(None);
49,090✔
197
        };
198
        let dtype = DType::Struct(
12,036✔
199
            StructFields::new(
12,036✔
200
                ["min", "max"].into(),
12,036✔
201
                vec![array.dtype().clone(), array.dtype().clone()],
12,036✔
202
            ),
12,036✔
203
            Nullability::Nullable,
12,036✔
204
        );
12,036✔
205
        Ok(Some(match V::min_max(&self.0, array)? {
12,036✔
206
            None => Scalar::null(dtype).into(),
244✔
207
            Some(MinMaxResult { min, max }) => Scalar::struct_(dtype, vec![min, max]).into(),
11,792✔
208
        }))
209
    }
61,126✔
210
}
211

212
#[cfg(test)]
213
mod tests {
214
    use arrow_buffer::BooleanBuffer;
215
    use vortex_buffer::buffer;
216

217
    use crate::arrays::{BoolArray, NullArray, PrimitiveArray};
218
    use crate::compute::{MinMaxResult, min_max};
219
    use crate::validity::Validity;
220

221
    #[test]
222
    fn test_prim_max() {
223
        let p = PrimitiveArray::new(buffer![1, 2, 3], Validity::NonNullable);
224
        assert_eq!(
225
            min_max(p.as_ref()).unwrap(),
226
            Some(MinMaxResult {
227
                min: 1.into(),
228
                max: 3.into()
229
            })
230
        );
231
    }
232

233
    #[test]
234
    fn test_bool_max() {
235
        let p = BoolArray::new(
236
            BooleanBuffer::from([true, true, true].as_slice()),
237
            Validity::NonNullable,
238
        );
239
        assert_eq!(
240
            min_max(p.as_ref()).unwrap(),
241
            Some(MinMaxResult {
242
                min: true.into(),
243
                max: true.into()
244
            })
245
        );
246

247
        let p = BoolArray::new(
248
            BooleanBuffer::from([false, false, false].as_slice()),
249
            Validity::NonNullable,
250
        );
251
        assert_eq!(
252
            min_max(p.as_ref()).unwrap(),
253
            Some(MinMaxResult {
254
                min: false.into(),
255
                max: false.into()
256
            })
257
        );
258

259
        let p = BoolArray::new(
260
            BooleanBuffer::from([false, true, false].as_slice()),
261
            Validity::NonNullable,
262
        );
263
        assert_eq!(
264
            min_max(p.as_ref()).unwrap(),
265
            Some(MinMaxResult {
266
                min: false.into(),
267
                max: true.into()
268
            })
269
        );
270
    }
271

272
    #[test]
273
    fn test_null() {
274
        let p = NullArray::new(1);
275
        assert_eq!(min_max(p.as_ref()).unwrap(), None);
276
    }
277
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc