This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new f289b0a282 [spark] Reuse Data Evolution MERGE matching between UPDATE
and INSERT (#11176)
f289b0a282 is described below
commit f289b0a2829f8b0c28ae92743f11893893ce1116
Author: JiabinYang <[email protected]>
AuthorDate: Mon Nov 16 00:07:36 2026 +0800
[spark] Reuse Data Evolution MERGE matching between UPDATE and INSERT
(#11176)
---
docs/docs/multimodal-table/data-evolution.mdx | 23 ++
docs/generated/core_configuration.html | 6 +
.../main/java/org/apache/paimon/CoreOptions.java | 17 ++
.../MergeIntoPaimonDataEvolutionTable.scala | 129 +++++++--
.../MergeIntoPaimonDataEvolutionTable.scala | 129 +++++++--
.../scala/org/apache/spark/sql/PaimonUtils.scala | 7 +
.../apache/spark/sql/paimon/shims/ClassicApi.scala | 4 +
.../DataEvolutionMergeJoinReuseConflictTest.scala | 179 ++++++++++++
.../commands/DataEvolutionMergeJoinReuseTest.scala | 307 +++++++++++++++++++++
.../spark/sql/paimon/shims/Classic3Api.scala | 22 ++
.../spark/sql/paimon/shims/Classic4Api.scala | 22 ++
11 files changed, 813 insertions(+), 32 deletions(-)
diff --git a/docs/docs/multimodal-table/data-evolution.mdx
b/docs/docs/multimodal-table/data-evolution.mdx
index c57b95a065..e9ba024f5a 100644
--- a/docs/docs/multimodal-table/data-evolution.mdx
+++ b/docs/docs/multimodal-table/data-evolution.mdx
@@ -210,6 +210,29 @@ row ID. Assign only the columns you intend to change;
assigning every column
can remove the I/O benefit of a partial update. Partition columns cannot be
changed by a matched partial update.
+#### Reuse MERGE Matching Results
+
+For `MERGE INTO` statements containing both matched updates and unmatched
+inserts, `data-evolution.merge-into.join-reuse` can reuse a match result stored
+on executor-local disk. It is disabled by default:
+
+```sql
+ALTER TABLE target_table SET TBLPROPERTIES (
+ 'data-evolution.merge-into.join-reuse' = 'true'
+);
+```
+
+Reuse requires Spark adaptive query execution and adaptive partition
coalescing.
+It applies to deterministic update-and-insert statements without subqueries,
+delete actions, `WHEN NOT MATCHED BY SOURCE`, or dedicated BLOB/VECTOR columns.
+Other statements use the original execution path.
+
+The shared full outer join avoids repeating the action matching work, but can
+increase shuffle and local disk I/O compared with the separate joins, including
+joins that can broadcast a small input. Compare complete SQL execution time and
+executor disk usage with representative data before enabling it. The shared
+result is released after the command, including when execution fails.
+
### Flink SQL
Use the `data_evolution_merge_into` procedure for matched updates. It runs in
diff --git a/docs/generated/core_configuration.html
b/docs/generated/core_configuration.html
index accf6c72dc..67e06edf25 100644
--- a/docs/generated/core_configuration.html
+++ b/docs/generated/core_configuration.html
@@ -566,6 +566,12 @@ under the License.
<td>Boolean</td>
<td>If true, enables the file-level pruning step for MergeInto
partial column update on data-evolution tables. Set this to false when most
files in the target partition are expected to be updated, so that the overhead
of collecting touched file IDs outweighs the benefit of pruning untouched
files.</td>
</tr>
+ <tr>
+ <td><h5>data-evolution.merge-into.join-reuse</h5></td>
+ <td style="word-wrap: break-word;">false</td>
+ <td>Boolean</td>
+ <td>Whether to reuse a disk-persisted match result between
deterministic UPDATE and INSERT actions on data evolution tables without DELETE
actions or dedicated BLOB/VECTOR columns. This replaces the two action joins
with a full outer join and trades repeated target scans for shuffle and
executor-local disk storage. Requires Spark adaptive query execution and
adaptive partition coalescing; otherwise the original join path is used.</td>
+ </tr>
<tr>
<td><h5>data-evolution.merge-into.source-persist</h5></td>
<td style="word-wrap: break-word;">false</td>
diff --git a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
index 7ef992afab..01074dd578 100644
--- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
+++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
@@ -2794,6 +2794,19 @@ public class CoreOptions implements Serializable {
.withDescription(
"Whether to persist source when process merge into
action on data evolution table.");
+ public static final ConfigOption<Boolean>
DATA_EVOLUTION_MERGE_INTO_JOIN_REUSE =
+ key("data-evolution.merge-into.join-reuse")
+ .booleanType()
+ .defaultValue(false)
+ .withDescription(
+ "Whether to reuse a disk-persisted match result
between deterministic "
+ + "UPDATE and INSERT actions on data
evolution tables without "
+ + "DELETE actions or dedicated BLOB/VECTOR
columns. This replaces "
+ + "the two action joins with a full outer
join and trades repeated "
+ + "target scans for shuffle and
executor-local disk storage. "
+ + "Requires Spark adaptive query execution
and adaptive partition "
+ + "coalescing; otherwise the original join
path is used.");
+
public static final ConfigOption<Boolean>
DATA_EVOLUTION_COMPACTION_SPLIT_LARGE_FILES =
key("data-evolution.compaction.split-large-files")
.booleanType()
@@ -4814,6 +4827,10 @@ public class CoreOptions implements Serializable {
return options.get(DATA_EVOLUTION_MERGE_INTO_SOURCE_PERSIST);
}
+ public boolean dataEvolutionMergeIntoJoinReuse() {
+ return options.get(DATA_EVOLUTION_MERGE_INTO_JOIN_REUSE);
+ }
+
public boolean blobCompactionEnabled() {
return options.get(BLOB_COMPACTION_ENABLED);
}
diff --git
a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala
b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala
index fc887a135e..9b425c661c 100644
---
a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala
+++
b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala
@@ -40,7 +40,7 @@ import org.apache.paimon.table.sink.{CommitMessage,
CommitMessageImpl}
import org.apache.paimon.table.source.DataSplit
import org.apache.paimon.table.source.snapshot.SnapshotReader
import org.apache.paimon.table.source.snapshot.TimeTravelUtil
-import org.apache.paimon.types.{BlobType, RowType}
+import org.apache.paimon.types.{BlobType, RowType, VectorType}
import org.apache.paimon.types.VectorType.isVectorStoreFile
import org.apache.paimon.utils.BranchManager
@@ -49,9 +49,9 @@ import org.apache.spark.sql.{Dataset, Row, SparkSession}
import org.apache.spark.sql.PaimonUtils._
import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver
-import org.apache.spark.sql.catalyst.expressions.{Alias, And,
AttributeReference, CreateNamedStruct, EqualTo, Expression, ExprId,
GetStructField, If, IsNull, Literal, Or, PythonUDF, SubqueryExpression}
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute,
AttributeReference, CreateNamedStruct, EqualTo, Expression, ExprId,
GetStructField, If, IsNotNull, IsNull, Literal, Or, PythonUDF,
SubqueryExpression}
import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral,
TrueLiteral}
-import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.{FullOuter, LeftAnti, LeftOuter}
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
import org.apache.spark.sql.functions.{col, udf}
@@ -380,6 +380,7 @@ case class MergeIntoPaimonDataEvolutionTable(
}
var targetActionCleanup = () => ()
+ var sharedMatches: Option[SharedMergeJoin] = None
try {
// step 1: find the related data splits for matched / insert actions.
lazy val matchedOrInsertDataSplits: Seq[DataSplit] = targetRelatedSplits(
@@ -392,6 +393,11 @@ case class MergeIntoPaimonDataEvolutionTable(
lazy val touchedFileTargetRelation =
createNewScanPlan(matchedOrInsertDataSplits, targetRelation)
+ if (canReuseMergeJoin(sparkSession) &&
matchedOrInsertDataSplits.nonEmpty) {
+ sharedMatches = Some(
+ createSharedMergeJoin(sparkSession, touchedFileTargetRelation,
persistSourceDss))
+ }
+
// step 2: invoke target-side action
val matchedResult =
if (matchedActions.nonEmpty) {
@@ -400,7 +406,8 @@ case class MergeIntoPaimonDataEvolutionTable(
sparkSession,
touchedFileTargetRelation,
firstRowIds,
- persistSourceDss)
+ persistSourceDss,
+ sharedMatches)
targetActionCleanup = result.cleanup
result
} else {
@@ -420,7 +427,11 @@ case class MergeIntoPaimonDataEvolutionTable(
// step 3: invoke insert action
val insertCommit =
if (notMatchedActions.nonEmpty)
- insertActionInvoke(sparkSession, touchedFileTargetRelation,
persistSourceDss)
+ insertActionInvoke(
+ sparkSession,
+ touchedFileTargetRelation,
+ persistSourceDss,
+ sharedMatches)
else Nil
DataEvolutionRowIdConflictCommitter.commit(
@@ -434,13 +445,83 @@ case class MergeIntoPaimonDataEvolutionTable(
Snapshot.Operation.MERGE
)
} finally {
- targetActionCleanup()
- if (persistSourceDss.isDefined) {
- persistSourceDss.get.unpersist(blocking = false)
+ try {
+ targetActionCleanup()
+ } finally {
+ try {
+ sharedMatches.foreach(_.cleanup())
+ } finally {
+ persistSourceDss.foreach(_.unpersist(blocking = false))
+ }
}
}
}
+ private lazy val mergeReadExpressions: Seq[Expression] = {
+ Seq(matchedCondition) ++ (matchedActions ++ notMatchedActions).flatMap {
+ case update: UpdateAction =>
+ update.condition.toSeq ++ update.assignments
+ .filter(a => updateColumns.contains(assignmentKeyAttribute(a)))
+ .map(_.value)
+ case insert: InsertAction =>
+ insert.condition.toSeq ++ insert.assignments.map(_.value)
+ case action => action.condition.toSeq
+ }
+ }
+
+ private def canReuseMergeJoin(sparkSession: SparkSession): Boolean = {
+ table.coreOptions().dataEvolutionMergeIntoJoinReuse() &&
+ sparkSession.conf.get("spark.sql.adaptive.enabled").toBoolean &&
+
sparkSession.conf.get("spark.sql.adaptive.coalescePartitions.enabled").toBoolean
&&
+ matchedActions.nonEmpty &&
matchedActions.forall(_.isInstanceOf[UpdateAction]) &&
+ notMatchedActions.nonEmpty && notMatchedBySourceActions.isEmpty &&
+ mergeReadExpressions.forall(e => e.deterministic &&
!SubqueryExpression.hasSubquery(e)) &&
+ !sourceTable.exists(
+ p => p.expressions.exists(e => !e.deterministic ||
SubqueryExpression.hasSubquery(e))) &&
+ !matchedCondition.exists(_.isInstanceOf[PythonUDF]) &&
+ !table.rowType().getFields.asScala.exists {
+ field => BlobType.isBlobFileField(field.`type`()) ||
field.`type`().isInstanceOf[VectorType]
+ }
+ }
+
+ private case class SharedMergeJoin(
+ dataset: Dataset[Row],
+ targetMarkerId: ExprId,
+ sourceMarkerId: ExprId,
+ cleanup: () => Unit) {
+ def targetMarker(plan: LogicalPlan): Attribute =
+ plan.output.find(_.exprId == targetMarkerId).get
+
+ def sourceMarker(plan: LogicalPlan): Attribute =
+ plan.output.find(_.exprId == sourceMarkerId).get
+ }
+
+ private def createSharedMergeJoin(
+ sparkSession: SparkSession,
+ touchedFileTargetRelation: DataSourceV2Relation,
+ persistSourceDss: Option[Dataset[Row]]): SharedMergeJoin = {
+ val needed = (mergeReadExpressions.flatMap(extractFields) ++ updateColumns)
+ .map(_.exprId)
+ .toSet
+ val targetAttributes = (targetRelation.output ++
targetRelation.metadataOutput)
+ .foldLeft(Seq.empty[AttributeReference]) {
+ (attrs, attr) => if (attrs.exists(_.exprId == attr.exprId)) attrs else
attrs :+ attr
+ }
+ .filter(attr => needed.contains(attr.exprId) || attr.name == ROW_ID_NAME)
+ val targetRead = touchedFileTargetRelation.copy(output = targetAttributes)
+ val targetMarker = Alias(TrueLiteral, ROW_FROM_TARGET)()
+ val sourceMarker = Alias(TrueLiteral, ROW_FROM_SOURCE)()
+ val targetProject = Project(targetRead.output :+ targetMarker, targetRead)
+ val sourceRead =
persistSourceDss.map(_.queryExecution.logical).getOrElse(sourceTable)
+ val sourceProject = Project(
+ sourceRead.output.filter(attr => needed.contains(attr.exprId)) :+
sourceMarker,
+ sourceRead)
+ val (dataset, cleanup) = createDiskCachedDataset(
+ sparkSession,
+ Join(targetProject, sourceProject, FullOuter, Some(matchedCondition),
JoinHint.NONE))
+ SharedMergeJoin(dataset, targetMarker.exprId, sourceMarker.exprId, cleanup)
+ }
+
private def pushDownMergeFilters(snapshotReader: SnapshotReader): Unit = {
val predicates = Seq(mergePartitionPredicate,
selfMergeActionPredicate).flatten
if (predicates.nonEmpty) {
@@ -591,7 +672,8 @@ case class MergeIntoPaimonDataEvolutionTable(
sparkSession: SparkSession,
touchedFileTargetRelation: DataSourceV2Relation,
firstRowIds: immutable.IndexedSeq[Long],
- persistSourceDss: Option[Dataset[Row]]): TargetActionResult = {
+ persistSourceDss: Option[Dataset[Row]],
+ sharedMatches: Option[SharedMergeJoin]): TargetActionResult = {
if (dataSplits.isEmpty) {
return TargetActionResult(Nil, None, () => ())
}
@@ -943,10 +1025,16 @@ case class MergeIntoPaimonDataEvolutionTable(
val sourceChild =
persistSourceDss.map(_.queryExecution.logical).getOrElse(sourceTable)
val sourceTableProj = Project(sourceTableProjExprs, sourceChild)
- val joinPlan =
- Join(targetTableProj, sourceTableProj, LeftOuter,
Some(matchedCondition), JoinHint.NONE)
- val rowFromSourceAttr = attribute(ROW_FROM_SOURCE, joinPlan)
- val rowFromTargetAttr = attribute(ROW_FROM_TARGET, joinPlan)
+ val (joinPlan, rowFromSourceAttr, rowFromTargetAttr) = sharedMatches
match {
+ case Some(shared) =>
+ val plan = shared.dataset.queryExecution.analyzed
+ val targetMarker = shared.targetMarker(plan)
+ (Filter(IsNotNull(targetMarker), plan), shared.sourceMarker(plan),
targetMarker)
+ case None =>
+ val plan =
+ Join(targetTableProj, sourceTableProj, LeftOuter,
Some(matchedCondition), JoinHint.NONE)
+ (plan, attribute(ROW_FROM_SOURCE, plan), attribute(ROW_FROM_TARGET,
plan))
+ }
val mergeRows = MergeRows(
isSourceRowPresent = rowFromSourceAttr,
@@ -1121,7 +1209,8 @@ case class MergeIntoPaimonDataEvolutionTable(
private def insertActionInvoke(
sparkSession: SparkSession,
touchedFileTargetRelation: DataSourceV2Relation,
- persistSourceDss: Option[Dataset[Row]]): Seq[CommitMessage] = {
+ persistSourceDss: Option[Dataset[Row]],
+ sharedMatches: Option[SharedMergeJoin]): Seq[CommitMessage] = {
val mergeFields = extractFields(matchedCondition)
val allReadFieldsOnTarget =
mergeFields.filter(field => targetTable.output.exists(attr =>
attr.equals(field)))
@@ -1130,8 +1219,16 @@ case class MergeIntoPaimonDataEvolutionTable(
touchedFileTargetRelation.copy(output = allReadFieldsOnTarget.toSeq)
val sourceReadPlan =
persistSourceDss.map(_.queryExecution.logical).getOrElse(sourceTable)
- val joinPlan =
- Join(sourceReadPlan, targetReadPlan, LeftAnti, Some(matchedCondition),
JoinHint.NONE)
+ val joinPlan = sharedMatches match {
+ case Some(shared) =>
+ val plan = shared.dataset.queryExecution.analyzed
+ val sourceIds = sourceTable.output.map(_.exprId).toSet
+ Project(
+ plan.output.filter(attr => sourceIds.contains(attr.exprId)),
+ Filter(IsNull(shared.targetMarker(plan)), plan))
+ case None =>
+ Join(sourceReadPlan, targetReadPlan, LeftAnti, Some(matchedCondition),
JoinHint.NONE)
+ }
// merge rows as there are multiple not matched actions
val mergeRows = MergeRows(
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala
index fc887a135e..9b425c661c 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala
@@ -40,7 +40,7 @@ import org.apache.paimon.table.sink.{CommitMessage,
CommitMessageImpl}
import org.apache.paimon.table.source.DataSplit
import org.apache.paimon.table.source.snapshot.SnapshotReader
import org.apache.paimon.table.source.snapshot.TimeTravelUtil
-import org.apache.paimon.types.{BlobType, RowType}
+import org.apache.paimon.types.{BlobType, RowType, VectorType}
import org.apache.paimon.types.VectorType.isVectorStoreFile
import org.apache.paimon.utils.BranchManager
@@ -49,9 +49,9 @@ import org.apache.spark.sql.{Dataset, Row, SparkSession}
import org.apache.spark.sql.PaimonUtils._
import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver
-import org.apache.spark.sql.catalyst.expressions.{Alias, And,
AttributeReference, CreateNamedStruct, EqualTo, Expression, ExprId,
GetStructField, If, IsNull, Literal, Or, PythonUDF, SubqueryExpression}
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute,
AttributeReference, CreateNamedStruct, EqualTo, Expression, ExprId,
GetStructField, If, IsNotNull, IsNull, Literal, Or, PythonUDF,
SubqueryExpression}
import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral,
TrueLiteral}
-import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.{FullOuter, LeftAnti, LeftOuter}
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
import org.apache.spark.sql.functions.{col, udf}
@@ -380,6 +380,7 @@ case class MergeIntoPaimonDataEvolutionTable(
}
var targetActionCleanup = () => ()
+ var sharedMatches: Option[SharedMergeJoin] = None
try {
// step 1: find the related data splits for matched / insert actions.
lazy val matchedOrInsertDataSplits: Seq[DataSplit] = targetRelatedSplits(
@@ -392,6 +393,11 @@ case class MergeIntoPaimonDataEvolutionTable(
lazy val touchedFileTargetRelation =
createNewScanPlan(matchedOrInsertDataSplits, targetRelation)
+ if (canReuseMergeJoin(sparkSession) &&
matchedOrInsertDataSplits.nonEmpty) {
+ sharedMatches = Some(
+ createSharedMergeJoin(sparkSession, touchedFileTargetRelation,
persistSourceDss))
+ }
+
// step 2: invoke target-side action
val matchedResult =
if (matchedActions.nonEmpty) {
@@ -400,7 +406,8 @@ case class MergeIntoPaimonDataEvolutionTable(
sparkSession,
touchedFileTargetRelation,
firstRowIds,
- persistSourceDss)
+ persistSourceDss,
+ sharedMatches)
targetActionCleanup = result.cleanup
result
} else {
@@ -420,7 +427,11 @@ case class MergeIntoPaimonDataEvolutionTable(
// step 3: invoke insert action
val insertCommit =
if (notMatchedActions.nonEmpty)
- insertActionInvoke(sparkSession, touchedFileTargetRelation,
persistSourceDss)
+ insertActionInvoke(
+ sparkSession,
+ touchedFileTargetRelation,
+ persistSourceDss,
+ sharedMatches)
else Nil
DataEvolutionRowIdConflictCommitter.commit(
@@ -434,13 +445,83 @@ case class MergeIntoPaimonDataEvolutionTable(
Snapshot.Operation.MERGE
)
} finally {
- targetActionCleanup()
- if (persistSourceDss.isDefined) {
- persistSourceDss.get.unpersist(blocking = false)
+ try {
+ targetActionCleanup()
+ } finally {
+ try {
+ sharedMatches.foreach(_.cleanup())
+ } finally {
+ persistSourceDss.foreach(_.unpersist(blocking = false))
+ }
}
}
}
+ private lazy val mergeReadExpressions: Seq[Expression] = {
+ Seq(matchedCondition) ++ (matchedActions ++ notMatchedActions).flatMap {
+ case update: UpdateAction =>
+ update.condition.toSeq ++ update.assignments
+ .filter(a => updateColumns.contains(assignmentKeyAttribute(a)))
+ .map(_.value)
+ case insert: InsertAction =>
+ insert.condition.toSeq ++ insert.assignments.map(_.value)
+ case action => action.condition.toSeq
+ }
+ }
+
+ private def canReuseMergeJoin(sparkSession: SparkSession): Boolean = {
+ table.coreOptions().dataEvolutionMergeIntoJoinReuse() &&
+ sparkSession.conf.get("spark.sql.adaptive.enabled").toBoolean &&
+
sparkSession.conf.get("spark.sql.adaptive.coalescePartitions.enabled").toBoolean
&&
+ matchedActions.nonEmpty &&
matchedActions.forall(_.isInstanceOf[UpdateAction]) &&
+ notMatchedActions.nonEmpty && notMatchedBySourceActions.isEmpty &&
+ mergeReadExpressions.forall(e => e.deterministic &&
!SubqueryExpression.hasSubquery(e)) &&
+ !sourceTable.exists(
+ p => p.expressions.exists(e => !e.deterministic ||
SubqueryExpression.hasSubquery(e))) &&
+ !matchedCondition.exists(_.isInstanceOf[PythonUDF]) &&
+ !table.rowType().getFields.asScala.exists {
+ field => BlobType.isBlobFileField(field.`type`()) ||
field.`type`().isInstanceOf[VectorType]
+ }
+ }
+
+ private case class SharedMergeJoin(
+ dataset: Dataset[Row],
+ targetMarkerId: ExprId,
+ sourceMarkerId: ExprId,
+ cleanup: () => Unit) {
+ def targetMarker(plan: LogicalPlan): Attribute =
+ plan.output.find(_.exprId == targetMarkerId).get
+
+ def sourceMarker(plan: LogicalPlan): Attribute =
+ plan.output.find(_.exprId == sourceMarkerId).get
+ }
+
+ private def createSharedMergeJoin(
+ sparkSession: SparkSession,
+ touchedFileTargetRelation: DataSourceV2Relation,
+ persistSourceDss: Option[Dataset[Row]]): SharedMergeJoin = {
+ val needed = (mergeReadExpressions.flatMap(extractFields) ++ updateColumns)
+ .map(_.exprId)
+ .toSet
+ val targetAttributes = (targetRelation.output ++
targetRelation.metadataOutput)
+ .foldLeft(Seq.empty[AttributeReference]) {
+ (attrs, attr) => if (attrs.exists(_.exprId == attr.exprId)) attrs else
attrs :+ attr
+ }
+ .filter(attr => needed.contains(attr.exprId) || attr.name == ROW_ID_NAME)
+ val targetRead = touchedFileTargetRelation.copy(output = targetAttributes)
+ val targetMarker = Alias(TrueLiteral, ROW_FROM_TARGET)()
+ val sourceMarker = Alias(TrueLiteral, ROW_FROM_SOURCE)()
+ val targetProject = Project(targetRead.output :+ targetMarker, targetRead)
+ val sourceRead =
persistSourceDss.map(_.queryExecution.logical).getOrElse(sourceTable)
+ val sourceProject = Project(
+ sourceRead.output.filter(attr => needed.contains(attr.exprId)) :+
sourceMarker,
+ sourceRead)
+ val (dataset, cleanup) = createDiskCachedDataset(
+ sparkSession,
+ Join(targetProject, sourceProject, FullOuter, Some(matchedCondition),
JoinHint.NONE))
+ SharedMergeJoin(dataset, targetMarker.exprId, sourceMarker.exprId, cleanup)
+ }
+
private def pushDownMergeFilters(snapshotReader: SnapshotReader): Unit = {
val predicates = Seq(mergePartitionPredicate,
selfMergeActionPredicate).flatten
if (predicates.nonEmpty) {
@@ -591,7 +672,8 @@ case class MergeIntoPaimonDataEvolutionTable(
sparkSession: SparkSession,
touchedFileTargetRelation: DataSourceV2Relation,
firstRowIds: immutable.IndexedSeq[Long],
- persistSourceDss: Option[Dataset[Row]]): TargetActionResult = {
+ persistSourceDss: Option[Dataset[Row]],
+ sharedMatches: Option[SharedMergeJoin]): TargetActionResult = {
if (dataSplits.isEmpty) {
return TargetActionResult(Nil, None, () => ())
}
@@ -943,10 +1025,16 @@ case class MergeIntoPaimonDataEvolutionTable(
val sourceChild =
persistSourceDss.map(_.queryExecution.logical).getOrElse(sourceTable)
val sourceTableProj = Project(sourceTableProjExprs, sourceChild)
- val joinPlan =
- Join(targetTableProj, sourceTableProj, LeftOuter,
Some(matchedCondition), JoinHint.NONE)
- val rowFromSourceAttr = attribute(ROW_FROM_SOURCE, joinPlan)
- val rowFromTargetAttr = attribute(ROW_FROM_TARGET, joinPlan)
+ val (joinPlan, rowFromSourceAttr, rowFromTargetAttr) = sharedMatches
match {
+ case Some(shared) =>
+ val plan = shared.dataset.queryExecution.analyzed
+ val targetMarker = shared.targetMarker(plan)
+ (Filter(IsNotNull(targetMarker), plan), shared.sourceMarker(plan),
targetMarker)
+ case None =>
+ val plan =
+ Join(targetTableProj, sourceTableProj, LeftOuter,
Some(matchedCondition), JoinHint.NONE)
+ (plan, attribute(ROW_FROM_SOURCE, plan), attribute(ROW_FROM_TARGET,
plan))
+ }
val mergeRows = MergeRows(
isSourceRowPresent = rowFromSourceAttr,
@@ -1121,7 +1209,8 @@ case class MergeIntoPaimonDataEvolutionTable(
private def insertActionInvoke(
sparkSession: SparkSession,
touchedFileTargetRelation: DataSourceV2Relation,
- persistSourceDss: Option[Dataset[Row]]): Seq[CommitMessage] = {
+ persistSourceDss: Option[Dataset[Row]],
+ sharedMatches: Option[SharedMergeJoin]): Seq[CommitMessage] = {
val mergeFields = extractFields(matchedCondition)
val allReadFieldsOnTarget =
mergeFields.filter(field => targetTable.output.exists(attr =>
attr.equals(field)))
@@ -1130,8 +1219,16 @@ case class MergeIntoPaimonDataEvolutionTable(
touchedFileTargetRelation.copy(output = allReadFieldsOnTarget.toSeq)
val sourceReadPlan =
persistSourceDss.map(_.queryExecution.logical).getOrElse(sourceTable)
- val joinPlan =
- Join(sourceReadPlan, targetReadPlan, LeftAnti, Some(matchedCondition),
JoinHint.NONE)
+ val joinPlan = sharedMatches match {
+ case Some(shared) =>
+ val plan = shared.dataset.queryExecution.analyzed
+ val sourceIds = sourceTable.output.map(_.exprId).toSet
+ Project(
+ plan.output.filter(attr => sourceIds.contains(attr.exprId)),
+ Filter(IsNull(shared.targetMarker(plan)), plan))
+ case None =>
+ Join(sourceReadPlan, targetReadPlan, LeftAnti, Some(matchedCondition),
JoinHint.NONE)
+ }
// merge rows as there are multiple not matched actions
val mergeRows = MergeRows(
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/PaimonUtils.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/PaimonUtils.scala
index 45fd057bc1..7745a0f5b0 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/PaimonUtils.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/PaimonUtils.scala
@@ -67,6 +67,13 @@ object PaimonUtils {
SparkShimLoader.shim.classicApi.createDataset(sparkSession, logicalPlan)
}
+ /** Creates a command-local disk cache, retaining AQE; the caller must
invoke its cleanup. */
+ def createDiskCachedDataset(
+ sparkSession: SparkSession,
+ logicalPlan: LogicalPlan): (Dataset[Row], () => Unit) = {
+ SparkShimLoader.shim.classicApi.createDiskCachedDataset(sparkSession,
logicalPlan)
+ }
+
/**
* Parse a read-only query, preferring [[ParserInterface.parseQuery]] which
rejects non-query
* statements at parse time. `parseQuery` was added in Spark 3.3, so on
Spark 3.2 (where it is
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/ClassicApi.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/ClassicApi.scala
index d320def940..f4948613d3 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/ClassicApi.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/spark/sql/paimon/shims/ClassicApi.scala
@@ -34,6 +34,10 @@ trait ClassicApi {
def createDataset(sparkSession: SparkSession, logicalPlan: LogicalPlan):
Dataset[Row]
+ def createDiskCachedDataset(
+ sparkSession: SparkSession,
+ logicalPlan: LogicalPlan): (Dataset[Row], () => Unit)
+
def prepareExecutedPlan(spark: SparkSession, logicalPlan: LogicalPlan):
SparkPlan
def recacheByPlan(spark: SparkSession, plan: LogicalPlan): Unit
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeJoinReuseConflictTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeJoinReuseConflictTest.scala
new file mode 100644
index 0000000000..02bb334687
--- /dev/null
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeJoinReuseConflictTest.scala
@@ -0,0 +1,179 @@
+/*
+ * 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.catalog.Identifier
+import org.apache.paimon.errors.ErrorMessages
+import org.apache.paimon.io.DataFileMeta
+import org.apache.paimon.spark.PaimonSparkTestBase
+import org.apache.paimon.spark.catalyst.analysis.PaimonRelation
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.source.DataSplit
+
+import org.apache.spark.scheduler.{SparkListener, SparkListenerBlockUpdated}
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.QueryPlanningTracker
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.storage.RDDBlockId
+
+import java.util.concurrent.{CountDownLatch, TimeUnit}
+
+import scala.collection.JavaConverters._
+
+class DataEvolutionMergeJoinReuseConflictTest extends PaimonSparkTestBase {
+
+ private def table: FileStoreTable =
+ paimonCatalog.getTable(Identifier.create(dbName0,
"target")).asInstanceOf[FileStoreTable]
+
+ private def snapshotId: Long = table.snapshotManager().latestSnapshotId()
+
+ private def files: Seq[DataFileMeta] =
+ table
+ .newReadBuilder()
+ .newScan()
+ .plan()
+ .splits()
+ .asScala
+ .flatMap(_.asInstanceOf[DataSplit].dataFiles().asScala)
+ .map(file => file.fileName() -> file)
+ .toMap
+ .values
+ .toSeq
+
+ private def withTarget(body: => Unit): Unit = {
+ withSparkSQLConf(
+ "spark.paimon.write.use-v2-write" -> "false",
+ "spark.sql.adaptive.enabled" -> "true",
+ "spark.sql.adaptive.coalescePartitions.enabled" -> "true") {
+ withTable("target") {
+ sql("""CREATE TABLE target (id INT, value INT, payload STRING)
TBLPROPERTIES (
+ |'row-tracking.enabled'='true', 'data-evolution.enabled'='true',
+ |'data-evolution.merge-into.join-reuse'='true',
'write-only'='true')""".stripMargin)
+ sql("""INSERT INTO target SELECT /*+ REPARTITION(1) */ *
+ |FROM VALUES (1,10,'a'),(2,20,'b') AS
v(id,value,payload)""".stripMargin)
+ sql("""INSERT INTO target SELECT /*+ REPARTITION(1) */ *
+ |FROM VALUES (3,30,'c'),(4,40,'d') AS
v(id,value,payload)""".stripMargin)
+ body
+ }
+ }
+ }
+
+ private def pinnedMerge(): MergeIntoPaimonDataEvolutionTable = {
+ val parsed = spark.sessionState.sqlParser.parsePlan(
+ """MERGE INTO target t USING (SELECT * FROM VALUES (1,100),(5,500) AS
v(id,value)) s
+ |ON t.id=s.id
+ |WHEN MATCHED THEN UPDATE SET value=s.value
+ |WHEN NOT MATCHED THEN INSERT (id,value,payload) VALUES
(s.id,s.value,'new')""".stripMargin)
+ val command = spark.sessionState.analyzer
+ .executeAndCheck(parsed, new QueryPlanningTracker)
+ .asInstanceOf[MergeIntoPaimonDataEvolutionTable]
+ val original = PaimonRelation.getPaimonRelation(command.targetTable)
+ val (pinnedTable, pinnedRelation) =
+
MergeIntoPaimonDataEvolutionTable.withMatchedUpdateScanOptions(command.v2Table,
original)
+ command.copy(
+ v2Table = pinnedTable,
+ targetTable = command.targetTable.transformDown {
+ case relation: DataSourceV2Relation if relation == original =>
pinnedRelation
+ })
+ }
+
+ private def withMaterializedCache(body: => Unit): Unit = {
+ val before = spark.sparkContext.getPersistentRDDs.keySet
+ val created = new CountDownLatch(1)
+ val listener = new SparkListener {
+ override def onBlockUpdated(event: SparkListenerBlockUpdated): Unit = {
+ val info = event.blockUpdatedInfo
+ if (
+ info.blockId.isInstanceOf[RDDBlockId] && info.diskSize > 0 &&
+ info.storageLevel.useDisk && !info.storageLevel.useMemory &&
+ !before.contains(info.blockId.asInstanceOf[RDDBlockId].rddId)
+ ) {
+ created.countDown()
+ }
+ }
+ }
+ spark.sparkContext.addSparkListener(listener)
+ try {
+ body
+ assert(created.await(10, TimeUnit.SECONDS), "The shared disk cache must
actually materialize")
+ assert(spark.sparkContext.getPersistentRDDs.keySet == before)
+ } finally {
+ spark.sparkContext.removeSparkListener(listener)
+ }
+ }
+
+ test("join reuse preserves a concurrent update and publishes no partial
insert on conflict") {
+ withTarget {
+ val merge = pinnedMerge()
+ sql("UPDATE target SET value=-1 WHERE id=1")
+ val concurrentRows = sql("SELECT *,_ROW_ID FROM target").collect().toSeq
+ val concurrentSnapshot = snapshotId
+ withMaterializedCache {
+ val error = intercept[Exception](merge.run(spark))
+ val causes =
Iterator.iterate[Throwable](error)(_.getCause).takeWhile(_ != null)
+ assert(
+ causes.exists(
+ cause =>
+ Option(cause.getMessage).exists(
+
_.contains(ErrorMessages.DATA_EVOLUTION_ROW_ID_CONFLICT_MESSAGE))),
+ s"Expected a row-ID conflict, got $error"
+ )
+ }
+ checkAnswer(sql("SELECT *,_ROW_ID FROM target"), concurrentRows)
+ assert(snapshotId == concurrentSnapshot)
+ }
+ }
+
+ test("join reuse rewrites stale partial ranges after compaction and commits
inserts atomically") {
+ withTarget {
+ val oldPairs = sql("SELECT id,_ROW_ID FROM target").collect().toSeq
+ val oldRanges = files.map(file => (file.firstRowId().longValue(),
file.rowCount())).toSet
+ assert(oldRanges == Set((0L, 2L), (2L, 2L)))
+ val merge = pinnedMerge()
+ sql("CALL sys.compact(table => 'target', options =>
'compaction.min.file-num=2')")
+ val compactedRanges =
+ files.map(file => (file.firstRowId().longValue(),
file.rowCount())).toSet
+ assert(
+ compactedRanges == Set((0L, 4L)),
+ s"Expected changed compaction ranges: $compactedRanges")
+ val compactedSnapshot = snapshotId
+ withMaterializedCache {
+ merge.run(spark)
+ }
+ checkAnswer(
+ sql("SELECT * FROM target"),
+ Seq(
+ Row(1, 100, "a"),
+ Row(2, 20, "b"),
+ Row(3, 30, "c"),
+ Row(4, 40, "d"),
+ Row(5, 500, "new")))
+ checkAnswer(sql("SELECT id,_ROW_ID FROM target WHERE id<=4"), oldPairs)
+ checkAnswer(sql("SELECT _ROW_ID FROM target"), (0L to 4L).map(Row(_)))
+ checkAnswer(sql("SELECT _ROW_ID FROM target WHERE id=5"), Seq(Row(4L)))
+ assert(snapshotId == compactedSnapshot + 1)
+ val rewritten =
+ files.filter(file => Option(file.writeCols()).exists(_.asScala.toSeq
== Seq("value")))
+ assert(
+ rewritten.exists(file => file.firstRowId().longValue() == 0L &&
file.rowCount() == 4L),
+ "The stale two-row partial update must be rewritten to the current
four-row range"
+ )
+ }
+ }
+}
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeJoinReuseTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeJoinReuseTest.scala
new file mode 100644
index 0000000000..58515b9605
--- /dev/null
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeJoinReuseTest.scala
@@ -0,0 +1,307 @@
+/*
+ * 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.catalog.Identifier
+import org.apache.paimon.spark.PaimonSparkTestBase
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.source.DataSplit
+
+import org.apache.spark.scheduler.{SparkListener, SparkListenerBlockUpdated}
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.util.QueryExecutionListener
+import org.apache.spark.storage.RDDBlockId
+
+import java.util.concurrent.{CountDownLatch, TimeUnit}
+import java.util.concurrent.atomic.AtomicBoolean
+
+import scala.collection.JavaConverters._
+
+class DataEvolutionMergeJoinReuseTest extends PaimonSparkTestBase {
+
+ private def snapshotId: Long =
+ paimonCatalog
+ .getTable(Identifier.create(dbName0, "target"))
+ .asInstanceOf[FileStoreTable]
+ .snapshotManager()
+ .latestSnapshotId()
+
+ private def createTarget(enabled: Boolean): Unit = {
+ sql(s"""CREATE TABLE target (id INT, value INT, payload STRING)
TBLPROPERTIES (
+ |'row-tracking.enabled'='true', 'data-evolution.enabled'='true',
+ |'data-evolution.merge-into.join-reuse'='$enabled')""".stripMargin)
+ sql("INSERT INTO target VALUES
(1,10,'a'),(2,20,'b'),(3,30,'c'),(NULL,40,'d')")
+ }
+
+ for (nullSafe <- Seq(false, true)) {
+ test(s"join reuse preserves complete ranges, action conditions and
nullSafe=$nullSafe") {
+ for (enabled <- Seq(false, true)) {
+ withSparkSQLConf(
+ "spark.paimon.write.use-v2-write" -> "false",
+ "spark.sql.adaptive.enabled" -> "true",
+ "spark.sql.adaptive.coalescePartitions.enabled" -> "true") {
+ withTable("target") {
+ withTempView("source") {
+ createTarget(enabled)
+ sql("""CREATE TEMPORARY VIEW source AS SELECT * FROM VALUES
+
|(1,100,'new1'),(2,200,'new2'),(4,400,'new4'),(NULL,900,'newnull')
+ |AS s(id,value,payload)""".stripMargin)
+ val oldPairs = sql("SELECT payload,_ROW_ID FROM
target").collect().toSet
+ val before = snapshotId
+ val persistedBefore = spark.sparkContext.getPersistentRDDs.keySet
+ val sharedPlanSeen = new CountDownLatch(1)
+ val targetScanSeen = new AtomicBoolean(false)
+ val unusedTargetPayloadRead = new AtomicBoolean(false)
+ val listener = new QueryExecutionListener {
+ override def onSuccess(name: String, qe: QueryExecution,
nanos: Long): Unit = {
+ val plan = qe.executedPlan.toString
+ if (plan.contains("InMemoryTableScan") &&
plan.contains("FullOuter")) {
+ val targetScans = plan
+ .split("\n")
+ .filter(_.contains("PaimonSplitScan: [target]"))
+ if (targetScans.nonEmpty) targetScanSeen.set(true)
+ if (targetScans.exists(_.takeWhile(_ !=
']').contains("payload#"))) {
+ unusedTargetPayloadRead.set(true)
+ }
+ sharedPlanSeen.countDown()
+ }
+ }
+ override def onFailure(name: String, qe: QueryExecution, e:
Exception): Unit = {}
+ }
+ spark.listenerManager.register(listener)
+ try {
+ val equality = if (nullSafe) "<=>" else "="
+ sql(s"""MERGE INTO target t USING source s ON t.id $equality
s.id
+ |WHEN MATCHED AND s.id=1 THEN UPDATE SET value=s.value
+ |WHEN MATCHED AND s.id IS NULL THEN UPDATE SET
value=s.value
+ |WHEN NOT MATCHED AND (s.id=4 OR s.id IS NULL) THEN
+ |INSERT (id,value,payload) VALUES
(s.id,s.value,s.payload)""".stripMargin)
+ val expected = Seq(
+ Row(1, 100, "a"),
+ Row(2, 20, "b"),
+ Row(3, 30, "c"),
+ Row(null, if (nullSafe) 900 else 40, "d"),
+ Row(4, 400, "new4")) ++
+ (if (nullSafe) Nil else Seq(Row(null, 900, "newnull")))
+ checkAnswer(sql("SELECT * FROM target"), expected)
+ assert(
+ sql("SELECT payload,_ROW_ID FROM target WHERE payload IN
('a','b','c','d')")
+ .collect()
+ .toSet == oldPairs)
+ assert(snapshotId == before + 1)
+ assert(spark.sparkContext.getPersistentRDDs.keySet ==
persistedBefore)
+ if (enabled) {
+ assert(
+ sharedPlanSeen.await(10, TimeUnit.SECONDS),
+ "Expected a cached full-outer match plan")
+ assert(
+ targetScanSeen.get(),
+ "Expected the cached plan to identify its target scan")
+ assert(
+ !unusedTargetPayloadRead.get(),
+ "Unchanged target payload must stay pruned")
+ }
+ } finally {
+ spark.listenerManager.unregister(listener)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ test("join reuse identifies presence markers by identity rather than
business column names") {
+ withSparkSQLConf(
+ "spark.paimon.write.use-v2-write" -> "false",
+ "spark.sql.adaptive.enabled" -> "true",
+ "spark.sql.adaptive.coalescePartitions.enabled" -> "true") {
+ withTable("target") {
+ withTempView("source") {
+ createTarget(enabled = true)
+ sql("""CREATE TEMPORARY VIEW source AS SELECT id,value,
+ |CAST(NULL AS INT) AS __row_from_target, CAST(NULL AS INT) AS
__row_from_source
+ |FROM VALUES (1,100),(4,400) AS s(id,value)""".stripMargin)
+ sql(
+ """MERGE INTO target t USING source s ON t.id=s.id
+ |WHEN MATCHED THEN UPDATE SET value=s.value
+ |WHEN NOT MATCHED THEN INSERT (id,value,payload) VALUES
+
|(s.id,s.value,COALESCE(CAST(s.__row_from_target+s.__row_from_source AS
STRING),'new'))""".stripMargin)
+ checkAnswer(
+ sql("SELECT * FROM target"),
+ Seq(
+ Row(1, 100, "a"),
+ Row(2, 20, "b"),
+ Row(3, 30, "c"),
+ Row(null, 40, "d"),
+ Row(4, 400, "new")))
+ }
+ }
+ }
+ }
+
+ test("join reuse preserves adaptive insert file sizing and falls back
without coalescing") {
+ for ((adaptive, coalesce) <- Seq((false, true), (true, false), (true,
true))) {
+ withSparkSQLConf(
+ "spark.paimon.write.use-v2-write" -> "false",
+ "spark.sql.shuffle.partitions" -> "32",
+ "spark.sql.adaptive.enabled" -> adaptive.toString,
+ "spark.sql.adaptive.coalescePartitions.enabled" -> coalesce.toString,
+ "spark.sql.adaptive.coalescePartitions.parallelismFirst" -> "false",
+ "spark.sql.adaptive.advisoryPartitionSizeInBytes" -> "67108864",
+ "spark.sql.adaptive.coalescePartitions.minPartitionSize" -> "1048576"
+ ) {
+ withTable("target") {
+ withTempView("source") {
+ createTarget(enabled = true)
+ sql("""CREATE TEMPORARY VIEW source AS
+ |SELECT CAST(id AS INT) AS id, CAST(id*100 AS INT) AS value
+ |FROM range(0,128,1,2)""".stripMargin)
+ val persistedBefore = spark.sparkContext.getPersistentRDDs.keySet
+ val sharedPlanSeen = new CountDownLatch(1)
+ val listener = new QueryExecutionListener {
+ override def onSuccess(name: String, qe: QueryExecution, nanos:
Long): Unit = {
+ val plan = qe.executedPlan.toString
+ if (plan.contains("InMemoryTableScan") &&
plan.contains("FullOuter")) {
+ sharedPlanSeen.countDown()
+ }
+ }
+ override def onFailure(name: String, qe: QueryExecution, e:
Exception): Unit = {}
+ }
+ spark.listenerManager.register(listener)
+ try {
+ sql("""MERGE INTO target t USING source s ON t.id=s.id
+ |WHEN MATCHED THEN UPDATE SET value=s.value
+ |WHEN NOT MATCHED THEN INSERT (id,value,payload)
+ |VALUES (s.id,s.value,'new')""".stripMargin)
+ val retainedPayloads = Map(1 -> "a", 2 -> "b", 3 -> "c")
+ val expected = (0 until 128).map {
+ id => Row(id, id * 100, retainedPayloads.getOrElse(id, "new"))
+ } :+ Row(null, 40, "d")
+ checkAnswer(sql("SELECT * FROM target"), expected)
+ val table = paimonCatalog
+ .getTable(Identifier.create(dbName0, "target"))
+ .asInstanceOf[FileStoreTable]
+ val insertedFiles = table
+ .newReadBuilder()
+ .newScan()
+ .plan()
+ .splits()
+ .asScala
+ .flatMap(_.asInstanceOf[DataSplit].dataFiles().asScala)
+ .filter(file => Option(file.firstRowId()).exists(_.longValue()
>= 4L))
+ .map(file => file.fileName() -> file)
+ .toMap
+ .values
+ .toSeq
+ assert(
+ insertedFiles.nonEmpty && insertedFiles.size <= 2,
+ s"Unexpected INSERT files ${insertedFiles.size}:
adaptive=$adaptive, coalesce=$coalesce")
+ assert(insertedFiles.map(_.rowCount()).sum == 125L)
+ assert(spark.sparkContext.getPersistentRDDs.keySet ==
persistedBefore)
+ if (adaptive && coalesce) {
+ assert(
+ sharedPlanSeen.await(10, TimeUnit.SECONDS),
+ "Expected the supported configuration to reuse the join")
+ }
+ } finally {
+ spark.listenerManager.unregister(listener)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ test("join reuse releases persisted matches when duplicate source matches
fail") {
+ for (enabled <- Seq(false, true)) {
+ withSparkSQLConf(
+ "spark.paimon.write.use-v2-write" -> "false",
+ "spark.sql.adaptive.enabled" -> "true",
+ "spark.sql.adaptive.coalescePartitions.enabled" -> "true") {
+ withTable("target") {
+ withTempView("source") {
+ createTarget(enabled)
+ sql(
+ "CREATE TEMPORARY VIEW source AS SELECT * FROM VALUES
(1,100),(1,200) AS s(id,value)")
+ val rows = sql("SELECT *,_ROW_ID FROM target").collect().toSeq
+ val before = snapshotId
+ val persistedBefore = spark.sparkContext.getPersistentRDDs.keySet
+ val cachedBlockSeen = new CountDownLatch(1)
+ val listener = new SparkListener {
+ override def onBlockUpdated(event: SparkListenerBlockUpdated):
Unit = {
+ val block = event.blockUpdatedInfo
+ block.blockId match {
+ case id: RDDBlockId
+ if !persistedBefore.contains(id.rddId) && block.diskSize
> 0 &&
+ block.storageLevel.useDisk &&
!block.storageLevel.useMemory =>
+ cachedBlockSeen.countDown()
+ case _ =>
+ }
+ }
+ }
+ spark.sparkContext.addSparkListener(listener)
+ try {
+ val error = intercept[Exception] {
+ sql(
+ """MERGE INTO target t USING source s ON t.id=s.id
+ |WHEN MATCHED THEN UPDATE SET value=s.value
+ |WHEN NOT MATCHED THEN INSERT (id,value,payload) VALUES
(s.id,s.value,'new')""".stripMargin)
+ }
+ val causes =
Iterator.iterate[Throwable](error)(_.getCause).takeWhile(_ != null).toSeq
+ assert(
+ causes.exists(
+ cause =>
+ Option(cause.getMessage).exists(_.contains("Row ID should
be incremental."))),
+ s"Expected duplicate RowID rejection, got ${causes.mkString(";
")}"
+ )
+ assert(
+ !causes.exists(
+ cause =>
+ Option(cause.getMessage).exists(
+ message =>
+ message.contains("MISSING_ATTRIBUTES") ||
message.contains(
+ "Resolved attribute(s)"))),
+ "Duplicate source matching must not fail because of cache
attribute binding"
+ )
+ checkAnswer(sql("SELECT *,_ROW_ID FROM target"), rows)
+ assert(snapshotId == before)
+ assert(spark.sparkContext.getPersistentRDDs.keySet ==
persistedBefore)
+ if (enabled) {
+ assert(
+ cachedBlockSeen.await(10, TimeUnit.SECONDS),
+ "Expected a materialized DISK_ONLY RDD block before
duplicate RowID rejection")
+ }
+ info(
+ s"Duplicate RowID rejected: enabled=$enabled, " +
+ s"diskCacheCreated=${cachedBlockSeen.getCount == 0}, " +
+ s"snapshot=$before, persistentRDDsRestored=true; " +
+ causes
+ .map(cause => s"${cause.getClass.getName}:
${cause.getMessage}")
+ .mkString("; "))
+ } finally {
+ spark.sparkContext.removeSparkListener(listener)
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git
a/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Classic3Api.scala
b/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Classic3Api.scala
index e0ff2caf06..ded31d2712 100644
---
a/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Classic3Api.scala
+++
b/paimon-spark/paimon-spark3-common/src/main/scala/org/apache/spark/sql/paimon/shims/Classic3Api.scala
@@ -23,8 +23,12 @@ import
org.apache.spark.sql.catalyst.catalog.FunctionResourceLoader
import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression}
import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, LogicalPlan}
import org.apache.spark.sql.execution.{QueryExecution, SparkPlan}
+import org.apache.spark.sql.execution.columnar.InMemoryRelation
import org.apache.spark.sql.execution.command.CommandUtils
import org.apache.spark.sql.internal.SessionResourceLoader
+import org.apache.spark.storage.StorageLevel
+
+import scala.util.control.NonFatal
class Classic3Api extends ClassicApi {
override def column(expression: Expression): Column = new Column(expression)
@@ -40,6 +44,24 @@ class Classic3Api extends ClassicApi {
Dataset.ofRows(spark, logicalPlan)
}
+ override def createDiskCachedDataset(
+ spark: SparkSession,
+ logicalPlan: LogicalPlan): (Dataset[Row], () => Unit) = {
+ val input = Dataset.ofRows(spark, logicalPlan)
+ val relation = InMemoryRelation(StorageLevel.DISK_ONLY,
input.queryExecution, None)
+ try {
+ // Optimizer alias elimination must not change consumer attribute
identities.
+ val cachedRelation =
relation.withOutput(input.queryExecution.analyzed.output)
+ (
+ Dataset.ofRows(spark, cachedRelation),
+ () => relation.cacheBuilder.clearCache(blocking = true))
+ } catch {
+ case NonFatal(e) =>
+ relation.cacheBuilder.clearCache(blocking = true)
+ throw e
+ }
+ }
+
override def recacheByPlan(spark: SparkSession, plan: LogicalPlan): Unit = {
spark.sharedState.cacheManager.recacheByPlan(spark, plan)
}
diff --git
a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Classic4Api.scala
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Classic4Api.scala
index 860ecc28d3..b5aa2408d9 100644
---
a/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Classic4Api.scala
+++
b/paimon-spark/paimon-spark4-common/src/main/scala/org/apache/spark/sql/paimon/shims/Classic4Api.scala
@@ -24,8 +24,12 @@ import org.apache.spark.sql.catalyst.expressions.{Attribute,
Expression}
import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, LogicalPlan}
import org.apache.spark.sql.classic.{ClassicConversions, Dataset =>
ClassicDataset, ExpressionUtils}
import org.apache.spark.sql.execution.{QueryExecution, SparkPlan}
+import org.apache.spark.sql.execution.columnar.InMemoryRelation
import org.apache.spark.sql.execution.command.CommandUtils
import org.apache.spark.sql.internal.SessionResourceLoader
+import org.apache.spark.storage.StorageLevel
+
+import scala.util.control.NonFatal
/**
* This class is used to implement the conversion from sql-api to classic one.
Make sure this is the
@@ -48,6 +52,24 @@ class Classic4Api extends ClassicApi with ClassicConversions
{
ClassicDataset.ofRows(spark, logicalPlan)
}
+ override def createDiskCachedDataset(
+ spark: SparkSession,
+ logicalPlan: LogicalPlan): (Dataset[Row], () => Unit) = {
+ val input = ClassicDataset.ofRows(spark, logicalPlan)
+ val relation = InMemoryRelation(StorageLevel.DISK_ONLY,
input.queryExecution, None)
+ try {
+ // Optimizer alias elimination must not change consumer attribute
identities.
+ val cachedRelation =
relation.withOutput(input.queryExecution.analyzed.output)
+ (
+ ClassicDataset.ofRows(spark, cachedRelation),
+ () => relation.cacheBuilder.clearCache(blocking = true))
+ } catch {
+ case NonFatal(e) =>
+ relation.cacheBuilder.clearCache(blocking = true)
+ throw e
+ }
+ }
+
override def recacheByPlan(spark: SparkSession, plan: LogicalPlan): Unit = {
spark.sharedState.cacheManager.recacheByPlan(spark, plan)
}