dongjoon-hyun commented on code in PR #60559: URL: https://github.com/apache/spark/pull/60559#discussion_r4607370521
########## 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, Review Comment: **[3] The rule does not fire for a target with a CHECK constraint, nor on the V1-write fallback.** The pattern needs `MergeRows` to be the query of `InsertOnlyMerge` itself. For a table with a CHECK constraint, `ResolveTableConstraints` wraps the query into `Filter(CheckInvariant(...), MergeRows(...))` (`TableConstraintResolution.scala:56-57`) in the same "Resolution" batch, and no rule pushes that filter through `MergeRows`. So every single-clause MERGE into such a table keeps `MergeRows`, and a condition such as `WHEN NOT MATCHED AND s.dt = '2026-11-17'` is no longer pushed into the source scan or used for partition pruning; it runs in `MergeRowsExec` after the full anti join. On the V1-write path, `AppendDataExecV1` optimizes the stored `analyzedQuery` again, which is now a bare `MergeRows` without its `InsertOnlyMerge` parent, so the `COMMAND` pruning skips the rule there too. This contradicts "This preserves source-side condition pushdown" in the description, and no test uses a CHECK constraint. One caveat for the fix: matching through the CHECK `Filter` lets `PushPredicateThroughJoin` push `CheckInvariant`, which is not `throwable`, below the anti join, where it would run on matched rows. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala: ########## @@ -47,42 +47,6 @@ object RewriteMergeIntoTable extends RewriteRowLevelCommand with PredicateHelper override def apply(plan: LogicalPlan): LogicalPlan = plan.resolveOperatorsWithPruning( _.containsPattern(MERGE_INTO_TABLE)) { // aligned is false when schema evolution is pending (see ResolveRowLevelCommandAssignments) - case m @ MergeIntoTable(aliasedTable, source, cond, matchedActions, notMatchedActions, - notMatchedBySourceActions, _) if m.resolved && m.rewritable && m.aligned && - matchedActions.isEmpty && notMatchedActions.size == 1 && - notMatchedBySourceActions.isEmpty => - - EliminateSubqueryAliases(aliasedTable) match { - case r: DataSourceV2Relation => - checkNoGeneratedColumns(r, MERGE) - validateMergeIntoConditions(m) - - // NOT MATCHED conditions may only refer to columns in source so they can be pushed down - val insertAction = removeMetadataAssignments(notMatchedActions).head - .asInstanceOf[InsertAction] - val filteredSource = insertAction.condition match { - case Some(insertCond) => Filter(insertCond, source) - case None => source - } - - // there is only one NOT MATCHED action, use a left anti join to remove any matching rows - // and switch to using a regular append instead of a row-level MERGE operation - // only unmatched source rows that match the condition are appended to the table - val joinPlan = Join(filteredSource, r, LeftAnti, Some(cond), JoinHint.NONE) - - val output = insertAction.assignments.map(_.value) - val outputColNames = r.output.map(_.name) - val projectList = output.zip(outputColNames).map { case (expr, name) => - Alias(expr, name)() - } - val project = Project(projectList, joinPlan) - - InsertOnlyMerge(r, project) - - case _ => - m - } - case m @ MergeIntoTable(aliasedTable, source, cond, matchedActions, notMatchedActions, Review Comment: **[2] Valid single-clause statements now fail analysis.** `CheckAnalysis` checks the `MergeRows` that this case now builds for a single clause, before `OptimizeInsertOnlyMerge` can turn it back into a `Project`. So INSERT values that relied on the handling of a `Project`, which worked for a single clause on the base branch (since 3.5.0), now fail: - a correlated scalar subquery, `VALUES (s.pk, (SELECT max(o.salary) FROM other o WHERE o.dep = s.dep), s.dep)`, fails with `UNSUPPORTED_CORRELATED_SCALAR_SUBQUERY`, because `ValidateSubqueryExpression.scala:172` accepts only `Filter`, `Project` and `SupportsSubquery`, although the message says that MERGE supports it; - an `IN` or `EXISTS` subquery, `VALUES (s.pk, s.pk IN (SELECT id FROM other), s.dep)`, fails with `UNSUPPORTED_IN_EXISTS_SUBQUERY`; - a window function, `VALUES (s.pk, row_number() OVER (ORDER BY s.pk), s.dep)`, fails with `UNSUPPORTED_EXPR_FOR_OPERATOR` and names the internal `MergeRows` operator; on the base branch `ExtractWindowExpressions` handled the `Project` in the same batch. Could the old `Project` and `Filter` case stay for statements whose actions hold no foldable expression other than literals, so that only the statements that may need the deferral use `MergeRows`? That would also avoid [1], [3] and [7]. Regression tests for these three shapes would help either way. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala: ########## @@ -107,8 +69,6 @@ object RewriteMergeIntoTable extends RewriteRowLevelCommand with PredicateHelper } val outputs = notMatchedInstructions.flatMap(_.outputs) - - // merge rows as there are multiple NOT MATCHED actions val mergeRows = MergeRows( Review Comment: **[1] A single-clause MERGE that keeps `MergeRows` can write -1 instead of NULL.** With the first case removed, a single `WHEN NOT MATCHED` clause is planned as this `MergeRows` too, and it stays in the optimized plan whenever `OptimizeInsertOnlyMerge` does not fire: a target with a CHECK constraint ([3]), a constant that failed to fold, or the V1-write fallback. That exposes single-clause MERGE to stale output nullability. `generateExpandOutput` (`RewriteRowLevelCommand.scala:395`) fixes the nullability of these output attributes in the "Resolution" batch, and the later "ScalaUDF Null Handling" batch wraps a UDF with primitive inputs into `If(IsNull(x), null, udf(x))`. The whole-stage codegen of `MergeRowsExec` builds its output row with the stale, non-nullable attributes and so drops the null bit: ```scala spark.udf.register("plus1", (x: Int) => x + 1) // t: pk INT, v INT, CONSTRAINT c CHECK (pk > 0); source s: (pk = 2, x = NULL) sql("""MERGE INTO t USING s ON t.pk = s.pk |WHEN NOT MATCHED THEN INSERT (pk, v) VALUES (s.pk, plus1(s.x))""".stripMargin) ``` Reading the code, this writes `(2, -1)` with whole-stage codegen on (`false` for a BOOLEAN result), also into a NOT NULL column, while the base branch writes `(2, NULL)` through its `Project`. MERGE statements that already used `MergeRows` have had this since `MergeRowsExec` got codegen (SPARK-53652, 4.2.0), so the root fix is in the nullability of `MergeRows.output`. Since this PR routes single-clause statements into it, it needs either that fix or keeping single-clause statements off `MergeRows` when no constant failed to fold. ########## 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: **[6] Failing constants inside NULLIF or BETWEEN inputs are not deferred.** `RewriteWithExpression` runs before any `ConstantFolding` and treats only `ConditionalExpression` as conditional (`RewriteWithExpression.scala:462`). A `MergeRows.Instruction` takes the `case other` path, so a non-cheap `With` definition that NULLIF or BETWEEN creates inside an instruction is moved into a `Project` below `MergeRows`, where this case cannot reach it: ```sql -- ANSI on; source (1, 10, 'hr') MERGE INTO t USING s ON t.pk = s.pk WHEN MATCHED AND s.salary < 0 THEN UPDATE SET salary = nullif(s.salary + 1 DIV 0, 0) WHEN MATCHED THEN UPDATE SET salary = s.salary ``` Reading the code, this still fails with `DIVIDE_BY_ZERO` during optimization, while `SET salary = s.salary + 1 DIV 0` completes with this PR, and so does the same `nullif` in a `CASE WHEN` branch of a SELECT. A later clause `WHEN MATCHED AND s.salary + 1 DIV 0 BETWEEN 1 AND 10 THEN DELETE` fails the same way. Treating an instruction like a conditional expression there, e.g. `case i: MergeRows.Instruction => inlineWithsThatGainNothing(i)` in `rewriteWithExprAndInputPlans`, would cover it; today the hoisted definition also runs for every joined row at runtime. ########## 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: **[4] The `ConditionalExpression` exemption does not hold for the condition.** The condition is pushed below the anti join, so it runs for every source row, matched ones included. `ConstantFolding` folds every child of a non-foldable conditional expression as a branch, including its always-evaluated input, so a failing constant there is tagged and left, and `hasUnfoldedConstants` returns false: ```sql -- ANSI on; target (1, 100, 'hr'); source (1, 10, 'hr') only MERGE INTO t USING s ON t.pk = s.pk WHEN NOT MATCHED AND IF(1 DIV 0 = 1, s.salary > 0, s.salary < 0) THEN INSERT (pk, salary, dep) VALUES (s.pk, s.salary, s.dep) ``` Reading the code, the pushed `Filter` evaluates the `If` predicate for the matched row, and the MERGE fails with `DIVIDE_BY_ZERO` (during optimization when the source is a local relation). After another `WHEN NOT MATCHED` clause, the same clause keeps `MergeRows` and completes, which is the clause-count dependence from the earlier [review comment](https://github.com/apache/spark/pull/60559#discussion_r4589700684). A failing constant in a branch, such as `IF(s.salary > 0, 1 DIV 0 = 1, FALSE)`, behaves the same. The comment at L50 holds only for the values, which stay above the anti join. Checking the condition without the exemption, e.g. `!condition.exists(e => e.foldable && !e.isInstanceOf[Literal])`, and keeping the exemption for the values would fix it. ########## 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: **[7] A non-boolean INSERT condition is no longer rejected during analysis.** MERGE action conditions are type-checked only through the `Filter` rule of `CheckAnalysis` (`CheckAnalysis.scala:780`, `DATATYPE_MISMATCH.FILTER_NOT_BOOLEAN`). The single clause's condition used to be such a `Filter`; now it is a `MergeRows` instruction, so `WHEN NOT MATCHED AND s.salary THEN INSERT *` with an INT `salary` passes analysis and fails later with an internal error: `PLAN_VALIDATION_FAILED_RULE_IN_BATCH` after `InferFiltersFromConstraints` builds `And(isnotnull(salary), salary)`, or a codegen compile error in `FilterExec` or `MergeRowsExec`. Checking `cond.dataType == BooleanType` in `checkMergeIntoCondition` would keep the analysis error and also cover the clauses that already went through `MergeRows`. ########## 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: **[5] Removing `MergeRows` lets later rules recreate the failure.** The guard sees the constants that exist when the rule runs, but once `MergeRows` is gone, later rules in the batch can create new ones in positions that are folded as always evaluated. `MergeRows` shields its instructions from these rewrites, so each statement below completes with a second `WHEN NOT MATCHED` clause but fails during optimization with one (ANSI on, every source row matched): - `CollapseProject` or `FoldablePropagation` inlines a constant from the source: `USING (SELECT pk, 0L AS d, dep FROM src) s ... WHEN NOT MATCHED THEN INSERT (pk, salary, dep) VALUES (s.pk, 100 DIV s.d, s.dep)` folds `100 DIV 0`; - `filterSource` itself inlines it into the condition, e.g. `WHEN NOT MATCHED AND 100 DIV s.d = 1`; - `ReorderAssociativeOperator` turns `s.salary + 2147483647 + 1` on an INT `salary` into `s.salary + (2147483647 + 1)`. The base branch fails the same way, but the description now says that this works "including single-clause insert-only MERGE". Keeping the values in `MergeRows` and moving only a condition that cannot fail into the pushed `Filter` would avoid it; otherwise the description could state the limitation. ########## 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: **[8] `filterSource` re-implements `PushDownPredicates` without its guards.** If the rule returned `Project(projectList, Filter(condition, child))`, `PushDownPredicates`, which runs earlier in the same batch, would push the filter through the `Project` and into the left side of the anti join in the next iteration, as the SQL pushdown test expects. Doing it here skips two of its guards: - expensive aliases are inlined unconditionally. For `WHEN NOT MATCHED AND nullif(my_scala_udf(s.x), '') IS NOT NULL`, `RewriteWithExpression` has already put the definition into a `Project` below `MergeRows`, and `replaceAlias` inlines it back into both references, so the UDF runs twice per source row instead of once on the base branch; - throwable conjuncts such as `raise_error` or `assert_true` are pushed into a join they should stay above, e.g. into the source's own anti join when `ON FALSE` has removed the MERGE's anti join. Could `filterSource` be dropped in favor of `Filter(condition, child)`? The unit tests that check the placement would then need `PushDownPredicates` in their batch. ########## 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: **[9] The single-insert shape is matched in two places.** This pattern and the one in `OptimizeInsertOnlyMerge.scala:34-35` describe the plan that `RewriteMergeIntoTable` builds; if one of them changes (the presence literals, `checkCardinality`), analysis and the optimizer silently disagree on which plans are single-insert. A shared extractor in `object MergeRows` would keep them in sync. Also, the reason in the comment holds for several insert instructions too, since each row evaluates the outputs of one instruction once, so it does not explain why only one clause is allowed; the reason seems to be keeping the nondeterministic values that the old single-clause `Project` accepted. ########## 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: **[10] Some branches of the new rule are not covered, and this test checks nothing.** This plan has no `COMMAND` pattern, so `transformUpWithPruning(_.containsPattern(COMMAND), ruleId)` (`OptimizeInsertOnlyMerge.scala:32-33`) returns before the pattern is tried; wrapping the same `MergeRows` in another command would test the `InsertOnlyMerge` guard. These changes to the rule also pass every test: - the `filterSource` fallback dropping the condition (`getOrElse(child)`); it is reachable with a `UNION ALL` source, since `PushDownLeftSemiAntiJoin` pushes the anti join below the `Union`; - `case _: Literal => child`, which would insert every unmatched row for a FALSE or NULL condition; - removing the `!c.foldable` guard; - `allowNonDeterministicExpression` returning true for every `MergeRows`. There is also no test with a CHECK-constrained target ([3]), and the codegen-off test (`MergeIntoTableSuiteBase.scala:2053`) does not assert that `MergeRowsExec` is still in the plan, so it would silently stop covering `initialize` if the rule's decision changes. ########## 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: **[11] Only the first iteration of this loop checks anything.** The table is created once and every condition holds for both source rows, so the first iteration inserts pk 2 and the next two are matched no-ops whose `checkAnswer` cannot fail; L2014 also counts filters without looking at them. Since `FinishAnalysis` runs before `ConstantFolding`, all three conditions fold the same way and take the same branch of the rule. One condition with a source row that does not satisfy it would be enough, and checking the `QueryExecution` from `withQueryExecutionsCaptured(spark) { sql(merge) }` would avoid analyzing and optimizing each MERGE twice (and the `CommandExecutionMode` import). ########## 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 => + i.mapChildren(constantFolding(_, isConditionalBranch = true)) Review Comment: **[13] Nit: a short comment for this case would help.** `Instruction` is `Unevaluable`, so this looks like the `case other` below except for the flag, and it could later be removed as redundant or narrowed to "the first condition of a list is always evaluated". For example: `MergeRows` evaluates one instruction list per row and stops at the first match, so no child of an instruction is always evaluated. The `FAILED_TO_EVALUATE` comment (L51-52) and the `tryFold` comment (L81-83) still mention only conditional expressions. ########## 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 { Review Comment: **[12] Several new test cases cover the same branch.** With seven suites, the new SQL tests run 63 times, and some of them repeat coverage: the two tests at L1897 and L1927 can be one MERGE, and `numClauses = 2` here runs the `MergeRows.Instruction` case of `ConstantFolding` again, which those two already cover. In the Catalyst suite, the tests at `OptimizeInsertOnlyMergeSuite.scala:101` and `OptimizeInsertOnlyMergeSuite.scala:114` take the same branches as the ones at `OptimizeInsertOnlyMergeSuite.scala:72` and `OptimizeInsertOnlyMergeSuite.scala:60`. One case per branch would keep the coverage with fewer runs. ########## 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] = { + plan match { + case join @ Join(_, _, LeftAnti, _, _) => + Some(join.copy(left = Filter(condition, join.left))) + // Column pruning may put a projection between MergeRows and the anti join. Review Comment: **[15] Nit: two comments no longer match the code.** This comment mentions only `ColumnPruning`, whose `Project` holds only attributes; the `Project` that actually needs `replaceAlias` comes from `PushDownLeftSemiAntiJoin` moving a source `Project` with aliases above the anti join. Also, the comment at `AcceptAnySchemaMergeIntoTableSuiteBase.scala:115` ("a single NOT MATCHED action and multiple NOT MATCHED actions are rewritten differently") no longer holds during analysis. ########## 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", Review Comment: **[14] Nit: `BIGINT` is required here.** The rest of the file uses `salary INT`, but with an INT column the value becomes `CheckOverflowInTableInsert(Cast(1 DIV 0 AS INT))`, which reports the `SparkArithmeticException` of its child as `CAST_OVERFLOW_IN_TABLE_INSERT`, so `getCondition == "DIVIDE_BY_ZERO"` at L1921 and L1981 would fail. A short comment would keep someone from normalizing it. -- 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]
