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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -602,8 +615,15 @@ class IncrementalExecution(
         // The prevOffsetSeqMetadata.isDefined check guards against the first 
batch, where
         // watermark propagation yields Some(0) for late events even though no 
state has been
         // evicted yet, which would incorrectly skip entries at timestamp 0.
+        //
+        // On the first batch after restoring a checkpoint with older join 
watermark semantics,
+        // the late-events watermark comes from re-simulating the previous 
batch with this
+        // version's output watermarks. It can be above the watermark that the 
older version
+        // evicted with, for example when this version leaves an unbounded 
input out of an
+        // upstream join's output watermark. Scan from the start once in that 
batch.
         val prevBatchLateEventsWm =
-          if (prevOffsetSeqMetadata.isDefined && 
allowMultipleStatefulOperators) {
+          if (prevOffsetSeqMetadata.isDefined && 
allowMultipleStatefulOperators &&
+              !isFirstBatchWithOlderJoinWatermarkSemantics) {

Review Comment:
   **Blocking (P1):** This reset covers only checkpoints pinned to an older 
version, but this PR also makes a stream-stream join's output watermark depend 
on the plan above it: `withJoinOutputWatermarkSides` copies the inputs the 
tracer reaches from the next stateful operator, and the tracer does not cross 
nodes such as a stream-static join. On the first batch of a run, the fresh 
propagator re-simulates the previous batch with the current plan, and for a 
version-1 checkpoint that re-simulated late-events watermark becomes a 
downstream V4 join's exclusive scan start. So after a restart that changes the 
plan between two joins in a way that raises the upstream join's output 
watermark, such as removing a stream-static anti join used as a filter, the 
downstream join's scan can start above rows the previous run never evicted, 
against the guarantee `evictByTimestamp` documents for its start. In this 
review's worked example, traced through the code, the upstream join holds its 
output waterma
 rk at 0 before the restart, so the downstream left outer join evicts nothing; 
afterwards that join's left scan starts about 20 minutes below the global 
watermark, so impressions buffered below that start are never evicted and their 
null-padded rows are never emitted. On the base branch the upstream join's 
output watermark did not depend on the plan above it.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +292,229 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     JoinStateWatermarkPredicates(leftStateWatermarkPredicate, 
rightStateWatermarkPredicate)
   }
 
+  /** Keep each cutoff attached to the column constrained by the join 
condition. */
+  private def getStateValueWatermarkForInput(
+      inputAttributes: Seq[Attribute],
+      otherInputAttributes: Seq[Attribute],
+      condition: Option[Expression],
+      eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+    val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+    // First try the watermarked column. If it has no inferable bound, try the 
other timestamp
+    // columns in input schema order and use the first with a bound. This 
makes the indexed column
+    // deterministic for a fixed input schema and join condition.
+    val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+      attribute.dataType == TimestampType && 
!eventTime.exists(_.semanticEquals(attribute))
+    }
+    candidates.iterator.flatMap { attribute =>
+      StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+        AttributeSet(otherInputAttributes), condition, 
eventWatermark).map(attribute -> _)
+    }.take(1).toSeq.headOption
+  }
+
+  /**
+   * Conservatively prove that older state can use the current watermark 
semantics. Without
+   * watermarks there is no affected state. An input that neither version 
evicts keeps the same
+   * rows, but its state watermark in the join's output watermark changed, so 
such an input is
+   * accepted only when no stateful operator after the join reads its event 
time:
+   * `consumedSides` names the inputs whose event time such an operator reads, 
both when the
+   * operator cannot be traced and none when no stateful operator follows. A 
key-only join, with
+   * no other condition and no equality key that uses an event time, is 
evicted by neither
+   * version, and V4 reads its rows by key prefix. Otherwise each side must 
have exactly one
+   * event-time column, and either its own event time must be the sole 
watermarked equality key
+   * at the same ordinal, or the join must be a time-interval join on the 
event times (see
+   * [[isOwnEventTimeIntervalJoin]]). This excludes other range bounds.
+   */
+  private[sql] def isWatermarkCheckpointCompatible(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      condition: Option[Expression],
+      consumedSides: Set[JoinSide]): Boolean = {
+    val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
+    val rightEventTime = rightAttributes.filter(_.metadata.contains(delayKey))
+    val keyOnly = condition.isEmpty && !(leftKeys ++ rightKeys).exists { key =>
+      key.references.exists(_.metadata.contains(delayKey)) || (key match {
+        case named: NamedExpression => named.metadata.contains(delayKey)
+        case _ => false
+      })
+    }
+
+    def watermarkKeyOrdinals(keys: Seq[Expression]): Seq[Int] = {
+      keys.zipWithIndex.collect {
+        case (key: NamedExpression, index) if key.metadata.contains(delayKey) 
=> index
+      }
+    }
+
+    def ownEventTimeKeyOrdinal(keys: Seq[Expression], eventTime: Attribute): 
Option[Int] = {
+      keys.zipWithIndex.collectFirst {
+        case (key: NamedExpression, index)
+            if key.metadata.contains(delayKey) && 
key.semanticEquals(eventTime) => index
+      }
+    }
+
+    val leftOrdinals = watermarkKeyOrdinals(leftKeys)
+    val rightOrdinals = watermarkKeyOrdinals(rightKeys)
+    if (leftEventTime.isEmpty && rightEventTime.isEmpty) {
+      leftOrdinals.isEmpty && rightOrdinals.isEmpty
+    } else if (keyOnly && consumedSides.isEmpty) {
+      true
+    } else if (leftEventTime.size == 1 && rightEventTime.size == 1) {
+      val leftOrdinal = ownEventTimeKeyOrdinal(leftKeys, leftEventTime.head)
+      val rightOrdinal = ownEventTimeKeyOrdinal(rightKeys, rightEventTime.head)
+      val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal == 
rightOrdinal &&
+        leftOrdinals == leftOrdinal.toSeq && rightOrdinals == 
rightOrdinal.toSeq
+      alignedOwnEventTimeKeys || isOwnEventTimeIntervalJoin(leftAttributes, 
rightAttributes,
+        leftKeys, rightKeys, condition, leftEventTime.head, 
rightEventTime.head, consumedSides)
+    } else {
+      false
+    }
+  }
+
+  /**
+   * Whether every ordering conjunct compares the two inputs' TIMESTAMP event 
times, each only
+   * cast or offset by constants (see 
[[StreamingJoinHelper.isConstantOffsetOf]]), and each event
+   * time either gets a range bound or gets none and is not in 
`consumedSides`. Older versions
+   * and this one solve such conjuncts the same way for columns with their own 
watermark, and
+   * older versions solved every column of an input but then found bounds only 
in the same
+   * conjuncts, so they derived the same value predicates, scan starts and V4 
index columns, and
+   * neither evicts an input that gets no bound. Old V4 stored a null event 
time at timestamp 0
+   * under the row's own key; both versions scan that entry the same way. No 
equality key may
+   * use an event time: older versions evicted such keys at the unshifted 
watermark. Time windows
+   * are excluded: older versions derived an ordering bound for them that this 
version removes.
+   */
+  private def isOwnEventTimeIntervalJoin(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      condition: Option[Expression],
+      leftEventTime: Attribute,
+      rightEventTime: Attribute,
+      consumedSides: Set[JoinSide]): Boolean = {
+    def conjuncts(e: Expression): Seq[Expression] = e match {
+      case And(left, right) => conjuncts(left) ++ conjuncts(right)
+      case other => Seq(other)
+    }
+    def eventTimeOf(e: Expression): Option[Attribute] =
+      Seq(leftEventTime, 
rightEventTime).find(StreamingJoinHelper.isConstantOffsetOf(e, _))
+    def comparesInputs(a: Expression, b: Expression): Boolean =
+      (eventTimeOf(a), eventTimeOf(b)) match {
+        case (Some(x), Some(y)) => !x.semanticEquals(y)
+        case _ => false
+      }
+    // The solver reads bounds only from these conjunct shapes; other 
conjuncts give no bound in
+    // either version.
+    val conditionIsInterval = condition.toSeq.flatMap(conjuncts).forall {

Review Comment:
   **Blocking (P1):** This requires every ordering conjunct to compare the two 
inputs' event times, so an interval join on the inputs' own event times that 
adds one more ordering conjunct neither version derives a bound from is still 
rejected on restart from an older checkpoint. Examples are `leftPrice >= 
rightPrice` between non-watermarked columns of both inputs, which the base 
branch's solver cannot evaluate and the new one finds no term for, and a month 
interval, which `collectTerms` cannot read in either version. For `leftKey = 
rightKey AND rightTime BETWEEN leftTime AND leftTime + INTERVAL 1 HOUR AND 
leftPrice >= rightPrice`, both versions evict the left side by `leftTime` and 
the right side by `rightTime` with the same cutoffs and derive the same output 
watermark, so the restart could resume, but it now fails with 
`STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE` and needs a new checkpoint and a 
replay. A comparison of one input's column with a constant is different: the 
base solver did
  turn it into a bound, so it should stay rejected.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60279#issuecomment-6775614175).
   
   **Recommended change:** In conditionIsInterval, also accept an ordering 
comparison that references attributes of both inputs and no watermarked 
attribute, and one the solver cannot read in either version because it contains 
a year-month interval, a calendar interval with months or another expression 
the solver does not support; judge each of a BETWEEN's two comparisons 
separately, as the solver reads them, so that every other comparison still has 
to compare the two event times; keep rejecting a comparison of one input's 
column with a constant. Update the migration guide's example of a rejected 
join, which names a month interval, and the stream-stream join checkpoint 
compatibility tests, so that the month-interval case resumes when nothing after 
the join reads the left event time, and add resuming cases with a comparison of 
non-time columns of both inputs.
   
   **Why this works:** Such comparisons give no bound in either version, so the 
remaining comparisons still decide each side's predicate and the existing 
per-side test decides acceptance.
   
   **Scope:** Widen the interval-join test of the restart compatibility check 
for comparisons that yield no bound in either version, and align the migration 
guide's example.
   
   **Risks:** Accepting a comparison that the base solver did read would let an 
older checkpoint resume with a different eviction; limiting the new acceptance 
to comparisons that reference both inputs and no watermarked attribute, and to 
unreadable expressions, judged separately for each half of a BETWEEN, keeps 
that set closed, and reverting restores the rejection.
   
   **Constraints:** Keep rejecting a one-input comparison with a constant, such 
as `leftTime > timestamp_seconds(1)` in an outer join's condition.
   
   **Success:** An older checkpoint of an interval join on the inputs' own 
event times with an extra comparison of non-time columns of both inputs resumes 
with the same results. An older month-interval checkpoint resumes when no 
stateful operator after the join reads the left event time. An older checkpoint 
with a one-input constant comparison in an outer join's condition, or with a 
BETWEEN whose other comparison bounds a column other than the event times, is 
still rejected. The migration guide no longer gives a month interval as an 
example of a join that is always rejected.
   
   **Verification:**
   - **Regression:** Restoring an older-marker checkpoint of `rightTime BETWEEN 
leftTime AND leftTime + INTERVAL 1 HOUR AND leftPrice >= rightPrice` resumes 
and matches later rows as the base branch would.
   - **Behavior:** The month-interval shape resumes with nothing after the join 
and is still rejected when a stateful operator after it reads leftTime.
   - **Compatibility:** The shapes the compatibility matrix rejects for another 
column, a constant conjunct, a negated event time and a shifted event-time key 
stay rejected.
   - **Inspection:** The migration guide's example of a rejected join matches 
the month-interval rule the check now applies.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -167,6 +170,16 @@ class IncrementalExecution(
   private val allowMultipleStatefulOperators: Boolean =
     
sparkSession.sessionState.conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
 
+  /**
+   * Whether this is the first batch of a run that restores a checkpoint 
pinned to older
+   * stream-stream join watermark semantics. Such a batch re-simulates the 
previous batch with
+   * this version's output watermarks, which the older version may not have 
evicted with.
+   */
+  private lazy val isFirstBatchWithOlderJoinWatermarkSemantics: Boolean = 
isFirstBatch &&

Review Comment:
   **Non-blocking (P2):** A checkpoint written before this change restores the 
missing marker as 0 and pins 0 again in every later offset log entry, so this 
is true on the first batch of every later run, not only the first run after the 
upgrade, and each V4 join then scans every eviction index from the start 
through the deletions of earlier evictions. From the second run on, the 
previous batch ran under this version, so the reason for the reset no longer 
holds; Spark 4.3.0 kept the scan start on every restart. Scheduled 
`Trigger.AvailableNow` or `Trigger.Once` jobs pay this on every run, and the 
cost grows with the deletions not yet compacted.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinCheckpointCompatibilitySuite.scala:
##########
@@ -0,0 +1,576 @@
+/*
+ * 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.file.Files
+
+import scala.jdk.CollectionConverters._
+import scala.util.Using
+
+import org.apache.hadoop.fs.Path
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeReference, Cast, Expression, GreaterThan}
+import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap, 
OffsetSeq, OffsetSeqLog}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.{StreamingSymmetricHashJoinExec,
 StreamingSymmetricHashJoinHelper}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinStateKeyWatermarkPredicate,
 JoinStateValueWatermarkPredicate, LeftSide, RightSide}
+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.sql.types.{IntegerType, LongType, MetadataBuilder, 
StructField, StructType, TimestampType}
+import org.apache.spark.tags.SlowSQLTest
+import org.apache.spark.util.Utils
+
+@SlowSQLTest
+class StreamingJoinCheckpointCompatibilitySuite extends StreamTest {
+  import testImplicits._
+
+  private val markerKey = 
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.key
+  private val currentMarker =
+    
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.defaultValue.get.toString
+
+  private def setMarker(checkpoint: String, marker: Option[String]): Unit = {
+    def update(conf: Map[String, String]): Map[String, String] = {
+      (conf - markerKey) ++ marker.map(markerKey -> _)
+    }
+    val offsetsPath = checkpoint + "/offsets"
+    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 = 
update(m.conf))))
+      case o: OffsetMap =>
+        o.copy(metadata = o.metadata.copy(conf = update(o.metadata.conf)))
+    }
+    val path = new Path(offsetsPath, batchId.toString)
+    assert(path.getFileSystem(spark.sessionState.newHadoopConf()).delete(path, 
false))
+    assert(log.add(batchId, updated))
+  }
+
+  private def snapshot(directory: File): Map[String, Seq[Byte]] = {
+    Using.resource(Files.walk(directory.toPath)) { paths =>
+      paths.iterator().asScala.filter(Files.isRegularFile(_)).map { path =>
+        directory.toPath.relativize(path).toString -> 
Files.readAllBytes(path).toSeq
+      }.toMap
+    }
+  }
+
+  private def pinnedMarker(checkpoint: String): Option[String] = {
+    new OffsetSeqLog(spark, checkpoint + 
"/offsets").getLatest().get._2.metadataOpt.get
+      .conf.get(markerKey)
+  }
+
+  private def markerAt(checkpoint: String, batchId: Long): Option[String] = {
+    new OffsetSeqLog(spark, checkpoint + 
"/offsets").get(batchId).get.metadataOpt.get
+      .conf.get(markerKey)
+  }
+
+  private def withJoinConf(version: Int, logVersion: Int)(f: => Unit): Unit = {
+    withSQLConf(
+        SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+        SQLConf.STREAMING_OFFSET_LOG_FORMAT_VERSION.key -> logVersion.toString,
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+        SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+  }
+
+  private def joinInputs(shape: String): (MemoryStream[(Int, Int)],
+      MemoryStream[(Int, Int)], DataFrame) = {
+    val leftInput = MemoryStream[(Int, Int)]
+    val rightInput = MemoryStream[(Int, Int)]
+    val leftData = leftInput.toDF().toDF("leftKey", "time")
+      .select($"leftKey", timestamp_seconds($"time").as("leftTime"),
+        timestamp_seconds($"time" + 10).as("expiry"))
+    val rightData = rightInput.toDF().toDF("rightKey", "time")
+      .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+    val left = if (Seq("equality", "expiry", "pruned expiry", "unbounded")
+        .contains(shape)) {
+      leftData.withWatermark("leftTime", "100 seconds")
+    } else {
+      leftData
+    }
+    val right = if (shape != "no watermark") {
+      rightData.withWatermark("rightTime", "100 seconds")
+    } else {
+      rightData
+    }
+    val condition = shape match {
+      case "range" => "leftKey = rightKey AND leftTime > rightTime - INTERVAL 
5 SECONDS"
+      case "expiry" => "leftKey = rightKey AND rightTime BETWEEN leftTime AND 
expiry"
+      case "pruned expiry" => "leftKey = rightKey AND rightTime <= expiry"
+      case "unbounded" => "leftKey = rightKey"
+      case _ => "leftKey = rightKey AND leftTime = rightTime"
+    }
+    val joined = left.join(right, expr(condition))
+    val result = if (shape == "unbounded") {
+      // A stateful operator after this key-only join reads its output 
watermark.
+      joined.select($"leftKey", $"rightKey", $"leftTime".cast("long"),
+        $"rightTime".cast("long")).dropDuplicates()
+    } else {
+      joined.select($"leftKey", $"rightKey")
+    }
+    (leftInput, rightInput, result)
+  }
+
+  test("checkpoint compatibility requires one aligned own-event-time equality 
key") {
+    val watermarkMetadata = new MetadataBuilder()
+      .putLong(EventTimeWatermark.delayKey, 0L).build()
+    val leftId = AttributeReference("leftId", IntegerType)()
+    val rightId = AttributeReference("rightId", IntegerType)()
+    val leftTime = AttributeReference("leftTime", TimestampType,
+      metadata = watermarkMetadata)()
+    val rightTime = AttributeReference("rightTime", TimestampType,
+      metadata = watermarkMetadata)()
+    val compatible = 
StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+      _: Seq[Attribute], _: Seq[Attribute], _: Seq[Expression], _: 
Seq[Expression], None,
+      consumedSides = Set(LeftSide, RightSide))
+
+    assert(compatible(Seq(leftId), Seq(rightId), Seq(leftId), Seq(rightId)))
+    assert(compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId, leftTime), Seq(rightId, rightTime)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId, leftTime), Seq(rightTime, rightId)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId, leftTime, leftTime), Seq(rightId, rightTime, rightTime)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId), Seq(rightId)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId),
+      Seq(leftId, leftTime), Seq(rightId, rightId)))
+    assert(!compatible(Seq(leftId), Seq(rightId, rightTime),
+      Seq(leftId, leftId), Seq(rightId, rightTime)))
+    assert(!compatible(Seq(leftTime, rightTime), Seq(rightTime),
+      Seq(leftTime), Seq(rightTime)))
+    assert(!compatible(Seq(leftTime), Seq(rightTime, leftTime),
+      Seq(leftTime), Seq(rightTime)))
+    // Metadata alone must not select an earlier key or hide a computed 
watermarked key.
+    val computed = Alias(leftTime, "computed")()
+    assert(!compatible(Seq(leftTime), Seq(rightTime),
+      Seq(computed, leftTime), Seq(rightTime, rightTime)))
+    assert(!compatible(Seq(leftId), Seq(rightId), Seq(computed), Seq(rightId)))
+
+    // A key-only join is accepted only when no stateful operator after it 
reads its output
+    // watermark. Another condition, or a key that uses an event time, makes 
it not key-only.
+    val notConsumed = 
StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+      _: Seq[Attribute], _: Seq[Attribute], _: Seq[Expression], _: 
Seq[Expression],
+      _: Option[Expression], consumedSides = Set.empty)
+    val leftInput = Seq(leftId, leftTime)
+    val rightInput = Seq(rightId, rightTime)
+    assert(notConsumed(leftInput, rightInput, Seq(leftId), Seq(rightId), None))
+    assert(!notConsumed(leftInput, rightInput, Seq(leftId), Seq(rightId),
+      Some(GreaterThan(leftId, rightId))))
+    assert(!notConsumed(leftInput, rightInput, Seq(leftId, Cast(leftTime, 
LongType)),
+      Seq(rightId, Cast(rightTime, LongType)), None))
+    assert(!notConsumed(leftInput, rightInput, Seq(leftId, computed), 
Seq(rightId, rightTime),
+      None))
+
+    // Ordering time windows is excluded even when nothing reads the output 
watermark: older
+    // versions derived an ordering bound for whole windows that this version 
removes.
+    val windowType = StructType(Seq(
+      StructField("start", TimestampType), StructField("end", TimestampType)))
+    val leftWindow = AttributeReference("leftWindow", windowType,
+      metadata = watermarkMetadata)()
+    val rightWindow = AttributeReference("rightWindow", windowType,
+      metadata = watermarkMetadata)()
+    assert(!notConsumed(Seq(leftId, leftWindow), Seq(rightId, rightWindow), 
Seq(leftId),
+      Seq(rightId), Some(GreaterThan(leftWindow, rightWindow))))
+  }
+
+  for {
+    version <- Seq(1, 2, 3, 4)
+    logVersion <- Seq(1, 2)
+    // Every marker below the current one takes the same rejection branch.
+    oldMarker <- Seq(None, Some("0"), Some((currentMarker.toInt - 
1).toString)).distinct
+    shape <- Seq("range", "expiry", "pruned expiry", "unbounded")
+  } {
+    test(s"reject old $shape checkpoint, V$version log=$logVersion 
old=$oldMarker") {
+      withJoinConf(version, logVersion) {
+        val (leftInput, rightInput, joined) = joinInputs(shape)
+        withTempDir { checkpointDir =>
+          val checkpoint = checkpointDir.getCanonicalPath
+          testStream(joined)(
+            StartStream(checkpointLocation = checkpoint),
+            MultiAddData(leftInput, (1, 10))(rightInput, (1, 10)),
+            CheckNewAnswer(if (shape == "unbounded") Row(1, 1, 10L, 10L)
+              else Row(1, 1)),
+            StopStream)
+          // Emulate old offset metadata. State is written by the current 
implementation;

Review Comment:
   **Nit (P3):** Every older checkpoint the compatibility suites accept is 
written by this build and only has its offset-log marker rewritten here, and 
the bundled historical join checkpoints are Spark 2.4.0 and 3.5.1 interval 
joins stopped at batch 0. So the claims about older V4 state, that it stored a 
NULL event time at timestamp 0 with an index entry and that the first-batch 
scan from the start finds every row the older version kept, have no committed 
test, and the round-2 chained-join reproduction is described in the PR but not 
committed. Two golden Spark 4.3.0 checkpoints in state format 4, a left outer 
interval join holding a NULL-time row and two chained joins, restored in this 
suite, would cover the upgrade path.
   
   **Verification:**
   - **Compatibility:** Both Spark 4.3.0 fixtures resume on this build with the 
expected outputs and leave no NULL-time row in state.
   - **Regression:** With the first-batch reset for checkpoints pinned to an 
older version removed, the single-join fixture keeps its NULL-time row in 
state, and with that reset and the one for joins that have a stream-stream join 
below them both removed, the chained-join fixture no longer emits its unmatched 
row.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -717,21 +727,94 @@ case class StreamingSymmetricHashJoinExec(
         Predicate.create(Literal(false), Seq.empty).eval _  // false = do not 
remove if no predicate
     }
 
+    // A NULL in the column that the state watermark predicate tests makes the 
predicate unknown,
+    // so eviction never removes the row. The row cannot match either: that 
column is an equality
+    // key, or a comparison in the join condition bounds it. Handle the row 
like one that fails
+    // the pre-join filter.
+    // The check takes the generated key and the input row, so the key is 
computed only once.
+    private[this] val isEvictionColumnNull: (UnsafeRow, UnsafeRow) => Boolean =
+      stateWatermarkPredicate match {
+        case Some(JoinStateKeyWatermarkPredicate(expr, _, _)) =>
+          // Only a NULL key fails equality. A struct key with a NULL field 
can still be equal.
+          val ordinal = expr.collectFirst { case b: BoundReference => 
b.ordinal }.get
+          (key, _) => key.isNullAt(ordinal)
+        case Some(JoinStateValueWatermarkPredicate(expr, _, _)) =>
+          val isNull = Predicate.create(IsNull(expr), inputAttributes)

Review Comment:
   **Nit (P3):** `expr` is the per-batch state predicate `column <= 
Literal(cutoff)`, and codegen inlines the cutoff, so each batch whose cutoff 
moves compiles another class in every executor JVM for each value-evicting 
side, on top of the existing eviction predicate, and adds a single-use entry to 
the codegen cache. `LessThanOrEqual` is null-intolerant and the literal is not 
null, so testing the compared column, or the window end field, for NULL gives 
the same result with generated code that stays the same across batches.
   
   **Verification:**
   - **Behavior:** Rows with a NULL range end or a NULL window are still 
emitted or dropped on arrival as the NULL eviction-column tests expect.
   - **Inspection:** The null check's expression contains no cutoff literal.



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,39 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Spark 4.4 holds back the output watermark of a stream-stream join when 
retained state can
+  still emit old event times. Downstream stateful operators may retain more 
state, take longer
+  to finalize results, or stop making progress while the join has no 
event-time eviction bound.
+  The join holds back only for an input whose event time reaches the next 
stateful operator: in
+  a join on `clickTime <= impressionTime + INTERVAL 1 HOUR`, a window 
aggregation over
+  `impressionTime` makes progress, and one over `clickTime` does not. Spark 
follows the event
+  time through projections, filters, unions, and time and session windows, to 
aggregations,
+  deduplication, stream-stream joins, and `flatMapGroupsWithState` or 
`transformWithState` with
+  event-time timeouts. When Spark cannot tell which input's event time the 
operator uses, for
+  example when the operator's event time is computed from the join output by a 
function, it
+  holds back for both inputs.
+
+- When restarting a stream-stream join from an older Spark version, Spark may 
reject the
+  existing checkpoint with `STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE`. Spark 
reuses the checkpoint
+  of a join without watermarks, of a join with an equality condition between 
the two inputs'
+  event times, such as `leftTime = rightTime`, and of a join whose time 
condition compares the
+  two inputs' event times, optionally cast, with constant intervals or 
numbers, such as

Review Comment:
   **Nit (P3):** Read literally, 'compares the two inputs' event times, 
optionally cast, with constant intervals or numbers' includes comparing an 
event time with a constant, which the check rejects: every ordering conjunct 
must compare the two event times with each other, and the compatibility suite 
rejects `leftTime > timestamp_seconds(1)` in a left outer join. Users could 
then skip preparing the replay the guide asks for. Suggested wording: 'compares 
the two inputs' event times with each other, each optionally cast and offset by 
constant intervals or numbers'.
   
   **Verification:**
   - **Inspection:** The migration note's reuse wording matches the accepted 
interval shapes and excludes one-input constant comparisons.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOutputWatermarkSuite.scala:
##########
@@ -0,0 +1,321 @@
+/*
+ * 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.sql.Timestamp
+
+import org.apache.spark.sql.{DataFrame, Encoders, Row}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinSide,
 LeftSide, RightSide}
+import org.apache.spark.sql.execution.streaming.runtime.{MemoryStream, 
StreamExecution}
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions.{col, count, expr, lit, session_window, 
timestamp_seconds, window}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinOutputWatermarkSuite extends StreamTest {
+  import testImplicits._
+
+  for (version <- Seq(2, 3, 4)) {
+    test(s"unbounded join state can emit an old event time after watermarks 
advance, V$version") {
+      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, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("key", "seconds")
+          .select($"key", timestamp_seconds($"seconds").as("leftTime"))
+          .withWatermark("leftTime", "10 seconds")
+        val right = rightInput.toDF().toDF("key", "seconds")
+          .select($"key", timestamp_seconds($"seconds").as("rightTime"))
+          .withWatermark("rightTime", "10 seconds")
+        val result = left.join(right, Seq("key"))
+          .select($"key", $"leftTime")
+          .dropDuplicatesWithinWatermark("key")
+          .select($"key", $"leftTime".cast("long"))
+
+        testStream(result)(
+          MultiAddData((leftInput, Seq((1, 5L))), (rightInput, Seq((9, 5L)))),
+          CheckNewAnswer(),
+          MultiAddData((leftInput, Seq((2, 30L))), (rightInput, Seq((3, 
30L)))),
+          CheckNewAnswer(),
+          // Process another batch so the join's output watermark reaches 
downstream operators.
+          AddData(rightInput, (4, 40L)),
+          CheckNewAnswer(),
+          // The retained left key 1 can still join after both input 
watermarks reach 20 seconds.
+          // The right event is newer than that watermark, but the joined left 
time is only 5.
+          AddData(rightInput, (1, 100L)),
+          CheckNewAnswer((1, 5L)),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.eventTimeWatermarkForLateEvents.contains(20000L))
+            assert(join.produceOutputWatermark(20000L).contains(0L))
+          })
+      }
+    }
+  }
+
+  // Impressions are bounded by the click watermark; clicks have no lower 
bound on clickTime.
+  private def oneDirectionalJoin(): (MemoryStream[(Int, Long)], 
MemoryStream[(Int, Long)],
+      DataFrame) = {
+    val impressionInput = MemoryStream[(Int, Long)]
+    val clickInput = MemoryStream[(Int, Long)]
+    val impressions = impressionInput.toDF().toDF("impressionAdId", "seconds")
+      .select($"impressionAdId", 
timestamp_seconds($"seconds").as("impressionTime"))
+      .withWatermark("impressionTime", "10 seconds")
+    val clicks = clickInput.toDF().toDF("clickAdId", "seconds")
+      .select($"clickAdId", timestamp_seconds($"seconds").as("clickTime"))
+      .withWatermark("clickTime", "10 seconds")
+    val joined = impressions.join(clicks,
+      expr("clickAdId = impressionAdId AND clickTime <= impressionTime + 
INTERVAL 10 SECONDS"))
+    (impressionInput, clickInput, joined)
+  }
+
+  private def windowCounts(
+      df: DataFrame,
+      timeColumn: String,
+      slide: String = "10 seconds"): DataFrame = {
+    df.groupBy(window(col(timeColumn), "10 seconds", 
slide)).agg(count("*").as("count"))
+      .select($"window.start".cast("long"), $"count")
+  }
+
+  // The join that reads the inputs, below any stream-stream join after it.
+  private def join(query: StreamExecution): StreamingSymmetricHashJoinExec = {
+    query.lastExecution.executedPlan.collect {
+      case j: StreamingSymmetricHashJoinExec
+          if 
!j.children.exists(_.exists(_.isInstanceOf[StreamingSymmetricHashJoinExec])) => 
j
+    }.head
+  }
+
+  private def runOneDirectionalJoin(
+      impressionInput: MemoryStream[(Int, Long)],
+      clickInput: MemoryStream[(Int, Long)],
+      result: DataFrame,
+      expectedRows: Seq[Row],
+      expectedSides: Option[Set[JoinSide]],
+      expectedOutputWatermark: Long): Unit = {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+      testStream(result, OutputMode.Append())(
+        MultiAddData((impressionInput, Seq((1, 5L), (2, 15L), (3, 25L))),
+          (clickInput, Seq((1, 8L), (2, 20L)))),
+        ProcessAllAvailable(),
+        // The click at 30 seconds joins the retained impression at 25 seconds.
+        MultiAddData((impressionInput, Seq((4, 60L))), (clickInput, Seq((3, 
30L), (9, 70L)))),
+        ProcessAllAvailable(),
+        MultiAddData((impressionInput, Seq((5, 100L))), (clickInput, Seq((9, 
110L)))),
+        ProcessAllAvailable(),
+        AddData(clickInput, (9, 150L)),
+        ProcessAllAvailable(),
+        AddData(impressionInput, (6, 200L)),
+        ProcessAllAvailable(),
+        CheckAnswer(expectedRows: _*),
+        Execute { query =>
+          val j = join(query)
+          assert(j.outputWatermarkSides == expectedSides)
+          assert(j.produceOutputWatermark(j.eventTimeWatermarkForEviction.get)
+            .contains(expectedOutputWatermark))
+          // No joined row arrives behind the watermark of the operator after 
the join.
+          assert(query.recentProgress.flatMap(_.stateOperators)
+            .map(_.numRowsDroppedByWatermark).sum == 0)
+        })
+    }
+  }
+
+  test("output watermark follows the bounded input when only its event time is 
used") {
+    val (impressionInput, clickInput, joined) = oneDirectionalJoin()
+    // Impressions are evicted below the click watermark (90 seconds) less 10 
seconds and 1 ms.

Review Comment:
   **Nit (P3):** In `runOneDirectionalJoin` the last batch's eviction watermark 
is 90 seconds because the impression input (100 seconds less 10) holds back the 
min-policy watermark; the click input's own watermark is 140 seconds by then. 
The asserted 79.999 seconds is that eviction watermark less 10 seconds and 1 
ms, so the comment should name the impression input as the one holding the 
watermark back, as the stream-stream join case further down does.
   
   **Verification:**
   - **Inspection:** The comment derives 79.999 seconds from the join's 
eviction watermark and names the input that holds it back.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -602,8 +615,15 @@ class IncrementalExecution(
         // The prevOffsetSeqMetadata.isDefined check guards against the first 
batch, where
         // watermark propagation yields Some(0) for late events even though no 
state has been
         // evicted yet, which would incorrectly skip entries at timestamp 0.
+        //
+        // On the first batch after restoring a checkpoint with older join 
watermark semantics,
+        // the late-events watermark comes from re-simulating the previous 
batch with this
+        // version's output watermarks. It can be above the watermark that the 
older version
+        // evicted with, for example when this version leaves an unbounded 
input out of an

Review Comment:
   **Nit (P3):** The older version already left an input without a bound out of 
a join's output watermark, because its state watermark was None and the minimum 
ignored it, and this version includes such an input as 0 unless the next 
operator does not read it, which gives the older value back. What can raise the 
re-simulated watermark is this version leaving out, through 
`outputWatermarkSides`, a bounded input that the next operator does not read 
but the older version included in the minimum. The comment also says the scan 
runs once, which the pinned marker does not ensure.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +292,229 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     JoinStateWatermarkPredicates(leftStateWatermarkPredicate, 
rightStateWatermarkPredicate)
   }
 
+  /** Keep each cutoff attached to the column constrained by the join 
condition. */
+  private def getStateValueWatermarkForInput(
+      inputAttributes: Seq[Attribute],
+      otherInputAttributes: Seq[Attribute],
+      condition: Option[Expression],
+      eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+    val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+    // First try the watermarked column. If it has no inferable bound, try the 
other timestamp
+    // columns in input schema order and use the first with a bound. This 
makes the indexed column
+    // deterministic for a fixed input schema and join condition.
+    val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+      attribute.dataType == TimestampType && 
!eventTime.exists(_.semanticEquals(attribute))
+    }
+    candidates.iterator.flatMap { attribute =>
+      StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+        AttributeSet(otherInputAttributes), condition, 
eventWatermark).map(attribute -> _)
+    }.take(1).toSeq.headOption
+  }
+
+  /**
+   * Conservatively prove that older state can use the current watermark 
semantics. Without
+   * watermarks there is no affected state. An input that neither version 
evicts keeps the same
+   * rows, but its state watermark in the join's output watermark changed, so 
such an input is
+   * accepted only when no stateful operator after the join reads its event 
time:
+   * `consumedSides` names the inputs whose event time such an operator reads, 
both when the
+   * operator cannot be traced and none when no stateful operator follows. A 
key-only join, with
+   * no other condition and no equality key that uses an event time, is 
evicted by neither
+   * version, and V4 reads its rows by key prefix. Otherwise each side must 
have exactly one
+   * event-time column, and either its own event time must be the sole 
watermarked equality key
+   * at the same ordinal, or the join must be a time-interval join on the 
event times (see
+   * [[isOwnEventTimeIntervalJoin]]). This excludes other range bounds.
+   */
+  private[sql] def isWatermarkCheckpointCompatible(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      condition: Option[Expression],
+      consumedSides: Set[JoinSide]): Boolean = {
+    val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
+    val rightEventTime = rightAttributes.filter(_.metadata.contains(delayKey))
+    val keyOnly = condition.isEmpty && !(leftKeys ++ rightKeys).exists { key =>
+      key.references.exists(_.metadata.contains(delayKey)) || (key match {
+        case named: NamedExpression => named.metadata.contains(delayKey)
+        case _ => false
+      })
+    }
+
+    def watermarkKeyOrdinals(keys: Seq[Expression]): Seq[Int] = {
+      keys.zipWithIndex.collect {
+        case (key: NamedExpression, index) if key.metadata.contains(delayKey) 
=> index
+      }
+    }
+
+    def ownEventTimeKeyOrdinal(keys: Seq[Expression], eventTime: Attribute): 
Option[Int] = {
+      keys.zipWithIndex.collectFirst {
+        case (key: NamedExpression, index)
+            if key.metadata.contains(delayKey) && 
key.semanticEquals(eventTime) => index
+      }
+    }
+
+    val leftOrdinals = watermarkKeyOrdinals(leftKeys)
+    val rightOrdinals = watermarkKeyOrdinals(rightKeys)
+    if (leftEventTime.isEmpty && rightEventTime.isEmpty) {
+      leftOrdinals.isEmpty && rightOrdinals.isEmpty
+    } else if (keyOnly && consumedSides.isEmpty) {
+      true
+    } else if (leftEventTime.size == 1 && rightEventTime.size == 1) {
+      val leftOrdinal = ownEventTimeKeyOrdinal(leftKeys, leftEventTime.head)
+      val rightOrdinal = ownEventTimeKeyOrdinal(rightKeys, rightEventTime.head)
+      val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal == 
rightOrdinal &&
+        leftOrdinals == leftOrdinal.toSeq && rightOrdinals == 
rightOrdinal.toSeq
+      alignedOwnEventTimeKeys || isOwnEventTimeIntervalJoin(leftAttributes, 
rightAttributes,
+        leftKeys, rightKeys, condition, leftEventTime.head, 
rightEventTime.head, consumedSides)
+    } else {
+      false
+    }
+  }
+
+  /**
+   * Whether every ordering conjunct compares the two inputs' TIMESTAMP event 
times, each only
+   * cast or offset by constants (see 
[[StreamingJoinHelper.isConstantOffsetOf]]), and each event
+   * time either gets a range bound or gets none and is not in 
`consumedSides`. Older versions
+   * and this one solve such conjuncts the same way for columns with their own 
watermark, and
+   * older versions solved every column of an input but then found bounds only 
in the same
+   * conjuncts, so they derived the same value predicates, scan starts and V4 
index columns, and
+   * neither evicts an input that gets no bound. Old V4 stored a null event 
time at timestamp 0
+   * under the row's own key; both versions scan that entry the same way. No 
equality key may
+   * use an event time: older versions evicted such keys at the unshifted 
watermark. Time windows
+   * are excluded: older versions derived an ordering bound for them that this 
version removes.

Review Comment:
   **Nit (P3):** This version still derives an ordering bound for time windows: 
`getStateValueWatermarkForInput` tries the watermarked window attribute first 
whatever its type, the solver solves `leftWindow > rightWindow` for it as the 
base branch did, and `watermarkExpression` applies the cutoff to the window 
end. Only the new TIMESTAMP-only gate excludes windows, so the reason given 
here and in the matching compatibility test comment is not true at this commit; 
if a later PR of the stack removes the bound, the comment should name it.
   
   **Verification:**
   - **Inspection:** The restart check's doc and the test comment give a reason 
for rejecting window orderings that holds at this commit.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +292,229 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     JoinStateWatermarkPredicates(leftStateWatermarkPredicate, 
rightStateWatermarkPredicate)
   }
 
+  /** Keep each cutoff attached to the column constrained by the join 
condition. */
+  private def getStateValueWatermarkForInput(
+      inputAttributes: Seq[Attribute],
+      otherInputAttributes: Seq[Attribute],
+      condition: Option[Expression],
+      eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+    val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+    // First try the watermarked column. If it has no inferable bound, try the 
other timestamp
+    // columns in input schema order and use the first with a bound. This 
makes the indexed column
+    // deterministic for a fixed input schema and join condition.
+    val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+      attribute.dataType == TimestampType && 
!eventTime.exists(_.semanticEquals(attribute))

Review Comment:
   **Blocking (P1):** Candidates here are only the event time and other 
TIMESTAMP columns, while the unchanged analysis check in 
`UnsupportedOperationChecker.checkForStreamStreamJoinWatermark` solves over the 
preserved side's whole output and reads `CAST(expiry AS TIMESTAMP)` as 
`expiry`, so it still admits a left, right or full outer join whose preserved 
side is bounded only through a DATE, TIMESTAMP_NTZ or numeric column cast to 
TIMESTAMP. That side then gets no eviction predicate, `removeAndReturnOldState` 
returns nothing for it, and its unmatched rows are never emitted with nulls and 
stay in state for the life of the query, in every state format. For `leftKey = 
rightKey AND rightTime <= CAST(expiry AS TIMESTAMP)` with a BIGINT `expiry`, a 
left row that never matches is emitted as `(2, null)` on the base branch and, 
as the author's reply confirms, never emitted with this change. SPARK-61348 
rejects the shape later in the stack, but each PR lands on master on its own, 
so master wou
 ld drop these rows until it merges.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60279#issuecomment-6775614175).
   
   **Recommended change:** Move the candidate rule, trying the event time and 
then the other TIMESTAMP columns one at a time, into StreamingJoinHelper and 
use it from getStateValueWatermarkForInput. In 
checkForStreamStreamJoinWatermark, reject a left, right or full outer join when 
a preserved side gets a bound from the whole-side solve but none from the 
candidate rule and the watermark is not in the join keys, with a message that 
names the side and suggests projecting the bounded column to TIMESTAMP before 
the join. Add outer-join cases to the unsupported-operation tests and the 
stream-stream join range eviction tests.
   
   **Why this works:** Analysis then admits an outer join only when execution 
will give each preserved side it found bounded a value predicate, so no 
admitted outer join keeps unmatched rows forever; projecting the column to 
TIMESTAMP makes it a candidate, so such a query can be rewritten to evict and 
emit correctly.
   
   **Scope:** Share one cutoff-column rule between analysis and execution, and 
reject outer joins whose preserved side has a bound only through a column that 
cannot carry a cutoff.
   
   **Risks:** Outer stream-stream joins whose preserved side is bounded only 
through a non-TIMESTAMP cast now fail at analysis where Spark 4.3 ran them with 
too-early null rows, and users must project the column to TIMESTAMP before the 
join; reverting the check brings back the silent loss.
   
   **Constraints:** Leave inner and left semi joins of this shape running; 
their state growth is the open reviewer decision on cast-bounded state. If the 
reviewer adopts eviction by the bounded cast for such sides, that eviction also 
closes this defect and replaces the rejection.
   
   **Exclusions:**
   - Left semi joins bounded only through a cast, which keep their rows without 
wrong results and belong to the open decision on cast-bounded state.
   - Full outer joins with a side that has no bound at all, which the existing 
check already admits.
   
   **Success:** A left, right or full outer stream-stream join whose preserved 
side is bounded only through a DATE, TIMESTAMP_NTZ or numeric column cast to 
TIMESTAMP fails analysis with a message naming the side. The same join with 
that column projected to TIMESTAMP before the join runs, evicts the side by 
that column and emits its unmatched rows with nulls. Outer joins bounded on the 
event time or another TIMESTAMP column, joins with the watermark in the join 
keys, and inner and left semi joins are admitted as before.
   
   **Verification:**
   - **Regression:** Left, right and full outer joins whose preserved side is 
bounded only through a BIGINT, DATE or TIMESTAMP_NTZ column cast to TIMESTAMP, 
explicitly or by type coercion, are rejected at analysis.
   - **Behavior:** A left outer join with the bounded column projected to 
TIMESTAMP before the join emits an unmatched row with nulls once the other 
input's watermark passes that column, in state formats 2 and 4.
   - **Compatibility:** Outer joins bounded on their event time or another 
TIMESTAMP column, joins with the watermark in the join keys, and inner and left 
semi joins bounded through a cast are still admitted.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -843,12 +926,12 @@ case class StreamingSymmetricHashJoinExec(
 
       nonLateRows.flatMap { row =>
         val thisRow = row.asInstanceOf[UnsafeRow]
-        // If this row fails the pre join filter, that means it can never 
satisfy the full join
-        // condition no matter what other side row it's matched with. This 
allows us to avoid
-        // adding it to the state, and generate an outer join row immediately 
(or do nothing in
-        // the case of inner join).
-        if (preJoinFilter(thisRow)) {
-          val key = keyGenerator(thisRow)
+        // If this row fails the pre join filter, or its eviction column is 
NULL, that means it can
+        // never satisfy the full join condition no matter what other side row 
it's matched with.
+        // This allows us to avoid adding it to the state, and generate an 
outer join row
+        // immediately (or do nothing in the case of inner join).
+        val key = if (preJoinFilter(thisRow)) keyGenerator(thisRow) else null
+        if (key != null && !isEvictionColumnNull(key, thisRow)) {

Review Comment:
   **Non-blocking (P2):** The never-match rule runs only when a row arrives, 
and V1 to V3 eviction still evaluates `column <= cutoff`, which is never true 
for NULL. Rows with a NULL event time or watermarked equality key that a 
restored V2 or V3 checkpoint already holds, for example on the preserved side 
of a left outer interval join where no `IsNotNull` filter is inferred, 
therefore stay in state and are never emitted with nulls, as on the base 
branch, while equal rows arriving after the upgrade are emitted at once. So the 
PR's 'No join keeps such a row in state' does not hold for restored state. 
Removing such rows in the V1 to V3 eviction functions too, by also evicting a 
row whose eviction column is NULL with the same null check the arrival path 
uses, needs no state migration, because those formats evaluate every stored row 
each batch; V4 already removes its restored rows, which it stored at timestamp 
0, in the first-batch scan.
   
   **Verification:**
   - **Regression:** Restore a left outer interval-join checkpoint in state 
formats 2 and 3 whose state holds a left row with a NULL event time, such as 
one written by Spark 4.3, and confirm the row is emitted padded with nulls in 
the first batch and leaves state.
   - **Compatibility:** The existing range eviction and NULL range-end tests 
produce the same rows and state counts.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -878,3 +1060,13 @@ class IncrementalExecution(
       }.exists(_ == true)
   }
 }
+
+/**
+ * A stateful operator that compares its input watermark with an event-time 
column carrying the
+ * event time `eventTime` of one input, `side`, of the stream-stream join 
`joinOperatorId`.
+ */
+private[runtime] case class JoinWatermarkConsumer(
+    consumer: SparkPlan,

Review Comment:
   **Nit (P3):** Both callers, `withJoinOutputWatermarkSides` and the restart 
check, read only `joinOperatorId` and `side` through `groupMap`, and nothing 
else references this private class, so `consumer` and `eventTime`, and the 
join-side attribute threaded through every `findJoinSides` result only to fill 
`eventTime`, are unused. Returning `(joinOperatorId, side)` pairs would make 
the tracer easier to read and avoid holding a plan reference per traced 
consumer.
   
   **Verification:**
   - **Compile:** The incremental planner compiles without the removed fields 
and the threaded attribute.
   - **Behavior:** The output watermark tracing tests give the same traced 
sides and watermarks.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +859,58 @@ class IncrementalExecution(
 
     override def apply(plan: SparkPlan): SparkPlan = {
       val planWithStateOpId = plan transform composedRule
+      // Validate the checkpoint-pinned semantics before writing state 
metadata or opening state,
+      // including a restart retrying an incomplete batch zero.
+      if (isFirstBatchWithOlderJoinWatermarkSemantics) {
+        def watermarkColumns(input: SparkPlan): String = {
+          val columns = input.output.filter(
+            _.metadata.contains(EventTimeWatermark.delayKey))
+          if (columns.isEmpty) "none" else columns.map(_.name).mkString(", ")
+        }
+        // A join's output watermark reaches every stateful operator above it. 
The nearest one
+        // reads the inputs that the tracer names, or both inputs when it 
cannot be traced.
+        val joinsBelowStatefulOperators = planWithStateOpId.collect {
+          case s: StatefulOperator => s.children.flatMap(_.collect {
+            case j: StreamingSymmetricHashJoinExec => 
j.stateInfo.map(_.operatorId)
+          }.flatten)
+        }.flatten.toSet
+        val tracedSides = joinWatermarkConsumers(planWithStateOpId)
+          .groupMap(_.joinOperatorId)(_.side)
+        def consumedSides(j: StreamingSymmetricHashJoinExec): Set[JoinSide] =
+          j.stateInfo.map(_.operatorId) match {
+            case Some(id) if joinsBelowStatefulOperators.contains(id) =>
+              tracedSides.get(id).map(_.toSet).getOrElse(Set(LeftSide, 
RightSide))

Review Comment:
   **Blocking (P1):** When the tracer finds no consumer for a join below a 
stateful operator, both inputs count as read, and the tracer finds none both 
when it cannot follow an operator's event-time column and when the operator has 
no event-time column at all. So a key-only join, or a one-directional interval 
join, followed only by `groupBy("key").count()` in update mode or by a 
deduplication on non-time columns, is rejected on restart from an older 
checkpoint, although neither version evicts its unbounded input and no operator 
compares an event time with the changed output watermark; the PR's own 
'unbounded' rejection case is one of these. The migration guide states the 
narrower rule that such a join keeps its checkpoint when no stateful operator 
after it uses the event time of an input without a bound. Operators that fire 
event-time timers, or that pass the watermark to user code as 
transformWithState does in every time mode, do use it and should keep counting.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60279#issuecomment-6775614175).
   
   **Recommended change:** Collect a join as below a watermark consumer only 
when some stateful operator above it has an event-time column in its input, 
fires event-time timers, or passes its input watermark to user code, as 
transformWithState does in every time mode, in Scala and in PySpark, through 
TimerValues.getCurrentWatermarkInMs; a join with no such operator above it has 
no consumed side, and every other join keeps today's traced-or-both rule. 
Update the stream-stream join checkpoint compatibility tests so that the 
key-only case followed by deduplication over cast event times resumes, add 
key-only and one-directional cases followed by an update-mode aggregation on a 
non-time key that resume, and add a key-only case followed by 
transformWithState in processing-time mode that is still rejected.
   
   **Why this works:** An operator that neither compares an event time with its 
watermark nor passes the watermark to user code is unaffected by the join's 
output watermark, and its output carries no event-time column for a later 
operator to read through the trace, so those restarts keep their meaning; any 
operator that could be affected still forces the conservative rule.
   
   **Scope:** Restrict the restart check's both-inputs fallback to joins below 
an operator that uses its watermark.
   
   **Risks:** If a stateful operator without an event-time column, event-time 
timers or a user-visible watermark did use its input watermark, accepting the 
restart would change its behavior silently; the trace found transformWithState, 
which passes the watermark to user code in every time mode, and the repair 
keeps counting it, and reverting restores the rejection.
   
   **Constraints:** Keep counting both inputs for any operator above the join 
whose event-time column cannot be traced to it. Keep counting both inputs for 
transformWithState above the join in every time mode, because its user code can 
read the input watermark.
   
   **Success:** An older checkpoint of a key-only join followed only by an 
update-mode aggregation or a deduplication on non-time columns resumes. An 
older checkpoint of a one-directional interval join followed only by such an 
operator resumes. Older checkpoints with an operator above the join that reads 
an event time the tracer cannot follow, fires event-time timers, or passes the 
watermark to user code, such as transformWithState in processing-time mode, are 
still rejected.
   
   **Verification:**
   - **Regression:** Restoring an older-marker checkpoint of a key-only join 
with watermarks on both inputs followed by `groupBy("key").count()` in update 
mode resumes and keeps counting.
   - **Compatibility:** A key-only join followed by a window aggregation over 
an unbounded input's event time, by transformWithState in event-time mode, or 
by transformWithState in processing-time mode, is still rejected.
   - **Inspection:** The migration guide's reuse criterion for one-directional 
and key-only joins describes the shapes the check accepts.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelperSuite.scala:
##########
@@ -48,6 +50,30 @@ class StreamingJoinHelperSuite extends AnalysisTest {
     }
   }
 
+  test("state watermark extraction ignores columns outside both attribute 
sets") {
+    val leftTime = AttributeReference("leftTime", TimestampType)()
+    val leftOffset = AttributeReference("leftOffset", LongType)()
+    val metadata = new MetadataBuilder().putLong(EventTimeWatermark.delayKey, 
1000).build()
+    val rightTime = AttributeReference("rightTime", TimestampType, metadata = 
metadata)()
+    val rightDelay = AttributeReference("rightDelay", DayTimeIntervalType())()
+    val conditions = Seq(
+      leftTime > TimestampAddInterval(rightTime, rightDelay),
+      leftTime.cast(LongType) + leftOffset > rightTime.cast(LongType))
+    val logAppender = new LogAppender("state watermark extraction")
+    withLogAppender(logAppender, level = Some(Level.WARN)) {
+      conditions.foreach { condition =>
+        withClue(condition.sql) {
+          // Eviction passes only the constrained column and the opposite 
event time.

Review Comment:
   **Nit (P3):** Eviction passes the constrained column with the whole opposite 
input, so for the first condition, `leftTime > rightTime + rightDelay`, 
eviction already gets None from the existing occurrence check; only the V4 
range-scan extraction and the left semi exact-cutoff derivation pass just the 
opposite event time and reach the new references check with it. The second 
condition does reach the new check through eviction too, because `leftOffset` 
is in neither set. Naming, for each condition, the callers that reach the check 
keeps a maintainer from concluding that eviction relies on it for the first one.
   
   **Verification:**
   - **Inspection:** The test comment attributes the first condition to the V4 
range-scan and left semi callers, which pass only the opposite event time, and 
the second condition also to eviction, which passes only the constrained column.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -717,21 +727,94 @@ case class StreamingSymmetricHashJoinExec(
         Predicate.create(Literal(false), Seq.empty).eval _  // false = do not 
remove if no predicate
     }
 
+    // A NULL in the column that the state watermark predicate tests makes the 
predicate unknown,
+    // so eviction never removes the row. The row cannot match either: that 
column is an equality
+    // key, or a comparison in the join condition bounds it. Handle the row 
like one that fails
+    // the pre-join filter.
+    // The check takes the generated key and the input row, so the key is 
computed only once.
+    private[this] val isEvictionColumnNull: (UnsafeRow, UnsafeRow) => Boolean =
+      stateWatermarkPredicate match {
+        case Some(JoinStateKeyWatermarkPredicate(expr, _, _)) =>
+          // Only a NULL key fails equality. A struct key with a NULL field 
can still be equal.
+          val ordinal = expr.collectFirst { case b: BoundReference => 
b.ordinal }.get
+          (key, _) => key.isNullAt(ordinal)

Review Comment:
   **Nit (P3):** Both new NULL-eviction tests put the NULL in a value-eviction 
column through `setupJoinWithNullableRangeEnd`, so this key branch never runs 
in a test: replacing it with `(_, _) => false` would bring back NULL-key rows 
that stay in V2 and V3 state and are never emitted, and every suite would still 
pass. A StreamingOuterJoinBase case with a NULL `leftTime` on the preserved 
side of a left outer join on `leftKey = rightKey AND leftTime = rightTime`, 
asserting the output and the updated state row count, would cover it in every 
state format.
   
   **Verification:**
   - **Regression:** With the key branch of the null check disabled, the new 
case fails in every state format: the row is then appended to state, which the 
updated state row count shows even after V1 to V3 eviction also removes NULL 
rows, and in V4 it is never emitted.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +292,229 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     JoinStateWatermarkPredicates(leftStateWatermarkPredicate, 
rightStateWatermarkPredicate)
   }
 
+  /** Keep each cutoff attached to the column constrained by the join 
condition. */
+  private def getStateValueWatermarkForInput(
+      inputAttributes: Seq[Attribute],
+      otherInputAttributes: Seq[Attribute],
+      condition: Option[Expression],
+      eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+    val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+    // First try the watermarked column. If it has no inferable bound, try the 
other timestamp
+    // columns in input schema order and use the first with a bound. This 
makes the indexed column
+    // deterministic for a fixed input schema and join condition.
+    val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+      attribute.dataType == TimestampType && 
!eventTime.exists(_.semanticEquals(attribute))
+    }
+    candidates.iterator.flatMap { attribute =>
+      StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+        AttributeSet(otherInputAttributes), condition, 
eventWatermark).map(attribute -> _)
+    }.take(1).toSeq.headOption
+  }
+
+  /**
+   * Conservatively prove that older state can use the current watermark 
semantics. Without
+   * watermarks there is no affected state. An input that neither version 
evicts keeps the same
+   * rows, but its state watermark in the join's output watermark changed, so 
such an input is
+   * accepted only when no stateful operator after the join reads its event 
time:
+   * `consumedSides` names the inputs whose event time such an operator reads, 
both when the
+   * operator cannot be traced and none when no stateful operator follows. A 
key-only join, with
+   * no other condition and no equality key that uses an event time, is 
evicted by neither
+   * version, and V4 reads its rows by key prefix. Otherwise each side must 
have exactly one
+   * event-time column, and either its own event time must be the sole 
watermarked equality key
+   * at the same ordinal, or the join must be a time-interval join on the 
event times (see
+   * [[isOwnEventTimeIntervalJoin]]). This excludes other range bounds.
+   */
+  private[sql] def isWatermarkCheckpointCompatible(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      condition: Option[Expression],
+      consumedSides: Set[JoinSide]): Boolean = {
+    val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
+    val rightEventTime = rightAttributes.filter(_.metadata.contains(delayKey))
+    val keyOnly = condition.isEmpty && !(leftKeys ++ rightKeys).exists { key =>
+      key.references.exists(_.metadata.contains(delayKey)) || (key match {
+        case named: NamedExpression => named.metadata.contains(delayKey)
+        case _ => false
+      })
+    }
+
+    def watermarkKeyOrdinals(keys: Seq[Expression]): Seq[Int] = {
+      keys.zipWithIndex.collect {
+        case (key: NamedExpression, index) if key.metadata.contains(delayKey) 
=> index
+      }
+    }
+
+    def ownEventTimeKeyOrdinal(keys: Seq[Expression], eventTime: Attribute): 
Option[Int] = {
+      keys.zipWithIndex.collectFirst {
+        case (key: NamedExpression, index)
+            if key.metadata.contains(delayKey) && 
key.semanticEquals(eventTime) => index
+      }
+    }
+
+    val leftOrdinals = watermarkKeyOrdinals(leftKeys)
+    val rightOrdinals = watermarkKeyOrdinals(rightKeys)
+    if (leftEventTime.isEmpty && rightEventTime.isEmpty) {
+      leftOrdinals.isEmpty && rightOrdinals.isEmpty
+    } else if (keyOnly && consumedSides.isEmpty) {
+      true
+    } else if (leftEventTime.size == 1 && rightEventTime.size == 1) {
+      val leftOrdinal = ownEventTimeKeyOrdinal(leftKeys, leftEventTime.head)
+      val rightOrdinal = ownEventTimeKeyOrdinal(rightKeys, rightEventTime.head)
+      val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal == 
rightOrdinal &&
+        leftOrdinals == leftOrdinal.toSeq && rightOrdinals == 
rightOrdinal.toSeq
+      alignedOwnEventTimeKeys || isOwnEventTimeIntervalJoin(leftAttributes, 
rightAttributes,
+        leftKeys, rightKeys, condition, leftEventTime.head, 
rightEventTime.head, consumedSides)
+    } else {
+      false
+    }
+  }
+
+  /**
+   * Whether every ordering conjunct compares the two inputs' TIMESTAMP event 
times, each only
+   * cast or offset by constants (see 
[[StreamingJoinHelper.isConstantOffsetOf]]), and each event
+   * time either gets a range bound or gets none and is not in 
`consumedSides`. Older versions
+   * and this one solve such conjuncts the same way for columns with their own 
watermark, and
+   * older versions solved every column of an input but then found bounds only 
in the same
+   * conjuncts, so they derived the same value predicates, scan starts and V4 
index columns, and
+   * neither evicts an input that gets no bound. Old V4 stored a null event 
time at timestamp 0
+   * under the row's own key; both versions scan that entry the same way. No 
equality key may
+   * use an event time: older versions evicted such keys at the unshifted 
watermark. Time windows
+   * are excluded: older versions derived an ordering bound for them that this 
version removes.
+   */
+  private def isOwnEventTimeIntervalJoin(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      condition: Option[Expression],
+      leftEventTime: Attribute,
+      rightEventTime: Attribute,
+      consumedSides: Set[JoinSide]): Boolean = {
+    def conjuncts(e: Expression): Seq[Expression] = e match {
+      case And(left, right) => conjuncts(left) ++ conjuncts(right)
+      case other => Seq(other)
+    }
+    def eventTimeOf(e: Expression): Option[Attribute] =
+      Seq(leftEventTime, 
rightEventTime).find(StreamingJoinHelper.isConstantOffsetOf(e, _))
+    def comparesInputs(a: Expression, b: Expression): Boolean =
+      (eventTimeOf(a), eventTimeOf(b)) match {
+        case (Some(x), Some(y)) => !x.semanticEquals(y)
+        case _ => false
+      }
+    // The solver reads bounds only from these conjunct shapes; other 
conjuncts give no bound in
+    // either version.
+    val conditionIsInterval = condition.toSeq.flatMap(conjuncts).forall {
+      case c @ (_: LessThan | _: LessThanOrEqual | _: GreaterThan | _: 
GreaterThanOrEqual) =>
+        val comparison = c.asInstanceOf[BinaryComparison]
+        comparesInputs(comparison.left, comparison.right)
+      case Between(input, lower, upper, _) =>
+        comparesInputs(input, lower) && comparesInputs(input, upper)
+      case _ => true
+    }
+    val keysUseEventTime = (leftKeys ++ rightKeys).exists(
+      _.references.exists(_.metadata.contains(delayKey)))
+    def boundsEventTime(
+        predicate: Option[JoinStateWatermarkPredicate], eventTime: Attribute): 
Boolean = {
+      predicate.exists {
+        case JoinStateValueWatermarkPredicate(e, _, _) => 
e.references.contains(eventTime)
+        case _ => false
+      }
+    }
+    val timestampEventTimes =
+      leftEventTime.dataType == TimestampType && rightEventTime.dataType == 
TimestampType
+    !keysUseEventTime && timestampEventTimes && conditionIsInterval && {
+      // The cutoffs are the watermark plus constants, so any watermark shows 
whether they exist.
+      val predicates = getStateWatermarkPredicates(leftAttributes, 
rightAttributes, leftKeys,
+        rightKeys, condition, Some(1000000L), None, useFirstEventTimeColumn = 
false)
+      def sameEviction(
+          predicate: Option[JoinStateWatermarkPredicate],
+          eventTime: Attribute,
+          side: JoinSide): Boolean = {
+        boundsEventTime(predicate, eventTime) || predicate.isEmpty && 
!consumedSides(side)
+      }
+      sameEviction(predicates.left, leftEventTime, LeftSide) &&
+        sameEviction(predicates.right, rightEventTime, RightSide)
+    }
+  }
+
+  /**
+   * For the right input of a left semi join, cutoffs at the late-events 
watermark that are exact
+   * today: no left row that passes late filtering can match a right row at or 
below them. Returns
+   * a predicate on the right join key and a predicate on the right input row, 
either of which
+   * can be absent.
+   *
+   * The key cutoff applies when the left input's late-filtered column is the 
left join key at an
+   * ordinal: the right key at that ordinal must then be above the late-events 
watermark. The
+   * value cutoff is on the right event time, solved only from conjuncts that 
compare it with the
+   * left input's late-filtered column, each shifted only by literal intervals 
without a day or
+   * month part, and with no cast. Any other conjunct can give a cutoff that 
is too high, so it
+   * gives none here: for example a bound on another right column, an interval 
with whole days,
+   * or a truncating cast.
+   * TODO(SPARK-61344, SPARK-61381): derive exact cutoffs for those conditions 
too.
+   */
+  def getLeftSemiExactRightCutoffs(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      condition: Option[Expression],
+      eventTimeWatermarkForLateEvents: Option[Long],
+      useFirstEventTimeColumn: Boolean): (Option[Expression], 
Option[Expression]) = {
+    // The column the left input's late filter compares with the late-events 
watermark.
+    val leftLateFiltered = WatermarkSupport.findEventTimeColumn(leftAttributes,
+      allowMultipleEventTimeColumns = useFirstEventTimeColumn)
+    val rightEventTime = WatermarkSupport.findEventTimeColumn(rightAttributes,
+      allowMultipleEventTimeColumns = useFirstEventTimeColumn)
+
+    val keyCutoff = leftLateFiltered.flatMap { column =>
+      leftKeys.indexWhere(_.semanticEquals(column)) match {
+        case ordinal if ordinal >= 0 =>
+          val rightKey = BoundReference(
+            ordinal, rightKeys(ordinal).dataType, rightKeys(ordinal).nullable)
+          watermarkExpression(Some(rightKey), eventTimeWatermarkForLateEvents)
+        case _ => None
+      }
+    }
+
+    // Whether the expression is the column shifted only by literal intervals 
that the solver
+    // counts exactly: no whole days, which Spark adds in the session time 
zone, and no months.
+    def isExactShiftOf(e: Expression, column: Attribute): Boolean = e match {
+      case a: Attribute => a.semanticEquals(column)
+      case Cast(child, TimestampType, _, _) if child.dataType == TimestampType 
=>

Review Comment:
   **Nit (P3):** This identity-cast case is the only cast `isExactShiftOf` 
accepts, and excluding other casts is what keeps same-batch left semi matches 
through a truncating cast: with `CAST(rightTime AS BIGINT) >= CAST(leftTime AS 
BIGINT) + 60` and a late-events watermark of 100.5 seconds, the solver would 
give a cutoff near 160.499 seconds, yet a left row at 100.6 seconds matches a 
right row at 160.2 seconds. No left semi test has a cast in its time condition 
or a fractional-second watermark, so widening this match would drop such 
matches without a failing test. A StreamingLeftSemiJoinBase case of that shape, 
run for V2 to V4, would give the exclusion a failure signal.
   
   **Verification:**
   - **Regression:** If the exact-shift check accepted a cast to BIGINT, the 
new case fails because the left row at 100.6 seconds is not emitted.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOutputWatermarkSuite.scala:
##########
@@ -0,0 +1,321 @@
+/*
+ * 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.sql.Timestamp
+
+import org.apache.spark.sql.{DataFrame, Encoders, Row}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinSide,
 LeftSide, RightSide}
+import org.apache.spark.sql.execution.streaming.runtime.{MemoryStream, 
StreamExecution}
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions.{col, count, expr, lit, session_window, 
timestamp_seconds, window}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinOutputWatermarkSuite extends StreamTest {
+  import testImplicits._
+
+  for (version <- Seq(2, 3, 4)) {
+    test(s"unbounded join state can emit an old event time after watermarks 
advance, V$version") {
+      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, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("key", "seconds")
+          .select($"key", timestamp_seconds($"seconds").as("leftTime"))
+          .withWatermark("leftTime", "10 seconds")
+        val right = rightInput.toDF().toDF("key", "seconds")
+          .select($"key", timestamp_seconds($"seconds").as("rightTime"))
+          .withWatermark("rightTime", "10 seconds")
+        val result = left.join(right, Seq("key"))
+          .select($"key", $"leftTime")
+          .dropDuplicatesWithinWatermark("key")
+          .select($"key", $"leftTime".cast("long"))
+
+        testStream(result)(
+          MultiAddData((leftInput, Seq((1, 5L))), (rightInput, Seq((9, 5L)))),
+          CheckNewAnswer(),
+          MultiAddData((leftInput, Seq((2, 30L))), (rightInput, Seq((3, 
30L)))),
+          CheckNewAnswer(),
+          // Process another batch so the join's output watermark reaches 
downstream operators.
+          AddData(rightInput, (4, 40L)),
+          CheckNewAnswer(),
+          // The retained left key 1 can still join after both input 
watermarks reach 20 seconds.
+          // The right event is newer than that watermark, but the joined left 
time is only 5.
+          AddData(rightInput, (1, 100L)),
+          CheckNewAnswer((1, 5L)),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.eventTimeWatermarkForLateEvents.contains(20000L))
+            assert(join.produceOutputWatermark(20000L).contains(0L))
+          })
+      }
+    }
+  }
+
+  // Impressions are bounded by the click watermark; clicks have no lower 
bound on clickTime.
+  private def oneDirectionalJoin(): (MemoryStream[(Int, Long)], 
MemoryStream[(Int, Long)],
+      DataFrame) = {
+    val impressionInput = MemoryStream[(Int, Long)]
+    val clickInput = MemoryStream[(Int, Long)]
+    val impressions = impressionInput.toDF().toDF("impressionAdId", "seconds")
+      .select($"impressionAdId", 
timestamp_seconds($"seconds").as("impressionTime"))
+      .withWatermark("impressionTime", "10 seconds")
+    val clicks = clickInput.toDF().toDF("clickAdId", "seconds")
+      .select($"clickAdId", timestamp_seconds($"seconds").as("clickTime"))
+      .withWatermark("clickTime", "10 seconds")
+    val joined = impressions.join(clicks,
+      expr("clickAdId = impressionAdId AND clickTime <= impressionTime + 
INTERVAL 10 SECONDS"))
+    (impressionInput, clickInput, joined)
+  }
+
+  private def windowCounts(
+      df: DataFrame,
+      timeColumn: String,
+      slide: String = "10 seconds"): DataFrame = {
+    df.groupBy(window(col(timeColumn), "10 seconds", 
slide)).agg(count("*").as("count"))
+      .select($"window.start".cast("long"), $"count")
+  }
+
+  // The join that reads the inputs, below any stream-stream join after it.
+  private def join(query: StreamExecution): StreamingSymmetricHashJoinExec = {
+    query.lastExecution.executedPlan.collect {
+      case j: StreamingSymmetricHashJoinExec
+          if 
!j.children.exists(_.exists(_.isInstanceOf[StreamingSymmetricHashJoinExec])) => 
j
+    }.head
+  }
+
+  private def runOneDirectionalJoin(
+      impressionInput: MemoryStream[(Int, Long)],
+      clickInput: MemoryStream[(Int, Long)],
+      result: DataFrame,
+      expectedRows: Seq[Row],
+      expectedSides: Option[Set[JoinSide]],
+      expectedOutputWatermark: Long): Unit = {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+      testStream(result, OutputMode.Append())(
+        MultiAddData((impressionInput, Seq((1, 5L), (2, 15L), (3, 25L))),
+          (clickInput, Seq((1, 8L), (2, 20L)))),
+        ProcessAllAvailable(),
+        // The click at 30 seconds joins the retained impression at 25 seconds.
+        MultiAddData((impressionInput, Seq((4, 60L))), (clickInput, Seq((3, 
30L), (9, 70L)))),
+        ProcessAllAvailable(),
+        MultiAddData((impressionInput, Seq((5, 100L))), (clickInput, Seq((9, 
110L)))),
+        ProcessAllAvailable(),
+        AddData(clickInput, (9, 150L)),
+        ProcessAllAvailable(),
+        AddData(impressionInput, (6, 200L)),
+        ProcessAllAvailable(),
+        CheckAnswer(expectedRows: _*),
+        Execute { query =>
+          val j = join(query)
+          assert(j.outputWatermarkSides == expectedSides)
+          assert(j.produceOutputWatermark(j.eventTimeWatermarkForEviction.get)
+            .contains(expectedOutputWatermark))
+          // No joined row arrives behind the watermark of the operator after 
the join.
+          assert(query.recentProgress.flatMap(_.stateOperators)
+            .map(_.numRowsDroppedByWatermark).sum == 0)
+        })
+    }
+  }
+
+  test("output watermark follows the bounded input when only its event time is 
used") {
+    val (impressionInput, clickInput, joined) = oneDirectionalJoin()
+    // Impressions are evicted below the click watermark (90 seconds) less 10 
seconds and 1 ms.
+    runOneDirectionalJoin(impressionInput, clickInput,
+      windowCounts(joined.select($"impressionTime"), "impressionTime"),
+      Seq(Row(0L, 1L), Row(10L, 1L), Row(20L, 1L)), Some(Set(LeftSide)), 
79999L)
+  }
+
+  Seq("clickTime", "clickTimeAlias").foreach { timeColumn =>
+    test(s"output watermark is held back when the unbounded input's event time 
is used: " +
+        timeColumn) {
+      val (impressionInput, clickInput, joined) = oneDirectionalJoin()
+      val clickTime = if (timeColumn == "clickTime") $"clickTime" else 
$"clickTime".as(timeColumn)
+      runOneDirectionalJoin(impressionInput, clickInput,
+        windowCounts(joined.select(clickTime), timeColumn), Nil, 
Some(Set(RightSide)), 0L)
+    }
+  }
+
+  // Each recognized path must carry the operator's event-time column to the 
join input it comes
+  // from. Over impressionTime the join narrows to the bounded input and emits 
what the base

Review Comment:
   **Nit (P3):** 'Emits what the base branch emits' names nothing once this is 
merged, so a reader cannot tell the expected result. Saying directly that the 
output watermark is the bounded input's state watermark, 79.999 seconds by 
default, keeps the comment meaningful.
   
   **Verification:**
   - **Inspection:** The traced-consumer comment states the expected output 
watermark directly.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinCheckpointCompatibilitySuite.scala:
##########
@@ -0,0 +1,576 @@
+/*
+ * 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.file.Files
+
+import scala.jdk.CollectionConverters._
+import scala.util.Using
+
+import org.apache.hadoop.fs.Path
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeReference, Cast, Expression, GreaterThan}
+import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap, 
OffsetSeq, OffsetSeqLog}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.{StreamingSymmetricHashJoinExec,
 StreamingSymmetricHashJoinHelper}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinStateKeyWatermarkPredicate,
 JoinStateValueWatermarkPredicate, LeftSide, RightSide}
+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.sql.types.{IntegerType, LongType, MetadataBuilder, 
StructField, StructType, TimestampType}
+import org.apache.spark.tags.SlowSQLTest
+import org.apache.spark.util.Utils
+
+@SlowSQLTest
+class StreamingJoinCheckpointCompatibilitySuite extends StreamTest {
+  import testImplicits._
+
+  private val markerKey = 
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.key
+  private val currentMarker =
+    
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.defaultValue.get.toString
+
+  private def setMarker(checkpoint: String, marker: Option[String]): Unit = {
+    def update(conf: Map[String, String]): Map[String, String] = {
+      (conf - markerKey) ++ marker.map(markerKey -> _)
+    }
+    val offsetsPath = checkpoint + "/offsets"
+    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 = 
update(m.conf))))
+      case o: OffsetMap =>
+        o.copy(metadata = o.metadata.copy(conf = update(o.metadata.conf)))
+    }
+    val path = new Path(offsetsPath, batchId.toString)
+    assert(path.getFileSystem(spark.sessionState.newHadoopConf()).delete(path, 
false))
+    assert(log.add(batchId, updated))
+  }
+
+  private def snapshot(directory: File): Map[String, Seq[Byte]] = {
+    Using.resource(Files.walk(directory.toPath)) { paths =>
+      paths.iterator().asScala.filter(Files.isRegularFile(_)).map { path =>
+        directory.toPath.relativize(path).toString -> 
Files.readAllBytes(path).toSeq
+      }.toMap
+    }
+  }
+
+  private def pinnedMarker(checkpoint: String): Option[String] = {
+    new OffsetSeqLog(spark, checkpoint + 
"/offsets").getLatest().get._2.metadataOpt.get
+      .conf.get(markerKey)
+  }
+
+  private def markerAt(checkpoint: String, batchId: Long): Option[String] = {
+    new OffsetSeqLog(spark, checkpoint + 
"/offsets").get(batchId).get.metadataOpt.get
+      .conf.get(markerKey)
+  }
+
+  private def withJoinConf(version: Int, logVersion: Int)(f: => Unit): Unit = {
+    withSQLConf(
+        SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+        SQLConf.STREAMING_OFFSET_LOG_FORMAT_VERSION.key -> logVersion.toString,
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+        SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+  }
+
+  private def joinInputs(shape: String): (MemoryStream[(Int, Int)],
+      MemoryStream[(Int, Int)], DataFrame) = {
+    val leftInput = MemoryStream[(Int, Int)]
+    val rightInput = MemoryStream[(Int, Int)]
+    val leftData = leftInput.toDF().toDF("leftKey", "time")
+      .select($"leftKey", timestamp_seconds($"time").as("leftTime"),
+        timestamp_seconds($"time" + 10).as("expiry"))
+    val rightData = rightInput.toDF().toDF("rightKey", "time")
+      .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+    val left = if (Seq("equality", "expiry", "pruned expiry", "unbounded")
+        .contains(shape)) {
+      leftData.withWatermark("leftTime", "100 seconds")
+    } else {
+      leftData
+    }
+    val right = if (shape != "no watermark") {
+      rightData.withWatermark("rightTime", "100 seconds")
+    } else {
+      rightData
+    }
+    val condition = shape match {
+      case "range" => "leftKey = rightKey AND leftTime > rightTime - INTERVAL 
5 SECONDS"
+      case "expiry" => "leftKey = rightKey AND rightTime BETWEEN leftTime AND 
expiry"
+      case "pruned expiry" => "leftKey = rightKey AND rightTime <= expiry"
+      case "unbounded" => "leftKey = rightKey"
+      case _ => "leftKey = rightKey AND leftTime = rightTime"
+    }
+    val joined = left.join(right, expr(condition))
+    val result = if (shape == "unbounded") {
+      // A stateful operator after this key-only join reads its output 
watermark.
+      joined.select($"leftKey", $"rightKey", $"leftTime".cast("long"),
+        $"rightTime".cast("long")).dropDuplicates()
+    } else {
+      joined.select($"leftKey", $"rightKey")
+    }
+    (leftInput, rightInput, result)
+  }
+
+  test("checkpoint compatibility requires one aligned own-event-time equality 
key") {
+    val watermarkMetadata = new MetadataBuilder()
+      .putLong(EventTimeWatermark.delayKey, 0L).build()
+    val leftId = AttributeReference("leftId", IntegerType)()
+    val rightId = AttributeReference("rightId", IntegerType)()
+    val leftTime = AttributeReference("leftTime", TimestampType,
+      metadata = watermarkMetadata)()
+    val rightTime = AttributeReference("rightTime", TimestampType,
+      metadata = watermarkMetadata)()
+    val compatible = 
StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+      _: Seq[Attribute], _: Seq[Attribute], _: Seq[Expression], _: 
Seq[Expression], None,
+      consumedSides = Set(LeftSide, RightSide))
+
+    assert(compatible(Seq(leftId), Seq(rightId), Seq(leftId), Seq(rightId)))
+    assert(compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId, leftTime), Seq(rightId, rightTime)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId, leftTime), Seq(rightTime, rightId)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId, leftTime, leftTime), Seq(rightId, rightTime, rightTime)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+      Seq(leftId), Seq(rightId)))
+    assert(!compatible(Seq(leftId, leftTime), Seq(rightId),
+      Seq(leftId, leftTime), Seq(rightId, rightId)))
+    assert(!compatible(Seq(leftId), Seq(rightId, rightTime),
+      Seq(leftId, leftId), Seq(rightId, rightTime)))
+    assert(!compatible(Seq(leftTime, rightTime), Seq(rightTime),
+      Seq(leftTime), Seq(rightTime)))
+    assert(!compatible(Seq(leftTime), Seq(rightTime, leftTime),
+      Seq(leftTime), Seq(rightTime)))
+    // Metadata alone must not select an earlier key or hide a computed 
watermarked key.
+    val computed = Alias(leftTime, "computed")()
+    assert(!compatible(Seq(leftTime), Seq(rightTime),
+      Seq(computed, leftTime), Seq(rightTime, rightTime)))
+    assert(!compatible(Seq(leftId), Seq(rightId), Seq(computed), Seq(rightId)))
+
+    // A key-only join is accepted only when no stateful operator after it 
reads its output
+    // watermark. Another condition, or a key that uses an event time, makes 
it not key-only.
+    val notConsumed = 
StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+      _: Seq[Attribute], _: Seq[Attribute], _: Seq[Expression], _: 
Seq[Expression],
+      _: Option[Expression], consumedSides = Set.empty)
+    val leftInput = Seq(leftId, leftTime)
+    val rightInput = Seq(rightId, rightTime)
+    assert(notConsumed(leftInput, rightInput, Seq(leftId), Seq(rightId), None))
+    assert(!notConsumed(leftInput, rightInput, Seq(leftId), Seq(rightId),
+      Some(GreaterThan(leftId, rightId))))
+    assert(!notConsumed(leftInput, rightInput, Seq(leftId, Cast(leftTime, 
LongType)),
+      Seq(rightId, Cast(rightTime, LongType)), None))
+    assert(!notConsumed(leftInput, rightInput, Seq(leftId, computed), 
Seq(rightId, rightTime),
+      None))
+
+    // Ordering time windows is excluded even when nothing reads the output 
watermark: older
+    // versions derived an ordering bound for whole windows that this version 
removes.
+    val windowType = StructType(Seq(
+      StructField("start", TimestampType), StructField("end", TimestampType)))
+    val leftWindow = AttributeReference("leftWindow", windowType,
+      metadata = watermarkMetadata)()
+    val rightWindow = AttributeReference("rightWindow", windowType,
+      metadata = watermarkMetadata)()
+    assert(!notConsumed(Seq(leftId, leftWindow), Seq(rightId, rightWindow), 
Seq(leftId),
+      Seq(rightId), Some(GreaterThan(leftWindow, rightWindow))))
+  }
+
+  for {
+    version <- Seq(1, 2, 3, 4)
+    logVersion <- Seq(1, 2)
+    // Every marker below the current one takes the same rejection branch.
+    oldMarker <- Seq(None, Some("0"), Some((currentMarker.toInt - 
1).toString)).distinct
+    shape <- Seq("range", "expiry", "pruned expiry", "unbounded")
+  } {
+    test(s"reject old $shape checkpoint, V$version log=$logVersion 
old=$oldMarker") {
+      withJoinConf(version, logVersion) {
+        val (leftInput, rightInput, joined) = joinInputs(shape)
+        withTempDir { checkpointDir =>
+          val checkpoint = checkpointDir.getCanonicalPath
+          testStream(joined)(
+            StartStream(checkpointLocation = checkpoint),
+            MultiAddData(leftInput, (1, 10))(rightInput, (1, 10)),
+            CheckNewAnswer(if (shape == "unbounded") Row(1, 1, 10L, 10L)
+              else Row(1, 1)),
+            StopStream)
+          // Emulate old offset metadata. State is written by the current 
implementation;
+          // rejection must not open or reinterpret it, regardless of its 
physical layout.
+          setMarker(checkpoint, oldMarker)
+          val originalBatchId = new OffsetSeqLog(spark, checkpoint + 
"/offsets")
+            .getLatest().get._1
+          val stateBefore = snapshot(new File(checkpoint, "state"))
+          val commitsBefore = snapshot(new File(checkpoint, "commits"))
+          for (attempt <- 1 to 2) {
+            // Session defaults must not bypass the checkpoint-pinned marker 
or state format.
+            withSQLConf(markerKey -> currentMarker,
+                SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "2") {
+              testStream(joined)(
+                StartStream(checkpointLocation = checkpoint),
+                AddData(rightInput, (2, 20 + attempt)),
+                ExpectFailure[AnalysisException](assertFailure = error => {
+                  checkError(error.asInstanceOf[AnalysisException],
+                    condition = "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE",
+                    parameters = Map(
+                      "joinCondition" -> ".*leftKey.*rightKey.*",
+                      "leftWatermarkColumns" ->
+                        (if (shape == "expiry" || shape == "unbounded") 
"leftTime" else "none"),
+                      "rightWatermarkColumns" -> "rightTime"),
+                    matchPVals = true)
+                }))
+            }
+            assert(snapshot(new File(checkpoint, "state")) == stateBefore)
+            assert(snapshot(new File(checkpoint, "commits")) == commitsBefore)
+            assert(markerAt(checkpoint, originalBatchId) == oldMarker)
+          }
+        }
+      }
+    }
+  }
+
+  for {
+    version <- Seq(1, 2, 3, 4)
+    logVersion <- Seq(1, 2)
+    shape <- Seq("equality", "no watermark", "range", "expiry", "pruned 
expiry")
+  } {
+    test(s"resume compatible $shape checkpoint, V$version log=$logVersion") {
+      withJoinConf(version, logVersion) {
+        val (leftInput, rightInput, joined) = joinInputs(shape)
+        withTempDir { checkpointDir =>
+          val checkpoint = checkpointDir.getCanonicalPath
+          testStream(joined)(
+            StartStream(checkpointLocation = checkpoint),
+            MultiAddData(leftInput, (1, 10))(rightInput, (2, 10)),
+            CheckNewAnswer(),
+            StopStream)
+          assert(pinnedMarker(checkpoint).contains(currentMarker))
+          val oldCompatible = Seq("equality", "no watermark").contains(shape)
+          val expectedMarker = if (oldCompatible) "0" else currentMarker
+          if (oldCompatible) setMarker(checkpoint, None)
+          withSQLConf(markerKey -> "0",
+              SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "2") {
+            testStream(joined)(
+              StartStream(checkpointLocation = checkpoint),
+              AddData(rightInput, (1, 10)),
+              CheckNewAnswer(Row(1, 1)),
+              Execute { query =>
+                val join = query.lastExecution.executedPlan.collect {
+                  case j: StreamingSymmetricHashJoinExec => j
+                }.head
+                assert(join.stateFormatVersion == version)
+              },
+              StopStream)
+          }
+          assert(pinnedMarker(checkpoint).contains(expectedMarker))
+        }
+      }
+    }
+  }
+
+  Seq(2, 4).foreach { version =>
+    test(s"reject an incompatible checkpoint retrying batch zero, V$version") {
+      withJoinConf(version, logVersion = 1) {
+        val (leftInput, rightInput, joined) = joinInputs("range")
+        withTempDir { checkpointDir =>
+          val checkpoint = checkpointDir.getCanonicalPath
+          testStream(joined)(
+            StartStream(checkpointLocation = checkpoint),
+            MultiAddData(leftInput, (1, 10))(rightInput, (1, 10)),
+            CheckNewAnswer(Row(1, 1)),
+            StopStream)
+          val offsets = new OffsetSeqLog(spark, checkpoint + "/offsets")
+          assert(offsets.getLatest().get._1 == 0L)
+          setMarker(checkpoint, None)
+          // Emulate a crash after state was written but before the first 
batch committed.
+          val commit = new Path(checkpoint, "commits/0")
+          
assert(commit.getFileSystem(spark.sessionState.newHadoopConf()).delete(commit, 
false))
+          val before = snapshot(new File(checkpoint, "state"))
+          val commitsBefore = snapshot(new File(checkpoint, "commits"))
+          testStream(joined)(
+            StartStream(checkpointLocation = checkpoint),
+            ExpectFailure[AnalysisException](assertFailure = error => {
+              checkError(error.asInstanceOf[AnalysisException],
+                condition = "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE",
+                parameters = Map(
+                  "joinCondition" -> 
".*leftKey.*rightKey.*leftTime.*rightTime.*",
+                  "leftWatermarkColumns" -> "none",
+                  "rightWatermarkColumns" -> "rightTime"),
+                matchPVals = true)
+            }))
+          assert(snapshot(new File(checkpoint, "state")) == before)
+          assert(snapshot(new File(checkpoint, "commits")) == commitsBefore)
+        }
+      }
+    }
+  }
+
+  private val intervalCondition =
+    "leftKey = rightKey AND rightTime >= leftTime AND rightTime <= leftTime + 
INTERVAL 5 SECONDS"
+
+  // Old state of a two-sided time-interval join on the inputs' own event 
times is reusable;

Review Comment:
   **Nit (P3):** The header says only two-sided interval joins on the inputs' 
own event times are reusable, but the table also expects 'one-directional 
interval' and 'key-only join keeping both event times' to resume, because no 
stateful operator after them reads the unbounded input's event time. A reader 
trusting the header could flip a correct row; the header should also name joins 
whose unbounded input no later stateful operator reads.
   
   **Verification:**
   - **Inspection:** The header describes every row the table marks as accepted.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +650,124 @@ class IncrementalExecution(
       watermarkPropagator.propagate(currentBatchId, plan, 
watermarkForCurrBatch)
     }
 
+    /**
+     * Find, for each stateful operator that applies its input watermark to an 
event-time column,
+     * which stream-stream join inputs' event times that column carries. The 
walk follows the
+     * column down through nodes that pass it on unchanged, to the same 
position in every input
+     * of a union, and through windows built from it, which end after it. It 
stops at a join, at
+     * another operator that writes state or sets an event time, and at any 
node it does not
+     * recognize; a join that no traced column reaches holds back for both 
inputs.
+     */
+    private def joinWatermarkConsumers(plan: SparkPlan): 
Seq[JoinWatermarkConsumer] = {
+      def eventTime(output: Seq[Attribute]): Option[Attribute] =
+        output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+
+      // A time or session window built from one column, plus constants, ends 
after that column.
+      def windowSource(window: Attribute, expression: Expression): 
Option[Attribute] = {
+        val isWindow = window.metadata.contains(TimeWindow.marker) ||
+          window.metadata.contains(SessionWindow.marker)
+        expression.references.toSeq match {
+          case Seq(source) if isWindow => Some(source)
+          case _ => None
+        }
+      }
+
+      def passThrough(child: SparkPlan, attribute: Attribute): Seq[(Long, 
JoinSide, Attribute)] =
+        child.output.find(_.exprId == 
attribute.exprId).toSeq.flatMap(findJoinSides(child, _))
+
+      def findJoinSides(
+          node: SparkPlan,
+          attribute: Attribute): Seq[(Long, JoinSide, Attribute)] = {
+        node match {
+          case j: StreamingSymmetricHashJoinExec =>
+            val side = if (eventTime(j.left.output).exists(_.exprId == 
attribute.exprId)) {
+              Some(LeftSide)
+            } else if (eventTime(j.right.output).exists(_.exprId == 
attribute.exprId)) {
+              Some(RightSide)
+            } else {
+              None
+            }
+            j.stateInfo.map(_.operatorId).zip(side).map { case (id, s) => (id, 
s, attribute) }
+              .toSeq
+          case p: ProjectExec =>
+            p.projectList.find(_.exprId == attribute.exprId).toSeq.flatMap {
+              case a: Attribute => passThrough(p.child, a)
+              case Alias(a: Attribute, _) => passThrough(p.child, a)
+              case alias: Alias =>
+                windowSource(alias.toAttribute, 
alias.child).toSeq.flatMap(passThrough(p.child, _))
+              case _ => Nil
+            }
+          case e: ExpandExec =>
+            // A sliding window is one projection per window; each must carry 
the same column.
+            val index = e.output.indexWhere(_.exprId == attribute.exprId)
+            val traced = e.projections.map { projection =>
+              projection.lift(index).toSeq.flatMap {
+                case a: Attribute => passThrough(e.child, a)
+                case expression =>
+                  windowSource(e.output(index), 
expression).toSeq.flatMap(passThrough(e.child, _))
+              }
+            }
+            if (traced.nonEmpty && traced.forall(_.nonEmpty) && 
traced.distinct.size == 1) {
+              traced.head
+            } else {
+              Nil
+            }
+          case u: UnionExec =>
+            val index = u.output.indexWhere(_.exprId == attribute.exprId)
+            if (index < 0) Nil else u.children.flatMap(c => findJoinSides(c, 
c.output(index)))
+          case _: StateStoreWriter | _: EventTimeWatermarkExec | _: 
UpdateEventTimeColumnExec =>
+            Nil
+          case u: UnaryExecNode if u.output.exists(_.exprId == 
attribute.exprId) =>
+            passThrough(u.child, attribute)
+          case _ => Nil
+        }
+      }
+
+      // The inputs whose event-time column each operator compares with its 
input watermark.
+      def watermarkedInputs(node: SparkPlan): Seq[SparkPlan] = node match {
+        case _: StateStoreSaveExec | _: StatefulStreamlineAggregateExec |
+            _: SessionWindowStateStoreSaveExec | _: StreamingDeduplicateExec |
+            _: StreamingDeduplicateWithinWatermarkExec | _: 
StreamingSymmetricHashJoinExec =>
+          node.children
+        case f: FlatMapGroupsWithStateExec if f.timeoutConf == 
EventTimeTimeout => Seq(f.child)
+        case f: FlatMapGroupsInPandasWithStateExec if f.timeoutConf == 
EventTimeTimeout =>

Review Comment:
   **Nit (P3):** The `applyInPandasWithState` and `transformWithStateInPandas` 
arms have no test: StreamingJoinOutputWatermarkSuite reaches only the JVM 
`flatMapGroupsWithState` and `transformWithState` arms, and no PySpark test 
runs these operators after a stream-stream join. If either guard stopped 
matching, the join would hold back for both inputs and event-time timeouts over 
the bounded input's event time would never fire, with no failing test. Tests in 
`test_pandas_grouped_map_with_state.py` and the transformWithState suites under 
`python/pyspark/sql/tests/pandas/streaming` would cover them.
   
   **Verification:**
   - **Regression:** If either PySpark operator's arm in the tracer stopped 
matching, the corresponding test fails because its timers never fire.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -896,7 +979,14 @@ case class StreamingSymmetricHashJoinExec(
         //   is done at this point. That said, input can be skipped to be 
added to the state store
         //   if input is going to be evicted in this batch. Though, input 
should be added to the
         //   state store if it's right outer join or full outer join, as 
unmatched output is
-        //   handled during state eviction.
+        //   handled during state eviction. A left semi join processes the 
right side first, so
+        //   the left input of this batch has not probed it yet: an input this 
batch evicts is
+        //   added, and the eviction at the end of the batch removes it, 
unless a cutoff at the
+        //   late-events watermark that is exact today shows no left row 
passing late filtering
+        //   can match it (see getLeftSemiExactRightCutoffs). The cutoff 
derivation gives no exact
+        //   cutoff otherwise: it can apply a bound on another right column to 
the right event

Review Comment:
   **Nit (P3):** This PR's `getStateValueWatermarkForInput` keeps each cutoff 
on the column it bounds, so the cutoff derivation no longer applies a bound on 
another right column to the right event time; that reason came from the 
SPARK-61380 branch, whose base still did. Both this comment and the 
`getLeftSemiExactRightCutoffs` doc also end with `TODO(SPARK-61344, 
SPARK-61381)`, naming this PR's own ticket as future work. Only the whole-day 
and truncating-cast reasons still hold, so the comments should keep those and 
name only SPARK-61381.
   
   **Verification:**
   - **Inspection:** The left semi storing comment and the exact-cutoff 
helper's doc state only reasons the current derivation has and cite only the 
follow-up ticket.



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