This is an automated email from the ASF dual-hosted git repository.
yihua pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/hudi-rs.git
The following commit(s) were added to refs/heads/main by this push:
new dd3272e2 feat(core): complete variant reads with shredded
reconstruction (#1086)
dd3272e2 is described below
commit dd3272e2dfe5d97db4226f1743ce40d1fa5735da
Author: Xuanyi Li <[email protected]>
AuthorDate: Sat Dec 5 12:25:55 2026 -0800
feat(core): complete variant reads with shredded reconstruction (#1086)
## Motivation
Complete end-to-end unshredded Variant reads and shredded reconstruction
after #631, the next step in #630. Avro named-type references still reach an
unimplemented conversion, nullable wrappers lose Variant extension metadata,
and generic schema projection can discard shredded payloads.
## Modification
Resolve named Avro types and preserve Variant metadata through nullable
fields and containers. Route Variant tables through the Hudi file-group reader
in DataFusion so schema reconciliation keeps their payload intact. Leave
unsupported Variant predicates to DataFusion. Reconstruct shredded values with
Arrow before projection can discard `typed_value`, preserving typed/residual
fallback across mixed file layouts and nested containers. Decode shredded Avro
logs at their writer schema be [...]
```text
Hudi Avro schema -> named-type resolution -> Arrow Variant fields
|
COW base / MOR base + logs -> Hudi file-group read -> reconstruct /
reconcile
|
Rust / DataFusion / Arrow bindings
```
Preserve upstream's handling of local timestamps and malformed Variant
records.
The change exceeds the usual PR size because it includes Java Avro
name-resolution compatibility, four reproducible multi-column fixtures, their
generator, and checks through both the core and DataFusion readers. These cover
tables where several columns reference the same Variant record.
Refs #630.
---
README.md | 1 +
crates/core/src/avro_to_arrow/schema.rs | 323 ++++++++++--------
crates/core/src/file_group/log_file/avro.rs | 71 +++-
crates/core/src/file_group/log_file/content.rs | 63 +++-
.../src/file_group/reader_v2/output_converter.rs | 6 +
crates/core/src/schema/avro_names.rs | 330 ++++++++++++++++++
crates/core/src/schema/batch_evolution.rs | 21 ++
crates/core/src/schema/mod.rs | 2 +
crates/core/src/schema/resolver.rs | 5 +-
crates/core/src/schema/variant.rs | 176 ++++++++++
crates/core/tests/variant_read_tests.rs | 380 +++++++++++++++++++++
crates/datafusion/Cargo.toml | 1 +
crates/datafusion/src/lib.rs | 22 +-
crates/datafusion/tests/variant_read_tests.rs | 79 +++++
crates/test/data/variant/README.md | 56 +++
crates/test/data/variant/generate.py | 120 +++++++
crates/test/data/variant/variant_cow.zip | Bin 0 -> 90526 bytes
crates/test/data/variant/variant_mor_avro.zip | Bin 0 -> 104069 bytes
crates/test/data/variant/variant_mor_spark.zip | Bin 0 -> 88480 bytes
crates/test/data/variant/variant_multi_cow.zip | Bin 0 -> 123004 bytes
crates/test/data/variant/variant_multi_mor.zip | Bin 0 -> 115953 bytes
crates/test/data/variant/variant_shredded_cow.zip | Bin 0 -> 138300 bytes
.../data/variant/variant_shredded_mixed_cow.zip | Bin 0 -> 88703 bytes
crates/test/data/variant/variant_shredded_mor.zip | Bin 0 -> 129126 bytes
crates/test/src/lib.rs | 1 +
crates/test/src/variant.rs | 81 +++++
docs/reader-spec.md | 17 +
python/hudi/_internal.pyi | 4 +
python/tests/test_variant_read.py | 40 +++
29 files changed, 1654 insertions(+), 145 deletions(-)
diff --git a/README.md b/README.md
index e4c7e9b0..11080ede 100644
--- a/README.md
+++ b/README.md
@@ -67,6 +67,7 @@ bindings. It creates, writes, and reads Hudi tables from Rust
and Python in a si
| Table services | Merge-on-read compaction (experimental: on demand,
inline, or in the background), rollback of failed writes, timeline archival |
| Metadata table | File listings, column and partition stats, record-level
index, kept up to date on every write and compacted as it grows (on by default)
|
| Base file formats | Parquet (read and write), Lance (read), HFile (metadata
table) |
+| Variant columns | Read, shredded or not; see the [reader
spec](docs/reader-spec.md#variant-columns) |
| Storage | Local file system, Amazon S3, Azure Blob Storage, Google
Cloud Storage |
| APIs | Rust and Python (read and write); C++ and a C ABI
(`hudi-ffi`) for file-slice reads |
| Query engines | [Apache DataFusion](#apache-datafusion) (`datafusion`
feature in Rust, included in Python); see [Other
Integrations](#other-integrations) |
diff --git a/crates/core/src/avro_to_arrow/schema.rs
b/crates/core/src/avro_to_arrow/schema.rs
index 9a29b6b3..52a4a4c2 100644
--- a/crates/core/src/avro_to_arrow/schema.rs
+++ b/crates/core/src/avro_to_arrow/schema.rs
@@ -15,14 +15,15 @@
// specific language governing permissions and limitations
// under the License.
-use crate::error::Result;
+use crate::error::{CoreError, Result};
use apache_avro::Schema as AvroSchema;
use apache_avro::schema::{Alias, DecimalSchema, EnumSchema, FixedSchema, Name,
RecordSchema};
+use apache_avro::schema::{NamesRef, ResolvedSchema};
use apache_avro::types::Value;
use arrow::datatypes::{DataType, IntervalUnit, Schema, TimeUnit, UnionMode};
use arrow::datatypes::{Field, UnionFields};
use parquet::variant::VariantType;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::Arc;
/// Timezone an Avro `timestamp-*` logical type denotes, per the Avro spec.
@@ -32,11 +33,16 @@ const HUDI_VARIANT_LOGICAL_TYPE: &str = "variant";
/// Converts an avro schema to an arrow schema
pub fn to_arrow_schema(avro_schema: &apache_avro::Schema) -> Result<Schema> {
+ let resolved = ResolvedSchema::try_from(avro_schema)?;
+ let mut converter = SchemaConverter {
+ names: resolved.get_names(),
+ resolving: HashSet::new(),
+ };
let mut schema_fields = vec![];
match avro_schema {
AvroSchema::Record(RecordSchema { fields, .. }) => {
for field in fields {
- schema_fields.push(schema_to_field_with_props(
+ schema_fields.push(converter.field(
&field.schema,
Some(&field.name),
field.is_nullable(),
@@ -44,154 +50,164 @@ pub fn to_arrow_schema(avro_schema: &apache_avro::Schema)
-> Result<Schema> {
)?)
}
}
- schema => schema_fields.push(schema_to_field(schema, Some(""),
false)?),
+ schema => schema_fields.push(converter.field(schema, Some(""), false,
None)?),
}
let schema = Schema::new(schema_fields);
Ok(schema)
}
-fn schema_to_field(
- schema: &apache_avro::Schema,
- name: Option<&str>,
- nullable: bool,
-) -> Result<Field> {
- schema_to_field_with_props(schema, name, nullable, Default::default())
-}
-
/// Arrow's conventional name for a map's entry struct, and what the parquet
/// reader produces — the two schemas have to agree by name to reconcile.
pub(crate) const MAP_ENTRIES_FIELD: &str = "key_value";
-fn schema_to_field_with_props(
- schema: &AvroSchema,
- name: Option<&str>,
- nullable: bool,
- props: Option<HashMap<String, String>>,
-) -> Result<Field> {
- let mut nullable = nullable;
- let field_type: DataType = match schema {
- AvroSchema::Ref { .. } => todo!("Add support for AvroSchema::Ref"),
- AvroSchema::Null => DataType::Null,
- AvroSchema::Boolean => DataType::Boolean,
- AvroSchema::Int => DataType::Int32,
- AvroSchema::Long => DataType::Int64,
- AvroSchema::Float => DataType::Float32,
- AvroSchema::Double => DataType::Float64,
- AvroSchema::Bytes => DataType::Binary,
- AvroSchema::String => DataType::Utf8,
- AvroSchema::Array(item_schema) =>
DataType::List(Arc::new(schema_to_field_with_props(
- &item_schema.items,
- Some("element"),
- false,
- None,
- )?)),
- AvroSchema::Map(value_schema) => {
- // An Arrow dictionary key must be an integer, so the
`Dictionary(Utf8, V)`
- // this used to produce was not a valid type and could not
reconcile
- // against the `Map` a parquet base file carries. Avro map keys are
- // always strings, and the entry struct is never null.
- let value_field =
- schema_to_field_with_props(&value_schema.types, Some("value"),
true, None)?;
- let entries = Field::new(
- MAP_ENTRIES_FIELD,
- DataType::Struct(
- vec![Field::new("key", DataType::Utf8, false),
value_field].into(),
- ),
+struct SchemaConverter<'a> {
+ names: &'a NamesRef<'a>,
+ resolving: HashSet<Name>,
+}
+
+impl SchemaConverter<'_> {
+ fn field(
+ &mut self,
+ schema: &AvroSchema,
+ name: Option<&str>,
+ nullable: bool,
+ props: Option<HashMap<String, String>>,
+ ) -> Result<Field> {
+ let mut nullable = nullable;
+ let field_type: DataType = match schema {
+ AvroSchema::Ref { name: reference } => {
+ let referred = self.names.get(reference).ok_or_else(|| {
+ CoreError::Schema(format!("Unknown Avro schema reference
'{reference}'"))
+ })?;
+ if !self.resolving.insert(reference.clone()) {
+ return Err(CoreError::Unsupported(format!(
+ "Recursive Avro schema '{reference}' cannot be
represented as Arrow"
+ )));
+ }
+ let field = self.field(referred, name, nullable, props);
+ self.resolving.remove(reference);
+ return field;
+ }
+ AvroSchema::Null => DataType::Null,
+ AvroSchema::Boolean => DataType::Boolean,
+ AvroSchema::Int => DataType::Int32,
+ AvroSchema::Long => DataType::Int64,
+ AvroSchema::Float => DataType::Float32,
+ AvroSchema::Double => DataType::Float64,
+ AvroSchema::Bytes => DataType::Binary,
+ AvroSchema::String => DataType::Utf8,
+ AvroSchema::Array(item_schema) =>
DataType::List(Arc::new(self.field(
+ &item_schema.items,
+ Some("element"),
false,
- );
- DataType::Map(Arc::new(entries), false)
- }
- AvroSchema::Union(us) => {
- // If there are only two variants and one of them is null, set the
other type as the field data type
- let has_nullable = us
-
.find_schema_with_known_schemata::<apache_avro::Schema>(&Value::Null, None,
&None)
- .is_some();
- let sub_schemas = us.variants();
- if has_nullable && sub_schemas.len() == 2 {
- nullable = true;
- if let Some(schema) = sub_schemas
- .iter()
- .find(|&schema| !matches!(schema, AvroSchema::Null))
- {
- schema_to_field_with_props(schema, None, has_nullable,
None)?
- .data_type()
- .clone()
- } else {
- return Err(apache_avro::Error::new(
- apache_avro::error::Details::GetUnionDuplicate,
+ None,
+ )?)),
+ AvroSchema::Map(value_schema) => {
+ // An Arrow dictionary key must be an integer, so the
`Dictionary(Utf8, V)`
+ // this used to produce was not a valid type and could not
reconcile
+ // against the `Map` a parquet base file carries. Avro map
keys are
+ // always strings, and the entry struct is never null.
+ let value_field = self.field(&value_schema.types,
Some("value"), true, None)?;
+ let entries = Field::new(
+ MAP_ENTRIES_FIELD,
+ DataType::Struct(
+ vec![Field::new("key", DataType::Utf8, false),
value_field].into(),
+ ),
+ false,
+ );
+ DataType::Map(Arc::new(entries), false)
+ }
+ AvroSchema::Union(us) => {
+ // If there are only two variants and one of them is null, set
the other type as the field data type
+ let has_nullable = us
+ .find_schema_with_known_schemata::<apache_avro::Schema>(
+ &Value::Null,
+ None,
+ &None,
)
- .into());
+ .is_some();
+ let sub_schemas = us.variants();
+ if has_nullable && sub_schemas.len() == 2 {
+ nullable = true;
+ if let Some(schema) = sub_schemas
+ .iter()
+ .find(|&schema| !matches!(schema, AvroSchema::Null))
+ {
+ return self.field(schema, name, true, props);
+ } else {
+ return Err(apache_avro::Error::new(
+ apache_avro::error::Details::GetUnionDuplicate,
+ )
+ .into());
+ }
+ } else {
+ let fields = sub_schemas
+ .iter()
+ .map(|s| self.field(s, None, has_nullable, None))
+ .collect::<Result<Vec<Field>>>()?;
+ let type_ids = 0_i8..fields.len() as i8;
+ DataType::Union(UnionFields::try_new(type_ids, fields)?,
UnionMode::Dense)
}
- } else {
- let fields = sub_schemas
+ }
+ AvroSchema::Record(RecordSchema { fields, .. }) => {
+ let fields: Result<_> = fields
.iter()
- .map(|s| schema_to_field_with_props(s, None, has_nullable,
None))
- .collect::<Result<Vec<Field>>>()?;
- let type_ids = 0_i8..fields.len() as i8;
- DataType::Union(UnionFields::try_new(type_ids, fields)?,
UnionMode::Dense)
+ .map(|field| {
+ let mut props = HashMap::new();
+ if let Some(doc) = &field.doc {
+ props.insert("avro::doc".to_string(), doc.clone());
+ }
+ /*if let Some(aliases) = fields.aliases {
+ props.insert("aliases", aliases);
+ }*/
+ self.field(&field.schema, Some(&field.name), false,
Some(props))
+ })
+ .collect();
+ DataType::Struct(fields?)
}
- }
- AvroSchema::Record(RecordSchema { fields, .. }) => {
- let fields: Result<_> = fields
- .iter()
- .map(|field| {
- let mut props = HashMap::new();
- if let Some(doc) = &field.doc {
- props.insert("avro::doc".to_string(), doc.clone());
- }
- /*if let Some(aliases) = fields.aliases {
- props.insert("aliases", aliases);
- }*/
- schema_to_field_with_props(&field.schema,
Some(&field.name), false, Some(props))
- })
- .collect();
- DataType::Struct(fields?)
- }
- AvroSchema::Enum(EnumSchema { .. }) => DataType::Utf8,
- AvroSchema::Fixed(FixedSchema { size, .. }) =>
DataType::FixedSizeBinary(*size as i32),
- AvroSchema::Decimal(DecimalSchema {
- precision, scale, ..
- }) => DataType::Decimal128(*precision as u8, *scale as i8),
- AvroSchema::BigDecimal => DataType::LargeBinary,
- AvroSchema::Uuid => DataType::FixedSizeBinary(16),
- AvroSchema::Date => DataType::Date32,
- AvroSchema::TimeMillis => DataType::Time32(TimeUnit::Millisecond),
- AvroSchema::TimeMicros => DataType::Time64(TimeUnit::Microsecond),
- // Avro's `timestamp-*` logical types are instants in UTC; the
- // timezone-naive variants are `local-timestamp-*` below. Carrying the
- // zone matters beyond correctness: a parquet base file reads back as
- // `Timestamp(_, "UTC")`, so dropping it here makes a log batch fail to
- // concatenate with the base batch it is merged against.
- AvroSchema::TimestampMillis => {
- DataType::Timestamp(TimeUnit::Millisecond,
Some(UTC_TIMEZONE.into()))
- }
- AvroSchema::TimestampMicros => {
- DataType::Timestamp(TimeUnit::Microsecond,
Some(UTC_TIMEZONE.into()))
- }
- AvroSchema::TimestampNanos => {
- DataType::Timestamp(TimeUnit::Nanosecond,
Some(UTC_TIMEZONE.into()))
- }
- // Timezone-naive: no zone, matching arrow-avro's decode of these
types and
- // a parquet base file written with isAdjustedToUTC=false.
- AvroSchema::LocalTimestampMillis =>
DataType::Timestamp(TimeUnit::Millisecond, None),
- AvroSchema::LocalTimestampMicros =>
DataType::Timestamp(TimeUnit::Microsecond, None),
- AvroSchema::LocalTimestampNanos =>
DataType::Timestamp(TimeUnit::Nanosecond, None),
- AvroSchema::Duration => DataType::Duration(TimeUnit::Millisecond),
- };
+ AvroSchema::Enum(EnumSchema { .. }) => DataType::Utf8,
+ AvroSchema::Fixed(FixedSchema { size, .. }) =>
DataType::FixedSizeBinary(*size as i32),
+ AvroSchema::Decimal(DecimalSchema {
+ precision, scale, ..
+ }) => DataType::Decimal128(*precision as u8, *scale as i8),
+ AvroSchema::BigDecimal => DataType::LargeBinary,
+ AvroSchema::Uuid => DataType::FixedSizeBinary(16),
+ AvroSchema::Date => DataType::Date32,
+ AvroSchema::TimeMillis => DataType::Time32(TimeUnit::Millisecond),
+ AvroSchema::TimeMicros => DataType::Time64(TimeUnit::Microsecond),
+ // Avro's `timestamp-*` logical types are instants in UTC; the
+ // timezone-naive variants are `local-timestamp-*` below. Carrying
the
+ // zone matters beyond correctness: a parquet base file reads back
as
+ // `Timestamp(_, "UTC")`, so dropping it here makes a log batch
fail to
+ // concatenate with the base batch it is merged against.
+ AvroSchema::TimestampMillis => {
+ DataType::Timestamp(TimeUnit::Millisecond,
Some(UTC_TIMEZONE.into()))
+ }
+ AvroSchema::TimestampMicros => {
+ DataType::Timestamp(TimeUnit::Microsecond,
Some(UTC_TIMEZONE.into()))
+ }
+ AvroSchema::TimestampNanos => {
+ DataType::Timestamp(TimeUnit::Nanosecond,
Some(UTC_TIMEZONE.into()))
+ }
+ // Timezone-naive: no zone, matching arrow-avro decoding and
Parquet.
+ AvroSchema::LocalTimestampMillis =>
DataType::Timestamp(TimeUnit::Millisecond, None),
+ AvroSchema::LocalTimestampMicros =>
DataType::Timestamp(TimeUnit::Microsecond, None),
+ AvroSchema::LocalTimestampNanos =>
DataType::Timestamp(TimeUnit::Nanosecond, None),
+ AvroSchema::Duration => DataType::Duration(TimeUnit::Millisecond),
+ };
- let data_type = field_type.clone();
- let name = name.unwrap_or_else(|| default_field_name(&data_type));
+ let data_type = field_type.clone();
+ let name = name.unwrap_or_else(|| default_field_name(&data_type));
- let mut field = Field::new(name, field_type, nullable);
- field.set_metadata(props.unwrap_or_default());
- // A record of another shape stays a plain struct, so the rest of the
- // table remains readable; `VariantArray::try_new` checks the shape again
- // when the column is read as a variant.
- if is_hudi_variant_schema(schema) && has_variant_shape(&field) {
- field.try_with_extension_type(VariantType)?;
+ let mut field = Field::new(name, field_type, nullable);
+ field.set_metadata(props.unwrap_or_default());
+ // Preserve ordinary structs whose shape does not match a Variant.
+ if is_hudi_variant_schema(schema) && has_variant_shape(&field) {
+ field.try_with_extension_type(VariantType)?;
+ }
+ Ok(field)
}
- Ok(field)
}
fn is_hudi_variant_schema(schema: &AvroSchema) -> bool {
@@ -533,4 +549,45 @@ mod tests {
assert_eq!(field.extension_type_name(), None, "{fields}");
}
}
+ #[test]
+ fn test_variant_references_preserve_extensions_in_nullable_containers() {
+ let avro = AvroSchema::parse_str(r#"{
+ "type":"record","name":"root","namespace":"example","fields":[
+
{"name":"v","type":["null",{"type":"record","name":"Variant","logicalType":"variant","fields":[
+
{"name":"value","type":"bytes"},{"name":"metadata","type":"bytes"}]}]},
+
{"name":"items","type":{"type":"array","items":["null","example.Variant"]}},
+
{"name":"attributes","type":{"type":"map","values":"example.Variant"}},
+
{"name":"ordinary","type":{"type":"record","name":"ordinary","fields":[
+
{"name":"metadata","type":"bytes"},{"name":"value","type":"bytes"}]}}
+ ]}"#).unwrap();
+ let schema = to_arrow_schema(&avro).unwrap();
+ schema.field(0).try_extension_type::<VariantType>().unwrap();
+ let DataType::List(element) = schema.field(1).data_type() else {
+ panic!("expected list")
+ };
+ assert!(element.is_nullable());
+ element.try_extension_type::<VariantType>().unwrap();
+ let DataType::Map(entries, _) = schema.field(2).data_type() else {
+ panic!("expected map")
+ };
+ let DataType::Struct(fields) = entries.data_type() else {
+ panic!("expected entries")
+ };
+ fields[1].try_extension_type::<VariantType>().unwrap();
+ assert!(schema.field(3).try_extension_type::<VariantType>().is_err());
+ }
+
+ #[test]
+ fn test_recursive_avro_reference_returns_error() {
+ let schema = AvroSchema::parse_str(
+
r#"{"type":"record","name":"node","fields":[{"name":"next","type":["null","node"]}]}"#,
+ )
+ .unwrap();
+ assert!(
+ to_arrow_schema(&schema)
+ .unwrap_err()
+ .to_string()
+ .contains("Recursive Avro schema")
+ );
+ }
}
diff --git a/crates/core/src/file_group/log_file/avro.rs
b/crates/core/src/file_group/log_file/avro.rs
index 8b508d7a..c013f54e 100644
--- a/crates/core/src/file_group/log_file/avro.rs
+++ b/crates/core/src/file_group/log_file/avro.rs
@@ -180,9 +180,8 @@ impl AvroBlockDecoder {
/// The Arrow schema decoded records will carry.
///
- /// Taken from the decoder rather than converted from the Avro JSON,
because
- /// `avro_to_arrow` does not handle named-type references and the metadata
- /// table's schema uses them. Dictionaries are unpacked to match what
+ /// Taken from the decoder rather than converted from the Avro JSON, to
preserve the decoder's physical
+ /// types and metadata. Dictionaries are unpacked to match what
/// [`flush`](Self::flush) emits.
pub fn schema(&self) -> SchemaRef {
let schema = self.decoder.schema();
@@ -751,4 +750,70 @@ mod variant_tests {
Variant::from("iceberg")
);
}
+ #[test]
+ fn test_variant_nested_nulls_survive_avro_decode_and_projection() {
+ use arrow::array::Array;
+ use arrow::array::AsArray;
+ let schema = AvroSchema::parse_str(r#"{
+ "type":"record","name":"root","fields":[
+
{"name":"v","type":["null",{"type":"record","name":"variant","logicalType":"variant","fields":[
+
{"name":"value","type":"bytes"},{"name":"metadata","type":"bytes"}]}]},
+
{"name":"items","type":{"type":"array","items":["null","variant"]}},
+ {"name":"attributes","type":{"type":"map","values":"variant"}}
+ ]}"#).unwrap();
+ let mut builder = VariantArrayBuilder::new(2);
+ builder.append_value(Variant::Null);
+ builder.append_value(42_i64);
+ let encoded = builder.build();
+ let value = |i| {
+ Value::Record(vec![
+ (
+ "value".into(),
+
Value::Bytes(encoded.value_column().as_binary_view().value(i).to_vec()),
+ ),
+ (
+ "metadata".into(),
+
Value::Bytes(encoded.metadata_column().as_binary_view().value(i).to_vec()),
+ ),
+ ])
+ };
+ let datum = Value::Record(vec![
+ ("v".into(), Value::Union(0, Box::new(Value::Null))),
+ (
+ "items".into(),
+ Value::Array(vec![
+ Value::Union(0, Box::new(Value::Null)),
+ Value::Union(1, Box::new(value(0))),
+ Value::Union(1, Box::new(value(1))),
+ ]),
+ ),
+ (
+ "attributes".into(),
+ Value::Map(std::collections::HashMap::from([(
+ "answer".into(),
+ value(1),
+ )])),
+ ),
+ ]);
+ let batch = read_variant(&schema, datum);
+ assert!(batch.column_by_name("v").unwrap().is_null(0));
+ let items = batch
+ .column_by_name("items")
+ .unwrap()
+ .as_list::<i32>()
+ .value(0);
+ let variants = VariantArray::try_new(&items).unwrap();
+ assert!(variants.is_null(0));
+ assert!(!variants.is_null(1));
+ assert_eq!(variants.try_value(1).unwrap(), Variant::Null);
+ assert_eq!(variants.try_value(2).unwrap().as_int64(), Some(42));
+ let map = batch.column_by_name("attributes").unwrap().as_map();
+ let values = VariantArray::try_new(map.values()).unwrap();
+ assert_eq!(values.try_value(0).unwrap().as_int64(), Some(42));
+ // The C Data Interface is also the schema/array transport used by the
bindings.
+ let array = arrow_array::StructArray::from(batch);
+ let (data, schema) = arrow::ffi::to_ffi(&array.to_data()).unwrap();
+ let imported = unsafe { arrow::ffi::from_ffi(data, &schema) }.unwrap();
+ assert_eq!(array.to_data(), imported);
+ }
}
diff --git a/crates/core/src/file_group/log_file/content.rs
b/crates/core/src/file_group/log_file/content.rs
index b81dba19..11e8f228 100644
--- a/crates/core/src/file_group/log_file/content.rs
+++ b/crates/core/src/file_group/log_file/content.rs
@@ -27,6 +27,7 @@ use crate::file_group::log_file::log_format::LogFormatVersion;
use crate::file_group::record_batches::RecordBatches;
use crate::hfile::record_key::fill_empty_entry_keys;
use crate::hfile::{HFileReader, HFileRecord};
+use crate::schema::avro_names::resolve_null_namespace_references;
use crate::schema::delete::delete_record_list_schema_json;
use
crate::schema::extended_promotion::record_needs_rewrite_for_extended_promotion;
use crate::schema::parquet_list_norm::normalize_parquet_metadata;
@@ -477,6 +478,15 @@ impl Decoder {
if let Some(found) = lock_setups().get(&key) {
return Ok(found.clone());
}
+ // Rewritten here rather than when the header is read so that it is
+ // worked out once per writer schema, not once per block. The reader
+ // schema is rewritten the same way so that the names still match.
+ let resolved_writer_schema =
resolve_null_namespace_references(writer_schema_json);
+ let writer_schema_json = resolved_writer_schema.as_ref();
+ let resolved_reader_schema = self
+ .reader_schema_json
+ .as_deref()
+ .map(resolve_null_namespace_references);
let narrowed = match &self.projection {
Some(columns) if narrow => narrow_avro_record(writer_schema_json,
columns),
_ => None,
@@ -484,7 +494,7 @@ impl Decoder {
let reader_schema_json = if is_partial {
None
} else {
- self.reader_schema_json.as_deref()
+ resolved_reader_schema.as_deref()
};
// Avro resolves what it defines as a promotion; Hudi permits more than
// that (a number, or anything with a logical type, to string) and Avro
@@ -496,10 +506,11 @@ impl Decoder {
Some(required_json) => {
let writer =
apache_avro::Schema::parse_str(writer_schema_json)?;
let required = apache_avro::Schema::parse_str(required_json)?;
- if record_needs_rewrite_for_extended_promotion(&writer,
&required)? {
+ if crate::schema::variant::has_shredded_variant(&writer)
+ || record_needs_rewrite_for_extended_promotion(&writer,
&required)?
+ {
log::warn!(
- "log block rewritten rather than resolved: its schema
differs from the \
- table's in a way Avro does not define a promotion for"
+ "log block decoded at its writer schema before
reconstruction and evolution"
);
let target = avro_json_to_arrow_schema(required_json)?;
(None, Some(Arc::new(target)))
@@ -1294,6 +1305,50 @@ mod tests {
use std::io::{BufReader, Cursor};
use std::sync::Arc;
+ #[test]
+ fn test_shredded_variant_log_reconstructs_before_reader_resolution() ->
Result<()> {
+ use parquet::variant::{VariantArray, VariantType};
+ let writer_json =
r#"{"type":"record","name":"root","fields":[{"name":"v","type":{"type":"record","name":"v","logicalType":"variant","fields":[{"name":"metadata","type":"bytes"},{"name":"value","type":["null","bytes"]},{"name":"typed_value","type":["null","long"]}]}}]}"#;
+ let required_json =
r#"{"type":"record","name":"root","fields":[{"name":"v","type":{"type":"record","name":"v","logicalType":"variant","fields":[{"name":"metadata","type":"bytes"},{"name":"value","type":["null","bytes"]}]}}]}"#;
+ let writer = apache_avro::Schema::parse_str(writer_json)?;
+ let datum = AvroValue::Record(vec![(
+ "v".into(),
+ AvroValue::Record(vec![
+ ("metadata".into(), AvroValue::Bytes(vec![1, 0, 0])),
+ (
+ "value".into(),
+ AvroValue::Union(0, Box::new(AvroValue::Null)),
+ ),
+ (
+ "typed_value".into(),
+ AvroValue::Union(1, Box::new(AvroValue::Long(42))),
+ ),
+ ]),
+ )]);
+ let body = to_avro_datum(&writer, datum)?;
+ let mut buf = Vec::new();
+ buf.extend_from_slice(&3u32.to_be_bytes());
+ buf.extend_from_slice(&1u32.to_be_bytes());
+ buf.extend_from_slice(&(body.len() as u32).to_be_bytes());
+ buf.extend(body);
+ let decoder = Decoder::new(Arc::new(HudiConfigs::empty()))
+ .with_reader_schema(Some(required_json.into()));
+ let header = HashMap::from([(BlockMetadataKey::Schema,
writer_json.into())]);
+ let batches = decoder.decode_avro_record_content(buf.as_slice(),
&header)?;
+ let batch = &batches.data_batches[0];
+ batch
+ .schema()
+ .field(0)
+ .try_extension_type::<VariantType>()?;
+ assert_eq!(
+ VariantArray::try_new(batch.column(0))?
+ .try_value(0)?
+ .as_int64(),
+ Some(42)
+ );
+ Ok(())
+ }
+
#[test]
fn test_decode_avro_content() -> Result<()> {
// Create Avro schema
diff --git a/crates/core/src/file_group/reader_v2/output_converter.rs
b/crates/core/src/file_group/reader_v2/output_converter.rs
index 78b3fd48..8c685875 100644
--- a/crates/core/src/file_group/reader_v2/output_converter.rs
+++ b/crates/core/src/file_group/reader_v2/output_converter.rs
@@ -90,6 +90,12 @@ fn narrow_array_to_field(
source_field: &Field,
target_field: &Field,
) -> Result<ArrayRef> {
+ if crate::schema::variant::contains_variant(target_field) {
+ return crate::schema::batch_evolution::evolve_array(
+ source,
+ &Arc::new(target_field.clone()),
+ );
+ }
if source_field.data_type() == target_field.data_type() {
return Ok(Arc::clone(source));
}
diff --git a/crates/core/src/schema/avro_names.rs
b/crates/core/src/schema/avro_names.rs
new file mode 100644
index 00000000..a5ad9570
--- /dev/null
+++ b/crates/core/src/schema/avro_names.rs
@@ -0,0 +1,330 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+//! Resolve Avro name references the way Java Avro does.
+//!
+//! The Avro spec resolves a reference without a dot in the namespace of the
+//! enclosing definition, so a type defined in the null namespace cannot be
+//! referred to from inside a named namespace. Java Avro looks a bare name up
in
+//! the null namespace when the enclosing one does not define it, and Hudi
+//! relies on that: it writes a table's first Variant column as
+//! `{"name": "variant", "namespace": "", ...}` and every later one as the
+//! reference `"variant"`. apache-avro and arrow-avro follow the spec and
reject
+//! such a schema, so [`resolve_null_namespace_references`] rewrites it into
one
+//! they accept before either parses it.
+
+use std::borrow::Cow;
+use std::collections::HashSet;
+
+use serde_json::Value;
+
+/// The namespace null-namespace types move to when a schema is rewritten. A
+/// type keeps its simple name, which is what Avro schema resolution compares.
+const NULL_NAMESPACE_STAND_IN: &str = "hudi_rs_null_namespace";
+
+const PRIMITIVES: [&str; 8] = [
+ "null", "boolean", "int", "long", "float", "double", "bytes", "string",
+];
+
+/// `schema_json` unchanged when every reference in it resolves per the Avro
spec,
+/// or otherwise rewritten so that it does, keeping what each reference denotes
+/// under Java's lookup. In the rewrite every named type declares its
namespace,
+/// null-namespace types move to a stand-in namespace, and every reference is a
+/// full name. A string that is not JSON is returned as is for the parser to
reject.
+pub(crate) fn resolve_null_namespace_references(schema_json: &str) -> Cow<'_,
str> {
+ let Ok(mut schema) = serde_json::from_str::<Value>(schema_json) else {
+ return Cow::Borrowed(schema_json);
+ };
+ if !has_null_namespace_fallback(&schema, None, &mut HashSet::new()) {
+ return Cow::Borrowed(schema_json);
+ }
+ qualify(&mut schema, None, &mut HashSet::new());
+ Cow::Owned(schema.to_string())
+}
+
+/// The namespace and full name of a named type definition `node`.
+fn definition_name(node: &Value, enclosing: Option<&str>) ->
Option<(Option<String>, String)> {
+ let name = node.get("name")?.as_str()?;
+ if let Some((ns, _)) = name.rsplit_once('.') {
+ return Some((Some(ns.to_string()), name.to_string()));
+ }
+ let ns = match node.get("namespace").and_then(Value::as_str) {
+ Some("") => None,
+ Some(ns) => Some(ns.to_string()),
+ None => enclosing.map(str::to_string),
+ };
+ let fullname = match &ns {
+ Some(ns) => format!("{ns}.{name}"),
+ None => name.to_string(),
+ };
+ Some((ns, fullname))
+}
+
+fn is_named_definition(node: &Value) -> bool {
+ matches!(
+ node.get("type").and_then(Value::as_str),
+ Some("record" | "error" | "enum" | "fixed")
+ )
+}
+
+/// What a name reference inside `enclosing` denotes under Java's lookup, and
+/// whether reaching it took the null-namespace fallback.
+fn resolve_reference(
+ reference: &str,
+ enclosing: Option<&str>,
+ defined: &HashSet<String>,
+) -> Option<(String, bool)> {
+ if PRIMITIVES.contains(&reference) {
+ return None;
+ }
+ if reference.contains('.') {
+ return Some((reference.to_string(), false));
+ }
+ if let Some(ns) = enclosing {
+ let qualified = format!("{ns}.{reference}");
+ if defined.contains(&qualified) {
+ return Some((qualified, false));
+ }
+ if defined.contains(reference) {
+ return Some((reference.to_string(), true));
+ }
+ return None;
+ }
+ defined
+ .contains(reference)
+ .then(|| (reference.to_string(), false))
+}
+
+/// Calls `visit` on each schema node directly nested in `node`, with the
+/// namespace that encloses it.
+fn for_each_child<'a, 'b>(
+ node: &'a Value,
+ enclosing: Option<&'b str>,
+ visit: &mut dyn FnMut(&'a Value, Option<&'b str>),
+) {
+ match node {
+ Value::Array(branches) => branches.iter().for_each(|b| visit(b,
enclosing)),
+ Value::Object(map) => {
+ if let Some(fields) = map.get("fields").and_then(Value::as_array) {
+ for field in fields {
+ if let Some(t) = field.get("type") {
+ visit(t, enclosing);
+ }
+ }
+ }
+ for key in ["items", "values"] {
+ if let Some(child) = map.get(key) {
+ visit(child, enclosing);
+ }
+ }
+ if let Some(t @ (Value::Object(_) | Value::Array(_))) =
map.get("type") {
+ visit(t, enclosing);
+ }
+ }
+ _ => {}
+ }
+}
+
+fn reference_of(node: &Value) -> Option<&str> {
+ match node {
+ Value::String(s) => Some(s),
+ Value::Object(map) if !is_named_definition(node) =>
map.get("type").and_then(Value::as_str),
+ _ => None,
+ }
+}
+
+/// Whether a reference in `node` needs Java's null-namespace fallback.
`defined`
+/// holds the full names defined so far: like Java's parser, a reference only
+/// sees the types defined before it, and a record sees itself.
+fn has_null_namespace_fallback(
+ node: &Value,
+ enclosing: Option<&str>,
+ defined: &mut HashSet<String>,
+) -> bool {
+ if let Some(reference) = reference_of(node)
+ && let Some((_, true)) = resolve_reference(reference, enclosing,
defined)
+ {
+ return true;
+ }
+ let ns = is_named_definition(node)
+ .then(|| definition_name(node, enclosing))
+ .flatten()
+ .map(|(ns, fullname)| {
+ defined.insert(fullname);
+ ns
+ });
+ let inner = match &ns {
+ Some(ns) => ns.as_deref(),
+ None => enclosing,
+ };
+ let mut found = false;
+ for_each_child(node, inner, &mut |child, enc| {
+ found = found || has_null_namespace_fallback(child, enc, defined);
+ });
+ found
+}
+
+/// `fullname` with a null-namespace type moved to the stand-in namespace.
+fn moved(fullname: &str) -> String {
+ if fullname.contains('.') {
+ fullname.to_string()
+ } else {
+ format!("{NULL_NAMESPACE_STAND_IN}.{fullname}")
+ }
+}
+
+/// Rewrites `node` so every reference resolves per the spec; `defined` as in
+/// [`has_null_namespace_fallback`].
+fn qualify(node: &mut Value, enclosing: Option<&str>, defined: &mut
HashSet<String>) {
+ if let Value::String(reference) = node {
+ if let Some((target, _)) = resolve_reference(reference, enclosing,
defined) {
+ *reference = moved(&target);
+ }
+ return;
+ }
+ if let Value::Array(branches) = node {
+ branches
+ .iter_mut()
+ .for_each(|b| qualify(b, enclosing, defined));
+ return;
+ }
+ let mut inner = enclosing.map(str::to_string);
+ if is_named_definition(node) {
+ if let Some((ns, fullname)) = definition_name(node, enclosing) {
+ defined.insert(fullname.clone());
+ let (new_ns, simple) = moved(&fullname)
+ .rsplit_once('.')
+ .map(|(n, s)| (n.to_string(), s.to_string()))
+ .expect("a moved name has a namespace");
+ node["name"] = Value::String(simple);
+ node["namespace"] = Value::String(new_ns);
+ inner = ns;
+ }
+ } else if let Some(Value::String(reference)) = node.get_mut("type")
+ && let Some((target, _)) = resolve_reference(reference, enclosing,
defined)
+ {
+ *reference = moved(&target);
+ }
+ let inner = inner.as_deref();
+ let Value::Object(map) = node else { return };
+ if let Some(Value::Array(fields)) = map.get_mut("fields") {
+ for field in fields {
+ if let Some(t) = field.get_mut("type") {
+ qualify(t, inner, defined);
+ }
+ }
+ }
+ for key in ["items", "values"] {
+ if let Some(child) = map.get_mut(key) {
+ qualify(child, inner, defined);
+ }
+ }
+ if let Some(t @ (Value::Object(_) | Value::Array(_))) =
map.get_mut("type") {
+ qualify(t, inner, defined);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use apache_avro::Schema;
+
+ /// The shape Hudi 1.2 writes for a table with three Variant columns, one
of
+ /// them inside a struct and one inside an array.
+ const HUDI_VARIANT_SCHEMA: &str =
r#"{"type":"record","name":"t_record","namespace":"hoodie.t","fields":[
+
{"name":"v","type":["null",{"type":"record","name":"variant","namespace":"","fields":[
+
{"name":"metadata","type":"bytes"},{"name":"value","type":"bytes"}],"logicalType":"variant"}],"default":null},
+ {"name":"w","type":["null","variant"],"default":null},
+
{"name":"s","type":["null",{"type":"record","name":"s","namespace":"hoodie.t.t_record","fields":[
+
{"name":"nv","type":["null","variant"],"default":null}]}],"default":null},
+
{"name":"arr","type":["null",{"type":"array","items":["null","variant"]}],"default":null}]}"#;
+
+ #[test]
+ fn java_null_namespace_fallback_is_rewritten_to_parse() {
+ assert!(Schema::parse_str(HUDI_VARIANT_SCHEMA).is_err());
+ let rewritten = resolve_null_namespace_references(HUDI_VARIANT_SCHEMA);
+ assert!(matches!(rewritten, Cow::Owned(_)));
+ let schema = Schema::parse_str(&rewritten).unwrap();
+ let canonical = schema.canonical_form();
+ assert_eq!(
+ canonical.matches("hudi_rs_null_namespace.variant").count(),
+ 4,
+ "one definition and three references: {canonical}"
+ );
+ // Names other than the moved one keep their namespaces.
+ assert!(canonical.contains("\"hoodie.t.t_record.s\""));
+ }
+
+ #[test]
+ fn spec_resolvable_schema_is_left_alone() {
+ let single =
r#"{"type":"record","name":"t_record","namespace":"hoodie.t","fields":[
+
{"name":"v","type":["null",{"type":"record","name":"variant","namespace":"","fields":[
+
{"name":"metadata","type":"bytes"},{"name":"value","type":"bytes"}]}]},
+ {"name":"e","type":{"type":"enum","name":"E","symbols":["A"]}},
+ {"name":"f","type":"E"},
+ {"name":"g","type":"hoodie.t.E"}]}"#;
+ assert!(matches!(
+ resolve_null_namespace_references(single),
+ Cow::Borrowed(_)
+ ));
+ assert!(matches!(
+ resolve_null_namespace_references("not json"),
+ Cow::Borrowed("not json")
+ ));
+ }
+
+ #[test]
+ fn reference_resolves_against_earlier_definitions_only() {
+ // `nv` comes before the record `hoodie.t.t_record.variant` is
defined, so
+ // Java resolves it to the null-namespace `variant`; `x` comes after
it.
+ let schema =
r#"{"type":"record","name":"t_record","namespace":"hoodie.t","fields":[
+
{"name":"v","type":{"type":"record","name":"variant","namespace":"","fields":[
+
{"name":"metadata","type":"bytes"},{"name":"value","type":"bytes"}]}},
+
{"name":"s","type":{"type":"record","name":"s","fields":[{"name":"nv","type":"variant"}]}},
+
{"name":"variant","type":{"type":"record","name":"variant","fields":[{"name":"a","type":"int"}]}},
+ {"name":"x","type":"variant"}]}"#;
+ let rewritten = resolve_null_namespace_references(schema);
+ let parsed: Value = serde_json::from_str(&rewritten).unwrap();
+ assert_eq!(
+ parsed["fields"][1]["type"]["fields"][0]["type"],
+ "hudi_rs_null_namespace.variant"
+ );
+ assert_eq!(parsed["fields"][3]["type"], "hoodie.t.variant");
+ Schema::parse_str(&rewritten).unwrap();
+ }
+
+ #[test]
+ fn enclosing_namespace_definition_wins_over_fallback() {
+ // `x` inside `ns` names `ns.x`, even though a null-namespace `x`
exists too.
+ let schema = r#"{"type":"record","name":"r","fields":[
+ {"name":"a","type":{"type":"fixed","name":"x","size":1}},
+
{"name":"b","type":{"type":"record","name":"in","namespace":"ns","fields":[
+ {"name":"c","type":{"type":"fixed","name":"x","size":2}},
+ {"name":"d","type":"x"},
+
{"name":"e","type":{"type":"record","name":"deep","fields":[{"name":"f","type":"r"}]}}]}}]}"#;
+ let rewritten = resolve_null_namespace_references(schema);
+ let parsed: Value = serde_json::from_str(&rewritten).unwrap();
+ let inner = &parsed["fields"][1]["type"]["fields"];
+ assert_eq!(inner[1]["type"], "ns.x");
+ assert_eq!(
+ inner[2]["type"]["fields"][0]["type"],
+ "hudi_rs_null_namespace.r"
+ );
+ Schema::parse_str(&rewritten).unwrap();
+ }
+}
diff --git a/crates/core/src/schema/batch_evolution.rs
b/crates/core/src/schema/batch_evolution.rs
index f93f10d7..eb34b9b0 100644
--- a/crates/core/src/schema/batch_evolution.rs
+++ b/crates/core/src/schema/batch_evolution.rs
@@ -32,6 +32,7 @@ use crate::Result;
use crate::error::CoreError;
use arrow_array::{Array, ArrayRef, RecordBatch, StringArray, new_null_array};
use arrow_schema::{DataType, FieldRef, SchemaRef, TimeUnit};
+use parquet::variant::{VariantArray, VariantType, unshred_variant};
use std::sync::Arc;
/// Microseconds per millisecond — the ÷1000 factor for the NTZ
(local-timestamp)
@@ -353,6 +354,26 @@ pub(crate) fn is_promotion(from: &DataType, to: &DataType)
-> bool {
}
pub(crate) fn evolve_array(src: &ArrayRef, target_field: &FieldRef) ->
Result<ArrayRef> {
+ // A shredded Variant carries `typed_value` beside `metadata` and `value`,
and
+ // `value` is null wherever the value was shredded. Generic struct
projection
+ // would drop that payload, so rebuild the binary form the table declares
first.
+ if target_field.has_valid_extension_type::<VariantType>()
+ && matches!(src.data_type(), DataType::Struct(fields) if
fields.iter().any(|f| f.name() == "typed_value"))
+ {
+ let shredded = VariantArray::try_new(src.as_ref()).map_err(|e| {
+ CoreError::Schema(format!(
+ "evolution: shredded Variant '{}': {e}",
+ target_field.name()
+ ))
+ })?;
+ let unshredded = unshred_variant(&shredded).map_err(|e| {
+ CoreError::Schema(format!(
+ "Failed to reconstruct Variant '{}': {e}",
+ target_field.name()
+ ))
+ })?;
+ return evolve_array(&ArrayRef::from(unshredded), target_field);
+ }
let st = src.data_type();
let tt = target_field.data_type();
if st == tt {
diff --git a/crates/core/src/schema/mod.rs b/crates/core/src/schema/mod.rs
index 3bfd089b..97bb7e46 100644
--- a/crates/core/src/schema/mod.rs
+++ b/crates/core/src/schema/mod.rs
@@ -22,6 +22,7 @@ use crate::schema::resolver::sanitize_avro_schema_str;
use arrow_schema::{Schema, SchemaRef};
use serde_json::Value;
+pub(crate) mod avro_names;
pub mod avro_schema_utils;
pub mod avsc;
pub mod batch_evolution;
@@ -30,6 +31,7 @@ pub mod extended_promotion;
pub(crate) mod history;
pub mod parquet_list_norm;
pub mod resolver;
+pub mod variant;
pub fn prepend_meta_fields(schema: SchemaRef) -> Result<Schema> {
let meta_field_schema = MetaField::schema();
diff --git a/crates/core/src/schema/resolver.rs
b/crates/core/src/schema/resolver.rs
index b1ca5a1e..8ed28f9d 100644
--- a/crates/core/src/schema/resolver.rs
+++ b/crates/core/src/schema/resolver.rs
@@ -23,6 +23,7 @@ use crate::error::{CoreError, Result};
use crate::file_group::base_file::lance::LanceBaseFileReader;
use crate::file_group::base_file::parquet::ParquetBaseFileReader;
use crate::metadata::commit::HoodieCommitMetadata;
+use crate::schema::avro_names::resolve_null_namespace_references;
use crate::schema::{prepend_meta_fields,
prepend_meta_fields_to_avro_schema_str};
use crate::storage::Storage;
use crate::storage::util::join_path_segments;
@@ -187,7 +188,7 @@ pub(crate) fn sanitize_avro_schema_str(avro_schema_str:
&str) -> String {
fn arrow_schema_from_avro_schema_str(avro_schema_str: &str) -> Result<Schema> {
let s = sanitize_avro_schema_str(avro_schema_str);
- let avro_schema = AvroSchema::parse_str(&s)
+ let avro_schema =
AvroSchema::parse_str(&resolve_null_namespace_references(&s))
.map_err(|e| CoreError::Schema(format!("Failed to parse Avro schema:
{e}")))?;
to_arrow_schema(&avro_schema)
@@ -195,7 +196,7 @@ fn arrow_schema_from_avro_schema_str(avro_schema_str: &str)
-> Result<Schema> {
/// Convert an Avro schema in JSON form to an Arrow schema.
pub fn avro_json_to_arrow_schema(avro_schema_str: &str) -> Result<Schema> {
- let avro = AvroSchema::parse_str(avro_schema_str)
+ let avro =
AvroSchema::parse_str(&resolve_null_namespace_references(avro_schema_str))
.map_err(|e| CoreError::Schema(format!("Failed to parse Avro schema:
{e}")))?;
to_arrow_schema(&avro)
}
diff --git a/crates/core/src/schema/variant.rs
b/crates/core/src/schema/variant.rs
new file mode 100644
index 00000000..7f44a30b
--- /dev/null
+++ b/crates/core/src/schema/variant.rs
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+use arrow_schema::{DataType, Field};
+use parquet::variant::VariantType;
+
+/// Whether a field or one of its nested children carries the Variant
extension.
+pub fn contains_variant(field: &Field) -> bool {
+ if field.has_valid_extension_type::<VariantType>() {
+ return true;
+ }
+ match field.data_type() {
+ DataType::Struct(fields) => fields.iter().any(|f| contains_variant(f)),
+ DataType::List(f)
+ | DataType::LargeList(f)
+ | DataType::FixedSizeList(f, _)
+ | DataType::Map(f, _) => contains_variant(f),
+ DataType::Union(fields, _) => fields.iter().any(|(_, f)|
contains_variant(f)),
+ _ => false,
+ }
+}
+
+/// Detect physical shredding in an Avro schema before reader-schema
resolution.
+pub(crate) fn has_shredded_variant(schema: &apache_avro::Schema) -> bool {
+ use apache_avro::Schema;
+ match schema {
+ Schema::Record(record) => {
+ (record
+ .attributes
+ .get("logicalType")
+ .and_then(serde_json::Value::as_str)
+ == Some("variant")
+ && record.fields.iter().any(|f| f.name == "typed_value"))
+ || record
+ .fields
+ .iter()
+ .any(|f| has_shredded_variant(&f.schema))
+ }
+ Schema::Array(array) => has_shredded_variant(&array.items),
+ Schema::Map(map) => has_shredded_variant(&map.types),
+ Schema::Union(union) =>
union.variants().iter().any(has_shredded_variant),
+ _ => false,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::file_group::reader_v2::output_converter::{OutputConverter,
ProjectionConverter};
+ use arrow_array::cast::AsArray;
+ use arrow_array::{
+ Array, ArrayRef, ListArray, MapArray, RecordBatch, StringArray,
StructArray,
+ };
+ use arrow_buffer::OffsetBuffer;
+ use parquet::variant::{VariantArray, json_to_variant, shred_variant};
+ use std::sync::Arc;
+
+ #[test]
+ fn test_shredded_variants_in_lists_and_maps_keep_nulls_and_residuals() {
+ let json: ArrayRef = Arc::new(StringArray::from(vec![
+ Some(r#"{"x":7,"keep":["a",null]}"#),
+ Some(r#"{"x":"residual","keep":true}"#),
+ Some("null"),
+ None,
+ ]));
+ let plain = json_to_variant(&json).unwrap();
+ let physical = shred_variant(
+ &plain,
+ &DataType::Struct(vec![Field::new("x", DataType::Int64,
true)].into()),
+ )
+ .unwrap();
+ let wrap = |array: VariantArray| {
+ let field = Arc::new(array.field("element"));
+ let values: ArrayRef = Arc::new(array.into_inner());
+ let list: ArrayRef = Arc::new(ListArray::new(
+ field,
+ OffsetBuffer::new(vec![0, 4].into()),
+ values.clone(),
+ None,
+ ));
+ let entries = StructArray::new(
+ vec![
+ Field::new("key", DataType::Utf8, false),
+ Field::new("value", values.data_type().clone(), true)
+ .with_extension_type(VariantType),
+ ]
+ .into(),
+ vec![
+ Arc::new(StringArray::from(vec!["a", "b", "c", "d"])),
+ values,
+ ],
+ None,
+ );
+ let entry_field = Arc::new(Field::new("key_value",
entries.data_type().clone(), false));
+ let map: ArrayRef = Arc::new(MapArray::new(
+ entry_field,
+ OffsetBuffer::new(vec![0, 4].into()),
+ entries,
+ None,
+ false,
+ ));
+ RecordBatch::try_from_iter(vec![("items", list), ("attributes",
map)]).unwrap()
+ };
+ let expected = wrap(plain.clone());
+ let source = wrap(physical);
+ let converter = ProjectionConverter::new(&expected.schema());
+ let result = converter.apply(source).unwrap();
+ let list_values = result.column(0).as_list::<i32>().values();
+ let map_values = result.column(1).as_map().values();
+ for column in [list_values, map_values] {
+ let actual = VariantArray::try_new(column).unwrap();
+ assert!(actual.is_null(3));
+ assert!(!actual.is_null(2));
+ let first = actual.try_value(0).unwrap();
+ let object = first.as_object().unwrap();
+ assert_eq!(object.get("x").unwrap().as_int64(), Some(7));
+ let keep = object.get("keep").unwrap();
+ let list = keep.as_list().unwrap();
+ assert_eq!(list.get(0),
Some(parquet::variant::Variant::from("a")));
+ assert_eq!(list.get(1), Some(parquet::variant::Variant::Null));
+ let second = actual.try_value(1).unwrap();
+ let object = second.as_object().unwrap();
+ assert_eq!(object.get("x").unwrap().as_string(), Some("residual"));
+ assert_eq!(object.get("keep").unwrap().as_boolean(), Some(true));
+ assert_eq!(
+ actual.try_value(2).unwrap(),
+ parquet::variant::Variant::Null
+ );
+ }
+ }
+ #[test]
+ fn test_corrupt_shredded_variant_returns_a_field_error() {
+ use arrow_array::{BinaryArray, Int64Array, new_null_array};
+ let fields = vec![
+ Field::new("metadata", DataType::Binary, false),
+ Field::new("value", DataType::Binary, true),
+ Field::new("typed_value", DataType::Int64, true),
+ ];
+ let array: ArrayRef = Arc::new(StructArray::new(
+ fields.clone().into(),
+ vec![
+ Arc::new(BinaryArray::from_vec(vec![&[255_u8][..]])),
+ new_null_array(&DataType::Binary, 1),
+ Arc::new(Int64Array::from(vec![42])),
+ ],
+ None,
+ ));
+ let source = RecordBatch::try_from_iter(vec![("v", array)]).unwrap();
+ let logical = Field::new("v",
DataType::Struct(fields[..2].to_vec().into()), true)
+ .with_extension_type(VariantType);
+ let target = Arc::new(arrow_schema::Schema::new(vec![logical]));
+ let error =
+ crate::schema::batch_evolution::project_batch_to_schema(&source,
&target).unwrap_err();
+ assert!(
+ error
+ .to_string()
+ .contains("Failed to reconstruct Variant 'v'"),
+ "{error}"
+ );
+ }
+}
diff --git a/crates/core/tests/variant_read_tests.rs
b/crates/core/tests/variant_read_tests.rs
new file mode 100644
index 00000000..118c5372
--- /dev/null
+++ b/crates/core/tests/variant_read_tests.rs
@@ -0,0 +1,380 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+//! Reads of Spark-written tables with Variant columns.
+//!
+//! `variant_cow`, `variant_mor_*` and `variant_shredded_mixed_cow` are Hudi's
own
+//! backward-compatibility fixtures (see the fixture README).
`variant_multi_*` and
+//! `variant_shredded_*` hold a top-level Variant, one inside a struct and one
inside
+//! an array. Hudi defines the Variant record once and refers to it by name
after
+//! that, through Java Avro's null-namespace lookup, so these tables only open
if
+//! that reference resolves. `variant_multi_*` come from Hudi 1.2 on Spark 4.0
and
+//! are unshredded; `variant_shredded_*` come from Hudi 1.3 on Spark 4.2 with
every
+//! base file shredding `v` and `s.nv`. Their expected values are the writer's
+//! inputs: Spark 4.0 with Hudi 1.2.1 cannot read the nested Variants back
itself.
+
+use std::collections::BTreeMap;
+use std::path::Path;
+
+use arrow::compute::concat_batches;
+use arrow_array::cast::AsArray;
+use arrow_array::types::Int32Type;
+use arrow_array::{Array, ArrayRef, RecordBatch};
+use arrow_schema::DataType;
+use hudi_core::table::{QueryType, ReadOptions, Table};
+use hudi_test::variant::{variant_rows, variant_table_path};
+use parquet::arrow::parquet_to_arrow_schema;
+use parquet::file::reader::{FileReader, SerializedFileReader};
+use parquet::variant::{VariantType, variant_to_json};
+use serde_json::{Value, json};
+
+#[tokio::test]
+async fn test_spark_variant_tables_snapshot_time_travel_and_projection() {
+ for name in ["variant_cow", "variant_mor_avro", "variant_mor_spark"] {
+ let root = variant_table_path(name);
+ let table = Table::new(root.to_str().unwrap()).await.unwrap();
+ let batch = table
+ .read(&ReadOptions::new().with_projection(["id", "v"]))
+ .await
+ .unwrap();
+ assert_eq!(
+ variant_rows(&batch),
+ vec![(1, json!({"new_field": 123, "updated": true}))],
+ "{name} snapshot"
+ );
+ let commits = &table.get_timeline().completed_commits;
+ let incremental = table
+ .read(
+ &ReadOptions::new()
+ .with_query_type(QueryType::Incremental)
+
.with_start_timestamp(commits[0].completion_timestamp.as_ref().unwrap())
+
.with_end_timestamp(commits[1].completion_timestamp.as_ref().unwrap())
+ .with_projection(["id", "v"]),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ variant_rows(&incremental),
+ vec![(1, json!({"new_field":123,"updated":true}))],
+ "{name} incremental update"
+ );
+ let first = &commits[0].timestamp;
+ let initial = table
+ .read(&ReadOptions::new().with_as_of_timestamp(first))
+ .await
+ .unwrap();
+ assert_eq!(
+ variant_rows(&initial),
+ vec![
+ (1, json!({"key":"value1", "num":1})),
+ (2, json!({"key":"value2", "list":[1,2,3]}))
+ ],
+ "{name} initial commit"
+ );
+ }
+}
+
+#[tokio::test]
+async fn test_mixed_spark_variants_reconstruct_before_projection() {
+ use arrow_schema::Schema;
+ use hudi_core::file_group::base_file::parquet::ParquetBaseFileReader;
+ use hudi_core::file_group::base_file::reader::{BaseFileReadOptions,
BaseFileReader};
+ use hudi_core::schema::batch_evolution::project_batch_to_schema;
+ use hudi_core::storage::Storage;
+ use std::sync::Arc;
+ let root = variant_table_path("variant_shredded_mixed_cow");
+ let storage = Storage::new(
+ Arc::new(Default::default()),
+ Arc::new(hudi_core::config::HudiConfigs::new([(
+ hudi_core::config::table::HudiTableConfig::BasePath.as_ref(),
+ root.to_str().unwrap(),
+ )])),
+ )
+ .unwrap();
+ let reader = ParquetBaseFileReader::new(storage);
+ let mut reconstructed = Vec::new();
+ let mut shredded_files = 0;
+ for entry in std::fs::read_dir(root).unwrap() {
+ let path = entry.unwrap().path();
+ if path.extension().is_none_or(|s| s != "parquet") {
+ continue;
+ }
+ let batch = reader
+ .read_data(
+ path.file_name().unwrap().to_str().unwrap(),
+ BaseFileReadOptions::default(),
+ )
+ .await
+ .unwrap();
+ let schema = batch.schema();
+ let DataType::Struct(fields) =
schema.field_with_name("v").unwrap().data_type() else {
+ panic!("variant must be a struct")
+ };
+ shredded_files += usize::from(fields.iter().any(|f| f.name() ==
"typed_value"));
+ let logical: arrow_schema::Fields = fields
+ .iter()
+ .filter(|f| f.name() != "typed_value")
+ .cloned()
+ .collect();
+ let target = Arc::new(Schema::new(
+ schema
+ .fields()
+ .iter()
+ .map(|f| {
+ if f.name() == "v" {
+ Arc::new(
+ f.as_ref()
+ .clone()
+
.with_data_type(DataType::Struct(logical.clone()))
+
.with_extension_type(parquet::variant::VariantType),
+ )
+ } else {
+ f.clone()
+ }
+ })
+ .collect::<Vec<_>>(),
+ ));
+ let projected = project_batch_to_schema(&batch, &target).unwrap();
+ assert_eq!(
+ projected.schema().field_with_name("v").unwrap().data_type(),
+ &DataType::Struct(logical)
+ );
+ reconstructed.push(projected);
+ }
+ assert_eq!(shredded_files, 1);
+ assert_eq!(
+ variant_rows(&reconstructed),
+ vec![
+ (1, json!({"key":"k1"})),
+ (2, json!({"key":"k2"})),
+ (3, json!({"key":3})),
+ (4, json!({"key":"k4"})),
+ ]
+ );
+}
+
+const INSERTS: [(i32, Option<&str>); 11] = [
+ (1, Some(r#"{"a":1,"b":"x","c":[1,2,3]}"#)),
+ (2, Some(r#""plain string""#)),
+ (3, Some("123")),
+ (4, Some("1.5")),
+ (5, Some("true")),
+ (6, Some("null")),
+ (7, Some(r#"{"big":12345678901234567890.123,"neg":-7}"#)),
+ (
+ 8,
+ Some(r#"{"deep":{"x":{"y":{"z":[{"k":"v"},null,[]]}}},"u":"héllo
☃"}"#),
+ ),
+ (9, None),
+ (10, Some("[]")),
+ (11, Some("{}")),
+];
+const UPSERTS: [(i32, &str); 4] = [
+ (1, r#"{"a":2,"b":"y","added":{"n":null}}"#),
+ (2, r#"[1,"two",3.0,false]"#),
+ (9, r#"{"was":"null"}"#),
+ (12, r#"{"inserted":"later"}"#),
+];
+const DELETED: i32 = 3;
+
+/// What one row holds: `v`, `s.nv` and the two elements of `arr`, as JSON.
+type Row = (Option<Value>, Option<Value>, Vec<Option<Value>>);
+
+fn table_path(name: &str) -> String {
+ variant_table_path(name).to_str().unwrap().to_string()
+}
+
+/// The requested time of the table's first commit.
+fn first_instant(path: &str) -> String {
+ let mut completed: Vec<String> =
std::fs::read_dir(Path::new(path).join(".hoodie/timeline"))
+ .unwrap()
+ .filter_map(|e| e.ok()?.file_name().into_string().ok())
+ .filter(|n| n.ends_with(".commit") || n.ends_with(".deltacommit"))
+ .collect();
+ completed.sort();
+ completed[0].split('_').next().unwrap().to_string()
+}
+
+/// Numbers compared by value: Variant stores `3.0` as a decimal that prints
as `3`.
+fn normalize(value: Value) -> Value {
+ match value {
+ Value::Number(n) => serde_json::json!(n.as_f64().unwrap()),
+ Value::Array(items) =>
Value::Array(items.into_iter().map(normalize).collect()),
+ Value::Object(map) => {
+ Value::Object(map.into_iter().map(|(k, v)| (k,
normalize(v))).collect())
+ }
+ other => other,
+ }
+}
+
+fn parse(json: &str) -> Value {
+ normalize(serde_json::from_str(json).unwrap())
+}
+
+fn variant_json(array: &ArrayRef) -> Vec<Option<Value>> {
+ let strings = variant_to_json(array).unwrap();
+ (0..strings.len())
+ .map(|i| strings.is_valid(i).then(|| parse(strings.value(i))))
+ .collect()
+}
+
+fn expected_row(json: Option<&str>, id: i32) -> Row {
+ let value = json.map(parse);
+ // The generator writes a Variant null into the array where the column is
SQL NULL.
+ let element = Some(value.clone().unwrap_or(Value::Null));
+ let marker = Some(parse(&format!(r#"{{"i":{id}}}"#)));
+ (value.clone(), value, vec![element, marker])
+}
+
+fn expected(with_later_commits: bool) -> BTreeMap<i32, Row> {
+ let mut rows: BTreeMap<i32, Row> = INSERTS
+ .iter()
+ .map(|&(id, json)| (id, expected_row(json, id)))
+ .collect();
+ if with_later_commits {
+ for (id, json) in UPSERTS {
+ rows.insert(id, expected_row(Some(json), id));
+ }
+ rows.remove(&DELETED);
+ }
+ rows
+}
+
+fn rows(batches: &[RecordBatch]) -> BTreeMap<i32, Row> {
+ let batch = concat_batches(&batches[0].schema(), batches).unwrap();
+ let ids = batch
+ .column_by_name("id")
+ .unwrap()
+ .as_primitive::<Int32Type>();
+ let v = variant_json(batch.column_by_name("v").unwrap());
+ let s = batch.column_by_name("s").unwrap().as_struct();
+ let nv = variant_json(s.column_by_name("nv").unwrap());
+ let arr = batch.column_by_name("arr").unwrap().as_list::<i32>();
+ (0..batch.num_rows())
+ .map(|i| {
+ let elements = variant_json(&arr.value(i));
+ (ids.value(i), (v[i].clone(), nv[i].clone(), elements))
+ })
+ .collect()
+}
+
+#[tokio::test]
+async fn reads_every_variant_column_in_snapshot_and_time_travel() {
+ for name in [
+ "variant_multi_cow",
+ "variant_multi_mor",
+ "variant_shredded_cow",
+ "variant_shredded_mor",
+ ] {
+ let path = table_path(name);
+ let table = Table::new(&path).await.unwrap();
+
+ let schema = table.get_schema().await.unwrap();
+ schema
+ .field_with_name("v")
+ .unwrap()
+ .try_extension_type::<VariantType>()
+ .unwrap();
+
+ // The rewrite that lets the schema parse stays internal.
+ let avro = table.get_schema_in_avro_str().await.unwrap();
+ assert!(!avro.contains("hudi_rs_null_namespace"), "{name}: {avro}");
+
+ let snapshot = table.read(&ReadOptions::new()).await.unwrap();
+ assert_eq!(rows(&snapshot), expected(true), "{name} snapshot");
+
+ let as_of =
ReadOptions::new().with_as_of_timestamp(first_instant(&path));
+ let first = table.read(&as_of).await.unwrap();
+ assert_eq!(
+ rows(&first),
+ expected(false),
+ "{name} as of the first commit"
+ );
+ }
+}
+
+/// The shredded fixtures only test unshredding if their base files are
shredded.
+#[test]
+fn shredded_fixtures_hold_shredded_base_files() {
+ for name in ["variant_shredded_cow", "variant_shredded_mor"] {
+ let base_files: Vec<_> = walk(Path::new(&table_path(name)))
+ .into_iter()
+ .filter(|p| p.extension().is_some_and(|e| e == "parquet"))
+ .collect();
+ assert!(!base_files.is_empty(), "{name} has no base files");
+ for file in base_files {
+ let reader =
SerializedFileReader::new(std::fs::File::open(&file).unwrap()).unwrap();
+ let schema =
+
parquet_to_arrow_schema(reader.metadata().file_metadata().schema_descr(), None)
+ .unwrap();
+ let DataType::Struct(s) =
schema.field_with_name("s").unwrap().data_type() else {
+ panic!("{} `s` is not a struct", file.display());
+ };
+ let nv = s.iter().find(|f| f.name() == "nv").unwrap();
+ for (name, field) in [("v", schema.field_with_name("v").unwrap()),
("s.nv", nv)] {
+ let DataType::Struct(children) = field.data_type() else {
+ panic!("{} `{name}` is not a struct", file.display());
+ };
+ assert!(
+ children.iter().any(|c| c.name() == "typed_value"),
+ "{} does not shred `{name}`",
+ file.display()
+ );
+ }
+ }
+ }
+}
+
+fn walk(dir: &Path) -> Vec<std::path::PathBuf> {
+ std::fs::read_dir(dir)
+ .unwrap()
+ .flat_map(|entry| {
+ let path = entry.unwrap().path();
+ if path.is_dir() {
+ walk(&path)
+ } else {
+ vec![path]
+ }
+ })
+ .collect()
+}
+
+/// Projecting `arr` leaves out `v`, the field that defines the Variant record,
+/// so a log block's narrowed schema has to carry the definition along.
+#[tokio::test]
+async fn projects_a_variant_whose_definition_is_in_a_dropped_column() {
+ let table = Table::new(&table_path("variant_multi_mor")).await.unwrap();
+ let options = ReadOptions::new().with_projection(["id", "arr"]);
+ let batches = table.read(&options).await.unwrap();
+ let batch = concat_batches(&batches[0].schema(), &batches).unwrap();
+ assert_eq!(batch.num_columns(), 2);
+
+ let ids = batch
+ .column_by_name("id")
+ .unwrap()
+ .as_primitive::<Int32Type>();
+ let arr = batch.column_by_name("arr").unwrap().as_list::<i32>();
+ let got: BTreeMap<i32, Vec<Option<Value>>> = (0..batch.num_rows())
+ .map(|i| (ids.value(i), variant_json(&arr.value(i))))
+ .collect();
+ let want: BTreeMap<i32, Vec<Option<Value>>> = expected(true)
+ .into_iter()
+ .map(|(id, (_, _, arr))| (id, arr))
+ .collect();
+ assert_eq!(got, want);
+}
diff --git a/crates/datafusion/Cargo.toml b/crates/datafusion/Cargo.toml
index 52e21ac1..3a665ff5 100644
--- a/crates/datafusion/Cargo.toml
+++ b/crates/datafusion/Cargo.toml
@@ -70,4 +70,5 @@ log = { workspace = true }
[dev-dependencies]
hudi-test = { path = "../test", features = ["datafusion"] }
parquet = { workspace = true }
+serde_json = { workspace = true }
tempfile = { workspace = true }
diff --git a/crates/datafusion/src/lib.rs b/crates/datafusion/src/lib.rs
index f3e9b335..6c3faf9b 100644
--- a/crates/datafusion/src/lib.rs
+++ b/crates/datafusion/src/lib.rs
@@ -579,6 +579,8 @@ impl HudiDataSource {
/// [`HudiScanExec`].
///
/// Routing matrix:
+ /// - Variant columns at any nesting depth → `HudiScanExec` (schema
handling),
+ /// decided by [`Self::use_parquet_source_without_file_slices`]
/// - Parquet COW → `ParquetSource`
/// - Parquet MOR read-optimized → `ParquetSource`
/// - Parquet MOR snapshot → `HudiScanExec` (base + log merging)
@@ -670,13 +672,15 @@ impl HudiDataSource {
Expr::Between(between) => {
// BETWEEN can be pushed if expr is a column and bounds are
literals
!between.negated
- && matches!(&*between.expr, Expr::Column(col) if
schema.column_with_name(&col.name).is_some())
+ && matches!(&*between.expr, Expr::Column(_))
+ && Self::is_supported_operand(schema, &between.expr)
&& matches!(&*between.low, Expr::Literal(..))
&& matches!(&*between.high, Expr::Literal(..))
}
Expr::InList(in_list) => {
!in_list.list.is_empty()
- && matches!(in_list.expr.as_ref(), Expr::Column(col) if
schema.column_with_name(&col.name).is_some())
+ && matches!(in_list.expr.as_ref(), Expr::Column(_))
+ && Self::is_supported_operand(schema, &in_list.expr)
&& in_list
.list
.iter()
@@ -700,7 +704,9 @@ impl HudiDataSource {
fn is_supported_operand(schema: &Schema, expr: &Expr) -> bool {
match expr {
- Expr::Column(col) => schema.column_with_name(&col.name).is_some(),
+ Expr::Column(col) => schema
+ .column_with_name(&col.name)
+ .is_some_and(|(_, f)|
!hudi_core::schema::variant::contains_variant(f)),
Expr::Literal(..) => true,
_ => false,
}
@@ -823,6 +829,16 @@ impl HudiDataSource {
&self,
read_options: &ReadOptions,
) -> Result<Option<bool>> {
+ // The native Parquet schema adapter can discard typed_value before
Hudi
+ // can reject or reconstruct a shredded Variant.
+ if self
+ .schema
+ .fields()
+ .iter()
+ .any(|f| hudi_core::schema::variant::contains_variant(f))
+ {
+ return Ok(Some(false));
+ }
if self.table.is_mor()
&& !read_options
.is_read_optimized()
diff --git a/crates/datafusion/tests/variant_read_tests.rs
b/crates/datafusion/tests/variant_read_tests.rs
new file mode 100644
index 00000000..500e8ff3
--- /dev/null
+++ b/crates/datafusion/tests/variant_read_tests.rs
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+use datafusion::physical_plan::displayable;
+use datafusion::prelude::SessionContext;
+use hudi_core::table::{ReadOptions, Table};
+use hudi_datafusion::HudiDataSource;
+use hudi_test::variant::{variant_rows, variant_table_path};
+use serde_json::json;
+use std::sync::Arc;
+
+#[tokio::test]
+async fn test_variant_table_scan_preserves_values_and_extensions() {
+ for name in ["variant_cow", "variant_mor_avro", "variant_mor_spark"] {
+ let root = variant_table_path(name);
+ let provider =
HudiDataSource::new(root.to_str().unwrap()).await.unwrap();
+ let context = SessionContext::new();
+ context
+ .register_table("variants", Arc::new(provider))
+ .unwrap();
+ let frame = context
+ .sql("SELECT id, v FROM variants WHERE id = 1")
+ .await
+ .unwrap();
+ let plan =
displayable(frame.clone().create_physical_plan().await.unwrap().as_ref())
+ .indent(true)
+ .to_string();
+ assert!(
+ plan.contains("HudiScanExec"),
+ "{name} should use HudiScanExec. Plan: {plan}"
+ );
+ let batches = frame.collect().await.unwrap();
+ assert_eq!(
+ variant_rows(&batches),
+ vec![(1, json!({"new_field":123,"updated":true}))],
+ "{name}"
+ );
+ }
+}
+
+/// Every base file of `variant_shredded_cow` shreds `v`, which DataFusion's
parquet
+/// source cannot cast to the table type; the scan must return the values the
core
+/// reader rebuilds.
+#[tokio::test]
+async fn test_shredded_variant_scan_matches_the_core_reader() {
+ let root = variant_table_path("variant_shredded_cow");
+ let path = root.to_str().unwrap();
+ let core = Table::new(path).await.unwrap();
+ let expected =
variant_rows(&core.read(&ReadOptions::new()).await.unwrap());
+ assert_eq!(expected.len(), 11);
+
+ let context = SessionContext::new();
+ context
+ .register_table("t",
Arc::new(HudiDataSource::new(path).await.unwrap()))
+ .unwrap();
+ let batches = context
+ .sql("SELECT id, v FROM t")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(variant_rows(&batches), expected);
+}
diff --git a/crates/test/data/variant/README.md
b/crates/test/data/variant/README.md
new file mode 100644
index 00000000..8d9cafaa
--- /dev/null
+++ b/crates/test/data/variant/README.md
@@ -0,0 +1,56 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+# Hudi Variant fixtures
+
+The ZIP files are unmodified Spark-generated Hudi tables from
+[apache/hudi at
d1ec4d3b043d19487b6b8a2ab4bb44665863bc5a](https://github.com/apache/hudi/tree/d1ec4d3b043d19487b6b8a2ab4bb44665863bc5a/hudi-common/src/test/resources/variant_backward_compat).
+They are Apache-2.0 licensed. The upstream README documents generation with
Spark 4.0
+and `TestVariantDataType.scala`.
+
+- `variant_cow.zip`: COW; Variant children are ordered value, metadata.
+- `variant_mor_avro.zip`: MOR with Avro data blocks; children are metadata,
value.
+- `variant_mor_spark.zip`: MOR produced using Spark records; children are
value, metadata.
+
+These table-version-9 fixtures contain an insert, an update of id 1 and
deletion
+of id 2. The first commit contains id 1 with `{"key":"value1","num":1}` and id
2
+with `{"key":"value2","list":[1,2,3]}`. The final snapshot contains only id 1
with
+`{"new_field":123,"updated":true}`. These expected values come from the
producer's
+SQL assertions, not from the Rust reader.
+
+Tests read the complete Hudi table, including its persisted schema and
timeline,
+and compare decoded logical values. The MOR fixtures exercise base/log merging;
+the historical read pins the pre-update values and the projection checks
extension
+metadata preservation.
+
+`variant_multi_{cow,mor}.zip` and `variant_shredded_{cow,mor}.zip` come from
+`generate.py` (header comment has the commands). Each table has a top-level
+Variant `v`, a Variant inside a struct (`s.nv`) and an array of Variants
(`arr`),
+partitioned, with an insert of 11 rows, an upsert of 3 rows plus 1 insert, and
a
+delete. `variant_multi_*` are written by Hudi 1.2.1 on Spark 4.0 and
unshredded.
+`variant_shredded_*` are written by Hudi 1.3.0-SNAPSHOT (apache/hudi fa803594)
on
+Spark 4.2 at table version 9, with a forced shredding schema so every base file
+shreds `v` and `s.nv`. Expected values are the generator's inputs.
+
+`variant_shredded_mixed_cow.zip` is the upstream Spark 4.1 fixture: ids 1–2
have
+a shredded string `key`, id 3 has an integer residual, and id 4 is unshredded.
+Its table version is 10, which hudi-rs does not support. Tests consume the
+unchanged Parquet base files and exercise Hudi schema reconciliation directly;
+they do not relabel the table version or claim version-10 timeline/log support.
diff --git a/crates/test/data/variant/generate.py
b/crates/test/data/variant/generate.py
new file mode 100644
index 00000000..c4e54f73
--- /dev/null
+++ b/crates/test/data/variant/generate.py
@@ -0,0 +1,120 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Write the Variant fixture tables.
+
+Unshredded (variant_multi_*), with Spark 4.0 and Hudi 1.2.1:
+ spark-submit --jars hudi-spark4.0-bundle_2.13-1.2.1.jar generate.py <out dir>
+Shredded (variant_shredded_*), with Spark 4.2 and a Hudi 1.3 bundle, since
shredded
+writes need a Spark 4.1+ writer:
+ spark-submit --jars hudi-spark4.2-bundle_2.13-1.3.0.jar generate.py <out
dir> shredded
+
+Each table goes to <out dir>/<name>; zip it from <out dir> leaving out `*.crc`.
+"""
+import os
+import sys
+
+from pyspark.sql import SparkSession
+
+OUT = sys.argv[1]
+SHREDDED = len(sys.argv) > 2 and sys.argv[2] == "shredded"
+# Table version 9 is the newest hudi-rs reads. Shredding is forced so that
every
+# base file shreds the top-level and struct-member Variants; array elements
stay
+# unshredded, as the writer leaves them.
+EXTRA_PROPS = {
+ "hoodie.write.table.version": "9",
+ "hoodie.parquet.variant.force.shredding.schema.for.test":
+ "a int, b string, big decimal(38, 3), neg int, u string",
+} if SHREDDED else {}
+
+spark = (
+ SparkSession.builder.appName("hudi-rs-variant-fixtures")
+ .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
+ .config("spark.kryo.registrator",
"org.apache.spark.HoodieSparkKryoRegistrar")
+ .config("spark.sql.extensions",
"org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
+ .config("spark.sql.catalog.spark_catalog",
"org.apache.spark.sql.hudi.catalog.HoodieCatalog")
+ .config("spark.sql.warehouse.dir", os.path.join(OUT, "warehouse"))
+ .config("spark.sql.session.timeZone", "UTC")
+ .getOrCreate()
+)
+
+# Keep in step with the expected values in
crates/core/tests/variant_read_tests.rs.
+INSERTS = {
+ 1: '{"a":1,"b":"x","c":[1,2,3]}',
+ 2: '"plain string"',
+ 3: "123",
+ 4: "1.5",
+ 5: "true",
+ 6: "null",
+ 7: '{"big":12345678901234567890.123,"neg":-7}',
+ 8: '{"deep":{"x":{"y":{"z":[{"k":"v"},null,[]]}}},"u":"héllo ☃"}',
+ 9: None,
+ 10: "[]",
+ 11: "{}",
+}
+UPSERTS = {
+ 1: '{"a":2,"b":"y","added":{"n":null}}',
+ 2: '[1,"two",3.0,false]',
+ 9: '{"was":"null"}',
+ 12: '{"inserted":"later"}',
+}
+
+
+def write(name, rows, ts):
+ data = [(k, ts, "p1" if k % 2 else "p2", j) for k, j in rows.items()]
+ spark.createDataFrame(data, "id INT, ts BIGINT, part STRING, j
STRING").createOrReplaceTempView("src")
+ exprs = {
+ "id": "id",
+ "ts": "ts",
+ "part": "part",
+ "v": "parse_json(j)",
+ "s": "named_struct('n', id, 'nv', parse_json(j))",
+ # parquet-avro cannot write a null array element, so SQL NULL becomes
a Variant null.
+ "arr": """array(parse_json(coalesce(j, 'null')),
parse_json(concat('{"i":', id, '}')))""",
+ }
+ # Spark rejects an INSERT column list that names a struct holding a
VARIANT, so
+ # insert by position.
+ cols = [c for c in spark.table(name).columns if not
c.startswith("_hoodie")]
+ spark.sql(f"INSERT INTO {name} SELECT {', '.join(exprs[c] for c in cols)}
FROM src")
+
+
+for k, v in EXTRA_PROPS.items():
+ spark.sql(f"SET {k}={v}")
+extra = "".join(f",\n '{k}' = '{v}'" for k, v in EXTRA_PROPS.items())
+
+for table_type in ["cow", "mor"]:
+ name = f"variant_{'shredded' if SHREDDED else 'multi'}_{table_type}"
+ spark.sql(f"DROP TABLE IF EXISTS {name}")
+ spark.sql(f"""
+ CREATE TABLE {name} (
+ id INT, ts BIGINT, part STRING,
+ v VARIANT, s STRUCT<n: INT, nv: VARIANT>, arr ARRAY<VARIANT>
+ ) USING hudi
+ PARTITIONED BY (part)
+ LOCATION '{os.path.join(OUT, name)}'
+ TBLPROPERTIES (
+ type = '{table_type}', primaryKey = 'id', preCombineField = 'ts',
+ 'hoodie.compact.inline' = 'false'{extra}
+ )""")
+ spark.sql("SET hoodie.spark.sql.insert.into.operation=insert")
+ write(name, INSERTS, 1)
+ # Upsert so that a MOR table writes its updates to log files.
+ spark.sql("SET hoodie.spark.sql.insert.into.operation=upsert")
+ write(name, UPSERTS, 2)
+ spark.sql(f"DELETE FROM {name} WHERE id = 3")
+
+spark.stop()
diff --git a/crates/test/data/variant/variant_cow.zip
b/crates/test/data/variant/variant_cow.zip
new file mode 100644
index 00000000..e1efe0f4
Binary files /dev/null and b/crates/test/data/variant/variant_cow.zip differ
diff --git a/crates/test/data/variant/variant_mor_avro.zip
b/crates/test/data/variant/variant_mor_avro.zip
new file mode 100644
index 00000000..610188de
Binary files /dev/null and b/crates/test/data/variant/variant_mor_avro.zip
differ
diff --git a/crates/test/data/variant/variant_mor_spark.zip
b/crates/test/data/variant/variant_mor_spark.zip
new file mode 100644
index 00000000..b1ab2984
Binary files /dev/null and b/crates/test/data/variant/variant_mor_spark.zip
differ
diff --git a/crates/test/data/variant/variant_multi_cow.zip
b/crates/test/data/variant/variant_multi_cow.zip
new file mode 100644
index 00000000..099fb1d9
Binary files /dev/null and b/crates/test/data/variant/variant_multi_cow.zip
differ
diff --git a/crates/test/data/variant/variant_multi_mor.zip
b/crates/test/data/variant/variant_multi_mor.zip
new file mode 100644
index 00000000..6736f85d
Binary files /dev/null and b/crates/test/data/variant/variant_multi_mor.zip
differ
diff --git a/crates/test/data/variant/variant_shredded_cow.zip
b/crates/test/data/variant/variant_shredded_cow.zip
new file mode 100644
index 00000000..934fc68c
Binary files /dev/null and b/crates/test/data/variant/variant_shredded_cow.zip
differ
diff --git a/crates/test/data/variant/variant_shredded_mixed_cow.zip
b/crates/test/data/variant/variant_shredded_mixed_cow.zip
new file mode 100644
index 00000000..84dc7ecf
Binary files /dev/null and
b/crates/test/data/variant/variant_shredded_mixed_cow.zip differ
diff --git a/crates/test/data/variant/variant_shredded_mor.zip
b/crates/test/data/variant/variant_shredded_mor.zip
new file mode 100644
index 00000000..890368d7
Binary files /dev/null and b/crates/test/data/variant/variant_shredded_mor.zip
differ
diff --git a/crates/test/src/lib.rs b/crates/test/src/lib.rs
index 805b6b31..dabd83a7 100644
--- a/crates/test/src/lib.rs
+++ b/crates/test/src/lib.rs
@@ -33,6 +33,7 @@ use zip::ZipArchive;
pub mod gold;
pub mod gold_options;
pub mod util;
+pub mod variant;
#[cfg(feature = "datafusion")]
pub mod v9_verification;
diff --git a/crates/test/src/variant.rs b/crates/test/src/variant.rs
new file mode 100644
index 00000000..1df278a2
--- /dev/null
+++ b/crates/test/src/variant.rs
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+use arrow_array::{Array, Int32Array, RecordBatch};
+use parquet::variant::{VariantArray, VariantType, variant_to_json};
+use serde_json::Value;
+use std::path::{Path, PathBuf};
+
+/// Path to a pinned Java/Spark-produced Variant table fixture.
+pub fn variant_table_path(name: &str) -> PathBuf {
+ let zip =
Path::new(env!("CARGO_MANIFEST_DIR")).join(format!("data/variant/{name}.zip"));
+ crate::extract_test_table(&zip).join(name)
+}
+
+/// Decode fixture rows to logical JSON while checking Variant extension
metadata.
+pub fn variant_rows(batches: &[RecordBatch]) -> Vec<(i32, Value)> {
+ let mut rows = Vec::new();
+ for batch in batches {
+ batch
+ .schema()
+ .field_with_name("v")
+ .unwrap()
+ .try_extension_type::<VariantType>()
+ .unwrap();
+ let ids = batch
+ .column_by_name("id")
+ .unwrap()
+ .as_any()
+ .downcast_ref::<Int32Array>()
+ .unwrap();
+ let column = batch.column_by_name("v").unwrap();
+ let variants = VariantArray::try_new(column).unwrap();
+ for i in 0..variants.len() {
+ variants
+ .try_value(i)
+ .unwrap_or_else(|e| panic!("{e}: {column:?}"));
+ }
+ // The JSON kernel expects metadata/value in that order and Binary
storage.
+ let canonical: arrow_array::ArrayRef =
std::sync::Arc::new(arrow_array::StructArray::new(
+ vec![
+ arrow_schema::Field::new("metadata",
arrow_schema::DataType::Binary, false),
+ arrow_schema::Field::new("value",
arrow_schema::DataType::Binary, true),
+ ]
+ .into(),
+ vec![
+ arrow_cast::cast(variants.metadata_column(),
&arrow_schema::DataType::Binary)
+ .unwrap(),
+ arrow_cast::cast(variants.value_column(),
&arrow_schema::DataType::Binary).unwrap(),
+ ],
+ variants.nulls().cloned(),
+ ));
+ let values = variant_to_json(&canonical).unwrap();
+ for row in 0..batch.num_rows() {
+ rows.push((
+ ids.value(row),
+ if values.is_null(row) {
+ Value::Null
+ } else {
+ serde_json::from_str(values.value(row)).unwrap()
+ },
+ ));
+ }
+ }
+ rows.sort_by_key(|(id, _)| *id);
+ rows
+}
diff --git a/docs/reader-spec.md b/docs/reader-spec.md
index b1d48706..4a41f975 100644
--- a/docs/reader-spec.md
+++ b/docs/reader-spec.md
@@ -348,3 +348,20 @@ For I/O cost estimation (on-disk base + log file sizes),
use `FileSlice::total_s
`Table` / `HudiTable` stores table configs (`HudiTableConfig`) and those read
configs whose scope is `TableOrRead`; a per-read value overrides them.
`ReadOnly` read configs — `hoodie.read.query.type` and the as-of/start/end
timestamps — are filtered out during construction and flow exclusively through
`ReadOptions` / `HudiReadOptions` per-call, so `hudi_options()` on the table
never reflects them.
Out of scope for this version: writer APIs, internal architecture (timeline
parsing, log-record merging, metadata table layout), the full configuration key
glossary (`HudiReadConfig` / `HudiTableConfig` members), and the DataFusion and
C++ bindings — separate spec follow-ups.
+
+## Variant columns
+
+Variant columns use Arrow Struct storage with the `arrow.parquet.variant`
+extension metadata. Unshredded Hudi Variant values are preserved through COW
and
+MOR reads, projections and the Arrow bindings. Consumers can use
+`parquet::variant::VariantArray::try_new` to decode values by child name; Hudi
+producers may order `value` and `metadata` differently. SQL null and an encoded
+Variant null remain distinct.
+
+A base file may store a Variant shredded, with a `typed_value` child holding
parts
+of the value in typed columns; a read that projects to the table schema
(`Table`,
+`HudiTable` and DataFusion reads) rebuilds the binary `value` from it, so
shredded
+and unshredded files read the same. Variant scans use the Hudi file-group
+reader in DataFusion, because DataFusion's Parquet scan cannot rebuild a
shredded
+value, so those base files get no row-group or page pruning. Variant
comparisons are not advertised as pushdown predicates; queries on ordinary
+columns of the same table continue to work.
diff --git a/python/hudi/_internal.pyi b/python/hudi/_internal.pyi
index 0bcdc241..5fea2d3f 100644
--- a/python/hudi/_internal.pyi
+++ b/python/hudi/_internal.pyi
@@ -483,6 +483,10 @@ class HudiTable:
"""
Returns the schema of the Hudi table, without meta fields.
+ A Variant column is a struct of binary ``metadata`` and ``value``
+ fields whose field metadata names the ``arrow.parquet.variant``
+ extension type; reads return the encoded bytes undecoded.
+
Returns:
pyarrow.Schema: The schema of the table.
"""
diff --git a/python/tests/test_variant_read.py
b/python/tests/test_variant_read.py
new file mode 100644
index 00000000..1b8dc196
--- /dev/null
+++ b/python/tests/test_variant_read.py
@@ -0,0 +1,40 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Variant extension metadata survives the Python Arrow binding."""
+
+from pathlib import Path
+from zipfile import ZipFile
+
+import pyarrow as pa
+
+from hudi import HudiReadOptions, HudiTable
+
+
+def test_variant_mor_read_preserves_extension_and_payload(tmp_path):
+ fixtures = Path(__file__).resolve().parents[2] / "crates/test/data/variant"
+ with ZipFile(fixtures / "variant_mor_avro.zip") as archive:
+ archive.extractall(tmp_path)
+ table = HudiTable(str(tmp_path / "variant_mor_avro"))
+ batches = table.read(HudiReadOptions(projection=["id", "v"]))
+ result = pa.Table.from_batches(batches)
+ assert result.column("id").to_pylist() == [1]
+ field = result.schema.field("v")
+ assert field.metadata[b"ARROW:extension:name"] == b"arrow.parquet.variant"
+ value = result.column("v").to_pylist()[0]
+ assert value["metadata"]
+ assert value["value"]