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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +872,84 @@ object DecorrelateInnerQuery extends PredicateHelper {
             // | 0 | null | null       | 0                              |  
<--- correct result
             // +---+------+------------+--------------------------------+
             if (groupingExpressions.isEmpty && handleCountBug) {
-              // Evaluate the aggregate expressions with zero tuples.
-              val resultMap = 
RewriteCorrelatedScalarSubquery.evalAggregateOnZeroTups(newAggregate)
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
-              // Create new aliases for aggregate expressions that have 
non-null default
-              // values and reconstruct the output with the `alwaysTrue` 
marker.
-              val projectList = newAggregate.aggregateExpressions.map { a =>
-                resultMap.get(a.exprId) match {
-                  // Aggregate expression is not subject to the count bug.
-                  case Some(Literal(null, _)) | None =>
-                    expressions += a
-                    // The attribute is nullable since it is from the 
right-hand side of a
-                    // left outer join.
-                    a.toAttribute.withNullability(true)
-                  case Some(default) =>
-                    assert(a.isInstanceOf[Alias], s"Cannot have non-aliased 
expression $a in " +
-                      s"aggregate that evaluates to non-null value with zero 
tuples.")
-                    val newAttr = a.newInstance()
-                    val ref = newAttr.toAttribute.withNullability(true)
-                    expressions += newAttr
-                    Alias(If(IsNull(alwaysTrueRef), default, ref), 
a.name)(a.exprId)
+              // `ref` if `zeroTupsResult` is NULL, or
+              // `if(isnull(alwaysTrue), zeroTupsResult, ref)` otherwise.
+              def withZeroTupsResult(zeroTupsResult: Expression, ref: 
Attribute): Expression =
+                zeroTupsResult match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
                 }
+              // Only the aggregate functions are evaluated with zero tuples, 
by taking their
+              // default results. An expression over them is computed above 
the left outer
+              // domain join on the corrected values, so that it is evaluated 
once per row on
+              // the value of that row, as for an outer row that has matching 
rows. Evaluating
+              // the whole expression with zero tuples instead fails at 
planning time if it
+              // throws (e.g. `10 / count(*)` in ANSI mode); and a Python UDF 
over them, which
+              // `ExtractPythonUDFs` lifts out of the conditional branch, 
would otherwise run at
+              // runtime for every outer row, including the rows whose 
subquery has matching rows.
+              //
+              // This pulls out every aggregate function, so an expression 
over several of them,
+              // e.g. `max(v) - min(v)`, carries one value per function into 
the domain join
+              // instead of one per column. Only an expression that contains a 
Python UDF needs
+              // the pull-out; for the others the same results could be kept 
by leaving the
+              // expression in the Aggregate and reading 
`if(isnull(alwaysTrue), <expression with
+              // each aggregate function replaced by its unfolded empty-input 
result>, column)`,
+              // which constant folding tolerates in the conditional branch. 
This single path is
+              // kept for simplicity; the alternative is a possible follow-up.
+              //
+              // TODO(SPARK-61444): 
`RewriteCorrelatedScalarSubquery.constructLeftJoins` still
+              // statically evaluates the whole zero-row result of a 
correlated scalar subquery,
+              // including subqueries whose count bug is handled here when it 
reaches their
+              // rewritten expression (e.g. under a Project with no top 
Aggregate), so such a
+              // subquery can still fail while the query is optimized (e.g. 
`10 / count(*)` in
+              // ANSI mode). SPARK-61444 addresses that path.
+              val pulledOut = mutable.HashMap.empty[Expression, Expression]
+              def pullOut(e: Expression, name: String, zeroTupsResult: 
Expression): Expression = {

Review Comment:
   Done; this is close to the shape you suggested. `pullOutAggregate(ae: 
AggregateExpression)` builds
   the `If` inside from 
`RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction)`,
   and `pullOutAggregates` walks the column and replaces each aggregate 
function with it. There is no
   separate zero-row-result parameter and no `withZeroTupsResult`. (It does not 
take the `name`
   argument or deduplicate, since there is only the UDF column to pull from 
now.)
   
   The check that selects the pull-out, `hasScalarPythonUDFOverAggregate`, 
stops at an
   `AggregateExpression`, so a Python UDF inside an aggregate's argument, e.g. 
`count(udf(v))`, is not
   pulled out and keeps its plan (a catalyst test pins this). Unlike
   `ExtractPythonUDFFromAggregate.hasPythonUdfOverAggregate`, it does not 
descend into an aggregate
   function, because such a UDF is replaced along with the function by its 
result over zero rows and
   is never lifted out of a branch.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +872,84 @@ object DecorrelateInnerQuery extends PredicateHelper {
             // | 0 | null | null       | 0                              |  
<--- correct result
             // +---+------+------------+--------------------------------+
             if (groupingExpressions.isEmpty && handleCountBug) {
-              // Evaluate the aggregate expressions with zero tuples.
-              val resultMap = 
RewriteCorrelatedScalarSubquery.evalAggregateOnZeroTups(newAggregate)
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
-              // Create new aliases for aggregate expressions that have 
non-null default
-              // values and reconstruct the output with the `alwaysTrue` 
marker.
-              val projectList = newAggregate.aggregateExpressions.map { a =>
-                resultMap.get(a.exprId) match {
-                  // Aggregate expression is not subject to the count bug.
-                  case Some(Literal(null, _)) | None =>
-                    expressions += a
-                    // The attribute is nullable since it is from the 
right-hand side of a
-                    // left outer join.
-                    a.toAttribute.withNullability(true)
-                  case Some(default) =>
-                    assert(a.isInstanceOf[Alias], s"Cannot have non-aliased 
expression $a in " +
-                      s"aggregate that evaluates to non-null value with zero 
tuples.")
-                    val newAttr = a.newInstance()
-                    val ref = newAttr.toAttribute.withNullability(true)
-                    expressions += newAttr
-                    Alias(If(IsNull(alwaysTrueRef), default, ref), 
a.name)(a.exprId)
+              // `ref` if `zeroTupsResult` is NULL, or
+              // `if(isnull(alwaysTrue), zeroTupsResult, ref)` otherwise.
+              def withZeroTupsResult(zeroTupsResult: Expression, ref: 
Attribute): Expression =
+                zeroTupsResult match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
                 }
+              // Only the aggregate functions are evaluated with zero tuples, 
by taking their
+              // default results. An expression over them is computed above 
the left outer
+              // domain join on the corrected values, so that it is evaluated 
once per row on
+              // the value of that row, as for an outer row that has matching 
rows. Evaluating
+              // the whole expression with zero tuples instead fails at 
planning time if it
+              // throws (e.g. `10 / count(*)` in ANSI mode); and a Python UDF 
over them, which
+              // `ExtractPythonUDFs` lifts out of the conditional branch, 
would otherwise run at
+              // runtime for every outer row, including the rows whose 
subquery has matching rows.
+              //
+              // This pulls out every aggregate function, so an expression 
over several of them,
+              // e.g. `max(v) - min(v)`, carries one value per function into 
the domain join
+              // instead of one per column. Only an expression that contains a 
Python UDF needs
+              // the pull-out; for the others the same results could be kept 
by leaving the
+              // expression in the Aggregate and reading 
`if(isnull(alwaysTrue), <expression with
+              // each aggregate function replaced by its unfolded empty-input 
result>, column)`,
+              // which constant folding tolerates in the conditional branch. 
This single path is
+              // kept for simplicity; the alternative is a possible follow-up.
+              //
+              // TODO(SPARK-61444): 
`RewriteCorrelatedScalarSubquery.constructLeftJoins` still
+              // statically evaluates the whole zero-row result of a 
correlated scalar subquery,
+              // including subqueries whose count bug is handled here when it 
reaches their
+              // rewritten expression (e.g. under a Project with no top 
Aggregate), so such a
+              // subquery can still fail while the query is optimized (e.g. 
`10 / count(*)` in
+              // ANSI mode). SPARK-61444 addresses that path.
+              val pulledOut = mutable.HashMap.empty[Expression, Expression]
+              def pullOut(e: Expression, name: String, zeroTupsResult: 
Expression): Expression = {
+                def mk = {
+                  val alias = Alias(e, name)()
+                  expressions += alias
+                  // The attribute is nullable since it is from the right-hand 
side of a
+                  // left outer join.
+                  withZeroTupsResult(zeroTupsResult, 
alias.toAttribute.withNullability(true))
+                }
+                // Deduplicate deterministic expressions only, as 
`PhysicalAggregation` does: a
+                // non-deterministic aggregate function used more than once is 
computed once per
+                // use there, and sharing one column would make the uses take 
the same value.
+                if (e.deterministic) 
pulledOut.getOrElseUpdate(e.canonicalized, mk) else mk
+              }
+              def zeroTupsResult(ae: AggregateExpression): Literal =
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction)
+              def rewrite(e: Expression): Expression = e match {
+                case ae: AggregateExpression =>
+                  pullOut(ae, ae.aggregateFunction.prettyName, 
zeroTupsResult(ae))
+                // A grouping-less Aggregate cannot reference an attribute 
outside an aggregate
+                // function (the analyzer rejects it), so this is unreachable 
from a query. Fail
+                // rather than silently take NULL, as the `case a =>` below 
does.

Review Comment:
   The reworked code no longer has that `case a =>` branch. `pullOutAggregates` 
has one unreachable
   case, an attribute outside an aggregate function, which throws 
`SparkException.internalError` with
   a comment that the analyzer rejects such a column. The projectList also 
throws `internalError` for
   a non-aliased Python UDF column.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -855,8 +857,12 @@ object DecorrelateInnerQuery extends PredicateHelper {
             // If an aggregate is subject to the COUNT bug:
             // 1) add a column `true AS alwaysTrue` to the result of the 
aggregate
             // 2) insert a left outer domain join between the outer query and 
this aggregate
-            // 3) rewrite the original aggregate's output column using the 
default value of the
-            //    aggregate function and the alwaysTrue column.
+            // 3) above the join, rebuild each output column from the 
corrected value of each
+            //    aggregate function it uses: for an outer row with no 
matching rows, which
+            //    `alwaysTrue` being null marks, the function takes its 
default value (e.g. 0 for
+            //    `count`). A single aggregate function becomes 
`if(isnull(alwaysTrue), default,
+            //    col)`, as the example below shows; an expression over 
aggregate functions, or a
+            //    literal, is computed above the join from those corrected 
values.

Review Comment:
   Rewrote step 3 of the block comment for the reworked flow. The "possible 
follow-up" note is gone
   with the code it described. SPARK-61444 (#60325) is now a dependency rather 
than a `TODO`. For the
   remaining follow-up (a single-top-`Aggregate` scalar subquery on the 
`constructLeftJoins` path), I
   filed SPARK-61660, referenced it in the description, and added a 
`TODO(SPARK-61660)` at the
   `constructLeftJoins` CASE 2 site.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +872,84 @@ object DecorrelateInnerQuery extends PredicateHelper {
             // | 0 | null | null       | 0                              |  
<--- correct result
             // +---+------+------------+--------------------------------+
             if (groupingExpressions.isEmpty && handleCountBug) {
-              // Evaluate the aggregate expressions with zero tuples.
-              val resultMap = 
RewriteCorrelatedScalarSubquery.evalAggregateOnZeroTups(newAggregate)
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
-              // Create new aliases for aggregate expressions that have 
non-null default
-              // values and reconstruct the output with the `alwaysTrue` 
marker.
-              val projectList = newAggregate.aggregateExpressions.map { a =>
-                resultMap.get(a.exprId) match {
-                  // Aggregate expression is not subject to the count bug.
-                  case Some(Literal(null, _)) | None =>
-                    expressions += a
-                    // The attribute is nullable since it is from the 
right-hand side of a
-                    // left outer join.
-                    a.toAttribute.withNullability(true)
-                  case Some(default) =>
-                    assert(a.isInstanceOf[Alias], s"Cannot have non-aliased 
expression $a in " +
-                      s"aggregate that evaluates to non-null value with zero 
tuples.")
-                    val newAttr = a.newInstance()
-                    val ref = newAttr.toAttribute.withNullability(true)
-                    expressions += newAttr
-                    Alias(If(IsNull(alwaysTrueRef), default, ref), 
a.name)(a.exprId)
+              // `ref` if `zeroTupsResult` is NULL, or
+              // `if(isnull(alwaysTrue), zeroTupsResult, ref)` otherwise.
+              def withZeroTupsResult(zeroTupsResult: Expression, ref: 
Attribute): Expression =
+                zeroTupsResult match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
                 }
+              // Only the aggregate functions are evaluated with zero tuples, 
by taking their
+              // default results. An expression over them is computed above 
the left outer
+              // domain join on the corrected values, so that it is evaluated 
once per row on
+              // the value of that row, as for an outer row that has matching 
rows. Evaluating
+              // the whole expression with zero tuples instead fails at 
planning time if it
+              // throws (e.g. `10 / count(*)` in ANSI mode); and a Python UDF 
over them, which
+              // `ExtractPythonUDFs` lifts out of the conditional branch, 
would otherwise run at
+              // runtime for every outer row, including the rows whose 
subquery has matching rows.
+              //
+              // This pulls out every aggregate function, so an expression 
over several of them,
+              // e.g. `max(v) - min(v)`, carries one value per function into 
the domain join
+              // instead of one per column. Only an expression that contains a 
Python UDF needs
+              // the pull-out; for the others the same results could be kept 
by leaving the
+              // expression in the Aggregate and reading 
`if(isnull(alwaysTrue), <expression with
+              // each aggregate function replaced by its unfolded empty-input 
result>, column)`,
+              // which constant folding tolerates in the conditional branch. 
This single path is
+              // kept for simplicity; the alternative is a possible follow-up.
+              //
+              // TODO(SPARK-61444): 
`RewriteCorrelatedScalarSubquery.constructLeftJoins` still
+              // statically evaluates the whole zero-row result of a 
correlated scalar subquery,
+              // including subqueries whose count bug is handled here when it 
reaches their
+              // rewritten expression (e.g. under a Project with no top 
Aggregate), so such a
+              // subquery can still fail while the query is optimized (e.g. 
`10 / count(*)` in
+              // ANSI mode). SPARK-61444 addresses that path.
+              val pulledOut = mutable.HashMap.empty[Expression, Expression]
+              def pullOut(e: Expression, name: String, zeroTupsResult: 
Expression): Expression = {
+                def mk = {
+                  val alias = Alias(e, name)()
+                  expressions += alias
+                  // The attribute is nullable since it is from the right-hand 
side of a
+                  // left outer join.
+                  withZeroTupsResult(zeroTupsResult, 
alias.toAttribute.withNullability(true))
+                }
+                // Deduplicate deterministic expressions only, as 
`PhysicalAggregation` does: a

Review Comment:
   That comment and the deduplication it described are removed. One related 
point: when the same
   aggregate function appears both in a Python UDF column and as a plain 
column, it is now output as
   two columns of the `Aggregate` (the plain one keeps its name; the UDF one is 
pulled out). The rows
   are identical and `PhysicalAggregation` computes the function once 
physically, so the only cost is
   the extra column through the domain join. I kept it simple rather than 
re-add the deduplication;
   let me know if you would rather I share the column.



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