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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -261,28 +261,47 @@ 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)
+      } 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. So does the default mode when the 
condition bounds no

Review Comment:
   **Nit (P3):** This comment reads as if every case without a bounded 
TIMESTAMP column applied the cutoff to the event time, but that holds only for 
an input with its own watermark. An input without one that the condition bounds 
only through a cast, such as `CAST(leftDate AS TIMESTAMP) BETWEEN rightTime - 
INTERVAL 1 DAY AND rightTime` with a watermark only on rightTime, gets no 
cutoff here: getStateValueWatermarkColumn picks no TIMESTAMP column, and 
`wholeInput` needs an event time. Its state is kept forever and a left outer 
join never emits its unmatched rows, as on master, which the PR description 
defers to SPARK-62044. A TODO naming SPARK-62044 here, with a comment saying 
that such an input gets no cutoff, would show code readers that the fix is 
partial.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60669#discussion_r4616191622).
   
   **Verification:**
   - **Inspection:** The comment and TODO at the whole-input fallback of 
getStateWatermarkPredicates state that an input with its own watermark falls 
back to its event time, and that an input without one, bounded only through a 
cast column, gets no cutoff until SPARK-62044.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,18 +749,30 @@ 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)
+
+    // The join condition bounds the column that the value predicate tests, so 
a row with a NULL
+    // in it can never match, and `column <= cutoff` never holds for it. The 
legacy mode tests the
+    // event time even when the condition bounds another column.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {

Review Comment:
   **Blocking (P1):** This screen assumes the condition bounds the predicate's 
column, but the default-mode fallback in getStateWatermarkPredicates 
(StreamingSymmetricHashJoinHelper.scala:279-284) builds the predicate on the 
event time when the condition bounds a watermarked input only through a 
non-TIMESTAMP column cast to TIMESTAMP. Reading the code with default settings, 
a left outer join on `leftKey = rightKey AND CAST(leftDate AS TIMESTAMP) 
BETWEEN rightTime - INTERVAL 1 DAY AND rightTime` that has buffered right (1, 
2026-01-01 12:00) and then receives left (1, leftTime NULL, leftDate 
2026-01-01) emits (1, null) at once instead of the match and also misses a 
later right (1, 2026-01-01 18:00), and an inner join returns neither match. 
EventTimeWatermarkExec and the late-row filter both pass a NULL leftTime, and 
master joins and stores the row. On state formats 1 to 3 the predicate function 
below also evicts such a row that an earlier version or legacy mode stored. 
Applying the scr
 een, in both places, only when the predicate's column is the one 
getStateValueWatermarkColumn picks for that input keeps it for the columns the 
condition bounds and restores the base branch's behavior in the fallback.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60669#discussion_r4616191522).
   
   **Verification:**
   - **Regression:** With default settings and watermarks on leftTime and 
rightTime, an inner join and a left outer join on `leftKey = rightKey AND 
CAST(leftDate AS TIMESTAMP) BETWEEN rightTime - INTERVAL 1 DAY AND rightTime` 
return the match of a left row whose leftTime is NULL with a right row buffered 
before it on state formats 2 and 4, and on state format 2 also its match with a 
right row of a later micro-batch, as the base branch does; state format 4 
indexes a NULL event time as 0, so its range eviction can remove such a row 
before a later micro-batch, also on the base branch.
   - **Behavior:** For the same left outer join, an unmatched left row with a 
non-NULL leftTime is emitted null-padded once the right watermark minus one day 
passes its leftTime, so the default-mode fallback keeps evicting such an input 
by its event time.
   - **Regression:** With state format 2, a left row with a NULL leftTime that 
a legacy-mode run of that join stored is not evicted after a restart in the 
default mode and still matches a later right row.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4399,6 +4399,21 @@ object SQLConf {
       .checkValue(v => Set(1, 2, 3, 4).contains(v), "Valid versions are 1, 2, 
3, and 4")
       .createWithDefault(2)
 
+  val STREAMING_JOIN_STATE_V4_INDEX_VERSION =
+    buildConf("spark.sql.streaming.join.stateFormatV4.indexVersion")
+      .internal()
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .doc("How state format version 4 of stream-stream joins orders the state 
of an input that " +
+        "it evicts by a range condition. 0: by the event time of the input, as 
in 4.3 and " +
+        "earlier and with spark.sql.streaming.statefulOperator.allowMultiple 
set to false. 1: by " +
+        "the column that the condition bounds. A streaming query keeps the 
version recorded in " +
+        "its checkpoint, and one restarted from a checkpoint without it uses 
0. With 0, a join " +
+        "whose condition does not bound the event time of such an input fails 
to restart.")

Review Comment:
   **Nit (P3):** The restart rule here no longer matches the check, which under 
version 0 fails only when an input with an event time would be evicted by 
another column, or when an outer join emits the unmatched rows of an input 
without one (StreamingSymmetricHashJoinExec.scala:387-394). An inner join with 
a watermark only on rightTime and `leftTime BETWEEN rightTime - INTERVAL 5 
SECONDS AND rightTime + INTERVAL 5 SECONDS` restarts under 0, as the new 
restart test asserts, and so does a watermarked input bounded only through a 
cast column. The doc also presents the value as an ordering choice, but version 
0 checkpoints keep an input without an event time out of the index rather than 
ordering it by one, and the state manager always orders by the predicate's 
column (StreamingSymmetricHashJoinExec.scala:737-739), so the value only 
records the checkpoint's layout and gates the check. Describing what each 
version records and which restarts fail under each, including a legacy-mode 
restart 
 of a version 1 checkpoint, would match the code.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60669#discussion_r4616191601).
   
   **Verification:**
   - **Inspection:** The doc of 
spark.sql.streaming.join.stateFormatV4.indexVersion names the same restart 
failures as the state format 4 restart check of the stream-stream join operator 
for both versions, and no longer says that version 0 orders every such input by 
its event time or that a join whose condition does not bound the event time 
always fails to restart.



##########
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 for adding the migration note. I still see this as blocking for this 
pull request, because its diff carries the eviction change: with the default 
settings, a stateful operator after such a join silently drops rows that it 
received and counted on master, and documenting the drop does not stop it. 
Tracking the output watermark in SPARK-62001 also leaves those queries with no 
way back, since setting spark.sql.streaming.statefulOperator.allowMultiple to 
false switches every stateful operator to one global watermark. Until 
SPARK-62001 lands, rejecting a stateful operator after such a join in the 
existing global-watermark correctness check, as the original comment suggested, 
would keep results correct; whether that change goes into #60667 or here is up 
to you.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4616191497","thread_id":"inline:4616191497","verdict_sha256":"301f52b9019ed1eec686a2b7e780f57d521a914905d4f87ed49a99396bc2218a"}
 -->



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -362,6 +364,41 @@ 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

Review Comment:
   **Nit (P3):** This comment, and the migration note's statement that such an 
outer join cannot restart after a change of 
spark.sql.streaming.statefulOperator.allowMultiple, cover more than the check 
does. For a state format 4 left outer join with a watermark only on rightTime, 
a checkpoint started in the default mode keeps index version 1 through a 
legacy-mode run, because StreamExecution.scala:343-348 records 0 only for a 
fresh start, and in legacy mode that input has no predicate, so the version-1 
branch below computes no column. The legacy run stores the input's rows without 
index entries, both restarts succeed, and once the default mode resumes those 
rows are never evicted or emitted, as on master for every such row. Your reply 
on the legacy-mode thread defers this path; a TODO at that branch naming it, 
with this comment and the migration bullet narrowed to checkpoints written by 
an earlier version or started in legacy mode, would make the deferral visible.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60669#discussion_r4616191601).
   
   **Verification:**
   - **Inspection:** The comment above the state format 4 restart check, the 
new TODO and the third bullet of the 4.3-to-4.4 migration section agree with 
the check: outer joins that emit the unmatched rows of an input without its own 
watermark fail to restart from checkpoints written by an earlier version or 
started in legacy mode, while a checkpoint started in the default mode restarts 
into legacy mode and back unchecked.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOneSidedWatermarkSuite.scala:
##########
@@ -0,0 +1,181 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinOneSidedWatermarkSuite extends StateStoreMetricsTest {
+  import testImplicits._
+
+  private def withJoinConf(version: Int)(f: => Unit): Unit = {
+    withSQLConf(
+      SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+      SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+      SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+  }
+
+  for {
+    version <- Seq(2, 3, 4)
+    joinType <- Seq("left_outer", "right_outer")
+  } {
+    test(s"range eviction needs only the opposite watermark, V$version 
$joinType") {
+      withSQLConf(
+        SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+        SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+        val leftInput = MemoryStream[(Int, Int)]
+        val rightInput = MemoryStream[(Int, Int)]
+        val leftData = leftInput.toDF().toDF("leftKey", "time")
+          .select($"leftKey", timestamp_seconds($"time").as("leftTime"))
+        val rightData = rightInput.toDF().toDF("rightKey", "time")
+          .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+        // Only the input whose rows are not preserved has a watermark.
+        val left = if (joinType == "right_outer") {
+          leftData.withWatermark("leftTime", "10 seconds")
+        } else {
+          leftData
+        }
+        val right = if (joinType == "left_outer") {
+          rightData.withWatermark("rightTime", "10 seconds")
+        } else {
+          rightData
+        }
+        val joined = left.join(right, expr("leftKey = rightKey AND " +
+          "leftTime BETWEEN rightTime - INTERVAL 5 SECONDS AND " +
+          "rightTime + INTERVAL 5 SECONDS"), joinType)
+          .select($"leftKey", $"rightKey", $"leftTime".cast("int"), 
$"rightTime".cast("int"))
+        val stateInput = if (joinType == "left_outer") leftInput else 
rightInput
+        val watermarkInput = if (joinType == "left_outer") rightInput else 
leftInput
+        def unmatched(key: Int): Row = {
+          if (joinType == "left_outer") Row(key, null, 5, null) else Row(null, 
key, null, 5)
+        }
+        withTempDir { checkpoint =>
+          testStream(joined)(
+            StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+            AddData(stateInput, (1, 5)), CheckNewAnswer(),
+            AddData(watermarkInput, (2, 30)), CheckNewAnswer(),
+            AddData(watermarkInput, (2, 40)), CheckNewAnswer(unmatched(1)),
+            StopStream,
+            StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+            // The input without a watermark can add rows below an earlier 
eviction cutoff.
+            AddData(stateInput, (3, 5)), CheckNewAnswer(unmatched(3)),
+            AddData(watermarkInput, (3, 5)), CheckNewAnswer(),
+            AddData(watermarkInput, (4, 50)), CheckNewAnswer(),
+            // The watermarked input keeps its state for arbitrarily old rows 
of the other input.
+            AddData(stateInput, (2, 30)), CheckNewAnswer(Row(2, 2, 30, 30)))
+        }
+      }
+    }
+  }
+
+  // The input without a watermark is evicted, and its matches within the 
range are kept.
+  for {
+    version <- Seq(2, 4)
+    (joinType, watermarkOnLeft) <- Seq(("inner", false), ("inner", true), 
("left_semi", false))

Review Comment:
   **Nit (P3):** The left_semi variant cannot fail: right (1, 8 s) matches the 
only stored left row (1, 5 s), and the semi join removes that row from state at 
once (StreamingSymmetricHashJoinExec.scala:906-913), so the `numRowsTotal === 
3` assertion counts only the three right rows whether or not left eviction 
runs, and the steps after the restart check only output. Dropping LeftSemi from 
the eviction call at StreamingSymmetricHashJoinExec.scala:645 would leave every 
case passing. Giving this variant a left row that no right row matches, such as 
another key at 5 s, and asserting that the state no longer holds it once the 
right watermark passes it would give the case a failure signal.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60669#discussion_r4616191680).
   
   **Verification:**
   - **Regression:** For a left semi join with a watermark only on rightTime 
and `leftTime BETWEEN rightTime - INTERVAL 5 SECONDS AND rightTime + INTERVAL 5 
SECONDS`, on state formats 2 and 4, an unmatched left row at 5 seconds leaves 
the state once the right watermark passes 10 seconds, and the case fails when 
the left input gets no eviction predicate.



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,40 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Since Spark 4.4, a stream-stream join whose condition bounds an input with 
its own watermark
+  only through another TIMESTAMP column, for example `rightTime BETWEEN 
leftTime AND expiry`,
+  evicts the state of that input by the bounded column instead of its event 
time. Earlier versions
+  could emit outer join rows too early and lose matches. Such a join can now 
emit rows below its
+  output watermark, which still assumes eviction by the event time, so a 
stateful operator after
+  it can drop them (SPARK-62001). With state format version 4, such a join 
cannot restart from a
+  checkpoint of an earlier version, or after a change of
+  `spark.sql.streaming.statefulOperator.allowMultiple`; start it with a new 
checkpoint. With
+  state format versions 1 to 3, it restarts, and rows that an earlier version 
evicted are not
+  restored. With `spark.sql.streaming.statefulOperator.allowMultiple` set to 
false, joins keep the
+  earlier behavior.
+
+- Since Spark 4.4, a range condition of a stream-stream join bounds the state 
of one input only
+  if it can be rearranged to `leftTime > rightTime + c` (or `>=`), where 
`rightTime` is the other
+  input's watermarked column, so that the cutoff rises with that watermark. 
For example,
+  `leftTime > rightTime - INTERVAL 5 SECONDS` bounds the state of the left 
input.
+  `CAST(leftTime AS LONG) > 10` no longer gives a cutoff, so it no longer 
holds back the cutoff of
+  other range conditions. `CAST(leftTime AS LONG) + CAST(rightTime AS LONG) > 
100` no longer
+  evicts state that later rows of the other input can still match. As a 
result, outer and semi
+  joins without a watermark in the join keys, whose only range condition has 
one of these forms,
+  fail analysis, also when an existing query restarts. To run such a query, 
add a range condition
+  that bounds the state, or a watermark in the join keys, and start it from a 
new checkpoint.
+
+- Since Spark 4.4, a stream-stream join also evicts the state of an input 
without its own
+  watermark when the other input's watermark and a range condition bound one 
of its TIMESTAMP
+  columns, for example `leftTime BETWEEN rightTime - INTERVAL 5 SECONDS AND 
rightTime +
+  INTERVAL 5 SECONDS` with a watermark only on `rightTime`. Earlier versions 
kept such state
+  forever and never emitted the unmatched rows of an outer join. With state 
format version 4, an
+  outer join that emits the unmatched rows of such an input cannot restart 
from a checkpoint of an
+  earlier version, or after a change of 
`spark.sql.streaming.statefulOperator.allowMultiple`;
+  start it with a new checkpoint. Other joins restart and keep the rows stored 
before the

Review Comment:
   **Nit (P3):** 'Other joins restart and keep the rows stored before the 
restart' holds only for state format 4, whose earlier rows of such an input are 
outside its index. On state formats 1 to 3, including the default 2, the 
restarted join evicts those rows through its value predicate once the cutoff 
passes them, and an outer join emits their unmatched rows then, possibly many 
in the first batch, as the state format 2 test of a row stored in legacy mode 
shows (StreamingJoinOneSidedWatermarkSuite.scala:151-180). Spelling out each 
format's restart outcome, as the first bullet of this section does for its 
case, would tell users of the default state format what to expect.
   
   **Verification:**
   - **Inspection:** The third bullet of the 4.3-to-4.4 section says that state 
format 4 joins other than the failing outer joins keep the earlier rows, and 
that state formats 1 to 3 evict them and emit an outer join's unmatched rows, 
matching the per-row eviction of those formats.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -362,6 +364,41 @@ 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.
+    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

Review Comment:
   **Nit (P3):** No test reaches this branch: the one-sided watermark suite and 
the state format 4 restart loop for inputs without their own watermark cover 
left and right outer, inner and left semi joins, although analysis accepts a 
full outer join with a watermark on only one input when the other input yields 
a cutoff (UnsupportedOperationChecker.scala:718-724). If this case returned 
false, an upgraded full outer join with a watermark only on rightTime would 
continue and never emit the left rows an earlier version kept out of the index, 
and no test would fail; that join's eviction and emission of the unwatermarked 
input never run in a test either. Full outer cases in both suites, including 
the restart from a checkpoint without the index version, would cover the branch 
and the eviction.
   
   **Verification:**
   - **Behavior:** A full outer join on `leftKey = rightKey AND leftTime 
BETWEEN rightTime - INTERVAL 5 SECONDS AND rightTime + INTERVAL 5 SECONDS` with 
a watermark only on rightTime emits an unmatched left row null-padded once the 
right watermark passes 10 seconds, on state formats 2 and 4.
   - **Regression:** On state format 4, restarting that full outer join from a 
checkpoint whose index version was removed fails with 
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE naming the left input, and the 
case fails if the full outer branch of the restart check stops rejecting it.



##########
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,
+              AttributeSet(otherSideInputAttributes), condition, watermark)
+          }
+        solve(eventTimeWatermarkForEviction).flatMap { case (column, 
stateValueWatermark) =>
+          // 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. Late-input filtering bounds only the 
event time, so a
+          // cutoff on another column always scans from the beginning.
+          val prevStateValueWatermark = 
eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+            solve(Some(lateWatermark)).collect {

Review Comment:
   Thanks, solving the bound over the whole input fixes the expiry example. The 
constant-only case this comment also named still loses rows on state format 4, 
though, and so does a conjunct with a negative watermark term: the bound is now 
solved with the solver from #60664, which no longer counts `CAST(lt AS LONG) > 
10` or a negative watermark term, while the earlier version kept them in its 
minimum. For a left outer join on `leftKey = rightKey AND lt > rt - INTERVAL 5 
SECONDS AND CAST(lt AS LONG) > 10` upgraded from 4.3, the first scan after the 
restart starts at the late-events watermark minus 5 seconds, so an unmatched 
left row between 10 seconds and that bound, which 4.3 kept, is never evicted 
and its null-padded row is never emitted, while state format 2 emits it after 
the same upgrade. Starting the first state format 4 eviction of each query run 
from the start of the index, as the original comment suggested, would cover 
both cases.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4616191565","thread_id":"inline:4616191565","verdict_sha256":"301f52b9019ed1eec686a2b7e780f57d521a914905d4f87ed49a99396bc2218a"}
 -->



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