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 1440e49e39 Spark 4.0, 4.1: Remove plan-time shredded variant checks 
from vectorized reads (#19032)
1440e49e39 is described below

commit 1440e49e39a7c436a687b0289be067a5cf411e2c
Author: Neelesh Salian <[email protected]>
AuthorDate: Wed Nov 18 18:44:21 2026 -0800

    Spark 4.0, 4.1: Remove plan-time shredded variant checks from vectorized 
reads (#19032)
---
 .../apache/iceberg/spark/source/SparkBatch.java    |  38 +----
 .../iceberg/spark/source/SparkScanBuilder.java     |  24 +---
 .../iceberg/spark/sql/TestSparkVariantRead.java    | 158 +++++++++++++++++----
 .../apache/iceberg/spark/source/SparkBatch.java    |  38 +----
 .../iceberg/spark/source/SparkScanBuilder.java     |  24 +---
 .../iceberg/spark/sql/TestSparkVariantRead.java    | 158 +++++++++++++++++----
 6 files changed, 281 insertions(+), 159 deletions(-)

diff --git 
a/spark/v4.0/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java
 
b/spark/v4.0/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java
index b50d060955..b6eca2bb9d 100644
--- 
a/spark/v4.0/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java
+++ 
b/spark/v4.0/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java
@@ -18,22 +18,17 @@
  */
 package org.apache.iceberg.spark.source;
 
-import java.nio.ByteBuffer;
 import java.util.List;
-import java.util.Map;
 import java.util.Objects;
 import java.util.function.Supplier;
 import org.apache.iceberg.FileFormat;
 import org.apache.iceberg.FileScanTask;
 import org.apache.iceberg.MetadataColumns;
-import org.apache.iceberg.MetricsConfig;
-import org.apache.iceberg.MetricsModes;
 import org.apache.iceberg.ScanTask;
 import org.apache.iceberg.ScanTaskGroup;
 import org.apache.iceberg.Schema;
 import org.apache.iceberg.SchemaParser;
 import org.apache.iceberg.Table;
-import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.io.FileIO;
 import org.apache.iceberg.spark.ImmutableOrcBatchReadConf;
 import org.apache.iceberg.spark.ImmutableParquetBatchReadConf;
@@ -42,7 +37,6 @@ import org.apache.iceberg.spark.ParquetBatchReadConf;
 import org.apache.iceberg.spark.SparkReadConf;
 import org.apache.iceberg.spark.SparkUtil;
 import org.apache.iceberg.types.Types;
-import org.apache.iceberg.util.PropertyUtil;
 import org.apache.spark.api.java.JavaSparkContext;
 import org.apache.spark.broadcast.Broadcast;
 import org.apache.spark.sql.connector.read.Batch;
@@ -155,7 +149,7 @@ class SparkBatch implements Batch {
 
   // conditions for using Parquet batch reads:
   // - Parquet vectorization is enabled
-  // - only primitives, unshredded variant, or metadata columns are projected
+  // - only primitives, variant, or metadata columns are projected
   // - all tasks are of FileScanTask type and read only Parquet files
   private boolean useParquetBatchReads() {
     return readConf.parquetVectorizationEnabled()
@@ -170,18 +164,7 @@ class SparkBatch implements Batch {
 
     } else if (task.isFileScanTask() && !task.isDataTask()) {
       FileScanTask fileScanTask = task.asFileScanTask();
-      if (fileScanTask.file().format() != FileFormat.PARQUET) {
-        return false;
-      }
-      Map<Integer, ByteBuffer> lowerBounds = fileScanTask.file().lowerBounds();
-      if (lowerBounds != null) {
-        for (Types.NestedField field : expectedSchema.columns()) {
-          if (field.type().isVariantType() && 
lowerBounds.containsKey(field.fieldId())) {
-            return false;
-          }
-        }
-      }
-      return true;
+      return fileScanTask.file().format() == FileFormat.PARQUET;
 
     } else {
       return false;
@@ -189,23 +172,6 @@ class SparkBatch implements Batch {
   }
 
   private boolean supportsParquetBatchReads(Types.NestedField field) {
-    if (field.type().isVariantType()) {
-      boolean shredVariants =
-          PropertyUtil.propertyAsBoolean(
-              table.properties(),
-              TableProperties.PARQUET_SHRED_VARIANTS,
-              TableProperties.PARQUET_SHRED_VARIANTS_DEFAULT);
-      if (shredVariants) {
-        return false;
-      }
-
-      MetricsConfig metricsConfig = MetricsConfig.forTable(table);
-      MetricsModes.MetricsMode mode = 
metricsConfig.columnMode(field.fieldId());
-      if (mode == MetricsModes.None.get() || mode == 
MetricsModes.Counts.get()) {
-        return false;
-      }
-    }
-
     return field.type().isPrimitiveType()
         || field.type().isVariantType()
         || MetadataColumns.isMetadataColumn(field.fieldId());
diff --git 
a/spark/v4.0/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java
 
b/spark/v4.0/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java
index ca00032f16..9710b0015d 100644
--- 
a/spark/v4.0/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java
+++ 
b/spark/v4.0/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java
@@ -480,7 +480,9 @@ public class SparkScanBuilder
             .project(expectedSchema)
             .metricsReporter(metricsReporter);
 
-    scan = includeStats(scan, expectedSchema, withStats);
+    if (withStats) {
+      scan = scan.includeColumnStats();
+    }
 
     if (snapshotId != null) {
       scan = scan.useSnapshot(snapshotId);
@@ -512,7 +514,9 @@ public class SparkScanBuilder
             .project(expectedSchema)
             .metricsReporter(metricsReporter);
 
-    scan = includeStats(scan, expectedSchema, withStats);
+    if (withStats) {
+      scan = scan.includeColumnStats();
+    }
 
     if (endSnapshotId != null) {
       scan = scan.toSnapshot(endSnapshotId);
@@ -521,22 +525,6 @@ public class SparkScanBuilder
     return configureSplitPlanning(scan);
   }
 
-  private <S extends org.apache.iceberg.Scan<S, ?, ?>> S includeStats(
-      S scan, Schema projection, boolean withStats) {
-    if (withStats) {
-      return scan.includeColumnStats();
-    }
-    List<String> variantColumns = variantColumnNames(projection);
-    return variantColumns.isEmpty() ? scan : 
scan.includeColumnStats(variantColumns);
-  }
-
-  private List<String> variantColumnNames(Schema projection) {
-    return projection.columns().stream()
-        .filter(field -> field.type().isVariantType())
-        .map(Types.NestedField::name)
-        .collect(Collectors.toList());
-  }
-
   @SuppressWarnings("CyclomaticComplexity")
   public Scan buildChangelogScan() {
     Preconditions.checkArgument(
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 92915f56bb..f52e813685 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
@@ -24,13 +24,16 @@ import java.io.File;
 import java.io.IOException;
 import java.util.Comparator;
 import java.util.List;
+import java.util.Map;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.Path;
 import org.apache.iceberg.DataFile;
 import org.apache.iceberg.DeleteFile;
 import org.apache.iceberg.FileScanTask;
 import org.apache.iceberg.Files;
+import org.apache.iceberg.RowLevelOperationMode;
 import org.apache.iceberg.SnapshotChanges;
+import org.apache.iceberg.SnapshotSummary;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.data.FileHelpers;
@@ -40,6 +43,7 @@ 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.SparkReadOptions;
 import org.apache.iceberg.spark.SparkSQLProperties;
 import org.apache.iceberg.spark.TestBase;
 import org.apache.iceberg.util.CharSequenceSet;
@@ -453,9 +457,7 @@ public class TestSparkVariantRead extends TestBase {
     assertHasTypedValueSubtree(table);
 
     sql("ALTER TABLE %s SET TBLPROPERTIES 
('write.parquet.shred-variants'='false')", toggleTable);
-    setVectorization(toggleTable, vectorized);
-
-    List<Row> rows = spark.table(toggleTable).select("id", 
"v").orderBy("id").collectAsList();
+    List<Row> rows = readSortedById(toggleTable, vectorized, 
ImmutableMap.of());
     assertThat(rows).hasSize(2);
     Variant v1 =
         new Variant(
@@ -536,9 +538,7 @@ public class TestSparkVariantRead extends TestBase {
 
     Table table = Spark3Util.loadIcebergTable(spark, noStatsTable);
     assertHasTypedValueSubtree(table);
-    setVectorization(noStatsTable, true);
-
-    List<Row> rows = spark.table(noStatsTable).select("id", 
"v").orderBy("id").collectAsList();
+    List<Row> rows = assertVectorizedMatchesRowReader(noStatsTable);
     assertThat(rows).hasSize(2);
     Variant v1 =
         new Variant(
@@ -580,26 +580,81 @@ public class TestSparkVariantRead extends TestBase {
   }
 
   @Test
-  void readMixedShreddedAndUnshreddedFiles()
+  void readShreddedEnabledByTableProperty()
       throws IOException, NoSuchTableException, ParseException {
-    String table = CATALOG + ".default.var_mixed_files";
+    String table = CATALOG + ".default.var_shredded_property";
     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]}'))",
+            + "TBLPROPERTIES ('format-version'='3', '%s'='true')",
+        table, TableProperties.PARQUET_SHRED_VARIANTS);
+    sql(
+        "INSERT INTO %s VALUES (1, parse_json('{\"a\": [1, 2]}')), (2, 
parse_json('{\"a\": [3]}'))",
         table);
 
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    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 readMixedObjectShreddedAndUnshreddedFiles()
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_mixed_object_files";
+    writeUnshreddedThenShreddedFile(
+        table, "{\"name\":\"bob\",\"age\":25}", 
"{\"name\":\"carol\",\"age\":41}");
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    assertThat(shreddedFiles(icebergTable)).containsExactlyInAnyOrder(false, 
true);
+    int variantId = icebergTable.schema().findField("v").fieldId();
+    try (CloseableIterable<FileScanTask> tasks =
+        icebergTable.newScan().includeColumnStats().planFiles()) {
+      assertThat(tasks)
+          .anyMatch(
+              task ->
+                  task.file().lowerBounds() != null
+                      && task.file().lowerBounds().containsKey(variantId));
+    }
+
+    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();
+    
assertThat(toVariant(rows.get(2)).getFieldByKey("name").getString()).isEqualTo("bob");
+    
assertThat(toVariant(rows.get(3)).getFieldByKey("age").getLong()).isEqualTo(41L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
+  @Test
+  void readShreddedIncrementalAppendScan() throws NoSuchTableException, 
ParseException {
+    String table = CATALOG + ".default.var_shredded_incremental";
+    writeUnshreddedThenShreddedFile(
+        table, "{\"name\":\"bob\",\"age\":25}", 
"{\"name\":\"carol\",\"age\":41}");
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    long unshreddedSnapshotId = icebergTable.currentSnapshot().parentId();
+    Map<String, String> incremental =
+        ImmutableMap.of(SparkReadOptions.START_SNAPSHOT_ID, 
String.valueOf(unshreddedSnapshotId));
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table, incremental);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(2L, 3L, 
4L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
+  @Test
+  void readMixedShreddedAndUnshreddedFiles()
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_mixed_files";
+    writeUnshreddedThenShreddedFile(table, "{\"a\":[1,2]}", "{\"a\":[3]}");
+
     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);
@@ -648,6 +703,33 @@ public class TestSparkVariantRead extends TestBase {
     sql("DROP TABLE IF EXISTS %s", table);
   }
 
+  @Test
+  void readShreddedVariantAfterDelete() throws IOException, 
NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_shredded_delete";
+    sql("DROP TABLE IF EXISTS %s", table);
+    sql(
+        "CREATE TABLE %s (id BIGINT, v VARIANT) USING iceberg "
+            + "TBLPROPERTIES ('format-version'='3', '%s'='%s')",
+        table, TableProperties.DELETE_MODE, 
RowLevelOperationMode.MERGE_ON_READ.modeName());
+    insertShredded(
+        "INSERT INTO %s SELECT /*+ COALESCE(1) */ * FROM ("
+            + "SELECT 1L AS id, parse_json('{\"name\":\"alice\",\"age\":30}') 
AS v "
+            + "UNION ALL SELECT 2L, 
parse_json('{\"name\":\"bob\",\"age\":25}') "
+            + "UNION ALL SELECT 3L, 
parse_json('{\"name\":\"carol\",\"age\":41}'))",
+        table);
+    sql("DELETE FROM %s WHERE id = 2", table);
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    assertHasTypedValueSubtree(icebergTable);
+    assertThat(icebergTable.currentSnapshot().summary())
+        .containsEntry(SnapshotSummary.ADDED_DVS_PROP, "1");
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(1L, 3L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
   private void setVectorization(boolean on) {
     sql(
         "ALTER TABLE %s SET TBLPROPERTIES 
('read.parquet.vectorization.enabled'='%s')",
@@ -679,13 +761,38 @@ public class TestSparkVariantRead extends TestBase {
     return false;
   }
 
+  private void writeUnshreddedThenShreddedFile(String table, String 
thirdValue, String fourthValue)
+      throws NoSuchTableException {
+    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('%s') "
+            + "UNION ALL SELECT 4L, parse_json('%s'))",
+        table, thirdValue, fourthValue);
+  }
+
   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);
+    return assertVectorizedMatchesRowReader(table, ImmutableMap.of());
+  }
+
+  private List<Row> assertVectorizedMatchesRowReader(
+      String table, Map<String, String> readOptions) {
+    List<Row> expected = readSortedById(table, false, readOptions);
+    List<Row> actual = readSortedById(table, true, readOptions);
 
     assertThat(actual).hasSameSizeAs(expected);
     for (int i = 0; i < expected.size(); i += 1) {
@@ -704,11 +811,12 @@ public class TestSparkVariantRead extends TestBase {
     return actual;
   }
 
-  private List<Row> readSortedById(String table, boolean vectorized) {
+  private List<Row> readSortedById(
+      String table, boolean vectorized, Map<String, String> readOptions) {
     setVectorization(table, vectorized);
+    Dataset<Row> df = 
spark.read().options(readOptions).table(table).select("id", "v");
     List<Row> rows = Lists.newArrayList();
-    SparkPlan plan =
-        executeAndKeepPlan(() -> rows.addAll(spark.table(table).select("id", 
"v").collectAsList()));
+    SparkPlan plan = executeAndKeepPlan(() -> rows.addAll(df.collectAsList()));
     assertColumnarScan(plan, vectorized);
 
     rows.sort(Comparator.comparingLong(row -> row.getLong(0)));
diff --git 
a/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java
 
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java
index 81fb008963..bb46cadf22 100644
--- 
a/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java
+++ 
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/SparkBatch.java
@@ -18,22 +18,17 @@
  */
 package org.apache.iceberg.spark.source;
 
-import java.nio.ByteBuffer;
 import java.util.List;
-import java.util.Map;
 import java.util.Objects;
 import java.util.function.Supplier;
 import org.apache.iceberg.FileFormat;
 import org.apache.iceberg.FileScanTask;
 import org.apache.iceberg.MetadataColumns;
-import org.apache.iceberg.MetricsConfig;
-import org.apache.iceberg.MetricsModes;
 import org.apache.iceberg.ScanTask;
 import org.apache.iceberg.ScanTaskGroup;
 import org.apache.iceberg.Schema;
 import org.apache.iceberg.SchemaParser;
 import org.apache.iceberg.Table;
-import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.io.FileIO;
 import org.apache.iceberg.spark.ImmutableOrcBatchReadConf;
 import org.apache.iceberg.spark.ImmutableParquetBatchReadConf;
@@ -43,7 +38,6 @@ import org.apache.iceberg.spark.SparkReadConf;
 import org.apache.iceberg.spark.SparkUtil;
 import org.apache.iceberg.types.Type;
 import org.apache.iceberg.types.Types;
-import org.apache.iceberg.util.PropertyUtil;
 import org.apache.spark.api.java.JavaSparkContext;
 import org.apache.spark.broadcast.Broadcast;
 import org.apache.spark.sql.connector.read.Batch;
@@ -153,7 +147,7 @@ class SparkBatch implements Batch {
 
   // conditions for using Parquet batch reads:
   // - Parquet vectorization is enabled
-  // - only primitives, unshredded variant, or metadata columns are projected, 
excluding geometry
+  // - only primitives, variant, or metadata columns are projected, excluding 
geometry
   //   and geography which are primitives with no Arrow vector yet
   // - all tasks are of FileScanTask type and read only Parquet files
   private boolean useParquetBatchReads() {
@@ -169,18 +163,7 @@ class SparkBatch implements Batch {
 
     } else if (task.isFileScanTask() && !task.isDataTask()) {
       FileScanTask fileScanTask = task.asFileScanTask();
-      if (fileScanTask.file().format() != FileFormat.PARQUET) {
-        return false;
-      }
-      Map<Integer, ByteBuffer> lowerBounds = fileScanTask.file().lowerBounds();
-      if (lowerBounds != null) {
-        for (Types.NestedField field : projection.columns()) {
-          if (field.type().isVariantType() && 
lowerBounds.containsKey(field.fieldId())) {
-            return false;
-          }
-        }
-      }
-      return true;
+      return fileScanTask.file().format() == FileFormat.PARQUET;
 
     } else {
       return false;
@@ -199,23 +182,6 @@ class SparkBatch implements Batch {
       return false;
     }
 
-    if (type.isVariantType()) {
-      boolean shredVariants =
-          PropertyUtil.propertyAsBoolean(
-              table.properties(),
-              TableProperties.PARQUET_SHRED_VARIANTS,
-              TableProperties.PARQUET_SHRED_VARIANTS_DEFAULT);
-      if (shredVariants) {
-        return false;
-      }
-
-      MetricsConfig metricsConfig = MetricsConfig.forTable(table);
-      MetricsModes.MetricsMode mode = 
metricsConfig.columnMode(field.fieldId());
-      if (mode == MetricsModes.None.get() || mode == 
MetricsModes.Counts.get()) {
-        return false;
-      }
-    }
-
     return type.isPrimitiveType() || type.isVariantType();
   }
 
diff --git 
a/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java
 
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java
index 6e0d895c9b..dd90730408 100644
--- 
a/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java
+++ 
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/SparkScanBuilder.java
@@ -21,7 +21,6 @@ package org.apache.iceberg.spark.source;
 import java.io.IOException;
 import java.util.List;
 import java.util.Objects;
-import java.util.stream.Collectors;
 import org.apache.iceberg.BaseMetadataTable;
 import org.apache.iceberg.BaseTable;
 import org.apache.iceberg.BatchScan;
@@ -49,7 +48,6 @@ import org.apache.iceberg.spark.SparkSchemaUtil;
 import org.apache.iceberg.spark.SparkTableUtil;
 import org.apache.iceberg.spark.TimeTravel;
 import org.apache.iceberg.types.Type;
-import org.apache.iceberg.types.Types;
 import org.apache.iceberg.util.Pair;
 import org.apache.spark.sql.SparkSession;
 import org.apache.spark.sql.catalyst.InternalRow;
@@ -328,7 +326,9 @@ public class SparkScanBuilder extends BaseSparkScanBuilder
             .project(projection)
             .metricsReporter(metricsReporter());
 
-    scan = includeStats(scan, projection, withStats);
+    if (withStats) {
+      scan = scan.includeColumnStats();
+    }
 
     if (endSnapshotId != null) {
       scan = scan.toSnapshot(endSnapshotId);
@@ -364,25 +364,11 @@ public class SparkScanBuilder extends BaseSparkScanBuilder
       scan = scan.ignoreResiduals();
     }
 
-    scan = includeStats(scan, projection, withStats);
-
-    return configureSplitPlanning(scan);
-  }
-
-  private <S extends org.apache.iceberg.Scan<S, ?, ?>> S includeStats(
-      S scan, Schema projection, boolean withStats) {
     if (withStats) {
-      return scan.includeColumnStats();
+      scan = scan.includeColumnStats();
     }
-    List<String> variantColumns = variantColumnNames(projection);
-    return variantColumns.isEmpty() ? scan : 
scan.includeColumnStats(variantColumns);
-  }
 
-  private List<String> variantColumnNames(Schema projection) {
-    return projection.columns().stream()
-        .filter(field -> field.type().isVariantType())
-        .map(Types.NestedField::name)
-        .collect(Collectors.toList());
+    return configureSplitPlanning(scan);
   }
 
   private BatchScan newIcebergBatchScan() {
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 92915f56bb..f52e813685 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
@@ -24,13 +24,16 @@ import java.io.File;
 import java.io.IOException;
 import java.util.Comparator;
 import java.util.List;
+import java.util.Map;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.Path;
 import org.apache.iceberg.DataFile;
 import org.apache.iceberg.DeleteFile;
 import org.apache.iceberg.FileScanTask;
 import org.apache.iceberg.Files;
+import org.apache.iceberg.RowLevelOperationMode;
 import org.apache.iceberg.SnapshotChanges;
+import org.apache.iceberg.SnapshotSummary;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.data.FileHelpers;
@@ -40,6 +43,7 @@ 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.SparkReadOptions;
 import org.apache.iceberg.spark.SparkSQLProperties;
 import org.apache.iceberg.spark.TestBase;
 import org.apache.iceberg.util.CharSequenceSet;
@@ -453,9 +457,7 @@ public class TestSparkVariantRead extends TestBase {
     assertHasTypedValueSubtree(table);
 
     sql("ALTER TABLE %s SET TBLPROPERTIES 
('write.parquet.shred-variants'='false')", toggleTable);
-    setVectorization(toggleTable, vectorized);
-
-    List<Row> rows = spark.table(toggleTable).select("id", 
"v").orderBy("id").collectAsList();
+    List<Row> rows = readSortedById(toggleTable, vectorized, 
ImmutableMap.of());
     assertThat(rows).hasSize(2);
     Variant v1 =
         new Variant(
@@ -536,9 +538,7 @@ public class TestSparkVariantRead extends TestBase {
 
     Table table = Spark3Util.loadIcebergTable(spark, noStatsTable);
     assertHasTypedValueSubtree(table);
-    setVectorization(noStatsTable, true);
-
-    List<Row> rows = spark.table(noStatsTable).select("id", 
"v").orderBy("id").collectAsList();
+    List<Row> rows = assertVectorizedMatchesRowReader(noStatsTable);
     assertThat(rows).hasSize(2);
     Variant v1 =
         new Variant(
@@ -580,26 +580,81 @@ public class TestSparkVariantRead extends TestBase {
   }
 
   @Test
-  void readMixedShreddedAndUnshreddedFiles()
+  void readShreddedEnabledByTableProperty()
       throws IOException, NoSuchTableException, ParseException {
-    String table = CATALOG + ".default.var_mixed_files";
+    String table = CATALOG + ".default.var_shredded_property";
     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]}'))",
+            + "TBLPROPERTIES ('format-version'='3', '%s'='true')",
+        table, TableProperties.PARQUET_SHRED_VARIANTS);
+    sql(
+        "INSERT INTO %s VALUES (1, parse_json('{\"a\": [1, 2]}')), (2, 
parse_json('{\"a\": [3]}'))",
         table);
 
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    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 readMixedObjectShreddedAndUnshreddedFiles()
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_mixed_object_files";
+    writeUnshreddedThenShreddedFile(
+        table, "{\"name\":\"bob\",\"age\":25}", 
"{\"name\":\"carol\",\"age\":41}");
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    assertThat(shreddedFiles(icebergTable)).containsExactlyInAnyOrder(false, 
true);
+    int variantId = icebergTable.schema().findField("v").fieldId();
+    try (CloseableIterable<FileScanTask> tasks =
+        icebergTable.newScan().includeColumnStats().planFiles()) {
+      assertThat(tasks)
+          .anyMatch(
+              task ->
+                  task.file().lowerBounds() != null
+                      && task.file().lowerBounds().containsKey(variantId));
+    }
+
+    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();
+    
assertThat(toVariant(rows.get(2)).getFieldByKey("name").getString()).isEqualTo("bob");
+    
assertThat(toVariant(rows.get(3)).getFieldByKey("age").getLong()).isEqualTo(41L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
+  @Test
+  void readShreddedIncrementalAppendScan() throws NoSuchTableException, 
ParseException {
+    String table = CATALOG + ".default.var_shredded_incremental";
+    writeUnshreddedThenShreddedFile(
+        table, "{\"name\":\"bob\",\"age\":25}", 
"{\"name\":\"carol\",\"age\":41}");
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    long unshreddedSnapshotId = icebergTable.currentSnapshot().parentId();
+    Map<String, String> incremental =
+        ImmutableMap.of(SparkReadOptions.START_SNAPSHOT_ID, 
String.valueOf(unshreddedSnapshotId));
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table, incremental);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(2L, 3L, 
4L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
+  @Test
+  void readMixedShreddedAndUnshreddedFiles()
+      throws IOException, NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_mixed_files";
+    writeUnshreddedThenShreddedFile(table, "{\"a\":[1,2]}", "{\"a\":[3]}");
+
     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);
@@ -648,6 +703,33 @@ public class TestSparkVariantRead extends TestBase {
     sql("DROP TABLE IF EXISTS %s", table);
   }
 
+  @Test
+  void readShreddedVariantAfterDelete() throws IOException, 
NoSuchTableException, ParseException {
+    String table = CATALOG + ".default.var_shredded_delete";
+    sql("DROP TABLE IF EXISTS %s", table);
+    sql(
+        "CREATE TABLE %s (id BIGINT, v VARIANT) USING iceberg "
+            + "TBLPROPERTIES ('format-version'='3', '%s'='%s')",
+        table, TableProperties.DELETE_MODE, 
RowLevelOperationMode.MERGE_ON_READ.modeName());
+    insertShredded(
+        "INSERT INTO %s SELECT /*+ COALESCE(1) */ * FROM ("
+            + "SELECT 1L AS id, parse_json('{\"name\":\"alice\",\"age\":30}') 
AS v "
+            + "UNION ALL SELECT 2L, 
parse_json('{\"name\":\"bob\",\"age\":25}') "
+            + "UNION ALL SELECT 3L, 
parse_json('{\"name\":\"carol\",\"age\":41}'))",
+        table);
+    sql("DELETE FROM %s WHERE id = 2", table);
+
+    Table icebergTable = Spark3Util.loadIcebergTable(spark, table);
+    assertHasTypedValueSubtree(icebergTable);
+    assertThat(icebergTable.currentSnapshot().summary())
+        .containsEntry(SnapshotSummary.ADDED_DVS_PROP, "1");
+
+    List<Row> rows = assertVectorizedMatchesRowReader(table);
+    assertThat(rows).extracting(row -> row.getLong(0)).containsExactly(1L, 3L);
+
+    sql("DROP TABLE IF EXISTS %s", table);
+  }
+
   private void setVectorization(boolean on) {
     sql(
         "ALTER TABLE %s SET TBLPROPERTIES 
('read.parquet.vectorization.enabled'='%s')",
@@ -679,13 +761,38 @@ public class TestSparkVariantRead extends TestBase {
     return false;
   }
 
+  private void writeUnshreddedThenShreddedFile(String table, String 
thirdValue, String fourthValue)
+      throws NoSuchTableException {
+    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('%s') "
+            + "UNION ALL SELECT 4L, parse_json('%s'))",
+        table, thirdValue, fourthValue);
+  }
+
   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);
+    return assertVectorizedMatchesRowReader(table, ImmutableMap.of());
+  }
+
+  private List<Row> assertVectorizedMatchesRowReader(
+      String table, Map<String, String> readOptions) {
+    List<Row> expected = readSortedById(table, false, readOptions);
+    List<Row> actual = readSortedById(table, true, readOptions);
 
     assertThat(actual).hasSameSizeAs(expected);
     for (int i = 0; i < expected.size(); i += 1) {
@@ -704,11 +811,12 @@ public class TestSparkVariantRead extends TestBase {
     return actual;
   }
 
-  private List<Row> readSortedById(String table, boolean vectorized) {
+  private List<Row> readSortedById(
+      String table, boolean vectorized, Map<String, String> readOptions) {
     setVectorization(table, vectorized);
+    Dataset<Row> df = 
spark.read().options(readOptions).table(table).select("id", "v");
     List<Row> rows = Lists.newArrayList();
-    SparkPlan plan =
-        executeAndKeepPlan(() -> rows.addAll(spark.table(table).select("id", 
"v").collectAsList()));
+    SparkPlan plan = executeAndKeepPlan(() -> rows.addAll(df.collectAsList()));
     assertColumnarScan(plan, vectorized);
 
     rows.sort(Comparator.comparingLong(row -> row.getLong(0)));

Reply via email to