vortex-array 0.59.4

Vortex in memory columnar data format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use std::any::Any;
use std::sync::LazyLock;

use arcref::ArcRef;
use vortex_dtype::DType;
use vortex_dtype::Nullability;
use vortex_error::VortexError;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_err;

use crate::Array;
use crate::arrays::ConstantVTable;
use crate::arrays::NullVTable;
use crate::compute::ComputeFn;
use crate::compute::ComputeFnVTable;
use crate::compute::InvocationArgs;
use crate::compute::Kernel;
use crate::compute::Options;
use crate::compute::Output;
use crate::expr::stats::Precision;
use crate::expr::stats::Stat;
use crate::expr::stats::StatsProviderExt;
use crate::scalar::Scalar;
use crate::vtable::VTable;

static IS_SORTED_FN: LazyLock<ComputeFn> = LazyLock::new(|| {
    let compute = ComputeFn::new("is_sorted".into(), ArcRef::new_ref(&IsSorted));
    for kernel in inventory::iter::<IsSortedKernelRef> {
        compute.register_kernel(kernel.0.clone());
    }
    compute
});

pub(crate) fn warm_up_vtable() -> usize {
    IS_SORTED_FN.kernels().len()
}

pub fn is_sorted(array: &dyn Array) -> VortexResult<Option<bool>> {
    is_sorted_opts(array, false)
}

pub fn is_strict_sorted(array: &dyn Array) -> VortexResult<Option<bool>> {
    is_sorted_opts(array, true)
}

pub fn is_sorted_opts(array: &dyn Array, strict: bool) -> VortexResult<Option<bool>> {
    Ok(IS_SORTED_FN
        .invoke(&InvocationArgs {
            inputs: &[array.into()],
            options: &IsSortedOptions { strict },
        })?
        .unwrap_scalar()?
        .as_bool()
        .value())
}

struct IsSorted;
impl ComputeFnVTable for IsSorted {
    fn invoke(
        &self,
        args: &InvocationArgs,
        kernels: &[ArcRef<dyn Kernel>],
    ) -> VortexResult<Output> {
        let IsSortedArgs { array, strict } = IsSortedArgs::try_from(args)?;

        // We currently don't support sorting struct arrays.
        if array.dtype().is_struct() {
            let scalar: Scalar = Some(false).into();
            return Ok(scalar.into());
        }

        let is_sorted = if strict {
            if let Some(Precision::Exact(value)) =
                array.statistics().get_as::<bool>(Stat::IsStrictSorted)
            {
                let scalar: Scalar = Some(value).into();
                return Ok(scalar.into());
            }

            let is_strict_sorted = is_sorted_impl(array, kernels, true)?;
            let array_stats = array.statistics();

            if is_strict_sorted.is_some() {
                if is_strict_sorted.unwrap_or(false) {
                    array_stats.set(Stat::IsSorted, Precision::Exact(true.into()));
                    array_stats.set(Stat::IsStrictSorted, Precision::Exact(true.into()));
                } else {
                    array_stats.set(Stat::IsStrictSorted, Precision::Exact(false.into()));
                }
            }

            is_strict_sorted
        } else {
            if let Some(Precision::Exact(value)) = array.statistics().get_as::<bool>(Stat::IsSorted)
            {
                let scalar: Scalar = Some(value).into();
                return Ok(scalar.into());
            }

            let is_sorted = is_sorted_impl(array, kernels, false)?;
            let array_stats = array.statistics();

            if is_sorted.is_some() {
                if is_sorted.unwrap_or(false) {
                    array_stats.set(Stat::IsSorted, Precision::Exact(true.into()));
                } else {
                    array_stats.set(Stat::IsSorted, Precision::Exact(false.into()));
                    array_stats.set(Stat::IsStrictSorted, Precision::Exact(false.into()));
                }
            }

            is_sorted
        };

        let scalar: Scalar = is_sorted.into();
        Ok(scalar.into())
    }

    fn return_dtype(&self, _args: &InvocationArgs) -> VortexResult<DType> {
        // We always return a nullable boolean where `null` indicates we couldn't determine
        // whether the array is constant.
        Ok(DType::Bool(Nullability::Nullable))
    }

    fn return_len(&self, _args: &InvocationArgs) -> VortexResult<usize> {
        Ok(1)
    }

    fn is_elementwise(&self) -> bool {
        true
    }
}

struct IsSortedArgs<'a> {
    array: &'a dyn Array,
    strict: bool,
}

impl<'a> TryFrom<&InvocationArgs<'a>> for IsSortedArgs<'a> {
    type Error = VortexError;

    fn try_from(value: &InvocationArgs<'a>) -> Result<Self, Self::Error> {
        if value.inputs.len() != 1 {
            vortex_bail!(
                "IsSorted function requires exactly one argument, got {}",
                value.inputs.len()
            );
        }
        let array = value.inputs[0]
            .array()
            .ok_or_else(|| vortex_err!("Invalid argument type for is sorted function"))?;
        let options = *value
            .options
            .as_any()
            .downcast_ref::<IsSortedOptions>()
            .ok_or_else(|| vortex_err!("Invalid options type for is sorted function"))?;

        Ok(IsSortedArgs {
            array,
            strict: options.strict,
        })
    }
}

#[derive(Clone, Copy)]
struct IsSortedOptions {
    strict: bool,
}

impl Options for IsSortedOptions {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

pub struct IsSortedKernelRef(ArcRef<dyn Kernel>);
inventory::collect!(IsSortedKernelRef);

#[derive(Debug)]
pub struct IsSortedKernelAdapter<V: VTable>(pub V);

impl<V: VTable + IsSortedKernel> IsSortedKernelAdapter<V> {
    pub const fn lift(&'static self) -> IsSortedKernelRef {
        IsSortedKernelRef(ArcRef::new_ref(self))
    }
}

impl<V: VTable + IsSortedKernel> Kernel for IsSortedKernelAdapter<V> {
    fn invoke(&self, args: &InvocationArgs) -> VortexResult<Option<Output>> {
        let IsSortedArgs { array, strict } = IsSortedArgs::try_from(args)?;
        let Some(array) = array.as_opt::<V>() else {
            return Ok(None);
        };

        let is_sorted = if strict {
            V::is_strict_sorted(&self.0, array)?
        } else {
            V::is_sorted(&self.0, array)?
        };

        let scalar: Scalar = is_sorted.into();
        Ok(Some(scalar.into()))
    }
}

pub trait IsSortedKernel: VTable {
    /// # Preconditions
    /// - The array's length is > 1.
    /// - The array is not encoded as `NullArray` or `ConstantArray`.
    /// - If doing a `strict` check, if the array is nullable, it'll have at most 1 null element
    ///   as the first item in the array.
    fn is_sorted(&self, array: &Self::Array) -> VortexResult<Option<bool>>;

    fn is_strict_sorted(&self, array: &Self::Array) -> VortexResult<Option<bool>>;
}

#[expect(
    clippy::wrong_self_convention,
    reason = "is_* naming follows Iterator::is_sorted convention"
)]
/// Helper methods to check sortedness with strictness
pub trait IsSortedIteratorExt: Iterator
where
    <Self as Iterator>::Item: PartialOrd,
{
    fn is_strict_sorted(self) -> bool
    where
        Self: Sized,
        Self::Item: PartialOrd,
    {
        self.is_sorted_by(|a, b| a < b)
    }
}

impl<T> IsSortedIteratorExt for T
where
    T: Iterator + ?Sized,
    T::Item: PartialOrd,
{
}

fn is_sorted_impl(
    array: &dyn Array,
    kernels: &[ArcRef<dyn Kernel>],
    strict: bool,
) -> VortexResult<Option<bool>> {
    // Arrays with 0 or 1 elements are strict sorted.
    if array.len() <= 1 {
        return Ok(Some(true));
    }

    // Constant and null arrays are always sorted, but not strict sorted.
    if array.is::<ConstantVTable>() || array.is::<NullVTable>() {
        return Ok(Some(!strict));
    }

    // Enforce strictness before we even try to check if the array is sorted.
    if strict {
        let invalid_count = array.invalid_count()?;
        match invalid_count {
            // We can keep going
            0 => {}
            // If we have a potential null value - it has to be the first one.
            1 => {
                if !array.is_invalid(0)? {
                    return Ok(Some(false));
                }
            }
            _ => return Ok(Some(false)),
        }
    }

    let args = InvocationArgs {
        inputs: &[array.into()],
        options: &IsSortedOptions { strict },
    };

    for kernel in kernels {
        if let Some(output) = kernel.invoke(&args)? {
            return Ok(output.unwrap_scalar()?.as_bool().value());
        }
    }

    if !array.is_canonical() {
        tracing::debug!(
            "No is_sorted implementation found for {}",
            array.encoding_id()
        );

        // Recurse to canonical implementation
        let array = array.to_canonical()?;

        return if strict {
            is_strict_sorted(array.as_ref())
        } else {
            is_sorted(array.as_ref())
        };
    }

    vortex_bail!(
        "No is_sorted function for canonical array: {}",
        array.encoding_id(),
    )
}

#[cfg(test)]
mod tests {
    use vortex_buffer::buffer;

    use crate::IntoArray;
    use crate::arrays::BoolArray;
    use crate::arrays::PrimitiveArray;
    use crate::compute::is_sorted;
    use crate::compute::is_strict_sorted;
    use crate::validity::Validity;
    #[test]
    fn test_is_sorted() {
        assert!(
            is_sorted(PrimitiveArray::new(buffer!(0, 1, 2, 3), Validity::AllValid).as_ref())
                .unwrap()
                .unwrap()
        );
        assert!(
            is_sorted(
                PrimitiveArray::new(
                    buffer!(0, 1, 2, 3),
                    Validity::Array(BoolArray::from_iter([false, true, true, true]).into_array())
                )
                .as_ref()
            )
            .unwrap()
            .unwrap()
        );
        assert!(
            !is_sorted(
                PrimitiveArray::new(
                    buffer!(0, 1, 2, 3),
                    Validity::Array(BoolArray::from_iter([true, false, true, true]).into_array())
                )
                .as_ref()
            )
            .unwrap()
            .unwrap()
        );

        assert!(
            !is_sorted(PrimitiveArray::new(buffer!(0, 1, 3, 2), Validity::AllValid).as_ref())
                .unwrap()
                .unwrap()
        );
        assert!(
            !is_sorted(
                PrimitiveArray::new(
                    buffer!(0, 1, 3, 2),
                    Validity::Array(BoolArray::from_iter([false, true, true, true]).into_array()),
                )
                .as_ref()
            )
            .unwrap()
            .unwrap()
        );
    }

    #[test]
    fn test_is_strict_sorted() {
        assert!(
            is_strict_sorted(PrimitiveArray::new(buffer!(0, 1, 2, 3), Validity::AllValid).as_ref())
                .unwrap()
                .unwrap()
        );
        assert!(
            is_strict_sorted(
                PrimitiveArray::new(
                    buffer!(0, 1, 2, 3),
                    Validity::Array(BoolArray::from_iter([false, true, true, true]).into_array())
                )
                .as_ref()
            )
            .unwrap()
            .unwrap()
        );
        assert!(
            !is_strict_sorted(
                PrimitiveArray::new(
                    buffer!(0, 1, 2, 3),
                    Validity::Array(BoolArray::from_iter([true, false, true, true]).into_array()),
                )
                .as_ref()
            )
            .unwrap()
            .unwrap()
        );

        assert!(
            !is_strict_sorted(
                PrimitiveArray::new(
                    buffer!(0, 1, 3, 2),
                    Validity::Array(BoolArray::from_iter([false, true, true, true]).into_array()),
                )
                .as_ref()
            )
            .unwrap()
            .unwrap()
        );
    }
}