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


##########
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:
   **Migration guide:** Following up on the behavior-change thread at L948. The 
PR description now documents that a guarded Python UDF, e.g. `CASE WHEN 
COUNT(*) = 0 THEN 0 ELSE udf(10 / COUNT(*)) END` in a correlated `LATERAL` 
subquery, fails at runtime with `DIVIDE_BY_ZERO` for an outer row without 
matching rows, and `SubquerySuite` pins that failure. Since a query that works 
today fails after an upgrade, could you add an entry to 
`docs/sql-migration-guide.md` (under "Upgrading from Spark SQL 4.3 to 4.4", or 
the release this lands in)?
   
   It may also be worth a legacy config that restores the previous rewrite, as 
`spark.sql.optimizer.decorrelateSubqueryLegacyIncorrectCountHandling.enabled` 
and 
`spark.sql.optimizer.decorrelateExistsSubqueryLegacyIncorrectCountHandling.enabled`
 do for earlier COUNT-bug changes. This branch changes the plan of every 
subquery whose COUNT bug it handles, so a config would give users a way back if 
another case like the one above shows up.



##########
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:
   **Test coverage:** The deduplication is keyed by `e.canonicalized`, so it 
relies on `AggregateExpression.canonicalized` keeping `isDistinct` and `filter` 
apart. The new tests only use two `count(1)`. Could you add a case such as 
`COUNT(r.d)`, `COUNT(DISTINCT r.d)` and `COUNT(r.d) FILTER (WHERE r.d > 1)` in 
the same correlated `LATERAL` subquery, which must stay three columns with 
different values? That would catch a later change of the key or of the 
canonicalization that merges them.



##########
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:
   **Test coverage:** This guard is tested only with `sum(rand(1))`, which 
cannot pass analysis, so the test inspects a plan that no query produces. In 
the earlier thread you verified that a non-deterministic UDAF with 
deterministic arguments (e.g. registered with `asNondeterministic()`) used 
twice keeps two aggregate expressions in the optimized plan of a scalar 
subquery over a lower `Aggregate` and of an `IN` subquery. Could you add that 
as a `SubquerySuite` test? It would pin that a real query reaches this guard, 
so that the guard is not later dropped or changed as if it were only defensive.



##########
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:
   **Design question:** I see the `TODO(SPARK-61444)` for `constructLeftJoins`. 
The planning-time failures on both paths come from this `tryEvalExpr`, which 
calls `expr.eval()` on a foldable zero-row expression without error handling. 
What do you think about handling it here instead, by returning the unevaluated 
expression on `NonFatal`, as `ConstantFolding.tryFold` does for a conditional 
branch?
   
   The zero-row result ends up in a conditional branch: `If(IsNull(alwaysTrue), 
...)` in `DecorrelateInnerQuery` (before this PR) and in CASE 2 of 
`constructLeftJoins`, and the `CaseWhen` in CASE 3. So `10 / COUNT(*)` would 
fail only at runtime for an outer row without matching rows on both paths, 
including `(SELECT 10 / COUNT(*) FROM b WHERE b.k = a.k)`, which the PR 
description says still fails while it is optimized. Then, as the comment at 
DecorrelateInnerQuery.scala L894-901 says, only an expression with a Python UDF 
would need the pull-out, and the other expressions would keep their plans and 
the domain join's width. (The `Filter` case of `evalSubqueryOnZeroTups` also 
calls `bindCondition.eval()` and would need the same treatment.)



##########
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 = {

Review Comment:
   **Simplification:** `pullOut` takes a generic `Expression` and a separate 
zero-row result, but both callers (L927 and L944) pass an `AggregateExpression` 
and `zeroTupsResult(ae)`. `withZeroTupsResult` has one caller (L916), and 
`zeroTupsResult` names three things: the def at L923 and the parameters at L880 
and L910, which shadow it. How about narrowing it to the aggregate function and 
building the `If` inside?
   
   ```scala
   def pullOut(ae: AggregateExpression, name: String): Expression = {
     def mk = {
       val alias = Alias(ae, name)()
       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)
       }
     }
     // Deduplicate deterministic expressions only, ...
     if (ae.deterministic) pulledOut.getOrElseUpdate(ae.canonicalized, mk) else 
mk
   }
   ```
   
   The callers become `pullOut(ae, ae.aggregateFunction.prettyName)` and 
`pullOut(ae, a.name)`, and `withZeroTupsResult` and the `zeroTupsResult` def go 
away.



##########
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
+              }
+              def zeroTupsResult(ae: AggregateExpression): Literal =
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction)
+              def rewrite(e: Expression): Expression = e match {
+                case ae: AggregateExpression =>
+                  pullOut(ae, ae.aggregateFunction.prettyName, 
zeroTupsResult(ae))
+                // A grouping-less Aggregate cannot reference an attribute 
outside an aggregate
+                // function (the analyzer rejects it), so this is unreachable 
from a query. Fail
+                // rather than silently take NULL, as the `case a =>` below 
does.

Review Comment:
   **Nit:** "as the `case a =>` below does" can be read as the `case a =>` 
branch silently taking NULL, while it also throws `internalError`. How about:
   
   ```suggestion
                   // function (the analyzer rejects it), so this is 
unreachable from a query. Fail,
                   // like the `case a =>` below, rather than silently take 
NULL.
   ```



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

Review Comment:
   **Reuse:** This says it deduplicates "as `PhysicalAggregation` does", but it 
reimplements the rule with a `HashMap` keyed by `canonicalized` and an 
`e.deterministic` check. `PhysicalAggregation` uses 
`EquivalentExpressions.addExpr`, which also skips what `supportedExpression` 
rejects, e.g. an expression containing a `LambdaVariable` (as in `MapObjects`) 
or a `CommonExpressionDef`. Such a deterministic aggregate function is shared 
here but computed once per use there. The result is the same, but the two rules 
can drift apart while the comment says they match. Could you reuse 
`EquivalentExpressions` here, or reword the comment to describe what this does 
(deduplicating deterministic aggregate functions by canonical form)?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -855,8 +857,12 @@ object DecorrelateInnerQuery extends PredicateHelper {
             // If an aggregate is subject to the COUNT bug:
             // 1) add a column `true AS alwaysTrue` to the result of the 
aggregate
             // 2) insert a left outer domain join between the outer query and 
this aggregate
-            // 3) rewrite the original aggregate's output column using the 
default value of the
-            //    aggregate function and the alwaysTrue column.
+            // 3) above the join, rebuild each output column from the 
corrected value of each
+            //    aggregate function it uses: for an outer row with no 
matching rows, which
+            //    `alwaysTrue` being null marks, the function takes its 
default value (e.g. 0 for
+            //    `count`). A single aggregate function becomes 
`if(isnull(alwaysTrue), default,
+            //    col)`, as the example below shows; an expression over 
aggregate functions, or a
+            //    literal, is computed above the join from those corrected 
values.

Review Comment:
   **Stale comment:** Step 3 says a single aggregate function becomes 
`if(isnull(alwaysTrue), default, col)`, but `withZeroTupsResult` keeps `col` as 
is when the default is NULL, so `max(b) AS m` reads just the pulled-out `max` 
column, as the new `DecorrelateInnerQuerySuite` test expects. It also says a 
literal is computed "from those corrected values", though a literal does not 
use them. How about:
   
   ```suggestion
               //    `count`). A single aggregate function becomes 
`if(isnull(alwaysTrue), default,
               //    col)`, as the example below shows, or stays `col` if its 
default is NULL (e.g.
               //    `max`); an expression over aggregate functions is computed 
above the join from
               //    those corrected values, and a literal stays a constant 
there.
   ```
   
   Also, "the alternative is a possible follow-up" at L901 could be a 
`TODO(SPARK-xxxxx)` with a JIRA, like the `TODO(SPARK-61444)` below it, so that 
it is tracked.



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