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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,89 @@ 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:
   Thanks, the fix holds: a query restarted from a checkpoint written before 
this change now keeps the earlier eviction for the crossed-key, expiry and 
right outer joins, so its later operator receives the rows it received before 
the upgrade. This review raises a related issue: the warning that such a 
restart still logs says the input has no cutoff on its event time, which no 
longer describes how that query evicts it.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4641996805","thread_id":"inline:4641996805","verdict_sha256":"9ac547afeb4eb00a58f39d2b74a380b19b9d268a60ce654af6f33d612404fa8c"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,133 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join that
+   * emits the rows of an input whose state has no cutoff on its event time, as
+   * [[checkStreamingQueryGlobalWatermarkLimit]] does for other operators. It 
takes the optimized
+   * plan, whose join conditions eviction uses, with its CTE references 
inlined: the optimizer
+   * keeps some CTE definitions, such as MATERIALIZED ones, whose joins would 
be missed. A query
+   * from a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` 
only logs a warning,
+   * and its join keeps evicting by the event time an input that would 
otherwise be evicted by
+   * another column.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    // A stream-stream join without an equality predicate fails in planning 
with its own error.
+    val hasJoinWithoutEquality = plan.exists {
+      case j @ Join(l, r, _, _, _) => l.isStreaming && r.isStreaming &&
+        ExtractEquiJoinKeys.unapply(j).isEmpty
+      case _ => false
+    }
+    if (hasJoinWithoutEquality) {
+      return
+    }
+    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 =>
+              // An input counts unless the operator's event times come only 
from other inputs.
+              val sources = eventTimeSources(subPlan, j)
+              joinInputWithoutStateCutoff(j,
+                  input => 
sources.forall(_.exists(input.outputSet.contains))).foreach { side =>
+                throwError("Detected pattern of possible 'correctness' issue: 
the state of the " +
+                  s"$side input of a stream-stream join has no cutoff on its 
event time, so the " +
+                  "join can emit its old rows below its output watermark, and 
a later stateful " +
+                  "operator drops them as late. Add a range condition that 
bounds the event time " +
+                  "of that input by the other input's watermark, or a 
watermark on the same join " +
+                  "key of both inputs, 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.
+  // TODO: An input that earlier versions also evicted by a join key other 
than its event time is
+  //   not checked yet, such as the right input of `leftKey = rightKey AND 
leftTime = rightTs`.
+  private def joinInputWithoutStateCutoff(
+      join: Join, counts: LogicalPlan => Boolean): 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)
+        .filter { case (_, input, _) => counts(input) }
+        .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
+        }
+    // With allowMultiple, an input is evicted by its equality key that the 
other input's
+    // watermark bounds. Where that is neither the key earlier versions 
evicted both inputs by
+    // nor the input's event time, its state keeps rows of any event time.
+    case ExtractEquiJoinKeys(joinType, leftKeys, rightKeys, _, _, left, right, 
_)
+        if left.isStreaming && right.isStreaming &&
+          SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE) =>
+      def watermarked(keys: Seq[Expression]): Option[Int] = 
Some(keys.indexWhere {
+        case ne: NamedExpression => 
ne.metadata.contains(EventTimeWatermark.delayKey)
+        case _ => false
+      }).filter(_ >= 0)
+      val shared = watermarked(leftKeys).orElse(watermarked(rightKeys))
+      Seq(("left", leftKeys, rightKeys, left), ("right", rightKeys, leftKeys, 
right))
+        .take(if (joinType == LeftSemi) 1 else 2)
+        .filter { case (_, _, _, input) => counts(input) }
+        .collectFirst {
+          case (side, keys, otherKeys, _) if watermarked(otherKeys).exists { i 
=>
+            !shared.contains(i) && watermarked(Seq(keys(i))).isEmpty } => side
+        }
+    case _ => None
+  }
+
+  // The columns of `join`'s output that the event-time columns of 
`operator`'s input are computed
+  // from, or None when the path from the operator down to the join has a node 
other than a
+  // projection, a filter, a watermark or an expansion, such as the one of a 
sliding window.
+  private def eventTimeSources(operator: LogicalPlan, join: Join): 
Option[AttributeSet] = {
+    def trace(plan: LogicalPlan, attrs: AttributeSet): Option[AttributeSet] = 
plan match {
+      case p if p eq join => Some(attrs)
+      case Project(list, child) =>
+        trace(child, AttributeSet(list.filter(e => 
attrs.contains(e.toAttribute))
+          .flatMap(_.references)))
+      case Filter(_, child) => trace(child, attrs)
+      case w: EventTimeWatermark => trace(w.child, attrs)
+      case Expand(projections, output, child) =>
+        trace(child, AttributeSet(output.indices.filter(i => 
attrs.contains(output(i)))
+          .flatMap(i => projections.flatMap(_(i).references))))
+      case _ => None
+    }
+    operator.children.find(_.exists(_ eq join)).flatMap { child =>
+      trace(child, AttributeSet(child.output.filter(hasEventTimeCol)))

Review Comment:
   **Blocking (P1):** By the review's reading of the code, the trace starts 
from every event-time column of the operator's input and returns None at any 
node other than a projection, filter, watermark or expansion (line 267), so 
every input of the join counts. In append mode with 10-second watermarks on 
both times, `left.join(right, expr("leftKey = rightKey AND rightTime <= 
leftTime + INTERVAL 10 SECONDS")).groupBy(window($"leftTime", "10 
seconds")).agg(max($"rightTime"))` fails at its first batch: max(rightTime) 
keeps rightTime in the aggregation's input, so the right input, whose state has 
no cutoff, is flagged, although the aggregation filters late rows only by its 
window on leftTime, which the join's output watermark bounds. The same join 
followed by repartition(2) or by a join with a static table, and then a window 
count on leftTime, is rejected because the trace stops there; 
StreamingJoinOutputWatermarkSuite expects that rejection for repartition(2) 
while it accepts the same qu
 ery without the repartition. On the base branch these queries run and drop 
nothing, and here only turning off 
`spark.sql.streaming.statefulOperator.checkCorrectness.enabled` lets a new 
query of these shapes start. Your reply says that #60713's e4ec72eccf8 fixes 
both cases; this branch does not include that commit yet.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60668#issuecomment-7092365469), 
[2](https://github.com/apache/spark/pull/60668#discussion_r4641996825).
   
   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:
##########
@@ -697,11 +736,18 @@ case class StreamingSymmetricHashJoinExec(
       stateFormatVersion = stateFormatVersion,
       skippedNullValueCount = skippedNullValueCount,
       joinStoreGenerator = joinStateManagerStoreGenerator,
-      joinKeyOrdinalForWatermark = joinKeyOrdinalForWatermark)
+      joinKeyOrdinalForWatermark = joinKeyOrdinalForWatermark,
+      stateValueWatermarkColumnOrdinal =
+        stateValueWatermarkColumnOrdinal(stateWatermarkPredicate, 
inputAttributes))
 
     private[this] val keyGenerator = UnsafeProjection.create(joinKeys, 
inputAttributes)
 
     private[this] val stateKeyWatermarkPredicateFunc = stateWatermarkPredicate 
match {
+      // A key that the opposite watermark selects can be NULL in a row that 
an earlier version

Review Comment:
   **Nit (P3):** An earlier version cannot have stored the rows this disjunct 
is for: a checkpoint of an earlier release restores checkJoinOutputWatermark as 
false, so usesSharedKeyOrdinal (lines 233-234) is true, 
joinKeyOrdinalForWatermark equals the shared ordinal, and the guard below never 
fires for that state. For example, a state format 2 checkpoint of `la = ra AND 
lb = rb` written before this change keeps evicting a left row with a NULL lb by 
la. Only rows that the legacy mode stored before a switch to the default mode 
reach this case, as the state format 2 and 3 test exercises, so a maintainer 
can keep or extend the disjunct for the wrong reason.
   
   **Verification:**
   - **Inspection:** The comment above the NULL disjunct of the key predicate 
in OneSideHashJoiner names rows stored in the legacy mode before a switch to 
the default mode as the only stored rows it handles, and does not name 
checkpoints of an earlier version.



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -23,6 +23,50 @@ 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, unless the condition also bounds the event time of that 
input by the other
+  input's watermark. 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. A query restarted 
from a checkpoint
+  of an earlier version keeps evicting an input that the new rule would evict 
by another column
+  by its event time, with the earlier handling of NULL values; start it with a 
new checkpoint to
+  use the new rule. With state format version 4, a join evicted by another 
column cannot restart
+  after a change of `spark.sql.streaming.statefulOperator.allowMultiple`; 
start it with a new
+  checkpoint. With `spark.sql.streaming.statefulOperator.allowMultiple` set to 
false, joins keep
+  the earlier behavior.
+
+- Since Spark 4.5, a stream-stream join whose inputs have watermarks on 
different equality keys, for
+  example `la = ra AND lb = rb` with watermarks on `la` and `rb`, evicts the 
state of each input by
+  the key that the opposite input's watermark bounds. Earlier versions evicted 
both by the same key
+  and could lose matches. In append mode, a new query fails when an operator 
that drops late rows
+  follows such a join, because the state of an input evicted by a key other 
than its event time
+  keeps rows of any event time. A row whose new eviction key is NULL, such as 
a left row with a NULL
+  `lb`, can never match: an outer join now emits it when it arrives. A NULL in 
`ra` keeps the
+  earlier handling. A query restarted from a checkpoint of an earlier version 
keeps evicting both
+  inputs by the same key, with the earlier handling of NULL keys; start it 
with a new checkpoint to
+  use the new rule. With state format version 4, such a join cannot restart 
after a change of
+  `spark.sql.streaming.statefulOperator.allowMultiple`; start it with a new 
checkpoint. With
+  `spark.sql.streaming.statefulOperator.allowMultiple` set to false, joins 
keep the earlier
+  behavior.
+
+- 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 that emits the rows of an input whose state is never 
evicted, for example a
+  join on a key without a watermark and without a time range on that input. 
Such a query could
+  drop joined rows as late. Add a watermark in the join keys, or a range 
condition that bounds each

Review Comment:
   **Nit (P3):** This entry says such a query fails, but the check rejects only 
when the later operator's event-time columns can come from the input without a 
cutoff, or when the path to the join cannot be traced: 
StreamingJoinOutputWatermarkSuite runs a one-sided range join followed by a 
window count on the bounded input without failing. The first two entries state 
the failure the same way (lines 33-35 and 51-52 of this file). The remedies 
here are also looser than the check's message: a watermark in the join keys 
still fails when the two inputs carry their watermarks on different keys, and a 
range such as `rightTime BETWEEN leftTime AND expiry`, which bounds the left 
input only through expiry, still fails under the first entry. Upgrading users 
can rewrite queries that would not fail, or apply a remedy that does not clear 
the failure.
   
   **Verification:**
   - **Regression:** The rejection of a window aggregation on la after a join 
on la = ra AND lb = rb with watermarks on la and rb offers a watermark on the 
same join key of both inputs and no range-condition remedy, while the rejection 
of a key-only join still offers the range-condition remedy.
   - **Inspection:** The three 4.4-to-4.5 Structured Streaming migration 
entries state that the failure needs the later operator's event time to come 
from the affected input, and the third entry's remedies are a range condition 
that bounds that input's event time and a watermark on the same join key of 
both inputs.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -309,12 +361,35 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     // left side keys effectively causes the timestamp on the right side to 
have a watermark.
     // We will use the ordinal of the left timestamp in the left keys to find 
the corresponding
     // right timestamp in the right keys.
-    leftKeys.zipWithIndex.collectFirst {
+    watermarkedKeyOrdinal(leftKeys).orElse(watermarkedKeyOrdinal(rightKeys))
+  }
+
+  /**
+   * The ordinal of the equality key that evicts the state of one side: the 
first watermarked key
+   * of the opposite input, whose future rows have that key above the 
watermark. When the
+   * opposite input has no watermarked key, and in the legacy mode with a 
single global

Review Comment:
   **Nit (P3):** This scaladoc presents the shared-key fallback, for an 
opposite input without a watermarked equality key, as part of a sound rule, but 
such an input still loses matches as on the base branch. For example, joining 
impressions to clicks on `i.adId = c.adId AND i.impTime = c.impTime` with 
watermarks on i.impTime and on c.clickTime, which is not a join key, keeps 
evicting impressions by impTime while clicks are late-filtered only on 
clickTime, so a click whose impTime the watermark has already passed finds no 
impression. The PR description defers these inputs, but only the SPARK-62002 
TODO here marks a known gap, so readers cannot tell that this fallback is one 
too.
   
   **Verification:**
   - **Inspection:** The scaladoc of findStateKeyOrdinalForWatermark marks, as 
a deferred gap, that an input whose opposite input has no watermarked equality 
key keeps the shared key and can still lose matches.



##########
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 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.
+    if (isFirstBatch && 
sparkSession.sessionState.conf.isUnsupportedOperationCheckEnabled) {
+      UnsupportedOperationChecker.checkStreamStreamJoinOutputWatermark(
+        InlineCTE(alwaysInline = true).apply(optimized), outputMode)

Review Comment:
   **Nit (P3):** By the review's reading of the optimizer, this InlineCTE call 
never finds a CTE: SparkOptimizer's 'Replace CTE with Repartition' batch, whose 
rule is non-excludable, has already replaced every CTE reference in the plan 
and its subqueries with its definition under a RepartitionByExpression, so the 
optimized plan holds no CTE node. The scaladoc of 
checkStreamStreamJoinOutputWatermark (UnsupportedOperationChecker.scala lines 
164-165) justifies the call by MATERIALIZED CTE definitions whose joins would 
be missed, but such a CTE reaches the check as a repartition between the join 
and the operator, where the trace stops. Removing the call changes no test; the 
only CTE test uses a plain CTE that the optimizer inlines anyway.
   
   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 +756,58 @@ 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. A NULL in
+    // an equality key that the opposite watermark selects can never match 
either; the key that
+    // findJoinKeyOrdinalForWatermark selects keeps the previous behavior.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _, true)) =>
+        Predicate.create(IsNull(column), inputAttributes).eval _
+      case Some(_: JoinStateKeyWatermarkPredicate) if 
joinKeyOrdinalForWatermark !=
+          findJoinKeyOrdinalForWatermark(leftKeys, rightKeys) =>
+        Predicate.create(IsNull(joinKeys(joinKeyOrdinalForWatermark.get)), 
inputAttributes).eval _
+      case _ => _ => false
+    }
+
+    // Such a row is not stored, but an earlier version or the legacy mode can 
have stored one.
+    // TODO: [SPARK-62038] State format 4 evicts by ranges of its index, which 
stores a NULL at
+    //  timestamp 0, below the scan start, so it still keeps such rows.
     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

Review Comment:
   **Nit (P3):** This comment ties SPARK-61380 only to left rows of the same 
batch. For a right input evicted by a picked column other than its event time, 
the admission below still skips a right row whose event time is at or below the 
cutoff solved over the whole input, although the picked-column eviction keeps 
it: with `k = rk AND lt BETWEEN re AND rx` and 0-second watermarks on lt and 
re, a right row (1, re 8 h, rx 12 h) in the batch whose eviction watermark is 
10 h is not stored, so a left row (1, lt 11 h) in the next batch is not 
emitted, while an inner join on the same condition returns the match. Your 
reply defers storing these rows to SPARK-61380, and the review honors that; 
without a TODO here, a reader of skipsEvictingRightRow cannot tell that this 
gap is known.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60668#issuecomment-7092365469), 
[2](https://github.com/apache/spark/pull/60668#discussion_r4641996854).
   
   **Verification:**
   - **Inspection:** A TODO naming SPARK-61380 at skipsEvictingRightRow says 
that a right row the picked-column eviction would keep can still be skipped, so 
a later left row can lose its match.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,40 +270,84 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             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 =>
+        val eventTime = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+        def wholeInput(watermark: Option[Long]): Option[Long] =
           StreamingJoinHelper.getStateValueWatermark(
             attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
             attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
             condition,
-            eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
+            watermark)
+        // The column that evicts this input, its cutoff, and whether the 
condition bounds that
+        // column. The legacy mode with a single global watermark keeps 
applying a cutoff on any
+        // column of this input to the event time. So does the default mode 
when the condition
+        // bounds no TIMESTAMP column, such as through a DATE column cast to 
TIMESTAMP only.
+        // So does a checkpoint written without the join output watermark 
check for an input that
+        // the default mode would evict by another column, since for such a 
checkpoint that check
+        // only warns about a later operator that drops the rows this eviction 
emits late.
+        // TODO: [SPARK-62044] An input bounded only through a column cast to 
TIMESTAMP is still
+        //  evicted by its event time with the cast column's cutoff, which can 
be too early.
+        def solve(watermark: Option[Long]): Option[(Attribute, Long, Boolean)] 
= {
+          val picked = if (useFirstEventTimeColumn) None else {
+            
StreamingJoinHelper.getStateValueWatermarkColumn(oneSideInputAttributes,
+              AttributeSet(otherSideInputAttributes), condition, 
watermark).filter {
+              case (c, _) => checkJoinOutputWatermark || 
eventTime.exists(_.semanticEquals(c))

Review Comment:
   **Nit (P3):** The event-time disjunct of this filter gives an upgraded input 
whose event time the condition bounds the per-column cutoff and the NULL rule 
that the migration guide documents for state formats 1 to 3: stored rows with a 
NULL event time are evicted, and emitted by an outer join, after the upgrade. 
The restarts without the setting run the expiry, crossed-key and key-only 
shapes or the bundled expiry fixture, and StreamingSymmetricHashJoinHelperSuite 
calls getStateWatermarkPredicates with the setting's default true. Replacing 
the filter with checkJoinOutputWatermark alone, after which an upgraded 
time-interval join keeps a stored row with a NULL leftTime in state for good on 
state format 2, changes no test.
   
   See **Shared repair plan 3** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +756,58 @@ 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. A NULL in
+    // an equality key that the opposite watermark selects can never match 
either; the key that
+    // findJoinKeyOrdinalForWatermark selects keeps the previous behavior.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _, true)) =>
+        Predicate.create(IsNull(column), inputAttributes).eval _
+      case Some(_: JoinStateKeyWatermarkPredicate) if 
joinKeyOrdinalForWatermark !=

Review Comment:
   **Nit (P3):** This guard and the one at the key predicate (line 749) keep 
the earlier NULL handling for the shared key, which the migration guide 
promises for a NULL in ra. Every NULL-key case in 
StreamingJoinEqualityWatermarkSuite puts the NULL in lb, its legacy-mode test 
has no NULLs, and the nullable-key tests of StreamingJoinSuite put the NULL in 
a null-safe key without a watermark, so dropping either guard, which would 
change the NULL handling of every join with a watermarked equality key, fails 
no test.
   
   **Verification:**
   - **Compatibility:** In the default mode on state formats 2 and 4, a full 
outer join on la = ra AND lb = rb with watermarks on la and rb stores a right 
row whose ra is NULL when it arrives, so the batch's updated state rows include 
it, as on the base branch; on state format 2 the row also stays in state, with 
no unmatched output for it, after a later batch whose watermark passes its rb.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,133 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join that
+   * emits the rows of an input whose state has no cutoff on its event time, as
+   * [[checkStreamingQueryGlobalWatermarkLimit]] does for other operators. It 
takes the optimized
+   * plan, whose join conditions eviction uses, with its CTE references 
inlined: the optimizer
+   * keeps some CTE definitions, such as MATERIALIZED ones, whose joins would 
be missed. A query
+   * from a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` 
only logs a warning,
+   * and its join keeps evicting by the event time an input that would 
otherwise be evicted by
+   * another column.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    // A stream-stream join without an equality predicate fails in planning 
with its own error.
+    val hasJoinWithoutEquality = plan.exists {
+      case j @ Join(l, r, _, _, _) => l.isStreaming && r.isStreaming &&
+        ExtractEquiJoinKeys.unapply(j).isEmpty
+      case _ => false
+    }
+    if (hasJoinWithoutEquality) {
+      return
+    }
+    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 =>
+              // An input counts unless the operator's event times come only 
from other inputs.
+              val sources = eventTimeSources(subPlan, j)
+              joinInputWithoutStateCutoff(j,
+                  input => 
sources.forall(_.exists(input.outputSet.contains))).foreach { side =>
+                throwError("Detected pattern of possible 'correctness' issue: 
the state of the " +
+                  s"$side input of a stream-stream join has no cutoff on its 
event time, so the " +
+                  "join can emit its old rows below its output watermark, and 
a later stateful " +
+                  "operator drops them as late. Add a range condition that 
bounds the event time " +
+                  "of that input by the other input's watermark, or a 
watermark on the same join " +
+                  "key of both inputs, 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.
+  // TODO: An input that earlier versions also evicted by a join key other 
than its event time is
+  //   not checked yet, such as the right input of `leftKey = rightKey AND 
leftTime = rightTs`.
+  private def joinInputWithoutStateCutoff(
+      join: Join, counts: LogicalPlan => Boolean): 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)
+        .filter { case (_, input, _) => counts(input) }
+        .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
+        }
+    // With allowMultiple, an input is evicted by its equality key that the 
other input's
+    // watermark bounds. Where that is neither the key earlier versions 
evicted both inputs by
+    // nor the input's event time, its state keeps rows of any event time.
+    case ExtractEquiJoinKeys(joinType, leftKeys, rightKeys, _, _, left, right, 
_)
+        if left.isStreaming && right.isStreaming &&
+          SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE) =>

Review Comment:
   **Nit (P3):** This path, like the picked-column clause at lines 227-229, 
reads only allowMultiple, while a restart from a checkpoint written before this 
change restores checkJoinOutputWatermark as false and keeps the earlier 
eviction. Restarting `l LEFT OUTER JOIN r ON la = ra AND lb = rb` with 
watermarks on la and rb, followed by an append-mode count over window(la, '10 
seconds'), evicts the left input by la and counts its rows as the base branch 
does, yet the first batch logs, with the query plan, that the state of the left 
input has no cutoff on its event time and that a later stateful operator drops 
its old rows; StreamingJoinOutputWatermarkSuite asserts this warning for the 
crossed-key and expiry restarts. Operators of upgraded queries are sent after 
drops that do not happen, and log-based alerts can fire; results are unchanged.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60668#discussion_r4641996805).
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -227,6 +229,9 @@ case class StreamingSymmetricHashJoinExec(
       SessionState.newHadoopConf(sparkContext.hadoopConfiguration, conf))
   private val allowMultipleStatefulOperators =
     conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+  // As in getStateWatermarkPredicates, which picks the key that evicts each 
input.
+  private val usesSharedKeyOrdinal = !allowMultipleStatefulOperators ||
+    !conf.getConf(SQLConf.STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK)

Review Comment:
   **Nit (P3):** A state format 4 restart of `la = ra AND lb = rb` from a 
checkpoint of an earlier release restores index version 0 and 
checkJoinOutputWatermark false, and relies on this disjunct for both the 
per-side ordinal that each joiner passes to its state manager and the 
index-version-0 key check in doExecute. The state format 4 crossed-key restarts 
in StreamingJoinRangeEvictionSuite remove only the index version and keep the 
setting recorded as true, so 'V4 restart from an older checkpoint fails when 
the opposite watermark picks another key' restarts a checkpoint that no earlier 
release writes; the only crossed-key restart without the setting runs state 
format 2, and the bundled state format 4 fixture joins on a key without a 
watermark. Dropping the disjunct makes such an upgrade fail with 
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE naming lb, and no test fails.
   
   See **Shared repair plan 3** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,133 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join that
+   * emits the rows of an input whose state has no cutoff on its event time, as
+   * [[checkStreamingQueryGlobalWatermarkLimit]] does for other operators. It 
takes the optimized
+   * plan, whose join conditions eviction uses, with its CTE references 
inlined: the optimizer
+   * keeps some CTE definitions, such as MATERIALIZED ones, whose joins would 
be missed. A query
+   * from a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` 
only logs a warning,
+   * and its join keeps evicting by the event time an input that would 
otherwise be evicted by
+   * another column.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    // A stream-stream join without an equality predicate fails in planning 
with its own error.
+    val hasJoinWithoutEquality = plan.exists {
+      case j @ Join(l, r, _, _, _) => l.isStreaming && r.isStreaming &&
+        ExtractEquiJoinKeys.unapply(j).isEmpty
+      case _ => false
+    }
+    if (hasJoinWithoutEquality) {
+      return
+    }
+    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 =>
+              // An input counts unless the operator's event times come only 
from other inputs.
+              val sources = eventTimeSources(subPlan, j)
+              joinInputWithoutStateCutoff(j,
+                  input => 
sources.forall(_.exists(input.outputSet.contains))).foreach { side =>
+                throwError("Detected pattern of possible 'correctness' issue: 
the state of the " +
+                  s"$side input of a stream-stream join has no cutoff on its 
event time, so the " +
+                  "join can emit its old rows below its output watermark, and 
a later stateful " +
+                  "operator drops them as late. Add a range condition that 
bounds the event time " +
+                  "of that input by the other input's watermark, or a 
watermark on the same join " +
+                  "key of both inputs, 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.
+  // TODO: An input that earlier versions also evicted by a join key other 
than its event time is
+  //   not checked yet, such as the right input of `leftKey = rightKey AND 
leftTime = rightTs`.
+  private def joinInputWithoutStateCutoff(
+      join: Join, counts: LogicalPlan => Boolean): 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)
+        .filter { case (_, input, _) => counts(input) }
+        .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
+        }
+    // With allowMultiple, an input is evicted by its equality key that the 
other input's
+    // watermark bounds. Where that is neither the key earlier versions 
evicted both inputs by
+    // nor the input's event time, its state keeps rows of any event time.
+    case ExtractEquiJoinKeys(joinType, leftKeys, rightKeys, _, _, left, right, 
_)
+        if left.isStreaming && right.isStreaming &&
+          SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE) =>
+      def watermarked(keys: Seq[Expression]): Option[Int] = 
Some(keys.indexWhere {
+        case ne: NamedExpression => 
ne.metadata.contains(EventTimeWatermark.delayKey)
+        case _ => false
+      }).filter(_ >= 0)
+      val shared = watermarked(leftKeys).orElse(watermarked(rightKeys))
+      Seq(("left", leftKeys, rightKeys, left), ("right", rightKeys, leftKeys, 
right))
+        .take(if (joinType == LeftSemi) 1 else 2)
+        .filter { case (_, _, _, input) => counts(input) }
+        .collectFirst {
+          case (side, keys, otherKeys, _) if watermarked(otherKeys).exists { i 
=>
+            !shared.contains(i) && watermarked(Seq(keys(i))).isEmpty } => side
+        }
+    case _ => None
+  }
+
+  // The columns of `join`'s output that the event-time columns of 
`operator`'s input are computed
+  // from, or None when the path from the operator down to the join has a node 
other than a
+  // projection, a filter, a watermark or an expansion, such as the one of a 
sliding window.
+  private def eventTimeSources(operator: LogicalPlan, join: Join): 
Option[AttributeSet] = {
+    def trace(plan: LogicalPlan, attrs: AttributeSet): Option[AttributeSet] = 
plan match {
+      case p if p eq join => Some(attrs)
+      case Project(list, child) =>
+        trace(child, AttributeSet(list.filter(e => 
attrs.contains(e.toAttribute))
+          .flatMap(_.references)))
+      case Filter(_, child) => trace(child, attrs)
+      case w: EventTimeWatermark => trace(w.child, attrs)
+      case Expand(projections, output, child) =>

Review Comment:
   **Nit (P3):** No test reaches this case: every window after a join in 
StreamingJoinOutputWatermarkSuite is a tumbling window, which takes the 
projection and filter path, and UnsupportedOperationsSuite builds no Expand. 
Deleting this case rejects a sliding window on the bounded input of a one-sided 
range join as if every input counted, and mis-mapping its projections can 
accept a sliding window on the unbounded input's event time, after which the 
aggregation drops joined rows as late; neither change fails a test.
   
   See **Shared repair plan 1** in the review body.



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -8419,6 +8419,13 @@
     ],
     "sqlState" : "55019"
   },
+  "STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE" : {
+    "message" : [
+      "Cannot restart the stream-stream join from this checkpoint. The 
checkpoint and this query order the state format version 4 state of the <side> 
input differently: one of them orders it by <column>. This happens with a 
checkpoint of an earlier version, or after a change of 
spark.sql.streaming.statefulOperator.allowMultiple.",

Review Comment:
   **Nit (P3):** A checkpoint of an earlier version no longer produces this 
error: OffsetSeqMetadata restores index version 0 and checkJoinOutputWatermark 
false for it whatever the session sets, so the version-0 branch of the restart 
check in StreamingSymmetricHashJoinExec sees the event time and the shared key 
and raises nothing, as the restart of the bundled earlier-version fixture in 
StreamingJoinRangeEvictionSuite shows. The error is raised only after a change 
of spark.sql.streaming.statefulOperator.allowMultiple or an index version set 
by hand, so a user who switched allowMultiple is first pointed at the 
checkpoint's age.
   
   **Verification:**
   - **Inspection:** The message of the state format 4 incompatibility error 
names a change of spark.sql.streaming.statefulOperator.allowMultiple as its 
cause and does not name a checkpoint of an earlier version.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -362,6 +367,38 @@ 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, or by
+    // the equality key that findJoinKeyOrdinalForWatermark picks (index 
version 0), so their
+    // checkpoints cannot evict that state by another column or key. Index 
version 1 orders it by
+    // the column or key that the default mode picks, which the legacy mode 
cannot evict or look
+    // rows up by.
+    val indexVersion = 
conf.getConf(SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION)
+    if (stateFormatVersion == 4 && (indexVersion == 0 || 
!allowMultipleStatefulOperators)) {
+      val sharedKeyOrdinal = findJoinKeyOrdinalForWatermark(leftKeys, 
rightKeys)
+      Seq((LeftSide, stateWatermarkPredicates.left, left.output, right.output, 
leftKeys),
+          (RightSide, stateWatermarkPredicates.right, right.output, 
left.output, rightKeys))
+          .foreach { case (side, predicate, attributes, otherAttributes, keys) 
=>
+          val eventTime = WatermarkSupport.findEventTimeColumnIndex(
+            attributes, allowMultipleEventTimeColumns = false)
+          val column = if (indexVersion == 0) {
+            stateValueWatermarkColumnOrdinal(predicate, attributes)
+          } else {
+            predicate.collect { case _: JoinStateValueWatermarkPredicate =>

Review Comment:
   **Non-blocking (P2):** This branch rebuilds the layout that the default mode 
wrote, from getStateValueWatermarkColumn here and from the opposite input's key 
at lines 391-393, without consulting the checkJoinOutputWatermark value 
restored from the same checkpoint. With that value false, the default mode 
wrote the state ordered by the event time and the shared key, because solve 
keeps only an event-time pick and usesSharedKeyOrdinal keeps the shared key. So 
a new state format 4 query started with checkJoinOutputWatermark false on `l 
LEFT OUTER JOIN r ON leftKey = rightKey AND rightTime BETWEEN leftTime AND 
expiry` fails a restart with allowMultiple set to false for the left input and 
`expiry`, and the same restart of `la = ra AND lb = rb` with watermarks on la 
and rb fails for lb, although the legacy mode reads the state as it was 
written. The error tells the user to start a new checkpoint, which discards 
compatible state; every setting on this path is internal and set away from its
  default.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60668#discussion_r4616349089).
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,13 +230,15 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     WatermarkSupport.findEventTimeColumn(rightAttributes,
       allowMultipleEventTimeColumns = useFirstEventTimeColumn)
 
-    val joinKeyOrdinalForWatermark: Option[Int] = 
findJoinKeyOrdinalForWatermark(
-      leftKeys, rightKeys)
-
     def getOneSideStateWatermarkPredicate(
+        joinSide: JoinSide,
         oneSideInputAttributes: Seq[Attribute],
         oneSideJoinKeys: Seq[Expression],
         otherSideInputAttributes: Seq[Attribute]): 
Option[JoinStateWatermarkPredicate] = {
+      // A checkpoint written without the join output watermark check keeps 
the shared key, as
+      // for an input evicted by another column below.
+      val joinKeyOrdinalForWatermark = findStateKeyOrdinalForWatermark(

Review Comment:
   **Nit (P3):** Here the left input of a crossed-key join is evicted by the 
opposite input's watermarked key, while getStateWatermark (lines 165-209 of 
this file), which produceOutputWatermark uses for the join's output watermark, 
still takes the shared key, so the output watermark no longer bounds the event 
times that the moved input holds. In update mode, which the chained-operator 
check does not cover, `l JOIN r ON la = ra AND lb = rb` with watermarks on la 
and rb followed by a count over window(la, '10 seconds') drops the restored 
match as late, just as the base branch lost it. The PR description defers the 
output watermark to SPARK-62001, but nothing at getStateWatermark or 
produceOutputWatermark says so, so a reader sees the base branch's assumption 
without its known exception.
   
   **Verification:**
   - **Inspection:** A TODO naming SPARK-62001 at getStateWatermark or 
produceOutputWatermark says that the state watermarks still assume eviction by 
the shared key or the event time and do not bound the rows that an input 
evicted by another key or column holds.



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

Review Comment:
   Thanks, the trace holds for the main case: a one-sided range join followed 
by a window count on the bounded input now runs. At this head the trace still 
starts from every event-time column of the later operator's input instead of an 
aggregation's grouping key, so a window count on leftTime that also aggregates 
rightTime is still rejected; since this branch does not include e4ec72eccf8 
from #60713, this review raises that case again. It also raises the related 
case of a pass-through node, such as a repartition or a join with a static 
table, between the join and the later operator.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4641996825","thread_id":"inline:4641996825","verdict_sha256":"9ac547afeb4eb00a58f39d2b74a380b19b9d268a60ce654af6f33d612404fa8c"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,89 @@ 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:
   Thanks, the cause now fits every flagged input. One part stands: for the 
crossed-key pattern, such as the left input of la = ra AND lb = rb with 
watermarks on la and rb, the first remedy, a range condition that bounds the 
event time of that input, cannot clear the rejection, because a watermark in 
the join keys makes both the check and the eviction ignore range conditions; 
only a watermark on the same join key of both inputs, the legacy mode, or 
disabling the check does. Saying which remedy fits which case would keep users 
from trying the first one there.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4641996840","thread_id":"inline:4641996840","verdict_sha256":"9ac547afeb4eb00a58f39d2b74a380b19b9d268a60ce654af6f33d612404fa8c"}
 -->



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +753,49 @@ 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. A NULL in
+    // an equality key that the opposite watermark selects can never match 
either; the key that
+    // findJoinKeyOrdinalForWatermark selects keeps the previous behavior.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _, true)) =>
+        Predicate.create(IsNull(column), inputAttributes).eval _
+      case Some(_: JoinStateKeyWatermarkPredicate) if 
joinKeyOrdinalForWatermark !=
+          findJoinKeyOrdinalForWatermark(leftKeys, rightKeys) =>
+        Predicate.create(IsNull(joinKeys(joinKeyOrdinalForWatermark.get)), 
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 &&

Review Comment:
   Agreed that the base branch drops these right rows too and that storing 
every row the picked column keeps can wait for SPARK-61380. This review raises 
a related issue: the code ties SPARK-61380 only to left rows of the same batch, 
so a reader of the left semi admission check cannot tell that skipping these 
right rows is a known, deferred gap.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4641996854","thread_id":"inline:4641996854","verdict_sha256":"9ac547afeb4eb00a58f39d2b74a380b19b9d268a60ce654af6f33d612404fa8c"}
 -->



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