diff --git a/fuzz/src/array/fill_null.rs b/fuzz/src/array/fill_null.rs index f3a49b25637..75adfa94847 100644 --- a/fuzz/src/array/fill_null.rs +++ b/fuzz/src/array/fill_null.rs @@ -49,6 +49,9 @@ pub fn fill_null_canonical_array( | Canonical::List(_) | Canonical::FixedSizeList(_) | Canonical::Extension(_) => canonical.into_array().fill_null(fill_value.clone())?, + Canonical::Union(_) => { + todo!("TODO(connor)[Union]: support Union arrays in the fill_null fuzzer") + } Canonical::Variant(_) => unreachable!("Variant arrays are not fuzzed"), }) } diff --git a/fuzz/src/array/mask.rs b/fuzz/src/array/mask.rs index f3cecec2b10..fd8eab2d6a8 100644 --- a/fuzz/src/array/mask.rs +++ b/fuzz/src/array/mask.rs @@ -149,6 +149,9 @@ pub fn mask_canonical_array( .with_nullability(masked_storage.dtype().nullability()); ExtensionArray::new(ext_dtype, masked_storage).into_array() } + Canonical::Union(_) => { + todo!("TODO(connor)[Union]: support Union arrays in the mask fuzzer") + } 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..887974c7d42 100644 --- a/fuzz/src/array/scalar_at.rs +++ b/fuzz/src/array/scalar_at.rs @@ -104,6 +104,9 @@ 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(_) => { + todo!("TODO(connor)[Union]: support Union arrays in the scalar_at fuzzer") + } 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..708c83debc4 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(_) => { + todo!("TODO(connor)[Union]: implement IsConstant for Union arrays") + } 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..de950e59d7d 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/min_max/mod.rs @@ -417,6 +417,9 @@ impl AggregateFnVTable for MinMax { Canonical::Decimal(d) => accumulate_decimal(partial, d, ctx), Canonical::Extension(e) => accumulate_extension(partial, e, ctx), Canonical::Null(_) => Ok(()), + Canonical::Union(_) => { + todo!("TODO(connor)[Union]: implement min_max for Union arrays") + } Canonical::Struct(_) | Canonical::List(_) | Canonical::FixedSizeList(_) 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 1d04a074d6f..0ca56bd1e9c 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 @@ -199,6 +199,9 @@ 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(_) => { + todo!("TODO(connor)[Union]: implement UncompressedSizeInBytes for Union arrays") + } Canonical::Extension(array) => extension_uncompressed_size_in_bytes(array, ctx), Canonical::Variant(_) => { vortex_bail!("UncompressedSizeInBytes is not supported for Variant arrays") diff --git a/vortex-array/src/arrays/dict/execute.rs b/vortex-array/src/arrays/dict/execute.rs index 47a9a051666..bfd5051d365 100644 --- a/vortex-array/src/arrays/dict/execute.rs +++ b/vortex-array/src/arrays/dict/execute.rs @@ -53,6 +53,9 @@ 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(_) => { + todo!("TODO(connor)[Union]: implement dictionary execution for Union arrays") + } Canonical::Extension(a) => Canonical::Extension(take_extension(&a, codes, ctx)), Canonical::Variant(a) => { let indices = codes.clone().into_array(); diff --git a/vortex-array/src/arrays/filter/execute/mod.rs b/vortex-array/src/arrays/filter/execute/mod.rs index 52b0373ac49..048b117933e 100644 --- a/vortex-array/src/arrays/filter/execute/mod.rs +++ b/vortex-array/src/arrays/filter/execute/mod.rs @@ -95,6 +95,9 @@ 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(_) => { + todo!("TODO(connor)[Union]: implement filter for Union arrays") + } 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..fcfebba1d69 100644 --- a/vortex-array/src/arrays/masked/execute.rs +++ b/vortex-array/src/arrays/masked/execute.rs @@ -50,6 +50,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(_) => { + todo!("TODO(connor)[Union]: implement masking for Union arrays") + } 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 001e20dee65..7c31a1b48b1 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 @@ -112,6 +112,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..0772283ee77 --- /dev/null +++ b/vortex-array/src/arrays/union/array.rs @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::iter::once; +use std::sync::Arc; + +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::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::UnionVariants; + +/// 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_parts( + type_ids: ArrayRef, + variants: UnionVariants, + children: &[ArrayRef], +) -> ArrayParts { + let len = type_ids.len(); + let nullability = type_ids.dtype().nullability(); + let slots: ArraySlots = once(Some(type_ids)) + .chain(children.iter().cloned().map(Some)) + .collect(); + + ArrayParts::new( + Union, + DType::Union(variants, nullability), + len, + EmptyArrayData, + ) + .with_slots(slots) +} + +/// 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 `u8` type IDs whose nulls represent outer union nulls. + 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: u8) -> 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 {} + +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, + children: impl Into>, + ) -> Self { + Self::try_new(type_ids, variants, children).vortex_expect("UnionArray construction failed") + } + + /// Try to construct a canonical sparse union array. + /// + /// Type ID values are not validated during construction. Accessing a non-null row whose type + /// ID is not declared by `variants` will panic. + /// + /// # Errors + /// + /// Returns an error if `type_ids` is not a `u8` array, or if the sparse children do not match + /// the variant schema and outer array length. + pub fn try_new( + type_ids: ArrayRef, + variants: UnionVariants, + children: impl Into>, + ) -> VortexResult { + vortex_ensure!( + matches!( + type_ids.dtype(), + DType::Primitive(crate::dtype::PType::U8, _) + ), + "UnionArray type_ids must be u8, got {}", + type_ids.dtype() + ); + + let children = children.into(); + Array::try_from_parts(make_union_parts(type_ids, variants, &children)) + } + + /// Construct a canonical sparse union array without validation. + /// + /// # Safety + /// + /// The caller must ensure `type_ids` is a `u8` array, every child has the corresponding variant + /// dtype, and all arrays have the same length. Null type IDs represent outer union nulls. + pub unsafe fn new_unchecked( + type_ids: ArrayRef, + variants: UnionVariants, + children: impl Into>, + ) -> Self { + let children = children.into(); + unsafe { Array::from_parts_unchecked(make_union_parts(type_ids, variants, &children)) } + } + + /// 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, + } + } + + /// Create an empty array for a union dtype. + pub(crate) fn empty(variants: UnionVariants, nullability: Nullability) -> Self { + let type_ids = PrimitiveArray::empty::(nullability).into_array(); + let children: Vec<_> = variants + .variants() + .map(|dtype| crate::Canonical::empty(&dtype).into_array()) + .collect(); + + Self::new(type_ids, variants, children) + } +} diff --git a/vortex-array/src/arrays/union/mod.rs b/vortex-array/src/arrays/union/mod.rs new file mode 100644 index 00000000000..e5f5a0f10e9 --- /dev/null +++ b/vortex-array/src/arrays/union/mod.rs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Canonical sparse union arrays. +//! +//! A [`UnionArray`] stores one `u8` 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. Outer union nulls are stored as nulls in the type IDs +//! child, independently of nulls in the selected variant child. +//! +//! Type ID values are not validated during construction. Accessing a non-null row whose type ID +//! is not declared by the union variants will panic. + +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; + +mod vtable; +pub use vtable::Union; + +pub(crate) fn union_type_ids_dtype(nullability: Nullability) -> DType { + DType::Primitive(PType::U8, nullability) +} + +#[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..51643a353b5 --- /dev/null +++ b/vortex-array/src/arrays/union/tests.rs @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_buffer::ByteBufferMut; +use vortex_buffer::buffer; +use vortex_error::VortexExpect; +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::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([5u8, 9, 5]).into_array(), + variants()?, + vec![ + PrimitiveArray::from_iter([10i32, 0, 30]).into_array(), + BoolArray::from_iter([false, true, false]).into_array(), + ], + ) +} + +fn nullable_variants() -> VortexResult { + UnionVariants::try_new( + ["number", "optional"].into(), + vec![ + DType::Primitive(PType::I32, Nullability::NonNullable), + DType::Primitive(PType::I64, Nullability::Nullable), + ], + vec![5, 9], + ) +} + +fn nullable_union_array() -> VortexResult { + UnionArray::try_new( + PrimitiveArray::from_option_iter([Some(5u8), None, Some(9), Some(9)]).into_array(), + nullable_variants()?, + vec![ + PrimitiveArray::from_iter([10i32, 0, 0, 0]).into_array(), + PrimitiveArray::from_option_iter([Some(0i64), Some(0), None, Some(40)]).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.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(), Nullability::NonNullable)? + ); + assert_eq!( + array.execute_scalar(1, &mut ctx)?, + Scalar::union(variants()?, 9, true.into(), Nullability::NonNullable)? + ); + 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([5u8, 9]).into_array(), + variants()?, + children, + ) + .is_err() + ); + assert!( + UnionArray::try_new( + PrimitiveArray::from_iter([5u8, 9, 5]).into_array(), + variants()?, + vec![PrimitiveArray::from_iter([10i32, 0, 30]).into_array()], + ) + .is_err() + ); + assert!( + UnionArray::try_new( + PrimitiveArray::from_iter([5u8, 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] +#[should_panic(expected = "Unknown UnionArray type ID 7")] +fn invalid_type_id_panics_when_accessed() { + let array = UnionArray::try_new( + PrimitiveArray::from_iter([5u8, 7, 5]).into_array(), + variants().vortex_expect("valid Union variants"), + vec![ + PrimitiveArray::from_iter([10i32, 0, 30]).into_array(), + BoolArray::from_iter([false, true, false]).into_array(), + ], + ) + .vortex_expect("structurally valid UnionArray"); + let mut ctx = array_session().create_execution_ctx(); + + let _scalar = array + .execute_scalar(1, &mut ctx) + .vortex_expect("UnionArray scalar access"); +} + +#[test] +fn outer_nulls_are_independent_from_inner_nulls() -> VortexResult<()> { + let variants = nullable_variants()?; + let array = nullable_union_array()?; + let mut ctx = array_session().create_execution_ctx(); + + assert_eq!( + array.dtype(), + &DType::Union(variants.clone(), Nullability::Nullable) + ); + assert_eq!( + array.validity()?.execute_mask(array.len(), &mut ctx)?, + Mask::from_iter([true, false, true, true]) + ); + assert_eq!( + array.execute_scalar(0, &mut ctx)?, + Scalar::union(variants.clone(), 5, 10i32.into(), Nullability::Nullable)? + ); + assert_eq!( + array.execute_scalar(1, &mut ctx)?, + Scalar::null(DType::Union(variants.clone(), Nullability::Nullable)) + ); + assert_eq!( + array.execute_scalar(2, &mut ctx)?, + Scalar::union( + variants, + 9, + Scalar::null(DType::Primitive(PType::I64, Nullability::Nullable)), + Nullability::Nullable, + )? + ); + + Ok(()) +} + +#[test] +fn serde_roundtrip() -> VortexResult<()> { + let session = array_session(); + let mut execution_ctx = session.create_execution_ctx(); + for array in [union_array()?, nullable_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(()) +} 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..23997c27707 --- /dev/null +++ b/vortex-array/src/arrays/union/vtable/mod.rs @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; +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_parts; +use crate::arrays::union::union_type_ids_dtype; +use crate::buffer::BufferHandle; +use crate::builders::ArrayBuilder; +use crate::dtype::DType; +use crate::serde::ArrayChildren; + +mod operations; +mod validate; +mod validity; + +/// A canonical [`Union`]-encoded array. +/// +/// This is similar to Arrow's "spase" union type. +pub type UnionArray = Array; + +/// The canonical Union encoding. +/// +/// This is similar to Arrow's "spase" union type. +#[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 type_ids = slots + .get(TYPE_IDS_SLOT) + .and_then(Option::as_ref) + .ok_or_else(|| vortex_err!("UnionArray is missing its type_ids slot"))?; + let variant_arrays = slots + .get(CHILDREN_OFFSET..) + .unwrap_or_default() + .iter() + .enumerate() + .map(|(index, slot)| { + slot.as_ref() + .ok_or_else(|| vortex_err!("UnionArray is missing child {index}")) + }) + .collect::>>()?; + + validate::validate_union_components(type_ids, &variant_arrays, dtype, len) + } + + 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, nullability) = dtype else { + vortex_bail!("Expected union dtype, found {dtype}") + }; + vortex_ensure_eq!( + children.len(), + CHILDREN_OFFSET + variants.len(), + "UnionArray expected {} children, found {}", + CHILDREN_OFFSET + variants.len(), + children.len() + ); + + let type_ids = children.get(TYPE_IDS_SLOT, &union_type_ids_dtype(*nullability), len)?; + let sparse_children = variants + .variants() + .enumerate() + .map(|(index, dtype)| children.get(CHILDREN_OFFSET + index, &dtype, len)) + .collect::>>()?; + + Ok(make_union_parts( + type_ids, + variants.clone(), + &sparse_children, + )) + } + + 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 { + todo!("TODO(connor)[Union]: implement execute for Union arrays") + } + + fn append_to_builder( + _array: ArrayView<'_, Self>, + _builder: &mut dyn ArrayBuilder, + _ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + todo!("TODO(connor)[Union]: implement append_to_builder for Union arrays") + } +} 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..d8adb83992d --- /dev/null +++ b/vortex-array/src/arrays/union/vtable/operations.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_error::vortex_panic; + +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_scalar = array.type_ids().execute_scalar(index, ctx)?; + let Some(type_id) = type_id_scalar.as_primitive().typed_value::() else { + return Ok(Scalar::null(array.dtype().clone())); + }; + + let Some(child_index) = array.variants().tag_to_child_index(type_id) else { + vortex_panic!("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, + array.dtype().nullability(), + ) + } +} diff --git a/vortex-array/src/arrays/union/vtable/validate.rs b/vortex-array/src/arrays/union/vtable/validate.rs new file mode 100644 index 00000000000..06ab5c79c1e --- /dev/null +++ b/vortex-array/src/arrays/union/vtable/validate.rs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure_eq; + +use crate::ArrayRef; +use crate::arrays::union::array::CHILDREN_OFFSET; +use crate::arrays::union::union_type_ids_dtype; +use crate::dtype::DType; + +pub(super) fn validate_union_components( + type_ids: &ArrayRef, + variant_arrays: &[&ArrayRef], + dtype: &DType, + len: usize, +) -> VortexResult<()> { + let DType::Union(variants, nullability) = dtype else { + vortex_bail!("Expected union dtype, found {dtype}") + }; + vortex_ensure_eq!( + variant_arrays.len(), + variants.len(), + "UnionArray has {} slots but expected {}", + CHILDREN_OFFSET + variant_arrays.len(), + CHILDREN_OFFSET + variants.len() + ); + + let expected_union_type_ids_dtype = union_type_ids_dtype(*nullability); + vortex_ensure_eq!( + type_ids.dtype(), + &expected_union_type_ids_dtype, + "UnionArray type_ids must have dtype {expected_union_type_ids_dtype}, got {}", + type_ids.dtype() + ); + vortex_ensure_eq!( + type_ids.len(), + len, + "UnionArray type_ids length {} does not match outer length {len}", + type_ids.len() + ); + + for (index, (variant_dtype, child)) in variants + .variants() + .zip(variant_arrays.iter().copied()) + .enumerate() + { + vortex_ensure_eq!( + child.len(), + len, + "UnionArray child {index} length {} does not match outer length {len}", + child.len() + ); + vortex_ensure_eq!( + child.dtype(), + &variant_dtype, + "UnionArray child {index} has dtype {} but expected {variant_dtype}", + child.dtype() + ); + } + + Ok(()) +} 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..80e043534e5 --- /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::arrays::union::UnionArrayExt; +use crate::validity::Validity; + +impl ValidityVTable for Union { + fn validity(array: ArrayView<'_, Union>) -> VortexResult { + array.type_ids().validity() + } +} diff --git a/vortex-array/src/canonical.rs b/vortex-array/src/canonical.rs index 71da52e1300..c1664f82af2 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. +/// Vortex canonical encodings have equivalent Arrow encodings that can be built zero-copy, except +/// [`UnionArray`], whose independent top-level validity cannot be represented directly by an Arrow +/// union. 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,9 @@ impl Canonical { Validity::from(n), ) }), - DType::Union(..) => todo!("TODO(connor)[Union]: unimplemented"), + DType::Union(variants, nullability) => { + Canonical::Union(UnionArray::empty(variants.clone(), *nullability)) + } DType::Variant(_) => { vortex_panic!(InvalidArgument: "Canonical empty is not supported for Variant") } @@ -401,6 +409,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 +678,18 @@ impl Executable for CanonicalValidity { StructArray::new_unchecked(fields, struct_fields, len, validity.execute(ctx)?) }))) } + Canonical::Union(union) => { + let UnionDataParts { + variants, + type_ids, + children, + } = union.into_data_parts(); + let type_ids = type_ids.execute::(ctx)?.0.into_array(); + + Ok(CanonicalValidity(Canonical::Union(unsafe { + UnionArray::new_unchecked(type_ids, variants, children) + }))) + } Canonical::Extension(ext) => Ok(CanonicalValidity(Canonical::Extension( ExtensionArray::new( ext.ext_dtype().clone(), @@ -829,6 +867,27 @@ 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() + .cloned() + .map(|child| { + child + .execute::(ctx) + .map(|canonical| canonical.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 +1062,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 +1103,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 +1119,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 +1138,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 +1157,7 @@ impl Matcher for AnyCanonical { || array.is::() || array.is::() || array.is::() + || array.is::() || array.is::() || array.is::() || array.is::() @@ -1102,6 +1177,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 7de16913c6b..cc76ffac2bd 100644 --- a/vortex-array/src/dtype/dtype_impl.rs +++ b/vortex-array/src/dtype/dtype_impl.rs @@ -319,7 +319,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..488a646bba4 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(_) => { + todo!("TODO(connor)[Union]: implement casting for Union arrays") + } 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 98a769ceea9..406ab31bdc3 100644 --- a/vortex-array/src/session/mod.rs +++ b/vortex-array/src/session/mod.rs @@ -28,6 +28,7 @@ use crate::arrays::Null; use crate::arrays::PiecewiseSequence; use crate::arrays::Primitive; use crate::arrays::Struct; +use crate::arrays::Union; use crate::arrays::VarBin; use crate::arrays::VarBinView; use crate::arrays::Variant; @@ -73,6 +74,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..cf6f593e79e 100644 --- a/vortex-compressor/src/compressor/cascade.rs +++ b/vortex-compressor/src/compressor/cascade.rs @@ -130,6 +130,9 @@ impl CascadingCompressor { )? .into_array()) } + Canonical::Union(_) => { + todo!("TODO(connor)[Union]: implement compression for Union arrays") + } 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..c6990811d6e 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!("TODO(connor)[Union]: implement DuckDB export for Union arrays") + } Canonical::Extension(ext) => extension::new_exporter(ext, ctx), Canonical::Variant(_) => { vortex_bail!("Variant arrays can't be exported to DuckDB")