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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -362,6 +364,24 @@ case class StreamingSymmetricHashJoinExec(
   }
 
   protected override def doExecute(): RDD[InternalRow] = {
+    // Older versions order the V4 state of an input by its event time, so 
their checkpoints
+    // cannot evict that state by another column.
+    if (stateFormatVersion == 4 &&
+        conf.getConf(SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION) == 0) {
+      Seq((LeftSide, stateWatermarkPredicates.left, left.output),
+          (RightSide, stateWatermarkPredicates.right, right.output)).foreach {
+        case (side, predicate, attributes) =>
+          val eventTime = WatermarkSupport.findEventTimeColumnIndex(
+            attributes, allowMultipleEventTimeColumns = false)
+          stateValueWatermarkColumnOrdinal(predicate, attributes)
+            .filterNot(eventTime.contains).foreach { column =>

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Agreed, reproduced: an upgraded state format 4 inner or left semi join 
failed to restart. Earlier versions keep such an input out of the index, so its 
old rows are never evicted but are still found by key. Now only an outer join 
that emits that input's unmatched rows fails, since it would never emit the old 
ones.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -261,28 +261,37 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             eventTimeWatermarkForEviction.get,
             prevStateKeyWatermark)
         }
-      } else if (isWatermarkDefinedOnInput) { // case 2 in the 
StreamingSymmetricHashJoinExec docs
-        val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
-          attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-          attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-          condition,
-          eventTimeWatermarkForEviction)
-        // A row can pass late-input filtering but already be eligible for 
eviction in this batch.
-        // When the previous join-derived state cutoff is ahead of the 
late-input watermark, a new
-        // row can fall at or below that cutoff. V4 must scan from the 
beginning to find such rows.
-        val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap 
{ lateWatermark =>
-          StreamingJoinHelper.getStateValueWatermark(
-            attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-            attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-            condition,
-            eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
-        }
-        val inputAttributeWithWatermark = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
-        val expr = watermarkExpression(inputAttributeWithWatermark, 
stateValueWatermark)
-        expr.map { e =>
-          // watermarkExpression only provides the expression when 
eventTimeWatermarkForEviction
-          // is defined
-          JoinStateValueWatermarkPredicate(e, stateValueWatermark.get, 
prevStateValueWatermark)
+      } else if (isWatermarkDefinedOnInput || !useFirstEventTimeColumn) {

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Master never evicts such an input, so these rows stay there as well. #60667 
now evicts any stored row whose eviction column is NULL, and that also covers 
inputs without a watermark here. Added a test that stores such a row in legacy 
mode and checks that it is emitted after a default-mode restart.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOneSidedWatermarkSuite.scala:
##########
@@ -0,0 +1,84 @@
+/*
+ * 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 org.apache.spark.sql.Row
+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.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinOneSidedWatermarkSuite extends StreamTest {
+  import testImplicits._
+
+  for {
+    version <- Seq(2, 3, 4)
+    joinType <- Seq("left_outer", "right_outer")

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Added: inner joins with a watermark on either input and left semi joins with 
a watermark on the right, on state formats 2 and 4. They check the matches, the 
state size after eviction, a restart, and a row that arrives below the cutoff.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinRangeEvictionSuite.scala:
##########
@@ -0,0 +1,311 @@
+/*
+ * 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.charset.StandardCharsets.UTF_8
+import java.nio.file.Files
+
+import org.apache.hadoop.fs.Path
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap, 
OffsetSeq, OffsetSeqLog}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+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.tags.SlowSQLTest
+import org.apache.spark.util.Utils
+
+@SlowSQLTest
+class StreamingJoinRangeEvictionSuite extends StateStoreMetricsTest {
+  import testImplicits._
+
+  private def withJoinConf(version: Int)(f: => Unit): Unit = {
+    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")(f)
+  }
+
+  // The left input has the event time leftTime and another TIMESTAMP column 
expiry. A negative
+  // end gives a NULL expiry.
+  private def joinWithExpiry(range: String, joinType: String)
+      : (MemoryStream[(Int, Long, Long)], MemoryStream[(Int, Long)], 
DataFrame) = {
+    val leftInput = MemoryStream[(Int, Long, Long)]
+    val rightInput = MemoryStream[(Int, Long)]
+    val left = leftInput.toDF().toDF("leftKey", "start", "end")
+      .select($"leftKey", timestamp_seconds($"start").as("leftTime"),
+        when($"end" >= 0, timestamp_seconds($"end")).as("expiry"))
+      .withWatermark("leftTime", "60 seconds")
+    val right = rightInput.toDF().toDF("rightKey", "time")
+      .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+      .withWatermark("rightTime", "60 seconds")
+    val condition = expr(s"leftKey = rightKey AND $range")
+    val joined = if (joinType == "right_outer") {
+      right.join(left, condition, joinType)
+    } else {
+      left.join(right, condition, joinType)
+    }
+    val result = joined.select($"leftKey", 
$"rightTime".cast("long").as("matchTime"),
+      $"leftTime".cast("long"))
+    (leftInput, rightInput, result)
+  }
+
+  // State format 3 shares the eviction code of format 2.
+  for {
+    version <- Seq(2, 4)
+    joinType <- Seq("inner", "left_outer", "right_outer")
+    shape <- Seq("between", "conjunction", "upper", "interval")
+  } {
+    test(s"range eviction uses the bounded column, V$version $joinType 
$shape") {
+      withJoinConf(version) {
+        val range = shape match {
+          case "between" => "rightTime BETWEEN leftTime AND expiry"
+          case "conjunction" => "rightTime >= leftTime AND rightTime <= expiry"
+          case "interval" => "rightTime BETWEEN leftTime AND leftTime + 
INTERVAL 10 MINUTES"
+          case _ => "rightTime <= expiry"
+        }
+        val (leftInput, rightInput, result) = joinWithExpiry(range, joinType)
+        testStream(result)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)), 
AddData(rightInput, (9, 100L)))),
+          CheckNewAnswer(),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9, 
400L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 400L)),
+          // The watermark has passed the start time, but the range has not 
expired.
+          CheckNewAnswer(),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.eventTimeWatermarkForEviction.contains(340000L))
+          },
+          AddData(rightInput, (1, 460L)),
+          CheckNewAnswer(Row(1, 460L, 100L)),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9, 
1000L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 1100L)),
+          CheckNewAnswer((if (joinType != "inner") Seq(Row(2, null, 100L)) 
else Nil): _*)
+        )
+      }
+    }
+  }
+
+  for {
+    version <- Seq(2, 3, 4)
+    joinType <- Seq("left_outer", "right_outer")
+  } {
+    test(s"range eviction includes newly admitted expired values, V$version 
$joinType") {
+      withJoinConf(version) {
+        val (leftInput, rightInput, result) = joinWithExpiry("rightTime <= 
expiry", joinType)
+        testStream(result)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 100L, 700L)), AddData(rightInput, (9, 
100L)))),
+          CheckNewAnswer(),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9, 
400L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 400L)), CheckNewAnswer(),
+          // The start passes late filtering, but expiry is below the previous 
eviction cutoff.
+          AddData(leftInput, (3, 460L, 200L)), CheckNewAnswer(Row(3, null, 
460L)),
+          AddData(rightInput, (9, 500L)), CheckNewAnswer())
+      }
+    }
+  }
+
+  for {
+    version <- Seq(2, 4)
+    joinType <- Seq("left_outer", "right_outer")
+  } {
+    test(s"a row whose range-eviction column is NULL is emitted on arrival, 
V$version $joinType") {
+      withJoinConf(version) {
+        val (leftInput, rightInput, result) =
+          joinWithExpiry("rightTime BETWEEN leftTime AND expiry", joinType)
+        testStream(result)(
+          // The row can never match, and the eviction predicate on expiry 
never removes it.
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, -1L), (2, 100L, 700L)), 
AddData(rightInput, (2, 150L)))),
+          CheckNewAnswer(Row(1, null, 100L), Row(2, 150L, 100L)),
+          assertNumStateRows(total = 2, updated = 2))
+      }
+    }
+  }
+
+  // In state format 4, the extra conjunct gives the right side a value 
predicate on rightTime, so
+  // that the range scan of the right joiner solves the bound that shifts by a 
column.
+  for {
+    bound <- Seq("leftTime > rightTime + rightDelay",
+      "CAST(leftTime AS BIGINT) + leftOffset > CAST(rightTime AS BIGINT)")
+    version <- Seq(2, 4)
+  } {
+    test(s"range eviction does not log solver errors for other columns: 
$bound, V$version") {
+      val logAppender = new LogAppender("stream-stream join state constraints")
+      withLogAppender(logAppender,
+          loggerNames = 
Seq(StreamingJoinHelper.getClass.getName.stripSuffix("$")),
+          level = Some(Level.WARN)) {
+        withJoinConf(version) {
+          val leftInput = MemoryStream[(Int, Long, Long)]
+          val rightInput = MemoryStream[(Int, Long, Int)]
+          val left = leftInput.toDF().toDF("leftKey", "time", "leftOffset")
+            .select($"leftKey", timestamp_seconds($"time").as("leftTime"), 
$"leftOffset")
+            .withWatermark("leftTime", "0 seconds")
+          val right = rightInput.toDF().toDF("rightKey", "time", "delay")
+            .select($"rightKey", timestamp_seconds($"time").as("rightTime"),
+              ($"delay" * expr("INTERVAL 1 SECOND")).as("rightDelay"))
+            .withWatermark("rightTime", "0 seconds")
+          val extra = if (version == 4) " AND leftTime < rightTime + INTERVAL 
1 HOUR" else ""
+          val joined = left.join(right, expr(s"leftKey = rightKey AND 
$bound$extra"))
+            .select($"leftKey", $"leftTime".cast("long"), 
$"rightTime".cast("long"))
+          testStream(joined)(
+            StreamProgressLockedActions(Seq(
+              AddData(leftInput, (1, 20L, 0L)), AddData(rightInput, (1, 10L, 
5)))),
+            CheckNewAnswer(Row(1, 20L, 10L)),
+            AddData(rightInput, (2, 30L, 1)),
+            CheckNewAnswer())
+        }
+      }
+      // A per-row column leaves the bound unknown, which is not an error.
+      assert(!logAppender.loggingEvents.exists(
+        _.getMessage.getFormattedMessage.contains("Error trying to extract 
state constraint")))
+    }
+  }
+
+  private val indexVersionKey = 
SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION.key
+
+  private def indexVersion(checkpoint: File): Option[String] = {
+    new OffsetSeqLog(spark, new File(checkpoint, 
"offsets").getCanonicalPath).getLatest().get._2
+      .metadataOpt.get.conf.get(indexVersionKey)
+  }
+
+  // Removes the V4 index version from the latest offset log entry, as older 
versions wrote it.
+  private def removeIndexVersion(checkpoint: File): Unit = {
+    val offsetsPath = new File(checkpoint, "offsets").getCanonicalPath
+    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 = m.conf - 
indexVersionKey)))
+      case o: OffsetMap =>
+        o.copy(metadata = o.metadata.copy(conf = o.metadata.conf - 
indexVersionKey))
+    }
+    val path = new Path(offsetsPath, batchId.toString)
+    assert(path.getFileSystem(spark.sessionState.newHadoopConf()).delete(path, 
false))
+    assert(log.add(batchId, updated))
+  }
+
+  // Copies a bundled checkpoint and points the copied operator metadata at 
the state schema files
+  // of the copy. The bundled metadata names them under the placeholder 
directory /checkpoint.
+  private def copyCheckpointFixture(name: String, checkpoint: File): Unit = {
+    Utils.copyDirectory(
+      new File(getClass.getResource(s"/structured-streaming/$name/").toURI), 
checkpoint)
+    val metadataDir = new File(checkpoint, "state/0/_metadata/v2")
+    metadataDir.listFiles().filter(f => f.isFile && 
!f.getName.startsWith(".")).foreach { file =>
+      val metadata = new String(Files.readAllBytes(file.toPath), UTF_8)
+      val updated = metadata.replace("file:/checkpoint/", new 
Path(checkpoint.toURI).toString + "/")
+      assert(updated != metadata, s"No state schema file is named in $file")
+      Files.write(file.toPath, updated.getBytes(UTF_8))
+    }
+  }
+
+  test("V4 restart from an older checkpoint keeps evicting by the event time") 
{
+    withJoinConf(4) {
+      withTempDir { checkpoint =>
+        val (leftInput, rightInput, result) = joinWithExpiry(
+          "rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES", 
"left_outer")
+        testStream(result)(
+          StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, 700L)), AddData(rightInput, (9, 
100L)))),
+          CheckNewAnswer(),
+          StopStream)
+        assert(indexVersion(checkpoint) === Some("1"))
+        removeIndexVersion(checkpoint)
+        testStream(result)(
+          StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+          AddData(rightInput, (1, 160L)),
+          CheckNewAnswer(Row(1, 160L, 100L)),

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   The event-time restart test in #60667 now checks eviction after the restart. 
Here the restart test covers the right side too: a right outer join fails for 
the right input, and inner and left semi joins continue.



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