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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,52 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks for a stateful operator after a stream-stream join whose state of 
an input has no
+   * cutoff, as [[checkStreamingQueryGlobalWatermarkLimit]] does for other 
operators. A query from
+   * a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` only 
logs a warning.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    val failWhenDetected = SQLConf.get.statefulOperatorCorrectnessCheckEnabled 
&&
+      
SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK)
+    try {
+      plan.foreach { subPlan =>
+        if (outputMode == InternalOutputModes.Append && 
isStatefulOperation(subPlan)) {
+          subPlan.foreach {
+            case j: Join if j ne subPlan =>
+              joinInputWithoutStateCutoff(j).foreach { side =>
+                throwError("Detected pattern of possible 'correctness' issue: 
the state of the " +
+                  s"$side input of a stream-stream join has no cutoff, so the 
join can emit its " +
+                  "old rows below its output watermark, and a later stateful 
operator drops them " +
+                  "as late. Add a watermark in the join keys or a range 
condition that bounds " +
+                  "that input by the other input's watermark, or set " +
+                  
"`spark.sql.streaming.statefulOperator.checkCorrectness.enabled` to false.")(j)
+              }
+            case _ =>
+          }
+        }
+      }
+    } catch {
+      case e: AnalysisException if !failWhenDetected =>
+        logWarning(log"${MDC(ANALYSIS_ERROR, e.message)};\n${MDC(QUERY_PLAN, 
plan)}", e)
+    }
+  }
+
+  // An input of a stream-stream join with an event time but no state cutoff, 
as eviction derives
+  // it: no watermark in the join keys, and no range condition that bounds the 
input by the
+  // watermark of the other input. A left semi join only emits stored left 
rows.
+  private def joinInputWithoutStateCutoff(join: Join): Option[String] = join 
match {
+    case Join(left, right, joinType, condition, _) if left.isStreaming && 
right.isStreaming &&

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 two tests: a watermarked stream joined with a static table before a 
window count, and a left semi join bounded only on its left input before a 
window count. Both run and emit the expected window.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOutputWatermarkSuite.scala:
##########
@@ -0,0 +1,163 @@
+/*
+ * 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 org.apache.hadoop.fs.Path
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.{AnalysisException, DataFrame}
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap, 
OffsetSeq, OffsetSeqLog}
+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
+
+/**
+ * A stateful operator after a stream-stream join whose state of an input has 
no cutoff. The join
+ * forwards its input watermark, so the operator would drop the old rows that 
the join emits.
+ */
+class StreamingJoinOutputWatermarkSuite extends StreamTest {
+  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)
+
+  private def input(side: String): (MemoryStream[(Int, Long)], DataFrame) = {
+    val stream = MemoryStream[(Int, Long)]
+    (stream, stream.toDF().toDF(s"${side}Key", "seconds")
+      .select(col(s"${side}Key"), 
timestamp_seconds($"seconds").as(s"${side}Time"))
+      .withWatermark(s"${side}Time", "10 seconds"))
+  }
+
+  // A window count over the join of the two inputs.
+  private def countJoined(condition: String, time: String)
+      : (MemoryStream[(Int, Long)], MemoryStream[(Int, Long)], DataFrame) = {
+    val (leftInput, left) = input("left")
+    val (rightInput, right) = input("right")
+    val result = left.join(right, expr(condition))
+      .groupBy(window(col(time), "10 seconds")).count()
+      .select($"window.start".cast("long"), $"count")
+    (leftInput, rightInput, result)
+  }
+
+  private val keyOnly = "leftKey = rightKey"
+
+  private def expectRejected(side: String): StreamAction = 
ExpectFailure[AnalysisException](
+    e => assert(e.getMessage.contains(
+      s"the state of the $side input of a stream-stream join has no cutoff")),
+    typeIsSuperClass = true)
+
+  for (version <- Seq(2, 4)) {
+    test(s"reject a key-only join before a window aggregation, V$version") {
+      withJoinConf(version) {
+        val (leftInput, _, result) = countJoined(keyOnly, "leftTime")
+        testStream(result)(AddData(leftInput, (1, 5L)), expectRejected("left"))
+      }
+    }
+
+    test(s"reject a range join bounded on one side only before a window 
aggregation, V$version") {
+      withJoinConf(version) {
+        val (leftInput, _, result) = countJoined(
+          "leftKey = rightKey AND rightTime <= leftTime + INTERVAL 10 
SECONDS", "rightTime")
+        testStream(result)(AddData(leftInput, (1, 5L)), 
expectRejected("right"))
+      }
+    }
+
+    test(s"accept a time-interval join before a window aggregation, 
V$version") {
+      withJoinConf(version) {
+        val (leftInput, rightInput, result) = countJoined(
+          "leftKey = rightKey AND rightTime BETWEEN leftTime AND leftTime + 
INTERVAL 10 SECONDS",
+          "leftTime")
+        testStream(result)(
+          MultiAddData(leftInput, (1, 5L))(rightInput, (1, 8L)), 
CheckNewAnswer(),
+          MultiAddData(leftInput, (2, 40L))(rightInput, (2, 40L)), 
CheckNewAnswer(),
+          AddData(rightInput, (2, 41L)), CheckNewAnswer((0L, 1L)))
+      }
+    }
+
+    test(s"accept a window-key join before a window aggregation, V$version") {
+      withJoinConf(version) {
+        val (leftInput, left) = input("left")
+        val (rightInput, right) = input("right")
+        val result = left.select($"leftKey".as("key"), window($"leftTime", "10 
seconds"))
+          .join(right.select($"rightKey".as("key"), window($"rightTime", "10 
seconds")),
+            Seq("key", "window"))
+          .groupBy("window").count()
+          .select($"window.start".cast("long"), $"count")
+        testStream(result)(
+          MultiAddData(leftInput, (1, 5L))(rightInput, (1, 8L)), 
CheckNewAnswer(),
+          MultiAddData(leftInput, (2, 40L))(rightInput, (2, 40L)), 
CheckNewAnswer(),
+          AddData(rightInput, (2, 41L)), CheckNewAnswer((0L, 1L)))
+      }
+    }
+  }
+
+  test("a key-only join before a window aggregation only warns with the check 
disabled") {
+    withJoinConf(4) {
+      withSQLConf(SQLConf.STATEFUL_OPERATOR_CHECK_CORRECTNESS_ENABLED.key -> 
"false") {
+        val (leftInput, rightInput, result) = countJoined(keyOnly, "leftTime")
+        val logAppender = new LogAppender("join output watermark")
+        withLogAppender(logAppender, level = Some(Level.WARN)) {
+          testStream(result)(
+            MultiAddData(leftInput, (1, 5L))(rightInput, (1, 5L)), 
CheckNewAnswer())
+        }
+        
assert(logAppender.loggingEvents.exists(_.getMessage.getFormattedMessage.contains(
+          "the state of the left input of a stream-stream join has no 
cutoff")))
+      }
+    }
+  }
+
+  test("a key-only join before a window aggregation keeps running from an 
older checkpoint") {
+    withJoinConf(4) {
+      withTempDir { checkpoint =>
+        val (leftInput, rightInput, result) = countJoined(keyOnly, "leftTime")
+        val start = StartStream(checkpointLocation = 
checkpoint.getCanonicalPath)
+        withSQLConf(SQLConf.STATEFUL_OPERATOR_CHECK_CORRECTNESS_ENABLED.key -> 
"false") {
+          testStream(result)(start,
+            MultiAddData(leftInput, (1, 5L))(rightInput, (1, 5L)), 
CheckNewAnswer(), StopStream)
+        }
+        removeCheckJoinOutputWatermark(checkpoint)
+        testStream(result)(start,

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. The restart test now first restarts from a checkpoint of this version 
(recorded true) and expects the rejection, then removes the conf from the 
offset log, restarts, and asserts the warning naming the left input.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,52 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks for a stateful operator after a stream-stream join whose state of 
an input has no
+   * cutoff, as [[checkStreamingQueryGlobalWatermarkLimit]] does for other 
operators. A query from
+   * a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` only 
logs a warning.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    val failWhenDetected = SQLConf.get.statefulOperatorCorrectnessCheckEnabled 
&&
+      
SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK)
+    try {
+      plan.foreach { subPlan =>
+        if (outputMode == InternalOutputModes.Append && 
isStatefulOperation(subPlan)) {
+          subPlan.foreach {
+            case j: Join if j ne subPlan =>
+              joinInputWithoutStateCutoff(j).foreach { side =>
+                throwError("Detected pattern of possible 'correctness' issue: 
the state of the " +

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.
   
   Kept. The check extends the chained-operator correctness check, which 
reports through the same `_LEGACY_ERROR_TEMP_3102` helper as every other check 
in this file. A new condition only for this case would make the two parts of 
one check report differently. Moving the file's checks to named conditions is 
better done for all of them at once.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,52 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks for a stateful operator after a stream-stream join whose state of 
an input has no
+   * cutoff, as [[checkStreamingQueryGlobalWatermarkLimit]] does for other 
operators. A query from
+   * a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` only 
logs a warning.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    val failWhenDetected = SQLConf.get.statefulOperatorCorrectnessCheckEnabled 
&&
+      
SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK)
+    try {
+      plan.foreach { subPlan =>
+        if (outputMode == InternalOutputModes.Append && 
isStatefulOperation(subPlan)) {

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.
   
   Done: a TODO at the append-mode condition names the Update-mode case, and 
the scaladoc and the conf doc now say the check covers append mode only.



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