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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,7 +567,168 @@ 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
+   * leaves 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`. 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 {
+      case Alias(child, _) => child.foldable
+      case e => e.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.
+  private def orderIrrelevant(f: AggregateFunction): Boolean = f match {
+    case _: Min | _: Max | _: Count | _: BitAndAgg | _: BitOrAgg | _: 
BitXorAgg => true
+    case _: Sum => !f.children.exists(c => c.dataType == FloatType || 
c.dataType == DoubleType)
+    case _: Average => f.children.forall(c =>
+      c.dataType.isInstanceOf[DecimalType] || 
c.dataType.isInstanceOf[AnsiIntervalType])
+    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, and
+   * LimitPushDown a LIMIT, into the inputs of some joins or, for a LIMIT 1, 
below a group-only
+   * aggregate (see limitMayBePushedIn). The check is conservative and looks 
at all of `root`.
+   */
+  private def mayMoveIntoOuterInput(root: LogicalPlan, exprId: ExprId): 
Boolean =
+    root.exists {
+      case p @ (_: Filter | _: Join) =>
+        !p.expressions.forall(_.deterministic) || 
p.expressions.exists(_.exists {
+          case s: SubqueryExpression =>
+            s.exprId != exprId && !repeatableInput(s.plan, inSubquery = true)
+          case _ => false
+        })
+      case l @ LocalLimit(limitExpr, child) =>
+        limitMayBePushedIn(child, limitExpr == Literal(1))
+      case _ => false
+    }
+
+  // Whether LimitPushDown can push a LIMIT above `plan` (a LIMIT 1 if `one`) 
into the input of a
+  // join or below a group-only aggregate in it, following its cases: through 
a UNION ALL, an
+  // OFFSET and a Project over a join, into the sides of an outer join with a 
condition that it
+  // keeps the rows of, and into a join without a condition, and, for a LIMIT 
1, below a
+  // group-only aggregate, which a DISTINCT, INTERSECT, EXCEPT or Deduplicate 
becomes.
+  private def limitMayBePushedIn(plan: LogicalPlan, one: Boolean): Boolean = 
plan match {
+    case u: Union => u.children.exists(limitMayBePushedIn(_, one))
+    case o: Offset => limitMayBePushedIn(o.child, one = false)
+    case Project(_, j: Join) => limitMayBePushedIn(j, one)

Review Comment:
   Thank you, I took [25] for this, see the reply there. With it, a `LIMIT` 
above the `Project` with the subquery stays above it until 
`RewriteCorrelatedScalarSubquery` has built the domain joins, whatever 
`PushDownPredicates` does first. For your two shapes (`WHERE o.k > 0` between, 
and `JOIN c ON c.flag = 1`), the optimized plan on 297f6fe080b has the domain 
joins and as many `LocalLimit`s as with the legacy conf, and none in the right 
side of a join; `SubquerySuite` checks both, and the `LEFT JOIN` without the 
filter.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,7 +567,168 @@ 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
+   * leaves 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`. 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 {
+      case Alias(child, _) => child.foldable
+      case e => e.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.
+  private def orderIrrelevant(f: AggregateFunction): Boolean = f match {
+    case _: Min | _: Max | _: Count | _: BitAndAgg | _: BitOrAgg | _: 
BitXorAgg => true
+    case _: Sum => !f.children.exists(c => c.dataType == FloatType || 
c.dataType == DoubleType)
+    case _: Average => f.children.forall(c =>
+      c.dataType.isInstanceOf[DecimalType] || 
c.dataType.isInstanceOf[AnsiIntervalType])
+    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, and
+   * LimitPushDown a LIMIT, into the inputs of some joins or, for a LIMIT 1, 
below a group-only
+   * aggregate (see limitMayBePushedIn). The check is conservative and looks 
at all of `root`.
+   */
+  private def mayMoveIntoOuterInput(root: LogicalPlan, exprId: ExprId): 
Boolean =
+    root.exists {
+      case p @ (_: Filter | _: Join) =>
+        !p.expressions.forall(_.deterministic) || 
p.expressions.exists(_.exists {
+          case s: SubqueryExpression =>
+            s.exprId != exprId && !repeatableInput(s.plan, inSubquery = true)
+          case _ => false
+        })
+      case l @ LocalLimit(limitExpr, child) =>
+        limitMayBePushedIn(child, limitExpr == Literal(1))
+      case _ => false
+    }
+
+  // Whether LimitPushDown can push a LIMIT above `plan` (a LIMIT 1 if `one`) 
into the input of a
+  // join or below a group-only aggregate in it, following its cases: through 
a UNION ALL, an
+  // OFFSET and a Project over a join, into the sides of an outer join with a 
condition that it
+  // keeps the rows of, and into a join without a condition, and, for a LIMIT 
1, below a
+  // group-only aggregate, which a DISTINCT, INTERSECT, EXCEPT or Deduplicate 
becomes.
+  private def limitMayBePushedIn(plan: LogicalPlan, one: Boolean): Boolean = 
plan match {
+    case u: Union => u.children.exists(limitMayBePushedIn(_, one))
+    case o: Offset => limitMayBePushedIn(o.child, one = false)
+    case Project(_, j: Join) => limitMayBePushedIn(j, one)
+    case j: Join => (j.joinType, j.condition) match {
+      case (LeftOuter | RightOuter, Some(_)) => true
+      case (_: InnerLike | LeftOuter | RightOuter | FullOuter | LeftSemi | 
LeftAnti, None) => true
+      case _ => false
+    }
+    case Project(_, child) if one => limitMayBePushedIn(child, one)

Review Comment:
   The same change should cover this: after `PushProjectionThroughUnion`, 
`LimitPushDown` puts a `LocalLimit` above each child of the `UNION ALL`, and 
the new guard keeps it above the `Project` with the subquery in that child. I 
could not check it with your query, though: it fails in the optimizer with `key 
not found: k#...` on master as well as with this PR (also with the legacy 
conf), so I will look at that failure separately.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,7 +567,168 @@ 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
+   * leaves 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`. 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 {
+      case Alias(child, _) => child.foldable
+      case e => e.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.
+  private def orderIrrelevant(f: AggregateFunction): Boolean = f match {
+    case _: Min | _: Max | _: Count | _: BitAndAgg | _: BitOrAgg | _: 
BitXorAgg => true
+    case _: Sum => !f.children.exists(c => c.dataType == FloatType || 
c.dataType == DoubleType)
+    case _: Average => f.children.forall(c =>
+      c.dataType.isInstanceOf[DecimalType] || 
c.dataType.isInstanceOf[AnsiIntervalType])
+    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, and
+   * LimitPushDown a LIMIT, into the inputs of some joins or, for a LIMIT 1, 
below a group-only
+   * aggregate (see limitMayBePushedIn). The check is conservative and looks 
at all of `root`.
+   */
+  private def mayMoveIntoOuterInput(root: LogicalPlan, exprId: ExprId): 
Boolean =
+    root.exists {
+      case p @ (_: Filter | _: Join) =>
+        !p.expressions.forall(_.deterministic) || 
p.expressions.exists(_.exists {

Review Comment:
   Agreed. 297f6fe080b also checks the other subqueries in the expressions of 
the operator with the subquery, as you suggested, so your query keeps the 
previous plan (same plan as with the legacy conf), and 
`PullupCorrelatedPredicatesSuite` checks a `Project` with another subquery with 
a `LIMIT`.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,7 +567,168 @@ 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
+   * leaves 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`. 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 {
+      case Alias(child, _) => child.foldable
+      case e => e.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.
+  private def orderIrrelevant(f: AggregateFunction): Boolean = f match {
+    case _: Min | _: Max | _: Count | _: BitAndAgg | _: BitOrAgg | _: 
BitXorAgg => true
+    case _: Sum => !f.children.exists(c => c.dataType == FloatType || 
c.dataType == DoubleType)
+    case _: Average => f.children.forall(c =>
+      c.dataType.isInstanceOf[DecimalType] || 
c.dataType.isInstanceOf[AnsiIntervalType])
+    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, and
+   * LimitPushDown a LIMIT, into the inputs of some joins or, for a LIMIT 1, 
below a group-only
+   * aggregate (see limitMayBePushedIn). The check is conservative and looks 
at all of `root`.
+   */
+  private def mayMoveIntoOuterInput(root: LogicalPlan, exprId: ExprId): 
Boolean =

Review Comment:
   Thank you, done: `LimitPushDown` keeps a `LIMIT` above a `Project` with a 
correlated scalar subquery, for the `Project` over a join and the `LIMIT 1` 
over a group-only aggregate (`hasCorrelatedScalarSubquery`), and 
`limitMayBePushedIn` is removed. `LimitPushdownSuite` checks both and that an 
uncorrelated subquery still lets the limit through. As you wrote, it also 
changes the plans of the domain joins of a lower `COUNT`, which no longer get 
the `LIMIT`; the description says so. The TPC-DS and TPC-H plans in the plan 
stability suites do not change.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,7 +567,168 @@ 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
+   * leaves 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`. 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

Review Comment:
   I kept relations accepted, since Spark takes a relation to give the same 
rows again elsewhere too, and the scaladoc of `repeatableInput` and the 
description now say so, including that a `LogicalRDD` over an RDD that does not 
is not detected.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,7 +567,168 @@ 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
+   * leaves 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`. 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 {
+      case Alias(child, _) => child.foldable
+      case e => e.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.
+  private def orderIrrelevant(f: AggregateFunction): Boolean = f match {
+    case _: Min | _: Max | _: Count | _: BitAndAgg | _: BitOrAgg | _: 
BitXorAgg => true
+    case _: Sum => !f.children.exists(c => c.dataType == FloatType || 
c.dataType == DoubleType)

Review Comment:
   Thank you. 297f6fe080b accepts a `SUM` or `AVG` of decimals only in ANSI 
mode, where an overflow fails the query instead of giving `NULL`, and 
`PullupCorrelatedPredicatesSuite` checks both modes.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -584,44 +745,65 @@ 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)
       }
     }
 
     plan.transformExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
-      case ScalarSubquery(sub, children, exprId, conditions, hint,
+      case ScalarSubquery(sub, outerAttrs, exprId, conditions, hint,
       mayHaveCountBugOld, needSingleJoinOld)
-        if children.nonEmpty =>
-
+        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.
+        lazy val domainJoinsWork = plan.children.forall(repeatableInput(_)) &&
+          !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
         def mayHaveCountBugAgg(a: Aggregate): Boolean = {
-          a.groupingExpressions.isEmpty && 
a.aggregateExpressions.exists(_.exists {
-            case a: AggregateExpression => 
a.aggregateFunction.defaultResult.isDefined
-            case _ => false
-          })
+          a.groupingExpressions.isEmpty && (hasDefaultResult(a) ||

Review Comment:
   Done: `hasOuterReferences(a)` now comes first, and the check of the outer 
input is one `lazy val` in `rewriteSubQueries`, outside the `case`.
   



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