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