From 33ce8b2259f7856f840ea53082527f1b32bc4c31 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Wed, 15 Jul 2026 16:06:24 -0400 Subject: [PATCH 1/2] Add UnionArray Signed-off-by: Connor Tsui --- fuzz/src/array/fill_null.rs | 1 + fuzz/src/array/mask.rs | 1 + fuzz/src/array/scalar_at.rs | 1 + .../src/aggregate_fn/fns/is_constant/mod.rs | 3 + .../src/aggregate_fn/fns/min_max/mod.rs | 1 + .../fns/uncompressed_size_in_bytes/mod.rs | 10 +- .../fns/uncompressed_size_in_bytes/union.rs | 25 +++ .../src/arrays/chunked/vtable/canonical.rs | 44 ++++ vortex-array/src/arrays/chunked/vtable/mod.rs | 9 +- .../src/arrays/constant/vtable/canonical.rs | 46 +++- vortex-array/src/arrays/dict/execute.rs | 12 + vortex-array/src/arrays/filter/execute/mod.rs | 9 + vortex-array/src/arrays/masked/execute.rs | 4 + vortex-array/src/arrays/mod.rs | 8 +- vortex-array/src/arrays/union/array.rs | 204 +++++++++++++++++ .../src/arrays/union/compute/filter.rs | 29 +++ vortex-array/src/arrays/union/compute/mod.rs | 7 + .../src/arrays/union/compute/rules.rs | 14 ++ .../src/arrays/union/compute/slice.rs | 30 +++ vortex-array/src/arrays/union/compute/take.rs | 34 +++ vortex-array/src/arrays/union/mod.rs | 15 ++ vortex-array/src/arrays/union/tests.rs | 201 +++++++++++++++++ vortex-array/src/arrays/union/vtable/mod.rs | 207 ++++++++++++++++++ .../src/arrays/union/vtable/operations.rs | 37 ++++ .../src/arrays/union/vtable/validity.rs | 16 ++ vortex-array/src/canonical.rs | 73 +++++- vortex-array/src/dtype/dtype_impl.rs | 2 +- vortex-array/src/lib.rs | 2 +- vortex-array/src/scalar_fn/fns/cast/mod.rs | 3 + vortex-array/src/session/mod.rs | 2 + vortex-compressor/src/compressor/cascade.rs | 14 ++ vortex-duckdb/src/exporter/canonical.rs | 3 + 32 files changed, 1053 insertions(+), 14 deletions(-) create mode 100644 vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/union.rs create mode 100644 vortex-array/src/arrays/union/array.rs create mode 100644 vortex-array/src/arrays/union/compute/filter.rs create mode 100644 vortex-array/src/arrays/union/compute/mod.rs create mode 100644 vortex-array/src/arrays/union/compute/rules.rs create mode 100644 vortex-array/src/arrays/union/compute/slice.rs create mode 100644 vortex-array/src/arrays/union/compute/take.rs create mode 100644 vortex-array/src/arrays/union/mod.rs create mode 100644 vortex-array/src/arrays/union/tests.rs create mode 100644 vortex-array/src/arrays/union/vtable/mod.rs create mode 100644 vortex-array/src/arrays/union/vtable/operations.rs create mode 100644 vortex-array/src/arrays/union/vtable/validity.rs diff --git a/fuzz/src/array/fill_null.rs b/fuzz/src/array/fill_null.rs index f3a49b25637..39b7885c248 100644 --- a/fuzz/src/array/fill_null.rs +++ b/fuzz/src/array/fill_null.rs @@ -49,6 +49,7 @@ pub fn fill_null_canonical_array( | Canonical::List(_) | Canonical::FixedSizeList(_) | Canonical::Extension(_) => canonical.into_array().fill_null(fill_value.clone())?, + Canonical::Union(_) => unreachable!("Union arrays are not fuzzed yet"), Canonical::Variant(_) => unreachable!("Variant arrays are not fuzzed"), }) } diff --git a/fuzz/src/array/mask.rs b/fuzz/src/array/mask.rs index f3cecec2b10..5d6e411dd22 100644 --- a/fuzz/src/array/mask.rs +++ b/fuzz/src/array/mask.rs @@ -149,6 +149,7 @@ pub fn mask_canonical_array( .with_nullability(masked_storage.dtype().nullability()); ExtensionArray::new(ext_dtype, masked_storage).into_array() } + Canonical::Union(_) => unreachable!("Union arrays are not fuzzed yet"), Canonical::Variant(_) => unreachable!("Variant arrays are not fuzzed"), }) } diff --git a/fuzz/src/array/scalar_at.rs b/fuzz/src/array/scalar_at.rs index e13ad75343d..7b809b5da93 100644 --- a/fuzz/src/array/scalar_at.rs +++ b/fuzz/src/array/scalar_at.rs @@ -104,6 +104,7 @@ pub fn scalar_at_canonical_array( let storage_scalar = scalar_at_canonical_array(storage_canonical, index, ctx)?; Scalar::extension_ref(array.ext_dtype().clone(), storage_scalar) } + Canonical::Union(_) => unreachable!("Union arrays are not fuzzed yet"), Canonical::Variant(_) => unreachable!("Variant arrays are not fuzzed"), }) } diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs b/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs index 490ede7f640..ad89513e7cd 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs @@ -404,6 +404,9 @@ impl AggregateFnVTable for IsConstant { Canonical::List(l) => check_listview_constant(l, ctx)?, Canonical::FixedSizeList(f) => check_fixed_size_list_constant(f, ctx)?, Canonical::Null(_) => true, + Canonical::Union(_) => { + vortex_bail!("Union arrays don't support IsConstant yet") + } Canonical::Variant(_) => { vortex_bail!("Variant arrays don't support IsConstant") } diff --git a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs b/vortex-array/src/aggregate_fn/fns/min_max/mod.rs index 51601ce76fd..b66b9fe792d 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/min_max/mod.rs @@ -420,6 +420,7 @@ impl AggregateFnVTable for MinMax { Canonical::Struct(_) | Canonical::List(_) | Canonical::FixedSizeList(_) + | Canonical::Union(_) | Canonical::Variant(_) => { vortex_bail!("Unsupported canonical type for min_max: {}", batch.dtype()) } diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs b/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs index 6b2feb380a7..dd51e25edae 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs @@ -9,6 +9,7 @@ mod list_view; mod null; mod primitive; mod struct_; +mod union; mod varbinview; use std::mem::size_of; @@ -21,6 +22,7 @@ use list_view::list_view_uncompressed_size_in_bytes; use null::null_uncompressed_size_in_bytes; use primitive::primitive_uncompressed_size_in_bytes; use struct_::struct_uncompressed_size_in_bytes; +use union::union_uncompressed_size_in_bytes; use varbinview::varbinview_uncompressed_size_in_bytes; use vortex_error::VortexExpect; use vortex_error::VortexResult; @@ -199,6 +201,7 @@ pub(crate) fn canonical_uncompressed_size_in_bytes( Canonical::List(array) => list_view_uncompressed_size_in_bytes(array, ctx), Canonical::FixedSizeList(array) => fixed_size_list_uncompressed_size_in_bytes(array, ctx), Canonical::Struct(array) => struct_uncompressed_size_in_bytes(array, ctx), + Canonical::Union(array) => union_uncompressed_size_in_bytes(array, ctx), Canonical::Extension(array) => extension_uncompressed_size_in_bytes(array, ctx), Canonical::Variant(_) => { vortex_bail!("UncompressedSizeInBytes is not supported for Variant arrays") @@ -229,11 +232,14 @@ pub(crate) fn constant_uncompressed_size_in_bytes( array.len(), array.scalar().as_binary().value().map(|value| value.len()), )?, - DType::List(..) | DType::FixedSizeList(..) | DType::Struct(..) | DType::Extension(_) => { + DType::List(..) + | DType::FixedSizeList(..) + | DType::Struct(..) + | DType::Union(..) + | DType::Extension(_) => { let canonical = array.array().clone().execute::(ctx)?; return canonical_uncompressed_size_in_bytes(&canonical, ctx); } - DType::Union(..) => todo!("TODO(connor)[Union]: unimplemented"), DType::Variant(_) => { vortex_bail!("UncompressedSizeInBytes is not supported for Variant arrays") } diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/union.rs b/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/union.rs new file mode 100644 index 00000000000..2f13252de9d --- /dev/null +++ b/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/union.rs @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_error::VortexResult; +use vortex_error::vortex_err; + +use super::uncompressed_size_in_bytes_u64; +use crate::ExecutionCtx; +use crate::arrays::UnionArray; +use crate::arrays::union::UnionArrayExt; + +pub(super) fn union_uncompressed_size_in_bytes( + array: &UnionArray, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let mut size = uncompressed_size_in_bytes_u64(array.type_ids(), ctx)?; + + for child in array.iter_children() { + size = size + .checked_add(uncompressed_size_in_bytes_u64(child, ctx)?) + .ok_or_else(|| vortex_err!("uncompressed size in bytes overflowed u64"))?; + } + + Ok(size) +} diff --git a/vortex-array/src/arrays/chunked/vtable/canonical.rs b/vortex-array/src/arrays/chunked/vtable/canonical.rs index 12c3bbcd9e4..3992a38ff82 100644 --- a/vortex-array/src/arrays/chunked/vtable/canonical.rs +++ b/vortex-array/src/arrays/chunked/vtable/canonical.rs @@ -19,11 +19,13 @@ use crate::arrays::FixedSizeListArray; use crate::arrays::ListViewArray; use crate::arrays::PrimitiveArray; use crate::arrays::StructArray; +use crate::arrays::UnionArray; use crate::arrays::VariantArray; use crate::arrays::chunked::ChunkedArrayExt; use crate::arrays::fixed_size_list::FixedSizeListArrayExt; use crate::arrays::listview::ListViewArrayExt; use crate::arrays::listview::ListViewRebuildMode; +use crate::arrays::union::UnionArrayExt; use crate::arrays::variant::VariantArrayExt; use crate::builders::builder_with_capacity_in; use crate::builtins::ArrayBuiltins; @@ -54,6 +56,7 @@ pub(super) fn _canonicalize( let struct_array = pack_struct_chunks(owned_chunks, ctx)?; Canonical::Struct(struct_array) } + DType::Union(..) => Canonical::Union(pack_union_chunks(owned_chunks, ctx)?), DType::List(elem_dtype, _) => Canonical::List(swizzle_list_chunks( &owned_chunks, array.array().validity()?, @@ -89,6 +92,47 @@ fn pack_struct_chunks(chunks: Vec, ctx: &mut ExecutionCtx) -> VortexRe .process_results(|iter| StructArray::try_concat(iter))? } +/// Packs sparse union chunks into one union with chunked type IDs and sparse children. +fn pack_union_chunks(chunks: Vec, ctx: &mut ExecutionCtx) -> VortexResult { + let union_chunks = chunks + .into_iter() + .map(|chunk| chunk.execute::(ctx)) + .collect::>>()?; + let variants = union_chunks[0].variants().clone(); + let type_ids = ChunkedArray::try_new( + union_chunks + .iter() + .map(|chunk| chunk.type_ids().clone()) + .collect(), + DType::Primitive(PType::I8, Nullability::NonNullable), + )? + .into_array(); + let children = (0..variants.len()) + .map(|index| { + let dtype = variants + .variant_by_index(index) + .vortex_expect("variant index must have a dtype"); + ChunkedArray::try_new( + union_chunks + .iter() + .map(|chunk| { + chunk + .child(index) + .vortex_expect("variant index must have a sparse child") + .clone() + }) + .collect(), + dtype, + ) + .map(IntoArray::into_array) + }) + .collect::>>()?; + + // SAFETY: Every component was taken from validated UnionArrays with the same dtype and + // chunked along identical row boundaries. + Ok(unsafe { UnionArray::new_unchecked(type_ids, variants, children) }) +} + /// Packs many [`VariantArray`]s into one [`VariantArray`] with chunked children. /// /// The caller guarantees there are at least 2 chunks. diff --git a/vortex-array/src/arrays/chunked/vtable/mod.rs b/vortex-array/src/arrays/chunked/vtable/mod.rs index 2eabd883742..8bb424c174f 100644 --- a/vortex-array/src/arrays/chunked/vtable/mod.rs +++ b/vortex-array/src/arrays/chunked/vtable/mod.rs @@ -251,9 +251,12 @@ impl VTable for Chunked { fn execute(array: Array, ctx: &mut ExecutionCtx) -> VortexResult { match array.dtype() { - // Struct, List, FixedSizeList, and Variant need child swizzling that the builder path - // cannot express. - DType::Struct(..) | DType::List(..) | DType::FixedSizeList(..) | DType::Variant(..) => { + // Nested canonical arrays need child swizzling that the builder path cannot express. + DType::Struct(..) + | DType::List(..) + | DType::FixedSizeList(..) + | DType::Union(..) + | DType::Variant(..) => { // TODO(joe)[#7674]: iterative execution here too Ok(ExecutionResult::done(_canonicalize(array.as_view(), ctx)?)) } diff --git a/vortex-array/src/arrays/constant/vtable/canonical.rs b/vortex-array/src/arrays/constant/vtable/canonical.rs index e160bcc16a9..919d4607076 100644 --- a/vortex-array/src/arrays/constant/vtable/canonical.rs +++ b/vortex-array/src/arrays/constant/vtable/canonical.rs @@ -8,6 +8,7 @@ use vortex_buffer::Buffer; use vortex_buffer::buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use crate::Canonical; use crate::ExecutionCtx; @@ -23,6 +24,7 @@ use crate::arrays::ListViewArray; use crate::arrays::NullArray; use crate::arrays::PrimitiveArray; use crate::arrays::StructArray; +use crate::arrays::UnionArray; use crate::arrays::VarBinViewArray; use crate::arrays::VariantArray; use crate::arrays::varbinview::BinaryView; @@ -164,7 +166,49 @@ pub(crate) fn constant_canonicalize( StructArray::new_unchecked(fields, struct_dtype.clone(), array.len(), validity) }) } - DType::Union(..) => todo!("TODO(connor)[Union]: unimplemented"), + DType::Union(variants) => { + if scalar.is_null() { + vortex_bail!( + "Canonicalizing a null union scalar is not supported until null semantics are defined" + ) + } + if variants.variants().any(|variant| variant.is_nullable()) { + vortex_bail!("Canonical UnionArray children must be non-nullable") + } + + let union = scalar.as_union(); + let type_id = union + .type_id() + .vortex_expect("non-null union scalar must have a type ID"); + let child_index = union + .child_index() + .vortex_expect("validated union scalar must select a child"); + let selected_value = union + .value() + .vortex_expect("non-null union scalar must have a value"); + let children = variants + .variants() + .enumerate() + .map(|(index, dtype)| { + let value = if index == child_index { + selected_value.clone() + } else { + Scalar::zero_value(&dtype) + }; + ConstantArray::new(value, array.len()).into_array() + }) + .collect::>(); + + // SAFETY: The scalar's validated type ID selects `child_index`; all sparse children + // have the declared dtype and the same length. + Canonical::Union(unsafe { + UnionArray::new_unchecked( + ConstantArray::new(type_id, array.len()).into_array(), + variants.clone(), + children, + ) + }) + } DType::Variant(_) => Canonical::Variant(VariantArray::try_new( array.array().clone().into_array(), None, diff --git a/vortex-array/src/arrays/dict/execute.rs b/vortex-array/src/arrays/dict/execute.rs index 47a9a051666..3dc7d0f596f 100644 --- a/vortex-array/src/arrays/dict/execute.rs +++ b/vortex-array/src/arrays/dict/execute.rs @@ -25,6 +25,8 @@ use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::arrays::Struct; use crate::arrays::StructArray; +use crate::arrays::Union; +use crate::arrays::UnionArray; use crate::arrays::VarBinView; use crate::arrays::VarBinViewArray; use crate::arrays::VariantArray; @@ -53,6 +55,7 @@ pub(crate) fn take_canonical( Canonical::FixedSizeList(take_fixed_size_list(&a, codes, ctx)) } Canonical::Struct(a) => Canonical::Struct(take_struct(&a, codes)), + Canonical::Union(a) => Canonical::Union(take_union(&a, codes)?), Canonical::Extension(a) => Canonical::Extension(take_extension(&a, codes, ctx)), Canonical::Variant(a) => { let indices = codes.clone().into_array(); @@ -165,6 +168,15 @@ fn take_struct(array: &StructArray, codes: &PrimitiveArray) -> StructArray { .into_owned() } +fn take_union(array: &UnionArray, codes: &PrimitiveArray) -> VortexResult { + let codes_ref = codes.clone().into_array(); + let array = array.as_view(); + Ok(::take(array, &codes_ref)? + .vortex_expect("take UnionArray should be supported") + .as_::() + .into_owned()) +} + fn take_extension( array: &ExtensionArray, codes: &PrimitiveArray, diff --git a/vortex-array/src/arrays/filter/execute/mod.rs b/vortex-array/src/arrays/filter/execute/mod.rs index 52b0373ac49..0dfe7ca44f8 100644 --- a/vortex-array/src/arrays/filter/execute/mod.rs +++ b/vortex-array/src/arrays/filter/execute/mod.rs @@ -21,9 +21,11 @@ use crate::arrays::ConstantArray; use crate::arrays::ExtensionArray; use crate::arrays::Filter; use crate::arrays::NullArray; +use crate::arrays::Union; use crate::arrays::VariantArray; use crate::arrays::extension::ExtensionArrayExt; use crate::arrays::filter::FilterArrayExt; +use crate::arrays::filter::FilterReduce; use crate::arrays::variant::VariantArrayExt; use crate::scalar::Scalar; use crate::validity::Validity; @@ -95,6 +97,13 @@ pub(super) fn execute_filter(canonical: Canonical, mask: &Arc) -> Ca Canonical::FixedSizeList(fixed_size_list::filter_fixed_size_list(&a, mask)) } Canonical::Struct(a) => Canonical::Struct(struct_::filter_struct(&a, mask)), + Canonical::Union(a) => Canonical::Union( + ::filter(a.as_view(), &Mask::Values(Arc::clone(mask))) + .vortex_expect("filter UnionArray") + .vortex_expect("UnionArray filter must be supported") + .as_::() + .into_owned(), + ), Canonical::Extension(a) => { let filtered_storage = a .storage_array() diff --git a/vortex-array/src/arrays/masked/execute.rs b/vortex-array/src/arrays/masked/execute.rs index c4173dd0cf6..c5fc9ac90af 100644 --- a/vortex-array/src/arrays/masked/execute.rs +++ b/vortex-array/src/arrays/masked/execute.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use crate::Canonical; use crate::IntoArray; @@ -50,6 +51,9 @@ pub fn mask_validity_canonical( Canonical::FixedSizeList(mask_validity_fixed_size_list(a, validity)?) } Canonical::Struct(a) => Canonical::Struct(mask_validity_struct(a, validity)?), + Canonical::Union(_) => { + vortex_bail!("Masking UnionArray is not supported until null semantics are defined") + } Canonical::Extension(a) => Canonical::Extension(mask_validity_extension(a, validity, ctx)?), Canonical::Variant(a) => Canonical::Variant(mask_validity_variant(a, validity, ctx)?), }) diff --git a/vortex-array/src/arrays/mod.rs b/vortex-array/src/arrays/mod.rs index 15b6b5aa6be..8b8f5f28d75 100644 --- a/vortex-array/src/arrays/mod.rs +++ b/vortex-array/src/arrays/mod.rs @@ -5,8 +5,8 @@ //! //! Canonical arrays are the default uncompressed representation for a logical dtype: //! [`NullArray`], [`BoolArray`], [`PrimitiveArray`], [`DecimalArray`], [`VarBinViewArray`], -//! [`ListViewArray`], [`FixedSizeListArray`], [`StructArray`], [`ExtensionArray`], and -//! [`VariantArray`]. +//! [`ListViewArray`], [`FixedSizeListArray`], [`StructArray`], [`UnionArray`], +//! [`ExtensionArray`], and [`VariantArray`]. //! //! Utility and lazy arrays represent common transformations without immediately materializing //! their result. Examples include [`ChunkedArray`] for concatenation, [`ConstantArray`] for repeated @@ -108,6 +108,10 @@ pub mod struct_; pub use struct_::Struct; pub use struct_::StructArray; +pub mod union; +pub use union::Union; +pub use union::UnionArray; + pub mod varbin; pub use varbin::VarBin; pub use varbin::VarBinArray; diff --git a/vortex-array/src/arrays/union/array.rs b/vortex-array/src/arrays/union/array.rs new file mode 100644 index 00000000000..e4dc751cba3 --- /dev/null +++ b/vortex-array/src/arrays/union/array.rs @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::iter::once; +use std::sync::Arc; + +use itertools::Itertools; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; + +use crate::ArrayRef; +use crate::ArraySlots; +use crate::IntoArray; +use crate::VortexSessionExecute; +use crate::array::Array; +use crate::array::ArrayParts; +use crate::array::EmptyArrayData; +use crate::array::TypedArrayRef; +use crate::arrays::PrimitiveArray; +use crate::arrays::Union; +use crate::dtype::DType; +use crate::dtype::Nullability; +use crate::dtype::PType; +use crate::dtype::UnionVariants; +use crate::legacy_session; + +/// The row-aligned array of type IDs selecting a union child. +pub(super) const TYPE_IDS_SLOT: usize = 0; +/// The offset at which the sparse child arrays begin in the slots vector. +pub(super) const CHILDREN_OFFSET: usize = 1; + +pub(super) fn make_union_slots(type_ids: &ArrayRef, children: &[ArrayRef]) -> ArraySlots { + once(Some(type_ids.clone())) + .chain(children.iter().cloned().map(Some)) + .collect() +} + +/// Concrete parts of a [`UnionArray`](super::UnionArray). +pub struct UnionDataParts { + /// The union variant schema. + pub variants: UnionVariants, + /// The row-aligned type IDs. + pub type_ids: ArrayRef, + /// The row-aligned sparse children in variant order. + pub children: Arc<[ArrayRef]>, +} + +/// Accessors for a canonical sparse union array. +pub trait UnionArrayExt: TypedArrayRef { + /// The union's variant schema. + fn variants(&self) -> &UnionVariants { + match self.as_ref().dtype() { + DType::Union(variants) => variants, + _ => unreachable!("UnionArrayExt requires a union dtype"), + } + } + + /// The row-aligned non-nullable `i8` type IDs. + fn type_ids(&self) -> &ArrayRef { + self.as_ref().slots()[TYPE_IDS_SLOT] + .as_ref() + .vortex_expect("UnionArray type_ids slot") + } + + /// Iterate over sparse children in variant order. + fn iter_children(&self) -> impl ExactSizeIterator + '_ { + self.as_ref().slots()[CHILDREN_OFFSET..] + .iter() + .map(|slot| slot.as_ref().vortex_expect("UnionArray child slot")) + } + + /// Return the sparse children in variant order. + fn children(&self) -> Arc<[ArrayRef]> { + self.iter_children().cloned().collect() + } + + /// Return a sparse child by its variant index. + fn child(&self, index: usize) -> Option<&ArrayRef> { + self.as_ref().slots().get(CHILDREN_OFFSET + index)?.as_ref() + } + + /// Return a sparse child selected by a data-level type ID. + fn child_by_type_id(&self, type_id: i8) -> Option<&ArrayRef> { + self.child(self.variants().tag_to_child_index(type_id)?) + } +} +impl> UnionArrayExt for T {} + +impl Array { + /// Construct a canonical sparse union array. + pub fn new( + type_ids: ArrayRef, + variants: UnionVariants, + children: impl Into>, + ) -> Self { + Self::try_new(type_ids, variants, children).vortex_expect("UnionArray construction failed") + } + + /// Try to construct a canonical sparse union array. + /// + /// Until Union nullability semantics are settled, the union and every child must be + /// non-nullable. + #[allow(clippy::disallowed_methods)] + pub fn try_new( + type_ids: ArrayRef, + variants: UnionVariants, + children: impl Into>, + ) -> VortexResult { + vortex_ensure!( + type_ids.dtype() == &DType::Primitive(PType::I8, Nullability::NonNullable), + "UnionArray type_ids must be non-nullable i8, got {}", + type_ids.dtype() + ); + + let children = children.into(); + let len = type_ids.len(); + let dtype = DType::Union(variants.clone()); + let slots = make_union_slots(&type_ids, &children); + let array = Array::try_from_parts( + ArrayParts::new(Union, dtype, len, EmptyArrayData).with_slots(slots), + )?; + + // Validate data-level tags when they are host-resident. Keep scalar access fallible so an + // invalid tag from non-host or untrusted serialized input still produces an error rather + // than unchecked indexing. + if type_ids.is_host() { + let primitive = + type_ids.execute::(&mut legacy_session().create_execution_ctx())?; + for type_id in primitive.as_slice::() { + vortex_ensure!( + variants.tag_to_child_index(*type_id).is_some(), + "UnionArray type ID {type_id} is not present in {:?}", + variants.type_ids() + ); + } + } + + Ok(array) + } + + /// Construct a canonical sparse union array without validation. + /// + /// # Safety + /// + /// The caller must ensure the type IDs are non-nullable `i8` values declared by `variants`, + /// every child has the corresponding variant dtype, and all arrays have the same length. The + /// union and its children must currently be non-nullable. + pub unsafe fn new_unchecked( + type_ids: ArrayRef, + variants: UnionVariants, + children: impl Into>, + ) -> Self { + let children = children.into(); + let len = type_ids.len(); + let slots = make_union_slots(&type_ids, &children); + unsafe { + Array::from_parts_unchecked( + ArrayParts::new(Union, DType::Union(variants), len, EmptyArrayData) + .with_slots(slots), + ) + } + } + + /// Deconstruct this array into its type IDs, variant schema, and sparse children. + pub fn into_data_parts(self) -> UnionDataParts { + let variants = self.variants().clone(); + let type_ids = self.type_ids().clone(); + let children = self.children(); + UnionDataParts { + variants, + type_ids, + children, + } + } + + /// Return the sparse child for a variant name. + pub fn child_by_name(&self, name: impl AsRef) -> VortexResult<&ArrayRef> { + let name = name.as_ref(); + let index = self + .variants() + .find(name) + .ok_or_else(|| vortex_err!("Unknown UnionArray variant {name}"))?; + Ok(self + .child(index) + .vortex_expect("variant index must have a child")) + } + + /// Create an empty array for a non-nullable union dtype. + pub(crate) fn empty(variants: UnionVariants) -> Self { + assert!( + variants.variants().all(|dtype| !dtype.is_nullable()), + "Canonical UnionArray children must be non-nullable" + ); + let type_ids = PrimitiveArray::from_iter(Vec::::new()).into_array(); + let children = variants + .variants() + .map(|dtype| crate::Canonical::empty(&dtype).into_array()) + .collect_vec(); + // SAFETY: All components are empty and use the dtypes declared by variants. + unsafe { Self::new_unchecked(type_ids, variants, children) } + } +} diff --git a/vortex-array/src/arrays/union/compute/filter.rs b/vortex-array/src/arrays/union/compute/filter.rs new file mode 100644 index 00000000000..013c2b8c3ea --- /dev/null +++ b/vortex-array/src/arrays/union/compute/filter.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use crate::ArrayRef; +use crate::IntoArray; +use crate::array::ArrayView; +use crate::arrays::Union; +use crate::arrays::UnionArray; +use crate::arrays::filter::FilterReduce; +use crate::arrays::union::UnionArrayExt; + +impl FilterReduce for Union { + fn filter(array: ArrayView<'_, Union>, mask: &Mask) -> VortexResult> { + let type_ids = array.type_ids().filter(mask.clone())?; + let children = array + .iter_children() + .map(|child| child.filter(mask.clone())) + .collect::>>()?; + + // SAFETY: Filtering every row-aligned component by the same mask preserves all invariants. + Ok(Some( + unsafe { UnionArray::new_unchecked(type_ids, array.variants().clone(), children) } + .into_array(), + )) + } +} diff --git a/vortex-array/src/arrays/union/compute/mod.rs b/vortex-array/src/arrays/union/compute/mod.rs new file mode 100644 index 00000000000..5da8b60b65d --- /dev/null +++ b/vortex-array/src/arrays/union/compute/mod.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +mod filter; +pub(crate) mod rules; +mod slice; +mod take; diff --git a/vortex-array/src/arrays/union/compute/rules.rs b/vortex-array/src/arrays/union/compute/rules.rs new file mode 100644 index 00000000000..4666a99b92f --- /dev/null +++ b/vortex-array/src/arrays/union/compute/rules.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use crate::arrays::Union; +use crate::arrays::dict::TakeReduceAdaptor; +use crate::arrays::filter::FilterReduceAdaptor; +use crate::arrays::slice::SliceReduceAdaptor; +use crate::optimizer::rules::ParentRuleSet; + +pub(crate) const PARENT_RULES: ParentRuleSet = ParentRuleSet::new(&[ + ParentRuleSet::lift(&SliceReduceAdaptor(Union)), + ParentRuleSet::lift(&FilterReduceAdaptor(Union)), + ParentRuleSet::lift(&TakeReduceAdaptor(Union)), +]); diff --git a/vortex-array/src/arrays/union/compute/slice.rs b/vortex-array/src/arrays/union/compute/slice.rs new file mode 100644 index 00000000000..3d912130e1b --- /dev/null +++ b/vortex-array/src/arrays/union/compute/slice.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; + +use vortex_error::VortexResult; + +use crate::ArrayRef; +use crate::IntoArray; +use crate::array::ArrayView; +use crate::arrays::Union; +use crate::arrays::UnionArray; +use crate::arrays::slice::SliceReduce; +use crate::arrays::union::UnionArrayExt; + +impl SliceReduce for Union { + fn slice(array: ArrayView<'_, Union>, range: Range) -> VortexResult> { + let type_ids = array.type_ids().slice(range.clone())?; + let children = array + .iter_children() + .map(|child| child.slice(range.clone())) + .collect::>>()?; + + // SAFETY: Slicing every row-aligned component by the same range preserves all invariants. + Ok(Some( + unsafe { UnionArray::new_unchecked(type_ids, array.variants().clone(), children) } + .into_array(), + )) + } +} diff --git a/vortex-array/src/arrays/union/compute/take.rs b/vortex-array/src/arrays/union/compute/take.rs new file mode 100644 index 00000000000..a9824678922 --- /dev/null +++ b/vortex-array/src/arrays/union/compute/take.rs @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_error::VortexResult; +use vortex_error::vortex_bail; + +use crate::ArrayRef; +use crate::IntoArray; +use crate::array::ArrayView; +use crate::arrays::Union; +use crate::arrays::UnionArray; +use crate::arrays::dict::TakeReduce; +use crate::arrays::union::UnionArrayExt; + +impl TakeReduce for Union { + fn take(array: ArrayView<'_, Union>, indices: &ArrayRef) -> VortexResult> { + if indices.dtype().is_nullable() { + vortex_bail!("Taking UnionArray with nullable indices is not supported yet") + } + + let type_ids = array.type_ids().take(indices.clone())?; + let children = array + .iter_children() + .map(|child| child.take(indices.clone())) + .collect::>>()?; + + // SAFETY: Taking every row-aligned component with the same non-null indices preserves all + // invariants and cannot introduce nulls. + Ok(Some( + unsafe { UnionArray::new_unchecked(type_ids, array.variants().clone(), children) } + .into_array(), + )) + } +} diff --git a/vortex-array/src/arrays/union/mod.rs b/vortex-array/src/arrays/union/mod.rs new file mode 100644 index 00000000000..9f54572b9ec --- /dev/null +++ b/vortex-array/src/arrays/union/mod.rs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +mod array; +pub use array::UnionArrayExt; +pub use array::UnionDataParts; + +pub(crate) mod compute; + +mod vtable; +pub use vtable::Union; +pub use vtable::UnionArray; + +#[cfg(test)] +mod tests; diff --git a/vortex-array/src/arrays/union/tests.rs b/vortex-array/src/arrays/union/tests.rs new file mode 100644 index 00000000000..f22834ed06a --- /dev/null +++ b/vortex-array/src/arrays/union/tests.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_buffer::ByteBufferMut; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_mask::Mask; +use vortex_session::registry::ReadContext; + +use crate::ArrayContext; +use crate::IntoArray; +use crate::VortexSessionExecute; +use crate::array_session; +use crate::arrays::BoolArray; +use crate::arrays::Chunked; +use crate::arrays::ChunkedArray; +use crate::arrays::ConstantArray; +use crate::arrays::PrimitiveArray; +use crate::arrays::Union; +use crate::arrays::UnionArray; +use crate::arrays::union::UnionArrayExt; +use crate::dtype::DType; +use crate::dtype::Nullability; +use crate::dtype::PType; +use crate::dtype::UnionVariants; +use crate::scalar::Scalar; +use crate::serde::SerializeOptions; +use crate::serde::SerializedArray; +use crate::validity::Validity; + +fn variants() -> VortexResult { + UnionVariants::try_new( + ["number", "flag"].into(), + vec![ + DType::Primitive(PType::I32, Nullability::NonNullable), + DType::Bool(Nullability::NonNullable), + ], + vec![5, 9], + ) +} + +fn union_array() -> VortexResult { + UnionArray::try_new( + PrimitiveArray::from_iter([5i8, 9, 5]).into_array(), + variants()?, + vec![ + PrimitiveArray::from_iter([10i32, 0, 30]).into_array(), + BoolArray::from_iter([false, true, false]).into_array(), + ], + ) +} + +#[test] +fn scalar_at_uses_type_id_indirection() -> VortexResult<()> { + let array = union_array()?; + let mut ctx = array_session().create_execution_ctx(); + + assert_eq!( + array.execute_scalar(0, &mut ctx)?, + Scalar::union(variants()?, 5, 10i32.into())? + ); + assert_eq!( + array.execute_scalar(1, &mut ctx)?, + Scalar::union(variants()?, 9, true.into())? + ); + assert!(matches!(array.validity()?, Validity::NonNullable)); + + Ok(()) +} + +#[test] +fn validates_sparse_components() -> VortexResult<()> { + let children = vec![ + PrimitiveArray::from_iter([10i32, 0, 30]).into_array(), + BoolArray::from_iter([false, true, false]).into_array(), + ]; + + assert!( + UnionArray::try_new( + PrimitiveArray::from_iter([5i8, 7, 5]).into_array(), + variants()?, + children.clone(), + ) + .is_err() + ); + assert!( + UnionArray::try_new( + PrimitiveArray::from_iter([5i8, 9]).into_array(), + variants()?, + children, + ) + .is_err() + ); + assert!( + UnionArray::try_new( + PrimitiveArray::from_iter([5i8, 9, 5]).into_array(), + variants()?, + vec![ + PrimitiveArray::new(buffer![10i32, 0, 30], Validity::AllValid).into_array(), + BoolArray::from_iter([false, true, false]).into_array(), + ], + ) + .is_err() + ); + + Ok(()) +} + +#[test] +fn structural_operations_preserve_sparse_alignment() -> VortexResult<()> { + let array = union_array()?.into_array(); + let mut ctx = array_session().create_execution_ctx(); + + let sliced = array.slice(1..3)?; + let filtered = array.filter(Mask::from_iter([true, false, true]))?; + let taken = array.take(PrimitiveArray::from_iter([2u32, 1]).into_array())?; + + assert_eq!( + sliced.execute_scalar(0, &mut ctx)?, + Scalar::union(variants()?, 9, true.into())? + ); + assert_eq!( + filtered.execute_scalar(1, &mut ctx)?, + Scalar::union(variants()?, 5, 30i32.into())? + ); + assert_eq!( + taken.execute_scalar(0, &mut ctx)?, + Scalar::union(variants()?, 5, 30i32.into())? + ); + + Ok(()) +} + +#[test] +fn serde_roundtrip() -> VortexResult<()> { + let session = array_session(); + let mut execution_ctx = session.create_execution_ctx(); + let array = union_array()?; + let dtype = array.dtype().clone(); + let len = array.len(); + let array_ctx = ArrayContext::empty(); + let serialized = + array + .clone() + .into_array() + .serialize(&array_ctx, &session, &SerializeOptions::default())?; + let mut concat = ByteBufferMut::empty(); + for buffer in serialized { + concat.extend_from_slice(buffer.as_ref()); + } + let decoded = SerializedArray::try_from(concat.freeze())?.decode( + &dtype, + len, + &ReadContext::new(array_ctx.to_ids()), + &session, + )?; + let decoded = decoded.as_::(); + + assert_eq!(decoded.variants(), array.variants()); + for index in 0..len { + assert_eq!( + decoded.array().execute_scalar(index, &mut execution_ctx)?, + array.execute_scalar(index, &mut execution_ctx)? + ); + } + + Ok(()) +} + +#[test] +fn constant_union_executes_to_sparse_union() -> VortexResult<()> { + let scalar = Scalar::union(variants()?, 9, true.into())?; + let mut ctx = array_session().create_execution_ctx(); + let array = ConstantArray::new(scalar.clone(), 3) + .into_array() + .execute::(&mut ctx)?; + + assert_eq!(array.len(), 3); + assert_eq!(array.execute_scalar(2, &mut ctx)?, scalar); + + Ok(()) +} + +#[test] +fn chunked_union_packs_components() -> VortexResult<()> { + let first = union_array()?.into_array().slice(0..1)?; + let second = union_array()?.into_array().slice(1..3)?; + let dtype = first.dtype().clone(); + let chunked = ChunkedArray::try_new(vec![first, second], dtype)?.into_array(); + let mut ctx = array_session().create_execution_ctx(); + let canonical = chunked.execute::(&mut ctx)?; + + assert!(canonical.type_ids().is::()); + assert!(canonical.iter_children().all(|child| child.is::())); + assert_eq!( + canonical.execute_scalar(2, &mut ctx)?, + Scalar::union(variants()?, 5, 30i32.into())? + ); + + Ok(()) +} diff --git a/vortex-array/src/arrays/union/vtable/mod.rs b/vortex-array/src/arrays/union/vtable/mod.rs new file mode 100644 index 00000000000..d19c7c46563 --- /dev/null +++ b/vortex-array/src/arrays/union/vtable/mod.rs @@ -0,0 +1,207 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use itertools::Itertools; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_panic; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +use crate::ArrayRef; +use crate::ExecutionCtx; +use crate::ExecutionResult; +use crate::array::Array; +use crate::array::ArrayId; +use crate::array::ArrayParts; +use crate::array::ArrayView; +use crate::array::EmptyArrayData; +use crate::array::VTable; +use crate::array::with_empty_buffers; +use crate::arrays::union::UnionArrayExt; +use crate::arrays::union::array::CHILDREN_OFFSET; +use crate::arrays::union::array::TYPE_IDS_SLOT; +use crate::arrays::union::array::make_union_slots; +use crate::arrays::union::compute::rules::PARENT_RULES; +use crate::buffer::BufferHandle; +use crate::builders::ArrayBuilder; +use crate::dtype::DType; +use crate::dtype::Nullability; +use crate::dtype::PType; +use crate::serde::ArrayChildren; + +mod operations; +mod validity; + +/// A canonical sparse [`Union`]-encoded array. +pub type UnionArray = Array; + +/// The canonical sparse Union encoding. +#[derive(Clone, Debug)] +pub struct Union; + +impl VTable for Union { + type TypedArrayData = EmptyArrayData; + type OperationsVTable = Self; + type ValidityVTable = Self; + + fn id(&self) -> ArrayId { + static ID: CachedId = CachedId::new("vortex.union"); + *ID + } + + fn validate( + &self, + _data: &EmptyArrayData, + dtype: &DType, + len: usize, + slots: &[Option], + ) -> VortexResult<()> { + let DType::Union(variants) = dtype else { + vortex_bail!("Expected union dtype, found {dtype}") + }; + vortex_ensure!( + !dtype.is_nullable(), + "Nullable UnionArray is not supported yet" + ); + vortex_ensure!( + variants.variants().all(|variant| !variant.is_nullable()), + "UnionArray children must be non-nullable" + ); + vortex_ensure!( + slots.len() == CHILDREN_OFFSET + variants.len(), + "UnionArray has {} slots but expected {}", + slots.len(), + CHILDREN_OFFSET + variants.len() + ); + + let type_ids = slots[TYPE_IDS_SLOT] + .as_ref() + .vortex_expect("UnionArray type_ids slot"); + vortex_ensure!( + type_ids.dtype() == &DType::Primitive(PType::I8, Nullability::NonNullable), + "UnionArray type_ids must be non-nullable i8, got {}", + type_ids.dtype() + ); + vortex_ensure!( + type_ids.len() == len, + "UnionArray type_ids length {} does not match outer length {len}", + type_ids.len() + ); + + for (index, (slot, variant_dtype)) in slots[CHILDREN_OFFSET..] + .iter() + .zip_eq(variants.variants()) + .enumerate() + { + let child = slot + .as_ref() + .ok_or_else(|| vortex_error::vortex_err!("UnionArray missing child {index}"))?; + vortex_ensure!( + child.len() == len, + "UnionArray child {index} length {} does not match outer length {len}", + child.len() + ); + vortex_ensure!( + child.dtype() == &variant_dtype, + "UnionArray child {index} has dtype {} but expected {variant_dtype}", + child.dtype() + ); + } + + Ok(()) + } + + fn nbuffers(_array: ArrayView<'_, Self>) -> usize { + 0 + } + + fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle { + vortex_panic!("UnionArray buffer index {idx} out of bounds") + } + + fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option { + vortex_panic!("UnionArray buffer_name index {idx} out of bounds") + } + + fn with_buffers( + &self, + array: ArrayView<'_, Self>, + buffers: &[BufferHandle], + ) -> VortexResult> { + with_empty_buffers(self, array, buffers) + } + + fn serialize( + _array: ArrayView<'_, Self>, + _session: &VortexSession, + ) -> VortexResult>> { + Ok(Some(vec![])) + } + + fn deserialize( + &self, + dtype: &DType, + len: usize, + metadata: &[u8], + buffers: &[BufferHandle], + children: &dyn ArrayChildren, + _session: &VortexSession, + ) -> VortexResult> { + vortex_ensure!(metadata.is_empty(), "UnionArray expects empty metadata"); + vortex_ensure!(buffers.is_empty(), "UnionArray expects no buffers"); + let DType::Union(variants) = dtype else { + vortex_bail!("Expected union dtype, found {dtype}") + }; + vortex_ensure!( + children.len() == CHILDREN_OFFSET + variants.len(), + "UnionArray expected {} children, found {}", + CHILDREN_OFFSET + variants.len(), + children.len() + ); + + let type_ids = children.get( + TYPE_IDS_SLOT, + &DType::Primitive(PType::I8, Nullability::NonNullable), + len, + )?; + let sparse_children = variants + .variants() + .enumerate() + .map(|(index, dtype)| children.get(CHILDREN_OFFSET + index, &dtype, len)) + .try_collect::<_, Vec<_>, _>()?; + let slots = make_union_slots(&type_ids, &sparse_children); + + Ok(ArrayParts::new(self.clone(), dtype.clone(), len, EmptyArrayData).with_slots(slots)) + } + + fn slot_name(array: ArrayView<'_, Self>, idx: usize) -> String { + if idx == TYPE_IDS_SLOT { + "type_ids".to_string() + } else { + array.variants().names()[idx - CHILDREN_OFFSET].to_string() + } + } + + fn execute(array: Array, _ctx: &mut ExecutionCtx) -> VortexResult { + Ok(ExecutionResult::done(array)) + } + + fn append_to_builder( + _array: ArrayView<'_, Self>, + _builder: &mut dyn ArrayBuilder, + _ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + vortex_bail!("append_to_builder is not supported for UnionArray yet") + } + + fn reduce_parent( + array: ArrayView<'_, Self>, + parent: &ArrayRef, + child_idx: usize, + ) -> VortexResult> { + PARENT_RULES.evaluate(array, parent, child_idx) + } +} diff --git a/vortex-array/src/arrays/union/vtable/operations.rs b/vortex-array/src/arrays/union/vtable/operations.rs new file mode 100644 index 00000000000..debd1b4ebac --- /dev/null +++ b/vortex-array/src/arrays/union/vtable/operations.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_error::VortexResult; +use vortex_error::vortex_err; + +use crate::ExecutionCtx; +use crate::array::ArrayView; +use crate::array::OperationsVTable; +use crate::arrays::Union; +use crate::arrays::union::UnionArrayExt; +use crate::scalar::Scalar; + +impl OperationsVTable for Union { + fn scalar_at( + array: ArrayView<'_, Union>, + index: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let type_id = array + .type_ids() + .execute_scalar(index, ctx)? + .as_primitive() + .typed_value::() + .ok_or_else(|| vortex_err!("UnionArray type ID at index {index} is null"))?; + let child_index = array + .variants() + .tag_to_child_index(type_id) + .ok_or_else(|| vortex_err!("Unknown UnionArray type ID {type_id}"))?; + let child = array + .child(child_index) + .ok_or_else(|| vortex_err!("UnionArray is missing child {child_index}"))?; + let child_scalar = child.execute_scalar(index, ctx)?; + + Scalar::union(array.variants().clone(), type_id, child_scalar) + } +} diff --git a/vortex-array/src/arrays/union/vtable/validity.rs b/vortex-array/src/arrays/union/vtable/validity.rs new file mode 100644 index 00000000000..0231b7a3334 --- /dev/null +++ b/vortex-array/src/arrays/union/vtable/validity.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_error::VortexResult; + +use crate::array::ArrayView; +use crate::array::ValidityVTable; +use crate::arrays::Union; +use crate::validity::Validity; + +impl ValidityVTable for Union { + fn validity(_array: ArrayView<'_, Union>) -> VortexResult { + // TODO(connor)[Union]: define how union and child nullability interact. + Ok(Validity::NonNullable) + } +} diff --git a/vortex-array/src/canonical.rs b/vortex-array/src/canonical.rs index 71da52e1300..f8daca7e4a9 100644 --- a/vortex-array/src/canonical.rs +++ b/vortex-array/src/canonical.rs @@ -35,6 +35,8 @@ use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::arrays::Struct; use crate::arrays::StructArray; +use crate::arrays::Union; +use crate::arrays::UnionArray; use crate::arrays::VarBinView; use crate::arrays::VarBinViewArray; use crate::arrays::Variant; @@ -47,6 +49,7 @@ use crate::arrays::listview::ListViewDataParts; use crate::arrays::listview::ListViewRebuildMode; use crate::arrays::primitive::PrimitiveDataParts; use crate::arrays::struct_::StructDataParts; +use crate::arrays::union::UnionDataParts; use crate::arrays::varbinview::VarBinViewDataParts; use crate::arrays::variant::VariantArrayExt; use crate::dtype::DType; @@ -69,7 +72,7 @@ use crate::validity::Validity; /// /// Each `Canonical` variant has a corresponding [`DType`] variant, with the notable exception of /// [`Canonical::VarBinView`], which is the canonical encoding for both [`DType::Utf8`] and -/// [`DType::Binary`]. [`DType::Union`] does not yet have a public canonical array. +/// [`DType::Binary`]. /// /// # Laziness /// @@ -80,8 +83,9 @@ use crate::validity::Validity; /// /// # Arrow interoperability /// -/// All of the Vortex canonical encodings have an equivalent Arrow encoding that can be built -/// zero-copy, and the corresponding Arrow array types can also be built directly. +/// Except for the currently experimental union encoding, Vortex canonical encodings have an +/// equivalent Arrow encoding that can be built zero-copy, and the corresponding Arrow array types +/// can also be built directly. /// /// The full list of canonical types and their equivalent Arrow array types are: /// @@ -128,6 +132,7 @@ pub enum Canonical { List(ListViewArray), FixedSizeList(FixedSizeListArray), Struct(StructArray), + Union(UnionArray), /// Canonical storage for extension dtypes, wrapping the canonical form of the storage dtype. Extension(ExtensionArray), /// Canonical storage for dynamic variant values, optionally with typed shredded paths. @@ -146,6 +151,7 @@ macro_rules! match_each_canonical { Canonical::List($ident) => $eval, Canonical::FixedSizeList($ident) => $eval, Canonical::Struct($ident) => $eval, + Canonical::Union($ident) => $eval, Canonical::Variant($ident) => $eval, Canonical::Extension($ident) => $eval, } @@ -228,7 +234,7 @@ impl Canonical { Validity::from(n), ) }), - DType::Union(..) => todo!("TODO(connor)[Union]: unimplemented"), + DType::Union(variants) => Canonical::Union(UnionArray::empty(variants.clone())), DType::Variant(_) => { vortex_panic!(InvalidArgument: "Canonical empty is not supported for Variant") } @@ -401,6 +407,24 @@ impl Canonical { } } + /// Return this canonical array as a sparse [`UnionArray`]. + pub fn as_union(&self) -> &UnionArray { + if let Canonical::Union(a) = self { + a + } else { + vortex_panic!("Cannot get UnionArray from {:?}", &self) + } + } + + /// Unwrap this canonical array as a sparse [`UnionArray`]. + pub fn into_union(self) -> UnionArray { + if let Canonical::Union(a) = self { + a + } else { + vortex_panic!("Cannot unwrap UnionArray from {:?}", &self) + } + } + pub fn as_extension(&self) -> &ExtensionArray { if let Canonical::Extension(a) = self { a @@ -652,6 +676,7 @@ impl Executable for CanonicalValidity { StructArray::new_unchecked(fields, struct_fields, len, validity.execute(ctx)?) }))) } + union @ Canonical::Union(_) => Ok(CanonicalValidity(union)), Canonical::Extension(ext) => Ok(CanonicalValidity(Canonical::Extension( ExtensionArray::new( ext.ext_dtype().clone(), @@ -829,6 +854,28 @@ impl Executable for RecursiveCanonical { ) }))) } + Canonical::Union(union) => { + let UnionDataParts { + variants, + type_ids, + children, + } = union.into_data_parts(); + let type_ids = type_ids.execute::(ctx)?.0.into_array(); + let children = children + .iter() + .map(|child| { + Ok(child + .clone() + .execute::(ctx)? + .0 + .into_array()) + }) + .collect::>>()?; + + Ok(RecursiveCanonical(Canonical::Union(unsafe { + UnionArray::new_unchecked(type_ids, variants, children) + }))) + } Canonical::Extension(ext) => Ok(RecursiveCanonical(Canonical::Extension( ExtensionArray::new( ext.ext_dtype().clone(), @@ -1003,6 +1050,18 @@ impl Executable for StructArray { } } +/// Execute the array to canonical form and unwrap as a [`UnionArray`]. +/// +/// This will panic if the array's dtype is not union. +impl Executable for UnionArray { + fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { + match array.try_downcast::() { + Ok(union_array) => Ok(union_array), + Err(array) => Ok(Canonical::execute(array, ctx)?.into_union()), + } + } +} + /// Execute the array to canonical form and unwrap as a [`VariantArray`]. /// /// This will panic if the array's dtype is not variant. @@ -1032,6 +1091,7 @@ pub enum CanonicalView<'a> { List(ArrayView<'a, ListView>), FixedSizeList(ArrayView<'a, FixedSizeList>), Struct(ArrayView<'a, Struct>), + Union(ArrayView<'a, Union>), Extension(ArrayView<'a, Extension>), Variant(ArrayView<'a, Variant>), } @@ -1047,6 +1107,7 @@ impl From> for Canonical { CanonicalView::List(a) => Canonical::List(a.into_owned()), CanonicalView::FixedSizeList(a) => Canonical::FixedSizeList(a.into_owned()), CanonicalView::Struct(a) => Canonical::Struct(a.into_owned()), + CanonicalView::Union(a) => Canonical::Union(a.into_owned()), CanonicalView::Extension(a) => Canonical::Extension(a.into_owned()), CanonicalView::Variant(a) => Canonical::Variant(a.into_owned()), } @@ -1065,6 +1126,7 @@ impl CanonicalView<'_> { CanonicalView::List(a) => a.array().clone(), CanonicalView::FixedSizeList(a) => a.array().clone(), CanonicalView::Struct(a) => a.array().clone(), + CanonicalView::Union(a) => a.array().clone(), CanonicalView::Extension(a) => a.array().clone(), CanonicalView::Variant(a) => a.array().clone(), } @@ -1083,6 +1145,7 @@ impl Matcher for AnyCanonical { || array.is::() || array.is::() || array.is::() + || array.is::() || array.is::() || array.is::() || array.is::() @@ -1102,6 +1165,8 @@ impl Matcher for AnyCanonical { Some(CanonicalView::Decimal(a)) } else if let Some(a) = array.as_opt::() { Some(CanonicalView::Struct(a)) + } else if let Some(a) = array.as_opt::() { + Some(CanonicalView::Union(a)) } else if let Some(a) = array.as_opt::() { Some(CanonicalView::List(a)) } else if let Some(a) = array.as_opt::() { diff --git a/vortex-array/src/dtype/dtype_impl.rs b/vortex-array/src/dtype/dtype_impl.rs index e3594f818c6..ce52079a94e 100644 --- a/vortex-array/src/dtype/dtype_impl.rs +++ b/vortex-array/src/dtype/dtype_impl.rs @@ -312,7 +312,7 @@ impl DType { } Some(sum) } - Union(..) => todo!("TODO(connor)[Union]: unimplemented"), + Union(..) => None, Variant(_) => None, Extension(ext) => ext.storage_dtype().element_size(), } diff --git a/vortex-array/src/lib.rs b/vortex-array/src/lib.rs index 9d3a59eb7a0..04be12a6d03 100644 --- a/vortex-array/src/lib.rs +++ b/vortex-array/src/lib.rs @@ -40,7 +40,7 @@ //! # Built-in, Lazy, and Experimental Arrays //! //! Built-in arrays live in [`arrays`]. Some are canonical (`PrimitiveArray`, `StructArray`, -//! `VarBinViewArray`); others are utility or lazy arrays such as [`ChunkedArray`], +//! `UnionArray`, `VarBinViewArray`); others are utility or lazy arrays such as [`ChunkedArray`], //! [`ConstantArray`], [`FilterArray`], [`SliceArray`], and [`ScalarFnArray`]. //! Lazy arrays defer work so compute kernels can operate on encoded data or prune children //! before materialization. diff --git a/vortex-array/src/scalar_fn/fns/cast/mod.rs b/vortex-array/src/scalar_fn/fns/cast/mod.rs index 20852779d42..1959da25a1d 100644 --- a/vortex-array/src/scalar_fn/fns/cast/mod.rs +++ b/vortex-array/src/scalar_fn/fns/cast/mod.rs @@ -185,6 +185,9 @@ fn cast_canonical( CanonicalView::List(a) => ::cast(a, dtype, ctx), CanonicalView::FixedSizeList(a) => ::cast(a, dtype, ctx), CanonicalView::Struct(a) => struct_cast(a, dtype, ctx), + CanonicalView::Union(_) => { + vortex_bail!("Union arrays don't support casting yet") + } CanonicalView::Extension(a) => ::cast(a, dtype), CanonicalView::Variant(_) => { vortex_bail!("Variant arrays don't support casting") diff --git a/vortex-array/src/session/mod.rs b/vortex-array/src/session/mod.rs index 2cb8414cbfd..c844a7b8015 100644 --- a/vortex-array/src/session/mod.rs +++ b/vortex-array/src/session/mod.rs @@ -27,6 +27,7 @@ use crate::arrays::Masked; use crate::arrays::Null; use crate::arrays::Primitive; use crate::arrays::Struct; +use crate::arrays::Union; use crate::arrays::VarBin; use crate::arrays::VarBinView; use crate::arrays::Variant; @@ -72,6 +73,7 @@ impl Default for ArraySession { this.register(ListView); this.register(FixedSizeList); this.register(Struct); + this.register(Union); this.register(Variant); this.register(Extension); diff --git a/vortex-compressor/src/compressor/cascade.rs b/vortex-compressor/src/compressor/cascade.rs index 9dbbc611448..d5797b0b37f 100644 --- a/vortex-compressor/src/compressor/cascade.rs +++ b/vortex-compressor/src/compressor/cascade.rs @@ -14,6 +14,7 @@ use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::FixedSizeListArray; use vortex_array::arrays::Masked; use vortex_array::arrays::StructArray; +use vortex_array::arrays::UnionArray; use vortex_array::arrays::Variant; use vortex_array::arrays::VariantArray; use vortex_array::arrays::extension::ExtensionArrayExt; @@ -23,6 +24,7 @@ use vortex_array::arrays::listview::list_from_list_view; use vortex_array::arrays::masked::MaskedArraySlotsExt; use vortex_array::arrays::scalar_fn::AnyScalarFn; use vortex_array::arrays::struct_::StructArrayExt; +use vortex_array::arrays::union::UnionArrayExt; use vortex_array::arrays::variant::VariantArrayExt; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; @@ -130,6 +132,18 @@ impl CascadingCompressor { )? .into_array()) } + Canonical::Union(union_array) => { + let type_ids = self.compress(union_array.type_ids(), exec_ctx)?; + let children = union_array + .iter_children() + .map(|child| self.compress(child, exec_ctx)) + .collect::>>()?; + + Ok( + UnionArray::try_new(type_ids, union_array.variants().clone(), children)? + .into_array(), + ) + } Canonical::List(list_view_array) => { if list_view_array.is_zero_copy_to_list() || list_view_array.elements().is_empty() { let list_array = list_from_list_view(list_view_array, exec_ctx)?; diff --git a/vortex-duckdb/src/exporter/canonical.rs b/vortex-duckdb/src/exporter/canonical.rs index 7ee47a40642..0bf9067250c 100644 --- a/vortex-duckdb/src/exporter/canonical.rs +++ b/vortex-duckdb/src/exporter/canonical.rs @@ -32,6 +32,9 @@ pub(crate) fn new_exporter( Canonical::List(array) => list_view::new_exporter(array, cache, ctx), Canonical::FixedSizeList(array) => fixed_size_list::new_exporter(array, cache, ctx), Canonical::Struct(array) => struct_::new_exporter(array, cache, ctx), + Canonical::Union(_) => { + vortex_bail!("Union arrays can't be exported to DuckDB yet") + } Canonical::Extension(ext) => extension::new_exporter(ext, ctx), Canonical::Variant(_) => { vortex_bail!("Variant arrays can't be exported to DuckDB") From 306ea83c5127834f0b9667193b23c7290810f349 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Wed, 15 Jul 2026 16:31:52 -0400 Subject: [PATCH 2/2] Clean up UnionArray implementation Signed-off-by: Connor Tsui --- .../src/arrays/chunked/vtable/canonical.rs | 12 +- .../src/arrays/constant/vtable/canonical.rs | 88 ++++++------ vortex-array/src/arrays/dict/execute.rs | 17 +-- vortex-array/src/arrays/filter/execute/mod.rs | 17 ++- vortex-array/src/arrays/union/array.rs | 131 ++++++++++-------- .../src/arrays/union/compute/filter.rs | 23 +-- vortex-array/src/arrays/union/compute/mod.rs | 5 + vortex-array/src/arrays/union/compute/take.rs | 36 ++--- vortex-array/src/arrays/union/mod.rs | 17 ++- vortex-array/src/arrays/union/tests.rs | 49 +++---- vortex-array/src/arrays/union/vtable/mod.rs | 41 ++---- vortex-array/src/canonical.rs | 9 +- 12 files changed, 234 insertions(+), 211 deletions(-) diff --git a/vortex-array/src/arrays/chunked/vtable/canonical.rs b/vortex-array/src/arrays/chunked/vtable/canonical.rs index 3992a38ff82..dcf8af39ae5 100644 --- a/vortex-array/src/arrays/chunked/vtable/canonical.rs +++ b/vortex-array/src/arrays/chunked/vtable/canonical.rs @@ -25,6 +25,7 @@ use crate::arrays::chunked::ChunkedArrayExt; use crate::arrays::fixed_size_list::FixedSizeListArrayExt; use crate::arrays::listview::ListViewArrayExt; use crate::arrays::listview::ListViewRebuildMode; +use crate::arrays::union::TYPE_IDS_DTYPE; use crate::arrays::union::UnionArrayExt; use crate::arrays::variant::VariantArrayExt; use crate::builders::builder_with_capacity_in; @@ -104,14 +105,13 @@ fn pack_union_chunks(chunks: Vec, ctx: &mut ExecutionCtx) -> VortexRes .iter() .map(|chunk| chunk.type_ids().clone()) .collect(), - DType::Primitive(PType::I8, Nullability::NonNullable), + TYPE_IDS_DTYPE, )? .into_array(); - let children = (0..variants.len()) - .map(|index| { - let dtype = variants - .variant_by_index(index) - .vortex_expect("variant index must have a dtype"); + let children = variants + .variants() + .enumerate() + .map(|(index, dtype)| { ChunkedArray::try_new( union_chunks .iter() diff --git a/vortex-array/src/arrays/constant/vtable/canonical.rs b/vortex-array/src/arrays/constant/vtable/canonical.rs index 919d4607076..ff4c1784700 100644 --- a/vortex-array/src/arrays/constant/vtable/canonical.rs +++ b/vortex-array/src/arrays/constant/vtable/canonical.rs @@ -32,6 +32,7 @@ use crate::builders::builder_with_capacity; use crate::dtype::DType; use crate::dtype::DecimalType; use crate::dtype::Nullability; +use crate::dtype::UnionVariants; use crate::match_each_decimal_value; use crate::match_each_decimal_value_type; use crate::match_each_native_ptype; @@ -167,47 +168,7 @@ pub(crate) fn constant_canonicalize( }) } DType::Union(variants) => { - if scalar.is_null() { - vortex_bail!( - "Canonicalizing a null union scalar is not supported until null semantics are defined" - ) - } - if variants.variants().any(|variant| variant.is_nullable()) { - vortex_bail!("Canonical UnionArray children must be non-nullable") - } - - let union = scalar.as_union(); - let type_id = union - .type_id() - .vortex_expect("non-null union scalar must have a type ID"); - let child_index = union - .child_index() - .vortex_expect("validated union scalar must select a child"); - let selected_value = union - .value() - .vortex_expect("non-null union scalar must have a value"); - let children = variants - .variants() - .enumerate() - .map(|(index, dtype)| { - let value = if index == child_index { - selected_value.clone() - } else { - Scalar::zero_value(&dtype) - }; - ConstantArray::new(value, array.len()).into_array() - }) - .collect::>(); - - // SAFETY: The scalar's validated type ID selects `child_index`; all sparse children - // have the declared dtype and the same length. - Canonical::Union(unsafe { - UnionArray::new_unchecked( - ConstantArray::new(type_id, array.len()).into_array(), - variants.clone(), - children, - ) - }) + Canonical::Union(constant_canonical_union(scalar, variants, array.len())?) } DType::Variant(_) => Canonical::Variant(VariantArray::try_new( array.array().clone().into_array(), @@ -232,6 +193,51 @@ pub(crate) fn constant_canonicalize( }) } +fn constant_canonical_union( + scalar: &Scalar, + variants: &UnionVariants, + len: usize, +) -> VortexResult { + if scalar.is_null() { + vortex_bail!( + "Canonicalizing a null union scalar is not supported until null semantics are defined" + ) + } + if variants.variants().any(|variant| variant.is_nullable()) { + vortex_bail!("Canonical UnionArray children must be non-nullable") + } + + let union = scalar.as_union(); + let type_id = union + .type_id() + .vortex_expect("non-null union scalar must have a type ID"); + let selected_child = union + .child_index() + .vortex_expect("validated union scalar must select a child"); + let selected_value = union + .value() + .vortex_expect("non-null union scalar must have a value"); + + let children = variants + .variants() + .enumerate() + .map(|(index, dtype)| { + let value = if index == selected_child { + selected_value.clone() + } else { + Scalar::zero_value(&dtype) + }; + ConstantArray::new(value, len).into_array() + }) + .collect::>(); + + UnionArray::try_new( + ConstantArray::new(type_id, len).into_array(), + variants.clone(), + children, + ) +} + fn constant_canonical_byte_view( scalar_bytes: Option<&[u8]>, dtype: &DType, diff --git a/vortex-array/src/arrays/dict/execute.rs b/vortex-array/src/arrays/dict/execute.rs index 3dc7d0f596f..b4a6cc05017 100644 --- a/vortex-array/src/arrays/dict/execute.rs +++ b/vortex-array/src/arrays/dict/execute.rs @@ -25,13 +25,12 @@ use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::arrays::Struct; use crate::arrays::StructArray; -use crate::arrays::Union; -use crate::arrays::UnionArray; use crate::arrays::VarBinView; use crate::arrays::VarBinViewArray; use crate::arrays::VariantArray; use crate::arrays::dict::TakeExecute; use crate::arrays::dict::TakeReduce; +use crate::arrays::union::compute::take_union; use crate::arrays::variant::VariantArrayExt; /// Take from a canonical array using indices (codes), returning a new canonical array. @@ -55,7 +54,10 @@ pub(crate) fn take_canonical( Canonical::FixedSizeList(take_fixed_size_list(&a, codes, ctx)) } Canonical::Struct(a) => Canonical::Struct(take_struct(&a, codes)), - Canonical::Union(a) => Canonical::Union(take_union(&a, codes)?), + Canonical::Union(a) => { + let indices = codes.clone().into_array(); + Canonical::Union(take_union(a.as_view(), &indices)?) + } Canonical::Extension(a) => Canonical::Extension(take_extension(&a, codes, ctx)), Canonical::Variant(a) => { let indices = codes.clone().into_array(); @@ -168,15 +170,6 @@ fn take_struct(array: &StructArray, codes: &PrimitiveArray) -> StructArray { .into_owned() } -fn take_union(array: &UnionArray, codes: &PrimitiveArray) -> VortexResult { - let codes_ref = codes.clone().into_array(); - let array = array.as_view(); - Ok(::take(array, &codes_ref)? - .vortex_expect("take UnionArray should be supported") - .as_::() - .into_owned()) -} - fn take_extension( array: &ExtensionArray, codes: &PrimitiveArray, diff --git a/vortex-array/src/arrays/filter/execute/mod.rs b/vortex-array/src/arrays/filter/execute/mod.rs index 0dfe7ca44f8..b4653787a58 100644 --- a/vortex-array/src/arrays/filter/execute/mod.rs +++ b/vortex-array/src/arrays/filter/execute/mod.rs @@ -21,11 +21,10 @@ use crate::arrays::ConstantArray; use crate::arrays::ExtensionArray; use crate::arrays::Filter; use crate::arrays::NullArray; -use crate::arrays::Union; use crate::arrays::VariantArray; use crate::arrays::extension::ExtensionArrayExt; use crate::arrays::filter::FilterArrayExt; -use crate::arrays::filter::FilterReduce; +use crate::arrays::union::compute::filter_union; use crate::arrays::variant::VariantArrayExt; use crate::scalar::Scalar; use crate::validity::Validity; @@ -97,13 +96,13 @@ pub(super) fn execute_filter(canonical: Canonical, mask: &Arc) -> Ca Canonical::FixedSizeList(fixed_size_list::filter_fixed_size_list(&a, mask)) } Canonical::Struct(a) => Canonical::Struct(struct_::filter_struct(&a, mask)), - Canonical::Union(a) => Canonical::Union( - ::filter(a.as_view(), &Mask::Values(Arc::clone(mask))) - .vortex_expect("filter UnionArray") - .vortex_expect("UnionArray filter must be supported") - .as_::() - .into_owned(), - ), + Canonical::Union(a) => { + let mask = Mask::Values(Arc::clone(mask)); + Canonical::Union( + filter_union(a.as_view(), &mask) + .vortex_expect("UnionArray children must support filter"), + ) + } Canonical::Extension(a) => { let filtered_storage = a .storage_array() diff --git a/vortex-array/src/arrays/union/array.rs b/vortex-array/src/arrays/union/array.rs index e4dc751cba3..fef81d2672d 100644 --- a/vortex-array/src/arrays/union/array.rs +++ b/vortex-array/src/arrays/union/array.rs @@ -4,7 +4,6 @@ use std::iter::once; use std::sync::Arc; -use itertools::Itertools; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure; @@ -20,9 +19,8 @@ use crate::array::EmptyArrayData; use crate::array::TypedArrayRef; use crate::arrays::PrimitiveArray; use crate::arrays::Union; +use crate::arrays::union::TYPE_IDS_DTYPE; use crate::dtype::DType; -use crate::dtype::Nullability; -use crate::dtype::PType; use crate::dtype::UnionVariants; use crate::legacy_session; @@ -31,10 +29,17 @@ pub(super) const TYPE_IDS_SLOT: usize = 0; /// The offset at which the sparse child arrays begin in the slots vector. pub(super) const CHILDREN_OFFSET: usize = 1; -pub(super) fn make_union_slots(type_ids: &ArrayRef, children: &[ArrayRef]) -> ArraySlots { - once(Some(type_ids.clone())) +pub(super) fn make_union_parts( + type_ids: ArrayRef, + variants: UnionVariants, + children: &[ArrayRef], +) -> ArrayParts { + let len = type_ids.len(); + let slots: ArraySlots = once(Some(type_ids)) .chain(children.iter().cloned().map(Some)) - .collect() + .collect(); + + ArrayParts::new(Union, DType::Union(variants), len, EmptyArrayData).with_slots(slots) } /// Concrete parts of a [`UnionArray`](super::UnionArray). @@ -85,11 +90,56 @@ pub trait UnionArrayExt: TypedArrayRef { fn child_by_type_id(&self, type_id: i8) -> Option<&ArrayRef> { self.child(self.variants().tag_to_child_index(type_id)?) } + + /// Return a sparse child selected by its variant name, if present. + fn child_by_name_opt(&self, name: impl AsRef) -> Option<&ArrayRef> { + self.child(self.variants().find(name)?) + } + + /// Return a sparse child selected by its variant name. + fn child_by_name(&self, name: impl AsRef) -> VortexResult<&ArrayRef> { + let name = name.as_ref(); + self.child_by_name_opt(name).ok_or_else(|| { + vortex_err!( + "Variant {name} not found in union array with names {:?}", + self.variants().names() + ) + }) + } } impl> UnionArrayExt for T {} +/// Validate host-resident type ID values eagerly. +/// +/// Non-host arrays remain valid structurally and are checked when their values are accessed. +#[allow(clippy::disallowed_methods)] +fn validate_type_id_values(array: &Array) -> VortexResult<()> { + if !array.type_ids().is_host() { + return Ok(()); + } + + let type_ids = array + .type_ids() + .clone() + .execute::(&mut legacy_session().create_execution_ctx())?; + for type_id in type_ids.as_slice::() { + vortex_ensure!( + array.variants().tag_to_child_index(*type_id).is_some(), + "UnionArray type ID {type_id} is not present in {:?}", + array.variants().type_ids() + ); + } + + Ok(()) +} + impl Array { /// Construct a canonical sparse union array. + /// + /// # Panics + /// + /// Panics if the components do not satisfy the invariants documented on + /// [`Self::new_unchecked`]. pub fn new( type_ids: ArrayRef, variants: UnionVariants, @@ -100,42 +150,26 @@ impl Array { /// Try to construct a canonical sparse union array. /// - /// Until Union nullability semantics are settled, the union and every child must be - /// non-nullable. - #[allow(clippy::disallowed_methods)] + /// Until Union nullability semantics are settled, every child must be non-nullable. + /// + /// # Errors + /// + /// Returns an error if the type IDs and sparse children do not match the variant schema or do + /// not all have the same length. pub fn try_new( type_ids: ArrayRef, variants: UnionVariants, children: impl Into>, ) -> VortexResult { vortex_ensure!( - type_ids.dtype() == &DType::Primitive(PType::I8, Nullability::NonNullable), + type_ids.dtype() == &TYPE_IDS_DTYPE, "UnionArray type_ids must be non-nullable i8, got {}", type_ids.dtype() ); let children = children.into(); - let len = type_ids.len(); - let dtype = DType::Union(variants.clone()); - let slots = make_union_slots(&type_ids, &children); - let array = Array::try_from_parts( - ArrayParts::new(Union, dtype, len, EmptyArrayData).with_slots(slots), - )?; - - // Validate data-level tags when they are host-resident. Keep scalar access fallible so an - // invalid tag from non-host or untrusted serialized input still produces an error rather - // than unchecked indexing. - if type_ids.is_host() { - let primitive = - type_ids.execute::(&mut legacy_session().create_execution_ctx())?; - for type_id in primitive.as_slice::() { - vortex_ensure!( - variants.tag_to_child_index(*type_id).is_some(), - "UnionArray type ID {type_id} is not present in {:?}", - variants.type_ids() - ); - } - } + let array = Array::try_from_parts(make_union_parts(type_ids, variants, &children))?; + validate_type_id_values(&array)?; Ok(array) } @@ -146,21 +180,14 @@ impl Array { /// /// The caller must ensure the type IDs are non-nullable `i8` values declared by `variants`, /// every child has the corresponding variant dtype, and all arrays have the same length. The - /// union and its children must currently be non-nullable. + /// children must currently be non-nullable. pub unsafe fn new_unchecked( type_ids: ArrayRef, variants: UnionVariants, children: impl Into>, ) -> Self { let children = children.into(); - let len = type_ids.len(); - let slots = make_union_slots(&type_ids, &children); - unsafe { - Array::from_parts_unchecked( - ArrayParts::new(Union, DType::Union(variants), len, EmptyArrayData) - .with_slots(slots), - ) - } + unsafe { Array::from_parts_unchecked(make_union_parts(type_ids, variants, &children)) } } /// Deconstruct this array into its type IDs, variant schema, and sparse children. @@ -175,30 +202,14 @@ impl Array { } } - /// Return the sparse child for a variant name. - pub fn child_by_name(&self, name: impl AsRef) -> VortexResult<&ArrayRef> { - let name = name.as_ref(); - let index = self - .variants() - .find(name) - .ok_or_else(|| vortex_err!("Unknown UnionArray variant {name}"))?; - Ok(self - .child(index) - .vortex_expect("variant index must have a child")) - } - /// Create an empty array for a non-nullable union dtype. pub(crate) fn empty(variants: UnionVariants) -> Self { - assert!( - variants.variants().all(|dtype| !dtype.is_nullable()), - "Canonical UnionArray children must be non-nullable" - ); let type_ids = PrimitiveArray::from_iter(Vec::::new()).into_array(); - let children = variants + let children: Vec<_> = variants .variants() .map(|dtype| crate::Canonical::empty(&dtype).into_array()) - .collect_vec(); - // SAFETY: All components are empty and use the dtypes declared by variants. - unsafe { Self::new_unchecked(type_ids, variants, children) } + .collect(); + + Self::new(type_ids, variants, children) } } diff --git a/vortex-array/src/arrays/union/compute/filter.rs b/vortex-array/src/arrays/union/compute/filter.rs index 013c2b8c3ea..4b26916bdbc 100644 --- a/vortex-array/src/arrays/union/compute/filter.rs +++ b/vortex-array/src/arrays/union/compute/filter.rs @@ -12,18 +12,19 @@ use crate::arrays::UnionArray; use crate::arrays::filter::FilterReduce; use crate::arrays::union::UnionArrayExt; +pub(crate) fn filter_union(array: ArrayView<'_, Union>, mask: &Mask) -> VortexResult { + let type_ids = array.type_ids().filter(mask.clone())?; + let children = array + .iter_children() + .map(|child| child.filter(mask.clone())) + .collect::>>()?; + + // SAFETY: Filtering every row-aligned component by the same mask preserves all invariants. + Ok(unsafe { UnionArray::new_unchecked(type_ids, array.variants().clone(), children) }) +} + impl FilterReduce for Union { fn filter(array: ArrayView<'_, Union>, mask: &Mask) -> VortexResult> { - let type_ids = array.type_ids().filter(mask.clone())?; - let children = array - .iter_children() - .map(|child| child.filter(mask.clone())) - .collect::>>()?; - - // SAFETY: Filtering every row-aligned component by the same mask preserves all invariants. - Ok(Some( - unsafe { UnionArray::new_unchecked(type_ids, array.variants().clone(), children) } - .into_array(), - )) + Ok(Some(filter_union(array, mask)?.into_array())) } } diff --git a/vortex-array/src/arrays/union/compute/mod.rs b/vortex-array/src/arrays/union/compute/mod.rs index 5da8b60b65d..e9208bf2185 100644 --- a/vortex-array/src/arrays/union/compute/mod.rs +++ b/vortex-array/src/arrays/union/compute/mod.rs @@ -2,6 +2,11 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors mod filter; +pub(crate) use filter::filter_union; + pub(crate) mod rules; + mod slice; + mod take; +pub(crate) use take::take_union; diff --git a/vortex-array/src/arrays/union/compute/take.rs b/vortex-array/src/arrays/union/compute/take.rs index a9824678922..9cca9a0794a 100644 --- a/vortex-array/src/arrays/union/compute/take.rs +++ b/vortex-array/src/arrays/union/compute/take.rs @@ -12,23 +12,27 @@ use crate::arrays::UnionArray; use crate::arrays::dict::TakeReduce; use crate::arrays::union::UnionArrayExt; -impl TakeReduce for Union { - fn take(array: ArrayView<'_, Union>, indices: &ArrayRef) -> VortexResult> { - if indices.dtype().is_nullable() { - vortex_bail!("Taking UnionArray with nullable indices is not supported yet") - } +pub(crate) fn take_union( + array: ArrayView<'_, Union>, + indices: &ArrayRef, +) -> VortexResult { + if indices.dtype().is_nullable() { + vortex_bail!("Taking UnionArray with nullable indices is not supported yet") + } - let type_ids = array.type_ids().take(indices.clone())?; - let children = array - .iter_children() - .map(|child| child.take(indices.clone())) - .collect::>>()?; + let type_ids = array.type_ids().take(indices.clone())?; + let children = array + .iter_children() + .map(|child| child.take(indices.clone())) + .collect::>>()?; - // SAFETY: Taking every row-aligned component with the same non-null indices preserves all - // invariants and cannot introduce nulls. - Ok(Some( - unsafe { UnionArray::new_unchecked(type_ids, array.variants().clone(), children) } - .into_array(), - )) + // SAFETY: Taking every row-aligned component with the same non-null indices preserves all + // invariants and cannot introduce nulls. + Ok(unsafe { UnionArray::new_unchecked(type_ids, array.variants().clone(), children) }) +} + +impl TakeReduce for Union { + fn take(array: ArrayView<'_, Union>, indices: &ArrayRef) -> VortexResult> { + Ok(Some(take_union(array, indices)?.into_array())) } } diff --git a/vortex-array/src/arrays/union/mod.rs b/vortex-array/src/arrays/union/mod.rs index 9f54572b9ec..b8671ccafd8 100644 --- a/vortex-array/src/arrays/union/mod.rs +++ b/vortex-array/src/arrays/union/mod.rs @@ -1,15 +1,30 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +//! Canonical sparse union arrays. +//! +//! A [`UnionArray`] stores one non-nullable `i8` type ID per row followed by one row-aligned child +//! for each variant. The type ID selects which child's value is active for a row; values in all +//! other children at that row are placeholders. +//! +//! Union nullability semantics are still being designed, so this encoding currently requires every +//! variant child to be non-nullable. + +use crate::dtype::DType; +use crate::dtype::Nullability; +use crate::dtype::PType; + mod array; pub use array::UnionArrayExt; pub use array::UnionDataParts; +pub use vtable::UnionArray; pub(crate) mod compute; mod vtable; pub use vtable::Union; -pub use vtable::UnionArray; + +pub(crate) const TYPE_IDS_DTYPE: DType = DType::Primitive(PType::I8, Nullability::NonNullable); #[cfg(test)] mod tests; diff --git a/vortex-array/src/arrays/union/tests.rs b/vortex-array/src/arrays/union/tests.rs index f22834ed06a..e800647d56b 100644 --- a/vortex-array/src/arrays/union/tests.rs +++ b/vortex-array/src/arrays/union/tests.rs @@ -55,6 +55,11 @@ fn scalar_at_uses_type_id_indirection() -> VortexResult<()> { let array = union_array()?; let mut ctx = array_session().create_execution_ctx(); + assert_eq!( + array.child_by_name("flag")?.dtype(), + &DType::Bool(Nullability::NonNullable) + ); + assert!(array.child_by_name_opt("missing").is_none()); assert_eq!( array.execute_scalar(0, &mut ctx)?, Scalar::union(variants()?, 5, 10i32.into())? @@ -75,33 +80,29 @@ fn validates_sparse_components() -> VortexResult<()> { BoolArray::from_iter([false, true, false]).into_array(), ]; - assert!( - UnionArray::try_new( - PrimitiveArray::from_iter([5i8, 7, 5]).into_array(), - variants()?, - children.clone(), - ) - .is_err() + let unknown_type_id = UnionArray::try_new( + PrimitiveArray::from_iter([5i8, 7, 5]).into_array(), + variants()?, + children.clone(), ); - assert!( - UnionArray::try_new( - PrimitiveArray::from_iter([5i8, 9]).into_array(), - variants()?, - children, - ) - .is_err() + assert!(unknown_type_id.is_err()); + + let mismatched_lengths = UnionArray::try_new( + PrimitiveArray::from_iter([5i8, 9]).into_array(), + variants()?, + children, ); - assert!( - UnionArray::try_new( - PrimitiveArray::from_iter([5i8, 9, 5]).into_array(), - variants()?, - vec![ - PrimitiveArray::new(buffer![10i32, 0, 30], Validity::AllValid).into_array(), - BoolArray::from_iter([false, true, false]).into_array(), - ], - ) - .is_err() + assert!(mismatched_lengths.is_err()); + + let nullable_child = UnionArray::try_new( + PrimitiveArray::from_iter([5i8, 9, 5]).into_array(), + variants()?, + vec![ + PrimitiveArray::new(buffer![10i32, 0, 30], Validity::AllValid).into_array(), + BoolArray::from_iter([false, true, false]).into_array(), + ], ); + assert!(nullable_child.is_err()); Ok(()) } diff --git a/vortex-array/src/arrays/union/vtable/mod.rs b/vortex-array/src/arrays/union/vtable/mod.rs index d19c7c46563..4023699c256 100644 --- a/vortex-array/src/arrays/union/vtable/mod.rs +++ b/vortex-array/src/arrays/union/vtable/mod.rs @@ -1,11 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use itertools::Itertools; -use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; +use vortex_error::vortex_err; use vortex_error::vortex_panic; use vortex_session::VortexSession; use vortex_session::registry::CachedId; @@ -20,16 +19,15 @@ use crate::array::ArrayView; use crate::array::EmptyArrayData; use crate::array::VTable; use crate::array::with_empty_buffers; +use crate::arrays::union::TYPE_IDS_DTYPE; use crate::arrays::union::UnionArrayExt; use crate::arrays::union::array::CHILDREN_OFFSET; use crate::arrays::union::array::TYPE_IDS_SLOT; -use crate::arrays::union::array::make_union_slots; +use crate::arrays::union::array::make_union_parts; use crate::arrays::union::compute::rules::PARENT_RULES; use crate::buffer::BufferHandle; use crate::builders::ArrayBuilder; use crate::dtype::DType; -use crate::dtype::Nullability; -use crate::dtype::PType; use crate::serde::ArrayChildren; mod operations; @@ -62,10 +60,6 @@ impl VTable for Union { let DType::Union(variants) = dtype else { vortex_bail!("Expected union dtype, found {dtype}") }; - vortex_ensure!( - !dtype.is_nullable(), - "Nullable UnionArray is not supported yet" - ); vortex_ensure!( variants.variants().all(|variant| !variant.is_nullable()), "UnionArray children must be non-nullable" @@ -79,9 +73,9 @@ impl VTable for Union { let type_ids = slots[TYPE_IDS_SLOT] .as_ref() - .vortex_expect("UnionArray type_ids slot"); + .ok_or_else(|| vortex_err!("UnionArray is missing its type_ids slot"))?; vortex_ensure!( - type_ids.dtype() == &DType::Primitive(PType::I8, Nullability::NonNullable), + type_ids.dtype() == &TYPE_IDS_DTYPE, "UnionArray type_ids must be non-nullable i8, got {}", type_ids.dtype() ); @@ -91,14 +85,10 @@ impl VTable for Union { type_ids.len() ); - for (index, (slot, variant_dtype)) in slots[CHILDREN_OFFSET..] - .iter() - .zip_eq(variants.variants()) - .enumerate() - { - let child = slot + for (index, variant_dtype) in variants.variants().enumerate() { + let child = slots[CHILDREN_OFFSET + index] .as_ref() - .ok_or_else(|| vortex_error::vortex_err!("UnionArray missing child {index}"))?; + .ok_or_else(|| vortex_err!("UnionArray is missing child {index}"))?; vortex_ensure!( child.len() == len, "UnionArray child {index} length {} does not match outer length {len}", @@ -162,19 +152,18 @@ impl VTable for Union { children.len() ); - let type_ids = children.get( - TYPE_IDS_SLOT, - &DType::Primitive(PType::I8, Nullability::NonNullable), - len, - )?; + let type_ids = children.get(TYPE_IDS_SLOT, &TYPE_IDS_DTYPE, len)?; let sparse_children = variants .variants() .enumerate() .map(|(index, dtype)| children.get(CHILDREN_OFFSET + index, &dtype, len)) - .try_collect::<_, Vec<_>, _>()?; - let slots = make_union_slots(&type_ids, &sparse_children); + .collect::>>()?; - Ok(ArrayParts::new(self.clone(), dtype.clone(), len, EmptyArrayData).with_slots(slots)) + Ok(make_union_parts( + type_ids, + variants.clone(), + &sparse_children, + )) } fn slot_name(array: ArrayView<'_, Self>, idx: usize) -> String { diff --git a/vortex-array/src/canonical.rs b/vortex-array/src/canonical.rs index f8daca7e4a9..2e4851ac15d 100644 --- a/vortex-array/src/canonical.rs +++ b/vortex-array/src/canonical.rs @@ -863,12 +863,11 @@ impl Executable for RecursiveCanonical { let type_ids = type_ids.execute::(ctx)?.0.into_array(); let children = children .iter() + .cloned() .map(|child| { - Ok(child - .clone() - .execute::(ctx)? - .0 - .into_array()) + child + .execute::(ctx) + .map(|canonical| canonical.0.into_array()) }) .collect::>>()?;