leaves12138 commented on code in PR #9213: URL: https://github.com/apache/paimon/pull/9213#discussion_r3782867788
########## 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: Implemented in 07e369ebb1. There is now a separate bounded path for DELETEs with `useRowIdFilter() == false` when the configured/default manifest parallelism permits parallel reads. Each worker only opens one `ManifestAvroReader`, `stableCopy()`s its compressed raw blocks, and closes the reader. The coordinator consumes the prefetched manifests in input order and exclusively owns Avro decoding, identifier filtering, the writer, `matchedEntries`, and `emittedDeletes`. Explicit parallelism 1 and single-manifest inputs still stream directly; compatible add-only compaction remains on the original streaming raw-copy path. I added a blocking FileIO test parameterized for both default (`null`) and explicit parallelism 2. It verifies two manifest reads overlap and validates the exact surviving entries, including the optional-manifest rewrite/keep behavior. The targeted Manifest suite passes: 110 tests, 0 failures, 1 existing skip. For a production-scale stress check, I routed the snapshot 8816 payload through the non-RowID identifier path by removing only the meta-level RowID ranges and forcing the selected manifests to rewrite. This is a stress test of the new branch, not the normal RowID-aware 8816 path (which remains about 6.8 s). On dev2 local/page-cached storage, identifier p1 was 43.21 s / 1.22 GiB peak RSS and p8 was 41.48 s / 1.55 GiB; current Legacy p8 was 46.07 s / 16.25 GiB. The modest local-time gain is expected because only compressed-block FileIO is prefetched, while decode/filter/write stays ordered and single-threaded; the main demonstrated gain is bounded memory, with additional latency hiding expected for object storage. -- 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]
