leaves12138 commented on code in PR #9213:
URL: https://github.com/apache/paimon/pull/9213#discussion_r3783023098


##########
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. I replaced the prefetch-only implementation with the stronger 
block-aware design in b7284308a7. All DELETE compactions now use the same 
bounded parallel manifest planner when the configured/default parallelism 
permits it, including the non-RowID identifier path. Each worker owns its 
identifier scratch and block-statistics objects and only reads immutable DELETE 
state. Unchanged schema-compatible blocks produce EncodedBlockMeta and are 
copied as compressed Avro blocks; blocks containing a DELETE or a deleted ADD 
are decoded and filtered by the coordinator in input order. The coordinator 
remains the sole owner of the writer, matchedEntries, and emittedDeletes. 
Compatible add-only compaction remains on the faster streaming raw-copy path.
   
   For blocks without RowID, EncodedBlockMeta keeps its original primitive 
constructor and uses -1/-1 as the no-RowID sentinel, so there is no boxed 
overload or binary signature change. I added coverage for raw block metadata 
without RowIDs and retained the blocking FileIO concurrency test for both 
default and explicit parallelism 2. Formatting/checks pass, and 56 directly 
related manifest tests pass.
   
   On dev2, the production-scale snapshot 8816 stress path (26,670,786 ADDs and 
11,410 DELETEs, forced through non-RowID identifier matching) completed the 
merge in 7.98 s with 1.66 GiB peak RSS. The earlier prefetch-only p8 result was 
41.48 s / 1.55 GiB, while current Legacy p8 was 46.07 s / 16.25 GiB. Full 
verification read all 26,659,376 output entries and exactly matched the Legacy 
fingerprints: b7ef9bb1f8347726, 45f036e957cd88ce, f7b77d2fd5a0b1c1, 
a0f943ec46d9a7ef.



-- 
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]

Reply via email to