JingsongLi commented on code in PR #9213: URL: https://github.com/apache/paimon/pull/9213#discussion_r3782335562
########## paimon-core/src/main/java/org/apache/paimon/operation/ManifestFileBlockMerger.java: ########## @@ -0,0 +1,911 @@ +/* + * 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.paimon.operation; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.data.BinaryRow; +import org.apache.paimon.data.GenericRow; +import org.apache.paimon.format.SimpleColStats; +import org.apache.paimon.format.SimpleStatsCollector; +import org.apache.paimon.io.ProjectedDataFileMeta; +import org.apache.paimon.manifest.CollectedDeletes; +import org.apache.paimon.manifest.CompactFileIdentifierSet; +import org.apache.paimon.manifest.FileEntry.ReusableIdentifier; +import org.apache.paimon.manifest.ManifestAvroReader; +import org.apache.paimon.manifest.ManifestAvroReader.RawBlock; +import org.apache.paimon.manifest.ManifestAvroReader.RowIterator; +import org.apache.paimon.manifest.ManifestAvroWriter; +import org.apache.paimon.manifest.ManifestAvroWriter.EncodedBlockMeta; +import org.apache.paimon.manifest.ManifestAvroWriter.EncodedEntry; +import org.apache.paimon.manifest.ManifestFile; +import org.apache.paimon.manifest.ManifestFileMeta; +import org.apache.paimon.manifest.PartitionDictionary; +import org.apache.paimon.manifest.ProjectedManifestEntry; +import org.apache.paimon.partition.PartitionPredicate; +import org.apache.paimon.stats.SimpleStatsConverter; +import org.apache.paimon.types.RowType; +import org.apache.paimon.utils.CloseableIterator; +import org.apache.paimon.utils.Filter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; + +import static org.apache.paimon.manifest.ManifestFileMeta.allContainsRowId; +import static org.apache.paimon.utils.ManifestReadThreadPool.sequentialBatchedExecute; +import static org.apache.paimon.utils.Preconditions.checkArgument; +import static org.apache.paimon.utils.Preconditions.checkState; + +/** Block-aware manifest compaction which never delegates to the legacy full-entry merger. */ +final class ManifestFileBlockMerger { + + private static final Logger LOG = LoggerFactory.getLogger(ManifestFileBlockMerger.class); + + private ManifestFileBlockMerger() {} + + static List<ManifestFileMeta> merge( + List<ManifestFileMeta> input, + List<ManifestFileMeta> newFilesForAbort, + ManifestFile manifestFile, + RowType partitionType, + CoreOptions options) + throws Exception { + long suggestedMetaSize = options.manifestTargetSize().getBytes(); + Integer manifestReadParallelism = options.scanManifestParallelism(); + Optional<List<ManifestFileMeta>> fullCompacted = + tryFullCompaction( + input, + newFilesForAbort, + manifestFile, + suggestedMetaSize, + options.manifestFullCompactionThresholdSize().getBytes(), + partitionType, + manifestReadParallelism); + if (fullCompacted.isPresent()) { + return fullCompacted.get(); + } + return compactMinor( + input, + newFilesForAbort, + manifestFile, + partitionType, + suggestedMetaSize, + options.manifestMergeMinCount(), + manifestReadParallelism); + } + + static Optional<List<ManifestFileMeta>> tryFullCompaction( + List<ManifestFileMeta> inputs, + List<ManifestFileMeta> newFilesForAbort, + ManifestFile manifestFile, + long suggestedMetaSize, + long sizeTrigger, + RowType partitionType, + @Nullable Integer manifestReadParallelism) + throws Exception { + checkArgument(sizeTrigger > 0, "Manifest full compaction size trigger cannot be zero."); + + Filter<ManifestFileMeta> mustChange = + file -> file.numDeletedFiles() > 0 || file.fileSize() < suggestedMetaSize; + long totalManifestSize = 0; + long deltaDeleteFileNum = 0; + long totalDeltaFileSize = 0; + List<ManifestFileMeta> deltaManifests = new ArrayList<>(); + for (ManifestFileMeta file : inputs) { + totalManifestSize += file.fileSize(); + if (mustChange.test(file)) { + totalDeltaFileSize += file.fileSize(); + deltaDeleteFileNum += file.numDeletedFiles(); + deltaManifests.add(file); + } + } + + if (totalDeltaFileSize < sizeTrigger) { + return Optional.empty(); + } + + LOG.info( + "Start Block-aware Manifest File Full Compaction: totalManifestSize: {}, deltaDeleteFileNum {}, totalDeltaFileSize {}", + totalManifestSize, + deltaDeleteFileNum, + totalDeltaFileSize); + + boolean useRowIdFilter = allContainsRowId(inputs); + final CollectedDeletes deletes = + collectDeletes( + deltaManifests, + manifestFile, + useRowIdFilter, + true, + manifestReadParallelism) + .toImmutable(); + try { + PartitionPredicate predicate; + if (deletes.isEmpty()) { + predicate = PartitionPredicate.ALWAYS_FALSE; + } else if (partitionType.getFieldCount() > 0) { + predicate = PartitionPredicate.fromMultiple(partitionType, deletes.partitions()); + } else { + predicate = PartitionPredicate.ALWAYS_TRUE; + } + + List<ManifestFileMeta> result = new ArrayList<>(); + List<ManifestFileMeta> toCompact = new LinkedList<>(inputs); + if (predicate != null) { + Iterator<ManifestFileMeta> iterator = toCompact.iterator(); + while (iterator.hasNext()) { + ManifestFileMeta file = iterator.next(); + if (mustChange.test(file)) { + continue; + } + if (!predicate.test( + file.numAddedFiles() + file.numDeletedFiles(), + file.partitionStats().minValues(), + file.partitionStats().maxValues(), + file.partitionStats().nullCounts())) { + iterator.remove(); + result.add(file); + } + } + } + + if (toCompact.size() <= 1) { + return Optional.empty(); + } + + List<ManifestFileMeta> rewritten = + rewriteManifests( + toCompact, + manifestFile, + partitionType, + deletes, + true, + mustChange, + result, + manifestReadParallelism); + result.addAll(rewritten); + newFilesForAbort.addAll(rewritten); + return Optional.of(result); + } finally { + deletes.release(); + } + } + + private static List<ManifestFileMeta> compactMinor( + List<ManifestFileMeta> input, + List<ManifestFileMeta> newFilesForAbort, + ManifestFile manifestFile, + RowType partitionType, + long suggestedMetaSize, + int suggestedMinMetaCount, + @Nullable Integer manifestReadParallelism) + throws Exception { + List<ManifestFileMeta> result = new ArrayList<>(); + List<ManifestFileMeta> candidates = new ArrayList<>(); + long totalSize = 0; + for (ManifestFileMeta manifest : input) { + totalSize += manifest.fileSize(); + candidates.add(manifest); + if (totalSize >= suggestedMetaSize) { + compactMinorBatch( + candidates, + result, + newFilesForAbort, + manifestFile, + partitionType, + manifestReadParallelism); + candidates.clear(); + totalSize = 0; + } + } + + if (candidates.size() >= suggestedMinMetaCount) { + compactMinorBatch( + candidates, + result, + newFilesForAbort, + manifestFile, + partitionType, + manifestReadParallelism); + } else { + result.addAll(candidates); + } + return result; + } + + private static void compactMinorBatch( + List<ManifestFileMeta> candidates, + List<ManifestFileMeta> result, + List<ManifestFileMeta> newFilesForAbort, + ManifestFile manifestFile, + RowType partitionType, + @Nullable Integer manifestReadParallelism) + throws Exception { + if (candidates.size() == 1) { + result.add(candidates.get(0)); + return; + } + + List<ManifestFileMeta> compacted = + mergeMinorManifests( + candidates, manifestFile, partitionType, manifestReadParallelism); + result.addAll(compacted); + newFilesForAbort.addAll(compacted); + } + + private static CollectedDeletes collectDeletes( + List<ManifestFileMeta> manifests, + ManifestFile manifestFile, + boolean collectRowIds, + boolean collectPartitions, + @Nullable Integer manifestReadParallelism) { + List<ManifestFileMeta> manifestsWithDeletes = new ArrayList<>(); + for (ManifestFileMeta manifest : manifests) { + if (manifest.numDeletedFiles() > 0) { + manifestsWithDeletes.add(manifest); + } + } + + CollectedDeletes result = new CollectedDeletes(collectRowIds); + if (manifestReadParallelism == null + || manifestReadParallelism <= 1 + || manifestsWithDeletes.size() <= 1) { + for (ManifestFileMeta manifest : manifestsWithDeletes) { + CollectedDeletes deletes = + collectDeletedEntries( + manifest, manifestFile, collectRowIds, collectPartitions); + result.combine(deletes); + deletes.release(); + } + return result; + } + + Function<ManifestFileMeta, List<CollectedDeletes>> scan = + manifest -> + Collections.singletonList( + collectDeletedEntries( + manifest, manifestFile, collectRowIds, collectPartitions)); + for (CollectedDeletes deletes : + sequentialBatchedExecute(scan, manifestsWithDeletes, manifestReadParallelism)) { + result.combine(deletes); + deletes.release(); + } + return result; + } + + private static CollectedDeletes collectDeletedEntries( + ManifestFileMeta manifest, + ManifestFile manifestFile, + boolean collectRowIds, + boolean collectPartitions) { + CollectedDeletes deletes = new CollectedDeletes(collectRowIds); + try (CloseableIterator<ProjectedManifestEntry> entries = + manifestFile.scan( + manifest.fileName(), ProjectedManifestEntry.DELETE_ENTRY_PROJECTION)) { + while (entries.hasNext()) { + ProjectedManifestEntry entry = entries.next(); + if (!entry.isDelete()) { + continue; + } + deletes.add(entry, collectRowIds, collectPartitions); + } + return deletes; + } catch (Exception e) { + deletes.release(); + throw new RuntimeException( + "Failed to collect DELETE entries from manifest " + manifest.fileName(), e); + } + } + + /** + * Compacts manifests in input order. RowID manifests can copy unaffected ADD-only Avro blocks + * verbatim; manifests without RowID use identifiers to filter decoded entries. + */ + private static List<ManifestFileMeta> mergeMinorManifests( + List<ManifestFileMeta> manifests, + ManifestFile manifestFile, + RowType partitionType, + @Nullable Integer manifestReadParallelism) + throws Exception { + boolean useRowIdFilter = allContainsRowId(manifests); + final CollectedDeletes deletes = + collectDeletes( + manifests, + manifestFile, + useRowIdFilter, + false, + manifestReadParallelism) + .toImmutable(); + try { + return rewriteManifests( + manifests, + manifestFile, + partitionType, + deletes, + false, + null, + null, + manifestReadParallelism); + } finally { + deletes.release(); + } + } + + private static List<ManifestFileMeta> rewriteManifests( + List<ManifestFileMeta> manifests, + ManifestFile manifestFile, + RowType partitionType, + CollectedDeletes deletes, + boolean fullCompaction, + @Nullable Filter<ManifestFileMeta> mustChange, + @Nullable List<ManifestFileMeta> unchangedManifests, + @Nullable Integer manifestReadParallelism) + throws Exception { + ManifestAvroWriter writer = manifestFile.createAvroWriter(); + CompactFileIdentifierSet matchedEntries = new CompactFileIdentifierSet(); + CompactFileIdentifierSet emittedDeletes = new CompactFileIdentifierSet(); + PartitionDictionary partitions = new PartitionDictionary(); + SimpleStatsConverter partitionStatsConverter = new SimpleStatsConverter(partitionType); + EncodedEntry metadata = new EncodedEntry(); + ReusableIdentifier reusableIdentifier = new ReusableIdentifier(); + boolean hasDeletes = !deletes.isEmpty(); + try { + // Row IDs let each manifest inspect DELETE matches independently. Use parallel + // planning only when there are multiple workers and manifests to offset the cost of + // retaining planned raw blocks before the single ordered writer consumes them. + if (hasDeletes + && deletes.useRowIdFilter() + && manifestReadParallelism != null Review Comment: Thanks, the RowID/default fix looks good, and the add-only benchmark is convincing; keeping compatible add-only manifests on the streaming raw-copy path makes sense. One case still seems uncovered: when DELETEs are present and useRowIdFilter() is false, the code still falls through to the serial loop even when scan.manifest.parallelism is null or explicitly greater than 1. This affects legacy or non-data-evolution manifests and requires decoded identifier filtering, so the add-only benchmark does not cover it. Could we add a separate bounded raw-block prefetch path only for non-RowID + DELETE compaction? Each worker would open one reader, stableCopy() the compressed blocks, and close the reader; the coordinator would then consume plans in input order and perform identifier filtering and all writer, matchedEntries, and emittedDeletes mutations on a single thread. This preserves the ADD/DELETE state machine and keeps memory bounded to one manifest per planning worker, while leaving add-only streaming unchanged. A blocking FileIO test for both default and explicit parallelism would cover the remaining contract. -- 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]
