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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,92 @@ 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 =>
+              // `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 = {
+                val f = ae.aggregateFunction
+                f.defaultResult.getOrElse(Literal.create(null, f.dataType))
+              }
+              def rewrite(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOut(ae, "aggResult", 
zeroTupsResult(ae))
+                // An attribute inside an expression over aggregate functions. 
A grouping-less
+                // Aggregate cannot reference one outside an aggregate 
function (the analyzer
+                // rejects it), so this is unreachable from SQL; as
+                // `RewriteCorrelatedScalarSubquery.evalAggExprOnZeroTups`, 
take it as NULL over
+                // zero rows in case it is reached.
+                case r: AttributeReference => pullOut(r, r.name, 
Literal.create(null, r.dataType))
+                case other => other.mapChildren(rewrite)
+              }
+              val projectList = newAggregate.aggregateExpressions.map {
+                // Not subject to the count bug: NULL for zero tuples.
+                case a @ (_: AttributeReference | Alias(_: AttributeReference, 
_)) =>
+                  expressions += a
+                  a.toAttribute.withNullability(true)
+                // A literal (SPARK-43156) keeps its name in the new aggregate.
+                case a @ Alias(l: Literal, _) =>
+                  if (l.value == null) {
                     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.")
+                  } else {
                     val newAttr = a.newInstance()
-                    val ref = newAttr.toAttribute.withNullability(true)
                     expressions += newAttr
-                    Alias(If(IsNull(alwaysTrueRef), default, ref), 
a.name)(a.exprId)
-                }
+                    Alias(withZeroTupsResult(l, 
newAttr.toAttribute.withNullability(true)),
+                      a.name)(a.exprId)
+                  }
+                // A single aggregate function, or an expression over 
aggregate functions,
+                // computed over the pulled-out, corrected values. A single 
function keeps its
+                // output name and exprId and shares its column with any 
expression over it.
+                case a: Alias =>
+                  a.withNewChildren(Seq(rewrite(a.child))).asInstanceOf[Alias]
+                case a =>

Review Comment:
   Resolved together with the `AttributeReference` branch above (the other 
unreachable case, your
   comment on the dead-code branch): both now fail with 
`SparkException.internalError`.



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