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


##########
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) {
+        // case 2 in the StreamingSymmetricHashJoinExec docs. The opposite 
watermark bounds the
+        // future matches, so this input needs no watermark of its own, except 
in the legacy mode.
+        val eventTime = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+        // The legacy mode with a single global watermark keeps applying a 
cutoff on any column of
+        // this input to the event time.
+        def solve(watermark: Option[Long]): Option[(Attribute, Long)] =
+          if (useFirstEventTimeColumn) {
+            StreamingJoinHelper.getStateValueWatermark(
+              attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
+              attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
+              condition,
+              watermark).map(eventTime.get -> _)
+          } else {
+            
StreamingJoinHelper.getStateValueWatermarkColumn(oneSideInputAttributes,

Review Comment:
   Thanks, with the guard a new query of this shape now fails instead of 
dropping rows. This review separately raises the restart case: a query 
restarted from a checkpoint written before this change only gets the guard's 
warning, and on state formats 1 to 3 it keeps dropping those rows.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4616191497","thread_id":"inline:4616191497","verdict_sha256":"ae199837c9a0b5345171834127c364b9ce9c0bb97b153e06a3472611a4380037"}
 -->



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

Review Comment:
   **Blocking (P1):** For a checkpoint written before this change, the offset 
log restores `spark.sql.streaming.statefulOperator.checkJoinOutputWatermark` as 
false, so `failWhenDetected` is false and the check only logs a warning, also 
for a join that this change starts evicting by another TIMESTAMP column. 
Reading the code for a state format 2 left outer join on `leftKey = rightKey 
AND rightTime BETWEEN leftTime AND expiry`, followed by an append-mode 
`groupBy(window(leftTime, '1 minute')).count()` with 60-second watermarks: the 
base branch emits two unmatched left rows with leftTime 100 s and expiry 700 s 
once the watermark reaches 340 s, while the aggregation's late-row watermark is 
still about 40 s, so it counts them. After a restart on this change, the join 
keeps them until the watermark passes their expiry and emits them when that 
late-row watermark is about 340 s, so the aggregation drops both and never 
emits their window, with only a warning in the driver log. New queries of 
 this shape fail the check and state format 4 restarts fail the layout check, 
so the drop is limited to state format 1 to 3 restarts.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60669#discussion_r4616191497).
   
   **Recommended change:** Make the chained-operator check fail when the 
flagged input is one that the default mode evicts by another TIMESTAMP column, 
also for a query restarted from a checkpoint without the check's conf, and keep 
the restart warning only for inputs without any state cutoff, whose drops the 
base branch already had; 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled set to false 
still turns the failure into a warning. Update the migration guide to say that 
such restarted queries fail and need a new checkpoint, and add a join restart 
test from a checkpoint without the conf.
   
   **Why this works:** A restarted query of this shape then fails at its first 
batch, before any row reaches the later operator, instead of running with an 
output watermark that its new eviction violates, while queries whose drops 
predate the change keep running with the warning, so no query that only had the 
base branch's drops starts failing.
   
   **Risks:** Restarted queries of this shape that ran on the base branch now 
fail at their first batch and need a new checkpoint; setting 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled to false rolls 
the failure back to a warning and brings the drops back.
   
   **Constraints:** The failure applies only to the pairs of input and 
late-row-dropping operator that the check flags once it relates the input to 
the operator's event-time column, so a restarted query whose operator never 
reads the flagged input's event time keeps running. Inputs without any state 
cutoff keep the warning on restart.
   
   **Exclusions:**
   - Correcting the join's output watermark for inputs evicted by another 
TIMESTAMP column, which the pull request defers to SPARK-62001.
   
   **Verification:**
   - **Regression:** A state format 2 left outer join on leftKey = rightKey AND 
rightTime BETWEEN leftTime AND expiry with an append-mode window count on 
leftTime, restarted from a checkpoint whose offset log lacks the check's conf, 
fails at its first batch instead of running and dropping the unmatched rows.
   - **Compatibility:** A key-only join before a window aggregation restarted 
from a checkpoint without the conf still runs and logs the warning, and with 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled set to false the 
restarted join evicted by another TIMESTAMP column only logs the warning.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -261,28 +266,65 @@ 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 =>
+      } else if (isWatermarkDefinedOnInput || !useFirstEventTimeColumn) {

Review Comment:
   **Blocking (P1):** Since this condition lets an input without its own 
watermark take the range path, the solver's cutoff now applies to it, and the 
solver passes a cast to a whole number of seconds through as the exact value, 
whether the cast is on this input's column or on the other input's. Reading the 
code for a left outer join with a 1-second watermark only on `rt` and `leftKey 
= rightKey AND CAST(lt AS LONG) >= CAST(rt AS LONG) - 5`: at a watermark of 
19.5 s the cutoff on `lt` is 14.499 s, so the left row (1, 14.2 s) is evicted 
and emitted with nulls, although right (1, 19.6 s) passes the late-row filter 
and matches it, since `CAST(14.2 AS LONG)` is 14 and `CAST(19.6 AS LONG) - 5` 
is 14. An inner join loses that match, and `CAST(lt AS DOUBLE) >= CAST(rt AS 
LONG) - 5` fails the same way. The base branch never evicted such an input, so 
it returned these matches. Ignoring, for an input without its own watermark, 
the conjuncts that the solver already marks as truncating would kee
 p the base branch's behavior for such bounds while exact bounds still evict, 
and the SPARK-62044 TODO above `solve` could name these casts.
   
   **Verification:**
   - **Regression:** With a left input without a watermark and a right input 
watermarked with a one-second delay, inner and left outer joins on leftKey = 
rightKey AND CAST(lt AS LONG) >= CAST(rt AS LONG) - 5, and on leftKey = 
rightKey AND CAST(lt AS DOUBLE) >= CAST(rt AS LONG) - 5, return the match of 
left (1, 14.2 s) with right (1, 19.6 s) that arrives after the watermark 
reaches 19.5 s, without a null row for the left row, on state formats 2 and 4.
   - **Compatibility:** One-sided joins whose input without a watermark is 
bounded by an exact range, such as leftTime BETWEEN rightTime - INTERVAL 5 
SECONDS AND rightTime + INTERVAL 5 SECONDS, still evict that input and emit its 
unmatched rows at the same batches on state formats 2 to 4.



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

Review Comment:
   **Blocking (P1):** This loop flags every stream-stream join below an 
operator that drops late rows, and `joinInputWithoutStateCutoff` decides from 
the join condition alone, so an input whose event time never reaches that 
operator's late-row filter still fails the query. Reading the code, an inner 
join on `leftKey = rightKey AND rightTime <= leftTime + INTERVAL 10 SECONDS` 
with both inputs watermarked, followed by `groupBy(window(leftTime, '10 
seconds')).count()` in append mode, now fails its first batch because the right 
input has no cutoff. The aggregation reads only leftTime, the left state is 
evicted at the watermark minus 10 seconds, and the join's output watermark is 
that cutoff, so every joined row's leftTime lies above the aggregation's 
late-row watermark and the base branch returns every count. A later 
stream-stream join whose side carrying the flagged join has no event-time 
column left is rejected the same way, and the only way to run either query is 
to set `spark.sql.str
 eaming.statefulOperator.checkCorrectness.enabled` to false, which relaxes the 
other chained-operator checks too.
   
   **Recommended change:** Make the chained-operator check pair each operator 
that drops late rows with the event-time column its late-row filter reads, and 
flag a stream-stream join input below it only when that column is, or is 
computed from, the input's own event time; for a later stream-stream join, 
check each of its sides only against the joins in that side's subtree. Where 
the check cannot follow the column, it keeps flagging the input. Add join tests 
for the shapes that now run again.
   
   **Why this works:** A late-row filter drops a row only by the event-time 
column it reads, so the rows of an input whose event time never reaches that 
column cannot be dropped as late; flagging only the inputs that do reach it 
removes the false rejections, while every shape the check rejects for a real 
risk, such as a key-only join or a one-sided bound aggregated on the unbounded 
input's time, still pairs the flagged input with the operator.
   
   **Risks:** Queries that now fail at their first batch run again; if the 
column tracing were too permissive for an unusual plan, such a query would drop 
joined rows as it did on the base branch, so the tracing must stay conservative 
wherever it cannot follow a column.
   
   **Constraints:** The pairing must mirror how the physical operators choose 
their event-time column, including a window built from the event time. The 
restart enforcement for inputs evicted by another TIMESTAMP column must apply 
to exactly the pairs this check flags.
   
   **Exclusions:**
   - Update mode, which the check's existing TODO leaves unchecked.
   
   **Verification:**
   - **Regression:** A new append-mode query with both inputs watermarked, an 
inner join on leftKey = rightKey AND rightTime <= leftTime + INTERVAL 10 
SECONDS and a window count on leftTime runs across several batches and returns 
the same counts as the base branch.
   - **Regression:** A key-only stream-stream join whose output keeps no 
event-time column of its inputs, followed by a later stream-stream join with 
another watermarked input, runs instead of failing at its first batch.
   - **Compatibility:** A key-only join before a window aggregation or a 
deduplication, a one-sided bound aggregated on the unbounded input's time, and 
a join evicted by another TIMESTAMP column before a window aggregation on that 
input's event time still fail at their first batch, and only log a warning with 
the correctness check disabled.



##########
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 " +

Review Comment:
   **Nit (P3):** `throwError` wraps this new failure in 
`_LEGACY_ERROR_TEMP_3102`, whose message is only `<msg>` and which has no 
SQLSTATE, while `common/utils/src/main/resources/error/README.md` says not to 
introduce new uncategorized errors. Clients that handle errors by condition or 
SQLSTATE, including Spark Connect and PySpark clients, can recognize this 
failure only by its text, and naming it later would change a user-visible error 
a second time; the change's other new failure already uses the named 
`STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE`. A new condition in 
error-conditions.json, with a SQLSTATE and the side as a parameter, would fix 
it and could carry a corrected message.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +753,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),

Review Comment:
   **Blocking (P1):** This call uses the solver's default `risingCutoffsOnly = 
true`, so the skip's threshold is not the base branch's whole-input cutoff when 
the condition also has a conjunct with a negative watermark term, which the 
base branch's minimum included. A left semi join processes its right input 
first, so a right row that this threshold skips can still match a left row of 
the same micro-batch whose late-row filter lags the eviction watermark. Reading 
the code for `l.k = r.k AND l.t BETWEEN r.e - INTERVAL 1 HOUR AND r.e AND 
CAST(l.t AS LONG) + CAST(r.e AS LONG) > 100` with delay 0: after a batch at 10 
h, a data batch that runs before any no-data batch evicts at 10 h but filters 
late rows at 0. The base branch's threshold, the minimum of 10 h - 1 ms and the 
falling 100 s - 10 h, stores right (1, 8 h), and left (1, 7.5 h) emits its 
match; here the threshold is 10 h - 1 ms, the right row is not stored and (1, 
7.5 h) is never emitted. Passing `risingCutoffsOnly = false` here 
 gives the base branch's threshold; it only keeps more right rows, which the 
end-of-batch eviction still removes.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60669#discussion_r4627362484).
   
   **Verification:**
   - **Regression:** In the default mode, a left semi join on l.k = r.k AND l.t 
BETWEEN r.e - INTERVAL 1 HOUR AND r.e AND CAST(l.t AS LONG) + CAST(r.e AS LONG) 
> 100 with delay 0 on both inputs, given a batch with events at 10 hours on 
both inputs and then, in one micro-batch before any no-data batch, right (1, e 
= 8 h) and left (1, t = 7.5 h), emits (1, 7.5 h) on state formats 2 and 4.
   - **Compatibility:** The left semi join whose bound on rx holds the cutoff 
at 7 hours still emits its same-batch match, and the right rows evicted at the 
end of each batch are unchanged.



##########
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:
   **Nit (P3):** This text, the scaladoc of 
`checkStreamStreamJoinOutputWatermark` and the doc of 
`spark.sql.streaming.statefulOperator.checkJoinOutputWatermark` describe every 
flagged input as one whose state has no cutoff, but with allowMultiple 
`joinInputWithoutStateCutoff` also flags an input that a range condition bounds 
through another TIMESTAMP column and that eviction removes by that column. For 
`leftKey = rightKey AND rightTime BETWEEN leftTime AND expiry` before a window 
aggregation on leftTime, which the new suite rejects with this text, the user 
is told that the left input has no cutoff and to add a range condition, 
although the condition already bounds it through expiry; only a bound on 
leftTime itself, such as `leftTime >= rightTime - INTERVAL 1 HOUR`, or a 
watermark in the join keys clears the check. A message that tells the two cases 
apart and names a bound on that input's event time as the remedy would match 
what the check detects.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -362,6 +364,45 @@ case class StreamingSymmetricHashJoinExec(
   }
 
   protected override def doExecute(): RDD[InternalRow] = {
+    // Older versions and the legacy mode order the V4 state of an input by 
its event time (index
+    // version 0), so their checkpoints cannot evict that state by another 
column. Index version 1
+    // orders it by the column that the default mode picks, which the legacy 
mode cannot evict.
+    // They keep the rows of an input without an event time out of the index. 
Such rows are never
+    // evicted, which only an outer join that emits the unmatched rows of that 
input cannot accept,
+    // so it fails with a checkpoint written by an earlier version or started 
in the legacy mode.
+    // TODO: [SPARK-62075] A legacy-mode run of a version 1 checkpoint is not 
checked for an input
+    //  without an event time. That input has no predicate in the legacy mode, 
so the rows of the
+    //  run get no index entry, and the default mode never evicts them 
afterwards.
+    val indexVersion = 
conf.getConf(SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION)
+    if (stateFormatVersion == 4 && (indexVersion == 0 || 
!allowMultipleStatefulOperators)) {
+      Seq((LeftSide, stateWatermarkPredicates.left, left.output, right.output),
+          (RightSide, stateWatermarkPredicates.right, right.output, 
left.output)).foreach {
+        case (side, predicate, attributes, otherAttributes) =>
+          val eventTime = WatermarkSupport.findEventTimeColumnIndex(
+            attributes, allowMultipleEventTimeColumns = false)
+          val column = if (indexVersion == 0) {
+            stateValueWatermarkColumnOrdinal(predicate, attributes)
+          } else {
+            predicate.collect { case _: JoinStateValueWatermarkPredicate =>
+              StreamingJoinHelper.getStateValueWatermarkColumn(attributes,
+                AttributeSet(otherAttributes), condition.full, Some(0L))
+            }.flatten.map { case (c, _) => 
attributes.indexWhere(_.semanticEquals(c)) }
+          }
+          val emitsUnmatchedRows = joinType match {
+            case LeftOuter => side == LeftSide
+            case RightOuter => side == RightSide
+            case FullOuter => true
+            case _ => false
+          }
+          column.filterNot(eventTime.contains)
+            .filter(_ => eventTime.isDefined || emitsUnmatchedRows).foreach { 
i =>

Review Comment:
   **Nit (P3):** Every failing restart case in StreamingJoinRangeEvictionSuite 
is a left, right or full outer join whose failing input also emits unmatched 
rows, so `emitsUnmatchedRows` alone makes each one throw, and dropping 
`eventTime.isDefined` from this filter leaves the suite green. An inner or left 
semi join on `rightTime BETWEEN leftTime AND expiry` restarted from an 
index-version-0 checkpoint would then continue, scan an index ordered by 
leftTime with the expiry cutoff, and evict rows that can still match. Inner and 
left semi restarts of that join from such a checkpoint, expecting 
`STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE` for the left input and 
`expiry`, would give the disjunct a failure signal.
   
   **Verification:**
   - **Behavior:** An inner and a left semi join on leftKey = rightKey AND 
rightTime BETWEEN leftTime AND expiry, restarted on state format 4 from a 
checkpoint of index version 0, fail with 
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE naming the left input and 
expiry.



##########
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) &&
+              StreamingJoinHelper.getStateValueWatermarkColumn(input.output, 
other.outputSet,
+                condition, Some(1000000)).exists { case (column, _) => 
!hasEventTimeCol(column) }
+              ) => 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

Review Comment:
   **Nit (P3):** No test reaches this stream-stream join case, the 
`EventTimeTimeout` and `EventTime` cases, the `DeduplicateWithinWatermark` 
case, or the event-time-column precondition of `dropsLateRows`: the suite 
rejects only window aggregations and a `dropDuplicates` whose child keeps an 
event time. Deleting this case, which covers a key-only join that feeds a later 
stream-stream join, inverting the timeout or time-mode cases, or dropping the 
precondition, which would reject a `dropDuplicates` over the join keys alone, 
changes no assertion. Cases in which a key-only join that keeps the unbounded 
input's event time is followed by a later stream-stream join, 
flatMapGroupsWithState with an event-time timeout, transformWithState in 
event-time mode or dropDuplicatesWithinWatermark, each failing, and one with a 
dropDuplicates over the join keys only, which runs, would pin them; the 
PySpark-only operators need a PySpark streaming test.
   
   **Verification:**
   - **Behavior:** A key-only join that keeps the unbounded input's event time, 
followed by a later stream-stream join on it, by flatMapGroupsWithState with an 
event-time timeout, by transformWithState in event-time mode, or by 
dropDuplicatesWithinWatermark, fails its first batch with the check's error, 
and a key-only join followed by a dropDuplicates over the join keys only runs.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -117,6 +121,29 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
     allStateWatermarks.reduceOption((x, y) => Math.min(x, y))
   }
 
+  /**
+   * Get the column that evicts the state of an input, with its state value 
watermark. That is the
+   * event time if the input has one and the condition bounds it, and 
otherwise the first other
+   * TIMESTAMP column in input order that the condition bounds. Each column is 
solved on its own,
+   * so the cutoff applies to the column that the condition bounds.
+   */
+  def getStateValueWatermarkColumn(
+      inputAttributes: Seq[Attribute],
+      attributesWithEventWatermark: AttributeSet,
+      joinCondition: Option[Expression],
+      eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+    val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+    val references = 
joinCondition.map(_.references).getOrElse(AttributeSet.empty)
+    val candidates = eventTime.toSeq ++ inputAttributes.filter { a =>
+      a.dataType == TimestampType && !eventTime.exists(_.semanticEquals(a)) &&
+        references.contains(a)
+    }
+    candidates.iterator.flatMap { a =>
+      getStateValueWatermark(AttributeSet(a), attributesWithEventWatermark, 
joinCondition,

Review Comment:
   Thanks, the right row in this example is now stored and its match emitted. 
This review separately raises a remaining case in which the skip's threshold is 
still higher than master's, so a left semi join can still lose a same-batch 
match that master returned.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4627362484","thread_id":"inline:4627362484","verdict_sha256":"ae199837c9a0b5345171834127c364b9ce9c0bb97b153e06a3472611a4380037"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -66,13 +66,17 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
    * @param attributesWithEventWatermark  attributes of the other side which 
has a watermark column
    * @param joinCondition                 join condition
    * @param eventWatermark                watermark defined on the input event 
data
+   * @param risingCutoffsOnly             whether only conjuncts whose cutoff 
rises with the

Review Comment:
   **Nit (P3):** With the default `true`, the `keepEarlierMinimum` branch of 
this method returns the earlier minimum over all conjuncts, constant-only and 
negative-sign ones included, for a cutoff through a truncating cast and for one 
solved for another column while the event time has no rising cutoff of its own. 
For example, `CAST(leftTime AS LONG) >= CAST(rightTime AS LONG) - 5 AND 
CAST(leftTime AS LONG) > 10` returns 10000, which StreamingJoinHelperSuite 
asserts, and with `CAST(leftTime AS LONG) + CAST(rightTime AS LONG) > 100` as 
the second conjunct it returns 0 at a 100000 ms watermark. Naming both 
exceptions in this doc, and both kinds of conjunct in the comment at that 
branch, would keep callers such as the left semi skip from misjudging which 
rule a call applies.
   
   **Verification:**
   - **Inspection:** The rising-only parameter doc and the comment at the 
earlier-minimum branch match the method's results for a cutoff through a 
truncating cast and for a cutoff solved for another column, including a 
negative-sign conjunct.



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