dramaticlly commented on code in PR #14948: URL: https://github.com/apache/iceberg/pull/14948#discussion_r4099753295
########## spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/MergingSortedRowDataReader.java: ########## @@ -0,0 +1,383 @@ +/* + * 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.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.Type; +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.catalyst.expressions.UnsafeProjection; +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.immutable.Range; + +/** + * 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 have the same sort order. A sort key on a nested field is + * not supported if that field is not in the requested projection. + */ +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; + 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) { + List<FileScanTask> tasks = Lists.newArrayList(taskGroup.tasks()); + int numFiles = tasks.size(); + + Preconditions.checkArgument( + numFiles > 1, "Merging reader requires multiple files, got %s", numFiles); + + Integer expectedOrderId = tasks.get(0).file().sortOrderId(); + Preconditions.checkArgument( + expectedOrderId != null && expectedOrderId != SortOrder.unsorted().orderId(), + "Merging reader requires sorted files, got sort order %s", + expectedOrderId); + Preconditions.checkArgument( + tasks.stream().allMatch(task -> Objects.equals(task.file().sortOrderId(), expectedOrderId)), + "Not all files in task group have the expected sort order %s", + expectedOrderId); + + SortOrder sortOrder = table.sortOrders().get(expectedOrderId); + Preconditions.checkArgument( + sortOrder != null, "Cannot find sort order %s in table %s", expectedOrderId, table.name()); + + LOG.debug( + "Creating merging reader for {} files with sort order {} in table {}", + numFiles, + expectedOrderId, + 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); + UnsafeProjection deepCopyProjection = + UnsafeProjection.create(SparkSchemaUtil.convert(mergeReadSchema)); + + this.resources = new CloseableGroup(); + // The group holds one reader per file plus the merge. Avoid leaking resources when close() + // failure on one resource is called. + resources.setSuppressCloseFailure(true); + this.fileReaders = + tasks.stream() + .map( + task -> + new RowDataReader( Review Comment: RowDataReader closes each file before opening the next, but this mergingSortedRowDataReader can hold multiple connection until the merge finishes.0 So this might subject to connection exhaustion, especially for small parquet files. The iceberg read split size is 128M and there's also 4M file open cost, so we shall not hold more than 32 of such. I am wondering if worth capping how many files one merge can open at once. ? -- 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]
