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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -871,8 +873,45 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
+              // Pull an aggregate function out as its own column of the 
aggregate, corrected for
+              // the count bug: `if(isnull(alwaysTrue), <default>, <ref>)`, or 
just `<ref>` when
+              // its result on zero rows is NULL. Used to rebuild a column 
over aggregate
+              // functions above the join, see the Python UDF case below.
+              def pullOutAggregate(ae: AggregateExpression): Expression = {
+                val alias = Alias(ae, ae.aggregateFunction.prettyName)()
+                expressions += alias
+                // The attribute is nullable since it is from the right-hand 
side of a left
+                // outer join.
+                val ref = alias.toAttribute.withNullability(true)
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction) 
match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
+                }
+              }
+              // Replace every aggregate function in an expression with its 
count-bug-corrected
+              // column, leaving the rest of the expression in place, so that 
it can be computed
+              // above the left outer join. Does not descend into an aggregate 
function (handled
+              // as a whole) and leaves a nested subquery untouched.
+              def pullOutAggregates(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOutAggregate(ae)
+                case other => other.mapChildren(pullOutAggregates)
+              }
+              // Whether a column applies a scalar Python UDF to an aggregate 
function's result,
+              // e.g. `inv(count(*))` or `CASE WHEN count(*) = 0 THEN 0 ELSE 
inv(count(*)) END`.
+              // Such a UDF is evaluated on the values over zero rows (see the 
case below). Unlike
+              // `ExtractPythonUDFFromAggregate.hasPythonUdfOverAggregate`, 
this stops at an
+              // aggregate function, so a Python UDF inside an aggregate 
function's argument, e.g.
+              // `count(udf(v))`, does not count: it is replaced along with 
the function by its
+              // result over zero rows and is never lifted out of a branch.
+              def hasScalarPythonUDFOverAggregate(e: Expression): Boolean = e 
match {

Review Comment:
   Resolved by the rework. There is no pull-out anymore, so there is no scope 
to settle: a column keeps its plan unless the optimizer leaves a UDF in its 
zero-row result, and then only that result is marked. Your guarded `CASE ... 
count(*) + f(o.k) END` folds away over zero rows, so it keeps master's plan. 
For an unguarded `count(*) + f(o.k)`, `ExtractPythonUDFFromAggregate` lifts `f` 
into a `Project` just above the `Aggregate` (below the domain join), where it 
is evaluated once per group as on master; what the marker makes conditional is 
the zero-row copy `f(NULL)`, which now runs only for outer rows without 
matching rows. The guarded shape keeping no marker is pinned in 
`DecorrelateInnerQuerySuite` ("a guarded ... keeps no marker after 
ConstantFolding and SimplifyConditionals"), and the unguarded shape keeping one 
in the same suite.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -871,8 +873,45 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
+              // Pull an aggregate function out as its own column of the 
aggregate, corrected for
+              // the count bug: `if(isnull(alwaysTrue), <default>, <ref>)`, or 
just `<ref>` when
+              // its result on zero rows is NULL. Used to rebuild a column 
over aggregate
+              // functions above the join, see the Python UDF case below.
+              def pullOutAggregate(ae: AggregateExpression): Expression = {
+                val alias = Alias(ae, ae.aggregateFunction.prettyName)()
+                expressions += alias
+                // The attribute is nullable since it is from the right-hand 
side of a left
+                // outer join.
+                val ref = alias.toAttribute.withNullability(true)
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction) 
match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
+                }
+              }
+              // Replace every aggregate function in an expression with its 
count-bug-corrected
+              // column, leaving the rest of the expression in place, so that 
it can be computed
+              // above the left outer join. Does not descend into an aggregate 
function (handled
+              // as a whole) and leaves a nested subquery untouched.
+              def pullOutAggregates(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOutAggregate(ae)
+                case other => other.mapChildren(pullOutAggregates)
+              }
+              // Whether a column applies a scalar Python UDF to an aggregate 
function's result,
+              // e.g. `inv(count(*))` or `CASE WHEN count(*) = 0 THEN 0 ELSE 
inv(count(*)) END`.
+              // Such a UDF is evaluated on the values over zero rows (see the 
case below). Unlike
+              // `ExtractPythonUDFFromAggregate.hasPythonUdfOverAggregate`, 
this stops at an
+              // aggregate function, so a Python UDF inside an aggregate 
function's argument, e.g.
+              // `count(udf(v))`, does not count: it is replaced along with 
the function by its
+              // result over zero rows and is never lifted out of a branch.
+              def hasScalarPythonUDFOverAggregate(e: Expression): Boolean = e 
match {
+                case _: AggregateExpression => false
+                case _ if PythonUDF.isScalarPythonUDF(e) => true

Review Comment:
   Covered. `PlanExternalUDFs` passes the marker's condition to 
`ExecuteExternalUDF` (`PlanExternalUDFsSuite`: "an external UDF inside an 
EvalOnlyWhen marker gets the condition", and no condition when it is also used 
outside a marker). `ExecuteExternalUDFExec` evaluates through the same 
`ConditionalUDFEvaluation` as the Python path. `ExecuteExternalUDFExecSuite` 
runs the node with a condition through an echo worker: it evaluates only the 
needed rows (interleaved back in input order) and starts no worker session when 
the condition is never true; `ConditionalUDFEvaluationSuite` covers the 
row-skipping and ordering with a plain evaluator. External UDF execution is 
`@Experimental`; the production dispatcher is not wired for a real worker yet, 
so there is no SQL-level end-to-end test of an external UDF over a correlated 
subquery, only the operator-level tests above.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -871,8 +873,45 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
+              // Pull an aggregate function out as its own column of the 
aggregate, corrected for
+              // the count bug: `if(isnull(alwaysTrue), <default>, <ref>)`, or 
just `<ref>` when
+              // its result on zero rows is NULL. Used to rebuild a column 
over aggregate
+              // functions above the join, see the Python UDF case below.
+              def pullOutAggregate(ae: AggregateExpression): Expression = {
+                val alias = Alias(ae, ae.aggregateFunction.prettyName)()
+                expressions += alias
+                // The attribute is nullable since it is from the right-hand 
side of a left
+                // outer join.
+                val ref = alias.toAttribute.withNullability(true)
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction) 
match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
+                }
+              }
+              // Replace every aggregate function in an expression with its 
count-bug-corrected
+              // column, leaving the rest of the expression in place, so that 
it can be computed
+              // above the left outer join. Does not descend into an aggregate 
function (handled
+              // as a whole) and leaves a nested subquery untouched.
+              def pullOutAggregates(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOutAggregate(ae)
+                case other => other.mapChildren(pullOutAggregates)

Review Comment:
   Unchanged, and still not a regression: an outer reference outside an 
aggregate function was already replaced by its inner attribute, which is `NULL` 
for an outer row without matching rows, so `inv(count(*) + o.k)` reads 
`inv(NULL)` there, as on master. The rework does not move this expression, so 
reading the domain attribute instead would be a separate improvement; I did not 
add a TODO for it, since it is pre-existing and distinct from the 
`constructLeftJoins` point in `TODO(SPARK-61660)`. I can file a JIRA and add a 
TODO at this spot if you prefer.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -882,12 +921,29 @@ object DecorrelateInnerQuery extends PredicateHelper {
                     // 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)
+                    val alias = a match {
+                      case alias: Alias => alias
+                      case _ =>
+                        throw SparkException.internalError(s"Cannot have 
non-aliased expression " +
+                          s"$a in aggregate that may not evaluate to null with 
zero tuples.")
+                    }
+                    if (hasScalarPythonUDFOverAggregate(alias.child)) {
+                      // A scalar Python UDF applied to an aggregate function, 
e.g. `inv(count(*))`.
+                      // Building `if(isnull(alwaysTrue), <default>, <ref>)` 
as in the else branch
+                      // would put the zero-row result `<default>`, e.g. 
`inv(0)`, in a conditional
+                      // branch, and `ExtractPythonUDFs` lifts a Python UDF 
out of a branch and
+                      // evaluates it for every row, so it would run on the 
zero-row values even for
+                      // an outer row with matching rows and could fail there 
(e.g. division by
+                      // zero). Instead pull every aggregate function out as 
its own corrected
+                      // column and compute the expression, including the UDF, 
above the join on
+                      // those corrected values.
+                      alias.withNewChild(pullOutAggregates(alias.child))

Review Comment:
   This is what the rework does, close to your suggestion: the optimizer 
simplifies the zero-row result (`ConstantFolding`, `SimplifyConditionals`, 
...), and the marker is kept only when a Python or external UDF is still left 
in it, via one helper (`EvalOnlyWhen.hasLiftedUDF`, a 
`PYTHON_UDF`/`EXTERNAL_UDF` tree-pattern pre-filter plus the operators' 
scalar/external test) that covers both. The difference from applying the rules 
here is that the rewrite applies none itself; it marks the branch and lets the 
normal optimizer batches decide, and a `SimplifyConditionals` rule drops the 
marker once no UDF remains.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -871,8 +873,45 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
+              // Pull an aggregate function out as its own column of the 
aggregate, corrected for
+              // the count bug: `if(isnull(alwaysTrue), <default>, <ref>)`, or 
just `<ref>` when
+              // its result on zero rows is NULL. Used to rebuild a column 
over aggregate
+              // functions above the join, see the Python UDF case below.
+              def pullOutAggregate(ae: AggregateExpression): Expression = {
+                val alias = Alias(ae, ae.aggregateFunction.prettyName)()
+                expressions += alias
+                // The attribute is nullable since it is from the right-hand 
side of a left
+                // outer join.
+                val ref = alias.toAttribute.withNullability(true)
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction) 
match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
+                }
+              }
+              // Replace every aggregate function in an expression with its 
count-bug-corrected
+              // column, leaving the rest of the expression in place, so that 
it can be computed
+              // above the left outer join. Does not descend into an aggregate 
function (handled
+              // as a whole) and leaves a nested subquery untouched.
+              def pullOutAggregates(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOutAggregate(ae)

Review Comment:
   No longer applies: there is no pull-out, so an aggregate is not duplicated. 
`count(*)` stays a single column of the `Aggregate` as on master.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -871,8 +873,45 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
               val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
               val expressions = ArrayBuffer.empty[NamedExpression]
+              // Pull an aggregate function out as its own column of the 
aggregate, corrected for
+              // the count bug: `if(isnull(alwaysTrue), <default>, <ref>)`, or 
just `<ref>` when
+              // its result on zero rows is NULL. Used to rebuild a column 
over aggregate
+              // functions above the join, see the Python UDF case below.
+              def pullOutAggregate(ae: AggregateExpression): Expression = {
+                val alias = Alias(ae, ae.aggregateFunction.prettyName)()
+                expressions += alias
+                // The attribute is nullable since it is from the right-hand 
side of a left
+                // outer join.
+                val ref = alias.toAttribute.withNullability(true)
+                
RewriteCorrelatedScalarSubquery.aggregateDefaultResult(ae.aggregateFunction) 
match {
+                  case Literal(null, _) => ref
+                  case default => If(IsNull(alwaysTrueRef), default, ref)
+                }
+              }
+              // Replace every aggregate function in an expression with its 
count-bug-corrected
+              // column, leaving the rest of the expression in place, so that 
it can be computed
+              // above the left outer join. Does not descend into an aggregate 
function (handled
+              // as a whole) and leaves a nested subquery untouched.
+              def pullOutAggregates(e: Expression): Expression = e match {
+                case ae: AggregateExpression => pullOutAggregate(ae)
+                case other => other.mapChildren(pullOutAggregates)
+              }
+              // Whether a column applies a scalar Python UDF to an aggregate 
function's result,
+              // e.g. `inv(count(*))` or `CASE WHEN count(*) = 0 THEN 0 ELSE 
inv(count(*)) END`.
+              // Such a UDF is evaluated on the values over zero rows (see the 
case below). Unlike
+              // `ExtractPythonUDFFromAggregate.hasPythonUdfOverAggregate`, 
this stops at an
+              // aggregate function, so a Python UDF inside an aggregate 
function's argument, e.g.
+              // `count(udf(v))`, does not count: it is replaced along with 
the function by its
+              // result over zero rows and is never lifted out of a branch.
+              def hasScalarPythonUDFOverAggregate(e: Expression): Boolean = e 
match {
+                case _: AggregateExpression => false
+                case _ if PythonUDF.isScalarPythonUDF(e) => true
+                case _ => e.children.exists(hasScalarPythonUDFOverAggregate)

Review Comment:
   Addressed. The rewrite decides whether to mark with 
`EvalOnlyWhen.hasLiftedUDF(default)` (a `PYTHON_UDF`/`EXTERNAL_UDF` 
tree-pattern pre-filter plus the operators' scalar/external test), and the new 
`EvalOnlyWhen.udfConditions` lookup in `ExtractPythonUDFs`/`PlanExternalUDFs` 
returns early unless the expressions contain the `EVAL_ONLY_WHEN` pattern, so 
the common no-UDF case is not walked.
   



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