szehon-ho commented on code in PR #60559: URL: https://github.com/apache/spark/pull/60559#discussion_r4629314012
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/OptimizeInsertOnlyMerge.scala: ########## @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.optimizer + +import org.apache.spark.sql.catalyst.expressions.{Alias, AliasHelper, ConditionalExpression, Expression, Literal} +import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral} +import org.apache.spark.sql.catalyst.plans.LeftAnti +import org.apache.spark.sql.catalyst.plans.logical.{Filter, InsertOnlyMerge, Join, LogicalPlan, MergeRows, Project} +import org.apache.spark.sql.catalyst.plans.logical.MergeRows.{Insert, Keep} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND + +/** + * Replaces a single insert instruction with a projection and source filter after constant folding. + */ +object OptimizeInsertOnlyMerge extends Rule[LogicalPlan] with AliasHelper { + override def apply(plan: LogicalPlan): LogicalPlan = plan.transformUpWithPruning( + _.containsPattern(COMMAND), ruleId) { + case merge @ InsertOnlyMerge(_, rows @ MergeRows(TrueLiteral, FalseLiteral, Nil, + Seq(instruction @ Keep(Insert, condition, values)), Nil, false, _, child), _, _) + if !hasUnfoldedConstants(instruction) => + val filtered = condition match { + case TrueLiteral => child + case _ => filterSource(child, condition).getOrElse(Filter(condition, child)) + } + val projectList = values.zip(rows.output).map { case (value, attr) => + Alias(value, attr.name)(exprId = attr.exprId, qualifier = attr.qualifier, + explicitMetadata = Some(attr.metadata)) + } + merge.copy(query = Project(projectList, filtered)) + } + + private def hasUnfoldedConstants(expr: Expression): Boolean = expr match { + case _: Literal => false + // These failures stay protected by the expression after MergeRows is removed. + case c: ConditionalExpression if !c.foldable => false Review Comment: The early folding check now also inspects the action condition for FAILED_TO_EVALUATE tags and retains MergeRows when it finds one. Added regressions for failures in both the IF input and an IF branch, covering matched rows that skip the condition and unmatched rows that reach it. --- <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub MCP. --> _This comment was generated with [GitHub MCP](http://go/mcps)._ ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/OptimizeInsertOnlyMerge.scala: ########## @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.optimizer + +import org.apache.spark.sql.catalyst.expressions.{Alias, AliasHelper, ConditionalExpression, Expression, Literal} +import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral} +import org.apache.spark.sql.catalyst.plans.LeftAnti +import org.apache.spark.sql.catalyst.plans.logical.{Filter, InsertOnlyMerge, Join, LogicalPlan, MergeRows, Project} +import org.apache.spark.sql.catalyst.plans.logical.MergeRows.{Insert, Keep} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND + +/** + * Replaces a single insert instruction with a projection and source filter after constant folding. + */ +object OptimizeInsertOnlyMerge extends Rule[LogicalPlan] with AliasHelper { + override def apply(plan: LogicalPlan): LogicalPlan = plan.transformUpWithPruning( + _.containsPattern(COMMAND), ruleId) { + case merge @ InsertOnlyMerge(_, rows @ MergeRows(TrueLiteral, FalseLiteral, Nil, + Seq(instruction @ Keep(Insert, condition, values)), Nil, false, _, child), _, _) + if !hasUnfoldedConstants(instruction) => Review Comment: Kept the fix scoped to constants visible during analysis and documented this limitation in the PR description and helper's method comment. Constants introduced later by source-alias inlining or arithmetic reassociation can still fail during optimization, as on the base branch. --- <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub MCP. --> _This comment was generated with [GitHub MCP](http://go/mcps)._ ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala: ########## @@ -92,6 +92,9 @@ object ConstantFolding extends Rule[LogicalPlan] { case c: ConditionalExpression if !c.foldable => c.mapChildren(constantFolding(_, isConditionalBranch = true)) + case i: MergeRows.Instruction => Review Comment: Merged master's SPARK-61920 fix (40e16cf737f) and removed our duplicate MergeRows.Instruction case in RewriteWithExpression. Retained the constant-folding regression with NULLIF/BETWEEN alongside the upstream tests for row-dependent failures. --- <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub MCP. --> _This comment was generated with [GitHub MCP](http://go/mcps)._ ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala: ########## @@ -92,9 +56,7 @@ object RewriteMergeIntoTable extends RewriteRowLevelCommand with PredicateHelper checkNoGeneratedColumns(r, MERGE) validateMergeIntoConditions(m) Review Comment: Added action-condition type validation in checkMergeIntoCondition, using DATATYPE_MISMATCH.FILTER_NOT_BOOLEAN. NULL conditions remain accepted, and SEARCH/ON keeps its existing validation path. Added regressions for an integer condition with and without a failing constant. --- <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub MCP. --> _This comment was generated with [GitHub MCP](http://go/mcps)._ ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/OptimizeInsertOnlyMerge.scala: ########## @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.optimizer + +import org.apache.spark.sql.catalyst.expressions.{Alias, AliasHelper, ConditionalExpression, Expression, Literal} +import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral} +import org.apache.spark.sql.catalyst.plans.LeftAnti +import org.apache.spark.sql.catalyst.plans.logical.{Filter, InsertOnlyMerge, Join, LogicalPlan, MergeRows, Project} +import org.apache.spark.sql.catalyst.plans.logical.MergeRows.{Insert, Keep} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND + +/** + * Replaces a single insert instruction with a projection and source filter after constant folding. + */ +object OptimizeInsertOnlyMerge extends Rule[LogicalPlan] with AliasHelper { + override def apply(plan: LogicalPlan): LogicalPlan = plan.transformUpWithPruning( + _.containsPattern(COMMAND), ruleId) { + case merge @ InsertOnlyMerge(_, rows @ MergeRows(TrueLiteral, FalseLiteral, Nil, + Seq(instruction @ Keep(Insert, condition, values)), Nil, false, _, child), _, _) + if !hasUnfoldedConstants(instruction) => + val filtered = condition match { + case TrueLiteral => child + case _ => filterSource(child, condition).getOrElse(Filter(condition, child)) + } + val projectList = values.zip(rows.output).map { case (value, attr) => + Alias(value, attr.name)(exprId = attr.exprId, qualifier = attr.qualifier, + explicitMetadata = Some(attr.metadata)) + } + merge.copy(query = Project(projectList, filtered)) + } + + private def hasUnfoldedConstants(expr: Expression): Boolean = expr match { + case _: Literal => false + // These failures stay protected by the expression after MergeRows is removed. + case c: ConditionalExpression if !c.foldable => false + case e => e.foldable || e.children.exists(hasUnfoldedConstants) + } + + private def filterSource(plan: LogicalPlan, condition: Expression): Option[LogicalPlan] = { Review Comment: Removed filterSource along with OptimizeInsertOnlyMerge. The early rewrite builds the existing source Filter and Project directly when folding is safe; subsequent predicate movement is left to the existing optimizer rules. --- <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub MCP. --> _This comment was generated with [GitHub MCP](http://go/mcps)._ ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/MergeRows.scala: ########## @@ -31,7 +32,14 @@ case class MergeRows( notMatchedBySourceInstructions: Seq[Instruction], checkCardinality: Boolean, output: Seq[Attribute], - child: LogicalPlan) extends UnaryNode { + child: LogicalPlan) extends UnaryNode with SupportsNonDeterministicExpression { + + // A single insert instruction evaluates each output once per inserted row. + override def allowNonDeterministicExpression: Boolean = this match { Review Comment: Removing OptimizeInsertOnlyMerge removes the duplicate structural match. Updated the comment here to explain that this exception preserves nondeterministic INSERT values when the single-insert path must retain MergeRows. --- <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub MCP. --> _This comment was generated with [GitHub MCP](http://go/mcps)._ ########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/OptimizeInsertOnlyMergeSuite.scala: ########## @@ -0,0 +1,127 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.optimizer + +import java.util.Collections + +import org.apache.spark.sql.catalyst.dsl.expressions._ +import org.apache.spark.sql.catalyst.expressions.{Alias, If, IntegralDivide, Literal} +import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral} +import org.apache.spark.sql.catalyst.plans.{LeftAnti, PlanTest} +import org.apache.spark.sql.catalyst.plans.logical.{Filter, InsertOnlyMerge, Join, JoinHint, LocalRelation, LogicalPlan, MergeRows, Project} +import org.apache.spark.sql.catalyst.plans.logical.MergeRows.{Insert, Instruction, Keep} +import org.apache.spark.sql.catalyst.rules.RuleExecutor +import org.apache.spark.sql.connector.catalog.InMemoryTable +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.types.{LongType, MetadataBuilder, StructType} + +class OptimizeInsertOnlyMergeSuite extends PlanTest { + private object Optimize extends RuleExecutor[LogicalPlan] { + override val batches: Seq[Batch] = Seq( + Batch("Optimize insert-only MERGE", Once, ConstantFolding, OptimizeInsertOnlyMerge)) + } + + private val source = LocalRelation($"sourceId".long, $"unused".int) + private val key = source.output.head + private val table = new InMemoryTable( + "target", new StructType().add("id", LongType), Array.empty, Collections.emptyMap()) + private val target = DataSourceV2Relation.create(table, None, None) + private val join = Join(source, target, LeftAnti, Some(key === target.output.head), JoinHint.NONE) + private val metadata = new MetadataBuilder().putString("comment", "target column").build() + + private def insert( + instructions: Seq[Instruction], + child: LogicalPlan = join): InsertOnlyMerge = { + val attrs = target.output.map(_.newInstance().withMetadata(metadata).withQualifier(Seq("t"))) + InsertOnlyMerge(target, MergeRows(TrueLiteral, FalseLiteral, Nil, instructions, Nil, + checkCardinality = false, attrs, child)) + } + + private def optimize(plan: InsertOnlyMerge): InsertOnlyMerge = { + Optimize.execute(plan).asInstanceOf[InsertOnlyMerge] + } + + test("fold constants and preserve the write output attributes") { + val plan = insert(Seq(Keep(Insert, key > (Literal(1L) + Literal(1L)), Seq(key + 1L)))) + val result = optimize(plan) + + val project = result.query.asInstanceOf[Project] + assert(project.output.map(_.exprId) == plan.query.output.map(_.exprId)) + assert(project.output.map(_.metadata) == plan.query.output.map(_.metadata)) + assert(project.output.map(_.qualifier) == plan.query.output.map(_.qualifier)) + assert(project.projectList.head.asInstanceOf[Alias].child.semanticEquals(key + 1L)) + comparePlans(project.child, join.copy(left = Filter(key > 2L, source))) + } + + gridTest("preserve a failed constant fold")(Seq("condition", "value")) { position => + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { + val bad = IntegralDivide(Literal(1L), Literal(0L)) + val instruction = if (position == "condition") { + Keep(Insert, bad === 1L, Seq(key)) + } else { + Keep(Insert, TrueLiteral, Seq(bad)) + } + val plan = insert(Seq(instruction)) + assert(optimize(plan).query.isInstanceOf[MergeRows]) + } + } + + test("failures inside a conditional expression remain protected") { + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { + val value = If(key > 0L, IntegralDivide(Literal(1L), Literal(0L)), Literal(1L)) + val result = optimize(insert(Seq(Keep(Insert, TrueLiteral, Seq(value))))) + val project = result.query.asInstanceOf[Project] + assert(project.projectList.head.asInstanceOf[Alias].child.semanticEquals(value)) + } + } + + test("preserve multiple insert actions") { + val plan = insert(Seq( + Keep(Insert, key < 0L, Seq(Literal(0L))), + Keep(Insert, TrueLiteral, Seq(key)))) + assert(optimize(plan).query.isInstanceOf[MergeRows]) + } + + test("do not remove MergeRows before its constants have been folded") { + val plan = insert(Seq(Keep(Insert, TrueLiteral, Seq(Literal(1L) + Literal(2L))))) + comparePlans(OptimizeInsertOnlyMerge(plan), plan) + } + + test("push the condition through a pruning projection above the anti join") { + val pruned = Project(Seq(Alias(key, "renamed")()), join) + val renamed = pruned.output.head + val result = optimize(insert(Seq(Keep(Insert, renamed > 0L, Seq(renamed))), pruned)) + val filteredJoin = result.query.collectFirst { case j: Join => j }.get + comparePlans(filteredJoin, join.copy(left = Filter(key > 0L, source))) + } + + test("keep source-dependent conditions below the anti join") { + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { + val condition = IntegralDivide(Literal(1L), key) > 0L + val result = optimize(insert(Seq(Keep(Insert, condition, Seq(key))))) + comparePlans(result.query.children.head, + join.copy(left = Filter(condition, source))) + } + } + + test("do not rewrite MergeRows outside an insert-only write") { Review Comment: Replaced the removed optimizer suite with RewriteMergeIntoTableSuite, including FALSE/NULL conditions and successful/failed folding. Added CHECK coverage and negative tests for nondeterministic values outside the single-insert path; the codegen-off regression now asserts MergeRowsExec is present. --- <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub MCP. --> _This comment was generated with [GitHub MCP](http://go/mcps)._ ########## sql/core/src/test/scala/org/apache/spark/sql/connector/MergeIntoTableSuiteBase.scala: ########## @@ -1893,6 +1894,182 @@ abstract class MergeIntoTableSuiteBase extends RowLevelOperationSuiteBase } } + test("MERGE defers constant-folding failures in unselected actions") { + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { + withTempView("source") { + createAndInitTable("pk INT NOT NULL, salary BIGINT, dep STRING", + """{ "pk": 1, "salary": 100, "dep": "hr" }""") + Seq((1, 10L, "hr")).toDF("pk", "salary", "dep").createOrReplaceTempView("source") + + val merge = + s"""MERGE INTO $tableNameAsString t + |USING source s + |ON t.pk = s.pk + |WHEN MATCHED AND s.salary < 0 THEN UPDATE SET salary = 1 DIV 0 + |WHEN MATCHED THEN UPDATE SET salary = s.salary + |WHEN NOT MATCHED THEN + | INSERT (pk, salary, dep) VALUES (s.pk, 1 DIV 0, s.dep) + |WHEN NOT MATCHED BY SOURCE THEN UPDATE SET salary = 1 DIV 0 + |""".stripMargin + sql(merge) + checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, 10L, "hr")) + + Seq((1, -1L, "hr")).toDF("pk", "salary", "dep").createOrReplaceTempView("source") + val error = intercept[SparkArithmeticException] { + sql(merge) + } + assert(error.getCondition == "DIVIDE_BY_ZERO") + checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, 10L, "hr")) + } + } + } + + test("MERGE defers constant-folding failures in later clause conditions") { + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { + withTempView("source") { + createAndInitTable("pk INT NOT NULL, salary INT, dep STRING", + """{ "pk": 1, "salary": 100, "dep": "hr" }""") + Seq((1, 10, "hr")).toDF("pk", "salary", "dep").createOrReplaceTempView("source") + + sql( + s"""MERGE INTO $tableNameAsString t + |USING source s + |ON t.pk = s.pk + |WHEN MATCHED AND t.salary > 0 THEN UPDATE SET salary = s.salary + |WHEN MATCHED AND 1 DIV 0 = 1 THEN DELETE + |WHEN NOT MATCHED AND 1 DIV 0 = 1 THEN + | INSERT (pk, salary, dep) VALUES (s.pk, s.salary, s.dep) + |WHEN NOT MATCHED BY SOURCE AND 1 DIV 0 = 1 THEN DELETE + |""".stripMargin) + checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, 10, "hr")) + } + } + } + + gridTest("insert-only MERGE defers constant-folding failures")(for { + numClauses <- Seq(1, 2) + (condition, salary) <- Seq("" -> "1 DIV 0", "AND 1 DIV 0 = 1" -> "s.salary") + } yield (numClauses, condition, salary)) { case (numClauses, condition, salary) => + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { + withTempView("source") { + createAndInitTable("pk INT NOT NULL, salary BIGINT, dep STRING", + """{ "pk": 1, "salary": 100, "dep": "hr" }""") + + val extraClause = if (numClauses == 2) { + "WHEN NOT MATCHED AND s.salary < 0 THEN INSERT *" + } else { + "" + } + val merge = + s"""MERGE INTO $tableNameAsString t + |USING source s + |ON t.pk = s.pk + |$extraClause + |WHEN NOT MATCHED $condition THEN + | INSERT (pk, salary, dep) VALUES (s.pk, $salary, s.dep) + |""".stripMargin + + Seq((1, 10L, "hr")).toDF("pk", "salary", "dep").createOrReplaceTempView("source") + sql(merge) + checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, 100L, "hr")) + + Seq((1, 10L, "hr"), (2, 20L, "hr")) + .toDF("pk", "salary", "dep").createOrReplaceTempView("source") + val error = intercept[SparkArithmeticException] { + sql(merge) + } + assert(error.getCondition == "DIVIDE_BY_ZERO") + checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, 100L, "hr")) + } + } + } + + test("insert-only MERGE preserves condition pushdown when constants fold") { + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { + withTempView("source") { + createAndInitTable("pk INT NOT NULL, salary BIGINT, dep STRING", + """{ "pk": 1, "salary": 100, "dep": "hr" }""") + spark.range(1, 3).selectExpr("CAST(id AS INT) AS pk", "id * 10 AS salary", "'hr' AS dep") + .createOrReplaceTempView("source") + + Seq( + "s.salary > CAST('5' AS BIGINT)", Review Comment: Replaced the loop with one predicate and a source row that it excludes. The test captures the actual QueryExecution once and checks for the expected pushed predicate and resulting rows. --- <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub MCP. --> _This comment was generated with [GitHub MCP](http://go/mcps)._ -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
