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


##########
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:
   Thank you, confirmed: before the change of approach in this round (on 
130b92a, which merged `master` after 489ffd2), your query got the domain joins 
(the optimized plan read `o` three times, and once with the legacy conf). With 
the new approach (see my comment), it no longer needs them: the result of its 
`COUNT(*)` over the `MAX` for an outer row without matching rows is computed 
before decorrelation, so the plan reads `o` once, as on `master`, and every 
outer row gets `1`. For the subqueries that still need the domain joins, e.g. 
with a filter between the aggregates, the check now covers your case too: 
another subquery that may give other rows counts wherever a filter or join 
condition can bring it into the outer input: in the condition itself, and in an 
alias that a condition references, also through other aliases and, by position, 
through the children of a `UNION ALL`, and of an `EXCEPT ALL` or `INTERSECT 
ALL`, which `RewriteExceptAll` and `RewriteIntersectAll` turn into a `UNI
 ON ALL` of the children first. A subquery in any other expression that is not 
an alias, such as a sort order, also counts, except the lateral subquery of a 
`LATERAL` join, which stays in its right side. Such a subquery under your query 
keeps the previous plan, and `PullupCorrelatedPredicatesSuite` checks it with 
`limitedScalar` in a `Project` above and a filter on `x`, also through a second 
alias, a `UNION ALL`, an `EXCEPT ALL`, an `INTERSECT ALL` and a join condition, 
and without the filter. Your query put into an `EXCEPT ALL` cannot be run end 
to end, though: it fails in the optimizer with `key not found` with the legacy 
conf as well, as in [23] (SPARK-59042).
   
   Unlike 489ffd2, another subquery of the operator itself that no condition 
reaches no longer counts: the domain joins take the distinct outer references 
of the input of the operator, and the joins that 
`RewriteCorrelatedScalarSubquery` builds before for its other subqueries keep 
every row of that input, or fail (see the last point below). This matters with 
[32]: if every other subquery of the operator counted, a second correlated 
subquery with `MAX` of a `DOUBLE` in the same `SELECT` would take the fix away 
from a first one that needs the domain joins, e.g. with a filter between its 
aggregates; with a filter on the second one, it does.
   
   Going through the rules that run before `RewriteCorrelatedScalarSubquery`, I 
also found other ways into the outer input, which now count too for the 
subqueries that need the domain joins:
   - A filter above on the alias of the subquery itself pushes a copy of it 
into the outer input, which the domain joins compute again, so the subquery 
itself counts there when its plan may give other rows, e.g. over a `MAX` of a 
`DOUBLE`, even where its result, such as a `COUNT(*)` over it, cannot change.
   - `ReorderJoin` moves a filter with a correlated subquery above the other 
inputs of the inner joins around it, e.g. `SELECT * FROM (SELECT * FROM a, c 
WHERE (SELECT COUNT(*) FROM (SELECT MAX(b.v) FROM b WHERE b.k = a.k AND b.k2 = 
c.k2)) = 1) x JOIN (SELECT rk FROM r LIMIT 2) l ON x.k = l.rk` got domain joins 
that read `r` three times in this round before the check below, computing the 
`LIMIT` again (with the new approach, it gets the fix without them). A subquery 
that needs them now keeps the previous handling when such joins have an input 
that may give other rows.
   - Another correlated subquery that may return more than one row and give 
other rows when computed again, e.g. `(SELECT b.v FROM b WHERE b.k = o.k AND 
rand() < 0.5)`: when it is in the operator, or in a `Project` above that 
`CollapseProject` merges into it, `RewriteCorrelatedScalarSubquery` can join it 
to the input first (the check takes one anywhere in the plan, to be 
conservative), and the domain joins compute its single join again, which could 
then fail with `SCALAR_SUBQUERY_TOO_MANY_ROWS`. One that returns one row, such 
as an aggregate without `GROUP BY`, does not count.
   



##########
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:
   Thank you, done: `orderIrrelevant` accepts `MIN` and `MAX` only for types 
whose equal values are the same (`sameWhenEqual`), i.e. without floating-point 
values or strings of a non-binary collation, also nested. It is your check, 
except that it also looks into the SQL type of a user-defined type, which 
`needNormalize` and `isBinaryStable` do not, while `MIN` and `MAX` compare such 
values by it. Running it locally, `MAX` and `MIN` over `(-0.0D), (0.0D)` in one 
partition return `-0.0`, and over `(0.0D), (-0.0D)` return `0.0`, and likewise 
`'a'` or `'A'` in `UTF8_LCASE`. With the new approach, your query gets the fix 
without the domain joins, so the `MAX` of the outer input is computed once; the 
check above is for the subqueries that still need them.
   
   The same holds for grouping and `DISTINCT`, `INTERSECT` and `EXCEPT` over 
strings of a non-binary collation: locally, each of them over `'a'` and `'A'` 
in `UTF8_LCASE` returns whichever comes first. Floating-point keys are 
normalized, so `GROUP BY` and `DISTINCT` return `0.0` in both orders. So 
`repeatableInput` now also accepts an `Aggregate` only if its output has no 
grouping key of such a string, and `Distinct`, `Intersect` and `Except` only 
without such strings in their output (`keyStable`); neither may have a 
user-defined type over floating-point values, which `NormalizeFloatingNumbers` 
does not normalize. `PullupCorrelatedPredicatesSuite` checks `MIN` and `MAX` of 
a `DOUBLE` and of a `UTF8_LCASE` string, `MAX` of a struct with a `DOUBLE` and 
of a user-defined type over `DOUBLE`s, grouping, `DISTINCT`, `INTERSECT` and 
`EXCEPT` over a `UTF8_LCASE` string, and grouping and `DISTINCT` over that 
user-defined type, which keep the previous handling, and `MAX` of an `INT`, a 
`UTF8_L
 CASE` grouping key that is not in the output, and grouping, `DISTINCT` and 
`INTERSECT` over a `DOUBLE`, which get the fix.
   



##########
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:
   Done: `apply` builds the check once for its plan and passes it to 
`rewriteAll`, which has the old body of `apply`. This re-indents that body 
again, which [29] had avoided, since the check has to be built outside of 
`transformUpWithPruning`; otherwise it only passes `mayMove` in the four calls. 
The check computes lazily, and once per plan, whether a filter or join 
condition is non-deterministic and the `exprId`s of the subqueries that count 
(see [31]); each subquery then only looks them up. The attributes that 
conditions reach are computed only if some subquery may give other rows. The 
check of the other subqueries of `plan` next to `inputRepeatable` is gone with 
[34].
   



##########
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:
   Done, with [31]: one check looks at all of `root`, and L775-780 are gone. Of 
the subqueries in `root` whose plan may give other rows when computed again, it 
does not take one in an alias that no filter or join condition reaches, for the 
reason in my reply to [31], except a correlated one that may return more than 
one row.
   



##########
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:
   Done: the lower `Aggregate`s are collected once in `lowerAggs`, as you 
suggested, and the checks of `rewriteSubQueries` over them use it: 
`mayHaveCountBugAgg`, `noDefaultResultCountBugAgg`, the UDF check and the new 
one for user-defined aggregate functions (see my comment).
   



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