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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,67 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join whose
+   * state of an input has no cutoff, as 
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+   * operators. It takes the optimized plan, whose join conditions eviction 
uses. 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 =>
+        // TODO: Update mode is not checked, although its aggregations also 
drop late rows.
+        if (outputMode == InternalOutputModes.Append && 
dropsLateRows(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 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):** This matches every Join with two streaming children, including 
one without an equality predicate, which StreamingJoinStrategy rejects only 
later, in physical planning, with 'Stream-stream join without equality 
predicate is not supported.' (SparkStrategies.scala lines 608-610). Reading the 
code, `left.join(right, expr("leftTime > rightTime"))` followed by a 10-second 
window count on leftTime now fails at its first batch with the new message 
naming the right input, and its remedies, a range bounding that input or the 
correctness switch, only lead to the planning error; with the switch off it 
logs the correctness warning first. The same happens when such a join is the 
later operator above a key-only join, and when a window count sits above both 
joins, because the count's subtree still holds the key-only join. Returning 
early from checkStreamStreamJoinOutputWatermark when the plan holds a 
stream-stream join that ExtractEquiJoinKeys does not match keeps the existing 
error
  for all of these.
   
   **Verification:**
   - **Regression:** A join of two 10-second-watermarked streams on leftTime > 
rightTime, followed in Append mode by a 10-second window count on leftTime, 
fails on a new checkpoint with the error saying a stream-stream join without 
equality predicate is not supported, and its message does not mention a state 
cutoff.
   - **Regression:** With 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled set to false, the 
same query fails with the same planning error and logs no warning about a 
stream-stream join input without a cutoff.
   - **Regression:** A key-only join of two watermarked streams, followed by a 
second stream-stream join whose only condition is a time range on a third 
watermarked stream, fails with the planning error about the missing equality 
predicate, not the new message.
   - **Regression:** The same two joins followed by a 10-second window count on 
the first join's left event time also fail with that planning error, not the 
new message.
   - **Compatibility:** The existing rejection, acceptance, warning and restart 
cases of the streaming join output watermark tests, whose joins all have a key 
equality, keep their outcomes.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,67 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join whose
+   * state of an input has no cutoff, as 
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+   * operators. It takes the optimized plan, whose join conditions eviction 
uses. 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 =>
+        // TODO: Update mode is not checked, although its aggregations also 
drop late rows.
+        if (outputMode == InternalOutputModes.Append && 
dropsLateRows(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 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) =>

Review Comment:
   **Nit (P3):** This accepts every join with a watermarked join key, and the 
comment above presents such a key as a cutoff for both inputs. But eviction 
uses each input's own key at the watermarked position 
(StreamingSymmetricHashJoinHelper.scala lines 230-263), so for leftKey = 
rightKey AND leftTime = rightTs, where the right input's event time is 
rightTime, right rows are evicted by rightTs. Reading the code, a stored right 
row whose rightTs is still ahead of the watermark and whose rightTime is old 
can join a later left row and be dropped as late by a window on rightTime, as 
on the base branch. Leaving these inputs to #60667 is fine, but only the 
description says so; a TODO at this case naming inputs evicted by a key other 
than their own event time, with that example and the follow-up, would keep the 
gap visible to readers of the check.
   
   **Verification:**
   - **Inspection:** The comment at the join-keys case of 
joinInputWithoutStateCutoff states that a join with a watermark in its keys can 
evict an input by a key that is not that input's event time, that such inputs 
are not yet checked, and which follow-up covers them; no code outside comments 
changes.



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -23,6 +23,15 @@ Note that this migration guide describes the items specific 
to Structured Stream
 Many items of SQL migration can be applied when migrating Structured Streaming 
to higher versions.
 Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-guide.html).
 
+## Upgrading from Structured Streaming 4.4 to 4.5
+
+- Since Spark 4.5, a new streaming query in append mode fails when its first 
micro-batch is
+  planned if an operator that drops late rows, such as a window aggregation, 
follows a
+  stream-stream join with an input whose state is never evicted, for example a 
join on a key

Review Comment:
   **Nit (P3):** For a left semi join the check looks only at the left input 
(UnsupportedOperationChecker.scala line 198), because only left rows are 
emitted. Under leftKey = rightKey AND leftTime > rightTime - INTERVAL 5 SECONDS 
the right input's state is never evicted, yet a window count on leftTime after 
that left semi join keeps running, as the new test 'accept a left semi join 
bounded on its left input before a window aggregation' asserts; by this 
sentence it would fail. Limiting the sentence to an input whose rows the join 
emits, for example 'a stream-stream join with an input whose rows it emits and 
whose state is never evicted', or naming the left semi exception, fixes it. The 
doc of spark.sql.streaming.statefulOperator.checkJoinOutputWatermark 
(SQLConf.scala lines 4460-4462) and the first sentence of the check's scaladoc 
(UnsupportedOperationChecker.scala lines 160-161) need the same change.
   
   **Verification:**
   - **Inspection:** The 4.5 migration guide entry, the 
checkJoinOutputWatermark conf doc and the check's scaladoc each limit the 
rejected join to an input whose rows the join emits, or name the left semi 
exception, and the behavior of the check is unchanged.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,67 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join whose
+   * state of an input has no cutoff, as 
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+   * operators. It takes the optimized plan, whose join conditions eviction 
uses. 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 =>
+        // TODO: Update mode is not checked, although its aggregations also 
drop late rows.
+        if (outputMode == InternalOutputModes.Append && 
dropsLateRows(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 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
+        }
+    case _ => None
+  }
+
+  // A stateful operator that drops the input rows below its watermark for 
late rows. Its
+  // physical operator filters by an event-time column of its input, so it 
needs one.
+  private def dropsLateRows(p: LogicalPlan): Boolean = p.isStreaming &&
+    p.children.exists(_.output.exists(hasEventTimeCol)) && (p match {
+      case _: Aggregate | _: Distinct | _: Deduplicate | _: 
DeduplicateWithinWatermark => true
+      case Join(left, right, _, _, _) => left.isStreaming && right.isStreaming
+      case f: FlatMapGroupsWithState => f.timeout == 
GroupStateTimeout.EventTimeTimeout
+      case f: FlatMapGroupsInPandasWithState => f.timeout == 
GroupStateTimeout.EventTimeTimeout
+      case t: TransformWithState => t.timeMode == EventTime
+      case t: TransformWithStateInPySpark => t.timeMode == EventTime

Review Comment:
   **Non-blocking (P2):** Only the aggregation and deduplication cases here 
have a failing signal: StreamingJoinOutputWatermarkSuite rejects a window count 
and a dropDuplicates after a key-only join and accepts flatMapGroupsWithState 
without a timeout, and no other suite exercises this check. Deleting the 
DeduplicateWithinWatermark or Join case, comparing the timeouts on lines 
213-214 with another value, or flipping the time-mode comparisons on lines 
215-216 keeps every test green. By the review's reading of the code, a key-only 
join followed by `.select("leftKey", 
"leftTime").groupByKey(...).flatMapGroupsWithState(OutputMode.Append(), 
GroupStateTimeout.EventTimeTimeout())(...)` would again drop the stored left 
row that joins late, since FlatMapGroupsWithStateExec filters late input with 
an event-time timeout (FlatMapGroupsWithStateExec.scala lines 148-149). Making 
the transformWithState cases true would instead reject processing-time queries 
that run correctly on the base branch, al
 so with no failing test.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60713#discussion_r4627142754).
   
   **Recommended change:** Add streaming join output watermark tests in which a 
key-only join of two watermarked inputs, narrowed to the left key and left 
event time as the existing flatMapGroupsWithState case does, is followed in 
Append mode by each late-dropping operator that no test covers yet: 
flatMapGroupsWithState with an event-time timeout, transformWithState in 
EventTime mode, dropDuplicatesWithinWatermark, and a second stream-stream join 
with a third watermarked input on a key equality bounded by a time range. Each 
of these tests expects the rejection naming the left input. Add one more in 
which transformWithState in ProcessingTime mode runs. Cover 
applyInPandasWithState with an event-time timeout, and 
transformWithStateInPandas in EventTime and ProcessingTime mode, with 
plan-level unsupported operation checker tests or with the PySpark stateful 
streaming tests.
   
   **Why this works:** Each new case runs the check on a plan in which the 
operator sits above a join input without a cutoff. Removing the operator's 
branch, or comparing against the wrong timeout or time mode, flips the outcome 
that the case asserts.
   
   **Risks:** PySpark stateful streaming tests run only where the Python test 
environment with pandas and pyarrow is available; plan-level checker cases for 
the Python nodes avoid that dependency.
   
   **Constraints:** Only test code changes; dropsLateRows and the check keep 
their behavior. Narrow the join's output to the left key and left event time 
before the later operator, as the existing flatMapGroupsWithState case does: 
with multiple stateful operators allowed, the default, these operators fail on 
an input with two event-time columns (WatermarkSupport.findEventTimeColumn), so 
a case that keeps both would not run even without the check.
   
   **Exclusions:**
   - Update-mode cases, which the PR defers.
   
   **Verification:**
   - **Regression:** A key-only join of two 10-second-watermarked streams, 
narrowed to the left key and left event time, followed in Append mode by 
flatMapGroupsWithState with an event-time timeout, is rejected at its first 
batch, naming the left input.
   - **Regression:** The same narrowed join followed by transformWithState in 
EventTime mode, by dropDuplicatesWithinWatermark, or by a second stream-stream 
join with a third watermarked input on a key equality whose range bounds that 
input by the left event time, is rejected at its first batch, naming the left 
input.
   - **Regression:** The same narrowed join followed by transformWithState in 
ProcessingTime mode runs on a new checkpoint and hands the user function a 
joined row whose stored left row joins after the watermark has passed that 
row's event time.
   - **Regression:** After the same narrowed key-only join, 
applyInPandasWithState with an event-time timeout and 
transformWithStateInPandas in EventTime mode are rejected, naming the left 
input, and transformWithStateInPandas in ProcessingTime mode is not, whether 
this is checked on the plan or end to end.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -158,6 +159,12 @@ class IncrementalExecution(
     // query started, which the plan must still apply to all the rows that it 
reads, see
     // StreamingV2ScanPushDown.
     StreamingV2ScanPushDown.checkPushedFilters(sparkSession, optimized, 
pushedFilterRewrites)
+    // Unlike the other checks, which run when the query starts, this one runs 
once the confs of
+    // the checkpoint are restored, on the plan that eviction derives from.

Review Comment:
   **Nit (P3):** Right below StreamingV2ScanPushDown.checkPushedFilters, which 
runs on every micro-batch's optimized plan, 'the other checks' reads as that 
call. The checks that run when the query starts are the unsupported operation 
checks in ResolveWriteToStream (ResolveWriteToStream.scala lines 55-65); naming 
them removes the misreading:
   
   ```suggestion
       // Unlike the other unsupported operation checks, which run when the 
query starts, this one
       // runs once the confs of the checkpoint are restored, on the plan that 
eviction derives from.
   ```
   
   **Verification:**
   - **Inspection:** The comment above the call to 
checkStreamStreamJoinOutputWatermark in IncrementalExecution.optimizedPlan 
names the other unsupported operation checks as running when the query starts, 
and nothing in it can be read as saying that the adjacent pushed-filter check 
runs at query start.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,67 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join whose
+   * state of an input has no cutoff, as 
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+   * operators. It takes the optimized plan, whose join conditions eviction 
uses. A query from a

Review Comment:
   **Nit (P3):** The traversal only sees joins below the late-dropping operator 
(subPlan.foreach on line 172), and an optimized plan can still keep a CTE 
definition, a MATERIALIZED one or a non-deterministic one referenced more than 
once (InlineCTE.scala lines 85-98), which leaves a CTERelationRef leaf where 
the join would be. The only caller covers this with InlineCTE(alwaysInline = 
true) (IncrementalExecution.scala lines 165-166), but neither this scaladoc nor 
that call site says why. The SQL CTE test uses a CTE referenced once, which the 
optimizer inlines anyway, so removing the call as redundant keeps every test 
green while joins in kept CTEs go unchecked. Saying here that the plan must 
have its CTE references inlined, and why, would prevent that.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60713#discussion_r4627142785).
   
   **Verification:**
   - **Inspection:** The scaladoc of the check states that its plan must be the 
optimized plan with its CTE references inlined, and that the optimizer keeps 
some CTE definitions, such as MATERIALIZED ones, whose joins the check would 
otherwise miss.



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