spark-test commented on code in PR #60559:
URL: https://github.com/apache/spark/pull/60559#discussion_r4589700684
##########
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:
**Non-blocking (P2):** This case only reaches expressions held in a
`MergeRows` instruction, and one MERGE shape has none. When a MERGE's only
clause is a single `WHEN NOT MATCHED` clause, the first case of
`RewriteMergeIntoTable` (RewriteMergeIntoTable.scala, lines 50-80) plans it as
`InsertOnlyMerge(target, Project(<INSERT values>, Join(Filter(<clause
condition>, source), target, LeftAnti, <ON>)))`, and `ConstantFolding.apply`
folds that `Project` and `Filter` with `isConditionalBranch = false`.
So, reading the code, with ANSI mode on and the data of the first new test
(target row pk 1, source row pk 1), this MERGE still fails with
`DIVIDE_BY_ZERO` during optimization, although every source row matches and the
INSERT never runs:
```sql
MERGE INTO t USING source s ON t.pk = s.pk
WHEN NOT MATCHED THEN INSERT (pk, salary, dep) VALUES (s.pk, 1 DIV 0, s.dep)
```
Adding any other clause, such as a `WHEN MATCHED` clause or a second `WHEN
NOT MATCHED` clause, moves the same clause into a `Keep(Insert)` instruction
and lets the statement complete, so whether a skipped constant fails the
command depends on how many clauses it has. A failing constant in the clause's
condition (`WHEN NOT MATCHED AND 1 DIV 0 = 1 THEN INSERT ...`) fails the same
way, and deferring the fold alone would not help there: this plan evaluates the
condition for every source row below the anti join, so the condition has to run
after the join, as it does in the `MergeRows` plan. Other constants that throw
when folded, such as an overflowing cast under ANSI mode or a store-assignment
overflow check, behave alike. This only affects MERGE statements that Spark's
built-in rewrite plans, that is, MERGE into DSv2 tables that support row-level
operations; the row-level plans and the insert-only plan with several `NOT
MATCHED` clauses are already covered by this case. Neither new
test runs an insert-only MERGE, so nothing would catch the difference.
**Recommended change:** In RewriteMergeIntoTable, guard the case for a MERGE
whose only clause is one NOT MATCHED clause so that it applies only when
constant folding succeeds for every expression in that clause's condition and
INSERT values. For each expression, first apply the rewrites that the
optimizer's Finish Analysis batch makes before any folding and that can turn a
constant that fails to evaluate into one that folds:
ReplaceExpressions.replace, then SpecialDatetimeValues.applyForExpression, in
that order, as TimeTravelSpec.resolveTimestampExpression prepares an expression
with ReplaceExpressions.replace before evaluating it. Then run
ConstantFolding.constantFolding with its default flag, which treats the
expression as always evaluated, as the optimizer treats that case's Filter and
Project, and treat a non-fatal error from any of these steps as a failed fold.
A MERGE that fails the check falls through to the existing insert-only case
below it, which already accepts NOT MA
TCHED clauses with no other clause types and holds each clause in a
Keep(Insert) MergeRows instruction over an unfiltered left anti join, where the
ConstantFolding case this PR adds defers the failure. Update that case's
comment, which says it handles multiple NOT MATCHED clauses, and add
insert-only MERGE tests to the shared MERGE test base.
**Why this works:** For a single NOT MATCHED clause, the rewrite puts the
clause's condition in a Filter on the source below the left anti join and its
values in a Project above it, so ConstantFolding folds their constants as
always evaluated and fails the MERGE even when no source row is unmatched. The
guard repeats that folding during the rewrite, after the same
runtime-replaceable and special datetime rewrites the optimizer applies before
it folds, and sends the statements whose fold fails to the MergeRows rewrite,
where the condition runs only for unmatched source rows and both the condition
and the values are instruction children that this PR's ConstantFolding case
folds as possibly unreached branches. Every other single NOT MATCHED clause
keeps its current plan, including the pushdown of its condition below the join,
apart from the narrow mismatches between the check and the optimizer's folding
that the risks name.
**Scope:** Send a single NOT MATCHED clause whose constants fail to fold
through the existing MergeRows insert-only rewrite, and cover insert-only MERGE
in the shared MERGE tests.
**Compatibility:** Every MERGE whose only clause is a NOT MATCHED clause
with a condition and values that fold once the optimizer's runtime-replaceable
and special datetime rewrites apply keeps its current optimized plan, including
the pushdown of its condition below the anti join and the Project that produces
its output columns.
**Risks:** The fold check evaluates each foldable expression of the single
NOT MATCHED clause once during analysis, in addition to the optimizer's
folding; the extra cost is bounded by that clause's constants. The check
reproduces the Finish Analysis rewrites that change whether such constants
fold, but other optimizer rules that run before the first ConstantFolding can
still change an expression first, such as NullPropagation replacing a null
check of a non-nullable expression with false, or the conversion of Python UDFs
to Catalyst expressions. If the check then fails for an expression that the
optimizer folds, that MERGE takes the MergeRows plan, whose results are still
correct but whose condition is no longer pushed below the anti join; if the
check passes where the optimizer's folding fails, the MERGE fails during
optimization exactly as it does on the base branch. A MERGE that takes the
fallback gets the MergeRows plan's output attributes, which carry the target
columns' nam
es, types, and metadata into the write schema, and its SQL metrics, as a MERGE
with several NOT MATCHED clauses already does; removing the guard restores the
current plan.
**Constraints:** Decide with the optimizer's own code rather than a separate
prediction: ReplaceExpressions.replace, then
SpecialDatetimeValues.applyForExpression, then ConstantFolding.constantFolding
in its default mode, in the order the optimizer applies them, so that a
constant the optimizer folds, such as CAST('today' AS DATE) under ANSI mode,
passes the check. Count only non-fatal errors as a failed fold, as
ConstantFolding does. Use the rewritten and folded copies only to decide the
guard; the planned Filter and Project keep the action's own expressions, which
the optimizer rewrites and folds as before. Keep the current plan, including
the source-side filter, for every single NOT MATCHED clause whose constants
pass the check.
**Exclusions:**
- When its constants fold, a single NOT MATCHED clause's condition still
runs below the anti join for every source row, as on the base branch, so a
condition that can fail per row, such as an ANSI division by a source column,
can still fail on a matched row; changing that pushdown is a separate design
question with a performance cost for every such MERGE.
**Success:** With ANSI mode on and a non-empty source whose rows all match
the target, a MERGE whose only clause is WHEN NOT MATCHED THEN INSERT with a
failing constant such as 1 DIV 0 in its values completes and leaves the table
unchanged. The same MERGE completes when the failing constant is in the
clause's condition, such as WHEN NOT MATCHED AND 1 DIV 0 = 1. When an unmatched
source row reaches that clause, the MERGE fails with the constant's error, such
as DIVIDE_BY_ZERO, and the table is unchanged. A single NOT MATCHED clause
whose condition and values fold keeps the base branch's plan, including one
whose constants fold only after the optimizer's runtime-replaceable or special
datetime rewrites, such as CAST('today' AS DATE) under ANSI mode: its condition
filters the source below the anti join and its values are a Project, with no
MergeRows.
**Verification:**
- **Regression:** Under ANSI mode, with a non-empty source whose rows all
match the target so the optimizer cannot prove the anti join empty, a MERGE
whose only clause is a NOT MATCHED INSERT with 1 DIV 0 among its values, and
one whose only clause has 1 DIV 0 = 1 as its condition, each complete and leave
the table unchanged, while both fail with DIVIDE_BY_ZERO on the base branch.
- **Behavior:** Adding one unmatched source row that reaches the clause with
the failing value makes the MERGE fail with DIVIDE_BY_ZERO as a
SparkArithmeticException and leaves the table unchanged, with whole-stage
codegen both on and off.
- **Compatibility:** Under ANSI mode, for a single NOT MATCHED clause whose
condition and values fold, such as a condition comparing a source column with a
cast literal and one comparing it with CAST('today' AS DATE), the plan the
rewrite produces still filters the source with that condition below the anti
join and the optimized plan contains no MergeRows, so existing insert-only
MERGEs keep their plan and pushdown; check the rewritten plan rather than the
optimized one for the filter, because ConvertToLocalRelation evaluates a
pushed-down Filter over a local source away.
--
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]