JingsongLi commented on code in PR #9812: URL: https://github.com/apache/paimon/pull/9812#discussion_r4011472294
########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/procedure/SparkManagedBlobOrphanFilesClean.scala: ########## @@ -0,0 +1,382 @@ +/* + * 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.rdd.RDD +import org.apache.spark.sql.{functions, DataFrame, Dataset, PaimonSparkSession, SparkSession} +import org.apache.spark.sql.catalyst.SQLConfHelper +import org.apache.spark.storage.StorageLevel + +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().persist(StorageLevel.MEMORY_AND_DISK) + 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") + .dropDuplicates("name") + .repartition(parallelism) + .persist(StorageLevel.MEMORY_AND_DISK) + 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().persist(StorageLevel.MEMORY_AND_DISK) + cached += usedPacks2 + val skipGc2 = usedPacks2 + .filter($"used_name" === ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC) + .limit(1) + .collect() + .nonEmpty + val topologyAfter = snapshotTopology() + val used1Packs = + usedPacks.filter($"used_name" =!= ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC) + val used2Packs = + usedPacks2.filter($"used_name" =!= ManagedBlobOrphanFilesClean.SKIP_MANAGED_BLOB_GC) + + val topologyChanged = topologyBefore != topologyAfter + val usedSetDifferences = used1Packs + .toDF() + .except(used2Packs.toDF()) + .union(used2Packs.toDF().except(used1Packs.toDF())) + val usedSetChanged = usedSetDifferences.limit(1).collect().nonEmpty + val frozenAbort = + skipGc || skipGc2 || candidateSkipGc || topologyChanged || usedSetChanged + + // Freeze every abort already observed by an action, and also retain dynamic gates so a cache + // miss that discovers a new unsafe mark cannot drop a live pack from the join. + // usedSetDifferences is in this lineage, but if mark caches are lost both passes recompute + // from the current filesystem and almost always agree, so the two-collection race check + // does not survive recomputation. The SKIP-marker gate still does. + val abortKeys = spark + .range(if (frozenAbort) 1L else 0L) + .select(functions.lit(1).as("abort_key")) + .union(abortKeyDf(usedPacks, "used_name")) + .union(abortKeyDf(usedPacks2, "used_name")) + .union(abortKeyDf(candidates, "name")) + .union(usedSetDifferences + .limit(1) + .select(functions.lit(1).as("abort_key"))) + .distinct() + if (frozenAbort) { + val reason = + if (usedSetChanged) { + "the used pack set changed during collection" + } else { + "sidecars, manifests, or candidate identities cannot be trusted, or snapshot topology changed during collection" + } + logWarning(s"Skip managed blob pack GC for table ${table.fullName()} because $reason.") + } + + val unused = + canonicalCandidates.join(used2Packs.toDF(), $"name" === $"used_name", "left_anti") + val toDelete = unused Review Comment: [P1] Freeze the validated used-pack mark before the deletion join After both initial marks protect pack P and `frozenAbort` is false, compaction can reuse P in a replacement data file and expiration can remove the old data file plus its `.blobref`. If Spark then loses the mark caches/downstream shuffle outputs while retaining the old `sidecarWorkItems` shuffle outputs, both marks can reread only those old sidecars. `ManagedBlobReachabilityCollector.fromSidecar(dataFile, sidecar)` returns safe-empty for the removed data/sidecar pair, so both recomputed sets lose P without emitting SKIP; they still agree, and the topology comparison is the earlier driver-side false value. This anti-join then admits the still-live P for deletion. `MEMORY_AND_DISK` does not freeze that filesystem-reading lineage. Please durably materialize and cut the validated mark lineage, or abort/restart validation when it must be recomputed, and add a regression preserving stale upstream sidecar shuffle outputs while losing the final marks. -- 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]
