Skip to content
2 changes: 1 addition & 1 deletion encodings/parquet-variant/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand All @@ -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 }
73 changes: 68 additions & 5 deletions encodings/parquet-variant/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -376,12 +377,30 @@ fn inferred_shredded_field_validity(
/// `forward` then `inverse` is structure-preserving for the shapes canonicalization produces;
/// fields the forward transform omitted (Parquet wrapper shells with no `typed_value`) are served
/// from the residual `value` and are intentionally not reconstructed here.
///
/// Parquet has no union, so a union field is folded into the residual `value` of its shell, which
/// writes its values with the `metadata` of each row; see [`fold_union`]. Without `metadata`, a
/// union cannot be rebuilt.
pub(crate) fn parquet_typed_value_from_logical_shredded(
shredded: ArrayRef,
metadata: Option<&ArrayRef>,
ctx: &mut ExecutionCtx,
) -> VortexResult<ArrayRef> {
// 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::<List>() {
let list_view = shredded.execute::<ListViewArray>(ctx)?;
list_from_list_view(list_view, ctx)?.into_array()
} else {
shredded
};

if let Some(list_array) = shredded.as_opt::<List>() {
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()?;
Comment on lines 398 to +402

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize sliced lists before assigning element metadata

When exporting a union nested in a shredded list after the Variant has been sliced, a canonical ListArray can retain the original full element buffer and non-zero offsets (vortex-array/src/arrays/list/compute/slice.rs). This branch skips list_from_list_view, assigns metadata across elements.len(), and then folds every element, including the unreachable prefix and suffix, using the first retained row's metadata. If a discarded union element is an object containing a field absent from that row's metadata, fold_union rejects the export; other discarded elements can likewise be encoded against the wrong metadata. Reset the offsets and slice the elements before deriving element metadata and rebuilding the typed value.

Useful? React with 👍 / 👎.

let elements = parquet_shredded_field_from_logical(elements, metadata.as_ref(), ctx)?;
return Ok(ListArray::try_new(
elements,
list_array.offsets().clone(),
Expand Down Expand Up @@ -410,7 +429,11 @@ pub(crate) fn parquet_typed_value_from_logical_shredded(
.zip(struct_array.iter_unmasked_fields())
{
names.push(FieldName::from(name.as_ref()));
fields.push(parquet_shredded_field_from_logical(field.clone(), ctx)?);
fields.push(parquet_shredded_field_from_logical(
field.clone(),
metadata,
ctx,
)?);
}

Ok(StructArray::try_new(
Expand All @@ -426,10 +449,27 @@ pub(crate) fn parquet_typed_value_from_logical_shredded(
/// representation, the inverse of [`logical_shredded_from_parquet_field`].
fn parquet_shredded_field_from_logical(
logical_field: ArrayRef,
metadata: Option<&ArrayRef>,
ctx: &mut ExecutionCtx,
) -> VortexResult<ArrayRef> {
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::<Variant>() {
logical_field.execute::<VariantArray>(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::<Variant>() {
Expand All @@ -439,10 +479,21 @@ fn parquet_shredded_field_from_logical(
let value = core.value().cloned().ok_or_else(|| {
vortex_err!("cannot rebuild Parquet shredded field: partially shredded Variant has no residual value")
})?;

if let Some(union) = variant
.shredded()
.filter(|shredded| shredded.dtype().is_union())
{
let value = fold_union(union.clone(), Some(value), core.metadata(), ctx)?;
return value_shell(value, len);
}

let typed_value = variant
.shredded()
.cloned()
.map(|shredded| parquet_typed_value_from_logical_shredded(shredded, ctx))
.map(|shredded| {
parquet_typed_value_from_logical_shredded(shredded, Some(core.metadata()), ctx)
})
.transpose()?;

let mut names = vec![FieldName::from("value")];
Expand All @@ -461,7 +512,7 @@ fn parquet_shredded_field_from_logical(
}

// Fully shredded field: rebuild its typed subtree and wrap it in a `typed_value`-only shell.
let typed_value = parquet_typed_value_from_logical_shredded(logical_field, ctx)?;
let typed_value = parquet_typed_value_from_logical_shredded(logical_field, metadata, ctx)?;
Ok(StructArray::try_new(
FieldNames::from_iter([FieldName::from("typed_value")]),
vec![typed_value],
Expand All @@ -471,6 +522,17 @@ fn parquet_shredded_field_from_logical(
.into_array())
}

/// A Parquet shredded field shell that holds only the residual `value`.
fn value_shell(value: ArrayRef, len: usize) -> VortexResult<ArrayRef> {
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<ParquetVariant> {
/// Returns the outer row validity for the Variant values.
Expand Down Expand Up @@ -956,7 +1018,8 @@ mod tests {
.clone();

// Inverse transform: rebuild a Parquet `typed_value` and reattach it.
let rebuilt_typed_value = parquet_typed_value_from_logical_shredded(logical, &mut ctx)?;
let rebuilt_typed_value =
parquet_typed_value_from_logical_shredded(logical, None, &mut ctx)?;
let rebuilt = ParquetVariant::try_new(
ParquetVariantArrayExt::parquet_variant_validity(&core),
core.metadata().clone(),
Expand Down
120 changes: 120 additions & 0 deletions encodings/parquet-variant/src/arrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -172,6 +174,17 @@ pub(crate) fn prepare_variant_for_export(
let array = array.execute_until::<ParquetVariantExportable>(ctx)?;

if let Some(variant) = array.as_opt::<Variant>() {
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!(
Expand All @@ -180,6 +193,7 @@ pub(crate) fn prepare_variant_for_export(
);
Some(parquet_typed_value_from_logical_shredded(
shredded.clone(),
None,
ctx,
)?)
}
Expand Down Expand Up @@ -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<ArrayRef> {
let core = prepare_variant_for_export(core, None, ctx)?;
let storage = core.as_::<ParquetVariant>();
let metadata = storage.metadata().clone();

if shredded.dtype().is_union() {
let value = fold_union(shredded, storage.value().cloned(), &metadata, ctx)?;
Comment on lines +255 to +260

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve union field names when preparing a null core

When every value fits a union shredding, the residual core can be stored and read back as a constant Variant-null array. Preparing that core with typed_value = None synthesizes metadata with an empty field-name dictionary, but fold_union subsequently needs the names of any object-valued union member to encode its fields and rejects names absent from this dictionary. Thus exporting a file-read Variant whose union contains struct members can fail solely because compression made its empty residual core constant. Build the synthesized metadata using names collected from shredded, or otherwise retain the original metadata before folding the union.

Useful? React with 👍 / 👎.

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.
///
Expand Down Expand Up @@ -527,11 +569,16 @@ mod tests {
use vortex_array::arrays::ChunkedArray;
use vortex_array::arrays::ConstantArray;
use vortex_array::arrays::ListArray;
use vortex_array::arrays::ListViewArray;
use vortex_array::arrays::MaskedArray;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::Struct;
use vortex_array::arrays::StructArray as VortexStructArray;
use vortex_array::arrays::VarBinViewArray;
use vortex_array::arrays::Variant;
use vortex_array::arrays::VariantArray;
use vortex_array::arrays::struct_::StructArrayExt;
use vortex_array::arrays::variant::VariantArraySlotsExt;
use vortex_array::assert_arrays_eq;
use vortex_array::dtype::DType;
use vortex_array::dtype::FieldNames;
Expand All @@ -544,6 +591,8 @@ mod tests {
use vortex_buffer::buffer;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_functions::variant_pack::VariantPack;
use vortex_functions::variant_pack::VariantPackOptions;
use vortex_session::VortexSession;

use super::PARQUET_VARIANT_ARROW_EXTENSION_NAME;
Expand Down Expand Up @@ -751,6 +800,77 @@ mod tests {
Ok(())
}

/// A partially shredded field read from a file is a lazy pack of its stored columns. It must
/// export as a `{value, typed_value}` field, as the canonical Variant does, and not as a
/// typed leaf of Variant storage.
#[rstest]
fn test_export_lazy_nested_residual(session: VortexSession) -> VortexResult<()> {
let core =
ConstantArray::new(Scalar::null(DType::Variant(Nullability::Nullable)), 2).into_array();
let nested = shredded_with_nested_residual()?;
let nested = nested.as_::<Struct>();
let a = nested.unmasked_field_by_name("a")?.as_::<Variant>();
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<ArrayRef> {
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::<ListViewArray>(&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();
Expand Down
Loading
Loading