dongjoon-hyun opened a new pull request, #60785:
URL: https://github.com/apache/spark/pull/60785

   ### What changes were proposed in this pull request?
   
   This PR fixes `ExtractEquiJoinKeys` so that an equality that can fail, such 
as an ANSI cast of a string compared with a column of the other side, is not a 
join key when it is written after a non-deterministic or throwable conjunct of 
the join condition, such as a `CASE WHEN` with `raise_error`.
   
   `ExtractEquiJoinKeys` takes every equality between the two sides of a join 
as a key, wherever it is in the condition. A hash join or a sort-merge join 
computes its keys on every row of its inputs, before the rest of its condition. 
So such an equality was evaluated also on the rows where a conjunct written 
before it is false, which the join removes without it.
   
   This PR takes the keys only from the conjuncts that may be evaluated ahead 
of the others, as `PredicateHelper.splitMovable` decides. `ReorderJoin` and 
`PushPredicateThroughJoin` use it for the same reason (#60649, #60646, #60725). 
These are the conjuncts before the first non-deterministic or throwable one, 
and, after it, the ones that can not fail. The other equalities stay in the 
other condition of the join, in their written order, so the join evaluates them 
only on the pairs of rows where the conjuncts before them hold. Only the 
condition decides it, not the columns of the join inputs that can fail 
(`failableOutput`), so that the keys stay the same when the inputs change, e.g. 
when AQE replaces them with query stages and plans the join again. 
`NormalizeFloatingNumbers` normalizes only the keys that it finds in the 
optimizer, so a `DOUBLE` key that appeared only then would not match `-0.0` 
with `0.0`.
   
   `PartitionPruning` looked for a pruning key in every equality of the join 
condition, and for the position of the other side of the equality among the 
join keys. It now looks only at the equalities that are join keys: a pruning 
filter evaluates the key ahead of the join too, and an equality that is not a 
key would have no position, which made the plan unresolved.
   
   | Join condition, with `g` a `CASE WHEN` with `raise_error` | Before | After 
|
   |---|---|---|
   | `g AND CAST(c1.s AS INT) = c3.z` | Hash or sort-merge join on `CAST(c1.s 
AS INT) = c3.z` | Nested loop join with the whole condition |
   | `c1.x = c3.w AND g AND CAST(c1.s AS INT) = c3.z` | Keys `c1.x = c3.w` and 
`CAST(c1.s AS INT) = c3.z` | Key `c1.x = c3.w`, other condition `g AND 
CAST(c1.s AS INT) = c3.z` |
   | `g AND CAST(c1.s AS INT) = c3.z AND c1.x = c3.w` | Keys `CAST(c1.s AS INT) 
= c3.z` and `c1.x = c3.w` | Key `c1.x = c3.w`, other condition `g AND CAST(c1.s 
AS INT) = c3.z` |
   | `CAST(c1.s AS INT) = c3.z AND g` | Key `CAST(c1.s AS INT) = c3.z` | 
Unchanged, as the equality is written first |
   
   All callers of `ExtractEquiJoinKeys` get the same keys: the physical join 
selection, also for streaming and AQE, `NormalizeFloatingNumbers`, 
`InjectRuntimeFilter`, dynamic partition pruning, `EliminateOuterJoin`, 
`ReusableBroadcastValueProjection`, and the statistics and distinct keys of a 
join. A join condition without a non-deterministic or throwable conjunct is not 
affected: then every equality between the two sides is a key, as before.
   
   ### Why are the changes needed?
   
   A query that should succeed fails. With ANSI mode, the default since Apache 
Spark 4.0.0, a cast of a string is enough.
   
   ```sql
   CREATE TABLE c1(x INT, s STRING) USING parquet;
   CREATE TABLE c3(z INT) USING parquet;
   INSERT INTO c1 VALUES (5, 'abc'), (1, '7');
   INSERT INTO c3 VALUES (7);
   
   -- Issue 1: It should return (1, 7), but fails with CAST_INVALID_INPUT.
   SELECT c1.x, c3.z FROM c1 JOIN c3 ON
     CASE WHEN c1.x > 3 THEN false WHEN c1.x >= 0 THEN true ELSE 
raise_error('k') END
     AND CAST(c1.s AS INT) = c3.z;
   
   -- Issue 2: It should return (1, 7) and (5, NULL), but fails with 
CAST_INVALID_INPUT.
   SELECT c1.x, c3.z FROM c1 LEFT JOIN c3 ON
     CASE WHEN c1.x > 3 THEN false WHEN c1.x >= 0 THEN true ELSE 
raise_error('k') END
     AND CAST(c1.s AS INT) = c3.z;
   ```
   
   The `CASE WHEN` is false on the row `(5, 'abc')`, so the cast, which fails 
on `'abc'`, should not run on it. Before this PR, the join of Issue 1 is 
planned with the cast as its key:
   
   ```
   BroadcastHashJoin [cast(s#27 as int)], [z#28], Inner, BuildRight, CASE WHEN 
(x#26 > 3) THEN false ...
   ```
   
   Issue 1 is a regression in the unreleased 4.4.0. On 
[v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) (2026-10-27) and 
the earlier releases, the `CASE WHEN` was also in a filter on `c1` below the 
join, which removed the row before the join computed its key. Up to 4.1, 
`PushPredicateThroughJoin` pushed it there, and on 4.2 and 4.3, which keep it 
in the join condition, `InferFiltersFromConstraints` copied it there. #60162 
(SPARK-60985) stopped inferring a filter that can fail, since such a filter is 
not in the query and can fail it too, so the join key became the first 
expression evaluated on the row. Issue 2 fails on the releases too, as no 
filter is inferred on the side that an outer join preserves.
   
   | Query | [v3.5.9](https://github.com/apache/spark/releases/tag/v3.5.9) 
(2026-07-12), [v4.0.5](https://github.com/apache/spark/releases/tag/v4.0.5) 
(2026-10-21), [v4.1.4](https://github.com/apache/spark/releases/tag/v4.1.4) 
(2026-10-21) | [v4.2.1](https://github.com/apache/spark/releases/tag/v4.2.1) 
(2026-10-21), [v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) 
(2026-10-27) | `master` | This PR |
   |---|---|---|---|---|
   | `JOIN` or `LEFT SEMI JOIN` with the `ON` condition of Issue 1, also with 
`<=>`, or with a key `c1.x = c3.w` before or after it | Returns | Returns | 
Fails | Returns |
   | `LEFT`, `RIGHT` or `FULL OUTER JOIN` or `LEFT ANTI JOIN` with that `ON` 
condition, or `NOT EXISTS` or `EXISTS (...) OR c1.x < 0` with it in the `WHERE` 
clause of the subquery | Fails | Fails | Fails | Returns |
   | `EXISTS` with it in the `WHERE` clause of the subquery | Returns | Fails | 
Fails | Returns |
   
   Each query gives the same result with a broadcast hash join, with a 
sort-merge join (`spark.sql.autoBroadcastJoinThreshold=-1`) and with the 
cost-based join reorder. On `master`, 
`spark.sql.legacy.inferFailableFiltersFromConstraints=true` makes the queries 
of the first row return.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes. The queries above return results instead of failing.
   
   A join whose condition has a non-deterministic or throwable conjunct 
followed by an equality that can fail is planned differently: as a nested loop 
join (`BroadcastNestedLoopJoin` or `CartesianProduct`) instead of a hash or 
sort-merge join if it has no other key, and on its other keys only otherwise. 
The check of whether an equality can fail 
(`ExprUtils.canEvaluateUnconditionally`) is conservative, so some equalities 
that can not fail are not keys there either, e.g. one over strings of a 
non-binary collation, which `RewriteCollationJoin` wraps in `CollationKey`. An 
equality over `FLOAT` or `DOUBLE` columns is still a key, as 
`NormalizeFloatingNumbers` moves the normalized keys to the front of the 
condition. Dynamic partition pruning is not applied on such an equality either. 
A join condition without a non-deterministic or throwable conjunct does not 
change, and no TPC-DS plan changes.
   
   An equality over a column that a projection below the join computes with an 
expression that can fail, e.g. `b.q = c3.z` over `SELECT x, CAST(s AS INT) AS q 
FROM c1`, is still a key, so that the keys do not depend on the inputs. Such a 
query still fails as before, also because `InferFiltersFromConstraints` adds 
`isnotnull(q)`, which is pushed below the projection.
   
   A stream-stream join of this kind no longer has such an equality among its 
keys. If it has no other key, it fails to start with `Stream-stream join 
without equality predicate is not supported`, instead of failing when the 
equality fails on a row that the conjunct before it removes. If it has other 
keys, the key schema of its state no longer includes the equality.
   
   ### How was this patch tested?
   
   Pass the CIs with the newly added test cases.
   
   - `ExtractEquiJoinKeysSuite` (new): for the condition 
`isnull(raise_error('boom')) AND CAST(s AS INT) = z AND a = z` with an ANSI 
cast, the only key is `a = z`, and the other condition is 
`isnull(raise_error('boom')) AND CAST(s AS INT) = z`. It fails without this PR.
   - `JoinSuite`: Issue 1 returns `(1, 7)`. It fails without this PR.
   - `JoinSuite`: with AQE converting a sort-merge join into a broadcast hash 
join, a join on `CASE WHEN ... raise_error ... AND b.q = CAST(c3.z AS DOUBLE) 
AND b.x = c3.w`, where `q` is a cast computed below the join, returns the row 
where `q` is `-0.0` and `c3.z` is `0`. It also passes without this PR, and 
fails if the keys depend on the columns of the inputs that can fail.
   - `DynamicPartitionPruningV1SuiteAEOff`/`AEOn`: a join with `CAST(f.p AS 
INT) = d.pi` on the partition column `p` after a `CASE WHEN` with `raise_error` 
returns its row, with no pruning filter. Without this PR, it gets a pruning 
filter on the cast. It fails with an unresolved plan if `PartitionPruning` 
scans the equalities that are not keys.
   
   I also ran the catalyst optimizer, planning, plans and statistics estimation 
suites, `*JoinSuite` in `sql/core`, the stream-stream join suites of 
`StreamingJoinSuite.scala`, `SubquerySuite`, `PlannerSuite`, 
`InjectRuntimeFilterSuite`, the `DynamicPartitionPruning*Suite`s, 
`AdaptiveQueryExecSuite`, `CollationSuite`, `DataFrameSuite` and the 
`PlanStabilitySuite`s locally. No golden files change. With a temporary suite 
(not included), the queries of the table above return the expected results on 
this PR with a broadcast hash join, a sort-merge join and the cost-based join 
reorder, and they and the stream-stream joins fail with `CAST_INVALID_INPUT` 
without it. A stream-stream join with the key `c1.x = c3.w` before the `CASE 
WHEN` returns the expected row on this PR.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: 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