dongjoon-hyun commented on code in PR #60296:
URL: https://github.com/apache/spark/pull/60296#discussion_r4560847115


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -596,32 +658,55 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
       mayHaveCountBugOld, needSingleJoinOld)
         if children.nonEmpty =>
 
+        // An Aggregate without grouping expressions returns one row even on 
empty input,
+        // whatever its aggregate functions are, and an Aggregate above it 
sees that row. If the
+        // Aggregate is correlated, decorrelation can lose that row (see 
below). An uncorrelated
+        // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree 
without outer references
+        // unchanged or inner joins it with the domain, and mayHaveCountBugAgg 
uses the same check
+        // (SubExprUtils.hasOuterReferences).
+        // An Aggregate with an aggregate function with a default result, such 
as COUNT, also
+        // qualifies, correlated or not, as before SPARK-60501; with
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only 
such an Aggregate
+        // does. So does it where the domain joins of DecorrelateInnerQuery, 
which compute the
+        // outer query again, are known not to work, so as not to make such 
queries worse than
+        // before. The check is conservative: e.g. the domain joins fail for a 
streaming query
+        // and for outer references that are not orderable, and can find other 
rows the second
+        // time for a non-deterministic input, or for a CTE that is not 
inlined, which may be a
+        // non-deterministic one (a CTERelationRef does not tell).
+        val domainJoinsWork = !plan.isStreaming &&
+          plan.children.forall(c => c.deterministic && 
!c.containsPattern(CTE)) &&

Review Comment:
   **[10] `domainJoinsWork` is decided on `plan.children` when this rule runs, 
but the domain joins are built later from the operator's child, which 
`PushDownPredicates` can still change.** For `SELECT * FROM (SELECT o.k, 
(SELECT COUNT(*) FROM (SELECT MAX(b.v) FROM b WHERE b.k = o.k)) c FROM o) WHERE 
spark60501_rk(k) > 500`, the `Filter` is still above the `Project` here, so 
`plan.children` is just `o`, the check passes, and the subquery gets the domain 
joins. In the operator optimization batch, `PushDownPredicates` runs before 
`RewriteCorrelatedScalarSubquery` (Optimizer.scala:108 and 
Optimizer.scala:152), and `PushPredicateThroughNonJoin` moves the condition 
below the `Project`, because it only requires the projected fields to be 
deterministic and `k` is a plain column (Optimizer.scala:2670). 
`RewriteCorrelatedScalarSubquery` then builds the domain from `currentChild` 
(L993), which is now `Filter(spark60501_rk(k) > 500, o)`, so the random filter 
is evaluated a second time for the d
 omain. Outer rows that pass the first evaluation but not the second get `c = 
NULL` instead of `1`, the failure that the new test at SubquerySuite.scala:3446 
describes. On `master`, this shape has no domain join and returns `1` for every 
row. A view or a derived table over the subquery, filtered by the caller, gets 
the same plan. Could the check cover the plan that the domain is finally built 
from (see item 15), and could a test cover this shape (item 13)?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -596,32 +658,55 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
       mayHaveCountBugOld, needSingleJoinOld)
         if children.nonEmpty =>
 
+        // An Aggregate without grouping expressions returns one row even on 
empty input,
+        // whatever its aggregate functions are, and an Aggregate above it 
sees that row. If the
+        // Aggregate is correlated, decorrelation can lose that row (see 
below). An uncorrelated
+        // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree 
without outer references
+        // unchanged or inner joins it with the domain, and mayHaveCountBugAgg 
uses the same check
+        // (SubExprUtils.hasOuterReferences).
+        // An Aggregate with an aggregate function with a default result, such 
as COUNT, also
+        // qualifies, correlated or not, as before SPARK-60501; with
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only 
such an Aggregate
+        // does. So does it where the domain joins of DecorrelateInnerQuery, 
which compute the
+        // outer query again, are known not to work, so as not to make such 
queries worse than
+        // before. The check is conservative: e.g. the domain joins fail for a 
streaming query
+        // and for outer references that are not orderable, and can find other 
rows the second
+        // time for a non-deterministic input, or for a CTE that is not 
inlined, which may be a

Review Comment:
   **[11] An outer input that is deterministic as a plan but not repeatable 
passes the check.** The comment covers a non-deterministic input, but 
`c.deterministic` is also true for `LIMIT` or `OFFSET` without a total order, 
`ORDER BY` a non-unique key with `LIMIT`, or a filter on `row_number()` over 
ties, which can keep other rows when they are computed again. For `SELECT o.k, 
o.x, (SELECT COUNT(*) FROM (SELECT MAX(b.v) FROM b WHERE b.k = o.k)) FROM 
(SELECT * FROM a LIMIT 1000) o` over a table `a` with several partitions, the 
domain copy is pruned to `k` by `PushProjectionThroughLimitAndOffset`, so it 
likely does not reuse the main copy's exchange, and the two `GlobalLimit`s can 
keep different rows depending on the shuffle fetch order. Outer rows missing 
from the domain then get `NULL` instead of `1`, while `master` needs no domain 
join for this shape. Could the check also reject such inputs, or could this 
comment and the migration guide say that they are not covered?



##########
sql/core/src/test/resources/sql-tests/inputs/subquery/scalar-subquery/nested-scalar-subquery-count-bug.sql:
##########
@@ -28,6 +28,269 @@ select (
   on l.cnt = r.cnt
 ) a from t1 order by a desc;
 
+-- test for count bug in nested aggregates whose lower aggregate has no 
function with a default
+-- result, such as COUNT: the lower aggregate returns one row even when no row 
of t2 matches
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 = 
t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select min(b2) m from t2 where t1.a1 = 
t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select sum(b2) m from t2 where t1.a1 = 
t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select avg(b2) m from t2 where t1.a1 = 
t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select sum(s) from (select coalesce(sum(b2), 10) s from t2 where 
t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+-- with a filter between the aggregates
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 = 
t2.b1)
+  where m is null ) a
+from t1 order by a1;
+
+-- with a literal next to the lower aggregate function
+select a1, ( select sum(s) from (select 10 s, max(b2) m from t2 where t1.a1 = 
t2.b1) ) a
+from t1 order by a1;
+
+-- with a non-equality correlated predicate
+select a1, ( select sum(s) from (select coalesce(sum(b2), 10) s from t2 where 
t2.b1 < t1.a1) ) a
+from t1 order by a1;
+
+-- with three levels of aggregates
+select a1, ( select count(*) from (select max(m) m2 from (select max(b2) m 
from t2
+  where t1.a1 = t2.b1)) ) a
+from t1 order by a1;
+
+-- with a grouped aggregate between the aggregates
+select a1, ( select count(*) from (select m from (select max(b2) m from t2
+  where t1.a1 = t2.b1) group by m) ) a
+from t1 order by a1;
+
+-- with a grouped top aggregate
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 = 
t2.b1) group by m ) a
+from t1 order by a1;
+
+-- with correlated predicates in both aggregates
+select a1, ( select sum(s) from (select coalesce(sum(b2), 10) s from t2 where 
t1.a1 = t2.b1)
+  where t1.a2 > 1 ) a
+from t1 order by a1;
+
+-- with an outer row whose correlated column is null
+select a1, ( select count(*) from (select max(b2) m from t2 where t.a1 = 
t2.b1) ) a
+from values (0), (1), (null) as t(a1) order by a1;
+
+-- with a join, a union, an intersect, a limit or a window function over the 
lower aggregates
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 = 
t2.b1) l,
+  (select min(b2) n from t2 where t1.a1 = t2.b1) r ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 = t2.b1
+  union all select min(b2) from t2 where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 = t2.b1
+  intersect select max(b2) from t2 where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select max(b2) m from t2 where t1.a1 = 
t2.b1 limit 1) ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select m, rank() over (order by m) r from
+  (select max(b2) m from t2 where t1.a1 = t2.b1)) ) a
+from t1 order by a1;
+
+-- with an uncorrelated lower aggregate and a correlated predicate above it
+select a1, ( select count(*) from (select max(b2) m from t2) where m > t1.a2 + 
1 ) a
+from t1 order by a1;
+
+select a1, ( select count(*) from (select count(*) c from t2) where c > t1.a2 
) a
+from t1 order by a1;
+
+-- with top aggregates over the one row of a lower aggregate that returns NULL 
on empty input:
+-- functions that return over a NULL row what they return over no rows, such 
as SUM and
+-- COLLECT_LIST, and others, such as COUNT(*), with FILTER, DISTINCT, decimal 
and bigint inputs
+select a1, ( select collect_list(m) from (select max(b2) m from t2 where t1.a1 
= t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select sum(m) + 1 from (select max(b2) m from t2 where t1.a1 = 
t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select stddev_samp(m) from (select max(b2) m from t2 where t1.a1 
= t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select struct(sum(m), count(m), max(m), min(m), avg(m), 
collect_set(m))
+  from (select max(b2) m from t2 where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select collect_list(m) respect nulls from (select max(b2) m from 
t2
+  where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select collect_set(m) respect nulls from (select max(b2) m from t2
+  where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select first(m) respect nulls from (select max(b2) m from t2
+  where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select struct(count(*), collect_list(m)) from (select max(b2) m 
from t2
+  where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select struct(count(*) filter (where m is null), count(*) filter 
(where m > 2))
+  from (select max(b2) m from t2 where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+select a1, ( select struct(sum(m) filter (where m > 2), sum(m) filter (where m 
> 3),
+  count(m) filter (where m is null), collect_list(m) filter (where m is null))
+  from (select max(b2) m from t2 where t1.a1 = t2.b1) ) a
+from t1 order by a1;
+
+-- a FILTER condition that fails on the NULL row is not evaluated for it, 
since the count bug

Review Comment:
   **[12] Minor: following up on your 
[reply](https://github.com/apache/spark/pull/60296#discussion_r4559640298) on 
item 7, a `FILTER` can also fail on the `NULL` row, not only keep or drop it.** 
For `a1 = 1`, the lower aggregate returns one row with `m = NULL`, and `10 / 
COALESCE(m, 0)` divides by zero on it, so in ANSI mode I think this query 
should fail, as the same subquery does with `t2.b1 = 1` instead of the 
correlated predicate, or as a `LATERAL` subquery, which `DecorrelateInnerQuery` 
handles. Here it returns `NULL`, because `sameResultOverEmptyLowerAggregate` 
keeps a top aggregate with a `FILTER` in `constructLeftJoins` 
(subquery.scala:621), which replaces the top function with its result over no 
rows. The migration guide now says that an expression over the result of the 
lower aggregate can fail for such a row, so this case goes the other way. The 
result is the same as on `master`, so this is not a regression, but the golden 
file now pins it as intended. Could a top aggrega
 te with a `FILTER` go to `DecorrelateInnerQuery`, like the functions outside 
the list, or could the comment here say that it differs from the `LATERAL` and 
uncorrelated forms?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -567,6 +567,68 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
      nonEquivalentGroupbyCols(query, aggNode.get).isEmpty
    }
 
+  // Whether some aggregate function of `a` has a default result on empty 
input, such as COUNT.
+  private def hasDefaultResult(a: Aggregate): Boolean =
+    a.aggregateExpressions.exists(_.exists {
+      case ae: AggregateExpression => 
ae.aggregateFunction.defaultResult.isDefined
+      case _ => false
+    })
+
+  /**
+   * Returns true if the Aggregate without grouping expressions `agg` returns 
the same result
+   * over the one row that the Aggregate without grouping expressions below it 
returns on empty
+   * input as over no rows, so that constructLeftJoins handles its count bug 
correctly even
+   * though decorrelation loses that row, with fewer joins than 
DecorrelateInnerQuery. E.g.
+   * SUM(s) and COLLECT_LIST(s) over s = MAX(b.v) return NULL and [] over 
both. The check is
+   * conservative: it accepts only a short list of functions of `agg` directly 
over outputs of
+   * lower aggregate functions, with only Projects between, and leaves other 
shapes that have
+   * this property, such as STDDEV_SAMP(s), to DecorrelateInnerQuery. It never 
accepts a lower
+   * Aggregate with a function with a `defaultResult`, such as COUNT, which 
DecorrelateInnerQuery
+   * handled before SPARK-60501. Like the rest of the count bug handling, this 
relies on
+   * `defaultResult` matching the result on empty input.
+   */
+  private def sameResultOverEmptyLowerAggregate(agg: Aggregate): Boolean = {
+    // The attributes of `plan` that the count bug handling takes as NULL when 
the lower Aggregate
+    // gets empty input.
+    def nullOnEmptyInput(plan: LogicalPlan): Option[AttributeSet] = plan match 
{
+      case Project(projectList, child) =>
+        nullOnEmptyInput(child).map { attrs =>
+          AttributeSet(projectList.collect {
+            case a: Attribute if attrs.contains(a) => a
+            case a @ Alias(c: Attribute, _) if attrs.contains(c) => 
a.toAttribute
+          })
+        }
+      case lower: Aggregate if lower.groupingExpressions.isEmpty &&
+          !lower.child.exists(_.isInstanceOf[Aggregate]) && 
!hasDefaultResult(lower) =>
+        Some(AttributeSet(lower.aggregateExpressions.collect {
+          case a @ Alias(_: AggregateExpression, _) => a.toAttribute
+        }))
+      case _ => None
+    }
+    val aggregates = agg.aggregateExpressions.flatMap(_.collect {
+      case ae: AggregateExpression => ae
+    })
+    agg.groupingExpressions.isEmpty &&
+      nullOnEmptyInput(agg.child).exists { attrs =>
+        aggregates.forall { ae =>
+          val sameResultOverNulls = ae.aggregateFunction match {
+            case _: Max | _: Min | _: Sum | _: Average | _: Count | _: First | 
_: Last => true

Review Comment:
   **[16] Minor: following up on item 7 
([thread](https://github.com/apache/spark/pull/60296#discussion_r4534296228)), 
the property is a list of classes in this rule.** Thank you for keeping the old 
plan for these shapes. As you wrote there, Spark has no property for "returns 
over a row of `NULL`s what it returns over no rows", so each function with it 
that is not listed, e.g. `BitAndAgg`, `BitOrAgg`, `BitXorAgg`, `Product`, 
`MaxBy`, `MinBy`, or a function from an extension, gets the extra domain joins, 
and keeping its plan means editing this rule. Could the property go on 
`AggregateFunction` next to `defaultResult` (default `false`), in this PR or a 
follow-up, so that each function states it where its empty-input result is 
already defined?



##########
sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala:
##########
@@ -3401,4 +3403,134 @@ class SubquerySuite extends SharedSparkSession
         Row(1, 2))
     }
   }
+
+  test("SPARK-60501: count bug of correlated scalar subqueries over an emptied 
local relation") {
+    withTempView("t1", "t2") {
+      sql("CREATE TEMP VIEW t1(a1, a2) AS VALUES (1, 1), (2, 2)")
+      sql("CREATE TEMP VIEW t2(b1, b2) AS VALUES (1, 1), (2, 2)")
+      // ConvertToLocalRelation, which the test session excludes, empties the 
filtered relation.
+      withSQLConf(SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> "") {
+        // Projections over a COUNT whose filtered input becomes empty.
+        checkAnswer(
+          sql("SELECT a1, (SELECT s * s FROM (SELECT c + 1 AS s FROM (SELECT 
COUNT(*) c FROM t2 " +
+            "WHERE t2.b1 = t1.a1 AND t2.b2 > 10))) FROM t1"),
+          Seq(Row(1, 1), Row(2, 1)))
+        // Results of COUNT(*) over a lower MAX, which goes to decorrelation, 
and of top aggregates
+        // over a lower MAX that stay in constructLeftJoins (the routing is 
checked in
+        // PullupCorrelatedPredicatesSuite).
+        checkAnswer(
+          sql("SELECT a1, (SELECT COUNT(*) FROM (SELECT MAX(b2) m FROM t2 " +
+            "WHERE t2.b1 = t1.a1 AND t2.b2 > 10)) FROM t1"),
+          Seq(Row(1, 1), Row(2, 1)))
+        checkAnswer(
+          sql("SELECT a1, (SELECT struct(SUM(m), COUNT(m), COLLECT_LIST(m)) 
FROM " +
+            "(SELECT MAX(b2) m FROM t2 WHERE t2.b1 = t1.a1 AND t2.b2 > 10)) 
FROM t1"),
+          Seq(Row(1, Row(null, 0, Seq())), Row(2, Row(null, 0, Seq()))))
+        // An uncorrelated lower COUNT returns the correct result, as before 
(the routing is
+        // checked in PullupCorrelatedPredicatesSuite).
+        checkAnswer(
+          sql("SELECT a1, (SELECT COUNT(*) FROM (SELECT COUNT(*) c FROM t2 
WHERE t2.b2 > 10) " +
+            "WHERE c < t1.a2) FROM t1"),
+          Seq(Row(1, 1), Row(2, 1)))
+      }
+    }
+  }
+
+  test("SPARK-60501: a non-deterministic input of the operator with the 
subquery keeps the " +

Review Comment:
   **[13] Minor: these tests put the non-deterministic expression only below 
the operator with the subquery.** Both queries compute `spark60501_rk` inside 
`o`, which `plan.children` sees. Could a test also cover the cases of items 10 
and 11: a non-deterministic predicate above a `Project` with the subquery, e.g. 
a derived table over the subquery filtered with `spark60501_rk(k) > 500`, and a 
`LIMIT` in the outer input, checking the result or that the optimized plan has 
no domain join, as the SPARK-60969 test above does with `collectLeaves`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -596,32 +658,55 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
       mayHaveCountBugOld, needSingleJoinOld)
         if children.nonEmpty =>
 
+        // An Aggregate without grouping expressions returns one row even on 
empty input,
+        // whatever its aggregate functions are, and an Aggregate above it 
sees that row. If the
+        // Aggregate is correlated, decorrelation can lose that row (see 
below). An uncorrelated
+        // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree 
without outer references
+        // unchanged or inner joins it with the domain, and mayHaveCountBugAgg 
uses the same check
+        // (SubExprUtils.hasOuterReferences).
+        // An Aggregate with an aggregate function with a default result, such 
as COUNT, also
+        // qualifies, correlated or not, as before SPARK-60501; with
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only 
such an Aggregate
+        // does. So does it where the domain joins of DecorrelateInnerQuery, 
which compute the
+        // outer query again, are known not to work, so as not to make such 
queries worse than
+        // before. The check is conservative: e.g. the domain joins fail for a 
streaming query
+        // and for outer references that are not orderable, and can find other 
rows the second
+        // time for a non-deterministic input, or for a CTE that is not 
inlined, which may be a
+        // non-deterministic one (a CTERelationRef does not tell).
+        val domainJoinsWork = !plan.isStreaming &&
+          plan.children.forall(c => c.deterministic && 
!c.containsPattern(CTE)) &&
+          children.forall(e => RowOrdering.isOrderable(e.dataType))
+        val legacyNestedAggregateCountBug =

Review Comment:
   **[17] Nit: `legacyNestedAggregateCountBug` is also true without the legacy 
conf.** It is `true` for a streaming query, a non-deterministic or CTE outer 
input, and outer references that are not orderable, so `mayHaveCountBugAgg` 
reads as if only the legacy conf turned the correlation check off, and the 
comment above ("So does it where ...") leaves the reader to put this together. 
`domainJoinsWork` also uses the pattern variable `children` (the outer 
attributes of the subquery, L678) right after `plan.children` (L677). Could the 
`val` be named for what it means (e.g. 
`onlyDefaultResultSelectsDecorrelation`), with a local name such as 
`outerAttrs` for `children`? Both `val`s are also computed for every correlated 
scalar subquery but read only when the top node is an `Aggregate`. The cost is 
small, since `deterministic` is cached on the plan, but they could be `lazy 
val`s.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -596,32 +658,55 @@ object PullupCorrelatedPredicates extends 
Rule[LogicalPlan] with PredicateHelper
       mayHaveCountBugOld, needSingleJoinOld)
         if children.nonEmpty =>
 
+        // An Aggregate without grouping expressions returns one row even on 
empty input,
+        // whatever its aggregate functions are, and an Aggregate above it 
sees that row. If the
+        // Aggregate is correlated, decorrelation can lose that row (see 
below). An uncorrelated
+        // one keeps its row: [[DecorrelateInnerQuery]] leaves a subtree 
without outer references
+        // unchanged or inner joins it with the domain, and mayHaveCountBugAgg 
uses the same check
+        // (SubExprUtils.hasOuterReferences).
+        // An Aggregate with an aggregate function with a default result, such 
as COUNT, also
+        // qualifies, correlated or not, as before SPARK-60501; with
+        // LEGACY_SCALAR_SUBQUERY_NESTED_AGGREGATE_COUNT_BUG_BEHAVIOR, only 
such an Aggregate
+        // does. So does it where the domain joins of DecorrelateInnerQuery, 
which compute the
+        // outer query again, are known not to work, so as not to make such 
queries worse than
+        // before. The check is conservative: e.g. the domain joins fail for a 
streaming query
+        // and for outer references that are not orderable, and can find other 
rows the second
+        // time for a non-deterministic input, or for a CTE that is not 
inlined, which may be a
+        // non-deterministic one (a CTERelationRef does not tell).
+        val domainJoinsWork = !plan.isStreaming &&

Review Comment:
   **[15] Minor: the check is a one-time decision on a plan that later rules 
still change.** `domainJoinsWork` decides the routing in this rule, but the 
domain joins compute again the plan that `RewriteCorrelatedScalarSubquery` sees 
at L993, after the operator optimization rules have rewritten the outer plan, 
which is how item 10 gets past it. Could the requirement travel with the 
subquery, e.g. a flag next to `mayHaveCountBug` saying that its domain joins 
compute the outer input again, so that the rules that change that input before 
`RewriteCorrelatedScalarSubquery` can keep it repeatable?



##########
docs/sql-migration-guide.md:
##########
@@ -100,6 +100,7 @@ license: |
 - Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT` 
adds to a Data Source V2 table, and whose condition reads the current time, 
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db = 
current_database()`, is checked against their values at the time of each write. 
Previously, it was checked against their values at the time of the `ALTER 
TABLE`, unless a write could not read back a predicate for its condition, such 
as one with a lambda function or one that passes a column to `datediff`, `year` 
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so 
each write parses and analyzes its SQL text under the session of the write, as 
it does for a constraint without a predicate that `CREATE TABLE` adds. A 
setting of the write such as `spark.sql.ansi.enforceReservedKeywords`, which 
reserves `TIME`, or `spark.sql.ansi.doubleQuotedIdentifiers` can then make it 
fail to parse the text or read it differently. A row-level operation
  that copies unchanged rows, such as a `DELETE` or `UPDATE` on a copy-on-write 
table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row that no longer 
satisfies the condition. For example, `ts >= current_timestamp() - INTERVAL 30 
DAYS` now fails such a `DELETE` once a copied row is older than 30 days. A 
condition that Spark detects a write could resolve differently is stored as 
before, so a write accepts and rejects the same rows for it as before. Examples 
are conditions that also read a variable, a `CHAR` column, a name with more 
than one part such as a column qualified by the table name, or a constant that 
depends on the session time zone, such as `'2024-01-01 00:00:00'` cast to a 
timestamp. So are conditions with a name such as `current_date` or `user` 
without parentheses, which a write can read as a column name, and conditions 
whose text the parser settings of the `ALTER TABLE`, such as 
`spark.sql.ansi.doubleQuotedIdentifiers` or 
`spark.sql.parser.escapedStringLiterals`, r
 ead differently from their default values. ANSI mode, 
`spark.sql.timestampType` and the session time zone are taken from the session 
for this comparison, as for a generation expression. A condition that reads the 
current date or time only through a typed literal such as `DATE 'today'` is 
also stored as before. An existing constraint keeps its stored predicate until 
it is dropped and added again. `Check.predicate()` is null for a constraint 
stored without a predicate, so a connector that validates or enforces it itself 
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set 
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding 
the constraint. A constraint added without it is not changed.
 - Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'` 
whose class implements 
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends 
either a Hive UDF class (such as `UDF` or `GenericUDF`) or 
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a 
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions 
created in earlier versions. Its result type, argument coercion, and null 
handling are defined by the V2 implementation selected by 
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic` 
property do not control the V2 path. For scalar functions, determinism uses 
`BoundFunction.isDeterministic()` (default `true`) and the arguments' 
determinism. A call with constant arguments can therefore become eligible for 
constant folding during query planning instead of being evaluated per row.
 - Since Spark 4.4, `next_day` and `last_day` fail with `DATETIME_OVERFLOW` 
when the result is later than the maximum `DATE`, `+5881580-07-11`, and `trunc` 
fails with it when the result is earlier than the minimum `DATE`, 
`-5877641-06-23`, regardless of `spark.sql.ansi.enabled`. Previously, these 
functions silently returned a wrong date, in most cases one at the other end of 
the `DATE` range; for example, `last_day(DATE'+5881580-07-11')` returned 
`-5877641-07-12` and `trunc(DATE'-5877641-06-23', 'MONTH')` returned 
`+5881580-06-20`, while `trunc` to `QUARTER` failed with `ARITHMETIC_OVERFLOW`. 
`next_day` and `trunc` to `WEEK` also returned a wrong date for the first days 
of the `DATE` range; for example, `next_day(DATE'-5877641-06-23', 'MO')` and 
`trunc(DATE'-5877641-07-01', 'WEEK')` returned `-5877641-06-25`, a Thursday, 
and now return `-5877641-06-29`.
+- Since Spark 4.4, a correlated scalar subquery whose top aggregate is over a 
correlated aggregate without `GROUP BY` returns the correct result for an outer 
row without matching rows. For example, `SELECT COUNT(*) FROM (SELECT MAX(b.v) 
FROM b WHERE b.k = a.k)` returned `0` instead of `1` for such a row 
(SPARK-60501, SPARK-60502). Data derived from affected query results may need 
to be recomputed. An expression over the result of the lower aggregate, 
including a Python UDF, can now also be evaluated for such a row, so it can 
fail there, e.g. `10 / COALESCE(MAX(b.v), 0)` in ANSI mode, even when another 
condition of the query removes that row. Such queries can also be planned with 
more left outer joins than before. The fix is conservative: where the 
decorrelation it relies on does not apply, such as in a streaming query, the 
previous result is kept. To restore the previous behavior, set 
`spark.sql.legacy.scalarSubqueryNestedAggregateCountBugBehavior` to `true`.

Review Comment:
   **[14] Minor: the guide names only a streaming query among the inputs that 
keep the previous result.** As you wrote in your 
[comment](https://github.com/apache/spark/pull/60296#issuecomment-6843913194), 
the check is conservative, and e.g. an unused non-deterministic column also 
keeps the previous result: `SELECT (SELECT COUNT(*) FROM (SELECT MAX(b.v) FROM 
b WHERE b.k = o.k)) FROM (SELECT k, rand() r FROM a) o` still returns `0` 
instead of `1` for an unmatched `k`. So does an outer input over any CTE that 
is not inlined, including a deterministic `WITH o AS MATERIALIZED (...)`, since 
its `CTERelationRef` sets the `CTE` pattern (subquery.scala:677), and outer 
references of a type that is not orderable. A user can hit these without 
streaming, and nothing in the plan or the result shows that the fix did not 
apply. Could the guide and the PR description also name a non-deterministic 
expression anywhere in the outer input, a CTE that is not inlined, and outer 
references that are not ord
 erable?



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