spark-test commented on code in PR #60713:
URL: https://github.com/apache/spark/pull/60713#discussion_r4627142770


##########
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 &&
+        !StreamingJoinHelper.isWatermarkInJoinKeys(join) =>
+      Seq(("left", left, right), ("right", right, left)).take(if (joinType == 
LeftSemi) 1 else 2)
+        .collectFirst {
+          case (side, input, other) if input.output.exists(hasEventTimeCol) &&
+              StreamingJoinHelper.getStateValueWatermark(
+                input.outputSet, other.outputSet, condition, 
Some(1000000)).isEmpty => side

Review Comment:
   **Blocking (P1):** `condition` here is the analyzed join's own condition, 
but state eviction uses the planned join, which is built from the optimized 
plan (`SparkStrategies.scala:602-606`, `IncrementalExecution.scala:612-618`). 
For an inner join, `PushPredicateThroughJoin` moves every deterministic filter 
conjunct that references both inputs into the join condition 
(`Optimizer.scala:3420-3441`). So your accepted time-interval case with the 
range moved into a filter,
   
   ```scala
   left.join(right, expr("leftKey = rightKey"))
     .where("rightTime >= leftTime AND rightTime <= leftTime + INTERVAL 10 
SECONDS")
     .groupBy(window($"leftTime", "10 seconds")).count()
   ```
   
   or the same query in SQL with the range in `WHERE`, or as a comma join, 
evicts both inputs on master and, by my reading of the code, returns the 
answers of the in-join form. With this PR its first batch fails with "the state 
of the left input of a stream-stream join has no cutoff", and the message asks 
for a range condition that bounds that input, which the query already has.
   
   See **Shared repair plan 2** in the review body.



##########
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:
   **Blocking (P1):** `isStatefulOperation` answers whether an operator keeps 
state, not whether it drops late input. `flatMapGroupsWithState` and 
`applyInPandasWithState` filter rows by the watermark only with 
`EventTimeTimeout` (`FlatMapGroupsWithStateExec.scala:147-153`), and 
`transformWithState`, in Scala and Python, only in `TimeMode.EventTime` 
(`TransformWithStateExec.scala:420-426`, 
`TransformWithStateInPySparkExec.scala:335-340`).
   
   So for a key-only join of two watermarked inputs followed by 
`groupByKey(...).flatMapGroupsWithState(OutputMode.Append, 
GroupStateTimeout.NoTimeout)(...)`, or by `transformWithState` in 
`TimeMode.ProcessingTime()`, master hands every joined row to the user 
function, including the stored left `(1, 5)` that joins in the last batch of 
your example. Nothing in these queries drops a late row, yet with this PR, by 
my reading of the code, their first batch on a new checkpoint fails with "the 
state of the left input of a stream-stream join has no cutoff", and the only 
way to run them is to turn the whole chained-operator correctness check into a 
warning.
   
   See **Shared repair plan 1** in the review body.



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

Review Comment:
   **Non-blocking (P2):** `subPlan.foreach` only sees joins inside the stateful 
operator's own subtree. For a streaming SQL query that defines the join in a 
`WITH` clause, the analyzed plan keeps `WithCTE`: `CTESubstitution` does not 
inline the CTEs of a query that is not a command 
(`CTESubstitution.scala:72-91`), the aggregate's subtree ends at a 
`CTERelationRef` leaf (`cteOperators.scala:216-224`), and `InlineCTE` runs only 
in the optimizer (`Optimizer.scala:199-200`), which is why `ProgressReporter` 
inlines the CTEs of the same plan itself (`ProgressReporter.scala:556-559`).
   
   So, reading the code, `WITH j AS (SELECT * FROM l JOIN r ON leftKey = 
rightKey) SELECT count(*) FROM j GROUP BY window(leftTime, '10 seconds')` over 
your two watermarked inputs runs and drops the late row without an error or a 
warning, on master and with this PR, while the same query without the `WITH` 
clause is rejected.
   
   See **Shared repair plan 2** in the review body.



##########
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 &&
+        !StreamingJoinHelper.isWatermarkInJoinKeys(join) =>
+      Seq(("left", left, right), ("right", right, left)).take(if (joinType == 
LeftSemi) 1 else 2)
+        .collectFirst {
+          case (side, input, other) if input.output.exists(hasEventTimeCol) &&

Review Comment:
   **Blocking (P1):** This reports the uncut input without asking which input's 
event time the later operators filter by. For your second example with the 
window on `leftTime`, the range gives the left input a state watermark, new 
left rows pass the join's late filter only above the input watermark, and the 
join's output watermark is the minimum of the left state watermark and the 
input watermark (`StreamingSymmetricHashJoinExec.scala:1125-1144`). Reading the 
code, no emitted `leftTime` is ever at or below the aggregation's late-events 
watermark, so master returns the batch answer, while with this PR the query 
fails at its first batch, naming the right input.
   
   The same holds for left or right outer joins whose nullable input has no 
cutoff (the start-time check, `UnsupportedOperationChecker.scala:754-782`, 
requires only the outer input's cutoff) and for full outer joins bounded on one 
side, whenever the later operator uses the bounded input's time. The 
description lists this as a known limit but gives no reason for keeping the 
rule coarse. If you keep it, please say in the description why tracing the 
filtered column was rejected, for example that a trace that misses a path could 
let a wrong result through, so the trade-off can be weighed.
   
   **Recommended change:** In 
UnsupportedOperationChecker.checkStreamStreamJoinOutputWatermark, for each 
late-filtering operator above a stream-stream join, determine the event-time 
attributes it filters by: for an aggregation, its event-time grouping key, the 
only event-time column its physical state store operators receive; for any 
other operator, each event-time column of its input. Trace each such attribute 
down to the join's output through the expressions that define it in 
projections, the Expand that a sliding window adds, window and session-window 
structs, aggregates, filters, unions and nested joins. Reject only when a 
traced attribute depends on an event-time attribute of an input without a 
cutoff, and fall back to rejecting whenever the trace reaches a node it cannot 
see through, such as a user function's output. Keep naming that input in the 
error and keep the warning path. Add streaming join output watermark tests for 
the one-sided range join with a tumbling and with a sl
 iding window on the bounded input's time, the same join with an aggregate 
function over the unbounded input's time, the left outer join bounded only on 
its outer input with the window on that input's time, and their unbounded 
counterparts, which stay rejected.
   
   **Why this works:** Rejecting by the source of the filtered column, instead 
of by the existence of any uncut input, matches execution: the join's output 
watermark bounds a bounded input's event time, so only an uncut input's event 
time can be late for the operator. Taking an aggregation's filtered column from 
its grouping keys, which are all its state store operators receive besides 
aggregation buffers, keeps the trace right on the analyzed plan, where the 
window projection still carries every input column, and on the optimized plan 
alike.
   
   **Compatibility:** Every query whose late-filtering operator filters by an 
uncut input's event time, including both examples in the PR description, stays 
rejected.
   
   **Risks:** A trace that wrongly concluded that a column comes only from a 
bounded input would accept a query that loses rows silently; falling back to 
rejection at every node the trace cannot see through, and a test for each 
traced node kind, bound that risk. Queries whose later operator filters by a 
column derived from both inputs, produced by a user function, or reaching the 
join through a node the trace does not follow, such as a generator, stay 
rejected and can still run with 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled set to false.
   
   **Constraints:** Never accept a query unless the trace shows the filtered 
column derives only from inputs that have a cutoff. Keep the per-input cutoff 
derivation the same as eviction's.
   
   **Exclusions:**
   - Update mode, which the author defers.
   - Inputs evicted by another column, which the PR leaves to a follow-up.
   
   **Verification:**
   - **Regression:** The one-sided range join with a tumbling and with a 
sliding window on the bounded input's time, and the left outer join bounded 
only on its outer input with a window on that input's time, run through enough 
batches to emit a window, with answers equal to the batch answer.
   - **Regression:** The one-sided range join followed by a window aggregation 
on the bounded input's time that also computes max(rightTime) runs with the 
batch answer.
   - **Behavior:** The same joins with the window on the unbounded input's 
time, and a later operator whose event-time column comes out of a user 
function, are rejected at the first batch naming the unbounded input.
   - **Behavior:** A deduplication without an event-time key that keeps only 
the bounded input's event time after the one-sided range join runs on a new 
checkpoint.



##########
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:
   **Nit (P3):** `throwError` wraps `_LEGACY_ERROR_TEMP_3102`, whose message is 
just `<msg>` and which has no SQLSTATE, and the error README says not to 
introduce new uncategorized errors 
(`common/utils/src/main/resources/error/README.md:127`). The file's other 
checks, including the 4.4 `EXCEPT` rejection, use the same helper, but this 
error reaches users only as the cause of a `StreamingQueryException` after 
`start()` has returned, where restart or alerting logic can tell it from other 
unsupported-operation errors only by matching the message text, as the new 
suite's `getMessage.contains` does.
   
   **Verification:**
   - **Behavior:** The cause of a rejected query's StreamingQueryException is 
an AnalysisException with the new condition and the input side as a parameter, 
asserted on the condition and its parameters rather than on the message text.
   - **Behavior:** With 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled set to false, the 
same query logs the warning with the new condition's message and runs.



##########
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:
   **Nit (P3):** The `isStreaming` guard here and the `LeftSemi` special case 
at `UnsupportedOperationChecker.scala:196` are all that keep two common shapes 
accepted: a watermarked stream joined with a static table before a window 
aggregation (without the guard the stream side would be reported, since a 
static side has no watermark to derive a cutoff from), and a left semi join 
bounded only on its left input before one. `StreamingJoinOutputWatermarkSuite` 
runs only inner stream-stream joins, and a search of the streaming test suites 
found no test that puts either shape before a stateful operator in Append mode 
(the left semi case in `MultiStatefulOperatorsSuite` bounds both inputs). A 
later refactor that drops either branch would stop those queries at their first 
batch with every test still passing.
   
   **Verification:**
   - **Regression:** A watermarked stream joined with a static table before a 
window aggregation, in Append mode on a new checkpoint, runs and emits the 
expected windows.
   - **Regression:** A left semi join on leftKey = rightKey AND leftTime > 
rightTime - INTERVAL 5 SECONDS, with both inputs watermarked, before a window 
aggregation on leftTime in Append mode on a new checkpoint, runs and emits the 
expected windows.



##########
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:
   **Nit (P3):** This restarted run only checks that a batch completes 
(`CheckNewAnswer()`), so the warning that checkpoints from earlier versions are 
meant to log is not asserted, and no test restarts from a checkpoint that 
recorded `checkJoinOutputWatermark=true`. A regression that runs the check only 
for batch 0 would let a query restarted from a checkpoint written by this 
version, for example after a first run with `checkCorrectness.enabled=false`, 
keep its silent wrong result, and one that skips the check when the restored 
value is false would drop the warning for old checkpoints; both would pass 
every test in the suite.
   
   **Verification:**
   - **Regression:** A key-only join before a window aggregation, first run 
with the correctness check disabled and then restarted with defaults from the 
same checkpoint, fails when the restarted run's first batch is planned, naming 
the left input.
   - **Regression:** The same query restarted from a checkpoint whose latest 
offset-log entry lacks the new conf runs a batch and logs 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)) {

Review Comment:
   **Nit (P3):** The description defers Update mode, but nothing in the code 
says so: the scaladoc of this check 
(`UnsupportedOperationChecker.scala:159-163`) and the doc of 
`spark.sql.streaming.statefulOperator.checkJoinOutputWatermark` 
(`SQLConf.scala:4460-4463`) read as covering every stateful operator after such 
a join. Inner and left semi stream-stream joins are accepted in Update mode 
(`UnsupportedOperationChecker.scala:551-557`), and an Update-mode aggregation 
drops rows below its late-events watermark (`statefulOperators.scala:989-996`), 
so those queries keep the silent drop. A TODO at this condition naming Update 
mode, and the Append-only scope in both docs, would keep the gap visible to 
whoever picks it up.
   
   **Verification:**
   - **Inspection:** The check's scaladoc and the conf doc state that only 
Append mode is checked, a TODO at the Append-mode condition names the deferred 
Update-mode case, and no code outside comments and the doc string changes.



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

Review Comment:
   **Nit (P3):** A left semi join also emits a matching incoming left row 
directly, without storing it (`StreamingSymmetricHashJoinExec.scala:825-833` 
and `900-902`); what lets the check skip the right input is that only left rows 
are emitted.
   
   ```suggestion
     // watermark of the other input. A left semi join only emits left rows.
   ```
   
   **Verification:**
   - **Inspection:** The comment explaining the left semi case describes the 
join as emitting left rows only, consistent with the left semi branches of the 
stream-stream join (StreamingSymmetricHashJoinExec.scala:825-837), and no 
comment in the check says that only stored left rows are emitted.



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