HeartSaVioR commented on code in PR #60279:
URL: https://github.com/apache/spark/pull/60279#discussion_r4546994791


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -717,21 +727,94 @@ case class StreamingSymmetricHashJoinExec(
         Predicate.create(Literal(false), Seq.empty).eval _  // false = do not 
remove if no predicate
     }
 
+    // A NULL in the column that the state watermark predicate tests makes the 
predicate unknown,
+    // so eviction never removes the row. The row cannot match either: that 
column is an equality
+    // key, or a comparison in the join condition bounds it. Handle the row 
like one that fails
+    // the pre-join filter.
+    // The check takes the generated key and the input row, so the key is 
computed only once.
+    private[this] val isEvictionColumnNull: (UnsafeRow, UnsafeRow) => Boolean =
+      stateWatermarkPredicate match {
+        case Some(JoinStateKeyWatermarkPredicate(expr, _, _)) =>
+          // Only a NULL key fails equality. A struct key with a NULL field 
can still be equal.
+          val ordinal = expr.collectFirst { case b: BoundReference => 
b.ordinal }.get
+          (key, _) => key.isNullAt(ordinal)

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
 The new test in `StreamingOuterJoinBase` joins on `leftKey = rightKey AND 
leftTime = rightTime` with a NULL `leftTime` on the preserved side. It checks 
that the row is emitted with nulls on arrival and that the state keeps only the 
two matched rows. It runs for every state format. If we replace the key branch 
of the null check with `false`, the test fails in all of them.
   
   <!-- sp2k-review3 reply 4537966911 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOutputWatermarkSuite.scala:
##########
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import java.sql.Timestamp
+
+import org.apache.spark.sql.{DataFrame, Encoders, Row}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinSide,
 LeftSide, RightSide}
+import org.apache.spark.sql.execution.streaming.runtime.{MemoryStream, 
StreamExecution}
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions.{col, count, expr, lit, session_window, 
timestamp_seconds, window}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinOutputWatermarkSuite extends StreamTest {
+  import testImplicits._
+
+  for (version <- Seq(2, 3, 4)) {
+    test(s"unbounded join state can emit an old event time after watermarks 
advance, V$version") {
+      withSQLConf(
+          SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+          SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+          SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+        val leftInput = MemoryStream[(Int, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("key", "seconds")
+          .select($"key", timestamp_seconds($"seconds").as("leftTime"))
+          .withWatermark("leftTime", "10 seconds")
+        val right = rightInput.toDF().toDF("key", "seconds")
+          .select($"key", timestamp_seconds($"seconds").as("rightTime"))
+          .withWatermark("rightTime", "10 seconds")
+        val result = left.join(right, Seq("key"))
+          .select($"key", $"leftTime")
+          .dropDuplicatesWithinWatermark("key")
+          .select($"key", $"leftTime".cast("long"))
+
+        testStream(result)(
+          MultiAddData((leftInput, Seq((1, 5L))), (rightInput, Seq((9, 5L)))),
+          CheckNewAnswer(),
+          MultiAddData((leftInput, Seq((2, 30L))), (rightInput, Seq((3, 
30L)))),
+          CheckNewAnswer(),
+          // Process another batch so the join's output watermark reaches 
downstream operators.
+          AddData(rightInput, (4, 40L)),
+          CheckNewAnswer(),
+          // The retained left key 1 can still join after both input 
watermarks reach 20 seconds.
+          // The right event is newer than that watermark, but the joined left 
time is only 5.
+          AddData(rightInput, (1, 100L)),
+          CheckNewAnswer((1, 5L)),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.eventTimeWatermarkForLateEvents.contains(20000L))
+            assert(join.produceOutputWatermark(20000L).contains(0L))
+          })
+      }
+    }
+  }
+
+  // Impressions are bounded by the click watermark; clicks have no lower 
bound on clickTime.
+  private def oneDirectionalJoin(): (MemoryStream[(Int, Long)], 
MemoryStream[(Int, Long)],
+      DataFrame) = {
+    val impressionInput = MemoryStream[(Int, Long)]
+    val clickInput = MemoryStream[(Int, Long)]
+    val impressions = impressionInput.toDF().toDF("impressionAdId", "seconds")
+      .select($"impressionAdId", 
timestamp_seconds($"seconds").as("impressionTime"))
+      .withWatermark("impressionTime", "10 seconds")
+    val clicks = clickInput.toDF().toDF("clickAdId", "seconds")
+      .select($"clickAdId", timestamp_seconds($"seconds").as("clickTime"))
+      .withWatermark("clickTime", "10 seconds")
+    val joined = impressions.join(clicks,
+      expr("clickAdId = impressionAdId AND clickTime <= impressionTime + 
INTERVAL 10 SECONDS"))
+    (impressionInput, clickInput, joined)
+  }
+
+  private def windowCounts(
+      df: DataFrame,
+      timeColumn: String,
+      slide: String = "10 seconds"): DataFrame = {
+    df.groupBy(window(col(timeColumn), "10 seconds", 
slide)).agg(count("*").as("count"))
+      .select($"window.start".cast("long"), $"count")
+  }
+
+  // The join that reads the inputs, below any stream-stream join after it.
+  private def join(query: StreamExecution): StreamingSymmetricHashJoinExec = {
+    query.lastExecution.executedPlan.collect {
+      case j: StreamingSymmetricHashJoinExec
+          if 
!j.children.exists(_.exists(_.isInstanceOf[StreamingSymmetricHashJoinExec])) => 
j
+    }.head
+  }
+
+  private def runOneDirectionalJoin(
+      impressionInput: MemoryStream[(Int, Long)],
+      clickInput: MemoryStream[(Int, Long)],
+      result: DataFrame,
+      expectedRows: Seq[Row],
+      expectedSides: Option[Set[JoinSide]],
+      expectedOutputWatermark: Long): Unit = {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+      testStream(result, OutputMode.Append())(
+        MultiAddData((impressionInput, Seq((1, 5L), (2, 15L), (3, 25L))),
+          (clickInput, Seq((1, 8L), (2, 20L)))),
+        ProcessAllAvailable(),
+        // The click at 30 seconds joins the retained impression at 25 seconds.
+        MultiAddData((impressionInput, Seq((4, 60L))), (clickInput, Seq((3, 
30L), (9, 70L)))),
+        ProcessAllAvailable(),
+        MultiAddData((impressionInput, Seq((5, 100L))), (clickInput, Seq((9, 
110L)))),
+        ProcessAllAvailable(),
+        AddData(clickInput, (9, 150L)),
+        ProcessAllAvailable(),
+        AddData(impressionInput, (6, 200L)),
+        ProcessAllAvailable(),
+        CheckAnswer(expectedRows: _*),
+        Execute { query =>
+          val j = join(query)
+          assert(j.outputWatermarkSides == expectedSides)
+          assert(j.produceOutputWatermark(j.eventTimeWatermarkForEviction.get)
+            .contains(expectedOutputWatermark))
+          // No joined row arrives behind the watermark of the operator after 
the join.
+          assert(query.recentProgress.flatMap(_.stateOperators)
+            .map(_.numRowsDroppedByWatermark).sum == 0)
+        })
+    }
+  }
+
+  test("output watermark follows the bounded input when only its event time is 
used") {
+    val (impressionInput, clickInput, joined) = oneDirectionalJoin()
+    // Impressions are evicted below the click watermark (90 seconds) less 10 
seconds and 1 ms.

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
 The comment now says the impression input holds the watermark back to 90 
seconds, that the click input is at 140 seconds by then, and that 79.999 
seconds is 90 seconds less 10 seconds and 1 ms.
   
   <!-- sp2k-review3 reply 4537966918 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOutputWatermarkSuite.scala:
##########
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import java.sql.Timestamp
+
+import org.apache.spark.sql.{DataFrame, Encoders, Row}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinSide,
 LeftSide, RightSide}
+import org.apache.spark.sql.execution.streaming.runtime.{MemoryStream, 
StreamExecution}
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions.{col, count, expr, lit, session_window, 
timestamp_seconds, window}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinOutputWatermarkSuite extends StreamTest {
+  import testImplicits._
+
+  for (version <- Seq(2, 3, 4)) {
+    test(s"unbounded join state can emit an old event time after watermarks 
advance, V$version") {
+      withSQLConf(
+          SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+          SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+          SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+        val leftInput = MemoryStream[(Int, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("key", "seconds")
+          .select($"key", timestamp_seconds($"seconds").as("leftTime"))
+          .withWatermark("leftTime", "10 seconds")
+        val right = rightInput.toDF().toDF("key", "seconds")
+          .select($"key", timestamp_seconds($"seconds").as("rightTime"))
+          .withWatermark("rightTime", "10 seconds")
+        val result = left.join(right, Seq("key"))
+          .select($"key", $"leftTime")
+          .dropDuplicatesWithinWatermark("key")
+          .select($"key", $"leftTime".cast("long"))
+
+        testStream(result)(
+          MultiAddData((leftInput, Seq((1, 5L))), (rightInput, Seq((9, 5L)))),
+          CheckNewAnswer(),
+          MultiAddData((leftInput, Seq((2, 30L))), (rightInput, Seq((3, 
30L)))),
+          CheckNewAnswer(),
+          // Process another batch so the join's output watermark reaches 
downstream operators.
+          AddData(rightInput, (4, 40L)),
+          CheckNewAnswer(),
+          // The retained left key 1 can still join after both input 
watermarks reach 20 seconds.
+          // The right event is newer than that watermark, but the joined left 
time is only 5.
+          AddData(rightInput, (1, 100L)),
+          CheckNewAnswer((1, 5L)),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.eventTimeWatermarkForLateEvents.contains(20000L))
+            assert(join.produceOutputWatermark(20000L).contains(0L))
+          })
+      }
+    }
+  }
+
+  // Impressions are bounded by the click watermark; clicks have no lower 
bound on clickTime.
+  private def oneDirectionalJoin(): (MemoryStream[(Int, Long)], 
MemoryStream[(Int, Long)],
+      DataFrame) = {
+    val impressionInput = MemoryStream[(Int, Long)]
+    val clickInput = MemoryStream[(Int, Long)]
+    val impressions = impressionInput.toDF().toDF("impressionAdId", "seconds")
+      .select($"impressionAdId", 
timestamp_seconds($"seconds").as("impressionTime"))
+      .withWatermark("impressionTime", "10 seconds")
+    val clicks = clickInput.toDF().toDF("clickAdId", "seconds")
+      .select($"clickAdId", timestamp_seconds($"seconds").as("clickTime"))
+      .withWatermark("clickTime", "10 seconds")
+    val joined = impressions.join(clicks,
+      expr("clickAdId = impressionAdId AND clickTime <= impressionTime + 
INTERVAL 10 SECONDS"))
+    (impressionInput, clickInput, joined)
+  }
+
+  private def windowCounts(
+      df: DataFrame,
+      timeColumn: String,
+      slide: String = "10 seconds"): DataFrame = {
+    df.groupBy(window(col(timeColumn), "10 seconds", 
slide)).agg(count("*").as("count"))
+      .select($"window.start".cast("long"), $"count")
+  }
+
+  // The join that reads the inputs, below any stream-stream join after it.
+  private def join(query: StreamExecution): StreamingSymmetricHashJoinExec = {
+    query.lastExecution.executedPlan.collect {
+      case j: StreamingSymmetricHashJoinExec
+          if 
!j.children.exists(_.exists(_.isInstanceOf[StreamingSymmetricHashJoinExec])) => 
j
+    }.head
+  }
+
+  private def runOneDirectionalJoin(
+      impressionInput: MemoryStream[(Int, Long)],
+      clickInput: MemoryStream[(Int, Long)],
+      result: DataFrame,
+      expectedRows: Seq[Row],
+      expectedSides: Option[Set[JoinSide]],
+      expectedOutputWatermark: Long): Unit = {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+      testStream(result, OutputMode.Append())(
+        MultiAddData((impressionInput, Seq((1, 5L), (2, 15L), (3, 25L))),
+          (clickInput, Seq((1, 8L), (2, 20L)))),
+        ProcessAllAvailable(),
+        // The click at 30 seconds joins the retained impression at 25 seconds.
+        MultiAddData((impressionInput, Seq((4, 60L))), (clickInput, Seq((3, 
30L), (9, 70L)))),
+        ProcessAllAvailable(),
+        MultiAddData((impressionInput, Seq((5, 100L))), (clickInput, Seq((9, 
110L)))),
+        ProcessAllAvailable(),
+        AddData(clickInput, (9, 150L)),
+        ProcessAllAvailable(),
+        AddData(impressionInput, (6, 200L)),
+        ProcessAllAvailable(),
+        CheckAnswer(expectedRows: _*),
+        Execute { query =>
+          val j = join(query)
+          assert(j.outputWatermarkSides == expectedSides)
+          assert(j.produceOutputWatermark(j.eventTimeWatermarkForEviction.get)
+            .contains(expectedOutputWatermark))
+          // No joined row arrives behind the watermark of the operator after 
the join.
+          assert(query.recentProgress.flatMap(_.stateOperators)
+            .map(_.numRowsDroppedByWatermark).sum == 0)
+        })
+    }
+  }
+
+  test("output watermark follows the bounded input when only its event time is 
used") {
+    val (impressionInput, clickInput, joined) = oneDirectionalJoin()
+    // Impressions are evicted below the click watermark (90 seconds) less 10 
seconds and 1 ms.
+    runOneDirectionalJoin(impressionInput, clickInput,
+      windowCounts(joined.select($"impressionTime"), "impressionTime"),
+      Seq(Row(0L, 1L), Row(10L, 1L), Row(20L, 1L)), Some(Set(LeftSide)), 
79999L)
+  }
+
+  Seq("clickTime", "clickTimeAlias").foreach { timeColumn =>
+    test(s"output watermark is held back when the unbounded input's event time 
is used: " +
+        timeColumn) {
+      val (impressionInput, clickInput, joined) = oneDirectionalJoin()
+      val clickTime = if (timeColumn == "clickTime") $"clickTime" else 
$"clickTime".as(timeColumn)
+      runOneDirectionalJoin(impressionInput, clickInput,
+        windowCounts(joined.select(clickTime), timeColumn), Nil, 
Some(Set(RightSide)), 0L)
+    }
+  }
+
+  // Each recognized path must carry the operator's event-time column to the 
join input it comes
+  // from. Over impressionTime the join narrows to the bounded input and emits 
what the base

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
 The comment now states the expected result: over `impressionTime` the output 
watermark is the bounded input's state watermark, 79.999 seconds by default.
   
   <!-- sp2k-review3 reply 4537966925 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinCheckpointCompatibilitySuite.scala:
##########
@@ -0,0 +1,576 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import java.io.File
+import java.nio.file.Files
+
+import scala.jdk.CollectionConverters._
+import scala.util.Using
+
+import org.apache.hadoop.fs.Path
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeReference, Cast, Expression, GreaterThan}
+import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap, 
OffsetSeq, OffsetSeqLog}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.{StreamingSymmetricHashJoinExec,
 StreamingSymmetricHashJoinHelper}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinStateKeyWatermarkPredicate,
 JoinStateValueWatermarkPredicate, LeftSide, RightSide}
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, LongType, MetadataBuilder, 
StructField, StructType, TimestampType}
+import org.apache.spark.tags.SlowSQLTest
+import org.apache.spark.util.Utils
+
+@SlowSQLTest
+class StreamingJoinCheckpointCompatibilitySuite extends StreamTest {
+  import testImplicits._
+
+  private val markerKey = 
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.key
+  private val currentMarker =
+    
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.defaultValue.get.toString
+
+  private def setMarker(checkpoint: String, marker: Option[String]): Unit = {
+    def update(conf: Map[String, String]): Map[String, String] = {
+      (conf - markerKey) ++ marker.map(markerKey -> _)
+    }
+    val offsetsPath = checkpoint + "/offsets"
+    val log = new OffsetSeqLog(spark, offsetsPath)
+    val (batchId, offsets) = log.getLatest().get
+    val updated = offsets match {
+      case o: OffsetSeq =>
+        o.copy(metadataOpt = o.metadataOpt.map(m => m.copy(conf = 
update(m.conf))))
+      case o: OffsetMap =>
+        o.copy(metadata = o.metadata.copy(conf = update(o.metadata.conf)))
+    }
+    val path = new Path(offsetsPath, batchId.toString)
+    assert(path.getFileSystem(spark.sessionState.newHadoopConf()).delete(path, 
false))
+    assert(log.add(batchId, updated))
+  }
+
+  private def snapshot(directory: File): Map[String, Seq[Byte]] = {
+    Using.resource(Files.walk(directory.toPath)) { paths =>
+      paths.iterator().asScala.filter(Files.isRegularFile(_)).map { path =>
+        directory.toPath.relativize(path).toString -> 
Files.readAllBytes(path).toSeq
+      }.toMap
+    }
+  }
+
+  private def pinnedMarker(checkpoint: String): Option[String] = {
+    new OffsetSeqLog(spark, checkpoint + 
"/offsets").getLatest().get._2.metadataOpt.get
+      .conf.get(markerKey)
+  }
+
+  private def markerAt(checkpoint: String, batchId: Long): Option[String] = {
+    new OffsetSeqLog(spark, checkpoint + 
"/offsets").get(batchId).get.metadataOpt.get
+      .conf.get(markerKey)
+  }
+
+  private def withJoinConf(version: Int, logVersion: Int)(f: => Unit): Unit = {
+    withSQLConf(
+        SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+        SQLConf.STREAMING_OFFSET_LOG_FORMAT_VERSION.key -> logVersion.toString,
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+        SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+  }
+
+  private def joinInputs(shape: String): (MemoryStream[(Int, Int)],
+      MemoryStream[(Int, Int)], DataFrame) = {
+    val leftInput = MemoryStream[(Int, Int)]
+    val rightInput = MemoryStream[(Int, Int)]
+    val leftData = leftInput.toDF().toDF("leftKey", "time")
+      .select($"leftKey", timestamp_seconds($"time").as("leftTime"),
+        timestamp_seconds($"time" + 10).as("expiry"))
+    val rightData = rightInput.toDF().toDF("rightKey", "time")
+      .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+    val left = if (Seq("equality", "expiry", "pruned expiry", "unbounded")
+        .contains(shape)) {
+      leftData.withWatermark("leftTime", "100 seconds")
+    } else {
+      leftData
+    }
+    val right = if (shape != "no watermark") {
+      rightData.withWatermark("rightTime", "100 seconds")
+    } else {
+      rightData
+    }
+    val condition = shape match {
+      case "range" => "leftKey = rightKey AND leftTime > rightTime - INTERVAL 
5 SECONDS"
+      case "expiry" => "leftKey = rightKey AND rightTime BETWEEN leftTime AND 
expiry"
+      case "pruned expiry" => "leftKey = rightKey AND rightTime <= expiry"
+      case "unbounded" => "leftKey = rightKey"
+      case _ => "leftKey = rightKey AND leftTime = rightTime"
+    }
+    val joined = left.join(right, expr(condition))
+    val result = if (shape == "unbounded") {
+      // A stateful operator after this key-only join reads its output 
watermark.
+      joined.select($"leftKey", $"rightKey", $"leftTime".cast("long"),
+        $"rightTime".cast("long")).dropDuplicates()
+    } else {
+      joined.select($"leftKey", $"rightKey")
+    }
+    (leftInput, rightInput, result)
+  }
+
+  test("checkpoint compatibility requires one aligned own-event-time equality 
key") {
+    val watermarkMetadata = new MetadataBuilder()
+      .putLong(EventTimeWatermark.delayKey, 0L).build()
+    val leftId = AttributeReference("leftId", IntegerType)()
+    val rightId = AttributeReference("rightId", IntegerType)()
+    val leftTime = AttributeReference("leftTime", TimestampType,
+      metadata = watermarkMetadata)()
+    val rightTime = AttributeReference("rightTime", TimestampType,
+      metadata = watermarkMetadata)()
+    val compatible = 
StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+      _: Seq[Attribute], _: Seq[Attribute], _: Seq[Expression], _: 
Seq[Expression], None,
+      consumedSides = Set(LeftSide, RightSide))
+
+    assert(compatible(Seq(leftId), Seq(rightId), Seq(leftId), Seq(rightId)))
+    assert(compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId, leftTime), Seq(rightId, rightTime)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId, leftTime), Seq(rightTime, rightId)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId, leftTime, leftTime), Seq(rightId, rightTime, rightTime)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId), Seq(rightId)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId),
+      Seq(leftId, leftTime), Seq(rightId, rightId)))
+    assert(!compatible(Seq(leftId), Seq(rightId, rightTime),
+      Seq(leftId, leftId), Seq(rightId, rightTime)))
+    assert(!compatible(Seq(leftTime, rightTime), Seq(rightTime),
+      Seq(leftTime), Seq(rightTime)))
+    assert(!compatible(Seq(leftTime), Seq(rightTime, leftTime),
+      Seq(leftTime), Seq(rightTime)))
+    // Metadata alone must not select an earlier key or hide a computed 
watermarked key.
+    val computed = Alias(leftTime, "computed")()
+    assert(!compatible(Seq(leftTime), Seq(rightTime),
+      Seq(computed, leftTime), Seq(rightTime, rightTime)))
+    assert(!compatible(Seq(leftId), Seq(rightId), Seq(computed), Seq(rightId)))
+
+    // A key-only join is accepted only when no stateful operator after it 
reads its output
+    // watermark. Another condition, or a key that uses an event time, makes 
it not key-only.
+    val notConsumed = 
StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+      _: Seq[Attribute], _: Seq[Attribute], _: Seq[Expression], _: 
Seq[Expression],
+      _: Option[Expression], consumedSides = Set.empty)
+    val leftInput = Seq(leftId, leftTime)
+    val rightInput = Seq(rightId, rightTime)
+    assert(notConsumed(leftInput, rightInput, Seq(leftId), Seq(rightId), None))
+    assert(!notConsumed(leftInput, rightInput, Seq(leftId), Seq(rightId),
+      Some(GreaterThan(leftId, rightId))))
+    assert(!notConsumed(leftInput, rightInput, Seq(leftId, Cast(leftTime, 
LongType)),
+      Seq(rightId, Cast(rightTime, LongType)), None))
+    assert(!notConsumed(leftInput, rightInput, Seq(leftId, computed), 
Seq(rightId, rightTime),
+      None))
+
+    // Ordering time windows is excluded even when nothing reads the output 
watermark: older
+    // versions derived an ordering bound for whole windows that this version 
removes.
+    val windowType = StructType(Seq(
+      StructField("start", TimestampType), StructField("end", TimestampType)))
+    val leftWindow = AttributeReference("leftWindow", windowType,
+      metadata = watermarkMetadata)()
+    val rightWindow = AttributeReference("rightWindow", windowType,
+      metadata = watermarkMetadata)()
+    assert(!notConsumed(Seq(leftId, leftWindow), Seq(rightId, rightWindow), 
Seq(leftId),
+      Seq(rightId), Some(GreaterThan(leftWindow, rightWindow))))
+  }
+
+  for {
+    version <- Seq(1, 2, 3, 4)
+    logVersion <- Seq(1, 2)
+    // Every marker below the current one takes the same rejection branch.
+    oldMarker <- Seq(None, Some("0"), Some((currentMarker.toInt - 
1).toString)).distinct
+    shape <- Seq("range", "expiry", "pruned expiry", "unbounded")
+  } {
+    test(s"reject old $shape checkpoint, V$version log=$logVersion 
old=$oldMarker") {
+      withJoinConf(version, logVersion) {
+        val (leftInput, rightInput, joined) = joinInputs(shape)
+        withTempDir { checkpointDir =>
+          val checkpoint = checkpointDir.getCanonicalPath
+          testStream(joined)(
+            StartStream(checkpointLocation = checkpoint),
+            MultiAddData(leftInput, (1, 10))(rightInput, (1, 10)),
+            CheckNewAnswer(if (shape == "unbounded") Row(1, 1, 10L, 10L)
+              else Row(1, 1)),
+            StopStream)
+          // Emulate old offset metadata. State is written by the current 
implementation;
+          // rejection must not open or reinterpret it, regardless of its 
physical layout.
+          setMarker(checkpoint, oldMarker)
+          val originalBatchId = new OffsetSeqLog(spark, checkpoint + 
"/offsets")
+            .getLatest().get._1
+          val stateBefore = snapshot(new File(checkpoint, "state"))
+          val commitsBefore = snapshot(new File(checkpoint, "commits"))
+          for (attempt <- 1 to 2) {
+            // Session defaults must not bypass the checkpoint-pinned marker 
or state format.
+            withSQLConf(markerKey -> currentMarker,
+                SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "2") {
+              testStream(joined)(
+                StartStream(checkpointLocation = checkpoint),
+                AddData(rightInput, (2, 20 + attempt)),
+                ExpectFailure[AnalysisException](assertFailure = error => {
+                  checkError(error.asInstanceOf[AnalysisException],
+                    condition = "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE",
+                    parameters = Map(
+                      "joinCondition" -> ".*leftKey.*rightKey.*",
+                      "leftWatermarkColumns" ->
+                        (if (shape == "expiry" || shape == "unbounded") 
"leftTime" else "none"),
+                      "rightWatermarkColumns" -> "rightTime"),
+                    matchPVals = true)
+                }))
+            }
+            assert(snapshot(new File(checkpoint, "state")) == stateBefore)
+            assert(snapshot(new File(checkpoint, "commits")) == commitsBefore)
+            assert(markerAt(checkpoint, originalBatchId) == oldMarker)
+          }
+        }
+      }
+    }
+  }
+
+  for {
+    version <- Seq(1, 2, 3, 4)
+    logVersion <- Seq(1, 2)
+    shape <- Seq("equality", "no watermark", "range", "expiry", "pruned 
expiry")
+  } {
+    test(s"resume compatible $shape checkpoint, V$version log=$logVersion") {
+      withJoinConf(version, logVersion) {
+        val (leftInput, rightInput, joined) = joinInputs(shape)
+        withTempDir { checkpointDir =>
+          val checkpoint = checkpointDir.getCanonicalPath
+          testStream(joined)(
+            StartStream(checkpointLocation = checkpoint),
+            MultiAddData(leftInput, (1, 10))(rightInput, (2, 10)),
+            CheckNewAnswer(),
+            StopStream)
+          assert(pinnedMarker(checkpoint).contains(currentMarker))
+          val oldCompatible = Seq("equality", "no watermark").contains(shape)
+          val expectedMarker = if (oldCompatible) "0" else currentMarker
+          if (oldCompatible) setMarker(checkpoint, None)
+          withSQLConf(markerKey -> "0",
+              SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "2") {
+            testStream(joined)(
+              StartStream(checkpointLocation = checkpoint),
+              AddData(rightInput, (1, 10)),
+              CheckNewAnswer(Row(1, 1)),
+              Execute { query =>
+                val join = query.lastExecution.executedPlan.collect {
+                  case j: StreamingSymmetricHashJoinExec => j
+                }.head
+                assert(join.stateFormatVersion == version)
+              },
+              StopStream)
+          }
+          assert(pinnedMarker(checkpoint).contains(expectedMarker))
+        }
+      }
+    }
+  }
+
+  Seq(2, 4).foreach { version =>
+    test(s"reject an incompatible checkpoint retrying batch zero, V$version") {
+      withJoinConf(version, logVersion = 1) {
+        val (leftInput, rightInput, joined) = joinInputs("range")
+        withTempDir { checkpointDir =>
+          val checkpoint = checkpointDir.getCanonicalPath
+          testStream(joined)(
+            StartStream(checkpointLocation = checkpoint),
+            MultiAddData(leftInput, (1, 10))(rightInput, (1, 10)),
+            CheckNewAnswer(Row(1, 1)),
+            StopStream)
+          val offsets = new OffsetSeqLog(spark, checkpoint + "/offsets")
+          assert(offsets.getLatest().get._1 == 0L)
+          setMarker(checkpoint, None)
+          // Emulate a crash after state was written but before the first 
batch committed.
+          val commit = new Path(checkpoint, "commits/0")
+          
assert(commit.getFileSystem(spark.sessionState.newHadoopConf()).delete(commit, 
false))
+          val before = snapshot(new File(checkpoint, "state"))
+          val commitsBefore = snapshot(new File(checkpoint, "commits"))
+          testStream(joined)(
+            StartStream(checkpointLocation = checkpoint),
+            ExpectFailure[AnalysisException](assertFailure = error => {
+              checkError(error.asInstanceOf[AnalysisException],
+                condition = "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE",
+                parameters = Map(
+                  "joinCondition" -> 
".*leftKey.*rightKey.*leftTime.*rightTime.*",
+                  "leftWatermarkColumns" -> "none",
+                  "rightWatermarkColumns" -> "rightTime"),
+                matchPVals = true)
+            }))
+          assert(snapshot(new File(checkpoint, "state")) == before)
+          assert(snapshot(new File(checkpoint, "commits")) == commitsBefore)
+        }
+      }
+    }
+  }
+
+  private val intervalCondition =
+    "leftKey = rightKey AND rightTime >= leftTime AND rightTime <= leftTime + 
INTERVAL 5 SECONDS"
+
+  // Old state of a two-sided time-interval join on the inputs' own event 
times is reusable;

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
 The header now says that joins whose unbounded input no later stateful 
operator reads also resume, for example a one-directional interval join or a 
key-only join.
   
   <!-- sp2k-review3 reply 4537966929 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +650,124 @@ class IncrementalExecution(
       watermarkPropagator.propagate(currentBatchId, plan, 
watermarkForCurrBatch)
     }
 
+    /**
+     * Find, for each stateful operator that applies its input watermark to an 
event-time column,
+     * which stream-stream join inputs' event times that column carries. The 
walk follows the
+     * column down through nodes that pass it on unchanged, to the same 
position in every input
+     * of a union, and through windows built from it, which end after it. It 
stops at a join, at
+     * another operator that writes state or sets an event time, and at any 
node it does not
+     * recognize; a join that no traced column reaches holds back for both 
inputs.
+     */
+    private def joinWatermarkConsumers(plan: SparkPlan): 
Seq[JoinWatermarkConsumer] = {
+      def eventTime(output: Seq[Attribute]): Option[Attribute] =
+        output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+
+      // A time or session window built from one column, plus constants, ends 
after that column.
+      def windowSource(window: Attribute, expression: Expression): 
Option[Attribute] = {
+        val isWindow = window.metadata.contains(TimeWindow.marker) ||
+          window.metadata.contains(SessionWindow.marker)
+        expression.references.toSeq match {
+          case Seq(source) if isWindow => Some(source)
+          case _ => None
+        }
+      }
+
+      def passThrough(child: SparkPlan, attribute: Attribute): Seq[(Long, 
JoinSide, Attribute)] =
+        child.output.find(_.exprId == 
attribute.exprId).toSeq.flatMap(findJoinSides(child, _))
+
+      def findJoinSides(
+          node: SparkPlan,
+          attribute: Attribute): Seq[(Long, JoinSide, Attribute)] = {
+        node match {
+          case j: StreamingSymmetricHashJoinExec =>
+            val side = if (eventTime(j.left.output).exists(_.exprId == 
attribute.exprId)) {
+              Some(LeftSide)
+            } else if (eventTime(j.right.output).exists(_.exprId == 
attribute.exprId)) {
+              Some(RightSide)
+            } else {
+              None
+            }
+            j.stateInfo.map(_.operatorId).zip(side).map { case (id, s) => (id, 
s, attribute) }
+              .toSeq
+          case p: ProjectExec =>
+            p.projectList.find(_.exprId == attribute.exprId).toSeq.flatMap {
+              case a: Attribute => passThrough(p.child, a)
+              case Alias(a: Attribute, _) => passThrough(p.child, a)
+              case alias: Alias =>
+                windowSource(alias.toAttribute, 
alias.child).toSeq.flatMap(passThrough(p.child, _))
+              case _ => Nil
+            }
+          case e: ExpandExec =>
+            // A sliding window is one projection per window; each must carry 
the same column.
+            val index = e.output.indexWhere(_.exprId == attribute.exprId)
+            val traced = e.projections.map { projection =>
+              projection.lift(index).toSeq.flatMap {
+                case a: Attribute => passThrough(e.child, a)
+                case expression =>
+                  windowSource(e.output(index), 
expression).toSeq.flatMap(passThrough(e.child, _))
+              }
+            }
+            if (traced.nonEmpty && traced.forall(_.nonEmpty) && 
traced.distinct.size == 1) {
+              traced.head
+            } else {
+              Nil
+            }
+          case u: UnionExec =>
+            val index = u.output.indexWhere(_.exprId == attribute.exprId)
+            if (index < 0) Nil else u.children.flatMap(c => findJoinSides(c, 
c.output(index)))
+          case _: StateStoreWriter | _: EventTimeWatermarkExec | _: 
UpdateEventTimeColumnExec =>
+            Nil
+          case u: UnaryExecNode if u.output.exists(_.exprId == 
attribute.exprId) =>
+            passThrough(u.child, attribute)
+          case _ => Nil
+        }
+      }
+
+      // The inputs whose event-time column each operator compares with its 
input watermark.
+      def watermarkedInputs(node: SparkPlan): Seq[SparkPlan] = node match {
+        case _: StateStoreSaveExec | _: StatefulStreamlineAggregateExec |
+            _: SessionWindowStateStoreSaveExec | _: StreamingDeduplicateExec |
+            _: StreamingDeduplicateWithinWatermarkExec | _: 
StreamingSymmetricHashJoinExec =>
+          node.children
+        case f: FlatMapGroupsWithStateExec if f.timeoutConf == 
EventTimeTimeout => Seq(f.child)
+        case f: FlatMapGroupsInPandasWithStateExec if f.timeoutConf == 
EventTimeTimeout =>

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Thanks. We are not adding these two tests in this PR. The 
`applyInPandasWithState` and `transformWithStateInPandas` arms use the same 
guards as the JVM arms, and `StreamingJoinOutputWatermarkSuite` covers those. A 
test for the Python arms needs a Python worker with pandas and pyarrow, and we 
cannot run one here. We do not want to commit a test we have not seen fail. We 
can add them in a follow-up if you want them.
   
   <!-- sp2k-review3 reply 4537966938 -->
   



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