diff --git a/encodings/parquet-variant/src/array.rs b/encodings/parquet-variant/src/array.rs index 2414a90fbdf..723cafd172b 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( @@ -510,6 +553,7 @@ mod tests { use parquet_variant_compute::VariantArrayBuilder; use parquet_variant_compute::json_to_variant; use parquet_variant_compute::shred_variant; + use rstest::rstest; use vortex_array::Canonical; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -525,6 +569,7 @@ mod tests { use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_error::vortex_err; + use vortex_mask::Mask; use vortex_session::VortexSession; use crate::ParquetVariant; @@ -747,6 +792,96 @@ 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(()) + } + + /// Each list element reads the metadata of the row that holds it. The lists differ in length + /// and hold objects whose field names differ, so every row has its own metadata dictionary and + /// field `p` has another ID in the first row than in the last. Filtering makes the shredded + /// list lazy, so canonicalizing must execute it first. + #[rstest] + #[case::list(false)] + #[case::filtered(true)] + fn canonical_reads_list_elements_with_their_row_metadata( + #[case] filtered: bool, + ) -> VortexResult<()> { + let json: ArrowArrayRef = Arc::new(StringArray::from(vec![ + r#"{"tags":[{"p":1},{"p":2},"x"]}"#, + r#"{"tags":[{"q":"z"}]}"#, + r#"{"tags":[10,{"r":true,"p":3}]}"#, + ])); + 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 mut array = ParquetVariant::from_arrow_variant(&shredded, &SESSION.arrow())?; + if filtered { + array = array.filter(Mask::from_iter([true, false, true]))?; + } + + let mut ctx = SESSION.create_execution_ctx(); + let canonical = array.clone().execute::(&mut ctx)?.into_array(); + + assert_eq!(canonical.len(), array.len()); + for row in 0..array.len() { + assert_eq!( + canonical.execute_scalar(row, &mut ctx)?, + array.execute_scalar(row, &mut ctx)?, + "row {row}" + ); + } + 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..936f97c933a 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,17 +373,21 @@ 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; @@ -324,8 +395,12 @@ mod tests { 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 +410,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 +1165,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 +1185,435 @@ 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(()) + } + + /// 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 +1704,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/vtable/mod.rs b/vortex-array/src/arrays/variant/vtable/mod.rs index 5ef9fb108e5..04e710ce74b 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, )) @@ -280,4 +285,40 @@ fn merge_struct_payload(typed: &Scalar, raw: Option<&Scalar>) -> VortexResult VortexResult<()> { + let nullable_variant = DType::Variant(Nullability::Nullable); + let typed = Scalar::list( + nullable_variant.clone(), + vec![ + Scalar::variant(Scalar::from(1i32)).cast(&nullable_variant)?, + Scalar::null(nullable_variant.clone()), + ], + Nullability::NonNullable, + ); + + let merged = merge_typed_scalar_as_variant(typed, None, &nullable_variant)?; + + let expected = Scalar::variant(Scalar::list( + DType::Variant(Nullability::NonNullable), + vec![ + Scalar::variant(Scalar::from(1i32)), + Scalar::variant(Scalar::null(DType::Null)), + ], + Nullability::NonNullable, + )) + .cast(&nullable_variant)?; + assert_eq!(merged, expected); + Ok(()) + } +}