spark-test commented on code in PR #60764:
URL: https://github.com/apache/spark/pull/60764#discussion_r4650769232


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -641,14 +653,16 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val newJoinCond = joinCond ++ equalityCond
               (newFilter, newJoinCond, newOuterReferenceMap)
             } else {
-              // Results of this sub-tree is not aggregated, so all correlated 
predicates
-              // can be directly used as outer query join conditions.
-              val newOuterReferences = parentOuterReferences -- 
equivalences.keySet
+              // Results of this sub-tree is not aggregated, so all correlated 
predicates that are
+              // not kept in place can be directly used as outer query join 
conditions.
+              val newOuterReferences = parentOuterReferences ++
+                collectOuterReferences(keptInPlace) -- equivalences.keySet
               val (newChild, joinCond, outerReferenceMap) =
                 decorrelate(child, newOuterReferences, aggregated, underSetOp)
               // Add the outer references mapping collected from the equality 
conditions.
               val newOuterReferenceMap = outerReferenceMap ++ equivalences
-              val newFilter = uncorrelated match {
+              val newKeptInPlace = replaceOuterReferences(keptInPlace, 
newOuterReferenceMap)

Review Comment:
   **Blocking (P1):** This line rewrites the kept conjuncts through 
`newOuterReferenceMap`, which also holds the `equivalences` from equalities 
written after the kept prefix, and line 659 has already left those columns out 
of the domain. So for `CASE WHEN g < 0 THEN raise_error('negative g') ELSE g > 
0 END AND 1 / t1.k > 0 AND t2.k = t1.k` under ANSI mode, with t1 = (1) and t2 = 
(0, 1), the kept division becomes `1 / t2.k > 0` in `Filter(guard AND 1 / t2.k 
> 0, t2)` and runs on t2's row (0, 1) before `t2.k = t1.k` is checked. Reading 
the code, that raises DIVIDE_BY_ZERO, while written order computes only 1 / 1 
and the base branch returns no row. The aggregated branch (line 644) does the 
same, where the base branch pulled `1 / outer(k) > 0` up as a join condition. 
Because the swap replaces an outer value with an equal inner one, it also 
changes rows for values that are equal but distinguishable, such as UTF8_LCASE 
'A' and 'a' read by `ascii`, and a guard on an outer column, such as `C
 ASE WHEN t1.v < 0 THEN raise_error('negative v') ELSE true END AND t2.k = 
t1.v`, now runs on t2's values.
   
   **Recommended change:** In both branches of the Filter case, give every 
outer column that a kept conjunct reads a domain attribute instead of 
subtracting `equivalences.keySet` for it, and rewrite the kept conjuncts only 
through the domain mapping the child returns for those columns, never through 
`equivalences`. A correlated conjunct written after the kept prefix that reads 
one of those columns is rewritten to the domain attribute and placed in the 
filter after the kept prefix instead of becoming an outer join condition, so a 
cannot-fail equality there still becomes the domain join's key. When the child 
maps a kept column to an inner attribute because a filter below equates it, 
keep the base branch's handling for this filter, with a TODO naming that 
cross-operator case. Add optimizer and end-to-end correlated subquery tests in 
which an equality written after the guard equates a column that a kept conjunct 
reads.
   
   **Why this works:** Each kept conjunct then reads a domain attribute that 
the domain join's `<=>` condition binds to the outer row's own value, so it is 
evaluated in written order on the values it is paired with. The later equality 
compares the inner column with that domain attribute inside the filter, where 
PushPredicateThroughJoin still moves it into the domain join's condition 
because it cannot fail, so the plan keeps an equi-join key.
   
   **Compatibility:** Filters without a throwable or non-deterministic 
conjunct, and kept conjuncts whose outer columns no equality covers, 
decorrelate exactly as at the PR head.
   
   **Risks:** Columns that an equality used to cover now enter the domain, so 
the domain join of such filters gains a column and their plans change, although 
the rewritten equality keeps an equi-join key. Filters whose kept column is 
equated in a filter below keep the base branch's written-order failures, which 
the TODO marks.
   
   **Constraints:** The domain eligibility check for column types and streaming 
outer plans must run on the full set of kept columns this repair puts in the 
domain.
   
   **Exclusions:**
   - Conditions split across operators, where the equality sits in a filter 
below the kept conjunct, keep the base branch's handling with a TODO, as the PR 
description defers them.
   
   **Verification:**
   - **Regression:** Under ANSI mode, EXISTS and scalar-subquery queries with a 
raise_error guard, then a division by an outer column, then an equality on that 
column, run on data where an inner row with a zero key passes the guard, return 
the written-order result instead of DIVIDE_BY_ZERO.
   - **Regression:** An EXISTS query with a guard on an outer column followed 
by an equality on that column, over an inner row whose key would trip the 
guard, returns the outer row instead of raising USER_RAISED_EXCEPTION.
   - **Behavior:** A plan check shows that a kept conjunct reading an outer 
column that a later equality also equates reads a domain attribute, and that 
the later equality compares the inner column with that attribute inside the 
filter.
   - **Behavior:** A filter whose kept column is equated in a filter below 
decorrelates as on the base branch.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -561,7 +561,18 @@ object DecorrelateInnerQuery extends PredicateHelper {
         plan match {
           case Filter(condition, child) =>
             val conditions = splitConjunctivePredicates(condition)
-            val (correlated, uncorrelated) = 
conditions.partition(containsOuter)
+            // A conjunct used as a join condition with the outer query is 
evaluated after the
+            // filter, or ahead of it once pushed into the outer query, and 
the conjuncts left in
+            // the filter are reordered. So the ones written up to the last 
one that may not be
+            // evaluated ahead of the others (see `splitMovable`, taking an 
outer reference as a
+            // column, which can not fail) stay first in the filter, in their 
written order, with
+            // their outer references replaced.
+            val (keptInPlace, rest) = {
+              val stayUp = splitMovable(conditions.map(stripOuterReference), 
Seq(child))._2.toSet
+              conditions.splitAt(
+                conditions.lastIndexWhere(cond => 
stayUp.contains(stripOuterReference(cond))) + 1)

Review Comment:
   **Blocking (P1):** Under ANSI mode `CAST(t2.s AS INT)` can fail, so for 
`EXISTS (SELECT 1 FROM t2 WHERE CASE WHEN g < 0 THEN raise_error('negative g') 
ELSE true END AND CAST(t2.s AS INT) = t1.k)` the boundary computed here keeps 
the cast equality in the prefix, k gets a domain, and the subquery becomes 
`Filter(guard AND CAST(s AS INT) = k', Join(Aggregate([k], t1), t2, Inner, 
None))`. PushPredicateThroughJoin keeps both conjuncts above that join, since 
the cast can fail after the guard (Optimizer.scala lines 3433-3466), so the 
join has no key and JoinSelection plans a BroadcastNestedLoopJoin or a 
CartesianProduct over NDV(t1.k) x |t2| pairs, after a second pass over t1 for 
the domain. The base branch planned a hash or sort-merge semi join on 
`CAST(t2.s AS INT) = t1.k` over `Filter(guard, t2)`, which already computed the 
cast only on rows the guard kept. This applies when such an equality is the 
last conjunct that may not move and no other kept conjunct reads an outer 
column; when 
 another kept conjunct does, the base branch evaluated that one out of written 
order, so the domain join there is the fix's own cost.
   
   **Recommended change:** When choosing the kept prefix, leave out its last 
conjunct when that conjunct is a deterministic correlated conjunct that is not 
throwable, reads inner columns, and has parts over outer columns alone that 
cannot fail, and end the prefix at the last conjunct before it that may not 
move. The conjuncts after that point join the ones written after the kept 
prefix, which the non-aggregated branch uses as outer join conditions, 
evaluated after the filter as on the base branch, and which the aggregated 
branch handles as it does today. Take out only that one conjunct: a second 
failable one would become a join key computed on rows the first rejects, and a 
throwable one under an Aggregate would be rewritten through the equalities 
written before it and run on rows they remove. Add an optimizer test, under 
ANSI mode, of an EXISTS subquery with a guard followed by `CAST(t2.s AS INT) = 
t1.k`.
   
   **Why this works:** Such a conjunct needs no domain: the outer join computes 
it on the subquery's output rows, which have already passed the kept conjuncts, 
and its outer side cannot fail, so using it as an outer join condition keeps 
the written order and restores the base branch's equi-join key. Every conjunct 
written before it stays in the filter, so the outer join evaluates it only on 
rows those conjuncts keep.
   
   **Compatibility:** Every kept conjunct except that last one stays in place 
in written order, and a throwable or non-deterministic conjunct never leaves 
the kept prefix.
   
   **Risks:** Only the last conjunct that may not move leaves the prefix. When 
a second failable correlated equality comes before it, or another kept conjunct 
reads an outer column, the domain stays and its join can still lack an 
equi-join key; the base branch evaluated that other conjunct out of written 
order, so that cost belongs to the fix itself.
   
   **Constraints:** A conjunct that leaves the prefix must read an inner 
column, so that it cannot be pushed into the outer plan.
   
   **Verification:**
   - **Regression:** A plan check under ANSI mode of an EXISTS subquery with a 
raise_error guard followed by a failable correlated equality shows no 
DomainJoin and the equality as an outer join condition.
   - **Behavior:** That query returns the same rows end to end as on the base 
branch.
   - **Regression:** Under ANSI mode, an EXISTS subquery with a raise_error 
guard followed by `CAST(t2.s AS INT) = t1.k AND t2.v + 1 = t1.v`, over an inner 
row whose cast matches no outer row and whose `t2.v + 1` overflows, returns the 
written-order rows instead of raising ARITHMETIC_OVERFLOW.
   - **Regression:** A plan check of a scalar subquery whose raise_error guard 
reads an inner and an outer column, written after a correlated equality on that 
outer column, keeps the guard in the filter over the domain join.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -561,7 +561,18 @@ object DecorrelateInnerQuery extends PredicateHelper {
         plan match {
           case Filter(condition, child) =>
             val conditions = splitConjunctivePredicates(condition)
-            val (correlated, uncorrelated) = 
conditions.partition(containsOuter)
+            // A conjunct used as a join condition with the outer query is 
evaluated after the
+            // filter, or ahead of it once pushed into the outer query, and 
the conjuncts left in
+            // the filter are reordered. So the ones written up to the last 
one that may not be
+            // evaluated ahead of the others (see `splitMovable`, taking an 
outer reference as a
+            // column, which can not fail) stay first in the filter, in their 
written order, with
+            // their outer references replaced.
+            val (keptInPlace, rest) = {
+              val stayUp = splitMovable(conditions.map(stripOuterReference), 
Seq(child))._2.toSet

Review Comment:
   **Non-blocking (P2):** Here the outer references are stripped to plain 
columns and only `Seq(child)` is passed, so splitMovable never sees that the 
outer plan computes a column with an expression that can fail. Take the PR's 
own test with the division moved into a derived table: `SELECT * FROM (SELECT 
k, 1 / v AS r FROM t1) o WHERE EXISTS (SELECT 1 FROM t2 WHERE t2.k = o.k AND 
CASE WHEN g < 0 THEN raise_error('negative g') ELSE g > 0 END AND o.r > 0)` 
under ANSI mode. `outer(r) > 0` stays movable, becomes a semi join condition 
and is pushed into o, where by the code `1 / v` raises DIVIDE_BY_ZERO on (1, 0) 
just as on the base branch, although the guard removes the only matching t2 
row. The comment's claim that an outer reference 'can not fail' hides this. A 
domain over r would also compute `1 / v` for every outer row, so covering these 
inputs needs the conjuncts that read them kept out of the outer plan; until 
then, a TODO should name them.
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala:
##########
@@ -3777,4 +3777,24 @@ class SubquerySuite extends SharedSparkSession
       }
     }
   }
+
+  test("SPARK-62142: keep the written order of a throwable condition in a 
correlated subquery") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      withTable("t1", "t2") {
+        sql("CREATE TABLE t1 (k INT, v INT) USING parquet")
+        sql("INSERT INTO t1 VALUES (1, 0)")
+        sql("CREATE TABLE t2 (k INT, g INT) USING parquet")
+        sql("INSERT INTO t2 VALUES (1, 0), (2, 1)")

Review Comment:
   **Nit (P3):** With t2 = (1, 0), (2, 1) no row has g < 0, so `raise_error` 
never runs and both queries below expect no row. A regression that evaluates 
the guard on rows the earlier equality removes, or a domain-join rewrite that 
loses rows, would still pass. The PR's issue-2 query, with a t2 row such as (3, 
-1) that no t1 row matches and an expected answer of (1, 0), plus a guarded 
case with a non-empty answer, would give this change a failure signal; the 
DecorrelateInnerQuerySuite case cannot, because comparePlans sorts filter 
conjuncts by hashCode.
   
   **Verification:**
   - **Regression:** The issue-2 EXISTS query, with t2 also holding (3, -1), 
returns (1, 0) end to end; the base branch fails it with USER_RAISED_EXCEPTION, 
so the case catches a regression of that order.
   - **Behavior:** A guarded correlated subquery whose answer is non-empty 
returns the written-order rows through the new domain join.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -641,14 +653,16 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val newJoinCond = joinCond ++ equalityCond
               (newFilter, newJoinCond, newOuterReferenceMap)
             } else {
-              // Results of this sub-tree is not aggregated, so all correlated 
predicates
-              // can be directly used as outer query join conditions.
-              val newOuterReferences = parentOuterReferences -- 
equivalences.keySet
+              // Results of this sub-tree is not aggregated, so all correlated 
predicates that are
+              // not kept in place can be directly used as outer query join 
conditions.
+              val newOuterReferences = parentOuterReferences ++
+                collectOuterReferences(keptInPlace) -- equivalences.keySet
               val (newChild, joinCond, outerReferenceMap) =
                 decorrelate(child, newOuterReferences, aggregated, underSetOp)
               // Add the outer references mapping collected from the equality 
conditions.
               val newOuterReferenceMap = outerReferenceMap ++ equivalences
-              val newFilter = uncorrelated match {
+              val newKeptInPlace = replaceOuterReferences(keptInPlace, 
newOuterReferenceMap)
+              val newFilter = (newKeptInPlace ++ uncorrelated) match {

Review Comment:
   **Non-blocking (P2):** Here every uncorrelated conjunct goes into the filter 
above the new DomainJoin placeholder, including ones splitMovable lets move, 
such as `t2.dt = '2026-11-01'` in `EXISTS (SELECT 1 FROM cat.t2 WHERE t2.dt = 
'2026-11-01' AND t2.k = t1.k AND CASE WHEN t2.g < 0 THEN raise_error('negative 
g') ELSE true END)`. OptimizeSubqueries runs the whole optimizer on the 
subquery while the placeholder is still there, V2ScanRelationPushDown pushes 
only a Filter directly over the scan builder (V2ScanRelationPushDown.scala 
lines 115-117), and a filter cannot be pushed through a DomainJoin 
(Optimizer.scala lines 3006-3024). So for a DSv2 table partitioned by dt the 
scan is built with no pushed filters and reads every partition, where the base 
branch pushed `dt = '2026-11-01'` to the source; the placeholder becomes a join 
only in the later RewriteSubquery batch, too late for push-down. DSv1 file 
sources still prune at physical planning.
   
   **Verification:**
   - **Behavior:** A plan check shows that cannot-fail uncorrelated predicates 
written before the guard, between the guard and a later conjunct that may not 
move, and after the kept prefix end up in a Filter directly over the relation 
below the DomainJoin, while the kept correlated conjuncts and the conjuncts 
that may not move stay above it in written order.
   - **Regression:** A guarded correlated EXISTS over a DSv2 catalog table with 
a pushable predicate shows that predicate among the scan's pushed filters.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -641,14 +653,16 @@ object DecorrelateInnerQuery extends PredicateHelper {
               val newJoinCond = joinCond ++ equalityCond
               (newFilter, newJoinCond, newOuterReferenceMap)
             } else {
-              // Results of this sub-tree is not aggregated, so all correlated 
predicates
-              // can be directly used as outer query join conditions.
-              val newOuterReferences = parentOuterReferences -- 
equivalences.keySet
+              // Results of this sub-tree is not aggregated, so all correlated 
predicates that are
+              // not kept in place can be directly used as outer query join 
conditions.
+              val newOuterReferences = parentOuterReferences ++

Review Comment:
   **Blocking (P1):** Adding `collectOuterReferences(keptInPlace)` here puts 
every outer column a kept conjunct reads into the domain, and the domain join's 
`m' <=> outer(m)` does not resolve when that column's type is not orderable, so 
`decorrelate` throws UNSUPPORTED_CORRELATED_REFERENCE_DATA_TYPE (lines 
541-551). For example, with t1(id INT, m MAP<STRING, INT>), `SELECT id FROM t1 
WHERE EXISTS (SELECT 1 FROM t2 WHERE map_contains_key(t1.m, t2.s) AND CASE WHEN 
g < 0 THEN raise_error('negative g') ELSE true END)` now fails at planning for 
every input, where the base branch used `map_contains_key(t1.m, t2.s)` as the 
semi join's condition and returned the row. The same applies to VARIANT, 
GEOMETRY, GEOGRAPHY and calendar-interval columns, to structs or arrays holding 
them, and to a non-deterministic conjunct such as `rand() < 0.5` in place of 
the guard; PullOutNestedDataOuterRefExpressions rescues only a map lookup 
`t1.m[key]` whose key reads no inner column.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -561,7 +561,18 @@ object DecorrelateInnerQuery extends PredicateHelper {
         plan match {
           case Filter(condition, child) =>
             val conditions = splitConjunctivePredicates(condition)
-            val (correlated, uncorrelated) = 
conditions.partition(containsOuter)
+            // A conjunct used as a join condition with the outer query is 
evaluated after the
+            // filter, or ahead of it once pushed into the outer query, and 
the conjuncts left in
+            // the filter are reordered. So the ones written up to the last 
one that may not be
+            // evaluated ahead of the others (see `splitMovable`, taking an 
outer reference as a
+            // column, which can not fail) stay first in the filter, in their 
written order, with
+            // their outer references replaced.
+            val (keptInPlace, rest) = {

Review Comment:
   **Non-blocking (P2):** This split fixes the written order for a filter, but 
the Join case of the same rule (lines 1012-1090) still partitions a correlated 
ON condition with `containsOuter`, pulls an inner join's correlated equalities 
up as join conditions with the outer query, and rebuilds the condition as 
`newCorrelated ++ uncorrelated`. With t1(k) = (1), t2(k, id) = (2, 1) and 
t3(id, g) = (1, -1), `SELECT * FROM t1 WHERE EXISTS (SELECT 1 FROM t2 JOIN t3 
ON t2.k = t1.k AND CASE WHEN t3.g < 0 THEN raise_error('negative g') ELSE true 
END AND t2.id = t3.id)` should return no row, but by the code the inner join 
evaluates the guard on the pair that `t2.id = t3.id` matches and raises, while 
the same conditions in a WHERE clause now return no row. For the other join 
types the correlated conjuncts stay in the condition but are still placed 
first, so in `t2 LEFT JOIN t3 ON t2.id = t3.id AND <guard> AND 1 / t1.v > 0` 
the division runs ahead of the guard. The PR description defers condition
 s split across operators, but an ON condition belongs to one operator.
   
   **Recommended change:** In the Join case, when an inner join's condition has 
a correlated conjunct and a throwable or non-deterministic one, decorrelate it 
as a Filter holding that condition over the same join without a condition, so 
the Filter case's kept prefix, and the checks the other repairs add to it, 
apply. For the other join types, rebuild the condition in its written order, 
with outer references replaced, instead of putting the correlated conjuncts 
first. Add optimizer and end-to-end correlated subquery tests with a guard in 
an ON clause after a correlated equality.
   
   **Why this works:** For an inner join, the ON condition and a filter over 
the join without it return the same rows, so routing it through the Filter case 
keeps the guard after the correlated conjuncts written before it and the 
failable ones after it. For the other joins, the rebuilt condition in written 
order keeps a failable conjunct behind the guard.
   
   **Compatibility:** Joins whose ON condition has no throwable or 
non-deterministic conjunct decorrelate as at the PR head.
   
   **Risks:** Inner joins whose correlated condition keeps a prefix get a 
domain over the whole join instead of pulled-up equalities, so their plans 
change and pay a domain join, the same cost as filters. Non-inner joins whose 
correlated condition was reordered get their conditions in written order, which 
changes those join conditions' plans.
   
   **Constraints:** The conversion applies only when the condition would keep a 
prefix in place, so inner joins without a throwable or non-deterministic 
conjunct keep the Join case's current plan.
   
   **Verification:**
   - **Regression:** The ON-clause query above returns no row instead of 
raising USER_RAISED_EXCEPTION, and the same conditions written in a WHERE 
clause return the same result.
   - **Behavior:** A plan check of a left outer join inside a subquery, with a 
guard before a correlated conjunct that can fail, keeps their written order in 
the join condition.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -561,7 +561,18 @@ object DecorrelateInnerQuery extends PredicateHelper {
         plan match {
           case Filter(condition, child) =>
             val conditions = splitConjunctivePredicates(condition)
-            val (correlated, uncorrelated) = 
conditions.partition(containsOuter)
+            // A conjunct used as a join condition with the outer query is 
evaluated after the

Review Comment:
   **Nit (P3):** The description defers conditions split across operators of a 
subquery, but this comment explains only the kept prefix, and the 
`splitMovable` call below never passes `afterBarrier`. So a guard in a filter 
above another filter that holds the correlated equality, as two `where` calls 
in the DataFrame API produce, still runs on rows the equality removes, and a 
throwable condition in a join below is not seen either, with nothing in the 
code saying so. A TODO here naming these deferred cases would keep a later 
change from assuming that the written order already holds across operators.
   
   See **Shared repair plan 2** in the review body.



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