[SPARK-61444][SQL] Keep the result on zero rows of a correlated subquery as an expression if it fails to fold #60325
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #60325"
general
weight: 0.35
sarutak
What changes were proposed in this pull request?
RewriteCorrelatedScalarSubquery.tryEvalExprnow keeps the expression when evaluating it fails, the same as it already does for an expression that is not foldable (SPARK-28441). LikeConstantFolding.tryFoldin a conditional branch (SPARK-39106), it evaluates a fresh copy of a stateful expression, and tags an expression that failed withFAILED_TO_EVALUATEso thatConstantFoldingdoes not evaluate it again. It tags a copy, so that the expression in the plan, e.g. a constant10 / 0in the output of theAggregate, is still evaluated there. When the evaluation fails, it returns the expression without its aliases, as for a folded value.The
Filtercase ofevalSubqueryOnZeroTups(aHAVINGclause) now checks whether the bound condition was evaluated to aLiteral, instead of checkingfoldableand callingeval()again, so a condition that failed to evaluate is kept as well.The Scaladoc of
bindingExpr,evalAggExprOnZeroTups,evalAggregateOnZeroTupsandevalSubqueryOnZeroTups, and the comment andassertmessage inDecorrelateInnerQuerythat use the result, now say that a result that can't be evaluated statically is kept as an expression.Why are the changes needed?
With ANSI mode on (the default), a correlated subquery fails while the query is optimized when its result on zero rows throws, even if every outer row has matching rows:
With
spark.sql.ansi.enabled=false, the same query returns the expected rows.To handle the COUNT bug,
evalSubqueryOnZeroTups(andDecorrelateInnerQuery, throughevalAggregateOnZeroTups) computes the result of the subquery on zero rows while the query is optimized, and puts it intoIf(IsNull(alwaysTrue), <result on zero rows>, <subquery result>), which uses it only for outer rows without matching rows.tryEvalExprcalledeval()on every foldable expression without catching its errors, so an error that can only happen for such an outer row failed the whole query, even when no such row exists.ConstantFoldingkeeps an expression that fails to evaluate in a conditional branch for the same reason (SPARK-39106).DecorrelateInnerQueryalso handles the COUNT bug ofLATERAL,EXISTSandINsubqueries (rewriteSubQueriesdecorrelates them withhandleCountBug = true, forEXISTSandINwith the defaultspark.sql.optimizer.decorrelateExistsSubqueryLegacyIncorrectCountHandling.enabled=false), so they fail in the same way. So do other errors, and errors with ANSI mode off:| Query, every outer row has matching rows | Before | After |
|---|---|---|
|
SELECT k, (SELECT 10 / COALESCE(MAX(v), 0) FROM i WHERE i.k = o.k) FROM o|DIVIDE_BY_ZERO|(1, 0.05), (2, 0.0333...)||
SELECT k, (SELECT CAST(COALESCE(MAX(CAST(v AS STRING)), 'x') AS INT) FROM i WHERE i.k = o.k) FROM o|CAST_INVALID_INPUT|(1, 200), (2, 300)||
SELECT k FROM o WHERE (SELECT 10 / COALESCE(MAX(v), 0) FROM i WHERE i.k = o.k) > 0.04|DIVIDE_BY_ZERO|(1)||
SELECT k, (SELECT COUNT() FROM i WHERE i.k = o.k HAVING 10 / COUNT() > 0) FROM o|DIVIDE_BY_ZERO|(1, 2), (2, 1)||
SELECT k, (SELECT MAX(c) FROM (SELECT 10 / COUNT() c FROM i WHERE i.k = o.k)) FROM o|DIVIDE_BY_ZERO|(1, 5.0), (2, 10.0)||
SELECT o.k, t.d FROM o, LATERAL (SELECT 10 / COALESCE(MAX(i.v), 0) d FROM i WHERE i.k = o.k) t|DIVIDE_BY_ZERO|(1, 0.05), (2, 0.0333...)||
SELECT k FROM o WHERE EXISTS (SELECT 10 / COALESCE(MAX(v), 0) FROM i WHERE i.k = o.k)|DIVIDE_BY_ZERO|(1), (2)||
SELECT k FROM o WHERE 5 IN (SELECT 1000 / COALESCE(MAX(v), 0) FROM i WHERE i.k = o.k)|DIVIDE_BY_ZERO|(1)|| ANSI off:
SELECT k, (SELECT element_at(array(1, 2), CAST(COUNT(v) AS INT)) FROM i WHERE i.k = o.k) FROM o|INVALID_INDEX_OF_ZERO|(1, 2), (2, 1)|In the default confs, the
HAVINGquery is handled inDecorrelateInnerQuery. Withspark.sql.optimizer.decorrelateInnerQuery.enabled=false, it is handled in CASE 3 ofconstructLeftJoins, which puts the result on zero rows into aCaseWhen, and fails and is fixed in the same way.Does this PR introduce _any_ user-facing change?
Yes. A correlated subquery whose result on zero rows fails to evaluate, e.g. with
DIVIDE_BY_ZEROorCAST_INVALID_INPUTin ANSI mode, orINVALID_INDEX_OF_ZERO, no longer fails the query while it is optimized. When the result on zero rows is used for an outer row without matching rows, the query still fails with the same error: at runtime, or while the query is optimized if the subquery is known to be empty, e.g.... FROM (SELECT FROM i WHERE false) x WHERE x.k = o.k, where the conditional branch goes away. With the default confs, a grouped scalar subquery does not use the result on zero rows, and neither does anEXISTSsubquery, so they no longer fail at all. A failing expression that is also a column of the subquery, e.g.10 / 0 dinLATERAL (SELECT count() c, 10 / 0 d FROM i WHERE i.k = o.k), still fails while the query is optimized. Queries that did not fail before are unchanged.The code is the same in branch-3.5 and later. ANSI mode is on by default since 4.0.
How was this patch tested?
SPARK-61444: COUNT bug with a result on zero rows that fails to evaluateinSubquerySuite:- With ANSI mode on, the queries in the table above where every outer row has matching rows return their rows. They cover the top
AggregateinconstructLeftJoins(inSELECTandWHERE), aHAVINGcondition, aCASTerror, a lowerAggregateinDecorrelateInnerQuery, andLATERAL,EXISTSandINsubqueries.- With an outer row without matching rows, the grouped scalar subquery and the
EXISTSsubquery return their rows. The scalar (inSELECTandWHERE),HAVING, lowerAggregate,LATERALandINqueries fail withDIVIDE_BY_ZERO, and theCASTquery withCAST_INVALID_INPUT. The test checks thatexecutedPlansucceeds for each of them beforecollect()fails, i.e. that the error comes at runtime.- The
HAVINGqueries also run withspark.sql.optimizer.decorrelateInnerQuery.enabled=false, so that CASE 3 ofconstructLeftJoinsuses the result of theFiltercase.-
LATERAL (SELECT count() c, 10 / 0 d ...)overo2and over an empty outer table fails withDIVIDE_BY_ZEROwhile the query is optimized, as on master.- With ANSI mode off, the
element_atquery returns its rows, and fails withINVALID_INDEX_OF_ZEROat runtime with an outer row without matching rows.- Without the change in
subquery.scala, the test fails. It also fails if the last case of theFilterbranch is preceded bycase c if c.foldable => Map.emptyor bycase c if c.foldable => bindings.build/sbt 'catalyst/testOnly RewriteSubquerySuite DecorrelateInnerQuerySuite PullupCorrelatedPredicatesSuite OptimizerSuite',build/sbt 'sql/testOnly org.apache.spark.sql.SubquerySuite'andbuild/sbt 'sql/testOnly org.apache.spark.sql.SQLQueryTestSuite -- -z subquery'(no golden file changes) pass.SPARK-61444: keep the result on zero rows of an Aggregate that fails to evaluateinRewriteSubquerySuitechecks thatevalAggregateOnZeroTupskeeps10 / coalesce(max(v), 0)with ANSI mode on as an expression without anAliasand with theFAILED_TO_EVALUATEtag, and evaluates it tonullwith ANSI mode off. For it and for a constant10 / 0, it checks that the expression in theAggregateis not tagged.catalyst/scalastyle,catalyst/Test/scalastyle,sql/scalastyleandsql/Test/scalastylepass.Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)