sarutak commented on PR #60296:
URL: https://github.com/apache/spark/pull/60296#issuecomment-7063394171

   Thank you for the review, @dongjoon-hyun. Going through [31]-[35], I found 
that the wrong results of [31] and [32], and those of the earlier rounds about 
the outer input, came from the domain joins of `DecorrelateInnerQuery` 
computing the outer input again. So I changed the approach for the common 
shapes. `PullupCorrelatedPredicates` now computes, from the subquery before 
decorrelation, its result for an outer row without matching rows, e.g. `1` for 
`COUNT(*)` over `MAX(b.v)`, and stores it in a new field 
`ScalarSubquery.countBugResult`; `constructLeftJoins` uses it instead of 
`evalSubqueryOnZeroTups`, which sees only the decorrelated subquery. These 
subqueries keep the joins of `master`, and this adds no domain join. Where 
decorrelation adds none anyway, e.g. for an equality correlation directly over 
the input of the lower aggregate, they get the fix whatever the outer query is, 
also for a streaming query, a non-deterministic outer input and outer 
references that are not orderabl
 e, which kept the wrong result in 489ffd2. (Where `master` adds a domain join, 
e.g. for a non-equality correlation or a correlation below a `UNION ALL`, it 
stays; see the second paragraph from the end for how the computed result is 
used there.) Of the 57 queries in the golden file with such a subquery that run 
without the legacy conf, 38 take this path. In one more, `SUM(m) + (SELECT 
MAX(c2) FROM t3)` over `MAX(b2) AS m`, the result cannot be computed, but the 
top aggregate gives the same result over the row of `NULL`s as over no rows, so 
it keeps `constructLeftJoins`, as it did before this change of approach. The 
other 18, where the result cannot be computed while the query is optimized (a 
filter, a join, a `UNION ALL`, an `INTERSECT`, a `LIMIT` or a window function 
between the aggregates, `PERCENTILE`, a subquery in or between the aggregates, 
or a result or grouping key that fails), still use the domain joins, with the 
checks of the previous rounds, as does a result that needs a P
 ython UDF (see `SubquerySuite`). Every query that the golden file had before 
this change of approach returns the same result as before it. The description 
is updated.
   
   This computes the top aggregate over one row as the collapse of round 1 did, 
but it does not rewrite the plan, so [1]-[4], [6] and [8] of your first review 
do not come back: it computes only a literal for the count-bug branch, only for 
subqueries that `master` already handles in `constructLeftJoins` (not over a 
lower `COUNT`, so `MAX(10 / c)` of [2] does not reach it), without stripping a 
`Project` ([1]), and a value that is not a literal, such as a Python UDF ([4]) 
or a failing expression, goes to the domain joins where they work, and keeps 
the handling of before otherwise (see the inline replies). The `SubquerySuite` 
test with `ConvertToLocalRelation` ([3]) covers these subqueries too. The 
arguments are evaluated once while the query is optimized, so the copies of [8] 
do not matter, and there is no plan rewrite that [6] would put next to 
`OptimizeOneRowPlan`: the computation over one row stays in 
`RewriteCorrelatedScalarSubquery`, since it only gives the literal of the 
count-bug
  branch. This changes my answer to [5]: the computation over one row is now 
part of this fix, and of its backports, but only as that literal. So I no 
longer plan the separate PR for `master` with the collapse and the stripping of 
top `Project`s; what was left for it, fewer joins for subqueries that `master` 
already handles in `DecorrelateInnerQuery`, does not change any result.
   
   The new field changes the arity of `ScalarSubquery`, so code that matches it 
with all its fields needs one more `_`, as for `mayHaveCountBug` and 
`needSingleJoin` before. For the backports to `branch-4.3` through 
`branch-4.0`, I plan to add overloads of the constructor, `apply` and `copy` of 
`ScalarSubquery` and `DomainJoin` with their previous parameters, so that code 
compiled against an earlier patch release that constructs or copies them keeps 
working. If you would rather keep this PR smaller, the domain-join part could 
be dropped, leaving those 18 queries with the results of before; I kept it so 
that this PR fixes them all.
   
   I addressed [31]-[35] for the subqueries that still use the domain joins in 
ca6c763, ca69f13, 3a46c77, c68bd92 and 9047fd9, and in 218c886 for keys of 
user-defined types ([32]) and for checking each chain of reordered joins once 
([33]); the other commits after 9047fd9 change the approach and follow up on 
it; see the inline replies. As you agreed, the conf version stays `4.4.0` and 
the migration guide entry stays under 4.3 to 4.4.
   
   In a last check before pushing, I found two more cases where this PR made a 
result wrong that `master` gets right, which now keep the previous handling. 
The domain joins of change 2 keep one of the outer values that compare equal, 
e.g. `0.0` for `-0.0` and `0.0`, so a correlation that tells them apart, e.g. 
`b.s = CAST(o.d AS STRING)` with a filter between the aggregates, gave the 
result of `0.0` to `-0.0`, where `master` pulls that correlation up without 
domain joins; outer references of such types now keep the previous handling 
there too, as they already did for change 1 under a domain join of `master` 
where the computed result could differ from that of `master` (see the second 
paragraph from the end). And a user-defined aggregate function without a 
default result can return a value other than `NULL` on empty input, e.g. a 
Scala `Aggregator` with a zero of `0`, while changes 1 and 2 take `NULL` there 
for a correlated one; `master` evaluates the top aggregate over no rows instead
 , unless a function with a default result such as `COUNT` is next to it, which 
is right e.g. for `COUNT(*) FILTER (WHERE s IS NULL)` over it. A subquery with 
such a function in a lower aggregate without `GROUP BY`, correlated or not, now 
keeps the previous handling, as with the legacy conf, to be conservative. 
`SubquerySuite` checks both. A user-defined aggregate function over no rows is 
taken as `NULL` elsewhere on `master` too: with `sum0` such an `Aggregator`, 
`(SELECT sum0(b.v) FROM b WHERE b.k = a.k)` and its `LATERAL` form return 
`NULL` instead of `0` for an outer row without matching rows (measured with 
this PR, which does not change these shapes, and with the legacy conf). So I 
would like to look at that separately, for all these shapes, rather than only 
for the nested one here.
   
   For change 2, a correlation that compares such an outer reference directly, 
e.g. `b.d = o.d`, cannot tell the values apart, so the domain joins would be 
right there, but this PR checks only the type of the outer references. Taking 
those subqueries in would need a check of every place where the outer reference 
is used (expressions, aggregate arguments, `FILTER`s, nested subqueries, and 
where later rules move conditions), of the kind of [24] and [31]-[34], where a 
gap would silently give a wrong result. It would only extend the fix to 
subqueries of change 2 over a `DOUBLE` or a string of a non-binary collation: 
those of change 1 with an equality correlation get the fix without domain 
joins, and none of the 57 golden queries changes its path. So I would like to 
look at it separately, which keeps this PR and its backports as they are, and 
needs no change to the migration guide entry; if you prefer it here, I can add 
it to this PR.
   
   #60366 is merged, so I merged `master` again and added the Python UDF test I 
mentioned, with the failing UDF of #60366. Since that UDF returns `NULL` for 
`NULL`, the test makes the value over no rows `0` with `COALESCE(MAX(ri.d), 
0)`: `SUM(x)` over `inv(COALESCE(MAX(ri.d), 0)) AS x` now returns results when 
every outer row has matching rows, and fails with `ZeroDivisionError` only when 
an outer row has none, which computes `inv(0)`.
   
   I also found that with 
`spark.sql.optimizer.decorrelateInnerQuery.evalCountBugUdfConditionally.enabled`
 set to `false`, this PR made that query fail even when every outer row 
matches, since the UDF then runs on the value over no rows for every outer row; 
`master` returns results there. So a subquery that needs the domain joins and 
has a Python or external UDF in the value over no rows of a correlated 
aggregate without `GROUP BY` now keeps the previous handling when that conf is 
off, and the test checks both; one whose result is computed before 
decorrelation, such as a `COUNT(*)` over the UDF, gets the fix either way. This 
PR no longer waits for another PR; the description is updated accordingly.
   
   One question. Apart from user-defined aggregate functions over no rows (see 
above), the wrong results that remain here, as far as I know, come from the 
domain joins. (A) The subqueries of change 2 do not use the domain joins where 
they are known not to work: where the outer input may give other rows when 
computed again (e.g. a non-deterministic outer input, a `LIMIT` in it, or a 
`DataFrame` over an RDD), for a streaming query, where the domain joins fail, 
for outer references that are not orderable, where they fail too, and where 
outer values that compare equal but differ, such as `-0.0` and `0.0`, could get 
each other's result, since the domain joins keep one of them (see above). They 
keep the wrong result of before for outer rows without matching rows, as do 
subqueries with a Python or external UDF in a lower value over no rows when the 
conf of SPARK-61482 is off. (B) The domain joins that `master` adds itself, 
e.g. for a non-equality correlation, miss outer rows with matching r
 ows where the outer input gives other rows when computed again, also for a 
single aggregate: with a non-deterministic outer key `kk` over 1000 rows, 
`(SELECT MAX(b.v) FROM b WHERE b.k < o.kk)` and `(SELECT COUNT(*) FROM b WHERE 
b.k < o.kk)` returned a wrong result for about a third of the rows, on `master` 
and with this PR; `EXISTS` and an equality correlation were not affected. A 
`LIMIT` above that `LimitPushDown` pushes into the copy of the outer input 
could also make them miss rows, as you noted in [25], although I could not 
reproduce that locally. They also keep one of the outer values that compare 
equal, e.g. `0.0` for `-0.0` and `0.0`, so a correlation that tells them apart, 
e.g. over `CAST(o.d AS STRING)`, gets the result of the other value.
   
   For the subqueries of change 1 that keep such a domain join of `master`, the 
result computed before decorrelation is used as is where it is the result of 
every outer row, e.g. `1` for `COUNT(*)` over a `MAX`, which also gets the rows 
that the domain join misses right (none of 1000 wrong, instead of about a 
third), or where it is the same as that of `master`, e.g. `NULL` for `SUM` over 
a `MAX`. Otherwise an outer row that the domain join misses, or gives the 
result of another value, would get it instead of the result over no rows that 
`master` gives, which can make it wrong where `master` happens to be right: 
`COUNT(*) FILTER (WHERE s IS NULL)` over `MAX(b.v) AS s` with `b.k < o.kk` 
returned 1 for 336 of 1000 rows with matching rows in a first version, where 
`master` returned the correct 0, and with `-0.0` and `0.0` it moved the wrong 
result from one row to the other. So there, where the domain joins are known 
not to work or the outer references have a type whose equal values may d
 iffer, it is not used, which keeps the results of `master`, also the wrong 
ones for rows without matching rows; and otherwise a `LIMIT` above the subquery 
is not pushed into its domain joins, as for change 2. For these subqueries this 
changes what I wrote on Nov 18, since this PR could otherwise make them worse 
than `master`; such a query with a `LIMIT` can be slower than in 4.3.0. The 
alternative is not to use the computed result there at all, which keeps the 
plan of `master` and leaves those rows without matching rows wrong; I chose the 
fix, but can switch if you prefer the plan. All of this relies on the rule 
telling which inputs give the same rows again. It takes a `LogicalRDD` as one 
that may not, since an RDD of random values gave the same `FILTER` shape a 
wrong result for 384 of 1000 rows, where `master` returned none; this also 
covers a `DataFrame` from local data in classic PySpark and a checkpointed one, 
which keep the results of `master` where they need domain joins. A so
 urce outside Spark that gives other rows, e.g. over JDBC, or a cached plan 
whose evicted partitions give other rows, is not detected.
   
   (B) is a bug of `master` independent of this PR, so I would file a separate 
JIRA for it (I found no existing one). Fixing (A) and (B) for inputs that give 
other rows needs a decorrelation that does not compute the outer input again. 
Spark cannot guarantee that a plan is computed once and reused, so it would be 
e.g. one that joins the outer rows themselves, with a row ID, to the inner side 
and aggregates per outer row. That cannot aggregate the inner side first or 
deduplicate the outer values, so such queries could be much slower than in 
4.3.0, and it does not help a streaming outer query, which would need state per 
outer row. Would you prefer that in the separate JIRA, applied only to outer 
inputs that may give other rows, or leaving those cases as known limitations?
   


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