From 85735273b5155c9a678f03bf55c431b69166bc00 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Wed, 18 Nov 2026 23:26:49 +0800 Subject: [PATCH 1/8] [spark] Narrow shared MERGE sources using pinned snapshots --- docs/docs/multimodal-table/data-evolution.mdx | 23 + .../java/org/apache/paimon/CoreOptions.java | 15 + .../MergeIntoPaimonDataEvolutionTable.scala | 157 +++++- .../MergeIntoPaimonDataEvolutionTable.scala | 157 +++++- .../DataEvolutionMergeNarrowSourceTest.scala | 450 ++++++++++++++++++ 5 files changed, 772 insertions(+), 30 deletions(-) create mode 100644 paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala diff --git a/docs/docs/multimodal-table/data-evolution.mdx b/docs/docs/multimodal-table/data-evolution.mdx index e9ba024f5ab5..3c0e988f835b 100644 --- a/docs/docs/multimodal-table/data-evolution.mdx +++ b/docs/docs/multimodal-table/data-evolution.mdx @@ -233,6 +233,29 @@ 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. +For a Paimon append source with large columns used only by INSERT, Spark can +keep those columns out of the shared result: + +```sql +ALTER TABLE target_table SET TBLPROPERTIES ( + 'data-evolution.merge-into.join-reuse' = 'true', + 'data-evolution.merge-into.join-reuse.narrow-source.enabled' = 'true' +); +``` + +The narrow-source option is disabled by default. It requires a single INT or +BIGINT equality key and a direct source table or a projection of its columns. +Spark pins the source snapshot before reading it and retrieves INSERT columns +with another source scan. Source duplicates and NULL keys retain the original +MERGE semantics. Unsupported statements, sources without a snapshot, and +statements using `data-evolution.merge-into.source-persist` keep the original +execution path. Schema-only changes newer than the data snapshot and retained +tags without a numbered snapshot file also use the original path. This can +reduce shuffle and disk cache size for wide sources, +but the extra scan and membership join can increase elapsed time. Compare +complete SQL execution time for the expected UPDATE/INSERT mix before enabling +it. This option does not perform positional source reads. + ### Flink SQL Use the `data_evolution_merge_into` procedure for matched updates. It runs in 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 96ef18a7c596..f1f3adc78517 100644 --- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java +++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java @@ -2822,6 +2822,17 @@ public String toString() { + "Requires Spark adaptive query execution and adaptive partition " + "coalescing; otherwise the original join path is used."); + public static final ConfigOption DATA_EVOLUTION_MERGE_INTO_NARROW_SOURCE = + key("data-evolution.merge-into.join-reuse.narrow-source.enabled") + .booleanType() + .defaultValue(false) + .withDescription( + "Whether Spark MERGE join reuse excludes INSERT-only source columns from " + + "the shared result and reads them again from a pinned source snapshot. " + + "Requires join reuse, a simple Paimon append source and an INT or BIGINT " + + "equality key. It reduces shared shuffle and cache size at the cost of " + + "another source scan. Unsupported sources use the original shared result."); + public static final ConfigOption DATA_EVOLUTION_COMPACTION_SPLIT_LARGE_FILES = key("data-evolution.compaction.split-large-files") .booleanType() @@ -4862,6 +4873,10 @@ public boolean dataEvolutionMergeIntoJoinReuse() { return options.get(DATA_EVOLUTION_MERGE_INTO_JOIN_REUSE); } + public boolean dataEvolutionMergeIntoNarrowSource() { + return options.get(DATA_EVOLUTION_MERGE_INTO_NARROW_SOURCE); + } + 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 9b425c661ce6..6f28ba27b6e6 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 @@ -49,14 +49,14 @@ 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, Attribute, AttributeReference, CreateNamedStruct, EqualTo, Expression, ExprId, GetStructField, If, IsNotNull, IsNull, Literal, Or, PythonUDF, SubqueryExpression} +import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, AttributeReference, CreateNamedStruct, EqualNullSafe, 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.{FullOuter, LeftAnti, LeftOuter} +import org.apache.spark.sql.catalyst.plans.{FullOuter, LeftAnti, LeftOuter, LeftSemi} 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} import org.apache.spark.sql.paimon.shims.SparkShimLoader -import org.apache.spark.sql.types.{BooleanType, StructType} +import org.apache.spark.sql.types.{BooleanType, IntegerType, LongType, StructType} import java.util.{HashMap => JHashMap} @@ -307,13 +307,27 @@ case class MergeIntoPaimonDataEvolutionTable( lazy val tableSchema: StructType = targetSparkTable.schema override def run(sparkSession: SparkSession): Seq[Row] = { + val pinnedSource = + if ( + table.coreOptions().dataEvolutionMergeIntoNarrowSource() && + !table.coreOptions().dataEvolutionMergeIntoSourcePersist() && + canReuseMergeJoin(sparkSession) && narrowSharedSourceKey.isDefined && + sourceTable.output.exists( + attr => allSharedDependencies.contains(attr.exprId) && + !updateSharedDependencies.contains(attr.exprId)) + ) { + pinNarrowSource(sourceTable, originalTargetRelation) + } else { + None + } + val command = pinnedSource.map(source => copy(sourceTable = source)).getOrElse(this) // Persist the schema that the analyzer evolved in memory (commit deferred to execution). SchemaEvolutionHelper.commitEvolvedSchemaAtExecution(table, targetRelation, sparkSession) - invokeMergeInto(sparkSession) + command.invokeMergeInto(sparkSession, pinnedSource.isDefined) Seq.empty[Row] } - private def invokeMergeInto(sparkSession: SparkSession): Unit = { + private def invokeMergeInto(sparkSession: SparkSession, narrowSource: Boolean): Unit = { val readSnapshot = TimeTravelUtil.tryTravelOrLatest(table) val snapshotReader = table.newSnapshotReader() if (readSnapshot != null) { @@ -395,7 +409,11 @@ case class MergeIntoPaimonDataEvolutionTable( if (canReuseMergeJoin(sparkSession) && matchedOrInsertDataSplits.nonEmpty) { sharedMatches = Some( - createSharedMergeJoin(sparkSession, touchedFileTargetRelation, persistSourceDss)) + createSharedMergeJoin( + sparkSession, + touchedFileTargetRelation, + persistSourceDss, + narrowSource)) } // step 2: invoke target-side action @@ -484,11 +502,42 @@ case class MergeIntoPaimonDataEvolutionTable( } } + private lazy val updateSharedDependencies: Set[ExprId] = { + val expressions = Seq(matchedCondition) ++ matchedActions.flatMap { + case update: UpdateAction => + update.condition.toSeq ++ update.assignments + .filter(a => updateColumns.contains(assignmentKeyAttribute(a))) + .map(_.value) + case action => action.condition.toSeq + } + (expressions.flatMap(extractFields) ++ updateColumns).map(_.exprId).toSet + } + + private lazy val allSharedDependencies: Set[ExprId] = + (mergeReadExpressions.flatMap(extractFields) ++ updateColumns).map(_.exprId).toSet + + private def narrowSharedSourceKey: Option[AttributeReference] = { + val sourceIds = sourceTable.output.map(_.exprId).toSet + val targetIds = targetRelation.output.map(_.exprId).toSet + def eligible(source: AttributeReference, target: AttributeReference): Boolean = + sourceIds.contains(source.exprId) && targetIds.contains(target.exprId) && + (source.dataType == IntegerType || source.dataType == LongType) && + source.dataType == target.dataType + matchedCondition match { + case EqualTo(left: AttributeReference, right: AttributeReference) => + if (eligible(left, right)) Some(left) + else if (eligible(right, left)) Some(right) + else None + case _ => None + } + } + private case class SharedMergeJoin( dataset: Dataset[Row], targetMarkerId: ExprId, sourceMarkerId: ExprId, - cleanup: () => Unit) { + cleanup: () => Unit, + rereadSourceKey: Option[AttributeReference]) { def targetMarker(plan: LogicalPlan): Attribute = plan.output.find(_.exprId == targetMarkerId).get @@ -499,10 +548,10 @@ case class MergeIntoPaimonDataEvolutionTable( private def createSharedMergeJoin( sparkSession: SparkSession, touchedFileTargetRelation: DataSourceV2Relation, - persistSourceDss: Option[Dataset[Row]]): SharedMergeJoin = { - val needed = (mergeReadExpressions.flatMap(extractFields) ++ updateColumns) - .map(_.exprId) - .toSet + persistSourceDss: Option[Dataset[Row]], + narrowSource: Boolean): SharedMergeJoin = { + val rereadKey = if (narrowSource) narrowSharedSourceKey else None + val needed = if (rereadKey.isDefined) updateSharedDependencies else allSharedDependencies val targetAttributes = (targetRelation.output ++ targetRelation.metadataOutput) .foldLeft(Seq.empty[AttributeReference]) { (attrs, attr) => if (attrs.exists(_.exprId == attr.exprId)) attrs else attrs :+ attr @@ -519,7 +568,7 @@ case class MergeIntoPaimonDataEvolutionTable( val (dataset, cleanup) = createDiskCachedDataset( sparkSession, Join(targetProject, sourceProject, FullOuter, Some(matchedCondition), JoinHint.NONE)) - SharedMergeJoin(dataset, targetMarker.exprId, sourceMarker.exprId, cleanup) + SharedMergeJoin(dataset, targetMarker.exprId, sourceMarker.exprId, cleanup, rereadKey) } private def pushDownMergeFilters(snapshotReader: SnapshotReader): Unit = { @@ -1223,9 +1272,24 @@ case class MergeIntoPaimonDataEvolutionTable( 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)) + shared.rereadSourceKey match { + case Some(key) => + val cachedKey = plan.output.find(_.exprId == key.exprId).get + val membershipKey = Alias(cachedKey, "__paimon_unmatched_source_key")() + val unmatched = Project( + Seq(membershipKey), Filter(IsNull(shared.targetMarker(plan)), plan)) + // Membership must retain NULL keys and every duplicate row in the fixed source. + Join( + sourceReadPlan, + unmatched, + LeftSemi, + Some(EqualNullSafe(key, membershipKey.toAttribute)), + JoinHint.NONE) + case None => + 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) } @@ -1432,6 +1496,69 @@ object MergeIntoPaimonDataEvolutionTable { final private val MERGE_DELETED_NAME = "_PAIMON_MERGE_INTO_DELETED" final private val RAW_BLOB_PLACEHOLDER_MARKER_PREFIX = "__paimon_raw_blob_placeholder_" + private[commands] def pinNarrowSource( + plan: LogicalPlan, + targetRelation: DataSourceV2Relation): Option[LogicalPlan] = { + def identity(table: FileStoreTable): (String, String) = + (table.location().toString, BranchManager.normalizeBranch(CoreOptions.branch(table.options()))) + + val target = targetRelation.table match { + case sparkTable: SparkTable => sparkTable.getTable.asInstanceOf[FileStoreTable] + case _ => return None + } + + def pin(current: LogicalPlan): Option[LogicalPlan] = current match { + case alias: SubqueryAlias => pin(alias.child).map(child => alias.copy(child = child)) + case project: Project if project.projectList.forall { + case _: AttributeReference => true + case Alias(_: AttributeReference, _) => true + case _ => false + } => + pin(project.child).map(child => project.copy(child = child)) + case relation: DataSourceV2Relation => + relation.table match { + case sparkTable: SparkTable => + sparkTable.getTable match { + case source: FileStoreTable + if source.primaryKeys().isEmpty && identity(source) != identity(target) && + Set( + CoreOptions.StartupMode.LATEST_FULL, + CoreOptions.StartupMode.LATEST, + CoreOptions.StartupMode.FROM_TIMESTAMP, + CoreOptions.StartupMode.FROM_SNAPSHOT, + CoreOptions.StartupMode.FROM_SNAPSHOT_FULL) + .contains(source.coreOptions().startupMode()) => + // Resolving scan.version can mutate options; never resolve it on the input table. + val copied = source.copy(new JHashMap[String, String]()) + Option(TimeTravelUtil.tryTravelOrLatest(copied)) + .filter(snapshot => copied.snapshotManager().snapshotExists(snapshot.id())) + .flatMap { + snapshot => + val options = new JHashMap[String, String]() + timeTravelOptionKeys.foreach(options.put(_, null)) + options.put(CoreOptions.SCAN_SNAPSHOT_ID.key(), snapshot.id().toString) + options.put(CoreOptions.SCAN_MODE.key(), CoreOptions.StartupMode.FROM_SNAPSHOT.toString) + val pinned = copied.copy(options) + // A schema-only change is newer than the data snapshot's read schema. + if (pinned.schema().id() != source.schema().id()) { + None + } else { + Some(SparkShimLoader.shim.copyDataSourceV2Relation( + relation, + SparkTable.of(pinned), + relation.output)) + } + } + case _ => None + } + case _ => None + } + case _ => None + } + + pin(plan) + } + private[commands] def withMatchedUpdateScanOptions( v2Table: SparkTable, relation: DataSourceV2Relation): (SparkTable, DataSourceV2Relation) = { 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 9b425c661ce6..6f28ba27b6e6 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 @@ -49,14 +49,14 @@ 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, Attribute, AttributeReference, CreateNamedStruct, EqualTo, Expression, ExprId, GetStructField, If, IsNotNull, IsNull, Literal, Or, PythonUDF, SubqueryExpression} +import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, AttributeReference, CreateNamedStruct, EqualNullSafe, 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.{FullOuter, LeftAnti, LeftOuter} +import org.apache.spark.sql.catalyst.plans.{FullOuter, LeftAnti, LeftOuter, LeftSemi} 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} import org.apache.spark.sql.paimon.shims.SparkShimLoader -import org.apache.spark.sql.types.{BooleanType, StructType} +import org.apache.spark.sql.types.{BooleanType, IntegerType, LongType, StructType} import java.util.{HashMap => JHashMap} @@ -307,13 +307,27 @@ case class MergeIntoPaimonDataEvolutionTable( lazy val tableSchema: StructType = targetSparkTable.schema override def run(sparkSession: SparkSession): Seq[Row] = { + val pinnedSource = + if ( + table.coreOptions().dataEvolutionMergeIntoNarrowSource() && + !table.coreOptions().dataEvolutionMergeIntoSourcePersist() && + canReuseMergeJoin(sparkSession) && narrowSharedSourceKey.isDefined && + sourceTable.output.exists( + attr => allSharedDependencies.contains(attr.exprId) && + !updateSharedDependencies.contains(attr.exprId)) + ) { + pinNarrowSource(sourceTable, originalTargetRelation) + } else { + None + } + val command = pinnedSource.map(source => copy(sourceTable = source)).getOrElse(this) // Persist the schema that the analyzer evolved in memory (commit deferred to execution). SchemaEvolutionHelper.commitEvolvedSchemaAtExecution(table, targetRelation, sparkSession) - invokeMergeInto(sparkSession) + command.invokeMergeInto(sparkSession, pinnedSource.isDefined) Seq.empty[Row] } - private def invokeMergeInto(sparkSession: SparkSession): Unit = { + private def invokeMergeInto(sparkSession: SparkSession, narrowSource: Boolean): Unit = { val readSnapshot = TimeTravelUtil.tryTravelOrLatest(table) val snapshotReader = table.newSnapshotReader() if (readSnapshot != null) { @@ -395,7 +409,11 @@ case class MergeIntoPaimonDataEvolutionTable( if (canReuseMergeJoin(sparkSession) && matchedOrInsertDataSplits.nonEmpty) { sharedMatches = Some( - createSharedMergeJoin(sparkSession, touchedFileTargetRelation, persistSourceDss)) + createSharedMergeJoin( + sparkSession, + touchedFileTargetRelation, + persistSourceDss, + narrowSource)) } // step 2: invoke target-side action @@ -484,11 +502,42 @@ case class MergeIntoPaimonDataEvolutionTable( } } + private lazy val updateSharedDependencies: Set[ExprId] = { + val expressions = Seq(matchedCondition) ++ matchedActions.flatMap { + case update: UpdateAction => + update.condition.toSeq ++ update.assignments + .filter(a => updateColumns.contains(assignmentKeyAttribute(a))) + .map(_.value) + case action => action.condition.toSeq + } + (expressions.flatMap(extractFields) ++ updateColumns).map(_.exprId).toSet + } + + private lazy val allSharedDependencies: Set[ExprId] = + (mergeReadExpressions.flatMap(extractFields) ++ updateColumns).map(_.exprId).toSet + + private def narrowSharedSourceKey: Option[AttributeReference] = { + val sourceIds = sourceTable.output.map(_.exprId).toSet + val targetIds = targetRelation.output.map(_.exprId).toSet + def eligible(source: AttributeReference, target: AttributeReference): Boolean = + sourceIds.contains(source.exprId) && targetIds.contains(target.exprId) && + (source.dataType == IntegerType || source.dataType == LongType) && + source.dataType == target.dataType + matchedCondition match { + case EqualTo(left: AttributeReference, right: AttributeReference) => + if (eligible(left, right)) Some(left) + else if (eligible(right, left)) Some(right) + else None + case _ => None + } + } + private case class SharedMergeJoin( dataset: Dataset[Row], targetMarkerId: ExprId, sourceMarkerId: ExprId, - cleanup: () => Unit) { + cleanup: () => Unit, + rereadSourceKey: Option[AttributeReference]) { def targetMarker(plan: LogicalPlan): Attribute = plan.output.find(_.exprId == targetMarkerId).get @@ -499,10 +548,10 @@ case class MergeIntoPaimonDataEvolutionTable( private def createSharedMergeJoin( sparkSession: SparkSession, touchedFileTargetRelation: DataSourceV2Relation, - persistSourceDss: Option[Dataset[Row]]): SharedMergeJoin = { - val needed = (mergeReadExpressions.flatMap(extractFields) ++ updateColumns) - .map(_.exprId) - .toSet + persistSourceDss: Option[Dataset[Row]], + narrowSource: Boolean): SharedMergeJoin = { + val rereadKey = if (narrowSource) narrowSharedSourceKey else None + val needed = if (rereadKey.isDefined) updateSharedDependencies else allSharedDependencies val targetAttributes = (targetRelation.output ++ targetRelation.metadataOutput) .foldLeft(Seq.empty[AttributeReference]) { (attrs, attr) => if (attrs.exists(_.exprId == attr.exprId)) attrs else attrs :+ attr @@ -519,7 +568,7 @@ case class MergeIntoPaimonDataEvolutionTable( val (dataset, cleanup) = createDiskCachedDataset( sparkSession, Join(targetProject, sourceProject, FullOuter, Some(matchedCondition), JoinHint.NONE)) - SharedMergeJoin(dataset, targetMarker.exprId, sourceMarker.exprId, cleanup) + SharedMergeJoin(dataset, targetMarker.exprId, sourceMarker.exprId, cleanup, rereadKey) } private def pushDownMergeFilters(snapshotReader: SnapshotReader): Unit = { @@ -1223,9 +1272,24 @@ case class MergeIntoPaimonDataEvolutionTable( 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)) + shared.rereadSourceKey match { + case Some(key) => + val cachedKey = plan.output.find(_.exprId == key.exprId).get + val membershipKey = Alias(cachedKey, "__paimon_unmatched_source_key")() + val unmatched = Project( + Seq(membershipKey), Filter(IsNull(shared.targetMarker(plan)), plan)) + // Membership must retain NULL keys and every duplicate row in the fixed source. + Join( + sourceReadPlan, + unmatched, + LeftSemi, + Some(EqualNullSafe(key, membershipKey.toAttribute)), + JoinHint.NONE) + case None => + 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) } @@ -1432,6 +1496,69 @@ object MergeIntoPaimonDataEvolutionTable { final private val MERGE_DELETED_NAME = "_PAIMON_MERGE_INTO_DELETED" final private val RAW_BLOB_PLACEHOLDER_MARKER_PREFIX = "__paimon_raw_blob_placeholder_" + private[commands] def pinNarrowSource( + plan: LogicalPlan, + targetRelation: DataSourceV2Relation): Option[LogicalPlan] = { + def identity(table: FileStoreTable): (String, String) = + (table.location().toString, BranchManager.normalizeBranch(CoreOptions.branch(table.options()))) + + val target = targetRelation.table match { + case sparkTable: SparkTable => sparkTable.getTable.asInstanceOf[FileStoreTable] + case _ => return None + } + + def pin(current: LogicalPlan): Option[LogicalPlan] = current match { + case alias: SubqueryAlias => pin(alias.child).map(child => alias.copy(child = child)) + case project: Project if project.projectList.forall { + case _: AttributeReference => true + case Alias(_: AttributeReference, _) => true + case _ => false + } => + pin(project.child).map(child => project.copy(child = child)) + case relation: DataSourceV2Relation => + relation.table match { + case sparkTable: SparkTable => + sparkTable.getTable match { + case source: FileStoreTable + if source.primaryKeys().isEmpty && identity(source) != identity(target) && + Set( + CoreOptions.StartupMode.LATEST_FULL, + CoreOptions.StartupMode.LATEST, + CoreOptions.StartupMode.FROM_TIMESTAMP, + CoreOptions.StartupMode.FROM_SNAPSHOT, + CoreOptions.StartupMode.FROM_SNAPSHOT_FULL) + .contains(source.coreOptions().startupMode()) => + // Resolving scan.version can mutate options; never resolve it on the input table. + val copied = source.copy(new JHashMap[String, String]()) + Option(TimeTravelUtil.tryTravelOrLatest(copied)) + .filter(snapshot => copied.snapshotManager().snapshotExists(snapshot.id())) + .flatMap { + snapshot => + val options = new JHashMap[String, String]() + timeTravelOptionKeys.foreach(options.put(_, null)) + options.put(CoreOptions.SCAN_SNAPSHOT_ID.key(), snapshot.id().toString) + options.put(CoreOptions.SCAN_MODE.key(), CoreOptions.StartupMode.FROM_SNAPSHOT.toString) + val pinned = copied.copy(options) + // A schema-only change is newer than the data snapshot's read schema. + if (pinned.schema().id() != source.schema().id()) { + None + } else { + Some(SparkShimLoader.shim.copyDataSourceV2Relation( + relation, + SparkTable.of(pinned), + relation.output)) + } + } + case _ => None + } + case _ => None + } + case _ => None + } + + pin(plan) + } + private[commands] def withMatchedUpdateScanOptions( v2Table: SparkTable, relation: DataSourceV2Relation): (SparkTable, DataSourceV2Relation) = { diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala new file mode 100644 index 000000000000..3e6c4d6aedd0 --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala @@ -0,0 +1,450 @@ +/* + * 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.spark.{PaimonSparkTestBase, SparkTable} +import org.apache.paimon.spark.schema.PaimonMetadataColumn +import org.apache.paimon.table.FileStoreTable + +import org.apache.spark.scheduler.{SparkListener, SparkListenerBlockUpdated} +import org.apache.spark.sql.Row +import org.apache.spark.sql.PaimonUtils.createDataset +import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan +import org.apache.spark.sql.execution.QueryExecution +import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper +import org.apache.spark.sql.execution.columnar.InMemoryTableScanExec +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation +import org.apache.spark.sql.paimon.Utils +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 DataEvolutionMergeNarrowSourceTest + extends PaimonSparkTestBase + with AdaptiveSparkPlanHelper { + + private def relation(plan: LogicalPlan): DataSourceV2Relation = + plan.collectFirst { case r: DataSourceV2Relation => r }.get + + private def fileTable(plan: LogicalPlan): FileStoreTable = + relation(plan).table.asInstanceOf[SparkTable].getTable.asInstanceOf[FileStoreTable] + + private def withTables(dataEvolutionSource: Boolean = false)(body: => Unit): Unit = { + withSparkSQLConf( + "spark.paimon.write.use-v2-write" -> "false", + "spark.sql.adaptive.enabled" -> "true", + "spark.sql.adaptive.coalescePartitions.enabled" -> "true") { + withTable("target", "source") { + sql("""CREATE TABLE target (id INT, value INT, payload STRING) TBLPROPERTIES ( + |'bucket'='-1', 'row-tracking.enabled'='true', 'data-evolution.enabled'='true', + |'data-evolution.merge-into.join-reuse'='true', + |'data-evolution.merge-into.join-reuse.narrow-source.enabled'='true')""".stripMargin) + val sourceOptions = if (dataEvolutionSource) { + ",'row-tracking.enabled'='true','data-evolution.enabled'='true'" + } else { + "" + } + sql(s"""CREATE TABLE source (id INT, value INT, insert_payload STRING) + |TBLPROPERTIES ('bucket'='-1'$sourceOptions)""".stripMargin) + body + } + } + } + + private def withNarrowPlan(expectNarrow: Boolean = true)(body: => Unit): Unit = { + val persistedBefore = spark.sparkContext.getPersistentRDDs.keySet + val semiJoinSeen = new AtomicBoolean(false) + val sharedCacheSeen = new AtomicBoolean(false) + val cachedInsertPayload = new AtomicBoolean(false) + val listener = new QueryExecutionListener { + override def onSuccess(name: String, qe: QueryExecution, nanos: Long): Unit = { + if (qe.executedPlan.toString.contains("LeftSemi")) semiJoinSeen.set(true) + foreach(qe.executedPlan) { + case memory: InMemoryTableScanExec + if memory.relation.cachedPlan.toString.contains("FullOuter") => + sharedCacheSeen.set(true) + if (memory.relation.output.exists(_.name == "insert_payload")) { + cachedInsertPayload.set(true) + } + case _ => + } + } + override def onFailure(name: String, qe: QueryExecution, e: Exception): Unit = {} + } + Utils.waitUntilEventEmpty(spark) + spark.listenerManager.register(listener) + try { + body + Utils.waitUntilEventEmpty(spark) + assert(sharedCacheSeen.get(), "Expected the shared full-outer match cache to be consumed") + if (expectNarrow) { + assert(semiJoinSeen.get(), "Expected late source payload materialization through LeftSemi") + assert(!cachedInsertPayload.get(), "INSERT-only payload must not enter the shared cache") + } else { + assert(!semiJoinSeen.get(), "Fallback must not add a source payload LeftSemi join") + assert(cachedInsertPayload.get(), "Fallback must retain INSERT payload in the shared cache") + } + assert(spark.sparkContext.getPersistentRDDs.keySet == persistedBefore) + } finally { + spark.listenerManager.unregister(listener) + } + } + + for (dataEvolution <- Seq(false, true)) { + test(s"pin narrow source preserves snapshot and ExprIds for dataEvolution=$dataEvolution") { + withTables(dataEvolution) { + sql("INSERT INTO source VALUES (1,10,'old')") + val metadataColumn = if (dataEvolution) { + PaimonMetadataColumn.ROW_ID_COLUMN + } else { + PaimonMetadataColumn.FILE_PATH_COLUMN + } + val metadataValue = sql(s"SELECT $metadataColumn FROM source").head().get(0) + assert(metadataValue != null) + if (dataEvolution) assert(metadataValue == 0L) + val plan = sql( + s"SELECT s.id AS source_id,s.value,s.insert_payload,s.$metadataColumn FROM source s") + .queryExecution.analyzed + val original = fileTable(plan) + val originalOptions = original.options().asScala.toMap + val snapshot = original.snapshotManager().latestSnapshotId() + val pinned = MergeIntoPaimonDataEvolutionTable + .pinNarrowSource(plan, createRelationV2("target")) + assert(pinned.isDefined, "A passthrough alias/project over a source table must be pinnable") + val pinnedPlan = pinned.get + assert(pinnedPlan.output.map(_.exprId) == plan.output.map(_.exprId)) + assert(relation(pinnedPlan).output.map(_.exprId) == relation(plan).output.map(_.exprId)) + assert(!(fileTable(pinnedPlan) eq original), "Pinning must copy the source table") + assert(fileTable(pinnedPlan).options().get("scan.snapshot-id") == snapshot.toString) + + // Construct and execute the Dataset only after the source has changed. + if (dataEvolution) sql("UPDATE source SET value=99 WHERE id=1") + sql("INSERT INTO source VALUES (2,20,'new')") + checkAnswer(createDataset(spark, pinnedPlan), Seq(Row(1, 10, "old", metadataValue))) + checkAnswer( + sql("SELECT * FROM source"), + Seq(Row(1, if (dataEvolution) 99 else 10, "old"), Row(2, 20, "new"))) + assert(original.options().asScala.toMap == originalOptions) + assert(loadTable("source").options().get("scan.snapshot-id") == null) + } + } + } + + test("pinned source retains its snapshot when recomputed after unpersist") { + withTables(dataEvolutionSource = true) { + sql("INSERT INTO source VALUES (1,10,'old')") + val plan = sql("SELECT * FROM source").queryExecution.analyzed + val pinned = MergeIntoPaimonDataEvolutionTable + .pinNarrowSource(plan, createRelationV2("target")) + assert(pinned.isDefined) + val persistedBefore = spark.sparkContext.getPersistentRDDs.keySet + val dataset = createDataset(spark, pinned.get).persist() + try { + checkAnswer(dataset, Seq(Row(1, 10, "old"))) + assert(spark.sparkContext.getPersistentRDDs.keySet.diff(persistedBefore).nonEmpty) + dataset.unpersist(blocking = true) + assert(spark.sparkContext.getPersistentRDDs.keySet == persistedBefore) + sql("UPDATE source SET value=99 WHERE id=1") + sql("INSERT INTO source VALUES (2,20,'new')") + checkAnswer(dataset, Seq(Row(1, 10, "old"))) + checkAnswer(sql("SELECT * FROM source"), Seq(Row(1, 99, "old"), Row(2, 20, "new"))) + } finally { + dataset.unpersist(blocking = true) + } + assert(spark.sparkContext.getPersistentRDDs.keySet == persistedBefore) + } + } + + test("pin narrow source retains explicit time travel instead of choosing latest") { + withTables(dataEvolutionSource = true) { + sql("INSERT INTO source VALUES (1,10,'historical')") + val historicalSnapshot = loadTable("source").snapshotManager().latestSnapshotId() + sql("UPDATE source SET value=20 WHERE id=1") + val plan = sql(s"SELECT * FROM source VERSION AS OF $historicalSnapshot") + .queryExecution.analyzed + val originalOptions = fileTable(plan).options().asScala.toMap + val pinned = MergeIntoPaimonDataEvolutionTable + .pinNarrowSource(plan, createRelationV2("target")) + assert(pinned.isDefined) + sql("INSERT INTO source VALUES (2,30,'latest')") + checkAnswer(createDataset(spark, pinned.get), Seq(Row(1, 10, "historical"))) + assert(fileTable(pinned.get).options().get("scan.snapshot-id") == historicalSnapshot.toString) + assert(fileTable(plan).options().asScala.toMap == originalOptions) + } + } + + for (rename <- Seq(true, false)) { + test(s"pin narrow source falls back after a schema-only change: rename=$rename") { + withTables() { + sql("INSERT INTO target VALUES (1,10,'old')") + sql("INSERT INTO source VALUES (1,100,'unused'),(4,400,'new')") + val before = loadTable("source") + val snapshot = before.snapshotManager().latestSnapshotId() + val schemaId = before.schema().id() + if (rename) { + sql("ALTER TABLE source RENAME COLUMN insert_payload TO payload2") + } else { + sql("ALTER TABLE source ADD COLUMNS (payload2 STRING)") + } + val plan = sql("SELECT * FROM source").queryExecution.analyzed + val original = fileTable(plan) + val originalOptions = original.options().asScala.toMap + assert(original.snapshotManager().latestSnapshotId() == snapshot) + assert(original.schema().id() > schemaId) + assert( + MergeIntoPaimonDataEvolutionTable + .pinNarrowSource(plan, createRelationV2("target")) + .isEmpty, + "Pinning must not replace the current source schema with the data snapshot schema") + val payload = if (rename) "s.payload2" else "COALESCE(s.payload2,s.insert_payload)" + sql(s"""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,$payload)""".stripMargin) + checkAnswer(sql("SELECT * FROM target"), Seq(Row(1, 100, "old"), Row(4, 400, "new"))) + assert(original.options().asScala.toMap == originalOptions) + } + } + } + + test("pin narrow source falls back when a retained tag has no snapshot metadata file") { + withTables() { + sql("INSERT INTO source VALUES (1,100,'tagged')") + val table = loadTable("source") + val snapshot = table.snapshotManager().latestSnapshotId() + table.createTag("retained", snapshot) + sql("INSERT INTO source VALUES (4,400,'latest')") + assert(table.fileIO().delete(table.snapshotManager().snapshotPath(snapshot), false)) + assert(!table.snapshotManager().snapshotExists(snapshot)) + val query = "SELECT * FROM source VERSION AS OF 'retained'" + checkAnswer(sql(query), Seq(Row(1, 100, "tagged"))) + val plan = sql(query).queryExecution.analyzed + val originalOptions = fileTable(plan).options().asScala.toMap + assert( + MergeIntoPaimonDataEvolutionTable + .pinNarrowSource(plan, createRelationV2("target")) + .isEmpty, + "A retained tag must keep its tag reader when the numbered snapshot file has expired") + checkAnswer(createDataset(spark, plan), Seq(Row(1, 100, "tagged"))) + assert(fileTable(plan).options().asScala.toMap == originalOptions) + } + } + + test("pin narrow source rejects self reads and complex analyzed source plans") { + withTables() { + sql("INSERT INTO source VALUES (1,10,'source')") + sql("INSERT INTO target VALUES (1,10,'target')") + val target = createRelationV2("target") + val self = sql("SELECT t.id AS source_id,t.value FROM target t").queryExecution.analyzed + assert(MergeIntoPaimonDataEvolutionTable.pinNarrowSource(self, target).isEmpty) + withTempView("computed_source") { + sql("CREATE TEMPORARY VIEW computed_source AS SELECT id,value+1 AS value FROM source") + Seq( + "SELECT * FROM computed_source", + "SELECT * FROM source WHERE id=1", + "SELECT id,value+1 AS value FROM source", + "SELECT id,COUNT(*) FROM source GROUP BY id", + "SELECT s.id FROM source s JOIN target t ON s.id=t.id", + "SELECT * FROM source UNION ALL SELECT * FROM source" + ).foreach { + query => + assert( + MergeIntoPaimonDataEvolutionTable + .pinNarrowSource(sql(query).queryExecution.analyzed, target) + .isEmpty, + s"Expected fallback for $query") + } + } + } + } + + test("pin narrow source distinguishes branches of the same table") { + withTables() { + sql("INSERT INTO target VALUES (1,10,'branch-base')") + sql("CALL sys.create_tag(table => 'test.target', tag => 'base', snapshot => 1)") + sql("CALL sys.create_branch(table => 'test.target', branch => 'other', tag => 'base')") + val plan = sql("SELECT * FROM `target$branch_other`").queryExecution.analyzed + val pinned = MergeIntoPaimonDataEvolutionTable + .pinNarrowSource(plan, createRelationV2("target")) + assert(pinned.isDefined, "A different branch is a distinct source identity") + sql("INSERT INTO target VALUES (2,20,'main-only')") + checkAnswer(createDataset(spark, pinned.get), Seq(Row(1, 10, "branch-base"))) + } + } + + test("pin narrow source returns None before the first source snapshot") { + withTables() { + val plan = sql("SELECT * FROM source").queryExecution.analyzed + assert(loadTable("source").snapshotManager().latestSnapshotId() == null) + assert( + MergeIntoPaimonDataEvolutionTable + .pinNarrowSource(plan, createRelationV2("target")) + .isEmpty) + sql("INSERT INTO target VALUES (1,10,'unchanged')") + 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,s.insert_payload)""".stripMargin) + checkAnswer(sql("SELECT * FROM target"), Seq(Row(1, 10, "unchanged"))) + } + } + + test("pin narrow source falls back for compacted-full startup mode") { + withTables() { + sql("INSERT INTO source VALUES (1,10,'source')") + val target = createRelationV2("target") + withSparkSQLConf("spark.paimon.scan.mode" -> "compacted-full") { + val plan = sql("SELECT * FROM source").queryExecution.analyzed + assert(fileTable(plan).options().get("scan.mode") == "compacted-full") + assert(MergeIntoPaimonDataEvolutionTable.pinNarrowSource(plan, target).isEmpty) + } + } + } + + for (nullSafe <- Seq(false, true)) { + test(s"narrow source preserves NULL matching and false update conditions: nullSafe=$nullSafe") { + withTables() { + sql("INSERT INTO target VALUES (1,10,'a'),(2,20,'b'),(3,30,'c'),(NULL,40,'d')") + sql("""INSERT INTO source VALUES (1,100,'new1'),(2,200,'new2'), + |(4,400,'new4'),(NULL,900,'newnull')""".stripMargin) + val oldPairs = sql("SELECT payload,_ROW_ID FROM target").collect().toSet + val snapshot = loadTable("target").snapshotManager().latestSnapshotId() + withNarrowPlan(expectNarrow = !nullSafe) { + 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 OR 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.insert_payload)""".stripMargin) + checkAnswer( + sql("SELECT * FROM target"), + 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")))) + assert( + sql("SELECT payload,_ROW_ID FROM target WHERE payload IN ('a','b','c','d')") + .collect() + .toSet == oldPairs) + assert(loadTable("target").snapshotManager().latestSnapshotId() == snapshot + 1) + } + } + } + } + + test("narrow source preserves multiple insert action schemas and duplicate unmatched rows") { + withTables(dataEvolutionSource = true) { + sql("INSERT INTO target VALUES (1,10,'old')") + sql("""INSERT INTO source VALUES (1,100,'unused'),(4,400,'first'), + |(5,500,'second'),(5,500,'second'),(6,600,'ignored')""".stripMargin) + withNarrowPlan() { + sql("""MERGE INTO target t USING source s ON t.id=s.id + |WHEN MATCHED THEN UPDATE SET value=s.value + |WHEN NOT MATCHED AND s.id=4 THEN INSERT (id,value,payload) + |VALUES (s.id,s.value+1,s.insert_payload) + |WHEN NOT MATCHED AND s.id=5 THEN INSERT (payload,id,value) + |VALUES (s.insert_payload,s.id,s.value+2)""".stripMargin) + checkAnswer( + sql("SELECT * FROM target"), + Seq( + Row(1, 100, "old"), + Row(4, 401, "first"), + Row(5, 502, "second"), + Row(5, 502, "second"))) + } + } + } + + test("narrow source rebuilds matches for a reused source schema after cleanup") { + withTables(dataEvolutionSource = true) { + sql("INSERT INTO target VALUES (1,10,'old')") + sql("INSERT INTO source VALUES (1,100,'unused'),(4,400,'first')") + val merge = """MERGE INTO target t USING + |(SELECT id,value,insert_payload AS payload FROM 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,s.payload)""".stripMargin + val persistedBefore = spark.sparkContext.getPersistentRDDs.keySet + sql(merge) + sql("UPDATE source SET value=value+1") + sql("INSERT INTO source VALUES (5,500,'second')") + sql(merge) + checkAnswer( + sql("SELECT * FROM target"), + Seq(Row(1, 101, "old"), Row(4, 401, "first"), Row(5, 500, "second"))) + assert(spark.sparkContext.getPersistentRDDs.keySet == persistedBefore) + } + } + + test("narrow source releases materialized matches when duplicate source matches fail") { + withTables() { + sql("INSERT INTO target VALUES (1,10,'unchanged')") + sql("INSERT INTO source VALUES (1,100,'a'),(1,200,'b'),(4,400,'not-committed')") + val rows = sql("SELECT *,_ROW_ID FROM target").collect().toSeq + val snapshot = loadTable("target").snapshotManager().latestSnapshotId() + 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,s.insert_payload)""".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 matches must fail on RowID validation rather than cache attribute binding") + assert(cachedBlockSeen.await(10, TimeUnit.SECONDS), "Expected a materialized disk cache") + checkAnswer(sql("SELECT *,_ROW_ID FROM target"), rows) + assert(loadTable("target").snapshotManager().latestSnapshotId() == snapshot) + assert(spark.sparkContext.getPersistentRDDs.keySet == persistedBefore) + } finally { + spark.sparkContext.removeSparkListener(listener) + } + } + } +} From 33d13e795d150b0a5063c5ffaba3cc3f5b62f3d6 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Thu, 19 Nov 2026 09:54:44 +0800 Subject: [PATCH 2/8] [spark] Format narrow MERGE command and regression suite --- .../MergeIntoPaimonDataEvolutionTable.scala | 51 +++++++++++-------- .../MergeIntoPaimonDataEvolutionTable.scala | 51 +++++++++++-------- .../DataEvolutionMergeNarrowSourceTest.scala | 33 ++++++------ 3 files changed, 76 insertions(+), 59 deletions(-) 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 6f28ba27b6e6..0dcafdfd8022 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 @@ -313,8 +313,9 @@ case class MergeIntoPaimonDataEvolutionTable( !table.coreOptions().dataEvolutionMergeIntoSourcePersist() && canReuseMergeJoin(sparkSession) && narrowSharedSourceKey.isDefined && sourceTable.output.exists( - attr => allSharedDependencies.contains(attr.exprId) && - !updateSharedDependencies.contains(attr.exprId)) + attr => + allSharedDependencies.contains(attr.exprId) && + !updateSharedDependencies.contains(attr.exprId)) ) { pinNarrowSource(sourceTable, originalTargetRelation) } else { @@ -1276,8 +1277,8 @@ case class MergeIntoPaimonDataEvolutionTable( case Some(key) => val cachedKey = plan.output.find(_.exprId == key.exprId).get val membershipKey = Alias(cachedKey, "__paimon_unmatched_source_key")() - val unmatched = Project( - Seq(membershipKey), Filter(IsNull(shared.targetMarker(plan)), plan)) + val unmatched = + Project(Seq(membershipKey), Filter(IsNull(shared.targetMarker(plan)), plan)) // Membership must retain NULL keys and every duplicate row in the fixed source. Join( sourceReadPlan, @@ -1500,7 +1501,9 @@ object MergeIntoPaimonDataEvolutionTable { plan: LogicalPlan, targetRelation: DataSourceV2Relation): Option[LogicalPlan] = { def identity(table: FileStoreTable): (String, String) = - (table.location().toString, BranchManager.normalizeBranch(CoreOptions.branch(table.options()))) + ( + table.location().toString, + BranchManager.normalizeBranch(CoreOptions.branch(table.options()))) val target = targetRelation.table match { case sparkTable: SparkTable => sparkTable.getTable.asInstanceOf[FileStoreTable] @@ -1526,29 +1529,33 @@ object MergeIntoPaimonDataEvolutionTable { CoreOptions.StartupMode.LATEST, CoreOptions.StartupMode.FROM_TIMESTAMP, CoreOptions.StartupMode.FROM_SNAPSHOT, - CoreOptions.StartupMode.FROM_SNAPSHOT_FULL) + CoreOptions.StartupMode.FROM_SNAPSHOT_FULL + ) .contains(source.coreOptions().startupMode()) => // Resolving scan.version can mutate options; never resolve it on the input table. val copied = source.copy(new JHashMap[String, String]()) Option(TimeTravelUtil.tryTravelOrLatest(copied)) .filter(snapshot => copied.snapshotManager().snapshotExists(snapshot.id())) .flatMap { - snapshot => - val options = new JHashMap[String, String]() - timeTravelOptionKeys.foreach(options.put(_, null)) - options.put(CoreOptions.SCAN_SNAPSHOT_ID.key(), snapshot.id().toString) - options.put(CoreOptions.SCAN_MODE.key(), CoreOptions.StartupMode.FROM_SNAPSHOT.toString) - val pinned = copied.copy(options) - // A schema-only change is newer than the data snapshot's read schema. - if (pinned.schema().id() != source.schema().id()) { - None - } else { - Some(SparkShimLoader.shim.copyDataSourceV2Relation( - relation, - SparkTable.of(pinned), - relation.output)) - } - } + snapshot => + val options = new JHashMap[String, String]() + timeTravelOptionKeys.foreach(options.put(_, null)) + options.put(CoreOptions.SCAN_SNAPSHOT_ID.key(), snapshot.id().toString) + options.put( + CoreOptions.SCAN_MODE.key(), + CoreOptions.StartupMode.FROM_SNAPSHOT.toString) + val pinned = copied.copy(options) + // A schema-only change is newer than the data snapshot's read schema. + if (pinned.schema().id() != source.schema().id()) { + None + } else { + Some( + SparkShimLoader.shim.copyDataSourceV2Relation( + relation, + SparkTable.of(pinned), + relation.output)) + } + } case _ => None } case _ => None 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 6f28ba27b6e6..0dcafdfd8022 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 @@ -313,8 +313,9 @@ case class MergeIntoPaimonDataEvolutionTable( !table.coreOptions().dataEvolutionMergeIntoSourcePersist() && canReuseMergeJoin(sparkSession) && narrowSharedSourceKey.isDefined && sourceTable.output.exists( - attr => allSharedDependencies.contains(attr.exprId) && - !updateSharedDependencies.contains(attr.exprId)) + attr => + allSharedDependencies.contains(attr.exprId) && + !updateSharedDependencies.contains(attr.exprId)) ) { pinNarrowSource(sourceTable, originalTargetRelation) } else { @@ -1276,8 +1277,8 @@ case class MergeIntoPaimonDataEvolutionTable( case Some(key) => val cachedKey = plan.output.find(_.exprId == key.exprId).get val membershipKey = Alias(cachedKey, "__paimon_unmatched_source_key")() - val unmatched = Project( - Seq(membershipKey), Filter(IsNull(shared.targetMarker(plan)), plan)) + val unmatched = + Project(Seq(membershipKey), Filter(IsNull(shared.targetMarker(plan)), plan)) // Membership must retain NULL keys and every duplicate row in the fixed source. Join( sourceReadPlan, @@ -1500,7 +1501,9 @@ object MergeIntoPaimonDataEvolutionTable { plan: LogicalPlan, targetRelation: DataSourceV2Relation): Option[LogicalPlan] = { def identity(table: FileStoreTable): (String, String) = - (table.location().toString, BranchManager.normalizeBranch(CoreOptions.branch(table.options()))) + ( + table.location().toString, + BranchManager.normalizeBranch(CoreOptions.branch(table.options()))) val target = targetRelation.table match { case sparkTable: SparkTable => sparkTable.getTable.asInstanceOf[FileStoreTable] @@ -1526,29 +1529,33 @@ object MergeIntoPaimonDataEvolutionTable { CoreOptions.StartupMode.LATEST, CoreOptions.StartupMode.FROM_TIMESTAMP, CoreOptions.StartupMode.FROM_SNAPSHOT, - CoreOptions.StartupMode.FROM_SNAPSHOT_FULL) + CoreOptions.StartupMode.FROM_SNAPSHOT_FULL + ) .contains(source.coreOptions().startupMode()) => // Resolving scan.version can mutate options; never resolve it on the input table. val copied = source.copy(new JHashMap[String, String]()) Option(TimeTravelUtil.tryTravelOrLatest(copied)) .filter(snapshot => copied.snapshotManager().snapshotExists(snapshot.id())) .flatMap { - snapshot => - val options = new JHashMap[String, String]() - timeTravelOptionKeys.foreach(options.put(_, null)) - options.put(CoreOptions.SCAN_SNAPSHOT_ID.key(), snapshot.id().toString) - options.put(CoreOptions.SCAN_MODE.key(), CoreOptions.StartupMode.FROM_SNAPSHOT.toString) - val pinned = copied.copy(options) - // A schema-only change is newer than the data snapshot's read schema. - if (pinned.schema().id() != source.schema().id()) { - None - } else { - Some(SparkShimLoader.shim.copyDataSourceV2Relation( - relation, - SparkTable.of(pinned), - relation.output)) - } - } + snapshot => + val options = new JHashMap[String, String]() + timeTravelOptionKeys.foreach(options.put(_, null)) + options.put(CoreOptions.SCAN_SNAPSHOT_ID.key(), snapshot.id().toString) + options.put( + CoreOptions.SCAN_MODE.key(), + CoreOptions.StartupMode.FROM_SNAPSHOT.toString) + val pinned = copied.copy(options) + // A schema-only change is newer than the data snapshot's read schema. + if (pinned.schema().id() != source.schema().id()) { + None + } else { + Some( + SparkShimLoader.shim.copyDataSourceV2Relation( + relation, + SparkTable.of(pinned), + relation.output)) + } + } case _ => None } case _ => None diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala index 3e6c4d6aedd0..0c90198a2861 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala @@ -23,8 +23,8 @@ import org.apache.paimon.spark.schema.PaimonMetadataColumn import org.apache.paimon.table.FileStoreTable import org.apache.spark.scheduler.{SparkListener, SparkListenerBlockUpdated} -import org.apache.spark.sql.Row import org.apache.spark.sql.PaimonUtils.createDataset +import org.apache.spark.sql.Row import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan import org.apache.spark.sql.execution.QueryExecution import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper @@ -39,9 +39,7 @@ import java.util.concurrent.atomic.AtomicBoolean import scala.collection.JavaConverters._ -class DataEvolutionMergeNarrowSourceTest - extends PaimonSparkTestBase - with AdaptiveSparkPlanHelper { +class DataEvolutionMergeNarrowSourceTest extends PaimonSparkTestBase with AdaptiveSparkPlanHelper { private def relation(plan: LogicalPlan): DataSourceV2Relation = plan.collectFirst { case r: DataSourceV2Relation => r }.get @@ -123,8 +121,7 @@ class DataEvolutionMergeNarrowSourceTest assert(metadataValue != null) if (dataEvolution) assert(metadataValue == 0L) val plan = sql( - s"SELECT s.id AS source_id,s.value,s.insert_payload,s.$metadataColumn FROM source s") - .queryExecution.analyzed + s"SELECT s.id AS source_id,s.value,s.insert_payload,s.$metadataColumn FROM source s").queryExecution.analyzed val original = fileTable(plan) val originalOptions = original.options().asScala.toMap val snapshot = original.snapshotManager().latestSnapshotId() @@ -180,8 +177,8 @@ class DataEvolutionMergeNarrowSourceTest sql("INSERT INTO source VALUES (1,10,'historical')") val historicalSnapshot = loadTable("source").snapshotManager().latestSnapshotId() sql("UPDATE source SET value=20 WHERE id=1") - val plan = sql(s"SELECT * FROM source VERSION AS OF $historicalSnapshot") - .queryExecution.analyzed + val plan = + sql(s"SELECT * FROM source VERSION AS OF $historicalSnapshot").queryExecution.analyzed val originalOptions = fileTable(plan).options().asScala.toMap val pinned = MergeIntoPaimonDataEvolutionTable .pinNarrowSource(plan, createRelationV2("target")) @@ -215,7 +212,8 @@ class DataEvolutionMergeNarrowSourceTest MergeIntoPaimonDataEvolutionTable .pinNarrowSource(plan, createRelationV2("target")) .isEmpty, - "Pinning must not replace the current source schema with the data snapshot schema") + "Pinning must not replace the current source schema with the data snapshot schema" + ) val payload = if (rename) "s.payload2" else "COALESCE(s.payload2,s.insert_payload)" sql(s"""MERGE INTO target t USING source s ON t.id=s.id |WHEN MATCHED THEN UPDATE SET value=s.value @@ -244,7 +242,8 @@ class DataEvolutionMergeNarrowSourceTest MergeIntoPaimonDataEvolutionTable .pinNarrowSource(plan, createRelationV2("target")) .isEmpty, - "A retained tag must keep its tag reader when the numbered snapshot file has expired") + "A retained tag must keep its tag reader when the numbered snapshot file has expired" + ) checkAnswer(createDataset(spark, plan), Seq(Row(1, 100, "tagged"))) assert(fileTable(plan).options().asScala.toMap == originalOptions) } @@ -343,7 +342,8 @@ class DataEvolutionMergeNarrowSourceTest 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")))) + (if (nullSafe) Nil else Seq(Row(null, 900, "newnull"))) + ) assert( sql("SELECT payload,_ROW_ID FROM target WHERE payload IN ('a','b','c','d')") .collect() @@ -430,14 +430,17 @@ class DataEvolutionMergeNarrowSourceTest assert( causes.exists( cause => Option(cause.getMessage).exists(_.contains("Row ID should be incremental."))), - s"Expected duplicate RowID rejection, got ${causes.mkString("; ")}") + 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 matches must fail on RowID validation rather than cache attribute binding") + message => + message.contains("MISSING_ATTRIBUTES") || + message.contains("Resolved attribute(s)"))), + "Duplicate matches must fail on RowID validation rather than cache attribute binding" + ) assert(cachedBlockSeen.await(10, TimeUnit.SECONDS), "Expected a materialized disk cache") checkAnswer(sql("SELECT *,_ROW_ID FROM target"), rows) assert(loadTable("target").snapshotManager().latestSnapshotId() == snapshot) From 4964431e3d56e161dd29cf87fe3920dd6881a6c2 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Fri, 20 Nov 2026 01:35:43 +0800 Subject: [PATCH 3/8] [spark] Preserve composite branch sources when narrowing MERGE --- docs/docs/multimodal-table/data-evolution.mdx | 5 ++- .../MergeIntoPaimonDataEvolutionTable.scala | 4 +- .../MergeIntoPaimonDataEvolutionTable.scala | 4 +- .../DataEvolutionMergeNarrowSourceTest.scala | 40 ++++++++++++++++++- 4 files changed, 48 insertions(+), 5 deletions(-) diff --git a/docs/docs/multimodal-table/data-evolution.mdx b/docs/docs/multimodal-table/data-evolution.mdx index 3c0e988f835b..8f710b57bbe0 100644 --- a/docs/docs/multimodal-table/data-evolution.mdx +++ b/docs/docs/multimodal-table/data-evolution.mdx @@ -250,8 +250,9 @@ with another source scan. Source duplicates and NULL keys retain the original MERGE semantics. Unsupported statements, sources without a snapshot, and statements using `data-evolution.merge-into.source-persist` keep the original execution path. Schema-only changes newer than the data snapshot and retained -tags without a numbered snapshot file also use the original path. This can -reduce shuffle and disk cache size for wide sources, +tags without a numbered snapshot file also use the original path. +Composite fallback/primary-branch sources also keep the original execution path. +This can reduce shuffle and disk cache size for wide sources, but the extra scan and membership join can increase elapsed time. Compare complete SQL execution time for the expected UPDATE/INSERT mix before enabling it. This option does not perform positional source reads. 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 0dcafdfd8022..eee5d7220b8e 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 @@ -35,7 +35,7 @@ import org.apache.paimon.spark.catalyst.analysis.PaimonUpdateTable.toColumn import org.apache.paimon.spark.catalyst.analysis.expressions.ExpressionHelper import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand import org.apache.paimon.spark.util.ScanPlanHelper.createNewScanPlan -import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.{FallbackReadFileStoreTable, FileStoreTable} import org.apache.paimon.table.sink.{CommitMessage, CommitMessageImpl} import org.apache.paimon.table.source.DataSplit import org.apache.paimon.table.source.snapshot.SnapshotReader @@ -1522,6 +1522,8 @@ object MergeIntoPaimonDataEvolutionTable { relation.table match { case sparkTable: SparkTable => sparkTable.getTable match { + // Pinning one branch would time-travel the other branch as well. + case _: FallbackReadFileStoreTable => None case source: FileStoreTable if source.primaryKeys().isEmpty && identity(source) != identity(target) && Set( 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 0dcafdfd8022..eee5d7220b8e 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 @@ -35,7 +35,7 @@ import org.apache.paimon.spark.catalyst.analysis.PaimonUpdateTable.toColumn import org.apache.paimon.spark.catalyst.analysis.expressions.ExpressionHelper import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand import org.apache.paimon.spark.util.ScanPlanHelper.createNewScanPlan -import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.{FallbackReadFileStoreTable, FileStoreTable} import org.apache.paimon.table.sink.{CommitMessage, CommitMessageImpl} import org.apache.paimon.table.source.DataSplit import org.apache.paimon.table.source.snapshot.SnapshotReader @@ -1522,6 +1522,8 @@ object MergeIntoPaimonDataEvolutionTable { relation.table match { case sparkTable: SparkTable => sparkTable.getTable match { + // Pinning one branch would time-travel the other branch as well. + case _: FallbackReadFileStoreTable => None case source: FileStoreTable if source.primaryKeys().isEmpty && identity(source) != identity(target) && Set( diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala index 0c90198a2861..bc59b6aad7b0 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala @@ -20,7 +20,7 @@ package org.apache.paimon.spark.commands import org.apache.paimon.spark.{PaimonSparkTestBase, SparkTable} import org.apache.paimon.spark.schema.PaimonMetadataColumn -import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.{FallbackReadFileStoreTable, FileStoreTable} import org.apache.spark.scheduler.{SparkListener, SparkListenerBlockUpdated} import org.apache.spark.sql.PaimonUtils.createDataset @@ -291,6 +291,44 @@ class DataEvolutionMergeNarrowSourceTest extends PaimonSparkTestBase with Adapti } } + test("narrow source preserves newer fallback branch partitions with the flag on or off") { + Seq(false, true).foreach { + narrow => + withTables() { + sql("DROP TABLE source") + sql("""CREATE TABLE source (id INT, value INT, insert_payload STRING, p INT) + |PARTITIONED BY (p) TBLPROPERTIES ('bucket'='-1')""".stripMargin) + sql("INSERT INTO source VALUES (1,100,'unused',0)") + sql("CALL sys.create_tag(table => 'test.source', tag => 'base', snapshot => 1)") + sql("CALL sys.create_branch(table => 'test.source', branch => 'other', tag => 'base')") + sql("ALTER TABLE source SET TBLPROPERTIES ('scan.fallback-branch'='other')") + // Keep the main data snapshot's schema current so schema mismatch cannot mask pinning. + sql("INSERT INTO source VALUES (2,200,'main',0)") + sql("INSERT INTO `source$branch_other` VALUES (4,400,'fallback',1)") + val source = loadTable("source").asInstanceOf[FallbackReadFileStoreTable] + val mainSnapshot = source.latestSnapshot().get() + assert(mainSnapshot.schemaId() == source.schema().id()) + assert(source.other().latestSnapshot().get().timeMillis() > mainSnapshot.timeMillis()) + checkAnswer( + sql("SELECT id,value,insert_payload FROM source"), + Seq(Row(1, 100, "unused"), Row(2, 200, "main"), Row(4, 400, "fallback"))) + sql( + s"""ALTER TABLE target SET TBLPROPERTIES ( + |'data-evolution.merge-into.join-reuse.narrow-source.enabled'='$narrow')""".stripMargin) + sql("INSERT INTO target VALUES (1,10,'old')") + withNarrowPlan(expectNarrow = false) { + 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,s.insert_payload)""".stripMargin) + checkAnswer( + sql("SELECT * FROM target"), + Seq(Row(1, 100, "old"), Row(2, 200, "main"), Row(4, 400, "fallback"))) + } + } + } + } + test("pin narrow source returns None before the first source snapshot") { withTables() { val plan = sql("SELECT * FROM source").queryExecution.analyzed From 66e405d2b681708d657f9514e9c1d67e905d9fe6 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Sat, 21 Nov 2026 22:20:58 +0800 Subject: [PATCH 4/8] [docs] Generate reference for narrow MERGE source option --- docs/generated/core_configuration.html | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/generated/core_configuration.html b/docs/generated/core_configuration.html index 4bbc4e082cc2..3be5b869920a 100644 --- a/docs/generated/core_configuration.html +++ b/docs/generated/core_configuration.html @@ -410,12 +410,6 @@ MemorySize When incremental size is bigger than this threshold, force a full compaction. - -
continuous-compaction.initial-scan-mode
- earliest -

Enum

- Initial snapshot mode for dedicated streaming compaction. When set to 'earliest' (the default), compaction starts from the earliest available snapshot if no COMPACT snapshot exists; when a COMPACT snapshot exists, compaction always resumes from the snapshot after it. When set to 'latest', the latest snapshot is read in ALL mode as the initial baseline and subsequent scans start from the next snapshot. The 'latest' mode skips historical snapshot changes and should only be used when historical changelog replay is not required.

Possible values: -
compaction.max-size-amplification-percent
200 @@ -506,6 +500,12 @@

Enum

Specify the consumer consistency mode for table.

Possible values: + +
continuous-compaction.initial-scan-mode
+ earliest +

Enum

+ Initial snapshot mode for dedicated streaming compaction. When set to 'earliest' (the default), compaction starts from the earliest available snapshot if no COMPACT snapshot exists; when a COMPACT snapshot exists, compaction always resumes from the snapshot after it. When set to 'latest', the latest snapshot is read in ALL mode as the initial baseline and subsequent scans start from the next snapshot. The 'latest' mode skips historical snapshot changes and should only be used when historical changelog replay is not required.

Possible values: +
continuous.discovery-interval
10 s @@ -578,6 +578,12 @@ Boolean 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. + +
data-evolution.merge-into.join-reuse.narrow-source.enabled
+ false + Boolean + Whether Spark MERGE join reuse excludes INSERT-only source columns from the shared result and reads them again from a pinned source snapshot. Requires join reuse, a simple Paimon append source and an INT or BIGINT equality key. It reduces shared shuffle and cache size at the cost of another source scan. Unsupported sources use the original shared result. +
data-evolution.merge-into.source-persist
false From e7ec26cb053c2e7f0eb1d4dca496b58443f16b99 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Sat, 21 Nov 2026 22:46:06 +0800 Subject: [PATCH 5/8] [ci] Retry a failed JDK setup once --- .github/workflows/ci-java.yml | 8 ++++++++ .github/workflows/ci-licensing.yml | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/.github/workflows/ci-java.yml b/.github/workflows/ci-java.yml index 1283bbe19f5d..9e3546abd1f1 100644 --- a/.github/workflows/ci-java.yml +++ b/.github/workflows/ci-java.yml @@ -46,6 +46,14 @@ jobs: with: persist-credentials: false - name: Set up JDK ${{ matrix.java }} + id: setup_java + continue-on-error: true + uses: actions/setup-java@v5 + with: + java-version: ${{ matrix.java }} + distribution: temurin + - name: Retry JDK setup after a download failure + if: ${{ steps.setup_java.outcome == 'failure' }} uses: actions/setup-java@v5 with: java-version: ${{ matrix.java }} diff --git a/.github/workflows/ci-licensing.yml b/.github/workflows/ci-licensing.yml index 1694621b69d0..65341059f74b 100644 --- a/.github/workflows/ci-licensing.yml +++ b/.github/workflows/ci-licensing.yml @@ -38,6 +38,14 @@ jobs: - uses: actions/checkout@v6 - name: Set JDK + id: setup_java + continue-on-error: true + uses: actions/setup-java@v5 + with: + java-version: 8 + distribution: 'temurin' + - name: Retry JDK setup after a download failure + if: ${{ steps.setup_java.outcome == 'failure' }} uses: actions/setup-java@v5 with: java-version: 8 From 3dc98d1fbbfc229c645d1c372d510bf537060a32 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Mon, 23 Nov 2026 22:04:56 +0800 Subject: [PATCH 6/8] Revert "[ci] Retry a failed JDK setup once" This reverts commit e7ec26cb053c2e7f0eb1d4dca496b58443f16b99. --- .github/workflows/ci-java.yml | 8 -------- .github/workflows/ci-licensing.yml | 8 -------- 2 files changed, 16 deletions(-) diff --git a/.github/workflows/ci-java.yml b/.github/workflows/ci-java.yml index 9e3546abd1f1..1283bbe19f5d 100644 --- a/.github/workflows/ci-java.yml +++ b/.github/workflows/ci-java.yml @@ -46,14 +46,6 @@ jobs: with: persist-credentials: false - name: Set up JDK ${{ matrix.java }} - id: setup_java - continue-on-error: true - uses: actions/setup-java@v5 - with: - java-version: ${{ matrix.java }} - distribution: temurin - - name: Retry JDK setup after a download failure - if: ${{ steps.setup_java.outcome == 'failure' }} uses: actions/setup-java@v5 with: java-version: ${{ matrix.java }} diff --git a/.github/workflows/ci-licensing.yml b/.github/workflows/ci-licensing.yml index 65341059f74b..1694621b69d0 100644 --- a/.github/workflows/ci-licensing.yml +++ b/.github/workflows/ci-licensing.yml @@ -38,14 +38,6 @@ jobs: - uses: actions/checkout@v6 - name: Set JDK - id: setup_java - continue-on-error: true - uses: actions/setup-java@v5 - with: - java-version: 8 - distribution: 'temurin' - - name: Retry JDK setup after a download failure - if: ${{ steps.setup_java.outcome == 'failure' }} uses: actions/setup-java@v5 with: java-version: 8 From afbe64ba663249a0ae8cf6d971a29ffc9c919130 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Mon, 23 Nov 2026 22:09:23 +0800 Subject: [PATCH 7/8] [spark] Keep narrow MERGE source snapshot contents fixed --- .../MergeIntoPaimonDataEvolutionTable.scala | 11 ++++- .../MergeIntoPaimonDataEvolutionTable.scala | 11 ++++- .../DataEvolutionMergeNarrowSourceTest.scala | 41 +++++++++++++++++++ 3 files changed, 59 insertions(+), 4 deletions(-) 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 eee5d7220b8e..fc5626286b81 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 @@ -24,11 +24,13 @@ import org.apache.paimon.Snapshot import org.apache.paimon.data.BinaryRow import org.apache.paimon.deletionvectors.DeletionVector import org.apache.paimon.format.blob.BlobFileFormat.isBlobFile +import org.apache.paimon.fs.Path import org.apache.paimon.index.GlobalIndexMeta import org.apache.paimon.io.{CompactIncrement, DataFileMeta, DataIncrement} import org.apache.paimon.manifest.IndexManifestEntry import org.apache.paimon.options.Options import org.apache.paimon.predicate.{Predicate, PredicateBuilder} +import org.apache.paimon.shade.caffeine2.com.github.benmanes.caffeine.cache.Caffeine import org.apache.paimon.spark.SparkTable import org.apache.paimon.spark.catalyst.analysis.PaimonRelation import org.apache.paimon.spark.catalyst.analysis.PaimonUpdateTable.toColumn @@ -1546,11 +1548,16 @@ object MergeIntoPaimonDataEvolutionTable { options.put( CoreOptions.SCAN_MODE.key(), CoreOptions.StartupMode.FROM_SNAPSHOT.toString) - val pinned = copied.copy(options) // A schema-only change is newer than the data snapshot's read schema. - if (pinned.schema().id() != source.schema().id()) { + if (snapshot.schemaId() != source.schema().id()) { None } else { + // Rollback can reuse a snapshot ID. Keep the resolved snapshot private to + // this MERGE so both scans plan from the same manifest lists. + val pinned = copied.copyWithoutTimeTravel(options) + val cache = Caffeine.newBuilder().build[Path, Snapshot]() + cache.put(pinned.snapshotManager().snapshotPath(snapshot.id()), snapshot) + pinned.setSnapshotCache(cache) Some( SparkShimLoader.shim.copyDataSourceV2Relation( relation, 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 eee5d7220b8e..fc5626286b81 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 @@ -24,11 +24,13 @@ import org.apache.paimon.Snapshot import org.apache.paimon.data.BinaryRow import org.apache.paimon.deletionvectors.DeletionVector import org.apache.paimon.format.blob.BlobFileFormat.isBlobFile +import org.apache.paimon.fs.Path import org.apache.paimon.index.GlobalIndexMeta import org.apache.paimon.io.{CompactIncrement, DataFileMeta, DataIncrement} import org.apache.paimon.manifest.IndexManifestEntry import org.apache.paimon.options.Options import org.apache.paimon.predicate.{Predicate, PredicateBuilder} +import org.apache.paimon.shade.caffeine2.com.github.benmanes.caffeine.cache.Caffeine import org.apache.paimon.spark.SparkTable import org.apache.paimon.spark.catalyst.analysis.PaimonRelation import org.apache.paimon.spark.catalyst.analysis.PaimonUpdateTable.toColumn @@ -1546,11 +1548,16 @@ object MergeIntoPaimonDataEvolutionTable { options.put( CoreOptions.SCAN_MODE.key(), CoreOptions.StartupMode.FROM_SNAPSHOT.toString) - val pinned = copied.copy(options) // A schema-only change is newer than the data snapshot's read schema. - if (pinned.schema().id() != source.schema().id()) { + if (snapshot.schemaId() != source.schema().id()) { None } else { + // Rollback can reuse a snapshot ID. Keep the resolved snapshot private to + // this MERGE so both scans plan from the same manifest lists. + val pinned = copied.copyWithoutTimeTravel(options) + val cache = Caffeine.newBuilder().build[Path, Snapshot]() + cache.put(pinned.snapshotManager().snapshotPath(snapshot.id()), snapshot) + pinned.setSnapshotCache(cache) Some( SparkShimLoader.shim.copyDataSourceV2Relation( relation, diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala index bc59b6aad7b0..dd33a8e7824b 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala @@ -34,10 +34,12 @@ import org.apache.spark.sql.paimon.Utils import org.apache.spark.sql.util.QueryExecutionListener import org.apache.spark.storage.RDDBlockId +import java.io.FileNotFoundException import java.util.concurrent.{CountDownLatch, TimeUnit} import java.util.concurrent.atomic.AtomicBoolean import scala.collection.JavaConverters._ +import scala.util.{Failure, Success, Try} class DataEvolutionMergeNarrowSourceTest extends PaimonSparkTestBase with AdaptiveSparkPlanHelper { @@ -172,6 +174,45 @@ class DataEvolutionMergeNarrowSourceTest extends PaimonSparkTestBase with Adapti } } + test("pin narrow source preserves snapshot contents when rollback reuses the ID") { + withTables() { + sql("INSERT INTO source VALUES (1,100,'matched')") + val previous = loadTable("source").snapshotManager().latestSnapshotId() + sql("INSERT INTO source VALUES (4,400,'old')") + val original = loadTable("source").snapshotManager().latestSnapshot() + val plan = sql("SELECT * FROM source").queryExecution.analyzed + val pinned = MergeIntoPaimonDataEvolutionTable + .pinNarrowSource(plan, createRelationV2("target")) + .get + checkAnswer(createDataset(spark, pinned), Seq(Row(1, 100, "matched"), Row(4, 400, "old"))) + + loadTable("source").rollbackTo(previous) + spark.catalog.refreshTable("source") + sql("INSERT INTO source VALUES (4,499,'replacement')") + val replacement = loadTable("source").snapshotManager().latestSnapshot() + assert(replacement.id() == original.id()) + assert(replacement.schemaId() == original.schemaId()) + assert(replacement.deltaManifestList() != original.deltaManifestList()) + checkAnswer( + sql("SELECT * FROM source"), + Seq(Row(1, 100, "matched"), Row(4, 499, "replacement"))) + assert(fileTable(pinned).snapshotManager().snapshot(original.id()) == original) + // The old files may have been deleted by rollback, but the reread must never + // substitute the replacement contents, even though the IDs and schemas match. + Try(createDataset(spark, pinned).collect().toSet) match { + case Success(rows) => assert(rows == Set(Row(1, 100, "matched"), Row(4, 400, "old"))) + case Failure(error) => + assert( + Iterator + .iterate[Throwable](error)(_.getCause) + .takeWhile(_ != null) + .exists(_.isInstanceOf[FileNotFoundException]), + s"Expected old snapshot files to be unavailable, got $error" + ) + } + } + } + test("pin narrow source retains explicit time travel instead of choosing latest") { withTables(dataEvolutionSource = true) { sql("INSERT INTO source VALUES (1,10,'historical')") From d201e73cc53494f5fcb3f91c1cca1388afbeb663 Mon Sep 17 00:00:00 2001 From: yangjiabin <706948683@qq.com> Date: Mon, 23 Nov 2026 22:18:47 +0800 Subject: [PATCH 8/8] [spark] Avoid narrow MERGE rereads that can skip files --- .../MergeIntoPaimonDataEvolutionTable.scala | 2 ++ .../MergeIntoPaimonDataEvolutionTable.scala | 2 ++ .../DataEvolutionMergeNarrowSourceTest.scala | 14 ++++++++++++++ 3 files changed, 18 insertions(+) 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 fc5626286b81..944b5f0616b7 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 @@ -1528,6 +1528,8 @@ object MergeIntoPaimonDataEvolutionTable { case _: FallbackReadFileStoreTable => None case source: FileStoreTable if source.primaryKeys().isEmpty && identity(source) != identity(target) && + !source.coreOptions().scanIgnoreLostFile() && + !source.coreOptions().scanIgnoreCorruptFile() && Set( CoreOptions.StartupMode.LATEST_FULL, CoreOptions.StartupMode.LATEST, 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 fc5626286b81..944b5f0616b7 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 @@ -1528,6 +1528,8 @@ object MergeIntoPaimonDataEvolutionTable { case _: FallbackReadFileStoreTable => None case source: FileStoreTable if source.primaryKeys().isEmpty && identity(source) != identity(target) && + !source.coreOptions().scanIgnoreLostFile() && + !source.coreOptions().scanIgnoreCorruptFile() && Set( CoreOptions.StartupMode.LATEST_FULL, CoreOptions.StartupMode.LATEST, diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala index dd33a8e7824b..0f21fd6bfdb5 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/DataEvolutionMergeNarrowSourceTest.scala @@ -231,6 +231,20 @@ class DataEvolutionMergeNarrowSourceTest extends PaimonSparkTestBase with Adapti } } + test("pin narrow source falls back when reads can skip source files") { + for (option <- Seq("scan.ignore-lost-files", "scan.ignore-corrupt-files")) { + withTables() { + sql(s"ALTER TABLE source SET TBLPROPERTIES ('$option'='true')") + sql("INSERT INTO source VALUES (1,10,'source')") + val plan = sql("SELECT * FROM source").queryExecution.analyzed + assert( + MergeIntoPaimonDataEvolutionTable + .pinNarrowSource(plan, createRelationV2("target")) + .isEmpty) + } + } + } + for (rename <- Seq(true, false)) { test(s"pin narrow source falls back after a schema-only change: rename=$rename") { withTables() {