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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -593,47 +744,92 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
         sub: LogicalPlan,
         outer: LogicalPlan,
         handleCountBug: Boolean = false): (LogicalPlan, Seq[Expression]) = {
-      if (SQLConf.get.decorrelateInnerQueryEnabled) {
+      if (conf.decorrelateInnerQueryEnabled) {
         DecorrelateInnerQuery(sub, outer, handleCountBug)
       } else {
         pullOutCorrelatedPredicates(sub, outer)
       }
     }
 
+    // Whether the outer input of `plan` gives the same rows when computed 
again (see below).
+    lazy val inputRepeatable = plan.children.forall(repeatableInput(_))
+
     plan.transformExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
-      case ScalarSubquery(sub, children, exprId, conditions, hint,
+      case ScalarSubquery(sub, outerAttrs, exprId, conditions, hint,
       mayHaveCountBugOld, needSingleJoinOld)
-        if children.nonEmpty =>
-
-        def mayHaveCountBugAgg(a: Aggregate): Boolean = {
-          a.groupingExpressions.isEmpty && 
a.aggregateExpressions.exists(_.exists {
-            case a: AggregateExpression => 
a.aggregateFunction.defaultResult.isDefined
-            case _ => false
-          })
-        }
+        if outerAttrs.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
+        // unchanged or inner joins it with the domain, and mayHaveCountBugAgg 
uses the same check
+        // (SubExprUtils.hasOuterReferences).
+        // An Aggregate with an aggregate function with a default result, such 
as COUNT, also
+        // qualifies, correlated or not, as before SPARK-60501. Only such an 
Aggregate does with
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, and 
where the domain joins
+        // of DecorrelateInnerQuery are known not to work, so as not to make 
such queries worse
+        // than before: where the outer input may give other rows when 
computed again (see
+        // repeatableInput and mayMoveIntoOuterInput), and for outer 
references that are not
+        // orderable, for which the domain joins fail.
+        // A filter above can also inline another subquery of `plan` through 
its alias, so those
+        // are checked as well.
+        lazy val domainJoinsWork = inputRepeatable &&
+          plan.expressions.forall(_.collect {

Review Comment:
   **[31] Minor: following up on [24], a filter above can also inline a 
subquery of a `Project` above the operator with the subquery, which neither 
L777-780 nor `mayMoveIntoOuterInput` looks at.**
   
   Thank you for checking the other subqueries of the operator for [24]. 
L777-780 look only at `plan.expressions`, and `mayMoveIntoOuterInput` only at 
the conditions of `Filter`s and `Join`s, but `PushPredicateThroughNonJoin` 
replaces the aliases of each `Project` that it pushes a condition through 
(Optimizer.scala:2844-2850). For
   
   ```sql
   SELECT * FROM (
     SELECT k, c, (SELECT t.x FROM t LIMIT 1) x
     FROM (SELECT o.k, (SELECT COUNT(*) FROM (SELECT MAX(b.v) FROM b WHERE b.k 
= o.k)) c FROM o))
   WHERE x > 0
   ```
   
   the subquery with the `LIMIT 1` is in the `Project` above `plan`, and the 
`Filter` has only `x > 0`, so both checks accept it. Then `PushDownPredicates` 
(Optimizer.scala:108) pushes `(SELECT t.x FROM t LIMIT 1) > 0` through both 
`Project`s into `o` before `RewriteCorrelatedScalarSubquery` 
(Optimizer.scala:152) builds the domain joins. That is the filter of [24], 
which `PullupCorrelatedPredicatesSuite` keeps on the previous handling 
(PullupCorrelatedPredicatesSuite.scala:306-312), so, as there, a matched outer 
row missing from the domain can get `NULL` instead of `1`, while `master` has 
no domain join for this shape. Could the check also look at the subqueries of 
the operators above `plan` (see [34] for one way), and could the suite cover 
this shape, with `limitedScalar` in a `Project` above and a filter on `x`?
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -576,7 +576,158 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
      nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
    }
 
-  private def rewriteSubQueries(plan: LogicalPlan): LogicalPlan = {
+  // Whether some aggregate function of `a` has a default result on empty 
input, such as COUNT.
+  private def hasDefaultResult(a: Aggregate): Boolean =
+    a.aggregateExpressions.exists(_.exists {
+      case ae: AggregateExpression => 
ae.aggregateFunction.defaultResult.isDefined
+      case _ => false
+    })
+
+  /**
+   * Returns true if the Aggregate without grouping expressions `agg` returns 
the same result
+   * over the one row that the Aggregate without grouping expressions below it 
returns on empty
+   * input as over no rows, so that constructLeftJoins handles its count bug 
correctly even
+   * though decorrelation loses that row, with fewer joins than 
DecorrelateInnerQuery. E.g.
+   * SUM(s) and COLLECT_LIST(s) over s = MAX(b.v) return NULL and [] over 
both. The check is
+   * conservative: it accepts only a short list of functions of `agg` directly 
over outputs of
+   * lower aggregate functions, with only Projects between, and leaves other 
shapes that have
+   * this property, such as STDDEV_SAMP(s), to DecorrelateInnerQuery. It never 
accepts a lower
+   * Aggregate with a function with a `defaultResult`, such as COUNT, which 
DecorrelateInnerQuery
+   * handled before SPARK-60501. Like the rest of the count bug handling, this 
relies on
+   * `defaultResult` matching the result on empty input.
+   */
+  private def sameResultOverEmptyLowerAggregate(agg: Aggregate): Boolean = {
+    // The attributes of `plan` that the count bug handling takes as NULL when 
the lower Aggregate
+    // gets empty input.
+    def nullOnEmptyInput(plan: LogicalPlan): Option[AttributeSet] = plan match 
{
+      case Project(projectList, child) =>
+        nullOnEmptyInput(child).map { attrs =>
+          AttributeSet(projectList.collect {
+            case a: Attribute if attrs.contains(a) => a
+            case a @ Alias(c: Attribute, _) if attrs.contains(c) => 
a.toAttribute
+          })
+        }
+      case lower: Aggregate if lower.groupingExpressions.isEmpty &&
+          !lower.child.exists(_.isInstanceOf[Aggregate]) && 
!hasDefaultResult(lower) =>
+        Some(AttributeSet(lower.aggregateExpressions.collect {
+          case a @ Alias(_: AggregateExpression, _) => a.toAttribute
+        }))
+      case _ => None
+    }
+    val aggregates = agg.aggregateExpressions.flatMap(_.collect {
+      case ae: AggregateExpression => ae
+    })
+    agg.groupingExpressions.isEmpty &&
+      nullOnEmptyInput(agg.child).exists { attrs =>
+        aggregates.forall { ae =>
+          val sameResultOverNulls = ae.aggregateFunction match {
+            case _: Max | _: Min | _: Sum | _: Average | _: Count | _: First | 
_: Last => true
+            // With RESPECT NULLS, they collect the NULLs.
+            case c: CollectList => c.ignoreNulls
+            case c: CollectSet => c.ignoreNulls
+            case _ => false
+          }
+          // A FILTER condition can fail on the row of NULLs, which 
constructLeftJoins does not
+          // evaluate it on, so it is left to DecorrelateInnerQuery.
+          ae.filter.isEmpty && sameResultOverNulls && 
ae.aggregateFunction.children.forall {
+            case a: Attribute => attrs.contains(a)
+            case _ => false
+          }
+        }
+      }
+  }
+
+  /**
+   * Whether `input`, the outer input of an operator with a correlated 
subquery, gives the same
+   * rows when the domain joins of [[DecorrelateInnerQuery]] compute it again. 
The check is
+   * conservative: it accepts only operators known to keep the same rows, 
deterministic
+   * expressions, aggregate functions whose result does not depend on the 
order of the rows, and
+   * leaf nodes other than a CTE that is not inlined (which may be a 
non-deterministic one; a
+   * CTERelationRef does not tell) and a streaming source (for which the 
domain joins fail). It
+   * also checks the plans of the subqueries in `input`. A relation is taken 
to give the same
+   * rows again, as elsewhere in Spark, e.g. in a self-join; a LogicalRDD over 
an RDD that does
+   * not is not detected. Anything else, e.g. a LIMIT (other than over rows of 
constants), a
+   * window function, a sample or a FIRST, keeps the previous handling.
+   */
+  private def repeatableInput(input: LogicalPlan, inSubquery: Boolean = 
false): Boolean =
+    !input.exists { p =>
+      val known = p match {
+        case _: Project | _: Filter | _: Join | _: Union | _: Distinct | _: 
Intersect | _: Except |
+             _: Sort | _: SubqueryAlias | _: RepartitionOperation | _: 
LateralJoin => true
+        // The domain join of a subquery of an operator in `input` takes its 
domain from the input
+        // of that operator, which this check accepts too. Directly in 
`input`, its domain comes
+        // from outside the plan this rule sees.
+        case _: DomainJoin => inSubquery
+        // E.g. the LIMIT 1 that RewriteNonCorrelatedExists adds for an 
uncorrelated EXISTS.
+        case l @ (_: LocalLimit | _: GlobalLimit) => 
constantOutput(l.children.head)
+        case a: Aggregate => !a.aggregateExpressions.exists(_.exists {
+          case ae: AggregateExpression => 
!orderIrrelevant(ae.aggregateFunction)
+          case _ => false
+        })
+        case _: CTERelationRef => false
+        case l: LeafNode => !l.isStreaming
+        case _ => false
+      }
+      !known || !p.expressions.forall(_.deterministic) ||
+        !p.subqueries.forall(repeatableInput(_, inSubquery = true))
+    }
+
+  // Whether every row of `plan` is the same row of constants, so that a LIMIT 
over it gives the
+  // same rows whichever rows it keeps.
+  private def constantOutput(plan: LogicalPlan): Boolean = plan match {
+    case Project(projectList, _) => projectList.forall(trimAliases(_).foldable)
+    case l @ (_: LocalLimit | _: GlobalLimit) => 
constantOutput(l.children.head)
+    case _ => false
+  }
+
+  // Whether `f` gives the same value when computed again over the same rows 
in another order.
+  // This is stricter than EliminateSorts.isOrderIrrelevantAggFunction, which 
only needs the
+  // result not to depend on a Sort below the aggregate: floating-point 
addition is not
+  // associative, so neither a SUM of floating-point values nor an AVG of 
anything but decimals
+  // and ANSI intervals, which AVG adds up as DOUBLE, nor a CentralMomentAgg 
qualifies; and a SUM
+  // or AVG of decimals becomes NULL on an overflow that depends on the order 
unless in ANSI
+  // mode, where the overflow fails the query; try_sum and try_avg become NULL 
on an overflow in
+  // any mode.
+  private def orderIrrelevant(f: AggregateFunction): Boolean = f match {
+    case _: Min | _: Max | _: Count | _: BitAndAgg | _: BitOrAgg | _: 
BitXorAgg => true

Review Comment:
   **[32] Minor: following up on [18] and [27], `MIN` and `MAX` return the 
first of the values that compare equal, so the domain joins can compute another 
value than the main copy.**
   
   `Max` updates its buffer with `greatest(max, child)` and merges with 
`greatest(max.left, max.right)` (Max.scala:63 and Max.scala:68), and `Greatest` 
keeps the earlier value unless a later one is greater (arithmetic.scala:1667). 
So for values that compare equal but are not the same, the result depends on 
the order of the rows and of the partial results: `-0.0` and `0.0`, which 
`SQLOrderingUtil.compareDoubles` takes as equal (SQLOrderingUtil.scala:29) and 
`NormalizeFloatingNumbers` normalizes only in grouping, join and window 
partition keys, and strings of a non-binary collation, such as `'a'` and `'A'` 
in `UTF8_LCASE`. `Min` is the same with `least`.
   
   With an outer input such as `(SELECT k, MAX(d) m FROM t GROUP BY k HAVING 
CAST(MAX(d) AS STRING) = '0.0') o`, over a group of `k` with both `-0.0` and 
`0.0`, the domain joins compute `MAX` again in another stage, as `AVG` in [18]. 
If they get `-0.0` there, `k` is missing from the domain, so the outer row of 
`k` gets `NULL` instead of `1`, even when it has matching rows in `b`. A filter 
above on `m`, which `PushDownPredicates` pushes into the outer input, does the 
same. On `master`, this shape has no domain join. Could `orderIrrelevant` 
accept `Min` and `Max` only for a type whose equal values are the same, e.g. 
`!NormalizeFloatingNumbers.needNormalize(dt) && 
UnsafeRowUtils.isBinaryStable(dt)`, or could the comment above say that it 
takes them as order-irrelevant anyway?
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -576,7 +576,158 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
      nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
    }
 
-  private def rewriteSubQueries(plan: LogicalPlan): LogicalPlan = {
+  // Whether some aggregate function of `a` has a default result on empty 
input, such as COUNT.
+  private def hasDefaultResult(a: Aggregate): Boolean =
+    a.aggregateExpressions.exists(_.exists {
+      case ae: AggregateExpression => 
ae.aggregateFunction.defaultResult.isDefined
+      case _ => false
+    })
+
+  /**
+   * Returns true if the Aggregate without grouping expressions `agg` returns 
the same result
+   * over the one row that the Aggregate without grouping expressions below it 
returns on empty
+   * input as over no rows, so that constructLeftJoins handles its count bug 
correctly even
+   * though decorrelation loses that row, with fewer joins than 
DecorrelateInnerQuery. E.g.
+   * SUM(s) and COLLECT_LIST(s) over s = MAX(b.v) return NULL and [] over 
both. The check is
+   * conservative: it accepts only a short list of functions of `agg` directly 
over outputs of
+   * lower aggregate functions, with only Projects between, and leaves other 
shapes that have
+   * this property, such as STDDEV_SAMP(s), to DecorrelateInnerQuery. It never 
accepts a lower
+   * Aggregate with a function with a `defaultResult`, such as COUNT, which 
DecorrelateInnerQuery
+   * handled before SPARK-60501. Like the rest of the count bug handling, this 
relies on
+   * `defaultResult` matching the result on empty input.
+   */
+  private def sameResultOverEmptyLowerAggregate(agg: Aggregate): Boolean = {
+    // The attributes of `plan` that the count bug handling takes as NULL when 
the lower Aggregate
+    // gets empty input.
+    def nullOnEmptyInput(plan: LogicalPlan): Option[AttributeSet] = plan match 
{
+      case Project(projectList, child) =>
+        nullOnEmptyInput(child).map { attrs =>
+          AttributeSet(projectList.collect {
+            case a: Attribute if attrs.contains(a) => a
+            case a @ Alias(c: Attribute, _) if attrs.contains(c) => 
a.toAttribute
+          })
+        }
+      case lower: Aggregate if lower.groupingExpressions.isEmpty &&
+          !lower.child.exists(_.isInstanceOf[Aggregate]) && 
!hasDefaultResult(lower) =>
+        Some(AttributeSet(lower.aggregateExpressions.collect {
+          case a @ Alias(_: AggregateExpression, _) => a.toAttribute
+        }))
+      case _ => None
+    }
+    val aggregates = agg.aggregateExpressions.flatMap(_.collect {
+      case ae: AggregateExpression => ae
+    })
+    agg.groupingExpressions.isEmpty &&
+      nullOnEmptyInput(agg.child).exists { attrs =>
+        aggregates.forall { ae =>
+          val sameResultOverNulls = ae.aggregateFunction match {
+            case _: Max | _: Min | _: Sum | _: Average | _: Count | _: First | 
_: Last => true
+            // With RESPECT NULLS, they collect the NULLs.
+            case c: CollectList => c.ignoreNulls
+            case c: CollectSet => c.ignoreNulls
+            case _ => false
+          }
+          // A FILTER condition can fail on the row of NULLs, which 
constructLeftJoins does not
+          // evaluate it on, so it is left to DecorrelateInnerQuery.
+          ae.filter.isEmpty && sameResultOverNulls && 
ae.aggregateFunction.children.forall {
+            case a: Attribute => attrs.contains(a)
+            case _ => false
+          }
+        }
+      }
+  }
+
+  /**
+   * Whether `input`, the outer input of an operator with a correlated 
subquery, gives the same
+   * rows when the domain joins of [[DecorrelateInnerQuery]] compute it again. 
The check is
+   * conservative: it accepts only operators known to keep the same rows, 
deterministic
+   * expressions, aggregate functions whose result does not depend on the 
order of the rows, and
+   * leaf nodes other than a CTE that is not inlined (which may be a 
non-deterministic one; a
+   * CTERelationRef does not tell) and a streaming source (for which the 
domain joins fail). It
+   * also checks the plans of the subqueries in `input`. A relation is taken 
to give the same
+   * rows again, as elsewhere in Spark, e.g. in a self-join; a LogicalRDD over 
an RDD that does
+   * not is not detected. Anything else, e.g. a LIMIT (other than over rows of 
constants), a
+   * window function, a sample or a FIRST, keeps the previous handling.
+   */
+  private def repeatableInput(input: LogicalPlan, inSubquery: Boolean = 
false): Boolean =
+    !input.exists { p =>
+      val known = p match {
+        case _: Project | _: Filter | _: Join | _: Union | _: Distinct | _: 
Intersect | _: Except |
+             _: Sort | _: SubqueryAlias | _: RepartitionOperation | _: 
LateralJoin => true
+        // The domain join of a subquery of an operator in `input` takes its 
domain from the input
+        // of that operator, which this check accepts too. Directly in 
`input`, its domain comes
+        // from outside the plan this rule sees.
+        case _: DomainJoin => inSubquery
+        // E.g. the LIMIT 1 that RewriteNonCorrelatedExists adds for an 
uncorrelated EXISTS.
+        case l @ (_: LocalLimit | _: GlobalLimit) => 
constantOutput(l.children.head)
+        case a: Aggregate => !a.aggregateExpressions.exists(_.exists {
+          case ae: AggregateExpression => 
!orderIrrelevant(ae.aggregateFunction)
+          case _ => false
+        })
+        case _: CTERelationRef => false
+        case l: LeafNode => !l.isStreaming
+        case _ => false
+      }
+      !known || !p.expressions.forall(_.deterministic) ||
+        !p.subqueries.forall(repeatableInput(_, inSubquery = true))
+    }
+
+  // Whether every row of `plan` is the same row of constants, so that a LIMIT 
over it gives the
+  // same rows whichever rows it keeps.
+  private def constantOutput(plan: LogicalPlan): Boolean = plan match {
+    case Project(projectList, _) => projectList.forall(trimAliases(_).foldable)
+    case l @ (_: LocalLimit | _: GlobalLimit) => 
constantOutput(l.children.head)
+    case _ => false
+  }
+
+  // Whether `f` gives the same value when computed again over the same rows 
in another order.
+  // This is stricter than EliminateSorts.isOrderIrrelevantAggFunction, which 
only needs the
+  // result not to depend on a Sort below the aggregate: floating-point 
addition is not
+  // associative, so neither a SUM of floating-point values nor an AVG of 
anything but decimals
+  // and ANSI intervals, which AVG adds up as DOUBLE, nor a CentralMomentAgg 
qualifies; and a SUM
+  // or AVG of decimals becomes NULL on an overflow that depends on the order 
unless in ANSI
+  // mode, where the overflow fails the query; try_sum and try_avg become NULL 
on an overflow in
+  // any mode.
+  private def orderIrrelevant(f: AggregateFunction): Boolean = f match {
+    case _: Min | _: Max | _: Count | _: BitAndAgg | _: BitOrAgg | _: 
BitXorAgg => true
+    case s: Sum => s.child.dataType match {
+      case FloatType | DoubleType => false
+      case _: DecimalType => s.evalContext.evalMode == EvalMode.ANSI
+      case _ => s.evalContext.evalMode != EvalMode.TRY
+    }
+    case a: Average => a.child.dataType match {
+      case _: DecimalType => a.evalMode == EvalMode.ANSI
+      case _: AnsiIntervalType => a.evalMode != EvalMode.TRY
+      case _ => false
+    }
+    case _ => false
+  }
+
+  /**
+   * Whether the operators above the operator with the correlated subquery 
`exprId` in `root`,
+   * the plan this rule runs on (the whole query, or the plan of a subquery 
when
+   * OptimizeSubqueries optimizes it), may put something into its outer input 
that gives other
+   * rows when computed again, through the rules that run before 
RewriteCorrelatedScalarSubquery
+   * builds the domain joins: PushDownPredicates can push a filter or join 
condition there. The
+   * check is conservative and looks at all of `root`. Of the cases of 
LimitPushDown for a Project,
+   * the ones into a join and, for a LIMIT 1, through a group-only Aggregate 
keep the LIMIT above
+   * a Project with a scalar subquery with a domain join with keepLimitAbove;
+   * the ones over UDF evaluation nodes or a UnionLoop occur only after the 
rewrite or in inputs
+   * that repeatableInput rejects. A correlated scalar subquery in a grouping 
expression is in a
+   * Project below the Aggregate by then (PullOutGroupingExpressions).
+   */
+  private def mayMoveIntoOuterInput(root: LogicalPlan, exprId: ExprId): 
Boolean =
+    root.exists {
+      case p @ (_: Filter | _: Join) =>

Review Comment:
   **[34] Nit: following up on [31], two places check whether another subquery 
can move into the outer input, and [31] falls between them.**
   
   L777-780 check the other subqueries of `plan`, which a filter above can 
inline through their aliases, and this function checks the subqueries in the 
conditions of `Filter`s and `Join`s in `root`, which `PushDownPredicates` can 
push. Since this function already looks at all of `root` (L712), could it check 
the subqueries in the expressions of every operator in `root` other than 
`exprId`, so that one check covers both and [31], and L775-780 go away? With 
[33], it would also be computed once.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -593,47 +744,92 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
         sub: LogicalPlan,
         outer: LogicalPlan,
         handleCountBug: Boolean = false): (LogicalPlan, Seq[Expression]) = {
-      if (SQLConf.get.decorrelateInnerQueryEnabled) {
+      if (conf.decorrelateInnerQueryEnabled) {
         DecorrelateInnerQuery(sub, outer, handleCountBug)
       } else {
         pullOutCorrelatedPredicates(sub, outer)
       }
     }
 
+    // Whether the outer input of `plan` gives the same rows when computed 
again (see below).
+    lazy val inputRepeatable = plan.children.forall(repeatableInput(_))
+
     plan.transformExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
-      case ScalarSubquery(sub, children, exprId, conditions, hint,
+      case ScalarSubquery(sub, outerAttrs, exprId, conditions, hint,
       mayHaveCountBugOld, needSingleJoinOld)
-        if children.nonEmpty =>
-
-        def mayHaveCountBugAgg(a: Aggregate): Boolean = {
-          a.groupingExpressions.isEmpty && 
a.aggregateExpressions.exists(_.exists {
-            case a: AggregateExpression => 
a.aggregateFunction.defaultResult.isDefined
-            case _ => false
-          })
-        }
+        if outerAttrs.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
+        // unchanged or inner joins it with the domain, and mayHaveCountBugAgg 
uses the same check
+        // (SubExprUtils.hasOuterReferences).
+        // An Aggregate with an aggregate function with a default result, such 
as COUNT, also
+        // qualifies, correlated or not, as before SPARK-60501. Only such an 
Aggregate does with
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, and 
where the domain joins
+        // of DecorrelateInnerQuery are known not to work, so as not to make 
such queries worse
+        // than before: where the outer input may give other rows when 
computed again (see
+        // repeatableInput and mayMoveIntoOuterInput), and for outer 
references that are not
+        // orderable, for which the domain joins fail.
+        // A filter above can also inline another subquery of `plan` through 
its alias, so those
+        // are checked as well.
+        lazy val domainJoinsWork = inputRepeatable &&
+          plan.expressions.forall(_.collect {
+            case s: SubqueryExpression if s.exprId != exprId => s
+          }.forall(s => repeatableInput(s.plan, inSubquery = true))) &&
+          !mayMoveIntoOuterInput(root, exprId) &&
+          outerAttrs.forall(e => RowOrdering.isOrderable(e.dataType))
+        lazy val onlyDefaultResultSelectsDecorrelation =
+          
conf.getConf(SQLConf.LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR)
 ||
+            !domainJoinsWork
+        // The lower Aggregates that selected decorrelation before SPARK-60501.
+        def defaultResultCountBugAgg(a: Aggregate): Boolean =
+          a.groupingExpressions.isEmpty && hasDefaultResult(a)
+        def mayHaveCountBugAgg(a: Aggregate): Boolean = 
defaultResultCountBugAgg(a) ||
+          (a.groupingExpressions.isEmpty && SubExprUtils.hasOuterReferences(a) 
&&
+            !onlyDefaultResultSelectsDecorrelation)
 
         // 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 &&
+        // [[DecorrelateInnerQuery]] is correct where its domain joins work 
(see domainJoinsWork
+        // above), and turning it off to handle it in constructLeftJoins is 
otherwise an
+        // optimization, so that additional, redundant left outer joins are 
not introduced.
+        val handleCountBugInDecorrelate = conf.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)
+          // If the top level node is an Agg, handle count bug in 
DecorrelateInnerQuery only if
+          // there exists a lower level Agg for which mayHaveCountBugAgg 
holds. Decorrelation
+          // groups a correlated lower level Agg by the outer (domain) 
columns, so it returns no
+          // row for an outer row without matching rows, instead of the one 
row it returns on
+          // empty input. constructLeftJoins only handles the count bug of the 
top level Agg and
+          // cannot bring back that row. Whether it is needed does not follow 
from whether the
+          // aggregate functions have a default result, e.g. COUNT(COUNT + 
COUNT), SUM(COUNT),
+          // COUNT(*) over MAX and SUM(COALESCE(SUM, 0)) all need it. Some 
shapes do not, because
+          // the top level Agg returns the same result over that row as over 
no rows, e.g. SUM(s)
+          // and COLLECT_LIST(s) over s = MAX; they are handled in 
constructLeftJoins, with fewer
+          // joins (see sameResultOverEmptyLowerAggregate).
           case agg: Aggregate => !agg.child.exists {
             case lowerAgg: Aggregate => mayHaveCountBugAgg(lowerAgg)
             case _ => false
-          }
+          } || sameResultOverEmptyLowerAggregate(agg)
           case _ => false
         })
-        val (newPlan, newCond) = decorrelate(sub, plan, 
handleCountBugInDecorrelate)
+        val (decorrelatedPlan, newCond) = decorrelate(sub, plan, 
handleCountBugInDecorrelate)
+        // With handleCountBugInDecorrelate, this says that the count bug is 
handled in
+        // DecorrelateInnerQuery only since SPARK-60501 (see 
DomainJoin.keepLimitAbove).
+        lazy val noDefaultResultCountBugAgg = sub match {

Review Comment:
   **[35] Nit: `noDefaultResultCountBugAgg` walks the lower `Aggregate`s again 
for `defaultResultCountBugAgg`, which `mayHaveCountBugAgg` already evaluates on 
each of them at L812-815.**
   
   Both blocks repeat `sub match { case agg: Aggregate => agg.child.exists { 
case lowerAgg: Aggregate => ... } }`, and the marking at L828-829 depends on 
the two staying in step. Could the lower `Aggregate`s be collected once, e.g.
   
   ```scala
   val lowerAggs = sub match {
     case agg: Aggregate => agg.child.collect { case a: Aggregate => a }
     case _ => Nil
   }
   ```
   
   with `lowerAggs.exists(mayHaveCountBugAgg)` at L812-815 and 
`sub.isInstanceOf[Aggregate] && !lowerAggs.exists(defaultResultCountBugAgg)` 
here?
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -593,47 +744,92 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
         sub: LogicalPlan,
         outer: LogicalPlan,
         handleCountBug: Boolean = false): (LogicalPlan, Seq[Expression]) = {
-      if (SQLConf.get.decorrelateInnerQueryEnabled) {
+      if (conf.decorrelateInnerQueryEnabled) {
         DecorrelateInnerQuery(sub, outer, handleCountBug)
       } else {
         pullOutCorrelatedPredicates(sub, outer)
       }
     }
 
+    // Whether the outer input of `plan` gives the same rows when computed 
again (see below).
+    lazy val inputRepeatable = plan.children.forall(repeatableInput(_))
+
     plan.transformExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
-      case ScalarSubquery(sub, children, exprId, conditions, hint,
+      case ScalarSubquery(sub, outerAttrs, exprId, conditions, hint,
       mayHaveCountBugOld, needSingleJoinOld)
-        if children.nonEmpty =>
-
-        def mayHaveCountBugAgg(a: Aggregate): Boolean = {
-          a.groupingExpressions.isEmpty && 
a.aggregateExpressions.exists(_.exists {
-            case a: AggregateExpression => 
a.aggregateFunction.defaultResult.isDefined
-            case _ => false
-          })
-        }
+        if outerAttrs.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
+        // unchanged or inner joins it with the domain, and mayHaveCountBugAgg 
uses the same check
+        // (SubExprUtils.hasOuterReferences).
+        // An Aggregate with an aggregate function with a default result, such 
as COUNT, also
+        // qualifies, correlated or not, as before SPARK-60501. Only such an 
Aggregate does with
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, and 
where the domain joins
+        // of DecorrelateInnerQuery are known not to work, so as not to make 
such queries worse
+        // than before: where the outer input may give other rows when 
computed again (see
+        // repeatableInput and mayMoveIntoOuterInput), and for outer 
references that are not
+        // orderable, for which the domain joins fail.
+        // A filter above can also inline another subquery of `plan` through 
its alias, so those
+        // are checked as well.
+        lazy val domainJoinsWork = inputRepeatable &&
+          plan.expressions.forall(_.collect {
+            case s: SubqueryExpression if s.exprId != exprId => s
+          }.forall(s => repeatableInput(s.plan, inSubquery = true))) &&
+          !mayMoveIntoOuterInput(root, exprId) &&

Review Comment:
   **[33] Nit: following up on [28], `mayMoveIntoOuterInput(root, exprId)` 
walks all of `root` again for each correlated scalar subquery.**
   
   `domainJoinsWork` is a `lazy val` inside the `case`, so for each correlated 
scalar subquery over a correlated lower `Aggregate` without a default result, 
`mayMoveIntoOuterInput` walks all of `root` and checks the plan of each 
subquery in a `Filter` or `Join` condition with `repeatableInput`, and L778-780 
check the other subqueries of `plan` the same way. A query with `n` such 
subqueries then walks `root` `n` times, and an operator with `k` of them checks 
its subqueries about `k * k` times, though only `s.exprId != exprId` depends on 
the subquery. Could the `exprId`s of the subqueries that fail 
`repeatableInput`, and whether a `Filter` or `Join` is non-deterministic, be 
computed once for `root` in `apply` (and for `plan` next to `inputRepeatable`), 
so that each subquery only checks that no other `exprId` is in that set?
   



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