From 50380f92ea8678df29bd599b9b510c7f8e6ae886 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Mon, 23 Nov 2026 16:26:33 +0000 Subject: [PATCH 1/3] Add vortex.variant_pack and read shredded paths from it without core storage A Variant stored as separate columns is put back together from its core storage and its shredded child. With the pack as a scalar function, variant_get over it reduces to a read of the shredded column when the pack is complete, so the scan never reads the core storage for a shredded path. Signed-off-by: Robert Kruszewski --- vortex-functions/src/expr.rs | 24 +++ vortex-functions/src/lib.rs | 2 + vortex-functions/src/variant_get/mod.rs | 108 ++++++++++++ vortex-functions/src/variant_pack.rs | 219 ++++++++++++++++++++++++ 4 files changed, 353 insertions(+) create mode 100644 vortex-functions/src/variant_pack.rs diff --git a/vortex-functions/src/expr.rs b/vortex-functions/src/expr.rs index e16223150f1..ef59c26731b 100644 --- a/vortex-functions/src/expr.rs +++ b/vortex-functions/src/expr.rs @@ -55,6 +55,8 @@ use crate::strpos::Strpos; use crate::variant_get::VariantGet; use crate::variant_get::VariantGetOptions; use crate::variant_get::VariantPath; +use crate::variant_pack::VariantPack; +use crate::variant_pack::VariantPackOptions; use crate::zip::Zip; /// Creates a CASE WHEN expression with one WHEN/THEN pair and an ELSE value. @@ -644,6 +646,28 @@ pub fn bound_variant_get( .vortex_expect("variant-get expressions require a Variant child") } +/// Creates a Variant expression from core storage and its shredded child. +/// +/// `complete` says whether every shredded path is absent from `core`; see +/// [`VariantPackOptions::complete`]. +pub fn variant_pack(core: Expression, shredded: Expression, complete: bool) -> Expression { + VariantPack.new_expr(VariantPackOptions::new(complete), vec![core, shredded]) +} + +/// Creates a Variant expression from core storage, a non-nullable shredded struct, and the +/// struct's validity. +pub fn variant_pack_with_validity( + core: Expression, + shredded: Expression, + validity: Expression, + complete: bool, +) -> Expression { + VariantPack.new_expr( + VariantPackOptions::with_shredded_validity(complete), + vec![core, shredded, validity], + ) +} + // ---- Like ---- /// Creates a SQL LIKE expression. diff --git a/vortex-functions/src/lib.rs b/vortex-functions/src/lib.rs index 9e8ff5acc8c..c151d632eaf 100644 --- a/vortex-functions/src/lib.rs +++ b/vortex-functions/src/lib.rs @@ -43,6 +43,7 @@ pub mod replace_time_zone; pub mod stat; pub mod strpos; pub mod variant_get; +pub mod variant_pack; pub mod zip; #[cfg(test)] @@ -68,6 +69,7 @@ pub fn initialize(session: &VortexSession) { scalar_fns.register(replace_time_zone::ReplaceTimeZone); scalar_fns.register(stat::StatFn); scalar_fns.register(strpos::Strpos); + scalar_fns.register(variant_pack::VariantPack); } /// A scalar function has a negative cost if applying it to an array and diff --git a/vortex-functions/src/variant_get/mod.rs b/vortex-functions/src/variant_get/mod.rs index 2cb13012445..699a924f88a 100644 --- a/vortex-functions/src/variant_get/mod.rs +++ b/vortex-functions/src/variant_get/mod.rs @@ -34,9 +34,12 @@ use vortex_array::scalar::Scalar; use vortex_array::scalar_fn::Arity; use vortex_array::scalar_fn::ChildName; use vortex_array::scalar_fn::ExecutionArgs; +use vortex_array::scalar_fn::ReduceNode; use vortex_array::scalar_fn::ScalarFnId; use vortex_array::scalar_fn::ScalarFnVTable; use vortex_array::scalar_fn::ScalarFnVTableExt; +use vortex_array::scalar_fn::builtin::cast::Cast; +use vortex_array::scalar_fn::builtin::get_item::GetItem; use vortex_array::scalar_fn::builtin::mask::Mask; use vortex_array::scalar_fn::session::ScalarFnSessionExt; use vortex_error::VortexResult; @@ -46,6 +49,8 @@ use vortex_session::VortexSession; use vortex_session::registry::CachedId; use vortex_utils::aliases::StringEscape; +use crate::variant_pack::VariantPack; + /// How many lazy layers `variant_get` unwraps from its input before it extracts row by row. const MAX_CANONICALIZE_DEPTH: usize = 8; @@ -223,6 +228,66 @@ impl ScalarFnVTable for VariantGet { builder.finish_into_variant().map(IntoArray::into_array) } + /// Reads a shredded path from the shredded child of a [`VariantPack`] input, leaving its + /// core storage unread. + fn reduce(&self, options: &Self::Options, node: &T) -> VortexResult> { + let input = node.child(0); + let Some(pack) = input + .scalar_fn() + .and_then(|scalar_fn| scalar_fn.as_opt::()) + else { + return Ok(None); + }; + let core = input.child(0); + let mut current = input.child(1); + let mut path = options.path().elements(); + // Whether `current` is below the shredded child itself. Only the shredded child can + // have left values in the core storage, so only reading it needs it to be complete. + let mut descended = false; + + loop { + let dtype = current.node_dtype()?; + match (&dtype, path.split_first()) { + // A shredded Variant holds the rest of the path itself. + (DType::Variant(_), _) if descended => { + let rest = VariantGetOptions::new( + VariantPath::new(path.iter().cloned()), + options.dtype().cloned(), + ); + return node.new_node(VariantGet.bind(rest), &[current]).map(Some); + } + (DType::Struct(fields, _), Some((VariantPathElement::Field(name), rest))) => { + if fields.find(name.as_ref()).is_none() { + // A field that was not shredded is only in the core storage. + return if descended { + Ok(None) + } else { + node.new_node(VariantGet.bind(options.clone()), &[core]) + .map(Some) + }; + } + if !descended && !pack.complete() { + return Ok(None); + } + current = current.new_node(GetItem.bind(name.clone()), &[current.clone()])?; + path = rest; + descended = true; + } + // The end of the path at a typed value of the requested dtype. + (dtype, None) + if options.dtype().is_some_and(|requested| { + !requested.is_variant() && dtype.eq_ignore_nullability(requested) + }) && (descended || (pack.complete() && !pack.shredded_validity())) => + { + return node + .new_node(Cast.bind(node.node_dtype()?), &[current]) + .map(Some); + } + _ => return Ok(None), + } + } + } + fn is_strict(&self, _options: &Self::Options) -> bool { true } @@ -606,6 +671,7 @@ mod tests { use vortex_array::Canonical; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; + use vortex_array::arrays::BoolArray; use vortex_array::arrays::Chunked; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ConstantArray; @@ -628,6 +694,7 @@ mod tests { use vortex_array::scalar::Scalar; use vortex_array::scalar::ScalarValue; use vortex_array::scalar_fn::ScalarFnVTable; + use vortex_array::validity::Validity; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; @@ -639,6 +706,7 @@ mod tests { use crate::variant_get::VariantGetOptions; use crate::variant_get::VariantPath; use crate::variant_get::VariantPathElement; + use crate::variant_pack::VariantPack; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); @@ -1322,4 +1390,44 @@ mod tests { } Ok(()) } + + #[test] + fn variant_get_root_struct_respects_variant_pack_shredded_validity() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let core = variant_rows([ + Scalar::variant(variant_object([])), + Scalar::null(DType::Variant(Nullability::Nullable)), + ])?; + let shredded = StructArray::try_new( + FieldNames::from_iter(["a"]), + vec![PrimitiveArray::from_option_iter([Some(10i32), None]).into_array()], + 2, + Validity::NonNullable, + )? + .into_array(); + let validity = BoolArray::from_iter([true, false]).into_array(); + let packed = + VariantPack::try_new_with_validity(core, shredded, validity, true)?.into_array(); + + let target = DType::struct_( + [("a", DType::Primitive(PType::I32, Nullability::Nullable))], + Nullability::Nullable, + ); + let expr = variant_get(root(), VariantPath::root(), Some(target)); + let result = packed + .apply(&expr)? + .optimize_ctx(&ctx)? + .execute::(&mut ctx)?; + assert!(result.is_valid(0, &mut ctx)?); + assert_eq!( + result + .execute_scalar(0, &mut ctx)? + .as_struct() + .field("a") + .and_then(|s| s.as_primitive().typed_value::()), + Some(10), + ); + assert!(result.is_invalid(1, &mut ctx)?); + Ok(()) + } } diff --git a/vortex-functions/src/variant_pack.rs b/vortex-functions/src/variant_pack.rs new file mode 100644 index 00000000000..457cdf39c70 --- /dev/null +++ b/vortex-functions/src/variant_pack.rs @@ -0,0 +1,219 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The `vortex.variant_pack` scalar function. + +use std::fmt; +use std::fmt::Display; +use std::fmt::Formatter; + +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::ScalarFnArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VariantArray; +use vortex_array::arrays::struct_::StructArrayExt; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::scalar_fn::Arity; +use vortex_array::scalar_fn::ChildName; +use vortex_array::scalar_fn::ExecutionArgs; +use vortex_array::scalar_fn::ScalarFnId; +use vortex_array::scalar_fn::ScalarFnVTable; +use vortex_array::scalar_fn::ScalarFnVTableExt; +use vortex_array::validity::Validity; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +/// Builds a Variant from its core storage and its shredded child. +/// +/// This is how a Variant that is stored as separate columns is put back together: `core` holds +/// the Variant values without what `shredded` holds, and `shredded` is the typed tree of the +/// fields that were shredded out. The result is the canonical [`VariantArray`] over the two. +/// +/// A shredded struct is null in the rows that are not objects. Stored with that validity it +/// would be a nullable struct, which a scan cannot push a field read through, so the validity +/// can be a third child, `validity`, over a `shredded` struct that is not nullable. The fields +/// of such a struct are null wherever the struct was. +/// +/// [`VariantGet`](super::variant_get::VariantGet) over this function reads a shredded path from +/// `shredded` alone, when [`VariantPackOptions::complete`] says that `core` cannot hold it. +#[derive(Clone)] +pub struct VariantPack; + +impl VariantPack { + /// Creates a lazy Variant over `core` and `shredded`. + /// + /// # Errors + /// + /// Returns an error if `core` is not Variant data or the two differ in length. + pub fn try_new( + core: ArrayRef, + shredded: ArrayRef, + options: VariantPackOptions, + ) -> VortexResult { + ScalarFnArray::try_new(VariantPack.bind(options), [core, shredded]) + } + + /// Creates a lazy Variant over `core` and a `shredded` struct whose validity is `validity`. + /// + /// # Errors + /// + /// Returns an error if `core` is not Variant data, `shredded` is not a struct that is not + /// nullable, `validity` is not a boolean array that is not nullable, or they differ in + /// length. + pub fn try_new_with_validity( + core: ArrayRef, + shredded: ArrayRef, + validity: ArrayRef, + complete: bool, + ) -> VortexResult { + let options = VariantPackOptions { + complete, + shredded_validity: true, + }; + ScalarFnArray::try_new(VariantPack.bind(options), [core, shredded, validity]) + } +} + +/// Options for [`VariantPack`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct VariantPackOptions { + complete: bool, + shredded_validity: bool, +} + +impl VariantPackOptions { + /// Creates options for a shredded child that is `complete` or not. + pub fn new(complete: bool) -> Self { + Self { + complete, + shredded_validity: false, + } + } + + /// Creates options for a shredded struct that is `complete` or not, whose validity is a + /// third child. + pub fn with_shredded_validity(complete: bool) -> Self { + Self { + complete, + shredded_validity: true, + } + } + + /// Whether the validity of the shredded struct is a third child. + pub fn shredded_validity(&self) -> bool { + self.shredded_validity + } + + /// Whether the shredded child holds every value it could hold. + /// + /// The core storage keeps a value that did not fit the shredded child: a value of another + /// type than a shredded leaf, or an object that was not split into a shredded struct. A + /// complete shredded child has no such row, so wherever it is null the path it represents + /// has no value, and the core storage need not be read to tell. + pub fn complete(&self) -> bool { + self.complete + } +} + +impl Display for VariantPackOptions { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{}", if self.complete { "complete" } else { "partial" })?; + if self.shredded_validity { + write!(f, ", validity")?; + } + Ok(()) + } +} + +impl ScalarFnVTable for VariantPack { + type Options = VariantPackOptions; + + fn id(&self) -> ScalarFnId { + static ID: CachedId = CachedId::new("vortex.variant_pack"); + *ID + } + + fn serialize(&self, options: &Self::Options) -> VortexResult>> { + Ok(Some(vec![ + u8::from(options.complete), + u8::from(options.shredded_validity), + ])) + } + + fn deserialize( + &self, + metadata: &[u8], + _session: &VortexSession, + ) -> VortexResult { + match metadata { + [complete @ (0 | 1), shredded_validity @ (0 | 1)] => Ok(VariantPackOptions { + complete: *complete == 1, + shredded_validity: *shredded_validity == 1, + }), + _ => vortex_bail!("invalid VariantPack options: {metadata:?}"), + } + } + + fn arity(&self, options: &Self::Options) -> Arity { + Arity::Exact(if options.shredded_validity { 3 } else { 2 }) + } + + fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName { + match child_idx { + 0 => ChildName::from("core"), + 1 => ChildName::from("shredded"), + 2 => ChildName::from("validity"), + _ => unreachable!("Invalid child index {child_idx} for VariantPack expression"), + } + } + + fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult { + vortex_ensure!( + arg_dtypes[0].is_variant(), + "VariantPack core storage must be a Variant, found {}", + arg_dtypes[0] + ); + if options.shredded_validity { + vortex_ensure!( + arg_dtypes[1].is_struct() && !arg_dtypes[1].is_nullable(), + "VariantPack takes the validity of a struct that is not nullable, found {}", + arg_dtypes[1] + ); + vortex_ensure_eq!( + arg_dtypes[2], + DType::Bool(Nullability::NonNullable), + "VariantPack validity must be a non-nullable boolean array" + ); + } + Ok(arg_dtypes[0].clone()) + } + + fn execute( + &self, + options: &Self::Options, + args: &dyn ExecutionArgs, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let shredded = args.get(1)?; + let shredded = if options.shredded_validity { + let fields = shredded.execute::(ctx)?; + StructArray::try_new( + fields.names().clone(), + fields.iter_unmasked_fields().cloned().collect::>(), + fields.len(), + Validity::Array(args.get(2)?), + )? + .into_array() + } else { + shredded + }; + Ok(VariantArray::try_new(args.get(0)?, Some(shredded))?.into_array()) + } +} From d75cdc0f53c0f22d5f452ef68c64a9d121d1a6b5 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Mon, 23 Nov 2026 16:39:56 +0000 Subject: [PATCH 2/3] Test each variant_get rule over VariantPack and take complete in try_new Each reduce rule is checked against the Variant that the pack builds, and against which child the reduced array reads. VariantPack::try_new takes complete as the variant_pack expression does, so it cannot be given options that need a validity child. Signed-off-by: Robert Kruszewski --- vortex-functions/src/variant_get/mod.rs | 103 ++++++++++++++++++++++++ vortex-functions/src/variant_pack.rs | 10 ++- 2 files changed, 110 insertions(+), 3 deletions(-) diff --git a/vortex-functions/src/variant_get/mod.rs b/vortex-functions/src/variant_get/mod.rs index 699a924f88a..955fbf86f1f 100644 --- a/vortex-functions/src/variant_get/mod.rs +++ b/vortex-functions/src/variant_get/mod.rs @@ -667,6 +667,7 @@ mod tests { use std::sync::Arc; use std::sync::LazyLock; + use rstest::rstest; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::IntoArray; @@ -676,8 +677,10 @@ mod tests { use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::ScalarFn; use vortex_array::arrays::StructArray; use vortex_array::arrays::VariantArray; + use vortex_array::arrays::scalar_fn::ScalarFnArrayExt; use vortex_array::arrays::variant::VariantArraySlotsExt; use vortex_array::assert_arrays_eq; use vortex_array::assert_nth_scalar_is_null; @@ -1430,4 +1433,104 @@ mod tests { assert!(result.is_invalid(1, &mut ctx)?); Ok(()) } + + /// How [`VariantGet`] over a [`VariantPack`] reduces. + #[derive(Debug, Clone, Copy)] + enum Reduced { + /// To a read of the shredded child alone. + ToShredded, + /// To an extraction from the core storage alone. + ToCore, + /// Not at all: the pack stays and executes to a whole Variant. + No, + } + + /// Variant objects whose field `a` is shredded as `i32` and field `n` as a shredded Variant, + /// over core storage that holds field `b`. When the pack is not complete, the core storage + /// also holds `a` for the last row, where the shredded `a` is null. + fn pack_over_core(complete: bool) -> VortexResult<(ArrayRef, ArrayRef, ArrayRef)> { + let b = |value: i32| Scalar::primitive(value, Nullability::NonNullable); + let last_row = if complete { + variant_object([("b", b(3))]) + } else { + variant_object([ + ("a", Scalar::primitive(7i32, Nullability::NonNullable)), + ("b", b(3)), + ]) + }; + let core = variant_rows([ + Scalar::variant(variant_object([("b", b(1))])), + Scalar::variant(variant_object([("b", b(2))])), + Scalar::variant(last_row), + ])?; + + let c = |value: i64| { + Scalar::variant(variant_object([( + "c", + Scalar::primitive(value, Nullability::NonNullable), + )])) + }; + let shredded = StructArray::try_new( + FieldNames::from_iter(["a", "n"]), + vec![ + PrimitiveArray::from_option_iter([Some(10i32), Some(20), None]).into_array(), + variant_rows([c(1), c(2), c(3)])?, + ], + 3, + Validity::NonNullable, + )? + .into_array(); + + let packed = VariantPack::try_new(core.clone(), shredded.clone(), complete)?.into_array(); + Ok((core, shredded, packed)) + } + + /// Each rule of [`VariantGet::reduce`] over a [`VariantPack`] extracts what the Variant that + /// the pack builds gives, and reads only the child that the rule says it reads. + #[rstest] + #[case::shredded_field_of_complete_pack(&["a"], PType::I32, true, Reduced::ToShredded)] + #[case::shredded_field_of_partial_pack(&["a"], PType::I32, false, Reduced::No)] + #[case::field_not_shredded(&["b"], PType::I32, true, Reduced::ToCore)] + #[case::path_into_shredded_variant(&["n", "c"], PType::I64, true, Reduced::ToShredded)] + #[case::leaf_of_other_type(&["a"], PType::I64, true, Reduced::No)] + fn variant_get_over_variant_pack_reduces( + #[case] path: &[&str], + #[case] ptype: PType, + #[case] complete: bool, + #[case] reduced: Reduced, + ) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let (core, shredded, packed) = pack_over_core(complete)?; + let expr = variant_get( + root(), + VariantPath::new(path.iter().map(|field| VariantPathElement::field(*field))), + Some(DType::Primitive(ptype, Nullability::Nullable)), + ); + + let actual = packed.apply(&expr)?.optimize_ctx(&ctx)?; + + let nodes = actual.depth_first_traversal().collect::>(); + let has_pack = nodes.iter().any(|node| { + node.as_opt::() + .is_some_and(|scalar_fn| scalar_fn.scalar_fn().id() == VariantPack.id()) + }); + // The optimizer can push the extraction into the chunks of `core`, so any of its arrays + // counts as reading it. + let core_nodes = core.depth_first_traversal().collect::>(); + let reads_core = nodes + .iter() + .any(|node| core_nodes.iter().any(|core_node| ArrayRef::ptr_eq(node, core_node))); + match reduced { + Reduced::ToShredded => assert!(!has_pack && !reads_core, "{actual}"), + Reduced::ToCore => assert!(!has_pack && reads_core, "{actual}"), + Reduced::No => assert!(has_pack, "{actual}"), + } + + let expected = VariantArray::try_new(core, Some(shredded))? + .into_array() + .apply(&expr)? + .execute::(&mut ctx)?; + assert_arrays_eq!(actual.execute::(&mut ctx)?, expected, &mut ctx); + Ok(()) + } } diff --git a/vortex-functions/src/variant_pack.rs b/vortex-functions/src/variant_pack.rs index 457cdf39c70..c156f0594b3 100644 --- a/vortex-functions/src/variant_pack.rs +++ b/vortex-functions/src/variant_pack.rs @@ -47,7 +47,8 @@ use vortex_session::registry::CachedId; pub struct VariantPack; impl VariantPack { - /// Creates a lazy Variant over `core` and `shredded`. + /// Creates a lazy Variant over `core` and `shredded`, which is `complete` or not; see + /// [`VariantPackOptions::complete`]. /// /// # Errors /// @@ -55,9 +56,12 @@ impl VariantPack { pub fn try_new( core: ArrayRef, shredded: ArrayRef, - options: VariantPackOptions, + complete: bool, ) -> VortexResult { - ScalarFnArray::try_new(VariantPack.bind(options), [core, shredded]) + ScalarFnArray::try_new( + VariantPack.bind(VariantPackOptions::new(complete)), + [core, shredded], + ) } /// Creates a lazy Variant over `core` and a `shredded` struct whose validity is `validity`. From 497a004dc15e166626bcb4c3591d82f29735f382 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Mon, 23 Nov 2026 14:40:12 -0500 Subject: [PATCH 3/3] Format the variant_get core-read check Co-Authored-By: Claude Opus 5.5 Signed-off-by: Will Manning --- vortex-functions/src/variant_get/mod.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/vortex-functions/src/variant_get/mod.rs b/vortex-functions/src/variant_get/mod.rs index 955fbf86f1f..293cf9bd350 100644 --- a/vortex-functions/src/variant_get/mod.rs +++ b/vortex-functions/src/variant_get/mod.rs @@ -1517,9 +1517,11 @@ mod tests { // The optimizer can push the extraction into the chunks of `core`, so any of its arrays // counts as reading it. let core_nodes = core.depth_first_traversal().collect::>(); - let reads_core = nodes - .iter() - .any(|node| core_nodes.iter().any(|core_node| ArrayRef::ptr_eq(node, core_node))); + let reads_core = nodes.iter().any(|node| { + core_nodes + .iter() + .any(|core_node| ArrayRef::ptr_eq(node, core_node)) + }); match reduced { Reduced::ToShredded => assert!(!has_pack && !reads_core, "{actual}"), Reduced::ToCore => assert!(!has_pack && reads_core, "{actual}"),