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

   ### What changes were proposed in this pull request?
   
   `DecorrelateInnerQuery` handles the COUNT bug of a correlated `Aggregate` 
without `GROUP BY` in a `LATERAL` subquery, in a scalar subquery whose top 
`Aggregate` is over such an `Aggregate` (SPARK-45507), and in `EXISTS` and `IN` 
subqueries. It groups the `Aggregate` by the correlated columns, joins it to 
the distinct values of those columns with a left outer join, and replaces each 
output column `col` whose result over zero rows is not `NULL` with 
`if(isnull(alwaysTrue), <col over zero rows>, col)`. It computes `<col over 
zero rows>` with `RewriteCorrelatedScalarSubquery.evalAggregateOnZeroTups`, 
which replaces each aggregate function with its result on empty input and folds 
the whole expression of the column while the query is optimized.
   
   This PR makes it evaluate only the aggregate functions on zero rows. For a 
column that is an expression over aggregate functions, such as `10 / COUNT(*)`, 
the `Aggregate` now outputs each aggregate function as a column of its own, and 
the `Project` above the left outer join computes the expression, referring to 
`if(isnull(alwaysTrue), <function over zero rows>, <function>)` for each 
aggregate function whose result over zero rows is not `NULL` and to the 
function directly otherwise. A column that is a single aggregate function, a 
literal or an attribute keeps its current plan.
   
   ### Why are the changes needed?
   
   Folding the whole expression while the query is optimized goes wrong in two 
ways:
   
   - If the expression fails on the values over zero rows, the query fails 
while it is optimized, even when every outer row has matching rows. With `a(k) 
= (1), (2)` and `b(k, v) = (1, 100), (1, 200), (2, 300)` in ANSI mode:
   
     ```sql
     SELECT a.k, t.d FROM a, LATERAL (SELECT 10 / COUNT(*) d FROM b WHERE b.k = 
a.k) t;
     -- [DIVIDE_BY_ZERO] Division by zero.
     -- expected: (1, 5.0), (2, 10.0)
     ```
   
     The same happens with `SUM(d)` over `10 / COUNT(*) AS d` in a scalar 
subquery, `EXISTS (SELECT 10 / COUNT(*) ...)` and `5 IN (SELECT 10 / COUNT(*) 
...)`. All four fail on Spark 4.0.0. The `LATERAL` case also fails on 3.2.0 
through 3.5 (it has used `DecorrelateInnerQuery` since SPARK-35551); the other 
three do not fail before 4.0.0, so they are regressions from SPARK-45507 and 
the `EXISTS`/`IN` decorrelation.
   - If the expression cannot be folded, such as a Python UDF, it stays in the 
`if` and runs at runtime. Python UDFs in a conditional branch are evaluated for 
every row, so it runs on the values over zero rows for every outer row, also 
for the rows with matching rows. With `inv = udf(lambda x: 100 // x)`, `SELECT 
a.k, t.d FROM a, LATERAL (SELECT inv(COUNT(*)) d FROM b WHERE b.k = a.k) t` 
fails with `ZeroDivisionError` with the tables above, where every outer row has 
matching rows.
   
   With this PR, these queries return `(1, 5.0), (2, 10.0)` and `(1, 50), (2, 
100)`, which are the results of the same queries without correlation (`b.k = 1` 
and `b.k = 2`).
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes. The queries above, and others of the same shapes (a `LATERAL` subquery, 
a scalar subquery whose top `Aggregate` is over the lower one, or an `EXISTS` 
or `IN` subquery) whose lower `Aggregate` without `GROUP BY` computes an 
expression that fails on its values over zero rows, no longer fail when every 
outer row has matching rows. For an outer row without matching rows, the 
expression is now evaluated at runtime on the values over zero rows, as for any 
other row, so such a query can fail at runtime instead of while it is 
optimized, e.g. the `LATERAL` query above with `a(k) = (1), (3)`. A subquery 
that does not use the value, such as the `EXISTS` subquery, does not fail. A 
query whose expression does not fail returns the same results as before.
   
   Queries whose subquery does not have a column that is an expression over 
aggregate functions in a correlated `Aggregate` without `GROUP BY` whose COUNT 
bug `DecorrelateInnerQuery` handles keep their plans. A column that is a single 
aggregate function, a literal or an attribute keeps its plan; any other column 
gets a new plan even when it does not fail, with the same result, because the 
expression moves from the `Aggregate` to the `Project` above the join. This 
includes an expression over aggregate functions, e.g. `COALESCE(MAX(b.v), 7) + 
COUNT(*)`, and a constant expression that is not yet a literal at this point, 
e.g. `CAST(5 AS BIGINT)`.
   
   This PR does not change a correlated scalar subquery whose COUNT bug 
`RewriteCorrelatedScalarSubquery.constructLeftJoins` handles, e.g. one whose 
only `Aggregate` is the top one: in ANSI mode, `(SELECT 10 / COUNT(*) FROM b 
WHERE b.k = a.k)` still fails while it is optimized, and SPARK-61444 covers 
that. `constructLeftJoins` also folds the result over zero rows of a subquery 
whose COUNT bug `DecorrelateInnerQuery` has handled, so a failing expression 
that `constructLeftJoins` reaches still fails while it is optimized: `10 / 
COUNT(*)` as the subquery result over a lower `Aggregate` (a `Project` between 
them, no top `Aggregate`), or `10 / COUNT(*)` over a top `COUNT(*)`.
   
   ### How was this patch tested?
   
   - Three new tests in `DecorrelateInnerQuerySuite`. The first checks the plan 
for expressions over aggregate functions (one aggregate function used twice, as 
two separate `count(1)` so the deduplication by canonical form is exercised, 
and one whose result over zero rows is `NULL`), single aggregate functions 
whose results over zero rows are and are not `NULL`, and a literal. The second 
checks that a non-deterministic aggregate function used twice keeps one 
`Aggregate` output per use and that the expression refers to both, as 
`PhysicalAggregation` does not deduplicate them (this shape does not pass 
analysis, so the test only pins the defensive behavior). The third checks that 
an aggregate function inside a Python UDF is pulled out of the UDF into the 
`Aggregate` and corrected for zero rows, so the test does not need Python.
   - Two new tests in `SubquerySuite` run, in ANSI mode, `10 / COUNT(*)` in a 
scalar subquery over a lower `Aggregate`, in a `LATERAL` subquery, and in 
`EXISTS` and `IN` subqueries, all with outer rows that have matching rows 
(these fail without the change); the scalar subquery with an outer row without 
matching rows, which is optimized without an error and fails only when it runs 
(it fails while it is optimized without the change); the `EXISTS` subquery over 
rows without matching rows, which does not fail; expressions over `COUNT` and 
`MAX` with outer rows without matching rows, which pin the results over zero 
rows; and a Python UDF over `10 / COUNT(*)` (which fails without the change 
through the ANSI division of its argument) and over `COUNT(*)`.
   - A mutation check on this commit: each of ten mutants, such as folding the 
whole expression as before (for all expressions, or only those with or without 
a Python UDF), dropping the result over zero rows of the new columns, taking 
`NULL` for it, deduplicating a non-deterministic aggregate function, or 
changing the plan of a single aggregate function or a literal, makes at least 
one of the tests above fail. A mutant that does not move an attribute outside 
aggregate functions to the `Aggregate` survives: the analyzer rejects such a 
column in a correlated subquery, so no query reaches it.
   - Existing tests: all golden files under `subquery/` and `join-lateral.sql`, 
`SubquerySuite`, `LateralColumnAliasSuite`, the catalyst 
`DecorrelateInnerQuerySuite`, `PullupCorrelatedPredicatesSuite` and 
`RewriteSubquerySuite`, and the TPC-DS and TPC-H plan stability suites, which 
have no plan changes.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Kiro CLI 3.1.0 (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