anuragmantri commented on code in PR #14948:
URL: https://github.com/apache/iceberg/pull/14948#discussion_r3732106678


##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/MergingSortedRowDataReader.java:
##########
@@ -0,0 +1,331 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.source;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Objects;
+import org.apache.iceberg.Accessor;
+import org.apache.iceberg.Accessors;
+import org.apache.iceberg.BaseScanTaskGroup;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.ScanTaskGroup;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.apache.iceberg.SortOrderComparators;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.spark.SparkSchemaUtil;
+import org.apache.iceberg.spark.source.metrics.TaskNumDeletes;
+import org.apache.iceberg.spark.source.metrics.TaskNumSplits;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Exceptions;
+import org.apache.iceberg.util.SortedMerge;
+import org.apache.spark.rdd.InputFileBlockHolder;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.catalyst.ProjectingInternalRow;
+import org.apache.spark.sql.connector.metric.CustomTaskMetric;
+import org.apache.spark.sql.connector.read.PartitionReader;
+import org.apache.spark.sql.types.StructType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.collection.JavaConverters;
+
+/**
+ * A {@link PartitionReader} that reads multiple sorted files and merges them 
into a single sorted
+ * stream using a k-way heap merge ({@link SortedMerge}).
+ *
+ * <p>Every file in the task group must be written with the table's current 
sort order. Sort keys on
+ * nested fields are not supported.
+ */
+class MergingSortedRowDataReader implements PartitionReader<InternalRow> {
+  private static final Logger LOG = 
LoggerFactory.getLogger(MergingSortedRowDataReader.class);
+
+  private final CloseableGroup resources;
+  private final CloseableIterator<TaggedRow> mergedIterator;
+  private final List<RowDataReader> fileReaders;
+  // non-null only when sort key columns were added to the read schema beyond 
what Spark projected
+  private final ProjectingInternalRow projectingRow;
+  private InternalRow current;
+  private FileBlock currentBlock;
+
+  MergingSortedRowDataReader(SparkInputPartition partition) {
+    this(
+        partition.table(),
+        partition.io(),
+        partition.taskGroup(),
+        partition.projection(),
+        partition.isCaseSensitive(),
+        partition.cacheDeleteFilesOnExecutors());
+  }
+
+  MergingSortedRowDataReader(
+      Table table,
+      FileIO io,
+      ScanTaskGroup<FileScanTask> taskGroup,
+      Schema projection,
+      boolean caseSensitive,
+      boolean cacheDeleteFilesOnExecutors) {
+    SortOrder sortOrder = table.sortOrder();
+    int numFiles = taskGroup.tasks().size();
+
+    Preconditions.checkArgument(
+        sortOrder.isSorted(), "Cannot create merging reader for unsorted table 
%s", table.name());
+    Preconditions.checkArgument(
+        numFiles > 1, "Merging reader requires multiple files, got %s", 
numFiles);
+
+    int expectedOrderId = sortOrder.orderId();
+    Preconditions.checkArgument(
+        taskGroup.tasks().stream()
+            .allMatch(task -> Objects.equals(task.file().sortOrderId(), 
expectedOrderId)),
+        "Not all files in task group have the expected sort order %s",
+        expectedOrderId);
+
+    LOG.debug(
+        "Creating merging reader for {} files with sort order {} in table {}",
+        numFiles,
+        sortOrder.orderId(),
+        table.name());
+
+    // Augment the projected schema with any sort key columns Spark did not 
request so that
+    // SortOrderComparators can access every sort key field during the merge.
+    Schema mergeReadSchema = mergeReadSchema(projection, sortOrder, table);
+    this.projectingRow = buildProjectingRow(projection, mergeReadSchema);
+
+    this.resources = new CloseableGroup();
+    List<FileScanTask> tasks = Lists.newArrayList(taskGroup.tasks());
+    this.fileReaders =
+        tasks.stream()
+            .map(
+                task ->
+                    new RowDataReader(
+                        table,
+                        io,
+                        new BaseScanTaskGroup<>(ImmutableList.of(task)),
+                        mergeReadSchema,
+                        caseSensitive,
+                        cacheDeleteFilesOnExecutors))
+            .toList();
+    fileReaders.forEach(resources::addCloseable);
+    // Wrap each reader as a CloseableIterable and feed into SortedMerge.
+    List<CloseableIterable<TaggedRow>> fileIterables = 
Lists.newArrayListWithCapacity(tasks.size());
+    for (int i = 0; i < tasks.size(); i++) {
+      fileIterables.add(readerToIterable(fileReaders.get(i), tasks.get(i)));
+    }
+    Comparator<InternalRow> rowComparator = buildComparator(mergeReadSchema, 
sortOrder);
+    SortedMerge<TaggedRow> sortedMerge =
+        new SortedMerge<>((a, b) -> rowComparator.compare(a.row(), b.row()), 
fileIterables);
+    resources.addCloseable(sortedMerge);
+    boolean threw = true;
+    try {
+      this.mergedIterator = sortedMerge.iterator();
+      threw = false;
+    } finally {
+      if (threw) {
+        Exceptions.close(resources, true);
+      }
+    }
+  }
+
+  /**
+   * Adapts a {@link RowDataReader} to a {@link CloseableIterable} for use 
with {@link SortedMerge}.
+   *
+   * <p>Rows are copied on the way into the heap. {@link SortedMerge} advances 
an iterator before
+   * returning the value it just polled, so an uncopied row would be 
overwritten by the next read
+   * from the same file since Spark's Parquet and ORC readers reuse {@link 
InternalRow} containers.
+   * At most one row per file is held at a time, so the copy is bounded by the 
number of files.
+   */
+  private CloseableIterable<TaggedRow> readerToIterable(RowDataReader reader, 
FileScanTask task) {
+    FileBlock block = new FileBlock(task.file().location(), task.start(), 
task.length());
+    return CloseableIterable.withNoopClose(
+        () ->
+            new CloseableIterator<>() {
+              private boolean advanced = false;
+              private boolean hasNext = false;
+
+              @Override
+              public boolean hasNext() {
+                if (!advanced) {
+                  try {
+                    hasNext = reader.next();
+                    advanced = true;
+                  } catch (IOException e) {
+                    throw new UncheckedIOException("Failed to advance reader", 
e);
+                  }
+                }
+                return hasNext;
+              }
+
+              @Override
+              public TaggedRow next() {
+                if (!advanced) {
+                  hasNext();
+                }
+                advanced = false;
+                return new TaggedRow(reader.get().copy(), block);
+              }
+
+              @Override
+              public void close() {
+                // Readers are owned by the enclosing CloseableGroup, not by 
the merge. SortedMerge
+                // drops iterators that are empty on the first hasNext() 
without closing them, so a
+                // file whose rows are all deleted would otherwise leak. 
Closing here too would
+                // double-close every reader the merge does drain.
+              }
+            });
+  }
+
+  @Override
+  public boolean next() throws IOException {
+    if (!mergedIterator.hasNext()) {
+      return false;
+    }
+
+    TaggedRow tagged = mergedIterator.next();
+    // all rows from one task share a FileBlock instance, so identity is 
enough to detect a switch
+    // and avoid re-allocating the block holder entry on every row
+    if (tagged.block() != currentBlock) {
+      FileBlock block = tagged.block();
+      InputFileBlockHolder.set(block.filePath(), block.start(), 
block.length());
+      this.currentBlock = block;
+    }
+
+    InternalRow merged = tagged.row();
+    if (projectingRow == null) {
+      this.current = merged;
+    } else {
+      projectingRow.project(merged);
+      this.current = projectingRow;
+    }
+
+    return true;
+  }
+
+  @Override
+  public InternalRow get() {
+    return current;
+  }
+
+  @Override
+  public void close() throws IOException {
+    resources.close();
+  }
+
+  @Override
+  public CustomTaskMetric[] currentMetricsValues() {
+    long totalDeletes =
+        fileReaders.stream()
+            .flatMap(reader -> Arrays.stream(reader.currentMetricsValues()))
+            .filter(metric -> metric instanceof TaskNumDeletes)
+            .mapToLong(CustomTaskMetric::value)
+            .sum();
+    return new CustomTaskMetric[] {
+      new TaskNumSplits(fileReaders.size()), new TaskNumDeletes(totalDeletes)
+    };
+  }
+
+  /**
+   * Builds a comparator for merging {@link InternalRow}s by the given sort 
order. Each side wraps
+   * its row in its own reusable {@link InternalRowWrapper} so the two 
arguments stay distinct.
+   */
+  private static Comparator<InternalRow> buildComparator(
+      Schema mergeReadSchema, SortOrder sortOrder) {
+    StructType sparkSchema = SparkSchemaUtil.convert(mergeReadSchema);
+    Comparator<StructLike> keyComparator =
+        SortOrderComparators.forSchema(mergeReadSchema, sortOrder);
+    InternalRowWrapper left = new InternalRowWrapper(sparkSchema, 
mergeReadSchema.asStruct());
+    InternalRowWrapper right = new InternalRowWrapper(sparkSchema, 
mergeReadSchema.asStruct());
+    return (r1, r2) -> keyComparator.compare(left.wrap(r1), right.wrap(r2));
+  }
+
+  /**
+   * Returns a {@link ProjectingInternalRow} that remaps columns from the 
wider merge schema back to
+   * the requested projection, or {@code null} if no extra columns were added.
+   */
+  private static ProjectingInternalRow buildProjectingRow(Schema projection, 
Schema mergeSchema) {
+    if (projection.columns().size() == mergeSchema.columns().size()) {
+      return null;
+    }

Review Comment:
   Yes, the same. Done.



##########
spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestMergingSortedRowDataReader.java:
##########
@@ -0,0 +1,596 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.source;
+
+import static org.apache.iceberg.types.Types.NestedField.required;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import org.apache.iceberg.BaseScanTaskGroup;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.Files;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.ScanTaskGroup;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortOrder;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableUtil;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.data.FileHelpers;
+import org.apache.iceberg.data.GenericRecord;
+import org.apache.iceberg.data.Record;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.spark.TestBase;
+import org.apache.iceberg.transforms.Transform;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.spark.rdd.InputFileBlockHolder;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.mockito.Mockito;
+
+class TestMergingSortedRowDataReader extends TestBase {
+
+  private static final Schema SCHEMA =
+      new Schema(
+          required(1, "id", Types.IntegerType.get()), required(2, "data", 
Types.StringType.get()));
+
+  private static final PartitionSpec SPEC = PartitionSpec.unpartitioned();
+
+  private Table table;
+
+  @TempDir private Path temp;
+
+  @BeforeEach
+  void before() {
+    table = catalog.createTable(TableIdentifier.of("default", 
"test_merging_reader"), SCHEMA, SPEC);
+    table.replaceSortOrder().asc("id").commit();
+  }
+
+  @AfterEach
+  void after() {
+    catalog.dropTable(TableIdentifier.of("default", "test_merging_reader"));
+  }
+
+  @Test
+  void mergeTwoSortedFiles() throws IOException {
+    DataFile file1 = writeDataFile(record(1, "a"), record(3, "c"), record(5, 
"e"));
+    DataFile file2 = writeDataFile(record(2, "b"), record(4, "d"), record(6, 
"f"));
+
+    table.newAppend().appendFile(file1).appendFile(file2).commit();
+
+    List<InternalRow> rows = readMerged(table);
+
+    assertThat(extractIds(rows)).containsExactly(1, 2, 3, 4, 5, 6);
+  }
+
+  @Test
+  void mergeWithDuplicateKeys() throws IOException {
+    DataFile file1 = writeDataFile(record(1, "a"), record(2, "b"));
+    DataFile file2 = writeDataFile(record(1, "c"), record(2, "d"));
+    DataFile file3 = writeDataFile(record(1, "e"), record(3, "f"));
+
+    
table.newAppend().appendFile(file1).appendFile(file2).appendFile(file3).commit();
+
+    List<InternalRow> rows = readMerged(table);
+
+    assertThat(extractIds(rows)).containsExactly(1, 1, 1, 2, 2, 3);
+  }
+
+  @Test
+  void mergeDescendingOrder() throws IOException {
+    catalog.dropTable(TableIdentifier.of("default", "test_merging_reader"));
+    table = catalog.createTable(TableIdentifier.of("default", 
"test_merging_reader"), SCHEMA, SPEC);
+    table.replaceSortOrder().desc("id").commit();
+
+    DataFile file1 = writeDataFile(record(6, "f"), record(4, "d"));
+    DataFile file2 = writeDataFile(record(5, "e"), record(3, "c"), record(1, 
"a"));
+
+    table.newAppend().appendFile(file1).appendFile(file2).commit();
+
+    List<InternalRow> rows = readMerged(table);
+
+    assertThat(extractIds(rows)).containsExactly(6, 5, 4, 3, 1);
+  }
+
+  @Test
+  void mergeWithNulls() throws IOException {
+    Schema nullableSchema =
+        new Schema(
+            Types.NestedField.optional(1, "id", Types.IntegerType.get()),
+            required(2, "data", Types.StringType.get()));
+
+    catalog.dropTable(TableIdentifier.of("default", "test_merging_reader"));
+    table =
+        catalog.createTable(
+            TableIdentifier.of("default", "test_merging_reader"), 
nullableSchema, SPEC);
+    table.replaceSortOrder().asc("id").commit();
+
+    DataFile file1 = writeDataFile(nullRecord("x"), record(3, "c"));
+    DataFile file2 = writeDataFile(nullRecord("y"), record(1, "a"), record(2, 
"b"));
+
+    table.newAppend().appendFile(file1).appendFile(file2).commit();
+
+    List<InternalRow> rows = readMerged(table);
+
+    assertThat(rows).hasSize(5);
+    assertThat(rows.get(0).isNullAt(0)).isTrue();
+    assertThat(rows.get(1).isNullAt(0)).isTrue();
+    assertThat(extractIds(rows.subList(2, 5))).containsExactly(1, 2, 3);
+  }
+
+  @Test
+  void mergeThreeFiles() throws IOException {
+    DataFile file1 = writeDataFile(record(1, "a"), record(4, "d"), record(7, 
"g"));
+    DataFile file2 = writeDataFile(record(2, "b"), record(5, "e"), record(8, 
"h"));
+    DataFile file3 = writeDataFile(record(3, "c"), record(6, "f"), record(9, 
"i"));
+
+    
table.newAppend().appendFile(file1).appendFile(file2).appendFile(file3).commit();
+
+    List<InternalRow> rows = readMerged(table);
+
+    assertThat(extractIds(rows)).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9);
+  }
+
+  @Test
+  void mergeWithSortKeyNotInProjection() throws IOException {
+    DataFile file1 = writeDataFile(record(1, "a"), record(3, "c"), record(5, 
"e"));
+    DataFile file2 = writeDataFile(record(2, "b"), record(4, "d"), record(6, 
"f"));
+
+    table.newAppend().appendFile(file1).appendFile(file2).commit();
+
+    // Project only "data". The sort key "id" is missing from the projection, 
so it is added to
+    // the read schema for the merge comparator and stripped from the rows 
returned to Spark.
+    Schema dataOnly = table.schema().select("data");
+    List<InternalRow> rows = readMerged(table, dataOnly);
+
+    // Rows come back ordered by id even though id is not projected.
+    assertThat(extractData(rows, 0)).containsExactly("a", "b", "c", "d", "e", 
"f");
+    // Only the projected column is present in the returned rows.
+    assertThat(rows.get(0).numFields()).isEqualTo(1);
+  }
+
+  @Test
+  void mergeAfterSortOrderEvolution() throws IOException {
+    // Evolve the sort order from "id" to "data". The reader should merge by 
the current order.
+    table.replaceSortOrder().asc("data").commit();
+
+    DataFile file1 = writeDataFile(record(5, "a"), record(3, "c"), record(1, 
"e"));
+    DataFile file2 = writeDataFile(record(6, "b"), record(4, "d"), record(2, 
"f"));
+
+    table.newAppend().appendFile(file1).appendFile(file2).commit();
+
+    List<InternalRow> rows = readMerged(table);
+
+    // Ordered by data, not by id.
+    assertThat(extractData(rows, 1)).containsExactly("a", "b", "c", "d", "e", 
"f");
+  }
+
+  @Test
+  void mergeWithStructColumnNotInSortOrder() throws IOException {
+    catalog.dropTable(TableIdentifier.of("default", "test_merging_reader"));
+
+    Schema schemaWithStruct =
+        new Schema(
+            required(1, "id", Types.IntegerType.get()),
+            required(2, "data", Types.StringType.get()),
+            required(
+                4, "location", Types.StructType.of(required(5, "city", 
Types.StringType.get()))));
+
+    table =
+        catalog.createTable(
+            TableIdentifier.of("default", "test_merging_reader"), 
schemaWithStruct, SPEC);
+    table.replaceSortOrder().asc("id").commit();
+
+    DataFile file1 = writeDataFile(structRecord(1, "a", "NYC"), 
structRecord(3, "c", "SFO"));
+    DataFile file2 = writeDataFile(structRecord(2, "b", "LAX"), 
structRecord(4, "d", "SEA"));
+
+    table.newAppend().appendFile(file1).appendFile(file2).commit();
+
+    // Project the struct but not the sort key, so the merge schema is widened 
around a struct.
+    Schema projection = table.schema().select("location");
+    List<InternalRow> rows = readMerged(table, projection);
+
+    assertThat(rows.get(0).numFields()).isEqualTo(1);
+    assertThat(rows.stream().map(row -> row.getStruct(0, 
1).getUTF8String(0).toString()).toList())
+        .containsExactly("NYC", "LAX", "SFO", "SEA");
+  }
+
+  @Test
+  void mergeRejectsStaleSortOrderId() throws IOException {
+    SortOrder oldSortOrder = table.sortOrder();
+
+    // file1 keeps the old order id, file2 is written with the evolved one
+    DataFile file1 =
+        DataFiles.builder(table.spec())
+            .copy(writeRecords(record(1, "a"), record(3, "c")))
+            .withSortOrder(oldSortOrder)
+            .build();
+
+    table.replaceSortOrder().asc("data").commit();
+    DataFile file2 = writeDataFile(record(2, "b"), record(4, "d"));
+
+    table.newAppend().appendFile(file1).appendFile(file2).commit();
+
+    assertThatThrownBy(() -> readMerged(table))
+        .isInstanceOf(IllegalArgumentException.class)
+        .hasMessageContaining("Not all files in task group have the expected 
sort order");
+  }
+
+  @Test
+  void mergeRejectsMissingSortOrderId() {
+    // sort_order_id is optional in the manifest schema, so a file may report 
null
+    ScanTaskGroup<FileScanTask> taskGroup =
+        taskGroupWithSortOrderIds(table.sortOrder().orderId(), null);
+
+    assertThatThrownBy(
+            () ->
+                new MergingSortedRowDataReader(
+                    table, table.io(), taskGroup, table.schema(), true, false))
+        .isInstanceOf(IllegalArgumentException.class)
+        .hasMessageContaining("Not all files in task group have the expected 
sort order");
+  }
+
+  @Test
+  void mergeRejectsSingleFile() throws IOException {
+    DataFile file1 = writeDataFile(record(1, "a"), record(3, "c"));
+
+    table.newAppend().appendFile(file1).commit();
+    table.refresh();
+
+    BaseScanTaskGroup<FileScanTask> taskGroup = new 
BaseScanTaskGroup<>(planFiles(table));
+
+    assertThatThrownBy(
+            () ->
+                new MergingSortedRowDataReader(
+                    table, table.io(), taskGroup, table.schema(), true, false))
+        .isInstanceOf(IllegalArgumentException.class)
+        .hasMessageContaining("Merging reader requires multiple files, got 1");
+  }
+
+  @Test
+  void mergeRejectsUnsortedTable() throws IOException {
+    catalog.dropTable(TableIdentifier.of("default", "test_merging_reader"));
+    table = catalog.createTable(TableIdentifier.of("default", 
"test_merging_reader"), SCHEMA, SPEC);
+
+    DataFile file1 = writeDataFile(record(1, "a"), record(3, "c"));
+    DataFile file2 = writeDataFile(record(2, "b"), record(4, "d"));
+
+    table.newAppend().appendFile(file1).appendFile(file2).commit();
+    table.refresh();
+
+    BaseScanTaskGroup<FileScanTask> taskGroup = new 
BaseScanTaskGroup<>(planFiles(table));
+
+    assertThatThrownBy(
+            () ->
+                new MergingSortedRowDataReader(
+                    table, table.io(), taskGroup, table.schema(), true, false))
+        .isInstanceOf(IllegalArgumentException.class)
+        .hasMessageContaining("Cannot create merging reader for unsorted 
table");
+  }
+
+  @Test
+  void mergeWithFileFullyRemovedByDeletes() throws IOException {

Review Comment:
   Added a test



##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/MergingSortedRowDataReader.java:
##########
@@ -0,0 +1,331 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.source;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Objects;
+import org.apache.iceberg.Accessor;
+import org.apache.iceberg.Accessors;
+import org.apache.iceberg.BaseScanTaskGroup;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.ScanTaskGroup;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.apache.iceberg.SortOrderComparators;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.spark.SparkSchemaUtil;
+import org.apache.iceberg.spark.source.metrics.TaskNumDeletes;
+import org.apache.iceberg.spark.source.metrics.TaskNumSplits;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Exceptions;
+import org.apache.iceberg.util.SortedMerge;
+import org.apache.spark.rdd.InputFileBlockHolder;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.catalyst.ProjectingInternalRow;
+import org.apache.spark.sql.connector.metric.CustomTaskMetric;
+import org.apache.spark.sql.connector.read.PartitionReader;
+import org.apache.spark.sql.types.StructType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.collection.JavaConverters;
+
+/**
+ * A {@link PartitionReader} that reads multiple sorted files and merges them 
into a single sorted
+ * stream using a k-way heap merge ({@link SortedMerge}).
+ *
+ * <p>Every file in the task group must be written with the table's current 
sort order. Sort keys on
+ * nested fields are not supported.
+ */
+class MergingSortedRowDataReader implements PartitionReader<InternalRow> {
+  private static final Logger LOG = 
LoggerFactory.getLogger(MergingSortedRowDataReader.class);
+
+  private final CloseableGroup resources;
+  private final CloseableIterator<TaggedRow> mergedIterator;
+  private final List<RowDataReader> fileReaders;
+  // non-null only when sort key columns were added to the read schema beyond 
what Spark projected
+  private final ProjectingInternalRow projectingRow;
+  private InternalRow current;
+  private FileBlock currentBlock;
+
+  MergingSortedRowDataReader(SparkInputPartition partition) {
+    this(
+        partition.table(),
+        partition.io(),
+        partition.taskGroup(),
+        partition.projection(),
+        partition.isCaseSensitive(),
+        partition.cacheDeleteFilesOnExecutors());
+  }
+
+  MergingSortedRowDataReader(
+      Table table,
+      FileIO io,
+      ScanTaskGroup<FileScanTask> taskGroup,
+      Schema projection,
+      boolean caseSensitive,
+      boolean cacheDeleteFilesOnExecutors) {
+    SortOrder sortOrder = table.sortOrder();
+    int numFiles = taskGroup.tasks().size();
+
+    Preconditions.checkArgument(
+        sortOrder.isSorted(), "Cannot create merging reader for unsorted table 
%s", table.name());
+    Preconditions.checkArgument(
+        numFiles > 1, "Merging reader requires multiple files, got %s", 
numFiles);
+
+    int expectedOrderId = sortOrder.orderId();
+    Preconditions.checkArgument(
+        taskGroup.tasks().stream()
+            .allMatch(task -> Objects.equals(task.file().sortOrderId(), 
expectedOrderId)),
+        "Not all files in task group have the expected sort order %s",
+        expectedOrderId);
+
+    LOG.debug(
+        "Creating merging reader for {} files with sort order {} in table {}",
+        numFiles,
+        sortOrder.orderId(),
+        table.name());
+
+    // Augment the projected schema with any sort key columns Spark did not 
request so that
+    // SortOrderComparators can access every sort key field during the merge.
+    Schema mergeReadSchema = mergeReadSchema(projection, sortOrder, table);
+    this.projectingRow = buildProjectingRow(projection, mergeReadSchema);
+
+    this.resources = new CloseableGroup();

Review Comment:
   Done.



##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/MergingSortedRowDataReader.java:
##########
@@ -0,0 +1,331 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.source;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Objects;
+import org.apache.iceberg.Accessor;
+import org.apache.iceberg.Accessors;
+import org.apache.iceberg.BaseScanTaskGroup;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.ScanTaskGroup;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.apache.iceberg.SortOrderComparators;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.spark.SparkSchemaUtil;
+import org.apache.iceberg.spark.source.metrics.TaskNumDeletes;
+import org.apache.iceberg.spark.source.metrics.TaskNumSplits;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Exceptions;
+import org.apache.iceberg.util.SortedMerge;
+import org.apache.spark.rdd.InputFileBlockHolder;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.catalyst.ProjectingInternalRow;
+import org.apache.spark.sql.connector.metric.CustomTaskMetric;
+import org.apache.spark.sql.connector.read.PartitionReader;
+import org.apache.spark.sql.types.StructType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.collection.JavaConverters;
+
+/**
+ * A {@link PartitionReader} that reads multiple sorted files and merges them 
into a single sorted
+ * stream using a k-way heap merge ({@link SortedMerge}).
+ *
+ * <p>Every file in the task group must be written with the table's current 
sort order. Sort keys on
+ * nested fields are not supported.
+ */
+class MergingSortedRowDataReader implements PartitionReader<InternalRow> {
+  private static final Logger LOG = 
LoggerFactory.getLogger(MergingSortedRowDataReader.class);
+
+  private final CloseableGroup resources;
+  private final CloseableIterator<TaggedRow> mergedIterator;
+  private final List<RowDataReader> fileReaders;
+  // non-null only when sort key columns were added to the read schema beyond 
what Spark projected
+  private final ProjectingInternalRow projectingRow;
+  private InternalRow current;
+  private FileBlock currentBlock;
+
+  MergingSortedRowDataReader(SparkInputPartition partition) {
+    this(
+        partition.table(),
+        partition.io(),
+        partition.taskGroup(),
+        partition.projection(),
+        partition.isCaseSensitive(),
+        partition.cacheDeleteFilesOnExecutors());
+  }
+
+  MergingSortedRowDataReader(
+      Table table,
+      FileIO io,
+      ScanTaskGroup<FileScanTask> taskGroup,
+      Schema projection,
+      boolean caseSensitive,
+      boolean cacheDeleteFilesOnExecutors) {
+    SortOrder sortOrder = table.sortOrder();
+    int numFiles = taskGroup.tasks().size();
+
+    Preconditions.checkArgument(
+        sortOrder.isSorted(), "Cannot create merging reader for unsorted table 
%s", table.name());
+    Preconditions.checkArgument(
+        numFiles > 1, "Merging reader requires multiple files, got %s", 
numFiles);
+
+    int expectedOrderId = sortOrder.orderId();
+    Preconditions.checkArgument(
+        taskGroup.tasks().stream()
+            .allMatch(task -> Objects.equals(task.file().sortOrderId(), 
expectedOrderId)),
+        "Not all files in task group have the expected sort order %s",
+        expectedOrderId);
+
+    LOG.debug(
+        "Creating merging reader for {} files with sort order {} in table {}",
+        numFiles,
+        sortOrder.orderId(),
+        table.name());
+
+    // Augment the projected schema with any sort key columns Spark did not 
request so that
+    // SortOrderComparators can access every sort key field during the merge.
+    Schema mergeReadSchema = mergeReadSchema(projection, sortOrder, table);
+    this.projectingRow = buildProjectingRow(projection, mergeReadSchema);
+
+    this.resources = new CloseableGroup();
+    List<FileScanTask> tasks = Lists.newArrayList(taskGroup.tasks());
+    this.fileReaders =
+        tasks.stream()
+            .map(
+                task ->
+                    new RowDataReader(
+                        table,
+                        io,
+                        new BaseScanTaskGroup<>(ImmutableList.of(task)),
+                        mergeReadSchema,
+                        caseSensitive,
+                        cacheDeleteFilesOnExecutors))
+            .toList();
+    fileReaders.forEach(resources::addCloseable);
+    // Wrap each reader as a CloseableIterable and feed into SortedMerge.
+    List<CloseableIterable<TaggedRow>> fileIterables = 
Lists.newArrayListWithCapacity(tasks.size());
+    for (int i = 0; i < tasks.size(); i++) {
+      fileIterables.add(readerToIterable(fileReaders.get(i), tasks.get(i)));
+    }
+    Comparator<InternalRow> rowComparator = buildComparator(mergeReadSchema, 
sortOrder);
+    SortedMerge<TaggedRow> sortedMerge =
+        new SortedMerge<>((a, b) -> rowComparator.compare(a.row(), b.row()), 
fileIterables);
+    resources.addCloseable(sortedMerge);
+    boolean threw = true;
+    try {
+      this.mergedIterator = sortedMerge.iterator();
+      threw = false;
+    } finally {
+      if (threw) {
+        Exceptions.close(resources, true);
+      }
+    }
+  }
+
+  /**
+   * Adapts a {@link RowDataReader} to a {@link CloseableIterable} for use 
with {@link SortedMerge}.
+   *
+   * <p>Rows are copied on the way into the heap. {@link SortedMerge} advances 
an iterator before
+   * returning the value it just polled, so an uncopied row would be 
overwritten by the next read
+   * from the same file since Spark's Parquet and ORC readers reuse {@link 
InternalRow} containers.
+   * At most one row per file is held at a time, so the copy is bounded by the 
number of files.
+   */
+  private CloseableIterable<TaggedRow> readerToIterable(RowDataReader reader, 
FileScanTask task) {
+    FileBlock block = new FileBlock(task.file().location(), task.start(), 
task.length());
+    return CloseableIterable.withNoopClose(
+        () ->
+            new CloseableIterator<>() {
+              private boolean advanced = false;
+              private boolean hasNext = false;
+
+              @Override
+              public boolean hasNext() {
+                if (!advanced) {
+                  try {
+                    hasNext = reader.next();
+                    advanced = true;
+                  } catch (IOException e) {
+                    throw new UncheckedIOException("Failed to advance reader", 
e);
+                  }
+                }
+                return hasNext;
+              }
+
+              @Override
+              public TaggedRow next() {
+                if (!advanced) {
+                  hasNext();
+                }
+                advanced = false;
+                return new TaggedRow(reader.get().copy(), block);
+              }
+
+              @Override
+              public void close() {
+                // Readers are owned by the enclosing CloseableGroup, not by 
the merge. SortedMerge
+                // drops iterators that are empty on the first hasNext() 
without closing them, so a
+                // file whose rows are all deleted would otherwise leak. 
Closing here too would
+                // double-close every reader the merge does drain.
+              }
+            });
+  }
+
+  @Override
+  public boolean next() throws IOException {
+    if (!mergedIterator.hasNext()) {
+      return false;
+    }
+
+    TaggedRow tagged = mergedIterator.next();
+    // all rows from one task share a FileBlock instance, so identity is 
enough to detect a switch
+    // and avoid re-allocating the block holder entry on every row
+    if (tagged.block() != currentBlock) {
+      FileBlock block = tagged.block();
+      InputFileBlockHolder.set(block.filePath(), block.start(), 
block.length());
+      this.currentBlock = block;
+    }
+
+    InternalRow merged = tagged.row();
+    if (projectingRow == null) {
+      this.current = merged;
+    } else {
+      projectingRow.project(merged);
+      this.current = projectingRow;
+    }
+
+    return true;
+  }
+
+  @Override
+  public InternalRow get() {
+    return current;
+  }
+
+  @Override
+  public void close() throws IOException {
+    resources.close();
+  }
+
+  @Override
+  public CustomTaskMetric[] currentMetricsValues() {
+    long totalDeletes =
+        fileReaders.stream()
+            .flatMap(reader -> Arrays.stream(reader.currentMetricsValues()))
+            .filter(metric -> metric instanceof TaskNumDeletes)
+            .mapToLong(CustomTaskMetric::value)
+            .sum();
+    return new CustomTaskMetric[] {
+      new TaskNumSplits(fileReaders.size()), new TaskNumDeletes(totalDeletes)
+    };
+  }
+
+  /**
+   * Builds a comparator for merging {@link InternalRow}s by the given sort 
order. Each side wraps
+   * its row in its own reusable {@link InternalRowWrapper} so the two 
arguments stay distinct.
+   */
+  private static Comparator<InternalRow> buildComparator(
+      Schema mergeReadSchema, SortOrder sortOrder) {
+    StructType sparkSchema = SparkSchemaUtil.convert(mergeReadSchema);
+    Comparator<StructLike> keyComparator =
+        SortOrderComparators.forSchema(mergeReadSchema, sortOrder);

Review Comment:
   Good catch, I looked at this more. In the merging reader, we are comparing 
the output of the transforms. So only impacted case seems to be 
`identity(UUID)`. I added a pre-condition to ensure the result of the transform 
cannot be UUID. But the actual check should be upstream when creating the 
`MergingSortedRowReader`. I will add that check in the wiring PR 
https://github.com/apache/iceberg/pull/16750



##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/MergingSortedRowDataReader.java:
##########
@@ -0,0 +1,331 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.source;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Objects;
+import org.apache.iceberg.Accessor;
+import org.apache.iceberg.Accessors;
+import org.apache.iceberg.BaseScanTaskGroup;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.ScanTaskGroup;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.apache.iceberg.SortOrderComparators;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.spark.SparkSchemaUtil;
+import org.apache.iceberg.spark.source.metrics.TaskNumDeletes;
+import org.apache.iceberg.spark.source.metrics.TaskNumSplits;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Exceptions;
+import org.apache.iceberg.util.SortedMerge;
+import org.apache.spark.rdd.InputFileBlockHolder;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.catalyst.ProjectingInternalRow;
+import org.apache.spark.sql.connector.metric.CustomTaskMetric;
+import org.apache.spark.sql.connector.read.PartitionReader;
+import org.apache.spark.sql.types.StructType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.collection.JavaConverters;
+
+/**
+ * A {@link PartitionReader} that reads multiple sorted files and merges them 
into a single sorted
+ * stream using a k-way heap merge ({@link SortedMerge}).
+ *
+ * <p>Every file in the task group must be written with the table's current 
sort order. Sort keys on
+ * nested fields are not supported.
+ */
+class MergingSortedRowDataReader implements PartitionReader<InternalRow> {
+  private static final Logger LOG = 
LoggerFactory.getLogger(MergingSortedRowDataReader.class);
+
+  private final CloseableGroup resources;
+  private final CloseableIterator<TaggedRow> mergedIterator;
+  private final List<RowDataReader> fileReaders;
+  // non-null only when sort key columns were added to the read schema beyond 
what Spark projected
+  private final ProjectingInternalRow projectingRow;
+  private InternalRow current;
+  private FileBlock currentBlock;
+
+  MergingSortedRowDataReader(SparkInputPartition partition) {
+    this(
+        partition.table(),
+        partition.io(),
+        partition.taskGroup(),
+        partition.projection(),
+        partition.isCaseSensitive(),
+        partition.cacheDeleteFilesOnExecutors());
+  }
+
+  MergingSortedRowDataReader(
+      Table table,
+      FileIO io,
+      ScanTaskGroup<FileScanTask> taskGroup,
+      Schema projection,
+      boolean caseSensitive,
+      boolean cacheDeleteFilesOnExecutors) {
+    SortOrder sortOrder = table.sortOrder();
+    int numFiles = taskGroup.tasks().size();
+
+    Preconditions.checkArgument(
+        sortOrder.isSorted(), "Cannot create merging reader for unsorted table 
%s", table.name());
+    Preconditions.checkArgument(
+        numFiles > 1, "Merging reader requires multiple files, got %s", 
numFiles);
+
+    int expectedOrderId = sortOrder.orderId();
+    Preconditions.checkArgument(
+        taskGroup.tasks().stream()
+            .allMatch(task -> Objects.equals(task.file().sortOrderId(), 
expectedOrderId)),
+        "Not all files in task group have the expected sort order %s",
+        expectedOrderId);
+
+    LOG.debug(
+        "Creating merging reader for {} files with sort order {} in table {}",
+        numFiles,
+        sortOrder.orderId(),
+        table.name());
+
+    // Augment the projected schema with any sort key columns Spark did not 
request so that
+    // SortOrderComparators can access every sort key field during the merge.
+    Schema mergeReadSchema = mergeReadSchema(projection, sortOrder, table);
+    this.projectingRow = buildProjectingRow(projection, mergeReadSchema);
+
+    this.resources = new CloseableGroup();
+    List<FileScanTask> tasks = Lists.newArrayList(taskGroup.tasks());
+    this.fileReaders =
+        tasks.stream()
+            .map(
+                task ->
+                    new RowDataReader(
+                        table,
+                        io,
+                        new BaseScanTaskGroup<>(ImmutableList.of(task)),
+                        mergeReadSchema,
+                        caseSensitive,
+                        cacheDeleteFilesOnExecutors))
+            .toList();
+    fileReaders.forEach(resources::addCloseable);
+    // Wrap each reader as a CloseableIterable and feed into SortedMerge.
+    List<CloseableIterable<TaggedRow>> fileIterables = 
Lists.newArrayListWithCapacity(tasks.size());
+    for (int i = 0; i < tasks.size(); i++) {
+      fileIterables.add(readerToIterable(fileReaders.get(i), tasks.get(i)));
+    }
+    Comparator<InternalRow> rowComparator = buildComparator(mergeReadSchema, 
sortOrder);
+    SortedMerge<TaggedRow> sortedMerge =
+        new SortedMerge<>((a, b) -> rowComparator.compare(a.row(), b.row()), 
fileIterables);
+    resources.addCloseable(sortedMerge);
+    boolean threw = true;
+    try {
+      this.mergedIterator = sortedMerge.iterator();
+      threw = false;
+    } finally {
+      if (threw) {
+        Exceptions.close(resources, true);
+      }
+    }
+  }
+
+  /**
+   * Adapts a {@link RowDataReader} to a {@link CloseableIterable} for use 
with {@link SortedMerge}.
+   *
+   * <p>Rows are copied on the way into the heap. {@link SortedMerge} advances 
an iterator before
+   * returning the value it just polled, so an uncopied row would be 
overwritten by the next read
+   * from the same file since Spark's Parquet and ORC readers reuse {@link 
InternalRow} containers.
+   * At most one row per file is held at a time, so the copy is bounded by the 
number of files.
+   */
+  private CloseableIterable<TaggedRow> readerToIterable(RowDataReader reader, 
FileScanTask task) {
+    FileBlock block = new FileBlock(task.file().location(), task.start(), 
task.length());
+    return CloseableIterable.withNoopClose(
+        () ->
+            new CloseableIterator<>() {
+              private boolean advanced = false;
+              private boolean hasNext = false;
+
+              @Override
+              public boolean hasNext() {
+                if (!advanced) {
+                  try {
+                    hasNext = reader.next();
+                    advanced = true;
+                  } catch (IOException e) {
+                    throw new UncheckedIOException("Failed to advance reader", 
e);
+                  }
+                }
+                return hasNext;
+              }
+
+              @Override
+              public TaggedRow next() {
+                if (!advanced) {
+                  hasNext();
+                }
+                advanced = false;
+                return new TaggedRow(reader.get().copy(), block);
+              }
+
+              @Override
+              public void close() {
+                // Readers are owned by the enclosing CloseableGroup, not by 
the merge. SortedMerge
+                // drops iterators that are empty on the first hasNext() 
without closing them, so a
+                // file whose rows are all deleted would otherwise leak. 
Closing here too would
+                // double-close every reader the merge does drain.
+              }
+            });
+  }
+
+  @Override
+  public boolean next() throws IOException {
+    if (!mergedIterator.hasNext()) {
+      return false;
+    }
+
+    TaggedRow tagged = mergedIterator.next();
+    // all rows from one task share a FileBlock instance, so identity is 
enough to detect a switch
+    // and avoid re-allocating the block holder entry on every row
+    if (tagged.block() != currentBlock) {
+      FileBlock block = tagged.block();
+      InputFileBlockHolder.set(block.filePath(), block.start(), 
block.length());
+      this.currentBlock = block;
+    }
+
+    InternalRow merged = tagged.row();
+    if (projectingRow == null) {
+      this.current = merged;
+    } else {
+      projectingRow.project(merged);
+      this.current = projectingRow;
+    }
+
+    return true;
+  }
+
+  @Override
+  public InternalRow get() {
+    return current;
+  }
+
+  @Override
+  public void close() throws IOException {
+    resources.close();
+  }
+
+  @Override
+  public CustomTaskMetric[] currentMetricsValues() {
+    long totalDeletes =
+        fileReaders.stream()
+            .flatMap(reader -> Arrays.stream(reader.currentMetricsValues()))
+            .filter(metric -> metric instanceof TaskNumDeletes)
+            .mapToLong(CustomTaskMetric::value)
+            .sum();
+    return new CustomTaskMetric[] {
+      new TaskNumSplits(fileReaders.size()), new TaskNumDeletes(totalDeletes)
+    };
+  }
+
+  /**
+   * Builds a comparator for merging {@link InternalRow}s by the given sort 
order. Each side wraps
+   * its row in its own reusable {@link InternalRowWrapper} so the two 
arguments stay distinct.
+   */
+  private static Comparator<InternalRow> buildComparator(
+      Schema mergeReadSchema, SortOrder sortOrder) {
+    StructType sparkSchema = SparkSchemaUtil.convert(mergeReadSchema);
+    Comparator<StructLike> keyComparator =
+        SortOrderComparators.forSchema(mergeReadSchema, sortOrder);
+    InternalRowWrapper left = new InternalRowWrapper(sparkSchema, 
mergeReadSchema.asStruct());
+    InternalRowWrapper right = new InternalRowWrapper(sparkSchema, 
mergeReadSchema.asStruct());
+    return (r1, r2) -> keyComparator.compare(left.wrap(r1), right.wrap(r2));
+  }
+
+  /**
+   * Returns a {@link ProjectingInternalRow} that remaps columns from the 
wider merge schema back to
+   * the requested projection, or {@code null} if no extra columns were added.
+   */
+  private static ProjectingInternalRow buildProjectingRow(Schema projection, 
Schema mergeSchema) {
+    if (projection.columns().size() == mergeSchema.columns().size()) {
+      return null;
+    }
+
+    List<Object> positions = 
Lists.newArrayListWithCapacity(projection.columns().size());
+    for (Types.NestedField column : projection.columns()) {
+      Accessor<StructLike> accessor = 
mergeSchema.accessorForField(column.fieldId());
+      Preconditions.checkArgument(
+          accessor != null,
+          "Cannot find projected field id %s in merge read schema",
+          column.fieldId());
+      positions.add(Accessors.toPosition(accessor));
+    }
+
+    StructType sparkSchema = SparkSchemaUtil.convert(projection);
+    return new ProjectingInternalRow(sparkSchema, 
JavaConverters.asScala(positions).toIndexedSeq());
+  }
+
+  /**
+   * Returns the schema to use when reading each file. This is the requested 
{@code projection}
+   * augmented with any sort key columns that are not already present, so the 
merge comparator can
+   * access every sort key field regardless of what Spark projected.
+   */
+  private static Schema mergeReadSchema(Schema projection, SortOrder 
sortOrder, Table table) {
+    Schema tableSchema = table.schema();
+    List<Types.NestedField> missingFields = Lists.newArrayList();
+
+    for (SortField sortField : sortOrder.fields()) {
+      int fieldId = sortField.sourceId();
+      Types.NestedField tableField = tableSchema.findField(fieldId);
+      Preconditions.checkArgument(
+          tableField != null,
+          "Cannot find sort field id %s in schema of table %s",
+          fieldId,
+          table.name());
+      Preconditions.checkArgument(
+          TypeUtil.ancestorFields(tableSchema, fieldId).isEmpty(),

Review Comment:
   Done.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to