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


##########
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:
   Reverted with the collapse. I will compute the arguments once in a `Project` 
below in the separate PR.
   



##########
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:
   The revert removed the second check and `simplifyForCountBug`. The condition 
that this PR changes, and `decorrelate()` next to it, now read the confs 
through `conf`. I left `SQLConf.get` in the `EXISTS` and `IN` branches, which 
this PR does not change.
   



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