This is an automated email from the ASF dual-hosted git repository.

huaxingao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg.git


The following commit(s) were added to refs/heads/main by this push:
     new 9d07de85da Arrow: Read projected shredded variants in vectorized 
Parquet reads (#18851)
9d07de85da is described below

commit 9d07de85da864e1dfc91b64f98438c52d885b704
Author: Neelesh Salian <[email protected]>
AuthorDate: Mon Nov 16 15:48:23 2026 -0800

    Arrow: Read projected shredded variants in vectorized Parquet reads (#18851)
    
    * Arrow: Read projected shredded variants in vectorized Parquet reads
    
    * skip shredded variants in lists and maps, test a required variant
    
    * PR review fixes: test multiple row groups, note unreachable typed_value 
throws
---
 .../arrow/vectorized/VectorizedArrowReader.java    | 122 ++++++++++++
 .../arrow/vectorized/VectorizedReaderBuilder.java  |  36 +++-
 .../arrow/vectorized/VectorizedVariantVisitor.java |   3 +-
 .../vectorized/TestVectorizedArrowReader.java      | 146 ++++++++++++++
 .../vectorized/TestVectorizedReaderBuilder.java    |  69 +++++--
 .../iceberg/spark/sql/TestSparkVariantRead.java    | 211 ++++++++++++++++++---
 .../iceberg/spark/sql/TestSparkVariantRead.java    | 211 ++++++++++++++++++---
 .../iceberg/spark/sql/TestSparkVariantRead.java    | 211 ++++++++++++++++++---
 8 files changed, 930 insertions(+), 79 deletions(-)

diff --git 
a/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedArrowReader.java
 
b/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedArrowReader.java
index fa8ec02224..c51480ba40 100644
--- 
a/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedArrowReader.java
+++ 
b/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedArrowReader.java
@@ -18,6 +18,8 @@
  */
 package org.apache.iceberg.arrow.vectorized;
 
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
 import java.util.Map;
 import java.util.Optional;
 import org.apache.arrow.memory.ArrowBuf;
@@ -36,6 +38,7 @@ import org.apache.arrow.vector.TimeStampMicroTZVector;
 import org.apache.arrow.vector.TimeStampMicroVector;
 import org.apache.arrow.vector.TimeStampNanoTZVector;
 import org.apache.arrow.vector.TimeStampNanoVector;
+import org.apache.arrow.vector.VarBinaryVector;
 import org.apache.arrow.vector.types.FloatingPointPrecision;
 import org.apache.arrow.vector.types.pojo.ArrowType;
 import org.apache.arrow.vector.types.pojo.Field;
@@ -45,9 +48,11 @@ import org.apache.iceberg.arrow.ArrowAllocation;
 import org.apache.iceberg.arrow.ArrowSchemaUtil;
 import org.apache.iceberg.arrow.vectorized.parquet.VectorizedColumnIterator;
 import org.apache.iceberg.parquet.ParquetUtil;
+import org.apache.iceberg.parquet.ParquetValueReader;
 import org.apache.iceberg.parquet.VectorizedReader;
 import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
 import org.apache.iceberg.types.Types;
+import org.apache.iceberg.variants.Variant;
 import org.apache.parquet.column.ColumnDescriptor;
 import org.apache.parquet.column.Dictionary;
 import org.apache.parquet.column.page.PageReadStore;
@@ -1093,4 +1098,121 @@ public class VectorizedArrowReader implements 
VectorizedReader<VectorHolder> {
       return "VectorizedVariantReader";
     }
   }
+
+  static final class RowBasedVariantReader extends VectorizedArrowReader {
+    private static final Types.NestedField METADATA_FIELD =
+        Types.NestedField.required(
+            VectorizedVariantVisitor.UNUSED_FIELD_ID, "metadata", 
Types.BinaryType.get());
+    private static final Types.NestedField VALUE_FIELD =
+        Types.NestedField.optional(
+            VectorizedVariantVisitor.UNUSED_FIELD_ID, "value", 
Types.BinaryType.get());
+
+    private final ParquetValueReader<Variant> reader;
+    private final BufferAllocator allocator;
+    private int batchSize = DEFAULT_BATCH_SIZE;
+    private VarBinaryVector metadataVector;
+    private VarBinaryVector valueVector;
+    private NullabilityHolder nulls;
+    private ByteBuffer metadataBuffer = 
ByteBuffer.allocate(0).order(ByteOrder.LITTLE_ENDIAN);
+    private ByteBuffer valueBuffer = 
ByteBuffer.allocate(0).order(ByteOrder.LITTLE_ENDIAN);
+
+    RowBasedVariantReader(
+        Types.NestedField icebergField,
+        ParquetValueReader<Variant> reader,
+        BufferAllocator allocator) {
+      super(icebergField);
+      this.reader = reader;
+      this.allocator = allocator;
+    }
+
+    @Override
+    public VectorHolder read(VectorHolder reuse, int numValsToRead) {
+      if (metadataVector == null) {
+        this.metadataVector = newVector(icebergField().name() + ".metadata");
+        this.valueVector = newVector(icebergField().name() + ".value");
+      } else {
+        metadataVector.setValueCount(0);
+        valueVector.setValueCount(0);
+      }
+
+      if (nulls == null || nulls.size() < numValsToRead) {
+        this.nulls = new NullabilityHolder(Math.max(batchSize, numValsToRead));
+      } else {
+        nulls.reset();
+      }
+
+      for (int i = 0; i < numValsToRead; i += 1) {
+        Variant variant = reader.read(null);
+        if (variant == null) {
+          metadataVector.setNull(i);
+          valueVector.setNull(i);
+          nulls.setNull(i);
+        } else {
+          int metadataSize = variant.metadata().sizeInBytes();
+          this.metadataBuffer = ensureCapacity(metadataBuffer, metadataSize);
+          variant.metadata().writeTo(metadataBuffer, 0);
+          metadataVector.setSafe(i, metadataBuffer.array(), 0, metadataSize);
+
+          int valueSize = variant.value().sizeInBytes();
+          this.valueBuffer = ensureCapacity(valueBuffer, valueSize);
+          variant.value().writeTo(valueBuffer, 0);
+          valueVector.setSafe(i, valueBuffer.array(), 0, valueSize);
+
+          nulls.setNotNull(i);
+        }
+      }
+
+      metadataVector.setValueCount(numValsToRead);
+      valueVector.setValueCount(numValsToRead);
+
+      return new VectorHolder.VariantVectorHolder(
+          icebergField(),
+          numValsToRead,
+          VectorHolder.vectorHolder(metadataVector, METADATA_FIELD, nulls),
+          VectorHolder.vectorHolder(valueVector, VALUE_FIELD, nulls));
+    }
+
+    private static ByteBuffer ensureCapacity(ByteBuffer buffer, int size) {
+      if (buffer.capacity() >= size) {
+        return buffer;
+      }
+
+      return ByteBuffer.allocate(Math.max(size, 2 * buffer.capacity()))
+          .order(ByteOrder.LITTLE_ENDIAN);
+    }
+
+    private VarBinaryVector newVector(String name) {
+      VarBinaryVector vector = new VarBinaryVector(name, allocator);
+      vector.setInitialCapacity(batchSize * 
AVERAGE_VARIABLE_WIDTH_RECORD_SIZE);
+      vector.allocateNewSafe();
+      return vector;
+    }
+
+    @Override
+    public void setRowGroupInfo(
+        PageReadStore source, Map<ColumnPath, ColumnChunkMetaData> metadata) {
+      reader.setPageSource(source);
+    }
+
+    @Override
+    public void setBatchSize(int batchSize) {
+      this.batchSize = (batchSize == 0) ? DEFAULT_BATCH_SIZE : batchSize;
+    }
+
+    @Override
+    public void close() {
+      if (metadataVector != null) {
+        metadataVector.close();
+      }
+
+      if (valueVector != null) {
+        valueVector.close();
+      }
+    }
+
+    @Override
+    public String toString() {
+      return "RowBasedVariantReader";
+    }
+  }
 }
diff --git 
a/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedReaderBuilder.java
 
b/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedReaderBuilder.java
index 12b741135c..ef6f84dced 100644
--- 
a/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedReaderBuilder.java
+++ 
b/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedReaderBuilder.java
@@ -18,6 +18,7 @@
  */
 package org.apache.iceberg.arrow.vectorized;
 
+import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 import java.util.function.BiFunction;
@@ -27,13 +28,17 @@ import org.apache.arrow.memory.BufferAllocator;
 import org.apache.iceberg.Schema;
 import org.apache.iceberg.arrow.ArrowAllocation;
 import 
org.apache.iceberg.arrow.vectorized.VectorizedArrowReader.ConstantVectorReader;
+import org.apache.iceberg.parquet.ParquetValueReader;
+import org.apache.iceberg.parquet.ParquetValueReaders;
 import org.apache.iceberg.parquet.ParquetVariantVisitor;
 import org.apache.iceberg.parquet.TypeWithSchemaVisitor;
+import org.apache.iceberg.parquet.VariantReaderBuilder;
 import org.apache.iceberg.parquet.VectorizedReader;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
 import org.apache.iceberg.relocated.com.google.common.collect.Lists;
 import org.apache.iceberg.relocated.com.google.common.collect.Maps;
 import org.apache.iceberg.types.Types;
+import org.apache.iceberg.variants.Variant;
 import org.apache.parquet.column.ColumnDescriptor;
 import org.apache.parquet.schema.GroupType;
 import org.apache.parquet.schema.MessageType;
@@ -41,6 +46,8 @@ import org.apache.parquet.schema.PrimitiveType;
 import org.apache.parquet.schema.Type;
 
 public class VectorizedReaderBuilder extends 
TypeWithSchemaVisitor<VectorizedReader<?>> {
+  private static final String TYPED_VALUE = "typed_value";
+
   private final MessageType parquetSchema;
   private final Schema icebergSchema;
   private final BufferAllocator rootAllocator;
@@ -163,14 +170,41 @@ public class VectorizedReaderBuilder extends 
TypeWithSchemaVisitor<VectorizedRea
       return null;
     }
 
+    if (isShredded(variant.asGroupType())) {
+      // shredded variants are read by the row-based reader built in variant()
+      return null;
+    }
+
     return new VectorizedVariantVisitor(
         currentPath(), parquetSchema, icebergSchema, rootAllocator, 
setArrowValidityVector);
   }
 
   @Override
+  @SuppressWarnings("unchecked")
   public VectorizedReader<?> variant(
       Types.VariantType iVariant, GroupType variant, VectorizedReader<?> 
result) {
-    return result;
+    // variants inside lists and maps are not read vectorized, like primitive()
+    if (iVariant == null
+        || parquetSchema.getMaxRepetitionLevel(currentPath()) > 0
+        || !isShredded(variant)) {
+      return result;
+    }
+
+    String[] path = currentPath();
+    ParquetValueReader<Variant> reader =
+        (ParquetValueReader<Variant>)
+            ParquetVariantVisitor.visit(
+                variant, new VariantReaderBuilder(parquetSchema, 
Arrays.asList(path)));
+    int definitionLevel = parquetSchema.getMaxDefinitionLevel(path) - 1;
+
+    return new VectorizedArrowReader.RowBasedVariantReader(
+        icebergSchema.findField(variant.getId().intValue()),
+        ParquetValueReaders.option(variant, definitionLevel, reader),
+        rootAllocator);
+  }
+
+  private static boolean isShredded(GroupType variant) {
+    return variant.containsField(TYPED_VALUE);
   }
 
   @Override
diff --git 
a/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedVariantVisitor.java
 
b/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedVariantVisitor.java
index abcae78a55..f7bab10af6 100644
--- 
a/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedVariantVisitor.java
+++ 
b/arrow/src/main/java/org/apache/iceberg/arrow/vectorized/VectorizedVariantVisitor.java
@@ -32,7 +32,7 @@ import org.apache.parquet.schema.PrimitiveType;
 
 /** Creates Arrow readers for a variant column's metadata and value leaves. */
 class VectorizedVariantVisitor extends 
ParquetVariantVisitor<VectorizedReader<?>> {
-  private static final int UNUSED_FIELD_ID = -1;
+  static final int UNUSED_FIELD_ID = -1;
 
   private final String[] variantGroupPath;
   private final MessageType parquetSchema;
@@ -92,6 +92,7 @@ class VectorizedVariantVisitor extends 
ParquetVariantVisitor<VectorizedReader<?>
     return null;
   }
 
+  // the typed_value throws below are not reached; shredded variants use 
RowBasedVariantReader
   @Override
   public VectorizedReader<?> primitive(PrimitiveType primitive) {
     throw new UnsupportedOperationException("Unsupported variant: shredded 
typed_value primitive");
diff --git 
a/arrow/src/test/java/org/apache/iceberg/arrow/vectorized/TestVectorizedArrowReader.java
 
b/arrow/src/test/java/org/apache/iceberg/arrow/vectorized/TestVectorizedArrowReader.java
index 9f76bfb644..e94d27ee92 100644
--- 
a/arrow/src/test/java/org/apache/iceberg/arrow/vectorized/TestVectorizedArrowReader.java
+++ 
b/arrow/src/test/java/org/apache/iceberg/arrow/vectorized/TestVectorizedArrowReader.java
@@ -19,9 +19,23 @@
 package org.apache.iceberg.arrow.vectorized;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
 import org.apache.arrow.vector.BigIntVector;
+import org.apache.arrow.vector.VarBinaryVector;
 import org.apache.iceberg.arrow.ArrowAllocation;
+import org.apache.iceberg.parquet.ParquetValueReader;
+import org.apache.iceberg.types.Types.BinaryType;
+import org.apache.iceberg.types.Types.NestedField;
+import org.apache.iceberg.types.Types.VariantType;
+import org.apache.iceberg.variants.Variant;
+import org.apache.iceberg.variants.VariantMetadata;
+import org.apache.iceberg.variants.VariantValue;
+import org.apache.iceberg.variants.Variants;
 import org.junit.jupiter.api.Test;
 
 class TestVectorizedArrowReader {
@@ -220,4 +234,136 @@ class TestVectorizedArrowReader {
 
     
assertThat(ArrowAllocation.rootAllocator().getAllocatedMemory()).isEqualTo(allocatedBefore);
   }
+
+  @Test
+  void rowBasedVariantReaderTracksNullsAcrossReusedBatches() {
+    long allocatedBefore = 
ArrowAllocation.rootAllocator().getAllocatedMemory();
+
+    Variant first = Variant.of(Variants.metadata("a"), Variants.of(1));
+    Variant second = Variant.of(Variants.metadata(), Variants.of("x"));
+    VectorizedArrowReader reader =
+        new VectorizedArrowReader.RowBasedVariantReader(
+            NestedField.optional(2, "data", VariantType.get()),
+            variantReader(null, first, second, null, first),
+            ArrowAllocation.rootAllocator());
+    reader.setBatchSize(2);
+
+    VectorHolder holder = reader.read(null, 2);
+    assertVariants(holder, null, first);
+    VarBinaryVector metadataVector =
+        (VarBinaryVector) ((VectorHolder.VariantVectorHolder) 
holder).metadataHolder().vector();
+    VarBinaryVector valueVector =
+        (VarBinaryVector) ((VectorHolder.VariantVectorHolder) 
holder).valueHolder().vector();
+
+    // a reused batch must overwrite every row's nullability, not keep the 
previous batch's
+    holder = reader.read(holder, 2);
+    assertVariants(holder, second, null);
+    assertThat(((VectorHolder.VariantVectorHolder) 
holder).metadataHolder().vector())
+        .as("reuse must not allocate a new vector")
+        .isSameAs(metadataVector);
+    assertThat(((VectorHolder.VariantVectorHolder) 
holder).valueHolder().vector())
+        .as("reuse must not allocate a new vector")
+        .isSameAs(valueVector);
+
+    // the last batch of a row group is usually shorter than the batch size
+    holder = reader.read(holder, 1);
+    assertVariants(holder, first);
+
+    reader.close();
+
+    
assertThat(ArrowAllocation.rootAllocator().getAllocatedMemory()).isEqualTo(allocatedBefore);
+  }
+
+  @Test
+  void rowBasedVariantReaderGrowsNullsForLargerRead() {
+    long allocatedBefore = 
ArrowAllocation.rootAllocator().getAllocatedMemory();
+
+    Variant value = Variant.of(Variants.metadata(), Variants.of(1));
+    VectorizedArrowReader reader =
+        new VectorizedArrowReader.RowBasedVariantReader(
+            NestedField.optional(2, "data", VariantType.get()),
+            variantReader(value, value, null, value, null),
+            ArrowAllocation.rootAllocator());
+    reader.setBatchSize(2);
+
+    VectorHolder holder = reader.read(null, 2);
+    assertVariants(holder, value, value);
+    holder = reader.read(holder, 3);
+    assertVariants(holder, null, value, null);
+
+    reader.close();
+
+    
assertThat(ArrowAllocation.rootAllocator().getAllocatedMemory()).isEqualTo(allocatedBefore);
+  }
+
+  @Test
+  void rowBasedVariantReaderResolvesZeroBatchSizeToTheDefault() {
+    long allocatedBefore = 
ArrowAllocation.rootAllocator().getAllocatedMemory();
+
+    VectorizedArrowReader reader =
+        new VectorizedArrowReader.RowBasedVariantReader(
+            NestedField.optional(2, "data", VariantType.get()),
+            variantReader(null),
+            ArrowAllocation.rootAllocator());
+    reader.setBatchSize(0);
+
+    VectorHolder.VariantVectorHolder holder =
+        (VectorHolder.VariantVectorHolder) reader.read(null, 1);
+    assertThat(holder.metadataHolder().nullabilityHolder().size())
+        .isEqualTo(VectorizedArrowReader.DEFAULT_BATCH_SIZE);
+
+    reader.close();
+
+    
assertThat(ArrowAllocation.rootAllocator().getAllocatedMemory()).isEqualTo(allocatedBefore);
+  }
+
+  private static void assertVariants(VectorHolder holder, Variant... expected) 
{
+    assertThat(holder).isInstanceOf(VectorHolder.VariantVectorHolder.class);
+    VectorHolder.VariantVectorHolder variantHolder = 
(VectorHolder.VariantVectorHolder) holder;
+    VectorHolder metadataHolder = variantHolder.metadataHolder();
+    VectorHolder valueHolder = variantHolder.valueHolder();
+    
assertThat(metadataHolder.icebergField().type()).isEqualTo(BinaryType.get());
+    assertThat(valueHolder.icebergField().type()).isEqualTo(BinaryType.get());
+    VarBinaryVector metadataVector = (VarBinaryVector) metadataHolder.vector();
+    VarBinaryVector valueVector = (VarBinaryVector) valueHolder.vector();
+
+    assertThat(variantHolder.numValues()).isEqualTo(expected.length);
+    assertThat(metadataVector.getValueCount()).isEqualTo(expected.length);
+    assertThat(valueVector.getValueCount()).isEqualTo(expected.length);
+    int expectedNulls = 0;
+    for (int i = 0; i < expected.length; i += 1) {
+      if (expected[i] == null) {
+        expectedNulls += 1;
+        
assertThat(metadataHolder.nullabilityHolder().isNullAt(i)).isEqualTo((byte) 1);
+        
assertThat(valueHolder.nullabilityHolder().isNullAt(i)).isEqualTo((byte) 1);
+      } else {
+        
assertThat(metadataHolder.nullabilityHolder().isNullAt(i)).isEqualTo((byte) 0);
+        
assertThat(valueHolder.nullabilityHolder().isNullAt(i)).isEqualTo((byte) 0);
+        
assertThat(metadataVector.get(i)).isEqualTo(serialize(expected[i].metadata()));
+        
assertThat(valueVector.get(i)).isEqualTo(serialize(expected[i].value()));
+      }
+    }
+
+    
assertThat(metadataHolder.nullabilityHolder().numNulls()).isEqualTo(expectedNulls);
+    
assertThat(valueHolder.nullabilityHolder().numNulls()).isEqualTo(expectedNulls);
+  }
+
+  private static byte[] serialize(VariantMetadata metadata) {
+    byte[] bytes = new byte[metadata.sizeInBytes()];
+    metadata.writeTo(ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN), 0);
+    return bytes;
+  }
+
+  private static byte[] serialize(VariantValue value) {
+    byte[] bytes = new byte[value.sizeInBytes()];
+    value.writeTo(ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN), 0);
+    return bytes;
+  }
+
+  @SuppressWarnings("unchecked")
+  private static ParquetValueReader<Variant> variantReader(Variant first, 
Variant... rest) {
+    ParquetValueReader<Variant> reader = mock(ParquetValueReader.class);
+    when(reader.read(any())).thenReturn(first, rest);
+    return reader;
+  }
 }
diff --git 
a/arrow/src/test/java/org/apache/iceberg/arrow/vectorized/TestVectorizedReaderBuilder.java
 
b/arrow/src/test/java/org/apache/iceberg/arrow/vectorized/TestVectorizedReaderBuilder.java
index a0ffda3f21..3b0d914fe9 100644
--- 
a/arrow/src/test/java/org/apache/iceberg/arrow/vectorized/TestVectorizedReaderBuilder.java
+++ 
b/arrow/src/test/java/org/apache/iceberg/arrow/vectorized/TestVectorizedReaderBuilder.java
@@ -18,14 +18,18 @@
  */
 package org.apache.iceberg.arrow.vectorized;
 
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatNoException;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
+import java.util.List;
 import java.util.stream.Stream;
 import org.apache.iceberg.Schema;
 import org.apache.iceberg.parquet.TypeWithSchemaVisitor;
+import org.apache.iceberg.parquet.VectorizedReader;
 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.IntegerType;
+import org.apache.iceberg.types.Types.ListType;
 import org.apache.iceberg.types.Types.NestedField;
 import org.apache.iceberg.types.Types.VariantType;
 import org.apache.iceberg.variants.Variant;
@@ -53,11 +57,12 @@ public class TestVectorizedReaderBuilder {
 
     VectorizedReaderBuilder builder =
         new VectorizedReaderBuilder(
-            icebergSchema, parquetSchema, false, ImmutableMap.of(), readers -> 
null);
+            icebergSchema, parquetSchema, false, ImmutableMap.of(), readers -> 
readers.get(1));
 
-    assertThatNoException()
-        .isThrownBy(
-            () -> TypeWithSchemaVisitor.visit(icebergSchema.asStruct(), 
parquetSchema, builder));
+    VectorizedReader<?> reader =
+        TypeWithSchemaVisitor.visit(icebergSchema.asStruct(), parquetSchema, 
builder);
+
+    
assertThat(reader).isInstanceOf(VectorizedArrowReader.VectorizedVariantReader.class);
   }
 
   @Test
@@ -156,7 +161,7 @@ public class TestVectorizedReaderBuilder {
   }
 
   @Test
-  void projectingShreddedVariantUnsupported() {
+  void projectedShreddedVariantUsesRowBasedReader() {
     Schema icebergSchema =
         new Schema(
             NestedField.required(1, "id", IntegerType.get()),
@@ -173,12 +178,54 @@ public class TestVectorizedReaderBuilder {
 
     VectorizedReaderBuilder builder =
         new VectorizedReaderBuilder(
-            icebergSchema, parquetSchema, false, ImmutableMap.of(), readers -> 
null);
+            icebergSchema, parquetSchema, false, ImmutableMap.of(), readers -> 
readers.get(1));
+
+    VectorizedReader<?> reader =
+        TypeWithSchemaVisitor.visit(icebergSchema.asStruct(), parquetSchema, 
builder);
+
+    
assertThat(reader).isInstanceOf(VectorizedArrowReader.RowBasedVariantReader.class);
+  }
+
+  @Test
+  void projectedShreddedListElementSkipped() {
+    Schema icebergSchema =
+        new Schema(
+            NestedField.required(1, "id", IntegerType.get()),
+            NestedField.optional(2, "list", ListType.ofOptional(3, 
VariantType.get())));
+
+    MessageType parquetSchema =
+        Types.buildMessage()
+            .addField(
+                Types.primitive(PrimitiveTypeName.INT32, 
Type.Repetition.REQUIRED)
+                    .id(1)
+                    .named("id"))
+            .addField(
+                Types.buildGroup(Type.Repetition.OPTIONAL)
+                    .as(LogicalTypeAnnotation.listType())
+                    .addField(
+                        Types.buildGroup(Type.Repetition.REPEATED)
+                            
.addField(shreddedVariant(Type.Repetition.OPTIONAL, 3, "element"))
+                            .named("list"))
+                    .id(2)
+                    .named("list"))
+            .named("table");
+
+    List<VectorizedReader<?>> variantReaders = Lists.newArrayList();
+    VectorizedReaderBuilder builder =
+        new VectorizedReaderBuilder(
+            icebergSchema, parquetSchema, false, ImmutableMap.of(), readers -> 
null) {
+          @Override
+          public VectorizedReader<?> variant(
+              VariantType iVariant, GroupType variant, VectorizedReader<?> 
result) {
+            VectorizedReader<?> reader = super.variant(iVariant, variant, 
result);
+            variantReaders.add(reader);
+            return reader;
+          }
+        };
+
+    TypeWithSchemaVisitor.visit(icebergSchema.asStruct(), parquetSchema, 
builder);
 
-    assertThatThrownBy(
-            () -> TypeWithSchemaVisitor.visit(icebergSchema.asStruct(), 
parquetSchema, builder))
-        .isInstanceOf(UnsupportedOperationException.class)
-        .hasMessage("Unsupported variant: shredded typed_value primitive");
+    assertThat(variantReaders).hasSize(1).containsOnlyNulls();
   }
 
   private static MessageType parquetSchemaWithVariant() {
diff --git 
a/spark/v4.0/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
 
b/spark/v4.0/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
index a73fba48b9..92915f56bb 100644
--- 
a/spark/v4.0/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
+++ 
b/spark/v4.0/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
@@ -22,6 +22,7 @@ import static org.assertj.core.api.Assertions.assertThat;
 
 import java.io.File;
 import java.io.IOException;
+import java.util.Comparator;
 import java.util.List;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.Path;
@@ -31,16 +32,20 @@ import org.apache.iceberg.FileScanTask;
 import org.apache.iceberg.Files;
 import org.apache.iceberg.SnapshotChanges;
 import org.apache.iceberg.Table;
+import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.data.FileHelpers;
 import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
 import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
 import org.apache.iceberg.relocated.com.google.common.collect.Lists;
 import org.apache.iceberg.spark.Spark3Util;
 import org.apache.iceberg.spark.SparkCatalog;
+import org.apache.iceberg.spark.SparkSQLProperties;
 import org.apache.iceberg.spark.TestBase;
 import org.apache.iceberg.util.CharSequenceSet;
 import org.apache.iceberg.util.Pair;
 import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
 import org.apache.parquet.hadoop.util.HadoopInputFile;
 import org.apache.spark.sql.Dataset;
 import org.apache.spark.sql.Row;
@@ -53,6 +58,7 @@ import org.apache.spark.unsafe.types.VariantVal;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.ValueSource;
 import scala.collection.JavaConverters;
@@ -498,16 +504,7 @@ public class TestSparkVariantRead extends TestBase {
         executeAndKeepPlan(
             () -> 
rows.addAll(spark.table(shreddedTable).select("id").collectAsList()));
     assertThat(rows).extracting(r -> 
r.getLong(0)).containsExactlyInAnyOrder(1L, 2L);
-
-    List<SparkPlan> leaves = 
JavaConverters.seqAsJavaList(plan.collectLeaves());
-    assertThat(leaves)
-        .singleElement()
-        .isInstanceOfSatisfying(
-            BatchScanExec.class,
-            scan ->
-                assertThat(scan.supportsColumnar())
-                    .as("Scan should be columnar only when vectorization is 
enabled")
-                    .isEqualTo(vectorized));
+    assertColumnarScan(plan, vectorized);
 
     sql("DROP TABLE IF EXISTS %s", shreddedTable);
   }
@@ -557,6 +554,100 @@ public class TestSparkVariantRead extends TestBase {
     sql("DROP TABLE IF EXISTS %s", noStatsTable);
   }
 
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void readShreddedArrayEnabledBySessionConf(boolean required)
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_shredded_array";
+    sql("DROP TABLE IF EXISTS %s", table);
+    sql(
+        "CREATE TABLE %s (id BIGINT, %s) USING iceberg TBLPROPERTIES 
('format-version'='3')",
+        table, required ? "v VARIANT NOT NULL" : "v VARIANT");
+    insertShredded(
+        "INSERT INTO %s VALUES (1, parse_json('{\"a\": [1, 2]}')), (2, 
parse_json('{\"a\": [3]}'))",
+        table);
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    
assertThat(icebergTable.schema().findField("v").isRequired()).isEqualTo(required);
+    assertHasTypedValueSubtree(icebergTable);
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(1L, 2L);
+    assertLongArray(toVariant(rows.get(0)).getFieldByKey("a"), 1L, 2L);
+    assertLongArray(toVariant(rows.get(1)).getFieldByKey("a"), 3L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
+  @Test
+  void readMixedShreddedAndUnshreddedFiles()
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_mixed_files";
+    sql("DROP TABLE IF EXISTS %s", table);
+    sql(
+        "CREATE TABLE %s (id BIGINT, v VARIANT) USING iceberg "
+            + "TBLPROPERTIES ('format-version'='3')",
+        table);
+    spark
+        .sql("SELECT 1L AS id, parse_json('{\"name\":\"alice\",\"age\":30}') 
AS v")
+        .coalesce(1)
+        .writeTo(table)
+        .append();
+    insertShredded(
+        "INSERT INTO %s SELECT /*+ COALESCE(1) */ * FROM ("
+            + "SELECT 2L AS id, CAST(NULL AS VARIANT) AS v "
+            + "UNION ALL SELECT 3L, parse_json('{\"a\":[1,2]}') "
+            + "UNION ALL SELECT 4L, parse_json('{\"a\":[3]}'))",
+        table);
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    assertThat(shreddedFiles(icebergTable)).containsExactlyInAnyOrder(false, 
true);
+    sql("ALTER TABLE %s SET TBLPROPERTIES 
('read.parquet.vectorization.batch-size'='2')", table);
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(1L, 2L, 
3L, 4L);
+    
assertThat(toVariant(rows.get(0)).getFieldByKey("name").getString()).isEqualTo("alice");
+    assertThat(rows.get(1).isNullAt(1)).isTrue();
+    assertLongArray(toVariant(rows.get(2)).getFieldByKey("a"), 1L, 2L);
+    assertLongArray(toVariant(rows.get(3)).getFieldByKey("a"), 3L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
+  @Test
+  void readShreddedVariantAcrossRowGroups()
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_shredded_row_groups";
+    sql("DROP TABLE IF EXISTS %s", table);
+    sql(
+        "CREATE TABLE %s (id BIGINT, v VARIANT) USING iceberg "
+            + "TBLPROPERTIES ('format-version'='3', '%s'='1', '%s'='1', 
'%s'='1')",
+        table,
+        TableProperties.PARQUET_ROW_GROUP_SIZE_BYTES,
+        TableProperties.PARQUET_ROW_GROUP_CHECK_MIN_RECORD_COUNT,
+        TableProperties.PARQUET_ROW_GROUP_CHECK_MAX_RECORD_COUNT);
+    insertShredded(
+        "INSERT INTO %s SELECT /*+ COALESCE(1) */ * FROM ("
+            + "SELECT 1L AS id, CAST(NULL AS VARIANT) AS v "
+            + "UNION ALL SELECT 2L, parse_json('{\"a\":[1,2]}') "
+            + "UNION ALL SELECT 3L, parse_json('{\"a\":[3]}'))",
+        table);
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    assertHasTypedValueSubtree(icebergTable);
+    assertThat(footers(icebergTable))
+        .singleElement()
+        .satisfies(footer -> 
assertThat(footer.getBlocks()).hasSizeGreaterThan(1));
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(1L, 2L, 
3L);
+    assertThat(rows.get(0).isNullAt(1)).isTrue();
+    assertLongArray(toVariant(rows.get(1)).getFieldByKey("a"), 1L, 2L);
+    assertLongArray(toVariant(rows.get(2)).getFieldByKey("a"), 3L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
   private void setVectorization(boolean on) {
     sql(
         "ALTER TABLE %s SET TBLPROPERTIES 
('read.parquet.vectorization.enabled'='%s')",
@@ -570,18 +661,10 @@ public class TestSparkVariantRead extends TestBase {
   }
 
   private static void assertHasTypedValueSubtree(Table table) throws 
IOException {
-    try (CloseableIterable<FileScanTask> tasks = table.newScan().planFiles()) {
-      assertThat(tasks).isNotEmpty();
-      for (FileScanTask task : tasks) {
-        HadoopInputFile inputFile =
-            HadoopInputFile.fromPath(new Path(task.file().location()), new 
Configuration());
-        try (ParquetFileReader reader = ParquetFileReader.open(inputFile)) {
-          assertThat(containsTypedValue(reader.getFileMetaData().getSchema()))
-              .as("Expected variant column to be shredded with a typed_value 
subtree")
-              .isTrue();
-        }
-      }
-    }
+    assertThat(shreddedFiles(table))
+        .as("Expected variant column to be shredded with a typed_value 
subtree")
+        .isNotEmpty()
+        .containsOnly(true);
   }
 
   private static boolean containsTypedValue(org.apache.parquet.schema.Type 
type) {
@@ -595,4 +678,88 @@ public class TestSparkVariantRead extends TestBase {
     }
     return false;
   }
+
+  private void insertShredded(String query, Object... args) {
+    withSQLConf(ImmutableMap.of(SparkSQLProperties.SHRED_VARIANTS, "true"), () 
-> sql(query, args));
+  }
+
+  private List<Row> assertVectorizedMatchesRowReader(String table) {
+    List<Row> expected = readSortedById(table, false);
+    List<Row> actual = readSortedById(table, true);
+
+    assertThat(actual).hasSameSizeAs(expected);
+    for (int i = 0; i < expected.size(); i += 1) {
+      Row expectedRow = expected.get(i);
+      Row actualRow = actual.get(i);
+      assertThat(actualRow.getLong(0)).isEqualTo(expectedRow.getLong(0));
+      assertThat(actualRow.isNullAt(1)).isEqualTo(expectedRow.isNullAt(1));
+      if (!expectedRow.isNullAt(1)) {
+        VariantVal expectedVariant = (VariantVal) expectedRow.get(1);
+        VariantVal actualVariant = (VariantVal) actualRow.get(1);
+        
assertThat(actualVariant.getMetadata()).isEqualTo(expectedVariant.getMetadata());
+        
assertThat(actualVariant.getValue()).isEqualTo(expectedVariant.getValue());
+      }
+    }
+
+    return actual;
+  }
+
+  private List<Row> readSortedById(String table, boolean vectorized) {
+    setVectorization(table, vectorized);
+    List<Row> rows = Lists.newArrayList();
+    SparkPlan plan =
+        executeAndKeepPlan(() -> rows.addAll(spark.table(table).select("id", 
"v").collectAsList()));
+    assertColumnarScan(plan, vectorized);
+
+    rows.sort(Comparator.comparingLong(row -> row.getLong(0)));
+    return rows;
+  }
+
+  private static void assertColumnarScan(SparkPlan plan, boolean columnar) {
+    List<SparkPlan> leaves = 
JavaConverters.seqAsJavaList(plan.collectLeaves());
+    assertThat(leaves)
+        .singleElement()
+        .isInstanceOfSatisfying(
+            BatchScanExec.class,
+            scan ->
+                assertThat(scan.supportsColumnar())
+                    .as("Scan should be columnar only when vectorization is 
enabled")
+                    .isEqualTo(columnar));
+  }
+
+  private static Variant toVariant(Row row) {
+    VariantVal variant = (VariantVal) row.get(1);
+    return new Variant(variant.getValue(), variant.getMetadata());
+  }
+
+  private static void assertLongArray(Variant array, long... expected) {
+    assertThat(array.arraySize()).isEqualTo(expected.length);
+    for (int i = 0; i < expected.length; i += 1) {
+      assertThat(array.getElementAtIndex(i).getLong()).isEqualTo(expected[i]);
+    }
+  }
+
+  private static List<Boolean> shreddedFiles(Table table) throws IOException {
+    List<Boolean> shredded = Lists.newArrayList();
+    for (ParquetMetadata footer : footers(table)) {
+      shredded.add(containsTypedValue(footer.getFileMetaData().getSchema()));
+    }
+
+    return shredded;
+  }
+
+  private static List<ParquetMetadata> footers(Table table) throws IOException 
{
+    List<ParquetMetadata> footers = Lists.newArrayList();
+    try (CloseableIterable<FileScanTask> tasks = table.newScan().planFiles()) {
+      for (FileScanTask task : tasks) {
+        HadoopInputFile inputFile =
+            HadoopInputFile.fromPath(new Path(task.file().location()), new 
Configuration());
+        try (ParquetFileReader reader = ParquetFileReader.open(inputFile)) {
+          footers.add(reader.getFooter());
+        }
+      }
+    }
+
+    return footers;
+  }
 }
diff --git 
a/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
 
b/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
index a73fba48b9..92915f56bb 100644
--- 
a/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
+++ 
b/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
@@ -22,6 +22,7 @@ import static org.assertj.core.api.Assertions.assertThat;
 
 import java.io.File;
 import java.io.IOException;
+import java.util.Comparator;
 import java.util.List;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.Path;
@@ -31,16 +32,20 @@ import org.apache.iceberg.FileScanTask;
 import org.apache.iceberg.Files;
 import org.apache.iceberg.SnapshotChanges;
 import org.apache.iceberg.Table;
+import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.data.FileHelpers;
 import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
 import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
 import org.apache.iceberg.relocated.com.google.common.collect.Lists;
 import org.apache.iceberg.spark.Spark3Util;
 import org.apache.iceberg.spark.SparkCatalog;
+import org.apache.iceberg.spark.SparkSQLProperties;
 import org.apache.iceberg.spark.TestBase;
 import org.apache.iceberg.util.CharSequenceSet;
 import org.apache.iceberg.util.Pair;
 import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
 import org.apache.parquet.hadoop.util.HadoopInputFile;
 import org.apache.spark.sql.Dataset;
 import org.apache.spark.sql.Row;
@@ -53,6 +58,7 @@ import org.apache.spark.unsafe.types.VariantVal;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.ValueSource;
 import scala.collection.JavaConverters;
@@ -498,16 +504,7 @@ public class TestSparkVariantRead extends TestBase {
         executeAndKeepPlan(
             () -> 
rows.addAll(spark.table(shreddedTable).select("id").collectAsList()));
     assertThat(rows).extracting(r -> 
r.getLong(0)).containsExactlyInAnyOrder(1L, 2L);
-
-    List<SparkPlan> leaves = 
JavaConverters.seqAsJavaList(plan.collectLeaves());
-    assertThat(leaves)
-        .singleElement()
-        .isInstanceOfSatisfying(
-            BatchScanExec.class,
-            scan ->
-                assertThat(scan.supportsColumnar())
-                    .as("Scan should be columnar only when vectorization is 
enabled")
-                    .isEqualTo(vectorized));
+    assertColumnarScan(plan, vectorized);
 
     sql("DROP TABLE IF EXISTS %s", shreddedTable);
   }
@@ -557,6 +554,100 @@ public class TestSparkVariantRead extends TestBase {
     sql("DROP TABLE IF EXISTS %s", noStatsTable);
   }
 
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void readShreddedArrayEnabledBySessionConf(boolean required)
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_shredded_array";
+    sql("DROP TABLE IF EXISTS %s", table);
+    sql(
+        "CREATE TABLE %s (id BIGINT, %s) USING iceberg TBLPROPERTIES 
('format-version'='3')",
+        table, required ? "v VARIANT NOT NULL" : "v VARIANT");
+    insertShredded(
+        "INSERT INTO %s VALUES (1, parse_json('{\"a\": [1, 2]}')), (2, 
parse_json('{\"a\": [3]}'))",
+        table);
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    
assertThat(icebergTable.schema().findField("v").isRequired()).isEqualTo(required);
+    assertHasTypedValueSubtree(icebergTable);
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(1L, 2L);
+    assertLongArray(toVariant(rows.get(0)).getFieldByKey("a"), 1L, 2L);
+    assertLongArray(toVariant(rows.get(1)).getFieldByKey("a"), 3L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
+  @Test
+  void readMixedShreddedAndUnshreddedFiles()
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_mixed_files";
+    sql("DROP TABLE IF EXISTS %s", table);
+    sql(
+        "CREATE TABLE %s (id BIGINT, v VARIANT) USING iceberg "
+            + "TBLPROPERTIES ('format-version'='3')",
+        table);
+    spark
+        .sql("SELECT 1L AS id, parse_json('{\"name\":\"alice\",\"age\":30}') 
AS v")
+        .coalesce(1)
+        .writeTo(table)
+        .append();
+    insertShredded(
+        "INSERT INTO %s SELECT /*+ COALESCE(1) */ * FROM ("
+            + "SELECT 2L AS id, CAST(NULL AS VARIANT) AS v "
+            + "UNION ALL SELECT 3L, parse_json('{\"a\":[1,2]}') "
+            + "UNION ALL SELECT 4L, parse_json('{\"a\":[3]}'))",
+        table);
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    assertThat(shreddedFiles(icebergTable)).containsExactlyInAnyOrder(false, 
true);
+    sql("ALTER TABLE %s SET TBLPROPERTIES 
('read.parquet.vectorization.batch-size'='2')", table);
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(1L, 2L, 
3L, 4L);
+    
assertThat(toVariant(rows.get(0)).getFieldByKey("name").getString()).isEqualTo("alice");
+    assertThat(rows.get(1).isNullAt(1)).isTrue();
+    assertLongArray(toVariant(rows.get(2)).getFieldByKey("a"), 1L, 2L);
+    assertLongArray(toVariant(rows.get(3)).getFieldByKey("a"), 3L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
+  @Test
+  void readShreddedVariantAcrossRowGroups()
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_shredded_row_groups";
+    sql("DROP TABLE IF EXISTS %s", table);
+    sql(
+        "CREATE TABLE %s (id BIGINT, v VARIANT) USING iceberg "
+            + "TBLPROPERTIES ('format-version'='3', '%s'='1', '%s'='1', 
'%s'='1')",
+        table,
+        TableProperties.PARQUET_ROW_GROUP_SIZE_BYTES,
+        TableProperties.PARQUET_ROW_GROUP_CHECK_MIN_RECORD_COUNT,
+        TableProperties.PARQUET_ROW_GROUP_CHECK_MAX_RECORD_COUNT);
+    insertShredded(
+        "INSERT INTO %s SELECT /*+ COALESCE(1) */ * FROM ("
+            + "SELECT 1L AS id, CAST(NULL AS VARIANT) AS v "
+            + "UNION ALL SELECT 2L, parse_json('{\"a\":[1,2]}') "
+            + "UNION ALL SELECT 3L, parse_json('{\"a\":[3]}'))",
+        table);
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    assertHasTypedValueSubtree(icebergTable);
+    assertThat(footers(icebergTable))
+        .singleElement()
+        .satisfies(footer -> 
assertThat(footer.getBlocks()).hasSizeGreaterThan(1));
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(1L, 2L, 
3L);
+    assertThat(rows.get(0).isNullAt(1)).isTrue();
+    assertLongArray(toVariant(rows.get(1)).getFieldByKey("a"), 1L, 2L);
+    assertLongArray(toVariant(rows.get(2)).getFieldByKey("a"), 3L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
   private void setVectorization(boolean on) {
     sql(
         "ALTER TABLE %s SET TBLPROPERTIES 
('read.parquet.vectorization.enabled'='%s')",
@@ -570,18 +661,10 @@ public class TestSparkVariantRead extends TestBase {
   }
 
   private static void assertHasTypedValueSubtree(Table table) throws 
IOException {
-    try (CloseableIterable<FileScanTask> tasks = table.newScan().planFiles()) {
-      assertThat(tasks).isNotEmpty();
-      for (FileScanTask task : tasks) {
-        HadoopInputFile inputFile =
-            HadoopInputFile.fromPath(new Path(task.file().location()), new 
Configuration());
-        try (ParquetFileReader reader = ParquetFileReader.open(inputFile)) {
-          assertThat(containsTypedValue(reader.getFileMetaData().getSchema()))
-              .as("Expected variant column to be shredded with a typed_value 
subtree")
-              .isTrue();
-        }
-      }
-    }
+    assertThat(shreddedFiles(table))
+        .as("Expected variant column to be shredded with a typed_value 
subtree")
+        .isNotEmpty()
+        .containsOnly(true);
   }
 
   private static boolean containsTypedValue(org.apache.parquet.schema.Type 
type) {
@@ -595,4 +678,88 @@ public class TestSparkVariantRead extends TestBase {
     }
     return false;
   }
+
+  private void insertShredded(String query, Object... args) {
+    withSQLConf(ImmutableMap.of(SparkSQLProperties.SHRED_VARIANTS, "true"), () 
-> sql(query, args));
+  }
+
+  private List<Row> assertVectorizedMatchesRowReader(String table) {
+    List<Row> expected = readSortedById(table, false);
+    List<Row> actual = readSortedById(table, true);
+
+    assertThat(actual).hasSameSizeAs(expected);
+    for (int i = 0; i < expected.size(); i += 1) {
+      Row expectedRow = expected.get(i);
+      Row actualRow = actual.get(i);
+      assertThat(actualRow.getLong(0)).isEqualTo(expectedRow.getLong(0));
+      assertThat(actualRow.isNullAt(1)).isEqualTo(expectedRow.isNullAt(1));
+      if (!expectedRow.isNullAt(1)) {
+        VariantVal expectedVariant = (VariantVal) expectedRow.get(1);
+        VariantVal actualVariant = (VariantVal) actualRow.get(1);
+        
assertThat(actualVariant.getMetadata()).isEqualTo(expectedVariant.getMetadata());
+        
assertThat(actualVariant.getValue()).isEqualTo(expectedVariant.getValue());
+      }
+    }
+
+    return actual;
+  }
+
+  private List<Row> readSortedById(String table, boolean vectorized) {
+    setVectorization(table, vectorized);
+    List<Row> rows = Lists.newArrayList();
+    SparkPlan plan =
+        executeAndKeepPlan(() -> rows.addAll(spark.table(table).select("id", 
"v").collectAsList()));
+    assertColumnarScan(plan, vectorized);
+
+    rows.sort(Comparator.comparingLong(row -> row.getLong(0)));
+    return rows;
+  }
+
+  private static void assertColumnarScan(SparkPlan plan, boolean columnar) {
+    List<SparkPlan> leaves = 
JavaConverters.seqAsJavaList(plan.collectLeaves());
+    assertThat(leaves)
+        .singleElement()
+        .isInstanceOfSatisfying(
+            BatchScanExec.class,
+            scan ->
+                assertThat(scan.supportsColumnar())
+                    .as("Scan should be columnar only when vectorization is 
enabled")
+                    .isEqualTo(columnar));
+  }
+
+  private static Variant toVariant(Row row) {
+    VariantVal variant = (VariantVal) row.get(1);
+    return new Variant(variant.getValue(), variant.getMetadata());
+  }
+
+  private static void assertLongArray(Variant array, long... expected) {
+    assertThat(array.arraySize()).isEqualTo(expected.length);
+    for (int i = 0; i < expected.length; i += 1) {
+      assertThat(array.getElementAtIndex(i).getLong()).isEqualTo(expected[i]);
+    }
+  }
+
+  private static List<Boolean> shreddedFiles(Table table) throws IOException {
+    List<Boolean> shredded = Lists.newArrayList();
+    for (ParquetMetadata footer : footers(table)) {
+      shredded.add(containsTypedValue(footer.getFileMetaData().getSchema()));
+    }
+
+    return shredded;
+  }
+
+  private static List<ParquetMetadata> footers(Table table) throws IOException 
{
+    List<ParquetMetadata> footers = Lists.newArrayList();
+    try (CloseableIterable<FileScanTask> tasks = table.newScan().planFiles()) {
+      for (FileScanTask task : tasks) {
+        HadoopInputFile inputFile =
+            HadoopInputFile.fromPath(new Path(task.file().location()), new 
Configuration());
+        try (ParquetFileReader reader = ParquetFileReader.open(inputFile)) {
+          footers.add(reader.getFooter());
+        }
+      }
+    }
+
+    return footers;
+  }
 }
diff --git 
a/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
 
b/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
index a73fba48b9..92915f56bb 100644
--- 
a/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
+++ 
b/spark/v4.2/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkVariantRead.java
@@ -22,6 +22,7 @@ import static org.assertj.core.api.Assertions.assertThat;
 
 import java.io.File;
 import java.io.IOException;
+import java.util.Comparator;
 import java.util.List;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.Path;
@@ -31,16 +32,20 @@ import org.apache.iceberg.FileScanTask;
 import org.apache.iceberg.Files;
 import org.apache.iceberg.SnapshotChanges;
 import org.apache.iceberg.Table;
+import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.data.FileHelpers;
 import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
 import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
 import org.apache.iceberg.relocated.com.google.common.collect.Lists;
 import org.apache.iceberg.spark.Spark3Util;
 import org.apache.iceberg.spark.SparkCatalog;
+import org.apache.iceberg.spark.SparkSQLProperties;
 import org.apache.iceberg.spark.TestBase;
 import org.apache.iceberg.util.CharSequenceSet;
 import org.apache.iceberg.util.Pair;
 import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
 import org.apache.parquet.hadoop.util.HadoopInputFile;
 import org.apache.spark.sql.Dataset;
 import org.apache.spark.sql.Row;
@@ -53,6 +58,7 @@ import org.apache.spark.unsafe.types.VariantVal;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.ValueSource;
 import scala.collection.JavaConverters;
@@ -498,16 +504,7 @@ public class TestSparkVariantRead extends TestBase {
         executeAndKeepPlan(
             () -> 
rows.addAll(spark.table(shreddedTable).select("id").collectAsList()));
     assertThat(rows).extracting(r -> 
r.getLong(0)).containsExactlyInAnyOrder(1L, 2L);
-
-    List<SparkPlan> leaves = 
JavaConverters.seqAsJavaList(plan.collectLeaves());
-    assertThat(leaves)
-        .singleElement()
-        .isInstanceOfSatisfying(
-            BatchScanExec.class,
-            scan ->
-                assertThat(scan.supportsColumnar())
-                    .as("Scan should be columnar only when vectorization is 
enabled")
-                    .isEqualTo(vectorized));
+    assertColumnarScan(plan, vectorized);
 
     sql("DROP TABLE IF EXISTS %s", shreddedTable);
   }
@@ -557,6 +554,100 @@ public class TestSparkVariantRead extends TestBase {
     sql("DROP TABLE IF EXISTS %s", noStatsTable);
   }
 
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void readShreddedArrayEnabledBySessionConf(boolean required)
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_shredded_array";
+    sql("DROP TABLE IF EXISTS %s", table);
+    sql(
+        "CREATE TABLE %s (id BIGINT, %s) USING iceberg TBLPROPERTIES 
('format-version'='3')",
+        table, required ? "v VARIANT NOT NULL" : "v VARIANT");
+    insertShredded(
+        "INSERT INTO %s VALUES (1, parse_json('{\"a\": [1, 2]}')), (2, 
parse_json('{\"a\": [3]}'))",
+        table);
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    
assertThat(icebergTable.schema().findField("v").isRequired()).isEqualTo(required);
+    assertHasTypedValueSubtree(icebergTable);
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(1L, 2L);
+    assertLongArray(toVariant(rows.get(0)).getFieldByKey("a"), 1L, 2L);
+    assertLongArray(toVariant(rows.get(1)).getFieldByKey("a"), 3L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
+  @Test
+  void readMixedShreddedAndUnshreddedFiles()
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_mixed_files";
+    sql("DROP TABLE IF EXISTS %s", table);
+    sql(
+        "CREATE TABLE %s (id BIGINT, v VARIANT) USING iceberg "
+            + "TBLPROPERTIES ('format-version'='3')",
+        table);
+    spark
+        .sql("SELECT 1L AS id, parse_json('{\"name\":\"alice\",\"age\":30}') 
AS v")
+        .coalesce(1)
+        .writeTo(table)
+        .append();
+    insertShredded(
+        "INSERT INTO %s SELECT /*+ COALESCE(1) */ * FROM ("
+            + "SELECT 2L AS id, CAST(NULL AS VARIANT) AS v "
+            + "UNION ALL SELECT 3L, parse_json('{\"a\":[1,2]}') "
+            + "UNION ALL SELECT 4L, parse_json('{\"a\":[3]}'))",
+        table);
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    assertThat(shreddedFiles(icebergTable)).containsExactlyInAnyOrder(false, 
true);
+    sql("ALTER TABLE %s SET TBLPROPERTIES 
('read.parquet.vectorization.batch-size'='2')", table);
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(1L, 2L, 
3L, 4L);
+    
assertThat(toVariant(rows.get(0)).getFieldByKey("name").getString()).isEqualTo("alice");
+    assertThat(rows.get(1).isNullAt(1)).isTrue();
+    assertLongArray(toVariant(rows.get(2)).getFieldByKey("a"), 1L, 2L);
+    assertLongArray(toVariant(rows.get(3)).getFieldByKey("a"), 3L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
+  @Test
+  void readShreddedVariantAcrossRowGroups()
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_shredded_row_groups";
+    sql("DROP TABLE IF EXISTS %s", table);
+    sql(
+        "CREATE TABLE %s (id BIGINT, v VARIANT) USING iceberg "
+            + "TBLPROPERTIES ('format-version'='3', '%s'='1', '%s'='1', 
'%s'='1')",
+        table,
+        TableProperties.PARQUET_ROW_GROUP_SIZE_BYTES,
+        TableProperties.PARQUET_ROW_GROUP_CHECK_MIN_RECORD_COUNT,
+        TableProperties.PARQUET_ROW_GROUP_CHECK_MAX_RECORD_COUNT);
+    insertShredded(
+        "INSERT INTO %s SELECT /*+ COALESCE(1) */ * FROM ("
+            + "SELECT 1L AS id, CAST(NULL AS VARIANT) AS v "
+            + "UNION ALL SELECT 2L, parse_json('{\"a\":[1,2]}') "
+            + "UNION ALL SELECT 3L, parse_json('{\"a\":[3]}'))",
+        table);
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    assertHasTypedValueSubtree(icebergTable);
+    assertThat(footers(icebergTable))
+        .singleElement()
+        .satisfies(footer -> 
assertThat(footer.getBlocks()).hasSizeGreaterThan(1));
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(1L, 2L, 
3L);
+    assertThat(rows.get(0).isNullAt(1)).isTrue();
+    assertLongArray(toVariant(rows.get(1)).getFieldByKey("a"), 1L, 2L);
+    assertLongArray(toVariant(rows.get(2)).getFieldByKey("a"), 3L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
   private void setVectorization(boolean on) {
     sql(
         "ALTER TABLE %s SET TBLPROPERTIES 
('read.parquet.vectorization.enabled'='%s')",
@@ -570,18 +661,10 @@ public class TestSparkVariantRead extends TestBase {
   }
 
   private static void assertHasTypedValueSubtree(Table table) throws 
IOException {
-    try (CloseableIterable<FileScanTask> tasks = table.newScan().planFiles()) {
-      assertThat(tasks).isNotEmpty();
-      for (FileScanTask task : tasks) {
-        HadoopInputFile inputFile =
-            HadoopInputFile.fromPath(new Path(task.file().location()), new 
Configuration());
-        try (ParquetFileReader reader = ParquetFileReader.open(inputFile)) {
-          assertThat(containsTypedValue(reader.getFileMetaData().getSchema()))
-              .as("Expected variant column to be shredded with a typed_value 
subtree")
-              .isTrue();
-        }
-      }
-    }
+    assertThat(shreddedFiles(table))
+        .as("Expected variant column to be shredded with a typed_value 
subtree")
+        .isNotEmpty()
+        .containsOnly(true);
   }
 
   private static boolean containsTypedValue(org.apache.parquet.schema.Type 
type) {
@@ -595,4 +678,88 @@ public class TestSparkVariantRead extends TestBase {
     }
     return false;
   }
+
+  private void insertShredded(String query, Object... args) {
+    withSQLConf(ImmutableMap.of(SparkSQLProperties.SHRED_VARIANTS, "true"), () 
-> sql(query, args));
+  }
+
+  private List<Row> assertVectorizedMatchesRowReader(String table) {
+    List<Row> expected = readSortedById(table, false);
+    List<Row> actual = readSortedById(table, true);
+
+    assertThat(actual).hasSameSizeAs(expected);
+    for (int i = 0; i < expected.size(); i += 1) {
+      Row expectedRow = expected.get(i);
+      Row actualRow = actual.get(i);
+      assertThat(actualRow.getLong(0)).isEqualTo(expectedRow.getLong(0));
+      assertThat(actualRow.isNullAt(1)).isEqualTo(expectedRow.isNullAt(1));
+      if (!expectedRow.isNullAt(1)) {
+        VariantVal expectedVariant = (VariantVal) expectedRow.get(1);
+        VariantVal actualVariant = (VariantVal) actualRow.get(1);
+        
assertThat(actualVariant.getMetadata()).isEqualTo(expectedVariant.getMetadata());
+        
assertThat(actualVariant.getValue()).isEqualTo(expectedVariant.getValue());
+      }
+    }
+
+    return actual;
+  }
+
+  private List<Row> readSortedById(String table, boolean vectorized) {
+    setVectorization(table, vectorized);
+    List<Row> rows = Lists.newArrayList();
+    SparkPlan plan =
+        executeAndKeepPlan(() -> rows.addAll(spark.table(table).select("id", 
"v").collectAsList()));
+    assertColumnarScan(plan, vectorized);
+
+    rows.sort(Comparator.comparingLong(row -> row.getLong(0)));
+    return rows;
+  }
+
+  private static void assertColumnarScan(SparkPlan plan, boolean columnar) {
+    List<SparkPlan> leaves = 
JavaConverters.seqAsJavaList(plan.collectLeaves());
+    assertThat(leaves)
+        .singleElement()
+        .isInstanceOfSatisfying(
+            BatchScanExec.class,
+            scan ->
+                assertThat(scan.supportsColumnar())
+                    .as("Scan should be columnar only when vectorization is 
enabled")
+                    .isEqualTo(columnar));
+  }
+
+  private static Variant toVariant(Row row) {
+    VariantVal variant = (VariantVal) row.get(1);
+    return new Variant(variant.getValue(), variant.getMetadata());
+  }
+
+  private static void assertLongArray(Variant array, long... expected) {
+    assertThat(array.arraySize()).isEqualTo(expected.length);
+    for (int i = 0; i < expected.length; i += 1) {
+      assertThat(array.getElementAtIndex(i).getLong()).isEqualTo(expected[i]);
+    }
+  }
+
+  private static List<Boolean> shreddedFiles(Table table) throws IOException {
+    List<Boolean> shredded = Lists.newArrayList();
+    for (ParquetMetadata footer : footers(table)) {
+      shredded.add(containsTypedValue(footer.getFileMetaData().getSchema()));
+    }
+
+    return shredded;
+  }
+
+  private static List<ParquetMetadata> footers(Table table) throws IOException 
{
+    List<ParquetMetadata> footers = Lists.newArrayList();
+    try (CloseableIterable<FileScanTask> tasks = table.newScan().planFiles()) {
+      for (FileScanTask task : tasks) {
+        HadoopInputFile inputFile =
+            HadoopInputFile.fromPath(new Path(task.file().location()), new 
Configuration());
+        try (ParquetFileReader reader = ParquetFileReader.open(inputFile)) {
+          footers.add(reader.getFooter());
+        }
+      }
+    }
+
+    return footers;
+  }
 }

Reply via email to