Skip to main content

vortex_array/
canonical.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Encodings that enable zero-copy sharing of data with Arrow.
5
6use std::any::TypeId;
7use std::sync::Arc;
8
9use vortex_buffer::BitBuffer;
10use vortex_buffer::Buffer;
11use vortex_error::VortexExpect;
12use vortex_error::VortexResult;
13use vortex_error::vortex_ensure;
14use vortex_error::vortex_panic;
15
16use crate::ArrayRef;
17use crate::ArraySlots;
18use crate::Executable;
19use crate::ExecutionCtx;
20use crate::IntoArray;
21use crate::array::ArrayView;
22use crate::array::VTable;
23use crate::array::child_to_validity;
24use crate::arrays::Bool;
25use crate::arrays::BoolArray;
26use crate::arrays::Decimal;
27use crate::arrays::DecimalArray;
28use crate::arrays::Extension;
29use crate::arrays::ExtensionArray;
30use crate::arrays::FixedSizeList;
31use crate::arrays::FixedSizeListArray;
32use crate::arrays::ListView;
33use crate::arrays::ListViewArray;
34use crate::arrays::Map;
35use crate::arrays::MapArray;
36use crate::arrays::Null;
37use crate::arrays::NullArray;
38use crate::arrays::Primitive;
39use crate::arrays::PrimitiveArray;
40use crate::arrays::Struct;
41use crate::arrays::StructArray;
42use crate::arrays::Union;
43use crate::arrays::UnionArray;
44use crate::arrays::VarBinView;
45use crate::arrays::VarBinViewArray;
46use crate::arrays::Variant;
47use crate::arrays::VariantArray;
48use crate::arrays::bool::BoolArraySlotsExt;
49use crate::arrays::bool::BoolDataParts;
50use crate::arrays::decimal::DecimalDataParts;
51use crate::arrays::extension::ExtensionArrayExt;
52use crate::arrays::fixed_size_list::FixedSizeListArrayExt;
53use crate::arrays::listview::ListViewDataParts;
54use crate::arrays::listview::ListViewRebuildMode;
55use crate::arrays::map::MapArrayExt;
56use crate::arrays::map::MapArraySlotsExt;
57use crate::arrays::primitive::PrimitiveDataParts;
58use crate::arrays::struct_::StructDataParts;
59use crate::arrays::union::UnionDataParts;
60use crate::arrays::varbinview::VarBinViewDataParts;
61use crate::arrays::variant::VariantArraySlotsExt;
62use crate::builders::VariantBuilder;
63use crate::dtype::DType;
64use crate::dtype::NativePType;
65use crate::dtype::Nullability;
66use crate::dtype::PType;
67use crate::match_each_decimal_value_type;
68use crate::match_each_native_ptype;
69use crate::matcher::Matcher;
70use crate::validity::Validity;
71
72/// An enum capturing the default uncompressed encodings for each [Vortex type](DType).
73///
74/// Any array can be decoded into canonical form via the `to_canonical`
75/// trait method. This is the simplest encoding for a type, and will not be compressed but may
76/// contain compressed child arrays.
77///
78/// Canonical form is useful for doing type-specific compute where you need to know that all
79/// elements are laid out decompressed and contiguous in memory.
80///
81/// Each `Canonical` variant has a corresponding [`DType`] variant, with the notable exception of
82/// [`Canonical::VarBinView`], which is the canonical encoding for both [`DType::Utf8`] and
83/// [`DType::Binary`].
84///
85/// # Laziness
86///
87/// Canonical form is not recursive, so while a `StructArray` is the canonical format for any
88/// `Struct` type, individual column child arrays may still be compressed. This allows
89/// compute over Vortex arrays to push decoding as late as possible, and ideally many child arrays
90/// never need to be decoded into canonical form at all depending on the compute.
91///
92/// # Arrow interoperability
93///
94/// Most Vortex canonical encodings have an equivalent Arrow encoding that can be built zero-copy,
95/// and the corresponding Arrow array types can also be built directly. Map array Arrow transport is
96/// not implemented yet, and [`UnionArray`]'s independent top-level validity cannot be represented
97/// directly by an Arrow union.
98///
99/// The full list of canonical types and their equivalent Arrow array types are:
100///
101/// * `NullArray`: `arrow_array::NullArray`
102/// * `BoolArray`: `arrow_array::BooleanArray`
103/// * `PrimitiveArray`: `arrow_array::PrimitiveArray`
104/// * `DecimalArray`: `arrow_array::Decimal128Array` and `arrow_array::Decimal256Array`
105/// * `VarBinViewArray`: `arrow_array::GenericByteViewArray`
106/// * `ListViewArray`: `arrow_array::ListViewArray`
107/// * `MapArray`: Vortex `ListView<Struct<key, value>>` storage
108/// * `FixedSizeListArray`: `arrow_array::FixedSizeListArray`
109/// * `StructArray`: `arrow_array::StructArray`
110///
111/// Vortex uses a logical type system, unlike Arrow which uses physical encodings for its types.
112/// As an example, there are at least six valid physical encodings for a `Utf8` array. This can
113/// create ambiguity.
114/// Thus, if you receive an Arrow array, compress it using Vortex, and then
115/// decompress it later to pass to a compute kernel, there are multiple suitable Arrow array
116/// variants to hold the data.
117///
118/// To disambiguate, we choose a canonical physical encoding for every Vortex [`DType`], which
119/// will correspond to an arrow-rs `arrow_schema::DataType`.
120///
121/// # Views support
122///
123/// Binary and String views, also known as "German strings" are a better encoding format for
124/// nearly all use-cases. Variable-length binary views are part of the Apache Arrow spec, and are
125/// fully supported by the Datafusion query engine. We use them as our canonical string encoding
126/// for all `Utf8` and `Binary` typed arrays in Vortex. They provide considerably faster filter
127/// execution than the core `StringArray` and `BinaryArray` types, at the expense of potentially
128/// needing garbage collection (`arrow_array::GenericByteViewArray::gc`) to clear unreferenced items
129/// from memory.
130///
131/// # For Developers
132///
133/// If you add another variant to this enum, make sure to update `canonical_kinds!`,
134/// and the fuzzer in `fuzz/fuzz_targets/array_ops.rs`.
135#[derive(Debug, Clone)]
136pub enum Canonical {
137    Null(NullArray),
138    Bool(BoolArray),
139    Primitive(PrimitiveArray),
140    Decimal(DecimalArray),
141    VarBinView(VarBinViewArray),
142    List(ListViewArray),
143    Map(MapArray),
144    FixedSizeList(FixedSizeListArray),
145    Struct(StructArray),
146    Union(UnionArray),
147    /// Canonical storage for extension dtypes, wrapping the canonical form of the storage dtype.
148    Extension(ExtensionArray),
149    /// Canonical storage for dynamic variant values, optionally with typed shredded paths.
150    Variant(VariantArray),
151}
152
153/// Match on every canonical variant and evaluate a code block on all variants
154macro_rules! match_each_canonical {
155    ($self:expr, | $ident:ident | $eval:expr) => {{
156        match $self {
157            Canonical::Null($ident) => $eval,
158            Canonical::Bool($ident) => $eval,
159            Canonical::Primitive($ident) => $eval,
160            Canonical::Decimal($ident) => $eval,
161            Canonical::VarBinView($ident) => $eval,
162            Canonical::List($ident) => $eval,
163            Canonical::Map($ident) => $eval,
164            Canonical::FixedSizeList($ident) => $eval,
165            Canonical::Struct($ident) => $eval,
166            Canonical::Union($ident) => $eval,
167            Canonical::Variant($ident) => $eval,
168            Canonical::Extension($ident) => $eval,
169        }
170    }};
171}
172
173impl Canonical {
174    /// Create an empty canonical array of the given dtype.
175    pub fn empty(dtype: &DType) -> Canonical {
176        match dtype {
177            DType::Null => Canonical::Null(NullArray::new(0)),
178            DType::Bool(n) => Canonical::Bool(unsafe {
179                BoolArray::new_unchecked(BitBuffer::empty(), Validity::from(n))
180            }),
181            DType::Primitive(ptype, n) => {
182                match_each_native_ptype!(ptype, |P| {
183                    Canonical::Primitive(unsafe {
184                        PrimitiveArray::new_unchecked(Buffer::<P>::empty(), Validity::from(n))
185                    })
186                })
187            }
188            DType::Decimal(decimal_type, n) => {
189                match_each_decimal_value_type!(decimal_type.canonical_values_type(), |D| {
190                    Canonical::Decimal(unsafe {
191                        DecimalArray::new_unchecked::<D>(
192                            Buffer::empty(),
193                            *decimal_type,
194                            Validity::from(n),
195                        )
196                    })
197                })
198            }
199            DType::Utf8(n) => Canonical::VarBinView(unsafe {
200                VarBinViewArray::new_unchecked(
201                    Buffer::empty(),
202                    Arc::new([]),
203                    dtype.clone(),
204                    Validity::from(n),
205                )
206            }),
207            DType::Binary(n) => Canonical::VarBinView(unsafe {
208                VarBinViewArray::new_unchecked(
209                    Buffer::empty(),
210                    Arc::new([]),
211                    dtype.clone(),
212                    Validity::from(n),
213                )
214            }),
215            DType::List(dtype, n) => Canonical::List(unsafe {
216                ListViewArray::new_unchecked(
217                    Canonical::empty(dtype).into_array(),
218                    Canonical::empty(&DType::Primitive(PType::U8, Nullability::NonNullable))
219                        .into_array(),
220                    Canonical::empty(&DType::Primitive(PType::U8, Nullability::NonNullable))
221                        .into_array(),
222                    Validity::from(n),
223                )
224                // An empty list view is trivially copyable to a list.
225                .with_zero_copy_to_list(true)
226            }),
227            DType::Map(map_dtype, nullability) => Canonical::Map(MapArray::new(
228                map_dtype.clone(),
229                Canonical::empty(&DType::List(
230                    Arc::new(map_dtype.entries_dtype()),
231                    *nullability,
232                ))
233                .into_listview(),
234            )),
235            DType::FixedSizeList(elem_dtype, list_size, null) => Canonical::FixedSizeList(unsafe {
236                FixedSizeListArray::new_unchecked(
237                    Canonical::empty(elem_dtype).into_array(),
238                    *list_size,
239                    Validity::from(null),
240                    0,
241                )
242            }),
243            DType::Struct(struct_dtype, n) => Canonical::Struct(unsafe {
244                StructArray::new_unchecked(
245                    struct_dtype
246                        .fields()
247                        .map(|f| Canonical::empty(&f).into_array())
248                        .collect::<Vec<_>>(),
249                    struct_dtype.clone(),
250                    0,
251                    Validity::from(n),
252                )
253            }),
254            DType::Union(variants, nullability) => {
255                Canonical::Union(UnionArray::empty(variants.clone(), *nullability))
256            }
257            DType::Variant(n) => Canonical::Variant(
258                VariantBuilder::new(*n)
259                    .finish_into_variant()
260                    .vortex_expect("an empty VariantBuilder finishes into an empty Variant"),
261            ),
262            DType::Extension(ext_dtype) => Canonical::Extension(ExtensionArray::new(
263                ext_dtype.clone(),
264                Canonical::empty(ext_dtype.storage_dtype()).into_array(),
265            )),
266        }
267    }
268
269    pub fn len(&self) -> usize {
270        match_each_canonical!(self, |arr| arr.len())
271    }
272
273    pub fn dtype(&self) -> &DType {
274        match_each_canonical!(self, |arr| arr.dtype())
275    }
276
277    pub fn is_empty(&self) -> bool {
278        match_each_canonical!(self, |arr| arr.is_empty())
279    }
280}
281
282impl Canonical {
283    /// Performs a (potentially expensive) compaction operation on the array before it is complete.
284    ///
285    /// This is mostly relevant for the variable-length types such as Utf8, Binary or List where
286    /// they can accumulate wasted space after slicing and taking operations.
287    ///
288    /// This operation can be very expensive and can result in things like allocations, full-scans
289    /// and copy operations.
290    pub fn compact(&self, ctx: &mut ExecutionCtx) -> VortexResult<Canonical> {
291        match self {
292            Canonical::Bool(array) => Ok(Canonical::Bool(array.trim_bits()?)),
293            Canonical::VarBinView(array) => Ok(Canonical::VarBinView(array.compact_buffers(ctx)?)),
294            Canonical::List(array) => Ok(Canonical::List(
295                array.rebuild(ListViewRebuildMode::TrimElements, ctx)?,
296            )),
297            Canonical::Map(array) => Ok(Canonical::Map(MapArray::new(
298                array.map_dtype().clone(),
299                array
300                    .entries()
301                    .as_::<ListView>()
302                    .into_owned()
303                    .rebuild(ListViewRebuildMode::TrimElements, ctx)?,
304            ))),
305            _ => Ok(self.clone()),
306        }
307    }
308}
309
310// Unwrap canonical type back down to specialized type.
311impl Canonical {
312    pub fn as_null(&self) -> &NullArray {
313        if let Canonical::Null(a) = self {
314            a
315        } else {
316            vortex_panic!("Cannot get NullArray from {:?}", &self)
317        }
318    }
319
320    pub fn into_null(self) -> NullArray {
321        if let Canonical::Null(a) = self {
322            a
323        } else {
324            vortex_panic!("Cannot unwrap NullArray from {:?}", &self)
325        }
326    }
327
328    pub fn as_bool(&self) -> &BoolArray {
329        if let Canonical::Bool(a) = self {
330            a
331        } else {
332            vortex_panic!("Cannot get BoolArray from {:?}", &self)
333        }
334    }
335
336    pub fn into_bool(self) -> BoolArray {
337        if let Canonical::Bool(a) = self {
338            a
339        } else {
340            vortex_panic!("Cannot unwrap BoolArray from {:?}", &self)
341        }
342    }
343
344    pub fn as_primitive(&self) -> &PrimitiveArray {
345        if let Canonical::Primitive(a) = self {
346            a
347        } else {
348            vortex_panic!("Cannot get PrimitiveArray from {:?}", &self)
349        }
350    }
351
352    pub fn into_primitive(self) -> PrimitiveArray {
353        if let Canonical::Primitive(a) = self {
354            a
355        } else {
356            vortex_panic!("Cannot unwrap PrimitiveArray from {:?}", &self)
357        }
358    }
359
360    pub fn as_decimal(&self) -> &DecimalArray {
361        if let Canonical::Decimal(a) = self {
362            a
363        } else {
364            vortex_panic!("Cannot get DecimalArray from {:?}", &self)
365        }
366    }
367
368    pub fn into_decimal(self) -> DecimalArray {
369        if let Canonical::Decimal(a) = self {
370            a
371        } else {
372            vortex_panic!("Cannot unwrap DecimalArray from {:?}", &self)
373        }
374    }
375
376    pub fn as_varbinview(&self) -> &VarBinViewArray {
377        if let Canonical::VarBinView(a) = self {
378            a
379        } else {
380            vortex_panic!("Cannot get VarBinViewArray from {:?}", &self)
381        }
382    }
383
384    pub fn into_varbinview(self) -> VarBinViewArray {
385        if let Canonical::VarBinView(a) = self {
386            a
387        } else {
388            vortex_panic!("Cannot unwrap VarBinViewArray from {:?}", &self)
389        }
390    }
391
392    pub fn as_listview(&self) -> &ListViewArray {
393        if let Canonical::List(a) = self {
394            a
395        } else {
396            vortex_panic!("Cannot get ListArray from {:?}", &self)
397        }
398    }
399
400    pub fn into_listview(self) -> ListViewArray {
401        if let Canonical::List(a) = self {
402            a
403        } else {
404            vortex_panic!("Cannot unwrap ListArray from {:?}", &self)
405        }
406    }
407
408    pub fn as_map(&self) -> &MapArray {
409        if let Canonical::Map(a) = self {
410            a
411        } else {
412            vortex_panic!("Cannot get MapArray from {:?}", &self)
413        }
414    }
415
416    pub fn into_map(self) -> MapArray {
417        if let Canonical::Map(a) = self {
418            a
419        } else {
420            vortex_panic!("Cannot unwrap MapArray from {:?}", &self)
421        }
422    }
423
424    pub fn as_fixed_size_list(&self) -> &FixedSizeListArray {
425        if let Canonical::FixedSizeList(a) = self {
426            a
427        } else {
428            vortex_panic!("Cannot get FixedSizeListArray from {:?}", &self)
429        }
430    }
431
432    pub fn into_fixed_size_list(self) -> FixedSizeListArray {
433        if let Canonical::FixedSizeList(a) = self {
434            a
435        } else {
436            vortex_panic!("Cannot unwrap FixedSizeListArray from {:?}", &self)
437        }
438    }
439
440    pub fn as_struct(&self) -> &StructArray {
441        if let Canonical::Struct(a) = self {
442            a
443        } else {
444            vortex_panic!("Cannot get StructArray from {:?}", &self)
445        }
446    }
447
448    pub fn into_struct(self) -> StructArray {
449        if let Canonical::Struct(a) = self {
450            a
451        } else {
452            vortex_panic!("Cannot unwrap StructArray from {:?}", &self)
453        }
454    }
455
456    /// Return this canonical array as a sparse [`UnionArray`].
457    pub fn as_union(&self) -> &UnionArray {
458        if let Canonical::Union(a) = self {
459            a
460        } else {
461            vortex_panic!("Cannot get UnionArray from {:?}", &self)
462        }
463    }
464
465    /// Unwrap this canonical array as a sparse [`UnionArray`].
466    pub fn into_union(self) -> UnionArray {
467        if let Canonical::Union(a) = self {
468            a
469        } else {
470            vortex_panic!("Cannot unwrap UnionArray from {:?}", &self)
471        }
472    }
473
474    pub fn as_extension(&self) -> &ExtensionArray {
475        if let Canonical::Extension(a) = self {
476            a
477        } else {
478            vortex_panic!("Cannot get ExtensionArray from {:?}", &self)
479        }
480    }
481
482    pub fn into_extension(self) -> ExtensionArray {
483        if let Canonical::Extension(a) = self {
484            a
485        } else {
486            vortex_panic!("Cannot unwrap ExtensionArray from {:?}", &self)
487        }
488    }
489}
490
491impl IntoArray for Canonical {
492    fn into_array(self) -> ArrayRef {
493        match_each_canonical!(self, |arr| arr.into_array())
494    }
495}
496
497impl From<Canonical> for ArrayRef {
498    fn from(value: Canonical) -> Self {
499        match_each_canonical!(value, |arr| arr.into_array())
500    }
501}
502
503/// Execute into [`Canonical`] by running `execute_until` with the [`AnyCanonical`] matcher.
504///
505/// Unlike executing into [`crate::Columnar`], this will fully expand constant arrays into their
506/// canonical form. Callers should prefer to execute into `Columnar` if they are able to optimize
507/// their use for constant arrays.
508impl Executable for Canonical {
509    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
510        let result = array.execute_until::<AnyCanonical>(ctx)?;
511        Ok(result
512            .as_opt::<AnyCanonical>()
513            .map(Canonical::from)
514            .vortex_expect("execute_until::<AnyCanonical> must return a canonical array"))
515    }
516}
517
518/// Recursively execute the array until it reaches canonical form along with its validity.
519///
520/// Callers should prefer to execute into `Columnar` instead of this specific target.
521/// This target is useful when preparing arrays for writing.
522pub struct CanonicalValidity(pub Canonical);
523
524impl Executable for CanonicalValidity {
525    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
526        match array.execute::<Canonical>(ctx)? {
527            n @ Canonical::Null(_) => Ok(CanonicalValidity(n)),
528            Canonical::Bool(b) => {
529                let validity = child_to_validity(b.validity_child(), b.dtype().nullability());
530                let len = b.len();
531                let BoolDataParts { bits, meta } = b.into_data().into_parts(len);
532                Ok(CanonicalValidity(Canonical::Bool(
533                    BoolArray::try_new_from_handle(
534                        bits,
535                        meta.offset(),
536                        meta.len(),
537                        validity.execute(ctx)?,
538                    )?,
539                )))
540            }
541            Canonical::Primitive(p) => {
542                let PrimitiveDataParts {
543                    ptype,
544                    buffer,
545                    validity,
546                } = p.into_data_parts();
547                Ok(CanonicalValidity(Canonical::Primitive(unsafe {
548                    PrimitiveArray::new_unchecked_from_handle(buffer, ptype, validity.execute(ctx)?)
549                })))
550            }
551            Canonical::Decimal(d) => {
552                let DecimalDataParts {
553                    decimal_dtype,
554                    values,
555                    values_type,
556                    validity,
557                } = d.into_data_parts();
558                Ok(CanonicalValidity(Canonical::Decimal(unsafe {
559                    DecimalArray::new_unchecked_handle(
560                        values,
561                        values_type,
562                        decimal_dtype,
563                        validity.execute(ctx)?,
564                    )
565                })))
566            }
567            Canonical::VarBinView(vbv) => {
568                let VarBinViewDataParts {
569                    dtype,
570                    buffers,
571                    views,
572                    validity,
573                } = vbv.into_data_parts();
574                Ok(CanonicalValidity(Canonical::VarBinView(unsafe {
575                    VarBinViewArray::new_handle_unchecked(
576                        views,
577                        buffers,
578                        dtype,
579                        validity.execute(ctx)?,
580                    )
581                })))
582            }
583            Canonical::List(l) => {
584                let zctl = l.is_zero_copy_to_list();
585                let ListViewDataParts {
586                    elements,
587                    offsets,
588                    sizes,
589                    validity,
590                    ..
591                } = l.into_data_parts();
592                Ok(CanonicalValidity(Canonical::List(unsafe {
593                    ListViewArray::new_unchecked(elements, offsets, sizes, validity.execute(ctx)?)
594                        .with_zero_copy_to_list(zctl)
595                })))
596            }
597            Canonical::Map(map) => {
598                let map_dtype = map.map_dtype().clone();
599                let entries = map.entries().clone();
600                Ok(CanonicalValidity(Canonical::Map(MapArray::new(
601                    map_dtype,
602                    entries.execute::<CanonicalValidity>(ctx)?.0.into_listview(),
603                ))))
604            }
605            Canonical::FixedSizeList(fsl) => {
606                let list_size = fsl.list_size();
607                let len = fsl.len();
608                let parts = fsl.into_data_parts();
609                let elements = parts.elements;
610                let validity = parts.validity;
611                Ok(CanonicalValidity(Canonical::FixedSizeList(
612                    FixedSizeListArray::new(elements, list_size, validity.execute(ctx)?, len),
613                )))
614            }
615            Canonical::Struct(st) => {
616                let len = st.len();
617                let StructDataParts {
618                    struct_fields,
619                    fields,
620                    validity,
621                } = st.into_data_parts();
622                Ok(CanonicalValidity(Canonical::Struct(unsafe {
623                    StructArray::new_unchecked(fields, struct_fields, len, validity.execute(ctx)?)
624                })))
625            }
626            Canonical::Union(union) => {
627                let UnionDataParts {
628                    variants,
629                    type_ids,
630                    children,
631                } = union.into_data_parts();
632                let type_ids = type_ids.execute::<CanonicalValidity>(ctx)?.0.into_array();
633
634                Ok(CanonicalValidity(Canonical::Union(unsafe {
635                    UnionArray::new_unchecked(type_ids, variants, children.iter().cloned())
636                })))
637            }
638            Canonical::Extension(ext) => Ok(CanonicalValidity(Canonical::Extension(
639                ExtensionArray::new(
640                    ext.ext_dtype().clone(),
641                    ext.storage_array()
642                        .clone()
643                        .execute::<CanonicalValidity>(ctx)?
644                        .0
645                        .into_array(),
646                ),
647            ))),
648            Canonical::Variant(variant) => {
649                let core_storage = recursively_canonicalize_slots(variant.core_storage(), ctx)?;
650                let shredded = variant
651                    .shredded()
652                    .map(|shredded| {
653                        if shredded.is::<Variant>() {
654                            recursively_canonicalize_slots(shredded, ctx)
655                        } else {
656                            shredded
657                                .clone()
658                                .execute::<CanonicalValidity>(ctx)
659                                .map(|canonical| canonical.0.into_array())
660                        }
661                    })
662                    .transpose()?;
663                Ok(CanonicalValidity(Canonical::Variant(
664                    VariantArray::try_new(core_storage, shredded)?,
665                )))
666            }
667        }
668    }
669}
670
671/// Recursively execute the array until all of its children are canonical.
672///
673/// This method is useful to guarantee that all operators are fully executed,
674/// callers should prefer an execution target that's suitable for their use case instead of this one.
675pub struct RecursiveCanonical(pub Canonical);
676
677// TODO: Currently only used for Variant, in the future
678// can probably be used for more canonical types like Struct.
679fn recursively_canonicalize_slots(
680    array: &ArrayRef,
681    ctx: &mut ExecutionCtx,
682) -> VortexResult<ArrayRef> {
683    let slots = array
684        .slots()
685        .iter()
686        .map(|slot| {
687            slot.as_ref()
688                .map(|child| {
689                    child
690                        .clone()
691                        .execute::<RecursiveCanonical>(ctx)
692                        .map(|canonical| canonical.0.into_array())
693                })
694                .transpose()
695        })
696        .collect::<VortexResult<ArraySlots>>()?;
697    // SAFETY: recursive canonicalization rewrites child slots to equivalent canonical
698    // representations, preserving the parent array's logical values and statistics.
699    unsafe { array.clone().with_slots(slots) }
700}
701impl Executable for RecursiveCanonical {
702    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
703        match array.execute::<Canonical>(ctx)? {
704            n @ Canonical::Null(_) => Ok(RecursiveCanonical(n)),
705            Canonical::Bool(b) => {
706                let validity = child_to_validity(b.validity_child(), b.dtype().nullability());
707                let len = b.len();
708                let BoolDataParts { bits, meta } = b.into_data().into_parts(len);
709                Ok(RecursiveCanonical(Canonical::Bool(
710                    BoolArray::try_new_from_handle(
711                        bits,
712                        meta.offset(),
713                        meta.len(),
714                        validity.execute(ctx)?,
715                    )?,
716                )))
717            }
718            Canonical::Primitive(p) => {
719                let PrimitiveDataParts {
720                    ptype,
721                    buffer,
722                    validity,
723                } = p.into_data_parts();
724                Ok(RecursiveCanonical(Canonical::Primitive(unsafe {
725                    PrimitiveArray::new_unchecked_from_handle(buffer, ptype, validity.execute(ctx)?)
726                })))
727            }
728            Canonical::Decimal(d) => {
729                let DecimalDataParts {
730                    decimal_dtype,
731                    values,
732                    values_type,
733                    validity,
734                } = d.into_data_parts();
735                Ok(RecursiveCanonical(Canonical::Decimal(unsafe {
736                    DecimalArray::new_unchecked_handle(
737                        values,
738                        values_type,
739                        decimal_dtype,
740                        validity.execute(ctx)?,
741                    )
742                })))
743            }
744            Canonical::VarBinView(vbv) => {
745                let VarBinViewDataParts {
746                    dtype,
747                    buffers,
748                    views,
749                    validity,
750                } = vbv.into_data_parts();
751                Ok(RecursiveCanonical(Canonical::VarBinView(unsafe {
752                    VarBinViewArray::new_handle_unchecked(
753                        views,
754                        buffers,
755                        dtype,
756                        validity.execute(ctx)?,
757                    )
758                })))
759            }
760            Canonical::List(l) => {
761                let zctl = l.is_zero_copy_to_list();
762                let ListViewDataParts {
763                    elements,
764                    offsets,
765                    sizes,
766                    validity,
767                    ..
768                } = l.into_data_parts();
769                Ok(RecursiveCanonical(Canonical::List(unsafe {
770                    ListViewArray::new_unchecked(
771                        elements.execute::<RecursiveCanonical>(ctx)?.0.into_array(),
772                        offsets.execute::<RecursiveCanonical>(ctx)?.0.into_array(),
773                        sizes.execute::<RecursiveCanonical>(ctx)?.0.into_array(),
774                        validity.execute(ctx)?,
775                    )
776                    .with_zero_copy_to_list(zctl)
777                })))
778            }
779            Canonical::Map(map) => {
780                let map_dtype = map.map_dtype().clone();
781                let entries = map.entries().clone();
782                Ok(RecursiveCanonical(Canonical::Map(MapArray::new(
783                    map_dtype,
784                    entries
785                        .execute::<RecursiveCanonical>(ctx)?
786                        .0
787                        .into_listview(),
788                ))))
789            }
790            Canonical::FixedSizeList(fsl) => {
791                let list_size = fsl.list_size();
792                let len = fsl.len();
793                let parts = fsl.into_data_parts();
794                let elements = parts.elements;
795                let validity = parts.validity;
796                Ok(RecursiveCanonical(Canonical::FixedSizeList(
797                    FixedSizeListArray::new(
798                        elements.execute::<RecursiveCanonical>(ctx)?.0.into_array(),
799                        list_size,
800                        validity.execute(ctx)?,
801                        len,
802                    ),
803                )))
804            }
805            Canonical::Struct(st) => {
806                let len = st.len();
807                let StructDataParts {
808                    struct_fields,
809                    fields,
810                    validity,
811                } = st.into_data_parts();
812                let executed_fields = fields
813                    .into_iter()
814                    .map(|f| Ok(f.execute::<RecursiveCanonical>(ctx)?.0.into_array()))
815                    .collect::<VortexResult<Vec<_>>>()?;
816
817                Ok(RecursiveCanonical(Canonical::Struct(unsafe {
818                    StructArray::new_unchecked(
819                        executed_fields,
820                        struct_fields,
821                        len,
822                        validity.execute(ctx)?,
823                    )
824                })))
825            }
826            Canonical::Union(union) => {
827                let UnionDataParts {
828                    variants,
829                    type_ids,
830                    children,
831                } = union.into_data_parts();
832                let type_ids = type_ids.execute::<RecursiveCanonical>(ctx)?.0.into_array();
833                let children = children
834                    .iter()
835                    .cloned()
836                    .map(|child| {
837                        child
838                            .execute::<RecursiveCanonical>(ctx)
839                            .map(|canonical| canonical.0.into_array())
840                    })
841                    .collect::<VortexResult<Vec<_>>>()?;
842
843                Ok(RecursiveCanonical(Canonical::Union(unsafe {
844                    UnionArray::new_unchecked(type_ids, variants, children)
845                })))
846            }
847            Canonical::Extension(ext) => Ok(RecursiveCanonical(Canonical::Extension(
848                ExtensionArray::new(
849                    ext.ext_dtype().clone(),
850                    ext.storage_array()
851                        .clone()
852                        .execute::<RecursiveCanonical>(ctx)?
853                        .0
854                        .into_array(),
855                ),
856            ))),
857            Canonical::Variant(variant) => {
858                let core_storage = recursively_canonicalize_slots(variant.core_storage(), ctx)?;
859                let shredded = variant
860                    .shredded()
861                    .map(|shredded| {
862                        if shredded.is::<Variant>() {
863                            recursively_canonicalize_slots(shredded, ctx)
864                        } else {
865                            shredded
866                                .clone()
867                                .execute::<RecursiveCanonical>(ctx)
868                                .map(|canonical| canonical.0.into_array())
869                        }
870                    })
871                    .transpose()?;
872                Ok(RecursiveCanonical(Canonical::Variant(
873                    VariantArray::try_new(core_storage, shredded)?,
874                )))
875            }
876        }
877    }
878}
879
880/// Execute a primitive typed array into a buffer of native values, assuming all values are valid.
881///
882/// # Errors
883///
884/// Returns a `VortexError` if the array is not all-valid (has any nulls).
885impl<T: NativePType> Executable for Buffer<T> {
886    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
887        let array = PrimitiveArray::execute(array, ctx)?;
888        vortex_ensure!(
889            matches!(
890                array.validity()?,
891                Validity::NonNullable | Validity::AllValid
892            ),
893            "Cannot execute to native buffer: array is not all-valid."
894        );
895        Ok(array.into_buffer())
896    }
897}
898
899/// Execute the array to canonical form and unwrap as a [`PrimitiveArray`].
900///
901/// This will panic if the array's dtype is not primitive.
902impl Executable for PrimitiveArray {
903    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
904        match array.try_downcast::<Primitive>() {
905            Ok(primitive) => Ok(primitive),
906            Err(array) => Ok(Canonical::execute(array, ctx)?.into_primitive()),
907        }
908    }
909}
910
911/// Execute the array to canonical form and unwrap as a [`BoolArray`].
912///
913/// This will panic if the array's dtype is not bool.
914impl Executable for BoolArray {
915    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
916        match array.try_downcast::<Bool>() {
917            Ok(bool_array) => Ok(bool_array),
918            Err(array) => Ok(Canonical::execute(array, ctx)?.into_bool()),
919        }
920    }
921}
922
923/// Execute the array to a [`BitBuffer`], aka a non-nullable  [`BoolArray`].
924///
925/// This will panic if the array's dtype is not non-nullable bool.
926impl Executable for BitBuffer {
927    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
928        let bool = BoolArray::execute(array, ctx)?;
929        assert!(
930            !bool.dtype().is_nullable(),
931            "bit buffer execute only works with non-nullable bool arrays"
932        );
933        Ok(bool.into_bit_buffer())
934    }
935}
936
937/// Execute the array to canonical form and unwrap as a [`NullArray`].
938///
939/// This will panic if the array's dtype is not null.
940impl Executable for NullArray {
941    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
942        match array.try_downcast::<Null>() {
943            Ok(null_array) => Ok(null_array),
944            Err(array) => Ok(Canonical::execute(array, ctx)?.into_null()),
945        }
946    }
947}
948
949/// Execute the array to canonical form and unwrap as a [`VarBinViewArray`].
950///
951/// This will panic if the array's dtype is not utf8 or binary.
952impl Executable for VarBinViewArray {
953    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
954        match array.try_downcast::<VarBinView>() {
955            Ok(varbinview) => Ok(varbinview),
956            Err(array) => Ok(Canonical::execute(array, ctx)?.into_varbinview()),
957        }
958    }
959}
960
961/// Execute the array to canonical form and unwrap as an [`ExtensionArray`].
962///
963/// This will panic if the array's dtype is not an extension type.
964impl Executable for ExtensionArray {
965    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
966        match array.try_downcast::<Extension>() {
967            Ok(ext_array) => Ok(ext_array),
968            Err(array) => Ok(Canonical::execute(array, ctx)?.into_extension()),
969        }
970    }
971}
972
973/// Execute the array to canonical form and unwrap as a [`DecimalArray`].
974///
975/// This will panic if the array's dtype is not decimal.
976impl Executable for DecimalArray {
977    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
978        match array.try_downcast::<Decimal>() {
979            Ok(decimal) => Ok(decimal),
980            Err(array) => Ok(Canonical::execute(array, ctx)?.into_decimal()),
981        }
982    }
983}
984
985/// Execute the array to canonical form and unwrap as a [`ListViewArray`].
986///
987/// This will panic if the array's dtype is not list.
988impl Executable for ListViewArray {
989    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
990        match array.try_downcast::<ListView>() {
991            Ok(list) => Ok(list),
992            Err(array) => Ok(Canonical::execute(array, ctx)?.into_listview()),
993        }
994    }
995}
996
997/// Execute the array to canonical form and unwrap as a [`MapArray`].
998///
999/// This will panic if the array's dtype is not map.
1000impl Executable for MapArray {
1001    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
1002        match array.try_downcast::<Map>() {
1003            Ok(map) => Ok(map),
1004            Err(array) => Ok(Canonical::execute(array, ctx)?.into_map()),
1005        }
1006    }
1007}
1008
1009/// Execute the array to canonical form and unwrap as a [`FixedSizeListArray`].
1010///
1011/// This will panic if the array's dtype is not fixed size list.
1012impl Executable for FixedSizeListArray {
1013    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
1014        match array.try_downcast::<FixedSizeList>() {
1015            Ok(fsl) => Ok(fsl),
1016            Err(array) => Ok(Canonical::execute(array, ctx)?.into_fixed_size_list()),
1017        }
1018    }
1019}
1020
1021/// Execute the array to canonical form and unwrap as a [`StructArray`].
1022///
1023/// This will panic if the array's dtype is not struct.
1024impl Executable for StructArray {
1025    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
1026        match array.try_downcast::<Struct>() {
1027            Ok(struct_array) => Ok(struct_array),
1028            Err(array) => Ok(Canonical::execute(array, ctx)?.into_struct()),
1029        }
1030    }
1031}
1032
1033/// Execute the array to canonical form and unwrap as a [`UnionArray`].
1034///
1035/// This will panic if the array's dtype is not union.
1036impl Executable for UnionArray {
1037    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
1038        match array.try_downcast::<Union>() {
1039            Ok(union_array) => Ok(union_array),
1040            Err(array) => Ok(Canonical::execute(array, ctx)?.into_union()),
1041        }
1042    }
1043}
1044
1045/// Execute the array to canonical form and unwrap as a [`VariantArray`].
1046///
1047/// This will panic if the array's dtype is not variant.
1048impl Executable for VariantArray {
1049    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
1050        match array.try_downcast::<Variant>() {
1051            Ok(variant_array) => Ok(variant_array),
1052            Err(array) => match Canonical::execute(array, ctx)? {
1053                Canonical::Variant(variant_array) => Ok(variant_array),
1054                canonical => {
1055                    vortex_panic!("Cannot unwrap VariantArray from {:?}", canonical)
1056                }
1057            },
1058        }
1059    }
1060}
1061
1062/// A view into a canonical array type.
1063///
1064/// Uses `ArrayView<V>` because these are obtained by
1065/// downcasting through the `Matcher` trait which returns `ArrayView<V>`.
1066#[derive(Debug, Clone, Copy)]
1067pub enum CanonicalView<'a> {
1068    Null(ArrayView<'a, Null>),
1069    Bool(ArrayView<'a, Bool>),
1070    Primitive(ArrayView<'a, Primitive>),
1071    Decimal(ArrayView<'a, Decimal>),
1072    VarBinView(ArrayView<'a, VarBinView>),
1073    List(ArrayView<'a, ListView>),
1074    Map(ArrayView<'a, Map>),
1075    FixedSizeList(ArrayView<'a, FixedSizeList>),
1076    Struct(ArrayView<'a, Struct>),
1077    Union(ArrayView<'a, Union>),
1078    Extension(ArrayView<'a, Extension>),
1079    Variant(ArrayView<'a, Variant>),
1080}
1081
1082impl From<CanonicalView<'_>> for Canonical {
1083    fn from(value: CanonicalView<'_>) -> Self {
1084        match value {
1085            CanonicalView::Null(a) => Canonical::Null(a.into_owned()),
1086            CanonicalView::Bool(a) => Canonical::Bool(a.into_owned()),
1087            CanonicalView::Primitive(a) => Canonical::Primitive(a.into_owned()),
1088            CanonicalView::Decimal(a) => Canonical::Decimal(a.into_owned()),
1089            CanonicalView::VarBinView(a) => Canonical::VarBinView(a.into_owned()),
1090            CanonicalView::List(a) => Canonical::List(a.into_owned()),
1091            CanonicalView::Map(a) => Canonical::Map(a.into_owned()),
1092            CanonicalView::FixedSizeList(a) => Canonical::FixedSizeList(a.into_owned()),
1093            CanonicalView::Struct(a) => Canonical::Struct(a.into_owned()),
1094            CanonicalView::Union(a) => Canonical::Union(a.into_owned()),
1095            CanonicalView::Extension(a) => Canonical::Extension(a.into_owned()),
1096            CanonicalView::Variant(a) => Canonical::Variant(a.into_owned()),
1097        }
1098    }
1099}
1100
1101impl CanonicalView<'_> {
1102    /// Convert to a type-erased [`ArrayRef`].
1103    pub fn to_array_ref(&self) -> ArrayRef {
1104        match self {
1105            CanonicalView::Null(a) => a.array().clone(),
1106            CanonicalView::Bool(a) => a.array().clone(),
1107            CanonicalView::Primitive(a) => a.array().clone(),
1108            CanonicalView::Decimal(a) => a.array().clone(),
1109            CanonicalView::VarBinView(a) => a.array().clone(),
1110            CanonicalView::List(a) => a.array().clone(),
1111            CanonicalView::Map(a) => a.array().clone(),
1112            CanonicalView::FixedSizeList(a) => a.array().clone(),
1113            CanonicalView::Struct(a) => a.array().clone(),
1114            CanonicalView::Union(a) => a.array().clone(),
1115            CanonicalView::Extension(a) => a.array().clone(),
1116            CanonicalView::Variant(a) => a.array().clone(),
1117        }
1118    }
1119}
1120
1121// Keep classification and checked conversion together so they use the same concrete types.
1122macro_rules! canonical_kinds {
1123    ($($kind:ident => $vtable:ty),+ $(,)?) => {
1124        /// Canonical encoding classification derived from the concrete array vtable.
1125        #[derive(Clone, Copy)]
1126        pub(crate) enum CanonicalKind {
1127            $($kind),+
1128        }
1129
1130        impl CanonicalKind {
1131            /// Classify a concrete vtable; monomorphization folds these type comparisons.
1132            #[inline]
1133            pub(crate) fn of<V: VTable>() -> Option<Self> {
1134                $(if TypeId::of::<V>() == TypeId::of::<$vtable>() {
1135                    return Some(Self::$kind);
1136                })+
1137                None
1138            }
1139
1140            /// # Safety
1141            /// `self` must be the kind returned by `of::<V>()` for the concrete vtable of `array`.
1142            #[inline]
1143            unsafe fn view(self, array: &ArrayRef) -> CanonicalView<'_> {
1144                match self {
1145                    // SAFETY: the caller guarantees `of::<V>()` matched `$vtable` by `TypeId`.
1146                    $(Self::$kind => CanonicalView::$kind(unsafe {
1147                        array.as_typed_unchecked::<$vtable>()
1148                    })),+
1149                }
1150            }
1151        }
1152    };
1153}
1154
1155canonical_kinds! {
1156    Null => Null,
1157    Bool => Bool,
1158    Primitive => Primitive,
1159    Decimal => Decimal,
1160    Struct => Struct,
1161    Union => Union,
1162    List => ListView,
1163    Map => Map,
1164    FixedSizeList => FixedSizeList,
1165    VarBinView => VarBinView,
1166    Variant => Variant,
1167    Extension => Extension,
1168}
1169
1170/// A matcher for any canonical array type.
1171pub struct AnyCanonical;
1172impl Matcher for AnyCanonical {
1173    type Match<'a> = CanonicalView<'a>;
1174
1175    #[inline]
1176    fn matches(array: &ArrayRef) -> bool {
1177        array.dyn_array().canonical_kind().is_some()
1178    }
1179
1180    #[inline]
1181    fn try_match(array: &ArrayRef) -> Option<Self::Match<'_>> {
1182        let kind = array.dyn_array().canonical_kind()?;
1183        // SAFETY: `kind` was computed from the concrete vtable of `array`.
1184        Some(unsafe { kind.view(array) })
1185    }
1186}
1187
1188#[cfg(test)]
1189mod tests {
1190    use std::sync::Arc;
1191    use std::sync::LazyLock;
1192
1193    use rstest::rstest;
1194    use vortex_error::VortexResult;
1195    use vortex_error::vortex_err;
1196    use vortex_session::VortexSession;
1197
1198    use crate::ArrayRef;
1199    use crate::Canonical;
1200    use crate::CanonicalValidity;
1201    use crate::IntoArray;
1202    use crate::VortexSessionExecute;
1203    use crate::array::new_foreign_array;
1204    use crate::arrays::Constant;
1205    use crate::arrays::ConstantArray;
1206    use crate::arrays::Primitive;
1207    use crate::arrays::PrimitiveArray;
1208    use crate::arrays::Struct;
1209    use crate::arrays::VarBinArray;
1210    use crate::arrays::Variant;
1211    use crate::arrays::VariantArray;
1212    use crate::arrays::struct_::StructArrayExt;
1213    use crate::arrays::variant::VariantArraySlotsExt;
1214    use crate::assert_arrays_eq;
1215    use crate::canonical::AnyCanonical;
1216    use crate::canonical::StructArray;
1217    use crate::dtype::DType;
1218    use crate::dtype::DecimalDType;
1219    use crate::dtype::MapDType;
1220    use crate::dtype::Nullability;
1221    use crate::dtype::PType;
1222    use crate::dtype::StructFields;
1223    use crate::dtype::UnionVariants;
1224    use crate::extension::datetime::TimeUnit;
1225    use crate::extension::datetime::Timestamp;
1226    use crate::scalar::Scalar;
1227
1228    /// A shared session for these canonical tests, used to create execution contexts.
1229    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
1230
1231    fn variant_core_storage(len: usize) -> ArrayRef {
1232        ConstantArray::new(
1233            Scalar::variant(Scalar::primitive(1i32, Nullability::NonNullable)),
1234            len,
1235        )
1236        .into_array()
1237    }
1238
1239    fn canonical_arrays(nullability: Nullability) -> VortexResult<Vec<ArrayRef>> {
1240        let i32_dtype = DType::Primitive(PType::I32, nullability);
1241        let dtypes = [
1242            DType::Null,
1243            DType::Bool(nullability),
1244            i32_dtype.clone(),
1245            DType::Decimal(DecimalDType::try_new(10, 2)?, nullability),
1246            DType::Utf8(nullability),
1247            DType::Binary(nullability),
1248            DType::List(Arc::new(i32_dtype.clone()), nullability),
1249            DType::FixedSizeList(Arc::new(i32_dtype.clone()), 2, nullability),
1250            DType::Map(
1251                MapDType::try_new(
1252                    DType::Utf8(Nullability::NonNullable),
1253                    i32_dtype.clone(),
1254                    false,
1255                )?,
1256                nullability,
1257            ),
1258            DType::Struct(
1259                StructFields::from_iter([("a", i32_dtype.clone())]),
1260                nullability,
1261            ),
1262            DType::Union(
1263                UnionVariants::new(["a"].into(), vec![i32_dtype])?,
1264                nullability,
1265            ),
1266            DType::Variant(nullability),
1267            DType::Extension(Timestamp::new(TimeUnit::Microseconds, nullability).erased()),
1268        ];
1269        let arrays: Vec<_> = dtypes
1270            .iter()
1271            .map(|dtype| Canonical::empty(dtype).into_array())
1272            .collect();
1273        Ok(arrays)
1274    }
1275
1276    #[rstest]
1277    fn empty_variant_is_a_valid_canonical(
1278        #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability,
1279    ) -> VortexResult<()> {
1280        let dtype = DType::Variant(nullability);
1281        let canonical = Canonical::empty(&dtype);
1282        assert!(matches!(canonical, Canonical::Variant(_)));
1283        assert_eq!(canonical.dtype(), &dtype);
1284        assert!(canonical.is_empty());
1285
1286        let array = canonical.into_array();
1287        assert!(array.is_empty());
1288        assert_eq!(array.dtype(), &dtype);
1289        assert_eq!(array.len(), 0);
1290        Ok(())
1291    }
1292
1293    #[test]
1294    fn empty_variant_slice_executes() -> VortexResult<()> {
1295        let source =
1296            ConstantArray::new(Scalar::null(DType::Variant(Nullability::Nullable)), 1).into_array();
1297
1298        let mut ctx = SESSION.create_execution_ctx();
1299        let result = source.slice(0..0)?.execute::<ArrayRef>(&mut ctx)?;
1300        assert!(result.is_empty());
1301        assert_eq!(result.dtype(), source.dtype());
1302        Ok(())
1303    }
1304
1305    #[rstest]
1306    fn any_canonical_matches_all_encodings(
1307        #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability,
1308    ) -> VortexResult<()> {
1309        for array in canonical_arrays(nullability)? {
1310            assert!(array.is::<AnyCanonical>(), "{array}");
1311            let canonical = Canonical::from(array.as_::<AnyCanonical>()).into_array();
1312            assert!(ArrayRef::ptr_eq(&array, &canonical));
1313        }
1314        Ok(())
1315    }
1316
1317    #[test]
1318    fn any_canonical_rejects_noncanonical_encodings() {
1319        let arrays = [
1320            ConstantArray::new(1i32, 4).into_array(),
1321            ConstantArray::new(true, 4).into_array(),
1322            ConstantArray::new("value", 4).into_array(),
1323            VarBinArray::from_iter([Some("value")], DType::Utf8(Nullability::Nullable))
1324                .into_array(),
1325        ];
1326        for array in arrays {
1327            assert!(!array.is::<AnyCanonical>(), "{array}");
1328            assert!(array.as_opt::<AnyCanonical>().is_none(), "{array}");
1329        }
1330    }
1331
1332    #[rstest]
1333    fn any_canonical_rejects_foreign_arrays_with_canonical_ids(
1334        #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability,
1335    ) -> VortexResult<()> {
1336        let mut ctx = SESSION.create_execution_ctx();
1337        for canonical in canonical_arrays(nullability)? {
1338            let foreign = new_foreign_array(
1339                canonical.encoding_id(),
1340                canonical.dtype().clone(),
1341                canonical.len(),
1342                vec![],
1343                vec![],
1344                Default::default(),
1345            )?;
1346            assert!(!foreign.is::<AnyCanonical>(), "{foreign}");
1347            assert!(foreign.as_opt::<AnyCanonical>().is_none(), "{foreign}");
1348            assert!(foreign.execute::<Canonical>(&mut ctx).is_err());
1349        }
1350        Ok(())
1351    }
1352
1353    #[test]
1354    fn canonical_validity_canonicalizes_variant_shredded_physical_slots() -> VortexResult<()> {
1355        let len = 2;
1356        let nested_shredded =
1357            StructArray::try_from_iter([("value", ConstantArray::new(10i32, len).into_array())])?;
1358        let inner_variant = VariantArray::try_new(
1359            variant_core_storage(len),
1360            Some(nested_shredded.into_array()),
1361        )?;
1362        let outer_variant =
1363            VariantArray::try_new(variant_core_storage(len), Some(inner_variant.into_array()))?;
1364
1365        let mut ctx = SESSION.create_execution_ctx();
1366        let Canonical::Variant(canonical) = outer_variant
1367            .into_array()
1368            .execute::<CanonicalValidity>(&mut ctx)?
1369            .0
1370        else {
1371            return Err(vortex_err!("expected canonical variant"));
1372        };
1373
1374        let nested_variant = canonical
1375            .shredded()
1376            .and_then(|shredded| shredded.as_opt::<Variant>())
1377            .ok_or_else(|| vortex_err!("expected nested variant shredded child"))?;
1378        let nested_struct = nested_variant
1379            .shredded()
1380            .and_then(|shredded| shredded.as_opt::<Struct>())
1381            .ok_or_else(|| vortex_err!("expected nested struct shredded child"))?;
1382        let value = nested_struct.unmasked_field_by_name("value")?;
1383
1384        assert!(value.is::<Primitive>());
1385        assert!(!value.is::<Constant>());
1386        assert_arrays_eq!(value, PrimitiveArray::from_iter([10i32, 10]), &mut ctx);
1387
1388        Ok(())
1389    }
1390}