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


##########
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:
   **[24] Minor: a filter above can also move another subquery of the operator 
itself into the outer input, which this check does not look at.**
   
   `PushPredicateThroughNonJoin` replaces the aliases of a `Project` in a 
condition that it pushes below it (Optimizer.scala:2684), and a scalar subquery 
is not expensive, so such a condition is pushed. For `SELECT * FROM (SELECT 
o.k, (SELECT COUNT(*) FROM (SELECT MAX(b.v) FROM b WHERE b.k = o.k)) c, (SELECT 
t.x FROM t LIMIT 1) x FROM o) WHERE x > 0`, the `Filter` above has only `x > 
0`, so L700-705 accept it, but it becomes `Filter((SELECT t.x FROM t LIMIT 1) > 
0, o)` in the outer input. That is the kind of filter that 
`PullupCorrelatedPredicatesSuite` keeps on the previous handling with `above = 
_.where(limitInSubquery)`. Could the check also look at the other subqueries in 
the expressions of the operator with this subquery, since a filter above can 
inline any of them?
   



##########
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:
   **[23] A `Project` with the subquery over a `UNION ALL` gets past 
`limitMayBePushedIn` too, through `PushProjectionThroughUnion`.**
   
   For `SELECT u.k, (SELECT COUNT(*) FROM (SELECT MAX(b.v) FROM b WHERE b.k = 
u.k)) c FROM (SELECT * FROM o LEFT JOIN d ON o.k = d.k2 UNION ALL SELECT k, k2 
FROM e) u LIMIT 10`, with `o(k)` and `d(k2)` so that the `Project` of `SELECT 
*` is removed in the `Union` batch, this rule sees `LocalLimit(Project(_, 
Union))`. `case u: Union` matches only a `Union` directly under the limit, and 
`case Project(_, child) if one` only a `LIMIT 1`, so it returns false. Then 
`PushProjectionThroughUnion`, the first rule of the iteration 
(Optimizer.scala:104), pushes the `Project`, which is deterministic with the 
subquery in it, into each child of the `Union` (Optimizer.scala:1498-1501), and 
`LimitPushDown` pushes `LocalLimit(10)` below the `Union` 
(Optimizer.scala:998-999) and, in the same `transformDown`, into the left side 
of the outer join (Optimizer.scala:1023-1024). So the domain join computes 
`LocalLimit(10, o)` again, with the same result as in [22] when `o` gives its 
rows in another order.
   



##########
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:
   **[27] Minor: following up on [18], a `SUM` or `AVG` of decimals can also 
depend on the order of the rows, through an overflow.**
   
   With ANSI off, a decimal `Sum` in a hash aggregate becomes `NULL` when its 
buffer overflows, since `UnsafeRow.setDecimal` writes `NULL` for a value that 
does not fit (UnsafeRow.java:288-289), and stays `NULL` (`bufferOverflow` in 
`Sum.mergeExpressions`). Whether it overflows depends on the order: for partial 
sums `9e37`, `9e37` and `-9e37` of a `DECIMAL(38, 0)` group, merging the two 
`9e37` first gives `NULL`, and any other order gives `9e37`, and the final 
aggregate merges them in the order the shuffle blocks arrive. So, as in [18], 
with `SELECT g, SUM(x) s FROM t GROUP BY g` as the outer input and `s` as the 
outer reference, the domain join can compute another `s` than the main copy. 
`Average` of decimals adds up its sum the same way. Could `orderIrrelevant` 
reject a decimal `Sum` and `Average`, or is this rare enough to only mention in 
the comment at L676-680?
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -670,25 +852,26 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
   /**
    * Pull up the correlated predicates and rewrite all subqueries in an 
operator tree..
    */
-  def apply(plan: LogicalPlan): LogicalPlan = plan.transformUpWithPruning(
-    _.containsPattern(PLAN_EXPRESSION)) {
-    case j: LateralJoin =>
-      val newPlan = rewriteSubQueries(j)
-      // Since a lateral join's output depends on its left child output and 
its lateral subquery's
-      // plan output, we need to trim the domain attributes added to the 
subquery's plan output
-      // to preserve the original output of the join.
-      if (!j.sameOutput(newPlan)) {
-        Project(j.output, newPlan)
-      } else {
-        newPlan
-      }
-    case j: Join if 
conf.getConf(DECORRELATE_PREDICATE_SUBQUERIES_IN_JOIN_CONDITION) =>
-      rewriteSubQueries(j)
-    // Only a few unary nodes (Project/Filter/Aggregate) can contain 
subqueries.
-    case q: UnaryNode =>
-      rewriteSubQueries(q)
-    case s: SupportsSubquery =>
-      rewriteSubQueries(s)
+  def apply(plan: LogicalPlan): LogicalPlan = {

Review Comment:
   **[29] Nit: `apply` only needs `, plan` in the four calls, but its body is 
wrapped in a block and re-indented, and the comment of the `LateralJoin` case 
is re-wrapped.**
   
   `def apply(plan: LogicalPlan): LogicalPlan = 
plan.transformUpWithPruning(...)` already has `plan` in scope, so the old 
layout works as is, and would keep this diff and the four backports smaller.
   



##########
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:
   **[25] Following up on [15], could `LimitPushDown` keep a limit above an 
operator that still has a correlated scalar subquery, instead of this rule 
predicting where it goes?**
   
   [22] and [23] get past `limitMayBePushedIn` because it predicts the plan 
that `LimitPushDown` sees from the plan that this rule sees, and the rules in 
between still change it. `PushDownLeftSemiAntiJoin` already keeps a join above 
a `Project` with a correlated scalar subquery 
(`!pList.exists(ScalarSubquery.hasCorrelatedScalarSubquery)`, 
PushDownLeftSemiAntiJoin.scala:43). With the same guard in `LimitPushDown`, 
`RewriteCorrelatedScalarSubquery` builds the domain join later in the same 
iteration, and from the next one `LimitPushDown` pushes the limit at most into 
the left side of the new left outer join, so the domain join sees every row of 
the outer input, whatever the shape.
   
   That would also remove `limitMayBePushedIn`, which repeats the cases of 
`pushLocalLimitThroughJoin` (Optimizer.scala:974-988) and has to follow every 
change there; if the current check stays, could the two share a helper? The 
guard would also change the plans of a lower `COUNT`, whose domain join on 
master can get the limit the same way, and the domain join would no longer get 
the limit; I have not checked how the plan stability suites take it. [24] would 
still need a check here.
   



##########
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:
   **[26] Minor: `case l: LeafNode => !l.isStreaming` accepts every relation, 
including a `LogicalRDD` over an RDD that gives other rows when computed 
again.**
   
   E.g. with `o = spark.createDataFrame(sc.parallelize(0 until 1000).map(_ => 
Tuple1(Random.nextInt(1000)))).toDF("k")`, not cached, the outer input is a 
`LogicalRDD`, which this check accepts, so the domain join computes the RDD 
again, and an outer `k` that the domain does not have gets `NULL` instead of 
`1`. The same input built with the non-deterministic UDF in `SubquerySuite` 
keeps the previous result. Spark generally takes a relation to give the same 
rows, e.g. in a self-join of such a DataFrame, so this may be acceptable, but 
could the scaladoc at L631-641 say so, or could `LogicalRDD` and `ExternalRDD` 
keep the previous handling, as a non-deterministic input does?
   



##########
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:
   **[22] `limitMayBePushedIn` looks at the plan when this rule runs, but 
`PushDownPredicates` runs before `LimitPushDown` in the same iteration and can 
turn a shape it rejects into one that `LimitPushDown` pushes into.**
   
   Thank you for following the cases of `LimitPushDown` for [19]. The rules 
before `RewriteCorrelatedScalarSubquery` in `operatorOptimizationRuleSet` still 
change the plan between this rule and `LimitPushDown`, e.g.:
   
   - A `Filter` between the `Project` with the subquery and the join. For 
`SELECT o.k, (SELECT COUNT(*) FROM (SELECT MAX(b.v) FROM b WHERE b.k = o.k)) c 
FROM (SELECT k FROM t GROUP BY k) o LEFT JOIN b ON o.k = b.k WHERE o.k > 0 
LIMIT 100`, this rule sees `LocalLimit(Project(_, Filter(_, Join)))`, which 
matches neither `case Project(_, j: Join)` nor, for a `LIMIT 100`, `case 
Project(_, child) if one`, so the subquery gets the domain joins. Then 
`PushDownPredicates` (Optimizer.scala:108) pushes `o.k > 0` into the left side 
of the join, and `LimitPushDown` (Optimizer.scala:112) pushes `LocalLimit(100)` 
there through `Project(_, Join)` (Optimizer.scala:1023-1024), before 
`RewriteCorrelatedScalarSubquery` (Optimizer.scala:152) builds the domain join 
from that input.
   - A join condition that `PushDownPredicates` moves into one side. For `... 
FROM (SELECT k FROM t GROUP BY k) o JOIN c ON c.flag = 1 LIMIT 100`, 
`limitMayBePushedIn` returns false for `Join(Inner, Some(_))`, but the join 
becomes `Join(Inner, None)` with the condition below its right side, and 
`LimitPushDown` pushes the limit into both sides (Optimizer.scala:980-983).
   
   The grouped `o` can give its rows in another order when it is computed 
again, so the main copy and the domain join can keep other 100 rows, and a 
matched outer row missing from the domain gets `NULL` instead of `1`, as in 
[10]. I did not run these; they are from the rule order. [25] suggests a way 
that does not depend on the shapes.
   



##########
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:
   **[28] Nit: `mayHaveCountBugAgg` reads 
`onlyDefaultResultSelectsDecorrelation` before 
`SubExprUtils.hasOuterReferences(a)`.**
   
   For an uncorrelated lower `Aggregate` without a default result, the lazy 
`val` then computes `domainJoinsWork`, which walks `plan.children` and `root`, 
although its value cannot change the result. Swapping the two operands would 
skip it. `plan.children.forall(repeatableInput(_))` also does not depend on the 
subquery, so it could be one `lazy val` in `rewriteSubQueries`, outside the 
`case`, instead of one for each correlated scalar subquery of the operator.
   



##########
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) =>

Review Comment:
   **[30] Nit: `l` in `case l @ LocalLimit(limitExpr, child)` is not used, and 
`constantOutput` (L668-671) could be 
`projectList.forall(trimAliases(_).foldable)`, with `trimAliases` from the 
`AliasHelper` that `PredicateHelper` extends.**
   



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