Stephen0421 commented on code in PR #9207: URL: https://github.com/apache/paimon/pull/9207#discussion_r3892291648
########## 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: Thanks. Distributed deletes now use idempotent accounting: a pack already absent after a previous attempt is still counted, and candidates are keyed by canonical identity so aliases are counted once. Added a MiniCluster test that fails after the first successful delete; it collects operator output through a restart-safe sink because `executeAndCollect` throws `Job restarted` on failover. The production entrypoint still uses `executeAndCollect` (same as `remove_orphan_files`), so a failed-over job still surfaces as a client failure rather than a returned count. ########## 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: Thanks. Used-pack identities are now `distinct(parallelism)` before the mark DataFrame is cached/joined, matching local `Set` semantics and the Flink keyed dedup. Candidates are also `dropDuplicates("name")`. Added coverage for two sidecars that reference the same pack identity. ########## 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: Thanks. Database-wide cleanup now executes and aggregates one table at a time and unpersists that table's cached datasets in a per-table `finally`, so cache usage is bounded by the largest table rather than the whole database. -- 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]
