You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iceberg.apache.org by bl...@apache.org on 2021/01/20 18:38:00 UTC

[iceberg] branch master updated: Spark: Detect ambiguous target row changes in MERGE INTO (#2021)

This is an automated email from the ASF dual-hosted git repository.

blue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iceberg.git


The following commit(s) were added to refs/heads/master by this push:
     new 88191c8  Spark: Detect ambiguous target row changes in MERGE INTO (#2021)
88191c8 is described below

commit 88191c83a22b401decfd06b9d72bf9bf37d1b727
Author: Dilip Biswal <dk...@gmail.com>
AuthorDate: Wed Jan 20 10:37:46 2021 -0800

    Spark: Detect ambiguous target row changes in MERGE INTO (#2021)
    
    Co-authored-by: Dilip Biswal <db...@adobe.com>
---
 LICENSE                                            |  1 +
 .../java/org/apache/iceberg/TableProperties.java   |  3 +
 .../extensions/IcebergSparkSessionExtensions.scala |  4 +-
 .../sql/catalyst/expressions/AccumulateFiles.scala | 43 +++++++++++
 .../sql/catalyst/optimizer/RewriteDelete.scala     |  7 +-
 .../sql/catalyst/optimizer/RewriteMergeInto.scala  | 35 +++++++--
 .../catalyst/plans/logical/DynamicFileFilter.scala | 20 +++++
 .../utils/RewriteRowLevelOperationHelper.scala     | 48 +++++++++++-
 .../spark/sql/catalyst/utils/SetAccumulator.scala  | 45 +++++++++++
 .../datasources/v2/DynamicFileFilterExec.scala     | 36 ++++++++-
 .../v2/ExtendedDataSourceV2Strategy.scala          |  5 ++
 .../spark/extensions/TestMergeIntoTable.java       | 90 +++++++++++++++++++++-
 12 files changed, 318 insertions(+), 19 deletions(-)

diff --git a/LICENSE b/LICENSE
index f25457a..44feea0 100644
--- a/LICENSE
+++ b/LICENSE
@@ -285,6 +285,7 @@ This product includes code from Apache Spark.
 * vectorized reading of definition levels in BaseVectorizedParquetValuesReader.java
 * portions of the extensions parser
 * casting logic in AssignmentAlignmentSupport
+* implementation of SetAccumulator.
 
 Copyright: 2011-2018 The Apache Software Foundation
 Home page: https://spark.apache.org/
diff --git a/core/src/main/java/org/apache/iceberg/TableProperties.java b/core/src/main/java/org/apache/iceberg/TableProperties.java
index 0dc5232..d7d528c 100644
--- a/core/src/main/java/org/apache/iceberg/TableProperties.java
+++ b/core/src/main/java/org/apache/iceberg/TableProperties.java
@@ -167,4 +167,7 @@ public class TableProperties {
 
   public static final String MERGE_MODE = "write.merge.mode";
   public static final String MERGE_MODE_DEFAULT = "copy-on-write";
+
+  public static final String MERGE_WRITE_CARDINALITY_CHECK = "write.merge.cardinality-check.enabled";
+  public static final boolean MERGE_WRITE_CARDINALITY_CHECK_DEFAULT = true;
 }
diff --git a/spark3-extensions/src/main/scala/org/apache/iceberg/spark/extensions/IcebergSparkSessionExtensions.scala b/spark3-extensions/src/main/scala/org/apache/iceberg/spark/extensions/IcebergSparkSessionExtensions.scala
index ffa3baf..cd3ff81 100644
--- a/spark3-extensions/src/main/scala/org/apache/iceberg/spark/extensions/IcebergSparkSessionExtensions.scala
+++ b/spark3-extensions/src/main/scala/org/apache/iceberg/spark/extensions/IcebergSparkSessionExtensions.scala
@@ -42,8 +42,8 @@ class IcebergSparkSessionExtensions extends (SparkSessionExtensions => Unit) {
     extensions.injectOptimizerRule { _ => OptimizeConditionsInRowLevelOperations }
     // TODO: PullupCorrelatedPredicates should handle row-level operations
     extensions.injectOptimizerRule { _ => PullupCorrelatedPredicatesInRowLevelOperations }
-    extensions.injectOptimizerRule { spark => RewriteDelete(spark.sessionState.conf) }
-    extensions.injectOptimizerRule { spark => RewriteMergeInto(spark.sessionState.conf) }
+    extensions.injectOptimizerRule { spark => RewriteDelete(spark) }
+    extensions.injectOptimizerRule { spark => RewriteMergeInto(spark) }
 
     // planner extensions
     extensions.injectPlannerStrategy { spark => ExtendedDataSourceV2Strategy(spark) }
diff --git a/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/expressions/AccumulateFiles.scala b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/expressions/AccumulateFiles.scala
new file mode 100644
index 0000000..b0d604d
--- /dev/null
+++ b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/expressions/AccumulateFiles.scala
@@ -0,0 +1,43 @@
+/*
+ * 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.spark.sql.catalyst.expressions
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.codegen.CodegenFallback
+import org.apache.spark.sql.catalyst.utils.SetAccumulator
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.sql.types.IntegerType
+
+case class AccumulateFiles(
+    filesAccumulator: SetAccumulator[String],
+    child: Expression) extends UnaryExpression with CodegenFallback {
+  override def dataType: DataType = IntegerType
+
+  override def nullable: Boolean = true
+  override def prettyName: String = "AccumulateFiles"
+  override lazy val deterministic = false
+  val RETURN_VAL: Integer = 1
+
+  override def eval(input: InternalRow) : Any = {
+    val resultVal = child.eval(input)
+    filesAccumulator.add(resultVal.toString)
+    RETURN_VAL
+  }
+}
diff --git a/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDelete.scala b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDelete.scala
index 7ebfbc0..ad401ae 100644
--- a/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDelete.scala
+++ b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDelete.scala
@@ -19,6 +19,7 @@
 
 package org.apache.spark.sql.catalyst.optimizer
 
+import org.apache.spark.sql.SparkSession
 import org.apache.spark.sql.catalyst.analysis.Resolver
 import org.apache.spark.sql.catalyst.expressions.Ascending
 import org.apache.spark.sql.catalyst.expressions.AttributeReference
@@ -44,11 +45,11 @@ import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.types.BooleanType
 
 // TODO: should be part of early scan push down after the delete condition is optimized
-case class RewriteDelete(conf: SQLConf) extends Rule[LogicalPlan] with RewriteRowLevelOperationHelper {
+case class RewriteDelete(spark: SparkSession) extends Rule[LogicalPlan] with RewriteRowLevelOperationHelper {
 
   import org.apache.spark.sql.execution.datasources.v2.ExtendedDataSourceV2Implicits._
 
-  override def resolver: Resolver = conf.resolver
+  override def resolver: Resolver = spark.sessionState.conf.resolver
 
   override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators {
     // don't rewrite deletes that can be answered by passing filters to deleteWhere in SupportsDelete
@@ -62,7 +63,7 @@ case class RewriteDelete(conf: SQLConf) extends Rule[LogicalPlan] with RewriteRo
       val mergeBuilder = r.table.asMergeable.newMergeBuilder("delete", writeInfo)
 
       val matchingRowsPlanBuilder = scanRelation => Filter(cond, scanRelation)
-      val scanPlan = buildDynamicFilterScanPlan(r.table, r.output, mergeBuilder, cond, matchingRowsPlanBuilder)
+      val scanPlan = buildDynamicFilterScanPlan(spark, r.table, r.output, mergeBuilder, cond, matchingRowsPlanBuilder)
 
       val remainingRowFilter = Not(EqualNullSafe(cond, Literal(true, BooleanType)))
       val remainingRowsPlan = Filter(remainingRowFilter, scanPlan)
diff --git a/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteMergeInto.scala b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteMergeInto.scala
index dfa011e..e355565 100644
--- a/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteMergeInto.scala
+++ b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteMergeInto.scala
@@ -19,6 +19,10 @@
 
 package org.apache.spark.sql.catalyst.optimizer
 
+import org.apache.iceberg.TableProperties.MERGE_WRITE_CARDINALITY_CHECK
+import org.apache.iceberg.TableProperties.MERGE_WRITE_CARDINALITY_CHECK_DEFAULT
+import org.apache.iceberg.util.PropertyUtil
+import org.apache.spark.sql.SparkSession
 import org.apache.spark.sql.catalyst.analysis.Resolver
 import org.apache.spark.sql.catalyst.expressions.Alias
 import org.apache.spark.sql.catalyst.expressions.Expression
@@ -43,13 +47,13 @@ import org.apache.spark.sql.catalyst.plans.logical.ReplaceData
 import org.apache.spark.sql.catalyst.plans.logical.UpdateAction
 import org.apache.spark.sql.catalyst.rules.Rule
 import org.apache.spark.sql.catalyst.utils.RewriteRowLevelOperationHelper
+import org.apache.spark.sql.connector.catalog.Table
 import org.apache.spark.sql.connector.iceberg.write.MergeBuilder
 import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
 import org.apache.spark.sql.execution.datasources.v2.DataSourceV2ScanRelation
-import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.types.BooleanType
 
-case class RewriteMergeInto(conf: SQLConf) extends Rule[LogicalPlan] with RewriteRowLevelOperationHelper  {
+case class RewriteMergeInto(spark: SparkSession) extends Rule[LogicalPlan] with RewriteRowLevelOperationHelper  {
   private val ROW_FROM_SOURCE = "_row_from_source_"
   private val ROW_FROM_TARGET = "_row_from_target_"
   private val TRUE_LITERAL = Literal(true, BooleanType)
@@ -57,7 +61,7 @@ case class RewriteMergeInto(conf: SQLConf) extends Rule[LogicalPlan] with Rewrit
 
   import org.apache.spark.sql.execution.datasources.v2.ExtendedDataSourceV2Implicits._
 
-  override def resolver: Resolver = conf.resolver
+  override def resolver: Resolver = spark.sessionState.conf.resolver
 
   override def apply(plan: LogicalPlan): LogicalPlan = {
     plan resolveOperators {
@@ -88,7 +92,7 @@ case class RewriteMergeInto(conf: SQLConf) extends Rule[LogicalPlan] with Rewrit
       case MergeIntoTable(target: DataSourceV2Relation, source: LogicalPlan, cond, matchedActions, notMatchedActions)
           if notMatchedActions.isEmpty =>
 
-        val (mergeBuilder, targetTableScan) = buildDynamicFilterTargetScan(target, source, cond)
+        val (mergeBuilder, targetTableScan) = buildDynamicFilterTargetScan(target, source, cond, matchedActions)
 
         // rewrite the matched actions to ensure there is always an action to produce the output row
         val (matchedConditions, matchedOutputs) = rewriteMatchedActions(matchedActions, target.output)
@@ -116,7 +120,7 @@ case class RewriteMergeInto(conf: SQLConf) extends Rule[LogicalPlan] with Rewrit
 
       case MergeIntoTable(target: DataSourceV2Relation, source: LogicalPlan, cond, matchedActions, notMatchedActions) =>
 
-        val (mergeBuilder, targetTableScan) = buildDynamicFilterTargetScan(target, source, cond)
+        val (mergeBuilder, targetTableScan) = buildDynamicFilterTargetScan(target, source, cond, matchedActions)
 
         // rewrite the matched actions to ensure there is always an action to produce the output row
         val (matchedConditions, matchedOutputs) = rewriteMatchedActions(matchedActions, target.output)
@@ -163,13 +167,15 @@ case class RewriteMergeInto(conf: SQLConf) extends Rule[LogicalPlan] with Rewrit
   private def buildDynamicFilterTargetScan(
       target: DataSourceV2Relation,
       source: LogicalPlan,
-      cond: Expression): (MergeBuilder, LogicalPlan) = {
+      cond: Expression,
+      matchedActions: Seq[MergeAction]): (MergeBuilder, LogicalPlan) = {
     // Construct the plan to prune target based on join condition between source and target.
     val mergeBuilder = target.table.asMergeable.newMergeBuilder("merge", newWriteInfo(target.schema))
     val matchingRowsPlanBuilder = (rel: DataSourceV2ScanRelation) =>
       Join(source, rel, Inner, Some(cond), JoinHint.NONE)
+    val runCountCheck = isCardinalityCheckEnabled(target.table) && isCardinalityCheckNeeded(matchedActions)
     val targetTableScan = buildDynamicFilterScanPlan(
-      target.table, target.output, mergeBuilder, cond, matchingRowsPlanBuilder)
+      spark, target.table, target.output, mergeBuilder, cond, matchingRowsPlanBuilder, runCountCheck)
 
     (mergeBuilder, targetTableScan)
   }
@@ -194,5 +200,20 @@ case class RewriteMergeInto(conf: SQLConf) extends Rule[LogicalPlan] with Rewrit
       (startMatchedConditions.take(catchAllIndex + 1), outputs.take(catchAllIndex + 1))
     }
   }
+
+  private def isCardinalityCheckEnabled(table: Table): Boolean = {
+    PropertyUtil.propertyAsBoolean(table.properties(),
+      MERGE_WRITE_CARDINALITY_CHECK, MERGE_WRITE_CARDINALITY_CHECK_DEFAULT)
+  }
+
+  private def isCardinalityCheckNeeded(actions: Seq[MergeAction]): Boolean = {
+    def hasUnconditionalDelete(action: Option[MergeAction]): Boolean = {
+      action match {
+        case Some(DeleteAction(None)) => true
+        case _ => false
+      }
+    }
+    !(actions.size == 1 && hasUnconditionalDelete(actions.headOption))
+  }
 }
 
diff --git a/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/DynamicFileFilter.scala b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/DynamicFileFilter.scala
index e41ef35..b4a84ab 100644
--- a/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/DynamicFileFilter.scala
+++ b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/DynamicFileFilter.scala
@@ -21,6 +21,7 @@ package org.apache.spark.sql.catalyst.plans.logical
 
 import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet}
 import org.apache.spark.sql.catalyst.util.truncatedString
+import org.apache.spark.sql.catalyst.utils.SetAccumulator
 import org.apache.spark.sql.connector.iceberg.read.SupportsFileFilter
 
 // TODO: fix stats (ignore the fact it is a binary node and report only scanRelation stats)
@@ -40,3 +41,22 @@ case class DynamicFileFilter(
     s"DynamicFileFilter${truncatedString(output, "[", ", ", "]", maxFields)}"
   }
 }
+
+case class DynamicFileFilterWithCountCheck(
+    scanPlan: LogicalPlan,
+    fileFilterPlan: LogicalPlan,
+    filterable: SupportsFileFilter,
+    filesAccumulator: SetAccumulator[String],
+    targetTableName: String) extends BinaryNode {
+
+  @transient
+  override lazy val references: AttributeSet = AttributeSet(fileFilterPlan.output)
+
+  override def left: LogicalPlan = scanPlan
+  override def right: LogicalPlan = fileFilterPlan
+  override def output: Seq[Attribute] = scanPlan.output
+
+  override def simpleString(maxFields: Int): String = {
+    s"DynamicFileFilterWithCountCheck${truncatedString(output, "[", ", ", "]", maxFields)}"
+  }
+}
diff --git a/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/utils/RewriteRowLevelOperationHelper.scala b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/utils/RewriteRowLevelOperationHelper.scala
index c8c8f25..5db4b74 100644
--- a/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/utils/RewriteRowLevelOperationHelper.scala
+++ b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/utils/RewriteRowLevelOperationHelper.scala
@@ -21,15 +21,24 @@ package org.apache.spark.sql.catalyst.utils
 import java.util.UUID
 import org.apache.spark.internal.Logging
 import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.SparkSession
 import org.apache.spark.sql.catalyst.analysis.Resolver
+import org.apache.spark.sql.catalyst.expressions.AccumulateFiles
+import org.apache.spark.sql.catalyst.expressions.Alias
 import org.apache.spark.sql.catalyst.expressions.And
 import org.apache.spark.sql.catalyst.expressions.Attribute
 import org.apache.spark.sql.catalyst.expressions.AttributeReference
 import org.apache.spark.sql.catalyst.expressions.AttributeSet
 import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.catalyst.expressions.GreaterThan
+import org.apache.spark.sql.catalyst.expressions.Literal
 import org.apache.spark.sql.catalyst.expressions.PredicateHelper
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.aggregate.Complete
+import org.apache.spark.sql.catalyst.expressions.aggregate.Sum
 import org.apache.spark.sql.catalyst.plans.logical.Aggregate
 import org.apache.spark.sql.catalyst.plans.logical.DynamicFileFilter
+import org.apache.spark.sql.catalyst.plans.logical.DynamicFileFilterWithCountCheck
 import org.apache.spark.sql.catalyst.plans.logical.Filter
 import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
 import org.apache.spark.sql.catalyst.plans.logical.Project
@@ -47,12 +56,16 @@ import org.apache.spark.sql.sources
 import org.apache.spark.sql.types.StructType
 import org.apache.spark.sql.util.CaseInsensitiveStringMap
 
+
 trait RewriteRowLevelOperationHelper extends PredicateHelper with Logging {
 
   import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Implicits._
 
   protected val FILE_NAME_COL = "_file"
   protected val ROW_POS_COL = "_pos"
+  protected val AFFECTED_FILES_ACC_NAME = "affectedFiles"
+  protected val AFFECTED_FILES_ACC_ALIAS_NAME = "_affectedFiles_"
+  protected val SUM_ROW_ID_ALIAS_NAME = "_sum_"
 
   def resolver: Resolver
 
@@ -73,11 +86,13 @@ trait RewriteRowLevelOperationHelper extends PredicateHelper with Logging {
   }
 
   protected def buildDynamicFilterScanPlan(
+      spark: SparkSession,
       table: Table,
       tableAttrs: Seq[AttributeReference],
       mergeBuilder: MergeBuilder,
       cond: Expression,
-      matchingRowsPlanBuilder: DataSourceV2ScanRelation => LogicalPlan): LogicalPlan = {
+      matchingRowsPlanBuilder: DataSourceV2ScanRelation => LogicalPlan,
+      performCountCheckForMerge: Boolean = false): LogicalPlan = {
 
     val scanBuilder = mergeBuilder.asScanBuilder
 
@@ -89,8 +104,17 @@ trait RewriteRowLevelOperationHelper extends PredicateHelper with Logging {
 
     scan match {
       case filterable: SupportsFileFilter =>
-        val matchingFilePlan = buildFileFilterPlan(scanRelation.output, matchingRowsPlanBuilder(scanRelation))
-        DynamicFileFilter(scanRelation, matchingFilePlan, filterable)
+        if (performCountCheckForMerge) {
+          val affectedFilesAcc = new SetAccumulator[String]()
+          spark.sparkContext.register(affectedFilesAcc, AFFECTED_FILES_ACC_NAME)
+          val planWithAccumulator = buildPlanWithFileAccumulator(affectedFilesAcc,
+            matchingRowsPlanBuilder(scanRelation))
+          DynamicFileFilterWithCountCheck(scanRelation, planWithAccumulator, filterable,
+            affectedFilesAcc, table.name())
+        } else {
+          val matchingFilePlan = buildFileFilterPlan(scanRelation.output, matchingRowsPlanBuilder(scanRelation))
+          DynamicFileFilter(scanRelation, matchingFilePlan, filterable)
+        }
       case _ =>
         scanRelation
     }
@@ -133,6 +157,24 @@ trait RewriteRowLevelOperationHelper extends PredicateHelper with Logging {
     Project(Seq(findOutputAttr(agg.output, FILE_NAME_COL)), agg)
   }
 
+  private def buildPlanWithFileAccumulator(
+         filesAccumulator: SetAccumulator[String],
+         prunedTargetPlan: LogicalPlan): LogicalPlan = {
+    val fileAttr = findOutputAttr(prunedTargetPlan.output, FILE_NAME_COL)
+    val rowPosAttr = findOutputAttr(prunedTargetPlan.output, ROW_POS_COL)
+    val accumulatorExpr = Alias(AccumulateFiles(filesAccumulator, fileAttr), AFFECTED_FILES_ACC_ALIAS_NAME)()
+    val projectList = Seq(fileAttr, rowPosAttr, accumulatorExpr)
+    val projectPlan = Project(projectList, prunedTargetPlan)
+    val affectedFilesAttr = findOutputAttr(projectPlan.output, AFFECTED_FILES_ACC_ALIAS_NAME)
+    val aggSumCol = Alias(AggregateExpression(Sum(affectedFilesAttr), Complete, false), SUM_ROW_ID_ALIAS_NAME)()
+    // Group by the rows by row id while collecting the files that need to be over written via accumulator.
+    val aggPlan = Aggregate(Seq(fileAttr, rowPosAttr), Seq(aggSumCol), projectPlan)
+    val sumAttr = findOutputAttr(aggPlan.output, SUM_ROW_ID_ALIAS_NAME)
+    val havingExpr = GreaterThan(sumAttr, Literal(1L))
+    // Identifies ambiguous row in the target.
+    Filter(havingExpr, aggPlan)
+  }
+
   protected def findOutputAttr(attrs: Seq[Attribute], attrName: String): Attribute = {
     attrs.find(attr => resolver(attr.name, attrName)).getOrElse {
       throw new AnalysisException(s"Cannot find $attrName in $attrs")
diff --git a/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/utils/SetAccumulator.scala b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/utils/SetAccumulator.scala
new file mode 100644
index 0000000..a694666
--- /dev/null
+++ b/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/utils/SetAccumulator.scala
@@ -0,0 +1,45 @@
+/*
+ * 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.spark.sql.catalyst.utils
+
+import java.util.Collections
+import org.apache.spark.util.AccumulatorV2
+
+class SetAccumulator[T] extends AccumulatorV2[T, java.util.Set[T]] {
+  private val _set = Collections.synchronizedSet(new java.util.HashSet[T]())
+
+  override def isZero: Boolean = _set.isEmpty
+
+  override def copy(): AccumulatorV2[T, java.util.Set[T]] = {
+    val newAcc = new SetAccumulator[T]()
+    newAcc._set.addAll(_set)
+    newAcc
+  }
+
+  override def reset(): Unit = _set.clear()
+
+  override def add(v: T): Unit = _set.add(v)
+
+  override def merge(other: AccumulatorV2[T, java.util.Set[T]]): Unit = {
+    _set.addAll(other.value)
+  }
+
+  override def value: java.util.Set[T] = _set
+}
diff --git a/spark3-extensions/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DynamicFileFilterExec.scala b/spark3-extensions/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DynamicFileFilterExec.scala
index 64af711..c2e2229 100644
--- a/spark3-extensions/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DynamicFileFilterExec.scala
+++ b/spark3-extensions/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DynamicFileFilterExec.scala
@@ -20,16 +20,18 @@
 package org.apache.spark.sql.execution.datasources.v2
 
 import collection.JavaConverters._
+import org.apache.spark.SparkException
 import org.apache.spark.rdd.RDD
 import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, SortOrder}
 import org.apache.spark.sql.catalyst.plans.physical
 import org.apache.spark.sql.catalyst.util.truncatedString
+import org.apache.spark.sql.catalyst.utils.SetAccumulator
 import org.apache.spark.sql.connector.iceberg.read.SupportsFileFilter
 import org.apache.spark.sql.execution.{BinaryExecNode, SparkPlan}
 import org.apache.spark.sql.vectorized.ColumnarBatch
 
-case class DynamicFileFilterExec(
+abstract class DynamicFileFilterExecBase(
     scanExec: SparkPlan,
     fileFilterExec: SparkPlan,
     @transient filterable: SupportsFileFilter) extends BinaryExecNode {
@@ -47,13 +49,41 @@ case class DynamicFileFilterExec(
   override protected def doExecute(): RDD[InternalRow] = scanExec.execute()
   override protected def doExecuteColumnar(): RDD[ColumnarBatch] = scanExec.executeColumnar()
 
+  override def simpleString(maxFields: Int): String = {
+    s"DynamicFileFilterExec${truncatedString(output, "[", ", ", "]", maxFields)}"
+  }
+}
+
+case class DynamicFileFilterExec(
+    scanExec: SparkPlan,
+    fileFilterExec: SparkPlan,
+    @transient filterable: SupportsFileFilter)
+  extends DynamicFileFilterExecBase(scanExec, fileFilterExec, filterable) {
+
   override protected def doPrepare(): Unit = {
     val rows = fileFilterExec.executeCollect()
     val matchedFileLocations = rows.map(_.getString(0))
     filterable.filterFiles(matchedFileLocations.toSet.asJava)
   }
+}
 
-  override def simpleString(maxFields: Int): String = {
-    s"DynamicFileFilterExec${truncatedString(output, "[", ", ", "]", maxFields)}"
+case class DynamicFileFilterWithCountCheckExec(
+    scanExec: SparkPlan,
+    fileFilterExec: SparkPlan,
+    @transient filterable: SupportsFileFilter,
+    filesAccumulator: SetAccumulator[String],
+    @transient targetTableName: String)
+  extends DynamicFileFilterExecBase(scanExec, fileFilterExec, filterable)  {
+
+  override protected def doPrepare(): Unit = {
+    val rows = fileFilterExec.executeCollect()
+    if (rows.size > 0) {
+      val msg =
+        s"""The same row of target table `$targetTableName` was identified more than
+           | once for an update, delete or insert operation of the MERGE statement.""".stripMargin
+      throw new SparkException(msg)
+    }
+    val matchedFileLocations = filesAccumulator.value
+    filterable.filterFiles(matchedFileLocations)
   }
 }
diff --git a/spark3-extensions/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ExtendedDataSourceV2Strategy.scala b/spark3-extensions/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ExtendedDataSourceV2Strategy.scala
index 3ba876d..47eba13 100644
--- a/spark3-extensions/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ExtendedDataSourceV2Strategy.scala
+++ b/spark3-extensions/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ExtendedDataSourceV2Strategy.scala
@@ -34,6 +34,7 @@ import org.apache.spark.sql.catalyst.plans.logical.AddPartitionField
 import org.apache.spark.sql.catalyst.plans.logical.Call
 import org.apache.spark.sql.catalyst.plans.logical.DropPartitionField
 import org.apache.spark.sql.catalyst.plans.logical.DynamicFileFilter
+import org.apache.spark.sql.catalyst.plans.logical.DynamicFileFilterWithCountCheck
 import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
 import org.apache.spark.sql.catalyst.plans.logical.MergeInto
 import org.apache.spark.sql.catalyst.plans.logical.ReplaceData
@@ -66,6 +67,10 @@ case class ExtendedDataSourceV2Strategy(spark: SparkSession) extends Strategy {
     case DynamicFileFilter(scanPlan, fileFilterPlan, filterable) =>
       DynamicFileFilterExec(planLater(scanPlan), planLater(fileFilterPlan), filterable) :: Nil
 
+    case DynamicFileFilterWithCountCheck(scanPlan, fileFilterPlan, filterable, filesAccumulator, name) =>
+      DynamicFileFilterWithCountCheckExec(planLater(scanPlan),
+        planLater(fileFilterPlan), filterable, filesAccumulator, name) :: Nil
+
     case PhysicalOperation(project, filters, DataSourceV2ScanRelation(_, scan: SupportsFileFilter, output)) =>
       // projection and filters were already pushed down in the optimizer.
       // this uses PhysicalOperation to get the projection and ensure that if the batch scan does
diff --git a/spark3-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestMergeIntoTable.java b/spark3-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestMergeIntoTable.java
index bf304e1..099bab8 100644
--- a/spark3-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestMergeIntoTable.java
+++ b/spark3-extensions/src/test/java/org/apache/iceberg/spark/extensions/TestMergeIntoTable.java
@@ -22,11 +22,13 @@ package org.apache.iceberg.spark.extensions;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
+import org.apache.iceberg.AssertHelpers;
 import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
 import org.apache.iceberg.spark.SparkCatalog;
 import org.apache.iceberg.spark.SparkSessionCatalog;
+import org.apache.spark.SparkException;
 import org.apache.spark.sql.Dataset;
 import org.apache.spark.sql.Row;
 import org.apache.spark.sql.catalyst.analysis.NoSuchTableException;
@@ -39,6 +41,7 @@ import org.junit.Test;
 import org.junit.runners.Parameterized;
 
 import static org.apache.iceberg.TableProperties.DEFAULT_FILE_FORMAT;
+import static org.apache.iceberg.TableProperties.MERGE_WRITE_CARDINALITY_CHECK;
 import static org.apache.iceberg.TableProperties.PARQUET_VECTORIZATION_ENABLED;
 
 public class TestMergeIntoTable extends SparkRowLevelOperationsTestBase {
@@ -230,12 +233,97 @@ public class TestMergeIntoTable extends SparkRowLevelOperationsTestBase {
             "WHEN NOT MATCHED AND source.id = 2 THEN INSERT * ";
 
     sql(sqlText, targetName);
-    sql("SELECT * FROM %s ORDER BY id, dep", targetName);
     assertEquals("Should have expected rows",
             ImmutableList.of(row(1, "emp-id-1"), row(2, "emp-id-2")),
             sql("SELECT * FROM %s ORDER BY id ASC NULLS LAST", targetName));
   }
 
+  @Test
+  public void testMultipleUpdatesForTargetRow() throws NoSuchTableException {
+    append(targetName, new Employee(1, "emp-id-one"), new Employee(6, "emp-id-6"));
+    append(sourceName, new Employee(1, "emp-id-1"), new Employee(1, "emp-id-1"),
+           new Employee(2, "emp-id-2"), new Employee(6, "emp-id-6"));
+
+    String sqlText = "MERGE INTO %s AS target " +
+            "USING %s AS source " +
+            "ON target.id = source.id " +
+            "WHEN MATCHED AND target.id = 1 THEN UPDATE SET * " +
+            "WHEN MATCHED AND target.id = 6 THEN DELETE " +
+            "WHEN NOT MATCHED AND source.id = 2 THEN INSERT * ";
+
+    String tabName = catalogName + "." + "default.target";
+    String errorMsg = "The same row of target table `" + tabName + "` was identified more than\n" +
+            " once for an update, delete or insert operation of the MERGE statement.";
+    AssertHelpers.assertThrows("Should complain ambiguous row in target",
+           SparkException.class, errorMsg, () -> sql(sqlText, targetName, sourceName));
+    assertEquals("Target should be unchanged",
+           ImmutableList.of(row(1, "emp-id-one"), row(6, "emp-id-6")),
+           sql("SELECT * FROM %s ORDER BY id ASC NULLS LAST", targetName));
+  }
+
+  @Test
+  public void testIgnoreMultipleUpdatesForTargetRow() throws NoSuchTableException {
+    append(targetName, new Employee(1, "emp-id-one"), new Employee(6, "emp-id-6"));
+    append(sourceName, new Employee(1, "emp-id-1"), new Employee(1, "emp-id-1"),
+           new Employee(2, "emp-id-2"), new Employee(6, "emp-id-6"));
+
+    // Disable count check
+    sql("ALTER TABLE %s SET TBLPROPERTIES('%s' '%b')", targetName, MERGE_WRITE_CARDINALITY_CHECK, false);
+
+    String sqlText = "MERGE INTO %s AS target " +
+            "USING %s AS source " +
+            "ON target.id = source.id " +
+            "WHEN MATCHED AND target.id = 1 THEN UPDATE SET * " +
+            "WHEN MATCHED AND target.id = 6 THEN DELETE " +
+            "WHEN NOT MATCHED AND source.id = 2 THEN INSERT * ";
+
+
+    sql(sqlText, targetName, sourceName);
+    assertEquals("Should have expected rows",
+           ImmutableList.of(row(1, "emp-id-1"), row(1, "emp-id-1"), row(2, "emp-id-2")),
+           sql("SELECT * FROM %s ORDER BY id ASC NULLS LAST", targetName));
+  }
+
+  @Test
+  public void testSingleUnconditionalDeleteDisbleCountCheck() throws NoSuchTableException {
+    append(targetName, new Employee(1, "emp-id-one"), new Employee(6, "emp-id-6"));
+    append(sourceName, new Employee(1, "emp-id-1"), new Employee(1, "emp-id-1"),
+           new Employee(2, "emp-id-2"), new Employee(6, "emp-id-6"));
+
+    String sqlText = "MERGE INTO %s AS target " +
+           "USING %s AS source " +
+           "ON target.id = source.id " +
+           "WHEN MATCHED THEN DELETE " +
+           "WHEN NOT MATCHED AND source.id = 2 THEN INSERT * ";
+
+    sql(sqlText, targetName, sourceName);
+    assertEquals("Should have expected rows",
+           ImmutableList.of(row(2, "emp-id-2")),
+           sql("SELECT * FROM %s ORDER BY id ASC NULLS LAST", targetName));
+  }
+
+  @Test
+  public void testSingleConditionalDeleteCountCheck() throws NoSuchTableException {
+    append(targetName, new Employee(1, "emp-id-one"), new Employee(6, "emp-id-6"));
+    append(sourceName, new Employee(1, "emp-id-1"), new Employee(1, "emp-id-1"),
+           new Employee(2, "emp-id-2"), new Employee(6, "emp-id-6"));
+
+    String sqlText = "MERGE INTO %s AS target " +
+           "USING %s AS source " +
+           "ON target.id = source.id " +
+           "WHEN MATCHED AND target.id = 1 THEN DELETE " +
+           "WHEN NOT MATCHED AND source.id = 2 THEN INSERT * ";
+
+    String tabName = catalogName + "." + "default.target";
+    String errorMsg = "The same row of target table `" + tabName + "` was identified more than\n" +
+            " once for an update, delete or insert operation of the MERGE statement.";
+    AssertHelpers.assertThrows("Should complain ambiguous row in target",
+           SparkException.class, errorMsg, () -> sql(sqlText, targetName, sourceName));
+    assertEquals("Target should be unchanged",
+           ImmutableList.of(row(1, "emp-id-one"), row(6, "emp-id-6")),
+           sql("SELECT * FROM %s ORDER BY id ASC NULLS LAST", targetName));
+  }
+
   protected void createAndInitUnPartitionedTargetTable(String tabName) {
     sql("CREATE TABLE %s (id INT, dep STRING) USING iceberg", tabName);
     initTable(tabName);