Stephen0421 commented on code in PR #9812: URL: https://github.com/apache/paimon/pull/9812#discussion_r4015877589
########## 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: Thanks for the catch. `persist(MEMORY_AND_DISK)` does not cut sidecar lineage. After a cache miss both marks can recompute from stale `sidecarWorkItems` shuffle, lose a reused pack via `fromSidecar` → `Result.empty()`, still agree, and pass the abort gates. The deletion join now collects the validated used names onto a driver-backed Dataset and anti-joins that, so a later recompute cannot reread sidecars or silently drop P. `frozenAbort` now returns an empty deletion Dataset on the driver. `abortKeys` is gone because it only helped when the mark could still be recomputed. Regression: `frozen used mark survives stale sidecar recompute` unpersists marks, clears shuffle, and asserts `collectUsedPacksDf` is not called a third time. `frozen used mark still deletes after sidecar reads start failing` asserts no sidecar reread after the freeze, while still deleting true orphans. Driver memory now scales with the used-pack set; an OOM fails the procedure instead of deleting live packs. I added a comment not to join the persisted `used2Packs` Dataset again, and a log of the frozen name count. There is no hard cap and no "use local mode" hint — local holds the same set on the calling JVM. No forced `broadcast()`; a large LocalRelation can still shuffle-join without putting sidecar reads back. -- 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]
