This is an automated email from the ASF dual-hosted git repository.

dongjoon-hyun pushed a commit to branch branch-4.1
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.1 by this push:
     new 1781be7fd6f1 [SPARK-61254][SQL] Fix wrong results by stale LogicalRDD 
constraints in checkpoints and recursive CTEs
1781be7fd6f1 is described below

commit 1781be7fd6f1601c8ce51e8791210c55baa8d2d6
Author: Dongjoon Hyun <[email protected]>
AuthorDate: Mon Nov 9 15:03:49 2026 -0800

    [SPARK-61254][SQL] Fix wrong results by stale LogicalRDD constraints in 
checkpoints and recursive CTEs
    
    ### What changes were proposed in this pull request?
    
    This PR aims to fix a correctness issue where `LogicalRDD` keeps a 
constraint of its source plan on the source plan's exprId instead of moving it 
onto its own output.
    
    `LogicalRDD.buildOutputAssocForRewrite` and 
`buildOutputAssocForRewriteWithNewOutput` now return an `AttributeMap`, which 
is keyed by exprId, instead of a `Map` keyed by full `AttributeReference` 
equality. The positional name and type checks and the size check stay 
unchanged, so the same outputs are accepted or rejected as before. Only the 
lookup in `rewriteStatistics` and `rewriteConstraints` changes.
    
    `rewriteStatsAndConstraints` uses these helpers in two places.
    - `LogicalRDD.fromDataset`, which builds `Dataset.checkpoint`, 
`Dataset.localCheckpoint` and the input of the `foreachBatch` sink.
    - `UnionLoopExec`, which builds the input of every recursive CTE iteration.
    
    ### Why are the changes needed?
    
    This is a correctness issue. The helpers pair the optimized output with the 
`LogicalRDD` output by position, but the lookup compares full attributes, 
including the qualifier and the nullability. When the optimizer changes the 
root exprIds, for example when `RemoveRedundantAliases` removes a same-name 
root alias, a constraint attribute that differs from the optimized output only 
in qualifier misses the map and keeps the exprId of the source plan.
    
    ```scala
    val df = spark.range(16).as("t").where($"t.id" > 5)
    val cp = df.select($"id".as("id")).localCheckpoint()
    // Optimized output: id#0, constraint: t.id#0 > 5, checkpoint output: id#1
    // `Map(id#0 -> id#1)` misses `t.id#0`, so `cp` keeps the constraint on the 
column of `df`.
    ```
    
    **Issue 1: A join of a checkpoint with its source returns wrong results.** 
`EliminateOuterJoin` reads the stale constraint as a null filter on the left 
side and turns the RIGHT OUTER JOIN into an INNER JOIN.
    
    ```scala
    // Issue 1: It should return 10, but returns 9 because the row (null, 15) 
is dropped.
    scala> df.join(cp, df("id") === cp("id") + 1, "right_outer").where(cp("id") 
> 0).count()
    res0: Long = 9
    ```
    
    **Issue 2: A recursive CTE fails.** The constraint `t.lvl < 5` of an 
iteration keeps the exprId of `lvl + 1 AS lvl`, so the next iteration sees it 
as a constraint of its own new `lvl` column, and `PruneFilters` removes the 
filter that stops the recursion. This is the symptom that SPARK-52353 fixed, in 
a case that its fix does not cover.
    
    ```sql
    -- Issue 2: It should return [1000, 4], but fails with 
RECURSION_LEVEL_LIMIT_EXCEEDED.
    WITH RECURSIVE r(k, lvl) AS (
      SELECT id AS k, 0 AS lvl FROM range(200)
      UNION ALL
      SELECT * FROM (SELECT k, lvl + 1 AS lvl FROM r LIMIT 100000) t WHERE 
t.lvl < 5)
    SELECT count(*), max(lvl) FROM r
    ```
    
    Column stats go through the same lookup, so they are keyed by exprId as 
well.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, this fixes wrong results and a query failure. With the default 
configurations, both issues above are reproduced on Apache Spark 4.0.4 (Issue 1 
only, because it has no recursive CTE), 4.1.3, 4.2.0 and 4.3.0. The checkpoint 
path has used this lookup since 
[v3.4.0](https://github.com/apache/spark/releases/tag/v3.4.0) (2023-04-07), and 
the recursive CTE path since 
[v4.1.0](https://github.com/apache/spark/releases/tag/v4.1.0) (2025-12-11).
    
    ### How was this patch tested?
    
    Pass the CIs with the newly added test cases.
    - `DataFrameSuite`: a join of a checkpoint with its source 
(`LogicalRDD.fromDataset`).
    - `cte-recursion.sql`: a recursive CTE whose filter on a subquery alias 
stays on top of the recursion (`UnionLoopExec`).
    
    Without the change in `buildOutputAssocForRewrite`, the `DataFrameSuite` 
test fails. Without the change in `buildOutputAssocForRewriteWithNewOutput`, 
the `cte-recursion.sql` test fails.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    Closes #60245 from dongjoon-hyun/SPARK-61254.
    
    Authored-by: Dongjoon Hyun <[email protected]>
    Signed-off-by: Dongjoon Hyun <[email protected]>
    
    (cherry picked from commit 1f563ab71ccb031a26d9f498e806196050d7cd84)
    Signed-off-by: Dongjoon Hyun <[email protected]>
---
 .../apache/spark/sql/execution/ExistingRDD.scala   |  7 ++++--
 .../analyzer-results/cte-recursion.sql.out         | 29 ++++++++++++++++++++++
 .../resources/sql-tests/inputs/cte-recursion.sql   |  8 ++++++
 .../sql-tests/results/cte-recursion.sql.out        | 13 ++++++++++
 .../org/apache/spark/sql/DataFrameSuite.scala      | 10 ++++++++
 5 files changed, 65 insertions(+), 2 deletions(-)

diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala
index d28ad0069b19..c9466255ce4d 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala
@@ -225,7 +225,9 @@ object LogicalRDD extends Logging {
     }.toMap
 
     if (rewrite.size == source.size) {
-      Some(rewrite)
+      // Keyed by exprId, because the attributes in the stats and the 
constraints can differ from
+      // `source` in qualifier or nullability.
+      Some(AttributeMap(rewrite))
     } else {
       None
     }
@@ -246,7 +248,8 @@ object LogicalRDD extends Logging {
     }.toMap
 
     if (rewrite.size == source.size) {
-      Some(rewrite)
+      // Keyed by exprId, for the same reason as in 
`buildOutputAssocForRewrite`.
+      Some(AttributeMap(rewrite))
     } else {
       None
     }
diff --git 
a/sql/core/src/test/resources/sql-tests/analyzer-results/cte-recursion.sql.out 
b/sql/core/src/test/resources/sql-tests/analyzer-results/cte-recursion.sql.out
index ae0de444ed5e..13dcebb21d3c 100644
--- 
a/sql/core/src/test/resources/sql-tests/analyzer-results/cte-recursion.sql.out
+++ 
b/sql/core/src/test/resources/sql-tests/analyzer-results/cte-recursion.sql.out
@@ -1782,6 +1782,35 @@ WithCTE
       +- CTERelationRef xxxx, true, [x#x, y#x], false, false
 
 
+-- !query
+WITH RECURSIVE r(k, lvl) AS (
+    SELECT id, 0 FROM range(5)
+    UNION ALL
+    SELECT * FROM (SELECT k, lvl + 1 AS lvl FROM r LIMIT 100) t WHERE t.lvl < 3
+)
+SELECT count(*), max(lvl) FROM r
+-- !query analysis
+WithCTE
+:- CTERelationDef xxxx, false
+:  +- SubqueryAlias r
+:     +- Project [id#xL AS k#xL, 0#x AS lvl#x]
+:        +- UnionLoop xxxx
+:           :- Project [id#xL, 0 AS 0#x]
+:           :  +- Range (0, 5, step=1)
+:           +- Project [k#xL, lvl#x]
+:              +- Filter (lvl#x < 3)
+:                 +- SubqueryAlias t
+:                    +- GlobalLimit 100
+:                       +- LocalLimit 100
+:                          +- Project [k#xL, (lvl#x + 1) AS lvl#x]
+:                             +- SubqueryAlias r
+:                                +- Project [id#xL AS k#xL, 0#x AS lvl#x]
+:                                   +- UnionLoopRef xxxx, [id#xL, 0#x], false
++- Aggregate [count(1) AS count(1)#xL, max(lvl#x) AS max(lvl)#x]
+   +- SubqueryAlias r
+      +- CTERelationRef xxxx, true, [k#xL, lvl#x], false, false
+
+
 -- !query
 SET spark.sql.cteRecursionAnchorRowsLimitToConvertToLocalRelation=100
 -- !query analysis
diff --git a/sql/core/src/test/resources/sql-tests/inputs/cte-recursion.sql 
b/sql/core/src/test/resources/sql-tests/inputs/cte-recursion.sql
index 4aa7be79a058..26a99f51d438 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/cte-recursion.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/cte-recursion.sql
@@ -648,6 +648,14 @@ WITH RECURSIVE tmp(x) AS (
 )
 SELECT * FROM rcte;
 
+-- Recursive CTE with a filter on a subquery alias that LIMIT keeps on top of 
the recursion
+WITH RECURSIVE r(k, lvl) AS (
+    SELECT id, 0 FROM range(5)
+    UNION ALL
+    SELECT * FROM (SELECT k, lvl + 1 AS lvl FROM r LIMIT 100) t WHERE t.lvl < 3
+)
+SELECT count(*), max(lvl) FROM r;
+
 SET spark.sql.cteRecursionAnchorRowsLimitToConvertToLocalRelation=100;
 
 -- Recursive CTE with multiple of the same reference in the anchor, which get 
referenced as different variables in subsequent iterations.
diff --git 
a/sql/core/src/test/resources/sql-tests/results/cte-recursion.sql.out 
b/sql/core/src/test/resources/sql-tests/results/cte-recursion.sql.out
index 536fc6c4ea63..1bc69539a4f2 100644
--- a/sql/core/src/test/resources/sql-tests/results/cte-recursion.sql.out
+++ b/sql/core/src/test/resources/sql-tests/results/cte-recursion.sql.out
@@ -1826,6 +1826,19 @@ struct<x:int,y:int>
 5      4
 
 
+-- !query
+WITH RECURSIVE r(k, lvl) AS (
+    SELECT id, 0 FROM range(5)
+    UNION ALL
+    SELECT * FROM (SELECT k, lvl + 1 AS lvl FROM r LIMIT 100) t WHERE t.lvl < 3
+)
+SELECT count(*), max(lvl) FROM r
+-- !query schema
+struct<count(1):bigint,max(lvl):int>
+-- !query output
+15     2
+
+
 -- !query
 SET spark.sql.cteRecursionAnchorRowsLimitToConvertToLocalRelation=100
 -- !query schema
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala 
b/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala
index d9ce3000a0c1..d3ffa5fed69c 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala
@@ -1669,6 +1669,16 @@ class DataFrameSuite extends QueryTest
     }
   }
 
+  test("SPARK-61254: LogicalRDD constraints should not reference the origin 
Dataset columns") {
+    val df = spark.range(16).as("t").where($"t.id" > 5)
+    // The optimizer removes the root alias, so the constraint `t.id > 5` 
differs from the
+    // optimized output `id` only in qualifier.
+    val cp = df.select($"id".as("id")).localCheckpoint()
+    checkAnswer(
+      df.join(cp, df("id") === cp("id") + 1, "right_outer").where(cp("id") > 
0),
+      (6L to 14L).map(i => Row(i + 1, i)) :+ Row(null, 15L))
+  }
+
   test("SPARK-10656: completely support special chars") {
     val df = Seq(1 -> "a").toDF("i_$.a", "d^'a.")
     checkAnswer(df.select(df("*")), Row(1, "a"))


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to