hudi-agent commented on code in PR #18065:
URL: https://github.com/apache/hudi/pull/18065#discussion_r3424867460
##########
hudi-hadoop-common/src/main/java/org/apache/hudi/avro/HoodieAvroWriteSupport.java:
##########
@@ -74,6 +325,182 @@ public void addFooterMetadata(String key, String value) {
footerMetadata.put(key, value);
}
+ /**
+ * Bundles the Avro sub-schema and {@link HoodieSchema.Variant} for a
shredded variant field,
+ * keyed by effective-schema field index in {@link #shreddedVariantFields}.
+ */
+ private static final class ShreddedVariantField {
+ private final Schema avroSchema;
+ private final HoodieSchema.Variant hoodieSchema;
+
+ ShreddedVariantField(Schema avroSchema, HoodieSchema.Variant hoodieSchema)
{
+ this.avroSchema = avroSchema;
+ this.hoodieSchema = hoodieSchema;
+ }
+ }
+
+ private static final Pattern DECIMAL_PATTERN = Pattern.compile(
+ "decimal\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)");
+
+ /**
+ * Applies a forced shredding schema to all variant fields in the given
schema.
+ * The forced schema DDL (e.g., {@code "a int, b string"}) defines the
typed_value
+ * fields that will be added to each variant column.
+ */
+ private static HoodieSchema applyForcedShreddingSchema(HoodieSchema schema,
String ddl) {
+ if (schema.getType() != HoodieSchemaType.RECORD) {
+ return schema;
+ }
+
+ Map<String, HoodieSchema> shreddedFields = parseShreddingDDL(ddl);
+
+ List<HoodieSchemaField> fields = schema.getFields();
+ List<HoodieSchemaField> newFields = new ArrayList<>();
+ boolean changed = false;
+
+ for (HoodieSchemaField field : fields) {
+ HoodieSchema fieldSchema = field.schema();
+ boolean wasNullable = fieldSchema.isNullable();
+ HoodieSchema unwrapped = wasNullable ? fieldSchema.getNonNullType() :
fieldSchema;
+
+ if (unwrapped.getType() == HoodieSchemaType.VARIANT) {
+ HoodieSchema.Variant shreddedVariant =
HoodieSchema.createVariantShreddedObject(
+ unwrapped.getAvroSchema().getName(),
+ unwrapped.getAvroSchema().getNamespace(),
+ unwrapped.getAvroSchema().getDoc(),
+ shreddedFields);
+ HoodieSchema replacement = wasNullable
+ ? HoodieSchema.createNullable(shreddedVariant) : shreddedVariant;
+
newFields.add(HoodieSchemaUtils.createNewSchemaField(field.makeNullable().withSchema(replacement)));
+ changed = true;
+ } else {
+ newFields.add(HoodieSchemaUtils.createNewSchemaField(field));
+ }
+ }
+
+ if (!changed) {
+ return schema;
+ }
+
+ return HoodieSchema.createRecord(
+ schema.getAvroSchema().getName(),
+ schema.getAvroSchema().getNamespace(),
+ schema.getAvroSchema().getDoc(),
+ newFields);
+ }
+
+ /**
+ * Parses a DDL-style shredding schema string (e.g., {@code "a int, b
string, c decimal(15,1)"})
+ * into a map of field names to their HoodieSchema types.
+ */
+ private static Map<String, HoodieSchema> parseShreddingDDL(String ddl) {
+ Map<String, HoodieSchema> fields = new LinkedHashMap<>();
+ for (String fieldDef : ddl.split(",")) {
Review Comment:
🤖 The naive `ddl.split(",")` here breaks decimal types: for the documented
example `"a int, b string, c decimal(15, 1)"`, the split yields `[..., " c
decimal(15", " 1)"]` and `parseSimpleType("decimal(15")` then throws
`Unsupported shredding type: decimal(15`. Both the config doc on
`PARQUET_VARIANT_FORCE_SHREDDING_SCHEMA_FOR_TEST` and the javadoc on
`parseShreddingDDL` itself advertise `decimal(15, 1)` as a supported example.
Could you make this paren-aware (track paren depth before splitting), or
restrict the doc to comma-free types?
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-spark-datasource/hudi-spark4-common/src/main/java/org/apache/hudi/variant/Spark4VariantShreddingProvider.java:
##########
@@ -0,0 +1,405 @@
+/*
+ * 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.
+ */
+
+package org.apache.hudi.variant;
+
+import org.apache.hudi.avro.VariantShreddingProvider;
+import org.apache.hudi.common.schema.HoodieSchema;
+
+import org.apache.avro.LogicalType;
+import org.apache.avro.LogicalTypes;
+import org.apache.avro.Schema;
+import org.apache.avro.generic.GenericData;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.spark.types.variant.Variant;
+import org.apache.spark.types.variant.VariantSchema;
+import org.apache.spark.types.variant.VariantShreddingWriter;
+import org.apache.spark.types.variant.VariantShreddingWriter.ShreddedResult;
+import
org.apache.spark.types.variant.VariantShreddingWriter.ShreddedResultBuilder;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ * Implementation of {@link VariantShreddingProvider} using Spark 4's variant
parsing library.
+ *
+ * <p>This class bridges the Avro record path and Spark's {@link
VariantShreddingWriter}
+ * to allow {@code HoodieRecordType.AVRO} to write shredded variant types. It
converts
+ * the shredded output into Avro {@link GenericRecord}s that can be written via
+ * {@link org.apache.hudi.avro.HoodieAvroWriteSupport}.</p>
+ *
+ * <p>The shredding logic is delegated to {@link
VariantShreddingWriter#castShredded},
+ * which handles scalar, object, and array shredding including residual value
construction
+ * for non-matching fields. This class implements the {@link ShreddedResult}
and
+ * {@link ShreddedResultBuilder} interfaces to collect the shredded components
into
+ * Avro GenericRecords.</p>
+ */
+public class Spark4VariantShreddingProvider implements
VariantShreddingProvider {
+
+ private static final String VALUE_FIELD = "value";
Review Comment:
🤖 nit: `VALUE_FIELD`, `METADATA_FIELD`, and `TYPED_VALUE_FIELD` duplicate
the constants already defined on `HoodieSchema.Variant` (`VARIANT_VALUE_FIELD`,
`VARIANT_METADATA_FIELD`, `VARIANT_TYPED_VALUE_FIELD`) that the rest of this PR
uses (e.g. in `HoodieAvroWriteSupport` and `BaseSpark4Adapter`). Could you drop
these local copies and reference `HoodieSchema.Variant.*` directly so there's a
single source of truth if the field names ever change?
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-hadoop-common/src/main/java/org/apache/hudi/io/storage/hadoop/HoodieAvroFileWriterFactory.java:
##########
@@ -140,9 +142,42 @@ private HoodieAvroWriteSupport
getHoodieAvroWriteSupport(HoodieSchema schema,
StorageConfiguration storageConf,
boolean
enableBloomFilter) {
Option<BloomFilter> filter = enableBloomFilter ?
Option.of(createBloomFilter(config)) : Option.empty();
+ HoodieSchema effectiveSchema =
HoodieAvroWriteSupport.generateEffectiveSchema(schema, config);
+ // Work on a copy so we never mutate the shared config's internal
Properties.
+ Properties props = TypedProperties.copy(config.getProps());
+ // Auto-detect variant shredding provider from classpath if not explicitly
configured
+ if (!props.containsKey(PARQUET_VARIANT_SHREDDING_PROVIDER_CLASS.key())) {
+ String detected = detectShreddingProvider();
+ if (detected != null) {
+ props.setProperty(PARQUET_VARIANT_SHREDDING_PROVIDER_CLASS.key(),
detected);
+ }
+ }
return (HoodieAvroWriteSupport) ReflectionUtils.loadClass(
config.getStringOrDefault(HoodieStorageConfig.HOODIE_AVRO_WRITE_SUPPORT_CLASS),
new Class<?>[] {MessageType.class, HoodieSchema.class, Option.class,
Properties.class},
- getAvroSchemaConverter((Configuration)
storageConf.unwrapAs(Configuration.class)).convert(schema), schema, filter,
config.getProps());
+ // Build the Parquet schema from the effective (possibly shredded)
schema so the message type
+ // matches the records actually written - a shredded variant has a
nullable value and a
+ // typed_value column; converting the original schema would mark value
REQUIRED and drop
+ // typed_value, failing the write with "Null-value for required field:
value".
+ getAvroSchemaConverter((Configuration)
storageConf.unwrapAs(Configuration.class)).convert(effectiveSchema), schema,
filter, props);
+ }
+
+ /**
+ * Auto-detect a {@link org.apache.hudi.avro.VariantShreddingProvider}
implementation
+ * available on the classpath. Returns the fully-qualified class name if
found, or null.
+ */
+ private static String detectShreddingProvider() {
+ String[] candidates = {
Review Comment:
🤖 nit: `detectShreddingProvider()` returns a fully-qualified class name
string, not a provider instance — the name implies it returns the object
itself. Something like `detectShreddingProviderClass()` would make the return
type's meaning immediately obvious without needing to read the Javadoc.
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
##########
hudi-spark-datasource/hudi-spark4-common/src/main/java/org/apache/hudi/variant/Spark4VariantShreddingProvider.java:
##########
@@ -0,0 +1,405 @@
+/*
+ * 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.
+ */
+
+package org.apache.hudi.variant;
+
+import org.apache.hudi.avro.VariantShreddingProvider;
+import org.apache.hudi.common.schema.HoodieSchema;
+
+import org.apache.avro.LogicalType;
+import org.apache.avro.LogicalTypes;
+import org.apache.avro.Schema;
+import org.apache.avro.generic.GenericData;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.spark.types.variant.Variant;
+import org.apache.spark.types.variant.VariantSchema;
+import org.apache.spark.types.variant.VariantShreddingWriter;
+import org.apache.spark.types.variant.VariantShreddingWriter.ShreddedResult;
+import
org.apache.spark.types.variant.VariantShreddingWriter.ShreddedResultBuilder;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ * Implementation of {@link VariantShreddingProvider} using Spark 4's variant
parsing library.
+ *
+ * <p>This class bridges the Avro record path and Spark's {@link
VariantShreddingWriter}
+ * to allow {@code HoodieRecordType.AVRO} to write shredded variant types. It
converts
+ * the shredded output into Avro {@link GenericRecord}s that can be written via
+ * {@link org.apache.hudi.avro.HoodieAvroWriteSupport}.</p>
+ *
+ * <p>The shredding logic is delegated to {@link
VariantShreddingWriter#castShredded},
+ * which handles scalar, object, and array shredding including residual value
construction
+ * for non-matching fields. This class implements the {@link ShreddedResult}
and
+ * {@link ShreddedResultBuilder} interfaces to collect the shredded components
into
+ * Avro GenericRecords.</p>
+ */
+public class Spark4VariantShreddingProvider implements
VariantShreddingProvider {
+
+ private static final String VALUE_FIELD = "value";
+ private static final String METADATA_FIELD = "metadata";
+ private static final String TYPED_VALUE_FIELD = "typed_value";
+
+ @Override
+ public GenericRecord shredVariantRecord(
+ GenericRecord unshreddedVariant,
+ Schema shreddedSchema,
+ HoodieSchema.Variant variantSchema) {
+
+ ByteBuffer valueBuf = (ByteBuffer) unshreddedVariant.get(VALUE_FIELD);
+ ByteBuffer metadataBuf = (ByteBuffer)
unshreddedVariant.get(METADATA_FIELD);
+
+ if (valueBuf == null || metadataBuf == null) {
+ return null;
+ }
+
+ byte[] valueBytes = toByteArray(valueBuf);
+ byte[] metadataBytes = toByteArray(metadataBuf);
+
+ Variant variant = new Variant(valueBytes, metadataBytes);
+
+ // Build VariantSchema from the Avro shredded schema, registering
+ // Avro schemas at each level for GenericRecord construction.
+ AvroShreddedResultBuilder builder = new AvroShreddedResultBuilder();
+ VariantSchema sparkSchema = buildVariantSchema(shreddedSchema, true,
builder);
+
+ // Delegate to Spark's VariantShreddingWriter for the actual shredding
logic.
+ AvroShreddedResult result = (AvroShreddedResult)
+ VariantShreddingWriter.castShredded(variant, sparkSchema, builder);
+
+ return result.toGenericRecord();
+ }
+
+ /**
+ * Builds a {@link VariantSchema} from an Avro {@link Schema} representing a
+ * shredded variant structure ({@code value}, {@code metadata}, {@code
typed_value}).
+ *
+ * <p>This method also registers the Avro schema mapping in the builder so
that
+ * {@link AvroShreddedResultBuilder#createEmpty} can create results with the
+ * correct Avro schema at each nesting level.</p>
+ */
+ private VariantSchema buildVariantSchema(Schema avroSchema, boolean
isTopLevel,
+ AvroShreddedResultBuilder builder) {
+ Schema.Field valueField = avroSchema.getField(VALUE_FIELD);
+ Schema.Field metadataField = avroSchema.getField(METADATA_FIELD);
+ Schema.Field typedValueField = avroSchema.getField(TYPED_VALUE_FIELD);
+
+ int idx = 0;
Review Comment:
🤖 nit: `idx` does double duty here — it's used as a post-increment position
counter during field index assignment, then its final value becomes
`numFields`. The name `idx` reads as "an index into something", not "a running
count". Could you rename it to `fieldCount` (or `pos`) to make it clearer that
its terminal value is the total number of fields, not the last field's index?
<sub><i>- AI-generated; verify before applying. React 👍/👎 to flag
quality.</i></sub>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]