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

vortex-data / vortex / 16935267080

13 Aug 2025 11:00AM UTC coverage: 24.312% (-63.3%) from 87.658%
16935267080

Pull #4226

github

web-flow
Merge 81b48c7fb into baa6ea202
Pull Request #4226: Support converting TimestampTZ to and from duckdb

0 of 2 new or added lines in 1 file covered. (0.0%)

20666 existing lines in 469 files now uncovered.

8726 of 35892 relevant lines covered (24.31%)

147.74 hits per line

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

84.25
/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, StatsProvider};
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>> {
78✔
31
    let scalar = MIN_MAX_FN
78✔
32
        .invoke(&InvocationArgs {
78✔
33
            inputs: &[array.into()],
78✔
34
            options: &(),
78✔
35
        })?
78✔
36
        .unwrap_scalar()?;
78✔
37
    MinMaxResult::from_scalar(scalar)
78✔
38
}
78✔
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>> {
156✔
48
        if scalar.is_null() {
156✔
49
            Ok(None)
16✔
50
        } else {
51
            let min = scalar
140✔
52
                .as_struct()
140✔
53
                .field_by_idx(0)
140✔
54
                .vortex_expect("missing min field");
140✔
55
            let max = scalar
140✔
56
                .as_struct()
140✔
57
                .field_by_idx(1)
140✔
58
                .vortex_expect("missing max field");
140✔
59
            Ok(Some(MinMaxResult { min, max }))
140✔
60
        }
61
    }
156✔
62
}
63

64
pub struct MinMax;
65

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

74
        let return_dtype = self.return_dtype(args)?;
78✔
75

76
        match min_max_impl(array, kernels)? {
78✔
77
            None => Ok(Scalar::null(return_dtype).into()),
8✔
78
            Some(MinMaxResult { min, max }) => {
70✔
79
                assert!(
70✔
80
                    min <= max,
70✔
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
70✔
89
                    .statistics()
70✔
90
                    .set(Stat::Min, Precision::Exact(min.value().clone()));
70✔
91
                array
70✔
92
                    .statistics()
70✔
93
                    .set(Stat::Max, Precision::Exact(max.value().clone()));
70✔
94

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

101
    fn return_dtype(&self, args: &InvocationArgs) -> VortexResult<DType> {
156✔
102
        let UnaryArgs { array, .. } = UnaryArgs::<()>::try_from(args)?;
156✔
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(
156✔
107
            StructFields::new(
156✔
108
                ["min", "max"].into(),
156✔
109
                vec![array.dtype().clone(), array.dtype().clone()],
156✔
110
            ),
156✔
111
            Nullability::Nullable,
156✔
112
        ))
156✔
113
    }
156✔
114

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

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

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

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

141
    let min = array
78✔
142
        .statistics()
78✔
143
        .get(Stat::Min)
78✔
144
        .and_then(Precision::as_exact);
78✔
145
    let max = array
78✔
146
        .statistics()
78✔
147
        .get(Stat::Max)
78✔
148
        .and_then(Precision::as_exact);
78✔
149

150
    if let Some((min, max)) = min.zip(max) {
78✔
UNCOV
151
        return Ok(Some(MinMaxResult { min, max }));
×
152
    }
78✔
153

154
    let args = InvocationArgs {
78✔
155
        inputs: &[array.into()],
78✔
156
        options: &(),
78✔
157
    };
78✔
158
    for kernel in kernels {
218✔
159
        if let Some(output) = kernel.invoke(&args)? {
218✔
160
            return MinMaxResult::from_scalar(output.unwrap_scalar()?);
78✔
161
        }
140✔
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
}
78✔
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>> {
218✔
194
        let inputs = UnaryArgs::<()>::try_from(args)?;
218✔
195
        let Some(array) = inputs.array.as_opt::<V>() else {
218✔
196
            return Ok(None);
140✔
197
        };
198
        let dtype = DType::Struct(
78✔
199
            StructFields::new(
78✔
200
                ["min", "max"].into(),
78✔
201
                vec![array.dtype().clone(), array.dtype().clone()],
78✔
202
            ),
78✔
203
            Nullability::Nullable,
78✔
204
        );
78✔
205
        Ok(Some(match V::min_max(&self.0, array)? {
78✔
206
            None => Scalar::null(dtype).into(),
8✔
207
            Some(MinMaxResult { min, max }) => Scalar::struct_(dtype, vec![min, max]).into(),
70✔
208
        }))
209
    }
218✔
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 · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc