leaves12138 commented on code in PR #9197:
URL: https://github.com/apache/paimon/pull/9197#discussion_r3772536661


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionCompactMergeConflictRewriter.scala:
##########
@@ -0,0 +1,403 @@
+/*
+ * 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.commands
+
+import org.apache.paimon.Snapshot
+import org.apache.paimon.data.BinaryRow
+import org.apache.paimon.format.blob.BlobFileFormat.isBlobFile
+import org.apache.paimon.io.{CompactIncrement, DataFileMeta, DataIncrement}
+import org.apache.paimon.spark.util.ScanPlanHelper
+import org.apache.paimon.table.{FileStoreTable, SpecialFields}
+import org.apache.paimon.table.sink.{CommitMessage, CommitMessageImpl}
+import org.apache.paimon.table.source.{DataSplit, IncrementalSplit}
+import org.apache.paimon.table.source.snapshot.SnapshotReader
+import org.apache.paimon.types.VectorType.isVectorStoreFile
+import org.apache.paimon.utils.Range
+
+import org.apache.spark.sql.{functions, SparkSession}
+import org.apache.spark.sql.PaimonUtils.createDataset
+import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver
+import org.apache.spark.sql.catalyst.expressions.AttributeReference
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.paimon.shims.SparkShimLoader
+
+import java.util.{Collections, List => JList, Optional => JOptional}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+/** Rebases MERGE-compatible partial-column files onto staged compact output 
boundaries. */
+class DataEvolutionCompactMergeConflictRewriter(
+    table: FileStoreTable,
+    targetRelation: DataSourceV2Relation)
+  extends ScanPlanHelper {
+
+  import DataEvolutionCompactMergeConflictRewriter._
+
+  def rewrite(
+      sparkSession: SparkSession,
+      baseSnapshot: Snapshot,
+      latestSnapshot: Snapshot,
+      compactMessages: JList[CommitMessage]): JOptional[JList[CommitMessage]] 
= {
+    if (
+      table.coreOptions().deletionVectorsEnabled() ||
+      latestSnapshot.schemaId() != baseSnapshot.schemaId() ||
+      latestSnapshot.id() <= baseSnapshot.id()
+    ) {
+      return JOptional.empty()
+    }
+
+    val messageImpls = compactMessages.asScala.collect {
+      case message: CommitMessageImpl => message
+    }
+    if (messageImpls.size != compactMessages.size()) {
+      return JOptional.empty()
+    }
+
+    val targets = messageImpls
+      .flatMap(
+        message =>
+          normalRowIdFiles(message.compactIncrement().compactAfter().asScala)
+            .map(file => CompactTarget(message, file)))
+      .toSeq
+    if (targets.isEmpty) {
+      return JOptional.empty()
+    }
+    val targetIndex = new CompactTargetIndex(targets)
+    if (!targetIndex.valid) {
+      return JOptional.empty()
+    }
+
+    // Snapshot.operation is optional and Python MERGE currently does not 
persist it. Validate
+    // the portable partial-column file contract below instead.
+    val additions = targetReader(latestSnapshot, targets)
+      .readIncrementalDiff(baseSnapshot)
+      .splits()
+      .asScala
+      .collect { case split: IncrementalSplit => split }
+      .flatMap(
+        split =>
+          split
+            .afterFiles()
+            .asScala
+            .map(file => AddedFile(split.partition(), split.bucket(), file)))
+
+    val additionsByTarget =
+      mutable.HashMap.empty[CompactTarget, mutable.ArrayBuffer[AddedFile]]
+    additions.foreach {
+      addition =>
+        val intersectingTargets = targetIndex.intersecting(addition)
+        if (intersectingTargets.nonEmpty) {
+          if (
+            !isRegularPartialFile(addition.file) ||
+            intersectingTargets.length != 1 ||
+            !intersectingTargets.head.contains(addition)
+          ) {
+            return JOptional.empty()
+          }
+          additionsByTarget
+            .getOrElseUpdate(intersectingTargets.head, 
mutable.ArrayBuffer.empty)
+            .append(addition)
+        }
+    }
+    if (additionsByTarget.isEmpty) {
+      return JOptional.empty()
+    }
+
+    val targetRewrites = targets.flatMap {
+      target =>
+        val files = 
additionsByTarget.get(target).map(_.toSeq).getOrElse(Seq.empty)
+        if (files.nonEmpty) {
+          val updatedFields = table
+            .rowType()
+            .getFieldNames
+            .asScala
+            .filter(name => files.exists(_.file.writeCols().contains(name)))
+            .toSeq
+          if (updatedFields.isEmpty) {
+            return JOptional.empty()
+          }
+          Some(TargetRewrite(target, files.toSeq, updatedFields))
+        } else {
+          None
+        }
+    }
+    if (targetRewrites.isEmpty) {
+      return JOptional.empty()
+    }
+
+    val currentSplits = targetReader(latestSnapshot, 
targetRewrites.map(_.target))
+      .read()
+      .splits()
+      .asScala
+      .collect { case split: DataSplit => split }
+      .toSeq
+
+    val rewrittenMessages = targetRewrites

Review Comment:
   `rewriteFiles` stages real data files, but this `flatMap` can invoke it 
multiple times for different `updatedFields` groups. If one group succeeds and 
a later group fails (for example, a Spark task/write failure), `rewrite` throws 
before returning any commit messages, so `commitWithMergeConflictRetry` never 
receives the already-created messages and cannot abort them. Those files are 
left as orphans even though no commit was attempted and cleanup is still 
unambiguously safe. Could we accumulate the staged messages in a `try` block 
and abort all previously produced messages on any subsequent rewrite failure 
(or make the writer expose an abortable rewrite result)? A failure-injection 
test with two field groups would also protect this path.



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