pvary commented on code in PR #14435: URL: https://github.com/apache/iceberg/pull/14435#discussion_r2619794558
########## parquet/src/main/java/org/apache/iceberg/parquet/ParquetFileMerger.java: ########## @@ -0,0 +1,634 @@ +/* + * 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.parquet; + +import static java.util.Collections.emptyMap; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.List; +import java.util.Map; +import java.util.function.LongUnaryOperator; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.DataFile; +import org.apache.iceberg.DataFiles; +import org.apache.iceberg.FileFormat; +import org.apache.iceberg.MetadataColumns; +import org.apache.iceberg.Metrics; +import org.apache.iceberg.MetricsConfig; +import org.apache.iceberg.PartitionSpec; +import org.apache.iceberg.StructLike; +import org.apache.iceberg.hadoop.HadoopOutputFile; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.io.InputFile; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.io.SeekableInputStream; +import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.types.Conversions; +import org.apache.iceberg.types.Types.LongType; +import org.apache.parquet.bytes.BytesInput; +import org.apache.parquet.bytes.DirectByteBufferAllocator; +import org.apache.parquet.bytes.HeapByteBufferAllocator; +import org.apache.parquet.column.ColumnDescriptor; +import org.apache.parquet.column.Encoding; +import org.apache.parquet.column.ParquetProperties; +import org.apache.parquet.column.statistics.LongStatistics; +import org.apache.parquet.column.statistics.Statistics; +import org.apache.parquet.column.values.ValuesWriter; +import org.apache.parquet.column.values.delta.DeltaBinaryPackingValuesWriterForLong; +import org.apache.parquet.crypto.InternalFileEncryptor; +import org.apache.parquet.hadoop.CodecFactory; +import org.apache.parquet.hadoop.ParquetFileReader; +import org.apache.parquet.hadoop.ParquetFileWriter; +import org.apache.parquet.hadoop.ParquetOutputFormat; +import org.apache.parquet.hadoop.metadata.BlockMetaData; +import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData; +import org.apache.parquet.hadoop.metadata.CompressionCodecName; +import org.apache.parquet.io.DelegatingSeekableInputStream; +import org.apache.parquet.schema.MessageType; +import org.apache.parquet.schema.PrimitiveType; +import org.apache.parquet.schema.Type; +import org.apache.parquet.schema.Types; + +/** + * Utility class for performing strict schema validation and merging of Parquet files at the + * row-group level. + * + * <p>This class ensures that all input files have identical Parquet schemas before merging. The + * merge operation is performed by copying row groups directly without + * serialization/deserialization, providing significant performance benefits over traditional + * read-rewrite approaches. + * + * <p>This class works with any Iceberg FileIO implementation (HadoopFileIO, S3FileIO, GCSFileIO, + * etc.), making it cloud-agnostic. + * + * <p>TODO: Encrypted tables are not supported + * + * <p>Key features: + * + * <ul> + * <li>Row group merging without deserialization using {@link ParquetFileWriter#appendFile} + * <li>Strict schema validation - all files must have identical {@link MessageType} + * <li>Metadata merging for Iceberg-specific footer data + * <li>Works with any FileIO implementation (local, S3, GCS, Azure, etc.) + * </ul> + * + * <p>Restrictions: + * + * <ul> + * <li>All files must have compatible schemas (identical {@link MessageType}) + * <li>Files must not be encrypted + * <li>Files must not have associated delete files or delete vectors + * <li>Table must not have a sort order (including z-ordered tables) + * </ul> + * + * <p>Typical usage: + * + * <pre> + * ValidationResult result = ParquetFileMerger.readAndValidateSchema(inputFiles); + * if (result != null) { + * ParquetFileMerger.mergeFiles( + * inputFiles, encryptedOutputFile, result.schema(), firstRowIds, + * rowGroupSize, columnIndexTruncateLength, result.metadata()); + * } + * </pre> + */ +public class ParquetFileMerger { + // Default buffer sizes for DeltaBinaryPackingValuesWriter + private static final int DEFAULT_INITIAL_BUFFER_SIZE = 64 * 1024; // 64KB + private static final int DEFAULT_PAGE_SIZE_FOR_ENCODING = 64 * 1024; // 64KB + + private ParquetFileMerger() { + // Utility class - prevent instantiation + } + + /** + * Validates that DataFiles can be merged and returns the Parquet schema if validation succeeds. + * + * <p>This method validates: + * + * <ul> + * <li>All Parquet-specific requirements (via {@link #canMergeAndGetSchema(List)}) + * <li>All files have the same partition spec + * <li>No files exceed the target output size (not splitting large files) + * </ul> + * + * <p>This validation is useful for compaction operations in Spark, Flink, or other engines that + * need to ensure files can be safely merged. The returned MessageType can be passed to {@link + * #mergeFiles} to avoid re-reading the schema. + * + * @param dataFiles List of DataFiles to validate + * @param fileIO FileIO to use for reading files + * @param targetOutputSize Maximum size for output file (files larger than this cannot be merged) + * @return MessageType schema if files can be merged, null otherwise + */ + public static MessageType canMergeAndGetSchema( + List<DataFile> dataFiles, FileIO fileIO, long targetOutputSize) { + Preconditions.checkArgument( + dataFiles != null && !dataFiles.isEmpty(), "dataFiles cannot be null or empty"); + + // Single loop to check partition spec consistency, file sizes, and build InputFile list + int firstSpecId = dataFiles.get(0).specId(); + List<InputFile> inputFiles = Lists.newArrayListWithCapacity(dataFiles.size()); + for (DataFile dataFile : dataFiles) { + // Check partition spec consistency - all files must have the same spec + if (dataFile.specId() != firstSpecId) { + return null; + } + + // Check file sizes - don't merge if splitting large files + if (dataFile.fileSizeInBytes() > targetOutputSize) { + return null; + } + + inputFiles.add(fileIO.newInputFile(dataFile.path().toString())); + } + + return canMergeAndGetSchema(inputFiles); + } + + private static MessageType readSchema(InputFile inputFile) throws IOException { + return ParquetFileReader.open(ParquetIO.file(inputFile)) + .getFooter() + .getFileMetaData() + .getSchema(); + } + + /** + * Validates that all row lineage column values are non-null in the input files. + * + * <p>When files already have physical row lineage columns and we're doing row lineage processing, + * we cannot automatically calculate null values during binary merge. This method ensures all + * values in both _row_id and _last_updated_sequence_number columns are present. + * + * <p>Additionally, this method requires that statistics exist for these columns. Statistics are + * necessary to extract the firstRowId for the merged DataFile metadata. Files without statistics + * cannot be merged because we cannot guarantee the output DataFile metadata will be consistent + * with the physical file contents. + * + * @param inputFiles List of input files to validate + * @return true if all row lineage columns have statistics with no nulls, false otherwise + */ + private static boolean validateRowLineageColumnsHaveNoNulls(List<InputFile> inputFiles) { + try { + for (InputFile inputFile : inputFiles) { + try (ParquetFileReader reader = ParquetFileReader.open(ParquetIO.file(inputFile))) { + List<BlockMetaData> rowGroups = reader.getFooter().getBlocks(); + + for (BlockMetaData rowGroup : rowGroups) { + for (ColumnChunkMetaData columnChunk : rowGroup.getColumns()) { + String columnPath = columnChunk.getPath().toDotString(); + + // Check if this is the _row_id column + if (columnPath.equals(MetadataColumns.ROW_ID.name())) { + Statistics<?> stats = columnChunk.getStatistics(); + // If stats are null, we can't verify no nulls exist - reject merge to be safe + // If stats exist and show nulls, reject merge + if (stats == null || stats.getNumNulls() > 0) { + return false; + } + } + + // Check if this is the _last_updated_sequence_number column + if (columnPath.equals(MetadataColumns.LAST_UPDATED_SEQUENCE_NUMBER.name())) { + Statistics<?> stats = columnChunk.getStatistics(); + // If stats are null, we can't verify no nulls exist - reject merge to be safe + // If stats exist and show nulls, reject merge + if (stats == null || stats.getNumNulls() > 0) { + return false; + } + } + } + } + } + } + return true; Review Comment: nit: newline -- 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]
