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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ 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 =>
+              // `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 = {
+                val f = ae.aggregateFunction
+                f.defaultResult.getOrElse(Literal.create(null, f.dataType))
+              }
+              def rewrite(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOut(ae, "aggResult", 
zeroTupsResult(ae))
+                // An attribute inside an expression over aggregate functions. 
A grouping-less
+                // Aggregate cannot reference one outside an aggregate 
function (the analyzer
+                // rejects it), so this is unreachable from SQL; as
+                // `RewriteCorrelatedScalarSubquery.evalAggExprOnZeroTups`, 
take it as NULL over
+                // zero rows in case it is reached.
+                case r: AttributeReference => pullOut(r, r.name, 
Literal.create(null, r.dataType))
+                case other => other.mapChildren(rewrite)
+              }
+              val projectList = newAggregate.aggregateExpressions.map {
+                // Not subject to the count bug: NULL for zero tuples.
+                case a @ (_: AttributeReference | Alias(_: AttributeReference, 
_)) =>
+                  expressions += a
+                  a.toAttribute.withNullability(true)
+                // A literal (SPARK-43156) keeps its name in the new aggregate.
+                case a @ Alias(l: Literal, _) =>
+                  if (l.value == null) {
                     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.")
+                  } else {
                     val newAttr = a.newInstance()
-                    val ref = newAttr.toAttribute.withNullability(true)
                     expressions += newAttr
-                    Alias(If(IsNull(alwaysTrueRef), default, ref), 
a.name)(a.exprId)
-                }
+                    Alias(withZeroTupsResult(l, 
newAttr.toAttribute.withNullability(true)),
+                      a.name)(a.exprId)
+                  }
+                // A single aggregate function, or an expression over 
aggregate functions,
+                // computed over the pulled-out, corrected values. A single 
function keeps its
+                // output name and exprId and shares its column with any 
expression over it.
+                case a: Alias =>

Review Comment:
   **Correctness:** This moves an expression column from the `Aggregate` into 
the `Project` above the left outer domain join. A Python UDF in a branch 
guarded by an aggregate value then runs on the zero-row values for every outer 
row without matching rows, because `ExtractPythonUDFs` lifts it out of the 
conditional branch and evaluates its arguments for every row.
   
   For example, in ANSI mode with `a(k) = (1), (3)` and `b(k, v) = (1, 100)`:
   
   ```sql
   SELECT a.k, t.d FROM a, LATERAL (
     SELECT CASE WHEN COUNT(*) = 0 THEN 0 ELSE udf(10 / COUNT(*)) END d
     FROM b WHERE b.k = a.k) t
   ```
   
   - Before: `tryEvalExpr` cannot fold the zero-row value `CASE WHEN 0 = 0 THEN 
0 ELSE udf(10 / 0) END`, but `SimplifyConditionals` reduces it to `0` before 
the Python UDF extraction. `ExtractPythonUDFFromAggregate` evaluates `udf(10 / 
count(1))` right above the `Aggregate`, i.e. only for the groups with matching 
rows. The query returns a row for both `k = 1` and `k = 3` (`d = 0` for `k = 
3`).
   - After: the `Project` computes `CASE WHEN if(isnull(alwaysTrue), 0, 
aggResult) = 0 THEN 0 ELSE udf(10 / if(isnull(alwaysTrue), 0, aggResult)) END`, 
and the lifted UDF argument `10 / 0` is computed for `k = 3`, so the query 
fails with `DIVIDE_BY_ZERO` at runtime.
   
   The same happens without ANSI: with `udf(lambda x: x + 1)`, `CASE WHEN 
COUNT(*) > 0 THEN udf(MAX(v)) END` now calls the UDF with `None` for `k = 3` 
and fails with `TypeError`.
   
   The uncorrelated form of such a query probably hits the same eager 
evaluation, so this may be an acceptable trade-off. Still, it turns a currently 
working query into a failing one and contradicts "A query whose expression does 
not fail returns the same results as before" in the PR description. Could you 
either keep such cases working, or document it as a behavior change and add a 
test for it?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ 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 =>
+              // `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 = {
+                val f = ae.aggregateFunction
+                f.defaultResult.getOrElse(Literal.create(null, f.dataType))
+              }
+              def rewrite(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOut(ae, "aggResult", 
zeroTupsResult(ae))
+                // An attribute inside an expression over aggregate functions. 
A grouping-less
+                // Aggregate cannot reference one outside an aggregate 
function (the analyzer
+                // rejects it), so this is unreachable from SQL; as
+                // `RewriteCorrelatedScalarSubquery.evalAggExprOnZeroTups`, 
take it as NULL over
+                // zero rows in case it is reached.
+                case r: AttributeReference => pullOut(r, r.name, 
Literal.create(null, r.dataType))
+                case other => other.mapChildren(rewrite)
+              }
+              val projectList = newAggregate.aggregateExpressions.map {
+                // Not subject to the count bug: NULL for zero tuples.
+                case a @ (_: AttributeReference | Alias(_: AttributeReference, 
_)) =>
+                  expressions += a
+                  a.toAttribute.withNullability(true)
+                // A literal (SPARK-43156) keeps its name in the new aggregate.
+                case a @ Alias(l: Literal, _) =>
+                  if (l.value == null) {
                     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.")
+                  } else {
                     val newAttr = a.newInstance()
-                    val ref = newAttr.toAttribute.withNullability(true)
                     expressions += newAttr
-                    Alias(If(IsNull(alwaysTrueRef), default, ref), 
a.name)(a.exprId)
-                }
+                    Alias(withZeroTupsResult(l, 
newAttr.toAttribute.withNullability(true)),
+                      a.name)(a.exprId)
+                  }
+                // A single aggregate function, or an expression over 
aggregate functions,
+                // computed over the pulled-out, corrected values. A single 
function keeps its
+                // output name and exprId and shares its column with any 
expression over it.

Review Comment:
   **PR description:** Since the second commit, a single aggregate function 
column also goes through `pullOut`, so its plan changes too. The `Aggregate` 
output is aliased as `aggResult` instead of its original name (e.g. `count(1) 
AS aggResult` instead of `count(1) AS cnt`), and a function whose zero-row 
result is NULL gets an extra `aggResult AS m` alias in the `Project` above the 
join (as `DecorrelateInnerQuerySuite` now expects). So EXPLAIN changes for 
every subquery whose COUNT bug is handled here, even without an expression 
column.
   
   These parts of the PR description seem to need an update:
   - "A column that is a single aggregate function, a literal or an attribute 
keeps its current plan." and "Queries whose subquery does not have a column 
that is an expression over aggregate functions ... keep their plans."
   - "Two new tests in `SubquerySuite`" (there are three now).
   - "this shape does not pass analysis, so the test only pins the defensive 
behavior" for the non-deterministic test, since a non-deterministic UDAF with 
deterministic arguments reaches this path, as the updated test comment says.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ 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 =>
+              // `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 = {

Review Comment:
   **Reuse:** This duplicates 
`aggFunc.defaultResult.getOrElse(Literal.create(null, aggFunc.dataType))` in 
`RewriteCorrelatedScalarSubquery.evalAggExprOnZeroTups` (`subquery.scala` 
L754-756). SPARK-61444 is going to touch `constructLeftJoins`, and keeping the 
zero-row default rule in two places makes it easy for the two paths to diverge. 
Could we extract a shared helper?
   
   Also, this PR removes the only caller of 
`RewriteCorrelatedScalarSubquery.evalAggregateOnZeroTups` outside 
`subquery.scala`, so it can be made `private` now.



##########
sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala:
##########
@@ -1874,6 +1875,107 @@ class SubquerySuite extends SharedSparkSession
     checkAnswer(df, Nil)
   }
 
+  test("SPARK-61482: COUNT bug of a lower aggregate with an expression over 
aggregate functions") {

Review Comment:
   **Test coverage:** The runtime failure for an outer row without matching 
rows is checked only for the scalar subquery. Could you also cover the 
`LATERAL` case with `a(k) = (1), (3)` from the PR description, the `IN` 
subquery, and a Python UDF in a conditional branch guarded by an aggregate 
value (see my comment in `DecorrelateInnerQuery`)?
   
   Also, the test name says "of a lower aggregate", but the test covers 
`LATERAL`, `EXISTS` and `IN` subqueries too.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ 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 =>
+              // `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 = {
+                val f = ae.aggregateFunction
+                f.defaultResult.getOrElse(Literal.create(null, f.dataType))
+              }
+              def rewrite(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOut(ae, "aggResult", 
zeroTupsResult(ae))
+                // An attribute inside an expression over aggregate functions. 
A grouping-less
+                // Aggregate cannot reference one outside an aggregate 
function (the analyzer
+                // rejects it), so this is unreachable from SQL; as
+                // `RewriteCorrelatedScalarSubquery.evalAggExprOnZeroTups`, 
take it as NULL over
+                // zero rows in case it is reached.
+                case r: AttributeReference => pullOut(r, r.name, 
Literal.create(null, r.dataType))

Review Comment:
   **Dead code:** As the comment says, this branch is unreachable from SQL: the 
analyzer rejects such a column, and an `Aggregate` cannot host outer 
references. The mutation check in the PR description also shows that no test 
covers it. If a future change makes it reachable, silently taking NULL could 
produce a wrong result without any signal. How about failing explicitly with 
`SparkException.internalError` here, like the `case a =>` branch below?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ 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 =>
+              // `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 = {
+                val f = ae.aggregateFunction
+                f.defaultResult.getOrElse(Literal.create(null, f.dataType))
+              }
+              def rewrite(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOut(ae, "aggResult", 
zeroTupsResult(ae))
+                // An attribute inside an expression over aggregate functions. 
A grouping-less
+                // Aggregate cannot reference one outside an aggregate 
function (the analyzer
+                // rejects it), so this is unreachable from SQL; as
+                // `RewriteCorrelatedScalarSubquery.evalAggExprOnZeroTups`, 
take it as NULL over
+                // zero rows in case it is reached.
+                case r: AttributeReference => pullOut(r, r.name, 
Literal.create(null, r.dataType))
+                case other => other.mapChildren(rewrite)
+              }
+              val projectList = newAggregate.aggregateExpressions.map {
+                // Not subject to the count bug: NULL for zero tuples.
+                case a @ (_: AttributeReference | Alias(_: AttributeReference, 
_)) =>
+                  expressions += a
+                  a.toAttribute.withNullability(true)
+                // A literal (SPARK-43156) keeps its name in the new aggregate.
+                case a @ Alias(l: Literal, _) =>
+                  if (l.value == null) {
                     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.")
+                  } else {
                     val newAttr = a.newInstance()
-                    val ref = newAttr.toAttribute.withNullability(true)
                     expressions += newAttr
-                    Alias(If(IsNull(alwaysTrueRef), default, ref), 
a.name)(a.exprId)
-                }
+                    Alias(withZeroTupsResult(l, 
newAttr.toAttribute.withNullability(true)),
+                      a.name)(a.exprId)
+                  }
+                // A single aggregate function, or an expression over 
aggregate functions,
+                // computed over the pulled-out, corrected values. A single 
function keeps its
+                // output name and exprId and shares its column with any 
expression over it.
+                case a: Alias =>
+                  a.withNewChildren(Seq(rewrite(a.child))).asInstanceOf[Alias]
+                case a =>

Review Comment:
   **Minor:** Previously, a non-`Alias` named expression whose zero-row result 
was NULL was kept as is (`case Some(Literal(null, _)) | None => expressions += 
a`). Now anything other than an attribute or an `Alias` throws 
`INTERNAL_ERROR`. It looks unreachable with the current analyzer, so this is 
fine by itself. However, the two unreachable cases are now handled differently: 
this one fails explicitly, while the `AttributeReference` case in `rewrite` 
silently takes NULL. It would be good to handle them consistently (see my 
comment on L930).



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ 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 =>
+              // `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 = {
+                val f = ae.aggregateFunction
+                f.defaultResult.getOrElse(Literal.create(null, f.dataType))
+              }
+              def rewrite(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOut(ae, "aggResult", 
zeroTupsResult(ae))
+                // An attribute inside an expression over aggregate functions. 
A grouping-less
+                // Aggregate cannot reference one outside an aggregate 
function (the analyzer
+                // rejects it), so this is unreachable from SQL; as
+                // `RewriteCorrelatedScalarSubquery.evalAggExprOnZeroTups`, 
take it as NULL over
+                // zero rows in case it is reached.
+                case r: AttributeReference => pullOut(r, r.name, 
Literal.create(null, r.dataType))
+                case other => other.mapChildren(rewrite)
+              }
+              val projectList = newAggregate.aggregateExpressions.map {
+                // Not subject to the count bug: NULL for zero tuples.
+                case a @ (_: AttributeReference | Alias(_: AttributeReference, 
_)) =>
+                  expressions += a
+                  a.toAttribute.withNullability(true)
+                // A literal (SPARK-43156) keeps its name in the new aggregate.
+                case a @ Alias(l: Literal, _) =>
+                  if (l.value == null) {
                     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.")
+                  } else {
                     val newAttr = a.newInstance()
-                    val ref = newAttr.toAttribute.withNullability(true)
                     expressions += newAttr
-                    Alias(If(IsNull(alwaysTrueRef), default, ref), 
a.name)(a.exprId)
-                }
+                    Alias(withZeroTupsResult(l, 
newAttr.toAttribute.withNullability(true)),
+                      a.name)(a.exprId)
+                  }
+                // A single aggregate function, or an expression over 
aggregate functions,
+                // computed over the pulled-out, corrected values. A single 
function keeps its
+                // output name and exprId and shares its column with any 
expression over it.
+                case a: Alias =>
+                  a.withNewChildren(Seq(rewrite(a.child))).asInstanceOf[Alias]
+                case a =>
+                  throw SparkException.internalError(
+                    s"Unexpected aggregate expression $a in a correlated 
subquery.")
               }
               // Insert a placeholder left outer domain join between the outer 
query and

Review Comment:
   **Stale comments:** The block comment and the example plans still describe 
the previous behavior:
   - L860-861: "rewrite the original aggregate's output column using the 
default value of the aggregate function and the alwaysTrue column"
   - L974-976 and L981-986: `Aggregate [a] [count(1) AS cnt', a, true AS 
alwaysTrue]` with `Project [if(isnull(alwaysTrue), 0, cnt') AS cnt, c']`
   
   With this PR, the `Aggregate` outputs `count(1) AS aggResult`, and 
expression columns are rebuilt in the `Project` from the corrected values of 
each aggregate function. Could you update them?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ 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 =>
+              // `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 = {
+                val f = ae.aggregateFunction
+                f.defaultResult.getOrElse(Literal.create(null, f.dataType))
+              }
+              def rewrite(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOut(ae, "aggResult", 
zeroTupsResult(ae))
+                // An attribute inside an expression over aggregate functions. 
A grouping-less
+                // Aggregate cannot reference one outside an aggregate 
function (the analyzer
+                // rejects it), so this is unreachable from SQL; as
+                // `RewriteCorrelatedScalarSubquery.evalAggExprOnZeroTups`, 
take it as NULL over
+                // zero rows in case it is reached.
+                case r: AttributeReference => pullOut(r, r.name, 
Literal.create(null, r.dataType))
+                case other => other.mapChildren(rewrite)
+              }
+              val projectList = newAggregate.aggregateExpressions.map {
+                // Not subject to the count bug: NULL for zero tuples.
+                case a @ (_: AttributeReference | Alias(_: AttributeReference, 
_)) =>
+                  expressions += a
+                  a.toAttribute.withNullability(true)
+                // A literal (SPARK-43156) keeps its name in the new aggregate.
+                case a @ Alias(l: Literal, _) =>

Review Comment:
   **Simplification:** Now that an expression is computed in the `Project` 
above the join, this literal-specific branch seems unnecessary. With it, `5 AS 
l` adds a column `5 AS l'` to the `Aggregate`, carries it through the domain 
join, and computes `if(isnull(alwaysTrue), 5, l')`, which is always `5`. 
Meanwhile, a constant expression like `CAST(5 AS BIGINT)` takes the generic 
`case a: Alias` path and is computed in the `Project` directly.
   
   The generic path gives the same result for both non-null and null literals, 
so could we remove this branch (including the `l.value == null` case) and save 
one column and one `If`? Since the plan of a single aggregate function already 
changes in this PR, keeping the plan of a literal as is seems less important.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ 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 =>
+              // `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 = {
+                val f = ae.aggregateFunction
+                f.defaultResult.getOrElse(Literal.create(null, f.dataType))
+              }
+              def rewrite(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOut(ae, "aggResult", 
zeroTupsResult(ae))

Review Comment:
   **Readability:** Every pulled-out aggregate function gets the same name 
`aggResult`. The decorrelated `Aggregate` can then output several columns with 
the same name, e.g. `max(v) AS aggResult#1, min(v) AS aggResult#2` for `MAX(v) 
- MIN(v)`, and an original name such as `cnt` disappears from it, which makes 
EXPLAIN harder to follow. How about keeping the original alias name for a 
single aggregate function column, and using a name derived from the function 
for one inside an expression?



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