laskoviymishka commented on code in PR #17520: URL: https://github.com/apache/iceberg/pull/17520#discussion_r3734430653
########## data/src/main/java/org/apache/iceberg/data/RecordVariantShreddingAnalyzer.java: ########## @@ -0,0 +1,86 @@ +/* + * 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.iceberg.data; + +import java.util.List; +import java.util.Map; +import org.apache.iceberg.Schema; +import org.apache.iceberg.parquet.VariantShreddingAnalyzer; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.types.Types.NestedField; +import org.apache.iceberg.variants.Variant; +import org.apache.iceberg.variants.VariantValue; +import org.apache.parquet.schema.Type; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Generic {@link Record} analyzer that resolves variant columns by their position in {@link + * Schema#columns()}; buffered rows must be built against the same {@link Schema} passed as the + * engine schema so {@link Record#get(int)} positions match the resolved indices. + */ +class RecordVariantShreddingAnalyzer extends VariantShreddingAnalyzer<Record, Schema> { + private static final Logger LOG = LoggerFactory.getLogger(RecordVariantShreddingAnalyzer.class); + + RecordVariantShreddingAnalyzer() {} + + @Override + public Map<Integer, Type> analyzeVariantColumns( + List<Record> bufferedRows, Schema icebergSchema, Schema engineSchema) { + // Record rows are built against the Iceberg schema; use it when no engine schema is supplied. + return super.analyzeVariantColumns( + bufferedRows, icebergSchema, engineSchema != null ? engineSchema : icebergSchema); + } + + @Override + protected int resolveColumnIndex(Schema engineSchema, String columnName) { + Preconditions.checkArgument(engineSchema != null, "Invalid engine schema: null"); + List<NestedField> columns = engineSchema.columns(); + for (int index = 0; index < columns.size(); index++) { + if (columns.get(index).name().equals(columnName)) { + return index; + } + } + + LOG.warn("Variant column {} not found in engine schema; skipping shredding", columnName); + return -1; + } + + @Override + protected List<VariantValue> extractVariantValues( + List<Record> bufferedRows, int variantFieldIndex) { + List<VariantValue> values = Lists.newArrayList(); + for (Record row : bufferedRows) { + Object fieldValue = row.get(variantFieldIndex); + if (fieldValue == null) { + continue; + } + + Preconditions.checkArgument( Review Comment: Everything else on this path degrades: a missing column warns and skips, an all-null buffer falls back to unshredded. This one throws, so a single unexpected object at a variant position fails the whole write rather than writing it unshredded. For the Kafka Connect case, where the `Record` is assembled from whatever the converter produced, I'd rather log and skip shredding for that column than fail the commit. Spark's analyzer doesn't check here at all and Flink throws `UnsupportedOperationException`, so there's no established behavior to match — but a hard failure from the most permissive of the three writers is the combination I'd least expect. ########## data/src/main/java/org/apache/iceberg/data/RecordVariantShreddingAnalyzer.java: ########## @@ -0,0 +1,86 @@ +/* + * 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.iceberg.data; + +import java.util.List; +import java.util.Map; +import org.apache.iceberg.Schema; +import org.apache.iceberg.parquet.VariantShreddingAnalyzer; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.types.Types.NestedField; +import org.apache.iceberg.variants.Variant; +import org.apache.iceberg.variants.VariantValue; +import org.apache.parquet.schema.Type; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Generic {@link Record} analyzer that resolves variant columns by their position in {@link + * Schema#columns()}; buffered rows must be built against the same {@link Schema} passed as the Review Comment: This contract is load-bearing and worth a test that pins it. `resolveColumnIndex` returns a position in the *engine* schema, but `extractVariantValues` reads it out of a `Record` built against the *Iceberg* schema via `row.get(index)`. When the engine schema is null it falls back to the Iceberg schema and the two coincide, which is the common path. `testExplicitEngineSchemaSurvivesSchemaCall` covers the case where the engine schema renames the variant to `w` so it's simply not found and shredding skips — the safe divergence. What isn't covered is an engine schema that keeps the name `v` but at a different position: there `resolveColumnIndex` hands back the engine position and `row.get()` reads a different field, silently. If that combination is meant to be unsupported, a `checkArgument` would make it loud; otherwise a reordering case would be worth adding here. ########## data/src/test/java/org/apache/iceberg/data/TestRecordVariantShreddingAnalyzer.java: ########## @@ -0,0 +1,559 @@ +/* + * 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.iceberg.data; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import org.apache.hadoop.fs.Path; +import org.apache.iceberg.FileFormat; +import org.apache.iceberg.Files; +import org.apache.iceberg.InternalTestHelpers; +import org.apache.iceberg.PartitionSpec; +import org.apache.iceberg.Schema; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableProperties; +import org.apache.iceberg.TestTables; +import org.apache.iceberg.data.parquet.GenericParquetReaders; +import org.apache.iceberg.encryption.EncryptedFiles; +import org.apache.iceberg.encryption.EncryptedOutputFile; +import org.apache.iceberg.formats.FileWriterBuilder; +import org.apache.iceberg.formats.FormatModelRegistry; +import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.io.DataWriter; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.io.OutputFileFactory; +import org.apache.iceberg.parquet.Parquet; +import org.apache.iceberg.parquet.ParquetFileTestUtils; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.types.Types; +import org.apache.iceberg.variants.Variant; +import org.apache.iceberg.variants.VariantTestUtil; +import org.apache.iceberg.variants.Variants; +import org.apache.parquet.example.data.Group; +import org.apache.parquet.hadoop.ParquetFileReader; +import org.apache.parquet.hadoop.ParquetReader; +import org.apache.parquet.hadoop.example.GroupReadSupport; +import org.apache.parquet.schema.GroupType; +import org.apache.parquet.schema.MessageType; +import org.apache.parquet.schema.Type; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +public class TestRecordVariantShreddingAnalyzer { + + private static final Schema VARIANT_AFTER_ID_SCHEMA = + new Schema( + Types.NestedField.required(1, "id", Types.LongType.get()), + Types.NestedField.optional(2, "v", Types.VariantType.get())); + + private static final Schema VARIANT_BEFORE_ID_SCHEMA = + new Schema( + Types.NestedField.optional(1, "v", Types.VariantType.get()), + Types.NestedField.required(2, "id", Types.LongType.get())); + + private static final Schema MULTI_VARIANT_SCHEMA = + new Schema( + Types.NestedField.required(1, "id", Types.LongType.get()), + Types.NestedField.optional(2, "v1", Types.VariantType.get()), + Types.NestedField.optional(3, "other", Types.StringType.get()), + Types.NestedField.optional(4, "v2", Types.VariantType.get())); + + // Engine schema whose variant column is named "w" instead of "v", so the "v" column resolved + // from the Iceberg schema is not found and shredding does not activate. + private static final Schema MISMATCHED_ENGINE_SCHEMA = + new Schema( + Types.NestedField.required(1, "id", Types.LongType.get()), + Types.NestedField.optional(2, "w", Types.VariantType.get())); + + private static final int VARIANT_FIELD_ID = 2; + private static final int VARIANT_FIRST_FIELD_ID = 1; + private static final int FIRST_MULTI_VARIANT_FIELD_ID = 2; + private static final int SECOND_MULTI_VARIANT_FIELD_ID = 4; + private static final String BUFFER_SIZE = "2"; + + private Variant variant; + private List<Record> records; + + @TempDir private java.nio.file.Path temp; + + @BeforeEach + public void before() { + variant = + VariantTestUtil.variant( + ImmutableMap.of( + "a", Variants.of(42), + "b", Variants.of("hello"))); + + GenericRecord record = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + records = + ImmutableList.of( + record.copy(ImmutableMap.of("id", 1L, "v", variant)), + record.copy(ImmutableMap.of("id", 2L, "v", variant)), + record.copy(ImmutableMap.of("id", 3L, "v", variant))); + } + + @Test + public void testAnalyzeVariantColumnsUsesIcebergColumnOrder() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns(records, VARIANT_AFTER_ID_SCHEMA, VARIANT_AFTER_ID_SCHEMA); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIELD_ID); + GroupType typedValue = shreddedTypes.get(VARIANT_FIELD_ID).asGroupType(); + assertThat(typedValue.getName()).isEqualTo("typed_value"); + assertThat(typedValue.containsField("a")).isTrue(); + assertThat(typedValue.containsField("b")).isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsWhenVariantIsFirstColumn() { + GenericRecord record = GenericRecord.create(VARIANT_BEFORE_ID_SCHEMA); + List<Record> variantFirstRecords = + ImmutableList.of( + record.copy(ImmutableMap.of("v", variant, "id", 1L)), + record.copy(ImmutableMap.of("v", variant, "id", 2L))); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + variantFirstRecords, VARIANT_BEFORE_ID_SCHEMA, VARIANT_BEFORE_ID_SCHEMA); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIRST_FIELD_ID); + assertThat(shreddedTypes.get(VARIANT_FIRST_FIELD_ID).asGroupType().containsField("a")).isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsWithMultipleNonAdjacentVariants() { + GenericRecord record = GenericRecord.create(MULTI_VARIANT_SCHEMA); + List<Record> multiVariantRecords = + ImmutableList.of( + record.copy(ImmutableMap.of("id", 1L, "v1", variant, "other", "x", "v2", variant)), + record.copy(ImmutableMap.of("id", 2L, "v1", variant, "other", "y", "v2", variant))); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + multiVariantRecords, MULTI_VARIANT_SCHEMA, MULTI_VARIANT_SCHEMA); + + assertThat(shreddedTypes) + .containsOnlyKeys(FIRST_MULTI_VARIANT_FIELD_ID, SECOND_MULTI_VARIANT_FIELD_ID); + assertThat(shreddedTypes.get(FIRST_MULTI_VARIANT_FIELD_ID).asGroupType().containsField("a")) + .isTrue(); + assertThat(shreddedTypes.get(SECOND_MULTI_VARIANT_FIELD_ID).asGroupType().containsField("b")) + .isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsSkipsNullVariantValues() { + GenericRecord withVariant = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + withVariant.setField("id", 1L); + withVariant.setField("v", variant); + + GenericRecord withNullVariant = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + withNullVariant.setField("id", 2L); + withNullVariant.setField("v", null); + + GenericRecord withVariant2 = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + withVariant2.setField("id", 3L); + withVariant2.setField("v", variant); + + List<Record> recordsWithNulls = ImmutableList.of(withVariant, withNullVariant, withVariant2); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + recordsWithNulls, VARIANT_AFTER_ID_SCHEMA, VARIANT_AFTER_ID_SCHEMA); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIELD_ID); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("a")).isTrue(); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("b")).isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsWithAllNullVariantValues() { + GenericRecord nullVariant1 = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + nullVariant1.setField("id", 1L); + nullVariant1.setField("v", null); + + GenericRecord nullVariant2 = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + nullVariant2.setField("id", 2L); + nullVariant2.setField("v", null); + + List<Record> allNullVariants = ImmutableList.of(nullVariant1, nullVariant2); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + allNullVariants, VARIANT_AFTER_ID_SCHEMA, VARIANT_AFTER_ID_SCHEMA); + + assertThat(shreddedTypes).isEmpty(); + } + + @Test + public void testAnalyzeVariantColumnsRejectsNonVariantValues() { + GenericRecord invalidRecord = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + invalidRecord.setField("id", 1L); + invalidRecord.setField("v", "not-a-variant"); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + assertThatThrownBy( + () -> + analyzer.analyzeVariantColumns( + ImmutableList.of(invalidRecord), + VARIANT_AFTER_ID_SCHEMA, + VARIANT_AFTER_ID_SCHEMA)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Expected Variant at index 1 but was: java.lang.String"); + } + + @Test + public void testAnalyzeVariantColumnsFallsBackToIcebergSchemaWhenEngineSchemaNull() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns(records, VARIANT_AFTER_ID_SCHEMA, null); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIELD_ID); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("a")).isTrue(); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("b")).isTrue(); + } + + @Test + public void testResolveColumnIndexRejectsNullEngineSchema() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + assertThatThrownBy(() -> analyzer.resolveColumnIndex(null, "v")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid engine schema: null"); + } + + @Test + public void testAnalyzeVariantColumnsSkipsColumnMissingFromEngineSchema() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns(records, VARIANT_AFTER_ID_SCHEMA, MISMATCHED_ENGINE_SCHEMA); + + assertThat(shreddedTypes).isEmpty(); + } + + @Test + public void testResolveColumnIndexResolvesPositionsAndReportsMisses() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + assertThat(analyzer.resolveColumnIndex(VARIANT_AFTER_ID_SCHEMA, "id")).isEqualTo(0); + assertThat(analyzer.resolveColumnIndex(VARIANT_AFTER_ID_SCHEMA, "v")).isEqualTo(1); + assertThat(analyzer.resolveColumnIndex(VARIANT_BEFORE_ID_SCHEMA, "v")).isEqualTo(0); + assertThat(analyzer.resolveColumnIndex(VARIANT_AFTER_ID_SCHEMA, "missing")).isEqualTo(-1); + } + + @Test + public void testGenericFileWriterFactoryShreddingRoundTrip() throws IOException { Review Comment: `GenericFileWriterFactory` is the right proxy — that's what `RecordUtils.createTableWriter` reaches — but the records here are built directly, and the rationale is about Kafka Connect specifically, where they come out of `RecordConverter`. Since the whole mechanism is positional, a converter producing records whose field positions don't line up with `Schema.columns()` would make this a silent no-op and nothing here would catch it. One test in `kafka-connect` that goes `SinkRecord` → `RecordConverter` → this writer and asserts the physical layout would cover the path the PR is actually for. ########## data/src/test/java/org/apache/iceberg/data/TestRecordVariantShreddingAnalyzer.java: ########## @@ -0,0 +1,559 @@ +/* + * 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.iceberg.data; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import org.apache.hadoop.fs.Path; +import org.apache.iceberg.FileFormat; +import org.apache.iceberg.Files; +import org.apache.iceberg.InternalTestHelpers; +import org.apache.iceberg.PartitionSpec; +import org.apache.iceberg.Schema; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableProperties; +import org.apache.iceberg.TestTables; +import org.apache.iceberg.data.parquet.GenericParquetReaders; +import org.apache.iceberg.encryption.EncryptedFiles; +import org.apache.iceberg.encryption.EncryptedOutputFile; +import org.apache.iceberg.formats.FileWriterBuilder; +import org.apache.iceberg.formats.FormatModelRegistry; +import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.io.DataWriter; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.io.OutputFileFactory; +import org.apache.iceberg.parquet.Parquet; +import org.apache.iceberg.parquet.ParquetFileTestUtils; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.types.Types; +import org.apache.iceberg.variants.Variant; +import org.apache.iceberg.variants.VariantTestUtil; +import org.apache.iceberg.variants.Variants; +import org.apache.parquet.example.data.Group; +import org.apache.parquet.hadoop.ParquetFileReader; +import org.apache.parquet.hadoop.ParquetReader; +import org.apache.parquet.hadoop.example.GroupReadSupport; +import org.apache.parquet.schema.GroupType; +import org.apache.parquet.schema.MessageType; +import org.apache.parquet.schema.Type; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +public class TestRecordVariantShreddingAnalyzer { + + private static final Schema VARIANT_AFTER_ID_SCHEMA = + new Schema( + Types.NestedField.required(1, "id", Types.LongType.get()), + Types.NestedField.optional(2, "v", Types.VariantType.get())); + + private static final Schema VARIANT_BEFORE_ID_SCHEMA = + new Schema( + Types.NestedField.optional(1, "v", Types.VariantType.get()), + Types.NestedField.required(2, "id", Types.LongType.get())); + + private static final Schema MULTI_VARIANT_SCHEMA = + new Schema( + Types.NestedField.required(1, "id", Types.LongType.get()), + Types.NestedField.optional(2, "v1", Types.VariantType.get()), + Types.NestedField.optional(3, "other", Types.StringType.get()), + Types.NestedField.optional(4, "v2", Types.VariantType.get())); + + // Engine schema whose variant column is named "w" instead of "v", so the "v" column resolved + // from the Iceberg schema is not found and shredding does not activate. + private static final Schema MISMATCHED_ENGINE_SCHEMA = + new Schema( + Types.NestedField.required(1, "id", Types.LongType.get()), + Types.NestedField.optional(2, "w", Types.VariantType.get())); + + private static final int VARIANT_FIELD_ID = 2; + private static final int VARIANT_FIRST_FIELD_ID = 1; + private static final int FIRST_MULTI_VARIANT_FIELD_ID = 2; + private static final int SECOND_MULTI_VARIANT_FIELD_ID = 4; + private static final String BUFFER_SIZE = "2"; + + private Variant variant; + private List<Record> records; + + @TempDir private java.nio.file.Path temp; + + @BeforeEach + public void before() { + variant = + VariantTestUtil.variant( + ImmutableMap.of( + "a", Variants.of(42), + "b", Variants.of("hello"))); + + GenericRecord record = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + records = + ImmutableList.of( + record.copy(ImmutableMap.of("id", 1L, "v", variant)), + record.copy(ImmutableMap.of("id", 2L, "v", variant)), + record.copy(ImmutableMap.of("id", 3L, "v", variant))); + } + + @Test + public void testAnalyzeVariantColumnsUsesIcebergColumnOrder() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns(records, VARIANT_AFTER_ID_SCHEMA, VARIANT_AFTER_ID_SCHEMA); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIELD_ID); + GroupType typedValue = shreddedTypes.get(VARIANT_FIELD_ID).asGroupType(); + assertThat(typedValue.getName()).isEqualTo("typed_value"); + assertThat(typedValue.containsField("a")).isTrue(); + assertThat(typedValue.containsField("b")).isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsWhenVariantIsFirstColumn() { + GenericRecord record = GenericRecord.create(VARIANT_BEFORE_ID_SCHEMA); + List<Record> variantFirstRecords = + ImmutableList.of( + record.copy(ImmutableMap.of("v", variant, "id", 1L)), + record.copy(ImmutableMap.of("v", variant, "id", 2L))); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + variantFirstRecords, VARIANT_BEFORE_ID_SCHEMA, VARIANT_BEFORE_ID_SCHEMA); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIRST_FIELD_ID); + assertThat(shreddedTypes.get(VARIANT_FIRST_FIELD_ID).asGroupType().containsField("a")).isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsWithMultipleNonAdjacentVariants() { + GenericRecord record = GenericRecord.create(MULTI_VARIANT_SCHEMA); + List<Record> multiVariantRecords = + ImmutableList.of( + record.copy(ImmutableMap.of("id", 1L, "v1", variant, "other", "x", "v2", variant)), + record.copy(ImmutableMap.of("id", 2L, "v1", variant, "other", "y", "v2", variant))); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + multiVariantRecords, MULTI_VARIANT_SCHEMA, MULTI_VARIANT_SCHEMA); + + assertThat(shreddedTypes) + .containsOnlyKeys(FIRST_MULTI_VARIANT_FIELD_ID, SECOND_MULTI_VARIANT_FIELD_ID); + assertThat(shreddedTypes.get(FIRST_MULTI_VARIANT_FIELD_ID).asGroupType().containsField("a")) + .isTrue(); + assertThat(shreddedTypes.get(SECOND_MULTI_VARIANT_FIELD_ID).asGroupType().containsField("b")) + .isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsSkipsNullVariantValues() { + GenericRecord withVariant = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + withVariant.setField("id", 1L); + withVariant.setField("v", variant); + + GenericRecord withNullVariant = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + withNullVariant.setField("id", 2L); + withNullVariant.setField("v", null); + + GenericRecord withVariant2 = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + withVariant2.setField("id", 3L); + withVariant2.setField("v", variant); + + List<Record> recordsWithNulls = ImmutableList.of(withVariant, withNullVariant, withVariant2); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + recordsWithNulls, VARIANT_AFTER_ID_SCHEMA, VARIANT_AFTER_ID_SCHEMA); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIELD_ID); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("a")).isTrue(); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("b")).isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsWithAllNullVariantValues() { + GenericRecord nullVariant1 = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + nullVariant1.setField("id", 1L); + nullVariant1.setField("v", null); + + GenericRecord nullVariant2 = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + nullVariant2.setField("id", 2L); + nullVariant2.setField("v", null); + + List<Record> allNullVariants = ImmutableList.of(nullVariant1, nullVariant2); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + allNullVariants, VARIANT_AFTER_ID_SCHEMA, VARIANT_AFTER_ID_SCHEMA); + + assertThat(shreddedTypes).isEmpty(); + } + + @Test + public void testAnalyzeVariantColumnsRejectsNonVariantValues() { + GenericRecord invalidRecord = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + invalidRecord.setField("id", 1L); + invalidRecord.setField("v", "not-a-variant"); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + assertThatThrownBy( + () -> + analyzer.analyzeVariantColumns( + ImmutableList.of(invalidRecord), + VARIANT_AFTER_ID_SCHEMA, + VARIANT_AFTER_ID_SCHEMA)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Expected Variant at index 1 but was: java.lang.String"); + } + + @Test + public void testAnalyzeVariantColumnsFallsBackToIcebergSchemaWhenEngineSchemaNull() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns(records, VARIANT_AFTER_ID_SCHEMA, null); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIELD_ID); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("a")).isTrue(); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("b")).isTrue(); + } + + @Test + public void testResolveColumnIndexRejectsNullEngineSchema() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + assertThatThrownBy(() -> analyzer.resolveColumnIndex(null, "v")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid engine schema: null"); + } + + @Test + public void testAnalyzeVariantColumnsSkipsColumnMissingFromEngineSchema() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns(records, VARIANT_AFTER_ID_SCHEMA, MISMATCHED_ENGINE_SCHEMA); + + assertThat(shreddedTypes).isEmpty(); + } + + @Test + public void testResolveColumnIndexResolvesPositionsAndReportsMisses() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + assertThat(analyzer.resolveColumnIndex(VARIANT_AFTER_ID_SCHEMA, "id")).isEqualTo(0); + assertThat(analyzer.resolveColumnIndex(VARIANT_AFTER_ID_SCHEMA, "v")).isEqualTo(1); + assertThat(analyzer.resolveColumnIndex(VARIANT_BEFORE_ID_SCHEMA, "v")).isEqualTo(0); + assertThat(analyzer.resolveColumnIndex(VARIANT_AFTER_ID_SCHEMA, "missing")).isEqualTo(-1); + } + + @Test + public void testGenericFileWriterFactoryShreddingRoundTrip() throws IOException { + Table table = + TestTables.create( + temp.resolve("table").toFile(), + "variant", + VARIANT_AFTER_ID_SCHEMA, + PartitionSpec.unpartitioned(), + 3); + try { + GenericFileWriterFactory writerFactory = + new GenericFileWriterFactory.Builder(table) + .dataFileFormat(FileFormat.PARQUET) + .dataSchema(VARIANT_AFTER_ID_SCHEMA) + .writerProperties( + ImmutableMap.of( + TableProperties.PARQUET_SHRED_VARIANTS, + "true", + TableProperties.PARQUET_VARIANT_BUFFER_SIZE, + BUFFER_SIZE)) + .build(); + + OutputFileFactory fileFactory = + OutputFileFactory.builderFor(table, 1, 1).format(FileFormat.PARQUET).build(); + EncryptedOutputFile encryptedOutputFile = fileFactory.newOutputFile(); + + // GenericFileWriterFactory does not forward an inputSchema, so engineSchema is null and the + // analyzer falls back to the Iceberg schema to resolve variant columns. + try (DataWriter<Record> writer = + writerFactory.newDataWriter(encryptedOutputFile, table.spec(), null)) { + for (Record rec : records) { + writer.write(rec); + } + } + + OutputFile outputFile = encryptedOutputFile.encryptingOutputFile(); + try (ParquetFileReader reader = + ParquetFileReader.open(ParquetFileTestUtils.file(outputFile.toInputFile()))) { + assertShreddedVariantParquetSchema(reader.getFooter().getFileMetaData().getSchema()); + } + + assertAllRawParquetRowsShredded(outputFile); + assertRecordsRoundTrip(outputFile, records); + } finally { + TestTables.clearTables(); + } + } + + @Test + public void testFormatModelRegistryShreddingRoundTrip() throws IOException { + OutputFile outputFile = Files.localOutput(temp.resolve("variant-shredded.parquet").toFile()); + EncryptedOutputFile encryptedOutputFile = EncryptedFiles.plainAsEncryptedOutput(outputFile); + + FileWriterBuilder<DataWriter<Record>, Schema> writeBuilder = + FormatModelRegistry.dataWriteBuilder(FileFormat.PARQUET, Record.class, encryptedOutputFile); + + try (DataWriter<Record> writer = + writeBuilder + .schema(VARIANT_AFTER_ID_SCHEMA) + .spec(PartitionSpec.unpartitioned()) + .setAll( + ImmutableMap.of( + TableProperties.PARQUET_SHRED_VARIANTS, + "true", + TableProperties.PARQUET_VARIANT_BUFFER_SIZE, + BUFFER_SIZE)) + .build()) { + for (Record rec : records) { + writer.write(rec); + } + } + + try (ParquetFileReader reader = + ParquetFileReader.open(ParquetFileTestUtils.file(outputFile.toInputFile()))) { + assertShreddedVariantParquetSchema(reader.getFooter().getFileMetaData().getSchema()); + } + + assertAllRawParquetRowsShredded(outputFile); + assertRecordsRoundTrip(outputFile, records); + } + + @Test + public void testExplicitNullEngineSchemaStillDerivesAndShreds() throws IOException { + OutputFile outputFile = + Files.localOutput(temp.resolve("explicit-null-engine.parquet").toFile()); + EncryptedOutputFile encryptedOutputFile = EncryptedFiles.plainAsEncryptedOutput(outputFile); + + FileWriterBuilder<DataWriter<Record>, Schema> writeBuilder = + FormatModelRegistry.dataWriteBuilder(FileFormat.PARQUET, Record.class, encryptedOutputFile); + + // Passing null explicitly behaves like not calling engineSchema at all: the analyzer falls + // back. + try (DataWriter<Record> writer = + writeBuilder + .engineSchema(null) + .schema(VARIANT_AFTER_ID_SCHEMA) + .spec(PartitionSpec.unpartitioned()) + .setAll( + ImmutableMap.of( + TableProperties.PARQUET_SHRED_VARIANTS, + "true", + TableProperties.PARQUET_VARIANT_BUFFER_SIZE, + BUFFER_SIZE)) + .build()) { + for (Record rec : records) { + writer.write(rec); + } + } + + try (ParquetFileReader reader = + ParquetFileReader.open(ParquetFileTestUtils.file(outputFile.toInputFile()))) { + assertShreddedVariantParquetSchema(reader.getFooter().getFileMetaData().getSchema()); + } + } + + @Test + public void testPostBufferRowWithUnsampledFieldPreservedInResidual() throws IOException { + Variant variantAbc = + VariantTestUtil.variant( + ImmutableMap.of( + "a", Variants.of(7), + "b", Variants.of("x"), + "c", Variants.of(99))); + + GenericRecord recordBuilder = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + // Buffer size is 2, so the layout is inferred from rows 1-2 (fields a, b). Row 3 adds field c, + // which is not in the inferred typed_value and must survive in the residual value column. + List<Record> mixedRecords = + ImmutableList.of( + recordBuilder.copy(ImmutableMap.of("id", 1L, "v", variant)), + recordBuilder.copy(ImmutableMap.of("id", 2L, "v", variant)), + recordBuilder.copy(ImmutableMap.of("id", 3L, "v", variantAbc))); + + OutputFile outputFile = Files.localOutput(temp.resolve("residual.parquet").toFile()); + EncryptedOutputFile encryptedOutputFile = EncryptedFiles.plainAsEncryptedOutput(outputFile); + + FileWriterBuilder<DataWriter<Record>, Schema> writeBuilder = + FormatModelRegistry.dataWriteBuilder(FileFormat.PARQUET, Record.class, encryptedOutputFile); + try (DataWriter<Record> writer = + writeBuilder + .schema(VARIANT_AFTER_ID_SCHEMA) + .spec(PartitionSpec.unpartitioned()) + .setAll( + ImmutableMap.of( + TableProperties.PARQUET_SHRED_VARIANTS, + "true", + TableProperties.PARQUET_VARIANT_BUFFER_SIZE, + BUFFER_SIZE)) + .build()) { + for (Record rec : mixedRecords) { + writer.write(rec); + } + } + + try (ParquetFileReader reader = + ParquetFileReader.open(ParquetFileTestUtils.file(outputFile.toInputFile()))) { + MessageType parquetSchema = reader.getFooter().getFileMetaData().getSchema(); + assertShreddedVariantParquetSchema(parquetSchema); + GroupType typedValue = + parquetSchema.getType("v").asGroupType().getType("typed_value").asGroupType(); + assertThat(typedValue.containsField("c")).isFalse(); + } + + assertRecordsRoundTrip(outputFile, mixedRecords); Review Comment: `assertAllRawParquetRowsShredded` is deliberately not called here because row 3 should carry a residual, which is right — but that leaves nothing asserting the residual actually exists. As written this passes whether `c` came back out of the residual `value` or the writer kept it somewhere else. One raw `ParquetReader<Group>` pass over row 3 checking `getFieldRepetitionCount("value") > 0` would confirm the overflow field really landed in the residual rather than being silently dropped. ########## data/src/test/java/org/apache/iceberg/data/TestRecordVariantShreddingAnalyzer.java: ########## @@ -0,0 +1,559 @@ +/* + * 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.iceberg.data; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import org.apache.hadoop.fs.Path; +import org.apache.iceberg.FileFormat; +import org.apache.iceberg.Files; +import org.apache.iceberg.InternalTestHelpers; +import org.apache.iceberg.PartitionSpec; +import org.apache.iceberg.Schema; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableProperties; +import org.apache.iceberg.TestTables; +import org.apache.iceberg.data.parquet.GenericParquetReaders; +import org.apache.iceberg.encryption.EncryptedFiles; +import org.apache.iceberg.encryption.EncryptedOutputFile; +import org.apache.iceberg.formats.FileWriterBuilder; +import org.apache.iceberg.formats.FormatModelRegistry; +import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.io.DataWriter; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.io.OutputFileFactory; +import org.apache.iceberg.parquet.Parquet; +import org.apache.iceberg.parquet.ParquetFileTestUtils; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.types.Types; +import org.apache.iceberg.variants.Variant; +import org.apache.iceberg.variants.VariantTestUtil; +import org.apache.iceberg.variants.Variants; +import org.apache.parquet.example.data.Group; +import org.apache.parquet.hadoop.ParquetFileReader; +import org.apache.parquet.hadoop.ParquetReader; +import org.apache.parquet.hadoop.example.GroupReadSupport; +import org.apache.parquet.schema.GroupType; +import org.apache.parquet.schema.MessageType; +import org.apache.parquet.schema.Type; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +public class TestRecordVariantShreddingAnalyzer { + + private static final Schema VARIANT_AFTER_ID_SCHEMA = + new Schema( + Types.NestedField.required(1, "id", Types.LongType.get()), + Types.NestedField.optional(2, "v", Types.VariantType.get())); + + private static final Schema VARIANT_BEFORE_ID_SCHEMA = + new Schema( + Types.NestedField.optional(1, "v", Types.VariantType.get()), + Types.NestedField.required(2, "id", Types.LongType.get())); + + private static final Schema MULTI_VARIANT_SCHEMA = + new Schema( + Types.NestedField.required(1, "id", Types.LongType.get()), + Types.NestedField.optional(2, "v1", Types.VariantType.get()), + Types.NestedField.optional(3, "other", Types.StringType.get()), + Types.NestedField.optional(4, "v2", Types.VariantType.get())); + + // Engine schema whose variant column is named "w" instead of "v", so the "v" column resolved + // from the Iceberg schema is not found and shredding does not activate. + private static final Schema MISMATCHED_ENGINE_SCHEMA = + new Schema( + Types.NestedField.required(1, "id", Types.LongType.get()), + Types.NestedField.optional(2, "w", Types.VariantType.get())); + + private static final int VARIANT_FIELD_ID = 2; + private static final int VARIANT_FIRST_FIELD_ID = 1; + private static final int FIRST_MULTI_VARIANT_FIELD_ID = 2; + private static final int SECOND_MULTI_VARIANT_FIELD_ID = 4; + private static final String BUFFER_SIZE = "2"; + + private Variant variant; + private List<Record> records; + + @TempDir private java.nio.file.Path temp; + + @BeforeEach + public void before() { + variant = + VariantTestUtil.variant( + ImmutableMap.of( + "a", Variants.of(42), + "b", Variants.of("hello"))); + + GenericRecord record = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + records = + ImmutableList.of( + record.copy(ImmutableMap.of("id", 1L, "v", variant)), + record.copy(ImmutableMap.of("id", 2L, "v", variant)), + record.copy(ImmutableMap.of("id", 3L, "v", variant))); + } + + @Test + public void testAnalyzeVariantColumnsUsesIcebergColumnOrder() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns(records, VARIANT_AFTER_ID_SCHEMA, VARIANT_AFTER_ID_SCHEMA); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIELD_ID); + GroupType typedValue = shreddedTypes.get(VARIANT_FIELD_ID).asGroupType(); + assertThat(typedValue.getName()).isEqualTo("typed_value"); + assertThat(typedValue.containsField("a")).isTrue(); + assertThat(typedValue.containsField("b")).isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsWhenVariantIsFirstColumn() { + GenericRecord record = GenericRecord.create(VARIANT_BEFORE_ID_SCHEMA); + List<Record> variantFirstRecords = + ImmutableList.of( + record.copy(ImmutableMap.of("v", variant, "id", 1L)), + record.copy(ImmutableMap.of("v", variant, "id", 2L))); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + variantFirstRecords, VARIANT_BEFORE_ID_SCHEMA, VARIANT_BEFORE_ID_SCHEMA); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIRST_FIELD_ID); + assertThat(shreddedTypes.get(VARIANT_FIRST_FIELD_ID).asGroupType().containsField("a")).isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsWithMultipleNonAdjacentVariants() { + GenericRecord record = GenericRecord.create(MULTI_VARIANT_SCHEMA); + List<Record> multiVariantRecords = + ImmutableList.of( + record.copy(ImmutableMap.of("id", 1L, "v1", variant, "other", "x", "v2", variant)), + record.copy(ImmutableMap.of("id", 2L, "v1", variant, "other", "y", "v2", variant))); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + multiVariantRecords, MULTI_VARIANT_SCHEMA, MULTI_VARIANT_SCHEMA); + + assertThat(shreddedTypes) + .containsOnlyKeys(FIRST_MULTI_VARIANT_FIELD_ID, SECOND_MULTI_VARIANT_FIELD_ID); + assertThat(shreddedTypes.get(FIRST_MULTI_VARIANT_FIELD_ID).asGroupType().containsField("a")) + .isTrue(); + assertThat(shreddedTypes.get(SECOND_MULTI_VARIANT_FIELD_ID).asGroupType().containsField("b")) + .isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsSkipsNullVariantValues() { + GenericRecord withVariant = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + withVariant.setField("id", 1L); + withVariant.setField("v", variant); + + GenericRecord withNullVariant = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + withNullVariant.setField("id", 2L); + withNullVariant.setField("v", null); + + GenericRecord withVariant2 = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + withVariant2.setField("id", 3L); + withVariant2.setField("v", variant); + + List<Record> recordsWithNulls = ImmutableList.of(withVariant, withNullVariant, withVariant2); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + recordsWithNulls, VARIANT_AFTER_ID_SCHEMA, VARIANT_AFTER_ID_SCHEMA); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIELD_ID); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("a")).isTrue(); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("b")).isTrue(); + } + + @Test + public void testAnalyzeVariantColumnsWithAllNullVariantValues() { + GenericRecord nullVariant1 = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + nullVariant1.setField("id", 1L); + nullVariant1.setField("v", null); + + GenericRecord nullVariant2 = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + nullVariant2.setField("id", 2L); + nullVariant2.setField("v", null); + + List<Record> allNullVariants = ImmutableList.of(nullVariant1, nullVariant2); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns( + allNullVariants, VARIANT_AFTER_ID_SCHEMA, VARIANT_AFTER_ID_SCHEMA); + + assertThat(shreddedTypes).isEmpty(); + } + + @Test + public void testAnalyzeVariantColumnsRejectsNonVariantValues() { + GenericRecord invalidRecord = GenericRecord.create(VARIANT_AFTER_ID_SCHEMA); + invalidRecord.setField("id", 1L); + invalidRecord.setField("v", "not-a-variant"); + + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + assertThatThrownBy( + () -> + analyzer.analyzeVariantColumns( + ImmutableList.of(invalidRecord), + VARIANT_AFTER_ID_SCHEMA, + VARIANT_AFTER_ID_SCHEMA)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Expected Variant at index 1 but was: java.lang.String"); + } + + @Test + public void testAnalyzeVariantColumnsFallsBackToIcebergSchemaWhenEngineSchemaNull() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns(records, VARIANT_AFTER_ID_SCHEMA, null); + + assertThat(shreddedTypes).containsOnlyKeys(VARIANT_FIELD_ID); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("a")).isTrue(); + assertThat(shreddedTypes.get(VARIANT_FIELD_ID).asGroupType().containsField("b")).isTrue(); + } + + @Test + public void testResolveColumnIndexRejectsNullEngineSchema() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + assertThatThrownBy(() -> analyzer.resolveColumnIndex(null, "v")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid engine schema: null"); + } + + @Test + public void testAnalyzeVariantColumnsSkipsColumnMissingFromEngineSchema() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + Map<Integer, Type> shreddedTypes = + analyzer.analyzeVariantColumns(records, VARIANT_AFTER_ID_SCHEMA, MISMATCHED_ENGINE_SCHEMA); + + assertThat(shreddedTypes).isEmpty(); + } + + @Test + public void testResolveColumnIndexResolvesPositionsAndReportsMisses() { + RecordVariantShreddingAnalyzer analyzer = new RecordVariantShreddingAnalyzer(); + + assertThat(analyzer.resolveColumnIndex(VARIANT_AFTER_ID_SCHEMA, "id")).isEqualTo(0); + assertThat(analyzer.resolveColumnIndex(VARIANT_AFTER_ID_SCHEMA, "v")).isEqualTo(1); + assertThat(analyzer.resolveColumnIndex(VARIANT_BEFORE_ID_SCHEMA, "v")).isEqualTo(0); + assertThat(analyzer.resolveColumnIndex(VARIANT_AFTER_ID_SCHEMA, "missing")).isEqualTo(-1); + } + + @Test + public void testGenericFileWriterFactoryShreddingRoundTrip() throws IOException { + Table table = + TestTables.create( + temp.resolve("table").toFile(), + "variant", + VARIANT_AFTER_ID_SCHEMA, + PartitionSpec.unpartitioned(), + 3); + try { + GenericFileWriterFactory writerFactory = + new GenericFileWriterFactory.Builder(table) + .dataFileFormat(FileFormat.PARQUET) + .dataSchema(VARIANT_AFTER_ID_SCHEMA) + .writerProperties( + ImmutableMap.of( + TableProperties.PARQUET_SHRED_VARIANTS, + "true", + TableProperties.PARQUET_VARIANT_BUFFER_SIZE, + BUFFER_SIZE)) + .build(); + + OutputFileFactory fileFactory = + OutputFileFactory.builderFor(table, 1, 1).format(FileFormat.PARQUET).build(); + EncryptedOutputFile encryptedOutputFile = fileFactory.newOutputFile(); + + // GenericFileWriterFactory does not forward an inputSchema, so engineSchema is null and the + // analyzer falls back to the Iceberg schema to resolve variant columns. + try (DataWriter<Record> writer = + writerFactory.newDataWriter(encryptedOutputFile, table.spec(), null)) { + for (Record rec : records) { + writer.write(rec); + } + } + + OutputFile outputFile = encryptedOutputFile.encryptingOutputFile(); + try (ParquetFileReader reader = + ParquetFileReader.open(ParquetFileTestUtils.file(outputFile.toInputFile()))) { + assertShreddedVariantParquetSchema(reader.getFooter().getFileMetaData().getSchema()); + } + + assertAllRawParquetRowsShredded(outputFile); + assertRecordsRoundTrip(outputFile, records); + } finally { + TestTables.clearTables(); + } + } + + @Test + public void testFormatModelRegistryShreddingRoundTrip() throws IOException { + OutputFile outputFile = Files.localOutput(temp.resolve("variant-shredded.parquet").toFile()); + EncryptedOutputFile encryptedOutputFile = EncryptedFiles.plainAsEncryptedOutput(outputFile); + + FileWriterBuilder<DataWriter<Record>, Schema> writeBuilder = + FormatModelRegistry.dataWriteBuilder(FileFormat.PARQUET, Record.class, encryptedOutputFile); + + try (DataWriter<Record> writer = + writeBuilder + .schema(VARIANT_AFTER_ID_SCHEMA) + .spec(PartitionSpec.unpartitioned()) + .setAll( + ImmutableMap.of( + TableProperties.PARQUET_SHRED_VARIANTS, + "true", + TableProperties.PARQUET_VARIANT_BUFFER_SIZE, + BUFFER_SIZE)) + .build()) { + for (Record rec : records) { + writer.write(rec); + } + } + + try (ParquetFileReader reader = + ParquetFileReader.open(ParquetFileTestUtils.file(outputFile.toInputFile()))) { + assertShreddedVariantParquetSchema(reader.getFooter().getFileMetaData().getSchema()); + } + + assertAllRawParquetRowsShredded(outputFile); + assertRecordsRoundTrip(outputFile, records); + } + + @Test + public void testExplicitNullEngineSchemaStillDerivesAndShreds() throws IOException { Review Comment: This one can't fail. The comment says passing null explicitly behaves like not calling `engineSchema` at all, and that's true — but it's true because both leave the field null and the fallback keys off null, so the test would still pass if the builder started tracking explicit-null separately, which is the thing it's meant to protect against. `testAnalyzeVariantColumnsFallsBackToIcebergSchemaWhenEngineSchemaNull` already proves the fallback shreds; if this test is meant to add something, assert on a property only the null path produces rather than that shredding happened at all — otherwise it's covered and could go. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
