sarutak opened a new pull request, #60296:
URL: https://github.com/apache/spark/pull/60296

   ### What changes were proposed in this pull request?
   
   A correlated scalar subquery whose top `Aggregate` is over a correlated 
`Aggregate` without `GROUP BY` returns wrong results for outer rows without 
matching rows, unless some lower `Aggregate` without `GROUP BY` in the subquery 
has an aggregate function with a default result on empty input, such as 
`COUNT`. This PR fixes that in `PullupCorrelatedPredicates`.
   
   `PullupCorrelatedPredicates` handles the count bug of a correlated scalar 
subquery in one of two places:
   
   - `DecorrelateInnerQuery`, which adds a left outer domain join for every 
correlated `Aggregate` without `GROUP BY` in the subquery, the top one 
included, and evaluates its outputs on zero rows.
   - `RewriteCorrelatedScalarSubquery.constructLeftJoins`, which only fixes the 
result of the top `Aggregate` after the subquery is joined to the outer query.
   
   When the top node of the subquery is an `Aggregate`, the rule has picked 
`DecorrelateInnerQuery` since SPARK-45507 only if a lower `Aggregate` without 
`GROUP BY` has an aggregate function with a `defaultResult`, such as `COUNT` or 
`COLLECT_LIST`. But an `Aggregate` without `GROUP BY` returns one row even on 
empty input, whatever its aggregate functions are, and the `Aggregate` above it 
sees that row. Decorrelation groups a correlated lower `Aggregate` by the 
correlated columns, so it returns no row for an outer row without matching 
rows, and `constructLeftJoins` cannot bring that row back.
   
   This PR makes three changes in 
`PullupCorrelatedPredicates.rewriteSubQueries`:
   
   1. The rule picks `DecorrelateInnerQuery` for every correlated lower 
`Aggregate` without `GROUP BY`. An uncorrelated one is not decorrelated and 
keeps its row, so it does not need the handling. This also stops a subquery 
with an uncorrelated lower `COUNT` from taking the extra join that SPARK-45507 
gave it.
   2. Before that choice, an `Aggregate` without `GROUP BY` over another one, 
with only `Project`s between them, becomes a `Project`. The lower one returns 
exactly one row, so each aggregate function of the upper one is computed over 
that row: the update expressions of the `DeclarativeAggregate` are applied once 
to its initial values, then its evaluate expression. For example, `COUNT(*)` 
becomes 1 and `SUM(s)` becomes `s` cast to the sum's type, both with the type 
of the original result. A `FILTER` keeps the initial values when its condition 
does not hold, and `DISTINCT` does not change the result over one row. The 
`Aggregate` is kept if one of its functions is not declarative, such as 
`COLLECT_LIST`, `PERCENTILE` or a UDAF, or if the result would not keep the 
data type or nullability of the function. After the rewrite, the lower 
`Aggregate` is often the top one, and `constructLeftJoins` handles its count 
bug with one join, as before this PR.
   3. To find the top node, the rule skips `Project`s at the top of the 
subquery that do not reference the outer query. Without this, the `Project` 
left by change 2, or one written in the query such as `SELECT s + 1 FROM 
(SELECT MAX(...) ...)`, made the rule handle the count bug in 
`DecorrelateInnerQuery`, with an extra domain join.
   
   Changes 2 and 3 are disabled when the rule keeps the plans of earlier 
versions: `spark.sql.optimizer.decorrelateInnerQuery.enabled=false`, 
`spark.sql.legacy.scalarSubqueryCountBugBehavior=true`, or the new internal 
conf `spark.sql.legacy.scalarSubqueryNestedAggregateCountBugBehavior=true` 
(default `false`), which restores the previous behavior. The PR also rewrites 
the comments that explain the choice, adds a note to the Scaladoc of 
`ImperativeAggregate` that the optimizer cannot compute it from expressions, 
and adds a migration guide entry.
   
   ### Why are the changes needed?
   
   The queries return wrong results without an error. With `a(k, x) = (1, 10), 
(2, 20)` and `b(k, v) = (1, 100), (1, 200)`:
   
   ```sql
   SELECT a.k, (SELECT COUNT(*) FROM (SELECT MAX(b.v) AS s FROM b WHERE b.k = 
a.k) t) FROM a;
   -- k = 2: 1 expected, 0 returned (SPARK-60501)
   
   SELECT a.k, (SELECT SUM(s) FROM (SELECT COALESCE(SUM(b.v), 10) AS s FROM b 
WHERE b.k = a.k) t)
   FROM a;
   -- k = 2: 10 expected, NULL returned (SPARK-60502)
   ```
   
   For `k = 2`, `SELECT MAX(b.v) FROM b WHERE b.k = 2` returns one row, `NULL`, 
so `COUNT(*)` over it is 1. Spark already returns 1 when the same query is 
written without correlation (`b.k = 2`) or with `LATERAL`, and SQLite returns 1 
and 10.
   
   The same happens with `MIN`, `SUM` and `AVG` as the lower aggregate 
function, with a `Filter`, a grouped `Aggregate`, a join, a `UNION ALL`, a 
`LIMIT` or a window function between the two aggregates, with a grouped top 
`Aggregate`, with a literal column next to the lower aggregate function, with a 
non-equality correlated predicate, and with three levels of aggregates.
   
   The code that this PR changes exists in `branch-4.0` and later. This PR is 
for `master` and `branch-4.x`. Separate backport PRs for `branch-4.3`, 
`branch-4.2`, `branch-4.1` and `branch-4.0` will follow, each with the 
migration guide entry of that branch, as SPARK-60486 did, and the conf version 
of that branch, as SPARK-51616 did. The backports to `branch-4.1` and 
`branch-4.0` also drop `withBindingPolicy`, which those branches do not have.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes.
   
   - A correlated scalar subquery whose top `Aggregate` is over a correlated 
`Aggregate` without `GROUP BY` returns the correct result for outer rows 
without matching rows, when no lower `Aggregate` without `GROUP BY` has a 
function with a default result. The queries above return 1 and 10 for `k = 2`.
   - The number of left outer joins changes for some correlated scalar 
subqueries. With the tables above, before and after this PR:
   
     | Subquery | Joins before | Joins after |
     |---|---|---|
     | `COUNT(*)`, `SUM(s)` or `SUM(s) + 1` over `MAX(b.v)`; `SUM(s)` over 
`COALESCE(SUM(b.v), 10)`; `COUNT(*)` over `MAX(s)` over `MAX(b.v)` | 1 | 1 |
     | `SUM(c)` over `COUNT(*)` | 3 | 1 |
     | `COUNT(*)` over `COUNT(*)` | 2 | 1 |
     | `s` or `s + 1` over `MAX(b.v)`; `COALESCE(c, 10)` over `COUNT(*)` | 2 | 
1 |
     | `COUNT(*)` over an uncorrelated `COUNT(*)` with a correlated `Filter` 
above it | 2 | 1 |
     | `COLLECT_LIST(s)` or `PERCENTILE(s, 0.5)` over `MAX(b.v)` | 1 | 3 |
     | `COUNT(*)` over `MAX(b.v)` with a `Filter` between them | 1 | 3 |
     | `COUNT(*)` over `MAX(b.v) UNION ALL MIN(b.v)` | 1 | 4 |
     | `COUNT(*)` over `MAX(b.v)` with a window between them | 1 | 3 |
     | `COUNT(*)` over a `GROUP BY s` over `MAX(b.v)` | 1 | 2 |
     | `COUNT(*)` over `MAX(b.v)` with a `LIMIT 1` between them | 1 | 2 |
     | `COUNT(*)` over a join of two one-row aggregates | 1 | 2 |
     | grouped `COUNT(*)` over `MAX(b.v)` | 1 | 2 |
   
     More joins remain when the top `Aggregate` has `GROUP BY` or a function 
the rewrite cannot compute over one row (a non-declarative function such as 
`COLLECT_LIST` or `PERCENTILE`, or one whose result would change type or 
nullability), or when a node other than a projection, such as a `Filter`, a 
join, a `LIMIT` or a window, is between the aggregates. Each added join joins 
the subquery with the distinct values of the correlated columns, which are 
computed from the outer query again, so such a query can be slower than before. 
This is also the case when the previous plan returned the correct result, as 
for `COLLECT_LIST(s)` over `MAX(b.v)`, because `COLLECT_LIST` skips the `NULL` 
row of the lower aggregate. None of the TPC-DS and TPC-H plans in the plan 
stability suites change.
   - `spark.sql.legacy.scalarSubqueryNestedAggregateCountBugBehavior=true` 
restores the previous behavior.
   
   Other plans do not change. A plan changes only for a correlated scalar 
subquery that has an `Aggregate` without `GROUP BY` below another `Aggregate` 
or below a `Project` without outer references (change 2 or 3, anywhere in the 
subquery), or a correlated lower `Aggregate` without `GROUP BY` (change 1). The 
fix does not change the paths where `PullupCorrelatedPredicates` does not 
handle the count bug in `DecorrelateInnerQuery`: 
`spark.sql.optimizer.decorrelateInnerQuery.enabled=false` and 
`spark.sql.legacy.scalarSubqueryCountBugBehavior=true`. Both are internal 
confs, and both also return wrong results for the shapes that SPARK-45507 fixed.
   
   ### How was this patch tested?
   
   - New queries in `nested-scalar-subquery-count-bug.sql` for each shape 
listed above, for correlated predicates in both aggregates, for an outer row 
whose correlated column is `NULL`, for an uncorrelated lower `MAX` and `COUNT` 
with a correlated predicate above it, and two queries under the legacy conf. 
Queries over the one row of a lower `MAX` check the rewrite of change 2: 
`COLLECT_LIST` alone and together with `COUNT(*)`, `FILTER` (including a 
condition that is `NULL`, and a `COUNT(*) FILTER` whose expected result tells 
it apart from treating a `NULL` condition as true), `DISTINCT`, `SUM` and `AVG` 
of decimal and bigint values, `STDDEV_SAMP`, `VAR_POP`, `FIRST`/`LAST` with and 
without `IGNORE NULLS`, and a grouped lower `Aggregate`, which is not 
rewritten. Two more check change 3 with a `Project` over a single correlated 
`MAX` and `COUNT`.
   - Two new tests in `PullupCorrelatedPredicatesSuite`. The first checks which 
of the two places handles the count bug for a correlated lower `MAX`, `SUM`, 
`COALESCE(SUM, 10)` and `COUNT`, a `MAX` whose correlated predicate is not 
right below it, a grouped `MAX`, and an uncorrelated `MAX` and `COUNT`, under 
`COLLECT_LIST` so that change 2 does not apply, and with the legacy conf. The 
second checks for which top aggregates and shapes change 2 removes the upper 
`Aggregate` (including a top aggregate with only a literal), that change 3 
skips only `Project`s without outer references, that a non-deterministic 
argument or `FILTER` and a result with another data type or nullability keep 
the `Aggregate`, and that each of the three confs disables both changes. Both 
check that running the rule again does not change the plan.
   - Every built-in function that is a `DeclarativeAggregate` after 
`ReplaceExpressions` (45 names, such as `MAX`, `SUM`, `AVG`, `STDDEV`, `CORR`, 
`REGR_*`, `MAX_BY`, `TRY_SUM`, `BOOL_AND` and `COUNT_IF`) was run over a 
correlated lower `MAX` of int, decimal, bigint, string, boolean and double 
values, with matching and missing keys and a `NULL` key: 182 combinations 
returned the same results as the same subquery with the key as a literal, and 
all of them were rewritten. The data type and nullability checks of change 2 
rejected none of them. Also, 18 lower and 14 top aggregate functions (252 
combinations) return the same results as with change 1 only.
   - Existing tests: all golden files under `subquery/`, `SubquerySuite`, the 
catalyst `PullupCorrelatedPredicatesSuite`, `DecorrelateInnerQuerySuite` and 
`RewriteSubquerySuite`, and the TPC-DS and TPC-H plan stability suites with and 
without stats. The plan stability suites have no plan changes.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Kiro CLI 2.37.1 (Claude Opus 5.5)
   


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