diff --git a/encodings/parquet-variant/src/array.rs b/encodings/parquet-variant/src/array.rs index 2414a90fbdf..a2335125fdd 100644 --- a/encodings/parquet-variant/src/array.rs +++ b/encodings/parquet-variant/src/array.rs @@ -18,12 +18,15 @@ use vortex_array::array_slots; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::List; use vortex_array::arrays::ListArray; +use vortex_array::arrays::ListViewArray; +use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::Struct; use vortex_array::arrays::StructArray; use vortex_array::arrays::Variant; use vortex_array::arrays::VariantArray; use vortex_array::arrays::list::ListArrayExt; use vortex_array::arrays::list::ListArraySlotsExt; +use vortex_array::arrays::listview::list_from_list_view; use vortex_array::arrays::struct_::StructArrayExt; use vortex_array::arrays::variant::VariantArraySlotsExt; use vortex_array::builtins::ArrayBuiltins; @@ -31,6 +34,7 @@ use vortex_array::dtype::DType; use vortex_array::dtype::FieldName; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; use vortex_array::optimizer::ArrayOptimizer; use vortex_array::scalar::Scalar; use vortex_array::validity::Validity; @@ -41,6 +45,7 @@ use vortex_arrow::ArrowSession; use vortex_arrow::ExecuteArrowExt; use vortex_arrow::level_validity; use vortex_arrow::to_arrow_null_buffer; +use vortex_buffer::BufferMut; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_err; @@ -182,12 +187,19 @@ pub(crate) fn logical_shredded_from_parquet_typed_value( typed_value: ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult { - if let Some(list_array) = typed_value.as_opt::() { - // Lists keep their original offsets and validity; only the physical element - // representation may need wrapper removal. + if typed_value.dtype().is_list() { + // Lists keep their offsets and validity. Each element reads its row's metadata, so the + // elements are taken from a `ListArray` whose offsets map elements to rows. + let list_array = match typed_value.as_opt::() { + Some(list_array) => list_array.into_owned(), + None => list_from_list_view(typed_value.execute::(ctx)?, ctx)?, + }; + let elements = list_array.elements().clone(); + let element_metadata = + element_metadata(metadata, list_array.offsets(), elements.len(), ctx)?; let elements = - logical_shredded_from_parquet_field(metadata, list_array.elements().clone(), ctx)? - .unwrap_or_else(|| list_array.elements().clone()); + logical_shredded_from_parquet_field(&element_metadata, elements.clone(), ctx)? + .unwrap_or(elements); return Ok(ListArray::try_new( elements, list_array.offsets().clone(), @@ -197,12 +209,12 @@ pub(crate) fn logical_shredded_from_parquet_typed_value( .into_array()); } - let Some(struct_array) = typed_value.as_opt::() else { + if !typed_value.dtype().is_struct() { return Ok(typed_value); - }; + } + let struct_array = typed_value.execute::(ctx)?; - // For object shredding, each struct field is a logical object field. Fields that - // are known wrapper shells without typed data are omitted from the canonical tree. + // For object shredding, each struct field is a logical object field. let mut names = Vec::new(); let mut fields = Vec::new(); for (name, field) in struct_array @@ -221,7 +233,7 @@ pub(crate) fn logical_shredded_from_parquet_typed_value( Ok(StructArray::try_new( FieldNames::from_iter(names), fields, - typed_value.len(), + struct_array.len(), struct_array.validity()?, )? .into_array()) @@ -229,36 +241,25 @@ pub(crate) fn logical_shredded_from_parquet_typed_value( /// Converts one Parquet shredded field to the corresponding canonical shredded child. /// -/// Returns `None` when the field is only a Parquet wrapper with no `typed_value`; that means the -/// logical field is not represented in shredded storage and must be served from raw `value`. +/// A wrapper with only a `value` column becomes an unshredded Variant child, because the Parquet +/// shredding spec keeps a shredded field's value in its own wrapper, not in the parent residual. +/// Returns `None` only for a wrapper with neither column. fn logical_shredded_from_parquet_field( metadata: &ArrayRef, field: ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - let Some(field_struct) = field.as_opt::() else { + if !field.dtype().is_struct() { return Ok(Some(field)); - }; + } + let field_struct = field.execute::(ctx)?; let only_parquet_fields = field_struct .names() .iter() .all(|name| matches!(name.as_ref(), "value" | "typed_value")); if only_parquet_fields { - let Some(typed_value) = field_struct.unmasked_field_by_name_opt("typed_value") else { - return Ok(None); - }; let validity = field_struct.validity()?; - // `unmasked_field_by_name_opt` intentionally ignores the parent struct validity. - // Reapply it here so null wrapper rows become null typed/raw rows downstream. - let typed_value = if validity.definitely_no_nulls() { - typed_value.clone() - } else { - typed_value - .clone() - .mask(validity.to_array(typed_value.len()))? - .optimize_ctx(ctx)? - }; let value = field_struct .unmasked_field_by_name_opt("value") .map(|value| { @@ -272,6 +273,26 @@ fn logical_shredded_from_parquet_field( } }) .transpose()?; + let Some(typed_value) = field_struct.unmasked_field_by_name_opt("typed_value") else { + let Some(value) = value else { + return Ok(None); + }; + let field_validity = inferred_shredded_field_validity(Some(&value), None, ctx)?; + let parquet_field = + ParquetVariant::try_new(field_validity, metadata.clone(), Some(value), None)?; + return VariantArray::try_new(parquet_field.into_array(), None) + .map(|array| Some(array.into_array())); + }; + // `unmasked_field_by_name_opt` intentionally ignores the parent struct validity. + // Reapply it here so null wrapper rows become null typed/raw rows downstream. + let typed_value = if validity.definitely_no_nulls() { + typed_value.clone() + } else { + typed_value + .clone() + .mask(validity.to_array(typed_value.len()))? + .optimize_ctx(ctx)? + }; let Some(value) = value else { // Fully shredded field: recurse through the typed subtree and expose its @@ -295,7 +316,29 @@ fn logical_shredded_from_parquet_field( .map(|array| Some(array.into_array())); } - logical_shredded_from_parquet_typed_value(metadata, field, ctx).map(Some) + logical_shredded_from_parquet_typed_value(metadata, field_struct.into_array(), ctx).map(Some) +} + +/// Returns the metadata of each list element: the metadata of the row whose list holds it. +fn element_metadata( + metadata: &ArrayRef, + offsets: &ArrayRef, + len: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let offsets = offsets + .cast(DType::Primitive(PType::U64, Nullability::NonNullable))? + .execute::(ctx)?; + + let mut rows = BufferMut::::zeroed(len); + for (row, bounds) in offsets.as_slice::().windows(2).enumerate() { + let start = usize::try_from(bounds[0])?; + let end = usize::try_from(bounds[1])?; + rows.get_mut(start..end) + .ok_or_else(|| vortex_err!("list offsets {start}..{end} exceed {len} elements"))? + .fill(row as u64); + } + metadata.take(rows.freeze().into_array()) } fn inferred_shredded_field_validity( @@ -747,6 +790,57 @@ mod tests { Ok(()) } + /// A shredded object field whose shell has only a `value` column holds its value there, not + /// in the residual object, so canonicalizing must keep the field. + #[test] + fn canonical_keeps_shredded_field_with_only_value() -> VortexResult<()> { + // Metadata with the dictionary `["a"]`, and the Variant int8 7. + let metadata = binary_view_array([b"\x01\x01\x00\x01a"]); + let a_value = binary_view_array([b"\x0c\x07"]); + let a_shell: ArrowArrayRef = Arc::new(StructArray::try_new( + vec![Arc::new(Field::new("value", DataType::BinaryView, true))].into(), + vec![a_value], + None, + )?); + let typed_value: ArrowArrayRef = Arc::new(StructArray::try_new( + vec![Arc::new(Field::new( + "a", + a_shell.data_type().clone(), + false, + ))] + .into(), + vec![a_shell], + None, + )?); + let residual: ArrowArrayRef = Arc::new({ + let mut builder = BinaryViewBuilder::new(); + builder.append_null(); + builder.finish() + }); + let struct_array = StructArray::try_new( + vec![ + Arc::new(Field::new("metadata", DataType::BinaryView, false)), + Arc::new(Field::new("value", DataType::BinaryView, true)), + Arc::new(Field::new( + "typed_value", + typed_value.data_type().clone(), + true, + )), + ] + .into(), + vec![metadata, residual, typed_value], + None, + )?; + + let arrow_variant = ArrowVariantArray::try_new(&struct_array)?; + let parquet_array = ParquetVariant::from_arrow_variant(&arrow_variant, &SESSION.arrow())?; + let mut ctx = SESSION.create_execution_ctx(); + let expected = parquet_array.execute_scalar(0, &mut ctx)?; + let canonical = parquet_array.execute::(&mut ctx)?.into_array(); + assert_eq!(canonical.execute_scalar(0, &mut ctx)?, expected); + Ok(()) + } + #[test] fn test_arrow_variant_import_value_and_typed_value_preserves_storage() -> VortexResult<()> { let metadata = binary_view_array([b"\x01\x00", b"\x01\x00"]); diff --git a/encodings/parquet-variant/src/extract.rs b/encodings/parquet-variant/src/extract.rs new file mode 100644 index 00000000000..49384096c16 --- /dev/null +++ b/encodings/parquet-variant/src/extract.rs @@ -0,0 +1,1091 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Extracts a path of object fields from unshredded Parquet Variant storage, reading the +//! [Variant encoding] in place. +//! +//! This covers the extractions a scan runs most: a string or an integer under a few object +//! fields, and structs and lists of them. Reading the bytes in place skips what the general +//! `variant_get` kernel does for every row and every path: building an Arrow array of the +//! storage, a `Variant` over each row, and a `Variant` over each object on the way down. A struct +//! reads the fields of each object in one pass, so it extracts several paths at once. +//! +//! The values that need no conversion are read from their bytes. Every other value is decoded and +//! converted with the `Variant` method that the general kernel converts it with, so the result is +//! the kernel's whatever a row holds. [`extract`] returns `None` only for an extraction it does +//! not cover at all, or for bytes that are not what the encoding says they are, and the caller +//! then falls back to the general kernel. +//! +//! [Variant encoding]: https://github.com/apache/parquet-format/blob/master/VariantEncoding.md + +use std::sync::Arc; + +use parquet_variant::Variant; +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::VarBinViewArray; +use vortex_array::arrays::varbinview::BinaryView; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldName; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::validity::Validity; +use vortex_buffer::BitBufferMut; +use vortex_buffer::BufferMut; +use vortex_buffer::ByteBufferMut; +use vortex_mask::Mask; + +/// Extracts `path`, a path of object fields, from each row of unshredded storage as `dtype`. +/// +/// `metadata` and `value` are the storage children, and `valid` the rows that hold a value. Each +/// value converts to `dtype` as the general kernel converts it, and a missing path, or a row +/// without a value, is a null. Returns `None` if [`covers`] does not cover `dtype`, or if the +/// bytes are not what the encoding says they are. +pub(crate) fn extract( + metadata: &VarBinViewArray, + value: &VarBinViewArray, + valid: &Mask, + path: &[&str], + dtype: &DType, +) -> Option { + let mut names = path + .iter() + .copied() + .map(FieldName::from) + .collect::>(); + let mut builder = Builder::new(dtype, &mut names, value.len())?; + let mut cache = FieldCache::new(&names); + + let depth = path.len(); + match &mut builder { + Builder::Utf8(utf8) => append_rows(utf8, &mut cache, metadata, value, valid, depth)?, + Builder::Int64(int64) => append_rows(int64, &mut cache, metadata, value, valid, depth)?, + nested => append_rows(nested, &mut cache, metadata, value, valid, depth)?, + } + + builder.finish() +} + +/// Whether [`extract`] covers extracting values as `dtype`. +/// +/// It covers strings, 64-bit integers, and structs and lists of them. The fields of a struct and +/// the elements of a list must be nullable, as a value that does not convert is a null. A struct +/// without fields is left to the general kernel, which cannot build one. +pub(crate) fn covers(dtype: &DType) -> bool { + match dtype { + DType::Utf8(_) | DType::Primitive(PType::I64, _) => true, + DType::Struct(fields, _) => { + fields.nfields() > 0 + && fields + .fields() + .all(|field| field.is_nullable() && covers(&field)) + } + DType::List(element, _) => element.is_nullable() && covers(element), + _ => false, + } +} + +/// Follows the first `depth` names of the cached names from `value`. +/// +/// Returns `Some(None)` if the path does not exist in the value, and `None` for bytes that are +/// cut short. +fn follow<'v>(fields: &Fields<'_>, mut value: &'v [u8], depth: usize) -> Option> { + for name in 0..depth { + // A value that is not an object has no fields. + let Some(object) = Object::new(value)? else { + return Some(None); + }; + match fields.find(&object, name)? { + Some(field) => value = field, + None => return Some(None), + } + } + Some(Some(value)) +} + +/// A dictionary without names. A primitive value has no fields, so it never reads the dictionary. +const EMPTY_METADATA: &[u8] = &[0x01, 0, 0]; + +/// Decodes the primitive `value` for a conversion of the general kernel. Returns `None` for bytes +/// that do not decode. +fn decode(value: &[u8]) -> Option> { + Variant::try_new(EMPTY_METADATA, value).ok() +} + +/// Appends the value of each row, which it converts to its dtype as the general kernel converts +/// it. +/// +/// The kernel converts a value to a string with [`Variant::as_string`], to an integer with +/// [`Variant::as_int64`], to a struct with [`Variant::as_object`], and to a list with +/// [`Variant::as_list`]. A value that does not convert is a null. +trait Append { + /// Appends `value`, converted to the builder's dtype. Returns `None` for bytes that are cut + /// short or do not decode. + fn append(&mut self, fields: &Fields<'_>, value: &[u8]) -> Option<()>; + + fn append_null(&mut self); +} + +/// Appends the extracted value of each row of the storage to `builder`. +/// +/// Generic over the builder, so that the loop of a string or an integer target is compiled for +/// that builder alone. +fn append_rows<'a, B: Append>( + builder: &mut B, + cache: &mut FieldCache<'a>, + metadata: &'a VarBinViewArray, + value: &VarBinViewArray, + valid: &Mask, + depth: usize, +) -> Option<()> { + for idx in 0..value.len() { + if !valid.value(idx) { + builder.append_null(); + continue; + } + let fields = cache.resolve(metadata, idx)?; + match follow(&fields, bytes_at(value, idx), depth)? { + Some(value) => builder.append(&fields, value)?, + None => builder.append_null(), + } + } + Some(()) +} + +/// Builds an extracted array of any dtype that [`covers`] covers. +enum Builder { + Utf8(Utf8Builder), + Int64(Int64Builder), + /// Reads each field from the field of the object of the same name. + Struct { + names: FieldNames, + /// The builder of each field, with the index of its name in the [`FieldCache`]. + fields: Vec<(usize, Builder)>, + validity: BitBufferMut, + }, + /// Reads each element from the element of the array. + List { + offsets: BufferMut, + elements: Box, + validity: BitBufferMut, + }, +} + +impl Builder { + /// A builder of `dtype`, which adds the field names of the structs in `dtype` to `names`. + /// + /// Returns `None` if [`covers`] does not cover `dtype`. + fn new(dtype: &DType, names: &mut Vec, capacity: usize) -> Option { + if !covers(dtype) { + return None; + } + Some(match dtype { + DType::Utf8(_) => Self::Utf8(Utf8Builder::new(capacity)), + DType::Primitive(..) => Self::Int64(Int64Builder::new(capacity)), + DType::Struct(struct_fields, _) => { + let mut fields = Vec::with_capacity(struct_fields.nfields()); + for (name, field_dtype) in struct_fields.names().iter().zip(struct_fields.fields()) + { + names.push(name.clone()); + let name = names.len() - 1; + fields.push((name, Self::new(&field_dtype, names, capacity)?)); + } + Self::Struct { + names: struct_fields.names().clone(), + fields, + validity: BitBufferMut::with_capacity(capacity), + } + } + DType::List(element, _) => { + let mut offsets = BufferMut::with_capacity(capacity + 1); + offsets.push(0); + Self::List { + offsets, + elements: Box::new(Self::new(element, names, capacity)?), + validity: BitBufferMut::with_capacity(capacity), + } + } + _ => return None, + }) + } + + /// Returns `None` if the strings do not fit the offsets of one buffer. + fn finish(self) -> Option { + Some(match self { + Self::Utf8(builder) => builder.finish()?, + Self::Int64(builder) => builder.finish(), + Self::Struct { + names, + fields, + validity, + } => { + let len = validity.len(); + let fields = fields + .into_iter() + .map(|(_, field)| field.finish()) + .collect::>>()?; + StructArray::try_new(names, fields, len, Validity::from(validity.freeze())) + .ok()? + .into_array() + } + Self::List { + offsets, + elements, + validity, + } => { + let elements = elements.finish()?; + let offsets = PrimitiveArray::new(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. + unsafe { + ListArray::new_unchecked( + elements, + offsets.into_array(), + Validity::from(validity.freeze()), + ) + } + .into_array() + } + }) + } +} + +impl Append for Builder { + fn append(&mut self, fields: &Fields<'_>, value: &[u8]) -> Option<()> { + match self { + Self::Utf8(builder) => builder.append(fields, value), + Self::Int64(builder) => builder.append(fields, value), + Self::Struct { + fields: builders, + validity, + .. + } => { + let object = Object::new(value)?; + for (name, builder) in builders.iter_mut() { + // Every field of a value that is not an object is null, as is the struct. + let field = match &object { + Some(object) => fields.find(object, *name)?, + None => None, + }; + match field { + Some(field) => builder.append(fields, field)?, + None => builder.append_null(), + } + } + validity.append(object.is_some()); + Some(()) + } + Self::List { + offsets, + elements, + validity, + } => { + let list = Elements::new(value)?; + let len = list.as_ref().map_or(0, |list| list.len); + for idx in 0..len { + let element = list.as_ref().and_then(|list| list.element(idx))?; + elements.append(fields, element)?; + } + let end = offsets.last().copied().unwrap_or_default(); + offsets.push(end + u64::try_from(len).ok()?); + validity.append(list.is_some()); + Some(()) + } + } + } + + fn append_null(&mut self) { + match self { + Self::Utf8(builder) => builder.append_null(), + Self::Int64(builder) => builder.append_null(), + Self::Struct { + fields, validity, .. + } => { + for (_, field) in fields { + field.append_null(); + } + validity.append(false); + } + Self::List { + offsets, validity, .. + } => { + let end = offsets.last().copied().unwrap_or_default(); + offsets.push(end); + validity.append(false); + } + } + } +} + +struct Utf8Builder { + views: BufferMut, + bytes: ByteBufferMut, + validity: BitBufferMut, +} + +impl Utf8Builder { + fn new(capacity: usize) -> Self { + Self { + views: BufferMut::with_capacity(capacity), + bytes: ByteBufferMut::empty(), + validity: BitBufferMut::with_capacity(capacity), + } + } + + #[inline] + fn push(&mut self, string: Option<&str>) { + self.validity.append(string.is_some()); + let string = string.unwrap_or_default().as_bytes(); + // The views are built here rather than by a builder, which would check the UTF-8 of every + // string a second time. The offset of an inlined string is not read, and `finish` checks + // that the offsets of the others fit. + let offset = u32::try_from(self.bytes.len()).unwrap_or(u32::MAX); + if string.len() > BinaryView::MAX_INLINED_SIZE { + self.bytes.extend_from_slice(string); + } + self.views.push(BinaryView::make_view(string, 0, offset)); + } + + /// Returns `None` if the strings do not fit the offsets of one buffer. + fn finish(self) -> Option { + u32::try_from(self.bytes.len()).ok()?; + // SAFETY: every view is either inlined or spans a string just copied to the only buffer, + // and each string was checked to be UTF-8 when it was read. + let array = unsafe { + VarBinViewArray::new_unchecked( + self.views.freeze(), + Arc::from([self.bytes.freeze()]), + DType::Utf8(Nullability::Nullable), + Validity::from(self.validity.freeze()), + ) + }; + Some(array.into_array()) + } +} + +impl Append for Utf8Builder { + #[inline] + fn append(&mut self, _fields: &Fields<'_>, value: &[u8]) -> Option<()> { + let header = *value.first()?; + let payload = &value[1..]; + let string = match (header & BASIC_TYPE_MASK, header >> 2) { + (SHORT_STRING, len) => Some(utf8(payload.get(..usize::from(len))?)?), + (PRIMITIVE, LONG_STRING) => { + let len = read_uint(payload, 4)?; + Some(utf8(payload.get(4..4 + len)?)?) + } + (OBJECT | ARRAY, _) => None, + // What `Variant::as_string` returns, which borrows from the variant and not from the + // value. + _ => match decode(value)? { + Variant::String(string) => Some(string), + Variant::ShortString(string) => Some(string.as_str()), + _ => None, + }, + }; + self.push(string); + Some(()) + } + + #[inline] + fn append_null(&mut self) { + self.push(None); + } +} + +struct Int64Builder { + values: BufferMut, + validity: BitBufferMut, +} + +impl Int64Builder { + fn new(capacity: usize) -> Self { + Self { + values: BufferMut::with_capacity(capacity), + validity: BitBufferMut::with_capacity(capacity), + } + } + + #[inline] + fn push(&mut self, integer: Option) { + self.values.push(integer.unwrap_or_default()); + self.validity.append(integer.is_some()); + } + + fn finish(self) -> ArrayRef { + PrimitiveArray::new(self.values.freeze(), Validity::from(self.validity.freeze())) + .into_array() + } +} + +impl Append for Int64Builder { + #[inline] + fn append(&mut self, _fields: &Fields<'_>, value: &[u8]) -> Option<()> { + let header = *value.first()?; + let payload = &value[1..]; + let integer = match (header & BASIC_TYPE_MASK, header >> 2) { + (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)?)), + (OBJECT | ARRAY, _) => None, + _ => decode(value)?.as_int64(), + }; + self.push(integer); + Some(()) + } + + #[inline] + fn append_null(&mut self) { + self.push(None); + } +} + +fn utf8(bytes: &[u8]) -> Option<&str> { + std::str::from_utf8(bytes).ok() +} + +/// The bytes of row `idx`, borrowed from `array`. +fn bytes_at(array: &VarBinViewArray, idx: usize) -> &[u8] { + let view = &array.views()[idx]; + if view.is_inlined() { + view.as_inlined().value() + } else { + let view = view.as_view(); + &array.buffer(view.buffer_index as usize).as_slice()[view.as_range()] + } +} + +/// How to find the fields of the cached names in the objects of rows that share one metadata. +#[derive(Clone, Copy)] +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]), + /// The dictionary holds one of the names more than once, so that the name has no single id. + /// The fields are found by name. + Names(Metadata<'a>, &'a [FieldName]), +} + +impl Fields<'_> { + /// The field of `object` with the cached name at index `name`, or `Some(None)` if the object + /// has no such field. + #[inline] + fn find<'v>(&self, object: &Object<'v>, name: usize) -> Option> { + match self { + Self::Ids(ids) => object.field_with_id(ids[name]), + Self::Names(metadata, names) => object.field(metadata, names[name].as_ref()), + } + } +} + +/// An id that is not in any dictionary: the ids of an object are at most four bytes wide. +const ABSENT: usize = usize::MAX; + +/// The [`Fields`] of a list of names, for the metadata of the rows seen most recently. +/// +/// Few rows have a metadata of their own: the rows of a table share a handful of shapes, and +/// the metadata child is dictionary encoded. Resolving the names against a metadata once turns +/// the lookup in every object from a binary search over names into a scan for an id. +/// +/// 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> { + names: &'a [FieldName], + /// The view of the metadata that each slot holds. + keys: Vec>, + /// The ids of the names for each slot, one run of `names.len()` ids per slot. + ids: Vec, + /// The metadata of each slot whose dictionary holds one of the names more than once. + duplicates: Vec>>, +} + +impl<'a> FieldCache<'a> { + const SLOTS: usize = 256; + + fn new(names: &'a [FieldName]) -> Self { + Self { + names, + keys: vec![None; Self::SLOTS], + ids: vec![ABSENT; Self::SLOTS * names.len()], + duplicates: vec![None; Self::SLOTS], + } + } + + /// The fields of the names for row `idx` of `metadata`. + #[inline] + 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); + let slot = usize::from(mixed.to_le_bytes()[7]); + let len = self.names.len(); + let ids = &mut self.ids[slot * len..(slot + 1) * len]; + + if self.keys[slot] != Some(key) { + // The slot is empty until its ids are complete, as a metadata that does not decode + // stops the fill part of the way through. + self.keys[slot] = None; + self.duplicates[slot] = Self::fill(self.names, ids, bytes_at(metadata, idx))?; + self.keys[slot] = Some(key); + } + + Some(match self.duplicates[slot] { + Some(metadata) => Fields::Names(metadata, self.names), + None => Fields::Ids(ids), + }) + } + + /// Writes the dictionary id of each name in `names` to `ids`. + /// + /// Returns the metadata if its dictionary holds one of the names more than once. + fn fill( + names: &[FieldName], + ids: &mut [usize], + metadata: &'a [u8], + ) -> Option>> { + let metadata = Metadata::new(metadata)?; + + // A path or a small struct has a number of names known when the scan compiles, so that + // the loop over the names unrolls. + if let Ok(ids) = <&mut [usize; 1]>::try_from(&mut *ids) { + return Self::scan(names, ids, metadata); + } + if let Ok(ids) = <&mut [usize; 2]>::try_from(&mut *ids) { + return Self::scan(names, ids, metadata); + } + if let Ok(ids) = <&mut [usize; 3]>::try_from(&mut *ids) { + return Self::scan(names, ids, metadata); + } + Self::scan(names, ids, metadata) + } + + /// Generic over the ids, so that each array length of [`Self::fill`] compiles a scan of + /// its own. + fn scan( + names: &[FieldName], + mut ids: impl AsMut<[usize]>, + metadata: Metadata<'a>, + ) -> Option>> { + let ids = ids.as_mut(); + ids.fill(ABSENT); + + // Every row of a table without a dictionary over its metadata misses, so this loop is + // hot. Each offset is read once, and the bytes of a name are compared only with names of + // the same length. + let mut offsets = metadata.offsets.chunks_exact(metadata.offset_size); + let mut start = read_uint(offsets.next()?, metadata.offset_size)?; + for (id, end) in offsets.take(metadata.len).enumerate() { + let end = read_uint(end, metadata.offset_size)?; + let len = end.checked_sub(start)?; + for (field, found) in names.iter().zip(ids.iter_mut()) { + let field = field.as_ref().as_bytes(); + if field.len() == len && metadata.names.get(start..end)? == field { + if *found != ABSENT { + return Some(Some(metadata)); + } + *found = id; + } + } + start = end; + } + Some(None) + } +} + +/// The first `N` bytes of `bytes`. +#[inline] +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 { + // 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 { + 1 => usize::from(*bytes.first()?), + 2 => usize::from(u16::from_le_bytes(array(bytes)?)), + 3 => { + let [low, mid, high] = array(bytes)?; + usize::from(low) | usize::from(mid) << 8 | usize::from(high) << 16 + } + 4 => usize::try_from(u32::from_le_bytes(array(bytes)?)).ok()?, + _ => return None, + }) +} + +/// 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; + +/// 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; + +/// The dictionary of field names of a Variant value. +#[derive(Clone, Copy)] +struct Metadata<'a> { + /// The number of names. + len: usize, + /// The width in bytes of an offset. + offset_size: usize, + /// The offsets of the names, one more than there are names. + offsets: &'a [u8], + /// The names, back to back. + names: &'a [u8], +} + +impl<'a> Metadata<'a> { + fn new(bytes: &'a [u8]) -> Option { + let header = *bytes.first()?; + let offset_size = usize::from(header >> 6) + 1; + let len = read_uint(bytes.get(1..)?, offset_size)?; + let offsets_start = 1 + offset_size; + let names_start = offsets_start + (len + 1) * offset_size; + Some(Self { + len, + offset_size, + offsets: bytes.get(offsets_start..names_start)?, + names: bytes.get(names_start..)?, + }) + } + + /// The name with dictionary id `id`. + fn name(&self, id: usize) -> Option<&'a [u8]> { + let start = read_uint(self.offsets.get(id * self.offset_size..)?, self.offset_size)?; + let end = read_uint( + self.offsets.get((id + 1) * self.offset_size..)?, + self.offset_size, + )?; + self.names.get(start..end) + } +} + +/// An object value: its field ids, sorted by field name, and the offsets of the field values. +struct Object<'a> { + len: usize, + id_size: usize, + offset_size: usize, + ids: &'a [u8], + offsets: &'a [u8], + values: &'a [u8], +} + +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> { + let header = *value.first()?; + if header & BASIC_TYPE_MASK != OBJECT { + return Some(None); + } + let header = header >> 2; + let offset_size = usize::from(header & 0b11) + 1; + let id_size = usize::from((header >> 2) & 0b11) + 1; + let len_size = if header & 0b1_0000 != 0 { 4 } else { 1 }; + + let len = read_uint(value.get(1..)?, len_size)?; + let ids_start = 1 + len_size; + let offsets_start = ids_start + len * id_size; + let values_start = offsets_start + (len + 1) * offset_size; + Some(Some(Self { + len, + id_size, + offset_size, + ids: value.get(ids_start..offsets_start)?, + offsets: value.get(offsets_start..values_start)?, + values: value.get(values_start..)?, + })) + } + + /// 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> { + 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); + }; + let offset = read_uint( + self.offsets.get(position * self.offset_size..)?, + self.offset_size, + )?; + Some(Some(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> { + let (mut low, mut high) = (0, self.len); + while low < high { + let mid = low + (high - low) / 2; + let id = read_uint(self.ids.get(mid * self.id_size..)?, self.id_size)?; + 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..)?)); + } + } + } + Some(None) + } +} + +/// An array value: the offsets of its elements, which follow one another. +struct Elements<'a> { + len: usize, + offset_size: usize, + offsets: &'a [u8], + values: &'a [u8], +} + +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> { + let header = *value.first()?; + if header & BASIC_TYPE_MASK != ARRAY { + return Some(None); + } + let header = header >> 2; + let offset_size = usize::from(header & 0b11) + 1; + let len_size = if header & 0b100 != 0 { 4 } else { 1 }; + + let len = read_uint(value.get(1..)?, len_size)?; + let offsets_start = 1 + len_size; + let values_start = offsets_start + (len + 1) * offset_size; + Some(Some(Self { + len, + offset_size, + offsets: value.get(offsets_start..values_start)?, + values: value.get(values_start..)?, + })) + } + + /// The value of element `idx`. + fn element(&self, idx: usize) -> Option<&'a [u8]> { + let offset = read_uint( + self.offsets.get(idx * self.offset_size..)?, + self.offset_size, + )?; + self.values.get(offset..) + } +} + +#[cfg(test)] +mod tests { + use std::sync::LazyLock; + + use arrow_array::ArrayRef as ArrowArrayRef; + use arrow_array::StringArray; + use parquet_variant::VariantPath as PqVariantPath; + use parquet_variant_compute::GetOptions; + use parquet_variant_compute::json_to_variant; + use parquet_variant_compute::variant_get; + use rstest::rstest; + use vortex_array::VortexSessionExecute; + use vortex_array::assert_arrays_eq; + use vortex_array::dtype::StructFields; + use vortex_arrow::ArrowSessionExt; + use vortex_error::VortexResult; + use vortex_error::vortex_err; + use vortex_session::VortexSession; + + use super::*; + use crate::ParquetVariant; + use crate::ParquetVariantArraySlotsExt; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); + + /// A string too long for the short string encoding, which holds at most 63 bytes. + fn long_string() -> String { + "x".repeat(100) + } + + /// An object with more fields than the one-byte count of a small object holds. + fn large_object() -> String { + let fields = (0..300) + .map(|idx| format!(r#""f{idx:03}":{idx}"#)) + .collect::>(); + format!("{{{}}}", fields.join(",")) + } + + /// Extracts `path` from `rows` as `dtype` in place, and with the general kernel. + /// + /// Returns the in-place result, if the extraction is covered, and the kernel's. + fn extract_both( + rows: &[String], + path: &str, + dtype: &DType, + ) -> VortexResult<(Option, ArrayRef)> { + let json: ArrowArrayRef = Arc::new(StringArray::from_iter_values(rows)); + let arrow_variant = json_to_variant(&json)?; + let arrow_storage: ArrowArrayRef = Arc::new(arrow_variant.clone().into_inner()); + let field = Arc::new(SESSION.arrow().to_arrow_field("", dtype)?); + let pq_path = if path.is_empty() { + PqVariantPath::default() + } else { + PqVariantPath::try_from(path)? + }; + let expected = variant_get( + &arrow_storage, + GetOptions::new_with_path(pq_path).with_as_type(Some(Arc::clone(&field))), + )?; + let expected = SESSION.arrow().from_arrow_array(expected, &field)?; + + let storage = ParquetVariant::from_arrow_variant(&arrow_variant, &SESSION.arrow())?; + let storage = storage.as_::(); + let mut ctx = SESSION.create_execution_ctx(); + let metadata = storage + .metadata() + .clone() + .execute::(&mut ctx)?; + let value = storage + .value() + .ok_or_else(|| vortex_err!("unshredded storage has a value"))? + .clone() + .execute::(&mut ctx)?; + let path = if path.is_empty() { + vec![] + } else { + path.split('.').collect::>() + }; + let actual = extract(&metadata, &value, &Mask::new_true(rows.len()), &path, dtype); + Ok((actual, expected)) + } + + fn utf8() -> DType { + DType::Utf8(Nullability::Nullable) + } + + fn int64() -> DType { + DType::Primitive(PType::I64, Nullability::Nullable) + } + + fn struct_of(fields: [(&str, DType); N]) -> DType { + DType::Struct(StructFields::from_iter(fields), Nullability::Nullable) + } + + fn list_of(element: DType) -> DType { + DType::List(Arc::new(element), Nullability::Nullable) + } + + /// A struct or a list is extracted as the general kernel extracts it, from rows whose values + /// at the path are objects, arrays, and neither, with fields and elements of every type. + #[rstest] + #[case::struct_at_the_root( + "", + struct_of([ + ("kind", utf8()), + ("time_us", int64()), + ("commit", struct_of([("collection", utf8()), ("rev", int64())])), + ]) + )] + #[case::struct_at_a_path("commit", struct_of([("collection", utf8()), ("rev", int64()), ("absent", utf8())]))] + #[case::list_of_strings("tags", list_of(utf8()))] + #[case::list_of_integers("nums", list_of(int64()))] + #[case::list_of_structs("items", list_of(struct_of([("n", int64())])))] + #[case::list_in_a_struct("", struct_of([("tags", list_of(utf8())), ("kind", utf8())]))] + fn extracts_structs_and_lists_as_the_kernel_does( + #[case] path: &str, + #[case] dtype: DType, + ) -> VortexResult<()> { + let rows = vec![ + r#"{"kind":"commit","time_us":5,"commit":{"collection":"post","rev":1},"tags":["a","b"],"nums":[1,2.5,"x",null],"items":[{"n":1},{"n":"two"},3]}"#.to_string(), + r#"{"kind":"identity","commit":"not an object","tags":"not a list","nums":[],"items":[]}"#.to_string(), + r#"{"kind":null,"commit":{"rev":2.0},"tags":[null,"c",{"x":1}],"nums":[300000000000]}"#.to_string(), + r#"{"other":true}"#.to_string(), + r#""a string""#.to_string(), + "[1,2,3]".to_string(), + large_object(), + ]; + + let (actual, expected) = extract_both(&rows, path, &dtype)?; + + let actual = actual.ok_or_else(|| vortex_err!("{path} as {dtype} must be covered"))?; + assert_arrays_eq!(actual, expected, &mut SESSION.create_execution_ctx()); + Ok(()) + } + + /// A value that does not convert is a null, so non-nullable fields and elements are not + /// covered, and neither are the dtypes the general kernel covers on its own. + #[rstest] + #[case::non_nullable_field(DType::Struct( + StructFields::from_iter([("a", DType::Utf8(Nullability::NonNullable))]), + Nullability::Nullable, + ))] + #[case::non_nullable_element(DType::List( + Arc::new(DType::Utf8(Nullability::NonNullable)), + Nullability::Nullable, + ))] + #[case::uncovered_field(struct_of([("a", DType::Bool(Nullability::Nullable))]))] + #[case::struct_without_fields(struct_of([]))] + fn does_not_cover_non_nullable_or_uncovered_children(#[case] dtype: DType) { + assert!(!covers(&dtype)); + } + + /// Whatever is extracted in place is what the general kernel extracts. + #[rstest] + #[case::field("kind", utf8())] + #[case::nested("commit.collection", utf8())] + #[case::deeply_nested("commit.record.text", utf8())] + #[case::integer("time_us", int64())] + #[case::nested_integer("commit.rev", int64())] + #[case::missing("absent", utf8())] + #[case::missing_nested("commit.absent", int64())] + #[case::field_of_a_large_object("f123", int64())] + fn extracts_what_the_kernel_extracts( + #[case] path: &str, + #[case] dtype: DType, + ) -> VortexResult<()> { + let rows = vec![ + // Short and long strings, and integers of every width. + format!( + r#"{{"kind":"commit","time_us":1732206349000167,"commit":{{"collection":"post","rev":1,"record":{{"text":"{}"}}}}}}"#, + long_string() + ), + r#"{"kind":"identity","time_us":-70000,"commit":{"collection":"","rev":-300}}"# + .to_string(), + r#"{"kind":"account","time_us":7,"commit":{"rev":3000000000}}"#.to_string(), + // An object without the field, a field that is not an object, and values that + // are not objects. + r#"{"other":true}"#.to_string(), + r#"{"kind":"commit","commit":"not an object"}"#.to_string(), + r#""a string""#.to_string(), + "[1,2,3]".to_string(), + large_object(), + ]; + + let (actual, expected) = extract_both(&rows, path, &dtype)?; + + let actual = actual.ok_or_else(|| vortex_err!("{path} as {dtype} must be covered"))?; + assert_arrays_eq!(actual, expected, &mut SESSION.create_execution_ctx()); + Ok(()) + } + + /// A value of another type than the one asked for converts as the general kernel converts + /// it, so a row of another type does not turn the extraction down. + #[rstest] + #[case::integer_as_string(r#"{"a":1}"#, utf8())] + #[case::double_as_string(r#"{"a":1.5}"#, utf8())] + #[case::boolean_as_string(r#"{"a":true}"#, utf8())] + #[case::null_as_string(r#"{"a":null}"#, utf8())] + #[case::object_as_string(r#"{"a":{"b":"x"}}"#, utf8())] + #[case::array_as_string(r#"{"a":["x"]}"#, utf8())] + #[case::string_as_integer(r#"{"a":"1"}"#, int64())] + #[case::null_as_integer(r#"{"a":null}"#, int64())] + #[case::boolean_as_integer(r#"{"a":true}"#, int64())] + #[case::fraction_as_integer(r#"{"a":1.5}"#, int64())] + #[case::whole_fraction_as_integer(r#"{"a":12.00}"#, int64())] + #[case::negative_fraction_as_integer(r#"{"a":-7.25}"#, int64())] + #[case::out_of_range_as_integer(r#"{"a":1e300}"#, int64())] + #[case::object_as_integer(r#"{"a":{"b":1}}"#, int64())] + #[case::array_as_integer(r#"{"a":[1]}"#, int64())] + fn converts_as_the_kernel_does(#[case] row: &str, #[case] dtype: DType) -> VortexResult<()> { + // Rows that are read without a conversion around the one that needs it. + let plain = if matches!(dtype, DType::Utf8(_)) { + r#"{"a":"x"}"# + } else { + r#"{"a":5}"# + }; + let rows = vec![plain.to_string(), row.to_string(), plain.to_string()]; + + let (actual, expected) = extract_both(&rows, "a", &dtype)?; + + let actual = actual.ok_or_else(|| vortex_err!("{row} as {dtype} must be covered"))?; + assert_arrays_eq!(actual, expected, &mut SESSION.create_execution_ctx()); + Ok(()) + } + + /// A dictionary may hold a name twice unless it is sorted, and an object may then use + /// either id. + #[rstest] + #[case::first_id(0)] + #[case::second_id(1)] + fn finds_a_field_whose_name_is_in_the_dictionary_twice(#[case] id: u8) -> VortexResult<()> { + // Version 1 with one-byte offsets, then two names, both "a". + let metadata = [0x01, 2, 0, 1, 2, b'a', b'a']; + // An object of one field, whose value is the short string "x". + let value = [0x02, 1, id, 0, 2, 0x05, b'x']; + let extracted = extract( + &VarBinViewArray::from_iter_bin([metadata]), + &VarBinViewArray::from_iter_bin([value]), + &Mask::new_true(1), + &["a"], + &utf8(), + ) + .ok_or_else(|| vortex_err!("not extracted in place"))?; + assert_arrays_eq!( + extracted, + VarBinViewArray::from_iter_nullable_str([Some("x")]), + &mut SESSION.create_execution_ctx() + ); + Ok(()) + } + + /// Rows that hold no value are null, whatever their bytes are. + #[test] + fn rows_without_a_value_are_null() -> VortexResult<()> { + let json: ArrowArrayRef = Arc::new(StringArray::from(vec![r#"{"a":"x"}"#, r#"{"a":"y"}"#])); + let storage = + ParquetVariant::from_arrow_variant(&json_to_variant(&json)?, &SESSION.arrow())?; + let storage = storage.as_::(); + let mut ctx = SESSION.create_execution_ctx(); + let metadata = storage + .metadata() + .clone() + .execute::(&mut ctx)?; + let value = storage + .value() + .ok_or_else(|| vortex_err!("unshredded storage has a value"))? + .clone() + .execute::(&mut ctx)?; + + let actual = extract( + &metadata, + &value, + &Mask::from_iter([true, false]), + &["a"], + &utf8(), + ) + .ok_or_else(|| vortex_err!("a string field must be covered"))?; + + assert_arrays_eq!( + actual, + VarBinViewArray::from_iter_nullable_str([Some("x"), None]), + &mut ctx + ); + Ok(()) + } +} diff --git a/encodings/parquet-variant/src/kernel.rs b/encodings/parquet-variant/src/kernel.rs index a550161e878..89aede5a832 100644 --- a/encodings/parquet-variant/src/kernel.rs +++ b/encodings/parquet-variant/src/kernel.rs @@ -22,11 +22,13 @@ use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::fns::all_non_distinct::AllNonDistinct; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; +use vortex_array::arrays::ConstantArray; use vortex_array::arrays::Dict; use vortex_array::arrays::Extension; use vortex_array::arrays::Filter; use vortex_array::arrays::Slice; use vortex_array::arrays::Struct; +use vortex_array::arrays::VarBinViewArray; use vortex_array::arrays::dict::TakeExecute; use vortex_array::arrays::dict::TakeExecuteAdaptor; use vortex_array::arrays::extension::ExtensionArrayExt; @@ -36,9 +38,11 @@ use vortex_array::arrays::scalar_fn::ExactScalarFn; use vortex_array::arrays::scalar_fn::ScalarFnArrayView; use vortex_array::arrays::slice::SliceExecuteAdaptor; use vortex_array::arrays::slice::SliceKernel; +use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; use vortex_array::kernel::ExecuteParentKernel; use vortex_array::optimizer::kernels::ArrayKernelsExt; +use vortex_array::scalar::Scalar; use vortex_array::scalar_fn::ScalarFnVTable; use vortex_arrow::ArrowExportOptions; use vortex_arrow::ArrowSession; @@ -59,6 +63,8 @@ use crate::ParquetVariant; use crate::ParquetVariantArrayExt; use crate::ParquetVariantArraySlotsExt; use crate::compute::AllNonDistinctParquetVariant; +use crate::extract::covers; +use crate::extract::extract; pub(crate) fn initialize(session: &VortexSession) { let kernels = session.kernels(); @@ -108,6 +114,28 @@ impl ExecuteParentKernel for VariantGetKernel { return Ok(None); } + // Residual storage without a value in any row holds no path, as for the rows of a + // shredded field that the typed column does not cover. Answer from the validity of the + // value alone, without decoding the metadata. This holds for any requested dtype, + // Variant included: a missing path is a null of it. + if array.typed_value().is_none() + && let Some(value) = array.value() + && value + .validity()? + .execute_mask(value.len(), ctx)? + .all_false() + { + return Ok(Some( + ConstantArray::new(Scalar::null(parent.dtype().clone()), array.len()).into_array(), + )); + } + + // A string or an integer under object fields of unshredded storage is read from the + // encoded bytes in place. Whatever that does not cover falls through to the kernel. + if let Some(extracted) = extract_in_place(&array, &parent, ctx)? { + return Ok(Some(extracted)); + } + let arrow_variant = array.to_arrow(&ArrowExportOptions::default(), ctx)?; let arrow_input: ArrowArrayRef = Arc::new(arrow_variant.into_inner()); let session = ctx.session().clone(); @@ -141,6 +169,45 @@ impl ExecuteParentKernel for VariantGetKernel { } } +/// Extracts with [`extract`], if it covers the extraction that `parent` asks of `array`. +fn extract_in_place( + array: &ArrayView<'_, ParquetVariant>, + parent: &ScalarFnArrayView<'_, VariantGet>, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let (Some(dtype), Some(value), None) = + (parent.options.dtype(), array.value(), array.typed_value()) + else { + return Ok(None); + }; + if !covers(dtype) { + return Ok(None); + } + let Some(path) = parent + .options + .path() + .elements() + .iter() + .map(|element| match element { + VariantPathElement::Field(name) => Some(name.as_ref()), + VariantPathElement::Index(_) => None, + }) + .collect::>>() + else { + return Ok(None); + }; + + 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 Some(extracted) = extract(&metadata, &value, &valid, &path, dtype) else { + return Ok(None); + }; + extracted.cast(parent.dtype().clone()).map(Some) +} + /// Performs the [`JsonToVariant`] conversion (and optional shredding) over JSON string storage. /// /// `JsonToVariant`'s definition lives in `vortex-json`; the registered `execute_parent` kernels @@ -306,26 +373,35 @@ mod tests { use arrow_schema::Field; use parquet_variant::Variant as PqVariant; use parquet_variant::VariantBuilder; + use parquet_variant_compute::ShreddedSchemaBuilder; use parquet_variant_compute::VariantArray as ArrowVariantArray; use parquet_variant_compute::VariantArrayBuilder; use parquet_variant_compute::json_to_variant; + use parquet_variant_compute::shred_variant; use rstest::rstest; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; + use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray as VortexStructArray; use vortex_array::arrays::VarBinArray; + 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::arrays::variant::decode_unshredded_storage; use vortex_array::assert_arrays_eq; use vortex_array::assert_nth_scalar_is_null; use vortex_array::dtype::DType as VortexDType; + use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; + use vortex_array::dtype::StructFields; + use vortex_array::expr::BoundExpression; + use vortex_array::expr::get_item; use vortex_array::expr::root; use vortex_array::optimizer::ArrayOptimizer; use vortex_array::validity::Validity; @@ -335,6 +411,7 @@ mod tests { use vortex_error::vortex_ensure; use vortex_error::vortex_err; use vortex_functions::expr::variant_get; + use vortex_functions::expr::variant_pack; use vortex_functions::variant_get::VariantPath; use vortex_functions::variant_get::VariantPathElement; use vortex_mask::Mask; @@ -1089,7 +1166,11 @@ mod tests { shredded.unmasked_field_by_name("a")?.dtype(), &VortexDType::Variant(Nullability::Nullable) ); - assert!(shredded.unmasked_field_by_name_opt("b").is_none()); + // `b` has only a `value` column, which holds its value, so it stays as a Variant field. + assert_eq!( + shredded.unmasked_field_by_name("b")?.dtype(), + &VortexDType::Variant(Nullability::Nullable) + ); let result = execute_variant_get( canonical, @@ -1105,6 +1186,499 @@ mod tests { Ok(()) } + /// Events shredded as `kind` and `commit.collection`, canonicalized. Only some events have a + /// `commit`, and `commit.rev` stays in the residual value of `commit`. + fn make_nested_shredded_events() -> VortexResult { + let json: ArrowArrayRef = Arc::new(StringArray::from(vec![ + r#"{"kind":"commit","commit":{"collection":"post","rev":1}}"#, + r#"{"kind":"identity"}"#, + r#"{"kind":"commit","commit":{"collection":"like","rev":2}}"#, + ])); + 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 parquet_array = ParquetVariant::from_arrow_variant(&shredded, &SESSION.arrow())?; + let mut ctx = SESSION.create_execution_ctx(); + let Canonical::Variant(canonical) = parquet_array.execute::(&mut ctx)? else { + return Err(vortex_err!("expected canonical variant array")); + }; + Ok(canonical.into_array()) + } + + /// The shapes in which a scan hands a Variant column to `variant_get`. + #[derive(Clone, Copy, Debug)] + enum Input { + Canonical, + Chunked, + Filtered, + } + + #[rstest] + #[case::canonical(Input::Canonical, &[0, 1, 2])] + #[case::chunked(Input::Chunked, &[0, 1, 2])] + #[case::filtered(Input::Filtered, &[0, 2])] + fn test_variant_get_nested_shredded_path( + #[case] input: Input, + #[case] rows: &[usize], + ) -> VortexResult<()> { + let events = make_nested_shredded_events()?; + let array = match input { + Input::Canonical => events, + Input::Chunked => ChunkedArray::try_new( + [events.slice(0..2)?, events.slice(2..3)?], + events.dtype().clone(), + )? + .into_array(), + Input::Filtered => events.filter(Mask::from_iter([true, false, true]))?, + }; + let mut ctx = SESSION.create_execution_ctx(); + + // `commit` is a partially shredded object, which holds the rest of the path. + let collection = [Some("post"), None, Some("like")]; + assert_arrays_eq!( + execute_variant_get( + array.clone(), + "$.commit.collection", + Some(VortexDType::Utf8(Nullability::Nullable)), + )?, + VarBinViewArray::from_iter_nullable_str(rows.iter().map(|&row| collection[row])), + &mut ctx + ); + + // A field that is not shredded comes from the residual value of `commit`. + let rev = [Some(1i64), None, Some(2)]; + assert_arrays_eq!( + execute_variant_get( + array, + "$.commit.rev", + Some(VortexDType::Primitive(PType::I64, Nullability::Nullable)), + )?, + PrimitiveArray::from_option_iter(rows.iter().map(|&row| rev[row])), + &mut ctx + ); + Ok(()) + } + + #[test] + fn test_variant_get_partially_shredded_struct_keeps_residual_fields() -> VortexResult<()> { + let events = make_nested_shredded_events()?; + let mut ctx = SESSION.create_execution_ctx(); + + let requested = VortexDType::Struct( + StructFields::new( + FieldNames::from(["collection", "rev"]), + vec![ + VortexDType::Utf8(Nullability::Nullable), + VortexDType::Primitive(PType::I64, Nullability::Nullable), + ], + ), + Nullability::Nullable, + ); + let expected = VortexStructArray::try_from_iter_with_validity( + [ + ( + "collection", + VarBinViewArray::from_iter_nullable_str([Some("post"), None, Some("like")]) + .into_array(), + ), + ( + "rev", + PrimitiveArray::from_option_iter([Some(1i64), None, Some(2)]).into_array(), + ), + ], + Validity::from_iter([true, false, true]), + )? + .into_array(); + + assert_arrays_eq!( + execute_variant_get(events, "$.commit", Some(requested))?, + expected, + &mut ctx + ); + Ok(()) + } + + #[test] + fn test_variant_get_filtered_shredded_list() -> VortexResult<()> { + let json: ArrowArrayRef = Arc::new(StringArray::from(vec![ + r#"{"a":1,"tags":[10,"x"]}"#, + r#"{"a":2,"tags":[30]}"#, + r#"{"a":3,"tags":[40,50]}"#, + ])); + let list_type = DataType::List(Arc::new(Field::new("item", DataType::Int32, true))); + let shredding = ShreddedSchemaBuilder::new() + .with_path("a", &DataType::Int32)? + .with_path("tags", &list_type)? + .build(); + let shredded = shred_variant(&json_to_variant(&json)?, &shredding)?; + let parquet_array = ParquetVariant::from_arrow_variant(&shredded, &SESSION.arrow())?; + let filtered = parquet_array.filter(Mask::from_iter([true, false, true]))?; + let mut ctx = SESSION.create_execution_ctx(); + + assert_arrays_eq!( + execute_variant_get( + filtered.clone(), + "$.a", + Some(VortexDType::Primitive(PType::I64, Nullability::Nullable)), + )?, + PrimitiveArray::from_option_iter([Some(1i64), Some(3)]), + &mut ctx + ); + assert_arrays_eq!( + execute_variant_get( + filtered.clone(), + "$.tags[0]", + Some(VortexDType::Primitive(PType::I64, Nullability::Nullable)), + )?, + PrimitiveArray::from_option_iter([Some(10i64), Some(40)]), + &mut ctx + ); + assert_arrays_eq!( + execute_variant_get( + filtered, + "$.tags[1]", + Some(VortexDType::Utf8(Nullability::Nullable)), + )?, + VarBinViewArray::from_iter_nullable_str([Some("x"), None]), + &mut ctx + ); + Ok(()) + } + + /// A chunked Variant builds one storage array, so that it compresses and deserializes as a + /// single array. + #[test] + fn test_chunked_storage_executes_to_one_storage_array() -> VortexResult<()> { + let first = make_unshredded_json_array(vec![Some(r#"{"a":1}"#), Some(r#"{"a":2}"#)])?; + let second = make_unshredded_json_array(vec![Some(r#"{"a":3}"#)])?; + let dtype = first.dtype().clone(); + let chunked = ChunkedArray::try_new([first, second], dtype)?.into_array(); + let mut ctx = SESSION.create_execution_ctx(); + + let Canonical::Variant(canonical) = chunked.clone().execute::(&mut ctx)? else { + return Err(vortex_err!("expected canonical variant array")); + }; + assert!(canonical.core_storage().is::()); + + let requested = VortexDType::Primitive(PType::I64, Nullability::Nullable); + assert_arrays_eq!( + execute_variant_get(chunked, "$.a", Some(requested))?, + PrimitiveArray::from_option_iter([Some(1i64), Some(2), Some(3)]), + &mut ctx + ); + Ok(()) + } + + /// Chunks of shredded storage build one storage array beside one shredded child, and keep + /// every value. + #[test] + fn test_chunked_shredded_storage_builds_one_storage_array() -> VortexResult<()> { + let json: ArrowArrayRef = Arc::new(StringArray::from(vec![ + r#"{"kind":"commit","n":1}"#, + r#"{"kind":"identity","n":2}"#, + r#"{"kind":"commit","n":3}"#, + ])); + let shredding = ShreddedSchemaBuilder::new() + .with_path("kind", &DataType::Utf8)? + .build(); + let shredded = shred_variant(&json_to_variant(&json)?, &shredding)?; + let storage = ParquetVariant::from_arrow_variant(&shredded, &SESSION.arrow())?; + let dtype = storage.dtype().clone(); + let chunked = ChunkedArray::try_new([storage.slice(0..2)?, storage.slice(2..3)?], dtype)? + .into_array(); + let mut ctx = SESSION.create_execution_ctx(); + + let Canonical::Variant(canonical) = chunked.clone().execute::(&mut ctx)? else { + return Err(vortex_err!("expected canonical variant array")); + }; + assert!(canonical.core_storage().is::()); + assert!(canonical.shredded().is_some()); + + assert_arrays_eq!( + execute_variant_get( + chunked.clone(), + "$.kind", + Some(VortexDType::Utf8(Nullability::Nullable)) + )?, + VarBinViewArray::from_iter_nullable_str([ + Some("commit"), + Some("identity"), + Some("commit") + ]), + &mut ctx + ); + let requested = VortexDType::Primitive(PType::I64, Nullability::Nullable); + assert_arrays_eq!( + execute_variant_get(chunked, "$.n", Some(requested))?, + PrimitiveArray::from_option_iter([Some(1i64), Some(2), Some(3)]), + &mut ctx + ); + Ok(()) + } + + /// The struct that the Variant layout stores for [`make_nested_shredded_events`]: the core + /// storage and the shredded child as fields, and an extraction of `path` as `dtype` from + /// the Variant packed back from them, optimized. + fn extraction_over_pack( + path: &str, + dtype: VortexDType, + complete: bool, + ) -> VortexResult<(ArrayRef, BoundExpression)> { + let events = make_nested_shredded_events()?; + let events = events.as_::(); + let shredded = events + .shredded() + .ok_or_else(|| vortex_err!("expected a shredded child"))? + .clone(); + let storage = VortexStructArray::try_new( + FieldNames::from(["core", "shredded"]), + vec![events.core_storage().clone(), shredded], + events.len(), + Validity::NonNullable, + )? + .into_array(); + + let packed = variant_pack( + get_item("core", root()), + get_item("shredded", root()), + complete, + ); + let expr = variant_get(packed, parse_path(path)?, Some(dtype)) + .bind(storage.dtype())? + .optimize_recursive()?; + Ok((storage, expr)) + } + + /// An extraction from a packed Variant reads the shredded child alone when it holds the + /// path, and the core storage alone when it does not. + #[rstest] + // A shredded leaf. + #[case::shredded("$.kind", &[Some("commit"), Some("identity"), Some("commit")], "shredded")] + // A leaf of a shredded object, which is a Variant of its own. + #[case::nested("$.commit.collection", &[Some("post"), None, Some("like")], "shredded")] + // A field that was not shredded is only in the core storage. + #[case::unshredded("$.other", &[None, None, None], "core")] + fn test_variant_get_over_complete_pack_reads_one_child( + #[case] path: &str, + #[case] expected: &[Option<&str>], + #[case] child: &str, + ) -> VortexResult<()> { + let utf8 = VortexDType::Utf8(Nullability::Nullable); + let (storage, expr) = extraction_over_pack(path, utf8, true)?; + + let read = expr.to_string(); + let other = if child == "core" { "shredded" } else { "core" }; + assert!(read.contains(child), "{read} must read {child}"); + assert!(!read.contains(other), "{read} must not read {other}"); + assert_arrays_eq!( + storage.apply_bound(&expr)?, + VarBinViewArray::from_iter_nullable_str(expected.iter().copied()), + &mut SESSION.create_execution_ctx() + ); + Ok(()) + } + + /// A shredded child that is not complete can have left a value in the core storage, so + /// the extraction keeps both. + #[test] + fn test_variant_get_over_partial_pack_reads_both_children() -> VortexResult<()> { + let utf8 = VortexDType::Utf8(Nullability::Nullable); + let (storage, expr) = extraction_over_pack("$.kind", utf8, false)?; + + let read = expr.to_string(); + assert!(read.contains("core") && read.contains("shredded"), "{read}"); + assert_arrays_eq!( + storage.apply_bound(&expr)?, + VarBinViewArray::from_iter_nullable_str([ + Some("commit"), + Some("identity"), + Some("commit") + ]), + &mut SESSION.create_execution_ctx() + ); + Ok(()) + } + + /// Decoding the storage once leaves a storage array whose children need no more decoding, + /// whether or not the Variant was filtered first, and extracts the same values. + #[rstest] + #[case::whole(false)] + #[case::filtered(true)] + fn test_decode_unshredded_storage(#[case] filtered: bool) -> VortexResult<()> { + let rows = vec![Some(r#"{"a":1}"#), Some(r#"{"a":2}"#), Some(r#"{"a":3}"#)]; + let array = make_unshredded_json_array(rows)?; + let (array, expected) = if filtered { + ( + array.filter(Mask::from_iter([true, false, true]))?, + [Some(1i64), Some(3)].as_slice(), + ) + } else { + (array, [Some(1i64), Some(2), Some(3)].as_slice()) + }; + let mut ctx = SESSION.create_execution_ctx(); + + let decoded = decode_unshredded_storage(array, &mut ctx)?; + + let variant = decoded.as_::(); + let storage = variant + .core_storage() + .as_opt::() + .ok_or_else(|| vortex_err!("expected parquet variant core storage"))?; + assert!(storage.metadata().is_canonical()); + assert!(storage.value().is_some_and(|value| value.is_canonical())); + assert_arrays_eq!( + execute_variant_get( + decoded, + "$.a", + Some(VortexDType::Primitive(PType::I64, Nullability::Nullable)), + )?, + PrimitiveArray::from_option_iter(expected.iter().copied()), + &mut ctx + ); + Ok(()) + } + + /// A shredded Variant is left alone: its extractions read the shredded children. + #[test] + fn test_decode_unshredded_storage_keeps_shredded() -> VortexResult<()> { + let events = make_nested_shredded_events()?; + let mut ctx = SESSION.create_execution_ctx(); + + let decoded = decode_unshredded_storage(events.clone(), &mut ctx)?; + + assert!(decoded.as_::().shredded().is_some()); + assert_arrays_eq!( + execute_variant_get( + decoded, + "$.kind", + Some(VortexDType::Utf8(Nullability::Nullable)), + )?, + execute_variant_get( + events, + "$.kind", + Some(VortexDType::Utf8(Nullability::Nullable)), + )?, + &mut ctx + ); + Ok(()) + } + + /// Rows whose value does not fit the shredded type stay in the residual value, and are + /// extracted from there into the positions the typed column leaves null. + #[rstest] + #[case::as_string(DataType::Utf8, VortexDType::Utf8(Nullability::Nullable))] + #[case::as_integer( + DataType::Int64, + VortexDType::Primitive(PType::I64, Nullability::Nullable) + )] + // Arrow reads the string "y" as true, so the shredded strings must convert as it does. + #[case::strings_as_boolean(DataType::Utf8, VortexDType::Bool(Nullability::Nullable))] + fn test_variant_get_fills_rows_the_shredded_column_lacks( + #[case] shredded_type: DataType, + #[case] requested: VortexDType, + ) -> VortexResult<()> { + let rows = vec![ + Some(r#"{"a":"x"}"#), + Some(r#"{"a":7}"#), + Some(r#"{"b":1}"#), + Some(r#"{"a":"y"}"#), + Some(r#"{"a":8}"#), + Some(r#"{"a":true}"#), + ]; + let unshredded = make_unshredded_json_array(rows.clone())?; + + let json: ArrowArrayRef = Arc::new(StringArray::from(rows)); + let shredding = ShreddedSchemaBuilder::new() + .with_path("a", &shredded_type)? + .build(); + let shredded = shred_variant(&json_to_variant(&json)?, &shredding)?; + let shredded = ParquetVariant::from_arrow_variant(&shredded, &SESSION.arrow())?; + let mut ctx = SESSION.create_execution_ctx(); + let Canonical::Variant(shredded) = shredded.execute::(&mut ctx)? else { + return Err(vortex_err!("expected canonical variant array")); + }; + + // Shredding must not change what a path extracts to. + let expected = execute_variant_get(unshredded, "$.a", Some(requested.clone()))?; + assert!( + !expected + .validity()? + .execute_mask(expected.len(), &mut ctx)? + .all_false(), + "the fixture must extract some values" + ); + assert_arrays_eq!( + execute_variant_get(shredded.into_array(), "$.a", Some(requested))?, + expected, + &mut ctx + ); + Ok(()) + } + + /// A chunk whose field `b` is shredded with only a `value` column, and an unshredded chunk, + /// canonicalize to one Variant whose shredded child is null in the rows of the unshredded + /// chunk. Those rows must read `b` from the core storage. + #[test] + fn test_variant_get_reads_core_for_rows_padded_by_canonicalization() -> VortexResult<()> { + // Metadata with the dictionary `["b"]`, and the short string "left". + let metadata = binary_view_array(&[b"\x01\x01\x00\x01b".as_slice()]); + let b_value = binary_view_array(&[b"\x11left".as_slice()]); + let b_shell: ArrowArrayRef = Arc::new(StructArray::try_new( + vec![Arc::new(Field::new("value", DataType::BinaryView, true))].into(), + vec![b_value], + None, + )?); + let typed_value: ArrowArrayRef = Arc::new(StructArray::try_new( + vec![Arc::new(Field::new( + "b", + b_shell.data_type().clone(), + false, + ))] + .into(), + vec![b_shell], + None, + )?); + let storage = StructArray::try_new( + vec![ + Arc::new(Field::new("metadata", DataType::BinaryView, false)), + Arc::new(Field::new("value", DataType::BinaryView, true)), + Arc::new(Field::new( + "typed_value", + typed_value.data_type().clone(), + true, + )), + ] + .into(), + vec![metadata, nullable_binary_view_array(&[None]), typed_value], + None, + )?; + let shredded = ParquetVariant::from_arrow_variant( + &ArrowVariantArray::try_new(&storage)?, + &SESSION.arrow(), + )?; + let unshredded = make_unshredded_json_array(vec![Some(r#"{"b":"right"}"#)])?; + + let dtype = shredded.dtype().clone(); + let chunked = ChunkedArray::try_new([shredded, unshredded], dtype)?.into_array(); + let mut ctx = SESSION.create_execution_ctx(); + let Canonical::Variant(canonical) = chunked.execute::(&mut ctx)? else { + return Err(vortex_err!("expected canonical variant array")); + }; + + assert_arrays_eq!( + execute_variant_get( + canonical.into_array(), + "$.b", + Some(VortexDType::Utf8(Nullability::Nullable)), + )?, + VarBinViewArray::from_iter_nullable_str([Some("left"), Some("right")]), + &mut ctx + ); + Ok(()) + } + #[test] fn test_variant_get_canonical_shredded_child_overrides_raw_core() -> VortexResult<()> { let canonical = make_canonical_raw_core_with_shredded_child()?; @@ -1195,4 +1769,35 @@ mod tests { Ok(()) } + + #[test] + fn test_variant_get_untyped_shredded_list_index() -> VortexResult<()> { + let json: ArrowArrayRef = Arc::new(StringArray::from(vec![ + r#"{"tags":[10,"x"]}"#, + r#"{"tags":[30]}"#, + r#"{"tags":[40,50]}"#, + ])); + let list_type = DataType::List(Arc::new(Field::new("item", DataType::Int32, true))); + let shredding = ShreddedSchemaBuilder::new() + .with_path("tags", &list_type)? + .build(); + let shredded = shred_variant(&json_to_variant(&json)?, &shredding)?; + let parquet_array = ParquetVariant::from_arrow_variant(&shredded, &SESSION.arrow())?; + let mut ctx = SESSION.create_execution_ctx(); + let canonical = parquet_array.execute::(&mut ctx)?.into_array(); + + let extracted = execute_variant_get(canonical, "$.tags[0]", None)?; + assert_eq!(extracted.len(), 3); + for (row, expected) in [10i32, 30, 40].into_iter().enumerate() { + let value = extracted.execute_scalar(row, &mut ctx)?; + assert_eq!( + value + .as_variant() + .value() + .and_then(|value| value.as_primitive().typed_value::()), + Some(expected) + ); + } + Ok(()) + } } diff --git a/encodings/parquet-variant/src/lib.rs b/encodings/parquet-variant/src/lib.rs index 26c3a9051cf..0112fe07c9e 100644 --- a/encodings/parquet-variant/src/lib.rs +++ b/encodings/parquet-variant/src/lib.rs @@ -30,6 +30,7 @@ mod arrow; mod arrow_properties; mod builder; mod compute; +mod extract; #[cfg(test)] mod json_to_variant_tests; mod kernel; diff --git a/vortex-array/src/arrays/variant/mod.rs b/vortex-array/src/arrays/variant/mod.rs index b7cbfe5a41c..74a953f729f 100644 --- a/vortex-array/src/arrays/variant/mod.rs +++ b/vortex-array/src/arrays/variant/mod.rs @@ -17,6 +17,10 @@ pub(crate) fn initialize(session: &vortex_session::VortexSession) { pub use self::vtable::merge_typed_scalar_as_variant; use crate::ArrayRef; +use crate::ArraySlots; +use crate::Canonical; +use crate::ExecutionCtx; +use crate::IntoArray; use crate::array::Array; use crate::array::ArrayParts; use crate::array::EmptyArrayData; @@ -75,6 +79,59 @@ impl Array { } } +/// Decodes the storage of an unshredded Variant `array`, so that every `variant_get` over it +/// reads the decoded children instead of decoding them again. +/// +/// A Variant with shredded children is returned as it is: an extraction usually reads a shredded +/// child, and decoding the storage would be wasted. +pub fn decode_unshredded_storage( + array: ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult { + vortex_ensure!( + array.dtype().is_variant(), + "expected a Variant, found {}", + array.dtype() + ); + let mut variant = array.execute::(ctx)?; + // The core storage can itself be lazy, such as a filter over the stored encoding. Execute it + // until it is the encoding that holds the children, which executes to itself. + loop { + if variant.shredded().is_some() { + return Ok(variant.into_array()); + } + let storage = variant + .core_storage() + .clone() + .execute::(ctx)?; + if storage.core_storage().encoding_id() == variant.core_storage().encoding_id() { + break; + } + variant = storage; + } + + 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 to decode. + if child.dtype().is_variant() { + Ok(child.clone()) + } else { + Ok(child.clone().execute::(ctx)?.into_array()) + } + }) + .transpose() + }) + .collect::>()?; + // SAFETY: executing a slot to its canonical form keeps its logical values. + let core_storage = unsafe { core_storage.clone().with_slots(slots) }?; + Ok(VariantArray::try_new(core_storage, None)?.into_array()) +} + #[cfg(test)] mod tests { use std::sync::LazyLock; diff --git a/vortex-array/src/arrays/variant/vtable/mod.rs b/vortex-array/src/arrays/variant/vtable/mod.rs index 5ef9fb108e5..e3d4afeb340 100644 --- a/vortex-array/src/arrays/variant/vtable/mod.rs +++ b/vortex-array/src/arrays/variant/vtable/mod.rs @@ -173,6 +173,7 @@ pub fn merge_typed_scalar_as_variant( } fn typed_list_as_variant_payload(typed_scalar: Scalar) -> VortexResult { + let element_dtype = DType::Variant(Nullability::NonNullable); let list = typed_scalar.as_list(); let elements = list .elements() @@ -180,14 +181,18 @@ fn typed_list_as_variant_payload(typed_scalar: Scalar) -> VortexResult { .into_iter() .map(|element| { if element.dtype().is_variant() { - element + if element.is_null() { + Ok(Scalar::variant(Scalar::null(DType::Null))) + } else { + element.cast(&element_dtype) + } } else { - Scalar::variant(element) + Ok(Scalar::variant(element)) } }) - .collect(); + .collect::>>()?; Ok(Scalar::list( - DType::Variant(Nullability::NonNullable), + element_dtype, elements, Nullability::NonNullable, )) diff --git a/vortex-btrblocks/src/builder.rs b/vortex-btrblocks/src/builder.rs index b19c511ec0c..4e356e53ed3 100644 --- a/vortex-btrblocks/src/builder.rs +++ b/vortex-btrblocks/src/builder.rs @@ -32,7 +32,8 @@ use crate::schemes::string; pub(crate) enum CompressionMode { /// Excludes nothing. Set by [`empty`](BtrBlocksCompressorBuilder::empty). All, - /// Excludes Zstd and Pco. Set by [`from_session`](BtrBlocksCompressorBuilder::from_session). + /// Excludes Zstd and Pco, except that Zstd stays for the binary storage of Variant arrays. + /// Set by [`from_session`](BtrBlocksCompressorBuilder::from_session). Default, /// Excludes buffer-level Zstd, keeping Zstd for strings and binary and Pco for numerics. /// Set by [`with_compact`](BtrBlocksCompressorBuilder::with_compact). @@ -96,6 +97,20 @@ impl CompressionMode { excluded } + /// Returns the schemes of [`excluded_schemes`](Self::excluded_schemes) that + /// [`build`](BtrBlocksCompressorBuilder::build) keeps for the storage children of Variant + /// arrays. + /// + /// An unshredded Variant value is an opaque binary blob that the lightweight schemes cannot + /// compress, so the default preset would otherwise store it raw. + fn variant_storage_schemes(self) -> Vec { + match self { + #[cfg(feature = "zstd")] + Self::Default => vec![binary::ZstdScheme.id()], + _ => Vec::new(), + } + } + /// Returns the serialized IDs [`build`](BtrBlocksCompressorBuilder::build) disallows in this /// mode, on top of the session's restrictions. fn excluded_encodings(self) -> Vec { @@ -234,11 +249,32 @@ impl BtrBlocksCompressorBuilder { /// Builds the configured [`BtrBlocksCompressor`] from the schemes that its preset does not /// exclude and whose produced serialized IDs are all allowed. pub fn build(self) -> BtrBlocksCompressor { - BtrBlocksCompressor(CascadingCompressor::new(self.allowed_schemes())) + let compressor = CascadingCompressor::new(self.allowed_schemes()); + // A second compressor is only needed when the storage keeps a scheme the preset drops. + let compressor = if self.mode.variant_storage_schemes().is_empty() { + compressor + } else { + compressor.with_variant_storage_compressor(CascadingCompressor::new( + self.variant_storage_schemes(), + )) + }; + BtrBlocksCompressor(compressor) } fn allowed_schemes(&self) -> Vec<&'static dyn Scheme> { - let excluded: HashSet = self.mode.excluded_schemes().into_iter().collect(); + self.schemes_without(self.mode.excluded_schemes()) + } + + /// The schemes that compress the storage children of Variant arrays. + fn variant_storage_schemes(&self) -> Vec<&'static dyn Scheme> { + let kept = self.mode.variant_storage_schemes(); + let mut excluded = self.mode.excluded_schemes(); + excluded.retain(|id| !kept.contains(id)); + self.schemes_without(excluded) + } + + fn schemes_without(&self, excluded: Vec) -> Vec<&'static dyn Scheme> { + let excluded: HashSet = excluded.into_iter().collect(); let excluded_ids: HashSet = self.mode.excluded_encodings().into_iter().collect(); let allowed = |id: &ArrayId| self.allowed.is_allowed(id) && !excluded_ids.contains(id); self.schemes @@ -312,6 +348,33 @@ mod tests { assert_eq!(!builder.allowed_schemes().is_empty(), retained); } + #[cfg(feature = "zstd")] + #[test] + fn default_keeps_binary_zstd_only_for_variant_storage() { + let builder = BtrBlocksCompressorBuilder::from_session(&SESSION).unrestricted(); + let has_zstd = |schemes: Vec<&'static dyn Scheme>, id: SchemeId| { + schemes.iter().any(|scheme| scheme.id() == id) + }; + + assert!(!has_zstd( + builder.allowed_schemes(), + binary::ZstdScheme.id() + )); + assert!(has_zstd( + builder.variant_storage_schemes(), + binary::ZstdScheme.id() + )); + // Strings inside a Variant are not storage, and buffer-level Zstd stays opt-in. + assert!(!has_zstd( + builder.variant_storage_schemes(), + string::ZstdScheme.id() + )); + assert!(!has_zstd( + builder.variant_storage_schemes(), + binary::ZstdBuffersScheme.id() + )); + } + #[test] fn delta_is_excluded_only_by_cuda() { let builder = BtrBlocksCompressorBuilder::from_session(&SESSION).unrestricted(); diff --git a/vortex-compressor/src/compressor/cascade.rs b/vortex-compressor/src/compressor/cascade.rs index c8f2d430230..5f6c8bd4319 100644 --- a/vortex-compressor/src/compressor/cascade.rs +++ b/vortex-compressor/src/compressor/cascade.rs @@ -270,7 +270,11 @@ impl CascadingCompressor { } else { variant_array.core_storage().clone() }; - let core_storage = self.compress_physical_slots(&core_storage, exec_ctx)?; + let core_storage = self + .variant_storage + .as_deref() + .unwrap_or(self) + .compress_physical_slots(&core_storage, exec_ctx)?; let shredded = variant_array .shredded() .map(|arr| { diff --git a/vortex-compressor/src/compressor/mod.rs b/vortex-compressor/src/compressor/mod.rs index 19199d77365..6fc9d050868 100644 --- a/vortex-compressor/src/compressor/mod.rs +++ b/vortex-compressor/src/compressor/mod.rs @@ -9,6 +9,8 @@ mod sample; mod select; mod structural; +use std::sync::Arc; + pub(crate) use cascade::TrialOutput; pub(crate) use cascade::exact_uncompressed_size; pub(crate) use sample::estimate_compression_ratio_with_sampling; @@ -52,6 +54,9 @@ pub struct CascadingCompressor { /// Descendant exclusion rules for the compressor's own cascading (e.g. excluding Dict from /// list offsets). root_exclusions: Vec, + + /// Compresses the storage children of Variant arrays in place of this compressor, if set. + variant_storage: Option>, } impl CascadingCompressor { @@ -69,8 +74,19 @@ impl CascadingCompressor { Self { schemes, root_exclusions, + variant_storage: None, } } + + /// Compresses the storage children of Variant arrays with `compressor` instead of this one. + /// + /// The storage of a Variant holds opaque binary values, such as its unshredded value, which + /// can warrant other schemes than the binary columns of a table. Shredded children are still + /// compressed by this compressor. + pub fn with_variant_storage_compressor(mut self, compressor: CascadingCompressor) -> Self { + self.variant_storage = Some(Arc::new(compressor)); + self + } } // NB: Cascading compression logic is located in `vortex-compressor/src/compressor/cascade.rs`. diff --git a/vortex-datafusion/src/convert/exprs/mod.rs b/vortex-datafusion/src/convert/exprs/mod.rs index 1165eb2f6e2..77a7c7affe9 100644 --- a/vortex-datafusion/src/convert/exprs/mod.rs +++ b/vortex-datafusion/src/convert/exprs/mod.rs @@ -36,6 +36,7 @@ use datafusion_physical_expr::DynamicFilterTracking; use datafusion_physical_expr::HigherOrderFunctionExpr; use datafusion_physical_expr::PhysicalExpr; use datafusion_physical_expr::ScalarFunctionExpr; +use datafusion_physical_expr::projection::ProjectionExpr; use datafusion_physical_expr::projection::ProjectionExprs; use datafusion_physical_expr::utils::collect_columns; use datafusion_physical_plan::expressions as df_expr; @@ -68,8 +69,11 @@ use vortex::expr::strpos; use vortex::expr::traversal::NodeExt; use vortex::expr::traversal::Transformed; use vortex::expr::var; +use vortex::expr::variant_get; use vortex::functions::like::Like; use vortex::functions::like::LikeOptions; +use vortex::functions::variant_get::VariantPath; +use vortex::functions::variant_get::VariantPathElement; use vortex::layout::layouts::row_idx; use vortex::scalar::Scalar; use vortex::scalar_fn::ScalarFnVTableExt; @@ -81,6 +85,9 @@ use vortex_arrow::ArrowSessionExt; use crate::row_index::RowIndex; +/// Name of the Variant extraction function of datafusion-variant. +const TRY_VARIANT_GET: &str = "try_variant_get"; + /// Result of splitting a projection into Vortex expressions and leftover DataFusion projections. pub struct ProcessedProjection { /// Projection evaluated by the Vortex scan. @@ -157,19 +164,40 @@ pub trait ExpressionConverter: Send + Sync { { return self.no_pushdown_projection(source_projection, input_schema); } - let mut scan_projection = Vec::with_capacity(source_projection.as_ref().len()); - for projection in source_projection.as_ref() { + // The scan evaluates each distinct expression once. DataFusion can ask for the same + // expression under several aliases, such as a `variant_get` that it hoists out of both a + // filter and a group key. + let output_fields = output_schema.fields(); + let mut scan_projection: Vec<(String, Expression)> = Vec::new(); + let mut scan_indices: Vec = Vec::new(); + let mut leftover_projection = Vec::with_capacity(source_projection.as_ref().len()); + for (idx, projection) in source_projection.as_ref().iter().enumerate() { let Some(expr) = self.try_convert(&projection.expr, input_schema)? else { return self.no_pushdown_projection(source_projection, input_schema); }; - scan_projection.push((projection.alias.clone(), expr)); + let output_type = output_fields[idx].data_type(); + let scan_idx = match scan_projection.iter().zip(&scan_indices).position( + |((_, scan), &scan_field_idx)| { + *scan == expr && output_fields[scan_field_idx].data_type() == output_type + }, + ) { + Some(scan_idx) => scan_idx, + None => { + scan_indices.push(idx); + scan_projection.push((projection.alias.clone(), expr)); + scan_projection.len() - 1 + } + }; + leftover_projection.push(ProjectionExpr::new( + Arc::new(df_expr::Column::new(&scan_projection[scan_idx].0, scan_idx)), + projection.alias.clone(), + )); } // The output schema names its fields after the projection aliases. - let output_indices = (0..scan_projection.len()).collect_vec(); Ok(ProcessedProjection { scan_projection: pack(scan_projection, Nullability::NonNullable), - scan_reference_schema: output_schema.clone(), - leftover_projection: ProjectionExprs::from_indices(&output_indices, output_schema), + scan_reference_schema: output_schema.project(&scan_indices)?, + leftover_projection: ProjectionExprs::new(leftover_projection), }) } @@ -786,6 +814,10 @@ impl DefaultExpressionConverter { return self.convert_array_sum(scalar_fn, schema, input_dtype); } + if scalar_fn.name() == TRY_VARIANT_GET { + return self.convert_variant_get(scalar_fn, schema, input_dtype); + } + let (input, length): (_, fn(Expression) -> Expression) = if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { let [input] = scalar_fn.args() else { @@ -823,6 +855,61 @@ impl DefaultExpressionConverter { Ok(cast(length(input), return_dtype)) } + /// Converts `try_variant_get(variant, path, type)` to the Vortex `variant_get`, so that the + /// scan reads a shredded path from its typed column instead of materializing the whole Variant. + /// + /// The function is matched by name, because it is not part of DataFusion: it has the contract + /// of [datafusion-variant], where `try_variant_get` returns null for a missing path or a value + /// that does not cast to the requested type (`CastOptions { safe: true }`), matching Vortex's + /// `variant_get` extraction. `variant_get` raises an error on failed casts (`safe: false`) and + /// is left in DataFusion. + /// + /// Only the typed form over a `$`-rooted path of plain object fields (`$.field(.field)*`) + /// converts. + /// + /// [datafusion-variant]: https://github.com/datafusion-contrib/datafusion-variant + fn convert_variant_get( + &self, + scalar_fn: &ScalarFunctionExpr, + schema: &Schema, + input_dtype: &DType, + ) -> Conversion { + let [input, path, _type] = scalar_fn.args() else { + return Err(Unconverted::Unsupported); + }; + let Some(Some(path)) = path + .downcast_ref::() + .map(|literal| literal.value().try_as_str().flatten()) + else { + return Err(Unconverted::Unsupported); + }; + let Some(fields) = path.strip_prefix("$.") else { + return Err(Unconverted::Unsupported); + }; + let is_field = |field: &str| { + !field.is_empty() && field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + }; + if !fields.split('.').all(is_field) { + return Err(Unconverted::Unsupported); + } + let path = fields + .split('.') + .map(VariantPathElement::field) + .collect::(); + + let input = self.convert_expr(input, schema, input_dtype)?; + if !converted_dtype(&input, input_dtype)?.is_variant() { + return Err(Unconverted::Unsupported); + } + let return_dtype = self + .arrow_dtype(&Field::new("", scalar_fn.return_type().clone(), true))? + .as_nullable(); + if return_dtype.is_variant() { + return Err(Unconverted::Unsupported); + } + Ok(variant_get(input, path, Some(return_dtype))) + } + /// Converts `array_sum` to `list_sum`. /// /// DataFusion casts the list to `List`, then adds each list's valid elements in diff --git a/vortex-datafusion/src/convert/exprs/tests.rs b/vortex-datafusion/src/convert/exprs/tests.rs index 20b889bc750..79ff73720da 100644 --- a/vortex-datafusion/src/convert/exprs/tests.rs +++ b/vortex-datafusion/src/convert/exprs/tests.rs @@ -3088,3 +3088,207 @@ fn test_fallible_boolean_rhs_is_residual( assert!(!converts(&expr, &batch.schema())?); Ok(()) } + +/// A stand-in for `try_variant_get` / `variant_get` of datafusion-variant, which returns the +/// type its third argument names. Only its name and return type matter to the conversion. +#[derive(Debug, PartialEq, Eq, Hash)] +struct TestVariantGet { + name: &'static str, + signature: datafusion_expr::Signature, +} + +impl datafusion_expr::ScalarUDFImpl for TestVariantGet { + fn name(&self) -> &str { + self.name + } + + fn signature(&self) -> &datafusion_expr::Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> DFResult { + Ok(DataType::Utf8View) + } + + fn invoke_with_args( + &self, + _args: datafusion_expr::ScalarFunctionArgs, + ) -> DFResult { + Err(exec_datafusion_err!( + "the conversion never invokes {}", + self.name + )) + } +} + +/// A schema with one Variant column, `data`, and `fn_name(data, path, 'VARCHAR')` over it. +fn variant_get_expr_named( + fn_name: &'static str, + path: &str, +) -> anyhow::Result<(Schema, Arc)> { + let session = VortexSession::default(); + let schema = + Schema::new(vec![session.arrow().to_arrow_field( + "data", + &DType::Variant(Nullability::NonNullable), + )?]); + let function = TestVariantGet { + name: fn_name, + signature: datafusion_expr::Signature::any(3, datafusion_expr::Volatility::Immutable), + }; + let literal = |value: &str| -> Arc { + Arc::new(df_expr::Literal::new(ScalarValue::Utf8(Some( + value.to_string(), + )))) + }; + let expr = Arc::new(ScalarFunctionExpr::try_new( + Arc::new(ScalarUDF::from(function)), + vec![ + Arc::new(df_expr::Column::new("data", 0)), + literal(path), + literal("VARCHAR"), + ], + &schema, + Arc::new(ConfigOptions::new()), + )?); + Ok((schema, expr)) +} + +/// A schema with one Variant column, `data`, and `try_variant_get(data, path, 'VARCHAR')` over it. +fn variant_get_expr(path: &str) -> anyhow::Result<(Schema, Arc)> { + variant_get_expr_named("try_variant_get", path) +} + +#[test] +fn test_variant_get_converts_to_native_extraction() -> anyhow::Result<()> { + let (schema, expr) = variant_get_expr("$.commit.collection")?; + + assert_eq!( + DefaultExpressionConverter::default().try_convert(&expr, &schema)?, + Some(variant_get( + get_item("data", root()), + VariantPath::new([ + VariantPathElement::field("commit"), + VariantPathElement::field("collection"), + ]), + Some(DType::Utf8(Nullability::Nullable)), + )), + ); + Ok(()) +} + +#[rstest] +#[case::bare_path("commit.collection")] +#[case::list_index("$.posts[0]")] +#[case::quoted_field("$['a.b']")] +#[case::empty_field("$.commit..collection")] +#[case::root("$")] +#[case::root_dot("$.")] +#[case::empty("")] +fn test_variant_get_keeps_other_paths_in_datafusion(#[case] path: &str) -> anyhow::Result<()> { + let (schema, expr) = variant_get_expr(path)?; + + assert_eq!( + DefaultExpressionConverter::default().try_convert(&expr, &schema)?, + None, + ); + Ok(()) +} + +#[test] +fn test_strict_variant_get_stays_in_datafusion() -> anyhow::Result<()> { + let (schema, expr) = variant_get_expr_named("variant_get", "$.commit.collection")?; + + assert_eq!( + DefaultExpressionConverter::default().try_convert(&expr, &schema)?, + None, + ); + Ok(()) +} + +#[test] +fn test_projection_evaluates_duplicate_expressions_once() -> anyhow::Result<()> { + let schema = Schema::new(vec![ + Field::new("a", DataType::Int32, false), + Field::new("b", DataType::Int32, false), + ]); + let column = |name: &str, index| Arc::new(df_expr::Column::new(name, index)); + let projection = ProjectionExprs::from(vec![ + ProjectionExpr::new(column("b", 1), "first"), + ProjectionExpr::new(column("a", 0), "other"), + ProjectionExpr::new(column("b", 1), "second"), + ]); + let output_schema = projection.project_schema(&schema)?; + + let processed = DefaultExpressionConverter::default().split_projection( + projection, + &schema, + &output_schema, + )?; + + assert_eq!( + processed.scan_projection, + pack( + [ + ("first", get_item("b", root())), + ("other", get_item("a", root())), + ], + Nullability::NonNullable, + ), + ); + assert_eq!( + processed.scan_reference_schema, + output_schema.project(&[0, 1])? + ); + assert_eq!( + processed.leftover_projection, + ProjectionExprs::from(vec![ + ProjectionExpr::new(column("first", 0), "first"), + ProjectionExpr::new(column("other", 1), "other"), + ProjectionExpr::new(column("first", 0), "second"), + ]), + ); + Ok(()) +} + +#[test] +fn test_projection_keeps_distinct_arrow_types_separate() -> anyhow::Result<()> { + let schema = Schema::new(vec![Field::new("s", DataType::Utf8, true)]); + let column = Arc::new(df_expr::Column::new("s", 0)) as Arc; + let view = Arc::new(df_expr::CastExpr::new( + Arc::clone(&column), + DataType::Utf8View, + None, + )) as Arc; + let projection = ProjectionExprs::from(vec![ + ProjectionExpr::new(column, "plain"), + ProjectionExpr::new(view, "view"), + ]); + let output_schema = projection.project_schema(&schema)?; + + let processed = DefaultExpressionConverter::default().split_projection( + projection, + &schema, + &output_schema, + )?; + + assert_eq!( + processed.scan_projection, + pack( + [ + ("plain", get_item("s", root())), + ("view", get_item("s", root())), + ], + Nullability::NonNullable, + ), + ); + assert_eq!(processed.scan_reference_schema, output_schema); + assert_eq!( + processed.leftover_projection, + ProjectionExprs::from(vec![ + ProjectionExpr::new(Arc::new(df_expr::Column::new("plain", 0)), "plain"), + ProjectionExpr::new(Arc::new(df_expr::Column::new("view", 1)), "view"), + ]), + ); + Ok(()) +} diff --git a/vortex-datafusion/src/persistent/opener.rs b/vortex-datafusion/src/persistent/opener.rs index 3ba227d6ca5..0c38a44f26b 100644 --- a/vortex-datafusion/src/persistent/opener.rs +++ b/vortex-datafusion/src/persistent/opener.rs @@ -45,10 +45,13 @@ use futures::TryStreamExt; use futures::stream; use object_store::path::Path; use tracing::Instrument; +use vortex::dtype::DType; use vortex::error::VortexError; use vortex::error::VortexExpect; use vortex::expr::Expression; use vortex::expr::and_collect; +use vortex::expr::lit; +use vortex::expr::transform::replace; use vortex::file::OpenOptionsSessionExt; use vortex::io::InstrumentedReadAt; use vortex::io::session::RuntimeSessionExt; @@ -60,6 +63,10 @@ use vortex::layout::scan::v2::partition_row_range; use vortex::layout::segments::SegmentSource; use vortex::metrics::Label; use vortex::metrics::MetricsRegistry; +use vortex::scalar_fn::builtin::binary::Binary; +use vortex::scalar_fn::builtin::get_item::GetItem; +use vortex::scalar_fn::builtin::literal::Literal; +use vortex::scalar_fn::builtin::operators::Operator; use vortex::scan::execution::driver::ScanDriver; use vortex::scan::prepare::ScanCache; use vortex::scan::prepare::WeakScanCache; @@ -190,6 +197,54 @@ impl VortexOpener { } } +/// Replaces every expression in `projection` that one of `filters` equates to a literal with +/// that literal. +/// +/// The scan applies `filters` before `projection`, so in every row it projects such an expression +/// has the literal's value. DataFusion still asks for it, because it plans the projection before +/// the scan absorbs the filter. Folding saves computing it again, which for a `variant_get` is a +/// pass over the Variant. +/// +/// Only computed expressions of types whose equal values are identical are folded: floats are +/// left alone because `0.0 = -0.0`, and plain columns because reading them is cheap. +fn fold_filter_equalities( + projection: Expression, + filters: &[Expression], + scope: &DType, +) -> Expression { + filters.iter().fold(projection, |projection, filter| { + if filter.as_opt::() != Some(&Operator::Eq) { + return projection; + } + let (expr, literal) = match ( + filter.child(0).as_opt::(), + filter.child(1).as_opt::(), + ) { + (None, Some(literal)) => (filter.child(0), literal), + (Some(literal), None) => (filter.child(1), literal), + _ => return projection, + }; + if literal.is_null() || expr.is::() { + return projection; + } + let Ok(dtype) = expr.return_dtype(scope) else { + return projection; + }; + let identical_when_equal = match &dtype { + DType::Bool(_) | DType::Utf8(_) | DType::Binary(_) => true, + DType::Primitive(ptype, _) => ptype.is_int(), + _ => false, + }; + if !identical_when_equal { + return projection; + } + match literal.cast(&dtype) { + Ok(value) => replace(projection, expr, lit(value)), + Err(_) => projection, + } + }) +} + impl FileOpener for VortexOpener { fn open(&self, file: PartitionedFile) -> DFResult { // Calculate the output schema before replacing partition columns with literals so it @@ -397,6 +452,8 @@ impl FileOpener for VortexOpener { } } } + // The scan applies these exactly, unlike the dynamic filters below. + let exact_filters = native_filters.clone(); // The operator that produces a dynamic filter enforces it exactly, so the scan // evaluates it only where the file has every column it reads. native_filters.extend( @@ -445,12 +502,15 @@ impl FileOpener for VortexOpener { // The schema of the stream returned from the vortex scan. // We use a reference schema for types that don't roundtrip (Dictionary, Utf8, etc.). - let scan_projection = scan_projection - .bind(vxf.dtype()) - .and_then(|projection| projection.optimize_recursive()) - .map_err(|_e| { - exec_datafusion_err!("Couldn't get the dtype for the underlying Vortex scan") - })?; + let scan_projection = + fold_filter_equalities(scan_projection, &exact_filters, vxf.dtype()) + .bind(vxf.dtype()) + .and_then(|projection| projection.optimize_recursive()) + .map_err(|_e| { + exec_datafusion_err!( + "Couldn't get the dtype for the underlying Vortex scan" + ) + })?; let scan_dtype = scan_projection.dtype().clone(); let stream_schema = @@ -2475,3 +2535,65 @@ mod tests { Ok(()) } } + +#[cfg(test)] +mod fold_tests { + use rstest::rstest; + use vortex::dtype::DType; + use vortex::dtype::Nullability; + use vortex::dtype::PType; + use vortex::dtype::StructFields; + use vortex::expr::Expression; + use vortex::expr::byte_length; + use vortex::expr::eq; + use vortex::expr::get_item; + use vortex::expr::gt; + use vortex::expr::lit; + use vortex::expr::lower; + use vortex::expr::pack; + use vortex::expr::root; + + use super::fold_filter_equalities; + + fn scope() -> DType { + DType::Struct( + StructFields::from_iter([ + ("s", DType::Utf8(Nullability::Nullable)), + ("f", DType::Primitive(PType::F64, Nullability::Nullable)), + ]), + Nullability::NonNullable, + ) + } + + fn lowered() -> Expression { + lower(get_item("s", root())) + } + + fn projection(expr: Expression) -> Expression { + pack([("out", expr)], Nullability::NonNullable) + } + + #[rstest] + #[case::expr_eq_literal(eq(lowered(), lit("a")))] + #[case::literal_eq_expr(eq(lit("a"), lowered()))] + fn folds_an_expression_the_filter_pins(#[case] filter: Expression) { + let folded = fold_filter_equalities(projection(lowered()), &[filter], &scope()); + + // The literal takes the nullable dtype of the expression it replaces. + let literal = lit(vortex::scalar::Scalar::utf8("a", Nullability::Nullable)); + assert_eq!(folded, projection(literal)); + } + + #[rstest] + // A range does not pin the value. + #[case::not_an_equality(byte_length(lowered()), gt(byte_length(lowered()), lit(1u64)))] + // Reading a column is cheap, and folding it would leave the scan without an input. + #[case::plain_column(get_item("s", root()), eq(get_item("s", root()), lit("a")))] + // `0.0 = -0.0`, so an equal float is not necessarily the same value. + #[case::float(get_item("f", root()), eq(get_item("f", root()), lit(0.0f64)))] + fn keeps_other_expressions(#[case] expr: Expression, #[case] filter: Expression) { + let folded = fold_filter_equalities(projection(expr.clone()), &[filter], &scope()); + + assert_eq!(folded, projection(expr)); + } +} diff --git a/vortex-datafusion/src/persistent/tests.rs b/vortex-datafusion/src/persistent/tests.rs index cd68115dad6..9cb5532c4cd 100644 --- a/vortex-datafusion/src/persistent/tests.rs +++ b/vortex-datafusion/src/persistent/tests.rs @@ -1503,3 +1503,42 @@ async fn test_ree_predicate_memtable_oracle( assert_eq!(batch_values(&actual), batch_values(&expected)); Ok(()) } + +#[tokio::test] +async fn test_projection_mixed_utf8_and_utf8view_layouts() -> anyhow::Result<()> { + let options = crate::VortexTableOptions { + projection_pushdown: true, + ..Default::default() + }; + let ctx = TestSessionContext::new_with_factory(Arc::new( + VortexFormatFactory::new().with_options(options), + )); + let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, true)])); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(StringArray::from(vec![ + Some("alpha"), + None, + Some("beta"), + ]))], + )?; + ctx.write_arrow_batch("mixed_utf8.vortex", &batch).await?; + let actual_table = ctx + .table_provider("actual", "/mixed_utf8.vortex", schema.as_ref().clone()) + .await?; + ctx.session.register_table("actual", actual_table)?; + ctx.session.register_table( + "oracle", + Arc::new(datafusion::datasource::MemTable::try_new( + schema, + vec![vec![batch]], + )?), + )?; + + let query = + |table: &str| format!("SELECT s AS plain, arrow_cast(s, 'Utf8View') AS view FROM {table}"); + let actual = ctx.session.sql(&query("actual")).await?.collect().await?; + let expected = ctx.session.sql(&query("oracle")).await?.collect().await?; + assert_eq!(actual, expected); + Ok(()) +} diff --git a/vortex-functions/src/expr.rs b/vortex-functions/src/expr.rs index e16223150f1..ef59c26731b 100644 --- a/vortex-functions/src/expr.rs +++ b/vortex-functions/src/expr.rs @@ -55,6 +55,8 @@ use crate::strpos::Strpos; use crate::variant_get::VariantGet; use crate::variant_get::VariantGetOptions; use crate::variant_get::VariantPath; +use crate::variant_pack::VariantPack; +use crate::variant_pack::VariantPackOptions; use crate::zip::Zip; /// Creates a CASE WHEN expression with one WHEN/THEN pair and an ELSE value. @@ -644,6 +646,28 @@ pub fn bound_variant_get( .vortex_expect("variant-get expressions require a Variant child") } +/// Creates a Variant expression from core storage and its shredded child. +/// +/// `complete` says whether every shredded path is absent from `core`; see +/// [`VariantPackOptions::complete`]. +pub fn variant_pack(core: Expression, shredded: Expression, complete: bool) -> Expression { + VariantPack.new_expr(VariantPackOptions::new(complete), vec![core, shredded]) +} + +/// Creates a Variant expression from core storage, a non-nullable shredded struct, and the +/// struct's validity. +pub fn variant_pack_with_validity( + core: Expression, + shredded: Expression, + validity: Expression, + complete: bool, +) -> Expression { + VariantPack.new_expr( + VariantPackOptions::with_shredded_validity(complete), + vec![core, shredded, validity], + ) +} + // ---- Like ---- /// Creates a SQL LIKE expression. diff --git a/vortex-functions/src/lib.rs b/vortex-functions/src/lib.rs index 9e8ff5acc8c..c151d632eaf 100644 --- a/vortex-functions/src/lib.rs +++ b/vortex-functions/src/lib.rs @@ -43,6 +43,7 @@ pub mod replace_time_zone; pub mod stat; pub mod strpos; pub mod variant_get; +pub mod variant_pack; pub mod zip; #[cfg(test)] @@ -68,6 +69,7 @@ pub fn initialize(session: &VortexSession) { scalar_fns.register(replace_time_zone::ReplaceTimeZone); scalar_fns.register(stat::StatFn); scalar_fns.register(strpos::Strpos); + scalar_fns.register(variant_pack::VariantPack); } /// 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 b49f0877ae8..699a924f88a 100644 --- a/vortex-functions/src/variant_get/mod.rs +++ b/vortex-functions/src/variant_get/mod.rs @@ -2,16 +2,24 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors mod variant; + +use std::cell::Cell; use std::fmt; use std::fmt::Display; use std::fmt::Formatter; +use std::sync::Arc; use prost::Message; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; +use vortex_array::arrays::Chunked; +use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ScalarFn; use vortex_array::arrays::ScalarFnArray; +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::builders::VariantBuilder; use vortex_array::builders::builder_with_capacity_in; @@ -26,9 +34,12 @@ use vortex_array::scalar::Scalar; use vortex_array::scalar_fn::Arity; use vortex_array::scalar_fn::ChildName; use vortex_array::scalar_fn::ExecutionArgs; +use vortex_array::scalar_fn::ReduceNode; use vortex_array::scalar_fn::ScalarFnId; use vortex_array::scalar_fn::ScalarFnVTable; use vortex_array::scalar_fn::ScalarFnVTableExt; +use vortex_array::scalar_fn::builtin::cast::Cast; +use vortex_array::scalar_fn::builtin::get_item::GetItem; use vortex_array::scalar_fn::builtin::mask::Mask; use vortex_array::scalar_fn::session::ScalarFnSessionExt; use vortex_error::VortexResult; @@ -38,6 +49,16 @@ use vortex_session::VortexSession; use vortex_session::registry::CachedId; use vortex_utils::aliases::StringEscape; +use crate::variant_pack::VariantPack; + +/// How many lazy layers `variant_get` unwraps from its input before it extracts row by row. +const MAX_CANONICALIZE_DEPTH: usize = 8; + +thread_local! { + /// How many inputs the executions of `variant_get` on this thread's stack have canonicalized. + static CANONICALIZE_DEPTH: Cell = const { Cell::new(0) }; +} + /// Registers [`VariantGet`] and its kernel for canonical variant arrays. pub(crate) fn initialize(session: &VortexSession) { session.scalar_fns().register(VariantGet); @@ -152,6 +173,20 @@ impl ScalarFnVTable for VariantGet { .dtype() .map_or(DType::Variant(Nullability::Nullable), DType::as_nullable); + // The kernels that extract in bulk are keyed on the Variant encodings. A lazy input, such + // as a filtered or chunked Variant read from a file, reaches this point without one, so + // bring it to those encodings before falling back to extracting row by row. + if let Some(chunked) = input.as_opt::() { + let chunks = chunked + .iter_chunks() + .map(|chunk| { + VariantGet::try_new(chunk.clone(), options.clone())? + .into_array() + .execute::(ctx) + }) + .collect::>>()?; + return Ok(ChunkedArray::try_new(chunks, dtype)?.into_array()); + } // A mask only nulls rows out, so it commutes with extraction. if let Some(masked) = input.as_opt::() && masked.scalar_fn().id() == Mask.id() @@ -162,6 +197,17 @@ impl ScalarFnVTable for VariantGet { .mask(masked.child_at(1).clone())? .execute::(ctx); } + // Each canonicalization unwraps one lazy layer, such as a filter over a slice over a + // shared array. An input that canonicalizes to itself, such as a constant, would recurse + // forever, so the depth is bounded. + if !input.is::() && CANONICALIZE_DEPTH.get() < MAX_CANONICALIZE_DEPTH { + let canonical = input.clone().execute::(ctx)?; + CANONICALIZE_DEPTH.set(CANONICALIZE_DEPTH.get() + 1); + let result = VariantGet::try_new(canonical.into_array(), options.clone()) + .and_then(|array| array.into_array().execute::(ctx)); + CANONICALIZE_DEPTH.set(CANONICALIZE_DEPTH.get() - 1); + return result; + } if !dtype.is_variant() { let mut builder = builder_with_capacity_in(&dtype, input.len(), ctx.allocator()); @@ -182,6 +228,66 @@ impl ScalarFnVTable for VariantGet { builder.finish_into_variant().map(IntoArray::into_array) } + /// Reads a shredded path from the shredded child of a [`VariantPack`] input, leaving its + /// core storage unread. + fn reduce(&self, options: &Self::Options, node: &T) -> VortexResult> { + let input = node.child(0); + let Some(pack) = input + .scalar_fn() + .and_then(|scalar_fn| scalar_fn.as_opt::()) + else { + return Ok(None); + }; + let core = input.child(0); + let mut current = input.child(1); + let mut path = options.path().elements(); + // Whether `current` is below the shredded child itself. Only the shredded child can + // have left values in the core storage, so only reading it needs it to be complete. + let mut descended = false; + + loop { + let dtype = current.node_dtype()?; + match (&dtype, path.split_first()) { + // A shredded Variant holds the rest of the path itself. + (DType::Variant(_), _) if descended => { + let rest = VariantGetOptions::new( + VariantPath::new(path.iter().cloned()), + options.dtype().cloned(), + ); + return node.new_node(VariantGet.bind(rest), &[current]).map(Some); + } + (DType::Struct(fields, _), Some((VariantPathElement::Field(name), rest))) => { + if fields.find(name.as_ref()).is_none() { + // A field that was not shredded is only in the core storage. + return if descended { + Ok(None) + } else { + node.new_node(VariantGet.bind(options.clone()), &[core]) + .map(Some) + }; + } + if !descended && !pack.complete() { + return Ok(None); + } + current = current.new_node(GetItem.bind(name.clone()), &[current.clone()])?; + path = rest; + descended = true; + } + // The end of the path at a typed value of the requested dtype. + (dtype, None) + if options.dtype().is_some_and(|requested| { + !requested.is_variant() && dtype.eq_ignore_nullability(requested) + }) && (descended || (pack.complete() && !pack.shredded_validity())) => + { + return node + .new_node(Cast.bind(node.node_dtype()?), &[current]) + .map(Some); + } + _ => return Ok(None), + } + } + } + fn is_strict(&self, _options: &Self::Options) -> bool { true } @@ -204,9 +310,144 @@ fn variant_get_scalar( return Ok(Scalar::null(output_dtype.clone())); } - value + Ok(cast_variant_scalar(value, output_dtype)? + .unwrap_or_else(|| Scalar::null(output_dtype.clone()))) +} + +fn cast_variant_scalar(value: Scalar, output_dtype: &DType) -> VortexResult> { + if value.is_null() { + return Ok(None); + } + + if output_dtype.is_variant() { + let variant = if value.dtype().is_variant() { + value + } else { + Scalar::variant(value) + }; + return variant.cast(output_dtype).map(Some); + } + + let Some(value) = variant_payload(value) else { + return Ok(None); + }; + + if value.is_null() { + return Ok(None); + } + + if let DType::Struct(target_fields, _) = output_dtype { + let Some(struct_scalar) = value.as_struct_opt() else { + return Ok(None); + }; + if struct_scalar.is_null() { + return Ok(None); + } + let mut fields = Vec::with_capacity(target_fields.nfields()); + for (name, field_dtype) in target_fields.names().iter().zip(target_fields.fields()) { + let field = match struct_scalar.field(name.as_ref()) { + Some(field) => match cast_variant_scalar(field, &field_dtype)? { + Some(cast_field) => cast_field, + None if field_dtype.is_nullable() => Scalar::null(field_dtype), + None => return Ok(None), + }, + None if field_dtype.is_nullable() => Scalar::null(field_dtype), + None => return Ok(None), + }; + fields.push(field); + } + return Ok(Some(Scalar::struct_(output_dtype.clone(), fields))); + } + + if let DType::List(elem_dtype, _) = output_dtype { + let Some(list_scalar) = value.as_list_opt() else { + return Ok(None); + }; + let Some(elements) = list_scalar.elements() else { + return Ok(None); + }; + let mut cast_elements = Vec::with_capacity(elements.len()); + for element in elements { + let cast_element = match cast_variant_scalar(element, elem_dtype)? { + Some(cast_element) => cast_element, + None if elem_dtype.is_nullable() => Scalar::null(elem_dtype.as_ref().clone()), + None => return Ok(None), + }; + cast_elements.push(cast_element); + } + return Ok(Some(Scalar::list( + Arc::clone(elem_dtype), + cast_elements, + output_dtype.nullability(), + ))); + } + + if let DType::FixedSizeList(elem_dtype, size, _) = output_dtype { + let Some(list_scalar) = value.as_list_opt() else { + return Ok(None); + }; + let Some(elements) = list_scalar.elements() else { + return Ok(None); + }; + if elements.len() != *size as usize { + return Ok(None); + } + let mut cast_elements = Vec::with_capacity(elements.len()); + for element in elements { + let cast_element = match cast_variant_scalar(element, elem_dtype)? { + Some(cast_element) => cast_element, + None if elem_dtype.is_nullable() => Scalar::null(elem_dtype.as_ref().clone()), + None => return Ok(None), + }; + cast_elements.push(cast_element); + } + return Ok(Some(Scalar::fixed_size_list( + Arc::clone(elem_dtype), + cast_elements, + output_dtype.nullability(), + ))); + } + + Ok(value .cast(output_dtype) - .or_else(|_| Ok(Scalar::null(output_dtype.clone()))) + .ok() + .or_else(|| convert_to_bool(&value, output_dtype))) +} + +/// Converts a number or a string to a Boolean as Arrow's Variant conversion does. A Vortex cast +/// converts neither to a Boolean. +/// +/// Zero is false and any other number is true. A string converts as [`string_as_bool`] reads it. +/// The value can be in a Variant, as a partially shredded field holds its values. +pub(super) fn convert_to_bool(scalar: &Scalar, dtype: &DType) -> Option { + if !dtype.is_boolean() { + return None; + } + + let value = if scalar.dtype().is_variant() { + scalar.as_variant().value()? + } else { + scalar + }; + + let boolean = match value.dtype() { + DType::Primitive(..) => !value.is_zero()?, + DType::Utf8(_) => string_as_bool(value.as_utf8().value()?.as_str())?, + _ => return None, + }; + Some(Scalar::bool(boolean, dtype.nullability())) +} + +/// Reads a string as a Boolean with the spellings that Arrow's string cast accepts, ignoring case +/// and the whitespace around the string. Returns `None` for any other string. +fn string_as_bool(string: &str) -> Option { + match string.trim().to_ascii_lowercase().as_str() { + // spellchecker:off + "t" | "tr" | "tru" | "true" | "y" | "ye" | "yes" | "on" | "1" => Some(true), + "f" | "fa" | "fal" | "fals" | "false" | "n" | "no" | "of" | "off" | "0" => Some(false), + // spellchecker:on + _ => None, + } } fn variant_path_scalar( @@ -423,12 +664,14 @@ impl From for VariantPathElement { #[cfg(test)] mod tests { + use std::sync::Arc; use std::sync::LazyLock; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; + use vortex_array::arrays::BoolArray; use vortex_array::arrays::Chunked; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ConstantArray; @@ -451,6 +694,7 @@ mod tests { use vortex_array::scalar::Scalar; use vortex_array::scalar::ScalarValue; use vortex_array::scalar_fn::ScalarFnVTable; + use vortex_array::validity::Validity; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; @@ -462,6 +706,7 @@ mod tests { use crate::variant_get::VariantGetOptions; use crate::variant_get::VariantPath; use crate::variant_get::VariantPathElement; + use crate::variant_pack::VariantPack; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); @@ -954,4 +1199,235 @@ mod tests { ); Ok(()) } + + #[test] + fn variant_get_non_nullable_nested_target_returns_null_without_panicking() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let row0 = Scalar::variant(Scalar::struct_( + DType::Struct( + StructFields::new( + FieldNames::from(["x"]), + vec![DType::Variant(Nullability::NonNullable)], + ), + Nullability::NonNullable, + ), + vec![Scalar::variant(Scalar::utf8( + "not_an_int", + Nullability::NonNullable, + ))], + )); + let row1 = Scalar::variant(Scalar::struct_( + DType::Struct( + StructFields::new( + FieldNames::from(["x"]), + vec![DType::Variant(Nullability::NonNullable)], + ), + Nullability::NonNullable, + ), + vec![Scalar::variant(Scalar::primitive( + 7i32, + Nullability::NonNullable, + ))], + )); + let input = ChunkedArray::try_new( + vec![ + ConstantArray::new(row0, 1).into_array(), + ConstantArray::new(row1, 1).into_array(), + ], + DType::Variant(Nullability::NonNullable), + )? + .into_array(); + + let struct_target = DType::Struct( + StructFields::new( + FieldNames::from(["x"]), + vec![DType::Primitive(PType::I32, Nullability::NonNullable)], + ), + Nullability::Nullable, + ); + let expr = variant_get(root(), VariantPath::root(), Some(struct_target)); + let result = input.apply(&expr)?.execute::(&mut ctx)?; + assert!(result.is_invalid(0, &mut ctx)?); + assert_eq!( + result + .execute_scalar(1, &mut ctx)? + .as_struct() + .field("x") + .and_then(|s| s.as_primitive().typed_value::()), + Some(7) + ); + + let list_row0 = Scalar::variant(Scalar::list( + DType::Variant(Nullability::NonNullable), + vec![Scalar::variant(Scalar::utf8( + "bad", + Nullability::NonNullable, + ))], + Nullability::NonNullable, + )); + let list_row1 = Scalar::variant(Scalar::list( + DType::Variant(Nullability::NonNullable), + vec![Scalar::variant(Scalar::primitive( + 9i32, + Nullability::NonNullable, + ))], + Nullability::NonNullable, + )); + let list_input = ChunkedArray::try_new( + vec![ + ConstantArray::new(list_row0, 1).into_array(), + ConstantArray::new(list_row1, 1).into_array(), + ], + DType::Variant(Nullability::NonNullable), + )? + .into_array(); + + let list_target = DType::List( + Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), + Nullability::Nullable, + ); + let list_expr = variant_get(root(), VariantPath::root(), Some(list_target)); + let list_result = list_input + .apply(&list_expr)? + .execute::(&mut ctx)?; + assert!(list_result.is_invalid(0, &mut ctx)?); + assert_eq!( + list_result + .execute_scalar(1, &mut ctx)? + .as_list() + .element(0) + .and_then(|s| s.as_primitive().typed_value::()), + Some(9) + ); + Ok(()) + } + + #[test] + fn variant_get_fixed_size_list_target() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let row0 = Scalar::variant(Scalar::list( + DType::Variant(Nullability::NonNullable), + vec![ + Scalar::variant(Scalar::primitive(1i64, Nullability::NonNullable)), + Scalar::variant(Scalar::primitive(2i64, Nullability::NonNullable)), + ], + Nullability::NonNullable, + )); + let row1 = Scalar::variant(Scalar::list( + DType::Variant(Nullability::NonNullable), + vec![Scalar::variant(Scalar::primitive( + 3i64, + Nullability::NonNullable, + ))], + Nullability::NonNullable, + )); + let input = ChunkedArray::try_new( + vec![ + ConstantArray::new(row0, 1).into_array(), + ConstantArray::new(row1, 1).into_array(), + ], + DType::Variant(Nullability::NonNullable), + )? + .into_array(); + + let target = DType::FixedSizeList( + Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)), + 2, + Nullability::Nullable, + ); + let expr = variant_get(root(), VariantPath::root(), Some(target)); + let result = input.apply(&expr)?.execute::(&mut ctx)?; + let scalar0 = result.execute_scalar(0, &mut ctx)?; + assert_eq!( + scalar0.as_list().elements().map(|elems| elems + .into_iter() + .map(|e| e.as_primitive().typed_value::()) + .collect::>()), + Some(vec![Some(1), Some(2)]) + ); + assert!(result.is_invalid(1, &mut ctx)?); + Ok(()) + } + + #[test] + fn variant_get_fixed_size_list_preserves_variant_nulls() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let variant_null = Scalar::variant(Scalar::null(DType::Null)); + let row = Scalar::variant(Scalar::list( + DType::Variant(Nullability::NonNullable), + vec![ + Scalar::variant(Scalar::primitive(7i32, Nullability::NonNullable)), + variant_null, + ], + Nullability::NonNullable, + )); + let input = ConstantArray::new(row, 1).into_array(); + + for elem_nullability in [Nullability::NonNullable, Nullability::Nullable] { + let target = DType::FixedSizeList( + Arc::new(DType::Variant(elem_nullability)), + 2, + Nullability::Nullable, + ); + let expr = variant_get(root(), VariantPath::root(), Some(target)); + let result = input.clone().apply(&expr)?.execute::(&mut ctx)?; + assert!(result.is_valid(0, &mut ctx)?); + let list = result.execute_scalar(0, &mut ctx)?; + let elems = list + .as_list() + .elements() + .ok_or_else(|| vortex_error::vortex_err!("expected non-null fixed-size list"))?; + assert_eq!(elems.len(), 2); + assert_eq!( + elems[0] + .as_variant() + .value() + .and_then(|v| v.as_primitive().typed_value::()), + Some(7) + ); + assert!(!elems[1].is_null()); + assert_eq!(elems[1].as_variant().is_variant_null(), Some(true)); + } + Ok(()) + } + + #[test] + fn variant_get_root_struct_respects_variant_pack_shredded_validity() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let core = variant_rows([ + Scalar::variant(variant_object([])), + Scalar::null(DType::Variant(Nullability::Nullable)), + ])?; + let shredded = StructArray::try_new( + FieldNames::from_iter(["a"]), + vec![PrimitiveArray::from_option_iter([Some(10i32), None]).into_array()], + 2, + Validity::NonNullable, + )? + .into_array(); + let validity = BoolArray::from_iter([true, false]).into_array(); + let packed = + VariantPack::try_new_with_validity(core, shredded, validity, true)?.into_array(); + + let target = DType::struct_( + [("a", DType::Primitive(PType::I32, Nullability::Nullable))], + Nullability::Nullable, + ); + let expr = variant_get(root(), VariantPath::root(), Some(target)); + let result = packed + .apply(&expr)? + .optimize_ctx(&ctx)? + .execute::(&mut ctx)?; + assert!(result.is_valid(0, &mut ctx)?); + assert_eq!( + result + .execute_scalar(0, &mut ctx)? + .as_struct() + .field("a") + .and_then(|s| s.as_primitive().typed_value::()), + Some(10), + ); + assert!(result.is_invalid(1, &mut ctx)?); + Ok(()) + } } diff --git a/vortex-functions/src/variant_get/variant.rs b/vortex-functions/src/variant_get/variant.rs index c77bc18cf54..2b1eff05b7f 100644 --- a/vortex-functions/src/variant_get/variant.rs +++ b/vortex-functions/src/variant_get/variant.rs @@ -4,6 +4,7 @@ use vortex_array::Array; use vortex_array::ArrayRef; use vortex_array::ArrayView; +use vortex_array::Canonical; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::arrays::Struct; @@ -14,16 +15,20 @@ use vortex_array::arrays::struct_::StructArrayExt; use vortex_array::arrays::variant::VariantArraySlotsExt; use vortex_array::arrays::variant::merge_typed_scalar_as_variant; 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::Nullability; use vortex_array::kernel::ExecuteParentKernel; use vortex_array::optimizer::ArrayOptimizer; use vortex_array::optimizer::kernels::ArrayKernelsExt; +use vortex_array::scalar::Scalar; use vortex_array::scalar_fn::ScalarFnVTable; use vortex_array::validity::Validity; -use vortex_error::VortexExpect; +use vortex_buffer::Buffer; +use vortex_error::VortexError; use vortex_error::VortexResult; +use vortex_mask::Mask; use vortex_session::VortexSession; use crate::builtins::ArrayFunctions; @@ -31,6 +36,7 @@ use crate::variant_get::VariantGet; use crate::variant_get::VariantGetOptions; use crate::variant_get::VariantPath; use crate::variant_get::VariantPathElement; +use crate::variant_get::convert_to_bool; pub(crate) fn initialize(session: &VortexSession) { let kernels = session.kernels(); @@ -69,37 +75,65 @@ impl ExecuteParentKernel for VariantGetKernel { .shredded() .map(|shredded| { typed_shredded_path(shredded, parent.options.path().elements(), ctx)? - .map(|typed| mask_with_validity(typed, &core_validity)?.optimize_ctx(ctx)) + .map(|(typed, remaining)| { + let typed = mask_with_validity(typed, &core_validity)?.optimize_ctx(ctx)?; + Ok::<_, VortexError>((typed, remaining)) + }) .transpose() }) .transpose()? .flatten(); - let Some(typed) = typed else { + let Some((typed, remaining)) = typed else { return make_fallback(ctx).map(Some); }; - // A shredded Variant child still needs VariantGet at the root to produce a - // concrete requested dtype. + // A shredded Variant child holds the rest of the path, in its own shredded tree or in + // its residual value. It also still needs VariantGet at its root to produce a concrete + // requested dtype. if typed.dtype().is_variant() - && parent - .options - .dtype() - .is_some_and(|dtype| !dtype.is_variant()) + && (!remaining.is_empty() + || parent + .options + .dtype() + .is_some_and(|dtype| !dtype.is_variant())) { - return execute_fallback_variant_get( - VariantGetOptions::new(VariantPath::root(), parent.options.dtype().cloned()), + let typed_mask = typed.validity()?.execute_mask(typed.len(), ctx)?; + if typed_mask.all_false() { + return make_fallback(ctx).map(Some); + } + + let nested = execute_fallback_variant_get( + VariantGetOptions::new( + VariantPath::new(remaining.iter().cloned()), + parent.options.dtype().cloned(), + ), typed, ctx, + )?; + + // A row without the nested Variant can still hold the path in core storage, as the + // rows of an unshredded chunk do once canonicalization pads the shredded child. + return fill_absent_from_core( + nested, + typed_mask, + array.core_storage(), + parent.options, + ctx, ) .map(Some); } + // A remaining path through a shredded list cannot be walked column-wise; defer to + // scalar extraction so shredded list elements and residual core storage are both read. + if !remaining.is_empty() { + return Ok(None); + } // Untyped VariantGet must return variant scalars, so typed shredded values // are wrapped as variants and merged with raw object fallback where needed. if parent.options.dtype().is_none_or(DType::is_variant) { let fallback = match typed.dtype() { DType::Struct(..) => Some(make_fallback(ctx)?), DType::List(..) | DType::FixedSizeList(..) => { - return make_fallback(ctx).map(Some); + return Ok(None); } _ => { let typed_mask = typed.validity()?.execute_mask(typed.len(), ctx)?; @@ -111,36 +145,109 @@ impl ExecuteParentKernel for VariantGetKernel { return merge_typed_as_variant(typed, fallback, ctx).map(Some); } - // For concrete output dtypes, trust the shredded child only when its logical - // dtype matches the request; otherwise the raw fallback owns cast semantics. - let requested_dtype = parent - .options - .dtype() - .vortex_expect("variant dtype handled above"); - if typed.dtype().as_nullable() != requested_dtype.as_nullable() { - return make_fallback(ctx).map(Some); + // A shredded struct or list can hold only some of an object's fields or nested + // partially-shredded values, with the rest in core storage. Defer to scalar + // extraction, which merges shredded and core storage per row before casting. + if matches!( + typed.dtype(), + DType::Struct(..) | DType::List(..) | DType::FixedSizeList(..) + ) { + return Ok(None); } - let typed = typed.cast(parent.dtype().clone())?; + // Null typed rows are not necessarily missing from the logical variant value; + // fill those rows from core storage and keep valid typed rows unchanged. let typed_mask = typed.validity()?.execute_mask(typed.len(), ctx)?; - if typed_mask.all_true() { - return Ok(Some(typed)); + if typed_mask.all_false() { + return make_fallback(ctx).map(Some); } - // Null typed rows are not necessarily missing from the logical variant value; - // fill those rows from core storage and keep valid typed rows unchanged. - // TODO: we are computing the entire fallback array here but only take indices where - // typed_mask is false, so we can narrow the core_storage to only the false - // indices and compute from there then zip - let fallback = make_fallback(ctx)?; - typed_mask - .into_array() - .zip(typed, fallback)? - .execute::(ctx) + // 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)?; + fill_absent_from_core(typed, typed_mask, array.core_storage(), parent.options, ctx) .map(Some) } } +/// Fills the rows of `extracted` that `present` marks absent from the shredded child, with the +/// extraction of the whole path from `core`. +/// +/// Usually the absent rows are missing from core storage as well, as for a field that only some +/// objects have. These rows are extracted on their own first: when none of them holds a value, +/// `extracted` is the whole answer and the rest of core storage is never read. +fn fill_absent_from_core( + extracted: ArrayRef, + present: Mask, + core: &ArrayRef, + options: &VariantGetOptions, + ctx: &mut ExecutionCtx, +) -> VortexResult { + if present.all_true() { + return Ok(extracted); + } + + let absent = execute_fallback_variant_get(options.clone(), core.filter(!&present)?, ctx)?; + if absent + .validity()? + .execute_mask(absent.len(), ctx)? + .all_false() + { + return Ok(extracted); + } + + // Scatter the extracted rows back to their positions: row `i` reads the extracted row that + // it is the n-th absent row for. Present rows read an arbitrary extracted row, which the zip + // discards. + let last = absent.len() as u64 - 1; + let mut taken = 0u64; + let positions = present + .to_bit_buffer() + .iter() + .map(|is_present| { + let position = taken; + taken += u64::from(!is_present); + position.min(last) + }) + .collect::>(); + let fallback = absent.take(positions.into_array())?; + + present + .into_array() + .zip(extracted, fallback)? + .execute::(ctx) +} + +/// Converts the typed values `typed` to `dtype`, as a single value converts: a value that does +/// not convert is a null. +fn convert_typed(typed: ArrayRef, dtype: &DType, ctx: &mut ExecutionCtx) -> VortexResult { + // Only the nullability differs, which keeps the encoding of the typed values. + if typed.dtype().eq_ignore_nullability(dtype) { + return typed.cast(dtype.clone()); + } + + // Most columns convert as a whole. A cast fails on the first value that does not convert, + // and only then is each value converted on its own. + if let Ok(converted) = typed + .cast(dtype.clone()) + .and_then(|converted| converted.execute::(ctx)) + { + return Ok(converted.into_array()); + } + + let mut builder = builder_with_capacity_in(dtype, typed.len(), ctx.allocator()); + for idx in 0..typed.len() { + let scalar = typed.execute_scalar(idx, ctx)?; + let converted = scalar + .cast(dtype) + .ok() + .or_else(|| convert_to_bool(&scalar, dtype)) + .unwrap_or_else(|| Scalar::null(dtype.clone())); + builder.append_scalar(&converted)?; + } + Ok(builder.finish()) +} + /// 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 @@ -155,15 +262,26 @@ fn mask_with_validity(array: ArrayRef, validity: &Validity) -> VortexResult( shredded: &ArrayRef, - path: &[VariantPathElement], + path: &'a [VariantPathElement], ctx: &mut ExecutionCtx, -) -> VortexResult> { +) -> VortexResult> { let mut current = shredded.clone(); - for element in path { + for (idx, element) in path.iter().enumerate() { + if current.dtype().is_variant() { + return Ok(Some((current, &path[idx..]))); + } let VariantPathElement::Field(name) = element else { - return Ok(None); + return Ok( + matches!(current.dtype(), DType::List(..) | DType::FixedSizeList(..)) + .then_some((current, &path[idx..])), + ); }; let DType::Struct(..) = current.dtype() else { return Ok(None); @@ -175,7 +293,7 @@ fn typed_shredded_path( current = mask_with_validity(field.clone(), ¤t_struct.validity()?)?; } - Ok(Some(current)) + Ok(Some((current, &[]))) } fn merge_typed_as_variant( @@ -206,3 +324,175 @@ fn execute_fallback_variant_get( .into_array() .execute::(ctx) } + +#[cfg(test)] +mod tests { + use std::sync::LazyLock; + + use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::BoolArray; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::StructArray; + use vortex_array::arrays::VarBinViewArray; + use vortex_array::arrays::VariantArray; + use vortex_array::assert_arrays_eq; + use vortex_array::builders::VariantBuilder; + use vortex_array::dtype::DType; + use vortex_array::dtype::FieldNames; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::expr::root; + use vortex_array::scalar::Scalar; + use vortex_array::validity::Validity; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use crate::expr::variant_get; + use crate::variant_get::VariantPath; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); + + /// Variant objects whose field `a` is shredded as `a`, over core storage that holds no value + /// of `a`, as shredding leaves it. + fn shredded_a(a: ArrayRef) -> VortexResult { + let len = a.len(); + let core = ConstantArray::new(Scalar::variant(Scalar::null(DType::Null)), len).into_array(); + 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 typed value of another dtype than the requested one converts from the typed child, as + /// a single value converts. A value that does not convert is a null. + #[rstest] + #[case::narrower( + PrimitiveArray::from_option_iter([Some(1i64), Some(-300), None]), + PType::I32, + PrimitiveArray::from_option_iter([Some(1i32), Some(-300), None]), + )] + #[case::wider( + PrimitiveArray::from_option_iter([Some(1i32), Some(-300), None]), + PType::I64, + PrimitiveArray::from_option_iter([Some(1i64), Some(-300), None]), + )] + #[case::out_of_range( + PrimitiveArray::from_option_iter([Some(1i64), Some(-300), None]), + PType::I8, + PrimitiveArray::from_option_iter([Some(1i8), None, None]), + )] + #[case::to_float( + PrimitiveArray::from_option_iter([Some(1i64), Some(-300), None]), + PType::F64, + PrimitiveArray::from_option_iter([Some(1f64), Some(-300.0), None]), + )] + fn converts_typed_values( + #[case] typed: PrimitiveArray, + #[case] requested: PType, + #[case] expected: PrimitiveArray, + ) -> VortexResult<()> { + let array = shredded_a(typed.into_array())?; + let expr = variant_get( + root(), + VariantPath::field("a"), + Some(DType::Primitive(requested, Nullability::Nullable)), + ); + + let mut ctx = SESSION.create_execution_ctx(); + let actual = array.apply(&expr)?.execute::(&mut ctx)?; + + assert_arrays_eq!(actual, expected.into_array(), &mut ctx); + Ok(()) + } + + /// A number reads as a Boolean as Arrow's Variant conversion reads it: zero is false. + #[test] + fn converts_typed_numbers_to_booleans() -> VortexResult<()> { + let typed = PrimitiveArray::from_option_iter([Some(0i64), Some(-3), None]); + let array = shredded_a(typed.into_array())?; + let expr = variant_get( + root(), + VariantPath::field("a"), + Some(DType::Bool(Nullability::Nullable)), + ); + + let mut ctx = SESSION.create_execution_ctx(); + let actual = array.apply(&expr)?.execute::(&mut ctx)?; + + assert_arrays_eq!( + actual, + BoolArray::from_iter([Some(false), Some(true), None]).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] + fn converts_typed_strings_to_booleans() -> VortexResult<()> { + let typed = VarBinViewArray::from_iter_nullable_str([ + Some("true"), + Some(" No "), + Some("1"), + Some("maybe"), + None, + ]); + let array = shredded_a(typed.into_array())?; + let expr = variant_get( + root(), + VariantPath::field("a"), + Some(DType::Bool(Nullability::Nullable)), + ); + + let mut ctx = SESSION.create_execution_ctx(); + let actual = array.apply(&expr)?.execute::(&mut ctx)?; + + assert_arrays_eq!( + actual, + BoolArray::from_iter([Some(true), Some(false), Some(true), None, None]).into_array(), + &mut ctx + ); + Ok(()) + } + + /// A number in a nested Variant, as a partially shredded field holds it, reads as a Boolean + /// too. + #[test] + fn converts_numbers_in_variants_to_booleans() -> VortexResult<()> { + let mut builder = VariantBuilder::new(Nullability::Nullable); + for value in [0i64, -3] { + let value = Scalar::primitive(value, Nullability::NonNullable); + builder.append_n_scalars(&Scalar::variant(value), 1)?; + } + builder.append_n_scalars(&Scalar::null(DType::Variant(Nullability::Nullable)), 1)?; + let array = shredded_a(builder.finish_into_variant()?.into_array())?; + let expr = variant_get( + root(), + VariantPath::field("a"), + Some(DType::Bool(Nullability::Nullable)), + ); + + let mut ctx = SESSION.create_execution_ctx(); + let actual = array.apply(&expr)?.execute::(&mut ctx)?; + + assert_arrays_eq!( + actual, + BoolArray::from_iter([Some(false), Some(true), None]).into_array(), + &mut ctx + ); + Ok(()) + } +} diff --git a/vortex-functions/src/variant_pack.rs b/vortex-functions/src/variant_pack.rs new file mode 100644 index 00000000000..457cdf39c70 --- /dev/null +++ b/vortex-functions/src/variant_pack.rs @@ -0,0 +1,219 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The `vortex.variant_pack` scalar function. + +use std::fmt; +use std::fmt::Display; +use std::fmt::Formatter; + +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::ScalarFnArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VariantArray; +use vortex_array::arrays::struct_::StructArrayExt; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +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_array::validity::Validity; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +/// Builds a Variant from its core storage and its shredded child. +/// +/// This is how a Variant that is stored as separate columns is put back together: `core` holds +/// the Variant values without what `shredded` holds, and `shredded` is the typed tree of the +/// fields that were shredded out. The result is the canonical [`VariantArray`] over the two. +/// +/// A shredded struct is null in the rows that are not objects. Stored with that validity it +/// would be a nullable struct, which a scan cannot push a field read through, so the validity +/// can be a third child, `validity`, over a `shredded` struct that is not nullable. The fields +/// of such a struct are null wherever the struct was. +/// +/// [`VariantGet`](super::variant_get::VariantGet) over this function reads a shredded path from +/// `shredded` alone, when [`VariantPackOptions::complete`] says that `core` cannot hold it. +#[derive(Clone)] +pub struct VariantPack; + +impl VariantPack { + /// Creates a lazy Variant over `core` and `shredded`. + /// + /// # Errors + /// + /// Returns an error if `core` is not Variant data or the two differ in length. + pub fn try_new( + core: ArrayRef, + shredded: ArrayRef, + options: VariantPackOptions, + ) -> VortexResult { + ScalarFnArray::try_new(VariantPack.bind(options), [core, shredded]) + } + + /// Creates a lazy Variant over `core` and a `shredded` struct whose validity is `validity`. + /// + /// # Errors + /// + /// Returns an error if `core` is not Variant data, `shredded` is not a struct that is not + /// nullable, `validity` is not a boolean array that is not nullable, or they differ in + /// length. + pub fn try_new_with_validity( + core: ArrayRef, + shredded: ArrayRef, + validity: ArrayRef, + complete: bool, + ) -> VortexResult { + let options = VariantPackOptions { + complete, + shredded_validity: true, + }; + ScalarFnArray::try_new(VariantPack.bind(options), [core, shredded, validity]) + } +} + +/// Options for [`VariantPack`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct VariantPackOptions { + complete: bool, + shredded_validity: bool, +} + +impl VariantPackOptions { + /// Creates options for a shredded child that is `complete` or not. + pub fn new(complete: bool) -> Self { + Self { + complete, + shredded_validity: false, + } + } + + /// Creates options for a shredded struct that is `complete` or not, whose validity is a + /// third child. + pub fn with_shredded_validity(complete: bool) -> Self { + Self { + complete, + shredded_validity: true, + } + } + + /// Whether the validity of the shredded struct is a third child. + pub fn shredded_validity(&self) -> bool { + self.shredded_validity + } + + /// Whether the shredded child holds every value it could hold. + /// + /// The core storage keeps a value that did not fit the shredded child: a value of another + /// type than a shredded leaf, or an object that was not split into a shredded struct. A + /// complete shredded child has no such row, so wherever it is null the path it represents + /// has no value, and the core storage need not be read to tell. + pub fn complete(&self) -> bool { + self.complete + } +} + +impl Display for VariantPackOptions { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{}", if self.complete { "complete" } else { "partial" })?; + if self.shredded_validity { + write!(f, ", validity")?; + } + Ok(()) + } +} + +impl ScalarFnVTable for VariantPack { + type Options = VariantPackOptions; + + fn id(&self) -> ScalarFnId { + static ID: CachedId = CachedId::new("vortex.variant_pack"); + *ID + } + + fn serialize(&self, options: &Self::Options) -> VortexResult>> { + Ok(Some(vec![ + u8::from(options.complete), + u8::from(options.shredded_validity), + ])) + } + + fn deserialize( + &self, + metadata: &[u8], + _session: &VortexSession, + ) -> VortexResult { + match metadata { + [complete @ (0 | 1), shredded_validity @ (0 | 1)] => Ok(VariantPackOptions { + complete: *complete == 1, + shredded_validity: *shredded_validity == 1, + }), + _ => vortex_bail!("invalid VariantPack options: {metadata:?}"), + } + } + + fn arity(&self, options: &Self::Options) -> Arity { + Arity::Exact(if options.shredded_validity { 3 } else { 2 }) + } + + fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName { + match child_idx { + 0 => ChildName::from("core"), + 1 => ChildName::from("shredded"), + 2 => ChildName::from("validity"), + _ => unreachable!("Invalid child index {child_idx} for VariantPack expression"), + } + } + + fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult { + vortex_ensure!( + arg_dtypes[0].is_variant(), + "VariantPack core storage must be a Variant, found {}", + arg_dtypes[0] + ); + if options.shredded_validity { + vortex_ensure!( + arg_dtypes[1].is_struct() && !arg_dtypes[1].is_nullable(), + "VariantPack takes the validity of a struct that is not nullable, found {}", + arg_dtypes[1] + ); + vortex_ensure_eq!( + arg_dtypes[2], + DType::Bool(Nullability::NonNullable), + "VariantPack validity must be a non-nullable boolean array" + ); + } + Ok(arg_dtypes[0].clone()) + } + + fn execute( + &self, + options: &Self::Options, + args: &dyn ExecutionArgs, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let shredded = args.get(1)?; + let shredded = if options.shredded_validity { + let fields = shredded.execute::(ctx)?; + StructArray::try_new( + fields.names().clone(), + fields.iter_unmasked_fields().cloned().collect::>(), + fields.len(), + Validity::Array(args.get(2)?), + )? + .into_array() + } else { + shredded + }; + Ok(VariantArray::try_new(args.get(0)?, Some(shredded))?.into_array()) + } +}