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

cloud-fan pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.x by this push:
     new 5409baf8f569 [SPARK-61247][SQL] Fix ASOF join results for a NOT NULL 
left ON key and a nullable right ON key
5409baf8f569 is described below

commit 5409baf8f569e1e18b44cb4362d0d7e93b02e776
Author: Luka Zdravić <[email protected]>
AuthorDate: Tue Nov 10 00:12:28 2026 +0000

    [SPARK-61247][SQL] Fix ASOF join results for a NOT NULL left ON key and a 
nullable right ON key
    
    ### What changes were proposed in this pull request?
    `SortMergeAsOfJoinScanner` compares left and right ON keys with one 
ordering, which it built from the nullability of the left keys only. For a NOT 
NULL left key, that ordering skips the NULL check, but the right key it 
compares can still be NULL. This PR builds the ordering with 
`RowOrdering.createNaturalAscendingOrdering`, which treats every key as 
nullable, as the sort-merge join does.
    
    ### Why are the changes needed?
    A NULL right key compared as its empty value, for example 0 for an INT key. 
So it could match a left key of 0, and a left key could miss its match because 
the scan stopped at the NULL row. STRING and DECIMAL keys failed with a 
NullPointerException.
    
    ### Does this PR introduce _any_ user-facing change?
    Yes, it fixes wrong results:
    
    ```sql
    SELECT t.k, q.tag FROM VALUES (-1, 10), (0, 10) AS t(k, ts)
    LEFT ASOF JOIN VALUES (CAST(NULL AS INT), 1, 'null key'), (-1, 2, 'minus 
one') AS q(k, ts, tag)
      MATCH_CONDITION (t.ts >= q.ts) ON t.k = q.k
    -- before: (-1, NULL), (0, 'null key')
    -- after:  (-1, 'minus one'), (0, NULL)
    ```
    
    ### How was this patch tested?
    New `AsOfJoinSortMergeSQLSuite` tests join a NOT NULL left key against a 
NULL right key for INT, STRING and DECIMAL keys and for the second of two ON 
keys, with the cursor scan off and on. A new `SortMergeAsOfJoinSuite` test does 
the same for a nearest join. The randomized comparison with a plain join now 
uses a NOT NULL left key for one seed. Without the fix, these 6 tests fail. The 
ASOF join suites, `PlannerSuite` and `SQLMetricsSuite` pass.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    Generated-by: Claude Code
    
    This pull request and its description were written by Isaac.
    
    Closes #60239 from LukaZdravic/asof-null-key-ordering.
    
    Authored-by: Luka Zdravić <[email protected]>
    Signed-off-by: Wenchen Fan <[email protected]>
    
    (cherry picked from commit b955b7d263ba9b5739cd4800da69d1f47c83edf7)
    Signed-off-by: Wenchen Fan <[email protected]>
    
    
    skip-checks: true
---
 .../execution/joins/SortMergeAsOfJoinExec.scala    | 10 +---
 .../spark/sql/AsOfJoinSortMergeSQLSuite.scala      | 69 ++++++++++++++++++++--
 .../apache/spark/sql/SortMergeAsOfJoinSuite.scala  | 29 +++++++++
 3 files changed, 97 insertions(+), 11 deletions(-)

diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
index be6da428f3a3..eb866d37d4ff 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeAsOfJoinExec.scala
@@ -25,8 +25,7 @@ import org.apache.spark.rdd.RDD
 import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.expressions._
 import org.apache.spark.sql.catalyst.expressions.BindReferences.bindReference
-import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext, 
GenerateOrdering,
-  GeneratePredicate}
+import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext, 
GeneratePredicate}
 import org.apache.spark.sql.catalyst.plans._
 import org.apache.spark.sql.catalyst.plans.logical.AsOfJoin
 import org.apache.spark.sql.catalyst.plans.physical._
@@ -195,13 +194,10 @@ private[joins] class SortMergeAsOfJoinScanner(
   private lazy val boundResidualCond =
     residualCondition.map(ShortCircuitPredicate.create(_, joinedOutput))
 
+  // A right key can be NULL even when the left key is NOT NULL, so every key 
is nullable here.
   private val equiKeyOrdering: Option[BaseOrdering] =
     if (leftKeys.nonEmpty) {
-      val keyAttributes = leftKeys.zipWithIndex.map { case (key, i) =>
-        AttributeReference(s"key_$i", key.dataType, key.nullable)()
-      }
-      Some(GenerateOrdering.generate(
-        keyAttributes.map(SortOrder(_, Ascending)), keyAttributes))
+      
Some(RowOrdering.createNaturalAscendingOrdering(leftKeys.map(_.dataType)))
     } else {
       None
     }
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/AsOfJoinSortMergeSQLSuite.scala 
b/sql/core/src/test/scala/org/apache/spark/sql/AsOfJoinSortMergeSQLSuite.scala
index 3a2ee710b50f..9804ae623062 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/AsOfJoinSortMergeSQLSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/AsOfJoinSortMergeSQLSuite.scala
@@ -1554,6 +1554,61 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
       Row(1, "q11") :: Row(2, "q12") :: Row(3, null) :: Row(4, null) :: Row(5, 
null) :: Nil)
   }
 
+  // Queries with NOT NULL left ON keys against nullable right ON keys that 
hold a NULL. The NULL
+  // right key sorts first, so it must compare below every left key. Read as 
its empty value, it
+  // would match left key 0 and end the group of key -1 before its row, or 
fail to compare.
+  private val notNullLeftKeyQueries: Map[String, (String, Seq[Row])] = Map(
+    "INT" -> (
+      """
+        |SELECT t.k, q.tag
+        |FROM VALUES (-1, 10), (0, 10) AS t(k, ts)
+        |LEFT ASOF JOIN VALUES (CAST(NULL AS INT), 1, 'null key'), (-1, 2, 
'minus one')
+        |  AS q(k, ts, tag)
+        |  MATCH_CONDITION (t.ts >= q.ts)
+        |  ON t.k = q.k
+        |""".stripMargin,
+      Row(-1, "minus one") :: Row(0, null) :: Nil),
+    "STRING" -> (
+      """
+        |SELECT t.k, q.tag
+        |FROM VALUES ('a', 10), ('b', 10) AS t(k, ts)
+        |LEFT ASOF JOIN VALUES (CAST(NULL AS STRING), 1, 'null key'), ('a', 2, 
'a key')
+        |  AS q(k, ts, tag)
+        |  MATCH_CONDITION (t.ts >= q.ts)
+        |  ON t.k = q.k
+        |""".stripMargin,
+      Row("a", "a key") :: Row("b", null) :: Nil),
+    // Literals, not CASTs: a CAST can return NULL, so it would not make the 
left key NOT NULL.
+    "DECIMAL" -> (
+      """
+        |SELECT CAST(t.k AS INT), q.tag
+        |FROM VALUES (-1.00BD, 10), (0.00BD, 10) AS t(k, ts)
+        |LEFT ASOF JOIN VALUES
+        |  (CAST(NULL AS DECIMAL(3, 2)), 1, 'null key'), (-1.00BD, 2, 'minus 
one')
+        |  AS q(k, ts, tag)
+        |  MATCH_CONDITION (t.ts >= q.ts)
+        |  ON t.k = q.k
+        |""".stripMargin,
+      Row(-1, "minus one") :: Row(0, null) :: Nil),
+    // Only the second ON key is NULL on the right. Read as 0, the row 'null 
b' would join the
+    // group of (1, 0), and a forward join would pick it first.
+    "second of two ON keys" -> (
+      """
+        |SELECT t.a, q.tag
+        |FROM VALUES (1, 0, 0) AS t(a, b, ts)
+        |ASOF JOIN VALUES (1, CAST(NULL AS INT), 1, 'null b'), (1, 0, 2, 'b 
zero')
+        |  AS q(a, b, ts, tag)
+        |  MATCH_CONDITION (t.ts <= q.ts)
+        |  ON t.a = q.a AND t.b = q.b
+        |""".stripMargin,
+      Row(1, "b zero") :: Nil))
+
+  gridTest("cursor scan: a NOT NULL left ON key never matches a NULL right ON 
key")(
+    notNullLeftKeyQueries.keys.toSeq.sorted) { keyShape =>
+    val (query, expected) = notNullLeftKeyQueries(keyShape)
+    checkCursorScan(sql(query), expected)
+  }
+
   test("cursor scan: a MATCH_CONDITION with the right side first still uses 
the cursor scan") {
     // The analyzer puts the left side first, so q.ts <= t.ts runs as t.ts >= 
q.ts.
     Seq(
@@ -1806,21 +1861,27 @@ class AsOfJoinSortMergeSQLSuite extends QueryTest
       .add("ts", IntegerType)
     val rightSchema = new StructType().add("k", IntegerType).add("ts", 
IntegerType)
       .add("tag", StringType)
-    (1 to 3).foreach { seed =>
+    // Seed 4 marks the left ON key NOT NULL and gives it no NULLs, against 
the right side's NULL
+    // ON key, so a key compare that drops the NULL check for a NOT NULL left 
key shows up.
+    val leftSchemaNotNullKey = new StructType().add("id", IntegerType)
+      .add("k", IntegerType, nullable = false).add("ts", IntegerType)
+    (1 to 4).foreach { seed =>
       val random = new Random(seed)
+      val leftKeyNotNull = seed == 4
       def orNull(value: Int): Any = if (random.nextInt(10) == 0) null else 
value
       def tag(): String =
         if (random.nextInt(8) == 0) null else 
random.alphanumeric.take(random.nextInt(40)).mkString
       // Left ON keys are 0 to 7 and right ON keys 2 to 9, so keys 0, 1, 8 and 
9 have one side.
       val leftRows = (0 until 200).map { id =>
-        Row(id, orNull(random.nextInt(8)), orNull(random.nextInt(100)))
+        val k = random.nextInt(8)
+        Row(id, if (leftKeyNotNull) k else orNull(k), 
orNull(random.nextInt(100)))
       }
       val rightRows = (2 until 10).flatMap { k =>
         random.shuffle((0 until 100).toList).take(30).map(ts => Row(k, ts, 
tag()))
       } ++ Seq(Row(null, 5, "NULL ON key"), Row(3, null, "NULL as-of key"))
       withTempView("t", "q") {
-        spark.createDataFrame(spark.sparkContext.parallelize(leftRows), 
leftSchema)
-          .createOrReplaceTempView("t")
+        spark.createDataFrame(spark.sparkContext.parallelize(leftRows),
+          if (leftKeyNotNull) leftSchemaNotNullKey else 
leftSchema).createOrReplaceTempView("t")
         spark.createDataFrame(spark.sparkContext.parallelize(rightRows), 
rightSchema)
           .createOrReplaceTempView("q")
         for {
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/SortMergeAsOfJoinSuite.scala 
b/sql/core/src/test/scala/org/apache/spark/sql/SortMergeAsOfJoinSuite.scala
index d75a955be330..af2b714f1e5d 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/SortMergeAsOfJoinSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/SortMergeAsOfJoinSuite.scala
@@ -2046,6 +2046,35 @@ class SortMergeAsOfJoinSuite extends QueryTest
     )
   }
 
+  test("nearest join never matches a NULL right equi-key against a NOT NULL 
left key") {
+    // The left key is NOT NULL and the right key nullable. The NULL right key 
sorts first, so a
+    // key compare that read it as 0 would match left key 0 and stop before 
the rows of key -1.
+    val left = spark.createDataFrame(
+      List(Row(-1, 10), Row(0, 10)).asJava,
+      StructType(
+        StructField("k", IntegerType, nullable = false) ::
+          StructField("ts", IntegerType, nullable = false) :: Nil))
+    val right = spark.createDataFrame(
+      List(Row(null, 1, "null key"), Row(-1, 2, "minus one")).asJava,
+      StructType(
+        StructField("k", IntegerType) ::
+          StructField("ts", IntegerType) ::
+          StructField("tag", StringType) :: Nil))
+    // One partition: with several, the NULL right row could land apart from 
the left rows and
+    // never be compared.
+    withSQLConf(SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val joined = left.joinAsOf(
+        right, left.col("ts"), right.col("ts"), usingColumns = Seq("k"),
+        joinType = "leftouter", tolerance = null,
+        allowExactMatches = true, direction = "nearest")
+        .select(left.col("k"), right.col("tag"))
+      checkAnswer(joined, Row(-1, "minus one") :: Row(0, null) :: Nil)
+      assert(collectFirst(joined.queryExecution.executedPlan) {
+        case j: SortMergeAsOfJoinExec => j
+      }.isDefined, s"Expected SortMergeAsOfJoinExec in 
plan:\n${joined.queryExecution}")
+    }
+  }
+
   test("null-safe equi-key (<=>) in ON matches null keys, unlike EqualTo") {
     // <=> is a residual (empty equi-keys), so null keys match, unlike EqualTo.
     val schema1 = StructType(


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

Reply via email to