This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-12245-a6c684842b8b224790f8bba8f31c12c05482fb91 in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit e28432bd5cfd834a08aedbc31bb6a3766362b44d Author: Kosta Tarasov <[email protected]> AuthorDate: Tue Nov 17 22:36:40 2026 +0000 [Variant] Validate storage fields in `VariantType` (#12245) # Which issue does this PR close? - Closes #11938. # Rationale for this change `VariantType` accepted any `Struct` as storage, so `try_new`, `validate` and `Field::try_canonical_extension_type` treated structs like `Struct("unrelated": Int32)` as Variant. Extension wrappers such as DataFusion's `DFVariant` (apache/datafusion#26822) should be able to delegate this check to the Arrow type instead of building a `VariantArray`. # What changes are included in this PR? `VariantType::supports_data_type` now requires a struct with a binary `metadata` field (or a dictionary or run-end encoded array of binary) and at least one of a binary `value` field and a `typed_value` field. These are the top-level checks `VariantArray::try_new` already applied, and `try_new` now calls this check instead of its own, so everything `VariantArray` reads still passes. That includes shredded storage without `value`, and the Parquet reader, which attaches `VariantType` to every VARIANT column. `try_new` runs it before canonicalizing shredded types, so a non-Variant struct reports the storage error rather than an illegal shredded type. Nullability is deliberately not checked, to keep reads lenient: arrow-rs wrote unshredded `value` as nullable before #10320, and those files must still read. `typed_value` types and nested shredded groups stay with `VariantArray`. Each failed check reports its own error, reusing the wording of `VariantArray`'s former per-field messages with `VariantType` in place of `VariantArray`. The storage layout is now documented on `VariantType`, and `VariantArray::try_new` links to it. # Are these changes tested? Yes. New unit tests in `variant.rs` cover accepted layouts (each binary type, dictionary and run-end encoded `metadata`, shredded, and `typed_value` without `value`) and rejected ones, asserting the error message for each. `VariantArray::try_new`'s per-field error tests duplicated these cases, so a single test replaces them, checking that the storage error is reported before canonicalization's illegal shredded type error. The other `parquet-variant-compute` and `parquet` Variant tests, including `variant_integration`, pass unchanged. # Are there any significant user-facing changes? Storage types that are not Variant storage now fail `VariantType::try_new` and `validate`, so `Field::with_extension_type(VariantType)` panics on them and `try_with_extension_type` returns an error. Code that tagged placeholder structs such as `Struct(Fields::empty())` needs a real storage type. `VariantArray::try_new` now reports invalid storage with `VariantType`'s errors. They keep the old per-field wording but name `VariantType`, a non-struct input reports `VariantType only supports StructArray, got ...`, and a struct with neither `value` nor `typed_value` now says either field is accepted. # AI usage disclosure Implementation and tests prepared with Claude Code. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]> --- arrow-schema/src/extension/canonical/variant.rs | 160 ++++++++++++++++++++++-- parquet-variant-compute/src/variant_array.rs | 141 ++++----------------- 2 files changed, 178 insertions(+), 123 deletions(-) diff --git a/arrow-schema/src/extension/canonical/variant.rs b/arrow-schema/src/extension/canonical/variant.rs index 178fac135b..0d8e0538a4 100644 --- a/arrow-schema/src/extension/canonical/variant.rs +++ b/arrow-schema/src/extension/canonical/variant.rs @@ -13,6 +13,21 @@ use crate::{ArrowError, DataType}; /// See [`VariantArray`] in the `parquet-variant-compute` crate for more examples /// of using this extension type. /// +/// # Storage +/// +/// The storage type must be a struct with the following fields, in any order: +/// +/// 1. `metadata`: binary, large_binary, or binary_view, optionally dictionary +/// or run-end encoded +/// +/// 2. `value`: binary, large_binary, or binary_view, required unless +/// `typed_value` is present +/// +/// 3. `typed_value`: optional shredded values +/// +/// The `typed_value` types and the encoded bytes are not checked here, see +/// [`VariantArray`]. +/// /// [`VariantArray`]: https://docs.rs/parquet-variant-compute/latest/parquet_variant_compute/struct.VariantArray.html #[derive(Debug, Clone, PartialEq)] pub struct VariantType; @@ -37,12 +52,48 @@ impl ExtensionType for VariantType { } fn supports_data_type(&self, data_type: &DataType) -> Result<(), ArrowError> { - if matches!(data_type, DataType::Struct(_)) { - Ok(()) - } else { - Err(ArrowError::InvalidArgumentError(format!( + // `DataType::is_binary` also accepts FixedSizeBinary + let is_binary = |data_type: &DataType| { + matches!( + data_type, + DataType::Binary | DataType::LargeBinary | DataType::BinaryView + ) + }; + let err = |message: String| Err(ArrowError::InvalidArgumentError(message)); + + let DataType::Struct(fields) = data_type else { + return err(format!( "VariantType only supports StructArray, got {data_type}" - ))) + )); + }; + + let Some((_, metadata)) = fields.find("metadata") else { + return err( + "Invalid VariantType: StructArray must contain a 'metadata' field".to_string(), + ); + }; + let metadata_ok = match metadata.data_type() { + DataType::Dictionary(_, values) => is_binary(values), + DataType::RunEndEncoded(_, values) => is_binary(values.data_type()), + other => is_binary(other), + }; + if !metadata_ok { + return err(format!( + "VariantType 'metadata' field must be Binary, LargeBinary, BinaryView, or a Dictionary or RunEndEncoded array of one of those types, got {}", + metadata.data_type() + )); + } + + match fields.find("value") { + Some((_, value)) if !is_binary(value.data_type()) => err(format!( + "VariantType 'value' field must be Binary, LargeBinary, or BinaryView, got {}", + value.data_type() + )), + None if fields.find("typed_value").is_none() => err( + "Invalid VariantType: StructArray must contain a 'value' or 'typed_value' field" + .to_string(), + ), + _ => Ok(()), } } @@ -61,17 +112,71 @@ mod tests { use super::*; use crate::extension::CanonicalExtensionType; use crate::{Field, Fields}; + use std::sync::Arc; + + fn storage(fields: Vec<Field>) -> DataType { + DataType::Struct(Fields::from(fields)) + } + + fn metadata(data_type: DataType) -> Field { + Field::new("metadata", data_type, false) + } + + fn value(data_type: DataType) -> Field { + Field::new("value", data_type, true) + } + + fn typed_value(data_type: DataType) -> Field { + Field::new("typed_value", data_type, true) + } #[test] - fn variant_type_requires_struct() { - let field = Field::new("v", DataType::Struct(Fields::empty()), true) - .with_extension_type(VariantType); + fn variant_type_canonical_extension() { + let data_type = storage(vec![ + metadata(DataType::BinaryView), + value(DataType::BinaryView), + ]); + let field = Field::new("v", data_type, true).with_extension_type(VariantType); assert!(field.has_valid_extension_type::<VariantType>()); assert_eq!( field.try_canonical_extension_type().unwrap(), CanonicalExtensionType::Variant(VariantType), ); + } + #[test] + fn variant_type_accepts_valid_storage() { + let dictionary = DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Binary)); + let run_end_encoded = DataType::RunEndEncoded( + Arc::new(Field::new("run_ends", DataType::Int32, false)), + Arc::new(Field::new("values", DataType::LargeBinary, true)), + ); + let valid = [ + storage(vec![metadata(DataType::Binary), value(DataType::Binary)]), + storage(vec![ + value(DataType::LargeBinary), + metadata(DataType::LargeBinary), + ]), + storage(vec![metadata(dictionary), value(DataType::BinaryView)]), + storage(vec![metadata(run_end_encoded), value(DataType::BinaryView)]), + storage(vec![ + metadata(DataType::BinaryView), + value(DataType::BinaryView), + typed_value(DataType::Int64), + ]), + // Allowed by the Arrow spec, though the Parquet shredding spec requires `value` + storage(vec![ + metadata(DataType::BinaryView), + typed_value(DataType::Utf8), + ]), + ]; + for data_type in valid { + VariantType::validate(&data_type, "").unwrap(); + } + } + + #[test] + fn variant_type_rejects_invalid_storage() { let err = Field::new("v", DataType::Binary, true) .try_with_extension_type(VariantType) .unwrap_err(); @@ -79,5 +184,44 @@ mod tests { err.to_string(), "Invalid argument error: VariantType only supports StructArray, got Binary" ); + + let invalid = [ + ( + storage(vec![Field::new("unrelated", DataType::Int32, false)]), + "Invalid VariantType: StructArray must contain a 'metadata' field", + ), + ( + storage(vec![ + metadata(DataType::FixedSizeBinary(16)), + value(DataType::BinaryView), + ]), + "VariantType 'metadata' field must be Binary, LargeBinary, BinaryView, or a Dictionary or RunEndEncoded array of one of those types, got FixedSizeBinary(16)", + ), + ( + storage(vec![ + metadata(DataType::Dictionary( + Box::new(DataType::Int8), + Box::new(DataType::Utf8), + )), + value(DataType::BinaryView), + ]), + "VariantType 'metadata' field must be Binary, LargeBinary, BinaryView, or a Dictionary or RunEndEncoded array of one of those types, got Dictionary(Int8, Utf8)", + ), + ( + storage(vec![metadata(DataType::BinaryView), value(DataType::Utf8)]), + "VariantType 'value' field must be Binary, LargeBinary, or BinaryView, got Utf8", + ), + ( + storage(vec![metadata(DataType::BinaryView)]), + "Invalid VariantType: StructArray must contain a 'value' or 'typed_value' field", + ), + ]; + for (data_type, expected) in invalid { + let err = VariantType::validate(&data_type, "").unwrap_err(); + assert_eq!( + err.to_string(), + format!("Invalid argument error: {expected}") + ); + } } } diff --git a/parquet-variant-compute/src/variant_array.rs b/parquet-variant-compute/src/variant_array.rs index 46faa20992..bbd17c4611 100644 --- a/parquet-variant-compute/src/variant_array.rs +++ b/parquet-variant-compute/src/variant_array.rs @@ -21,7 +21,7 @@ use arrow::datatypes::{ TimestampMicrosecondType, TimestampNanosecondType, }; use arrow::error::Result; -use arrow_schema::extension::Uuid as UuidExtension; +use arrow_schema::extension::{ExtensionType, Uuid as UuidExtension}; use arrow_schema::{ArrowError, DataType, Field, FieldRef, TimeUnit}; use chrono::{DateTime, NaiveTime}; use parquet_variant::{ @@ -92,25 +92,6 @@ pub(crate) fn validate_binary_array(array: &dyn Array, field_name: &str) -> Resu } } -/// Validates that a metadata array has binary-like logical values. -fn validate_metadata_array(array: &dyn Array) -> Result<()> { - let is_binary = |data_type: &DataType| { - matches!( - data_type, - DataType::Binary | DataType::LargeBinary | DataType::BinaryView - ) - }; - match array.data_type() { - data_type if is_binary(data_type) => Ok(()), - DataType::Dictionary(_, values) if is_binary(values) => Ok(()), - DataType::RunEndEncoded(_, values) if is_binary(values.data_type()) => Ok(()), - _ => Err(ArrowError::InvalidArgumentError(format!( - "VariantArray 'metadata' field must be Binary, LargeBinary, BinaryView, or a Dictionary or RunEndEncoded array of one of those types, got {}", - array.data_type() - ))), - } -} - /// An array of Parquet [`Variant`] values /// /// A [`VariantArray`] wraps an Arrow [`StructArray`] that stores the underlying @@ -274,39 +255,26 @@ impl VariantArray { /// - A new instance of `VariantArray`. /// /// # Errors: - /// - If the `StructArray` does not contain the required fields + /// - If the data type is not valid [`VariantType`] storage + /// - If `typed_value` contains a type that cannot be shredded /// /// # Requirements of the `StructArray` /// - /// 1. A required field named `metadata` which is binary, large_binary, or - /// binary_view, optionally dictionary or run-end-encoded - /// - /// 2. A required field named `value` that is binary, large_binary, or - /// binary_view - /// - /// 3. An optional field named `typed_value` which can be any primitive type - /// or be a list, large_list, fixed_size_list, list_view or struct. Fixed-size lists are - /// normalized to variable-length lists on read. + /// See [`VariantType`] for the required fields. `typed_value` can be any + /// primitive type or be a list, large_list, fixed_size_list, list_view or + /// struct. Fixed-size lists are normalized to variable-length lists on read. /// pub fn try_new(inner: &dyn Array) -> Result<Self> { + // Before canonicalizing, which would report a non-Variant struct's fields as illegal + // shredded types + VariantType.supports_data_type(inner.data_type())?; + // Canonicalize shredded typed_value fields (e.g. decimal narrowing) let inner = canonicalize_shredded_types(inner)?; - - let Some(inner) = inner.as_struct_opt() else { - return Err(ArrowError::InvalidArgumentError( - "Invalid VariantArray: requires StructArray as input".to_string(), - )); - }; - - // Note the specification allows for any order so we must search by name - - // Ensure the StructArray has a metadata field with binary-like logical values - let Some(metadata_col) = inner.column_by_name("metadata") else { - return Err(ArrowError::InvalidArgumentError( - "Invalid VariantArray: StructArray must contain a 'metadata' field".to_string(), - )); - }; - validate_metadata_array(metadata_col.as_ref())?; + let inner = inner.as_struct(); + let metadata_col = inner + .column_by_name("metadata") + .expect("checked by VariantType"); let shredding_state = ShreddingState::try_from(inner)?; @@ -1313,33 +1281,25 @@ mod test { use arrow::array::{ BinaryArray, BinaryDictionaryBuilder, BinaryRunBuilder, BinaryViewArray, Decimal32Array, Decimal64Array, Decimal128Array, FixedSizeBinaryArray, FixedSizeListArray, Int8Array, - Int32Array, Int64Array, LargeBinaryArray, LargeListArray, LargeListViewArray, ListArray, - ListViewArray, StringArray, Time64MicrosecondArray, + Int64Array, LargeBinaryArray, LargeListArray, LargeListViewArray, ListArray, ListViewArray, + StringArray, Time64MicrosecondArray, UInt8Array, }; use arrow::buffer::{OffsetBuffer, ScalarBuffer}; use arrow_schema::{Field, Fields}; use parquet_variant::{EMPTY_VARIANT_METADATA_BYTES, ShortString}; #[test] - fn invalid_not_a_struct_array() { - let array = make_binary_view_array(); - // Should fail because the input is not a StructArray - let err = VariantArray::try_new(&array); - assert_eq!( - err.unwrap_err().to_string(), - "Invalid argument error: Invalid VariantArray: requires StructArray as input" - ); - } - - #[test] - fn invalid_missing_metadata() { - let fields = Fields::from(vec![Field::new("value", DataType::BinaryView, true)]); - let array = StructArray::new(fields, vec![make_binary_view_array()], None); - // Should fail because the StructArray does not contain a 'metadata' field - let err = VariantArray::try_new(&array); + fn invalid_storage_checked_before_canonicalizing() { + // `UInt8` is also an illegal shredded type, but the storage error must win + let array = StructArrayAssembler::new() + .with_field("metadata", make_binary_view_array(), false) + .with_field("value", Arc::new(UInt8Array::from(vec![1])), true) + .build() + .unwrap(); + let err = VariantArray::try_new(&array).unwrap_err(); assert_eq!( - err.unwrap_err().to_string(), - "Invalid argument error: Invalid VariantArray: StructArray must contain a 'metadata' field" + err.to_string(), + "Invalid argument error: VariantType 'value' field must be Binary, LargeBinary, or BinaryView, got UInt8" ); } @@ -1366,33 +1326,6 @@ mod test { assert_eq!(variant_array.value(0), Variant::from(1i64)); assert_eq!(variant_array.value(1), Variant::Null); assert_eq!(variant_array.value(2), Variant::from(3i64)); - - // With no `typed_value` either, there is nothing to read, so `value` stays required. - let fields = Fields::from(vec![Field::new("metadata", DataType::BinaryView, false)]); - let metadata_only = StructArray::new(fields, vec![make_binary_view_array()], None); - let err = VariantArray::try_new(&metadata_only); - assert_eq!( - err.unwrap_err().to_string(), - "Invalid argument error: Invalid VariantArray: StructArray must contain a 'value' field" - ); - } - - #[test] - fn invalid_metadata_field_type() { - let fields = Fields::from(vec![ - Field::new("metadata", DataType::Int32, true), // not supported - Field::new("value", DataType::BinaryView, true), - ]); - let array = StructArray::new( - fields, - vec![make_int32_array(), make_binary_view_array()], - None, - ); - let err = VariantArray::try_new(&array); - assert_eq!( - err.unwrap_err().to_string(), - "Invalid argument error: VariantArray 'metadata' field must be Binary, LargeBinary, BinaryView, or a Dictionary or RunEndEncoded array of one of those types, got Int32" - ); } #[test] @@ -1459,32 +1392,10 @@ mod test { } } - #[test] - fn invalid_value_field_type() { - let fields = Fields::from(vec![ - Field::new("metadata", DataType::BinaryView, true), - Field::new("value", DataType::Int32, true), - ]); - let array = StructArray::new( - fields, - vec![make_binary_view_array(), make_int32_array()], - None, - ); - let err = VariantArray::try_new(&array); - assert_eq!( - err.unwrap_err().to_string(), - "Invalid argument error: VariantArray 'value' field must be Binary, LargeBinary, or BinaryView, got Int32" - ); - } - fn make_binary_view_array() -> ArrayRef { Arc::new(BinaryViewArray::from(vec![b"test" as &[u8]])) } - fn make_int32_array() -> ArrayRef { - Arc::new(Int32Array::from(vec![1])) - } - fn make_variant_struct_with_typed_value(typed_value: ArrayRef) -> StructArray { let metadata = BinaryViewArray::from_iter_values(std::iter::repeat_n( EMPTY_VARIANT_METADATA_BYTES,
