dongjoon-hyun commented on code in PR #60366:
URL: https://github.com/apache/spark/pull/60366#discussion_r4570413765


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -882,12 +921,29 @@ object DecorrelateInnerQuery extends PredicateHelper {
                     // left outer join.
                     a.toAttribute.withNullability(true)
                   case Some(default) =>
-                    assert(a.isInstanceOf[Alias], s"Cannot have non-aliased 
expression $a in " +
-                      s"aggregate that evaluates to non-null value with zero 
tuples.")
-                    val newAttr = a.newInstance()
-                    val ref = newAttr.toAttribute.withNullability(true)
-                    expressions += newAttr
-                    Alias(If(IsNull(alwaysTrueRef), default, ref), 
a.name)(a.exprId)
+                    val alias = a match {
+                      case alias: Alias => alias
+                      case _ =>
+                        throw SparkException.internalError(s"Cannot have 
non-aliased expression " +
+                          s"$a in aggregate that may not evaluate to null with 
zero tuples.")
+                    }
+                    if (hasScalarPythonUDFOverAggregate(alias.child)) {

Review Comment:
   **Behavior change:** Following up on 
https://github.com/apache/spark/pull/60366#discussion_r4568976018. Thank you 
for the measurements; I agree that the guard does not protect a Python UDF 
outside a correlated subquery. Still, `LATERAL (SELECT CASE WHEN COUNT(*) = 0 
THEN 0 ELSE udf(10 / COUNT(*)) END d FROM r WHERE l.a = r.c)` returns rows on 
master and fails with `DIVIDE_BY_ZERO` after this PR, and users who rely on it 
have no way back except rewriting the query.
   
   Since you offered, I'd still prefer a legacy config that keeps the 
`if(isnull(alwaysTrue), <default>, col)` rewrite for this branch, as 
`spark.sql.optimizer.decorrelateSubqueryLegacyIncorrectCountHandling.enabled` 
does for the earlier COUNT bug changes. Alternatively, the comment at L940 
sketches a way to avoid the regression without a config.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -871,8 +873,45 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
+              // Pull an aggregate function out as its own column of the 
aggregate, corrected for
+              // the count bug: `if(isnull(alwaysTrue), <default>, <ref>)`, or 
just `<ref>` when
+              // its result on zero rows is NULL. Used to rebuild a column 
over aggregate
+              // functions above the join, see the Python UDF case below.
+              def pullOutAggregate(ae: AggregateExpression): Expression = {
+                val alias = Alias(ae, ae.aggregateFunction.prettyName)()
+                expressions += alias
+                // The attribute is nullable since it is from the right-hand 
side of a left
+                // outer join.
+                val ref = alias.toAttribute.withNullability(true)
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction) 
match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
+                }
+              }
+              // Replace every aggregate function in an expression with its 
count-bug-corrected
+              // column, leaving the rest of the expression in place, so that 
it can be computed
+              // above the left outer join. Does not descend into an aggregate 
function (handled
+              // as a whole) and leaves a nested subquery untouched.
+              def pullOutAggregates(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOutAggregate(ae)
+                case other => other.mapChildren(pullOutAggregates)
+              }
+              // Whether a column applies a scalar Python UDF to an aggregate 
function's result,
+              // e.g. `inv(count(*))` or `CASE WHEN count(*) = 0 THEN 0 ELSE 
inv(count(*)) END`.
+              // Such a UDF is evaluated on the values over zero rows (see the 
case below). Unlike
+              // `ExtractPythonUDFFromAggregate.hasPythonUdfOverAggregate`, 
this stops at an
+              // aggregate function, so a Python UDF inside an aggregate 
function's argument, e.g.
+              // `count(udf(v))`, does not count: it is replaced along with 
the function by its
+              // result over zero rows and is never lifted out of a branch.
+              def hasScalarPythonUDFOverAggregate(e: Expression): Boolean = e 
match {

Review Comment:
   **Scope:** The name and the comment say a UDF applied to an aggregate 
function's result, but this returns true for any scalar Python UDF outside an 
aggregate function, whether or not it reads an aggregate.
   
   For example, in `CASE WHEN count(*) = 0 THEN 0 ELSE count(*) + f(o.k) END`, 
`f` does not read `count(*)`, yet the column is pulled out. On master the 
zero-row result simplifies to `0`; with this PR, `ExtractPythonUDFs` lifts 
`f(i.k)` (`o.k` replaced by its inner equivalent) out of the `CASE` and calls 
it as `f(NULL)` for an outer row without matching rows.
   
   Narrowing it to a UDF whose subtree contains an `AggregateExpression` would 
keep the master plan for such a guarded column, though it would also keep the 
master plan for an unguarded `count(*) + f(o.k)`. Either way is fine with me, 
but could you settle it explicitly, and make the comment and the migration 
guide describe whichever scope the code has?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -958,6 +980,11 @@ object RewriteCorrelatedScalarSubquery extends 
Rule[LogicalPlan] with AliasHelpe
 
             if (havingNode.isEmpty) {
               // CASE 2: Subquery with no HAVING clause
+              // TODO(SPARK-61660): when `resultWithZeroTups` applies a scalar 
Python UDF to an

Review Comment:
   **Consistency:** Thank you for filing SPARK-61660. Until it lands, the two 
paths behave in opposite ways for the same expression:
   - An unguarded `inv(count(*))` fails as a single top-level aggregate, 
`(SELECT inv(count(*)) FROM b WHERE b.k = a.k)`, but works in `LATERAL`.
   - A guarded `CASE WHEN count(*) = 0 THEN 0 ELSE inv(10 / count(*)) END` 
keeps working as a single top-level aggregate, but fails in `LATERAL` or 
`(SELECT d FROM (SELECT ... d ...))`.
   
   Since SPARK-61660 will bring the same behavior change to this path, could it 
land in the same release, so that one migration guide entry describes both 
paths? Otherwise the entry needs another update later, and users see the 
guarded case break in two steps.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -871,8 +873,45 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
+              // Pull an aggregate function out as its own column of the 
aggregate, corrected for
+              // the count bug: `if(isnull(alwaysTrue), <default>, <ref>)`, or 
just `<ref>` when
+              // its result on zero rows is NULL. Used to rebuild a column 
over aggregate
+              // functions above the join, see the Python UDF case below.
+              def pullOutAggregate(ae: AggregateExpression): Expression = {
+                val alias = Alias(ae, ae.aggregateFunction.prettyName)()
+                expressions += alias
+                // The attribute is nullable since it is from the right-hand 
side of a left
+                // outer join.
+                val ref = alias.toAttribute.withNullability(true)
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction) 
match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
+                }
+              }
+              // Replace every aggregate function in an expression with its 
count-bug-corrected
+              // column, leaving the rest of the expression in place, so that 
it can be computed
+              // above the left outer join. Does not descend into an aggregate 
function (handled
+              // as a whole) and leaves a nested subquery untouched.
+              def pullOutAggregates(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOutAggregate(ae)
+                case other => other.mapChildren(pullOutAggregates)
+              }
+              // Whether a column applies a scalar Python UDF to an aggregate 
function's result,
+              // e.g. `inv(count(*))` or `CASE WHEN count(*) = 0 THEN 0 ELSE 
inv(count(*)) END`.
+              // Such a UDF is evaluated on the values over zero rows (see the 
case below). Unlike
+              // `ExtractPythonUDFFromAggregate.hasPythonUdfOverAggregate`, 
this stops at an
+              // aggregate function, so a Python UDF inside an aggregate 
function's argument, e.g.
+              // `count(udf(v))`, does not count: it is replaced along with 
the function by its
+              // result over zero rows and is never lifted out of a branch.
+              def hasScalarPythonUDFOverAggregate(e: Expression): Boolean = e 
match {
+                case _: AggregateExpression => false
+                case _ if PythonUDF.isScalarPythonUDF(e) => true

Review Comment:
   **External UDF:** This checks only `PythonUDF.isScalarPythonUDF`. With 
`spark.sql.execution.udf.unified.execution.enabled`, an 
`ExternalUserDefinedFunction` seems to have the same problem: 
`PlanExternalUDFs.collectEvaluableUDFs` also descends into conditional 
branches, so for `LATERAL (SELECT ext_inv(count(*)) d FROM b WHERE b.k = a.k)`, 
`ext_inv(0)` in `if(isnull(alwaysTrue), ext_inv(0), d')` would be planned as an 
`ExecuteExternalUDF` for every row and fail even when every outer row has 
matching rows. Could you cover it here as well, or track it with a 
`TODO(SPARK-xxxxx)`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -871,8 +873,45 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
+              // Pull an aggregate function out as its own column of the 
aggregate, corrected for
+              // the count bug: `if(isnull(alwaysTrue), <default>, <ref>)`, or 
just `<ref>` when
+              // its result on zero rows is NULL. Used to rebuild a column 
over aggregate
+              // functions above the join, see the Python UDF case below.
+              def pullOutAggregate(ae: AggregateExpression): Expression = {
+                val alias = Alias(ae, ae.aggregateFunction.prettyName)()
+                expressions += alias
+                // The attribute is nullable since it is from the right-hand 
side of a left
+                // outer join.
+                val ref = alias.toAttribute.withNullability(true)
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction) 
match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
+                }
+              }
+              // Replace every aggregate function in an expression with its 
count-bug-corrected
+              // column, leaving the rest of the expression in place, so that 
it can be computed
+              // above the left outer join. Does not descend into an aggregate 
function (handled
+              // as a whole) and leaves a nested subquery untouched.
+              def pullOutAggregates(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOutAggregate(ae)
+                case other => other.mapChildren(pullOutAggregates)

Review Comment:
   **Outer reference (non-blocking, pre-existing):** An outer reference outside 
an aggregate function has already been replaced by an inner attribute here (its 
inner equivalent, e.g. `i.k` from `i.k = o.k`), which is NULL for an outer row 
without matching rows. So `LATERAL (SELECT inv(count(*) + o.k) d FROM i WHERE 
i.k = o.k)` computes `inv(if(isnull(alwaysTrue), 0, count) + i.k)`, i.e. 
`inv(NULL)`, for such a row, while the subquery over zero rows is `inv(0 + 
o.k)`.
   
   master has the same issue, since `evalAggExprOnZeroTups` replaces the 
attribute with NULL, so this is not a regression. But now that the expression 
is computed above the join, where the domain attribute (`x2` in the new tests) 
is available, it may be worth reading that instead, or at least leaving a TODO.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -882,12 +921,29 @@ object DecorrelateInnerQuery extends PredicateHelper {
                     // left outer join.
                     a.toAttribute.withNullability(true)
                   case Some(default) =>
-                    assert(a.isInstanceOf[Alias], s"Cannot have non-aliased 
expression $a in " +
-                      s"aggregate that evaluates to non-null value with zero 
tuples.")
-                    val newAttr = a.newInstance()
-                    val ref = newAttr.toAttribute.withNullability(true)
-                    expressions += newAttr
-                    Alias(If(IsNull(alwaysTrueRef), default, ref), 
a.name)(a.exprId)
+                    val alias = a match {
+                      case alias: Alias => alias
+                      case _ =>
+                        throw SparkException.internalError(s"Cannot have 
non-aliased expression " +
+                          s"$a in aggregate that may not evaluate to null with 
zero tuples.")
+                    }
+                    if (hasScalarPythonUDFOverAggregate(alias.child)) {
+                      // A scalar Python UDF applied to an aggregate function, 
e.g. `inv(count(*))`.
+                      // Building `if(isnull(alwaysTrue), <default>, <ref>)` 
as in the else branch
+                      // would put the zero-row result `<default>`, e.g. 
`inv(0)`, in a conditional
+                      // branch, and `ExtractPythonUDFs` lifts a Python UDF 
out of a branch and
+                      // evaluates it for every row, so it would run on the 
zero-row values even for
+                      // an outer row with matching rows and could fail there 
(e.g. division by
+                      // zero). Instead pull every aggregate function out as 
its own corrected
+                      // column and compute the expression, including the UDF, 
above the join on
+                      // those corrected values.
+                      alias.withNewChild(pullOutAggregates(alias.child))

Review Comment:
   **Design question:** What do you think about deciding on the zero-row result 
instead of the column? `default` here still holds the Python UDF unfolded, e.g. 
`CASE WHEN 0 = 0 THEN 0 ELSE udf(10 / 0) END` for the guarded column. If it 
were simplified first (e.g. `ConstantFolding` and `SimplifyConditionals` 
applied to it) and the pull-out were used only when a Python UDF remains in it:
   - `inv(count(*))` keeps `inv(0)` and is pulled out, as this PR does.
   - `CASE WHEN count(*) = 0 THEN 0 ELSE udf(10 / count(*)) END` simplifies to 
`0` and keeps the master rewrite, so it keeps working without a legacy config.
   
   The same check on what survives in the zero-row result could also cover 
`ExternalUserDefinedFunction` (L908) with one predicate. The trade-off is 
applying those expression rules here, which may not be worth it; I'd like to 
hear your thoughts.



##########
docs/sql-migration-guide.md:
##########
@@ -100,6 +100,7 @@ license: |
 - Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT` 
adds to a Data Source V2 table, and whose condition reads the current time, 
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db = 
current_database()`, is checked against their values at the time of each write. 
Previously, it was checked against their values at the time of the `ALTER 
TABLE`, unless a write could not read back a predicate for its condition, such 
as one with a lambda function or one that passes a column to `datediff`, `year` 
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so 
each write parses and analyzes its SQL text under the session of the write, as 
it does for a constraint without a predicate that `CREATE TABLE` adds. A 
setting of the write such as `spark.sql.ansi.enforceReservedKeywords`, which 
reserves `TIME`, or `spark.sql.ansi.doubleQuotedIdentifiers` can then make it 
fail to parse the text or read it differently. A row-level operation
  that copies unchanged rows, such as a `DELETE` or `UPDATE` on a copy-on-write 
table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row that no longer 
satisfies the condition. For example, `ts >= current_timestamp() - INTERVAL 30 
DAYS` now fails such a `DELETE` once a copied row is older than 30 days. A 
condition that Spark detects a write could resolve differently is stored as 
before, so a write accepts and rejects the same rows for it as before. Examples 
are conditions that also read a variable, a `CHAR` column, a name with more 
than one part such as a column qualified by the table name, or a constant that 
depends on the session time zone, such as `'2024-01-01 00:00:00'` cast to a 
timestamp. So are conditions with a name such as `current_date` or `user` 
without parentheses, which a write can read as a column name, and conditions 
whose text the parser settings of the `ALTER TABLE`, such as 
`spark.sql.ansi.doubleQuotedIdentifiers` or 
`spark.sql.parser.escapedStringLiterals`, r
 ead differently from their default values. ANSI mode, 
`spark.sql.timestampType` and the session time zone are taken from the session 
for this comparison, as for a generation expression. A condition that reads the 
current date or time only through a typed literal such as `DATE 'today'` is 
also stored as before. An existing constraint keeps its stored predicate until 
it is dropped and added again. `Check.predicate()` is null for a constraint 
stored without a predicate, so a connector that validates or enforces it itself 
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set 
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding 
the constraint. A constraint added without it is not changed.
 - Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'` 
whose class implements 
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends 
either a Hive UDF class (such as `UDF` or `GenericUDF`) or 
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a 
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions 
created in earlier versions. Its result type, argument coercion, and null 
handling are defined by the V2 implementation selected by 
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic` 
property do not control the V2 path. For scalar functions, determinism uses 
`BoundFunction.isDeterministic()` (default `true`) and the arguments' 
determinism. A call with constant arguments can therefore become eligible for 
constant folding during query planning instead of being evaluated per row.
 - Since Spark 4.4, `next_day` and `last_day` fail with `DATETIME_OVERFLOW` 
when the result is later than the maximum `DATE`, `+5881580-07-11`, and `trunc` 
fails with it when the result is earlier than the minimum `DATE`, 
`-5877641-06-23`, regardless of `spark.sql.ansi.enabled`. Previously, these 
functions silently returned a wrong date, in most cases one at the other end of 
the `DATE` range; for example, `last_day(DATE'+5881580-07-11')` returned 
`-5877641-07-12` and `trunc(DATE'-5877641-06-23', 'MONTH')` returned 
`+5881580-06-20`, while `trunc` to `QUARTER` failed with `ARITHMETIC_OVERFLOW`. 
`next_day` and `trunc` to `WEEK` also returned a wrong date for the first days 
of the `DATE` range; for example, `next_day(DATE'-5877641-06-23', 'MO')` and 
`trunc(DATE'-5877641-07-01', 'WEEK')` returned `-5877641-06-25`, a Thursday, 
and now return `-5877641-06-29`.
+- Since Spark 4.4, in a correlated `LATERAL` subquery, or a scalar subquery 
whose COUNT bug `DecorrelateInnerQuery` handles (that is, not a single 
top-level aggregate), a scalar Python UDF applied to an aggregate function of 
an aggregate without `GROUP BY`, such as `inv(count(*))` where `inv` divides by 
its argument, is evaluated once per distinct value of the correlated columns, 
above the left outer join, on that row's aggregate values. A query whose outer 
rows all have matching rows no longer fails: previously the UDF applied to the 
result over zero rows, such as `inv(0)`, was kept in a conditional branch and, 
because Spark evaluates a Python UDF in a conditional branch for every row, it 
was evaluated even on the outer rows that have matching rows. For an outer row 
without matching rows the UDF is now evaluated on the aggregate functions' 
results over zero rows, so a query that relied on guarding such a UDF, for 
example `CASE WHEN count(*) = 0 THEN 0 ELSE inv(10 / count(*)) END`, 
 can now fail there: with `DIVIDE_BY_ZERO` in ANSI mode, or by calling the UDF 
with the values over zero rows (e.g. `NULL` for `max`) without ANSI mode. This 
matches the same subquery without correlation, and a guarded Python UDF outside 
any subquery, which already fail this way; previously the correlated form's 
result over zero rows was simplified to the guarded constant by the optimizer. 
A scalar subquery that is a single top-level aggregate, such as `(SELECT 
inv(count(*)) FROM b WHERE b.k = a.k)`, is not affected.

Review Comment:
   **Migration guide:** A few points on the scope:
   - `DecorrelateInnerQuery` also handles the COUNT bug of an `IN` subquery, 
which the PR description lists as affected, but this entry mentions only 
`LATERAL` and scalar subqueries.
   - "(that is, not a single top-level aggregate)" is broader than the code. 
For a scalar subquery whose top is an `Aggregate`, `DecorrelateInnerQuery` 
handles the COUNT bug only when a lower aggregate without `GROUP BY` has a 
function with a non-NULL result over zero rows (`mayHaveCountBugAgg`), so e.g. 
`SELECT SUM(d) FROM (SELECT inv(max(v)) d FROM b WHERE b.k = a.k)` is not 
affected. It also depends on 
`spark.sql.optimizer.decorrelateInnerQuery.enabled` and 
`spark.sql.legacy.scalarSubqueryCountBugBehavior` (and 
`spark.sql.optimizer.decorrelateExistsSubqueryLegacyIncorrectCountHandling.enabled`
 for `IN`).
   - If a legacy config is added (see L930), a "To restore the previous 
behavior, set ..." sentence, like the other entries.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -871,8 +873,45 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
+              // Pull an aggregate function out as its own column of the 
aggregate, corrected for
+              // the count bug: `if(isnull(alwaysTrue), <default>, <ref>)`, or 
just `<ref>` when
+              // its result on zero rows is NULL. Used to rebuild a column 
over aggregate
+              // functions above the join, see the Python UDF case below.
+              def pullOutAggregate(ae: AggregateExpression): Expression = {
+                val alias = Alias(ae, ae.aggregateFunction.prettyName)()
+                expressions += alias
+                // The attribute is nullable since it is from the right-hand 
side of a left
+                // outer join.
+                val ref = alias.toAttribute.withNullability(true)
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction) 
match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
+                }
+              }
+              // Replace every aggregate function in an expression with its 
count-bug-corrected
+              // column, leaving the rest of the expression in place, so that 
it can be computed
+              // above the left outer join. Does not descend into an aggregate 
function (handled
+              // as a whole) and leaves a nested subquery untouched.
+              def pullOutAggregates(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOutAggregate(ae)

Review Comment:
   **Nit:** Each occurrence of an aggregate function is pulled out on its own, 
so `CASE WHEN count(*) = 0 THEN 0 ELSE udf(10 / count(*)) END` or 
`udf(count(*), count(*))` adds two `count(1)` columns and two `If`s. I 
understand the deduplication was dropped on purpose in the rework, and 
`PhysicalAggregation` merges deterministic ones physically, so this only 
affects the logical plan and the domain join's input width. Feel free to ignore 
if you prefer to keep it simple.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuerySuite.scala:
##########
@@ -830,4 +831,177 @@ class DecorrelateInnerQuerySuite extends PlanTest {
       check(outputPlan, joinCond, correctAnswer, Seq(a < b))
     }
   }
+
+  test("SPARK-61482: COUNT bug handling pulls an aggregate function out of a 
Python UDF") {

Review Comment:
   **Test coverage:** The new catalyst tests use a UDF directly over aggregate 
functions. Could you add plan tests for the other shapes whose plan this PR 
changes: a UDF in a branch guarded by an aggregate value (`CASE WHEN cnt = 0 
THEN 0 ELSE udf(10 / cnt) END`), and a UDF outside any aggregate function, e.g. 
`cnt + udf(OuterReference(x))` (see L906 and L897)? They need no Python, and 
would pin the scope of `hasScalarPythonUDFOverAggregate` whichever way it is 
settled.



##########
sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala:
##########
@@ -3401,4 +3402,171 @@ class SubquerySuite extends SharedSparkSession
         Row(1, 2))
     }
   }
+
+  test("SPARK-61444: COUNT bug with a result on zero rows that fails to 
evaluate") {
+    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")
+      // The outer row k = 3 of o2 has no matching rows and uses the result on 
zero rows. The query
+      // is still optimized and planned, and fails when it runs.
+      def checkFailsAtRuntime[T <: SparkThrowable : ClassTag](
+          query: String,
+          condition: String): Unit = withClue(query) {
+        val df = sql(query)
+        df.queryExecution.executedPlan
+        val e = intercept[T](df.collect())
+        assert(e.getCondition === condition)
+      }
+
+      withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+        // 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, 
handled in
+        // DecorrelateInnerQuery with the default confs.
+        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)
+        // LATERAL, EXISTS and IN subqueries, also handled in 
DecorrelateInnerQuery.
+        checkAnswer(
+          sql("SELECT o.k, t.d FROM o, " +
+            "LATERAL (SELECT 10 / coalesce(max(i.v), 0) d FROM i WHERE i.k = 
o.k) t"),
+          Row(1, 0.05) :: Row(2, 10.0 / 300) :: Nil)
+        checkAnswer(
+          sql("SELECT k FROM o WHERE " +
+            "EXISTS (SELECT 10 / coalesce(max(v), 0) FROM i WHERE i.k = o.k)"),
+          Row(1) :: Row(2) :: Nil)
+        checkAnswer(
+          sql("SELECT k FROM o WHERE " +
+            "5 IN (SELECT 1000 / coalesce(max(v), 0) FROM i WHERE i.k = o.k)"),
+          Row(1) :: Nil)
+
+        // A grouped subquery and EXISTS don't use the result on zero rows, so 
they don't fail
+        // for the outer row k = 3 of o2 either.
+        checkAnswer(
+          sql("SELECT k, (SELECT 10 / coalesce(max(v), 0) FROM i WHERE i.k = 
o2.k GROUP BY i.k) " +
+            "FROM o2"),
+          Row(1, 0.05) :: Row(2, 10.0 / 300) :: Row(3, null) :: Nil)
+        checkAnswer(
+          sql("SELECT k FROM o2 WHERE " +
+            "EXISTS (SELECT 10 / coalesce(max(v), 0) FROM i WHERE i.k = 
o2.k)"),
+          Row(1) :: Row(2) :: Row(3) :: Nil)
+
+        Seq(
+          "SELECT k, (SELECT 10 / coalesce(max(v), 0) FROM i WHERE i.k = o2.k) 
FROM o2",
+          "SELECT k FROM o2 WHERE (SELECT 10 / coalesce(max(v), 0) FROM i 
WHERE i.k = o2.k) " +
+            "> 0.04",
+          "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",
+          "SELECT o2.k, t.d FROM o2, " +
+            "LATERAL (SELECT 10 / coalesce(max(i.v), 0) d FROM i WHERE i.k = 
o2.k) t",
+          "SELECT k FROM o2 WHERE " +
+            "5 IN (SELECT 1000 / coalesce(max(v), 0) FROM i WHERE i.k = o2.k)"
+        ).foreach(checkFailsAtRuntime[SparkArithmeticException](_, 
"DIVIDE_BY_ZERO"))
+        checkFailsAtRuntime[SparkNumberFormatException](
+          "SELECT k, (SELECT CAST(coalesce(max(CAST(v AS STRING)), 'x') AS 
INT) " +
+            "FROM i WHERE i.k = o2.k) FROM o2",
+          "CAST_INVALID_INPUT")
+
+        // Without DecorrelateInnerQuery, the HAVING clause is handled in CASE 
3 of
+        // RewriteCorrelatedScalarSubquery.constructLeftJoins.
+        withSQLConf(SQLConf.DECORRELATE_INNER_QUERY_ENABLED.key -> "false") {
+          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)
+          checkFailsAtRuntime[SparkArithmeticException](
+            "SELECT k, (SELECT count(*) FROM i WHERE i.k = o2.k HAVING 10 / 
count(*) > 0) " +
+              "FROM o2",
+            "DIVIDE_BY_ZERO")
+        }
+      }
+
+      // An expression can also fail to evaluate with ANSI mode off.
+      withSQLConf(SQLConf.ANSI_ENABLED.key -> "false") {
+        checkAnswer(
+          sql("SELECT k, (SELECT element_at(array(1, 2), CAST(count(v) AS 
INT)) FROM i " +
+            "WHERE i.k = o.k) FROM o"),
+          Row(1, 2) :: Row(2, 1) :: Nil)
+        checkFailsAtRuntime[SparkRuntimeException](
+          "SELECT k, (SELECT element_at(array(1, 2), CAST(count(v) AS INT)) 
FROM i " +
+            "WHERE i.k = o2.k) FROM o2",
+          "INVALID_INDEX_OF_ZERO")
+      }
+    }
+  }
+
+  test("SPARK-61482: COUNT bug of a lower aggregate with a PythonUDF over 
aggregate functions") {
+    import IntegratedUDFTestUtils._
+
+    assume(shouldTestPythonUDFs)
+
+    val pythonTestUDF = TestPythonUDF(name = "udf")
+    registerTestUDF(pythonTestUDF, spark)
+
+    // `ml` keeps only the rows of `l` with matching rows in `r`. The Python 
UDF is evaluated
+    // once per row on the value of that row, and not also on the result over 
zero tuples,
+    // `udf(10 / 0)`. Without this change the UDF is lifted out of the 
conditional branch by
+    // `ExtractPythonUDFs` and evaluated on `10 / 0` for every row, failing in 
ANSI mode.
+    withTempView("ml") {
+      sql("CREATE TEMPORARY VIEW ml AS SELECT * FROM l WHERE a > 1")
+      withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+        checkAnswer(
+          sql("SELECT l.a, (SELECT SUM(d) FROM (SELECT udf(10 / COUNT(*)) d 
FROM r " +
+            "WHERE l.a = r.c)) FROM ml l"),
+          Row(2, 5.0) :: Row(2, 5.0) :: Row(3, 10.0) :: Row(6, 10.0) :: Nil)
+        checkAnswer(
+          sql("SELECT l.a, t.d FROM ml l, LATERAL (SELECT udf(10 / COUNT(*)) d 
FROM r " +
+            "WHERE l.a = r.c) t"),
+          Row(2, 5.0) :: Row(2, 5.0) :: Row(3, 10.0) :: Row(6, 10.0) :: Nil)
+      }
+    }
+    checkAnswer(
+      sql("SELECT l.a, (SELECT SUM(d) FROM (SELECT udf(COUNT(*)) + 1 d FROM r 
" +
+        "WHERE l.a = r.c)) FROM l"),
+      Row(1, 1L) :: Row(1, 1L) :: Row(2, 3L) :: Row(2, 3L) :: Row(3, 2L) ::
+        Row(null, 1L) :: Row(null, 1L) :: Row(6, 2L) :: Nil)
+  }
+
+  test("SPARK-61482: a Python UDF guarded by an aggregate value has its 
argument evaluated " +
+    "on the zero-row values for an outer row without matching rows") {
+    import IntegratedUDFTestUtils._
+
+    assume(shouldTestPythonUDFs)
+
+    registerTestUDF(TestPythonUDF(name = "udf"), spark)
+
+    // Behavior change: the UDF column is rebuilt above the domain join, so 
`ExtractPythonUDFs`
+    // lifts the UDF argument out of the `CASE` branch and evaluates it for 
every outer row,
+    // including rows without matching rows, where the aggregate's value over 
zero rows is used.
+    // This matches the uncorrelated form, which already evaluates the 
argument eagerly, but it
+    // turns a query that worked before into a failing one. In ANSI mode the 
lifted argument
+    // `10 / 0` fails at runtime for such a row.
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      val df = sql("SELECT l.a, t.d FROM l, LATERAL (SELECT " +
+        "CASE WHEN COUNT(*) = 0 THEN 0 ELSE udf(10 / COUNT(*)) END d FROM r 
WHERE l.a = r.c) t")
+      df.queryExecution.optimizedPlan

Review Comment:
   **Nit:** The result of `df.queryExecution.optimizedPlan` is not used. If the 
intent is to show that the query is optimized without errors and fails only at 
runtime, a short comment would make that clear; otherwise it can be removed.
   
   ```suggestion
         // The query is optimized without errors; it fails only at runtime.
         df.queryExecution.optimizedPlan
   ```



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -871,8 +873,45 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
+              // Pull an aggregate function out as its own column of the 
aggregate, corrected for
+              // the count bug: `if(isnull(alwaysTrue), <default>, <ref>)`, or 
just `<ref>` when
+              // its result on zero rows is NULL. Used to rebuild a column 
over aggregate
+              // functions above the join, see the Python UDF case below.
+              def pullOutAggregate(ae: AggregateExpression): Expression = {

Review Comment:
   **Reuse:** Pulling the aggregates of a UDF column into the `Aggregate` and 
computing the rest above it is also what 
`ExtractPythonUDFFromAggregate.extract` and 
`PlanExternalUDFs.extractExternalUDFFromAggregate` do, and each of the three 
has its own rule for when a UDF is over an aggregate: `references.isEmpty || 
exists(belongAggregate)` in the other two, and any UDF outside an aggregate 
function here. I understand why this one stops at an aggregate function, but a 
shared predicate, at least for the Python and external UDF cases, would keep 
them from drifting apart when one of them changes.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -871,8 +873,45 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
+              // Pull an aggregate function out as its own column of the 
aggregate, corrected for
+              // the count bug: `if(isnull(alwaysTrue), <default>, <ref>)`, or 
just `<ref>` when
+              // its result on zero rows is NULL. Used to rebuild a column 
over aggregate
+              // functions above the join, see the Python UDF case below.
+              def pullOutAggregate(ae: AggregateExpression): Expression = {
+                val alias = Alias(ae, ae.aggregateFunction.prettyName)()
+                expressions += alias
+                // The attribute is nullable since it is from the right-hand 
side of a left
+                // outer join.
+                val ref = alias.toAttribute.withNullability(true)
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction) 
match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
+                }
+              }
+              // Replace every aggregate function in an expression with its 
count-bug-corrected
+              // column, leaving the rest of the expression in place, so that 
it can be computed
+              // above the left outer join. Does not descend into an aggregate 
function (handled
+              // as a whole) and leaves a nested subquery untouched.
+              def pullOutAggregates(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOutAggregate(ae)
+                case other => other.mapChildren(pullOutAggregates)
+              }
+              // Whether a column applies a scalar Python UDF to an aggregate 
function's result,
+              // e.g. `inv(count(*))` or `CASE WHEN count(*) = 0 THEN 0 ELSE 
inv(count(*)) END`.
+              // Such a UDF is evaluated on the values over zero rows (see the 
case below). Unlike
+              // `ExtractPythonUDFFromAggregate.hasPythonUdfOverAggregate`, 
this stops at an
+              // aggregate function, so a Python UDF inside an aggregate 
function's argument, e.g.
+              // `count(udf(v))`, does not count: it is replaced along with 
the function by its
+              // result over zero rows and is never lifted out of a branch.
+              def hasScalarPythonUDFOverAggregate(e: Expression): Boolean = e 
match {
+                case _: AggregateExpression => false
+                case _ if PythonUDF.isScalarPythonUDF(e) => true
+                case _ => e.children.exists(hasScalarPythonUDFOverAggregate)

Review Comment:
   **Nit:** This walks the whole expression of every count-bug column, 
including the common case without any Python UDF. A tree-pattern check would 
skip it there:
   
   ```scala
                 def hasScalarPythonUDFOverAggregate(e: Expression): Boolean =
                   e.containsPattern(PYTHON_UDF) && (e match {
                     case _: AggregateExpression => false
                     case _ if PythonUDF.isScalarPythonUDF(e) => true
                     case _ => 
e.children.exists(hasScalarPythonUDFOverAggregate)
                   })
   ```
   
   with `PYTHON_UDF` added to the `TreePattern` import.



-- 
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]

Reply via email to