diff --git a/encodings/parquet-variant/Cargo.toml b/encodings/parquet-variant/Cargo.toml index ce8776645c7..56e31c318bf 100644 --- a/encodings/parquet-variant/Cargo.toml +++ b/encodings/parquet-variant/Cargo.toml @@ -29,6 +29,7 @@ vortex-buffer = { workspace = true } vortex-error = { workspace = true } vortex-functions = { workspace = true } vortex-json = { workspace = true } +vortex-layout = { workspace = true } vortex-mask = { workspace = true } vortex-session = { workspace = true } @@ -41,5 +42,4 @@ vortex-array = { workspace = true, features = ["_test-harness"] } vortex-arrow = { workspace = true, features = ["_test-harness-hegel"] } vortex-file = { workspace = true, features = ["tokio"] } vortex-io = { workspace = true, features = ["tokio"] } -vortex-layout = { workspace = true } vortex-uuid = { workspace = true } diff --git a/encodings/parquet-variant/src/array.rs b/encodings/parquet-variant/src/array.rs index a2335125fdd..14a46f2800d 100644 --- a/encodings/parquet-variant/src/array.rs +++ b/encodings/parquet-variant/src/array.rs @@ -53,6 +53,7 @@ use vortex_error::vortex_err; use crate::ParquetVariant; use crate::ParquetVariantArray; use crate::arrow::prepare_variant_for_export; +use crate::fold::fold_union; #[array_slots(ParquetVariant)] pub struct ParquetVariantSlots { @@ -376,12 +377,30 @@ fn inferred_shredded_field_validity( /// `forward` then `inverse` is structure-preserving for the shapes canonicalization produces; /// fields the forward transform omitted (Parquet wrapper shells with no `typed_value`) are served /// from the residual `value` and are intentionally not reconstructed here. +/// +/// Parquet has no union, so a union field is folded into the residual `value` of its shell, which +/// writes its values with the `metadata` of each row; see [`fold_union`]. Without `metadata`, a +/// union cannot be rebuilt. pub(crate) fn parquet_typed_value_from_logical_shredded( shredded: ArrayRef, + metadata: Option<&ArrayRef>, ctx: &mut ExecutionCtx, ) -> VortexResult { + // A shredded list read from a file can be chunked, lazy or a list view, which hides its + // elements. + let shredded = if shredded.dtype().is_list() && !shredded.is::() { + let list_view = shredded.execute::(ctx)?; + list_from_list_view(list_view, ctx)?.into_array() + } else { + shredded + }; + if let Some(list_array) = shredded.as_opt::() { - let elements = parquet_shredded_field_from_logical(list_array.elements().clone(), ctx)?; + let elements = list_array.elements().clone(); + let metadata = metadata + .map(|metadata| element_metadata(metadata, list_array.offsets(), elements.len(), ctx)) + .transpose()?; + let elements = parquet_shredded_field_from_logical(elements, metadata.as_ref(), ctx)?; return Ok(ListArray::try_new( elements, list_array.offsets().clone(), @@ -410,7 +429,11 @@ pub(crate) fn parquet_typed_value_from_logical_shredded( .zip(struct_array.iter_unmasked_fields()) { names.push(FieldName::from(name.as_ref())); - fields.push(parquet_shredded_field_from_logical(field.clone(), ctx)?); + fields.push(parquet_shredded_field_from_logical( + field.clone(), + metadata, + ctx, + )?); } Ok(StructArray::try_new( @@ -426,10 +449,27 @@ pub(crate) fn parquet_typed_value_from_logical_shredded( /// representation, the inverse of [`logical_shredded_from_parquet_field`]. fn parquet_shredded_field_from_logical( logical_field: ArrayRef, + metadata: Option<&ArrayRef>, ctx: &mut ExecutionCtx, ) -> VortexResult { let len = logical_field.len(); + // A union holds the whole value of the rows it holds, so it folds into a `value`-only shell. + if logical_field.dtype().is_union() { + let metadata = metadata + .ok_or_else(|| vortex_err!("cannot rebuild a shredded union without its metadata"))?; + let value = fold_union(logical_field, None, metadata, ctx)?; + return value_shell(value, len); + } + + // A partially shredded field read from a file can be lazy, such as the pack of the columns + // that store it, which hides that it is a Variant. + let logical_field = if logical_field.dtype().is_variant() && !logical_field.is::() { + logical_field.execute::(ctx)?.into_array() + } else { + logical_field + }; + // Partially shredded fields canonicalize to a nested Variant whose core storage holds the // residual `value` and whose own shredded tree holds the typed children. if let Some(variant) = logical_field.as_opt::() { @@ -439,10 +479,21 @@ fn parquet_shredded_field_from_logical( let value = core.value().cloned().ok_or_else(|| { vortex_err!("cannot rebuild Parquet shredded field: partially shredded Variant has no residual value") })?; + + if let Some(union) = variant + .shredded() + .filter(|shredded| shredded.dtype().is_union()) + { + let value = fold_union(union.clone(), Some(value), core.metadata(), ctx)?; + return value_shell(value, len); + } + let typed_value = variant .shredded() .cloned() - .map(|shredded| parquet_typed_value_from_logical_shredded(shredded, ctx)) + .map(|shredded| { + parquet_typed_value_from_logical_shredded(shredded, Some(core.metadata()), ctx) + }) .transpose()?; let mut names = vec![FieldName::from("value")]; @@ -461,7 +512,7 @@ fn parquet_shredded_field_from_logical( } // Fully shredded field: rebuild its typed subtree and wrap it in a `typed_value`-only shell. - let typed_value = parquet_typed_value_from_logical_shredded(logical_field, ctx)?; + let typed_value = parquet_typed_value_from_logical_shredded(logical_field, metadata, ctx)?; Ok(StructArray::try_new( FieldNames::from_iter([FieldName::from("typed_value")]), vec![typed_value], @@ -471,6 +522,17 @@ fn parquet_shredded_field_from_logical( .into_array()) } +/// A Parquet shredded field shell that holds only the residual `value`. +fn value_shell(value: ArrayRef, len: usize) -> VortexResult { + Ok(StructArray::try_new( + FieldNames::from_iter([FieldName::from("value")]), + vec![value], + len, + Validity::NonNullable, + )? + .into_array()) +} + /// Non-slot accessors and Arrow conversion for Parquet Variant storage arrays. pub trait ParquetVariantArrayExt: TypedArrayRef { /// Returns the outer row validity for the Variant values. @@ -956,7 +1018,8 @@ mod tests { .clone(); // Inverse transform: rebuild a Parquet `typed_value` and reattach it. - let rebuilt_typed_value = parquet_typed_value_from_logical_shredded(logical, &mut ctx)?; + let rebuilt_typed_value = + parquet_typed_value_from_logical_shredded(logical, None, &mut ctx)?; let rebuilt = ParquetVariant::try_new( ParquetVariantArrayExt::parquet_variant_validity(&core), core.metadata().clone(), diff --git a/encodings/parquet-variant/src/arrow.rs b/encodings/parquet-variant/src/arrow.rs index 041686f007b..f4e3de55079 100644 --- a/encodings/parquet-variant/src/arrow.rs +++ b/encodings/parquet-variant/src/arrow.rs @@ -61,6 +61,8 @@ use crate::ParquetVariantArrayExt; use crate::ParquetVariantArraySlotsExt; use crate::array::parquet_typed_value_from_logical_shredded; use crate::builder::StorageBuilder; +use crate::fold::fold_union; +use crate::shred::has_union; /// Arrow canonical extension name for Parquet Variant storage. const PARQUET_VARIANT_ARROW_EXTENSION_NAME: &str = "arrow.parquet.variant"; @@ -172,6 +174,17 @@ pub(crate) fn prepare_variant_for_export( let array = array.execute_until::(ctx)?; if let Some(variant) = array.as_opt::() { + if let Some(shredded) = variant + .shredded() + .filter(|shredded| has_union(shredded.dtype())) + { + vortex_ensure!( + typed_value.is_none(), + "multiple levels of Variant shredding are unsupported during Arrow export" + ); + return prepare_union_for_export(variant.core_storage().clone(), shredded.clone(), ctx); + } + let typed_value = match variant.shredded() { Some(shredded) => { vortex_ensure!( @@ -180,6 +193,7 @@ pub(crate) fn prepare_variant_for_export( ); Some(parquet_typed_value_from_logical_shredded( shredded.clone(), + None, ctx, )?) } @@ -229,6 +243,34 @@ pub(crate) fn prepare_variant_for_export( vortex_bail!("cannot export Variant without ParquetVariant core storage") } +/// Prepares the Variant of `core` storage with a `shredded` child that holds a union. +/// +/// Parquet has no union, so each union is folded into the residual value of its node, with the +/// metadata of each row; see [`fold_union`]. The core storage is prepared first for its metadata. +fn prepare_union_for_export( + core: ArrayRef, + shredded: ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let core = prepare_variant_for_export(core, None, ctx)?; + let storage = core.as_::(); + let metadata = storage.metadata().clone(); + + if shredded.dtype().is_union() { + let value = fold_union(shredded, storage.value().cloned(), &metadata, ctx)?; + return ParquetVariant::try_new( + ParquetVariantArrayExt::parquet_variant_validity(&storage), + metadata, + Some(value), + None, + ) + .map(IntoArray::into_array); + } + + let typed_value = parquet_typed_value_from_logical_shredded(shredded, Some(&metadata), ctx)?; + attach_typed_value(core, Some(typed_value)) +} + /// Prepares every chunk of the `ChunkedArray` `array`, then concatenates their storage into one /// Parquet Variant array. /// @@ -527,11 +569,16 @@ mod tests { use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::ListArray; + use vortex_array::arrays::ListViewArray; use vortex_array::arrays::MaskedArray; use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::Struct; use vortex_array::arrays::StructArray as VortexStructArray; use vortex_array::arrays::VarBinViewArray; + use vortex_array::arrays::Variant; use vortex_array::arrays::VariantArray; + use vortex_array::arrays::struct_::StructArrayExt; + use vortex_array::arrays::variant::VariantArraySlotsExt; use vortex_array::assert_arrays_eq; use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; @@ -544,6 +591,8 @@ mod tests { use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_error::vortex_bail; + use vortex_functions::variant_pack::VariantPack; + use vortex_functions::variant_pack::VariantPackOptions; use vortex_session::VortexSession; use super::PARQUET_VARIANT_ARROW_EXTENSION_NAME; @@ -751,6 +800,77 @@ mod tests { Ok(()) } + /// A partially shredded field read from a file is a lazy pack of its stored columns. It must + /// export as a `{value, typed_value}` field, as the canonical Variant does, and not as a + /// typed leaf of Variant storage. + #[rstest] + fn test_export_lazy_nested_residual(session: VortexSession) -> VortexResult<()> { + let core = + ConstantArray::new(Scalar::null(DType::Variant(Nullability::Nullable)), 2).into_array(); + let nested = shredded_with_nested_residual()?; + let nested = nested.as_::(); + let a = nested.unmasked_field_by_name("a")?.as_::(); + let a_shredded = VortexStructArray::try_new( + FieldNames::from_iter(["y"]), + vec![PrimitiveArray::from_option_iter([Some(5i32), None]).into_array()], + 2, + Validity::NonNullable, + )? + .into_array(); + + let shredded = |a: ArrayRef| -> VortexResult { + Ok(VortexStructArray::try_new( + FieldNames::from_iter(["a"]), + vec![a], + 2, + Validity::NonNullable, + )? + .into_array()) + }; + let canonical = VariantArray::try_new(a.core_storage().clone(), Some(a_shredded.clone()))?; + let lazy = VariantPack::try_new( + a.core_storage().clone(), + a_shredded, + VariantPackOptions::new(false), + )?; + let expected = + VariantArray::try_new(core.clone(), Some(shredded(canonical.into_array())?))?; + let actual = VariantArray::try_new(core, Some(shredded(lazy.into_array())?))?; + + let expected = export_variant(&session, expected.into_array())?; + let actual = export_variant(&session, actual.into_array())?; + + assert_struct_arrays_eq(actual.inner(), expected.inner()); + Ok(()) + } + + /// A shredded list read from a file is a list view. Its elements must export as + /// `{value, typed_value}` fields, as those of a list do. + #[rstest] + fn test_export_list_view_shredding(session: VortexSession) -> VortexResult<()> { + let mut ctx = session.create_execution_ctx(); + let list = ListArray::try_new( + PrimitiveArray::from_iter([1i32, 2, 3]).into_array(), + PrimitiveArray::from_iter([0u32, 2, 3]).into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + let list_view = list + .clone() + .execute::(&mut ctx)? + .into_array(); + + let expected = VariantArray::try_new(variant_null_core(2), Some(list))?; + let actual = VariantArray::try_new(variant_null_core(2), Some(list_view))?; + + let expected = export_variant(&session, expected.into_array())?; + let actual = export_variant(&session, actual.into_array())?; + + assert_struct_arrays_eq(actual.inner(), expected.inner()); + Ok(()) + } + #[rstest] fn test_export_rejects_nested_shredding_under_mask(session: VortexSession) -> VortexResult<()> { let mut ctx = session.create_execution_ctx(); diff --git a/encodings/parquet-variant/src/extract.rs b/encodings/parquet-variant/src/extract.rs index 49384096c16..417afa91b67 100644 --- a/encodings/parquet-variant/src/extract.rs +++ b/encodings/parquet-variant/src/extract.rs @@ -451,7 +451,7 @@ fn utf8(bytes: &[u8]) -> Option<&str> { } /// The bytes of row `idx`, borrowed from `array`. -fn bytes_at(array: &VarBinViewArray, idx: usize) -> &[u8] { +pub(crate) fn bytes_at(array: &VarBinViewArray, idx: usize) -> &[u8] { let view = &array.views()[idx]; if view.is_inlined() { view.as_inlined().value() @@ -463,7 +463,7 @@ fn bytes_at(array: &VarBinViewArray, idx: usize) -> &[u8] { /// How to find the fields of the cached names in the objects of rows that share one metadata. #[derive(Clone, Copy)] -enum Fields<'a> { +pub(crate) enum Fields<'a> { /// The dictionary id of each name. [`ABSENT`] is the id of a name that the dictionary does /// not hold, which no object has. Ids(&'a [usize]), @@ -482,6 +482,16 @@ impl Fields<'_> { Self::Names(metadata, names) => object.field(metadata, names[name].as_ref()), } } + + /// The position in `object` of the field with the cached name at index `name`, or + /// `Some(None)` if the object has no such field. + #[inline] + pub(crate) fn position(&self, object: &Object<'_>, name: usize) -> Option> { + match self { + Self::Ids(ids) => object.position_with_id(ids[name]), + Self::Names(metadata, names) => object.position(metadata, names[name].as_ref()), + } + } } /// An id that is not in any dictionary: the ids of an object are at most four bytes wide. @@ -496,7 +506,7 @@ const ABSENT: usize = usize::MAX; /// The slots are direct mapped on a hash of the metadata's view. Rows with the same metadata /// under a dictionary have the same view. A miss writes the ids of the slot in place, so that it /// neither allocates nor moves them. -struct FieldCache<'a> { +pub(crate) struct FieldCache<'a> { names: &'a [FieldName], /// The view of the metadata that each slot holds. keys: Vec>, @@ -509,7 +519,7 @@ struct FieldCache<'a> { impl<'a> FieldCache<'a> { const SLOTS: usize = 256; - fn new(names: &'a [FieldName]) -> Self { + pub(crate) fn new(names: &'a [FieldName]) -> Self { Self { names, keys: vec![None; Self::SLOTS], @@ -520,7 +530,11 @@ impl<'a> FieldCache<'a> { /// The fields of the names for row `idx` of `metadata`. #[inline] - fn resolve(&mut self, metadata: &'a VarBinViewArray, idx: usize) -> Option> { + pub(crate) fn resolve( + &mut self, + metadata: &'a VarBinViewArray, + idx: usize, + ) -> Option> { let key = metadata.views()[idx].as_u128(); // The top byte of the low half of a multiplicative hash, as the table has 256 slots. let mixed = (key ^ (key >> 64)).wrapping_mul(0x9E37_79B9_7F4A_7C15); @@ -601,13 +615,13 @@ impl<'a> FieldCache<'a> { /// The first `N` bytes of `bytes`. #[inline] -fn array(bytes: &[u8]) -> Option<[u8; N]> { +pub(crate) fn array(bytes: &[u8]) -> Option<[u8; N]> { bytes.get(..N)?.try_into().ok() } /// Reads a little-endian unsigned integer of `width` bytes, at most four. #[inline] -fn read_uint(bytes: &[u8], width: usize) -> Option { +pub(crate) fn read_uint(bytes: &[u8], width: usize) -> Option { // The width is one byte far more often than not, and a fixed-width read is a single load // where copying a variable number of bytes is a call. Some(match width { @@ -623,22 +637,22 @@ fn read_uint(bytes: &[u8], width: usize) -> Option { } /// The two low bits of a value's first byte, its basic type. -const BASIC_TYPE_MASK: u8 = 0b11; -const PRIMITIVE: u8 = 0; -const SHORT_STRING: u8 = 1; -const OBJECT: u8 = 2; -const ARRAY: u8 = 3; +pub(crate) const BASIC_TYPE_MASK: u8 = 0b11; +pub(crate) const PRIMITIVE: u8 = 0; +pub(crate) const SHORT_STRING: u8 = 1; +pub(crate) const OBJECT: u8 = 2; +pub(crate) const ARRAY: u8 = 3; /// Primitive type ids, the six high bits of a primitive value's first byte. -const INT8: u8 = 3; -const INT16: u8 = 4; -const INT32: u8 = 5; -const INT64: u8 = 6; -const LONG_STRING: u8 = 16; +pub(crate) const INT8: u8 = 3; +pub(crate) const INT16: u8 = 4; +pub(crate) const INT32: u8 = 5; +pub(crate) const INT64: u8 = 6; +pub(crate) const LONG_STRING: u8 = 16; /// The dictionary of field names of a Variant value. #[derive(Clone, Copy)] -struct Metadata<'a> { +pub(crate) struct Metadata<'a> { /// The number of names. len: usize, /// The width in bytes of an offset. @@ -676,7 +690,7 @@ impl<'a> Metadata<'a> { } /// An object value: its field ids, sorted by field name, and the offsets of the field values. -struct Object<'a> { +pub(crate) struct Object<'a> { len: usize, id_size: usize, offset_size: usize, @@ -687,7 +701,7 @@ struct Object<'a> { impl<'a> Object<'a> { /// Reads the object header of `value`, or returns `Some(None)` if it is not an object. - fn new(value: &'a [u8]) -> Option> { + pub(crate) fn new(value: &'a [u8]) -> Option> { let header = *value.first()?; if header & BASIC_TYPE_MASK != OBJECT { return Some(None); @@ -711,34 +725,59 @@ impl<'a> Object<'a> { })) } - /// The value of the field whose name has dictionary id `id`, or `Some(None)` if the object - /// has no such field. + /// The number of fields. + pub(crate) fn len(&self) -> usize { + self.len + } + + /// The width in bytes of a field id. + pub(crate) fn id_size(&self) -> usize { + self.id_size + } + + /// The id bytes of the field at `position`, as the object stores them. + pub(crate) fn id_bytes(&self, position: usize) -> Option<&'a [u8]> { + self.ids + .get(position * self.id_size..(position + 1) * self.id_size) + } + + /// The value of the field at `position`, followed by whatever the object stores after it. #[inline] - fn field_with_id(&self, id: usize) -> Option> { - let position = if self.id_size == 1 { - self.ids.iter().position(|&field| usize::from(field) == id) - } else { - let mut position = None; - for (idx, field) in self.ids.chunks_exact(self.id_size).enumerate() { - if read_uint(field, self.id_size)? == id { - position = Some(idx); - break; - } - } - position - }; - let Some(position) = position else { - return Some(None); - }; + pub(crate) fn value(&self, position: usize) -> Option<&'a [u8]> { let offset = read_uint( self.offsets.get(position * self.offset_size..)?, self.offset_size, )?; - Some(Some(self.values.get(offset..)?)) + self.values.get(offset..) } - /// The value of the field `name`, or `Some(None)` if the object has no such field. - fn field(&self, metadata: &Metadata<'_>, name: &str) -> Option> { + /// The position of the field whose name has dictionary id `id`, or `Some(None)` if the + /// object has no such field. + #[inline] + fn position_with_id(&self, id: usize) -> Option> { + if self.id_size == 1 { + return Some(self.ids.iter().position(|&field| usize::from(field) == id)); + } + for (idx, field) in self.ids.chunks_exact(self.id_size).enumerate() { + if read_uint(field, self.id_size)? == id { + return Some(Some(idx)); + } + } + Some(None) + } + + /// The value of the field whose name has dictionary id `id`, or `Some(None)` if the object + /// has no such field. + #[inline] + fn field_with_id(&self, id: usize) -> Option> { + match self.position_with_id(id)? { + Some(position) => self.value(position).map(Some), + None => Some(None), + } + } + + /// The position of the field `name`, or `Some(None)` if the object has no such field. + fn position(&self, metadata: &Metadata<'_>, name: &str) -> Option> { let (mut low, mut high) = (0, self.len); while low < high { let mid = low + (high - low) / 2; @@ -746,21 +785,23 @@ impl<'a> Object<'a> { match metadata.name(id)?.cmp(name.as_bytes()) { std::cmp::Ordering::Less => low = mid + 1, std::cmp::Ordering::Greater => high = mid, - std::cmp::Ordering::Equal => { - let offset = read_uint( - self.offsets.get(mid * self.offset_size..)?, - self.offset_size, - )?; - return Some(Some(self.values.get(offset..)?)); - } + std::cmp::Ordering::Equal => return Some(Some(mid)), } } Some(None) } + + /// The value of the field `name`, or `Some(None)` if the object has no such field. + fn field(&self, metadata: &Metadata<'_>, name: &str) -> Option> { + match self.position(metadata, name)? { + Some(position) => self.value(position).map(Some), + None => Some(None), + } + } } /// An array value: the offsets of its elements, which follow one another. -struct Elements<'a> { +pub(crate) struct Elements<'a> { len: usize, offset_size: usize, offsets: &'a [u8], @@ -769,7 +810,7 @@ struct Elements<'a> { impl<'a> Elements<'a> { /// Reads the array header of `value`, or returns `Some(None)` if it is not an array. - fn new(value: &'a [u8]) -> Option> { + pub(crate) fn new(value: &'a [u8]) -> Option> { let header = *value.first()?; if header & BASIC_TYPE_MASK != ARRAY { return Some(None); @@ -789,8 +830,13 @@ impl<'a> Elements<'a> { })) } - /// The value of element `idx`. - fn element(&self, idx: usize) -> Option<&'a [u8]> { + /// The number of elements. + pub(crate) fn len(&self) -> usize { + self.len + } + + /// The value of element `idx`, followed by the elements after it. + pub(crate) fn element(&self, idx: usize) -> Option<&'a [u8]> { let offset = read_uint( self.offsets.get(idx * self.offset_size..)?, self.offset_size, diff --git a/encodings/parquet-variant/src/fold.rs b/encodings/parquet-variant/src/fold.rs new file mode 100644 index 00000000000..f41ca0b5dba --- /dev/null +++ b/encodings/parquet-variant/src/fold.rs @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Folds a shredded union back into the residual binary value. +//! +//! Parquet Variant storage has no union, so a Variant shredded into one exports with the union +//! as Variant bytes. A member holds the whole value of a row, and the residual holds nothing of +//! it, so the bytes of the member value take the place of the residual of that row. +//! +//! The bytes are written with the metadata of the row, so that the field ids of an object are the +//! ids of its names in that metadata. A member object was shredded from an object of that row, so +//! the metadata has each of its names. + +use parquet_variant::ObjectFieldBuilder; +use parquet_variant::VariantBuilder; +use parquet_variant::VariantBuilderExt; +use parquet_variant::VariantMetadata; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::UnionArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::builders::ArrayBuilder; +use vortex_array::builders::VarBinViewBuilder; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::scalar::Scalar; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; + +use crate::extract::bytes_at; + +/// The residual binary value of a node that holds `union`, with `residual` the residual of the +/// rows that the union does not hold, and `metadata` the metadata of each row. +pub(crate) fn fold_union( + union: ArrayRef, + residual: Option, + metadata: &ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let len = union.len(); + let union = union.execute::(ctx)?.into_array(); + let metadata = metadata.clone().execute::(ctx)?; + let residual = residual + .map(|residual| { + let valid = residual.validity()?.execute_mask(len, ctx)?; + Ok::<_, vortex_error::VortexError>((residual.execute::(ctx)?, valid)) + }) + .transpose()?; + + let mut value = VarBinViewBuilder::with_capacity_in( + DType::Binary(Nullability::Nullable), + len, + ctx.allocator().clone(), + ); + for idx in 0..len { + let member = union.execute_scalar(idx, ctx)?; + match member.as_union().child() { + Some(member) => value.append_value(encode(bytes_at(&metadata, idx), &member)?), + None => match &residual { + Some((residual, valid)) if valid.value(idx) => { + value.append_value(bytes_at(residual, idx)); + } + _ => value.append_null(), + }, + } + } + Ok(value.finish_into_varbinview().into_array()) +} + +/// The Variant bytes of `value`, with the field ids of the names in `metadata`. +fn encode(metadata: &[u8], value: &Scalar) -> VortexResult> { + let metadata = VariantMetadata::try_new(metadata)?; + let mut builder = VariantBuilder::new().with_field_names(metadata.iter()); + append(&mut builder, value)?; + + let (written, value) = builder.finish(); + vortex_ensure_eq!( + VariantMetadata::try_new(&written)?.len(), + metadata.len(), + "a shredded union holds an object field whose name is not in the metadata of its row" + ); + Ok(value) +} + +/// Appends the typed value `value` to `builder`. A null is a value that is missing. +fn append(builder: &mut B, value: &Scalar) -> VortexResult<()> { + if value.is_null() { + builder.append_null(); + return Ok(()); + } + + let missing = || vortex_err!("a valid {} scalar has no value", value.dtype()); + match value.dtype() { + DType::Bool(_) => builder.append_value(value.as_bool().value().ok_or_else(missing)?), + DType::Primitive(ptype, _) => { + let primitive = value.as_primitive(); + match ptype { + PType::I8 => builder.append_value(primitive.as_::().ok_or_else(missing)?), + PType::I16 => builder.append_value(primitive.as_::().ok_or_else(missing)?), + PType::I32 => builder.append_value(primitive.as_::().ok_or_else(missing)?), + PType::I64 => builder.append_value(primitive.as_::().ok_or_else(missing)?), + PType::F32 => builder.append_value(primitive.as_::().ok_or_else(missing)?), + PType::F64 => builder.append_value(primitive.as_::().ok_or_else(missing)?), + _ => vortex_bail!("a shredded union cannot hold a {ptype} value"), + } + } + DType::Utf8(_) => { + let string = value.as_utf8().value().ok_or_else(missing)?; + builder.append_value(string.as_str()); + } + DType::Binary(_) => { + let binary = value.as_binary().value().ok_or_else(missing)?; + builder.append_value(binary.as_slice()); + } + DType::Struct(..) => { + let fields = value.as_struct(); + let mut object = builder.try_new_object()?; + for name in fields.names().iter() { + let field = fields.field(name.as_ref()).ok_or_else(missing)?; + append( + &mut ObjectFieldBuilder::new(name.as_ref(), &mut object), + &field, + )?; + } + object.finish(); + } + DType::List(..) => { + let elements = value.as_list().elements().ok_or_else(missing)?; + let mut list = builder.try_new_list()?; + for element in &elements { + append(&mut list, element)?; + } + list.finish(); + } + DType::Union(..) => match value.as_union().child() { + Some(member) => append(builder, &member)?, + None => builder.append_null(), + }, + _ => vortex_bail!("a shredded union cannot hold a {} value", value.dtype()), + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use parquet_variant::Variant as PqVariant; + use parquet_variant::VariantBuilder; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::scalar::Scalar; + use vortex_error::VortexResult; + + use super::encode; + + /// An object is written with the field ids of the metadata of its row, so the bytes read + /// back with that metadata. + #[test] + fn encodes_an_object_with_the_ids_of_its_row() -> VortexResult<()> { + let mut row = VariantBuilder::new(); + row.new_object() + .with_field("z", 1i64) + .with_field("a", "x") + .finish(); + let (metadata, _) = row.finish(); + + let object = Scalar::struct_( + DType::struct_( + [ + ("a", DType::Utf8(Nullability::Nullable)), + ("z", DType::Primitive(PType::I64, Nullability::Nullable)), + ], + Nullability::Nullable, + ), + [ + Scalar::utf8("x", Nullability::Nullable), + Scalar::primitive(1i64, Nullability::Nullable), + ], + ); + let value = encode(&metadata, &object)?; + + let variant = PqVariant::try_new(&metadata, &value)?; + let object = variant.as_object().expect("an object"); + assert_eq!(object.get("a"), Some(PqVariant::from("x"))); + assert_eq!(object.get("z"), Some(PqVariant::from(1i64))); + Ok(()) + } +} diff --git a/encodings/parquet-variant/src/kernel.rs b/encodings/parquet-variant/src/kernel.rs index 89aede5a832..7d2f42730a4 100644 --- a/encodings/parquet-variant/src/kernel.rs +++ b/encodings/parquet-variant/src/kernel.rs @@ -49,11 +49,15 @@ use vortex_arrow::ArrowSession; use vortex_arrow::ArrowSessionExt; use vortex_arrow::ExecuteArrowExt; use vortex_error::VortexResult; +use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; use vortex_error::vortex_err; use vortex_functions::variant_get::VariantGet; use vortex_functions::variant_get::VariantPath; use vortex_functions::variant_get::VariantPathElement; +use vortex_functions::variant_shred::VariantShred; +use vortex_functions::variant_shred::VariantShredStrict; +use vortex_functions::variant_shred::VariantShredUnion; use vortex_json::Json; use vortex_json::JsonToVariant; use vortex_mask::Mask; @@ -65,6 +69,9 @@ use crate::ParquetVariantArraySlotsExt; use crate::compute::AllNonDistinctParquetVariant; use crate::extract::covers; use crate::extract::extract; +use crate::shred::Mismatch; +use crate::shred::has_union; +use crate::shred::shred; pub(crate) fn initialize(session: &VortexSession) { let kernels = session.kernels(); @@ -84,6 +91,17 @@ pub(crate) fn initialize(session: &VortexSession) { TakeExecuteAdaptor(ParquetVariant), ); kernels.register_execute_parent_kernel(VariantGet.id(), ParquetVariant, VariantGetKernel); + kernels.register_execute_parent_kernel(VariantShred.id(), ParquetVariant, VariantShredKernel); + kernels.register_execute_parent_kernel( + VariantShredStrict.id(), + ParquetVariant, + VariantShredStrictKernel, + ); + kernels.register_execute_parent_kernel( + VariantShredUnion.id(), + ParquetVariant, + VariantShredUnionKernel, + ); kernels.register_execute_parent_kernel( JsonToVariant.id(), Extension, @@ -97,6 +115,108 @@ pub(crate) fn initialize(session: &VortexSession) { ); } +/// Shreds unshredded storage. Storage that is shredded already is left to +/// [`VariantShred`] itself, which rejects it. +#[derive(Default, Debug)] +struct VariantShredKernel; + +impl ExecuteParentKernel for VariantShredKernel { + type Parent = ExactScalarFn; + + fn execute_parent( + &self, + array: ArrayView<'_, ParquetVariant>, + parent: ScalarFnArrayView<'_, VariantShred>, + child_idx: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + if child_idx != 0 || array.typed_value().is_some() { + return Ok(None); + } + + let schema = parent.options.schema(); + vortex_ensure!( + !has_union(schema), + "{} shreds into Parquet storage, which has no union, not {schema}", + VariantShred.id() + ); + shred( + &array, + schema, + Mismatch::Residual, + parent.dtype().is_nullable(), + ctx, + ) + .map(Some) + } +} + +/// Shreds unshredded storage by a schema that can hold unions. Storage that is shredded already +/// is left to [`VariantShredUnion`] itself, which rejects it. +#[derive(Default, Debug)] +struct VariantShredUnionKernel; + +impl ExecuteParentKernel for VariantShredUnionKernel { + type Parent = ExactScalarFn; + + fn execute_parent( + &self, + array: ArrayView<'_, ParquetVariant>, + parent: ScalarFnArrayView<'_, VariantShredUnion>, + child_idx: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + if child_idx != 0 || array.typed_value().is_some() { + return Ok(None); + } + + shred( + &array, + parent.options.schema(), + Mismatch::Residual, + parent.dtype().is_nullable(), + ctx, + ) + .map(Some) + } +} + +/// Shreds unshredded storage, and fails on a value that does not fit the schema. Storage that +/// is shredded already is left to [`VariantShredStrict`] itself, which rejects it. +#[derive(Default, Debug)] +struct VariantShredStrictKernel; + +impl ExecuteParentKernel for VariantShredStrictKernel { + type Parent = ExactScalarFn; + + fn execute_parent( + &self, + array: ArrayView<'_, ParquetVariant>, + parent: ScalarFnArrayView<'_, VariantShredStrict>, + child_idx: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + if child_idx != 0 || array.typed_value().is_some() { + return Ok(None); + } + + let schema = parent.options.schema(); + vortex_ensure!( + !has_union(schema), + "{} shreds into Parquet storage, which has no union, not {schema}", + VariantShredStrict.id() + ); + shred( + &array, + schema, + Mismatch::Reject, + parent.dtype().is_nullable(), + ctx, + ) + .map(Some) + } +} + #[derive(Default, Debug)] struct VariantGetKernel; diff --git a/encodings/parquet-variant/src/lib.rs b/encodings/parquet-variant/src/lib.rs index 0112fe07c9e..7aae1590218 100644 --- a/encodings/parquet-variant/src/lib.rs +++ b/encodings/parquet-variant/src/lib.rs @@ -31,10 +31,12 @@ mod arrow_properties; mod builder; mod compute; mod extract; +mod fold; #[cfg(test)] mod json_to_variant_tests; mod kernel; mod operations; +mod shred; mod validity; mod vtable; @@ -44,6 +46,7 @@ pub use array::ParquetVariantArrayExt; pub use array::ParquetVariantArraySlotsExt; pub use array::ParquetVariantSlots; pub use array::ParquetVariantSlotsView; +pub use shred::InferredShredding; use vortex_array::session::ArraySessionExt; use vortex_arrow::ArrowSessionExt; pub use vortex_json::JsonToVariant; diff --git a/encodings/parquet-variant/src/shred/exact.rs b/encodings/parquet-variant/src/shred/exact.rs new file mode 100644 index 00000000000..dc9440bdc92 --- /dev/null +++ b/encodings/parquet-variant/src/shred/exact.rs @@ -0,0 +1,754 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Shreds unshredded storage by reading the [Variant encoding] in place. +//! +//! A value moves into a typed column only if its type is the type of the column, as the +//! [Variant shredding] specification requires. Every other value stays in the residual binary +//! value, byte for byte. The only conversion is between the integer widths, which are one +//! equivalence class: an integer moves into an integer column that it fits. +//! +//! An object moves into a shredded struct, and the residual value of the row keeps the fields +//! that the struct does not shred. An array moves into a shredded list, and each element is +//! shredded by the element of the schema. +//! +//! [Variant encoding]: https://github.com/apache/parquet-format/blob/master/VariantEncoding.md +//! [Variant shredding]: https://github.com/apache/parquet-format/blob/master/VariantShredding.md + +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::builders::ArrayBuilder; +use vortex_array::builders::VarBinViewBuilder; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldName; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::validity::Validity; +use vortex_buffer::BitBufferMut; +use vortex_buffer::BufferAllocatorRef; +use vortex_buffer::BufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_err; +use vortex_mask::Mask; + +use super::union::UnionMember; +use crate::extract::ARRAY; +use crate::extract::BASIC_TYPE_MASK; +use crate::extract::Elements; +use crate::extract::FieldCache; +use crate::extract::Fields; +use crate::extract::INT8; +use crate::extract::INT16; +use crate::extract::INT32; +use crate::extract::INT64; +use crate::extract::LONG_STRING; +use crate::extract::OBJECT; +use crate::extract::Object; +use crate::extract::PRIMITIVE; +use crate::extract::SHORT_STRING; +use crate::extract::array; +use crate::extract::bytes_at; +use crate::extract::read_uint; + +/// Primitive type ids that [`crate::extract`] does not read. +const NULL: u8 = 0; +const TRUE: u8 = 1; +const FALSE: u8 = 2; +const DOUBLE: u8 = 7; +const DECIMAL4: u8 = 8; +const DECIMAL8: u8 = 9; +const DECIMAL16: u8 = 10; +const DATE: u8 = 11; +const TIMESTAMP_MICROS: u8 = 12; +const TIMESTAMP_NTZ_MICROS: u8 = 13; +const FLOAT: u8 = 14; +const BINARY: u8 = 15; +const TIME_NTZ: u8 = 17; +const TIMESTAMP_NANOS: u8 = 18; +const TIMESTAMP_NTZ_NANOS: u8 = 19; +const UUID: u8 = 20; + +/// What happens to a value that does not fit the schema. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Mismatch { + /// The value stays in the residual binary value, as the Parquet specification requires. + Residual, + /// Shredding fails. + Reject, +} + +/// Shreds the values of unshredded storage by `schema`. +/// +/// `metadata` and `value` are the storage children, and `valid` the rows that hold a value. +/// Returns the residual `value` child and the `typed_value` child of the shredded storage. +pub(super) fn shred( + metadata: &VarBinViewArray, + value: &VarBinViewArray, + valid: &Mask, + schema: &DType, + mismatch: Mismatch, + allocator: &BufferAllocatorRef, +) -> VortexResult<(ArrayRef, ArrayRef)> { + let mut names = Vec::new(); + let mut shredder = Shredder::new( + schema, + Node::root(schema, mismatch), + &mut names, + value.len(), + allocator, + )?; + let mut cache = FieldCache::new(&names); + + for idx in 0..value.len() { + if !valid.value(idx) { + shredder.append_missing(); + continue; + } + + let malformed = || vortex_err!("Variant value of row {idx} is malformed"); + let fields = cache.resolve(metadata, idx).ok_or_else(malformed)?; + match shredder.append(&fields, bytes_at(value, idx)) { + Ok(()) => {} + Err(Fail::Malformed) => return Err(malformed()), + Err(Fail::Rejected(reason)) => vortex_bail!("Variant value of row {idx} {reason}"), + } + } + + shredder.finish() +} + +/// Why a value could not be appended. +pub(super) enum Fail { + /// The bytes are cut short or do not decode. + Malformed, + /// The value does not fit the schema, and the shredding rejects it. + Rejected(String), +} + +/// Turns a value that is missing because bytes do not decode into [`Fail::Malformed`]. +pub(super) trait OrMalformed { + fn or_malformed(self) -> Result; +} + +impl OrMalformed for Option { + #[inline] + fn or_malformed(self) -> Result { + self.ok_or(Fail::Malformed) + } +} + +/// Where a node is in the schema, and what happens to a value that does not fit it. +struct Node { + /// The path of the node, such as `$.commit.rev` or `$.tags[]`. + path: String, + /// The schema of the node. + schema: DType, + mismatch: Mismatch, +} + +impl Node { + fn root(schema: &DType, mismatch: Mismatch) -> Self { + Self { + path: "$".to_string(), + schema: schema.clone(), + mismatch, + } + } + + /// The node of `schema` at `path` below this node. + fn child(&self, path: String, schema: &DType) -> Self { + Self { + path, + schema: schema.clone(), + mismatch: self.mismatch, + } + } + + fn rejects(&self) -> bool { + self.mismatch == Mismatch::Reject + } + + fn reject(&self) -> Fail { + Fail::Rejected(format!( + "at `{}` does not fit the shredding schema {}", + self.path, self.schema + )) + } +} + +/// The `value` and `typed_value` columns of one node of the schema. +struct Shredder { + node: Node, + /// The binary values that are not in `typed`. + value: VarBinViewBuilder, + typed: Typed, +} + +/// The builder of a `typed_value` column. +enum Typed { + Utf8(VarBinViewBuilder), + Binary(VarBinViewBuilder), + Bool(Leaf), + I8(Leaf), + I16(Leaf), + I32(Leaf), + I64(Leaf), + F32(Leaf), + F64(Leaf), + Object(Box), + List(Box), + /// A union takes a value whole, as a leaf does. + Union(Box), +} + +/// A shredded struct. Each field shreds the field of the object of the same name. +struct ObjectShredder { + names: FieldNames, + /// The shredder of each field, with the index of its name in the [`FieldCache`]. + fields: Vec<(usize, Shredder)>, + validity: BitBufferMut, + /// For each field of the current object, whether a shredder took it. + taken: Vec, + /// The residual object of the current row. + residual: Vec, +} + +/// A shredded list. Each element is shredded by the same shredder. +struct ListShredder { + offsets: BufferMut, + elements: Shredder, + validity: BitBufferMut, +} + +/// The values and validity of a typed leaf. +pub(super) struct Leaf { + values: BufferMut, + validity: BitBufferMut, +} + +impl Leaf { + pub(super) fn new(capacity: usize) -> Self { + Self { + values: BufferMut::with_capacity(capacity), + validity: BitBufferMut::with_capacity(capacity), + } + } + + #[inline] + pub(super) fn push(&mut self, value: Option) { + self.values.push(value.unwrap_or_default()); + self.validity.append(value.is_some()); + } +} + +impl Leaf { + pub(super) fn finish(self) -> ArrayRef { + PrimitiveArray::new(self.values.freeze(), Validity::from(self.validity.freeze())) + .into_array() + } +} + +impl Leaf { + pub(super) fn finish_bool(self) -> ArrayRef { + let values = self.values.iter().copied().collect::(); + BoolArray::new(values.freeze(), Validity::from(self.validity.freeze())).into_array() + } +} + +impl Shredder { + /// A shredder of `schema`, which adds the field names of the structs in `schema` to + /// `names`. The strings and binaries are allocated by `allocator`. + fn new( + schema: &DType, + node: Node, + names: &mut Vec, + capacity: usize, + allocator: &BufferAllocatorRef, + ) -> VortexResult { + let typed = match schema { + DType::Utf8(_) => Typed::Utf8(VarBinViewBuilder::with_capacity_in( + DType::Utf8(Nullability::Nullable), + capacity, + allocator.clone(), + )), + DType::Binary(_) => Typed::Binary(binary_builder(capacity, allocator)), + DType::Bool(_) => Typed::Bool(Leaf::new(capacity)), + DType::Primitive(PType::I8, _) => Typed::I8(Leaf::new(capacity)), + DType::Primitive(PType::I16, _) => Typed::I16(Leaf::new(capacity)), + DType::Primitive(PType::I32, _) => Typed::I32(Leaf::new(capacity)), + DType::Primitive(PType::I64, _) => Typed::I64(Leaf::new(capacity)), + DType::Primitive(PType::F32, _) => Typed::F32(Leaf::new(capacity)), + DType::Primitive(PType::F64, _) => Typed::F64(Leaf::new(capacity)), + DType::Struct(struct_fields, _) => { + let mut fields = Vec::with_capacity(struct_fields.nfields()); + for (name, field) in struct_fields.names().iter().zip(struct_fields.fields()) { + let child = node.child(format!("{}.{name}", node.path), &field); + names.push(name.clone()); + let name = names.len() - 1; + fields.push((name, Self::new(&field, child, names, capacity, allocator)?)); + } + Typed::Object(Box::new(ObjectShredder { + names: struct_fields.names().clone(), + fields, + validity: BitBufferMut::with_capacity(capacity), + taken: Vec::new(), + residual: Vec::new(), + })) + } + DType::List(element, _) => { + let mut offsets = BufferMut::with_capacity(capacity + 1); + offsets.push(0); + Typed::List(Box::new(ListShredder { + offsets, + elements: Self::new( + element, + node.child(format!("{}[]", node.path), element), + names, + capacity, + allocator, + )?, + validity: BitBufferMut::with_capacity(capacity), + })) + } + DType::Union(..) => Typed::Union(Box::new(UnionMember::new( + schema, names, capacity, allocator, + )?)), + _ => vortex_bail!( + "a Parquet Variant can only be shredded into strings, binaries, booleans, signed \ + integers, floats, structs, lists and unions, not {schema}" + ), + }; + + Ok(Self { + node, + value: binary_builder(capacity, allocator), + typed, + }) + } + + /// Appends a row without a value: an object field that the object does not have, or a + /// row that is null. + fn append_missing(&mut self) { + self.value.append_null(); + self.typed.append_null(); + } + + /// Appends `value`, the bytes of a value followed by any other bytes. + fn append(&mut self, fields: &Fields<'_>, value: &[u8]) -> Result<(), Fail> { + let value = value + .get(..value_len(value).or_malformed()?) + .or_malformed()?; + + // A shredding that rejects keeps nothing in the residual. A Variant null holds no + // value, so it is stored as one that is missing. + if self.node.rejects() && header(value) == Some((PRIMITIVE, NULL)) { + self.append_missing(); + return Ok(()); + } + + let taken = match &mut self.typed { + Typed::Utf8(builder) => { + let string = string(value); + if let Some(string) = string { + builder.append_value(string); + } + string.is_some() + } + Typed::Binary(builder) => { + let binary = binary(value); + if let Some(binary) = binary { + builder.append_value(binary); + } + binary.is_some() + } + Typed::Bool(leaf) => push(leaf, boolean(value)), + Typed::I8(leaf) => push(leaf, integer(value).and_then(|v| i8::try_from(v).ok())), + Typed::I16(leaf) => push(leaf, integer(value).and_then(|v| i16::try_from(v).ok())), + Typed::I32(leaf) => push(leaf, integer(value).and_then(|v| i32::try_from(v).ok())), + Typed::I64(leaf) => push(leaf, integer(value)), + Typed::F32(leaf) => push(leaf, float(value)), + Typed::F64(leaf) => push(leaf, double(value)), + Typed::Union(union) => union.append_fitting(fields, value)?, + Typed::Object(object) => { + return object.append(fields, value, &mut self.value, &self.node); + } + Typed::List(list) => return list.append(fields, value, &mut self.value, &self.node), + }; + + if taken { + self.value.append_null(); + } else if self.node.rejects() { + return Err(self.node.reject()); + } else { + self.typed.append_null(); + self.value.append_value(value); + } + Ok(()) + } + + /// The `value` and `typed_value` columns. + fn finish(mut self) -> VortexResult<(ArrayRef, ArrayRef)> { + let value = self.value.finish_into_varbinview().into_array(); + let typed = match self.typed { + Typed::Utf8(mut builder) | Typed::Binary(mut builder) => { + builder.finish_into_varbinview().into_array() + } + Typed::Bool(leaf) => leaf.finish_bool(), + Typed::I8(leaf) => leaf.finish(), + Typed::I16(leaf) => leaf.finish(), + Typed::I32(leaf) => leaf.finish(), + Typed::I64(leaf) => leaf.finish(), + Typed::F32(leaf) => leaf.finish(), + Typed::F64(leaf) => leaf.finish(), + Typed::Object(object) => object.finish()?, + Typed::List(list) => list.finish()?, + Typed::Union(union) => union.finish()?, + }; + Ok((value, typed)) + } + + /// The struct of the `value` and `typed_value` columns, as a shredded object field or list + /// element stores them. + fn finish_field(self, validity: Validity) -> VortexResult { + let len = self.value.len(); + let (value, typed) = self.finish()?; + Ok(StructArray::try_new( + FieldNames::from(["value", "typed_value"]), + vec![value, typed], + len, + validity, + )? + .into_array()) + } +} + +impl Typed { + fn append_null(&mut self) { + match self { + Self::Utf8(builder) | Self::Binary(builder) => builder.append_null(), + Self::Bool(leaf) => leaf.push(None), + Self::I8(leaf) => leaf.push(None), + Self::I16(leaf) => leaf.push(None), + Self::I32(leaf) => leaf.push(None), + Self::I64(leaf) => leaf.push(None), + Self::F32(leaf) => leaf.push(None), + Self::F64(leaf) => leaf.push(None), + Self::Object(object) => object.append_null(), + Self::List(list) => list.append_null(), + Self::Union(union) => union.append_null(), + } + } +} + +impl ObjectShredder { + fn append_null(&mut self) { + for (_, field) in &mut self.fields { + field.append_missing(); + } + self.validity.append(false); + } + + /// Appends `value`, the bytes of exactly one value, and its residual to `residual`. + fn append( + &mut self, + fields: &Fields<'_>, + value: &[u8], + residual: &mut VarBinViewBuilder, + node: &Node, + ) -> Result<(), Fail> { + let Some(object) = Object::new(value).or_malformed()? else { + if node.rejects() { + return Err(node.reject()); + } + self.append_null(); + residual.append_value(value); + return Ok(()); + }; + + self.taken.clear(); + self.taken.resize(object.len(), false); + let mut shredded = 0; + for (name, field) in &mut self.fields { + match fields.position(&object, *name).or_malformed()? { + Some(position) => { + *self.taken.get_mut(position).or_malformed()? = true; + shredded += 1; + field.append(fields, object.value(position).or_malformed()?)?; + } + None => field.append_missing(), + } + } + self.validity.append(true); + + if shredded == object.len() { + residual.append_null(); + } else if shredded == 0 { + residual.append_value(value); + } else { + write_object(&object, &self.taken, &mut self.residual).or_malformed()?; + residual.append_value(&self.residual); + } + Ok(()) + } + + fn finish(self) -> VortexResult { + let len = self.validity.len(); + let fields = self + .fields + .into_iter() + .map(|(_, field)| field.finish_field(Validity::NonNullable)) + .collect::>>()?; + Ok(StructArray::try_new( + self.names, + fields, + len, + Validity::from(self.validity.freeze()), + )? + .into_array()) + } +} + +impl ListShredder { + fn append_null(&mut self) { + let end = self.offsets.last().copied().unwrap_or_default(); + self.offsets.push(end); + self.validity.append(false); + } + + /// Appends `value`, the bytes of exactly one value, and its residual to `residual`. + fn append( + &mut self, + fields: &Fields<'_>, + value: &[u8], + residual: &mut VarBinViewBuilder, + node: &Node, + ) -> Result<(), Fail> { + let Some(list) = Elements::new(value).or_malformed()? else { + if node.rejects() { + return Err(node.reject()); + } + self.append_null(); + residual.append_value(value); + return Ok(()); + }; + + for idx in 0..list.len() { + self.elements + .append(fields, list.element(idx).or_malformed()?)?; + } + let end = self.offsets.last().copied().unwrap_or_default(); + self.offsets + .push(end + u64::try_from(list.len()).ok().or_malformed()?); + self.validity.append(true); + residual.append_null(); + Ok(()) + } + + fn finish(self) -> VortexResult { + let elements = self.elements.finish_field(Validity::AllValid)?; + let offsets = PrimitiveArray::new(self.offsets.freeze(), Validity::NonNullable); + // SAFETY: the offsets start at zero and grow by the number of elements each list + // appended, so they end at the number of elements, and there is one more offset than + // there are validity bits. + Ok(unsafe { + ListArray::new_unchecked( + elements, + offsets.into_array(), + Validity::from(self.validity.freeze()), + ) + } + .into_array()) + } +} + +pub(super) fn binary_builder(capacity: usize, allocator: &BufferAllocatorRef) -> VarBinViewBuilder { + VarBinViewBuilder::with_capacity_in( + DType::Binary(Nullability::Nullable), + capacity, + allocator.clone(), + ) +} + +/// Pushes `value` to `leaf`, and returns whether there was one. +#[inline] +fn push(leaf: &mut Leaf, value: Option) -> bool { + if value.is_some() { + leaf.push(value); + } + value.is_some() +} + +/// The basic type of `value`, and the six bits above it. +#[inline] +fn header(value: &[u8]) -> Option<(u8, u8)> { + let header = *value.first()?; + Some((header & BASIC_TYPE_MASK, header >> 2)) +} + +/// The string that `value` holds, if it is a string. +pub(super) fn string(value: &[u8]) -> Option<&str> { + let bytes = match header(value)? { + (SHORT_STRING, len) => value.get(1..1 + usize::from(len))?, + (PRIMITIVE, LONG_STRING) => sized(value)?, + _ => return None, + }; + std::str::from_utf8(bytes).ok() +} + +/// The bytes that `value` holds, if it is a binary. +pub(super) fn binary(value: &[u8]) -> Option<&[u8]> { + match header(value)? { + (PRIMITIVE, BINARY) => sized(value), + _ => None, + } +} + +/// The payload of a primitive with a four-byte size. +fn sized(value: &[u8]) -> Option<&[u8]> { + let len = read_uint(value.get(1..)?, 4)?; + value.get(5..5 + len) +} + +pub(super) fn boolean(value: &[u8]) -> Option { + match header(value)? { + (PRIMITIVE, TRUE) => Some(true), + (PRIMITIVE, FALSE) => Some(false), + _ => None, + } +} + +/// The integer that `value` holds, if it is an integer of any width. +pub(super) fn integer(value: &[u8]) -> Option { + let payload = value.get(1..)?; + match header(value)? { + (PRIMITIVE, INT8) => Some(i64::from(i8::from_le_bytes(array(payload)?))), + (PRIMITIVE, INT16) => Some(i64::from(i16::from_le_bytes(array(payload)?))), + (PRIMITIVE, INT32) => Some(i64::from(i32::from_le_bytes(array(payload)?))), + (PRIMITIVE, INT64) => Some(i64::from_le_bytes(array(payload)?)), + _ => None, + } +} + +pub(super) fn float(value: &[u8]) -> Option { + match header(value)? { + (PRIMITIVE, FLOAT) => Some(f32::from_le_bytes(array(value.get(1..)?)?)), + _ => None, + } +} + +pub(super) fn double(value: &[u8]) -> Option { + match header(value)? { + (PRIMITIVE, DOUBLE) => Some(f64::from_le_bytes(array(value.get(1..)?)?)), + _ => None, + } +} + +/// The length in bytes of the value at the start of `value`. +fn value_len(value: &[u8]) -> Option { + let (basic_type, bits) = header(value)?; + let bits = usize::from(bits); + match basic_type { + SHORT_STRING => Some(1 + bits), + PRIMITIVE => Some( + 1 + match u8::try_from(bits).ok()? { + 0 | TRUE | FALSE => 0, + INT8 => 1, + INT16 => 2, + INT32 | DATE | FLOAT => 4, + INT64 | DOUBLE | TIMESTAMP_MICROS | TIMESTAMP_NTZ_MICROS | TIME_NTZ + | TIMESTAMP_NANOS | TIMESTAMP_NTZ_NANOS => 8, + DECIMAL4 => 5, + DECIMAL8 => 9, + UUID => 16, + DECIMAL16 => 17, + BINARY | LONG_STRING => 4 + read_uint(value.get(1..)?, 4)?, + _ => return None, + }, + ), + OBJECT => { + let offset_size = (bits & 0b11) + 1; + let id_size = ((bits >> 2) & 0b11) + 1; + let len_size = if bits & 0b1_0000 != 0 { 4 } else { 1 }; + let len = read_uint(value.get(1..)?, len_size)?; + let offsets = 1 + len_size + len * id_size; + let last = offsets + len * offset_size; + let values = read_uint(value.get(last..)?, offset_size)?; + Some(last + offset_size + values) + } + ARRAY => { + let offset_size = (bits & 0b11) + 1; + let len_size = if bits & 0b100 != 0 { 4 } else { 1 }; + let len = read_uint(value.get(1..)?, len_size)?; + let last = 1 + len_size + len * offset_size; + let values = read_uint(value.get(last..)?, offset_size)?; + Some(last + offset_size + values) + } + _ => None, + } +} + +/// Writes the fields of `object` that are not `taken` to `out`, as an object of their own. +/// +/// The fields keep their ids, so the object reads with the metadata of the row, and their +/// order, which is the order of their names. +fn write_object(object: &Object<'_>, taken: &[bool], out: &mut Vec) -> Option<()> { + let mut len = 0; + let mut size = 0; + for (position, _) in taken.iter().enumerate().filter(|(_, taken)| !**taken) { + let value = object.value(position)?; + len += 1; + size += value_len(value)?; + } + + let id_size = object.id_size(); + let offset_size = uint_size(size)?; + let is_large = len > usize::from(u8::MAX); + let header = (u8::from(is_large) << 4) + | (u8::try_from(id_size - 1).ok()? << 2) + | u8::try_from(offset_size - 1).ok()?; + + out.clear(); + out.push(header << 2 | OBJECT); + write_uint(out, len, if is_large { 4 } else { 1 }); + for (position, _) in taken.iter().enumerate().filter(|(_, taken)| !**taken) { + out.extend_from_slice(object.id_bytes(position)?); + } + + let mut offset = 0; + for (position, _) in taken.iter().enumerate().filter(|(_, taken)| !**taken) { + write_uint(out, offset, offset_size); + offset += value_len(object.value(position)?)?; + } + write_uint(out, offset, offset_size); + + for (position, _) in taken.iter().enumerate().filter(|(_, taken)| !**taken) { + let value = object.value(position)?; + out.extend_from_slice(value.get(..value_len(value)?)?); + } + Some(()) +} + +/// The number of bytes of the smallest unsigned integer that holds `value`, at most four. +fn uint_size(value: usize) -> Option { + Some(match value { + 0..=0xFF => 1, + 0x100..=0xFFFF => 2, + 0x1_0000..=0xFF_FFFF => 3, + _ => { + u32::try_from(value).ok()?; + 4 + } + }) +} + +fn write_uint(out: &mut Vec, value: usize, width: usize) { + out.extend_from_slice(&value.to_le_bytes()[..width]); +} diff --git a/encodings/parquet-variant/src/shred/infer.rs b/encodings/parquet-variant/src/shred/infer.rs new file mode 100644 index 00000000000..baa254ebb91 --- /dev/null +++ b/encodings/parquet-variant/src/shred/infer.rs @@ -0,0 +1,286 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Infers a shredding schema from a sample of the values. + +use std::collections::BTreeMap; + +use parquet_variant::Variant as PqVariant; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; +use vortex_array::scalar_fn::ScalarFnRef; +use vortex_array::scalar_fn::ScalarFnVTableExt; +use vortex_arrow::ArrowExportOptions; +use vortex_error::VortexResult; +use vortex_functions::variant_shred::VariantShred; +use vortex_functions::variant_shred::VariantShredOptions; +use vortex_layout::layouts::variant::VariantShreddingPolicy; + +use crate::ParquetVariant; +use crate::ParquetVariantArrayExt; +use crate::arrow::prepare_variant_for_export; + +/// Shreds the object fields that a sample of the values has in common. +/// +/// The schema is inferred from the first chunk of a stream. It shreds each object field that +/// holds values of one type in every sampled row that has it, and that enough sampled rows have. +/// The types are strings, booleans, integers of any width, which shred as 64-bit integers, and +/// doubles. A field that also holds values of other types is not shredded, and stays in the +/// residual binary value. +#[derive(Clone, Debug)] +pub struct InferredShredding { + max_sampled_rows: usize, + max_depth: usize, + max_fields: usize, + min_presence_percent: usize, +} + +impl Default for InferredShredding { + fn default() -> Self { + Self { + max_sampled_rows: 1024, + max_depth: 4, + max_fields: 64, + min_presence_percent: 1, + } + } +} + +impl InferredShredding { + /// Reads at most `rows` rows of the first chunk, spread evenly over it. The default is 1024. + pub fn with_max_sampled_rows(mut self, rows: usize) -> Self { + self.max_sampled_rows = rows.max(1); + self + } + + /// Shreds fields at most `depth` objects deep. The default is 4. + pub fn with_max_depth(mut self, depth: usize) -> Self { + self.max_depth = depth; + self + } + + /// Shreds at most `fields` fields, those in the most sampled rows. The default is 64. + pub fn with_max_fields(mut self, fields: usize) -> Self { + self.max_fields = fields; + self + } + + /// Shreds a field only if at least `percent` percent of the sampled rows have it. The + /// default is 1. + pub fn with_min_presence_percent(mut self, percent: usize) -> Self { + self.min_presence_percent = percent.min(100); + self + } +} + +impl VariantShreddingPolicy for InferredShredding { + /// Shreds by the inferred schema, and keeps a value that does not fit it in the core + /// storage, as Parquet shredding does. + fn shredding( + &self, + first: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + Ok(self + .schema(first, ctx)? + .map(|schema| VariantShred.bind(VariantShredOptions::new(schema)))) + } +} + +impl InferredShredding { + /// The schema inferred from a sample of the `first` chunk, or `None` if no field is worth + /// shredding. + pub(crate) fn schema( + &self, + first: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + let storage = prepare_variant_for_export(first.clone(), None, ctx)?; + let variants = storage + .as_::() + .to_arrow(&ArrowExportOptions::default(), ctx)?; + + let len = variants.len(); + let step = len.div_ceil(self.max_sampled_rows).max(1); + let mut root = Node::default(); + let mut sampled = 0usize; + for idx in (0..len).step_by(step) { + if variants.is_valid(idx) { + sampled += 1; + root.observe(&variants.try_value(idx)?, 0, self.max_depth); + } + } + + let min_rows = (sampled * self.min_presence_percent).div_ceil(100).max(1); + let mut fields = Vec::new(); + root.collect(&mut Vec::new(), min_rows, &mut fields); + + // The fields in the most rows, and of those the ones that sort first. + fields.sort_by(|(left_path, left, _), (right_path, right, _)| { + right.cmp(left).then_with(|| left_path.cmp(right_path)) + }); + fields.truncate(self.max_fields); + if fields.is_empty() { + return Ok(None); + } + + let mut shredded = Shredded::default(); + for (path, _, kind) in fields { + shredded.insert(&path, kind); + } + Ok(Some(shredded.dtype())) + } +} + +/// The types of value that a field is shredded into. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Utf8, + Bool, + Integer, + Double, +} + +impl Kind { + const ALL: [Self; 4] = [Self::Utf8, Self::Bool, Self::Integer, Self::Double]; + + fn of(variant: &PqVariant<'_, '_>) -> Option { + Some(match variant { + PqVariant::String(_) | PqVariant::ShortString(_) => Self::Utf8, + PqVariant::BooleanTrue | PqVariant::BooleanFalse => Self::Bool, + PqVariant::Int8(_) + | PqVariant::Int16(_) + | PqVariant::Int32(_) + | PqVariant::Int64(_) => Self::Integer, + PqVariant::Double(_) => Self::Double, + _ => return None, + }) + } + + fn dtype(self) -> DType { + match self { + Self::Utf8 => DType::Utf8(Nullability::Nullable), + Self::Bool => DType::Bool(Nullability::Nullable), + Self::Integer => DType::Primitive(PType::I64, Nullability::Nullable), + Self::Double => DType::Primitive(PType::F64, Nullability::Nullable), + } + } +} + +/// The tree of the fields to shred, which becomes the schema. +#[derive(Default)] +struct Shredded { + /// The type of the values at this path, if it is a field to shred. + kind: Option, + /// The fields of the object at this path. + fields: BTreeMap, +} + +impl Shredded { + fn insert(&mut self, path: &[String], kind: Kind) { + match path.split_first() { + Some((name, rest)) => self + .fields + .entry(name.clone()) + .or_default() + .insert(rest, kind), + None => self.kind = Some(kind), + } + } + + /// A field is only shredded if no sampled row holds an object at it, so a path with fields + /// never has a type as well. + fn dtype(&self) -> DType { + if let Some(kind) = self.kind { + return kind.dtype(); + } + DType::Struct( + StructFields::from_iter( + self.fields + .iter() + .map(|(name, field)| (name.as_str(), field.dtype())), + ), + Nullability::Nullable, + ) + } +} + +/// What the sampled rows hold at one path. +#[derive(Default)] +struct Node { + /// How many rows hold a value of each [`Kind`], in the order of [`Kind::ALL`]. + kinds: [usize; Kind::ALL.len()], + /// How many rows hold a value of another type, objects included. + others: usize, + /// The fields of the objects at this path. + fields: BTreeMap, +} + +impl Node { + fn observe(&mut self, variant: &PqVariant<'_, '_>, depth: usize, max_depth: usize) { + match variant { + // A Variant null is in no typed column, and fits beside any. + PqVariant::Null => {} + PqVariant::Object(object) => { + self.others += 1; + if depth < max_depth { + for (name, field) in object.iter() { + self.fields.entry(name.to_owned()).or_default().observe( + &field, + depth + 1, + max_depth, + ); + } + } + } + other => match Kind::of(other) { + Some(kind) => self.kinds[kind as usize] += 1, + None => self.others += 1, + }, + } + } + + /// The type of the values at this path, if every row that has a value holds one of it. + fn kind(&self) -> Option<(Kind, usize)> { + if self.others != 0 { + return None; + } + let mut found = None; + for (kind, rows) in Kind::ALL.into_iter().zip(self.kinds) { + if rows > 0 { + if found.is_some() { + return None; + } + found = Some((kind, rows)); + } + } + found + } + + /// Appends the fields to shred under this path, each with the number of rows that have it + /// and the type of its values. + fn collect( + &self, + path: &mut Vec, + min_rows: usize, + fields: &mut Vec<(Vec, usize, Kind)>, + ) { + // The root is not a field. + if !path.is_empty() + && let Some((kind, rows)) = self.kind() + && rows >= min_rows + { + fields.push((path.clone(), rows, kind)); + } + + for (name, field) in &self.fields { + path.push(name.clone()); + field.collect(path, min_rows, fields); + path.pop(); + } + } +} diff --git a/encodings/parquet-variant/src/shred/mod.rs b/encodings/parquet-variant/src/shred/mod.rs new file mode 100644 index 00000000000..59794c6eb93 --- /dev/null +++ b/encodings/parquet-variant/src/shred/mod.rs @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Shreds unshredded Parquet Variant storage. +//! +//! A reader of an unshredded Variant decodes every value to extract one field of it. Shredding +//! the fields that the values have in common moves each into a typed column of its own, which a +//! reader extracts without touching the rest. +//! +//! Shredding never changes what a Variant holds: a row whose value does not fit the schema keeps +//! it in the residual binary value. A value fits a typed column only if it has the type of the +//! column, so the schema only has to fit most rows to be worth it, and [`InferredShredding`] +//! infers it from a sample. + +mod exact; +mod infer; +#[cfg(test)] +mod tests; +mod union; + +pub(crate) use exact::Mismatch; +pub use infer::InferredShredding; +pub(crate) use union::has_union; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::VariantArray; +use vortex_array::dtype::DType; +use vortex_error::VortexResult; +use vortex_error::vortex_err; + +use crate::ParquetVariant; +use crate::ParquetVariantArrayExt; +use crate::ParquetVariantArraySlotsExt; + +/// Shreds the unshredded storage `array` by `schema`. +/// +/// The result holds the same values as `array`, and is `nullable` or not. It is Parquet Variant +/// storage with a shredded child, unless `schema` holds a union, which Parquet storage cannot +/// hold. It is then the canonical Variant over that storage. +pub(crate) fn shred( + array: &ArrayView<'_, ParquetVariant>, + schema: &DType, + mismatch: Mismatch, + nullable: bool, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let value = array + .value() + .ok_or_else(|| vortex_err!("unshredded Parquet Variant storage has no value"))?; + + let len = array.len(); + let valid = &array.parquet_variant_validity().execute_mask(len, ctx)? + & &value.validity()?.execute_mask(len, ctx)?; + let metadata = array.metadata().clone().execute::(ctx)?; + let value = value.clone().execute::(ctx)?; + + let (value, typed_value) = + exact::shred(&metadata, &value, &valid, schema, mismatch, ctx.allocator())?; + + let validity = array.validity()?; + let validity = if nullable { + validity.into_nullable() + } else { + validity + }; + let storage = ParquetVariant::try_new( + validity, + array.metadata().clone(), + Some(value), + Some(typed_value), + )? + .into_array(); + if has_union(schema) { + return Ok(storage.execute::(ctx)?.into_array()); + } + Ok(storage) +} diff --git a/encodings/parquet-variant/src/shred/tests.rs b/encodings/parquet-variant/src/shred/tests.rs new file mode 100644 index 00000000000..21533cfc60c --- /dev/null +++ b/encodings/parquet-variant/src/shred/tests.rs @@ -0,0 +1,624 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::fmt::Write as _; +use std::sync::Arc; +use std::sync::LazyLock; + +use arrow_array::ArrayRef as ArrowArrayRef; +use arrow_array::StringArray; +use parquet_variant::Variant as PqVariant; +use parquet_variant_compute::json_to_variant; +use parquet_variant_compute::unshred_variant; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::VariantArray; +use vortex_array::arrays::struct_::StructArrayExt; +use vortex_array::arrays::variant::VariantArraySlotsExt; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; +use vortex_array::dtype::UnionVariants; +use vortex_array::expr::root; +use vortex_arrow::ArrowExportOptions; +use vortex_arrow::ArrowSessionExt; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_functions::expr::variant_get; +use vortex_functions::variant_get::VariantPath; +use vortex_functions::variant_shred::VariantShred; +use vortex_functions::variant_shred::VariantShredStrict; +use vortex_functions::variant_shred::VariantShredUnion; +use vortex_session::VortexSession; + +use super::InferredShredding; +use crate::ParquetVariant; +use crate::ParquetVariantArrayExt; +use crate::ParquetVariantArraySlotsExt; +use crate::arrow::prepare_variant_for_export; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +const ROWS: [&str; 4] = [ + r#"{"kind":"commit","time_us":1,"commit":{"collection":"post","rev":"a"},"tags":["x"]}"#, + r#"{"kind":"commit","time_us":2,"commit":{"collection":"like","rev":7}}"#, + r#"{"kind":"identity","time_us":3,"mixed":"text"}"#, + r#"{"kind":"account","time_us":"late","mixed":4}"#, +]; + +/// Values of every type in each field, so that each typed column takes some and not others. +const VALUES: [Option<&str>; 9] = [ + Some(r#"{"n":1,"s":"a","b":true,"d":0.5,"l":[1,"x",null],"o":{"n":1,"x":2}}"#), + Some(r#"{"n":1.5,"s":7,"b":1,"d":2,"l":"x","o":{"x":3}}"#), + Some(r#"{"n":true,"s":null,"b":"true","d":"0.5","l":[],"o":[1]}"#), + Some(r#"{"n":300,"s":"a long string that is not inlined","b":false,"o":{"n":"1"}}"#), + Some(r#"{"n":-9007199254740993,"l":[[1]],"o":{"n":2}}"#), + Some(r#"{"n":null,"x":{"n":1}}"#), + Some(r#"[{"n":1}]"#), + Some("1"), + None, +]; + +fn from_json<'a>(rows: impl IntoIterator>) -> VortexResult { + let json: ArrowArrayRef = Arc::new(StringArray::from_iter(rows)); + ParquetVariant::from_arrow_variant(&json_to_variant(&json)?, &SESSION.arrow()) +} + +fn variants() -> VortexResult { + from_json(ROWS.map(Some)) +} + +fn utf8() -> DType { + DType::Utf8(Nullability::Nullable) +} + +fn int(ptype: PType) -> DType { + DType::Primitive(ptype, Nullability::Nullable) +} + +fn boolean() -> DType { + DType::Bool(Nullability::Nullable) +} + +fn list(element: DType) -> DType { + DType::List(Arc::new(element), Nullability::Nullable) +} + +fn object(fields: &[(&str, DType)]) -> DType { + DType::Struct( + StructFields::from_iter(fields.iter().map(|(name, dtype)| (*name, dtype.clone()))), + Nullability::Nullable, + ) +} + +fn shred_into(array: ArrayRef, dtype: DType) -> VortexResult { + VariantShred::try_new(array, dtype)? + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) +} + +fn inferred(policy: &InferredShredding) -> VortexResult> { + policy.schema(&variants()?, &mut SESSION.create_execution_ctx()) +} + +fn shredded() -> VortexResult { + let dtype = + inferred(&InferredShredding::default())?.ok_or_else(|| vortex_err!("nothing to shred"))?; + shred_into(variants()?, dtype) +} + +/// The Parquet Variant storage of `array`. +fn storage(array: ArrayRef) -> VortexResult { + prepare_variant_for_export(array, None, &mut SESSION.create_execution_ctx()) +} + +/// The value of each row of `array`, unshredded by the Arrow Variant reader, with the integers +/// of all widths written alike. +fn values(array: ArrayRef) -> VortexResult>> { + let mut ctx = SESSION.create_execution_ctx(); + let variants = unshred_variant( + &storage(array)? + .as_::() + .to_arrow(&ArrowExportOptions::default(), &mut ctx)?, + )?; + (0..variants.len()) + .map(|idx| { + if !variants.is_valid(idx) { + return Ok(None); + } + let mut out = String::new(); + render(&variants.try_value(idx)?, &mut out); + Ok(Some(out)) + }) + .collect() +} + +#[expect( + clippy::use_debug, + reason = "the Debug of a Variant names its type and value" +)] +fn render(variant: &PqVariant<'_, '_>, out: &mut String) { + match variant { + PqVariant::Object(object) => { + out.push('{'); + for (name, field) in object.iter() { + let _ = write!(out, "{name:?}:"); + render(&field, out); + out.push(','); + } + out.push('}'); + } + PqVariant::List(list) => { + out.push('['); + for element in list.iter() { + render(&element, out); + out.push(','); + } + out.push(']'); + } + PqVariant::Int8(_) | PqVariant::Int16(_) | PqVariant::Int32(_) | PqVariant::Int64(_) => { + let _ = write!(out, "int {:?}", variant.as_int64()); + } + other => { + let _ = write!(out, "{other:?}"); + } + } +} + +/// The `typed_value` column of the shredded field `name` of `array`. +fn typed_field(array: ArrayRef, name: &str) -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); + let typed_value = storage(array)? + .as_::() + .typed_value() + .ok_or_else(|| vortex_err!("not shredded"))? + .clone() + .execute::(&mut ctx)?; + let field = typed_value + .unmasked_field_by_name(name)? + .clone() + .execute::(&mut ctx)?; + Ok(field.unmasked_field_by_name("typed_value")?.clone()) +} + +/// The names of the fields of the shredded child of `array`. +fn shredded_names(array: ArrayRef) -> VortexResult> { + let shredded = array + .execute::(&mut SESSION.create_execution_ctx())? + .shredded() + .ok_or_else(|| vortex_err!("not shredded"))? + .dtype() + .clone(); + let DType::Struct(fields, _) = shredded else { + return Err(vortex_err!("shredded as {shredded}")); + }; + Ok(fields.names().iter().map(|name| name.to_string()).collect()) +} + +fn get(array: ArrayRef, path: &[&str], dtype: DType) -> VortexResult { + let path = VariantPath::new(path.iter().map(|name| (*name).into())); + array + .apply(&variant_get(root(), path, Some(dtype)))? + .execute::(&mut SESSION.create_execution_ctx()) +} + +#[test] +fn infers_the_fields_of_one_type() -> VortexResult<()> { + // `time_us`, `mixed` and `commit.rev` hold two types, and `tags` holds a list. + assert_eq!( + inferred(&InferredShredding::default())?, + Some(object(&[ + ("commit", object(&[("collection", utf8())])), + ("kind", utf8()), + ])) + ); + Ok(()) +} + +#[test] +fn infers_each_type_of_value() -> VortexResult<()> { + let array = from_json([ + Some(r#"{"s":"a","b":true,"i":1,"d":0.5,"n":null}"#), + Some(r#"{"s":"b","b":false,"i":300,"d":1.5,"n":null}"#), + ])?; + let inferred = + InferredShredding::default().schema(&array, &mut SESSION.create_execution_ctx())?; + assert_eq!( + inferred, + Some(object(&[ + ("b", boolean()), + ("d", int(PType::F64)), + ("i", int(PType::I64)), + ("s", utf8()), + ])) + ); + Ok(()) +} + +#[test] +fn infers_the_fields_in_the_most_rows() -> VortexResult<()> { + let policy = InferredShredding::default().with_max_fields(1); + assert_eq!(inferred(&policy)?, Some(object(&[("kind", utf8())]))); + Ok(()) +} + +#[test] +fn infers_fields_that_enough_rows_have() -> VortexResult<()> { + // `commit.collection` is in two rows of four. + let policy = InferredShredding::default().with_min_presence_percent(75); + assert_eq!(inferred(&policy)?, Some(object(&[("kind", utf8())]))); + Ok(()) +} + +#[test] +fn infers_fields_no_deeper_than_the_depth() -> VortexResult<()> { + let policy = InferredShredding::default().with_max_depth(1); + assert_eq!(inferred(&policy)?, Some(object(&[("kind", utf8())]))); + Ok(()) +} + +#[test] +fn infers_nothing_from_values_without_common_fields() -> VortexResult<()> { + let array = from_json([Some("1"), Some("[1,2]"), Some("\"a\"")])?; + let inferred = + InferredShredding::default().schema(&array, &mut SESSION.create_execution_ctx())?; + assert!(inferred.is_none()); + Ok(()) +} + +#[test] +fn shreds_by_the_given_schema() -> VortexResult<()> { + let schema = object(&[("kind", utf8())]); + assert_eq!(shredded_names(shred_into(variants()?, schema)?)?, ["kind"]); + Ok(()) +} + +#[test] +fn shreds_by_the_inferred_schema() -> VortexResult<()> { + assert_eq!(shredded_names(shredded()?)?, ["commit", "kind"]); + Ok(()) +} + +#[rstest] +#[case::variant(DType::Variant(Nullability::Nullable))] +#[case::unsigned(int(PType::U8))] +#[case::decimal(DType::Decimal(DecimalDType::new(10, 2), Nullability::Nullable))] +#[case::nested(object(&[("o", list(DType::Variant(Nullability::Nullable)))]))] +fn rejects_leaves_of_other_types(#[case] leaf: DType) -> VortexResult<()> { + assert!(shred_into(variants()?, object(&[("time_us", leaf)])).is_err()); + Ok(()) +} + +#[test] +fn does_not_shred_a_shredded_variant() -> VortexResult<()> { + assert!(shred_into(shredded()?, object(&[("kind", utf8())])).is_err()); + Ok(()) +} + +#[rstest] +#[case::string(object(&[("s", utf8())]))] +#[case::binary(object(&[("s", DType::Binary(Nullability::Nullable))]))] +#[case::boolean(object(&[("b", boolean())]))] +#[case::int8(object(&[("n", int(PType::I8))]))] +#[case::int16(object(&[("n", int(PType::I16))]))] +#[case::int32(object(&[("n", int(PType::I32))]))] +#[case::int64(object(&[("n", int(PType::I64))]))] +#[case::float(object(&[("d", int(PType::F32))]))] +#[case::double(object(&[("d", int(PType::F64))]))] +#[case::nested(object(&[("o", object(&[("n", int(PType::I64))]))]))] +#[case::every_field(object(&[("o", object(&[("n", int(PType::I64)), ("x", int(PType::I64))]))]))] +#[case::list(object(&[("l", list(int(PType::I64)))]))] +#[case::nested_list(object(&[("l", list(list(int(PType::I64))))]))] +#[case::list_of_objects(list(object(&[("n", int(PType::I64))])))] +#[case::root(int(PType::I64))] +#[case::all(object(&[ + ("b", boolean()), + ("d", int(PType::F64)), + ("l", list(utf8())), + ("n", int(PType::I64)), + ("o", object(&[("n", utf8())])), + ("s", utf8()), +]))] +fn shredding_keeps_every_value(#[case] schema: DType) -> VortexResult<()> { + let array = from_json(VALUES)?; + assert_eq!(values(shred_into(array.clone(), schema)?)?, values(array)?); + Ok(()) +} + +#[test] +fn shreds_the_values_of_the_column_type() -> VortexResult<()> { + // 1.5, true and a Variant null are not integers, and stay in the residual value. + let shredded = shred_into(from_json(VALUES)?, object(&[("n", int(PType::I64))]))?; + assert_arrays_eq!( + typed_field(shredded, "n")?, + PrimitiveArray::from_option_iter([ + Some(1i64), + None, + None, + Some(300), + Some(-9007199254740993), + None, + None, + None, + None, + ]), + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} + +#[test] +fn shreds_the_integers_that_fit_the_column() -> VortexResult<()> { + let shredded = shred_into(from_json(VALUES)?, object(&[("n", int(PType::I8))]))?; + assert_arrays_eq!( + typed_field(shredded, "n")?, + PrimitiveArray::from_option_iter([ + Some(1i8), + None, + None, + None, + None, + None, + None, + None, + None + ]), + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} + +#[test] +fn shreds_booleans_alone() -> VortexResult<()> { + let shredded = shred_into(from_json(VALUES)?, object(&[("b", boolean())]))?; + assert_arrays_eq!( + typed_field(shredded, "b")?, + BoolArray::from_iter([ + Some(true), + None, + None, + Some(false), + None, + None, + None, + None, + None + ]), + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} + +#[test] +fn shreds_objects_with_many_fields_and_names() -> VortexResult<()> { + // More than 255 fields, whose ids are two bytes wide. + let fields = (0..300) + .map(|idx| format!(r#""f{idx:03}":{idx}"#)) + .collect::>() + .join(","); + let row = format!("{{{fields}}}"); + let array = from_json([Some(row.as_str()), Some(r#"{"f150":"x"}"#)])?; + + let schema = object(&[("f000", int(PType::I64)), ("f299", int(PType::I64))]); + assert_eq!(values(shred_into(array.clone(), schema)?)?, values(array)?); + Ok(()) +} + +#[rstest] +#[case::shredded(&["kind"])] +#[case::nested(&["commit", "collection"])] +#[case::residual(&["mixed"])] +#[case::residual_nested(&["commit", "rev"])] +#[case::missing(&["nope"])] +fn shredding_keeps_the_strings(#[case] path: &[&str]) -> VortexResult<()> { + let expected = get(variants()?, path, utf8())? + .execute::(&mut SESSION.create_execution_ctx())?; + assert_arrays_eq!( + get(shredded()?, path, utf8())?, + expected, + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} + +#[rstest] +#[case::residual(&["time_us"])] +#[case::residual_nested(&["commit", "rev"])] +fn shredding_keeps_the_integers(#[case] path: &[&str]) -> VortexResult<()> { + let int64 = int(PType::I64); + let expected = get(variants()?, path, int64.clone())? + .execute::(&mut SESSION.create_execution_ctx())?; + assert_arrays_eq!( + get(shredded()?, path, int64)?, + expected, + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} + +fn shred_strictly(array: ArrayRef, dtype: DType) -> VortexResult { + VariantShredStrict::try_new(array, dtype)? + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) +} + +/// A strict shredding fails on a value that does not fit the schema, and says where it is. +#[rstest] +// `commit.rev` of the first row is a string. +#[case::leaf(ROWS.map(Some).to_vec(), object(&[("commit", object(&[("rev", int(PType::I64))]))]), "row 0 at `$.commit.rev`")] +#[case::object(vec![Some(r#"{"commit":{"rev":1}}"#), Some(r#"{"commit":5}"#)], object(&[("commit", object(&[("rev", int(PType::I64))]))]), "row 1 at `$.commit`")] +#[case::list(vec![Some(r#"{"tags":["x"]}"#), Some(r#"{"tags":"x"}"#)], object(&[("tags", list(utf8()))]), "row 1 at `$.tags`")] +#[case::element(vec![Some(r#"{"tags":["x",1]}"#)], object(&[("tags", list(utf8()))]), "row 0 at `$.tags[]`")] +fn strict_shredding_rejects_a_value_that_does_not_fit( + #[case] rows: Vec>, + #[case] schema: DType, + #[case] reason: &str, +) -> VortexResult<()> { + let Err(error) = shred_strictly(from_json(rows)?, schema) else { + return Err(vortex_err!("a value that does not fit was shredded")); + }; + assert!(error.to_string().contains(reason), "{error}"); + Ok(()) +} + +/// A strict shredding of values that fit the schema keeps every value, and stores none of the +/// shredded paths in the residual. A Variant null fits, as a missing value. +#[test] +fn strict_shredding_keeps_values_that_fit() -> VortexResult<()> { + let array = from_json([ + Some(r#"{"kind":"commit","commit":{"collection":"post","rev":"a"}}"#), + Some(r#"{"kind":"identity","n":null}"#), + Some(r#"{"kind":null,"commit":{"collection":"like"}}"#), + None, + ])?; + let schema = object(&[ + ("commit", object(&[("collection", utf8())])), + ("kind", utf8()), + ]); + let shredded = shred_strictly(array.clone(), schema)?; + + for path in [&["kind"][..], &["commit", "collection"], &["commit", "rev"]] { + let expected = get(array.clone(), path, utf8())? + .execute::(&mut SESSION.create_execution_ctx())?; + assert_arrays_eq!( + get(shredded.clone(), path, utf8())?, + expected, + &mut SESSION.create_execution_ctx() + ); + } + + // No value of `kind` is left in its residual. + let kind = storage(shredded)? + .as_::() + .typed_value() + .ok_or_else(|| vortex_err!("not shredded"))? + .clone() + .execute::(&mut SESSION.create_execution_ctx())? + .unmasked_field_by_name("kind")? + .clone() + .execute::(&mut SESSION.create_execution_ctx())?; + let residual = kind.unmasked_field_by_name("value")?.clone(); + assert!( + residual + .validity()? + .execute_mask(residual.len(), &mut SESSION.create_execution_ctx())? + .all_false() + ); + Ok(()) +} + +fn union(members: &[(&str, DType)]) -> DType { + let variants = UnionVariants::new( + FieldNames::from_iter(members.iter().map(|(name, _)| *name)), + members.iter().map(|(_, dtype)| dtype.clone()).collect(), + ) + .vortex_expect("distinct member names"); + DType::Union(variants, Nullability::Nullable) +} + +fn shred_into_union(array: ArrayRef, dtype: DType) -> VortexResult { + VariantShredUnion::try_new(array, dtype)? + .into_array() + .execute::(&mut SESSION.create_execution_ctx()) +} + +/// A union shredding keeps every value, whether a member holds it or the residual does, and the +/// export folds the union back into Variant bytes. +#[rstest] +#[case::leaves(object(&[("n", union(&[("int", int(PType::I64)), ("str", utf8())]))]))] +#[case::narrow_first(object(&[("n", union(&[("small", int(PType::I8)), ("big", int(PType::I64))]))]))] +#[case::struct_member(object(&[( + "o", + union(&[ + ("object", object(&[("n", int(PType::I64)), ("x", int(PType::I64))])), + ("list", list(int(PType::I64))), + ]), +)]))] +#[case::list_member(object(&[("l", union(&[("list", list(union(&[("int", int(PType::I64)), ("str", utf8())])))]))]))] +#[case::in_a_list(object(&[("l", list(union(&[("int", int(PType::I64)), ("str", utf8())])))]))] +#[case::root(union(&[ + ("object", object(&[("n", int(PType::I64)), ("x", object(&[("n", int(PType::I64))]))])), + ("int", int(PType::I64)), +]))] +#[case::nested(object(&[("o", union(&[("object", object(&[("n", union(&[("int", int(PType::I64)), ("str", utf8())]))]))]))]))] +fn union_shredding_keeps_every_value(#[case] schema: DType) -> VortexResult<()> { + let array = from_json(VALUES)?; + assert_eq!( + values(shred_into_union(array.clone(), schema)?)?, + values(array)? + ); + Ok(()) +} + +/// A value goes to the member of its type, and a value of no member stays in the residual. +#[test] +fn union_shredding_moves_values_into_members() -> VortexResult<()> { + let array = from_json([ + Some(r#"{"n":1}"#), + Some(r#"{"n":"x"}"#), + Some(r#"{"n":true}"#), + Some(r#"{"m":1}"#), + ])?; + let schema = object(&[("n", union(&[("int", int(PType::I64)), ("str", utf8())]))]); + let shredded = shred_into_union(array, schema)?; + + // `n` keeps the values that fit no member, so it canonicalizes to a nested Variant whose own + // shredded child is the union. + let mut ctx = SESSION.create_execution_ctx(); + let variant = shredded.clone().execute::(&mut ctx)?; + let fields = variant + .shredded() + .ok_or_else(|| vortex_err!("not shredded"))? + .clone() + .execute::(&mut ctx)?; + let n = fields + .unmasked_field_by_name("n")? + .clone() + .execute::(&mut ctx)?; + let n_dtype = n + .shredded() + .ok_or_else(|| vortex_err!("n is not shredded"))? + .dtype(); + assert!(n_dtype.is_union(), "{n_dtype}"); + + assert_arrays_eq!( + get(shredded.clone(), &["n"], int(PType::I64))?, + PrimitiveArray::from_option_iter([Some(1i64), None, Some(1), None]), + &mut ctx + ); + assert_arrays_eq!( + get(shredded.clone(), &["n"], utf8())?, + VarBinViewArray::from_iter_nullable_str([None, Some("x"), None, None]), + &mut ctx + ); + assert_arrays_eq!( + get(shredded, &["n"], boolean())?, + BoolArray::from_iter([Some(true), None, Some(true), None]), + &mut ctx + ); + Ok(()) +} + +/// A Parquet shredding writes Parquet storage, which has no union. +#[test] +fn parquet_shredding_rejects_a_union() -> VortexResult<()> { + let schema = object(&[("n", union(&[("int", int(PType::I64)), ("str", utf8())]))]); + assert!(shred_into(from_json(VALUES)?, schema.clone()).is_err()); + assert!(shred_strictly(from_json(VALUES)?, schema).is_err()); + Ok(()) +} diff --git a/encodings/parquet-variant/src/shred/union.rs b/encodings/parquet-variant/src/shred/union.rs new file mode 100644 index 00000000000..fa1573d2eee --- /dev/null +++ b/encodings/parquet-variant/src/shred/union.rs @@ -0,0 +1,475 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Shreds values into the members of a union. +//! +//! A union node of the schema takes a value whole, or not at all: the value goes to the first +//! member that holds all of it, and the residual of the node keeps a value that no member holds. +//! So a member has no residual of its own, and its typed tree is the value. +//! +//! A leaf member holds a value of its type, with the integer widths as one class, as a typed +//! column of the shredder does. A struct member holds an object if it names each field of the +//! object and holds the value of each. A list member holds an array if it holds each element. +//! A Variant null fits no member. + +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::UnionArray; +use vortex_array::builders::ArrayBuilder; +use vortex_array::builders::VarBinViewBuilder; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldName; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; +use vortex_array::dtype::UnionVariants; +use vortex_array::validity::Validity; +use vortex_buffer::BitBufferMut; +use vortex_buffer::BufferAllocatorRef; +use vortex_buffer::BufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; + +use super::exact::Fail; +use super::exact::Leaf; +use super::exact::OrMalformed; +use super::exact::binary; +use super::exact::binary_builder; +use super::exact::boolean; +use super::exact::double; +use super::exact::float; +use super::exact::integer; +use super::exact::string; +use crate::extract::Elements; +use crate::extract::Fields; +use crate::extract::Object; + +/// Whether `schema` is or holds a union. +pub(crate) fn has_union(schema: &DType) -> bool { + match schema { + DType::Union(..) => true, + DType::Struct(fields, _) => fields.fields().any(|field| has_union(&field)), + DType::List(element, _) => has_union(element), + _ => false, + } +} + +/// The dtype of the shredded column of a node of `schema` in a union. +/// +/// It is a function of the schema alone, so that every chunk of a stream has the same dtype. A +/// member is null in the rows of the other members, and a struct field is null where the object +/// does not have it, so each node is nullable. +fn member_dtype(schema: &DType) -> VortexResult { + Ok(match schema { + DType::Struct(fields, _) => DType::Struct( + StructFields::new( + fields.names().clone(), + fields + .fields() + .map(|field| member_dtype(&field)) + .collect::>>()?, + ), + Nullability::Nullable, + ), + DType::List(element, _) => { + DType::List(member_dtype(element)?.into(), Nullability::Nullable) + } + DType::Union(variants, _) => { + DType::Union(member_variants(variants)?, Nullability::Nullable) + } + leaf => leaf.as_nullable(), + }) +} + +/// The variants of the shredded column of a union of `variants`. +fn member_variants(variants: &UnionVariants) -> VortexResult { + let dtypes = variants + .variants() + .map(|variant| member_dtype(&variant)) + .collect::>>()?; + UnionVariants::try_new( + variants.names().clone(), + dtypes, + variants.type_ids().to_vec(), + ) +} + +/// The values of one node of a union, each of which the node holds whole. +enum Member { + Utf8(VarBinViewBuilder), + Binary(VarBinViewBuilder), + Bool(Leaf), + I8(Leaf), + I16(Leaf), + I32(Leaf), + I64(Leaf), + F32(Leaf), + F64(Leaf), + Object(Box), + List(Box), + Union(Box), +} + +/// A struct member. Each field holds the field of the object of the same name. +struct ObjectMember { + dtype: DType, + /// The member of each field, with the index of its name in the [`FieldCache`]. + /// + /// [`FieldCache`]: crate::extract::FieldCache + fields: Vec<(usize, Member)>, + validity: BitBufferMut, +} + +/// A list member. Each element is held by the same member. +struct ListMember { + offsets: BufferMut, + elements: Member, + validity: BitBufferMut, +} + +/// A union. Each value goes to the first member that holds it. +pub(super) struct UnionMember { + variants: UnionVariants, + type_ids: BufferMut, + validity: BitBufferMut, + members: Vec, +} + +impl Member { + /// A member of `schema`, which adds the field names of the structs in `schema` to `names`. + /// The strings and binaries are allocated by `allocator`. + fn new( + schema: &DType, + names: &mut Vec, + capacity: usize, + allocator: &BufferAllocatorRef, + ) -> VortexResult { + Ok(match schema { + DType::Utf8(_) => Self::Utf8(VarBinViewBuilder::with_capacity_in( + DType::Utf8(Nullability::Nullable), + capacity, + allocator.clone(), + )), + DType::Binary(_) => Self::Binary(binary_builder(capacity, allocator)), + DType::Bool(_) => Self::Bool(Leaf::new(capacity)), + DType::Primitive(PType::I8, _) => Self::I8(Leaf::new(capacity)), + DType::Primitive(PType::I16, _) => Self::I16(Leaf::new(capacity)), + DType::Primitive(PType::I32, _) => Self::I32(Leaf::new(capacity)), + DType::Primitive(PType::I64, _) => Self::I64(Leaf::new(capacity)), + DType::Primitive(PType::F32, _) => Self::F32(Leaf::new(capacity)), + DType::Primitive(PType::F64, _) => Self::F64(Leaf::new(capacity)), + DType::Struct(struct_fields, _) => { + let mut fields = Vec::with_capacity(struct_fields.nfields()); + for (name, field) in struct_fields.names().iter().zip(struct_fields.fields()) { + names.push(name.clone()); + let name = names.len() - 1; + fields.push((name, Self::new(&field, names, capacity, allocator)?)); + } + Self::Object(Box::new(ObjectMember { + dtype: member_dtype(schema)?, + fields, + validity: BitBufferMut::with_capacity(capacity), + })) + } + DType::List(element, _) => { + let mut offsets = BufferMut::with_capacity(capacity + 1); + offsets.push(0); + Self::List(Box::new(ListMember { + offsets, + elements: Self::new(element, names, capacity, allocator)?, + validity: BitBufferMut::with_capacity(capacity), + })) + } + DType::Union(..) => Self::Union(Box::new(UnionMember::new( + schema, names, capacity, allocator, + )?)), + _ => vortex_bail!( + "a Variant can only be shredded into strings, binaries, booleans, signed integers, \ + floats, structs, lists and unions, not {schema}" + ), + }) + } + + /// Whether this member holds all of `value`, the bytes of a value followed by any other + /// bytes. + fn fits(&self, fields: &Fields<'_>, value: &[u8]) -> Result { + Ok(match self { + Self::Utf8(_) => string(value).is_some(), + Self::Binary(_) => binary(value).is_some(), + Self::Bool(_) => boolean(value).is_some(), + Self::I8(_) => integer(value).is_some_and(|v| i8::try_from(v).is_ok()), + Self::I16(_) => integer(value).is_some_and(|v| i16::try_from(v).is_ok()), + Self::I32(_) => integer(value).is_some_and(|v| i32::try_from(v).is_ok()), + Self::I64(_) => integer(value).is_some(), + Self::F32(_) => float(value).is_some(), + Self::F64(_) => double(value).is_some(), + Self::Object(object) => object.fits(fields, value)?, + Self::List(list) => list.fits(fields, value)?, + Self::Union(union) => union.member(fields, value)?.is_some(), + }) + } + + /// Appends `value`, which this member [fits](Self::fits). + fn append(&mut self, fields: &Fields<'_>, value: &[u8]) -> Result<(), Fail> { + match self { + Self::Utf8(builder) => builder.append_value(string(value).or_malformed()?), + Self::Binary(builder) => builder.append_value(binary(value).or_malformed()?), + Self::Bool(leaf) => leaf.push(Some(boolean(value).or_malformed()?)), + Self::I8(leaf) => leaf.push(Some(narrow(value)?)), + Self::I16(leaf) => leaf.push(Some(narrow(value)?)), + Self::I32(leaf) => leaf.push(Some(narrow(value)?)), + Self::I64(leaf) => leaf.push(Some(integer(value).or_malformed()?)), + Self::F32(leaf) => leaf.push(Some(float(value).or_malformed()?)), + Self::F64(leaf) => leaf.push(Some(double(value).or_malformed()?)), + Self::Object(object) => object.append(fields, value)?, + Self::List(list) => list.append(fields, value)?, + Self::Union(union) => union.append(fields, value)?, + } + Ok(()) + } + + /// Appends a row that this member does not hold. + fn append_null(&mut self) { + match self { + Self::Utf8(builder) | Self::Binary(builder) => builder.append_null(), + Self::Bool(leaf) => leaf.push(None), + Self::I8(leaf) => leaf.push(None), + Self::I16(leaf) => leaf.push(None), + Self::I32(leaf) => leaf.push(None), + Self::I64(leaf) => leaf.push(None), + Self::F32(leaf) => leaf.push(None), + Self::F64(leaf) => leaf.push(None), + Self::Object(object) => object.append_null(), + Self::List(list) => list.append_null(), + Self::Union(union) => union.append_null(), + } + } + + fn finish(self) -> VortexResult { + Ok(match self { + Self::Utf8(mut builder) | Self::Binary(mut builder) => { + builder.finish_into_varbinview().into_array() + } + Self::Bool(leaf) => leaf.finish_bool(), + Self::I8(leaf) => leaf.finish(), + Self::I16(leaf) => leaf.finish(), + Self::I32(leaf) => leaf.finish(), + Self::I64(leaf) => leaf.finish(), + Self::F32(leaf) => leaf.finish(), + Self::F64(leaf) => leaf.finish(), + Self::Object(object) => object.finish()?, + Self::List(list) => list.finish()?, + Self::Union(union) => union.finish()?, + }) + } +} + +/// The integer that `value` holds, narrowed to `T`. +fn narrow>(value: &[u8]) -> Result { + integer(value) + .and_then(|value| T::try_from(value).ok()) + .or_malformed() +} + +impl ObjectMember { + fn fits(&self, fields: &Fields<'_>, value: &[u8]) -> Result { + let Some(object) = Object::new(value).or_malformed()? else { + return Ok(false); + }; + + let mut held = 0; + for (name, field) in &self.fields { + if let Some(position) = fields.position(&object, *name).or_malformed()? { + if !field.fits(fields, object.value(position).or_malformed()?)? { + return Ok(false); + } + held += 1; + } + } + Ok(held == object.len()) + } + + fn append(&mut self, fields: &Fields<'_>, value: &[u8]) -> Result<(), Fail> { + let object = Object::new(value).or_malformed()?.or_malformed()?; + for (name, field) in &mut self.fields { + match fields.position(&object, *name).or_malformed()? { + Some(position) => field.append(fields, object.value(position).or_malformed()?)?, + None => field.append_null(), + } + } + self.validity.append(true); + Ok(()) + } + + fn append_null(&mut self) { + for (_, field) in &mut self.fields { + field.append_null(); + } + self.validity.append(false); + } + + fn finish(self) -> VortexResult { + let DType::Struct(struct_fields, _) = self.dtype else { + vortex_bail!("a struct member has dtype {}", self.dtype); + }; + let len = self.validity.len(); + let fields = self + .fields + .into_iter() + .map(|(_, field)| field.finish()) + .collect::>>()?; + Ok(StructArray::try_new( + struct_fields.names().clone(), + fields, + len, + Validity::from(self.validity.freeze()), + )? + .into_array()) + } +} + +impl ListMember { + fn fits(&self, fields: &Fields<'_>, value: &[u8]) -> Result { + let Some(list) = Elements::new(value).or_malformed()? else { + return Ok(false); + }; + + for idx in 0..list.len() { + if !self + .elements + .fits(fields, list.element(idx).or_malformed()?)? + { + return Ok(false); + } + } + Ok(true) + } + + fn append(&mut self, fields: &Fields<'_>, value: &[u8]) -> Result<(), Fail> { + let list = Elements::new(value).or_malformed()?.or_malformed()?; + for idx in 0..list.len() { + self.elements + .append(fields, list.element(idx).or_malformed()?)?; + } + + let end = self.offsets.last().copied().unwrap_or_default(); + self.offsets + .push(end + u64::try_from(list.len()).ok().or_malformed()?); + self.validity.append(true); + Ok(()) + } + + fn append_null(&mut self) { + let end = self.offsets.last().copied().unwrap_or_default(); + self.offsets.push(end); + self.validity.append(false); + } + + fn finish(self) -> VortexResult { + let elements = self.elements.finish()?; + let offsets = PrimitiveArray::new(self.offsets.freeze(), Validity::NonNullable); + // SAFETY: the offsets start at zero and grow by the number of elements each list + // appended, so they end at the number of elements, and there is one more offset than + // there are validity bits. + Ok(unsafe { + ListArray::new_unchecked( + elements, + offsets.into_array(), + Validity::from(self.validity.freeze()), + ) + } + .into_array()) + } +} + +impl UnionMember { + /// A union of `schema`, which adds the field names of the structs in `schema` to `names`. + pub(super) fn new( + schema: &DType, + names: &mut Vec, + capacity: usize, + allocator: &BufferAllocatorRef, + ) -> VortexResult { + let DType::Union(variants, _) = schema else { + vortex_bail!("a union member has schema {schema}"); + }; + + let members = variants + .variants() + .map(|variant| Member::new(&variant, names, capacity, allocator)) + .collect::>>()?; + Ok(Self { + variants: member_variants(variants)?, + type_ids: BufferMut::with_capacity(capacity), + validity: BitBufferMut::with_capacity(capacity), + members, + }) + } + + /// The index of the first member that holds all of `value`. + fn member(&self, fields: &Fields<'_>, value: &[u8]) -> Result, Fail> { + for (idx, member) in self.members.iter().enumerate() { + if member.fits(fields, value)? { + return Ok(Some(idx)); + } + } + Ok(None) + } + + /// Appends `value` to the first member that holds all of it, and returns whether there was + /// one. If there was none, nothing is appended. + pub(super) fn append_fitting( + &mut self, + fields: &Fields<'_>, + value: &[u8], + ) -> Result { + let Some(held_by) = self.member(fields, value)? else { + return Ok(false); + }; + + for (idx, member) in self.members.iter_mut().enumerate() { + if idx == held_by { + member.append(fields, value)?; + } else { + member.append_null(); + } + } + let type_id = self.variants.type_ids().get(held_by).or_malformed()?; + self.type_ids.push(*type_id); + self.validity.append(true); + Ok(true) + } + + fn append(&mut self, fields: &Fields<'_>, value: &[u8]) -> Result<(), Fail> { + if self.append_fitting(fields, value)? { + Ok(()) + } else { + Err(Fail::Malformed) + } + } + + pub(super) fn append_null(&mut self) { + for member in &mut self.members { + member.append_null(); + } + self.type_ids.push(0); + self.validity.append(false); + } + + pub(super) fn finish(self) -> VortexResult { + let type_ids = PrimitiveArray::new( + self.type_ids.freeze(), + Validity::from(self.validity.freeze()), + ) + .into_array(); + let members = self + .members + .into_iter() + .map(Member::finish) + .collect::>>()?; + Ok(UnionArray::try_new(type_ids, self.variants, members)?.into_array()) + } +} diff --git a/encodings/parquet-variant/src/vtable/mod.rs b/encodings/parquet-variant/src/vtable/mod.rs index 59bb7f8a7b4..05a0c166531 100644 --- a/encodings/parquet-variant/src/vtable/mod.rs +++ b/encodings/parquet-variant/src/vtable/mod.rs @@ -223,11 +223,15 @@ mod tests { use arrow_array::ArrayRef as ArrowArrayRef; use arrow_array::Int32Array; + use arrow_array::StringArray; use arrow_array::StructArray; use arrow_array::builder::BinaryViewBuilder; use arrow_schema::DataType; use arrow_schema::Field; + use parquet_variant_compute::ShreddedSchemaBuilder; use parquet_variant_compute::VariantArray as ArrowVariantArray; + use parquet_variant_compute::json_to_variant; + use parquet_variant_compute::shred_variant; use rstest::fixture; use rstest::rstest; use vortex_array::ArrayContext; @@ -243,9 +247,13 @@ mod tests { use vortex_array::arrays::variant::VariantArraySlotsExt; use vortex_array::assert_arrays_eq; use vortex_array::dtype::DType; + use vortex_array::dtype::FieldNames; + use vortex_array::dtype::FieldPath; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; + use vortex_array::dtype::UnionVariants; use vortex_array::dtype::session::DTypeSessionExt; + use vortex_array::expr::root; use vortex_array::serde::SerializeOptions; use vortex_array::serde::SerializedArray; use vortex_array::session::ArraySessionExt; @@ -264,13 +272,22 @@ mod tests { use vortex_error::vortex_err; use vortex_file::OpenOptionsSessionExt; use vortex_file::WriteOptionsSessionExt; + use vortex_functions::expr::variant_get; + use vortex_functions::variant_get::VariantPath; + use vortex_functions::variant_get::VariantPathElement; use vortex_io::session::RuntimeSession; + use vortex_layout::LayoutRef; use vortex_layout::layouts::flat::writer::FlatLayoutStrategy; + use vortex_layout::layouts::struct_::Struct as StructLayoutEncoding; + use vortex_layout::layouts::variant::NoShredding; + use vortex_layout::layouts::variant::UnionShredding; + use vortex_layout::layouts::variant::VariantShreddingPolicy; use vortex_layout::session::LayoutSession; use vortex_layout::session::LayoutSessionExt; use vortex_session::VortexSession; use vortex_session::registry::ReadContext; + use crate::InferredShredding; use crate::ParquetVariant; use crate::array::ParquetVariantArraySlotsExt; @@ -453,6 +470,309 @@ mod tests { Ok(()) } + const WRITER_ROWS: [&str; 3] = [ + r#"{"kind":"commit","n":1,"commit":{"collection":"post"},"mixed":1}"#, + r#"{"kind":"identity","n":2,"mixed":"two"}"#, + r#"{"kind":"commit","n":3,"commit":{"collection":"like"}}"#, + ]; + + fn writer_rows(session: &VortexSession) -> VortexResult { + let json: ArrowArrayRef = Arc::new(StringArray::from(WRITER_ROWS.to_vec())); + ParquetVariant::from_arrow_variant(&json_to_variant(&json)?, &session.arrow()) + } + + /// Whether `layout` stores a shredded Variant, as a struct layout of a Variant. + fn is_variant_layout(layout: &LayoutRef) -> bool { + layout.is::() && layout.dtype().is_variant() + } + + /// The number of Variant layouts in the tree under `layout`. + fn variant_layouts(layout: &LayoutRef) -> VortexResult { + let own = usize::from(is_variant_layout(layout)); + layout + .children()? + .iter() + .try_fold(own, |count, child| Ok(count + variant_layouts(child)?)) + } + + /// A writer with a shredding policy writes an unshredded Variant with the Variant layout + /// too, and a scan extracts what the unshredded Variant holds. + #[rstest] + #[tokio::test] + async fn test_file_roundtrip_variant_shredded_by_the_writer( + parquet_variant_file_session: VortexResult, + ) -> VortexResult<()> { + let session = parquet_variant_file_session?; + crate::initialize(&session); + let unshredded = writer_rows(&session)?; + + let mut bytes = ByteBufferMut::empty(); + session + .write_options() + .with_strategy( + vortex_file::WriteStrategyBuilder::from_session(&session) + .with_variant_shredding(Arc::new(InferredShredding::default())) + .build(), + ) + .write(&mut bytes, unshredded.to_array_stream()) + .await?; + let file = session.open_options().open_buffer(bytes)?; + assert!(is_variant_layout(file.footer().layout())); + + let utf8 = DType::Utf8(Nullability::Nullable); + let i64 = DType::Primitive(PType::I64, Nullability::Nullable); + let mut ctx = session.create_execution_ctx(); + for (path, dtype) in [ + (VariantPath::field("kind"), utf8.clone()), + ( + VariantPath::new([ + VariantPathElement::field("commit"), + VariantPathElement::field("collection"), + ]), + utf8.clone(), + ), + (VariantPath::field("n"), i64.clone()), + // A field of two types is not shredded, and stays in the core storage. + (VariantPath::field("mixed"), utf8), + (VariantPath::field("mixed"), i64), + ] { + let extraction = variant_get(root(), path, Some(dtype)); + let expected = unshredded + .clone() + .apply(&extraction)? + .execute::(&mut ctx)?; + let scanned = file + .scan()? + .with_projection(extraction.bind(file.dtype())?) + .into_array_stream()? + .read_all() + .await?; + assert_arrays_eq!(scanned, expected, &mut ctx); + } + Ok(()) + } + + /// A union shredding writes each member of a union, and a scan extracts the values of each + /// type from the file. + #[rstest] + #[tokio::test] + async fn test_file_roundtrip_variant_shredded_into_a_union( + parquet_variant_file_session: VortexResult, + ) -> VortexResult<()> { + let session = parquet_variant_file_session?; + crate::initialize(&session); + let unshredded = writer_rows(&session)?; + + let utf8 = DType::Utf8(Nullability::Nullable); + let i64 = DType::Primitive(PType::I64, Nullability::Nullable); + let mixed = DType::Union( + UnionVariants::new(["int", "str"].into(), vec![i64.clone(), utf8.clone()])?, + Nullability::Nullable, + ); + let schema = DType::struct_( + [("kind", utf8.clone()), ("mixed", mixed)], + Nullability::Nullable, + ); + + let mut bytes = ByteBufferMut::empty(); + session + .write_options() + .with_strategy( + vortex_file::WriteStrategyBuilder::from_session(&session) + .with_variant_shredding(Arc::new(UnionShredding::new(schema))) + .build(), + ) + .write(&mut bytes, unshredded.to_array_stream()) + .await?; + let file = session.open_options().open_buffer(bytes)?; + assert!(is_variant_layout(file.footer().layout())); + + let mut ctx = session.create_execution_ctx(); + let actual = file.scan()?.into_array_stream()?.read_all().await?; + // The export folds the union back into the Variant bytes of each row. + let exported = crate::arrow::prepare_variant_for_export(actual.clone(), None, &mut ctx)?; + for (path, dtype) in [ + (VariantPath::field("kind"), utf8.clone()), + (VariantPath::field("mixed"), utf8.clone()), + (VariantPath::field("mixed"), i64.clone()), + (VariantPath::field("n"), i64), + ] { + let extraction = variant_get(root(), path, Some(dtype)); + let expected = unshredded + .clone() + .apply(&extraction)? + .execute::(&mut ctx)?; + + assert_arrays_eq!( + actual + .clone() + .apply(&extraction)? + .execute::(&mut ctx)?, + expected, + &mut ctx + ); + assert_arrays_eq!( + exported + .clone() + .apply(&extraction)? + .execute::(&mut ctx)?, + expected, + &mut ctx + ); + let scanned = file + .scan()? + .with_projection(extraction.bind(file.dtype())?) + .into_array_stream()? + .read_all() + .await?; + assert_arrays_eq!(scanned, expected, &mut ctx); + } + Ok(()) + } + + /// A policy for one field overrides the default policy for that field alone. + #[rstest] + #[case::default_for_both(None, None, 2)] + #[case::override_one(None, Some(Arc::new(NoShredding) as Arc), 1)] + #[case::only_one( + Some(Arc::new(NoShredding) as Arc), + Some(Arc::new(InferredShredding::default()) as Arc), + 1 + )] + #[case::neither(Some(Arc::new(NoShredding) as Arc), None, 0)] + #[tokio::test] + async fn test_file_variant_shredding_for_each_field( + parquet_variant_file_session: VortexResult, + #[case] default: Option>, + #[case] for_b: Option>, + #[case] shredded_fields: usize, + ) -> VortexResult<()> { + let session = parquet_variant_file_session?; + crate::initialize(&session); + let unshredded = writer_rows(&session)?; + let table = vortex_array::arrays::StructArray::try_new( + FieldNames::from(["a", "b"]), + vec![unshredded.clone(), unshredded.clone()], + unshredded.len(), + Validity::NonNullable, + )? + .into_array(); + + let shredded_layouts = async |default: Option>, + for_b: Option>| + -> VortexResult { + let mut strategy = vortex_file::WriteStrategyBuilder::from_session(&session) + .with_variant_shredding( + default.unwrap_or_else(|| Arc::new(InferredShredding::default())), + ); + if let Some(for_b) = for_b { + strategy = strategy.with_variant_shredding_at(FieldPath::from_name("b"), for_b); + } + let mut bytes = ByteBufferMut::empty(); + session + .write_options() + .with_strategy(strategy.build()) + .write(&mut bytes, table.clone().to_array_stream()) + .await?; + let file = session.open_options().open_buffer(bytes)?; + variant_layouts(file.footer().layout()) + }; + + // A shredded field can have more than one Variant layout, for the objects in it. + let per_field = shredded_layouts(None, Some(Arc::new(NoShredding))).await?; + assert!(per_field > 0); + assert_eq!( + shredded_layouts(default, for_b).await?, + shredded_fields * per_field + ); + Ok(()) + } + + /// A shredded object is written with the Variant layout, as a column for its core storage + /// and one for each shredded field. Reading the Variant back, and extracting a path in the + /// scan, return what the Variant that was written holds. + #[rstest] + #[tokio::test] + async fn test_file_roundtrip_shredded_object_with_variant_layout( + parquet_variant_file_session: VortexResult, + ) -> VortexResult<()> { + let session = parquet_variant_file_session?; + crate::initialize(&session); + + // Only some events have a `commit`, and `commit.rev` stays in its residual value. + let json: ArrowArrayRef = Arc::new(StringArray::from(vec![ + r#"{"kind":"commit","n":1,"commit":{"collection":"post","rev":7}}"#, + r#"{"kind":"identity","n":2}"#, + r#"{"kind":"commit","n":3,"commit":{"collection":"like","rev":8}}"#, + ])); + let shredding = ShreddedSchemaBuilder::new() + .with_path("kind", &DataType::Utf8)? + .with_path("commit.collection", &DataType::Utf8)? + .build(); + let shredded = shred_variant(&json_to_variant(&json)?, &shredding)?; + let expected = ParquetVariant::from_arrow_variant(&shredded, &session.arrow())?; + + let mut bytes = ByteBufferMut::empty(); + session + .write_options() + .with_strategy(vortex_file::WriteStrategyBuilder::from_session(&session).build()) + .write(&mut bytes, expected.to_array_stream()) + .await?; + let file = session.open_options().open_buffer(bytes)?; + // The Variant is stored in a struct layout of its own dtype. + assert!(is_variant_layout(file.footer().layout())); + + let utf8 = DType::Utf8(Nullability::Nullable); + let i64 = DType::Primitive(PType::I64, Nullability::Nullable); + let mut ctx = session.create_execution_ctx(); + let actual = file.scan()?.into_array_stream()?.read_all().await?; + for (path, dtype) in [ + // A shredded leaf, and a leaf of a shredded object. + (VariantPath::field("kind"), utf8.clone()), + ( + VariantPath::new([ + VariantPathElement::field("commit"), + VariantPathElement::field("collection"), + ]), + utf8, + ), + // A field in the residual value of a shredded object, and one in the core storage. + ( + VariantPath::new([ + VariantPathElement::field("commit"), + VariantPathElement::field("rev"), + ]), + i64.clone(), + ), + (VariantPath::field("n"), i64), + ] { + let extraction = variant_get(root(), path.clone(), Some(dtype)); + let extracted = expected + .clone() + .apply(&extraction)? + .execute::(&mut ctx)?; + + // Extracting from the Variant that was read back. + assert_arrays_eq!( + actual + .clone() + .apply(&extraction)? + .execute::(&mut ctx)?, + extracted, + &mut ctx + ); + // Extracting in the scan, which reads the column that holds the path. + let scanned = file + .scan()? + .with_projection(extraction.bind(file.dtype())?) + .into_array_stream()? + .read_all() + .await?; + assert_arrays_eq!(scanned, extracted, &mut ctx); + } + Ok(()) + } + #[rstest] #[tokio::test] async fn test_file_roundtrip_typed_value_variant_with_zoned_strategy( diff --git a/vortex-array/src/arrays/variant/vtable/mod.rs b/vortex-array/src/arrays/variant/vtable/mod.rs index e3d4afeb340..dd9af5788e5 100644 --- a/vortex-array/src/arrays/variant/vtable/mod.rs +++ b/vortex-array/src/arrays/variant/vtable/mod.rs @@ -150,6 +150,7 @@ pub fn merge_typed_scalar_as_variant( fallback_scalar: Option, dtype: &DType, ) -> VortexResult { + let typed_scalar = without_unions(typed_scalar)?; let scalar = if typed_scalar.is_null() { fallback_scalar.unwrap_or_else(|| Scalar::null(dtype.clone())) } else if matches!( @@ -172,6 +173,94 @@ pub fn merge_typed_scalar_as_variant( } } +/// Replaces each union in the typed value `scalar` by the value of its member. +/// +/// A struct or list that holds a union becomes one of Variants, as the members of the union +/// differ in dtype. A null union is a value that is missing, as a null field is. +fn without_unions(scalar: Scalar) -> VortexResult { + if !has_union(scalar.dtype()) { + return Ok(scalar); + } + + if let Some(union) = scalar.as_union_opt() { + return match union.child() { + Some(member) => without_unions(member), + None => Ok(Scalar::null(scalar.dtype().clone())), + }; + } + + if scalar.is_null() { + return Ok(Scalar::null(DType::Variant(Nullability::Nullable))); + } + + let as_variant = |value: Scalar| -> VortexResult> { + let value = without_unions(value)?; + Ok((!value.is_null()).then(|| { + if value.dtype().is_variant() { + value + } else { + Scalar::variant(value) + } + })) + }; + + match scalar.dtype() { + DType::Struct(..) => { + let fields = scalar.as_struct(); + let mut names = Vec::new(); + let mut values = Vec::new(); + for name in fields.names().iter() { + if let Some(value) = fields + .field(name.as_ref()) + .map(as_variant) + .transpose()? + .flatten() + { + names.push(FieldName::from(name.as_ref())); + values.push(value.into_value()); + } + } + + let fields = StructFields::new( + FieldNames::from(names), + vec![DType::Variant(Nullability::NonNullable); values.len()], + ); + Scalar::try_new( + DType::Struct(fields, Nullability::NonNullable), + Some(ScalarValue::Tuple(values)), + ) + } + DType::List(..) | DType::FixedSizeList(..) => { + let elements = scalar + .as_list() + .elements() + .unwrap_or_default() + .into_iter() + .map(|element| { + Ok(as_variant(element)? + .unwrap_or_else(|| Scalar::variant(Scalar::null(DType::Null)))) + }) + .collect::>>()?; + Ok(Scalar::list( + DType::Variant(Nullability::NonNullable), + elements, + Nullability::NonNullable, + )) + } + _ => Ok(scalar), + } +} + +/// Whether `dtype` is or holds a union. +fn has_union(dtype: &DType) -> bool { + match dtype { + DType::Union(..) => true, + DType::Struct(fields, _) => fields.fields().any(|field| has_union(&field)), + DType::List(element, _) | DType::FixedSizeList(element, ..) => has_union(element), + _ => false, + } +} + fn typed_list_as_variant_payload(typed_scalar: Scalar) -> VortexResult { let element_dtype = DType::Variant(Nullability::NonNullable); let list = typed_scalar.as_list(); diff --git a/vortex-edition/src/declarations/unstable/mod.rs b/vortex-edition/src/declarations/unstable/mod.rs index f2a1913ac46..eb7ba3ea03e 100644 --- a/vortex-edition/src/declarations/unstable/mod.rs +++ b/vortex-edition/src/declarations/unstable/mod.rs @@ -34,5 +34,6 @@ pub static DECLARATION: EditionDeclaration = EditionDeclaration { added: &[ EditionMember::array(&"vortex.decimal_byte_parts.v2"), EditionMember::array(&"vortex.widen"), + EditionMember::layout(&"vortex.variant"), ], }; diff --git a/vortex-file/src/strategy.rs b/vortex-file/src/strategy.rs index e345e89b48b..85a89a3a0de 100644 --- a/vortex-file/src/strategy.rs +++ b/vortex-file/src/strategy.rs @@ -29,6 +29,8 @@ use vortex_layout::layouts::list::writer::ListLayoutStrategy; use vortex_layout::layouts::repartition::RepartitionStrategy; use vortex_layout::layouts::repartition::RepartitionWriterOptions; use vortex_layout::layouts::table::TableStrategy; +use vortex_layout::layouts::variant; +use vortex_layout::layouts::variant::VariantShreddingPolicy; use vortex_layout::layouts::zoned::writer::ZonedLayoutOptions; use vortex_layout::layouts::zoned::writer::ZonedStrategy; use vortex_session::VortexSession; @@ -129,6 +131,13 @@ pub struct WriteStrategyBuilder { /// /// [`ListLayoutStrategy`]: vortex_layout::layouts::list::writer::ListLayoutStrategy use_list_layout: bool, + /// Whether shredded Variant fields are split into columns with a struct layout. + use_variant_layout: bool, + /// Chooses how to shred the Variant fields that are not shredded and have no policy of their + /// own, if the Variant layout is used. + variant_shredding: Option>, + /// Chooses how to shred the Variant field at each path, if the Variant layout is used. + variant_shredding_at: HashMap>, } impl WriteStrategyBuilder { @@ -147,9 +156,37 @@ impl WriteStrategyBuilder { use_list_layout: session .enabled_component_ids(ComponentKind::Layout) .contains(&List.id()), + use_variant_layout: session + .enabled_component_ids(ComponentKind::Layout) + .contains(&variant::layout_id()), + variant_shredding: None, + variant_shredding_at: HashMap::new(), } } + /// Shred the Variant fields that are not shredded as `policy` chooses, so that the Variant + /// layout stores what they have in common as columns. A field with a policy of its own, set + /// with [`with_variant_shredding_at`](Self::with_variant_shredding_at), uses that instead. + /// + /// This has no effect unless the session enables the Variant layout, which is unstable. + pub fn with_variant_shredding(mut self, policy: Arc) -> Self { + self.variant_shredding = Some(policy); + self + } + + /// Shred the Variant field at `field` as `policy` chooses, if it is not shredded. The root + /// path is a Variant written on its own. + /// + /// This has no effect unless the session enables the Variant layout, which is unstable. + pub fn with_variant_shredding_at( + mut self, + field: impl Into, + policy: Arc, + ) -> Self { + self.variant_shredding_at.insert(field.into(), policy); + self + } + /// Override the row block size used for row repartitioning and zoned statistics. /// /// Larger blocks reduce footer/statistics overhead. Smaller blocks can improve pruning and @@ -304,6 +341,16 @@ impl WriteStrategyBuilder { TableStrategy::new(Arc::new(validity_strategy), Arc::new(constant)) .with_field_writers(self.field_writers); + if self.use_variant_layout { + table_strategy = table_strategy.with_variant_layout(); + if let Some(policy) = self.variant_shredding { + table_strategy = table_strategy.with_variant_shredding(policy); + } + for (field, policy) in self.variant_shredding_at { + table_strategy = table_strategy.with_variant_shredding_at(field, policy); + } + } + if self.use_list_layout { // We need a closure here to enable recursive application of list layout. table_strategy = table_strategy.with_list_layout_factory( diff --git a/vortex-functions/src/expr.rs b/vortex-functions/src/expr.rs index ef59c26731b..1e9e8e70989 100644 --- a/vortex-functions/src/expr.rs +++ b/vortex-functions/src/expr.rs @@ -57,6 +57,8 @@ use crate::variant_get::VariantGetOptions; use crate::variant_get::VariantPath; use crate::variant_pack::VariantPack; use crate::variant_pack::VariantPackOptions; +use crate::variant_shred::VariantShred; +use crate::variant_shred::VariantShredOptions; use crate::zip::Zip; /// Creates a CASE WHEN expression with one WHEN/THEN pair and an ELSE value. @@ -668,6 +670,12 @@ pub fn variant_pack_with_validity( ) } +/// Creates an expression that shreds the unshredded Variant `child` by `schema`, keeping the +/// values it holds. +pub fn variant_shred(child: Expression, schema: DType) -> Expression { + VariantShred.new_expr(VariantShredOptions::new(schema), vec![child]) +} + // ---- Like ---- /// Creates a SQL LIKE expression. diff --git a/vortex-functions/src/lib.rs b/vortex-functions/src/lib.rs index c151d632eaf..53749afa78b 100644 --- a/vortex-functions/src/lib.rs +++ b/vortex-functions/src/lib.rs @@ -44,6 +44,7 @@ pub mod stat; pub mod strpos; pub mod variant_get; pub mod variant_pack; +pub mod variant_shred; pub mod zip; #[cfg(test)] @@ -70,6 +71,9 @@ pub fn initialize(session: &VortexSession) { scalar_fns.register(stat::StatFn); scalar_fns.register(strpos::Strpos); scalar_fns.register(variant_pack::VariantPack); + scalar_fns.register(variant_shred::VariantShred); + scalar_fns.register(variant_shred::VariantShredStrict); + scalar_fns.register(variant_shred::VariantShredUnion); } /// A scalar function has a negative cost if applying it to an array and diff --git a/vortex-functions/src/variant_get/mod.rs b/vortex-functions/src/variant_get/mod.rs index 699a924f88a..60b89a76fd6 100644 --- a/vortex-functions/src/variant_get/mod.rs +++ b/vortex-functions/src/variant_get/mod.rs @@ -21,12 +21,14 @@ use vortex_array::arrays::Variant; use vortex_array::arrays::VariantArray; use vortex_array::arrays::chunked::ChunkedArrayExt; use vortex_array::arrays::scalar_fn::ScalarFnArrayExt; +use vortex_array::arrays::variant::decode_unshredded_storage; use vortex_array::builders::VariantBuilder; use vortex_array::builders::builder_with_capacity_in; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; use vortex_array::dtype::FieldName; use vortex_array::dtype::Nullability; +use vortex_array::expr::BoundExpression; use vortex_array::expr::display::ExprDisplay; use vortex_array::proto::expr as pb; use vortex_array::proto::expr::variant_path_element; @@ -50,6 +52,7 @@ use vortex_session::registry::CachedId; use vortex_utils::aliases::StringEscape; use crate::variant_pack::VariantPack; +use crate::variant_pack::VariantPackOptions; /// How many lazy layers `variant_get` unwraps from its input before it extracts row by row. const MAX_CANONICALIZE_DEPTH: usize = 8; @@ -283,6 +286,31 @@ impl ScalarFnVTable for VariantGet { .new_node(Cast.bind(node.node_dtype()?), &[current]) .map(Some); } + + // A union holds the rest of the path in its members. It is the whole Variant + // here, so the Variant reads it over a core storage that holds no value. A core + // storage that is constant already holds no value, and stops the rewrite. + // + // That core storage holds a Variant null, where the union does not hold the + // row. An untyped request would read it as a Variant null and not as a value + // that is missing, so only a request of a typed value is rewritten. + (DType::Union(..), _) + if options.dtype().is_some_and(|dtype| !dtype.is_variant()) + && (descended || (pack.complete() && core.as_constant().is_none())) => + { + let empty = + Scalar::variant(Scalar::null(DType::Null)).cast(&core.node_dtype()?)?; + let variant = node.new_node( + VariantPack.bind(VariantPackOptions::new(true)), + &[node.new_constant(empty), current], + )?; + let rest = VariantGetOptions::new( + VariantPath::new(path.iter().cloned()), + options.dtype().cloned(), + ); + return node.new_node(VariantGet.bind(rest), &[variant]).map(Some); + } + _ => return Ok(None), } } @@ -293,6 +321,30 @@ impl ScalarFnVTable for VariantGet { } } +/// Decodes the storage of an unshredded Variant `array` if `expr` extracts from it more than once, +/// as each `variant_get` would otherwise decode it again. +pub fn decode_for_repeated_extraction( + array: ArrayRef, + expr: &BoundExpression, + ctx: &mut ExecutionCtx, +) -> VortexResult { + if array.dtype().is_variant() && count_variant_gets(expr) > 1 { + decode_unshredded_storage(array, ctx) + } else { + Ok(array) + } +} + +/// The number of `variant_get` calls in `expr`. +fn count_variant_gets(expr: &BoundExpression) -> usize { + usize::from(expr.is::()) + + expr + .children() + .iter() + .map(count_variant_gets) + .sum::() +} + fn variant_get_scalar( scalar: &Scalar, options: &VariantGetOptions, @@ -677,6 +729,8 @@ mod tests { use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; + use vortex_array::arrays::UnionArray; + use vortex_array::arrays::VarBinViewArray; use vortex_array::arrays::VariantArray; use vortex_array::arrays::variant::VariantArraySlotsExt; use vortex_array::assert_arrays_eq; @@ -687,7 +741,9 @@ mod tests { use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::StructFields; + use vortex_array::dtype::UnionVariants; use vortex_array::expr::Expression; + use vortex_array::expr::get_item; use vortex_array::expr::proto::ExprSerializeProtoExt; use vortex_array::expr::root; use vortex_array::optimizer::ArrayOptimizer; @@ -702,6 +758,7 @@ mod tests { use vortex_session::VortexSession; use crate::expr::variant_get; + use crate::expr::variant_pack; use crate::variant_get::VariantGet; use crate::variant_get::VariantGetOptions; use crate::variant_get::VariantPath; @@ -837,6 +894,96 @@ mod tests { .execute::(&mut SESSION.create_execution_ctx()) } + /// A shredded union holds the whole Variant in its rows, so a complete pack reads the path + /// from the union and not from the core storage. + #[test] + fn variant_get_reads_a_shredded_union_without_the_core() -> VortexResult<()> { + let union = UnionVariants::new( + ["int", "str"].into(), + vec![ + DType::Primitive(PType::I64, Nullability::NonNullable), + DType::Utf8(Nullability::NonNullable), + ], + )?; + let shredded = DType::struct_( + [("a", DType::Union(union, Nullability::Nullable))], + Nullability::NonNullable, + ); + let scope = DType::struct_( + [ + ("core", DType::Variant(Nullability::Nullable)), + ("shredded", shredded), + ], + Nullability::NonNullable, + ); + let expr = variant_get( + variant_pack(get_item("core", root()), get_item("shredded", root()), true), + parse_path("$.a")?, + Some(DType::Primitive(PType::I64, Nullability::Nullable)), + ) + .bind(&scope)?; + + let optimized = expr.optimize_recursive()?; + + assert_eq!(optimized.dtype(), expr.dtype()); + assert!(!optimized.to_string().contains("core"), "got {optimized}"); + Ok(()) + } + + /// The rewrite of a `variant_get` over a shredded union reads the values of the union. + #[test] + fn variant_get_over_a_shredded_union_reads_its_values() -> VortexResult<()> { + let variants = UnionVariants::new( + ["int", "str"].into(), + vec![ + DType::Primitive(PType::I64, Nullability::NonNullable), + DType::Utf8(Nullability::NonNullable), + ], + )?; + let type_ids = PrimitiveArray::from_option_iter([Some(0u8), Some(1), None]).into_array(); + let ints = PrimitiveArray::from_iter([1i64, 0, 0]).into_array(); + let strs = VarBinViewArray::from_iter_str(["", "x", ""]).into_array(); + let union = UnionArray::try_new(type_ids, variants, [ints, strs])?.into_array(); + let shredded = StructArray::try_new( + FieldNames::from_iter(["a"]), + vec![union], + 3, + Validity::NonNullable, + )? + .into_array(); + let core = ConstantArray::new( + Scalar::variant(Scalar::null(DType::Null)) + .cast(&DType::Variant(Nullability::Nullable))?, + 3, + ) + .into_array(); + let array = StructArray::try_new( + FieldNames::from_iter(["core", "shredded"]), + vec![core, shredded], + 3, + Validity::NonNullable, + )? + .into_array(); + + let expr = variant_get( + variant_pack(get_item("core", root()), get_item("shredded", root()), true), + parse_path("$.a")?, + Some(DType::Primitive(PType::I64, Nullability::Nullable)), + ); + let actual = array + .apply(&expr)? + .optimize_ctx(&SESSION)? + .execute::(&mut SESSION.create_execution_ctx())?; + + let mut ctx = SESSION.create_execution_ctx(); + assert_arrays_eq!( + actual, + PrimitiveArray::from_option_iter([Some(1i64), None, None]), + &mut ctx + ); + Ok(()) + } + #[test] fn variant_get_path_parse_and_display() { let path = parse_path("$.data[1].a").unwrap(); diff --git a/vortex-functions/src/variant_get/variant.rs b/vortex-functions/src/variant_get/variant.rs index 2b1eff05b7f..3f8759246eb 100644 --- a/vortex-functions/src/variant_get/variant.rs +++ b/vortex-functions/src/variant_get/variant.rs @@ -7,11 +7,16 @@ use vortex_array::ArrayView; use vortex_array::Canonical; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::Struct; +use vortex_array::arrays::UnionArray; use vortex_array::arrays::Variant; use vortex_array::arrays::scalar_fn::ExactScalarFn; use vortex_array::arrays::scalar_fn::ScalarFnArrayView; use vortex_array::arrays::struct_::StructArrayExt; +use vortex_array::arrays::union::UnionArrayExt; +use vortex_array::arrays::union::UnionArraySlotsExt; use vortex_array::arrays::variant::VariantArraySlotsExt; use vortex_array::arrays::variant::merge_typed_scalar_as_variant; use vortex_array::builders::VariantBuilder; @@ -25,6 +30,7 @@ use vortex_array::optimizer::kernels::ArrayKernelsExt; use vortex_array::scalar::Scalar; use vortex_array::scalar_fn::ScalarFnVTable; use vortex_array::validity::Validity; +use vortex_buffer::BitBufferMut; use vortex_buffer::Buffer; use vortex_error::VortexError; use vortex_error::VortexResult; @@ -76,7 +82,8 @@ impl ExecuteParentKernel for VariantGetKernel { .map(|shredded| { typed_shredded_path(shredded, parent.options.path().elements(), ctx)? .map(|(typed, remaining)| { - let typed = mask_with_validity(typed, &core_validity)?.optimize_ctx(ctx)?; + let typed = + mask_with_validity(typed, &core_validity, ctx)?.optimize_ctx(ctx)?; Ok::<_, VortexError>((typed, remaining)) }) .transpose() @@ -164,7 +171,11 @@ impl ExecuteParentKernel for VariantGetKernel { // The core storage holds no value of a row that the typed child holds, so a typed value // of another dtype than the requested one converts from the typed child. - let typed = convert_typed(typed, parent.dtype(), ctx)?; + let typed = if typed.dtype().is_union() { + convert_union(typed, parent.dtype(), ctx)? + } else { + convert_typed(typed, parent.dtype(), ctx)? + }; fill_absent_from_core(typed, typed_mask, array.core_storage(), parent.options, ctx) .map(Some) } @@ -248,13 +259,139 @@ fn convert_typed(typed: ArrayRef, dtype: &DType, ctx: &mut ExecutionCtx) -> Vort Ok(builder.finish()) } +/// The rows of each member of the union `union`, and the member, in the order of its variants. +fn union_members(union: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult> { + let len = union.len(); + let union = union.execute::(ctx)?; + let valid = union.type_ids().validity()?.execute_mask(len, ctx)?; + let type_ids = union.type_ids().clone().execute::(ctx)?; + let variants = union.variants(); + + let mut rows = vec![BitBufferMut::new_unset(len); variants.len()]; + for (idx, type_id) in type_ids.as_slice::().iter().enumerate() { + if valid.value(idx) + && let Some(member) = variants.tag_to_child_index(*type_id) + { + rows[member].set(idx); + } + } + + Ok(rows + .into_iter() + .zip(union.iter_children().cloned()) + .map(|(rows, member)| (Mask::from(rows.freeze()), member)) + .collect()) +} + +/// Merges `members`, each with the rows it holds, into one array of `dtype`. A row that no member +/// holds is null. +fn merge_members( + members: Vec<(Mask, ArrayRef)>, + dtype: &DType, + len: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let dtype = dtype.as_nullable(); + let mut merged = ConstantArray::new(Scalar::null(dtype.clone()), len).into_array(); + for (rows, member) in members { + merged = rows.into_array().zip(member.cast(dtype.clone())?, merged)?; + } + merged.execute::(ctx) +} + +/// The field `name` of the struct members of the union `union`. +/// +/// A row of another member has no such field, and is null. If the members shred the field as +/// different dtypes, the field is the Variant of each value. Returns `None` if no struct member +/// shreds the field. +fn union_field( + union: ArrayRef, + name: &str, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let len = union.len(); + let mut fields = Vec::new(); + for (rows, member) in union_members(union, ctx)? { + if !member.dtype().is_struct() { + continue; + } + + let member = member.execute::>(ctx)?; + if let Some(field) = member.unmasked_field_by_name_opt(name) { + fields.push(( + rows, + mask_with_validity(field.clone(), &member.validity()?, ctx)?, + )); + } + } + + let Some(dtype) = fields.first().map(|(_, field)| field.dtype().as_nullable()) else { + return Ok(None); + }; + if fields + .iter() + .any(|(_, field)| !field.dtype().eq_ignore_nullability(&dtype)) + { + return merge_members_as_variant(&fields, len, ctx).map(Some); + } + + merge_members(fields, &dtype, len, ctx).map(Some) +} + +/// Merges `members`, each with the rows it holds, into one array of the Variants of their +/// values. A row that no member holds is null. +fn merge_members_as_variant( + members: &[(Mask, ArrayRef)], + len: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let dtype = DType::Variant(Nullability::Nullable); + let mut builder = VariantBuilder::new(Nullability::Nullable); + for idx in 0..len { + let value = match members.iter().find(|(rows, _)| rows.value(idx)) { + Some((_, member)) => member.execute_scalar(idx, ctx)?, + None => Scalar::null(dtype.clone()), + }; + let value = merge_typed_scalar_as_variant(value, None, &dtype)?; + builder.append_n_scalars(&value, 1)?; + } + builder.finish_into_variant().map(IntoArray::into_array) +} + +/// Converts the values of the union `union` to `dtype`, each member as [`convert_typed`] +/// converts it. +fn convert_union(union: ArrayRef, dtype: &DType, ctx: &mut ExecutionCtx) -> VortexResult { + let len = union.len(); + let members = union_members(union, ctx)? + .into_iter() + .map(|(rows, member)| Ok((rows, convert_typed(member, dtype, ctx)?))) + .collect::>>()?; + merge_members(members, dtype, len, ctx) +} + /// Nulls out the rows of `array` that `validity` marks invalid. /// /// A validity without nulls leaves `array` as it is: wrapping it in a mask would hide its /// encoding from the kernels that extract from it. -fn mask_with_validity(array: ArrayRef, validity: &Validity) -> VortexResult { +fn mask_with_validity( + array: ArrayRef, + validity: &Validity, + ctx: &mut ExecutionCtx, +) -> VortexResult { match validity { Validity::NonNullable | Validity::AllValid => Ok(array), + validity if array.dtype().is_union() => { + // The validity of a union is the validity of its type ids. + let len = array.len(); + let union = array.execute::(ctx)?; + let type_ids = union.type_ids().clone().mask(validity.to_array(len))?; + let union = UnionArray::try_new( + type_ids, + union.variants().clone(), + union.iter_children().cloned(), + )?; + Ok(union.into_array()) + } validity => { let len = array.len(); array.mask(validity.to_array(len)) @@ -283,6 +420,15 @@ fn typed_shredded_path<'a>( .then_some((current, &path[idx..])), ); }; + + if current.dtype().is_union() { + let Some(field) = union_field(current, name.as_ref(), ctx)? else { + return Ok(None); + }; + current = field; + continue; + } + let DType::Struct(..) = current.dtype() else { return Ok(None); }; @@ -290,7 +436,7 @@ fn typed_shredded_path<'a>( let Some(field) = current_struct.unmasked_field_by_name_opt(name.as_ref()) else { return Ok(None); }; - current = mask_with_validity(field.clone(), ¤t_struct.validity()?)?; + current = mask_with_validity(field.clone(), ¤t_struct.validity()?, ctx)?; } Ok(Some((current, &[]))) @@ -337,6 +483,7 @@ mod tests { use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; + use vortex_array::arrays::UnionArray; use vortex_array::arrays::VarBinViewArray; use vortex_array::arrays::VariantArray; use vortex_array::assert_arrays_eq; @@ -345,14 +492,17 @@ mod tests { use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; + use vortex_array::dtype::UnionVariants; use vortex_array::expr::root; use vortex_array::scalar::Scalar; use vortex_array::validity::Validity; use vortex_error::VortexResult; + use vortex_error::vortex_err; use vortex_session::VortexSession; use crate::expr::variant_get; use crate::variant_get::VariantPath; + use crate::variant_get::VariantPathElement; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); @@ -439,6 +589,221 @@ mod tests { Ok(()) } + /// The core storage of `len` rows that each hold `value`, or no value. + fn core(value: Option, len: usize) -> ArrayRef { + let value = value.unwrap_or_else(|| Scalar::null(DType::Null)); + ConstantArray::new(Scalar::variant(value), len).into_array() + } + + /// The Variants of `core`, whose field `a` is shredded as `a`. + fn shredded_over(core: ArrayRef, a: ArrayRef) -> VortexResult { + let len = a.len(); + let shredded = StructArray::try_new( + FieldNames::from_iter(["a"]), + vec![a], + len, + Validity::NonNullable, + )? + .into_array(); + Ok(VariantArray::try_new(core, Some(shredded))?.into_array()) + } + + /// A union of an integer `int` and a string `str`, with the rows `1`, `"x"` and null. + fn int_or_str() -> VortexResult { + let variants = UnionVariants::new( + ["int", "str"].into(), + vec![ + DType::Primitive(PType::I64, Nullability::NonNullable), + DType::Utf8(Nullability::NonNullable), + ], + )?; + let type_ids = PrimitiveArray::from_option_iter([Some(0u8), Some(1), None]).into_array(); + let ints = PrimitiveArray::from_iter([1i64, 0, 0]).into_array(); + let strs = VarBinViewArray::from_iter_str(["", "x", ""]).into_array(); + Ok(UnionArray::try_new(type_ids, variants, [ints, strs])?.into_array()) + } + + #[rstest] + #[case::member( + DType::Primitive(PType::I64, Nullability::Nullable), + PrimitiveArray::from_option_iter([Some(1i64), None, None]).into_array(), + )] + #[case::other_member( + DType::Utf8(Nullability::Nullable), + VarBinViewArray::from_iter_nullable_str([None, Some("x"), None]).into_array(), + )] + #[case::converted( + DType::Primitive(PType::F64, Nullability::Nullable), + PrimitiveArray::from_option_iter([Some(1f64), None, None]).into_array(), + )] + fn reads_a_typed_value_from_a_union( + #[case] requested: DType, + #[case] expected: ArrayRef, + ) -> VortexResult<()> { + let array = shredded_over(core(None, 3), int_or_str()?)?; + let expr = variant_get(root(), VariantPath::field("a"), Some(requested)); + + let mut ctx = SESSION.create_execution_ctx(); + let actual = array.apply(&expr)?.execute::(&mut ctx)?; + + assert_arrays_eq!(actual, expected, &mut ctx); + Ok(()) + } + + /// A row that the union does not hold reads the core storage. + #[test] + fn reads_a_variant_from_a_union() -> VortexResult<()> { + let fallback = Scalar::struct_( + DType::struct_( + [("a", DType::Primitive(PType::F64, Nullability::NonNullable))], + Nullability::NonNullable, + ), + [Scalar::primitive(3.5f64, Nullability::NonNullable)], + ); + let array = shredded_over(core(Some(fallback), 3), int_or_str()?)?; + let expr = variant_get(root(), VariantPath::field("a"), None); + + let mut ctx = SESSION.create_execution_ctx(); + let actual = array.apply(&expr)?.execute::(&mut ctx)?; + + let expected = [ + Scalar::primitive(1i64, Nullability::NonNullable), + Scalar::utf8("x", Nullability::NonNullable), + Scalar::primitive(3.5f64, Nullability::NonNullable), + ]; + for (idx, value) in expected.into_iter().enumerate() { + let actual = actual.execute_scalar(idx, &mut ctx)?; + assert_eq!(actual.as_variant().value(), Some(&value), "row {idx}"); + } + Ok(()) + } + + /// A struct that holds a union reads as a Variant whose field holds the value of the member. + #[test] + fn reads_a_struct_with_a_union_as_a_variant() -> VortexResult<()> { + let array = shredded_over(core(None, 3), int_or_str()?)?; + let expr = variant_get(root(), VariantPath::root(), None); + + let mut ctx = SESSION.create_execution_ctx(); + let actual = array.apply(&expr)?.execute::(&mut ctx)?; + + let expected = [ + Some(Scalar::primitive(1i64, Nullability::NonNullable)), + Some(Scalar::utf8("x", Nullability::NonNullable)), + None, + ]; + for (idx, value) in expected.into_iter().enumerate() { + let object = actual.execute_scalar(idx, &mut ctx)?; + let object = object + .as_variant() + .value() + .ok_or_else(|| vortex_err!("row {idx} is not an object"))? + .as_struct(); + let field = object + .field("a") + .and_then(|field| field.as_variant().value().cloned()); + assert_eq!(field, value, "row {idx}"); + } + Ok(()) + } + + /// A field that two struct members shred as different dtypes reads the value of each. + #[rstest] + #[case::int( + DType::Primitive(PType::I64, Nullability::Nullable), + PrimitiveArray::from_option_iter([Some(5i64), None]).into_array(), + )] + #[case::string( + DType::Utf8(Nullability::Nullable), + VarBinViewArray::from_iter_nullable_str([None, Some("y")]).into_array(), + )] + fn reads_a_field_of_members_of_different_dtypes( + #[case] requested: DType, + #[case] expected: ArrayRef, + ) -> VortexResult<()> { + let object = |dtype: DType| DType::struct_([("x", dtype)], Nullability::NonNullable); + let variants = UnionVariants::new( + ["int", "str"].into(), + vec![ + object(DType::Primitive(PType::I64, Nullability::NonNullable)), + object(DType::Utf8(Nullability::NonNullable)), + ], + )?; + let type_ids = PrimitiveArray::from_option_iter([Some(0u8), Some(1)]).into_array(); + let ints = StructArray::try_new( + FieldNames::from_iter(["x"]), + vec![PrimitiveArray::from_iter([5i64, 0]).into_array()], + 2, + Validity::NonNullable, + )? + .into_array(); + let strs = StructArray::try_new( + FieldNames::from_iter(["x"]), + vec![VarBinViewArray::from_iter_str(["", "y"]).into_array()], + 2, + Validity::NonNullable, + )? + .into_array(); + let union = UnionArray::try_new(type_ids, variants, [ints, strs])?.into_array(); + + let array = shredded_over(core(None, 2), union)?; + let expr = variant_get( + root(), + VariantPath::new([ + VariantPathElement::Field("a".into()), + VariantPathElement::Field("x".into()), + ]), + Some(requested), + ); + + let mut ctx = SESSION.create_execution_ctx(); + let actual = array.apply(&expr)?.execute::(&mut ctx)?; + + assert_arrays_eq!(actual, expected, &mut ctx); + Ok(()) + } + + /// A field of a struct member reads from that member. The rows of another member have no + /// such field. + #[test] + fn reads_a_field_of_a_union_member() -> VortexResult<()> { + let object = DType::struct_( + [("x", DType::Primitive(PType::I64, Nullability::NonNullable))], + Nullability::NonNullable, + ); + let variants = UnionVariants::new( + ["object", "str"].into(), + vec![object, DType::Utf8(Nullability::NonNullable)], + )?; + let type_ids = PrimitiveArray::from_option_iter([Some(0u8), Some(1), Some(0)]).into_array(); + let objects = StructArray::try_new( + FieldNames::from_iter(["x"]), + vec![PrimitiveArray::from_iter([5i64, 0, 7]).into_array()], + 3, + Validity::NonNullable, + )? + .into_array(); + let strs = VarBinViewArray::from_iter_str(["", "y", ""]).into_array(); + let union = UnionArray::try_new(type_ids, variants, [objects, strs])?.into_array(); + + let array = shredded_over(core(None, 3), union)?; + let expr = variant_get( + root(), + VariantPath::new([ + VariantPathElement::Field("a".into()), + VariantPathElement::Field("x".into()), + ]), + Some(DType::Primitive(PType::I64, Nullability::Nullable)), + ); + + let mut ctx = SESSION.create_execution_ctx(); + let actual = array.apply(&expr)?.execute::(&mut ctx)?; + + let expected = PrimitiveArray::from_option_iter([Some(5i64), None, Some(7)]); + assert_arrays_eq!(actual, expected.into_array(), &mut ctx); + Ok(()) + } + /// A string reads as a Boolean as Arrow's Variant conversion reads it, so a shredded string /// field gives what the unshredded value gives. #[test] diff --git a/vortex-functions/src/variant_shred.rs b/vortex-functions/src/variant_shred.rs new file mode 100644 index 00000000000..dc323a3a59f --- /dev/null +++ b/vortex-functions/src/variant_shred.rs @@ -0,0 +1,363 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The scalar functions that shred an unshredded Variant by a schema. +//! +//! Each function is one shredding behaviour, and differs only in what happens to a value that +//! does not fit the schema: +//! +//! - [`VariantShred`] keeps it in the core storage, as Parquet shredding does. +//! - [`VariantShredStrict`] fails. +//! - [`VariantShredUnion`] keeps it in the core storage too, but its schema can hold unions, so +//! that a value of each type in the union fits. + +use std::fmt; +use std::fmt::Display; +use std::fmt::Formatter; + +use prost::Message; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::ScalarFnArray; +use vortex_array::arrays::VariantArray; +use vortex_array::arrays::variant::VariantArraySlotsExt; +use vortex_array::dtype::DType; +use vortex_array::dtype::proto::dtype as pb; +use vortex_array::scalar_fn::Arity; +use vortex_array::scalar_fn::ChildName; +use vortex_array::scalar_fn::ExecutionArgs; +use vortex_array::scalar_fn::ScalarFnId; +use vortex_array::scalar_fn::ScalarFnVTable; +use vortex_array::scalar_fn::ScalarFnVTableExt; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +/// Shreds an unshredded Variant by a schema. +/// +/// The schema is a tree of the typed columns to shred into: a struct for an object, a list for +/// an array, and any other dtype for a typed leaf. The result holds the same values as the input. +/// Each value that fits the schema moves into the shredded child, and the core storage keeps the +/// rest. So the schema only says where the values are stored, not what they are. +/// +/// The shredded child follows the shape of the schema, but its dtype is not the schema: a leaf +/// can be a Variant, which also holds the values of other types. +/// +/// The encoding of the Variant storage does the work, through a kernel that it registers for this +/// function. An encoding without such a kernel cannot be shredded, and execution fails. +#[derive(Clone)] +pub struct VariantShred; + +/// Shreds an unshredded Variant by a schema, and fails on a value that does not fit it. +/// +/// A value fits the schema as for [`VariantShred`], and a Variant null fits every position of +/// it. So the shredded child holds every value at the paths that the schema names, and the core +/// storage holds only the object fields that the schema does not name. +/// +/// The encoding of the Variant storage does the work, through a kernel that it registers for this +/// function. An encoding without such a kernel cannot be shredded, and execution fails. +#[derive(Clone)] +pub struct VariantShredStrict; + +/// Shreds an unshredded Variant by a schema that can hold unions. +/// +/// A union can be at any position of the schema, and its members can be leaves, structs, lists +/// and unions. A value goes to the first member that holds all of it: a leaf of its type, a +/// struct that names each field of the object and holds the value of each, or a list that holds +/// each element. The core storage keeps a value that no member holds, as [`VariantShred`] keeps +/// a value that does not fit. +/// +/// A member holds the whole value, so the core storage has nothing of a value that a member +/// holds. A union is the only node of the schema whose shredded child is not the typed column +/// that Parquet shreds into, so a Variant shredded by such a schema is not Parquet storage. +/// +/// The encoding of the Variant storage does the work, through a kernel that it registers for this +/// function. An encoding without such a kernel cannot be shredded, and execution fails. +#[derive(Clone)] +pub struct VariantShredUnion; + +impl VariantShredUnion { + /// Creates a lazy shredding of the Variant `input` by `schema`, which can hold unions. + /// + /// # Errors + /// + /// Returns an error if `input` is not a Variant. + pub fn try_new(input: ArrayRef, schema: DType) -> VortexResult { + ScalarFnArray::try_new( + VariantShredUnion.bind(VariantShredOptions::new(schema)), + [input], + ) + } +} + +impl VariantShredStrict { + /// Creates a lazy strict shredding of the Variant `input` by `schema`. + /// + /// # Errors + /// + /// Returns an error if `input` is not a Variant. + pub fn try_new(input: ArrayRef, schema: DType) -> VortexResult { + ScalarFnArray::try_new( + VariantShredStrict.bind(VariantShredOptions::new(schema)), + [input], + ) + } +} + +impl VariantShred { + /// Creates a lazy shredding of the Variant `input` by `schema`. + /// + /// # Errors + /// + /// Returns an error if `input` is not a Variant. + pub fn try_new(input: ArrayRef, schema: DType) -> VortexResult { + ScalarFnArray::try_new(VariantShred.bind(VariantShredOptions::new(schema)), [input]) + } +} + +/// Options for [`VariantShred`]. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct VariantShredOptions { + schema: DType, +} + +impl VariantShredOptions { + /// Creates options that shred by `schema`. + pub fn new(schema: DType) -> Self { + Self { schema } + } + + /// The tree of the typed columns to shred into. + pub fn schema(&self) -> &DType { + &self.schema + } + + fn serialize(&self) -> VortexResult>> { + Ok(Some(pb::DType::try_from(&self.schema)?.encode_to_vec())) + } + + fn deserialize(metadata: &[u8], session: &VortexSession) -> VortexResult { + let dtype = pb::DType::decode(metadata)?; + Ok(Self::new(DType::from_proto(&dtype, session)?)) + } +} + +impl Display for VariantShredOptions { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.schema) + } +} + +impl ScalarFnVTable for VariantShred { + type Options = VariantShredOptions; + + fn id(&self) -> ScalarFnId { + static ID: CachedId = CachedId::new("vortex.variant_shred"); + *ID + } + + fn serialize(&self, options: &Self::Options) -> VortexResult>> { + options.serialize() + } + + fn deserialize(&self, metadata: &[u8], session: &VortexSession) -> VortexResult { + VariantShredOptions::deserialize(metadata, session) + } + + fn arity(&self, _options: &Self::Options) -> Arity { + Arity::Exact(1) + } + + fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName { + input_name(child_idx) + } + + fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult { + input_dtype(arg_dtypes) + } + + fn execute( + &self, + options: &Self::Options, + args: &dyn ExecutionArgs, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + execute_on_storage(self, options, args, ctx) + } +} + +impl ScalarFnVTable for VariantShredStrict { + type Options = VariantShredOptions; + + fn id(&self) -> ScalarFnId { + static ID: CachedId = CachedId::new("vortex.variant_shred.strict"); + *ID + } + + fn serialize(&self, options: &Self::Options) -> VortexResult>> { + options.serialize() + } + + fn deserialize(&self, metadata: &[u8], session: &VortexSession) -> VortexResult { + VariantShredOptions::deserialize(metadata, session) + } + + fn arity(&self, _options: &Self::Options) -> Arity { + Arity::Exact(1) + } + + fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName { + input_name(child_idx) + } + + fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult { + input_dtype(arg_dtypes) + } + + fn execute( + &self, + options: &Self::Options, + args: &dyn ExecutionArgs, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + execute_on_storage(self, options, args, ctx) + } +} + +impl ScalarFnVTable for VariantShredUnion { + type Options = VariantShredOptions; + + fn id(&self) -> ScalarFnId { + static ID: CachedId = CachedId::new("vortex.variant_shred.union"); + *ID + } + + fn serialize(&self, options: &Self::Options) -> VortexResult>> { + options.serialize() + } + + fn deserialize(&self, metadata: &[u8], session: &VortexSession) -> VortexResult { + VariantShredOptions::deserialize(metadata, session) + } + + fn arity(&self, _options: &Self::Options) -> Arity { + Arity::Exact(1) + } + + fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName { + input_name(child_idx) + } + + fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult { + input_dtype(arg_dtypes) + } + + fn execute( + &self, + options: &Self::Options, + args: &dyn ExecutionArgs, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + execute_on_storage(self, options, args, ctx) + } +} + +fn input_name(child_idx: usize) -> ChildName { + match child_idx { + 0 => ChildName::from("input"), + _ => unreachable!("Invalid child index {child_idx} for a Variant shredding"), + } +} + +/// A shredding returns a Variant of the dtype of its `input`. +fn input_dtype(arg_dtypes: &[DType]) -> VortexResult { + vortex_ensure!( + arg_dtypes[0].is_variant(), + "A Variant shredding input must be a Variant, found {}", + arg_dtypes[0] + ); + Ok(arg_dtypes[0].clone()) +} + +/// Hands the core storage of the input to the kernel of its encoding for `shredding`. +/// +/// The kernels are keyed on the storage encodings. An input that is a canonical Variant, or a +/// lazy array over one, reaches this point first. +fn execute_on_storage>( + shredding: &V, + options: &VariantShredOptions, + args: &dyn ExecutionArgs, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let input = args.get(0)?; + let variant = input.clone().execute::(ctx)?; + vortex_ensure!( + variant.shredded().is_none(), + "A Variant shredding takes a Variant that is not shredded" + ); + + let core = variant.core_storage(); + if core.encoding_id() == input.encoding_id() { + vortex_bail!( + "Variant storage {} has no kernel for {}", + core.encoding_id(), + shredding.id() + ); + } + ScalarFnArray::try_new(shredding.bind(options.clone()), [core.clone()])? + .into_array() + .execute::(ctx) +} + +#[cfg(test)] +mod tests { + use vortex_array::dtype::FieldName; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::dtype::StructFields; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use super::*; + + #[test] + fn options_roundtrip() -> VortexResult<()> { + let dtype = DType::Struct( + StructFields::from_iter([ + ( + FieldName::from("a"), + DType::Primitive(PType::I64, Nullability::Nullable), + ), + (FieldName::from("b"), DType::Utf8(Nullability::Nullable)), + ]), + Nullability::Nullable, + ); + let options = VariantShredOptions::new(dtype); + + let metadata = VariantShred.serialize(&options)?.unwrap_or_default(); + let decoded = VariantShred.deserialize(&metadata, &VortexSession::empty())?; + + assert_eq!(decoded, options); + Ok(()) + } + + #[test] + fn return_dtype_is_the_input_dtype() -> VortexResult<()> { + let options = VariantShredOptions::new(DType::Utf8(Nullability::Nullable)); + let variant = DType::Variant(Nullability::NonNullable); + + assert_eq!( + VariantShred.return_dtype(&options, std::slice::from_ref(&variant))?, + variant + ); + assert!( + VariantShred + .return_dtype(&options, &[DType::Utf8(Nullability::Nullable)]) + .is_err() + ); + Ok(()) + } +} diff --git a/vortex-layout/src/layouts/flat/mod.rs b/vortex-layout/src/layouts/flat/mod.rs index 419bb6f43d1..fa80c1a2fb8 100644 --- a/vortex-layout/src/layouts/flat/mod.rs +++ b/vortex-layout/src/layouts/flat/mod.rs @@ -31,6 +31,7 @@ use crate::layouts::flat::reader::FlatReader; use crate::plan::physical::FilterPlan; use crate::plan::physical::PlanRef; use crate::plan::physical::SegmentScan; +use crate::plan::physical::SharePlan; use crate::segments::SegmentId; use crate::segments::SegmentSource; @@ -134,8 +135,15 @@ impl VTable for Flat { layout.array_ctx().clone(), layout.array_tree().cloned(), ); + // A filter and a projection that both extract from a Variant each scan its segment. Under + // a share, the split decodes the segment once, and with it the storage of the Variant. + let scan = if layout.dtype().is_variant() { + SharePlan::new(scan.into_plan()).into_plan() + } else { + scan.into_plan() + }; // TODO(ji): remove the Filter from the flat layout plan and return the segment scan. - Ok(FilterPlan::new(scan.into_plan()).into_plan()) + Ok(FilterPlan::new(scan).into_plan()) } } diff --git a/vortex-layout/src/layouts/flat/reader.rs b/vortex-layout/src/layouts/flat/reader.rs index 38a9bf0218d..aa833be262b 100644 --- a/vortex-layout/src/layouts/flat/reader.rs +++ b/vortex-layout/src/layouts/flat/reader.rs @@ -20,6 +20,7 @@ use vortex_array::expr::BoundExpression; use vortex_array::serde::SerializedArray; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_functions::variant_get::decode_for_repeated_extraction; use vortex_mask::Mask; use vortex_session::VortexSession; @@ -151,6 +152,9 @@ impl LayoutReader for FlatReader { array = array.slice(row_range.clone())?; } + array = + decode_for_repeated_extraction(array, &expr, &mut session.create_execution_ctx())?; + let mask_density = mask.density(); let array_mask = if mask_density < EXPR_EVAL_THRESHOLD { // We have the choice to apply the filter or the expression first, we apply the @@ -196,6 +200,7 @@ impl LayoutReader for FlatReader { let name = Arc::clone(&self.name); let array = self.array_future(); let expr = expr.clone(); + let session = self.session.clone(); Ok(async move { trace!("Flat array evaluation {} - {}", name, expr); @@ -221,6 +226,9 @@ impl LayoutReader for FlatReader { array = array.filter(mask)?; } + array = + decode_for_repeated_extraction(array, &expr, &mut session.create_execution_ctx())?; + // Evaluate the projection expression. array = array.apply_bound(&expr)?; diff --git a/vortex-layout/src/layouts/mod.rs b/vortex-layout/src/layouts/mod.rs index e1d6bc8d1fd..687151c4cbe 100644 --- a/vortex-layout/src/layouts/mod.rs +++ b/vortex-layout/src/layouts/mod.rs @@ -24,6 +24,7 @@ pub mod repartition; pub mod row_idx; pub mod struct_; pub mod table; +pub mod variant; pub mod zoned; pub type SharedArrayFuture = Shared>>; diff --git a/vortex-layout/src/layouts/struct_/mod.rs b/vortex-layout/src/layouts/struct_/mod.rs index 389d04f9423..576913b34ad 100644 --- a/vortex-layout/src/layouts/struct_/mod.rs +++ b/vortex-layout/src/layouts/struct_/mod.rs @@ -4,10 +4,11 @@ mod reader; pub mod writer; +use std::any::Any; use std::sync::Arc; use reader::StructReader; -use vortex_array::EmptyMetadata; +use vortex_array::ProstMetadata; use vortex_array::dtype::DType; use vortex_array::dtype::Field; use vortex_array::dtype::FieldMask; @@ -16,6 +17,7 @@ use vortex_array::dtype::StructFields; use vortex_error::VortexExpect; 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_session::SessionExt; @@ -23,17 +25,26 @@ use vortex_session::VortexSession; use vortex_session::registry::CachedId; pub use writer::StructStrategy; +use crate::DynLayout; use crate::Layout; +use crate::LayoutBuildContext; use crate::LayoutChildType; +use crate::LayoutDeserialization; use crate::LayoutDeserializeArgs; use crate::LayoutId; use crate::LayoutParts; +use crate::LayoutPlugin; use crate::LayoutReaderContext; use crate::LayoutReaderRef; use crate::LayoutRef; +use crate::LayoutSerialization; use crate::VTable; use crate::children::OwnedLayoutChildren; +use crate::layouts::variant; +use crate::layouts::variant::StructLayoutMetadata; +use crate::layouts::variant::VariantStorage; use crate::lowering::slots_from_layout; +use crate::plan::physical::EvalPlan; use crate::plan::physical::PackPlan; use crate::plan::physical::PlanRef; use crate::segments::SegmentSource; @@ -46,27 +57,54 @@ pub struct Struct; pub use Struct as StructLayoutEncoding; /// A layout decomposing a struct into one child per field and optional validity. +/// +/// A struct layout also stores a shredded Variant, as the struct of its core storage and its +/// shredded child; see [`variant`](crate::layouts::variant). The layout then reads the Variant +/// as the pack of its columns. pub type StructLayout = Layout; impl VTable for Struct { - type LayoutData = (); - type Metadata = EmptyMetadata; + /// How the layout stores a Variant, if its dtype is a Variant. + type LayoutData = Option; + type Metadata = ProstMetadata; fn id(&self) -> LayoutId { static ID: CachedId = CachedId::new("vortex.struct"); *ID } - fn metadata(_layout: &Layout) -> Self::Metadata { - EmptyMetadata + fn metadata(layout: &Layout) -> Self::Metadata { + ProstMetadata( + layout + .data() + .as_ref() + .map(VariantStorage::metadata) + .unwrap_or_default(), + ) } fn deserialize( &self, args: &LayoutDeserializeArgs<'_>, - _metadata: &EmptyMetadata, + metadata: &StructLayoutMetadata, ) -> VortexResult { - Layout::::validate_children(args.dtype, args.children.nchildren())?; + let variant = if args.dtype.is_variant() { + Some(VariantStorage::deserialize( + args.dtype, + metadata, + args.session, + )?) + } else { + vortex_ensure!( + metadata.is_empty(), + "Struct layout of a struct must have no metadata" + ); + None + }; + let storage_dtype = variant + .as_ref() + .map_or(args.dtype, VariantStorage::storage_dtype); + Layout::::validate_children(storage_dtype, args.children.nchildren())?; for idx in 0..args.children.nchildren() { let child_row_count = args.children.child_row_count(idx); @@ -76,7 +114,7 @@ impl VTable for Struct { "Struct child {idx} row count does not match parent" ); } - Ok(()) + Ok(variant) } fn nslots(layout: &Layout) -> usize { @@ -86,7 +124,7 @@ impl VTable for Struct { } fn slot_to_child(layout: &Layout, slot: usize) -> Option { - let nullable = layout.dtype().is_nullable(); + let nullable = layout.storage_dtype().is_nullable(); match slot { 0 => nullable.then_some(0), _ => Some(slot - 1 + usize::from(nullable)), @@ -94,7 +132,7 @@ impl VTable for Struct { } fn child_dtype(layout: &Layout, slot: usize) -> VortexResult { - StructLayout::slot_dtype(layout.dtype(), slot) + StructLayout::slot_dtype(layout.storage_dtype(), slot) } fn child_type(layout: &Layout, slot: usize) -> LayoutChildType { @@ -127,6 +165,8 @@ impl VTable for Struct { )?)) } + /// A Variant is the stored columns packed back together. An extraction over this plan folds + /// into the pack, and from there into a read of the shredded column it names. fn new_plan(layout: &Layout) -> VortexResult { // SAFETY: Struct layout construction validates child count and row counts. Its slots are // validity then one per field, which are the Pack slots, and its logical slot schema @@ -134,12 +174,82 @@ impl VTable for Struct { let plan = unsafe { PackPlan::from_slots_unchecked( layout.struct_fields().clone(), - layout.dtype().nullability(), + layout.storage_dtype().nullability(), layout.row_count(), slots_from_layout(&layout.to_layout()), ) + } + .into_plan(); + + match layout.data() { + Some(variant) => Ok(EvalPlan::try_new(variant.variant()?, plan)?.into_plan()), + None => Ok(plan), + } + } +} + +/// The layout plugin of the struct layout. +/// +/// A struct layout of a struct is written as `vortex.struct`. A struct layout of a Variant is +/// written as [`variant::layout_id`], so that the contract of `vortex.struct` stays as it is, and +/// only a session that enables the unstable edition writes or reads it. +#[derive(Clone, Copy, Debug, Default)] +pub struct StructPlugin; + +impl LayoutPlugin for StructPlugin { + fn as_any(&self) -> &dyn Any { + self + } + + fn id(&self) -> LayoutId { + VTable::id(&Struct) + } + + fn serialized_ids(&self) -> Vec { + vec![VTable::id(&Struct), variant::layout_id()] + } + + fn serialize( + &self, + layout: &dyn DynLayout, + _session: &VortexSession, + ) -> VortexResult { + let serialized_id = if layout.dtype().is_variant() { + variant::layout_id() + } else { + VTable::id(&Struct) }; - Ok(plan.into_plan()) + Ok(LayoutSerialization { + serialized_id, + metadata: layout.metadata(), + }) + } + + fn deserialize( + &self, + parts: LayoutDeserialization<'_>, + ctx: &LayoutBuildContext<'_>, + ) -> VortexResult { + let is_variant = parts.serialized_id == variant::layout_id(); + vortex_ensure!( + parts.dtype.is_variant() == is_variant, + "Layout {} cannot store {}", + parts.serialized_id, + parts.dtype + ); + // The contract of `vortex.struct` is frozen with no metadata at all. + vortex_ensure!( + is_variant || parts.metadata.is_empty(), + "Struct layout of a struct must have no metadata" + ); + LayoutPlugin::deserialize( + &Struct, + LayoutDeserialization { + serialized_id: VTable::id(&Struct), + ..parts + }, + ctx, + ) } } @@ -153,16 +263,62 @@ impl Layout { row_count, Vec::new(), OwnedLayoutChildren::layout_children(children), - (), + None, ) .into_typed() } - /// Returns the struct fields. + /// Creates a struct layout of a Variant of `dtype`, shredded as `shredded`, over the struct + /// layout `storage` of its stored struct. + /// + /// # Errors + /// + /// Returns an error if `dtype` is not a Variant, or `storage` is not a struct layout of the + /// struct that stores a Variant of `dtype` shredded as `shredded`. + pub fn try_new_variant( + dtype: DType, + shredded: DType, + storage: &LayoutRef, + complete: bool, + ) -> VortexResult { + let variant = VariantStorage::try_new(&dtype, shredded, complete)?; + vortex_ensure_eq!( + storage.dtype(), + variant.storage_dtype(), + "Struct layout of a Variant does not store its dtype and shredded dtype" + ); + let Some(storage) = storage.as_opt::() else { + vortex_bail!( + "Struct layout of a Variant must store a struct layout, found {}", + storage.encoding_id() + ); + }; + Ok(LayoutParts::new( + Struct, + dtype, + storage.row_count(), + Vec::new(), + Arc::clone(storage.children()), + Some(variant), + ) + .into_typed()) + } + + /// Returns the fields of the struct that the layout stores. + /// + /// For a struct, these are its own fields. For a Variant, these are the fields of the + /// struct of its core storage and its shredded child. pub fn struct_fields(&self) -> &StructFields { - self.dtype() + self.storage_dtype() .as_struct_fields_opt() - .vortex_expect("Struct layout dtype must be a struct") + .vortex_expect("Struct layout must store a struct") + } + + /// Returns the dtype of the struct that the layout stores. + fn storage_dtype(&self) -> &DType { + self.data() + .as_ref() + .map_or_else(|| self.dtype(), VariantStorage::storage_dtype) } /// Invokes `per_child` for fields selected by `field_mask`. @@ -223,8 +379,10 @@ mod tests { use vortex_session::registry::ReadContext; use super::*; + use crate::layout_children; use crate::layouts::flat::FlatLayout; use crate::segments::SegmentId; + use crate::test::SESSION; fn flat_child(dtype: DType, segment: u32) -> LayoutRef { FlatLayout::new(3, dtype, SegmentId::from(segment), ReadContext::new([])).into_layout() @@ -291,4 +449,72 @@ mod tests { Ok(()) } + + /// Reads `layout` back from the wire representation `id` and `metadata`. + fn read(layout: &LayoutRef, id: LayoutId, metadata: &[u8]) -> VortexResult { + let read_ctx = ReadContext::new([]); + let children = layout_children(layout.children()?); + StructPlugin.deserialize( + LayoutDeserialization { + serialized_id: id, + dtype: layout.dtype(), + row_count: layout.row_count(), + metadata, + segment_ids: vec![], + children: children.as_ref(), + }, + &LayoutBuildContext { + session: &SESSION, + array_read_ctx: &read_ctx, + }, + ) + } + + /// A struct layout of a struct keeps the contract of `vortex.struct`: no metadata. A struct + /// layout of a Variant is written as `vortex.variant`, and each wire ID reads only its own + /// dtype. + #[test] + fn variant_is_written_under_its_own_id() -> VortexResult<()> { + let i32 = DType::Primitive(PType::I32, Nullability::NonNullable); + let plain = StructLayout::new( + 3, + two_field_struct(Nullability::NonNullable), + vec![flat_child(i32.clone(), 0), flat_child(i32, 1)], + ) + .into_layout(); + let written = StructPlugin.serialize(plain.as_ref(), &SESSION)?; + assert_eq!(written.serialized_id, VTable::id(&Struct)); + assert!(written.metadata.is_empty()); + + // A nullable Variant is stored in a struct that is not nullable. + let dtype = DType::Variant(Nullability::Nullable); + let shredded = DType::Primitive(PType::I64, Nullability::Nullable); + let storage = StructLayout::new( + 3, + variant::storage_dtype(&dtype, shredded.clone()), + vec![ + flat_child(dtype.clone(), 0), + flat_child(shredded.clone(), 1), + ], + ) + .into_layout(); + let stored = StructLayout::try_new_variant(dtype, shredded, &storage, true)?; + assert_eq!(stored.nchildren(), 2); + assert_eq!(stored.slot_to_child(0), None); + let stored = stored.into_layout(); + + let written = StructPlugin.serialize(stored.as_ref(), &SESSION)?; + assert_eq!(written.serialized_id, variant::layout_id()); + let read_back = read(&stored, written.serialized_id, &written.metadata)?; + assert_eq!( + read_back.as_::().struct_fields(), + storage.as_::().struct_fields() + ); + + assert!(read(&stored, VTable::id(&Struct), &written.metadata).is_err()); + assert!(read(&plain, variant::layout_id(), &[]).is_err()); + // Bytes that decode to no known field are still metadata. + assert!(read(&plain, VTable::id(&Struct), &[0x18, 0x01]).is_err()); + Ok(()) + } } diff --git a/vortex-layout/src/layouts/struct_/reader.rs b/vortex-layout/src/layouts/struct_/reader.rs index 1b468498fae..b759d9ca41b 100644 --- a/vortex-layout/src/layouts/struct_/reader.rs +++ b/vortex-layout/src/layouts/struct_/reader.rs @@ -52,6 +52,7 @@ use crate::RowSplits; use crate::SplitRange; use crate::layouts::partitioned::PartitionedEval; use crate::layouts::struct_::StructLayout; +use crate::layouts::variant::VariantStorage; use crate::segments::SegmentSource; #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -89,6 +90,13 @@ pub struct StructReader { /// for every f in fields. expanded_root_expr: BoundExpression, + /// For a stored Variant, the Variant as an expression over the stored struct. + /// + /// Every expression over the Variant is rewritten with the Variant replaced by this + /// expression. Optimizing that turns an extraction of a shredded path into a read of the + /// field that holds it, which is then partitioned like any other. + variant: Option, + field_lookup: Option>, partitioned_expr_cache: DashMap>>, } @@ -113,7 +121,8 @@ impl StructReader { .collect() }); - let nullable = layout.dtype().is_nullable(); + let storage_dtype = layout.storage_dtype().clone(); + let nullable = storage_dtype.is_nullable(); let extra = nullable as usize; let mut dtypes: Vec = Vec::with_capacity(struct_dt.nfields() + extra); @@ -135,7 +144,12 @@ impl StructReader { ); // Create an expanded root expression that contains all fields of the struct. - let expanded_root_expr = expanded_struct_root(layout.dtype(), struct_dt)?; + let expanded_root_expr = expanded_struct_root(&storage_dtype, struct_dt)?; + let variant = layout + .data() + .as_ref() + .map(VariantStorage::variant) + .transpose()?; // This is where we need to do some complex things with the scan in order to split it into // different scans for different fields. @@ -144,6 +158,7 @@ impl StructReader { name, session, expanded_root_expr, + variant, lazy_children, field_lookup, partitioned_expr_cache: DashMap::with_hasher_and_shard_amount(Default::default(), 8), @@ -220,18 +235,36 @@ impl StructReader { Ok(cell.get_or_init(|| result).clone()) } + /// Rewrites `expr`, over a stored Variant, to an expression over the stored struct. + fn over_storage(&self, expr: &BoundExpression) -> VortexResult { + let Some(variant) = &self.variant else { + return Ok(expr.clone()); + }; + let expr = expr.clone().transform_down(|expr| { + if !expr.is_root() { + return Ok(Transformed::no(expr)); + } + Ok(Transformed { + value: variant.clone(), + order: TraversalOrder::Skip, + changed: true, + }) + })?; + expr.into_inner().optimize_recursive() + } + fn compute_partitioned_expr(&self, expr: &BoundExpression) -> VortexResult { // First, we expand the root scope into the fields of the struct to ensure // that partitioning works correctly. - let expr = - expand_struct_root(expr.clone(), &self.expanded_root_expr, self.struct_fields())?; + let expr = expand_struct_root( + self.over_storage(expr)?, + &self.expanded_root_expr, + self.struct_fields(), + )?; // Partition the expression into expressions that can be evaluated // over individual coordinates. - let fields = self - .dtype() - .as_struct_fields_opt() - .vortex_expect("struct dtype"); + let fields = self.struct_fields(); let mut partitioned = partition_bound(expr.clone(), make_struct_item_annotator(fields))?; if partitioned.partitions.len() == 1 { @@ -456,6 +489,14 @@ impl LayoutReader for StructReader { split_range: &SplitRange, splits: &mut RowSplits, ) -> VortexResult<()> { + // A field of a stored Variant can be in any of the stored fields. + let all = [FieldMask::All]; + let field_mask: &[FieldMask] = if self.variant.is_some() { + &all + } else { + field_mask + }; + if splits.mode() == BoundaryMode::PositionsOnly { if let Some(validity_ref) = self.validity()? { validity_ref.register_splits(field_mask, split_range, splits)?; diff --git a/vortex-layout/src/layouts/table.rs b/vortex-layout/src/layouts/table.rs index 08575a80515..e90f2a9c1de 100644 --- a/vortex-layout/src/layouts/table.rs +++ b/vortex-layout/src/layouts/table.rs @@ -28,6 +28,8 @@ use crate::LayoutStrategy; use crate::LayoutWriterContext; use crate::layouts::list::writer::ListLayoutStrategy; use crate::layouts::struct_::StructStrategy; +use crate::layouts::variant::VariantShreddingPolicy; +use crate::layouts::variant::VariantStrategy; use crate::segments::SegmentSinkRef; use crate::sequence::SendableSequentialStream; use crate::sequence::SequencePointer; @@ -61,6 +63,14 @@ pub struct TableStrategy { /// /// [`ListLayoutStrategy`]: ListLayoutStrategy list_layout_factory: Option, + /// Whether shredded Variant fields are written with [`VariantStrategy`]. + variant_layout: bool, + /// Chooses how to shred the Variant fields that are not shredded and have no override in + /// `variant_shredding_at`. + variant_shredding: Option>, + /// Chooses how to shred the Variant field at each path, relative to the level this + /// dispatcher sits at. The root path is the field this dispatcher writes. + variant_shredding_at: HashMap>, } impl TableStrategy { @@ -88,6 +98,9 @@ impl TableStrategy { validity, leaf: fallback, list_layout_factory: None, + variant_layout: false, + variant_shredding: None, + variant_shredding_at: HashMap::default(), } } @@ -175,6 +188,39 @@ impl TableStrategy { self.list_layout_factory = Some(Arc::new(factory)); self } + + /// Enable writing shredded Variant fields with [`VariantStrategy`], which stores the core + /// storage and each shredded field as columns of their own. + /// + /// **Note**: this is an unstable and experimental layout that is expected to change. + /// Using it may lead to unreadable files in the future. + pub fn with_variant_layout(mut self) -> Self { + self.variant_layout = true; + self + } + + /// Shred the Variant fields that are not shredded as `policy` chooses, so that + /// [`VariantStrategy`] has columns to split them into. A field with a policy of its own, set + /// with [`with_variant_shredding_at`](Self::with_variant_shredding_at), uses that instead. + /// + /// This has no effect without [`with_variant_layout`](Self::with_variant_layout). + pub fn with_variant_shredding(mut self, policy: Arc) -> Self { + self.variant_shredding = Some(policy); + self + } + + /// Shred the Variant field at `field_path` as `policy` chooses, if it is not shredded. The + /// root path is a Variant written on its own. + /// + /// This has no effect without [`with_variant_layout`](Self::with_variant_layout). + pub fn with_variant_shredding_at( + mut self, + field_path: impl Into, + policy: Arc, + ) -> Self { + self.variant_shredding_at.insert(field_path.into(), policy); + self + } } impl TableStrategy { @@ -188,7 +234,11 @@ impl TableStrategy { // The distinct named first-segments of our override paths are the only fields that need // anything other than the default dispatcher. let mut named_first: HashSet = HashSet::default(); - for path in self.leaf_writers.keys() { + for path in self + .leaf_writers + .keys() + .chain(self.variant_shredding_at.keys()) + { if let Some(Field::Name(name)) = path.parts().first() { named_first.insert(name.clone()); } @@ -239,11 +289,24 @@ impl TableStrategy { } } + // A path to the field itself becomes the root path, which applies to the field. + let mut new_shredding = HashMap::default(); + for (field_path, policy) in &self.variant_shredding_at { + if field_path.parts().first() == Some(field) + && let Some(subpath) = field_path.clone().step_into() + { + new_shredding.insert(subpath, Arc::clone(policy)); + } + } + Self { leaf_writers: new_writers, validity: Arc::clone(&self.validity), leaf: Arc::clone(&self.leaf), list_layout_factory: self.list_layout_factory.clone(), + variant_layout: self.variant_layout, + variant_shredding: self.variant_shredding.clone(), + variant_shredding_at: new_shredding, } } @@ -255,6 +318,9 @@ impl TableStrategy { validity: Arc::clone(&self.validity), leaf: Arc::clone(&self.leaf), list_layout_factory: self.list_layout_factory.clone(), + variant_layout: self.variant_layout, + variant_shredding: self.variant_shredding.clone(), + variant_shredding_at: HashMap::default(), } } @@ -305,6 +371,26 @@ impl LayoutStrategy for TableStrategy { .await; } + if dtype.is_variant() && self.variant_layout { + // The stored struct goes back through a clean dispatcher, so that its shredded + // child is split into columns, and a Variant in it is split in turn. + // A Variant inside the struct is the residual of a shredded object. The policy has + // seen its fields already, so it is written as it is. + let mut storage = self.descend_clean(); + storage.variant_shredding = None; + let mut strategy = VariantStrategy::new(Arc::new(storage), Arc::clone(&self.leaf)); + let policy = self + .variant_shredding_at + .get(&FieldPath::root()) + .or(self.variant_shredding.as_ref()); + if let Some(policy) = policy { + strategy = strategy.with_shredding(Arc::clone(policy)); + } + return strategy + .write_stream(ctx, segment_sink, stream, eof, session) + .await; + } + // Leaf: hand off to the leaf strategy. self.leaf .write_stream(ctx, segment_sink, stream, eof, session) diff --git a/vortex-layout/src/layouts/variant/mod.rs b/vortex-layout/src/layouts/variant/mod.rs new file mode 100644 index 00000000000..8c6eba4e637 --- /dev/null +++ b/vortex-layout/src/layouts/variant/mod.rs @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Stores a shredded Variant in a struct layout, as the struct of its core storage and its +//! shredded child. +//! +//! The struct is written like any other, so the shredded child, usually a struct itself, becomes +//! a column per shredded field. The struct layout reads the Variant as the pack of its columns, +//! so a scan that extracts a shredded path reads the column that holds it, and leaves the core +//! storage, which holds the bulk of the bytes, unread. +//! +//! **Note**: this is an unstable and experimental format that is expected to change. Using it may +//! lead to unreadable files in the future. + +pub mod writer; + +use prost::Message; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldName; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::get_item; +use vortex_array::expr::root; +use vortex_array::proto::dtype as pb; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; +use vortex_functions::expr::variant_pack; +use vortex_functions::expr::variant_pack_with_validity; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; +pub use writer::FixedShredding; +pub use writer::NoShredding; +pub use writer::StrictShredding; +pub use writer::UnionShredding; +pub use writer::VariantShreddingPolicy; +pub use writer::VariantStrategy; + +use crate::LayoutId; + +/// Name of the field of the stored struct that holds the core storage. +pub(crate) const CORE: &str = "core"; + +/// Name of the field of the stored struct that holds the shredded child. +pub(crate) const SHREDDED: &str = "shredded"; + +/// Name of the field of the stored struct that holds the validity of a shredded struct. +pub(crate) const VALIDITY: &str = "validity"; + +/// The wire ID of a struct layout that stores a shredded Variant. +/// +/// A struct layout of a struct is written as `vortex.struct`, whose contract is frozen. A struct +/// layout of a Variant is written under this ID, which is in the unstable edition. +pub fn layout_id() -> LayoutId { + static ID: CachedId = CachedId::new("vortex.variant"); + *ID +} + +/// Whether a shredded child of `shredded` dtype is stored without its validity, which is then a +/// column of its own. +/// +/// A scan cannot push a field read through a nullable struct, so a shredded struct, which is +/// null in the rows that are not objects, is stored as a struct that is not nullable. +pub(crate) fn splits_validity(shredded: &DType) -> bool { + shredded.is_struct() && shredded.is_nullable() +} + +/// The dtype of the struct that stores a Variant of `dtype` shredded as `shredded`. +pub(crate) fn storage_dtype(dtype: &DType, shredded: DType) -> DType { + let mut fields = vec![(FieldName::from(CORE), dtype.clone())]; + if splits_validity(&shredded) { + fields.push((FieldName::from(SHREDDED), shredded.as_nonnullable())); + fields.push(( + FieldName::from(VALIDITY), + DType::Bool(Nullability::NonNullable), + )); + } else { + fields.push((FieldName::from(SHREDDED), shredded)); + } + DType::Struct(StructFields::from_iter(fields), Nullability::NonNullable) +} + +/// How a struct layout stores a shredded Variant. +#[derive(Clone, Debug)] +pub struct VariantStorage { + /// The dtype of the stored struct. + storage_dtype: DType, + /// The dtype of the shredded child. + shredded_dtype: DType, + /// Whether the shredded child holds every value it could hold; see + /// [`VariantPackOptions::complete`](vortex_functions::variant_pack::VariantPackOptions::complete). + complete: bool, +} + +impl VariantStorage { + /// Stores a Variant of `dtype`, shredded as `shredded`. + /// + /// # Errors + /// + /// Returns an error if `dtype` is not a Variant. + pub(crate) fn try_new(dtype: &DType, shredded: DType, complete: bool) -> VortexResult { + vortex_ensure!( + dtype.is_variant(), + "a struct layout stores a shredded Variant only for a Variant dtype, found {dtype}" + ); + Ok(Self { + storage_dtype: storage_dtype(dtype, shredded.clone()), + shredded_dtype: shredded, + complete, + }) + } + + /// Reads how a Variant of `dtype` is stored from the `metadata` of its struct layout. + pub(crate) fn deserialize( + dtype: &DType, + metadata: &StructLayoutMetadata, + session: &VortexSession, + ) -> VortexResult { + let shredded = pb::DType::decode(metadata.shredded_dtype.as_slice()) + .map_err(|e| vortex_err!("invalid shredded dtype in struct layout: {e}"))?; + let shredded = DType::from_proto(&shredded, session)?; + Self::try_new(dtype, shredded, metadata.complete) + } + + /// The metadata of the struct layout that stores the Variant. + pub(crate) fn metadata(&self) -> StructLayoutMetadata { + let shredded = pb::DType::try_from(&self.shredded_dtype) + .map(|shredded| shredded.encode_to_vec()) + .unwrap_or_default(); + StructLayoutMetadata { + shredded_dtype: shredded, + complete: self.complete, + } + } + + /// The dtype of the stored struct. + pub(crate) fn storage_dtype(&self) -> &DType { + &self.storage_dtype + } + + /// The Variant, as an expression over the stored struct. + pub(crate) fn variant(&self) -> VortexResult { + let variant = if splits_validity(&self.shredded_dtype) { + variant_pack_with_validity( + get_item(CORE, root()), + get_item(SHREDDED, root()), + get_item(VALIDITY, root()), + self.complete, + ) + } else { + variant_pack( + get_item(CORE, root()), + get_item(SHREDDED, root()), + self.complete, + ) + }; + variant.bind(&self.storage_dtype) + } +} + +/// Serialized metadata of a struct layout. +/// +/// A struct layout of a struct has no metadata, so this message is empty for it. A struct layout +/// of a Variant records how the Variant is shredded. +#[derive(prost::Message)] +pub struct StructLayoutMetadata { + /// The dtype of the shredded child, as a serialized `vortex.dtype.DType`. + #[prost(bytes, tag = "1")] + shredded_dtype: Vec, + /// Whether the shredded child holds every value it could hold. + #[prost(bool, tag = "2")] + complete: bool, +} + +impl StructLayoutMetadata { + /// Whether the metadata records nothing, as for a struct layout of a struct. + pub(crate) fn is_empty(&self) -> bool { + self.shredded_dtype.is_empty() && !self.complete + } +} diff --git a/vortex-layout/src/layouts/variant/writer.rs b/vortex-layout/src/layouts/variant/writer.rs new file mode 100644 index 00000000000..62f39529fc9 --- /dev/null +++ b/vortex-layout/src/layouts/variant/writer.rs @@ -0,0 +1,409 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Writes a shredded Variant stream as a struct layout of the Variant. + +use std::fmt::Debug; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; + +use async_trait::async_trait; +use futures::StreamExt; +use futures::future; +use futures::stream; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ScalarFnArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VariantArray; +use vortex_array::arrays::struct_::StructArrayExt; +use vortex_array::arrays::variant::VariantArraySlotsExt; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::scalar_fn::ScalarFnRef; +use vortex_array::scalar_fn::ScalarFnVTableExt; +use vortex_array::validity::Validity; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_err; +use vortex_functions::variant_get::VariantGet; +use vortex_functions::variant_get::VariantGetOptions; +use vortex_functions::variant_get::VariantPath; +use vortex_functions::variant_shred::VariantShred; +use vortex_functions::variant_shred::VariantShredOptions; +use vortex_functions::variant_shred::VariantShredStrict; +use vortex_functions::variant_shred::VariantShredUnion; +use vortex_session::VortexSession; + +use super::CORE; +use super::SHREDDED; +use super::VALIDITY; +use super::splits_validity; +use super::storage_dtype; +use crate::LayoutRef; +use crate::LayoutStrategy; +use crate::LayoutWriterContext; +use crate::layouts::struct_::StructLayout; +use crate::segments::SegmentSinkRef; +use crate::sequence::SendableSequentialStream; +use crate::sequence::SequenceId; +use crate::sequence::SequencePointer; +use crate::sequence::SequentialStreamAdapter; +use crate::sequence::SequentialStreamExt; + +/// Chooses how to shred a Variant stream that is written unshredded. +/// +/// The policy chooses a shredding: a scalar function of one Variant, such as [`VariantShred`] +/// or [`VariantShredStrict`], that returns the Variant with a shredded child. The function says +/// both what to shred and what happens to a value that does not fit. The encoding of the +/// Variant storage does the work, through its kernel for the function, so every policy shreds +/// as fast as the encoding can. +pub trait VariantShreddingPolicy: Debug + Send + Sync { + /// The shredding of the stream, chosen from its `first` chunk. + /// + /// Every chunk of the stream is shredded by this function. Returns `None` to write the + /// stream unshredded. + fn shredding( + &self, + first: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult>; +} + +/// Shreds every Variant stream by one schema, and keeps a value that does not fit it in the +/// core storage, as Parquet shredding does; see [`VariantShred`]. +#[derive(Clone, Debug)] +pub struct FixedShredding { + schema: DType, +} + +impl FixedShredding { + /// Shreds by `schema`. + pub fn new(schema: DType) -> Self { + Self { schema } + } +} + +impl VariantShreddingPolicy for FixedShredding { + fn shredding( + &self, + _first: &ArrayRef, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + Ok(Some( + VariantShred.bind(VariantShredOptions::new(self.schema.clone())), + )) + } +} + +/// Shreds every Variant stream by one schema, and fails the write on a value that does not fit +/// it; see [`VariantShredStrict`]. +#[derive(Clone, Debug)] +pub struct StrictShredding { + schema: DType, +} + +impl StrictShredding { + /// Shreds by `schema`. + pub fn new(schema: DType) -> Self { + Self { schema } + } +} + +impl VariantShreddingPolicy for StrictShredding { + fn shredding( + &self, + _first: &ArrayRef, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + Ok(Some( + VariantShredStrict.bind(VariantShredOptions::new(self.schema.clone())), + )) + } +} + +/// Shreds every Variant stream by one schema, which can hold unions; see [`VariantShredUnion`]. +#[derive(Clone, Debug)] +pub struct UnionShredding { + schema: DType, +} + +impl UnionShredding { + /// Shreds by `schema`. + pub fn new(schema: DType) -> Self { + Self { schema } + } +} + +impl VariantShreddingPolicy for UnionShredding { + fn shredding( + &self, + _first: &ArrayRef, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + Ok(Some( + VariantShredUnion.bind(VariantShredOptions::new(self.schema.clone())), + )) + } +} + +/// Writes every Variant stream unshredded. Use it to turn a default policy off for one field. +#[derive(Clone, Copy, Debug, Default)] +pub struct NoShredding; + +impl VariantShreddingPolicy for NoShredding { + fn shredding( + &self, + _first: &ArrayRef, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + Ok(None) + } +} + +/// Writes a shredded Variant stream as the struct of its core storage and its shredded child. +/// +/// A stream whose first chunk is not shredded is shredded as the [`VariantShreddingPolicy`] +/// chooses, if there is one. Otherwise the stream has nothing to split, and is written by the +/// fallback strategy as it is. Every chunk of a shredded stream must be shredded alike. +/// +/// **Note**: this writes an unstable and experimental layout that is expected to change. Using +/// it may lead to unreadable files in the future. +#[derive(Clone)] +pub struct VariantStrategy { + /// Writes the struct of the core storage and the shredded child. + storage: Arc, + /// Writes a Variant stream that is not shredded. + fallback: Arc, + /// Chooses how to shred a stream that is not shredded. + shredding: Option>, +} + +impl VariantStrategy { + /// Creates a Variant writer that writes the struct of a shredded Variant through `storage`, + /// and a Variant that is not shredded through `fallback`. + pub fn new(storage: Arc, fallback: Arc) -> Self { + Self { + storage, + fallback, + shredding: None, + } + } + + /// Shreds a stream that is not shredded as `policy` chooses, instead of writing it through + /// the fallback. + pub fn with_shredding(mut self, policy: Arc) -> Self { + self.shredding = Some(policy); + self + } +} + +#[async_trait] +impl LayoutStrategy for VariantStrategy { + async fn write_stream( + &self, + ctx: LayoutWriterContext, + segment_sink: SegmentSinkRef, + mut stream: SendableSequentialStream, + eof: SequencePointer, + session: &VortexSession, + ) -> VortexResult { + let dtype = stream.dtype().clone(); + if !dtype.is_variant() { + vortex_bail!("VariantStrategy can only write Variant streams, got {dtype}"); + } + + // The dtype of a Variant does not say how it is shredded, so the first chunk decides. + let first = stream.next().await.transpose()?; + let shredded_dtype = |chunk: &ArrayRef| -> VortexResult> { + let variant = chunk + .clone() + .execute::(&mut session.create_execution_ctx())?; + Ok(variant.shredded().map(|shredded| shredded.dtype().clone())) + }; + // A stream that arrives shredded keeps its shredding. The policy only shreds one that + // does not. + let shredding = match (&first, &self.shredding) { + (Some((_, chunk)), Some(policy)) if shredded_dtype(chunk)?.is_none() => { + policy.shredding(chunk, &mut session.create_execution_ctx())? + } + _ => None, + }; + let shred = { + let session = session.clone(); + move |chunk: VortexResult<(SequenceId, ArrayRef)>| { + let Some(shredding) = &shredding else { + return chunk; + }; + let (sequence_id, chunk) = chunk?; + let shredded = ScalarFnArray::try_new(shredding.clone(), [chunk])? + .into_array() + .execute::(&mut session.create_execution_ctx())?; + Ok((sequence_id, shredded)) + } + }; + + let first = first.map(|chunk| shred(Ok(chunk))).transpose()?; + let shredded_dtype = first + .as_ref() + .map(|(_, chunk)| shredded_dtype(chunk)) + .transpose()? + .flatten(); + let stream = stream::iter(first.map(Ok)).chain(stream.map(shred)); + + let Some(shredded_dtype) = shredded_dtype else { + let stream = SequentialStreamAdapter::new(dtype, stream).sendable(); + return self + .fallback + .write_stream(ctx, segment_sink, stream, eof, session) + .await; + }; + + let complete = Arc::new(AtomicBool::new(true)); + let stream = { + let complete = Arc::clone(&complete); + let shredded_dtype = shredded_dtype.clone(); + let session = session.clone(); + stream.then(move |chunk| { + let result = chunk.and_then(|(sequence_id, chunk)| { + let mut ctx = session.create_execution_ctx(); + let (storage, chunk_complete) = split(chunk, &shredded_dtype, &mut ctx)?; + if !chunk_complete { + complete.store(false, Ordering::Relaxed); + } + Ok((sequence_id, storage)) + }); + future::ready(result) + }) + }; + let storage_dtype = storage_dtype(&dtype, shredded_dtype.clone()); + let storage = self + .storage + .write_stream( + ctx, + segment_sink, + SequentialStreamAdapter::new(storage_dtype, stream).sendable(), + eof, + session, + ) + .await?; + + // The stream is exhausted, so every chunk has reported whether it is complete. + Ok(StructLayout::try_new_variant( + dtype, + shredded_dtype, + &storage, + complete.load(Ordering::Relaxed), + )? + .into_layout()) + } +} + +/// Splits a Variant `chunk` into the struct of its core storage and its shredded child, of +/// `shredded_dtype`, and reports whether the shredded child is complete. +fn split( + chunk: ArrayRef, + shredded_dtype: &DType, + ctx: &mut ExecutionCtx, +) -> VortexResult<(ArrayRef, bool)> { + let len = chunk.len(); + let variant = chunk.execute::(ctx)?; + let shredded = variant + .shredded() + .ok_or_else(|| vortex_err!("only some chunks of a Variant stream are shredded"))? + .clone(); + let complete = is_complete(variant.core_storage(), &shredded, ctx)?; + + let shredded = if shredded.dtype() == shredded_dtype { + shredded + } else if shredded.dtype().eq_ignore_nullability(shredded_dtype) { + shredded.cast(shredded_dtype.clone())? + } else { + vortex_bail!( + "chunks of a Variant stream are shredded as {} and as {shredded_dtype}", + shredded.dtype() + ); + }; + // The core storage is written in its own encoding, not as a canonical Variant around it: + // the writers below slice their input, and a slice reaches the storage encoding directly. + let mut names = vec![CORE, SHREDDED]; + let mut fields = vec![variant.core_storage().clone()]; + if splits_validity(shredded_dtype) { + let shredded = shredded.execute::(ctx)?; + let validity = shredded.validity()?.execute_mask(len, ctx)?; + fields.push( + StructArray::try_new( + shredded.names().clone(), + shredded.iter_unmasked_fields().cloned().collect::>(), + len, + Validity::NonNullable, + )? + .into_array(), + ); + names.push(VALIDITY); + fields.push(validity.into_array()); + } else { + fields.push(shredded); + } + let storage = + StructArray::try_new(FieldNames::from(names), fields, len, Validity::NonNullable)?; + Ok((storage.into_array(), complete)) +} + +/// Whether `shredded` holds every value it could hold, so that `core` has no value for a path +/// that `shredded` represents; see +/// [`VariantPackOptions::complete`](vortex_functions::variant_pack::VariantPackOptions::complete). +/// +/// Only the rows where `shredded` is null can have left their value in `core`, so only those +/// rows of `core` are read. +fn is_complete(core: &ArrayRef, shredded: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { + let valid = shredded.validity()?.execute_mask(shredded.len(), ctx)?; + if valid.all_true() { + return Ok(true); + } + let core = core.filter(!&valid)?; + let mut has_no_value = |path: VariantPath, dtype: Option| -> VortexResult { + let values = VariantGet::try_new(core.clone(), VariantGetOptions::new(path, dtype))? + .into_array() + .execute::(ctx)?; + Ok(values + .validity()? + .execute_mask(values.len(), ctx)? + .all_false()) + }; + + match shredded.dtype() { + // A row that is not in a shredded struct must not be an object with a shredded field. + DType::Struct(fields, _) => { + for name in fields.names().iter() { + if !has_no_value(VariantPath::field(name.clone()), None)? { + return Ok(false); + } + } + // The struct is stored without its validity, so a field read must find a null in + // the rows where the struct was. + let fields = shredded.clone().execute::(ctx)?; + for field in fields.iter_unmasked_fields() { + let field = field.filter(!&valid)?; + if !field + .validity()? + .execute_mask(field.len(), ctx)? + .all_false() + { + return Ok(false); + } + } + Ok(true) + } + // A union is the whole Variant in the rows it holds, so a row that it does not hold must + // have no value at all. + DType::Union(..) => has_no_value(VariantPath::root(), None), + DType::Variant(_) | DType::List(..) | DType::FixedSizeList(..) => Ok(false), + // A row that is not in a shredded leaf must not hold a value of the leaf's dtype. + leaf => has_no_value(VariantPath::root(), Some(leaf.clone())), + } +} diff --git a/vortex-layout/src/lowering/segment_scan/execute.rs b/vortex-layout/src/lowering/segment_scan/execute.rs index f688041cfce..12b1b01090c 100644 --- a/vortex-layout/src/lowering/segment_scan/execute.rs +++ b/vortex-layout/src/lowering/segment_scan/execute.rs @@ -6,6 +6,11 @@ use std::ops::Range; use vortex_array::ArrayRef; +use vortex_array::ArraySlots; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::VariantArray; +use vortex_array::arrays::variant::VariantArraySlotsExt; use vortex_array::buffer::BufferHandle; use vortex_array::serde::SerializedArray; use vortex_error::VortexResult; @@ -21,6 +26,7 @@ use vortex_scan::execution::operator::Step; use vortex_session::VortexSession; use super::SegmentScanPlan; +use crate::arrays::shared::Shared; use crate::segments::SegmentId; /// Decodes the whole of a scan's segment. @@ -33,12 +39,43 @@ fn decode( Some(tree) => SerializedArray::from_flatbuffer_and_segment(tree.clone(), segment)?, None => SerializedArray::try_from(segment)?, }; - serialized.decode( + let array = serialized.decode( plan.dtype(), usize::try_from(plan.row_count())?, &plan.data().array_ctx, session, - ) + )?; + if array.dtype().is_variant() { + return share_variant_storage(array, session); + } + Ok(array) +} + +/// Shares the children of a Variant's core storage, so that each is decoded at most once however +/// many `variant_get` calls read it. +/// +/// Every extraction from an unshredded path decodes the metadata and the value of the storage. +/// Sharing keeps that lazy: a query that only reads shredded children never decodes them. +fn share_variant_storage(array: ArrayRef, session: &VortexSession) -> VortexResult { + let variant = array.execute::(&mut session.create_execution_ctx())?; + let core_storage = variant.core_storage(); + let slots = core_storage + .slots() + .iter() + .map(|slot| { + slot.as_ref().map(|child| { + // A Variant child is storage of its own, not a child that decodes. + if child.dtype().is_variant() { + child.clone() + } else { + Shared::new(child.clone()).into_array() + } + }) + }) + .collect::(); + // SAFETY: a shared array has the logical values of its source. + let core_storage = unsafe { core_storage.clone().with_slots(slots) }?; + Ok(VariantArray::try_new(core_storage, variant.shredded().cloned())?.into_array()) } /// Slices a whole decoded segment to `slice`, then keeps the rows `filter` selects. diff --git a/vortex-layout/src/session.rs b/vortex-layout/src/session.rs index bb8afedeb19..7f2780fa75c 100644 --- a/vortex-layout/src/session.rs +++ b/vortex-layout/src/session.rs @@ -21,7 +21,7 @@ use crate::layouts::dict::Dict; use crate::layouts::flat::Flat; use crate::layouts::indexed::Indexed; use crate::layouts::list::List; -use crate::layouts::struct_::Struct; +use crate::layouts::struct_::StructPlugin; use crate::layouts::zoned::LegacyStats; use crate::layouts::zoned::Zoned; @@ -77,7 +77,7 @@ impl Default for LayoutSession { // Register the built-in layout encodings. this.register(&Chunked as &dyn LayoutPlugin); this.register(&Flat as &dyn LayoutPlugin); - this.register(&Struct as &dyn LayoutPlugin); + this.register(&StructPlugin as &dyn LayoutPlugin); this.register(&Zoned as &dyn LayoutPlugin); this.register(&LegacyStats as &dyn LayoutPlugin); this.register(&Dict as &dyn LayoutPlugin); diff --git a/vortex-scan/src/plan/builtins/eval/execute.rs b/vortex-scan/src/plan/builtins/eval/execute.rs index 361e068a31f..0068e3b8284 100644 --- a/vortex-scan/src/plan/builtins/eval/execute.rs +++ b/vortex-scan/src/plan/builtins/eval/execute.rs @@ -3,8 +3,10 @@ //! Applying an expression to each batch. +use vortex_array::VortexSessionExecute; use vortex_array::expr::BoundExpression; use vortex_error::VortexResult; +use vortex_functions::variant_get::decode_for_repeated_extraction; use crate::execution::operator::Cx; use crate::execution::operator::Input; @@ -23,10 +25,15 @@ impl EvalStage { } impl Operator for EvalStage { - fn compute(&mut self, input: Input, _cx: &mut Cx<'_>) -> VortexResult { + fn compute(&mut self, input: Input, cx: &mut Cx<'_>) -> VortexResult { let Input::Batch(batch) = input else { return Ok(Step::End); }; + let batch = decode_for_repeated_extraction( + batch, + &self.expression, + &mut cx.session().create_execution_ctx(), + )?; Ok(Step::Final(batch.apply_bound(&self.expression)?)) } } diff --git a/vortex-scan/src/plan/builtins/eval/mod.rs b/vortex-scan/src/plan/builtins/eval/mod.rs index 1375eba6b52..87153febbaf 100644 --- a/vortex-scan/src/plan/builtins/eval/mod.rs +++ b/vortex-scan/src/plan/builtins/eval/mod.rs @@ -186,8 +186,9 @@ impl PlanParentReduceRule for EvalEvalRule { changed: true, }) })?; - // We want to fold repeated expressions like ($.a).b -> $.a.b. - let expr = expr.into_inner().optimize()?; + // We want to fold repeated expressions like ($.a).b -> $.a.b, wherever they are in the + // expression: under a comparison, say, in a filter. + let expr = expr.into_inner().optimize_recursive()?; let plan = EvalPlan::try_new(expr, child.child_plan()?)?; Ok(Some(plan.into_plan())) }