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


##########
paimon-core/src/main/java/org/apache/paimon/operation/ManifestFileBlockMerger.java:
##########
@@ -0,0 +1,916 @@
+/*
+ * 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 {
+            // DELETE lookups are immutable, and every planning worker owns 
its lookup scratch and
+            // block statistics. Plan manifests in parallel while the single 
ordered writer keeps
+            // matched ADD and emitted DELETE state on this thread.
+            if (hasDeletes
+                    && (manifestReadParallelism == null || 
manifestReadParallelism > 1)
+                    && manifests.size() > 1) {
+                // Keep decompression and primitive entry inspection parallel. 
The batched executor
+                // bounds retained raw blocks to at most one manifest per 
planning thread, while the
+                // single writer still emits manifests in input order.
+                Function<ManifestFileMeta, List<ManifestRewritePlan>> planner =
+                        manifest -> {
+                            try {
+                                return Collections.singletonList(
+                                        planManifestRewrite(
+                                                manifest, manifestFile, 
partitionType, deletes));
+                            } catch (Exception e) {
+                                throw new RuntimeException(
+                                        "Failed to plan manifest rewrite for "
+                                                + manifest.fileName(),
+                                        e);
+                            }
+                        };
+                for (ManifestRewritePlan plan :
+                        sequentialBatchedExecute(planner, manifests, 
manifestReadParallelism)) {

Review Comment:
   [P2] Please make the planner batch lifetime explicit on failures. 
`sequentialBatchedExecute` submits an entire batch, but 
`ThreadPoolUtils.futuresToIterIter` propagates the first `Future.get()` failure 
or interrupt without cancelling or waiting for sibling futures; a writer 
failure while consuming an early plan has the same effect. Both callers then 
execute `deletes.release()` in `finally`, which replaces the identifier set's 
backing arrays while other non-RowID planners may still be inside 
`CollectedDeletes.isDeleted()`. This creates a use-after-release race and 
leaves object-store reads running on the shared manifest pool during commit 
cancellation or transient I/O failures. Please cancel and drain all submitted 
planners before returning/throwing, and release `deletes` only after they have 
stopped. A fault-injection test that blocks one planner, fails another (and the 
writer), and asserts that no reads continue after the method returns would 
cover this.



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