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


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/procedure/SparkManagedBlobOrphanFilesClean.scala:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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.spark.procedure
+
+import org.apache.paimon.catalog.{Catalog, Identifier}
+import org.apache.paimon.fs.Path
+import org.apache.paimon.manifest.{ManifestFile, ManifestFileMeta, 
ManifestList}
+import org.apache.paimon.operation.{CleanOrphanFilesResult, 
ManagedBlobOrphanFilesClean}
+import org.apache.paimon.operation.ManagedBlobOrphanFilesClean.SidecarWorkItem
+import org.apache.paimon.operation.OrphanFilesClean.retryReadingFiles
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.utils.DataFilePathFactories
+import org.apache.paimon.utils.FileStorePathFactory.BUCKET_PATH_PREFIX
+import org.apache.paimon.utils.Preconditions
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.{functions, Dataset, PaimonSparkSession, 
SparkSession}
+import org.apache.spark.sql.catalyst.SQLConfHelper
+
+import java.util
+import java.util.function.Consumer
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+case class SparkManagedBlobOrphanFilesClean(
+    specifiedTable: FileStoreTable,
+    specifiedOlderThanMillis: Long,
+    parallelism: Int,
+    dryRunPara: Boolean,
+    @transient spark: SparkSession)
+  extends SparkManagedBlobOrphanFilesCleanBase(specifiedTable, 
specifiedOlderThanMillis, dryRunPara)
+  with SQLConfHelper
+  with Logging {
+
+  def doClean(): (Dataset[(Long, Long)], Seq[Dataset[_]]) = {
+    import spark.implicits._
+
+    SparkManagedBlobOrphanFilesClean.checkParallelism(parallelism)
+    val cached = new mutable.ArrayBuffer[Dataset[_]]()
+    try {
+      val topologyBefore = snapshotTopology()
+      val usedPacks = collectUsedPacksDf().cache()
+      cached += usedPacks
+      val skipGc = usedPacks
+        .filter($"used_name" === 
ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+        .limit(1)
+        .collect()
+        .nonEmpty
+
+      val fileDirs = listPaimonFileDirs.asScala.map(_.toString).toSeq
+      val maxFileDirsParallelism = Math.min(Math.max(fileDirs.size, 1), 
parallelism)
+      val candidates = spark.sparkContext
+        .parallelize(fileDirs, maxFileDirsParallelism)
+        .flatMap {
+          dir =>
+            tryBestListingDirs(new Path(dir)).asScala
+              .filter(file => !file.isDir)
+              .filter(oldEnough)
+              .filter(
+                file => 
ManagedBlobOrphanFilesClean.isManagedBlobPackName(file.getPath.getName))
+              .map {
+                file =>
+                  val path = file.getPath
+                  val parent = path.getParent
+                  (
+                    packIdentityForCandidate(path),
+                    path.toString,
+                    file.getLen,
+                    if (parent == null) "" else parent.toString)
+              }
+        }
+        .toDF("name", "path", "len", "dataDir")
+        .repartition(parallelism)
+        .cache()
+      cached += candidates
+      val candidateSkipGc = candidates
+        .filter($"name" === ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+        .limit(1)
+        .collect()
+        .nonEmpty
+      val canonicalCandidates = candidates
+        .filter($"name" =!= ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+
+      betweenUsedCollections()
+      val usedPacks2 = collectUsedPacksDf().cache()

Review Comment:
   [P1] Materialize the safety marker with the deletion input
   
   This cache does not freeze the second mark: Spark may recompute an evicted 
or lost block from live storage. `skipGc2` and `usedChanged` are reduced to 
driver booleans now, but the anti-join is evaluated later. If a recomputation 
then encounters a temporarily unreadable live `.blobref`, it emits only 
`SKIP_MANAGED_BLOB_GC`; line 113 filters that marker out while the 
already-computed `skipGc2 = false` is not revisited. The referenced old pack 
can therefore disappear from the join's used set and be deleted. Please 
reliably checkpoint/truncate this lineage and derive the skip flag, set 
comparison, and deletion join from the same immutable materialization (or 
otherwise keep the gate in the same deletion DAG). A regression can unpersist 
the returned cache after `doClean`, make the next sidecar read fail, and verify 
that no live pack is deleted.



##########
paimon-core/src/main/java/org/apache/paimon/operation/LocalManagedBlobOrphanFilesClean.java:
##########
@@ -0,0 +1,344 @@
+/*
+ * 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.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.Table;
+import org.apache.paimon.utils.Pair;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletionService;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorCompletionService;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.apache.paimon.utils.FileStorePathFactory.BUCKET_PATH_PREFIX;
+import static org.apache.paimon.utils.Preconditions.checkArgument;
+import static org.apache.paimon.utils.ThreadPoolUtils.createCachedThreadPool;
+import static 
org.apache.paimon.utils.ThreadPoolUtils.randomlyExecuteSequentialReturn;
+import static org.apache.paimon.utils.ThreadPoolUtils.randomlyOnlyExecute;
+
+/** Local {@link ManagedBlobOrphanFilesClean}. */
+public class LocalManagedBlobOrphanFilesClean extends 
ManagedBlobOrphanFilesClean
+        implements AutoCloseable {
+
+    /**
+     * Upper bound for waiting cancelled table cleanups after a database-wide 
failure. {@code
+     * shutdownNow()} only requests interruption; a FileIO call may ignore it 
until a socket
+     * timeout. Waiting forever would hide the original failure.
+     */
+    private static final long TERMINATION_TIMEOUT_MS = 
TimeUnit.SECONDS.toMillis(120);
+
+    private final ThreadPoolExecutor executor;
+
+    public LocalManagedBlobOrphanFilesClean(
+            FileStoreTable table, long olderThanMillis, boolean dryRun) {
+        super(table, olderThanMillis, dryRun);
+        this.executor =
+                createCachedThreadPool(
+                        table.coreOptions().fileOperationThreadNum(),
+                        "MANAGED_BLOB_ORPHAN_FILES_CLEAN");
+    }
+
+    public CleanOrphanFilesResult clean() throws IOException {
+        List<Path> deleteFiles = new ArrayList<>();
+        long deletedFilesLenInBytes = 0;
+        Map<String, Pair<Path, Long>> candidates = getCandidatePacks();
+        if (candidates.isEmpty()) {
+            return new CleanOrphanFilesResult(0, 0, deleteFiles);
+        }
+        if (candidates.containsKey(SKIP_MANAGED_BLOB_GC)) {
+            LOG.warn(
+                    "Skip managed blob pack GC for table {} because a listed 
pack path cannot be resolved safely.",
+                    table.fullName());
+            return new CleanOrphanFilesResult(0, 0, deleteFiles);
+        }
+
+        List<String> topologyBefore = snapshotTopology();
+        Set<String> usedPacks = collectUsedPacks();
+        betweenUsedCollections();
+        Set<String> usedPacks2 = collectUsedPacks();
+        if (shouldAbortPackGc(topologyBefore, usedPacks, usedPacks2)) {
+            return new CleanOrphanFilesResult(0, 0, deleteFiles);
+        }
+
+        for (Map.Entry<String, Pair<Path, Long>> candidate : 
candidates.entrySet()) {
+            throwIfInterrupted();
+            if (usedPacks2.contains(candidate.getKey())) {
+                continue;
+            }
+            Pair<Path, Long> info = candidate.getValue();
+            if (cleanManagedBlobFile(info.getLeft())) {
+                deletedFilesLenInBytes += info.getRight();
+                deleteFiles.add(info.getLeft());
+            }
+        }
+
+        throwIfInterrupted();
+        if (!dryRun) {
+            cleanEmptyDataDirectory(deleteFiles);
+        }
+        return new CleanOrphanFilesResult(deleteFiles.size(), 
deletedFilesLenInBytes, deleteFiles);
+    }
+
+    private static void throwIfInterrupted() throws IOException {
+        if (Thread.currentThread().isInterrupted()) {
+            throw new IOException("Interrupted while cleaning managed blob 
orphan files.");
+        }
+    }
+
+    @Override
+    protected Set<String> collectUsedPacks() {
+        ReachabilityScan scan = newReachabilityScan();
+        return validBranches().stream()
+                .flatMap(branch -> getUsedPacks(branch, scan).stream())
+                .collect(Collectors.toSet());
+    }
+
+    private Set<String> getUsedPacks(String branch, ReachabilityScan scan) {
+        Set<String> used = ConcurrentHashMap.newKeySet();
+        try {
+            randomlyOnlyExecute(

Review Comment:
   [P2] Observe snapshot failures before waiting on stalled siblings
   
   `randomlyOnlyExecute` ultimately calls `Future.get()` in submission order. 
With parallelism greater than one, an earlier snapshot can block in 
uninterruptible manifest/sidecar I/O while a later snapshot task has already 
failed. That failure is never observed, the table future never completes, and 
the outer `CompletionService` cannot enter its cancellation and bounded-wait 
path. Please consume these snapshot tasks in completion order and cancel the 
remaining tasks on the first failure. The existing completion-order tests cover 
sibling tables, but not sibling snapshot tasks within one mark pass.



##########
paimon-core/src/main/java/org/apache/paimon/operation/LocalManagedBlobOrphanFilesClean.java:
##########
@@ -0,0 +1,344 @@
+/*
+ * 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.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.Table;
+import org.apache.paimon.utils.Pair;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletionService;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorCompletionService;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.apache.paimon.utils.FileStorePathFactory.BUCKET_PATH_PREFIX;
+import static org.apache.paimon.utils.Preconditions.checkArgument;
+import static org.apache.paimon.utils.ThreadPoolUtils.createCachedThreadPool;
+import static 
org.apache.paimon.utils.ThreadPoolUtils.randomlyExecuteSequentialReturn;
+import static org.apache.paimon.utils.ThreadPoolUtils.randomlyOnlyExecute;
+
+/** Local {@link ManagedBlobOrphanFilesClean}. */
+public class LocalManagedBlobOrphanFilesClean extends 
ManagedBlobOrphanFilesClean
+        implements AutoCloseable {
+
+    /**
+     * Upper bound for waiting cancelled table cleanups after a database-wide 
failure. {@code
+     * shutdownNow()} only requests interruption; a FileIO call may ignore it 
until a socket
+     * timeout. Waiting forever would hide the original failure.
+     */
+    private static final long TERMINATION_TIMEOUT_MS = 
TimeUnit.SECONDS.toMillis(120);
+
+    private final ThreadPoolExecutor executor;
+
+    public LocalManagedBlobOrphanFilesClean(
+            FileStoreTable table, long olderThanMillis, boolean dryRun) {
+        super(table, olderThanMillis, dryRun);
+        this.executor =
+                createCachedThreadPool(
+                        table.coreOptions().fileOperationThreadNum(),
+                        "MANAGED_BLOB_ORPHAN_FILES_CLEAN");
+    }
+
+    public CleanOrphanFilesResult clean() throws IOException {
+        List<Path> deleteFiles = new ArrayList<>();
+        long deletedFilesLenInBytes = 0;
+        Map<String, Pair<Path, Long>> candidates = getCandidatePacks();
+        if (candidates.isEmpty()) {
+            return new CleanOrphanFilesResult(0, 0, deleteFiles);
+        }
+        if (candidates.containsKey(SKIP_MANAGED_BLOB_GC)) {
+            LOG.warn(
+                    "Skip managed blob pack GC for table {} because a listed 
pack path cannot be resolved safely.",
+                    table.fullName());
+            return new CleanOrphanFilesResult(0, 0, deleteFiles);
+        }
+
+        List<String> topologyBefore = snapshotTopology();
+        Set<String> usedPacks = collectUsedPacks();
+        betweenUsedCollections();
+        Set<String> usedPacks2 = collectUsedPacks();
+        if (shouldAbortPackGc(topologyBefore, usedPacks, usedPacks2)) {
+            return new CleanOrphanFilesResult(0, 0, deleteFiles);
+        }
+
+        for (Map.Entry<String, Pair<Path, Long>> candidate : 
candidates.entrySet()) {
+            throwIfInterrupted();
+            if (usedPacks2.contains(candidate.getKey())) {
+                continue;
+            }
+            Pair<Path, Long> info = candidate.getValue();
+            if (cleanManagedBlobFile(info.getLeft())) {
+                deletedFilesLenInBytes += info.getRight();
+                deleteFiles.add(info.getLeft());
+            }
+        }
+
+        throwIfInterrupted();
+        if (!dryRun) {
+            cleanEmptyDataDirectory(deleteFiles);
+        }
+        return new CleanOrphanFilesResult(deleteFiles.size(), 
deletedFilesLenInBytes, deleteFiles);
+    }
+
+    private static void throwIfInterrupted() throws IOException {
+        if (Thread.currentThread().isInterrupted()) {
+            throw new IOException("Interrupted while cleaning managed blob 
orphan files.");
+        }
+    }
+
+    @Override
+    protected Set<String> collectUsedPacks() {
+        ReachabilityScan scan = newReachabilityScan();
+        return validBranches().stream()
+                .flatMap(branch -> getUsedPacks(branch, scan).stream())
+                .collect(Collectors.toSet());
+    }
+
+    private Set<String> getUsedPacks(String branch, ReachabilityScan scan) {
+        Set<String> used = ConcurrentHashMap.newKeySet();
+        try {
+            randomlyOnlyExecute(
+                    executor,
+                    snapshot -> {
+                        try {
+                            emitUsedPacks(branch, snapshot, scan, used::add);
+                        } catch (IOException e) {
+                            throw new RuntimeException(e);
+                        }
+                    },
+                    safelyGetAllSnapshots(branch));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+        return used;
+    }
+
+    private Map<String, Pair<Path, Long>> getCandidatePacks() {
+        List<Path> fileDirs = listPaimonFileDirs();
+        Iterator<Pair<Path, Long>> packs =
+                randomlyExecuteSequentialReturn(executor, packLister(), 
fileDirs);
+        Map<String, Pair<Path, Long>> result = new HashMap<>();
+        while (packs.hasNext()) {
+            Pair<Path, Long> fileInfo = packs.next();
+            Optional<String> identity = 
packIdentityForCleanup(fileInfo.getLeft());
+            if (!identity.isPresent()) {
+                result.clear();
+                result.put(SKIP_MANAGED_BLOB_GC, fileInfo);
+                return result;
+            }
+            result.put(identity.get(), fileInfo);
+        }
+        return result;
+    }
+
+    private Function<Path, List<Pair<Path, Long>>> packLister() {
+        return path ->
+                tryBestListingDirs(path).stream()
+                        .filter(status -> !status.isDir())
+                        .filter(this::oldEnough)
+                        .filter(status -> 
isManagedBlobPackName(status.getPath().getName()))
+                        .map(status -> Pair.of(status.getPath(), 
status.getLen()))
+                        .collect(Collectors.toList());
+    }
+
+    private void cleanEmptyDataDirectory(List<Path> deleted) {
+        if (deleted.isEmpty()) {
+            return;
+        }
+        Set<Path> bucketDirs =
+                deleted.stream()
+                        .map(Path::getParent)
+                        .filter(path -> 
path.toString().contains(BUCKET_PATH_PREFIX))
+                        .collect(Collectors.toSet());
+        randomlyOnlyExecute(executor, this::tryDeleteEmptyDirectory, 
bucketDirs);
+        Set<Path> partitionDirs =
+                
bucketDirs.stream().map(Path::getParent).collect(Collectors.toSet());
+        tryCleanDataDirectory(partitionDirs, partitionKeysNum);
+    }
+
+    public static List<LocalManagedBlobOrphanFilesClean> createCleans(
+            Catalog catalog,
+            String databaseName,
+            @Nullable String tableName,
+            long olderThanMillis,
+            @Nullable Integer parallelism,
+            boolean dryRun)
+            throws Catalog.DatabaseNotExistException, 
Catalog.TableNotExistException {
+        List<String> tableNames = Collections.singletonList(tableName);
+        if (tableName == null || "*".equals(tableName)) {
+            tableNames = catalog.listTables(databaseName);
+        }
+
+        Map<String, String> dynamicOptions =
+                parallelism == null
+                        ? Collections.emptyMap()
+                        : new HashMap<String, String>() {
+                            {
+                                put(
+                                        
CoreOptions.FILE_OPERATION_THREAD_NUM.key(),
+                                        parallelism.toString());
+                            }
+                        };
+
+        List<LocalManagedBlobOrphanFilesClean> cleans = new 
ArrayList<>(tableNames.size());
+        for (String t : tableNames) {
+            Identifier identifier = new Identifier(databaseName, t);
+            Table table = catalog.getTable(identifier).copy(dynamicOptions);
+            checkArgument(
+                    table instanceof FileStoreTable,
+                    "Only FileStoreTable supports remove-orphan-blobs action. 
The table type is '%s'.",
+                    table.getClass().getName());
+            cleans.add(
+                    new LocalManagedBlobOrphanFilesClean(
+                            (FileStoreTable) table, olderThanMillis, dryRun));
+        }
+        return cleans;
+    }
+
+    public static CleanOrphanFilesResult executeDatabase(
+            Catalog catalog,
+            String databaseName,
+            @Nullable String tableName,
+            long olderThanMillis,
+            @Nullable Integer parallelism,
+            boolean dryRun)
+            throws Catalog.DatabaseNotExistException, 
Catalog.TableNotExistException {
+        List<LocalManagedBlobOrphanFilesClean> tableCleans =
+                createCleans(
+                        catalog, databaseName, tableName, olderThanMillis, 
parallelism, dryRun);
+        ExecutorService executorService =
+                
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

Review Comment:
   [P2] Use daemon workers for timeout-abandoned cleanup
   
   `Executors.newFixedThreadPool` creates non-daemon workers, but the new 
bounded termination wait intentionally returns even when this executor is still 
alive. If a sibling FileIO call ignores interruption past the 120-second 
deadline, the procedure returns while a non-daemon cleanup worker remains, 
which can prevent a standalone JVM from exiting and can accumulate leaked 
workers in embedded local-mode calls. 
`testExecuteDatabaseDoesNotHangOnUninterruptibleDelete` confirms 
`isTerminated() == false` and only avoids the leak by manually releasing its 
fake FileIO. Please use a named daemon thread factory for this production pool 
while retaining the bounded wait and interruption checks.



##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/procedure/SparkManagedBlobOrphanFilesClean.scala:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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.spark.procedure
+
+import org.apache.paimon.catalog.{Catalog, Identifier}
+import org.apache.paimon.fs.Path
+import org.apache.paimon.manifest.{ManifestFile, ManifestFileMeta, 
ManifestList}
+import org.apache.paimon.operation.{CleanOrphanFilesResult, 
ManagedBlobOrphanFilesClean}
+import org.apache.paimon.operation.ManagedBlobOrphanFilesClean.SidecarWorkItem
+import org.apache.paimon.operation.OrphanFilesClean.retryReadingFiles
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.utils.DataFilePathFactories
+import org.apache.paimon.utils.FileStorePathFactory.BUCKET_PATH_PREFIX
+import org.apache.paimon.utils.Preconditions
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.{functions, Dataset, PaimonSparkSession, 
SparkSession}
+import org.apache.spark.sql.catalyst.SQLConfHelper
+
+import java.util
+import java.util.function.Consumer
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+case class SparkManagedBlobOrphanFilesClean(
+    specifiedTable: FileStoreTable,
+    specifiedOlderThanMillis: Long,
+    parallelism: Int,
+    dryRunPara: Boolean,
+    @transient spark: SparkSession)
+  extends SparkManagedBlobOrphanFilesCleanBase(specifiedTable, 
specifiedOlderThanMillis, dryRunPara)
+  with SQLConfHelper
+  with Logging {
+
+  def doClean(): (Dataset[(Long, Long)], Seq[Dataset[_]]) = {
+    import spark.implicits._
+
+    SparkManagedBlobOrphanFilesClean.checkParallelism(parallelism)
+    val cached = new mutable.ArrayBuffer[Dataset[_]]()
+    try {
+      val topologyBefore = snapshotTopology()
+      val usedPacks = collectUsedPacksDf().cache()
+      cached += usedPacks
+      val skipGc = usedPacks
+        .filter($"used_name" === 
ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+        .limit(1)
+        .collect()
+        .nonEmpty
+
+      val fileDirs = listPaimonFileDirs.asScala.map(_.toString).toSeq
+      val maxFileDirsParallelism = Math.min(Math.max(fileDirs.size, 1), 
parallelism)
+      val candidates = spark.sparkContext
+        .parallelize(fileDirs, maxFileDirsParallelism)
+        .flatMap {
+          dir =>
+            tryBestListingDirs(new Path(dir)).asScala
+              .filter(file => !file.isDir)
+              .filter(oldEnough)
+              .filter(
+                file => 
ManagedBlobOrphanFilesClean.isManagedBlobPackName(file.getPath.getName))
+              .map {
+                file =>
+                  val path = file.getPath
+                  val parent = path.getParent
+                  (
+                    packIdentityForCandidate(path),
+                    path.toString,
+                    file.getLen,
+                    if (parent == null) "" else parent.toString)
+              }
+        }
+        .toDF("name", "path", "len", "dataDir")
+        .repartition(parallelism)
+        .cache()
+      cached += candidates
+      val candidateSkipGc = candidates
+        .filter($"name" === ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+        .limit(1)
+        .collect()
+        .nonEmpty
+      val canonicalCandidates = candidates
+        .filter($"name" =!= ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+
+      betweenUsedCollections()
+      val usedPacks2 = collectUsedPacksDf().cache()
+      cached += usedPacks2
+      val skipGc2 = usedPacks2
+        .filter($"used_name" === 
ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+        .limit(1)
+        .collect()
+        .nonEmpty
+      val topologyAfter = snapshotTopology()
+      val used1Packs: Dataset[_] =
+        usedPacks.filter($"used_name" =!= 
ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+      val used2Packs: Dataset[_] =
+        usedPacks2.filter($"used_name" =!= 
ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+      val usedChanged = used1Packs
+        .toDF()
+        .except(used2Packs.toDF())
+        .union(used2Packs.toDF().except(used1Packs.toDF()))
+        .limit(1)
+        .count() > 0
+      val abort =
+        skipGc || skipGc2 || candidateSkipGc || topologyBefore != 
topologyAfter || usedChanged
+      if (abort) {
+        logWarning(
+          s"Skip managed blob pack GC for table ${table.fullName()} because 
sidecars, manifests, or candidate identities cannot be trusted, or used packs 
changed during collection.")
+      }
+
+      val unused =
+        canonicalCandidates.join(used2Packs.toDF(), $"name" === $"used_name", 
"left_anti")
+      val toDelete = if (abort) unused.limit(0) else unused
+
+      val deleted: Dataset[(Long, Long)] = toDelete
+        .repartition(parallelism, $"dataDir")
+        .mapPartitions {
+          it =>
+            var deletedFilesCount = 0L
+            var deletedFilesLenInBytes = 0L
+            val dataDirs = new mutable.HashSet[String]()
+            while (it.hasNext) {
+              val fileInfo = it.next()
+              val pathToClean = fileInfo.getString(1)
+              val deletedPath = new Path(pathToClean)
+              if (cleanManagedBlobFile(deletedPath)) {
+                deletedFilesLenInBytes += fileInfo.getLong(2)
+                logInfo(s"Cleaned managed blob pack: $pathToClean")
+                dataDirs.add(fileInfo.getString(3))
+                deletedFilesCount += 1
+              }
+            }
+            if (!dryRun) {
+              val bucketDirs = dataDirs
+                .filter(_.contains(BUCKET_PATH_PREFIX))
+                .map(new Path(_))
+              tryCleanDataDirectory(bucketDirs.asJava, partitionKeysNum + 1)
+            }
+            Iterator.single((deletedFilesCount, deletedFilesLenInBytes))
+        }
+
+      (deleted, cached.toSeq)
+    } catch {
+      case t: Throwable =>
+        cached.foreach(_.unpersist())
+        throw t
+    }
+  }
+
+  private[procedure] def collectUsedPacksDf(): Dataset[_] = {
+    import spark.implicits._
+    val branches = validBranches()
+    val maxBranchParallelism = Math.min(branches.size(), parallelism)
+    val manifestLists = spark.sparkContext
+      .parallelize(branches.asScala.toSeq, maxBranchParallelism)
+      .flatMap {
+        branch =>
+          safelyGetAllSnapshots(branch).asScala.flatMap {
+            snapshot =>
+              Seq(
+                snapshot.changelogManifestList(),
+                snapshot.deltaManifestList(),
+                snapshot.baseManifestList())
+                .filter(_ != null)
+                .map((branch, _))
+          }
+      }
+      .distinct(parallelism)
+
+    val manifests = manifestLists
+      .mapPartitions {
+        lists =>
+          val branchManifestLists = new util.HashMap[String, ManifestList]()
+          lists.flatMap {
+            case (branch, listName) =>
+              val manifestList = branchManifestLists.computeIfAbsent(
+                branch,
+                (key: String) =>
+                  
specifiedTable.switchToBranch(key).store.manifestListFactory.create)
+              val metas = retryReadingFiles[java.util.List[ManifestFileMeta]](
+                () => manifestList.readWithIOException(listName),
+                null)
+              if (metas == null) {
+                logWarning(
+                  s"Manifest list $listName is missing while collecting used 
managed blob packs. Skip pack GC this run.")
+                Iterator.single((true, branch, listName))
+              } else {
+                metas.asScala.iterator.map(meta => (false, branch, 
meta.fileName()))
+              }
+          }
+      }
+      .distinct(parallelism)
+
+    val sidecarWorkItems = manifests
+      .mapPartitions {
+        records =>
+          val branchManifestFiles = new util.HashMap[String, ManifestFile]()
+          val branchPathFactories = new util.HashMap[String, 
DataFilePathFactories]()
+          records.flatMap {
+            case (unsafe, _, _) if unsafe =>
+              Iterator.single(
+                (ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC, null: 
SidecarWorkItem))
+            case (_, branch, manifestName) =>
+              val branchTable = specifiedTable.switchToBranch(branch)
+              val manifestFile = branchManifestFiles.computeIfAbsent(
+                branch,
+                (_: String) => branchTable.store.manifestFileFactory.create)
+              val pathFactories = branchPathFactories.computeIfAbsent(
+                branch,
+                (_: String) => new 
DataFilePathFactories(branchTable.store.pathFactory))
+              val entries =
+                retryReadingFiles(() => 
manifestFile.readWithIOException(manifestName), null)
+              if (entries == null) {
+                logWarning(
+                  s"Manifest $manifestName is missing while collecting used 
managed blob packs. Skip pack GC this run.")
+                Iterator.single(
+                  (ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC, null: 
SidecarWorkItem))
+              } else {
+                entries.asScala.iterator.flatMap {
+                  entry =>
+                    createSidecarWorkItemsForSpark(
+                      entry,
+                      pathFactories.get(entry.partition(), 
entry.bucket())).asScala.iterator
+                      .map(workItem => (workItem.dedupIdentity(), workItem))
+                }
+              }
+          }
+      }
+      .distinct(parallelism)
+
+    sidecarWorkItems
+      .mapPartitions {
+        records =>
+          val scan = newReachabilityScan()
+          records.flatMap {
+            case (_, null) =>
+              Iterator.single(ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+            case (_, workItem) =>
+              val names = new util.ArrayList[String]()
+              emitUsedPacksForSpark(
+                workItem,
+                scan,
+                new Consumer[String] {
+                  override def accept(name: String): Unit = names.add(name)
+                })
+              names.iterator().asScala
+          }
+      }
+      .toDF("used_name")
+  }
+
+}
+
+object SparkManagedBlobOrphanFilesClean extends SQLConfHelper {
+
+  private def checkParallelism(parallelism: Int): Unit = {
+    Preconditions.checkArgument(
+      parallelism > 0,
+      "Parallelism must be greater than 0, but was %s.",
+      Int.box(parallelism))
+  }
+
+  def executeDatabase(
+      catalog: Catalog,
+      databaseName: String,
+      tableName: String,
+      olderThanMillis: Long,
+      parallelismOpt: Integer,
+      dryRun: Boolean): CleanOrphanFilesResult = {
+    val spark = PaimonSparkSession.active
+    val parallelism = if (parallelismOpt == null) {
+      Math.max(spark.sparkContext.defaultParallelism, 
conf.numShufflePartitions)
+    } else {
+      parallelismOpt.intValue()
+    }
+    checkParallelism(parallelism)
+
+    val tableNames = if (tableName == null || "*" == tableName) {
+      catalog.listTables(databaseName).asScala
+    } else {
+      tableName :: Nil
+    }
+    val tables = tableNames.map {
+      tableName =>
+        val identifier = new Identifier(databaseName, tableName)
+        val table = catalog.getTable(identifier)
+        assert(
+          table.isInstanceOf[FileStoreTable],
+          s"Only FileStoreTable supports remove-orphan-blobs action. The table 
type is '${table.getClass.getName}'.")
+        table.asInstanceOf[FileStoreTable]
+    }
+    if (tables.isEmpty) {
+      return new CleanOrphanFilesResult(0, 0)
+    }
+    val deleted = new mutable.ArrayBuffer[Dataset[(Long, Long)]]()
+    val waitToRelease = new mutable.ArrayBuffer[Dataset[_]]()
+    try {
+      tables.foreach {
+        table =>
+          val (tableDeleted, tableCached) = new 
SparkManagedBlobOrphanFilesClean(
+            table,
+            olderThanMillis,
+            parallelism,
+            dryRun,
+            spark
+          ).doClean()
+          waitToRelease ++= tableCached

Review Comment:
   [P2] Bound cache lifetime for database-wide cleanup
   
   For `database.*`, each table materializes two used-pack marks plus 
candidates, but every table's three cached datasets remain in `waitToRelease` 
until all tables have been scanned and the combined deletion action finishes. 
Cache/disk usage therefore grows with the whole database rather than the 
largest table, causing eviction/recomputation, excessive spill, or cleanup 
failure; it also widens the cache-recomputation window described in the P1 
comment. Please execute and aggregate one table at a time and unpersist its 
datasets in a per-table `finally`, or process a bounded number of tables per 
batch.



##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/orphan/FlinkManagedBlobOrphanFilesClean.java:
##########
@@ -0,0 +1,867 @@
+/*
+ * 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.flink.orphan;
+
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.flink.utils.BoundedOneInputOperator;
+import org.apache.paimon.flink.utils.BoundedTwoInputOperator;
+import org.apache.paimon.fs.FileStatus;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.manifest.ManifestEntry;
+import org.apache.paimon.manifest.ManifestFile;
+import org.apache.paimon.manifest.ManifestFileMeta;
+import org.apache.paimon.manifest.ManifestList;
+import org.apache.paimon.operation.CleanOrphanFilesResult;
+import org.apache.paimon.operation.ManagedBlobOrphanFilesClean;
+import org.apache.paimon.operation.ManagedBlobOrphanFilesClean.SidecarWorkItem;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.Table;
+import org.apache.paimon.utils.DataFilePathFactories;
+import org.apache.paimon.utils.FileStorePathFactory;
+
+import org.apache.flink.api.common.RuntimeExecutionMode;
+import org.apache.flink.api.common.functions.OpenContext;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.api.java.tuple.Tuple3;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.CoreOptions;
+import org.apache.flink.configuration.ExecutionOptions;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.streaming.api.functions.sink.v2.DiscardingSink;
+import org.apache.flink.streaming.api.operators.InputSelection;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.CloseableIterator;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.OutputTag;
+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.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Consumer;
+
+import static 
org.apache.flink.api.common.typeinfo.BasicTypeInfo.STRING_TYPE_INFO;
+import static org.apache.flink.util.Preconditions.checkState;
+import static org.apache.paimon.utils.FileStorePathFactory.BUCKET_PATH_PREFIX;
+import static org.apache.paimon.utils.Preconditions.checkArgument;
+
+/** Flink {@link ManagedBlobOrphanFilesClean}. */
+public class FlinkManagedBlobOrphanFilesClean extends 
ManagedBlobOrphanFilesClean {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FlinkManagedBlobOrphanFilesClean.class);
+
+    @Nullable private final Integer parallelism;
+
+    public FlinkManagedBlobOrphanFilesClean(
+            FileStoreTable table,
+            long olderThanMillis,
+            boolean dryRun,
+            @Nullable Integer parallelism) {
+        super(table, olderThanMillis, dryRun);
+        validateParallelism(parallelism);
+        this.parallelism = parallelism;
+    }
+
+    @Nullable
+    public DataStream<CleanOrphanFilesResult> 
doClean(StreamExecutionEnvironment env) {
+        List<String> topologyBefore;
+        try {
+            topologyBefore = snapshotTopology();
+        } catch (java.io.IOException e) {
+            throw new RuntimeException(e);
+        }
+
+        Configuration flinkConf = new Configuration();
+        flinkConf.set(ExecutionOptions.RUNTIME_MODE, 
RuntimeExecutionMode.BATCH);
+        flinkConf.set(ExecutionOptions.SORT_INPUTS, false);
+        flinkConf.set(ExecutionOptions.USE_BATCH_STATE_BACKEND, false);
+        if (parallelism != null) {
+            flinkConf.set(CoreOptions.DEFAULT_PARALLELISM, parallelism);
+        }
+        
flinkConf.setString("execution.batch.adaptive.auto-parallelism.enabled", 
"false");
+        env.configure(flinkConf);
+
+        List<String> branches = validBranches();
+        final OutputTag<Boolean> firstMarkSkipGcTag =
+                new OutputTag<Boolean>("first-managed-blob-mark-skip") {};
+        SingleOutputStreamOperator<Tuple2<String, String>> firstManifestLists =
+                env.fromCollection(branches)
+                        .name("branch-source")
+                        .process(
+                                new ProcessFunction<String, Tuple2<String, 
String>>() {
+                                    @Override
+                                    public void processElement(
+                                            String branch,
+                                            ProcessFunction<String, 
Tuple2<String, String>>.Context
+                                                    ctx,
+                                            Collector<Tuple2<String, String>> 
out)
+                                            throws Exception {
+                                        emitManifestLists(branch, 
out::collect);
+                                    }
+                                })
+                        .name("collect-first-mark-manifest-lists");
+
+        SingleOutputStreamOperator<String> usedPacks =
+                collectUsedPacks(firstManifestLists, firstMarkSkipGcTag, 
"first");
+
+        DataStream<Boolean> firstMarkCompleted = markCompletion(usedPacks, 
"first");
+        SingleOutputStreamOperator<Tuple2<String, String>> secondManifestLists 
=
+                firstMarkCompleted
+                        .transform(
+                                "wait-before-second-managed-blob-mark",
+                                Types.TUPLE(Types.STRING, Types.STRING),
+                                new BoundedOneInputOperator<Boolean, 
Tuple2<String, String>>() {
+
+                                    @Override
+                                    public void 
processElement(StreamRecord<Boolean> element) {}
+
+                                    @Override
+                                    public void endInput() throws Exception {
+                                        for (String branch : branches) {
+                                            emitManifestLists(
+                                                    branch,
+                                                    manifestList ->
+                                                            output.collect(
+                                                                    new 
StreamRecord<>(
+                                                                            
manifestList)));
+                                        }
+                                    }
+                                })
+                        .forceNonParallel();
+
+        final OutputTag<Boolean> secondMarkSkipGcTag =
+                new OutputTag<Boolean>("second-managed-blob-mark-skip") {};
+        SingleOutputStreamOperator<String> usedPacks2 =
+                collectUsedPacks(secondManifestLists, secondMarkSkipGcTag, 
"second");
+
+        DataStream<Boolean> usedPacksChanged = compareUsedPacks(usedPacks, 
usedPacks2);
+        DataStream<Boolean> topologyChanged =
+                markCompletion(usedPacks2, "second")
+                        .transform(
+                                "check-managed-blob-snapshot-topology",
+                                TypeInformation.of(Boolean.class),
+                                new BoundedOneInputOperator<Boolean, 
Boolean>() {
+
+                                    @Override
+                                    public void 
processElement(StreamRecord<Boolean> element) {}
+
+                                    @Override
+                                    public void endInput() throws Exception {
+                                        List<String> topologyAfter = 
snapshotTopology();
+                                        if 
(!topologyBefore.equals(topologyAfter)) {
+                                            LOG.warn(
+                                                    "Skip managed blob pack GC 
for table {} because snapshot topology changed during used-pack collection.",
+                                                    table.fullName());
+                                            output.collect(new 
StreamRecord<>(Boolean.TRUE));
+                                        }
+                                    }
+                                })
+                        .forceNonParallel();
+
+        final OutputTag<Boolean> candidateSkipGcTag =
+                new OutputTag<Boolean>("candidate-managed-blob-skip") {};
+        SingleOutputStreamOperator<Tuple3<String, String, Long>> candidates =
+                env.fromCollection(Collections.singletonList(1), 
TypeInformation.of(Integer.class))
+                        .process(
+                                new ProcessFunction<Integer, String>() {
+                                    @Override
+                                    public void processElement(
+                                            Integer i,
+                                            ProcessFunction<Integer, 
String>.Context ctx,
+                                            Collector<String> out) {
+                                        FileStorePathFactory pathFactory =
+                                                table.store().pathFactory();
+                                        listPaimonFileDirs(
+                                                        table.fullName(),
+                                                        
pathFactory.manifestPath().toString(),
+                                                        
pathFactory.indexPath().toString(),
+                                                        
pathFactory.statisticsPath().toString(),
+                                                        
pathFactory.dataFilePath().toString(),
+                                                        partitionKeysNum,
+                                                        
table.coreOptions().dataFileExternalPaths())
+                                                .stream()
+                                                .map(Path::toUri)
+                                                .map(Object::toString)
+                                                .forEach(out::collect);
+                                    }
+                                })
+                        .name("list-dirs")
+                        .forceNonParallel()
+                        .process(
+                                new ProcessFunction<String, Tuple3<String, 
String, Long>>() {
+                                    @Override
+                                    public void processElement(
+                                            String dir,
+                                            ProcessFunction<String, 
Tuple3<String, String, Long>>
+                                                            .Context
+                                                    ctx,
+                                            Collector<Tuple3<String, String, 
Long>> out) {
+                                        for (FileStatus file : 
tryBestListingDirs(new Path(dir))) {
+                                            if (!file.isDir()
+                                                    && oldEnough(file)
+                                                    && isManagedBlobPackName(
+                                                            
file.getPath().getName())) {
+                                                Optional<String> identity =
+                                                        
FlinkManagedBlobOrphanFilesClean.this
+                                                                
.packIdentityForCleanup(
+                                                                        
file.getPath());
+                                                if (identity.isPresent()) {
+                                                    out.collect(
+                                                            Tuple3.of(
+                                                                    
identity.get(),
+                                                                    
file.getPath().toString(),
+                                                                    
file.getLen()));
+                                                } else {
+                                                    LOG.warn(
+                                                            "Cannot safely 
identify candidate managed blob pack {}. Skip pack GC this run.",
+                                                            file.getPath());
+                                                    
ctx.output(candidateSkipGcTag, Boolean.TRUE);
+                                                }
+                                            }
+                                        }
+                                    }
+                                })
+                        .name("collect-candidate-packs");
+
+        final OutputTag<Tuple2<String, Long>> unusedPackTag =
+                new OutputTag<Tuple2<String, Long>>("unused-managed-blob") {};
+
+        SingleOutputStreamOperator<CleanOrphanFilesResult> unusedJoin =
+                usedPacks2
+                        .keyBy(identity -> identity)
+                        .connect(candidates.keyBy(candidate -> candidate.f0))
+                        .transform(
+                                "join-used-and-candidate-packs",
+                                
TypeInformation.of(CleanOrphanFilesResult.class),
+                                new BoundedTwoInputOperator<
+                                        String,
+                                        Tuple3<String, String, Long>,
+                                        CleanOrphanFilesResult>() {
+
+                                    private boolean buildEnd;
+                                    private final Set<String> used = new 
HashSet<>();
+
+                                    @Override
+                                    public InputSelection nextSelection() {
+                                        return buildEnd
+                                                ? InputSelection.SECOND
+                                                : InputSelection.FIRST;
+                                    }
+
+                                    @Override
+                                    public void endInput(int inputId) {
+                                        switch (inputId) {
+                                            case 1:
+                                                checkState(!buildEnd, "Should 
not build ended.");
+                                                buildEnd = true;
+                                                break;
+                                            case 2:
+                                                checkState(buildEnd, "Should 
build ended.");
+                                                output.collect(
+                                                        new StreamRecord<>(
+                                                                new 
CleanOrphanFilesResult(0, 0)));
+                                                break;
+                                        }
+                                    }
+
+                                    @Override
+                                    public void 
processElement1(StreamRecord<String> element) {
+                                        used.add(element.getValue());
+                                    }
+
+                                    @Override
+                                    public void processElement2(
+                                            StreamRecord<Tuple3<String, 
String, Long>> element) {
+                                        checkState(buildEnd, "Should build 
ended.");
+                                        Tuple3<String, String, Long> candidate 
= element.getValue();
+                                        if (!used.contains(candidate.f0)) {
+                                            output.collect(
+                                                    unusedPackTag,
+                                                    new StreamRecord<>(
+                                                            
Tuple2.of(candidate.f1, candidate.f2)));
+                                        }
+                                    }
+                                });
+
+        DataStream<Boolean> skipGc =
+                usedPacks
+                        .getSideOutput(firstMarkSkipGcTag)
+                        .union(
+                                usedPacks2.getSideOutput(secondMarkSkipGcTag),
+                                usedPacksChanged,
+                                topologyChanged,
+                                candidates.getSideOutput(candidateSkipGcTag));
+
+        final OutputTag<Path> emptyDirTag = new 
OutputTag<Path>("empty-managed-blob-dir") {};
+        SingleOutputStreamOperator<CleanOrphanFilesResult> cleaned =
+                unusedJoin
+                        .getSideOutput(unusedPackTag)
+                        .connect(skipGc.broadcast())
+                        .transform(
+                                "clean-unused-managed-blobs",
+                                
TypeInformation.of(CleanOrphanFilesResult.class),
+                                new BoundedTwoInputOperator<
+                                        Tuple2<String, Long>, Boolean, 
CleanOrphanFilesResult>() {
+
+                                    private boolean skipEnded;
+                                    private boolean skipGc;
+                                    private long emittedFilesCount;
+                                    private long emittedFilesLen;
+
+                                    @Override
+                                    public InputSelection nextSelection() {
+                                        return skipEnded
+                                                ? InputSelection.FIRST
+                                                : InputSelection.SECOND;
+                                    }
+
+                                    @Override
+                                    public void endInput(int inputId) {
+                                        switch (inputId) {
+                                            case 2:
+                                                checkState(!skipEnded, "Should 
not skip ended.");
+                                                skipEnded = true;
+                                                LOG.info("Managed blob GC skip 
flag: {}", skipGc);
+                                                break;
+                                            case 1:
+                                                checkState(skipEnded, "Should 
skip ended.");
+                                                output.collect(
+                                                        new StreamRecord<>(
+                                                                new 
CleanOrphanFilesResult(
+                                                                        
emittedFilesCount,
+                                                                        
emittedFilesLen)));
+                                                break;
+                                        }
+                                    }
+
+                                    @Override
+                                    public void processElement1(
+                                            StreamRecord<Tuple2<String, Long>> 
element) {
+                                        checkState(skipEnded, "Should skip 
ended.");
+                                        if (skipGc) {
+                                            return;
+                                        }
+                                        Tuple2<String, Long> fileInfo = 
element.getValue();
+                                        Path path = new Path(fileInfo.f0);
+                                        if (cleanPack(path)) {

Review Comment:
   [P2] Make deletion accounting stable across retries
   
   These counters are attempt-local and are emitted only from `endInput`. If an 
attempt deletes pack A and then the TaskManager/operator fails before emitting 
its result, a restarted attempt resets the counters and sees A already absent, 
so the final successful job omits A from the returned count and byte total. 
Please either disable retries for the destructive phase or persist 
attempt-independent, idempotent deletion accounting. Add a MiniCluster failover 
test that fails after one successful delete and verifies the final aggregate.



##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/procedure/SparkManagedBlobOrphanFilesClean.scala:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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.spark.procedure
+
+import org.apache.paimon.catalog.{Catalog, Identifier}
+import org.apache.paimon.fs.Path
+import org.apache.paimon.manifest.{ManifestFile, ManifestFileMeta, 
ManifestList}
+import org.apache.paimon.operation.{CleanOrphanFilesResult, 
ManagedBlobOrphanFilesClean}
+import org.apache.paimon.operation.ManagedBlobOrphanFilesClean.SidecarWorkItem
+import org.apache.paimon.operation.OrphanFilesClean.retryReadingFiles
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.utils.DataFilePathFactories
+import org.apache.paimon.utils.FileStorePathFactory.BUCKET_PATH_PREFIX
+import org.apache.paimon.utils.Preconditions
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.{functions, Dataset, PaimonSparkSession, 
SparkSession}
+import org.apache.spark.sql.catalyst.SQLConfHelper
+
+import java.util
+import java.util.function.Consumer
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+case class SparkManagedBlobOrphanFilesClean(
+    specifiedTable: FileStoreTable,
+    specifiedOlderThanMillis: Long,
+    parallelism: Int,
+    dryRunPara: Boolean,
+    @transient spark: SparkSession)
+  extends SparkManagedBlobOrphanFilesCleanBase(specifiedTable, 
specifiedOlderThanMillis, dryRunPara)
+  with SQLConfHelper
+  with Logging {
+
+  def doClean(): (Dataset[(Long, Long)], Seq[Dataset[_]]) = {
+    import spark.implicits._
+
+    SparkManagedBlobOrphanFilesClean.checkParallelism(parallelism)
+    val cached = new mutable.ArrayBuffer[Dataset[_]]()
+    try {
+      val topologyBefore = snapshotTopology()
+      val usedPacks = collectUsedPacksDf().cache()
+      cached += usedPacks
+      val skipGc = usedPacks
+        .filter($"used_name" === 
ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+        .limit(1)
+        .collect()
+        .nonEmpty
+
+      val fileDirs = listPaimonFileDirs.asScala.map(_.toString).toSeq
+      val maxFileDirsParallelism = Math.min(Math.max(fileDirs.size, 1), 
parallelism)
+      val candidates = spark.sparkContext
+        .parallelize(fileDirs, maxFileDirsParallelism)
+        .flatMap {
+          dir =>
+            tryBestListingDirs(new Path(dir)).asScala
+              .filter(file => !file.isDir)
+              .filter(oldEnough)
+              .filter(
+                file => 
ManagedBlobOrphanFilesClean.isManagedBlobPackName(file.getPath.getName))
+              .map {
+                file =>
+                  val path = file.getPath
+                  val parent = path.getParent
+                  (
+                    packIdentityForCandidate(path),
+                    path.toString,
+                    file.getLen,
+                    if (parent == null) "" else parent.toString)
+              }
+        }
+        .toDF("name", "path", "len", "dataDir")
+        .repartition(parallelism)
+        .cache()
+      cached += candidates
+      val candidateSkipGc = candidates
+        .filter($"name" === ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+        .limit(1)
+        .collect()
+        .nonEmpty
+      val canonicalCandidates = candidates
+        .filter($"name" =!= ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+
+      betweenUsedCollections()
+      val usedPacks2 = collectUsedPacksDf().cache()
+      cached += usedPacks2
+      val skipGc2 = usedPacks2
+        .filter($"used_name" === 
ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+        .limit(1)
+        .collect()
+        .nonEmpty
+      val topologyAfter = snapshotTopology()
+      val used1Packs: Dataset[_] =
+        usedPacks.filter($"used_name" =!= 
ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+      val used2Packs: Dataset[_] =
+        usedPacks2.filter($"used_name" =!= 
ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+      val usedChanged = used1Packs
+        .toDF()
+        .except(used2Packs.toDF())
+        .union(used2Packs.toDF().except(used1Packs.toDF()))
+        .limit(1)
+        .count() > 0
+      val abort =
+        skipGc || skipGc2 || candidateSkipGc || topologyBefore != 
topologyAfter || usedChanged
+      if (abort) {
+        logWarning(
+          s"Skip managed blob pack GC for table ${table.fullName()} because 
sidecars, manifests, or candidate identities cannot be trusted, or used packs 
changed during collection.")
+      }
+
+      val unused =
+        canonicalCandidates.join(used2Packs.toDF(), $"name" === $"used_name", 
"left_anti")
+      val toDelete = if (abort) unused.limit(0) else unused
+
+      val deleted: Dataset[(Long, Long)] = toDelete
+        .repartition(parallelism, $"dataDir")
+        .mapPartitions {
+          it =>
+            var deletedFilesCount = 0L
+            var deletedFilesLenInBytes = 0L
+            val dataDirs = new mutable.HashSet[String]()
+            while (it.hasNext) {
+              val fileInfo = it.next()
+              val pathToClean = fileInfo.getString(1)
+              val deletedPath = new Path(pathToClean)
+              if (cleanManagedBlobFile(deletedPath)) {
+                deletedFilesLenInBytes += fileInfo.getLong(2)
+                logInfo(s"Cleaned managed blob pack: $pathToClean")
+                dataDirs.add(fileInfo.getString(3))
+                deletedFilesCount += 1
+              }
+            }
+            if (!dryRun) {
+              val bucketDirs = dataDirs
+                .filter(_.contains(BUCKET_PATH_PREFIX))
+                .map(new Path(_))
+              tryCleanDataDirectory(bucketDirs.asJava, partitionKeysNum + 1)
+            }
+            Iterator.single((deletedFilesCount, deletedFilesLenInBytes))
+        }
+
+      (deleted, cached.toSeq)
+    } catch {
+      case t: Throwable =>
+        cached.foreach(_.unpersist())
+        throw t
+    }
+  }
+
+  private[procedure] def collectUsedPacksDf(): Dataset[_] = {
+    import spark.implicits._
+    val branches = validBranches()
+    val maxBranchParallelism = Math.min(branches.size(), parallelism)
+    val manifestLists = spark.sparkContext
+      .parallelize(branches.asScala.toSeq, maxBranchParallelism)
+      .flatMap {
+        branch =>
+          safelyGetAllSnapshots(branch).asScala.flatMap {
+            snapshot =>
+              Seq(
+                snapshot.changelogManifestList(),
+                snapshot.deltaManifestList(),
+                snapshot.baseManifestList())
+                .filter(_ != null)
+                .map((branch, _))
+          }
+      }
+      .distinct(parallelism)
+
+    val manifests = manifestLists
+      .mapPartitions {
+        lists =>
+          val branchManifestLists = new util.HashMap[String, ManifestList]()
+          lists.flatMap {
+            case (branch, listName) =>
+              val manifestList = branchManifestLists.computeIfAbsent(
+                branch,
+                (key: String) =>
+                  
specifiedTable.switchToBranch(key).store.manifestListFactory.create)
+              val metas = retryReadingFiles[java.util.List[ManifestFileMeta]](
+                () => manifestList.readWithIOException(listName),
+                null)
+              if (metas == null) {
+                logWarning(
+                  s"Manifest list $listName is missing while collecting used 
managed blob packs. Skip pack GC this run.")
+                Iterator.single((true, branch, listName))
+              } else {
+                metas.asScala.iterator.map(meta => (false, branch, 
meta.fileName()))
+              }
+          }
+      }
+      .distinct(parallelism)
+
+    val sidecarWorkItems = manifests
+      .mapPartitions {
+        records =>
+          val branchManifestFiles = new util.HashMap[String, ManifestFile]()
+          val branchPathFactories = new util.HashMap[String, 
DataFilePathFactories]()
+          records.flatMap {
+            case (unsafe, _, _) if unsafe =>
+              Iterator.single(
+                (ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC, null: 
SidecarWorkItem))
+            case (_, branch, manifestName) =>
+              val branchTable = specifiedTable.switchToBranch(branch)
+              val manifestFile = branchManifestFiles.computeIfAbsent(
+                branch,
+                (_: String) => branchTable.store.manifestFileFactory.create)
+              val pathFactories = branchPathFactories.computeIfAbsent(
+                branch,
+                (_: String) => new 
DataFilePathFactories(branchTable.store.pathFactory))
+              val entries =
+                retryReadingFiles(() => 
manifestFile.readWithIOException(manifestName), null)
+              if (entries == null) {
+                logWarning(
+                  s"Manifest $manifestName is missing while collecting used 
managed blob packs. Skip pack GC this run.")
+                Iterator.single(
+                  (ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC, null: 
SidecarWorkItem))
+              } else {
+                entries.asScala.iterator.flatMap {
+                  entry =>
+                    createSidecarWorkItemsForSpark(
+                      entry,
+                      pathFactories.get(entry.partition(), 
entry.bucket())).asScala.iterator
+                      .map(workItem => (workItem.dedupIdentity(), workItem))
+                }
+              }
+          }
+      }
+      .distinct(parallelism)
+
+    sidecarWorkItems
+      .mapPartitions {
+        records =>
+          val scan = newReachabilityScan()
+          records.flatMap {
+            case (_, null) =>
+              Iterator.single(ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC)
+            case (_, workItem) =>
+              val names = new util.ArrayList[String]()
+              emitUsedPacksForSpark(
+                workItem,
+                scan,
+                new Consumer[String] {
+                  override def accept(name: String): Unit = names.add(name)
+                })
+              names.iterator().asScala
+          }
+      }
+      .toDF("used_name")

Review Comment:
   [P2] Deduplicate pack identities before caching the mark
   
   The sidecars are distinct, but the emitted `used_name` identities are not. 
Compaction deliberately reuses packs, so retained old and new data files can 
contribute the same identity repeatedly; both mark caches and the final 
anti-join then retain and shuffle every occurrence. Local mode returns a `Set`, 
and the Flink path performs a keyed identity deduplication. Please apply a 
distributed `distinct(parallelism)` before returning/caching this DataFrame and 
cover multiple distinct sidecars referencing one pack.



##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/orphan/FlinkManagedBlobOrphanFilesClean.java:
##########
@@ -0,0 +1,867 @@
+/*
+ * 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.flink.orphan;
+
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.flink.utils.BoundedOneInputOperator;
+import org.apache.paimon.flink.utils.BoundedTwoInputOperator;
+import org.apache.paimon.fs.FileStatus;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.manifest.ManifestEntry;
+import org.apache.paimon.manifest.ManifestFile;
+import org.apache.paimon.manifest.ManifestFileMeta;
+import org.apache.paimon.manifest.ManifestList;
+import org.apache.paimon.operation.CleanOrphanFilesResult;
+import org.apache.paimon.operation.ManagedBlobOrphanFilesClean;
+import org.apache.paimon.operation.ManagedBlobOrphanFilesClean.SidecarWorkItem;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.Table;
+import org.apache.paimon.utils.DataFilePathFactories;
+import org.apache.paimon.utils.FileStorePathFactory;
+
+import org.apache.flink.api.common.RuntimeExecutionMode;
+import org.apache.flink.api.common.functions.OpenContext;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.api.java.tuple.Tuple3;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.CoreOptions;
+import org.apache.flink.configuration.ExecutionOptions;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.streaming.api.functions.sink.v2.DiscardingSink;
+import org.apache.flink.streaming.api.operators.InputSelection;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.CloseableIterator;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.OutputTag;
+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.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Consumer;
+
+import static 
org.apache.flink.api.common.typeinfo.BasicTypeInfo.STRING_TYPE_INFO;
+import static org.apache.flink.util.Preconditions.checkState;
+import static org.apache.paimon.utils.FileStorePathFactory.BUCKET_PATH_PREFIX;
+import static org.apache.paimon.utils.Preconditions.checkArgument;
+
+/** Flink {@link ManagedBlobOrphanFilesClean}. */
+public class FlinkManagedBlobOrphanFilesClean extends 
ManagedBlobOrphanFilesClean {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FlinkManagedBlobOrphanFilesClean.class);
+
+    @Nullable private final Integer parallelism;
+
+    public FlinkManagedBlobOrphanFilesClean(
+            FileStoreTable table,
+            long olderThanMillis,
+            boolean dryRun,
+            @Nullable Integer parallelism) {
+        super(table, olderThanMillis, dryRun);
+        validateParallelism(parallelism);
+        this.parallelism = parallelism;
+    }
+
+    @Nullable
+    public DataStream<CleanOrphanFilesResult> 
doClean(StreamExecutionEnvironment env) {
+        List<String> topologyBefore;
+        try {
+            topologyBefore = snapshotTopology();
+        } catch (java.io.IOException e) {
+            throw new RuntimeException(e);
+        }
+
+        Configuration flinkConf = new Configuration();
+        flinkConf.set(ExecutionOptions.RUNTIME_MODE, 
RuntimeExecutionMode.BATCH);
+        flinkConf.set(ExecutionOptions.SORT_INPUTS, false);
+        flinkConf.set(ExecutionOptions.USE_BATCH_STATE_BACKEND, false);
+        if (parallelism != null) {
+            flinkConf.set(CoreOptions.DEFAULT_PARALLELISM, parallelism);
+        }
+        
flinkConf.setString("execution.batch.adaptive.auto-parallelism.enabled", 
"false");
+        env.configure(flinkConf);
+
+        List<String> branches = validBranches();
+        final OutputTag<Boolean> firstMarkSkipGcTag =
+                new OutputTag<Boolean>("first-managed-blob-mark-skip") {};
+        SingleOutputStreamOperator<Tuple2<String, String>> firstManifestLists =
+                env.fromCollection(branches)
+                        .name("branch-source")
+                        .process(
+                                new ProcessFunction<String, Tuple2<String, 
String>>() {
+                                    @Override
+                                    public void processElement(
+                                            String branch,
+                                            ProcessFunction<String, 
Tuple2<String, String>>.Context
+                                                    ctx,
+                                            Collector<Tuple2<String, String>> 
out)
+                                            throws Exception {
+                                        emitManifestLists(branch, 
out::collect);
+                                    }
+                                })
+                        .name("collect-first-mark-manifest-lists");
+
+        SingleOutputStreamOperator<String> usedPacks =
+                collectUsedPacks(firstManifestLists, firstMarkSkipGcTag, 
"first");
+
+        DataStream<Boolean> firstMarkCompleted = markCompletion(usedPacks, 
"first");
+        SingleOutputStreamOperator<Tuple2<String, String>> secondManifestLists 
=
+                firstMarkCompleted
+                        .transform(
+                                "wait-before-second-managed-blob-mark",
+                                Types.TUPLE(Types.STRING, Types.STRING),
+                                new BoundedOneInputOperator<Boolean, 
Tuple2<String, String>>() {
+
+                                    @Override
+                                    public void 
processElement(StreamRecord<Boolean> element) {}
+
+                                    @Override
+                                    public void endInput() throws Exception {
+                                        for (String branch : branches) {
+                                            emitManifestLists(
+                                                    branch,
+                                                    manifestList ->
+                                                            output.collect(
+                                                                    new 
StreamRecord<>(
+                                                                            
manifestList)));
+                                        }
+                                    }
+                                })
+                        .forceNonParallel();
+
+        final OutputTag<Boolean> secondMarkSkipGcTag =
+                new OutputTag<Boolean>("second-managed-blob-mark-skip") {};
+        SingleOutputStreamOperator<String> usedPacks2 =
+                collectUsedPacks(secondManifestLists, secondMarkSkipGcTag, 
"second");
+
+        DataStream<Boolean> usedPacksChanged = compareUsedPacks(usedPacks, 
usedPacks2);
+        DataStream<Boolean> topologyChanged =
+                markCompletion(usedPacks2, "second")
+                        .transform(
+                                "check-managed-blob-snapshot-topology",
+                                TypeInformation.of(Boolean.class),
+                                new BoundedOneInputOperator<Boolean, 
Boolean>() {
+
+                                    @Override
+                                    public void 
processElement(StreamRecord<Boolean> element) {}
+
+                                    @Override
+                                    public void endInput() throws Exception {
+                                        List<String> topologyAfter = 
snapshotTopology();
+                                        if 
(!topologyBefore.equals(topologyAfter)) {
+                                            LOG.warn(
+                                                    "Skip managed blob pack GC 
for table {} because snapshot topology changed during used-pack collection.",
+                                                    table.fullName());
+                                            output.collect(new 
StreamRecord<>(Boolean.TRUE));
+                                        }
+                                    }
+                                })
+                        .forceNonParallel();
+
+        final OutputTag<Boolean> candidateSkipGcTag =
+                new OutputTag<Boolean>("candidate-managed-blob-skip") {};
+        SingleOutputStreamOperator<Tuple3<String, String, Long>> candidates =
+                env.fromCollection(Collections.singletonList(1), 
TypeInformation.of(Integer.class))
+                        .process(
+                                new ProcessFunction<Integer, String>() {
+                                    @Override
+                                    public void processElement(
+                                            Integer i,
+                                            ProcessFunction<Integer, 
String>.Context ctx,
+                                            Collector<String> out) {
+                                        FileStorePathFactory pathFactory =
+                                                table.store().pathFactory();
+                                        listPaimonFileDirs(
+                                                        table.fullName(),
+                                                        
pathFactory.manifestPath().toString(),
+                                                        
pathFactory.indexPath().toString(),
+                                                        
pathFactory.statisticsPath().toString(),
+                                                        
pathFactory.dataFilePath().toString(),
+                                                        partitionKeysNum,
+                                                        
table.coreOptions().dataFileExternalPaths())
+                                                .stream()
+                                                .map(Path::toUri)
+                                                .map(Object::toString)
+                                                .forEach(out::collect);
+                                    }
+                                })
+                        .name("list-dirs")
+                        .forceNonParallel()
+                        .process(
+                                new ProcessFunction<String, Tuple3<String, 
String, Long>>() {
+                                    @Override
+                                    public void processElement(
+                                            String dir,
+                                            ProcessFunction<String, 
Tuple3<String, String, Long>>
+                                                            .Context
+                                                    ctx,
+                                            Collector<Tuple3<String, String, 
Long>> out) {
+                                        for (FileStatus file : 
tryBestListingDirs(new Path(dir))) {
+                                            if (!file.isDir()
+                                                    && oldEnough(file)
+                                                    && isManagedBlobPackName(
+                                                            
file.getPath().getName())) {
+                                                Optional<String> identity =
+                                                        
FlinkManagedBlobOrphanFilesClean.this
+                                                                
.packIdentityForCleanup(
+                                                                        
file.getPath());
+                                                if (identity.isPresent()) {
+                                                    out.collect(
+                                                            Tuple3.of(
+                                                                    
identity.get(),
+                                                                    
file.getPath().toString(),
+                                                                    
file.getLen()));
+                                                } else {
+                                                    LOG.warn(
+                                                            "Cannot safely 
identify candidate managed blob pack {}. Skip pack GC this run.",
+                                                            file.getPath());
+                                                    
ctx.output(candidateSkipGcTag, Boolean.TRUE);
+                                                }
+                                            }
+                                        }
+                                    }
+                                })
+                        .name("collect-candidate-packs");
+
+        final OutputTag<Tuple2<String, Long>> unusedPackTag =
+                new OutputTag<Tuple2<String, Long>>("unused-managed-blob") {};
+
+        SingleOutputStreamOperator<CleanOrphanFilesResult> unusedJoin =
+                usedPacks2
+                        .keyBy(identity -> identity)
+                        .connect(candidates.keyBy(candidate -> candidate.f0))
+                        .transform(
+                                "join-used-and-candidate-packs",
+                                
TypeInformation.of(CleanOrphanFilesResult.class),
+                                new BoundedTwoInputOperator<
+                                        String,
+                                        Tuple3<String, String, Long>,
+                                        CleanOrphanFilesResult>() {
+
+                                    private boolean buildEnd;
+                                    private final Set<String> used = new 
HashSet<>();
+
+                                    @Override
+                                    public InputSelection nextSelection() {
+                                        return buildEnd
+                                                ? InputSelection.SECOND
+                                                : InputSelection.FIRST;
+                                    }
+
+                                    @Override
+                                    public void endInput(int inputId) {
+                                        switch (inputId) {
+                                            case 1:
+                                                checkState(!buildEnd, "Should 
not build ended.");
+                                                buildEnd = true;
+                                                break;
+                                            case 2:
+                                                checkState(buildEnd, "Should 
build ended.");
+                                                output.collect(
+                                                        new StreamRecord<>(
+                                                                new 
CleanOrphanFilesResult(0, 0)));
+                                                break;
+                                        }
+                                    }
+
+                                    @Override
+                                    public void 
processElement1(StreamRecord<String> element) {
+                                        used.add(element.getValue());
+                                    }
+
+                                    @Override
+                                    public void processElement2(
+                                            StreamRecord<Tuple3<String, 
String, Long>> element) {
+                                        checkState(buildEnd, "Should build 
ended.");
+                                        Tuple3<String, String, Long> candidate 
= element.getValue();
+                                        if (!used.contains(candidate.f0)) {
+                                            output.collect(
+                                                    unusedPackTag,
+                                                    new StreamRecord<>(
+                                                            
Tuple2.of(candidate.f1, candidate.f2)));
+                                        }
+                                    }
+                                });
+
+        DataStream<Boolean> skipGc =
+                usedPacks
+                        .getSideOutput(firstMarkSkipGcTag)
+                        .union(
+                                usedPacks2.getSideOutput(secondMarkSkipGcTag),
+                                usedPacksChanged,
+                                topologyChanged,
+                                candidates.getSideOutput(candidateSkipGcTag));
+
+        final OutputTag<Path> emptyDirTag = new 
OutputTag<Path>("empty-managed-blob-dir") {};
+        SingleOutputStreamOperator<CleanOrphanFilesResult> cleaned =
+                unusedJoin
+                        .getSideOutput(unusedPackTag)
+                        .connect(skipGc.broadcast())
+                        .transform(
+                                "clean-unused-managed-blobs",
+                                
TypeInformation.of(CleanOrphanFilesResult.class),
+                                new BoundedTwoInputOperator<
+                                        Tuple2<String, Long>, Boolean, 
CleanOrphanFilesResult>() {
+
+                                    private boolean skipEnded;
+                                    private boolean skipGc;
+                                    private long emittedFilesCount;
+                                    private long emittedFilesLen;
+
+                                    @Override
+                                    public InputSelection nextSelection() {

Review Comment:
   [P2] Break the candidate/abort pipelined feedback cycle
   
   `skipGc` includes the candidate operator's side output, while input 1 
contains unused packs derived from that same operator's main output. This 
selection waits for input 2 to end before consuming input 1. With the supported 
`execution.batch-shuffle-mode=ALL_EXCHANGES_PIPELINED` and enough candidates to 
fill input-1 buffers, input 1 backpressures `unusedJoin`, then the candidate 
main output; the candidate operator cannot finish its side output, so input 2 
never ends and the job hangs. Please add a blocking/materialized boundary 
before deletion, force blocking exchanges for this job, or complete candidate 
validation as a separate phase. Add a constrained-buffer pipelined-shuffle 
regression.



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