sarutak commented on code in PR #60325:
URL: https://github.com/apache/spark/pull/60325#discussion_r4538719168
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -724,7 +725,16 @@ object RewriteCorrelatedScalarSubquery extends
Rule[LogicalPlan] with AliasHelpe
// Needs to evaluate them on query runtime.
expr
} else {
- Literal.create(expr.eval(), expr.dataType)
+ try {
+ Literal.create(expr.eval(), expr.dataType)
+ } catch {
+ // SPARK-61444: The result on zero tuples is only used for the outer
rows without
+ // matching rows, in a conditional branch such as
If(IsNull(alwaysTrue), ...). If its
+ // evaluation fails, e.g. with DIVIDE_BY_ZERO in ANSI mode, evaluate
it in query runtime
+ // instead, so that the query fails only if such an outer row exists.
ConstantFolding
+ // does the same in conditional branches (SPARK-39106).
+ case NonFatal(_) => expr
Review Comment:
A few points here:
- "evaluate it in query runtime instead": as in point 2 of the review body,
when the subquery is known to be empty, the conditional branch goes away and
`ConstantFolding` evaluates the expression, so `SELECT k, (SELECT 10 /
coalesce(max(v), 0) FROM (SELECT * FROM i WHERE false) x WHERE x.k = o.k) FROM
o` still fails while it is optimized. Something like "keep it, so that it is
evaluated later, and the query fails only if the result on zero rows is used"
would cover that.
- Minor: `ConstantFolding.tryFold` evaluates
`expr.freshCopyIfContainsStatefulExpression()` and tags an expression that
failed with `FAILED_TO_EVALUATE`, while this evaluates `expr` itself and does
not tag it. Before this PR, an instance whose `eval()` threw never stayed in
the plan; now it does, e.g. a `CreateMap` (stateful) after
`DUPLICATED_MAP_KEY`. I did not find a path where its state is observed, since
runtime evaluation makes fresh copies, but doing the same as `tryFold` would
keep the two in line.
- Minor: when the evaluation fails, this returns `expr` with its `Alias`, so
an `Alias` with the `exprId` of the aggregate output ends up inside the `If` /
`CaseWhen`, while the success path returns a bare `Literal`. The results are
the same, and the non-foldable path from SPARK-28441 already does this, but
returning `trimAliases(expr)` would keep the plan shape the same as for a
folded value.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -715,7 +716,7 @@ object RewriteCorrelatedScalarSubquery extends
Rule[LogicalPlan] with AliasHelpe
/**
* Checks if given expression is foldable. Evaluates it and returns it as
literal, if yes.
- * If not, returns the original expression without evaluation.
+ * If not, or if the evaluation fails, returns the original expression
without evaluation.
Review Comment:
Minor: "without evaluation" does not hold when the evaluation fails, since
the expression was evaluated then. "returns the original expression" would be
accurate for both cases.
##########
sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala:
##########
@@ -3401,4 +3401,52 @@ class SubquerySuite extends SharedSparkSession
Row(1, 2))
}
}
+
+ test("SPARK-61444: COUNT bug with a result on zero rows that fails to
evaluate") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ withTempView("o", "o2", "i") {
+ Seq(1, 2).toDF("k").createOrReplaceTempView("o")
+ Seq(1, 2, 3).toDF("k").createOrReplaceTempView("o2")
+ Seq((1, 100), (1, 200), (2, 300)).toDF("k",
"v").createOrReplaceTempView("i")
+ // Every outer row has matching rows, so the result on zero rows is
not used, and the
+ // queries must not fail while the subquery is rewritten.
+ // The top Aggregate, handled in
RewriteCorrelatedScalarSubquery.constructLeftJoins.
+ checkAnswer(
+ sql("SELECT k, (SELECT 10 / coalesce(max(v), 0) FROM i WHERE i.k =
o.k) FROM o"),
+ Row(1, 0.05) :: Row(2, 10.0 / 300) :: Nil)
+ checkAnswer(
+ sql("SELECT k, (SELECT CAST(coalesce(max(CAST(v AS STRING)), 'x') AS
INT) " +
+ "FROM i WHERE i.k = o.k) FROM o"),
+ Row(1, 200) :: Row(2, 300) :: Nil)
+ checkAnswer(
+ sql("SELECT k FROM o WHERE (SELECT 10 / coalesce(max(v), 0) FROM i
WHERE i.k = o.k) " +
+ "> 0.04"),
+ Row(1) :: Nil)
+ // A HAVING clause whose condition fails to evaluate on zero rows.
+ checkAnswer(
+ sql("SELECT k, (SELECT count(*) FROM i WHERE i.k = o.k HAVING 10 /
count(*) > 0) " +
+ "FROM o"),
+ Row(1, 2) :: Row(2, 1) :: Nil)
Review Comment:
With the default confs, the `HAVING` queries in this test do not reach CASE
3 of `constructLeftJoins`. `rewriteSubQueries` handles the count bug of a
subquery whose top node is not an `Aggregate`, such as the `Filter` of a
`HAVING` clause, in `DecorrelateInnerQuery`, so `mayHaveCountBug = false`, and
`constructLeftJoins` computes the result on zero rows without using it. So the
test checks that the `Filter` branch no longer calls `eval()` again, but not
what it now returns for a condition that failed to evaluate. I added `case c if
c.foldable => Map.empty` before its last case, and in a second run `=>
bindings`, and `SPARK-61444` passed both times.
CASE 3 uses the value with
`spark.sql.optimizer.decorrelateInnerQuery.enabled=false` (the optimized plan
also has the `CaseWhen` with
`spark.sql.legacy.scalarSubqueryCountBugBehavior=true`). Could the `HAVING`
queries, at least the `o2` one below, also run with
`decorrelateInnerQuery.enabled=false`? With it, the `o2` one fails with
`DIVIDE_BY_ZERO` at runtime, and with the two replacements above it returns
`(1, 2), (2, 1), (3, NULL)` and `(1, 2), (2, 1), (3, 0)` instead. The
description's "`CaseWhen` in CASE 3" is also reached only with a non-default
conf such as these.
##########
sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala:
##########
@@ -3401,4 +3401,52 @@ class SubquerySuite extends SharedSparkSession
Row(1, 2))
}
}
+
+ test("SPARK-61444: COUNT bug with a result on zero rows that fails to
evaluate") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ withTempView("o", "o2", "i") {
+ Seq(1, 2).toDF("k").createOrReplaceTempView("o")
+ Seq(1, 2, 3).toDF("k").createOrReplaceTempView("o2")
+ Seq((1, 100), (1, 200), (2, 300)).toDF("k",
"v").createOrReplaceTempView("i")
+ // Every outer row has matching rows, so the result on zero rows is
not used, and the
+ // queries must not fail while the subquery is rewritten.
+ // The top Aggregate, handled in
RewriteCorrelatedScalarSubquery.constructLeftJoins.
+ checkAnswer(
+ sql("SELECT k, (SELECT 10 / coalesce(max(v), 0) FROM i WHERE i.k =
o.k) FROM o"),
+ Row(1, 0.05) :: Row(2, 10.0 / 300) :: Nil)
+ checkAnswer(
+ sql("SELECT k, (SELECT CAST(coalesce(max(CAST(v AS STRING)), 'x') AS
INT) " +
+ "FROM i WHERE i.k = o.k) FROM o"),
+ Row(1, 200) :: Row(2, 300) :: Nil)
+ checkAnswer(
+ sql("SELECT k FROM o WHERE (SELECT 10 / coalesce(max(v), 0) FROM i
WHERE i.k = o.k) " +
+ "> 0.04"),
+ Row(1) :: Nil)
+ // A HAVING clause whose condition fails to evaluate on zero rows.
+ checkAnswer(
+ sql("SELECT k, (SELECT count(*) FROM i WHERE i.k = o.k HAVING 10 /
count(*) > 0) " +
+ "FROM o"),
+ Row(1, 2) :: Row(2, 1) :: Nil)
+ // A lower Aggregate, handled in DecorrelateInnerQuery.
+ checkAnswer(
+ sql("SELECT k, (SELECT max(c) FROM (SELECT 10 / count(*) c FROM i
WHERE i.k = o.k)) " +
+ "FROM o"),
+ Row(1, 5.0) :: Row(2, 10.0) :: Nil)
+
+ // The outer row k = 3 of o2 has no matching rows and uses the result
on zero rows, so
+ // the queries still fail, at runtime.
+ Seq(
+ "SELECT k, (SELECT 10 / coalesce(max(v), 0) FROM i WHERE i.k = o2.k)
FROM o2",
+ "SELECT k, (SELECT count(*) FROM i WHERE i.k = o2.k HAVING 10 /
count(*) > 0) FROM o2",
+ "SELECT k, (SELECT max(c) FROM (SELECT 10 / count(*) c FROM i WHERE
i.k = o2.k)) " +
+ "FROM o2"
+ ).foreach { query =>
+ val e = intercept[SparkArithmeticException] {
+ sql(query).collect()
+ }
+ assert(e.getCondition === "DIVIDE_BY_ZERO")
+ }
Review Comment:
On master, these three queries already fail with `DIVIDE_BY_ZERO` while the
query is optimized, so `intercept[SparkArithmeticException] {
sql(query).collect() }` does not show that the error now comes at runtime, as
the comment says. With this PR, `df.queryExecution.executedPlan` succeeds for
all three, so calling it before the `intercept` would check that.
The `WHERE` query and the `CAST` query above have no `o2` counterpart here.
Their `o2` versions, `SELECT k FROM o2 WHERE (SELECT 10 / coalesce(max(v), 0)
FROM i WHERE i.k = o2.k) > 0.04` and `SELECT k, (SELECT
CAST(coalesce(max(CAST(v AS STRING)), 'x') AS INT) FROM i WHERE i.k = o2.k)
FROM o2`, fail while the query is optimized without this change. With it,
`executedPlan` succeeds and `collect()` fails with `DIVIDE_BY_ZERO` and
`CAST_INVALID_INPUT`. Could they be added to the list, with the expected
exception class and condition of each (the `CAST` one throws
`SparkNumberFormatException` with `CAST_INVALID_INPUT`)? That would also make
"the `DIVIDE_BY_ZERO` queries still fail with `DIVIDE_BY_ZERO`" in the
description hold for all four of them; the `WHERE` one is not in the list now.
--
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]