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


##########
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 the pointer to #60713. The follow-up for an input evicted by 
another column is not part of this diff: with this stack, such a join, for 
example on `rightTime BETWEEN leftTime AND expiry`, still reports the cutoff 
solved over the whole input as that input's state watermark, so an Append-mode 
stateful operator after it silently drops rows that reached it on master. This 
review therefore still raises it as blocking for this pull request. Landing 
that follow-up before this stack merges, or adding the guard for this case to 
#60667 or here, would resolve it.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4616191497","thread_id":"inline:4616191497","verdict_sha256":"0faa63c127797b5996257a15931623ef6297099eddb8ea4fec1a95091f52a9d9"}
 -->



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -261,28 +265,63 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             eventTimeWatermarkForEviction.get,
             prevStateKeyWatermark)
         }
-      } else if (isWatermarkDefinedOnInput) { // case 2 in the 
StreamingSymmetricHashJoinExec docs
-        val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
-          attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-          attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-          condition,
-          eventTimeWatermarkForEviction)
-        // A row can pass late-input filtering but already be eligible for 
eviction in this batch.
-        // When the previous join-derived state cutoff is ahead of the 
late-input watermark, a new
-        // row can fall at or below that cutoff. V4 must scan from the 
beginning to find such rows.
-        val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap 
{ lateWatermark =>
+      } else if (isWatermarkDefinedOnInput || !useFirstEventTimeColumn) {
+        // 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))
+        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.
+        // An input without its own watermark that the condition bounds only 
through a cast gets
+        // no cutoff.
+        // 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, or not
+        //  at all when it has no watermark of its own.
+        def solve(watermark: Option[Long]): Option[(Attribute, Long, Boolean)] 
= {
+          val picked = if (useFirstEventTimeColumn) None else {
+            
StreamingJoinHelper.getStateValueWatermarkColumn(oneSideInputAttributes,
+              AttributeSet(otherSideInputAttributes), condition, watermark)
+          }
+          picked.map { case (c, w) => (c, w, true) }.orElse {
+            for (e <- eventTime; w <- wholeInput(watermark)) yield (e, w, 
false)

Review Comment:
   **Blocking (P1):** With the rising-only rule, `wholeInput` no longer takes 
constant-only and negative-sign conjuncts into its minimum, and this fallback 
applies that cutoff to the event time although it was solved for another 
column. On the base branch such a conjunct held the cutoff back. Reading the 
code for a left outer join on `leftKey = rightKey AND CAST(leftDate AS 
TIMESTAMP) >= rightTime AND CAST(leftTime AS LONG) > 10` with watermarks on 
leftTime and rightTime: the base branch capped the leftTime cutoff at 10 s, 
which evicts only rows the left-only filter never stores, so the left row (1, 
leftTime 100 s, leftDate 1970-01-05) stays and later matches the right row (1, 
rightTime 200 s). With this change the cutoff from leftDate evicts that row 
once the watermark passes 100 s, the join emits (1, null), and the later right 
row finds no match. An inner join with `CAST(leftTime AS LONG) + CAST(rightTime 
AS LONG) > 100` in place of the constant loses matches the same way, and so d
 oes any other-column bound with 
spark.sql.streaming.statefulOperator.allowMultiple set to false, for example 
`rightTime BETWEEN leftTime AND expiry AND CAST(leftTime AS LONG) > 10`.
   
   When the event time has no rising cutoff of its own, taking this fallback's 
cutoff and its state format 4 scan start from the base branch's minimum over 
all conjuncts (`getStateValueWatermark` with `risingCutoffsOnly = false`) would 
restore those matches. The rising-only rule would still apply to every picked 
column, to an event time that has its own rising cutoff, to the analysis check 
and to the state format 4 probe ranges. The migration-guide sentence about this 
case would then say that such conjuncts still hold the cutoff back, as in 
earlier versions.
   
   **Verification:**
   - **Regression:** With watermarks on leftTime and rightTime and state 
formats 2 and 4, a left outer join keeps a left row whose leftTime is below the 
watermark, and matches it with a right row of a later micro-batch that the 
condition still admits instead of emitting the left row null-padded, both in 
the default mode on `leftKey = rightKey AND CAST(leftDate AS TIMESTAMP) >= 
rightTime AND CAST(leftTime AS LONG) > 10` and with 
spark.sql.streaming.statefulOperator.allowMultiple set to false on `leftKey = 
rightKey AND rightTime BETWEEN leftTime AND expiry AND CAST(leftTime AS LONG) > 
10`.
   - **Regression:** With `CAST(leftTime AS LONG) + CAST(rightTime AS LONG) > 
100` in place of the constant-only conjunct in both conditions, an inner join, 
once the watermark passes 50 seconds, keeps a left row whose leftTime lies 
between 100 seconds minus the watermark and the watermark, and matches it with 
a right row of a later micro-batch, in the default mode and with 
spark.sql.streaming.statefulOperator.allowMultiple set to false, as the base 
branch does.
   - **Compatibility:** With spark.sql.streaming.statefulOperator.allowMultiple 
set to false, a left outer join on `leftKey = rightKey AND leftTime > rightTime 
- INTERVAL 5 SECONDS AND CAST(leftTime AS LONG) > 10` still emits an unmatched 
left row null-padded and removes it from state once the watermark passes its 
leftTime plus 5 seconds, because its event time has a rising cutoff of its own.



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

Review Comment:
   **Blocking (P1):** Solving the right input's event time on its own raises 
its cutoff, and that cutoff decides whether a left semi join keeps a right row: 
the right side's completion check skips storing a row the value predicate 
already matches, on the assumption that this batch's left rows have probed it, 
but a left semi join processes the right input first. Reading the code for `l.k 
= r.k AND l.t BETWEEN r.e - INTERVAL 1 HOUR AND r.e AND r.x >= l.t - INTERVAL 3 
HOURS` with delay 0 on both inputs: after a batch with events at 10 h, a batch 
that runs before any no-data batch evicts at 10 h but filters late rows at 0. 
Its right row (k, e = 8 h, x = 8 h) and left row (k, t = 7.5 h) match. The base 
branch tested the right row against the whole-input cutoff of 7 h on r.e and 
stored it, so (k, 7.5 h) was emitted. With this change the cutoff is 10 h, so 
the right row is not stored, the left row finds nothing, and the end-of-batch 
eviction at 9 h removes it unmatched. A plain `l.t BETWEEN
  r.e - INTERVAL 1 HOUR AND r.e` already loses such matches on the base branch; 
the raised cutoffs widen the range of right rows the skip drops.
   
   **Recommended change:** In AddingProcessedRowToStateCompletionIterator in 
StreamingSymmetricHashJoinExec.scala, store every processed right row of a left 
semi join instead of skipping one that the key or value predicate marks as 
evicting in this batch, and leave its removal to the end-of-batch eviction that 
a left semi join already runs on both sides; keep the skip for inner and outer 
joins, whose left rows probe before the right ones. Add left semi join tests.
   
   **Why this works:** With the row in state, this batch's left rows, which 
pass late filtering against the previous batch's watermark, find it when they 
probe, and the end-of-batch removeOldState removes it with the other right rows 
at or below the cutoff, so no admitted left row misses a match whatever the 
right cutoff is.
   
   **Compatibility:** Inner and outer joins keep skipping right rows that this 
batch's left rows have already probed, and a left semi join still emits each 
matched left row once.
   
   **Risks:** Right rows of a left semi join that arrive at or below the cutoff 
are now written to state and removed in the same batch, which adds state store 
writes and, with state format 4, index merges and deletes for those rows; 
results only gain the matches that were lost.
   
   **Constraints:** The change applies only to left semi joins; inner and outer 
joins keep skipping right rows that this batch's left rows have already probed. 
A matched left row of a left semi join must still be emitted once and removed 
from state as today.
   
   **Verification:**
   - **Regression:** In the default mode with delay 0 on both inputs and state 
formats 2 and 4, a left semi join on `l.k = r.k AND l.t BETWEEN r.e - INTERVAL 
1 HOUR AND r.e AND r.x >= l.t - INTERVAL 3 HOURS`, given a batch with events at 
10 hours on both inputs and then, in one micro-batch before any no-data batch, 
right (k, e = 8 h, x = 8 h) and left (k, t = 7.5 h), emits (k, 7.5 h).
   - **Regression:** In the same setting, a left semi join on `l.k = r.k AND 
l.t BETWEEN r.e - INTERVAL 1 HOUR AND r.e` emits the match of a left row with a 
right row of the same micro-batch whose r.e lies between the previous and the 
current watermark, a match the base branch also loses.
   - **Compatibility:** A left semi join emits each matched left row once and, 
after the batch, holds no right row at or below the right input's cutoff, and 
inner and right outer joins store the same right rows as before.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,18 +753,30 @@ case class StreamingSymmetricHashJoinExec(
         Predicate.create(Literal(false), Seq.empty).eval _ // false = do not 
remove if no predicate
     }
 
-    private[this] val stateValueWatermarkPredicateFunc = 
stateWatermarkPredicate match {
-      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)
 
+    // When the join condition bounds the column that the value predicate 
tests, a row with a NULL
+    // in it can never match, and `column <= cutoff` never holds for it. The 
legacy mode, and the
+    // default mode for an input bounded only through a column cast to 
TIMESTAMP, test the event
+    // time, which the condition need not bound.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _, true)) =>
+        Predicate.create(IsNull(column), inputAttributes).eval _
+      case _ => _ => false
+    }
+
+    // Such a row is not stored, but an earlier version or the legacy mode can 
have stored one.
+    private[this] val stateValueWatermarkPredicateFunc = 
stateWatermarkPredicate match {
+      case Some(JoinStateValueWatermarkPredicate(expr, _, _, _)) =>
+        val predicate = Predicate.create(expr, inputAttributes)
+        (row: UnsafeRow) => predicate.eval(row) || isEvictionColumnNull(row)

Review Comment:
   **Nit (P3):** For every predicate on a column the default mode picked, which 
includes ordinary time-interval joins with watermarks on both inputs, this 
closure makes two generated-predicate calls for each value that eviction keeps 
on state formats 1 to 3, and for each right input row in the completion check, 
where the IsNull half is always false because such rows were screened on 
arrival; the base branch made one call. Building this function from 
`Predicate.create(Or(expr, IsNull(column)), inputAttributes)` when 
`conditionBoundsColumn` is true, and from `expr` alone otherwise, returns the 
same results with one call, and `isEvictionColumnNull` can stay for the arrival 
screen.
   
   **Verification:**
   - **Inspection:** When the default mode picked the column, the function that 
eviction and the right side's completion check call compiles `column <= cutoff 
OR column IS NULL` as a single predicate, and the function for a predicate 
without a picked column is unchanged.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4399,6 +4399,26 @@ 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.4 and " +
+        "earlier and with spark.sql.streaming.statefulOperator.allowMultiple 
set to false, " +
+        "keeping the rows of an input without an event time out of the index. 
1: by the column " +

Review Comment:
   **Nit (P3):** The restart failures listed here now match the check, but the 
doc still describes each version as an ordering, and the new clause 'keeping 
the rows of an input without an event time out of the index' does not hold for 
new rows. Under version 0 in the default mode, an inner or left semi join with 
a watermark only on rightTime and `leftTime BETWEEN rightTime - INTERVAL 5 
SECONDS AND rightTime + INTERVAL 5 SECONDS` passes the restart check, and state 
format 4 then orders the left input's new rows by leftTime and writes their 
index entries, because the state manager follows the run's predicate column 
whatever version the checkpoint recorded. Describing 0 as the layout of a 
checkpoint written by 4.4 or earlier, or started with 
spark.sql.streaming.statefulOperator.allowMultiple set to false, and 1 as that 
of a checkpoint started with it set to true, saying that new rows follow the 
column the current run evicts by, and naming allowMultiple instead of 'the 
default mode' and 
 'the legacy mode' would match the code. 'With 0, the default mode fails to 
run' also reads as if it meant the conf's default, which is 1.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60669#discussion_r4623031782).
   
   **Verification:**
   - **Inspection:** Read against the state format 4 restart check in 
StreamingSymmetricHashJoinExec and the ordering column of 
SymmetricHashJoinStateManagerV4, the doc no longer presents the version as 
choosing the ordering or says that version 0 keeps new rows of an input without 
an event time out of the index, and it refers to allowMultiple rather than to 
undefined modes.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -73,12 +73,15 @@ object StreamingSymmetricHashJoinHelper extends Logging {
   }
   /**
    * Predicate for watermark on state values. See 
[[JoinStateKeyWatermarkPredicate]] for
-   * the semantics of `stateWatermark` and `prevStateWatermark`.
+   * the semantics of `stateWatermark` and `prevStateWatermark`. 
`conditionBoundsColumn` is true

Review Comment:
   **Nit (P3):** In the legacy mode, a time-interval join on `rightTime BETWEEN 
leftTime AND leftTime + INTERVAL 10 MINUTES` tests leftTime, which the 
condition bounds, yet `solve` returns `bounds = false` for every legacy-mode 
and event-time fallback predicate, so the flag is false and a row with a NULL 
leftTime is still stored, as the helper-suite and legacy-mode range eviction 
tests expect. A maintainer who trusts this doc could set the flag there and 
change the legacy mode's NULL handling. Saying that the flag is true only when 
the default mode evicts by a column that getStateValueWatermarkColumn picked 
because the condition bounds it, and false in the legacy mode and the 
event-time fallback, would match the code.
   
   **Verification:**
   - **Inspection:** Read against getStateWatermarkPredicates, the doc of 
conditionBoundsColumn matches the branches that set it to true and to false, 
including a legacy-mode time-interval join whose condition bounds the event 
time.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinRangeEvictionSuite.scala:
##########
@@ -0,0 +1,626 @@
+/*
+ * 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 java.io.File
+import java.nio.charset.StandardCharsets.UTF_8
+import java.nio.file.Files
+
+import org.apache.hadoop.fs.Path
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap, 
OffsetSeq, OffsetSeqLog}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+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
+import org.apache.spark.util.Utils
+
+@SlowSQLTest
+class StreamingJoinRangeEvictionSuite 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)
+  }
+
+  // The left input has the event time leftTime and another TIMESTAMP column 
expiry. A negative
+  // start or end gives a NULL leftTime or expiry.
+  private def joinWithExpiry(range: String, joinType: String)
+      : (MemoryStream[(Int, Long, Long)], MemoryStream[(Int, Long)], 
DataFrame) = {
+    val leftInput = MemoryStream[(Int, Long, Long)]
+    val rightInput = MemoryStream[(Int, Long)]
+    val left = leftInput.toDF().toDF("leftKey", "start", "end")
+      .select($"leftKey", when($"start" >= 0, 
timestamp_seconds($"start")).as("leftTime"),
+        when($"end" >= 0, timestamp_seconds($"end")).as("expiry"))
+      .withWatermark("leftTime", "60 seconds")
+    val right = rightInput.toDF().toDF("rightKey", "time")
+      .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+      .withWatermark("rightTime", "60 seconds")
+    val condition = expr(s"leftKey = rightKey AND $range")
+    val joined = if (joinType == "right_outer") {
+      right.join(left, condition, joinType)
+    } else {
+      left.join(right, condition, joinType)
+    }
+    val result = joined.select($"leftKey", 
$"rightTime".cast("long").as("matchTime"),
+      $"leftTime".cast("long"))
+    (leftInput, rightInput, result)
+  }
+
+  // State format 3 shares the eviction code of format 2.
+  for {
+    version <- Seq(2, 4)
+    joinType <- Seq("inner", "left_outer", "right_outer")
+    shape <- Seq("between", "conjunction", "upper", "interval")
+  } {
+    test(s"range eviction uses the bounded column, V$version $joinType 
$shape") {
+      withJoinConf(version) {
+        val range = shape match {
+          case "between" => "rightTime BETWEEN leftTime AND expiry"
+          case "conjunction" => "rightTime >= leftTime AND rightTime <= expiry"
+          case "interval" => "rightTime BETWEEN leftTime AND leftTime + 
INTERVAL 10 MINUTES"
+          case _ => "rightTime <= expiry"
+        }
+        val (leftInput, rightInput, result) = joinWithExpiry(range, joinType)
+        testStream(result)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)), 
AddData(rightInput, (9, 100L)))),
+          CheckNewAnswer(),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9, 
400L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 400L)),
+          // The watermark has passed the start time, but the range has not 
expired.
+          CheckNewAnswer(),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.eventTimeWatermarkForEviction.contains(340000L))
+          },
+          AddData(rightInput, (1, 460L)),
+          CheckNewAnswer(Row(1, 460L, 100L)),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9, 
1000L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 1100L)),
+          CheckNewAnswer((if (joinType != "inner") Seq(Row(2, null, 100L)) 
else Nil): _*)
+        )
+      }
+    }
+  }
+
+  for {
+    version <- Seq(2, 3, 4)
+    joinType <- Seq("left_outer", "right_outer")
+  } {
+    test(s"range eviction includes newly admitted expired values, V$version 
$joinType") {
+      withJoinConf(version) {
+        val (leftInput, rightInput, result) = joinWithExpiry("rightTime <= 
expiry", joinType)
+        testStream(result)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 100L, 700L)), AddData(rightInput, (9, 
100L)))),
+          CheckNewAnswer(),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9, 
400L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 400L)), CheckNewAnswer(),
+          // The start passes late filtering, but expiry is below the previous 
eviction cutoff.
+          AddData(leftInput, (3, 460L, 200L)), CheckNewAnswer(Row(3, null, 
460L)),
+          AddData(rightInput, (9, 500L)), CheckNewAnswer())
+      }
+    }
+  }
+
+  for {
+    version <- Seq(2, 4)
+    joinType <- Seq("left_outer", "right_outer")
+  } {
+    test(s"a row whose range-eviction column is NULL is emitted on arrival, 
V$version $joinType") {
+      withJoinConf(version) {
+        val (leftInput, rightInput, result) =
+          joinWithExpiry("rightTime BETWEEN leftTime AND expiry", joinType)
+        testStream(result)(
+          // The row can never match, so it is not stored, although the next 
eviction would remove
+          // it.
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, -1L), (2, 100L, 700L)), 
AddData(rightInput, (2, 150L)))),
+          CheckNewAnswer(Row(1, null, 100L), Row(2, 150L, 100L)),
+          assertNumStateRows(total = 2, updated = 2))
+      }
+    }
+  }
+
+  for (version <- Seq(2, 4)) {
+    test(s"a row whose event time is NULL is emitted on arrival, V$version") {
+      withJoinConf(version) {
+        val (leftInput, rightInput, result) = joinWithExpiry(
+          "rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES", 
"left_outer")
+        testStream(result)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, -1L, 700L), (2, 100L, 700L)), 
AddData(rightInput, (2, 150L)))),
+          CheckNewAnswer(Row(1, null, null), Row(2, 150L, 100L)),
+          assertNumStateRows(total = 2, updated = 2))
+      }
+    }
+  }
+
+  // The condition bounds the left input only through leftDate cast to 
TIMESTAMP, so the left
+  // input is evicted by leftTime with the cutoff from leftDate, as in earlier 
versions. A negative
+  // start gives a NULL leftTime, which the condition does not reference.
+  private def joinWithDate(joinType: String)
+      : (MemoryStream[(Int, Long, Int)], MemoryStream[(Int, Long)], DataFrame) 
= {
+    val leftInput = MemoryStream[(Int, Long, Int)]
+    val rightInput = MemoryStream[(Int, Long)]
+    val left = leftInput.toDF().toDF("leftKey", "start", "day")
+      .select($"leftKey", when($"start" >= 0, 
timestamp_seconds($"start")).as("leftTime"),
+        date_add(lit("1970-01-01").cast("date"), $"day").as("leftDate"))
+      .withWatermark("leftTime", "60 seconds")
+    val right = rightInput.toDF().toDF("rightKey", "time")
+      .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+      .withWatermark("rightTime", "60 seconds")
+    val result = left.join(right,
+      expr("leftKey = rightKey AND CAST(leftDate AS TIMESTAMP) >= rightTime"), 
joinType)
+      .select($"leftKey", $"rightTime".cast("long").as("matchTime"), 
$"leftTime".cast("long"))
+    (leftInput, rightInput, result)
+  }
+
+  for {
+    version <- Seq(2, 4)
+    joinType <- Seq("inner", "left_outer")
+  } {
+    test(s"an input bounded only through a cast column keeps the earlier 
eviction, " +
+        s"V$version $joinType") {
+      withJoinConf(version) {
+        val (leftInput, rightInput, result) = joinWithDate(joinType)
+        testStream(result)(
+          // The left row with a NULL leftTime and a leftDate of one day 
matches.
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, -1L, 1), (2, 100L, 0)), AddData(rightInput, 
(1, 100L)))),
+          CheckNewAnswer(Row(1, 100L, null)),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 400L, 0)), AddData(rightInput, (1, 400L)))),
+          CheckNewAnswer(Row(1, 400L, null)),
+          // The cutoff on leftTime is 340 s. State format 4 indexed the NULL 
leftTime as 0 and
+          // evicted it in the last batch.
+          AddData(rightInput, (1, 500L)),
+          CheckNewAnswer(
+            (if (version == 2) Seq(Row(1, 500L, null)) else Nil) ++
+              (if (joinType == "left_outer") Seq(Row(2, null, 100L)) else 
Nil): _*))
+      }
+    }
+  }
+
+  // The legacy mode stores rows by the earlier rule: it evicts by the event 
time, with the cutoff
+  // from expiry, and keeps a row whose event time is NULL.
+  for (version <- Seq(2, 4)) {
+    test(s"range eviction in the legacy mode keeps the earlier behavior, 
V$version") {
+      withJoinConf(version) {
+        withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+          val (leftInput, rightInput, result) =
+            joinWithExpiry("rightTime BETWEEN leftTime AND expiry", 
"left_outer")
+          testStream(result)(
+            StreamProgressLockedActions(Seq(
+              AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L), (3, -1L, 
700L)),
+              AddData(rightInput, (9, 100L)))),
+            CheckNewAnswer(),
+            assertNumStateRows(total = 4, updated = 4),
+            StreamProgressLockedActions(Seq(
+              AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9, 
400L)))),
+            // State format 4 indexes a NULL event time as 0.
+            CheckNewAnswer((if (version == 4) Seq(Row(3, null, null)) else 
Nil): _*),
+            AddData(rightInput, (9, 400L)),
+            CheckNewAnswer(Row(1, null, 100L), Row(2, null, 100L)),
+            AddData(rightInput, (1, 460L)),
+            CheckNewAnswer())
+        }
+      }
+    }
+  }
+
+  // An earlier version, like the legacy mode, stored a row whose expiry is 
NULL and evicted it by
+  // leftTime.
+  for (version <- Seq(2, 3)) {
+    test(s"a stored row whose range-eviction column is NULL is evicted, 
V$version") {
+      withJoinConf(version) {
+        withTempDir { checkpoint =>
+          val (leftInput, rightInput, result) =
+            joinWithExpiry("rightTime BETWEEN leftTime AND expiry", 
"left_outer")
+          withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") 
{
+            testStream(result)(
+              StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+              StreamProgressLockedActions(Seq(
+                AddData(leftInput, (1, 100L, -1L)), AddData(rightInput, (9, 
100L)))),
+              CheckNewAnswer(),
+              StreamProgressLockedActions(Seq(
+                AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9, 
400L)))),
+              CheckNewAnswer(),
+              StopStream)
+          }
+          testStream(result)(
+            StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+            AddData(rightInput, (9, 400L)),
+            CheckNewAnswer(Row(1, null, 100L)))
+        }
+      }
+    }
+  }
+
+  // In state format 4, the extra conjunct gives the right side a value 
predicate on rightTime, so
+  // that the range scan of the right joiner solves the bound that shifts by a 
column.
+  for {
+    bound <- Seq("leftTime > rightTime + rightDelay",
+      "CAST(leftTime AS BIGINT) + leftOffset > CAST(rightTime AS BIGINT)")
+    version <- Seq(2, 4)
+  } {
+    test(s"range eviction does not log solver errors for other columns: 
$bound, V$version") {
+      val logAppender = new LogAppender("stream-stream join state constraints")
+      withLogAppender(logAppender,
+          loggerNames = 
Seq(StreamingJoinHelper.getClass.getName.stripSuffix("$")),
+          level = Some(Level.WARN)) {
+        withJoinConf(version) {
+          val leftInput = MemoryStream[(Int, Long, Long)]
+          val rightInput = MemoryStream[(Int, Long, Int)]
+          val left = leftInput.toDF().toDF("leftKey", "time", "leftOffset")
+            .select($"leftKey", timestamp_seconds($"time").as("leftTime"), 
$"leftOffset")
+            .withWatermark("leftTime", "0 seconds")
+          val right = rightInput.toDF().toDF("rightKey", "time", "delay")
+            .select($"rightKey", timestamp_seconds($"time").as("rightTime"),
+              ($"delay" * expr("INTERVAL 1 SECOND")).as("rightDelay"))
+            .withWatermark("rightTime", "0 seconds")
+          val extra = if (version == 4) " AND leftTime < rightTime + INTERVAL 
1 HOUR" else ""
+          val joined = left.join(right, expr(s"leftKey = rightKey AND 
$bound$extra"))
+            .select($"leftKey", $"leftTime".cast("long"), 
$"rightTime".cast("long"))
+          testStream(joined)(
+            StreamProgressLockedActions(Seq(
+              AddData(leftInput, (1, 20L, 0L)), AddData(rightInput, (1, 10L, 
5)))),
+            CheckNewAnswer(Row(1, 20L, 10L)),
+            AddData(rightInput, (2, 30L, 1)),
+            CheckNewAnswer())
+        }
+      }
+      // A per-row column leaves the bound unknown, which is not an error.
+      assert(!logAppender.loggingEvents.exists(
+        _.getMessage.getFormattedMessage.contains("Error trying to extract 
state constraint")))
+    }
+  }
+
+  private val indexVersionKey = 
SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION.key
+
+  private def indexVersion(checkpoint: File): Option[String] = {
+    new OffsetSeqLog(spark, new File(checkpoint, 
"offsets").getCanonicalPath).getLatest().get._2
+      .metadataOpt.get.conf.get(indexVersionKey)
+  }
+
+  // Removes the V4 index version from the latest offset log entry, as older 
versions wrote it.
+  private def removeIndexVersion(checkpoint: File): Unit = {
+    val offsetsPath = new File(checkpoint, "offsets").getCanonicalPath
+    val log = new OffsetSeqLog(spark, offsetsPath)
+    val (batchId, offsets) = log.getLatest().get
+    val updated = offsets match {
+      case o: OffsetSeq =>
+        o.copy(metadataOpt = o.metadataOpt.map(m => m.copy(conf = m.conf - 
indexVersionKey)))
+      case o: OffsetMap =>
+        o.copy(metadata = o.metadata.copy(conf = o.metadata.conf - 
indexVersionKey))
+    }
+    val path = new Path(offsetsPath, batchId.toString)
+    assert(path.getFileSystem(spark.sessionState.newHadoopConf()).delete(path, 
false))
+    assert(log.add(batchId, updated))
+  }
+
+  // Copies a bundled checkpoint and points the copied operator metadata at 
the state schema files
+  // of the copy. The bundled metadata names them under the placeholder 
directory /checkpoint.
+  private def copyCheckpointFixture(name: String, checkpoint: File): Unit = {
+    Utils.copyDirectory(
+      new File(getClass.getResource(s"/structured-streaming/$name/").toURI), 
checkpoint)
+    val metadataDir = new File(checkpoint, "state/0/_metadata/v2")
+    metadataDir.listFiles().filter(f => f.isFile && 
!f.getName.startsWith(".")).foreach { file =>
+      val metadata = new String(Files.readAllBytes(file.toPath), UTF_8)
+      val updated = metadata.replace("file:/checkpoint/", new 
Path(checkpoint.toURI).toString + "/")
+      assert(updated != metadata, s"No state schema file is named in $file")
+      Files.write(file.toPath, updated.getBytes(UTF_8))
+    }
+  }
+
+  test("V4 restart from an older checkpoint keeps evicting by the event time") 
{
+    withJoinConf(4) {
+      withTempDir { checkpoint =>
+        val (leftInput, rightInput, result) = joinWithExpiry(
+          "rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES", 
"left_outer")
+        testStream(result)(
+          StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)), 
AddData(rightInput, (9, 100L)))),
+          CheckNewAnswer(),
+          StopStream)
+        assert(indexVersion(checkpoint) === Some("1"))
+        removeIndexVersion(checkpoint)
+        testStream(result)(
+          StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+          AddData(rightInput, (1, 160L)),
+          CheckNewAnswer(Row(1, 160L, 100L)),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9, 
1000L)))),
+          CheckNewAnswer(),
+          // The cutoff on leftTime is 340 s.
+          AddData(rightInput, (9, 1000L)),
+          CheckNewAnswer(Row(2, null, 100L)),
+          StopStream)
+        assert(indexVersion(checkpoint) === Some("0"))
+      }
+    }
+  }
+
+  // The legacy mode orders the state by the event time.
+  for (legacyFirst <- Seq(true, false)) {
+    test("V4 restart fails when the legacy mode changes and the condition 
bounds another " +
+        s"column, legacy first=$legacyFirst") {
+      withJoinConf(4) {
+        withTempDir { checkpoint =>
+          val (leftInput, rightInput, result) =
+            joinWithExpiry("rightTime BETWEEN leftTime AND expiry", 
"left_outer")
+          withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> 
(!legacyFirst).toString) {
+            testStream(result)(
+              StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+              StreamProgressLockedActions(Seq(
+                AddData(leftInput, (1, 100L, 700L)), AddData(rightInput, (9, 
100L)))),
+              CheckNewAnswer(),
+              StopStream)
+          }
+          assert(indexVersion(checkpoint) === Some(if (legacyFirst) "0" else 
"1"))
+          withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> 
legacyFirst.toString) {
+            testStream(result)(
+              StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+              AddData(rightInput, (9, 400L)),
+              ExpectFailure[AnalysisException] { e =>
+                checkError(
+                  e.asInstanceOf[AnalysisException],
+                  condition = 
"STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE",
+                  parameters = Map("side" -> "left", "column" -> "`expiry`"))
+              })
+          }
+          // The failed restart keeps the recorded version.
+          assert(indexVersion(checkpoint) === Some(if (legacyFirst) "0" else 
"1"))
+        }
+      }
+    }
+  }
+
+  // The legacy mode, like earlier versions, evicted left rows only up to the 
lower cutoff from
+  // expiry, so the V4 scan after the restart must start at or below that 
cutoff.
+  test("V4 restart evicts rows between the earlier and the new cutoff") {
+    withJoinConf(4) {
+      withTempDir { checkpoint =>
+        val (leftInput, rightInput, result) = joinWithExpiry("leftTime >= " +
+          "rightTime - INTERVAL 10 SECONDS AND expiry >= rightTime - INTERVAL 
100 SECONDS",
+          "left_outer")
+        withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+          testStream(result)(
+            StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+            StreamProgressLockedActions(Seq(
+              AddData(leftInput, (1, 900L, 5000L), (8, 1000L, 5000L)),
+              AddData(rightInput, (9, 1000L)))),
+            CheckNewAnswer(),
+            // The watermark is 940 s, and the cutoff from expiry keeps 
leftTime 900 s.
+            AddData(rightInput, (9, 1000L)),
+            CheckNewAnswer(),
+            StopStream)
+        }
+        testStream(result)(
+          StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+          AddData(rightInput, (9, 1300L)),
+          CheckNewAnswer(Row(1, null, 900L)))
+      }
+    }
+  }
+
+  // Within a run, the V4 scan of the left input starts at the event time's 
own cutoff, which is
+  // above the cutoff from expiry.
+  test("V4 range eviction by the event time over several batches of a run") {
+    withJoinConf(4) {
+      val (leftInput, rightInput, result) = joinWithExpiry("leftTime >= " +
+        "rightTime - INTERVAL 10 SECONDS AND expiry >= rightTime - INTERVAL 
100 SECONDS",
+        "left_outer")
+      testStream(result)(
+        StreamProgressLockedActions(Seq(
+          AddData(leftInput, (1, 900L, 5000L), (8, 1000L, 5000L)),
+          AddData(rightInput, (9, 1000L)))),
+        CheckNewAnswer(),
+        // The watermark is 940 s, so the cutoff on leftTime is 930 s.
+        AddData(rightInput, (9, 1000L)),
+        CheckNewAnswer(Row(1, null, 900L)),
+        StreamProgressLockedActions(Seq(
+          AddData(leftInput, (2, 1200L, 5000L)), AddData(rightInput, (9, 
1300L)))),
+        CheckNewAnswer(),
+        // The watermark is 1140 s, so the cutoff on leftTime is 1130 s.
+        AddData(rightInput, (2, 1300L)),
+        CheckNewAnswer(Row(8, null, 1000L)),
+        AddData(rightInput, (9, 1300L)),
+        CheckNewAnswer())
+    }
+  }
+
+  // A legacy-mode restart of a checkpoint that orders the state by the event 
time works.
+  test("V4 restart in the legacy mode of a join evicted by the event time") {
+    withJoinConf(4) {
+      withTempDir { checkpoint =>
+        val (leftInput, rightInput, result) = joinWithExpiry(
+          "rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES", 
"left_outer")
+        testStream(result)(
+          StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)), 
AddData(rightInput, (9, 100L)))),
+          CheckNewAnswer(),
+          StopStream)
+        assert(indexVersion(checkpoint) === Some("1"))
+        withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+          testStream(result)(
+            StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+            AddData(rightInput, (1, 160L)),
+            CheckNewAnswer(Row(1, 160L, 100L)),
+            StreamProgressLockedActions(Seq(
+              AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9, 
1000L)))),
+            CheckNewAnswer(),
+            AddData(rightInput, (9, 1000L)),
+            CheckNewAnswer(Row(2, null, 100L)))
+        }
+      }
+    }
+  }
+
+  test("V4 restart in the legacy mode fails for the right input that is 
evicted by another " +
+      "column") {
+    withJoinConf(4) {
+      withTempDir { checkpoint =>
+        val (leftInput, rightInput, result) =
+          joinWithExpiry("rightTime BETWEEN leftTime AND expiry", 
"right_outer")
+        testStream(result)(
+          StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, 700L)), AddData(rightInput, (9, 
100L)))),
+          CheckNewAnswer(),
+          StopStream)
+        withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+          testStream(result)(
+            StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+            AddData(rightInput, (9, 400L)),
+            ExpectFailure[AnalysisException] { e =>
+              checkError(
+                e.asInstanceOf[AnalysisException],
+                condition = "STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE",
+                parameters = Map("side" -> "right", "column" -> "`expiry`"))
+            })
+        }
+      }
+    }
+  }
+
+  // Only state format 4 orders the state by the column, and the check covers 
both inputs.
+  for ((version, joinType) <- Seq((2, "left_outer"), (4, "right_outer"))) {
+    test(s"restart from a checkpoint without the index version, V$version 
$joinType") {
+      withJoinConf(version) {
+        withTempDir { checkpoint =>
+          val (leftInput, rightInput, result) =
+            joinWithExpiry("rightTime BETWEEN leftTime AND expiry", joinType)
+          testStream(result)(
+            StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+            StreamProgressLockedActions(Seq(
+              AddData(leftInput, (1, 100L, 700L)), AddData(rightInput, (9, 
100L)))),
+            CheckNewAnswer(),
+            StopStream)
+          removeIndexVersion(checkpoint)
+          testStream(result)(
+            StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+            AddData(rightInput, (1, 460L)),
+            if (version == 4) {
+              ExpectFailure[AnalysisException] { e =>
+                checkError(
+                  e.asInstanceOf[AnalysisException],
+                  condition = 
"STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE",
+                  parameters = Map("side" -> "right", "column" -> "`expiry`"))
+              }
+            } else {
+              CheckNewAnswer(Row(1, 460L, 100L))
+            })
+        }
+      }
+    }
+  }
+
+  // An earlier version kept the rows of an input without its own watermark 
out of the V4 index.
+  // Outer joins would never emit them, while inner and left semi joins still 
find them.
+  for (joinType <- Seq("left_outer", "right_outer", "full_outer", "inner", 
"left_semi")) {
+    test(s"V4 restart from an older checkpoint for an input without its own 
watermark, $joinType") {
+      withJoinConf(4) {
+        withTempDir { checkpoint =>
+          val leftInput = MemoryStream[(Int, Long)]
+          val rightInput = MemoryStream[(Int, Long)]
+          val left = leftInput.toDF().toDF("leftKey", "time")
+            .select($"leftKey", timestamp_seconds($"time").as("leftTime"))
+          val right = rightInput.toDF().toDF("rightKey", "time")
+            .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+          val (stateInput, watermarkInput, joined) = if (joinType == 
"right_outer") {
+            (rightInput, leftInput, left.withWatermark("leftTime", "10 
seconds").join(right,
+              expr("leftKey = rightKey AND rightTime BETWEEN " +
+                "leftTime - INTERVAL 5 SECONDS AND leftTime + INTERVAL 5 
SECONDS"),
+              joinType).select($"rightKey"))
+          } else {
+            (leftInput, rightInput, left.join(right.withWatermark("rightTime", 
"10 seconds"),
+              expr("leftKey = rightKey AND leftTime BETWEEN " +
+                "rightTime - INTERVAL 5 SECONDS AND rightTime + INTERVAL 5 
SECONDS"),
+              joinType).select($"leftKey"))
+          }
+          testStream(joined)(
+            StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+            AddData(stateInput, (1, 5L)),
+            CheckNewAnswer(),
+            StopStream)
+          removeIndexVersion(checkpoint)

Review Comment:
   **Nit (P3):** Removing the index version changes only the offset log: the 
first run already gave the input without its own watermark a value predicate, 
so state format 4 stored its rows by leftTime or rightTime with index entries, 
while an earlier version, like a legacy-mode run, stores them under random 
bucket timestamps without index entries. If state format 4 stopped finding such 
rows, for example by probing that input with a timestamp range, the inner and 
left_semi cases would still pass, although the comment above the loop says 
these joins 'still find' the old rows. Writing the first run with 
spark.sql.streaming.statefulOperator.allowMultiple set to false, which builds 
that layout and records index version 0, and then restarting in the default 
mode would let the inner and left semi expectations check it.
   
   **Verification:**
   - **Regression:** With state format 4, an inner join with a watermark only 
on rightTime and a left semi join with a watermark only on the right input, 
whose first run with spark.sql.streaming.statefulOperator.allowMultiple set to 
false stored a left row without an index entry, restart in the default mode and 
match that row with a later right row, and the left semi join emits it exactly 
once across two matching right rows.



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