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


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

Review Comment:
   Done. Added a `TODO(SPARK-61444)` noting that 
`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 
it is optimized, and
   SPARK-61444 addresses that path.



##########
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))
+                }
+                // 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 single aggregate function or a literal (SPARK-43156) 
keeps its name in the
+                // new aggregate.
+                case a @ Alias(child @ (_: Literal | _: AggregateExpression), 
_) =>

Review Comment:
   Fixed. Every aggregate column now goes through the same `pullOut` (I removed 
the separate
   single-aggregate-function branch, which the generic branch handles while 
keeping the output name,
   exprId and metadata), so a function used both as its own column and inside 
an expression is output
   once, shared between them, in a single pass (you were right that a first 
pass is not needed — thank
   you). Added a `SubquerySuite` test with `COUNT(*)` as a column and inside an 
expression that asserts
   the decorrelated `Aggregate` outputs `count` once. The 
`DecorrelateInnerQuerySuite` plan test, which
   already used two separate `count(1)` instances, now expects `c` and `m` to 
share the pulled-out
   columns.



##########
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:
   Thank you — you are right that the pulled-out reference is nullable, so the 
optimized plan computes
   `array(COUNT(*))` with element type `array<bigint>` (`containsNull = true`) 
while it is analyzed as
   `array<bigint not null>`. Looking closer, this does not reach a result: the 
element is
   `if(isnull(alwaysTrue), 0, count)`, so a matched outer row gives the real 
(non-null) count and an
   outer row without matching rows gives `[0]` — a `NULL` element never occurs. 
It is also the
   nullability the base already gives the corrected value at the top level. I 
left it rather than mark
   the matched value `KnownNotNull`, which needs care for functions whose 
result over zero rows is
   `NULL` (the sketch aggregates are non-nullable but return `NULL` here). I 
can file a follow-up to
   tighten the plan's nested nullability if you think it is worth it.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuerySuite.scala:
##########
@@ -209,6 +210,117 @@ class DecorrelateInnerQuerySuite extends PlanTest {
     check(innerPlan, outerPlan, correctAnswer, Seq(x <=> x))
   }
 
+  test("SPARK-61482: COUNT bug handling evaluates only aggregate functions on 
zero tuples") {
+    val outerPlan = testRelation2
+    // Two separate `count(1)` instances, as two `COUNT(*)` in a query are: 
canonically equal,
+    // so they are deduplicated into one output, with different `exprId`s.

Review Comment:
   Done, applied your rewording.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuerySuite.scala:
##########
@@ -209,6 +210,117 @@ class DecorrelateInnerQuerySuite extends PlanTest {
     check(innerPlan, outerPlan, correctAnswer, Seq(x <=> x))
   }
 
+  test("SPARK-61482: COUNT bug handling evaluates only aggregate functions on 
zero tuples") {
+    val outerPlan = testRelation2
+    // Two separate `count(1)` instances, as two `COUNT(*)` in a query are: 
canonically equal,
+    // so they are deduplicated into one output, with different `exprId`s.
+    val cnt1 = count(Literal(1))
+    val cnt2 = count(Literal(1))
+    val maxB = max(b)
+    // Expressions over an aggregate function used twice and over one whose 
result over zero
+    // tuples is NULL, single aggregate functions whose results over zero 
tuples are not NULL
+    // and NULL, and a literal.
+    val d = Alias(cnt1 * 10L + cnt2, "d")()
+    val e = Alias(Coalesce(Seq(maxB, Literal(0))), "e")()
+    val c = Alias(count(Literal(1)), "c")()
+    val m = Alias(maxB, "m")()
+    val l = Alias(Literal(5), "l")()
+    val innerPlan =
+      Aggregate(Nil, Seq(d, e, c, m, l),
+        Filter(OuterReference(x) === a,
+          testRelation))
+    val (outputPlan, joinCond) =
+      DecorrelateInnerQuery(innerPlan, outerPlan.select(), handleCountBug = 
true)
+
+    val cntRes = Alias(cnt1, "aggResult")()
+    val maxRes = Alias(maxB, "aggResult")()
+    val c2 = c.newInstance()
+    val l2 = l.newInstance()
+    val alwaysTrue = Alias(Literal.TrueLiteral, "alwaysTrue")()
+    val alwaysTrueRef = alwaysTrue.toAttribute.withNullability(true)
+    def zeroTups(default: Expression, ref: NamedExpression): Expression =
+      If(IsNull(alwaysTrueRef), default, ref.toAttribute.withNullability(true))
+    val x2 = x.newInstance()
+    val cntValue = zeroTups(Literal(0L), cntRes)
+    val correctAnswer =
+      Project(Seq(
+          Alias(cntValue * 10L + cntValue, "d")(d.exprId),
+          Alias(Coalesce(Seq(maxRes.toAttribute.withNullability(true), 
Literal(0))), "e")(
+            e.exprId),
+          Alias(zeroTups(Literal(0L), c2), "c")(c.exprId),
+          m.toAttribute.withNullability(true),
+          Alias(zeroTups(Literal(5), l2), "l")(l.exprId),
+          x2),
+        DomainJoin(Seq(x2),
+          Aggregate(Seq(a), Seq(cntRes, maxRes, c2, m, l2, a, alwaysTrue),
+            testRelation),
+          LeftOuter,
+          Some(x2 === a)))
+    check(outputPlan, joinCond, correctAnswer, Seq(x2 <=> x))
+  }
+
+  test("SPARK-61482: COUNT bug handling does not deduplicate non-deterministic 
aggregates") {
+    val outerPlan = testRelation2
+    // A non-deterministic aggregate function used twice in an expression. The 
two uses are
+    // canonically equal, but `PhysicalAggregation` does not deduplicate them, 
so each must keep
+    // its own column and the expression must refer to both. (A 
non-deterministic aggregate
+    // cannot occur in a query that passes analysis, so this only pins the 
defensive behavior;
+    // the plan is inspected directly rather than compared, as it would not 
pass `checkAnalysis`.)

Review Comment:
   Done, and thank you for the correction. I verified that two 
non-deterministic aggregate expressions remain in the optimized plan for a
   scalar subquery over a lower `Aggregate` and for an `IN` subquery (in 
`EXISTS` the value is pruned).
   I applied your rewording. The fixture keeps `sum(rand(1))`, whose argument 
is non-deterministic and
   so does not pass analysis, and the test inspects the plan directly.



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