sarutak commented on code in PR #60366:
URL: https://github.com/apache/spark/pull/60366#discussion_r4568975645


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -752,20 +752,27 @@ object RewriteCorrelatedScalarSubquery extends 
Rule[LogicalPlan] with AliasHelpe
     // in the expression with the value they would return for zero input 
tuples.
     // Also replace attribute refs (for example, for grouping columns) with 
NULL.
     val rewrittenExpr = expr transform {
-      case a @ AggregateExpression(aggFunc, _, _, resultId, _) =>
-        aggFunc.defaultResult.getOrElse(Literal.create(null, aggFunc.dataType))
+      case AggregateExpression(aggFunc, _, _, _, _) => 
aggregateDefaultResult(aggFunc)
 
       case a: AttributeReference => Literal.create(null, a.dataType)
     }
 
     tryEvalExpr(rewrittenExpr)

Review Comment:
   Adopted, thank you; see the lead comment. SPARK-61444 (#60325) owns the 
`tryEvalExpr` fallback and
   this PR relies on it for every foldable expression on both paths, keeping 
the pull-out only for a
   Python UDF column. The `Filter` case of `evalSubqueryOnZeroTups` is also 
covered by #60325.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +872,84 @@ object DecorrelateInnerQuery extends PredicateHelper {
             // | 0 | null | null       | 0                              |  
<--- correct result
             // +---+------+------------+--------------------------------+
             if (groupingExpressions.isEmpty && handleCountBug) {

Review Comment:
   Added a `docs/sql-migration-guide.md` entry (under "Upgrading from Spark SQL 
4.3 to 4.4").
   
   I did not add a legacy config. I measured the behavior: a guarded Python UDF 
fails the same way
   without correlation and outside any subquery, so this is not a new failure 
mode but the removal of
   an exception. In ANSI mode on the base (master + #60325):
   - `SELECT CASE WHEN COUNT(*) = 0 THEN 0 ELSE udf(10 / COUNT(*)) END FROM r 
WHERE r.c = 99`
     (uncorrelated, zero matching rows) fails with `DIVIDE_BY_ZERO`.
   - `SELECT CASE WHEN x = 0 THEN 0 ELSE udf(10 / x) END FROM VALUES (0), (2) 
AS t(x)` (no subquery)
     fails with `DIVIDE_BY_ZERO` on the `x = 0` row.
   
   `ExtractPythonUDFs` lifts a Python UDF out of a conditional branch 
everywhere, so the guard never
   protects a Python UDF; the correlated subquery only looked like it did 
because its result over
   zero rows was folded to the guarded constant while the query was optimized. 
The reworked PR also
   narrows the change from "every subquery whose COUNT bug 
`DecorrelateInnerQuery` handles" to "a
   column with a Python UDF over aggregate functions", so the plan-change scope 
you mentioned is much
   smaller now. A legacy config would restore the fold for the correlated form 
only, re-introducing
   the `inv(COUNT(*))` failure for every outer row that this PR fixes, while 
still not making the
   guard work elsewhere. I think documenting it is right, but I am happy to add 
a config if you
   prefer.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuerySuite.scala:
##########
@@ -209,6 +210,116 @@ class DecorrelateInnerQuerySuite extends PlanTest {
     check(innerPlan, outerPlan, correctAnswer, Seq(x <=> x))
   }
 
+  test("SPARK-61482: COUNT bug handling evaluates only aggregate functions on 
zero tuples") {
+    val outerPlan = testRelation2
+    // Two separate `count(1)` instances with different `exprId`s, like two 
`COUNT(*)` in a
+    // query. They are canonically equal, so they are deduplicated into one 
output.
+    val cnt1 = count(Literal(1))
+    val cnt2 = count(Literal(1))
+    val maxB = max(b)
+    // Expressions over an aggregate function used twice and over one whose 
result over zero
+    // tuples is NULL, single aggregate functions (shared with the expressions 
above) whose
+    // results over zero tuples are not NULL and NULL, and a literal.
+    val d = Alias(cnt1 * 10L + cnt2, "d")()
+    val e = Alias(Coalesce(Seq(maxB, Literal(0))), "e")()
+    val c = Alias(count(Literal(1)), "c")()
+    val m = Alias(max(b), "m")()
+    val l = Alias(Literal(5), "l")()
+    val innerPlan =
+      Aggregate(Nil, Seq(d, e, c, m, l),
+        Filter(OuterReference(x) === a,
+          testRelation))
+    val (outputPlan, joinCond) =
+      DecorrelateInnerQuery(innerPlan, outerPlan.select(), handleCountBug = 
true)
+
+    val cntRes = Alias(cnt1, "count")()
+    val maxRes = Alias(maxB, "max")()
+    val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
+    val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
+    val maxRef = maxRes.toAttribute.withNullability(true)
+    // `c` shares `count`'s column, `m` shares `max`'s column, and the literal 
`l` is a constant
+    // in the Project above the join rather than a column of the Aggregate.
+    val cntValue = If(IsNull(alwaysTrueRef), Literal(0L),
+      cntRes.toAttribute.withNullability(true))
+    val x2 = x.newInstance()
+    val correctAnswer =
+      Project(Seq(
+          Alias(cntValue * 10L + cntValue, "d")(d.exprId),
+          Alias(Coalesce(Seq(maxRef, Literal(0))), "e")(e.exprId),
+          Alias(cntValue, "c")(c.exprId),
+          Alias(maxRef, "m")(m.exprId),
+          Alias(Literal(5), "l")(l.exprId),
+          x2),
+        DomainJoin(Seq(x2),
+          Aggregate(Seq(a), Seq(cntRes, maxRes, a, alwaysTrue),
+            testRelation),
+          LeftOuter,
+          Some(x2 === a)))
+    check(outputPlan, joinCond, correctAnswer, Seq(x2 <=> x))
+  }
+
+  test("SPARK-61482: COUNT bug handling does not deduplicate non-deterministic 
aggregates") {

Review Comment:
   Both are about the deduplication, which the reworked PR no longer has (there 
is no shared
   pulled-out column), so neither test is needed. Each aggregate function in a 
Python UDF column is
   pulled out on its own.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +872,84 @@ object DecorrelateInnerQuery extends PredicateHelper {
             // | 0 | null | null       | 0                              |  
<--- correct result
             // +---+------+------------+--------------------------------+
             if (groupingExpressions.isEmpty && handleCountBug) {
-              // Evaluate the aggregate expressions with zero tuples.
-              val resultMap = 
RewriteCorrelatedScalarSubquery.evalAggregateOnZeroTups(newAggregate)
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
-              // Create new aliases for aggregate expressions that have 
non-null default
-              // values and reconstruct the output with the `alwaysTrue` 
marker.
-              val projectList = newAggregate.aggregateExpressions.map { a =>
-                resultMap.get(a.exprId) match {
-                  // Aggregate expression is not subject to the count bug.
-                  case Some(Literal(null, _)) | None =>
-                    expressions += a
-                    // The attribute is nullable since it is from the 
right-hand side of a
-                    // 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)
+              // `ref` if `zeroTupsResult` is NULL, or
+              // `if(isnull(alwaysTrue), zeroTupsResult, ref)` otherwise.
+              def withZeroTupsResult(zeroTupsResult: Expression, ref: 
Attribute): Expression =
+                zeroTupsResult match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
                 }
+              // Only the aggregate functions are evaluated with zero tuples, 
by taking their
+              // default results. An expression over them is computed above 
the left outer
+              // domain join on the corrected values, so that it is evaluated 
once per row on
+              // the value of that row, as for an outer row that has matching 
rows. Evaluating
+              // the whole expression with zero tuples instead fails at 
planning time if it
+              // throws (e.g. `10 / count(*)` in ANSI mode); and a Python UDF 
over them, which
+              // `ExtractPythonUDFs` lifts out of the conditional branch, 
would otherwise run at
+              // runtime for every outer row, including the rows whose 
subquery has matching rows.
+              //
+              // This pulls out every aggregate function, so an expression 
over several of them,
+              // e.g. `max(v) - min(v)`, carries one value per function into 
the domain join
+              // instead of one per column. Only an expression that contains a 
Python UDF needs
+              // the pull-out; for the others the same results could be kept 
by leaving the
+              // expression in the Aggregate and reading 
`if(isnull(alwaysTrue), <expression with
+              // each aggregate function replaced by its unfolded empty-input 
result>, column)`,
+              // which constant folding tolerates in the conditional branch. 
This single path is
+              // kept for simplicity; the alternative is a possible follow-up.
+              //
+              // TODO(SPARK-61444): 
`RewriteCorrelatedScalarSubquery.constructLeftJoins` still
+              // statically evaluates the whole zero-row result of a 
correlated scalar subquery,
+              // including subqueries whose count bug is handled here when it 
reaches their
+              // rewritten expression (e.g. under a Project with no top 
Aggregate), so such a
+              // subquery can still fail while the query is optimized (e.g. 
`10 / count(*)` in
+              // ANSI mode). SPARK-61444 addresses that path.
+              val pulledOut = mutable.HashMap.empty[Expression, Expression]
+              def pullOut(e: Expression, name: String, zeroTupsResult: 
Expression): Expression = {
+                def mk = {
+                  val alias = Alias(e, name)()
+                  expressions += alias
+                  // The attribute is nullable since it is from the right-hand 
side of a
+                  // left outer join.
+                  withZeroTupsResult(zeroTupsResult, 
alias.toAttribute.withNullability(true))
+                }
+                // Deduplicate deterministic expressions only, as 
`PhysicalAggregation` does: a
+                // non-deterministic aggregate function used more than once is 
computed once per
+                // use there, and sharing one column would make the uses take 
the same value.
+                if (e.deterministic) 
pulledOut.getOrElseUpdate(e.canonicalized, mk) else mk

Review Comment:
   Both are about the deduplication, which the reworked PR no longer has (there 
is no shared
   pulled-out column), so neither test is needed. Each aggregate function in a 
Python UDF column is
   pulled out on its own.



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