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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,73 @@ 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. With allowMultiple, an input that eviction 
picks another column
+  // for counts too, since its state keeps rows of any event time. 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 ||
+              SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE) &&

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.
   
   Fixed. A query restarted from a checkpoint written before the join output 
watermark check keeps the earlier eviction for an input that would be evicted 
by another column: that input is evicted by its event time again, with the 
earlier NULL handling and left semi skip, while the check still logs its 
warning. So a later operator receives what it received before the upgrade. A 
new query gets the new eviction and the check's error. New tests restart a 
state format 2 query with a window count from such a checkpoint, and the Spark 
4.3 state format 4 checkpoint, which now restarts with the earlier results.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,73 @@ 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 " +

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.
   
   Fixed: the message now says that the state of that input has no cutoff on 
its event time, and suggests a range condition that bounds the event time of 
that input by the other input's watermark. The scaladoc, the doc of the conf 
and the migration entry say the same.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +740,44 @@ case class StreamingSymmetricHashJoinExec(
         Predicate.create(Literal(false), Seq.empty).eval _ // false = do not 
remove if no predicate
     }
 
+    private[this] var updatedStateRowsCount = 0
+    private[this] var numRemovedFromOtherSideDuringJoinCount = 0
+    private[this] val allowMultipleStatefulOperators: Boolean =
+      conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+
+    // When the default mode picked the column that the value predicate tests 
because the join
+    // condition bounds it, a row with a NULL in it can never match, and 
`column <= cutoff` never
+    // holds for it. The legacy mode, and the default mode for an input 
bounded only through a
+    // column cast to TIMESTAMP, test the event time, which the condition need 
not bound.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _, true)) =>
+        Predicate.create(IsNull(column), inputAttributes).eval _
+      case _ => _ => false
+    }
+
+    // Such a row is not stored, but an earlier version or the legacy mode can 
have stored one.
     private[this] val stateValueWatermarkPredicateFunc = 
stateWatermarkPredicate match {
-      case Some(JoinStateValueWatermarkPredicate(expr, _, _)) =>
+      case Some(JoinStateValueWatermarkPredicate(expr @ 
LessThanOrEqual(column, _), _, _, true)) =>
+        Predicate.create(Or(expr, IsNull(column)), inputAttributes).eval _
+      case Some(JoinStateValueWatermarkPredicate(expr, _, _, _)) =>
         Predicate.create(expr, inputAttributes).eval _
       case _ =>
         Predicate.create(Literal(false), Seq.empty).eval _  // false = do not 
remove if no predicate
     }
 
-    private[this] var updatedStateRowsCount = 0
-    private[this] var numRemovedFromOtherSideDuringJoinCount = 0
-    private[this] val allowMultipleStatefulOperators: Boolean =
-      conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+    // A left semi join processes its right input first, so this batch's left 
rows can still match
+    // a right row that the completion check skips (SPARK-61380). Earlier 
versions tested it against
+    // the cutoff on the event time solved over the whole input, which a 
picked column can exceed.
+    private[this] val skipsEvictingRightRow: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(p: JoinStateValueWatermarkPredicate) if 
p.conditionBoundsColumn &&
+          joinType == LeftSemi && joinSide == RightSide =>
+        val cutoff = 
StreamingJoinHelper.getStateValueWatermark(AttributeSet(inputAttributes),
+          AttributeSet(left.output), condition.full, 
eventTimeWatermarkForEviction)
+        
WatermarkSupport.watermarkExpression(WatermarkSupport.findEventTimeColumn(inputAttributes,

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.
   
   This is the same as master: master also skips the right row (1, 8 h, 12 h), 
because it tests the event time against the same whole-input cutoff, and loses 
that match for every join type. This PR keeps master's skip for left semi 
joins, so it is not worse; storing the rows that the picked column keeps is 
tracked with [SPARK-61380](https://issues.apache.org/jira/browse/SPARK-61380) 
(#60307).



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +740,44 @@ case class StreamingSymmetricHashJoinExec(
         Predicate.create(Literal(false), Seq.empty).eval _ // false = do not 
remove if no predicate
     }
 
+    private[this] var updatedStateRowsCount = 0
+    private[this] var numRemovedFromOtherSideDuringJoinCount = 0
+    private[this] val allowMultipleStatefulOperators: Boolean =
+      conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+
+    // When the default mode picked the column that the value predicate tests 
because the join
+    // condition bounds it, a row with a NULL in it can never match, and 
`column <= cutoff` never
+    // holds for it. The legacy mode, and the default mode for an input 
bounded only through a
+    // column cast to TIMESTAMP, test the event time, which the condition need 
not bound.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _, true)) =>
+        Predicate.create(IsNull(column), inputAttributes).eval _
+      case _ => _ => false
+    }
+
+    // Such a row is not stored, but an earlier version or the legacy mode can 
have stored one.
     private[this] val stateValueWatermarkPredicateFunc = 
stateWatermarkPredicate match {
-      case Some(JoinStateValueWatermarkPredicate(expr, _, _)) =>
+      case Some(JoinStateValueWatermarkPredicate(expr @ 
LessThanOrEqual(column, _), _, _, true)) =>
+        Predicate.create(Or(expr, IsNull(column)), inputAttributes).eval _
+      case Some(JoinStateValueWatermarkPredicate(expr, _, _, _)) =>
         Predicate.create(expr, inputAttributes).eval _
       case _ =>
         Predicate.create(Literal(false), Seq.empty).eval _  // false = do not 
remove if no predicate
     }
 
-    private[this] var updatedStateRowsCount = 0
-    private[this] var numRemovedFromOtherSideDuringJoinCount = 0
-    private[this] val allowMultipleStatefulOperators: Boolean =
-      conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+    // A left semi join processes its right input first, so this batch's left 
rows can still match
+    // a right row that the completion check skips (SPARK-61380). Earlier 
versions tested it against
+    // the cutoff on the event time solved over the whole input, which a 
picked column can exceed.
+    private[this] val skipsEvictingRightRow: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(p: JoinStateValueWatermarkPredicate) if 
p.conditionBoundsColumn &&
+          joinType == LeftSemi && joinSide == RightSide =>
+        val cutoff = 
StreamingJoinHelper.getStateValueWatermark(AttributeSet(inputAttributes),
+          AttributeSet(left.output), condition.full, 
eventTimeWatermarkForEviction)
+        
WatermarkSupport.watermarkExpression(WatermarkSupport.findEventTimeColumn(inputAttributes,
+          allowMultipleEventTimeColumns = false), cutoff)
+          .map(Predicate.create(_, inputAttributes).eval _).getOrElse((_: 
UnsafeRow) => false)

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.
   
   Fixed: where the value predicate tests the event time with the same cutoff, 
the skip reuses it, so no second predicate is compiled.



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -23,6 +23,33 @@ 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 stream-stream join evicts the state of an input with its 
own watermark by
+  another TIMESTAMP column of that input when the join condition limits how 
long a row of that
+  input can match only through that column, for example through `expiry` in
+  `rightTime BETWEEN leftTime AND expiry`. Earlier versions evicted by the 
event time, and could
+  emit outer join rows too early and lose matches. Such a join can emit rows 
below its output
+  watermark, which still assumes eviction by the event time, so in append mode 
a new query fails
+  when an operator that drops late rows follows it, as described below for an 
input whose state
+  is never evicted. In such a join, and in a time-interval join such as
+  `rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES`, a row whose 
eviction column is
+  NULL can never match: an outer join now emits it when it arrives, and no 
join keeps it in state.
+  With state format versions 1 to 3, such rows that a checkpoint of an earlier 
version holds are
+  evicted, and emitted by an outer join, after the upgrade. With state format 
version 4, a join
+  evicted by another column cannot restart from a checkpoint of an earlier 
version, or after a
+  change of `spark.sql.streaming.statefulOperator.allowMultiple`; start it 
with a new checkpoint.
+  With state format versions 1 to 3, it restarts, and rows that an earlier 
version evicted are
+  not restored. With `spark.sql.streaming.statefulOperator.allowMultiple` set 
to false, joins keep

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.
   
   We keep the legacy mode as the way back, as answered before: a setting that 
restores only the earlier eviction would also restore its wrong results. A 
query restarted from an existing checkpoint now keeps the earlier eviction for 
inputs evicted by another column.



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