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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,6 +567,85 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
      nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
    }
 
+  // Returns true if 'plan' returns exactly one row: an Aggregate without 
grouping expressions
+  // returns one row even on empty input. Unlike guaranteedToReturnOneRow, 
which allows at most
+  // one row, this must be exactly one, so it does not look through a Filter, 
a Limit or a Window.
+  private def returnsExactlyOneRow(plan: LogicalPlan): Boolean = plan match {
+    case Project(_, child) => returnsExactlyOneRow(child)
+    case a: Aggregate => a.groupingExpressions.isEmpty
+    case _ => false
+  }
+
+  /**
+   * Returns an expression that computes `ae` over a single input row, or None 
if it cannot.
+   * The expression applies the update expressions of the 
[[DeclarativeAggregate]] once to its
+   * initial values, and then its evaluate expression; a FILTER keeps the 
initial values when
+   * its condition does not hold. DISTINCT does not change the result over a 
single row.
+   *
+   * Only a [[DeclarativeAggregate]] can be computed this way, see the note in
+   * [[ImperativeAggregate]]. Returns None if an argument or the FILTER is 
non-deterministic,
+   * because the update expressions may evaluate an argument more than once 
and the FILTER is
+   * evaluated once per buffer value; CheckAnalysis rejects a 
non-deterministic argument, and SQL
+   * function resolution a non-deterministic FILTER, but a plan built another 
way may not. Also
+   * returns None if the result does not keep the data type and nullability of 
`ae`.
+   */
+  private def evalAggregateOnOneRow(ae: AggregateExpression): 
Option[Expression] = {
+    ae.aggregateFunction match {
+      case f: DeclarativeAggregate
+          if f.children.forall(_.deterministic) && 
ae.filter.forall(_.deterministic) =>
+        def bindBuffer(e: Expression, values: Seq[Expression]): Expression = {
+          val buffer = AttributeMap(f.aggBufferAttributes.zip(values))
+          e.transform { case a: AttributeReference if buffer.contains(a) => 
buffer(a) }
+        }
+        val updated = f.updateExpressions.map(bindBuffer(_, f.initialValues))
+        val filtered = ae.filter match {
+          case Some(cond) => updated.zip(f.initialValues).map { case (u, i) => 
If(cond, u, i) }
+          case None => updated
+        }
+        val result = bindBuffer(f.evaluateExpression, filtered)

Review Comment:
   **[2] Following up on @raviston's 
[comment](https://github.com/apache/spark/pull/60296#issuecomment-6787609011): 
the collapse also folds the arguments of the top aggregate itself, not only the 
expressions of the lower `Aggregate`.** In `SELECT a.k, (SELECT MAX(10 / c) 
FROM (SELECT COUNT(*) c FROM b WHERE b.k = a.k)) FROM a`, the lower `COUNT(*)` 
is safe, but `MAX` becomes `greatest(null, 10 / c)` in a `Project` above it. 
`evalSubqueryOnZeroTups` binds `c` to `0` in `bindingExpr`, and `tryEvalExpr` 
throws `DIVIDE_BY_ZERO` while the query is optimized, even when every `a.k` has 
rows in `b` or `a` is empty. Before this PR, `evalAggregateOnZeroTups` replaced 
`MAX` with its default result and never evaluated its argument. So the second 
option in that comment (not collapsing when the expressions of the lower 
`Aggregate` cannot be folded safely) would not cover this case, while the 
`tryEvalExpr` fallback covers both. Could the fix cover the collapsed arguments 
too, and could a test add t
 his shape next to Q2 and Q3?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,6 +567,85 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
      nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
    }
 
+  // Returns true if 'plan' returns exactly one row: an Aggregate without 
grouping expressions
+  // returns one row even on empty input. Unlike guaranteedToReturnOneRow, 
which allows at most
+  // one row, this must be exactly one, so it does not look through a Filter, 
a Limit or a Window.
+  private def returnsExactlyOneRow(plan: LogicalPlan): Boolean = plan match {
+    case Project(_, child) => returnsExactlyOneRow(child)
+    case a: Aggregate => a.groupingExpressions.isEmpty
+    case _ => false
+  }
+
+  /**
+   * Returns an expression that computes `ae` over a single input row, or None 
if it cannot.
+   * The expression applies the update expressions of the 
[[DeclarativeAggregate]] once to its
+   * initial values, and then its evaluate expression; a FILTER keeps the 
initial values when
+   * its condition does not hold. DISTINCT does not change the result over a 
single row.
+   *
+   * Only a [[DeclarativeAggregate]] can be computed this way, see the note in
+   * [[ImperativeAggregate]]. Returns None if an argument or the FILTER is 
non-deterministic,
+   * because the update expressions may evaluate an argument more than once 
and the FILTER is
+   * evaluated once per buffer value; CheckAnalysis rejects a 
non-deterministic argument, and SQL
+   * function resolution a non-deterministic FILTER, but a plan built another 
way may not. Also
+   * returns None if the result does not keep the data type and nullability of 
`ae`.
+   */
+  private def evalAggregateOnOneRow(ae: AggregateExpression): 
Option[Expression] = {
+    ae.aggregateFunction match {
+      case f: DeclarativeAggregate
+          if f.children.forall(_.deterministic) && 
ae.filter.forall(_.deterministic) =>
+        def bindBuffer(e: Expression, values: Seq[Expression]): Expression = {
+          val buffer = AttributeMap(f.aggBufferAttributes.zip(values))
+          e.transform { case a: AttributeReference if buffer.contains(a) => 
buffer(a) }
+        }
+        val updated = f.updateExpressions.map(bindBuffer(_, f.initialValues))
+        val filtered = ae.filter match {
+          case Some(cond) => updated.zip(f.initialValues).map { case (u, i) => 
If(cond, u, i) }
+          case None => updated
+        }
+        val result = bindBuffer(f.evaluateExpression, filtered)
+        if (result.dataType == ae.dataType && (ae.nullable || 
!result.nullable)) {
+          Some(result)
+        } else {
+          None
+        }
+      case _ => None
+    }
+  }
+
+  /**
+   * Rewrites each Aggregate without grouping expressions over a node that 
returns exactly one
+   * row (see `returnsExactlyOneRow`) into a Project, if 
`evalAggregateOnOneRow` can compute all
+   * of its aggregate expressions. This removes a nested Aggregate from a 
correlated scalar
+   * subquery, such as `SELECT MAX(c) FROM (SELECT SUM(b) AS c FROM t WHERE 
t.a = outer.a)`, so
+   * that its count bug can be handled in
+   * [[RewriteCorrelatedScalarSubquery#constructLeftJoins]] instead of in
+   * [[DecorrelateInnerQuery]], which joins with the domain of the outer 
columns.
+   */
+  private def collapseAggregatesOverOneRow(plan: LogicalPlan): LogicalPlan = 
plan.transformUp {
+    // An Aggregate that carries a hint (an extension point, see 
AggregateHint) is kept.
+    case a @ Aggregate(Nil, aggregateExpressions, child, None) if 
returnsExactlyOneRow(child) =>
+      val results = aggregateExpressions.flatMap(_.collect {
+        case ae: AggregateExpression => ae.canonicalized -> 
evalAggregateOnOneRow(ae)
+      }).toMap
+      if (results.values.forall(_.isDefined)) {
+        val projectList = aggregateExpressions.map(_.transformDown {
+          case ae: AggregateExpression => results(ae.canonicalized).get
+        }.asInstanceOf[NamedExpression])
+        Project(projectList, child)
+      } else {
+        a
+      }
+  }
+
+  // Strips the Projects without outer references at the top of 'plan', to 
find the node that
+  // decides how the count bug is handled. A Project with outer references 
stops the strip: it
+  // must be handled in DecorrelateInnerQuery, since constructLeftJoins 
evaluates the top node
+  // over zero rows and cannot evaluate an outer reference there.
+  private def stripTopProjects(plan: LogicalPlan): LogicalPlan = plan match {
+    case p @ Project(_, child) if !p.projectList.exists(containsOuter) => 
stripTopProjects(child)

Review Comment:
   **[4] With a stripped `Project` or a collapsed aggregate, a Python UDF in 
the subquery now runs on the zero-row value for every outer row.** 
`evalSubqueryOnZeroTups` keeps a non-foldable result such as `inv(0)` as an 
expression (SPARK-28441), and CASE 2 puts it into `If(IsNull(alwaysTrue), 
inv(0), x)` in the outer `Project`. `ExtractPythonUDFs` also extracts UDFs from 
conditional branches, so `BatchEvalPython` computes `inv(0)` for every row. 
With `inv = udf(lambda x: 1 / x)`, `SELECT a.k, (SELECT inv(c) FROM (SELECT 
COUNT(*) c FROM b WHERE b.k = a.k)) FROM a` now fails with `ZeroDivisionError`, 
even when every key matches. Before this PR, the `Project` top went to 
`DecorrelateInnerQuery` with `mayHaveCountBug = false`, so `inv` saw only real 
counts. `SUM(inv(c))` behaves the same after the collapse. The same already 
happens on `master` for `inv(COUNT(*))` in the top `Aggregate`, but this PR 
moves shapes that worked into that path. Could both changes skip a `Project` or 
an aggrega
 te whose expressions contain a Python UDF?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -592,32 +671,69 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
     }
 
     plan.transformExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
-      case ScalarSubquery(sub, children, exprId, conditions, hint,
+      case ScalarSubquery(originalSub, children, exprId, conditions, hint,
       mayHaveCountBugOld, needSingleJoinOld)
         if children.nonEmpty =>
 
+        // An Aggregate without grouping expressions returns one row even on 
empty input,
+        // whatever its aggregate functions are, and an Aggregate above it 
sees that row. If the
+        // Aggregate is correlated, decorrelation can lose that row (see 
below). An uncorrelated
+        // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree 
without outer references
+        // (SubExprUtils.hasOuterReferences) unchanged, at most inner joining 
it with the domain,
+        // and the non-legacy branch below uses the same check. With
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only 
such an Aggregate
+        // with an aggregate function that has a default result, such as 
COUNT, qualifies,
+        // whether it is correlated or not.
+        val legacyNestedAggregateCountBug =
+          
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR)
+        val legacyCountBugHandling = 
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING)
         def mayHaveCountBugAgg(a: Aggregate): Boolean = {
-          a.groupingExpressions.isEmpty && 
a.aggregateExpressions.exists(_.exists {
-            case a: AggregateExpression => 
a.aggregateFunction.defaultResult.isDefined
-            case _ => false
+          a.groupingExpressions.isEmpty && (if (legacyNestedAggregateCountBug) 
{
+            a.aggregateExpressions.exists(_.exists {
+              case ae: AggregateExpression => 
ae.aggregateFunction.defaultResult.isDefined
+              case _ => false
+            })
+          } else {
+            SubExprUtils.hasOuterReferences(a)
           })
         }
 
+        // Collapsing an Aggregate over one row (see 
collapseAggregatesOverOneRow) and looking
+        // through the Projects at the top let constructLeftJoins handle the 
count bug of more
+        // subqueries. Neither is done when this rule runs again on a 
rewritten subquery
+        // (mayHaveCountBugOld is defined), or when the plans of earlier 
versions are kept:
+        // decorrelateInnerQuery is disabled, or 
LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING or
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR is 
enabled.
+        val simplifyForCountBug = mayHaveCountBugOld.isEmpty &&
+          SQLConf.get.decorrelateInnerQueryEnabled && !legacyCountBugHandling 
&&
+          !legacyNestedAggregateCountBug
+        val sub = if (simplifyForCountBug) {
+          collapseAggregatesOverOneRow(originalSub)
+        } else {
+          originalSub
+        }
+        val topNode = if (simplifyForCountBug) stripTopProjects(sub) else sub

Review Comment:
   **[3] With two `Project`s that `PhysicalOperation` cannot collapse, the 
count-bug guard of `OptimizeSubqueries` misses, and the subquery can return 
`NULL`.** The guard at Optimizer.scala:428 matches 
`ScalarSubquery(PhysicalOperation(_, _, Aggregate), ...)`, but 
`collectProjectsAndFilters` stops at a `Project` that repeats a non-cheap alias 
(patterns.scala:63), so it returns the `Project`, not the `Aggregate`, and the 
subquery is optimized as a whole. For example, with the VALUES views of the new 
golden file, `SELECT a1, (SELECT s * s FROM (SELECT c + 1 AS s FROM (SELECT 
COUNT(*) c FROM t2 WHERE t2.b1 = t1.a1 AND t2.b2 > 10))) FROM t1` should return 
`1` for every row. In a regular session, `ConvertToLocalRelation` empties the 
filter, `PropagateEmptyRelation` removes the grouped `Aggregate` and both 
`Project`s, and `evalSubqueryOnZeroTups` treats the empty `LocalRelation` as 
all-`NULL`, so CASE 1 returns `NULL`. (The test sessions exclude 
`ConvertToLocalRelation`, so a golden-file t
 est may need it enabled.) Before this PR, the `Project` top went to 
`DecorrelateInnerQuery`, whose left outer `DomainJoin` is not a `Join` for 
`PropagateEmptyRelation`, so it returned `1`. The collapse alone can build the 
same shape, e.g. `AVG` over a collapsed `MAX` over a correlated `MAX`. Could 
`stripTopProjects` and the collapse apply only when the result still matches 
that guard, and could a test cover this shape?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,6 +567,85 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
      nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
    }
 
+  // Returns true if 'plan' returns exactly one row: an Aggregate without 
grouping expressions
+  // returns one row even on empty input. Unlike guaranteedToReturnOneRow, 
which allows at most
+  // one row, this must be exactly one, so it does not look through a Filter, 
a Limit or a Window.
+  private def returnsExactlyOneRow(plan: LogicalPlan): Boolean = plan match {
+    case Project(_, child) => returnsExactlyOneRow(child)
+    case a: Aggregate => a.groupingExpressions.isEmpty
+    case _ => false
+  }
+
+  /**
+   * Returns an expression that computes `ae` over a single input row, or None 
if it cannot.
+   * The expression applies the update expressions of the 
[[DeclarativeAggregate]] once to its
+   * initial values, and then its evaluate expression; a FILTER keeps the 
initial values when
+   * its condition does not hold. DISTINCT does not change the result over a 
single row.
+   *
+   * Only a [[DeclarativeAggregate]] can be computed this way, see the note in
+   * [[ImperativeAggregate]]. Returns None if an argument or the FILTER is 
non-deterministic,
+   * because the update expressions may evaluate an argument more than once 
and the FILTER is
+   * evaluated once per buffer value; CheckAnalysis rejects a 
non-deterministic argument, and SQL
+   * function resolution a non-deterministic FILTER, but a plan built another 
way may not. Also
+   * returns None if the result does not keep the data type and nullability of 
`ae`.
+   */
+  private def evalAggregateOnOneRow(ae: AggregateExpression): 
Option[Expression] = {
+    ae.aggregateFunction match {
+      case f: DeclarativeAggregate
+          if f.children.forall(_.deterministic) && 
ae.filter.forall(_.deterministic) =>
+        def bindBuffer(e: Expression, values: Seq[Expression]): Expression = {
+          val buffer = AttributeMap(f.aggBufferAttributes.zip(values))
+          e.transform { case a: AttributeReference if buffer.contains(a) => 
buffer(a) }
+        }
+        val updated = f.updateExpressions.map(bindBuffer(_, f.initialValues))

Review Comment:
   **[8] Minor: `bindBuffer` copies the aggregate argument into every buffer 
reference.** The update expressions reference the argument once per buffer 
slot, and L605 copies each updated expression into every buffer reference of 
`evaluateExpression`, so the argument appears about 3 times for `AVG` and more 
for `STDDEV_SAMP` or `CORR`, partly inside `If` branches, where subexpression 
elimination does not always dedupe it. A deterministic but expensive argument 
is then evaluated several times per row, and again in the zero-row evaluation. 
Could the arguments be computed once in a `Project` below before binding?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -592,32 +671,69 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
     }
 
     plan.transformExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
-      case ScalarSubquery(sub, children, exprId, conditions, hint,
+      case ScalarSubquery(originalSub, children, exprId, conditions, hint,
       mayHaveCountBugOld, needSingleJoinOld)
         if children.nonEmpty =>
 
+        // An Aggregate without grouping expressions returns one row even on 
empty input,
+        // whatever its aggregate functions are, and an Aggregate above it 
sees that row. If the
+        // Aggregate is correlated, decorrelation can lose that row (see 
below). An uncorrelated
+        // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree 
without outer references
+        // (SubExprUtils.hasOuterReferences) unchanged, at most inner joining 
it with the domain,
+        // and the non-legacy branch below uses the same check. With
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only 
such an Aggregate
+        // with an aggregate function that has a default result, such as 
COUNT, qualifies,
+        // whether it is correlated or not.
+        val legacyNestedAggregateCountBug =
+          
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR)
+        val legacyCountBugHandling = 
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING)
         def mayHaveCountBugAgg(a: Aggregate): Boolean = {
-          a.groupingExpressions.isEmpty && 
a.aggregateExpressions.exists(_.exists {
-            case a: AggregateExpression => 
a.aggregateFunction.defaultResult.isDefined
-            case _ => false
+          a.groupingExpressions.isEmpty && (if (legacyNestedAggregateCountBug) 
{
+            a.aggregateExpressions.exists(_.exists {
+              case ae: AggregateExpression => 
ae.aggregateFunction.defaultResult.isDefined
+              case _ => false
+            })
+          } else {
+            SubExprUtils.hasOuterReferences(a)

Review Comment:
   **[7] Minor: change 1 also adds domain joins where the old result was 
correct.** Every correlated lower `Aggregate` without `GROUP BY` under a top 
node that cannot be collapsed (a non-declarative top function, a grouped top, 
or a `Filter`, `Limit`, `Window` or join in between) now goes to 
`DecorrelateInnerQuery`, with one left outer domain join per such `Aggregate`, 
each computing the distinct correlated values from the outer query again. The 
table in the description shows `COLLECT_LIST(s)` over `MAX(b.v)` going from 1 
to 3 joins, although its old result was correct because `COLLECT_LIST` skips 
the `NULL` row, and only the all-or-nothing legacy conf avoids it. Could the 
rule keep the old plan when every top aggregate function skips `NULL` inputs 
and its argument is an output of a lower aggregate function that returns `NULL` 
on empty input, as in `COLLECT_LIST(s)`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -592,32 +671,69 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
     }
 
     plan.transformExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
-      case ScalarSubquery(sub, children, exprId, conditions, hint,
+      case ScalarSubquery(originalSub, children, exprId, conditions, hint,
       mayHaveCountBugOld, needSingleJoinOld)
         if children.nonEmpty =>
 
+        // An Aggregate without grouping expressions returns one row even on 
empty input,
+        // whatever its aggregate functions are, and an Aggregate above it 
sees that row. If the
+        // Aggregate is correlated, decorrelation can lose that row (see 
below). An uncorrelated
+        // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree 
without outer references
+        // (SubExprUtils.hasOuterReferences) unchanged, at most inner joining 
it with the domain,
+        // and the non-legacy branch below uses the same check. With
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only 
such an Aggregate
+        // with an aggregate function that has a default result, such as 
COUNT, qualifies,
+        // whether it is correlated or not.
+        val legacyNestedAggregateCountBug =
+          
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR)
+        val legacyCountBugHandling = 
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING)
         def mayHaveCountBugAgg(a: Aggregate): Boolean = {
-          a.groupingExpressions.isEmpty && 
a.aggregateExpressions.exists(_.exists {
-            case a: AggregateExpression => 
a.aggregateFunction.defaultResult.isDefined
-            case _ => false
+          a.groupingExpressions.isEmpty && (if (legacyNestedAggregateCountBug) 
{
+            a.aggregateExpressions.exists(_.exists {
+              case ae: AggregateExpression => 
ae.aggregateFunction.defaultResult.isDefined
+              case _ => false
+            })
+          } else {
+            SubExprUtils.hasOuterReferences(a)
           })
         }
 
+        // Collapsing an Aggregate over one row (see 
collapseAggregatesOverOneRow) and looking
+        // through the Projects at the top let constructLeftJoins handle the 
count bug of more
+        // subqueries. Neither is done when this rule runs again on a 
rewritten subquery
+        // (mayHaveCountBugOld is defined), or when the plans of earlier 
versions are kept:
+        // decorrelateInnerQuery is disabled, or 
LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING or
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR is 
enabled.
+        val simplifyForCountBug = mayHaveCountBugOld.isEmpty &&
+          SQLConf.get.decorrelateInnerQueryEnabled && !legacyCountBugHandling 
&&
+          !legacyNestedAggregateCountBug
+        val sub = if (simplifyForCountBug) {
+          collapseAggregatesOverOneRow(originalSub)
+        } else {
+          originalSub
+        }
+        val topNode = if (simplifyForCountBug) stripTopProjects(sub) else sub
+
         // The below logic controls handling count bug for scalar subqueries in
         // [[DecorrelateInnerQuery]], and if we don't handle it here, we 
handle it in
         // [[RewriteCorrelatedScalarSubquery#constructLeftJoins]]. Note that 
handling it in
         // [[DecorrelateInnerQuery]] is always correct, and turning it off to 
handle it in
         // constructLeftJoins is an optimization, so that additional, 
redundant left outer joins are
         // not introduced.
         val handleCountBugInDecorrelate = 
SQLConf.get.decorrelateInnerQueryEnabled &&
-          !conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING) && 
!(sub match {
-          // Handle count bug only if there exists lower level Aggs with count 
bugs. It does not
-          // matter if the top level agg is count bug vulnerable or not, 
because:
-          // 1. If the top level agg is count bug vulnerable, it can be 
handled in
-          // constructLeftJoins, unless there are lower aggs that are count 
bug vulnerable.
-          // E.g. COUNT(COUNT + COUNT)
-          // 2. If the top level agg is not count bug vulnerable, it can be 
count bug vulnerable if
-          // there are lower aggs that are count bug vulnerable. E.g. 
SUM(COUNT)
+          !legacyCountBugHandling && !(topNode match {

Review Comment:
   **[9] Nit: the conf gating is stated twice.** 
`SQLConf.get.decorrelateInnerQueryEnabled && !legacyCountBugHandling` is 
computed in L707-L709 and again in L723-L724, `sub` and `topNode` each check 
`simplifyForCountBug`, and the block mixes `conf.getConf` with `SQLConf.get`. 
Could one `val` (e.g. `countBugHandledInRule`) and `val (sub, topNode) = if 
(simplifyForCountBug) { ... } else (originalSub, originalSub)` state it once, 
so that the collapse and the decision that depends on it cannot drift apart?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,6 +567,85 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
      nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
    }
 
+  // Returns true if 'plan' returns exactly one row: an Aggregate without 
grouping expressions
+  // returns one row even on empty input. Unlike guaranteedToReturnOneRow, 
which allows at most
+  // one row, this must be exactly one, so it does not look through a Filter, 
a Limit or a Window.
+  private def returnsExactlyOneRow(plan: LogicalPlan): Boolean = plan match {
+    case Project(_, child) => returnsExactlyOneRow(child)
+    case a: Aggregate => a.groupingExpressions.isEmpty
+    case _ => false
+  }
+
+  /**
+   * Returns an expression that computes `ae` over a single input row, or None 
if it cannot.
+   * The expression applies the update expressions of the 
[[DeclarativeAggregate]] once to its
+   * initial values, and then its evaluate expression; a FILTER keeps the 
initial values when
+   * its condition does not hold. DISTINCT does not change the result over a 
single row.
+   *
+   * Only a [[DeclarativeAggregate]] can be computed this way, see the note in
+   * [[ImperativeAggregate]]. Returns None if an argument or the FILTER is 
non-deterministic,
+   * because the update expressions may evaluate an argument more than once 
and the FILTER is
+   * evaluated once per buffer value; CheckAnalysis rejects a 
non-deterministic argument, and SQL
+   * function resolution a non-deterministic FILTER, but a plan built another 
way may not. Also
+   * returns None if the result does not keep the data type and nullability of 
`ae`.
+   */
+  private def evalAggregateOnOneRow(ae: AggregateExpression): 
Option[Expression] = {
+    ae.aggregateFunction match {
+      case f: DeclarativeAggregate
+          if f.children.forall(_.deterministic) && 
ae.filter.forall(_.deterministic) =>
+        def bindBuffer(e: Expression, values: Seq[Expression]): Expression = {
+          val buffer = AttributeMap(f.aggBufferAttributes.zip(values))
+          e.transform { case a: AttributeReference if buffer.contains(a) => 
buffer(a) }
+        }
+        val updated = f.updateExpressions.map(bindBuffer(_, f.initialValues))
+        val filtered = ae.filter match {
+          case Some(cond) => updated.zip(f.initialValues).map { case (u, i) => 
If(cond, u, i) }
+          case None => updated
+        }
+        val result = bindBuffer(f.evaluateExpression, filtered)
+        if (result.dataType == ae.dataType && (ae.nullable || 
!result.nullable)) {
+          Some(result)
+        } else {
+          None
+        }
+      case _ => None
+    }
+  }
+
+  /**
+   * Rewrites each Aggregate without grouping expressions over a node that 
returns exactly one
+   * row (see `returnsExactlyOneRow`) into a Project, if 
`evalAggregateOnOneRow` can compute all
+   * of its aggregate expressions. This removes a nested Aggregate from a 
correlated scalar
+   * subquery, such as `SELECT MAX(c) FROM (SELECT SUM(b) AS c FROM t WHERE 
t.a = outer.a)`, so
+   * that its count bug can be handled in
+   * [[RewriteCorrelatedScalarSubquery#constructLeftJoins]] instead of in
+   * [[DecorrelateInnerQuery]], which joins with the domain of the outer 
columns.
+   */
+  private def collapseAggregatesOverOneRow(plan: LogicalPlan): LogicalPlan = 
plan.transformUp {

Review Comment:
   **[6] Minor: `collapseAggregatesOverOneRow` is a general rewrite inside a 
subquery rule.** An `Aggregate` without grouping over a child that returns 
exactly one row can become a `Project` anywhere, and `OptimizeOneRowPlan` 
already holds the related rewrites for a child with at most one row (a 
group-only `Aggregate` to a `Project`, dropping `DISTINCT`). Here the rewrite 
runs only in the first `PullupCorrelatedPredicates` pass of a correlated scalar 
subquery, so the same shape elsewhere is not simplified, and a later fix of the 
one-row evaluation (e.g. item 2) has to go into a subquery-specific helper. 
Could the rewrite live next to `OptimizeOneRowPlan`, with this rule calling it?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,6 +567,85 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
      nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
    }
 
+  // Returns true if 'plan' returns exactly one row: an Aggregate without 
grouping expressions
+  // returns one row even on empty input. Unlike guaranteedToReturnOneRow, 
which allows at most
+  // one row, this must be exactly one, so it does not look through a Filter, 
a Limit or a Window.
+  private def returnsExactlyOneRow(plan: LogicalPlan): Boolean = plan match {
+    case Project(_, child) => returnsExactlyOneRow(child)
+    case a: Aggregate => a.groupingExpressions.isEmpty
+    case _ => false
+  }
+
+  /**
+   * Returns an expression that computes `ae` over a single input row, or None 
if it cannot.
+   * The expression applies the update expressions of the 
[[DeclarativeAggregate]] once to its
+   * initial values, and then its evaluate expression; a FILTER keeps the 
initial values when
+   * its condition does not hold. DISTINCT does not change the result over a 
single row.
+   *
+   * Only a [[DeclarativeAggregate]] can be computed this way, see the note in
+   * [[ImperativeAggregate]]. Returns None if an argument or the FILTER is 
non-deterministic,
+   * because the update expressions may evaluate an argument more than once 
and the FILTER is
+   * evaluated once per buffer value; CheckAnalysis rejects a 
non-deterministic argument, and SQL
+   * function resolution a non-deterministic FILTER, but a plan built another 
way may not. Also
+   * returns None if the result does not keep the data type and nullability of 
`ae`.
+   */
+  private def evalAggregateOnOneRow(ae: AggregateExpression): 
Option[Expression] = {
+    ae.aggregateFunction match {
+      case f: DeclarativeAggregate
+          if f.children.forall(_.deterministic) && 
ae.filter.forall(_.deterministic) =>
+        def bindBuffer(e: Expression, values: Seq[Expression]): Expression = {
+          val buffer = AttributeMap(f.aggBufferAttributes.zip(values))
+          e.transform { case a: AttributeReference if buffer.contains(a) => 
buffer(a) }
+        }
+        val updated = f.updateExpressions.map(bindBuffer(_, f.initialValues))
+        val filtered = ae.filter match {
+          case Some(cond) => updated.zip(f.initialValues).map { case (u, i) => 
If(cond, u, i) }
+          case None => updated
+        }
+        val result = bindBuffer(f.evaluateExpression, filtered)
+        if (result.dataType == ae.dataType && (ae.nullable || 
!result.nullable)) {
+          Some(result)
+        } else {
+          None
+        }
+      case _ => None
+    }
+  }
+
+  /**
+   * Rewrites each Aggregate without grouping expressions over a node that 
returns exactly one
+   * row (see `returnsExactlyOneRow`) into a Project, if 
`evalAggregateOnOneRow` can compute all
+   * of its aggregate expressions. This removes a nested Aggregate from a 
correlated scalar
+   * subquery, such as `SELECT MAX(c) FROM (SELECT SUM(b) AS c FROM t WHERE 
t.a = outer.a)`, so
+   * that its count bug can be handled in
+   * [[RewriteCorrelatedScalarSubquery#constructLeftJoins]] instead of in
+   * [[DecorrelateInnerQuery]], which joins with the domain of the outer 
columns.
+   */
+  private def collapseAggregatesOverOneRow(plan: LogicalPlan): LogicalPlan = 
plan.transformUp {
+    // An Aggregate that carries a hint (an extension point, see 
AggregateHint) is kept.
+    case a @ Aggregate(Nil, aggregateExpressions, child, None) if 
returnsExactlyOneRow(child) =>
+      val results = aggregateExpressions.flatMap(_.collect {
+        case ae: AggregateExpression => ae.canonicalized -> 
evalAggregateOnOneRow(ae)
+      }).toMap
+      if (results.values.forall(_.isDefined)) {
+        val projectList = aggregateExpressions.map(_.transformDown {
+          case ae: AggregateExpression => results(ae.canonicalized).get
+        }.asInstanceOf[NamedExpression])
+        Project(projectList, child)
+      } else {
+        a
+      }
+  }
+
+  // Strips the Projects without outer references at the top of 'plan', to 
find the node that
+  // decides how the count bug is handled. A Project with outer references 
stops the strip: it
+  // must be handled in DecorrelateInnerQuery, since constructLeftJoins 
evaluates the top node
+  // over zero rows and cannot evaluate an outer reference there.
+  private def stripTopProjects(plan: LogicalPlan): LogicalPlan = plan match {
+    case p @ Project(_, child) if !p.projectList.exists(containsOuter) => 
stripTopProjects(child)

Review Comment:
   **[1] `stripTopProjects` can strip a `Project` that holds a nested 
correlated subquery, which is then never decorrelated.** `containsOuter` does 
not look into the plan of a nested subquery, and the outer attributes of that 
subquery are plain attributes of this one. So in `SELECT a.k, (SELECT c + 
(SELECT MAX(d.y) FROM d WHERE d.z = c) FROM (SELECT COUNT(*) c FROM b WHERE b.k 
= a.k)) FROM a`, the `Project` is stripped and the subquery takes the 
`constructLeftJoins` path with `mayHaveCountBug = true`. There, the count-bug 
case of `OptimizeSubqueries` (Optimizer.scala:428) optimizes only the child of 
the `Aggregate` and keeps `projections` as they are, so the nested subquery 
keeps `OuterReference(c)` with an empty join condition. 
`evalSubqueryOnZeroTups` also copies it, with its outer attributes bound to 
`0`, into the outer `If(IsNull(alwaysTrue), ...)`. The main-plan 
`RewriteCorrelatedScalarSubquery` then joins these plans without a condition 
and leaves an unevaluable `OuterReference
 `, so the query fails. Before this PR, the `Project` top went to 
`DecorrelateInnerQuery`, and the normal path of `OptimizeSubqueries` rewrote 
the nested subquery. An uncorrelated nested subquery in such a `Project` is 
also left unoptimized. Could `stripTopProjects` also stop at a `Project` with a 
subquery expression (`p.projectList.exists(SubqueryExpression.hasSubquery)`), 
and could a test cover this shape?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -592,32 +671,69 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
     }
 
     plan.transformExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
-      case ScalarSubquery(sub, children, exprId, conditions, hint,
+      case ScalarSubquery(originalSub, children, exprId, conditions, hint,
       mayHaveCountBugOld, needSingleJoinOld)
         if children.nonEmpty =>
 
+        // An Aggregate without grouping expressions returns one row even on 
empty input,
+        // whatever its aggregate functions are, and an Aggregate above it 
sees that row. If the
+        // Aggregate is correlated, decorrelation can lose that row (see 
below). An uncorrelated
+        // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree 
without outer references
+        // (SubExprUtils.hasOuterReferences) unchanged, at most inner joining 
it with the domain,
+        // and the non-legacy branch below uses the same check. With
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only 
such an Aggregate
+        // with an aggregate function that has a default result, such as 
COUNT, qualifies,
+        // whether it is correlated or not.
+        val legacyNestedAggregateCountBug =
+          
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR)
+        val legacyCountBugHandling = 
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING)
         def mayHaveCountBugAgg(a: Aggregate): Boolean = {
-          a.groupingExpressions.isEmpty && 
a.aggregateExpressions.exists(_.exists {
-            case a: AggregateExpression => 
a.aggregateFunction.defaultResult.isDefined
-            case _ => false
+          a.groupingExpressions.isEmpty && (if (legacyNestedAggregateCountBug) 
{
+            a.aggregateExpressions.exists(_.exists {
+              case ae: AggregateExpression => 
ae.aggregateFunction.defaultResult.isDefined
+              case _ => false
+            })
+          } else {
+            SubExprUtils.hasOuterReferences(a)
           })
         }
 
+        // Collapsing an Aggregate over one row (see 
collapseAggregatesOverOneRow) and looking
+        // through the Projects at the top let constructLeftJoins handle the 
count bug of more
+        // subqueries. Neither is done when this rule runs again on a 
rewritten subquery
+        // (mayHaveCountBugOld is defined), or when the plans of earlier 
versions are kept:
+        // decorrelateInnerQuery is disabled, or 
LEGACY_SCALAR_SUBQUERY_COUNT_BUG_HANDLING or
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR is 
enabled.
+        val simplifyForCountBug = mayHaveCountBugOld.isEmpty &&

Review Comment:
   **[5] Could changes 2 and 3 go to a separate PR for `master`?** Change 1 
(`mayHaveCountBugAgg` checks correlation, L697) fixes the wrong results. 
Changes 2 and 3 (the one-row evaluation of a `DeclarativeAggregate` and the 
stripping of top `Project`s) avoid the extra joins that change 1 adds, but they 
send new plan shapes to `constructLeftJoins`, whose count-bug guard in 
`OptimizeSubqueries` and `evalSubqueryOnZeroTups` were not written for them, 
and items 1-4 all come from there. The PR description plans backports to 
`branch-4.3` through `branch-4.0`. Could this PR keep only change 1 (the extra 
joins are already listed in the description), with changes 2 and 3 proposed on 
`master` separately, so that the backports stay small?



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