spark-test commented on code in PR #60366:
URL: https://github.com/apache/spark/pull/60366#discussion_r4581619919


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -866,29 +868,79 @@ 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.
+              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))

Review Comment:
   Thanks for checking. After the rework, a column without a Python UDF, such 
as `array(COUNT(*))`, keeps its analyzed type, but the widening still reaches 
the Python UDF columns this PR rebuilds, so I'd fix it in this PR rather than 
in a follow-up. Rows are unchanged, as you say; the mismatch is only in the 
declared type. Functions whose result over zero rows is NULL, such as the 
sketch aggregates you mention, are read without the `if(isnull(alwaysTrue), 
...)` correction, so a fix that changes only the corrected functions leaves 
them as they are. This review raises the remaining case, a rebuilt column that 
nests a function such as `count` in a struct, array or map, with a suggested 
fix.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4547009620","thread_id":"inline:4547009620","verdict_sha256":"18909f0085542367814ff9a9e7a12acb91aa26306bf84fa58a0329b394e0e252"}
 -->



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

Review Comment:
   **Nit (P3):** `ref` is declared nullable because it comes from the right 
side of the left outer join, so `if(isnull(alwaysTrue), 0, count)` is nullable 
even though `count` never returns NULL. The rework keeps this off columns 
without a Python UDF, but a rebuilt column that nests the corrected value still 
widens its type. Reading the code, in `LATERAL (SELECT named_struct('n', 
count(*), 'u', udf(max(i.v))) s FROM i WHERE i.k = o.k)`, `s` keeps its 
analyzed expression ID but now has `n` nullable, while the references above the 
subquery still declare `n` as `bigint NOT NULL`. `UpdateAttributeNullability` 
only fixes top-level nullability and the plan integrity check compares types as 
nullable, so nothing reports it, and rows do not change because `n` is 0 or the 
actual count. The `If` reads `ref` only for outer rows with matching rows, so 
wrapping it in `KnownNotNull` when the function is not nullable, e.g. 
`If(IsNull(alwaysTrueRef), default, if (ae.nullable) ref else KnownNotNull(ref
 ))`, keeps the analyzed type. A function whose result over zero rows is NULL 
takes the `case Literal(null, _)` branch and keeps its nullable reference, and 
the plan tests that pull out `count` would then expect the `KnownNotNull`.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60366#discussion_r4547009620).
   
   **Verification:**
   - **Regression:** In a correlated subquery whose COUNT bug 
DecorrelateInnerQuery handles, a Python UDF column that builds a struct with a 
count field keeps the analyzed struct type, with that field non-nullable, in 
the decorrelated plan.
   - **Behavior:** Such a subquery returns the same values as before: 0 for the 
count field of an outer row without matching rows and the actual count 
otherwise.
   - **Compatibility:** A pulled-out function whose result over zero rows is 
NULL, such as max, is still read through a nullable reference, so an outer row 
without matching rows gets NULL.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -958,6 +980,11 @@ object RewriteCorrelatedScalarSubquery extends 
Rule[LogicalPlan] with AliasHelpe
 
             if (havingNode.isEmpty) {
               // CASE 2: Subquery with no HAVING clause
+              // TODO(SPARK-61660): when `resultWithZeroTups` applies a scalar 
Python UDF to an
+              // aggregate function, e.g. `inv(count(*))`, the UDF is kept in 
this conditional
+              // branch and `ExtractPythonUDFs` evaluates it on the values 
over zero rows for every
+              // outer row, so the query can fail even when every outer row 
has matching rows. See
+              // SPARK-61482 for the same fix on the `DecorrelateInnerQuery` 
path.

Review Comment:
   **Nit (P3):** This TODO names only "this conditional branch", but CASE 3 
below, which handles a subquery with a HAVING clause when 
`spark.sql.optimizer.decorrelateInnerQuery.enabled` is off or 
`spark.sql.legacy.scalarSubqueryCountBugBehavior` is on, keeps the same 
`resultWithZeroTups` as the first branch of its `CaseWhen`. Reading the code, 
with decorrelation off, `SELECT o.k, (SELECT udf(10 / count(*)) FROM i WHERE 
i.k = o.k HAVING count(*) >= 0) FROM o` in ANSI mode takes CASE 3, and 
`ExtractPythonUDFs` evaluates `10 / 0` for every outer row, so the query fails 
even when every outer row has matching rows. Nothing at CASE 3 says the fix is 
deferred, so SPARK-61660 could fix CASE 2 and leave CASE 3 failing. Naming both 
branches here would keep the deferral visible:
   
   ```suggestion
                 // TODO(SPARK-61660): when `resultWithZeroTups` applies a 
scalar Python UDF to an
                 // aggregate function, e.g. `inv(count(*))`, the UDF is kept 
in this branch and in
                 // the `CaseWhen` of CASE 3 below, and `ExtractPythonUDFs` 
evaluates it on the values
                 // over zero rows for every outer row, so the query can fail 
even when every outer
                 // row has matching rows. See SPARK-61482 for the 
`DecorrelateInnerQuery` fix.
   ```
   
   **Verification:**
   - **Inspection:** A SPARK-61660 TODO names CASE 3's CaseWhen branch of 
constructLeftJoins as deferred, alongside CASE 2's If branch, and no code 
changes.



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