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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -596,32 +658,55 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
       mayHaveCountBugOld, needSingleJoinOld)
         if children.nonEmpty =>
 
+        // An Aggregate without grouping expressions returns one row even on 
empty input,
+        // whatever its aggregate functions are, and an Aggregate above it 
sees that row. If the
+        // Aggregate is correlated, decorrelation can lose that row (see 
below). An uncorrelated
+        // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree 
without outer references
+        // 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; with
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only 
such an Aggregate
+        // does. So does it where the domain joins of DecorrelateInnerQuery, 
which compute the
+        // outer query again, are known not to work, so as not to make such 
queries worse than
+        // before. The check is conservative: e.g. the domain joins fail for a 
streaming query
+        // and for outer references that are not orderable, and can find other 
rows the second
+        // time for a non-deterministic input, or for a CTE that is not 
inlined, which may be a
+        // non-deterministic one (a CTERelationRef does not tell).
+        val domainJoinsWork = !plan.isStreaming &&

Review Comment:
   With the change in the reply to [10], the check looks at the operators above 
the subquery that the rules before `RewriteCorrelatedScalarSubquery` can move 
into the outer input (`PushDownPredicates` and `LimitPushDown`, the ones I 
found going through those rules), and accepts only an outer input built from 
operators known to give the same rows again, so an operator that another rule 
turns into something else later, such as `Deduplicate`, keeps the previous plan 
too. A flag next to `mayHaveCountBug` would let the check be narrower, but 
every rule that can change the outer input before 
`RewriteCorrelatedScalarSubquery` would have to respect it. I would like to 
keep this PR to the conservative check; would that be OK with you?
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,6 +567,68 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
      nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
    }
 
+  // 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

Review Comment:
   I agree that the property belongs on `AggregateFunction` next to 
`defaultResult`. It touches every aggregate function that has it, so I would 
like to do it in a follow-up PR, if that is OK with you.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -596,32 +658,55 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
       mayHaveCountBugOld, needSingleJoinOld)
         if children.nonEmpty =>
 
+        // An Aggregate without grouping expressions returns one row even on 
empty input,
+        // whatever its aggregate functions are, and an Aggregate above it 
sees that row. If the
+        // Aggregate is correlated, decorrelation can lose that row (see 
below). An uncorrelated
+        // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree 
without outer references
+        // 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; with
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only 
such an Aggregate
+        // does. So does it where the domain joins of DecorrelateInnerQuery, 
which compute the
+        // outer query again, are known not to work, so as not to make such 
queries worse than
+        // before. The check is conservative: e.g. the domain joins fail for a 
streaming query
+        // and for outer references that are not orderable, and can find other 
rows the second
+        // time for a non-deterministic input, or for a CTE that is not 
inlined, which may be a
+        // non-deterministic one (a CTERelationRef does not tell).
+        val domainJoinsWork = !plan.isStreaming &&
+          plan.children.forall(c => c.deterministic && 
!c.containsPattern(CTE)) &&
+          children.forall(e => RowOrdering.isOrderable(e.dataType))
+        val legacyNestedAggregateCountBug =

Review Comment:
   Done: the `val` is now `onlyDefaultResultSelectsDecorrelation`, the pattern 
variable is `outerAttrs`, and both `val`s are `lazy`.
   



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